OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

Rev 80 | Rev 132 | 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;
25 ilm 20
import org.openconcerto.openoffice.StyleDesc;
73 ilm 21
import org.openconcerto.openoffice.XMLVersion;
17 ilm 22
import org.openconcerto.openoffice.spreadsheet.BytesProducer.ByteArrayProducer;
23
import org.openconcerto.openoffice.spreadsheet.BytesProducer.ImageProducer;
73 ilm 24
import org.openconcerto.openoffice.spreadsheet.CellStyle.StyleTableCellProperties;
61 ilm 25
import org.openconcerto.openoffice.style.data.BooleanStyle;
20 ilm 26
import org.openconcerto.openoffice.style.data.DataStyle;
61 ilm 27
import org.openconcerto.openoffice.style.data.DateStyle;
17 ilm 28
import org.openconcerto.utils.FileUtils;
73 ilm 29
import org.openconcerto.utils.TimeUtils;
80 ilm 30
import org.openconcerto.utils.TimeUtils.DurationNullsChanger;
73 ilm 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
 
80 ilm 91
    static private boolean LO_MODE = true;
92
    // no date part, all time part to zero
93
    static private final DurationNullsChanger TIME_NULLS = new TimeUtils.DurationNullsBuilder(TimeUtils.EmptyFieldPolicy.SET_TO_ZERO).setToNull(TimeUtils.getDateFields()).build();
94
 
95
    public static void setTimeValueMode(boolean loMode) {
96
        LO_MODE = loMode;
97
    }
98
 
99
    /**
100
     * Whether {@link #setValue(Object)} formats {@link Duration} using the standard way or using
101
     * the LibreOffice way. LibreOffice does not support years, months and days in cells ; even set
102
     * to 0 (it does in user meta fields). The initial value is <code>true</code>.
103
     *
104
     * @return <code>true</code> if durations should be formatted the LibO way.
105
     */
106
    public static boolean getTimeValueMode() {
107
        return LO_MODE;
108
    }
109
 
25 ilm 110
    MutableCell(Row<D> parent, Element elem, StyleDesc<CellStyle> styleDesc) {
111
        super(parent, elem, styleDesc);
17 ilm 112
    }
113
 
114
    // ask our column to our row so we don't have to update anything when columns are removed/added
115
    public final int getX() {
116
        return this.getRow().getX(this);
117
    }
118
 
119
    public final int getY() {
120
        return this.getRow().getY();
121
    }
122
 
21 ilm 123
    public final Point getPoint() {
124
        return new Point(getX(), getY());
125
    }
126
 
127
    final void setRowsSpanned(final int rowsSpanned) {
128
        if (rowsSpanned <= 1)
129
            this.getElement().removeAttribute("number-rows-spanned", getNS().getTABLE());
130
        else
131
            this.getElement().setAttribute("number-rows-spanned", String.valueOf(rowsSpanned), getNS().getTABLE());
132
    }
133
 
17 ilm 134
    // *** setValue
135
 
136
    private void setValueAttributes(ODValueType type, Object val) {
73 ilm 137
        final Namespace valueNS = getValueNS();
138
        final Attribute valueTypeAttr = this.getElement().getAttribute("value-type", valueNS);
67 ilm 139
        // e.g. DATE
140
        final ODValueType currentType = valueTypeAttr == null ? null : ODValueType.get(valueTypeAttr.getValue());
141
 
17 ilm 142
        if (type == null) {
143
            if (valueTypeAttr != null) {
144
                valueTypeAttr.detach();
145
            }
146
        } else {
73 ilm 147
            if (!type.equals(currentType)) {
148
                if (valueTypeAttr != null) {
149
                    valueTypeAttr.setValue(type.getName());
150
                } else {
151
                    // create an instance of Attribute to avoid a getAttribute() in the simpler
152
                    // setAttribute()
153
                    this.getElement().setAttribute(new Attribute("value-type", type.getName(), valueNS));
154
                }
155
            }
17 ilm 156
        }
73 ilm 157
 
158
        // remove old value attribute (assume Element is valid, otherwise we would need to remove
159
        // all possible value attributes)
160
        if (currentType != null && (!currentType.equals(type) || type == ODValueType.STRING)) {
161
            // e.g. @date-value
162
            this.getElement().removeAttribute(currentType.getValueAttribute(), valueNS);
163
        }
164
        // Like LO, do not generate string-value
165
        if (type != null && type != ODValueType.STRING) {
80 ilm 166
            // LO cells don't support the full syntax of a duration (user meta fields do)
167
            // instead it support only values without nYnMnD
168
            if (type == ODValueType.TIME && getTimeValueMode()) {
169
                final Duration d = val instanceof Duration ? (Duration) val : TimeUtils.timePartToDuration((Calendar) val);
170
                val = TIME_NULLS.apply(getODDocument().getEpoch().normalizeToHours(d));
171
            }
73 ilm 172
            this.getElement().setAttribute(type.getValueAttribute(), type.format(val), valueNS);
173
        }
17 ilm 174
    }
175
 
176
    private void setTextP(String value) {
83 ilm 177
        if (value == null) {
17 ilm 178
            this.getElement().removeContent();
83 ilm 179
        } else {
180
            new Lines(this.getODDocument(), value).setText(getElement(), getTextValueMode());
17 ilm 181
        }
182
    }
183
 
184
    private void setValue(ODValueType type, Object value, String textP) {
185
        this.setValueAttributes(type, value);
186
        this.setTextP(textP);
187
    }
188
 
189
    public void clearValue() {
190
        this.setValue(null, null, null);
191
    }
192
 
193
    public void setValue(Object obj) {
25 ilm 194
        this.setValue(obj, true);
195
    }
196
 
197
    public void setValue(Object obj, final boolean allowTypeChange) throws UnsupportedOperationException {
20 ilm 198
        final ODValueType type;
199
        final ODValueType currentType = getValueType();
200
        // try to keep current type, since for example a Number can work with FLOAT, PERCENTAGE
201
        // and CURRENCY
202
        if (currentType != null && currentType.canFormat(obj.getClass())) {
203
            type = currentType;
204
        } else {
57 ilm 205
            final ODValueType tmp = ODValueType.forObject(obj);
206
            // allow any Object
207
            if (allowTypeChange && tmp == null) {
208
                type = ODValueType.STRING;
209
                obj = String.valueOf(obj);
210
            } else {
211
                type = tmp;
212
            }
25 ilm 213
        }
214
        if (type == null) {
20 ilm 215
            throw new IllegalArgumentException("Couldn't infer type of " + obj);
216
        }
25 ilm 217
        this.setValue(obj, type, allowTypeChange, true);
20 ilm 218
    }
219
 
220
    /**
221
     * Change the value of this cell.
222
     *
223
     * @param obj the new cell value.
224
     * @param vt the value type.
25 ilm 225
     * @param allowTypeChange if <code>true</code> <code>obj</code> and <code>vt</code> might be
226
     *        changed to allow the data style to format, e.g. from Boolean.FALSE to 0.
20 ilm 227
     * @param lenient <code>false</code> to throw an exception if we can't format according to the
228
     *        ODF, <code>true</code> to try best-effort.
229
     * @throws UnsupportedOperationException if <code>obj</code> couldn't be formatted.
230
     */
25 ilm 231
    public void setValue(Object obj, ODValueType vt, final boolean allowTypeChange, final boolean lenient) throws UnsupportedOperationException {
20 ilm 232
        final String text;
25 ilm 233
        final Tuple3<String, ODValueType, Object> formatted = format(obj, vt, !allowTypeChange, lenient);
234
        vt = formatted.get1();
235
        obj = formatted.get2();
20 ilm 236
 
25 ilm 237
        if (formatted.get0() != null) {
238
            text = formatted.get0();
20 ilm 239
        } else {
240
            // either there were no format or formatting failed
241
            if (vt == ODValueType.FLOAT) {
242
                text = formatNumber((Number) obj, getDefaultStyle());
243
            } else if (vt == ODValueType.PERCENTAGE) {
244
                text = formatPercent((Number) obj, getDefaultStyle());
245
            } else if (vt == ODValueType.CURRENCY) {
246
                text = formatCurrency((Number) obj, getDefaultStyle());
247
            } else if (vt == ODValueType.DATE) {
25 ilm 248
                final Date d;
249
                if (obj instanceof Calendar) {
250
                    d = ((Calendar) obj).getTime();
251
                } else {
252
                    d = (Date) obj;
253
                }
254
                text = TextPDateFormat.format(d);
20 ilm 255
            } else if (vt == ODValueType.TIME) {
25 ilm 256
                if (obj instanceof Duration) {
257
                    final Duration normalized = getODDocument().getEpoch().normalizeToHours((Duration) obj);
73 ilm 258
                    text = "" + normalized.getHours() + ':' + TextPMinuteSecondFormat.format(normalized.getMinutes()) + ':' + TextPMinuteSecondFormat.format(TimeUtils.getSeconds(normalized));
25 ilm 259
                } else {
260
                    text = TextPTimeFormat.format(((Calendar) obj).getTime());
261
                }
20 ilm 262
            } else if (vt == ODValueType.BOOLEAN) {
61 ilm 263
                // LO do not use the the document language but the system language
264
                // http://help.libreoffice.org/Common/Selecting_the_Document_Language
265
                Locale l = Locale.getDefault();
266
                // except of course if there's a data style
267
                final CellStyle s = getStyle();
268
                if (s != null) {
269
                    final DataStyle ds = s.getDataStyle();
270
                    if (ds != null)
271
                        l = DateStyle.getLocale(ds.getElement());
272
                }
273
                text = BooleanStyle.toString((Boolean) obj, l, lenient);
20 ilm 274
            } else if (vt == ODValueType.STRING) {
275
                text = obj.toString();
19 ilm 276
            } else {
20 ilm 277
                throw new IllegalStateException(vt + " unknown");
19 ilm 278
            }
20 ilm 279
        }
280
        this.setValue(vt, obj, text);
17 ilm 281
    }
282
 
25 ilm 283
    // return null String if no data style exists, or if one exists but we couldn't use it
284
    private Tuple3<String, ODValueType, Object> format(Object obj, ODValueType valueType, boolean onlyCast, boolean lenient) {
285
        String res = null;
20 ilm 286
        try {
25 ilm 287
            final Tuple3<DataStyle, ODValueType, Object> ds = getDataStyleAndValue(obj, valueType, onlyCast);
288
            if (ds != null) {
289
                obj = ds.get2();
290
                valueType = ds.get1();
291
                // act like OO, that is if we set a String to a Date cell, change the value and
292
                // value-type but leave the data-style untouched
293
                if (ds.get0().canFormat(obj.getClass()))
294
                    res = ds.get0().format(obj, getDefaultStyle(), lenient);
295
            }
20 ilm 296
        } catch (UnsupportedOperationException e) {
297
            if (lenient)
65 ilm 298
                Log.get().log(Level.WARNING, "Couldn't format", e);
20 ilm 299
            else
300
                throw e;
301
        }
25 ilm 302
        return Tuple3.create(res, valueType, obj);
20 ilm 303
    }
304
 
305
    public final DataStyle getDataStyle() {
25 ilm 306
        final Tuple3<DataStyle, ODValueType, Object> s = this.getDataStyleAndValue(this.getValue(), this.getValueType(), true);
307
        return s != null ? s.get0() : null;
308
    }
309
 
310
    private final Tuple3<DataStyle, ODValueType, Object> getDataStyleAndValue(Object obj, ODValueType valueType, boolean onlyCast) {
20 ilm 311
        final CellStyle s = this.getStyle();
73 ilm 312
        return s != null ? s.getDataStyle(obj, valueType, onlyCast) : null;
20 ilm 313
    }
314
 
315
    protected final CellStyle getDefaultStyle() {
316
        return this.getRow().getSheet().getDefaultCellStyle();
317
    }
318
 
17 ilm 319
    public void replaceBy(String oldValue, String newValue) {
320
        replaceContentBy(this.getElement(), oldValue, newValue);
321
    }
322
 
323
    private void replaceContentBy(Element l, String oldValue, String newValue) {
20 ilm 324
        final List<?> content = l.getContent();
17 ilm 325
        for (int i = 0; i < content.size(); i++) {
326
            final Object obj = content.get(i);
327
            if (obj instanceof Text) {
328
                // System.err.println(" Text --> " + obj.toString());
329
                final Text t = (Text) obj;
330
                t.setText(t.getText().replaceAll(oldValue, newValue));
331
            } else if (obj instanceof Element) {
332
                replaceContentBy((Element) obj, oldValue, newValue);
333
            }
334
        }
335
    }
336
 
73 ilm 337
    /**
338
     * Set the raw value of the formula attribute.
339
     *
340
     * @param formula the raw value, e.g. "of:sum(A1:A2)".
341
     */
342
    public final void setRawFormula(final String formula) {
343
        // from 19.642 table:formula of OpenDocument-v1.2 : Whenever the initial text of a formula
344
        // has the appearance of an NCName followed by ":", an OpenDocument producer shall provide a
345
        // valid namespace prefix in order to eliminate any ambiguity.
346
        final String nsPrefix = getFormulaNSPrefix(formula).get0();
347
        if (nsPrefix != null && this.getElement().getNamespace(nsPrefix) == null) {
348
            throw new IllegalArgumentException("Unknown namespace prefix : " + nsPrefix);
349
        }
350
        this.setFormulaNoCheck(formula);
351
    }
352
 
353
    private final void setFormulaNoCheck(final String formula) {
354
        this.getElement().setAttribute("formula", formula, getTABLE());
355
    }
356
 
357
    public final void setFormulaAndNamespace(final Tuple2<Namespace, String> formula) {
358
        this.setFormulaAndNamespace(formula.get0(), formula.get1());
359
    }
360
 
361
    public final void setFormula(final String formula) {
362
        this.setFormulaAndNamespace(null, formula);
363
    }
364
 
365
    public final void setFormulaAndNamespace(final Namespace ns, final String formula) {
366
        if (getODDocument().getVersion() == XMLVersion.OOo) {
367
            if (ns != null)
368
                throw new IllegalArgumentException("Namespaces not supported by this version : " + ns);
369
            this.setFormulaNoCheck(formula);
370
        } else if (ns == null) {
371
            final String nsPrefix = getFormulaNSPrefix(formula).get0();
372
            if (nsPrefix != null) {
373
                // eliminate ambiguity
374
                final Namespace defaultNS = getDefaultFormulaNS();
375
                // prevent infinite recursion
376
                if (defaultNS == null)
377
                    throw new IllegalStateException("Cannot resolve ambiguity, formula appears to begin with " + nsPrefix + " and no default namespace found");
378
                this.setFormulaAndNamespace(defaultNS, formula);
379
            } else {
380
                this.setFormulaNoCheck(formula);
381
            }
382
        } else {
383
            final Namespace existingNS = this.getElement().getNamespace(ns.getPrefix());
384
            if (existingNS == null)
385
                this.getElement().getDocument().getRootElement().addNamespaceDeclaration(ns);
386
            else if (!existingNS.equals(ns))
387
                throw new IllegalStateException("Namespace conflict : " + existingNS + " != " + ns);
388
            this.setFormulaNoCheck(ns.getPrefix() + ':' + formula);
389
        }
390
    }
391
 
17 ilm 392
    public final void unmerge() {
393
        // from 8.1.3 Table Cell : table-cell are like covered-table-cell with some extra
394
        // optional attributes so it's safe to rename covered cells into normal ones
395
        final int x = this.getX();
396
        final int y = this.getY();
397
        final int columnsSpanned = getColumnsSpanned();
398
        final int rowsSpanned = getRowsSpanned();
399
        for (int i = 0; i < columnsSpanned; i++) {
400
            for (int j = 0; j < rowsSpanned; j++) {
401
                // don't mind if we change us at 0,0 we're already a table-cell
402
                this.getRow().getSheet().getImmutableCellAt(x + i, y + j).getElement().setName("table-cell");
403
            }
404
        }
405
        this.getElement().removeAttribute("number-columns-spanned", getNS().getTABLE());
406
        this.getElement().removeAttribute("number-rows-spanned", getNS().getTABLE());
407
    }
408
 
409
    /**
410
     * Merge this cell and the following ones. If this cell already spanned multiple columns/rows
411
     * this method un-merge any additional cells.
412
     *
413
     * @param columnsSpanned number of columns to merge.
414
     * @param rowsSpanned number of rows to merge.
415
     */
416
    public final void merge(final int columnsSpanned, final int rowsSpanned) {
417
        final int currentCols = this.getColumnsSpanned();
418
        final int currentRows = this.getRowsSpanned();
419
 
420
        // nothing to do
421
        if (columnsSpanned == currentCols && rowsSpanned == currentRows)
422
            return;
423
 
424
        final int x = this.getX();
425
        final int y = this.getY();
426
 
427
        // check for problems before any modifications
428
        for (int i = 0; i < columnsSpanned; i++) {
429
            for (int j = 0; j < rowsSpanned; j++) {
430
                final boolean coveredByThis = i < currentCols && j < currentRows;
431
                if (!coveredByThis) {
432
                    final int x2 = x + i;
433
                    final int y2 = y + j;
434
                    final Cell<D> immutableCell = this.getRow().getSheet().getImmutableCellAt(x2, y2);
435
                    // check for overlapping range from inside
436
                    if (immutableCell.coversOtherCells())
437
                        throw new IllegalArgumentException("Cell at " + x2 + "," + y2 + " is a merged cell.");
438
                    // and outside
439
                    if (immutableCell.getElement().getName().equals("covered-table-cell"))
440
                        throw new IllegalArgumentException("Cell at " + x2 + "," + y2 + " is already covered.");
441
                }
442
            }
443
        }
444
 
445
        final boolean shrinks = columnsSpanned < currentCols || rowsSpanned < currentRows;
446
        if (shrinks)
447
            this.unmerge();
448
 
449
        // from 8.1.3 Table Cell : table-cell are like covered-table-cell with some extra
450
        // optional attributes so it's safe to rename
451
        for (int i = 0; i < columnsSpanned; i++) {
452
            for (int j = 0; j < rowsSpanned; j++) {
453
                final boolean coveredByThis = i < currentCols && j < currentRows;
454
                // don't cover this,
455
                // if we grow the current covered cells are invalid so don't try to access them
456
                if ((i != 0 || j != 0) && (shrinks || !coveredByThis))
457
                    // MutableCell is needed to break repeated
458
                    this.getRow().getSheet().getCellAt(x + i, y + j).getElement().setName("covered-table-cell");
459
            }
460
        }
461
        this.getElement().setAttribute("number-columns-spanned", columnsSpanned + "", getNS().getTABLE());
462
        this.getElement().setAttribute("number-rows-spanned", rowsSpanned + "", getNS().getTABLE());
463
    }
464
 
465
    @Override
466
    public final String getStyleName() {
467
        return this.getRow().getSheet().getStyleNameAt(this.getX(), this.getY());
468
    }
469
 
73 ilm 470
    public final StyleTableCellProperties getTableCellProperties() {
471
        return this.getRow().getSheet().getTableCellPropertiesAt(this.getX(), this.getY());
472
    }
473
 
17 ilm 474
    public void setImage(final File pic) throws IOException {
475
        this.setImage(pic, false);
476
    }
477
 
478
    public void setImage(final File pic, boolean keepRatio) throws IOException {
479
        this.setImage(pic.getName(), new ByteArrayProducer(FileUtils.readBytes(pic), keepRatio));
480
    }
481
 
482
    public void setImage(final String name, final Image img) throws IOException {
483
        this.setImage(name, img == null ? null : new ImageProducer(img, true));
484
    }
485
 
486
    private void setImage(final String name, final BytesProducer data) {
487
        final Namespace draw = this.getNS().getNS("draw");
488
        final Element frame = this.getElement().getChild("frame", draw);
489
        final Element imageElem = frame == null ? null : frame.getChild("image", draw);
490
 
491
        if (imageElem != null) {
492
            final Attribute refAttr = imageElem.getAttribute("href", this.getNS().getNS("xlink"));
493
            this.getODDocument().getPackage().putFile(refAttr.getValue(), null);
494
 
495
            if (data == null)
496
                frame.detach();
497
            else {
498
                refAttr.setValue("Pictures/" + name + (data.getFormat() != null ? "." + data.getFormat() : ""));
499
                this.getODDocument().getPackage().putFile(refAttr.getValue(), data.getBytes(new ODFrame<D>(getODDocument(), frame)));
500
            }
501
        } else if (data != null)
502
            throw new IllegalStateException("this cell doesn't contain an image: " + this);
503
    }
504
 
505
    public final void setBackgroundColor(final Color color) {
73 ilm 506
        this.getPrivateStyle().getTableCellProperties(this).setBackgroundColor(color);
17 ilm 507
    }
508
}