OpenConcerto

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

svn://code.openconcerto.org/openconcerto

Rev

Rev 20 | Rev 28 | 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
 /*
15
 * Créé le 28 oct. 2004
16
 */
17
package org.openconcerto.openoffice;
18
 
19 ilm 19
import org.openconcerto.utils.CollectionUtils;
17 ilm 20
import org.openconcerto.xml.JDOMUtils;
21
import org.openconcerto.xml.Validator;
22
 
21 ilm 23
import java.math.BigDecimal;
17 ilm 24
import java.util.ArrayList;
25
import java.util.HashMap;
26
import java.util.Iterator;
27
import java.util.List;
28
import java.util.Map;
29
import java.util.Map.Entry;
19 ilm 30
import java.util.SortedMap;
31
import java.util.TreeMap;
17 ilm 32
import java.util.regex.Matcher;
33
import java.util.regex.Pattern;
34
 
35
import javax.xml.XMLConstants;
36
import javax.xml.validation.Schema;
37
import javax.xml.validation.SchemaFactory;
38
 
39
import org.jdom.Content;
40
import org.jdom.Document;
41
import org.jdom.Element;
42
import org.jdom.JDOMException;
43
import org.jdom.Namespace;
44
import org.jdom.Parent;
45
import org.jdom.Text;
46
import org.jdom.xpath.XPath;
47
import org.xml.sax.SAXException;
48
 
49
/**
50
 * Various bits of OpenDocument XML.
51
 *
52
 * @author Sylvain CUAZ
19 ilm 53
 * @see #get(XMLFormatVersion)
17 ilm 54
 */
19 ilm 55
public abstract class OOXML implements Comparable<OOXML> {
17 ilm 56
 
19 ilm 57
    /**
58
     * If this system property is set to <code>true</code> then {@link #get(XMLFormatVersion)} will
59
     * never return <code>null</code>, allowing to support unknown versions.
60
     */
61
    public static final String LAST_FOR_UNKNOWN_PROP = OOXML.class.getPackage().getName() + ".lastOOXMLForUnknownVersion";
62
    private static final XML_OO instanceOO = new XML_OO();
63
    private static final SortedMap<String, XML_OD> instancesODByDate = new TreeMap<String, XML_OD>();
64
    private static final Map<String, XML_OD> instancesODByVersion = new HashMap<String, XML_OD>();
65
    private static final List<OOXML> values;
66
    private static OOXML defaultInstance;
17 ilm 67
 
19 ilm 68
    static {
69
        register(new XML_OD_1_0());
70
        register(new XML_OD_1_1());
71
        register(new XML_OD_1_2());
72
        values = new ArrayList<OOXML>(instancesODByDate.size() + 1);
73
        values.add(instanceOO);
74
        values.addAll(instancesODByDate.values());
75
 
76
        setDefault(getLast());
77
    }
78
 
79
    private static void register(XML_OD xml) {
80
        assert xml.getVersion() == XMLVersion.OD;
81
        instancesODByDate.put(xml.getDateString(), xml);
82
        instancesODByVersion.put(xml.getFormatVersion().getOfficeVersion(), xml);
83
    }
84
 
17 ilm 85
    /**
86
     * Returns the instance that match the requested version.
87
     *
88
     * @param version the version.
19 ilm 89
     * @return the corresponding instance, <code>null</code> for unsupported versions.
90
     * @see #LAST_FOR_UNKNOWN_PROP
17 ilm 91
     */
19 ilm 92
    public static OOXML get(XMLFormatVersion version) {
93
        return get(version, Boolean.getBoolean(LAST_FOR_UNKNOWN_PROP));
17 ilm 94
    }
95
 
19 ilm 96
    public static OOXML get(XMLFormatVersion version, final boolean lastForUnknown) {
97
        if (version.getXMLVersion() == XMLVersion.OOo) {
98
            return instanceOO;
99
        } else {
100
            final XML_OD res = instancesODByVersion.get(version.getOfficeVersion());
101
            if (res == null && lastForUnknown)
102
                return getLast(version.getXMLVersion());
103
            else
104
                return res;
105
        }
17 ilm 106
    }
107
 
19 ilm 108
    public static OOXML get(Element root) {
109
        return XMLFormatVersion.get(root).getXML();
17 ilm 110
    }
111
 
112
    /**
19 ilm 113
     * Return all known instances in the order they were published.
17 ilm 114
     *
19 ilm 115
     * @return all known instances ordered.
116
     * @see #compareTo(OOXML)
17 ilm 117
     */
19 ilm 118
    static public final List<OOXML> values() {
119
        return values;
120
    }
17 ilm 121
 
19 ilm 122
    static public final OOXML getLast() {
123
        return CollectionUtils.getLast(values);
124
    }
17 ilm 125
 
19 ilm 126
    static public final OOXML getLast(XMLVersion version) {
127
        if (version == XMLVersion.OOo)
128
            return instanceOO;
129
        else
130
            return instancesODByDate.get(instancesODByDate.lastKey());
17 ilm 131
    }
132
 
19 ilm 133
    public static void setDefault(OOXML ns) {
134
        defaultInstance = ns;
135
    }
136
 
137
    public static OOXML getDefault() {
138
        return defaultInstance;
139
    }
140
 
141
    static private final String rt2oo(String content, String tagName, String styleName) {
142
        return content.replaceAll("\\[" + tagName + "\\]", "<text:span text:style-name=\"" + styleName + "\">").replaceAll("\\[/" + tagName + "\\]", "</text:span>");
143
    }
144
 
21 ilm 145
    static private final BigDecimal parseLength(final Element elem, final String attrName, final Namespace ns, LengthUnit unit) {
146
        final String attr = elem.getAttributeValue(attrName, ns);
147
        if (attr == null)
148
            return null;
149
        return LengthUnit.parsePositiveLength(attr, unit, false);
150
    }
151
 
17 ilm 152
    // *** instances
153
 
19 ilm 154
    private final XMLFormatVersion version;
155
    private final String dateString;
17 ilm 156
 
19 ilm 157
    private OOXML(XMLFormatVersion version, final String dateString) {
17 ilm 158
        this.version = version;
19 ilm 159
        this.dateString = dateString;
17 ilm 160
    }
161
 
19 ilm 162
    /**
163
     * The date the specification was published.
164
     *
165
     * @return the date in "yyyyMMdd" format.
166
     */
167
    public final String getDateString() {
168
        return this.dateString;
169
    }
170
 
171
    /**
172
     * Compare the date the specification was published.
173
     *
174
     * @param o the object to be compared.
175
     * @see #getDateString()
176
     */
177
    @Override
178
    public int compareTo(OOXML o) {
179
        return this.dateString.compareTo(o.dateString);
180
    }
181
 
17 ilm 182
    public final XMLVersion getVersion() {
19 ilm 183
        return this.getFormatVersion().getXMLVersion();
17 ilm 184
    }
185
 
19 ilm 186
    public final XMLFormatVersion getFormatVersion() {
187
        return this.version;
17 ilm 188
    }
189
 
19 ilm 190
    public abstract boolean canValidate();
191
 
17 ilm 192
    /**
193
     * Verify that the passed document is a valid OpenOffice.org 1 or ODF document.
194
     *
195
     * @param doc the xml to test.
196
     * @return a validator on <code>doc</code>.
197
     */
19 ilm 198
    public abstract Validator getValidator(Document doc);
17 ilm 199
 
200
    /**
201
     * Return the names of font face declarations.
202
     *
203
     * @return at index 0 the name of the container element, at 1 the qualified name of its
204
     *         children.
205
     */
19 ilm 206
    public abstract String[] getFontDecls();
17 ilm 207
 
208
    public final Element getLineBreak() {
209
        return new Element("line-break", getVersion().getTEXT());
210
    }
211
 
19 ilm 212
    public abstract Element getTab();
17 ilm 213
 
19 ilm 214
    public abstract String getFrameQName();
17 ilm 215
 
19 ilm 216
    public abstract Element createFormattingProperties(final String family);
217
 
218
    protected final List encodeRT_L(String content, Map<String, String> styles) {
17 ilm 219
        String res = JDOMUtils.OUTPUTTER.escapeElementEntities(content);
19 ilm 220
        for (final Entry<String, String> e : styles.entrySet()) {
221
            res = rt2oo(res, e.getKey(), e.getValue());
17 ilm 222
        }
223
        try {
224
            return JDOMUtils.parseString(res, getVersion().getALL());
225
        } catch (JDOMException e) {
226
            // should not happpen as we did escapeElementEntities which gives valid xml and then
227
            // rt2oo which introduce only static xml
228
            throw new IllegalStateException("could not parse " + res, e);
229
        }
230
    }
231
 
232
    /**
233
     * Convert rich text (with [] tags) into XML.
234
     *
235
     * @param content the string to convert, eg "texte [b]gras[/b]".
236
     * @param styles the mapping from tagname (eg "b") to the name of the character style (eg
237
     *        "Gras").
238
     * @return the corresponding element.
239
     */
19 ilm 240
    public final Element encodeRT(String content, Map<String, String> styles) {
17 ilm 241
        return new Element("span", getVersion().getTEXT()).addContent(encodeRT_L(content, styles));
242
    }
243
 
244
    // create the necessary <text:s c="n"/>
245
    private Element createSpaces(String spacesS) {
246
        return new Element("s", getVersion().getTEXT()).setAttribute("c", spacesS.length() + "", getVersion().getTEXT());
247
    }
248
 
249
    /**
250
     * Encode a String to OO XML. Handles substition of whitespaces to their OO equivalent.
251
     *
252
     * @param s a plain ole String, eg "term\tdefinition".
253
     * @return an Element suitable to be inserted in an OO XML document, eg
254
     *
255
     *         <pre>
256
     *     &lt;text:span&gt;term&lt;text:tab-stop/&gt;definition&lt;/text:span&gt;
257
     * </pre>
258
     *
259
     *         .
260
     */
261
    public final Element encodeWS(final String s) {
262
        return new Element("span", getVersion().getTEXT()).setContent(encodeWSasList(s));
263
    }
264
 
20 ilm 265
    public final List<Content> encodeWSasList(final String s) {
17 ilm 266
        final List<Content> res = new ArrayList<Content>();
267
        final Matcher m = Pattern.compile("\n|\t| {2,}").matcher(s);
268
        int last = 0;
269
        while (m.find()) {
270
            res.add(new Text(s.substring(last, m.start())));
271
            switch (m.group().charAt(0)) {
272
            case '\n':
273
                res.add(getLineBreak());
274
                break;
275
            case '\t':
276
                res.add(getTab());
277
                break;
278
            case ' ':
279
                res.add(createSpaces(m.group()));
280
                break;
281
 
282
            default:
283
                throw new IllegalStateException("unknown item: " + m.group());
284
            }
285
            last = m.end();
286
        }
287
        res.add(new Text(s.substring(last)));
288
        return res;
289
    }
290
 
291
    @SuppressWarnings("unchecked")
292
    public final void encodeWS(final Text t) {
293
        final Parent parent = t.getParent();
294
        final int ind = parent.indexOf(t);
295
        t.detach();
296
        parent.getContent().addAll(ind, encodeWSasList(t.getText()));
297
    }
298
 
299
    @SuppressWarnings("unchecked")
300
    public final Element encodeWS(final Element elem) {
301
        final XPath path;
302
        try {
19 ilm 303
            path = OOUtils.getXPath(".//text()", getVersion());
17 ilm 304
        } catch (JDOMException e) {
305
            // static path, hence always valid
306
            throw new IllegalStateException("cannot create XPath", e);
307
        }
308
        try {
309
            final Iterator iter = new ArrayList(path.selectNodes(elem)).iterator();
310
            while (iter.hasNext()) {
311
                final Text t = (Text) iter.next();
312
                encodeWS(t);
313
            }
314
        } catch (JDOMException e) {
315
            throw new IllegalArgumentException("cannot find text nodes of " + elem, e);
316
        }
317
        return elem;
318
    }
319
 
21 ilm 320
    /**
321
     * Return the coordinates of the top-left and bottom-right of the passed shape.
322
     *
323
     * @param elem an XML element.
324
     * @param unit the unit of the returned numbers.
325
     * @return an array of 4 numbers, <code>null</code> if <code>elem</code> is not a shape, numbers
326
     *         themselves are never <code>null</code>.
327
     */
328
    public final BigDecimal[] getCoordinates(Element elem, LengthUnit unit) {
329
        return this.getCoordinates(elem, unit, true, true);
330
    }
331
 
332
    /**
333
     * Return the coordinates of the top-left and bottom-right of the passed shape.
334
     *
335
     * @param elem an XML element.
336
     * @param unit the unit of the returned numbers.
337
     * @param horizontal <code>true</code> if the x coordinates should be computed,
338
     *        <code>false</code> meaning items 0 and 2 of the result are <code>null</code>.
339
     * @param vertical <code>true</code> if the y coordinates should be computed, <code>false</code>
340
     *        meaning items 1 and 3 of the result are <code>null</code>.
341
     * @return an array of 4 numbers, <code>null</code> if <code>elem</code> is not a shape, numbers
342
     *         themselves are only <code>null</code> if requested with <code>horizontal</code> or
343
     *         <code>vertical</code>.
344
     */
345
    public final BigDecimal[] getCoordinates(Element elem, LengthUnit unit, final boolean horizontal, final boolean vertical) {
346
        return getCoordinates(elem, getVersion().getNS("svg"), unit, horizontal, vertical);
347
    }
348
 
349
    static private final BigDecimal[] getCoordinates(Element elem, final Namespace svgNS, LengthUnit unit, final boolean horizontal, final boolean vertical) {
350
        if (elem.getName().equals("g") && elem.getNamespacePrefix().equals("draw")) {
351
            // put below if to allow null to be returned by getLocalCoordinates() if elem isn't a
352
            // shape
353
            if (!horizontal && !vertical)
354
                return new BigDecimal[] { null, null, null, null };
355
 
356
            // an OpenDocument group (of shapes) doesn't have any coordinates nor any width and
357
            // height so iterate through its components to find its coordinates
358
            BigDecimal minX = null, minY = null;
359
            BigDecimal maxX = null, maxY = null;
360
            for (final Object c : elem.getChildren()) {
361
                final Element child = (Element) c;
362
                final BigDecimal[] childCoord = getCoordinates(child, svgNS, unit, horizontal, vertical);
363
                // e.g. <office:event-listeners>, <svg:desc>, <svg:title>
364
                if (childCoord != null) {
365
                    {
366
                        final BigDecimal x = childCoord[0];
367
                        final BigDecimal x2 = childCoord[2];
368
                        if (x != null) {
369
                            assert x2 != null;
370
                            if (minX == null || x.compareTo(minX) < 0)
371
                                minX = x;
372
                            if (maxX == null || x2.compareTo(maxX) > 0)
373
                                maxX = x2;
374
                        }
375
                    }
376
                    {
377
                        final BigDecimal y = childCoord[1];
378
                        final BigDecimal y2 = childCoord[3];
379
                        if (y != null) {
380
                            assert y2 != null;
381
                            if (minY == null || y.compareTo(minY) < 0)
382
                                minY = y;
383
                            if (maxY == null || y2.compareTo(maxY) > 0)
384
                                maxY = y2;
385
                        }
386
                    }
387
                }
388
            }
389
            // works because we check above if both horizontal and vertical are false
390
            if (minX == null && minY == null)
391
                throw new IllegalArgumentException("Empty group : " + JDOMUtils.output(elem));
392
            return new BigDecimal[] { minX, minY, maxX, maxY };
393
        } else {
394
            return getLocalCoordinates(elem, svgNS, unit, horizontal, vertical);
395
        }
396
    }
397
 
398
    // return null if elem isn't a shape (no x/y or no width/height)
399
    // BigDecimal null if and only if horizontal/vertical is false
400
    static private final BigDecimal[] getLocalCoordinates(Element elem, final Namespace svgNS, LengthUnit unit, final boolean horizontal, final boolean vertical) {
401
        final BigDecimal x = parseLength(elem, "x", svgNS, unit);
402
        final BigDecimal x1 = parseLength(elem, "x1", svgNS, unit);
403
        if (x == null && x1 == null)
404
            return null;
405
 
406
        final BigDecimal y = parseLength(elem, "y", svgNS, unit);
407
        final BigDecimal y1 = parseLength(elem, "y1", svgNS, unit);
408
        if (y == null && y1 == null)
409
            throw new IllegalArgumentException("Have x but missing y in " + JDOMUtils.output(elem));
410
 
411
        final BigDecimal startX;
412
        final BigDecimal endX;
413
        if (horizontal) {
414
            if (x == null) {
415
                startX = x1;
416
                endX = parseLength(elem, "x2", svgNS, unit);
417
            } else {
418
                startX = x;
419
                final BigDecimal width = parseLength(elem, "width", svgNS, unit);
420
                endX = width == null ? null : startX.add(width);
421
            }
422
            // return null if there's no second coordinate (it's a point)
423
            if (endX == null)
424
                return null;
425
        } else {
426
            startX = null;
427
            endX = null;
428
        }
429
 
430
        final BigDecimal startY;
431
        final BigDecimal endY;
432
        if (vertical) {
433
            if (y == null) {
434
                startY = y1;
435
                endY = parseLength(elem, "y2", svgNS, unit);
436
            } else {
437
                startY = y;
438
                final BigDecimal height = parseLength(elem, "height", svgNS, unit);
439
                endY = height == null ? null : startY.add(height);
440
            }
441
            // return null if there's no second coordinate (it's a point)
442
            if (endY == null)
443
                return null;
444
        } else {
445
            startY = null;
446
            endY = null;
447
        }
448
 
449
        return new BigDecimal[] { startX, startY, endX, endY };
450
    }
451
 
19 ilm 452
    private static final class XML_OO extends OOXML {
453
        public XML_OO() {
454
            super(XMLFormatVersion.getOOo(), "20020501");
455
        }
456
 
457
        @Override
458
        public boolean canValidate() {
459
            return true;
460
        }
461
 
462
        @Override
463
        public Validator getValidator(Document doc) {
464
            // DTDs are stubborn, xmlns have to be exactly where they want
465
            // in this case the root element
466
            for (final Namespace n : getVersion().getALL())
467
                doc.getRootElement().addNamespaceDeclaration(n);
468
            return new Validator.DTDValidator(doc, OOUtils.getBuilderLoadDTD());
469
        }
470
 
471
        @Override
472
        public String[] getFontDecls() {
473
            return new String[] { "font-decls", "style:font-decl" };
474
        }
475
 
476
        @Override
477
        public final Element getTab() {
478
            return new Element("tab-stop", getVersion().getTEXT());
479
        }
480
 
481
        @Override
482
        public String getFrameQName() {
483
            return "draw:text-box";
484
        }
485
 
486
        @Override
487
        public Element createFormattingProperties(String family) {
488
            return new Element("properties", this.getVersion().getSTYLE());
489
        }
490
    }
491
 
492
    private static class XML_OD extends OOXML {
493
        private final String schemaFile;
494
        private Schema schema = null;
495
 
496
        public XML_OD(final String dateString, final String versionString, final String schemaFile) {
497
            super(XMLFormatVersion.get(XMLVersion.OD, versionString), dateString);
498
            this.schemaFile = schemaFile;
499
        }
500
 
501
        @Override
502
        public boolean canValidate() {
503
            return this.schemaFile != null;
504
        }
505
 
506
        private Schema getSchema() throws SAXException {
507
            if (this.schema == null && this.schemaFile != null) {
508
                this.schema = SchemaFactory.newInstance(XMLConstants.RELAXNG_NS_URI).newSchema(getClass().getResource("oofficeDTDs/" + this.schemaFile));
509
            }
510
            return this.schema;
511
        }
512
 
513
        @Override
514
        public Validator getValidator(Document doc) {
515
            final Schema schema;
516
            try {
517
                schema = this.getSchema();
518
            } catch (SAXException e) {
519
                throw new IllegalStateException("relaxNG schemas pb", e);
520
            }
521
            return schema == null ? null : new Validator.JAXPValidator(doc, schema);
522
        }
523
 
524
        @Override
525
        public final String[] getFontDecls() {
526
            return new String[] { "font-face-decls", "style:font-face" };
527
        }
528
 
529
        @Override
530
        public final Element getTab() {
531
            return new Element("tab", getVersion().getTEXT());
532
        }
533
 
534
        @Override
535
        public String getFrameQName() {
536
            return "draw:frame";
537
        }
538
 
539
        @Override
540
        public Element createFormattingProperties(String family) {
541
            return new Element(family + "-properties", this.getVersion().getSTYLE());
542
        }
543
    }
544
 
545
    private static final class XML_OD_1_0 extends XML_OD {
546
        public XML_OD_1_0() {
547
            super("20061130", "1.0", null);
548
        }
549
    }
550
 
551
    private static final class XML_OD_1_1 extends XML_OD {
552
        public XML_OD_1_1() {
553
            super("20070201", "1.1", "OpenDocument-strict-schema-v1.1.rng");
554
        }
555
    }
556
 
557
    private static final class XML_OD_1_2 extends XML_OD {
558
        public XML_OD_1_2() {
559
            super("20110317", "1.2", "OpenDocument-v1.2-cs01-schema.rng");
560
        }
561
    }
17 ilm 562
}