summaryrefslogtreecommitdiffstats
path: root/src/main/java/com/kitfox/svg/Text.java
blob: 2ab9a0af9b8946013e0a39bb28a3b5ede88ae4f9 (plain) (blame)
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
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
/*
 * SVG Salamander
 * Copyright (c) 2004, Mark McKay
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or 
 * without modification, are permitted provided that the following
 * conditions are met:
 *
 *   - Redistributions of source code must retain the above 
 *     copyright notice, this list of conditions and the following
 *     disclaimer.
 *   - Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials 
 *     provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE. 
 * 
 * Mark McKay can be contacted at mark@kitfox.com.  Salamander and other
 * projects can be found at http://www.kitfox.com
 *
 * Created on January 26, 2004, 1:56 AM
 */
package com.kitfox.svg;

import com.kitfox.svg.xml.StyleAttribute;
import java.awt.Graphics2D;
import java.awt.Shape;
import java.awt.font.FontRenderContext;
import java.awt.geom.AffineTransform;
import java.awt.geom.GeneralPath;
import java.awt.geom.Rectangle2D;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

//import org.apache.batik.ext.awt.geom.ExtendedGeneralPath;
/**
 * @author Mark McKay
 * @author <a href="mailto:mark@kitfox.com">Mark McKay</a>
 */
public class Text extends ShapeElement
{
    public static final String TAG_NAME = "text";
    
    float x = 0;
    float y = 0;
    AffineTransform transform = null;
    String fontFamily;
    float fontSize;
    //List of strings and tspans containing the content of this node
    LinkedList content = new LinkedList();
    Shape textShape;
    public static final int TXAN_START = 0;
    public static final int TXAN_MIDDLE = 1;
    public static final int TXAN_END = 2;
    int textAnchor = TXAN_START;
    public static final int TXST_NORMAL = 0;
    public static final int TXST_ITALIC = 1;
    public static final int TXST_OBLIQUE = 2;
    int fontStyle;
    public static final int TXWE_NORMAL = 0;
    public static final int TXWE_BOLD = 1;
    public static final int TXWE_BOLDER = 2;
    public static final int TXWE_LIGHTER = 3;
    public static final int TXWE_100 = 4;
    public static final int TXWE_200 = 5;
    public static final int TXWE_300 = 6;
    public static final int TXWE_400 = 7;
    public static final int TXWE_500 = 8;
    public static final int TXWE_600 = 9;
    public static final int TXWE_700 = 10;
    public static final int TXWE_800 = 11;
    public static final int TXWE_900 = 12;
    int fontWeight;

    /**
     * Creates a new instance of Stop
     */
    public Text()
    {
    }

    public String getTagName()
    {
        return TAG_NAME;
    }

    public void appendText(String text)
    {
        content.addLast(text);
    }

    public void appendTspan(Tspan tspan) throws SVGElementException
    {
        super.loaderAddChild(null, tspan);
        content.addLast(tspan);
    }

    /**
     * Discard cached information
     */
    public void rebuild() throws SVGException
    {
        build();
    }

    public java.util.List getContent()
    {
        return content;
    }

    /**
     * Called after the start element but before the end element to indicate
     * each child tag that has been processed
     */
    public void loaderAddChild(SVGLoaderHelper helper, SVGElement child) throws SVGElementException
    {
        super.loaderAddChild(helper, child);

        content.addLast(child);
    }

    /**
     * Called during load process to add text scanned within a tag
     */
    public void loaderAddText(SVGLoaderHelper helper, String text)
    {
        Matcher matchWs = Pattern.compile("\\s*").matcher(text);
        if (!matchWs.matches())
        {
            content.addLast(text);
        }
    }

    public void build() throws SVGException
    {
        super.build();

        StyleAttribute sty = new StyleAttribute();

        if (getPres(sty.setName("x")))
        {
            x = sty.getFloatValueWithUnits();
        }

        if (getPres(sty.setName("y")))
        {
            y = sty.getFloatValueWithUnits();
        }

        if (getStyle(sty.setName("font-family")))
        {
            fontFamily = sty.getStringValue();
        } else
        {
            fontFamily = "Sans Serif";
        }

        if (getStyle(sty.setName("font-size")))
        {
            fontSize = sty.getFloatValueWithUnits();
        } else
        {
            fontSize = 12f;
        }

        if (getStyle(sty.setName("font-style")))
        {
            String s = sty.getStringValue();
            if ("normal".equals(s))
            {
                fontStyle = TXST_NORMAL;
            } else if ("italic".equals(s))
            {
                fontStyle = TXST_ITALIC;
            } else if ("oblique".equals(s))
            {
                fontStyle = TXST_OBLIQUE;
            }
        } else
        {
            fontStyle = TXST_NORMAL;
        }

        if (getStyle(sty.setName("font-weight")))
        {
            String s = sty.getStringValue();
            if ("normal".equals(s))
            {
                fontWeight = TXWE_NORMAL;
            } else if ("bold".equals(s))
            {
                fontWeight = TXWE_BOLD;
            }
        } else
        {
            fontWeight = TXWE_NORMAL;
        }

        if (getStyle(sty.setName("text-anchor")))
        {
            String s = sty.getStringValue();
            if (s.equals("middle"))
            {
                textAnchor = TXAN_MIDDLE;
            } else if (s.equals("end"))
            {
                textAnchor = TXAN_END;
            } else
            {
                textAnchor = TXAN_START;
            }
        } else
        {
            textAnchor = TXAN_START;
        }

        //text anchor
        //text-decoration
        //text-rendering

        buildFont();
    }

    protected void buildFont() throws SVGException
    {
        int style;
        switch (fontStyle)
        {
            case TXST_ITALIC:
                style = java.awt.Font.ITALIC;
                break;
            default:
                style = java.awt.Font.PLAIN;
                break;
        }

        int weight;
        switch (fontWeight)
        {
            case TXWE_BOLD:
            case TXWE_BOLDER:
                weight = java.awt.Font.BOLD;
                break;
            default:
                weight = java.awt.Font.PLAIN;
                break;
        }

        //Get font
        Font font = diagram.getUniverse().getFont(fontFamily);
        if (font == null)
        {
//            System.err.println("Could not load font");

            java.awt.Font sysFont = new java.awt.Font(fontFamily, style | weight, (int) fontSize);
            buildSysFont(sysFont);
            return;
        }

//        font = new java.awt.Font(font.getFamily(), style | weight, font.getSize());

//        Area textArea = new Area();
        GeneralPath textPath = new GeneralPath();
        textShape = textPath;

        float cursorX = x, cursorY = y;

        FontFace fontFace = font.getFontFace();
        //int unitsPerEm = fontFace.getUnitsPerEm();
        int ascent = fontFace.getAscent();
        float fontScale = fontSize / (float) ascent;

//        AffineTransform oldXform = g.getTransform();
        AffineTransform xform = new AffineTransform();

        for (Iterator it = content.iterator(); it.hasNext();)
        {
            Object obj = it.next();

            if (obj instanceof String)
            {
                String text = (String) obj;
                if (text != null)
                {
                    text = text.trim();
                }

                strokeWidthScalar = 1f / fontScale;

                for (int i = 0; i < text.length(); i++)
                {
                    xform.setToIdentity();
                    xform.setToTranslation(cursorX, cursorY);
                    xform.scale(fontScale, fontScale);
//                    g.transform(xform);

                    String unicode = text.substring(i, i + 1);
                    MissingGlyph glyph = font.getGlyph(unicode);

                    Shape path = glyph.getPath();
                    if (path != null)
                    {
                        path = xform.createTransformedShape(path);
                        textPath.append(path, false);
                    }
//                    else glyph.render(g);

                    cursorX += fontScale * glyph.getHorizAdvX();

//                    g.setTransform(oldXform);
                }

                strokeWidthScalar = 1f;
            } else if (obj instanceof Tspan)
            {
                Tspan tspan = (Tspan) obj;

                xform.setToIdentity();
                xform.setToTranslation(cursorX, cursorY);
                xform.scale(fontScale, fontScale);
//                tspan.setCursorX(cursorX);
//                tspan.setCursorY(cursorY);

                Shape tspanShape = tspan.getShape();
                tspanShape = xform.createTransformedShape(tspanShape);
                textPath.append(tspanShape, false);
//                tspan.render(g);
//                cursorX = tspan.getCursorX();
//                cursorY = tspan.getCursorY();
            }

        }

        switch (textAnchor)
        {
            case TXAN_MIDDLE:
            {
                AffineTransform at = new AffineTransform();
                at.translate(-textPath.getBounds2D().getWidth() / 2, 0);
                textPath.transform(at);
                break;
            }
            case TXAN_END:
            {
                AffineTransform at = new AffineTransform();
                at.translate(-textPath.getBounds2D().getWidth(), 0);
                textPath.transform(at);
                break;
            }
        }
    }

    private void buildSysFont(java.awt.Font font) throws SVGException
    {
        GeneralPath textPath = new GeneralPath();
        textShape = textPath;

        float cursorX = x, cursorY = y;

//        FontMetrics fm = g.getFontMetrics(font);
        FontRenderContext frc = new FontRenderContext(null, true, true);

//        FontFace fontFace = font.getFontFace();
        //int unitsPerEm = fontFace.getUnitsPerEm();
//        int ascent = fm.getAscent();
//        float fontScale = fontSize / (float)ascent;

//        AffineTransform oldXform = g.getTransform();
        AffineTransform xform = new AffineTransform();

        for (Iterator it = content.iterator(); it.hasNext();)
        {
            Object obj = it.next();

            if (obj instanceof String)
            {
                String text = (String) obj;

                Shape textShape = font.createGlyphVector(frc, text).getOutline(cursorX, cursorY);
                textPath.append(textShape, false);
//                renderShape(g, textShape);
//                g.drawString(text, cursorX, cursorY);

                Rectangle2D rect = font.getStringBounds(text, frc);
                cursorX += (float) rect.getWidth();
            } else if (obj instanceof Tspan)
            {
                /*
                 Tspan tspan = (Tspan)obj;
                 
                 xform.setToIdentity();
                 xform.setToTranslation(cursorX, cursorY);
                 
                 Shape tspanShape = tspan.getShape();
                 tspanShape = xform.createTransformedShape(tspanShape);
                 textArea.add(new Area(tspanShape));
                 
                 cursorX += tspanShape.getBounds2D().getWidth();
                 */


                Tspan tspan = (Tspan) obj;
                tspan.setCursorX(cursorX);
                tspan.setCursorY(cursorY);
                tspan.addShape(textPath);
                cursorX = tspan.getCursorX();
                cursorY = tspan.getCursorY();

            }
        }

        switch (textAnchor)
        {
            case TXAN_MIDDLE:
            {
                AffineTransform at = new AffineTransform();
                at.translate(-textPath.getBounds2D().getWidth() / 2, 0);
                textPath.transform(at);
                break;
            }
            case TXAN_END:
            {
                AffineTransform at = new AffineTransform();
                at.translate(-textPath.getBounds2D().getWidth(), 0);
                textPath.transform(at);
                break;
            }
        }
    }

    public void render(Graphics2D g) throws SVGException
    {
        beginLayer(g);
        renderShape(g, textShape);
        finishLayer(g);
    }

    public Shape getShape()
    {
        return shapeToParent(textShape);
    }

    public Rectangle2D getBoundingBox() throws SVGException
    {
        return boundsToParent(includeStrokeInBounds(textShape.getBounds2D()));
    }

    /**
     * Updates all attributes in this diagram associated with a time event. Ie,
     * all attributes with track information.
     *
     * @return - true if this node has changed state as a result of the time
     * update
     */
    public boolean updateTime(double curTime) throws SVGException
    {
//        if (trackManager.getNumTracks() == 0) return false;
        boolean changeState = super.updateTime(curTime);

        //Get current values for parameters
        StyleAttribute sty = new StyleAttribute();
        boolean shapeChange = false;

        if (getPres(sty.setName("x")))
        {
            float newVal = sty.getFloatValueWithUnits();
            if (newVal != x)
            {
                x = newVal;
                shapeChange = true;
            }
        }

        if (getPres(sty.setName("y")))
        {
            float newVal = sty.getFloatValueWithUnits();
            if (newVal != y)
            {
                y = newVal;
                shapeChange = true;
            }
        }

        if (getPres(sty.setName("font-family")))
        {
            String newVal = sty.getStringValue();
            if (!newVal.equals(fontFamily))
            {
                fontFamily = newVal;
                shapeChange = true;
            }
        }

        if (getPres(sty.setName("font-size")))
        {
            float newVal = sty.getFloatValueWithUnits();
            if (newVal != fontSize)
            {
                fontSize = newVal;
                shapeChange = true;
            }
        }


        if (getStyle(sty.setName("font-style")))
        {
            String s = sty.getStringValue();
            int newVal = fontStyle;
            if ("normal".equals(s))
            {
                newVal = TXST_NORMAL;
            } else if ("italic".equals(s))
            {
                newVal = TXST_ITALIC;
            } else if ("oblique".equals(s))
            {
                newVal = TXST_OBLIQUE;
            }
            if (newVal != fontStyle)
            {
                fontStyle = newVal;
                shapeChange = true;
            }
        }

        if (getStyle(sty.setName("font-weight")))
        {
            String s = sty.getStringValue();
            int newVal = fontWeight;
            if ("normal".equals(s))
            {
                newVal = TXWE_NORMAL;
            } else if ("bold".equals(s))
            {
                newVal = TXWE_BOLD;
            }
            if (newVal != fontWeight)
            {
                fontWeight = newVal;
                shapeChange = true;
            }
        }

        if (shapeChange)
        {
            build();
//            buildFont();
//            return true;
        }

        return changeState || shapeChange;
    }
}