OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

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