OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

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