OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

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