File: DefaultTeXFontParser.java

package info (click to toggle)
libjmathtex-java 0.7~pre-4
  • links: PTS, VCS
  • area: main
  • in suites: lenny, squeeze
  • size: 952 kB
  • ctags: 1,112
  • sloc: java: 5,129; xml: 2,151; makefile: 24
file content (514 lines) | stat: -rw-r--r-- 22,609 bytes parent folder | download
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
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
/* DefaultTeXFontParser.java
 * =========================================================================
 * This file is part of the JMathTeX Library - http://jmathtex.sourceforge.net
 *
 * Copyright (C) 2004-2007 Universiteit Gent
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or (at
 * your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * A copy of the GNU General Public License can be found in the file
 * LICENSE.txt provided with the source distribution of this program (see
 * the META-INF directory in the source jar). This license can also be
 * found on the GNU website at http://www.gnu.org/licenses/gpl.html.
 *
 * If you did not receive a copy of the GNU General Public License along
 * with this program, contact the lead developer, or write to the Free
 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301, USA.
 *
 */

package be.ugent.caagt.jmathtex;

import java.awt.Font;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.List;

import org.jdom.Attribute;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;

/**
 * Parses the font information from an XML-file.
 */
class DefaultTeXFontParser {
    
    /**
     * Number of font ids in a single font description file.
     */
    private static final int NUMBER_OF_FONT_IDS = 4;
    
    private static interface CharChildParser { // NOPMD
        public void parse(Element el, char ch, FontInfo info) throws XMLResourceParseException;
    }
    
    private static class ExtensionParser implements CharChildParser {
        
        
        ExtensionParser() {
            // avoid generation of access class
        }
        
        public void parse(Element el, char ch, FontInfo info)
        throws ResourceParseException {
            int[] extensionChars = new int[4];
            // get required integer attributes
            extensionChars[DefaultTeXFont.REP] = DefaultTeXFontParser
                    .getIntAndCheck("rep", el);
            // get optional integer attributes
            extensionChars[DefaultTeXFont.TOP] = DefaultTeXFontParser
                    .getOptionalInt("top", el, DefaultTeXFont.NONE);
            extensionChars[DefaultTeXFont.MID] = DefaultTeXFontParser
                    .getOptionalInt("mid", el, DefaultTeXFont.NONE);
            extensionChars[DefaultTeXFont.BOT] = DefaultTeXFontParser
                    .getOptionalInt("bot", el, DefaultTeXFont.NONE);
            
            // parsing OK, add extension info
            info.setExtension(ch, extensionChars);
        }
    }
    
    private static class KernParser implements CharChildParser {
        
        KernParser() {
            // avoid generation of access class
        }
        
        public void parse(Element el, char ch, FontInfo info)
        throws ResourceParseException {
            // get required integer attribute
            int code = DefaultTeXFontParser.getIntAndCheck("code", el);
            // get required float attribute
            float kernAmount = DefaultTeXFontParser.getFloatAndCheck("val", el);
            
            // parsing OK, add kern info
            info.addKern(ch, (char) code, kernAmount);
        }
    }
    
    private static class LigParser implements CharChildParser {
        
        LigParser() {
            // avoid generation of access class
        }
        
        public void parse(Element el, char ch, FontInfo info)
        throws ResourceParseException {
            // get required integer attributes
            int code = DefaultTeXFontParser.getIntAndCheck("code", el);
            int ligCode = DefaultTeXFontParser.getIntAndCheck("ligCode", el);
            
            // parsing OK, add ligature info
            info.addLigature(ch, (char) code, (char) ligCode);
        }
    }
    
    private static class NextLargerParser implements CharChildParser {
        
        NextLargerParser() {
            // avoid generation of access class
        }
        
        public void parse(Element el, char ch, FontInfo info)
        throws ResourceParseException {
            // get required integer attributes
            int fontId = DefaultTeXFontParser.getIntAndCheck("fontId", el);
            int code = DefaultTeXFontParser.getIntAndCheck("code", el);
            
            // parsing OK, add "next larger" info
            info.setNextLarger(ch, (char) code, fontId);
        }
    }
    
    public static final String RESOURCE_NAME = "DefaultTeXFont.xml";
    
    public static final String STYLE_MAPPING_EL = "TextStyleMapping";
    public static final String SYMBOL_MAPPING_EL = "SymbolMapping";
    public static final String GEN_SET_EL = "GeneralSettings";
    public static final String MUFONTID_ATTR = "mufontid";
    public static final String SPACEFONTID_ATTR = "spacefontid";
    
    private static Map<String,Integer> rangeTypeMappings = new HashMap<String,Integer>();
    private static Map<String,CharChildParser>
            charChildParsers = new HashMap<String,CharChildParser>();
    
    private Map<String,CharFont[]> parsedTextStyles;
    
    private Element root;
    
    static {
        // string-to-constant mappings
        setRangeTypeMappings();
        // parsers for the child elements of a "Char"-element
        setCharChildParsers();
    }
    
    public DefaultTeXFontParser() throws ResourceParseException {
        try {
            root = new SAXBuilder().build(
                    DefaultTeXFontParser.class.getResourceAsStream(RESOURCE_NAME)
                    ).getRootElement();
            
            // parse textstyles ahead of the rest, because it's used while
            // parsing the default text style
            parsedTextStyles = parseStyleMappings();
        } catch (JDOMException e) { // JDOMException or IOException
            throw new XMLResourceParseException(RESOURCE_NAME, e);
        } catch (IOException e) { // JDOMException or IOException
            throw new XMLResourceParseException(RESOURCE_NAME, e);
        }
    }
    
    private static void setCharChildParsers() {
        charChildParsers.put("Kern", new KernParser());
        charChildParsers.put("Lig", new LigParser());
        charChildParsers.put("NextLarger", new NextLargerParser());
        charChildParsers.put("Extension", new ExtensionParser());
    }
    
    public FontInfo[] parseFontDescriptions() throws ResourceParseException {
        FontInfo[] res = new FontInfo[NUMBER_OF_FONT_IDS];
        Element fontDescriptions = root.getChild("FontDescriptions");
        if (fontDescriptions != null) { // element present
            // iterate all "Font"-elements
            for (Object obj : fontDescriptions.getChildren("Font")) {
                Element font = (Element) obj;
                // get required string attribute
                String fontName = getAttrValueAndCheckIfNotNull("name", font);
                // get required integer attribute
                int fontId = getIntAndCheck("id", font);
                if (fontId < 0) // id must be greater than 0!!
                    throw new XMLResourceParseException(RESOURCE_NAME, "Font", "id",
                            "must have a positive integer value!");
                // get required real attributes
                float space = getFloatAndCheck("space", font);
                float xHeight = getFloatAndCheck("xHeight", font);
                float quad = getFloatAndCheck("quad", font);
                
                // get optional integer attribute
                int skewChar = getOptionalInt("skewChar", font, -1);
                
                // try reading the font
                Font f = createFont(fontName);
                
                // create FontInfo-object
                FontInfo info = new FontInfo(fontId, f, xHeight, space, quad);
                if (skewChar != -1) // attribute set
                    info.setSkewChar((char) skewChar);
                
                // process all "Char"-elements
                for (Object object : font.getChildren("Char"))
                    processCharElement((Element) object, info);
                
                // parsing OK, add to table
                if (res[fontId] == null)
                    res[fontId] = info;
                else
                    throw new XMLResourceParseException(RESOURCE_NAME, "Font", "id",
                            "occurs more than once");
            }
        }
        return res;
    }
    
    private static void processCharElement(Element charElement, FontInfo info)
    throws ResourceParseException {
        // retrieve required integer attribute
        char ch = (char) getIntAndCheck("code", charElement);
        // retrieve optional float attributes
        float[] metrics = new float[4];
        metrics[DefaultTeXFont.WIDTH] = getOptionalFloat("width", charElement, 0);
        metrics[DefaultTeXFont.HEIGHT] = getOptionalFloat("height", charElement,
                0);
        metrics[DefaultTeXFont.DEPTH] = getOptionalFloat("depth", charElement, 0);
        metrics[DefaultTeXFont.IT] = getOptionalFloat("italic", charElement, 0);
        // set metrics
        info.setMetrics(ch, metrics);
        
        // process children
        for (Object obj : charElement.getChildren()) {
            Element el = (Element)obj;
            Object parser = charChildParsers.get(el.getName());
            if (parser == null) // unknown element
                throw new XMLResourceParseException(RESOURCE_NAME
                        + ": a <Char>-element has an unknown childelement '"
                        + el.getName() + "'!");
            else
                // process the child element
                ((CharChildParser) parser).parse(el, ch, info);
        }
    }
    
    private Font createFont(String name) throws ResourceParseException {
        InputStream fontIn = null;
        try {
            fontIn = DefaultTeXFontParser.class.getResourceAsStream(name);
            return Font.createFont(java.awt.Font.TRUETYPE_FONT, fontIn);
        } catch (Exception e) {
            throw new XMLResourceParseException(RESOURCE_NAME
                    + ": error reading font '" + name + "'. Error message: "
                    + e.getMessage());
        } finally {
            try {
                if (fontIn != null)
                    fontIn.close();
            } catch (IOException ioex) {
                throw new RuntimeException("Close threw exception", ioex);
            }
        }
    }
    
    public Map<String,CharFont> parseSymbolMappings() throws ResourceParseException {
        Map<String,CharFont> res = new HashMap<String,CharFont>();
        Element symbolMappings = root.getChild("SymbolMappings");
        if (symbolMappings == null)
            // "SymbolMappings" is required!
            throw new XMLResourceParseException(RESOURCE_NAME, "SymbolMappings");
        else { // element present
            // iterate all mappings
            for (Object obj : symbolMappings.getChildren(SYMBOL_MAPPING_EL)) {
                Element mapping = (Element) obj;
                // get string attribute
                String symbolName = getAttrValueAndCheckIfNotNull("name", mapping);
                // get integer attributes
                int ch = getIntAndCheck("ch", mapping), fontId = getIntAndCheck(
                        "fontId", mapping);
                // put mapping in table
                res.put(symbolName, new CharFont((char) ch, fontId));
            }
        }
        
        // "sqrt" must allways be present (used internally only!)
        if (res.get("sqrt") == null)
            throw new XMLResourceParseException(
                    RESOURCE_NAME
                    + ": the required mapping <SymbolMap name=\"sqrt\" ... /> is not found!");
        else
            // parsing OK
            return res;
    }
    
    public String[] parseDefaultTextStyleMappings()
    throws ResourceParseException {
        String[] res = new String[3];
        Element defaultTextStyleMappings = root
                .getChild("DefaultTextStyleMapping");
        if (defaultTextStyleMappings == null)
            // "DefaultTextStyleMappings" is required!
            throw new XMLResourceParseException(RESOURCE_NAME,
                    "DefaultTextStyleMapping");
        else { // element present
            // iterate all mappings
            for (Object obj : defaultTextStyleMappings.getChildren("MapStyle")) {
                Element mapping = (Element) obj;
                // get range name and check if it's valid
                String code = getAttrValueAndCheckIfNotNull("code", mapping);
                Object codeMapping = rangeTypeMappings.get(code);
                if (codeMapping == null) // unknown range name
                    throw new XMLResourceParseException(RESOURCE_NAME, "MapStyle",
                            "code", "contains an unknown \"range name\" '" + code
                            + "'!");
                // get mapped style and check if it exists
                String textStyleName = getAttrValueAndCheckIfNotNull("textStyle",
                        mapping);
                Object styleMapping = parsedTextStyles.get(textStyleName);
                if (styleMapping == null) // unknown text style
                    throw new XMLResourceParseException(RESOURCE_NAME, "MapStyle",
                            "textStyle", "contains an unknown text style '"
                            + textStyleName + "'!");
                // now check if the range is defined within the mapped text style
                CharFont[] charFonts = (CharFont[]) parsedTextStyles
                        .get(textStyleName);
                int index = ((Integer) codeMapping).intValue();
                if (charFonts[index] == null) // range not defined
                    throw new XMLResourceParseException(RESOURCE_NAME
                            + ": the default text style mapping '" + textStyleName
                            + "' for the range '" + code
                            + "' contains no mapping for that range!");
                else
                    // everything OK, put mapping in table
                    res[index] = textStyleName;
            }
        }
        return res;
    }
    
    public Map<String,Float> parseParameters() throws ResourceParseException {
        Map<String,Float> res = new HashMap<String,Float>();
        Element parameters = root.getChild("Parameters");
        if (parameters == null)
            // "Parameters" is required!
            throw new XMLResourceParseException(RESOURCE_NAME, "Parameters");
        else { // element present
            // iterate all attributes
            for (Object obj : parameters.getAttributes()) {
                String name = ((Attribute) obj).getName();
                // set float value (if valid)
                res.put(name, new Float(getFloatAndCheck(name, parameters)));
            }
            return res;
        }
    }
    
    public Map<String,Number> parseGeneralSettings() throws ResourceParseException {
        Map <String,Number>res = new HashMap<String,Number>();
        // TODO: must this be 'Number' ?
        Element generalSettings = root.getChild("GeneralSettings");
        if (generalSettings == null)
            // "GeneralSettings" is required!
            throw new XMLResourceParseException(RESOURCE_NAME, "GeneralSettings");
        else { // element present
            // set required int values (if valid)
            res.put(MUFONTID_ATTR, getIntAndCheck(MUFONTID_ATTR,
                    generalSettings)); // autoboxing
            res.put(SPACEFONTID_ATTR, getIntAndCheck(SPACEFONTID_ATTR,
                    generalSettings)); // autoboxing
            // set required float values (if valid)
            res.put("scriptfactor", getFloatAndCheck("scriptfactor",
                    generalSettings)); // autoboxing
            res.put("scriptscriptfactor", getFloatAndCheck(
                    "scriptscriptfactor", generalSettings)); // autoboxing
            
        }
        return res;
    }
    
    public Map<String,CharFont[]> parseTextStyleMappings() {
        return parsedTextStyles;
    }
    
    private Map<String,CharFont[]> parseStyleMappings() throws ResourceParseException {
        Map<String,CharFont[]> res = new HashMap<String,CharFont[]>();
        Element textStyleMappings = root.getChild("TextStyleMappings");
        if (textStyleMappings == null)
            // "TextStyleMappings" is required!
            throw new XMLResourceParseException(RESOURCE_NAME, "TextStyleMappings");
        else { // element present
            // iterate all mappings
            for (Object obj : textStyleMappings.getChildren(STYLE_MAPPING_EL)) {
                Element mapping = (Element) obj;
                // get required string attribute
                String textStyleName = getAttrValueAndCheckIfNotNull("name",
                        mapping);
                List mapRangeList = mapping.getChildren("MapRange");
                // iterate all mapping ranges
                CharFont[] charFonts = new CharFont[3];
                for (Object object : mapRangeList) {
                    Element mapRange = (Element) object;
                    // get required integer attributes
                    int fontId = getIntAndCheck("fontId", mapRange);
                    int ch = getIntAndCheck("start", mapRange);
                    // get required string attribute and check if it's a known range
                    String code = getAttrValueAndCheckIfNotNull("code", mapRange);
                    Object codeMapping = rangeTypeMappings.get(code);
                    if (codeMapping == null)
                        throw new XMLResourceParseException(RESOURCE_NAME,
                                "MapRange", "code",
                                "contains an unknown \"range name\" '" + code + "'!");
                    else
                        charFonts[((Integer) codeMapping).intValue()] = new CharFont(
                                (char) ch, fontId);
                }
                res.put(textStyleName, charFonts);
            }
        }
        return res;
    }
    
    private static void setRangeTypeMappings() {
        rangeTypeMappings.put("numbers", DefaultTeXFont.NUMBERS); // autoboxing
        rangeTypeMappings.put("capitals", DefaultTeXFont.CAPITALS); // autoboxing
        rangeTypeMappings.put("small", DefaultTeXFont.SMALL); // autoboxing
    }
    
    private static String getAttrValueAndCheckIfNotNull(String attrName,
            Element element) throws ResourceParseException {
        String attrValue = element.getAttributeValue(attrName);
        if (attrValue == null)
            throw new XMLResourceParseException(RESOURCE_NAME, element.getName(),
                    attrName, null);
        return attrValue;
    }
    
    public static float getFloatAndCheck(String attrName, Element element)
    throws ResourceParseException {
        String attrValue = getAttrValueAndCheckIfNotNull(attrName, element);
        
        // try parsing string to float value
        float res = 0;
        try {
            res = (float) Double.parseDouble(attrValue);
        } catch (NumberFormatException e) {
            throw new XMLResourceParseException(RESOURCE_NAME, element.getName(),
                    attrName, "has an invalid real value!");
        }
        // parsing OK
        return res;
    }
    
    public static int getIntAndCheck(String attrName, Element element)
    throws ResourceParseException {
        String attrValue = getAttrValueAndCheckIfNotNull(attrName, element);
        
        // try parsing string to integer value
        int res = 0;
        try {
            res = Integer.parseInt(attrValue);
        } catch (NumberFormatException e) {
            throw new XMLResourceParseException(RESOURCE_NAME, element.getName(),
                    attrName, "has an invalid integer value!");
        }
        // parsing OK
        return res;
    }
    
    public static int getOptionalInt(String attrName, Element element,
            int defaultValue) throws ResourceParseException {
        String attrValue = element.getAttributeValue(attrName);
        if (attrValue == null) // attribute not present
            return defaultValue;
        else {
            // try parsing string to integer value
            int res = 0;
            try {
                res = Integer.parseInt(attrValue);
            } catch (NumberFormatException e) {
                throw new XMLResourceParseException(RESOURCE_NAME, element
                        .getName(), attrName, "has an invalid integer value!");
            }
            // parsing OK
            return res;
        }
    }
    
    public static float getOptionalFloat(String attrName, Element element,
            float defaultValue) throws ResourceParseException {
        String attrValue = element.getAttributeValue(attrName);
        if (attrValue == null) // attribute not present
            return defaultValue;
        else {
            // try parsing string to float value
            float res = 0;
            try {
                res = (float) Double.parseDouble(attrValue);
            } catch (NumberFormatException e) {
                throw new XMLResourceParseException(RESOURCE_NAME, element
                        .getName(), attrName, "has an invalid float value!");
            }
            // parsing OK
            return res;
        }
    }
}