OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

Rev 25 | Rev 61 | 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;
17 ilm 22
import org.openconcerto.openoffice.spreadsheet.BytesProducer.ByteArrayProducer;
23
import org.openconcerto.openoffice.spreadsheet.BytesProducer.ImageProducer;
20 ilm 24
import org.openconcerto.openoffice.style.data.DataStyle;
25
import org.openconcerto.utils.ExceptionUtils;
17 ilm 26
import org.openconcerto.utils.FileUtils;
25 ilm 27
import org.openconcerto.utils.Tuple3;
17 ilm 28
 
29
import java.awt.Color;
30
import java.awt.Image;
21 ilm 31
import java.awt.Point;
17 ilm 32
import java.io.File;
33
import java.io.IOException;
34
import java.text.DateFormat;
35
import java.text.DecimalFormat;
36
import java.text.NumberFormat;
20 ilm 37
import java.util.Calendar;
17 ilm 38
import java.util.Date;
39
import java.util.List;
40
 
25 ilm 41
import javax.xml.datatype.DatatypeConstants;
42
import javax.xml.datatype.Duration;
43
 
17 ilm 44
import org.jdom.Attribute;
45
import org.jdom.Element;
46
import org.jdom.Namespace;
47
import org.jdom.Text;
48
 
49
/**
50
 * A cell whose value can be changed.
51
 *
52
 * @author Sylvain
53
 * @param <D> type of document
54
 */
55
public class MutableCell<D extends ODDocument> extends Cell<D> {
56
 
20 ilm 57
    static private final DateFormat TextPDateFormat = DateFormat.getDateInstance();
58
    static private final DateFormat TextPTimeFormat = DateFormat.getTimeInstance();
25 ilm 59
    static private final NumberFormat TextPMinuteSecondFormat = new DecimalFormat("00.###");
20 ilm 60
    static private final NumberFormat TextPFloatFormat = DecimalFormat.getNumberInstance();
61
    static private final NumberFormat TextPPercentFormat = DecimalFormat.getPercentInstance();
62
    static private final NumberFormat TextPCurrencyFormat = DecimalFormat.getCurrencyInstance();
17 ilm 63
 
20 ilm 64
    static public String formatNumber(Number n, final CellStyle defaultStyle) {
65
        return formatNumber(TextPFloatFormat, n, defaultStyle, false);
66
    }
67
 
68
    static public String formatPercent(Number n, final CellStyle defaultStyle) {
69
        return formatNumber(TextPPercentFormat, n, defaultStyle, true);
70
    }
71
 
72
    static public String formatCurrency(Number n, final CellStyle defaultStyle) {
73
        return formatNumber(TextPCurrencyFormat, n, defaultStyle, true);
74
    }
75
 
76
    static private String formatNumber(NumberFormat format, Number n, final CellStyle defaultStyle, boolean forceFraction) {
77
        synchronized (format) {
78
            final int decPlaces = DataStyle.getDecimalPlaces(defaultStyle);
79
            format.setMinimumFractionDigits(forceFraction ? decPlaces : 0);
80
            format.setMaximumFractionDigits(decPlaces);
81
            return format.format(n);
82
        }
83
    }
84
 
25 ilm 85
    MutableCell(Row<D> parent, Element elem, StyleDesc<CellStyle> styleDesc) {
86
        super(parent, elem, styleDesc);
17 ilm 87
    }
88
 
89
    // ask our column to our row so we don't have to update anything when columns are removed/added
90
    public final int getX() {
91
        return this.getRow().getX(this);
92
    }
93
 
94
    public final int getY() {
95
        return this.getRow().getY();
96
    }
97
 
21 ilm 98
    public final Point getPoint() {
99
        return new Point(getX(), getY());
100
    }
101
 
102
    final void setRowsSpanned(final int rowsSpanned) {
103
        if (rowsSpanned <= 1)
104
            this.getElement().removeAttribute("number-rows-spanned", getNS().getTABLE());
105
        else
106
            this.getElement().setAttribute("number-rows-spanned", String.valueOf(rowsSpanned), getNS().getTABLE());
107
    }
108
 
17 ilm 109
    // *** setValue
110
 
111
    private void setValueAttributes(ODValueType type, Object val) {
112
        if (type == null) {
113
            final Attribute valueTypeAttr = this.getElement().getAttribute("value-type", getValueNS());
114
            if (valueTypeAttr != null) {
115
                valueTypeAttr.detach();
116
                this.getElement().removeAttribute(ODValueType.get(valueTypeAttr.getValue()).getValueAttribute(), getValueNS());
117
            }
118
        } else {
119
            this.getElement().setAttribute("value-type", type.getName(), getValueNS());
120
            this.getElement().setAttribute(type.getValueAttribute(), type.format(val), getValueNS());
121
        }
122
    }
123
 
124
    // ATTN this removes any content associated with this cell be it notes, cell anchored objects,
125
    // etc. This is because it's difficult to tell apart the text content and the rest (e.g. notes),
126
    // for example in Calc office:annotation is a child of table:cell whereas in Writer it's a child
127
    // of text:p.
128
    private void setTextP(String value) {
129
        if (value == null)
130
            this.getElement().removeContent();
131
        else {
132
            // try to reuse the first text:p to keep style
133
            final Element child = this.getElement().getChild("p", getNS().getTEXT());
134
            final Element t = child != null ? child : new Element("p", getNS().getTEXT());
20 ilm 135
            t.setContent(OOXML.get(this.getODDocument().getFormatVersion()).encodeWSasList(value));
17 ilm 136
 
137
            this.getElement().setContent(t);
138
        }
139
    }
140
 
141
    private void setValue(ODValueType type, Object value, String textP) {
142
        this.setValueAttributes(type, value);
143
        this.setTextP(textP);
144
    }
145
 
146
    public void clearValue() {
147
        this.setValue(null, null, null);
148
    }
149
 
150
    public void setValue(Object obj) {
25 ilm 151
        this.setValue(obj, true);
152
    }
153
 
154
    public void setValue(Object obj, final boolean allowTypeChange) throws UnsupportedOperationException {
20 ilm 155
        final ODValueType type;
156
        final ODValueType currentType = getValueType();
157
        // try to keep current type, since for example a Number can work with FLOAT, PERCENTAGE
158
        // and CURRENCY
159
        if (currentType != null && currentType.canFormat(obj.getClass())) {
160
            type = currentType;
161
        } else {
57 ilm 162
            final ODValueType tmp = ODValueType.forObject(obj);
163
            // allow any Object
164
            if (allowTypeChange && tmp == null) {
165
                type = ODValueType.STRING;
166
                obj = String.valueOf(obj);
167
            } else {
168
                type = tmp;
169
            }
25 ilm 170
        }
171
        if (type == null) {
20 ilm 172
            throw new IllegalArgumentException("Couldn't infer type of " + obj);
173
        }
25 ilm 174
        this.setValue(obj, type, allowTypeChange, true);
20 ilm 175
    }
176
 
177
    /**
178
     * Change the value of this cell.
179
     *
180
     * @param obj the new cell value.
181
     * @param vt the value type.
25 ilm 182
     * @param allowTypeChange if <code>true</code> <code>obj</code> and <code>vt</code> might be
183
     *        changed to allow the data style to format, e.g. from Boolean.FALSE to 0.
20 ilm 184
     * @param lenient <code>false</code> to throw an exception if we can't format according to the
185
     *        ODF, <code>true</code> to try best-effort.
186
     * @throws UnsupportedOperationException if <code>obj</code> couldn't be formatted.
187
     */
25 ilm 188
    public void setValue(Object obj, ODValueType vt, final boolean allowTypeChange, final boolean lenient) throws UnsupportedOperationException {
20 ilm 189
        final String text;
25 ilm 190
        final Tuple3<String, ODValueType, Object> formatted = format(obj, vt, !allowTypeChange, lenient);
191
        vt = formatted.get1();
192
        obj = formatted.get2();
20 ilm 193
 
25 ilm 194
        if (formatted.get0() != null) {
195
            text = formatted.get0();
20 ilm 196
        } else {
197
            // either there were no format or formatting failed
198
            if (vt == ODValueType.FLOAT) {
199
                text = formatNumber((Number) obj, getDefaultStyle());
200
            } else if (vt == ODValueType.PERCENTAGE) {
201
                text = formatPercent((Number) obj, getDefaultStyle());
202
            } else if (vt == ODValueType.CURRENCY) {
203
                text = formatCurrency((Number) obj, getDefaultStyle());
204
            } else if (vt == ODValueType.DATE) {
25 ilm 205
                final Date d;
206
                if (obj instanceof Calendar) {
207
                    d = ((Calendar) obj).getTime();
208
                } else {
209
                    d = (Date) obj;
210
                }
211
                text = TextPDateFormat.format(d);
20 ilm 212
            } else if (vt == ODValueType.TIME) {
25 ilm 213
                if (obj instanceof Duration) {
214
                    final Duration normalized = getODDocument().getEpoch().normalizeToHours((Duration) obj);
215
                    text = "" + normalized.getHours() + ':' + TextPMinuteSecondFormat.format(normalized.getMinutes()) + ':'
216
                            + TextPMinuteSecondFormat.format(normalized.getField(DatatypeConstants.SECONDS));
217
                } else {
218
                    text = TextPTimeFormat.format(((Calendar) obj).getTime());
219
                }
20 ilm 220
            } else if (vt == ODValueType.BOOLEAN) {
221
                if (lenient)
222
                    text = obj.toString();
223
                else
224
                    throw new UnsupportedOperationException(vt + " not supported");
225
            } else if (vt == ODValueType.STRING) {
226
                text = obj.toString();
19 ilm 227
            } else {
20 ilm 228
                throw new IllegalStateException(vt + " unknown");
19 ilm 229
            }
20 ilm 230
        }
231
        this.setValue(vt, obj, text);
17 ilm 232
    }
233
 
25 ilm 234
    // return null String if no data style exists, or if one exists but we couldn't use it
235
    private Tuple3<String, ODValueType, Object> format(Object obj, ODValueType valueType, boolean onlyCast, boolean lenient) {
236
        String res = null;
20 ilm 237
        try {
25 ilm 238
            final Tuple3<DataStyle, ODValueType, Object> ds = getDataStyleAndValue(obj, valueType, onlyCast);
239
            if (ds != null) {
240
                obj = ds.get2();
241
                valueType = ds.get1();
242
                // act like OO, that is if we set a String to a Date cell, change the value and
243
                // value-type but leave the data-style untouched
244
                if (ds.get0().canFormat(obj.getClass()))
245
                    res = ds.get0().format(obj, getDefaultStyle(), lenient);
246
            }
20 ilm 247
        } catch (UnsupportedOperationException e) {
248
            if (lenient)
249
                Log.get().warning(ExceptionUtils.getStackTrace(e));
250
            else
251
                throw e;
252
        }
25 ilm 253
        return Tuple3.create(res, valueType, obj);
20 ilm 254
    }
255
 
256
    public final DataStyle getDataStyle() {
25 ilm 257
        final Tuple3<DataStyle, ODValueType, Object> s = this.getDataStyleAndValue(this.getValue(), this.getValueType(), true);
258
        return s != null ? s.get0() : null;
259
    }
260
 
261
    private final Tuple3<DataStyle, ODValueType, Object> getDataStyleAndValue(Object obj, ODValueType valueType, boolean onlyCast) {
20 ilm 262
        final CellStyle s = this.getStyle();
25 ilm 263
        return s != null ? getStyle().getDataStyle(obj, valueType, onlyCast) : null;
20 ilm 264
    }
265
 
266
    protected final CellStyle getDefaultStyle() {
267
        return this.getRow().getSheet().getDefaultCellStyle();
268
    }
269
 
17 ilm 270
    public void replaceBy(String oldValue, String newValue) {
271
        replaceContentBy(this.getElement(), oldValue, newValue);
272
    }
273
 
274
    private void replaceContentBy(Element l, String oldValue, String newValue) {
20 ilm 275
        final List<?> content = l.getContent();
17 ilm 276
        for (int i = 0; i < content.size(); i++) {
277
            final Object obj = content.get(i);
278
            if (obj instanceof Text) {
279
                // System.err.println(" Text --> " + obj.toString());
280
                final Text t = (Text) obj;
281
                t.setText(t.getText().replaceAll(oldValue, newValue));
282
            } else if (obj instanceof Element) {
283
                replaceContentBy((Element) obj, oldValue, newValue);
284
            }
285
        }
286
    }
287
 
288
    public final void unmerge() {
289
        // from 8.1.3 Table Cell : table-cell are like covered-table-cell with some extra
290
        // optional attributes so it's safe to rename covered cells into normal ones
291
        final int x = this.getX();
292
        final int y = this.getY();
293
        final int columnsSpanned = getColumnsSpanned();
294
        final int rowsSpanned = getRowsSpanned();
295
        for (int i = 0; i < columnsSpanned; i++) {
296
            for (int j = 0; j < rowsSpanned; j++) {
297
                // don't mind if we change us at 0,0 we're already a table-cell
298
                this.getRow().getSheet().getImmutableCellAt(x + i, y + j).getElement().setName("table-cell");
299
            }
300
        }
301
        this.getElement().removeAttribute("number-columns-spanned", getNS().getTABLE());
302
        this.getElement().removeAttribute("number-rows-spanned", getNS().getTABLE());
303
    }
304
 
305
    /**
306
     * Merge this cell and the following ones. If this cell already spanned multiple columns/rows
307
     * this method un-merge any additional cells.
308
     *
309
     * @param columnsSpanned number of columns to merge.
310
     * @param rowsSpanned number of rows to merge.
311
     */
312
    public final void merge(final int columnsSpanned, final int rowsSpanned) {
313
        final int currentCols = this.getColumnsSpanned();
314
        final int currentRows = this.getRowsSpanned();
315
 
316
        // nothing to do
317
        if (columnsSpanned == currentCols && rowsSpanned == currentRows)
318
            return;
319
 
320
        final int x = this.getX();
321
        final int y = this.getY();
322
 
323
        // check for problems before any modifications
324
        for (int i = 0; i < columnsSpanned; i++) {
325
            for (int j = 0; j < rowsSpanned; j++) {
326
                final boolean coveredByThis = i < currentCols && j < currentRows;
327
                if (!coveredByThis) {
328
                    final int x2 = x + i;
329
                    final int y2 = y + j;
330
                    final Cell<D> immutableCell = this.getRow().getSheet().getImmutableCellAt(x2, y2);
331
                    // check for overlapping range from inside
332
                    if (immutableCell.coversOtherCells())
333
                        throw new IllegalArgumentException("Cell at " + x2 + "," + y2 + " is a merged cell.");
334
                    // and outside
335
                    if (immutableCell.getElement().getName().equals("covered-table-cell"))
336
                        throw new IllegalArgumentException("Cell at " + x2 + "," + y2 + " is already covered.");
337
                }
338
            }
339
        }
340
 
341
        final boolean shrinks = columnsSpanned < currentCols || rowsSpanned < currentRows;
342
        if (shrinks)
343
            this.unmerge();
344
 
345
        // from 8.1.3 Table Cell : table-cell are like covered-table-cell with some extra
346
        // optional attributes so it's safe to rename
347
        for (int i = 0; i < columnsSpanned; i++) {
348
            for (int j = 0; j < rowsSpanned; j++) {
349
                final boolean coveredByThis = i < currentCols && j < currentRows;
350
                // don't cover this,
351
                // if we grow the current covered cells are invalid so don't try to access them
352
                if ((i != 0 || j != 0) && (shrinks || !coveredByThis))
353
                    // MutableCell is needed to break repeated
354
                    this.getRow().getSheet().getCellAt(x + i, y + j).getElement().setName("covered-table-cell");
355
            }
356
        }
357
        this.getElement().setAttribute("number-columns-spanned", columnsSpanned + "", getNS().getTABLE());
358
        this.getElement().setAttribute("number-rows-spanned", rowsSpanned + "", getNS().getTABLE());
359
    }
360
 
361
    @Override
362
    public final String getStyleName() {
363
        return this.getRow().getSheet().getStyleNameAt(this.getX(), this.getY());
364
    }
365
 
366
    public void setImage(final File pic) throws IOException {
367
        this.setImage(pic, false);
368
    }
369
 
370
    public void setImage(final File pic, boolean keepRatio) throws IOException {
371
        this.setImage(pic.getName(), new ByteArrayProducer(FileUtils.readBytes(pic), keepRatio));
372
    }
373
 
374
    public void setImage(final String name, final Image img) throws IOException {
375
        this.setImage(name, img == null ? null : new ImageProducer(img, true));
376
    }
377
 
378
    private void setImage(final String name, final BytesProducer data) {
379
        final Namespace draw = this.getNS().getNS("draw");
380
        final Element frame = this.getElement().getChild("frame", draw);
381
        final Element imageElem = frame == null ? null : frame.getChild("image", draw);
382
 
383
        if (imageElem != null) {
384
            final Attribute refAttr = imageElem.getAttribute("href", this.getNS().getNS("xlink"));
385
            this.getODDocument().getPackage().putFile(refAttr.getValue(), null);
386
 
387
            if (data == null)
388
                frame.detach();
389
            else {
390
                refAttr.setValue("Pictures/" + name + (data.getFormat() != null ? "." + data.getFormat() : ""));
391
                this.getODDocument().getPackage().putFile(refAttr.getValue(), data.getBytes(new ODFrame<D>(getODDocument(), frame)));
392
            }
393
        } else if (data != null)
394
            throw new IllegalStateException("this cell doesn't contain an image: " + this);
395
    }
396
 
397
    public final void setBackgroundColor(final Color color) {
398
        this.getPrivateStyle().getTableCellProperties().setBackgroundColor(color);
399
    }
400
}