OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

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