OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

Rev 21 | Rev 57 | 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 {
25 ilm 162
            type = ODValueType.forObject(obj);
163
        }
164
        if (type == null) {
20 ilm 165
            throw new IllegalArgumentException("Couldn't infer type of " + obj);
166
        }
25 ilm 167
        this.setValue(obj, type, allowTypeChange, true);
20 ilm 168
    }
169
 
170
    /**
171
     * Change the value of this cell.
172
     *
173
     * @param obj the new cell value.
174
     * @param vt the value type.
25 ilm 175
     * @param allowTypeChange if <code>true</code> <code>obj</code> and <code>vt</code> might be
176
     *        changed to allow the data style to format, e.g. from Boolean.FALSE to 0.
20 ilm 177
     * @param lenient <code>false</code> to throw an exception if we can't format according to the
178
     *        ODF, <code>true</code> to try best-effort.
179
     * @throws UnsupportedOperationException if <code>obj</code> couldn't be formatted.
180
     */
25 ilm 181
    public void setValue(Object obj, ODValueType vt, final boolean allowTypeChange, final boolean lenient) throws UnsupportedOperationException {
20 ilm 182
        final String text;
25 ilm 183
        final Tuple3<String, ODValueType, Object> formatted = format(obj, vt, !allowTypeChange, lenient);
184
        vt = formatted.get1();
185
        obj = formatted.get2();
20 ilm 186
 
25 ilm 187
        if (formatted.get0() != null) {
188
            text = formatted.get0();
20 ilm 189
        } else {
190
            // either there were no format or formatting failed
191
            if (vt == ODValueType.FLOAT) {
192
                text = formatNumber((Number) obj, getDefaultStyle());
193
            } else if (vt == ODValueType.PERCENTAGE) {
194
                text = formatPercent((Number) obj, getDefaultStyle());
195
            } else if (vt == ODValueType.CURRENCY) {
196
                text = formatCurrency((Number) obj, getDefaultStyle());
197
            } else if (vt == ODValueType.DATE) {
25 ilm 198
                final Date d;
199
                if (obj instanceof Calendar) {
200
                    d = ((Calendar) obj).getTime();
201
                } else {
202
                    d = (Date) obj;
203
                }
204
                text = TextPDateFormat.format(d);
20 ilm 205
            } else if (vt == ODValueType.TIME) {
25 ilm 206
                if (obj instanceof Duration) {
207
                    final Duration normalized = getODDocument().getEpoch().normalizeToHours((Duration) obj);
208
                    text = "" + normalized.getHours() + ':' + TextPMinuteSecondFormat.format(normalized.getMinutes()) + ':'
209
                            + TextPMinuteSecondFormat.format(normalized.getField(DatatypeConstants.SECONDS));
210
                } else {
211
                    text = TextPTimeFormat.format(((Calendar) obj).getTime());
212
                }
20 ilm 213
            } else if (vt == ODValueType.BOOLEAN) {
214
                if (lenient)
215
                    text = obj.toString();
216
                else
217
                    throw new UnsupportedOperationException(vt + " not supported");
218
            } else if (vt == ODValueType.STRING) {
219
                text = obj.toString();
19 ilm 220
            } else {
20 ilm 221
                throw new IllegalStateException(vt + " unknown");
19 ilm 222
            }
20 ilm 223
        }
224
        this.setValue(vt, obj, text);
17 ilm 225
    }
226
 
25 ilm 227
    // return null String if no data style exists, or if one exists but we couldn't use it
228
    private Tuple3<String, ODValueType, Object> format(Object obj, ODValueType valueType, boolean onlyCast, boolean lenient) {
229
        String res = null;
20 ilm 230
        try {
25 ilm 231
            final Tuple3<DataStyle, ODValueType, Object> ds = getDataStyleAndValue(obj, valueType, onlyCast);
232
            if (ds != null) {
233
                obj = ds.get2();
234
                valueType = ds.get1();
235
                // act like OO, that is if we set a String to a Date cell, change the value and
236
                // value-type but leave the data-style untouched
237
                if (ds.get0().canFormat(obj.getClass()))
238
                    res = ds.get0().format(obj, getDefaultStyle(), lenient);
239
            }
20 ilm 240
        } catch (UnsupportedOperationException e) {
241
            if (lenient)
242
                Log.get().warning(ExceptionUtils.getStackTrace(e));
243
            else
244
                throw e;
245
        }
25 ilm 246
        return Tuple3.create(res, valueType, obj);
20 ilm 247
    }
248
 
249
    public final DataStyle getDataStyle() {
25 ilm 250
        final Tuple3<DataStyle, ODValueType, Object> s = this.getDataStyleAndValue(this.getValue(), this.getValueType(), true);
251
        return s != null ? s.get0() : null;
252
    }
253
 
254
    private final Tuple3<DataStyle, ODValueType, Object> getDataStyleAndValue(Object obj, ODValueType valueType, boolean onlyCast) {
20 ilm 255
        final CellStyle s = this.getStyle();
25 ilm 256
        return s != null ? getStyle().getDataStyle(obj, valueType, onlyCast) : null;
20 ilm 257
    }
258
 
259
    protected final CellStyle getDefaultStyle() {
260
        return this.getRow().getSheet().getDefaultCellStyle();
261
    }
262
 
17 ilm 263
    public void replaceBy(String oldValue, String newValue) {
264
        replaceContentBy(this.getElement(), oldValue, newValue);
265
    }
266
 
267
    private void replaceContentBy(Element l, String oldValue, String newValue) {
20 ilm 268
        final List<?> content = l.getContent();
17 ilm 269
        for (int i = 0; i < content.size(); i++) {
270
            final Object obj = content.get(i);
271
            if (obj instanceof Text) {
272
                // System.err.println(" Text --> " + obj.toString());
273
                final Text t = (Text) obj;
274
                t.setText(t.getText().replaceAll(oldValue, newValue));
275
            } else if (obj instanceof Element) {
276
                replaceContentBy((Element) obj, oldValue, newValue);
277
            }
278
        }
279
    }
280
 
281
    public final void unmerge() {
282
        // from 8.1.3 Table Cell : table-cell are like covered-table-cell with some extra
283
        // optional attributes so it's safe to rename covered cells into normal ones
284
        final int x = this.getX();
285
        final int y = this.getY();
286
        final int columnsSpanned = getColumnsSpanned();
287
        final int rowsSpanned = getRowsSpanned();
288
        for (int i = 0; i < columnsSpanned; i++) {
289
            for (int j = 0; j < rowsSpanned; j++) {
290
                // don't mind if we change us at 0,0 we're already a table-cell
291
                this.getRow().getSheet().getImmutableCellAt(x + i, y + j).getElement().setName("table-cell");
292
            }
293
        }
294
        this.getElement().removeAttribute("number-columns-spanned", getNS().getTABLE());
295
        this.getElement().removeAttribute("number-rows-spanned", getNS().getTABLE());
296
    }
297
 
298
    /**
299
     * Merge this cell and the following ones. If this cell already spanned multiple columns/rows
300
     * this method un-merge any additional cells.
301
     *
302
     * @param columnsSpanned number of columns to merge.
303
     * @param rowsSpanned number of rows to merge.
304
     */
305
    public final void merge(final int columnsSpanned, final int rowsSpanned) {
306
        final int currentCols = this.getColumnsSpanned();
307
        final int currentRows = this.getRowsSpanned();
308
 
309
        // nothing to do
310
        if (columnsSpanned == currentCols && rowsSpanned == currentRows)
311
            return;
312
 
313
        final int x = this.getX();
314
        final int y = this.getY();
315
 
316
        // check for problems before any modifications
317
        for (int i = 0; i < columnsSpanned; i++) {
318
            for (int j = 0; j < rowsSpanned; j++) {
319
                final boolean coveredByThis = i < currentCols && j < currentRows;
320
                if (!coveredByThis) {
321
                    final int x2 = x + i;
322
                    final int y2 = y + j;
323
                    final Cell<D> immutableCell = this.getRow().getSheet().getImmutableCellAt(x2, y2);
324
                    // check for overlapping range from inside
325
                    if (immutableCell.coversOtherCells())
326
                        throw new IllegalArgumentException("Cell at " + x2 + "," + y2 + " is a merged cell.");
327
                    // and outside
328
                    if (immutableCell.getElement().getName().equals("covered-table-cell"))
329
                        throw new IllegalArgumentException("Cell at " + x2 + "," + y2 + " is already covered.");
330
                }
331
            }
332
        }
333
 
334
        final boolean shrinks = columnsSpanned < currentCols || rowsSpanned < currentRows;
335
        if (shrinks)
336
            this.unmerge();
337
 
338
        // from 8.1.3 Table Cell : table-cell are like covered-table-cell with some extra
339
        // optional attributes so it's safe to rename
340
        for (int i = 0; i < columnsSpanned; i++) {
341
            for (int j = 0; j < rowsSpanned; j++) {
342
                final boolean coveredByThis = i < currentCols && j < currentRows;
343
                // don't cover this,
344
                // if we grow the current covered cells are invalid so don't try to access them
345
                if ((i != 0 || j != 0) && (shrinks || !coveredByThis))
346
                    // MutableCell is needed to break repeated
347
                    this.getRow().getSheet().getCellAt(x + i, y + j).getElement().setName("covered-table-cell");
348
            }
349
        }
350
        this.getElement().setAttribute("number-columns-spanned", columnsSpanned + "", getNS().getTABLE());
351
        this.getElement().setAttribute("number-rows-spanned", rowsSpanned + "", getNS().getTABLE());
352
    }
353
 
354
    @Override
355
    public final String getStyleName() {
356
        return this.getRow().getSheet().getStyleNameAt(this.getX(), this.getY());
357
    }
358
 
359
    public void setImage(final File pic) throws IOException {
360
        this.setImage(pic, false);
361
    }
362
 
363
    public void setImage(final File pic, boolean keepRatio) throws IOException {
364
        this.setImage(pic.getName(), new ByteArrayProducer(FileUtils.readBytes(pic), keepRatio));
365
    }
366
 
367
    public void setImage(final String name, final Image img) throws IOException {
368
        this.setImage(name, img == null ? null : new ImageProducer(img, true));
369
    }
370
 
371
    private void setImage(final String name, final BytesProducer data) {
372
        final Namespace draw = this.getNS().getNS("draw");
373
        final Element frame = this.getElement().getChild("frame", draw);
374
        final Element imageElem = frame == null ? null : frame.getChild("image", draw);
375
 
376
        if (imageElem != null) {
377
            final Attribute refAttr = imageElem.getAttribute("href", this.getNS().getNS("xlink"));
378
            this.getODDocument().getPackage().putFile(refAttr.getValue(), null);
379
 
380
            if (data == null)
381
                frame.detach();
382
            else {
383
                refAttr.setValue("Pictures/" + name + (data.getFormat() != null ? "." + data.getFormat() : ""));
384
                this.getODDocument().getPackage().putFile(refAttr.getValue(), data.getBytes(new ODFrame<D>(getODDocument(), frame)));
385
            }
386
        } else if (data != null)
387
            throw new IllegalStateException("this cell doesn't contain an image: " + this);
388
    }
389
 
390
    public final void setBackgroundColor(final Color color) {
391
        this.getPrivateStyle().getTableCellProperties().setBackgroundColor(color);
392
    }
393
}