OpenConcerto

Dépôt officiel du code source de l'ERP OpenConcerto
sonarqube

svn://code.openconcerto.org/openconcerto

Rev

Rev 67 | Rev 80 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
17 ilm 1
/*
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
3
 *
4
 * Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
5
 *
6
 * The contents of this file are subject to the terms of the GNU General Public License Version 3
7
 * only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
8
 * copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
9
 * language governing permissions and limitations under the License.
10
 *
11
 * When distributing the software, include this License Header Notice in each file.
12
 */
13
 
14
 package org.openconcerto.openoffice.spreadsheet;
15
 
20 ilm 16
import org.openconcerto.openoffice.Log;
17 ilm 17
import org.openconcerto.openoffice.ODDocument;
18
import org.openconcerto.openoffice.ODFrame;
19
import org.openconcerto.openoffice.ODValueType;
20 ilm 20
import org.openconcerto.openoffice.OOXML;
25 ilm 21
import org.openconcerto.openoffice.StyleDesc;
73 ilm 22
import org.openconcerto.openoffice.XMLVersion;
17 ilm 23
import org.openconcerto.openoffice.spreadsheet.BytesProducer.ByteArrayProducer;
24
import org.openconcerto.openoffice.spreadsheet.BytesProducer.ImageProducer;
73 ilm 25
import org.openconcerto.openoffice.spreadsheet.CellStyle.StyleTableCellProperties;
61 ilm 26
import org.openconcerto.openoffice.style.data.BooleanStyle;
20 ilm 27
import org.openconcerto.openoffice.style.data.DataStyle;
61 ilm 28
import org.openconcerto.openoffice.style.data.DateStyle;
17 ilm 29
import org.openconcerto.utils.FileUtils;
73 ilm 30
import org.openconcerto.utils.TimeUtils;
31
import org.openconcerto.utils.Tuple2;
25 ilm 32
import org.openconcerto.utils.Tuple3;
17 ilm 33
 
34
import java.awt.Color;
35
import java.awt.Image;
21 ilm 36
import java.awt.Point;
17 ilm 37
import java.io.File;
38
import java.io.IOException;
39
import java.text.DateFormat;
40
import java.text.DecimalFormat;
41
import java.text.NumberFormat;
20 ilm 42
import java.util.Calendar;
17 ilm 43
import java.util.Date;
44
import java.util.List;
61 ilm 45
import java.util.Locale;
65 ilm 46
import java.util.logging.Level;
17 ilm 47
 
25 ilm 48
import javax.xml.datatype.Duration;
49
 
17 ilm 50
import org.jdom.Attribute;
51
import org.jdom.Element;
52
import org.jdom.Namespace;
53
import org.jdom.Text;
54
 
55
/**
56
 * A cell whose value can be changed.
57
 *
58
 * @author Sylvain
59
 * @param <D> type of document
60
 */
61
public class MutableCell<D extends ODDocument> extends Cell<D> {
62
 
20 ilm 63
    static private final DateFormat TextPDateFormat = DateFormat.getDateInstance();
64
    static private final DateFormat TextPTimeFormat = DateFormat.getTimeInstance();
25 ilm 65
    static private final NumberFormat TextPMinuteSecondFormat = new DecimalFormat("00.###");
20 ilm 66
    static private final NumberFormat TextPFloatFormat = DecimalFormat.getNumberInstance();
67
    static private final NumberFormat TextPPercentFormat = DecimalFormat.getPercentInstance();
68
    static private final NumberFormat TextPCurrencyFormat = DecimalFormat.getCurrencyInstance();
17 ilm 69
 
20 ilm 70
    static public String formatNumber(Number n, final CellStyle defaultStyle) {
73 ilm 71
        return formatNumber(TextPFloatFormat, n, defaultStyle);
20 ilm 72
    }
73
 
74
    static public String formatPercent(Number n, final CellStyle defaultStyle) {
73 ilm 75
        return formatNumber(TextPPercentFormat, n, defaultStyle);
20 ilm 76
    }
77
 
78
    static public String formatCurrency(Number n, final CellStyle defaultStyle) {
73 ilm 79
        return formatNumber(TextPCurrencyFormat, n, defaultStyle);
20 ilm 80
    }
81
 
73 ilm 82
    static private String formatNumber(NumberFormat format, Number n, final CellStyle defaultStyle) {
20 ilm 83
        synchronized (format) {
84
            final int decPlaces = DataStyle.getDecimalPlaces(defaultStyle);
73 ilm 85
            format.setMinimumFractionDigits(0);
20 ilm 86
            format.setMaximumFractionDigits(decPlaces);
87
            return format.format(n);
88
        }
89
    }
90
 
25 ilm 91
    MutableCell(Row<D> parent, Element elem, StyleDesc<CellStyle> styleDesc) {
92
        super(parent, elem, styleDesc);
17 ilm 93
    }
94
 
95
    // ask our column to our row so we don't have to update anything when columns are removed/added
96
    public final int getX() {
97
        return this.getRow().getX(this);
98
    }
99
 
100
    public final int getY() {
101
        return this.getRow().getY();
102
    }
103
 
21 ilm 104
    public final Point getPoint() {
105
        return new Point(getX(), getY());
106
    }
107
 
108
    final void setRowsSpanned(final int rowsSpanned) {
109
        if (rowsSpanned <= 1)
110
            this.getElement().removeAttribute("number-rows-spanned", getNS().getTABLE());
111
        else
112
            this.getElement().setAttribute("number-rows-spanned", String.valueOf(rowsSpanned), getNS().getTABLE());
113
    }
114
 
17 ilm 115
    // *** setValue
116
 
117
    private void setValueAttributes(ODValueType type, Object val) {
73 ilm 118
        final Namespace valueNS = getValueNS();
119
        final Attribute valueTypeAttr = this.getElement().getAttribute("value-type", valueNS);
67 ilm 120
        // e.g. DATE
121
        final ODValueType currentType = valueTypeAttr == null ? null : ODValueType.get(valueTypeAttr.getValue());
122
 
17 ilm 123
        if (type == null) {
124
            if (valueTypeAttr != null) {
125
                valueTypeAttr.detach();
126
            }
127
        } else {
73 ilm 128
            if (!type.equals(currentType)) {
129
                if (valueTypeAttr != null) {
130
                    valueTypeAttr.setValue(type.getName());
131
                } else {
132
                    // create an instance of Attribute to avoid a getAttribute() in the simpler
133
                    // setAttribute()
134
                    this.getElement().setAttribute(new Attribute("value-type", type.getName(), valueNS));
135
                }
136
            }
17 ilm 137
        }
73 ilm 138
 
139
        // remove old value attribute (assume Element is valid, otherwise we would need to remove
140
        // all possible value attributes)
141
        if (currentType != null && (!currentType.equals(type) || type == ODValueType.STRING)) {
142
            // e.g. @date-value
143
            this.getElement().removeAttribute(currentType.getValueAttribute(), valueNS);
144
        }
145
        // Like LO, do not generate string-value
146
        if (type != null && type != ODValueType.STRING) {
147
            this.getElement().setAttribute(type.getValueAttribute(), type.format(val), valueNS);
148
        }
17 ilm 149
    }
150
 
151
    // ATTN this removes any content associated with this cell be it notes, cell anchored objects,
152
    // etc. This is because it's difficult to tell apart the text content and the rest (e.g. notes),
153
    // for example in Calc office:annotation is a child of table:cell whereas in Writer it's a child
154
    // of text:p.
155
    private void setTextP(String value) {
156
        if (value == null)
157
            this.getElement().removeContent();
158
        else {
159
            // try to reuse the first text:p to keep style
160
            final Element child = this.getElement().getChild("p", getNS().getTEXT());
161
            final Element t = child != null ? child : new Element("p", getNS().getTEXT());
73 ilm 162
            t.setContent(OOXML.get(this.getODDocument().getFormatVersion(), false).encodeWSasList(value));
17 ilm 163
 
164
            this.getElement().setContent(t);
165
        }
166
    }
167
 
168
    private void setValue(ODValueType type, Object value, String textP) {
169
        this.setValueAttributes(type, value);
170
        this.setTextP(textP);
171
    }
172
 
173
    public void clearValue() {
174
        this.setValue(null, null, null);
175
    }
176
 
177
    public void setValue(Object obj) {
25 ilm 178
        this.setValue(obj, true);
179
    }
180
 
181
    public void setValue(Object obj, final boolean allowTypeChange) throws UnsupportedOperationException {
20 ilm 182
        final ODValueType type;
183
        final ODValueType currentType = getValueType();
184
        // try to keep current type, since for example a Number can work with FLOAT, PERCENTAGE
185
        // and CURRENCY
186
        if (currentType != null && currentType.canFormat(obj.getClass())) {
187
            type = currentType;
188
        } else {
57 ilm 189
            final ODValueType tmp = ODValueType.forObject(obj);
190
            // allow any Object
191
            if (allowTypeChange && tmp == null) {
192
                type = ODValueType.STRING;
193
                obj = String.valueOf(obj);
194
            } else {
195
                type = tmp;
196
            }
25 ilm 197
        }
198
        if (type == null) {
20 ilm 199
            throw new IllegalArgumentException("Couldn't infer type of " + obj);
200
        }
25 ilm 201
        this.setValue(obj, type, allowTypeChange, true);
20 ilm 202
    }
203
 
204
    /**
205
     * Change the value of this cell.
206
     *
207
     * @param obj the new cell value.
208
     * @param vt the value type.
25 ilm 209
     * @param allowTypeChange if <code>true</code> <code>obj</code> and <code>vt</code> might be
210
     *        changed to allow the data style to format, e.g. from Boolean.FALSE to 0.
20 ilm 211
     * @param lenient <code>false</code> to throw an exception if we can't format according to the
212
     *        ODF, <code>true</code> to try best-effort.
213
     * @throws UnsupportedOperationException if <code>obj</code> couldn't be formatted.
214
     */
25 ilm 215
    public void setValue(Object obj, ODValueType vt, final boolean allowTypeChange, final boolean lenient) throws UnsupportedOperationException {
20 ilm 216
        final String text;
25 ilm 217
        final Tuple3<String, ODValueType, Object> formatted = format(obj, vt, !allowTypeChange, lenient);
218
        vt = formatted.get1();
219
        obj = formatted.get2();
20 ilm 220
 
25 ilm 221
        if (formatted.get0() != null) {
222
            text = formatted.get0();
20 ilm 223
        } else {
224
            // either there were no format or formatting failed
225
            if (vt == ODValueType.FLOAT) {
226
                text = formatNumber((Number) obj, getDefaultStyle());
227
            } else if (vt == ODValueType.PERCENTAGE) {
228
                text = formatPercent((Number) obj, getDefaultStyle());
229
            } else if (vt == ODValueType.CURRENCY) {
230
                text = formatCurrency((Number) obj, getDefaultStyle());
231
            } else if (vt == ODValueType.DATE) {
25 ilm 232
                final Date d;
233
                if (obj instanceof Calendar) {
234
                    d = ((Calendar) obj).getTime();
235
                } else {
236
                    d = (Date) obj;
237
                }
238
                text = TextPDateFormat.format(d);
20 ilm 239
            } else if (vt == ODValueType.TIME) {
25 ilm 240
                if (obj instanceof Duration) {
241
                    final Duration normalized = getODDocument().getEpoch().normalizeToHours((Duration) obj);
73 ilm 242
                    text = "" + normalized.getHours() + ':' + TextPMinuteSecondFormat.format(normalized.getMinutes()) + ':' + TextPMinuteSecondFormat.format(TimeUtils.getSeconds(normalized));
25 ilm 243
                } else {
244
                    text = TextPTimeFormat.format(((Calendar) obj).getTime());
245
                }
20 ilm 246
            } else if (vt == ODValueType.BOOLEAN) {
61 ilm 247
                // LO do not use the the document language but the system language
248
                // http://help.libreoffice.org/Common/Selecting_the_Document_Language
249
                Locale l = Locale.getDefault();
250
                // except of course if there's a data style
251
                final CellStyle s = getStyle();
252
                if (s != null) {
253
                    final DataStyle ds = s.getDataStyle();
254
                    if (ds != null)
255
                        l = DateStyle.getLocale(ds.getElement());
256
                }
257
                text = BooleanStyle.toString((Boolean) obj, l, lenient);
20 ilm 258
            } else if (vt == ODValueType.STRING) {
259
                text = obj.toString();
19 ilm 260
            } else {
20 ilm 261
                throw new IllegalStateException(vt + " unknown");
19 ilm 262
            }
20 ilm 263
        }
264
        this.setValue(vt, obj, text);
17 ilm 265
    }
266
 
25 ilm 267
    // return null String if no data style exists, or if one exists but we couldn't use it
268
    private Tuple3<String, ODValueType, Object> format(Object obj, ODValueType valueType, boolean onlyCast, boolean lenient) {
269
        String res = null;
20 ilm 270
        try {
25 ilm 271
            final Tuple3<DataStyle, ODValueType, Object> ds = getDataStyleAndValue(obj, valueType, onlyCast);
272
            if (ds != null) {
273
                obj = ds.get2();
274
                valueType = ds.get1();
275
                // act like OO, that is if we set a String to a Date cell, change the value and
276
                // value-type but leave the data-style untouched
277
                if (ds.get0().canFormat(obj.getClass()))
278
                    res = ds.get0().format(obj, getDefaultStyle(), lenient);
279
            }
20 ilm 280
        } catch (UnsupportedOperationException e) {
281
            if (lenient)
65 ilm 282
                Log.get().log(Level.WARNING, "Couldn't format", e);
20 ilm 283
            else
284
                throw e;
285
        }
25 ilm 286
        return Tuple3.create(res, valueType, obj);
20 ilm 287
    }
288
 
289
    public final DataStyle getDataStyle() {
25 ilm 290
        final Tuple3<DataStyle, ODValueType, Object> s = this.getDataStyleAndValue(this.getValue(), this.getValueType(), true);
291
        return s != null ? s.get0() : null;
292
    }
293
 
294
    private final Tuple3<DataStyle, ODValueType, Object> getDataStyleAndValue(Object obj, ODValueType valueType, boolean onlyCast) {
20 ilm 295
        final CellStyle s = this.getStyle();
73 ilm 296
        return s != null ? s.getDataStyle(obj, valueType, onlyCast) : null;
20 ilm 297
    }
298
 
299
    protected final CellStyle getDefaultStyle() {
300
        return this.getRow().getSheet().getDefaultCellStyle();
301
    }
302
 
17 ilm 303
    public void replaceBy(String oldValue, String newValue) {
304
        replaceContentBy(this.getElement(), oldValue, newValue);
305
    }
306
 
307
    private void replaceContentBy(Element l, String oldValue, String newValue) {
20 ilm 308
        final List<?> content = l.getContent();
17 ilm 309
        for (int i = 0; i < content.size(); i++) {
310
            final Object obj = content.get(i);
311
            if (obj instanceof Text) {
312
                // System.err.println(" Text --> " + obj.toString());
313
                final Text t = (Text) obj;
314
                t.setText(t.getText().replaceAll(oldValue, newValue));
315
            } else if (obj instanceof Element) {
316
                replaceContentBy((Element) obj, oldValue, newValue);
317
            }
318
        }
319
    }
320
 
73 ilm 321
    /**
322
     * Set the raw value of the formula attribute.
323
     *
324
     * @param formula the raw value, e.g. "of:sum(A1:A2)".
325
     */
326
    public final void setRawFormula(final String formula) {
327
        // from 19.642 table:formula of OpenDocument-v1.2 : Whenever the initial text of a formula
328
        // has the appearance of an NCName followed by ":", an OpenDocument producer shall provide a
329
        // valid namespace prefix in order to eliminate any ambiguity.
330
        final String nsPrefix = getFormulaNSPrefix(formula).get0();
331
        if (nsPrefix != null && this.getElement().getNamespace(nsPrefix) == null) {
332
            throw new IllegalArgumentException("Unknown namespace prefix : " + nsPrefix);
333
        }
334
        this.setFormulaNoCheck(formula);
335
    }
336
 
337
    private final void setFormulaNoCheck(final String formula) {
338
        this.getElement().setAttribute("formula", formula, getTABLE());
339
    }
340
 
341
    public final void setFormulaAndNamespace(final Tuple2<Namespace, String> formula) {
342
        this.setFormulaAndNamespace(formula.get0(), formula.get1());
343
    }
344
 
345
    public final void setFormula(final String formula) {
346
        this.setFormulaAndNamespace(null, formula);
347
    }
348
 
349
    public final void setFormulaAndNamespace(final Namespace ns, final String formula) {
350
        if (getODDocument().getVersion() == XMLVersion.OOo) {
351
            if (ns != null)
352
                throw new IllegalArgumentException("Namespaces not supported by this version : " + ns);
353
            this.setFormulaNoCheck(formula);
354
        } else if (ns == null) {
355
            final String nsPrefix = getFormulaNSPrefix(formula).get0();
356
            if (nsPrefix != null) {
357
                // eliminate ambiguity
358
                final Namespace defaultNS = getDefaultFormulaNS();
359
                // prevent infinite recursion
360
                if (defaultNS == null)
361
                    throw new IllegalStateException("Cannot resolve ambiguity, formula appears to begin with " + nsPrefix + " and no default namespace found");
362
                this.setFormulaAndNamespace(defaultNS, formula);
363
            } else {
364
                this.setFormulaNoCheck(formula);
365
            }
366
        } else {
367
            final Namespace existingNS = this.getElement().getNamespace(ns.getPrefix());
368
            if (existingNS == null)
369
                this.getElement().getDocument().getRootElement().addNamespaceDeclaration(ns);
370
            else if (!existingNS.equals(ns))
371
                throw new IllegalStateException("Namespace conflict : " + existingNS + " != " + ns);
372
            this.setFormulaNoCheck(ns.getPrefix() + ':' + formula);
373
        }
374
    }
375
 
17 ilm 376
    public final void unmerge() {
377
        // from 8.1.3 Table Cell : table-cell are like covered-table-cell with some extra
378
        // optional attributes so it's safe to rename covered cells into normal ones
379
        final int x = this.getX();
380
        final int y = this.getY();
381
        final int columnsSpanned = getColumnsSpanned();
382
        final int rowsSpanned = getRowsSpanned();
383
        for (int i = 0; i < columnsSpanned; i++) {
384
            for (int j = 0; j < rowsSpanned; j++) {
385
                // don't mind if we change us at 0,0 we're already a table-cell
386
                this.getRow().getSheet().getImmutableCellAt(x + i, y + j).getElement().setName("table-cell");
387
            }
388
        }
389
        this.getElement().removeAttribute("number-columns-spanned", getNS().getTABLE());
390
        this.getElement().removeAttribute("number-rows-spanned", getNS().getTABLE());
391
    }
392
 
393
    /**
394
     * Merge this cell and the following ones. If this cell already spanned multiple columns/rows
395
     * this method un-merge any additional cells.
396
     *
397
     * @param columnsSpanned number of columns to merge.
398
     * @param rowsSpanned number of rows to merge.
399
     */
400
    public final void merge(final int columnsSpanned, final int rowsSpanned) {
401
        final int currentCols = this.getColumnsSpanned();
402
        final int currentRows = this.getRowsSpanned();
403
 
404
        // nothing to do
405
        if (columnsSpanned == currentCols && rowsSpanned == currentRows)
406
            return;
407
 
408
        final int x = this.getX();
409
        final int y = this.getY();
410
 
411
        // check for problems before any modifications
412
        for (int i = 0; i < columnsSpanned; i++) {
413
            for (int j = 0; j < rowsSpanned; j++) {
414
                final boolean coveredByThis = i < currentCols && j < currentRows;
415
                if (!coveredByThis) {
416
                    final int x2 = x + i;
417
                    final int y2 = y + j;
418
                    final Cell<D> immutableCell = this.getRow().getSheet().getImmutableCellAt(x2, y2);
419
                    // check for overlapping range from inside
420
                    if (immutableCell.coversOtherCells())
421
                        throw new IllegalArgumentException("Cell at " + x2 + "," + y2 + " is a merged cell.");
422
                    // and outside
423
                    if (immutableCell.getElement().getName().equals("covered-table-cell"))
424
                        throw new IllegalArgumentException("Cell at " + x2 + "," + y2 + " is already covered.");
425
                }
426
            }
427
        }
428
 
429
        final boolean shrinks = columnsSpanned < currentCols || rowsSpanned < currentRows;
430
        if (shrinks)
431
            this.unmerge();
432
 
433
        // from 8.1.3 Table Cell : table-cell are like covered-table-cell with some extra
434
        // optional attributes so it's safe to rename
435
        for (int i = 0; i < columnsSpanned; i++) {
436
            for (int j = 0; j < rowsSpanned; j++) {
437
                final boolean coveredByThis = i < currentCols && j < currentRows;
438
                // don't cover this,
439
                // if we grow the current covered cells are invalid so don't try to access them
440
                if ((i != 0 || j != 0) && (shrinks || !coveredByThis))
441
                    // MutableCell is needed to break repeated
442
                    this.getRow().getSheet().getCellAt(x + i, y + j).getElement().setName("covered-table-cell");
443
            }
444
        }
445
        this.getElement().setAttribute("number-columns-spanned", columnsSpanned + "", getNS().getTABLE());
446
        this.getElement().setAttribute("number-rows-spanned", rowsSpanned + "", getNS().getTABLE());
447
    }
448
 
449
    @Override
450
    public final String getStyleName() {
451
        return this.getRow().getSheet().getStyleNameAt(this.getX(), this.getY());
452
    }
453
 
73 ilm 454
    public final StyleTableCellProperties getTableCellProperties() {
455
        return this.getRow().getSheet().getTableCellPropertiesAt(this.getX(), this.getY());
456
    }
457
 
17 ilm 458
    public void setImage(final File pic) throws IOException {
459
        this.setImage(pic, false);
460
    }
461
 
462
    public void setImage(final File pic, boolean keepRatio) throws IOException {
463
        this.setImage(pic.getName(), new ByteArrayProducer(FileUtils.readBytes(pic), keepRatio));
464
    }
465
 
466
    public void setImage(final String name, final Image img) throws IOException {
467
        this.setImage(name, img == null ? null : new ImageProducer(img, true));
468
    }
469
 
470
    private void setImage(final String name, final BytesProducer data) {
471
        final Namespace draw = this.getNS().getNS("draw");
472
        final Element frame = this.getElement().getChild("frame", draw);
473
        final Element imageElem = frame == null ? null : frame.getChild("image", draw);
474
 
475
        if (imageElem != null) {
476
            final Attribute refAttr = imageElem.getAttribute("href", this.getNS().getNS("xlink"));
477
            this.getODDocument().getPackage().putFile(refAttr.getValue(), null);
478
 
479
            if (data == null)
480
                frame.detach();
481
            else {
482
                refAttr.setValue("Pictures/" + name + (data.getFormat() != null ? "." + data.getFormat() : ""));
483
                this.getODDocument().getPackage().putFile(refAttr.getValue(), data.getBytes(new ODFrame<D>(getODDocument(), frame)));
484
            }
485
        } else if (data != null)
486
            throw new IllegalStateException("this cell doesn't contain an image: " + this);
487
    }
488
 
489
    public final void setBackgroundColor(final Color color) {
73 ilm 490
        this.getPrivateStyle().getTableCellProperties(this).setBackgroundColor(color);
17 ilm 491
    }
492
}