OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

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