aboutsummaryrefslogtreecommitdiffstats
path: root/src/java/org/apache/fop/svg/font/FOPGVTGlyphVector.java
blob: 0abffc52c433519445e972bd071fcb3ea0bb7beb (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
382
383
384
385
386
387
388
389
390
391
392
393
394
395
/*
 * 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
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/* $Id$ */

package org.apache.fop.svg.font;

import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.Shape;
import java.awt.font.FontRenderContext;
import java.awt.font.GlyphJustificationInfo;
import java.awt.font.GlyphMetrics;
import java.awt.geom.AffineTransform;
import java.awt.geom.GeneralPath;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.text.AttributedCharacterIterator;
import java.text.CharacterIterator;
import java.text.StringCharacterIterator;
import java.util.Arrays;
import java.util.List;

import org.apache.batik.gvt.font.GVTFont;
import org.apache.batik.gvt.font.GVTGlyphMetrics;
import org.apache.batik.gvt.font.GVTGlyphVector;
import org.apache.batik.gvt.font.GVTLineMetrics;
import org.apache.batik.gvt.text.GVTAttributedCharacterIterator;

import org.apache.fop.fonts.Font;
import org.apache.fop.fonts.FontMetrics;
import org.apache.fop.fonts.GlyphMapping;
import org.apache.fop.fonts.TextFragment;
import org.apache.fop.traits.MinOptMax;

class FOPGVTGlyphVector implements GVTGlyphVector {

    protected final CharacterIterator charIter;

    private final FOPGVTFont font;

    private final int fontSize;

    private final FontMetrics fontMetrics;

    private final FontRenderContext frc;

    protected int[] glyphs;

    protected List associations;

    protected float[] positions;

    private Rectangle2D[] boundingBoxes;

    private GeneralPath outline;

    private AffineTransform[] glyphTransforms;

    private boolean[] glyphVisibilities;

    private Rectangle2D logicalBounds;

    FOPGVTGlyphVector(FOPGVTFont font, final CharacterIterator iter, FontRenderContext frc) {
        this.charIter = iter;
        this.font = font;
        Font f = font.getFont();
        this.fontSize = f.getFontSize();
        this.fontMetrics = f.getFontMetrics();
        this.frc = frc;
    }

    public void performDefaultLayout() {
        Font f = font.getFont();
        TextFragment text = new SVGTextFragment(charIter);
        MinOptMax letterSpaceIPD = MinOptMax.ZERO;
        MinOptMax[] letterSpaceAdjustments = new MinOptMax[charIter.getEndIndex() - charIter.getBeginIndex()];
        GlyphMapping mapping = GlyphMapping.doGlyphMapping(text, charIter.getBeginIndex(), charIter.getEndIndex(),
            f, letterSpaceIPD, letterSpaceAdjustments, '\0', '\0', false, 0, true);
        maybeReverse(mapping);
        CharacterIterator glyphAsCharIter =
            mapping.mapping != null ? new StringCharacterIterator(mapping.mapping) : charIter;
        this.glyphs = buildGlyphs(f, glyphAsCharIter);
        this.associations = mapping.associations;
        this.positions = buildGlyphPositions(glyphAsCharIter, mapping.gposAdjustments, letterSpaceAdjustments);
        this.glyphVisibilities = new boolean[this.glyphs.length];
        Arrays.fill(glyphVisibilities, true);
        this.glyphTransforms = new AffineTransform[this.glyphs.length];
    }

    protected void maybeReverse(GlyphMapping mapping) {
    }

    private static class SVGTextFragment implements TextFragment {

        private final CharacterIterator charIter;

        private String script;

        private String language;

        SVGTextFragment(CharacterIterator charIter) {
            this.charIter = charIter;
            if (charIter instanceof AttributedCharacterIterator) {
                AttributedCharacterIterator aci = (AttributedCharacterIterator) charIter;
                aci.first();
                this.script = (String) aci.getAttribute(GVTAttributedCharacterIterator.TextAttribute.SCRIPT);
                this.language = (String) aci.getAttribute(GVTAttributedCharacterIterator.TextAttribute.LANGUAGE);
            }
        }

        public CharSequence subSequence(int startIndex, int endIndex) {
            StringBuilder sb = new StringBuilder();
            for (char c = charIter.first(); c != CharacterIterator.DONE; c = charIter.next()) {
                sb.append(c);
            }
            return sb.toString();
        }

        public String getScript() {
            if (script != null) {
                return script;
            } else {
                return "auto";
            }
        }

        public String getLanguage() {
            if (language != null) {
                return language;
            } else {
                return "none";
            }
        }

        public char charAt(int index) {
            return charIter.setIndex(index - charIter.getBeginIndex());
        }
    }

    private int[] buildGlyphs(Font font, final CharacterIterator glyphAsCharIter) {
        int[] glyphs = new int[glyphAsCharIter.getEndIndex() - glyphAsCharIter.getBeginIndex()];
        int index = 0;
        for (char c = glyphAsCharIter.first();  c != CharacterIterator.DONE; c = glyphAsCharIter.next()) {
            glyphs[index] = font.mapChar(c);
            index++;
        }
        return glyphs;
    }

    private static final int[] PA_ZERO = new int[4];

    /**
     * Build glyph position array.
     * @param glyphAsCharIter iterator for mapped glyphs as char codes (not glyph codes)
     * @param dp optionally null glyph position adjustments array
     * @param lsa optionally null letter space adjustments array
     * @return array of floats that denote [X,Y] position pairs for each glyph including
     * including an implied subsequent glyph; i.e., returned array contains one more pair
     * than the numbers of glyphs, where the position denoted by this last pair represents
     * the position after the last glyph has incurred advancement
     */
    private float[] buildGlyphPositions(final CharacterIterator glyphAsCharIter, int[][] dp, MinOptMax[] lsa) {
        int numGlyphs = glyphAsCharIter.getEndIndex() - glyphAsCharIter.getBeginIndex();
        float[] positions = new float[2 * (numGlyphs + 1)];
        float xc = 0f;
        float yc = 0f;
        if (dp != null) {
            for (int i = 0; i < numGlyphs + 1; ++i) {
                int[] pa = ((i >= dp.length) || (dp[i] == null)) ? PA_ZERO : dp[i];
                float xo = xc + ((float) pa[0]) / 1000f;
                float yo = yc - ((float) pa[1]) / 1000f;
                float xa = getGlyphWidth(i) + ((float) pa[2]) / 1000f;
                float ya = ((float) pa[3]) / 1000f;
                int k = 2 * i;
                positions[k + 0] = xo;
                positions[k + 1] = yo;
                xc += xa;
                yc += ya;
            }
        } else if (lsa != null) {
            for (int i = 0; i < numGlyphs + 1; ++i) {
                MinOptMax sa = (((i + 1) >= lsa.length) || (lsa[i + 1] == null)) ? MinOptMax.ZERO : lsa[i + 1];
                float xo = xc;
                float yo = yc;
                float xa = getGlyphWidth(i) + sa.getOpt() / 1000f;
                float ya = 0;
                int k = 2 * i;
                positions[k + 0] = xo;
                positions[k + 1] = yo;
                xc += xa;
                yc += ya;
            }
        }
        return positions;
    }

    private float getGlyphWidth(int index) {
        if (index < glyphs.length) {
            return fontMetrics.getWidth(glyphs[index], fontSize) / 1000000f;
        } else {
            return 0f;
        }
    }

    public GVTFont getFont() {
        return font;
    }

    public FontRenderContext getFontRenderContext() {
        return frc;
    }

    public int getGlyphCode(int glyphIndex) {
        return glyphs[glyphIndex];
    }

    public int[] getGlyphCodes(int beginGlyphIndex, int numEntries,
            int[] codeReturn) {
        if (codeReturn == null) {
            codeReturn = new int[numEntries];
        }
        System.arraycopy(glyphs, beginGlyphIndex, codeReturn, 0, numEntries);
        return codeReturn;
    }

    public GlyphJustificationInfo getGlyphJustificationInfo(int glyphIndex) {
        // TODO Auto-generated method stub
        throw new UnsupportedOperationException();
    }

    public Shape getGlyphLogicalBounds(int glyphIndex) {
        GVTGlyphMetrics metrics = getGlyphMetrics(glyphIndex);
        Point2D pos = getGlyphPosition(glyphIndex);
        GVTLineMetrics fontMetrics = font.getLineMetrics(0);
        Rectangle2D bounds = new Rectangle2D.Float(0, -fontMetrics.getDescent(), metrics.getHorizontalAdvance(),
                fontMetrics.getAscent() + fontMetrics.getDescent());
        AffineTransform t = AffineTransform.getTranslateInstance(pos.getX(), pos.getY());
        AffineTransform transf = getGlyphTransform(glyphIndex);
        if (transf != null) {
            t.concatenate(transf);
        }
        t.scale(1, -1); // Translate from glyph coordinate system to user
        return t.createTransformedShape(bounds);
    }

    public GVTGlyphMetrics getGlyphMetrics(int glyphIndex) {
        Rectangle2D bbox = getBoundingBoxes()[glyphIndex];
        return new GVTGlyphMetrics(positions[2 * (glyphIndex + 1)] - positions[2 * glyphIndex],
                (fontMetrics.getAscender(fontSize) - fontMetrics.getDescender(fontSize)) / 1000000f,
                bbox, GlyphMetrics.STANDARD);
    }

    public Shape getGlyphOutline(int glyphIndex) {
        Shape glyphBox = getBoundingBoxes()[glyphIndex];
        AffineTransform tr = AffineTransform.getTranslateInstance(positions[glyphIndex * 2],
                positions[glyphIndex * 2 + 1]);
        AffineTransform glyphTransform = getGlyphTransform(glyphIndex);
        if (glyphTransform != null) {
            tr.concatenate(glyphTransform);
        }
        return tr.createTransformedShape(glyphBox);
    }

    public Rectangle2D getGlyphCellBounds(int glyphIndex) {
        // TODO Auto-generated method stub
        throw new UnsupportedOperationException();
    }

    public Point2D getGlyphPosition(int glyphIndex) {
        int positionIndex = glyphIndex * 2;
        return new Point2D.Float(positions[positionIndex], positions[positionIndex + 1]);
    }

    public float[] getGlyphPositions(int beginGlyphIndex, int numEntries, float[] positionReturn) {
        if (positionReturn == null) {
            positionReturn = new float[numEntries * 2];
        }
        System.arraycopy(positions, beginGlyphIndex * 2, positionReturn, 0, numEntries * 2);
        return positionReturn;
    }

    public AffineTransform getGlyphTransform(int glyphIndex) {
        return glyphTransforms[glyphIndex];
    }

    public Shape getGlyphVisualBounds(int glyphIndex) {
        Rectangle2D bbox = getBoundingBoxes()[glyphIndex];
        Point2D pos = getGlyphPosition(glyphIndex);
        AffineTransform t = AffineTransform.getTranslateInstance(pos.getX(), pos.getY());
        AffineTransform transf = getGlyphTransform(glyphIndex);
        if (transf != null) {
            t.concatenate(transf);
        }
        return t.createTransformedShape(bbox);
    }

    public Rectangle2D getLogicalBounds() {
        if (logicalBounds == null) {
            GeneralPath logicalBoundsPath = new GeneralPath();
            for (int i = 0; i < getNumGlyphs(); i++) {
                Shape glyphLogicalBounds = getGlyphLogicalBounds(i);
                logicalBoundsPath.append(glyphLogicalBounds, false);
            }
            logicalBounds = logicalBoundsPath.getBounds2D();
        }
        return logicalBounds;
    }

    public int getNumGlyphs() {
        return glyphs.length;
    }

    public Shape getOutline() {
        if (outline == null) {
            outline = new GeneralPath();
            for (int i = 0; i < glyphs.length; i++) {
                outline.append(getGlyphOutline(i), false);
            }
        }
        return outline;
    }

    public Shape getOutline(float x, float y) {
        // TODO Auto-generated method stub
        throw new UnsupportedOperationException();
    }

    public Rectangle2D getGeometricBounds() {
        // TODO Auto-generated method stub
        throw new UnsupportedOperationException();
    }

    public Rectangle2D getBounds2D(AttributedCharacterIterator aci) {
        return getOutline().getBounds2D();
    }

    public void setGlyphPosition(int glyphIndex, Point2D newPos) {
        int idx = glyphIndex * 2;
        positions[idx] = (float) newPos.getX();
        positions[idx + 1] = (float) newPos.getY();
    }

    public void setGlyphTransform(int glyphIndex, AffineTransform newTX) {
        glyphTransforms[glyphIndex] = newTX;
    }

    public void setGlyphVisible(int glyphIndex, boolean visible) {
        glyphVisibilities[glyphIndex] = visible;
    }

    public boolean isGlyphVisible(int glyphIndex) {
        return glyphVisibilities[glyphIndex];
    }

    public int getCharacterCount(int startGlyphIndex, int endGlyphIndex) {
        // TODO Not that simple if complex scripts are involved
        return endGlyphIndex - startGlyphIndex + 1;
    }

    public void draw(Graphics2D graphics2d, AttributedCharacterIterator aci) {
        // NOP
    }

    private Rectangle2D[] getBoundingBoxes() {
        if (boundingBoxes == null) {
            buildBoundingBoxes();
        }
        return boundingBoxes;
    }

    private void buildBoundingBoxes() {
        boundingBoxes = new Rectangle2D[glyphs.length];
        for (int i = 0; i < glyphs.length; i++) {
            Rectangle bbox = fontMetrics.getBoundingBox(glyphs[i], fontSize);
            boundingBoxes[i] = new Rectangle2D.Float(bbox.x / 1000000f, -(bbox.y + bbox.height) / 1000000f,
                    bbox.width / 1000000f, bbox.height / 1000000f);
        }
    }

}