summaryrefslogtreecommitdiff
path: root/xmerge/source/xmerge/java/org/openoffice/xmerge/converter/xml/StyleCatalog.java
blob: 818a4f250db96f4cb3c2c4a3a8d84e02ef87978d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */

package org.openoffice.xmerge.converter.xml;

import java.lang.reflect.Constructor;
import java.util.ArrayList;

import org.openoffice.xmerge.util.Debug;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;


/**
 *  A <code>StyleCatalog</code> holds a collection of <code>Style</code>
 *  objects.  It is intended for use when parsing or building a DOM
 *  document.
 *
 *  Each entry in the <code>StyleCatalog</code> represents a
 *  <code>Style</code>, and is an object which is a subclass of
 *  <code>Style</code>.
 *
 *  @author David Proulx
 *  @see <a href="Style.html">Style</a>
 */
public class StyleCatalog {

    private ArrayList<Style> styles;  // The actual styles

    /**
     *  Constructor
     *
     *  @param  initialEntries  Expected number of entries to set
     *                          for efficiency purposes.
     */
    public StyleCatalog(int initialEntries) {
        styles = new ArrayList<Style>(initialEntries);
    }


    /**
     *  <p>Parse the <code>Document</code> starting from <code>node</code>
     *  and working downward, and add all styles found, so long as their
     *  family name is listed in <code>families</code>.  For each
     *  family name in <code>families</code> there must be a corresponding
     *  element in <code>classes</code>, which specifies the class type
     *  to use for that family.  All of these classes must be
     *  subclasses of <code>Style</code>.  There can be multiple
     *  classes specified for a particular family.</p>
     *
     *  <p>If <code>defaultClass</code> is non-null, then all styles that
     *  are found will be added.  Any <code>Style</code> whose family is
     *  not listed in <code>families</code> will be added using defaultClass,
     *  which, of course, must be a subclass of <code>Style</code>.
     *  If <code>alwaysCreateDefault</code> is true, then a class
     *  of type <code>defaultClass</code> will always be created,
     *  regardless of whether there was also a match in
     *  <code>families</code>.</p>
     *
     *  <p>DJP Todo: make it recursive so that <code>node</code> can be
     *  higher up in the <code>Document</code> tree.</p>
     *
     *  @param  node                 The node to be searched for
     *                               <code>Style</code> objects.
     *  @param  families             An array of <code>Style</code> families
     *                               to add.
     *  @param  classes              An array of class types corresponding
     *                               to the families array.
     *  @param  defaultClass         All <code>Style</code> objects that are
     *                               found are added to this class.
     *  @param  alwaysCreateDefault  A class of type <code>defaultClass</code>
     *                               will always be created, regardless of
     *                               whether there is a match in the
     *                               families array.
     */
    public void add(Node node, String families[], Class<?> classes[],
    Class<?> defaultClass, boolean alwaysCreateDefault) {

    if (node == null)
            return;

        if (families == null)
            families = new String[0];
        if (classes == null)
            classes = new Class[0];
        if (node.hasChildNodes()) {
            NodeList children = node.getChildNodes();
            int len = children.getLength();

            for (int i = 0; i < len; i++) {
                boolean found = false;
                Node child = children.item(i);
                String name = child.getNodeName();
                if (name.equals("style:default-style") || name.equals("style:style")) {
                    String familyName = getFamilyName(child);
                    if (familyName == null) {
                        Debug.log(Debug.ERROR, "familyName is null!");
                        continue;
                    }

                    for (int j = 0; j < families.length; j++) {
                        if (families[j].equals(familyName)) {
                            Class<?> styleClass = classes[j];
                            callConstructor(classes[j], child);
                            found = true;
                        }
                    }
                    if ((!found || alwaysCreateDefault) && (defaultClass != null))
                        callConstructor(defaultClass, child);
                }
            }
        }
    }


    /**
     *  Call the constructor of class <code>cls</code> with parameters
     *  <code>node</code>, and add the resulting <code>Style</code> to
     *  the catalog.
     *
     *  @param  cls   The class whose constructor will be called.
     *  @param  node  The constructed class will be added to this node.
     */
    private void callConstructor(Class<?> cls, Node node) {
        Class<?> params[] = new Class[2];
        params[0] = Node.class;
        params[1] = this.getClass();
        try {
            Constructor<?> c = cls.getConstructor(params);
            Object p[] = new Object[2];
            p[0] = node;
            p[1] = this;
            styles.add((Style) c.newInstance(p));
        } catch (Exception e) {
            Debug.log(Debug.ERROR, "Exception when calling constructor", e);
        }
    }


    /**
     *  Add a <code>Style</code> to the catalog.
     *
     *  @param  s  The <code>Style</code> to add.
     */
    public void add(Style s) {
        styles.add(s);
    }


    /**
     *  Return the first <code>Style</code> matching the specified names.
     *
     *  @param  name        Name to match, null is considered
     *                      <i>always match</i>.
     *  @param  family      Family to match, null is considered
     *                      <i>always match</i>.
     *  @param  parent      Parent to match, null is considered
     *                      <i>always match</i>.
     *  @param  styleClass  styleClass to match, null is considered
     *                      <i>always match</i>.
     *
     *  @return  <code>Style</code> value if all parameters match,
     *           null otherwise
     */
    public Style lookup(String name, String family, String parent,
                        Class<?> styleClass) {
        int nStyles = styles.size();
        for (int i = 0; i < nStyles; i++) {
            Style s = styles.get(i);
            if ((name != null) && (s.getName() != null)
            && (!s.getName().equals(name)))
                continue;
            if ((family != null) && (s.getFamily() != null)
            && (!s.getFamily().equals(family)))
                continue;
            if ((parent != null) && (s.getParent() != null)
            && (!s.getParent().equals(parent)))
                continue;
            if ((styleClass != null) && (s.getClass() != styleClass))
                continue;
            if (s.getName() == null) continue;  // DJP: workaround for "null name" problem
            return s;
        }
        return null;  // none found
    }


    /**
     *  Given a <code>Style</code> <code>s<code> return all
     *  <code>Style</code> objects that match.
     *
     *  @param  s  <code>Style</code> to match.
     *
     *  @return  An array of <code>Style</code> objects that match, an
     *           empty array if none match.
     */
    public Style[] getMatching(Style s) {

        // Run through and count the matching styles so we know how big of
        // an array to allocate.
        int matchCount = 0;
        int nStyles = styles.size();
        for (int j = 0; j < nStyles; j++) {
            Style p = styles.get(j).getResolved();
            if (p.isSubset(s)) matchCount++;
        }

        // Now allocate the array, and run through again, populating it.
        Style[] matchArray = new Style[matchCount];
        matchCount = 0;
        for (int j = 0; j < nStyles; j++) {
            Style p = styles.get(j).getResolved();
            if (p.isSubset(s)) matchArray[matchCount++] = p;
        }
        return matchArray;
    }


    /**
     *  Given a <code>Style</code> <code>s</code>, return the
     *  <code>style</code> that is the closest match.  Not currently
     *  implemented.
     *
     *  @param  s  <code>Style</code> to match.
     *
     *  @return  The <code>Style</code> that most closely matches.
     */
    public Style getBestMatch(Style s) {
        // DJP: is this needed?
        // DJP ToDo: implement this
        return null;
    }


    /**
     *  <p>Create a <code>Node</code> named <code>name</code> in
     *  <code>Document</code> <code>parentDoc</code>, and write the
     *  entire <code>StyleCatalog</code> to it.</p>
     *
     *  <p>Note that the resulting node is returned, but is not connected
     *  into the document.  Placing the output node in the document is
     *  left to the caller.</p>
     *
     *  @param  parentDoc  The <code>Document</code> to add the
     *                     <code>Node</code>.
     *  @param  name       The name of the <code>Node</code> to add.
     *
     *  @return  The <code>Element</code> that was created.
     */
    public Element writeNode(org.w3c.dom.Document parentDoc, String name) {
        Element rootNode = parentDoc.createElement(name);

        int len = styles.size();
        for (int j = 0; j < len; j++) {
            Style s = styles.get(j);

            Element styleNode = parentDoc.createElement("style:style");

            if (s.getName() != null)
                styleNode.setAttribute("style:name", s.getName());
            if (s.getParent() != null)
                styleNode.setAttribute("style:parent-style-name", s.getParent());
            if (s.getFamily() != null)
                styleNode.setAttribute("style:family", s.getFamily());

            Element propertiesNode = (Element) s.createNode(parentDoc, "style:properties");
            // DJP: only add node if has children OR attributes
            if (propertiesNode != null)
                styleNode.appendChild(propertiesNode);

            rootNode.appendChild(styleNode);
        }

        return rootNode;
    }


    /**
     *  Dump the <code>Style</code> table in Comma Separated Value (CSV)
     *  format
     *
     *  @param  para  If true, dump in paragraph <code>Style</code>,
     *                otherwise dump in text style.
     */
    public void dumpCSV(boolean para) {
        if (!para) {
            TextStyle.dumpHdr();
            int nStyles = styles.size();
            for (int i = 0; i < nStyles; i++) {
                Style s = styles.get(i);
                if (s.getClass().equals(TextStyle.class))
                    ((TextStyle)s).dumpCSV();
            }
        } else {
            ParaStyle.dumpHdr();
            int nStyles = styles.size();
            for (int i = 0; i < nStyles; i++) {
                Style s = styles.get(i);
                if (s.getClass().equals(ParaStyle.class))
                    ((ParaStyle)s).dumpCSV();
            }
        }

    }


    /**
     *  Check whether a given node represents a <code>Style</code>
     *  that should be added to the catalog, and if so, return the
     *  class type for it.  If <code>Style</code> should not be added,
     *  or if node is not a <code>Style</code>, return null.
     *
     *  @param  node          The <code>Node</code> to be checked.
     *  @param  families      An array of <code>Style</code> families.
     *  @param  classes       An array of class types corresponding to the
     *                        families array.
     *  @param  defaultClass  The default class.
     *
     *  @return  The class that is appropriate for this node.
     */
    private Class<?> getClass(Node node, String[] families, Class<?>[] classes,
    Class<?> defaultClass) {
        NamedNodeMap attributes = node.getAttributes();
        if (attributes != null) {
            int len = attributes.getLength();
            for (int i = 0; i < len; i++) {
                Node attr = attributes.item(i);
                if (attr.getNodeName().equals("style:family")) {
                    String familyName = attr.getNodeValue();
                    for (int j = 0; j < families.length; j++) {
                        if (families[j].equals(familyName))
                            return classes[j];
                    }
                    return defaultClass;
                }
            }
        }
        return null;
    }


    /**
     *  Find the family attribute of a <code>Style</code> <code>Node</code>.
     *
     *  @param  node  The <code>Node</code> to check.
     *
     *  @return  The family attribute, or null if one does not
     *           exist.
     */
    private String getFamilyName(Node node) {
        NamedNodeMap attributes = node.getAttributes();
        if (attributes != null) {
            int len = attributes.getLength();
            for (int i = 0; i < len; i++) {
                Node attr = attributes.item(i);
                if (attr.getNodeName().equals("style:family")) {
                    return attr.getNodeValue();
                }
            }
        }
        return null;
    }
}