Debian Codegraph @

src/com/github/weisj/jsvg/nodes/text/TextPath.java

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
•1 /*
2 * MIT License
3 *
4 * Copyright (c) 2021-2026 Jannis Weis
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
7 * associated documentation files (the "Software"), to deal in the Software without restriction,
8 * including without limitation the rights to use, copy, modify, merge, publish, distribute,
9 * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
10 * furnished to do so, subject to the following conditions:
11 *
12 * The above copyright notice and this permission notice shall be included in all copies or
13 * substantial portions of the Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
16 * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
20 *
21 */
22 package com.github.weisj.jsvg.nodes.text;
23
24 import java.awt.*;
25 import java.awt.geom.*;
26 import java.util.List;
27
28 import org.jetbrains.annotations.NotNull;
29 import org.jetbrains.annotations.Nullable;
30
31 import com.github.weisj.jsvg.attributes.FillRule;
32 import com.github.weisj.jsvg.attributes.text.GlyphRenderMethod;
33 import com.github.weisj.jsvg.attributes.text.Side;
34 import com.github.weisj.jsvg.attributes.text.Spacing;
35 import com.github.weisj.jsvg.attributes.text.TextAnchor;
36 import com.github.weisj.jsvg.attributes.value.PercentageDimension;
37 import com.github.weisj.jsvg.geometry.SVGShape;
38 import com.github.weisj.jsvg.geometry.size.Length;
39 import com.github.weisj.jsvg.geometry.util.GeometryUtil;
40 import com.github.weisj.jsvg.geometry.util.ReversePathIterator;
41 import com.github.weisj.jsvg.nodes.Anchor;
42 import com.github.weisj.jsvg.nodes.SVGNode;
43 import com.github.weisj.jsvg.nodes.ShapeNode;
44 import com.github.weisj.jsvg.nodes.animation.Animate;
45 import com.github.weisj.jsvg.nodes.animation.AnimateTransform;
46 import com.github.weisj.jsvg.nodes.animation.Set;
47 import com.github.weisj.jsvg.nodes.prototype.HasGeometryContext;
48 import com.github.weisj.jsvg.nodes.prototype.Transformable;
49 import com.github.weisj.jsvg.nodes.prototype.impl.HasGeometryContextImpl;
50 import com.github.weisj.jsvg.nodes.prototype.spec.Category;
51 import com.github.weisj.jsvg.nodes.prototype.spec.ElementCategories;
52 import com.github.weisj.jsvg.nodes.prototype.spec.NotImplemented;
53 import com.github.weisj.jsvg.nodes.prototype.spec.PermittedContent;
54 import com.github.weisj.jsvg.nodes.text.TextSegment.RenderableSegment.UseTextLengthForCalculation;
55 import com.github.weisj.jsvg.parser.TextContent;
56 import com.github.weisj.jsvg.parser.impl.AttributeNode;
57 import com.github.weisj.jsvg.parser.impl.AttributeNode.ElementRelation;
58 import com.github.weisj.jsvg.renderer.MeasureContext;
59 import com.github.weisj.jsvg.renderer.RenderContext;
60 import com.github.weisj.jsvg.renderer.impl.ElementBounds;
61 import com.github.weisj.jsvg.renderer.output.Output;
62 import com.github.weisj.jsvg.renderer.output.TextOutput;
63 import com.github.weisj.jsvg.util.AttributeUtil;
64 import com.github.weisj.jsvg.util.PathUtil;
65
66 @ElementCategories({Category.Graphic, Category.TextContent, Category.TextContentChild})
67 @PermittedContent(
68 categories = {Category.Descriptive},
69 anyOf = {Anchor.class, TextSpan.class, Animate.class, AnimateTransform.class, Set.class, /* <altGlyph>, <tref> */},
70 charData = true
71 )
72 public final class TextPath extends TextContainer<TextSegment>
73 implements HasGeometryContext.ByDelegate, TextLayoutGroup, CursorContext {
74 public static final String TAG = "textpath";
75 private static final boolean DEBUG = false;
76
77 private final LayoutGroupSegment<TextSegment, TextPath> asSegment = new LayoutGroupSegment<>(this, this);
78
79 private HasGeometryContext geometryContext;
80 private SVGShape pathShape;
81 private @Nullable Transformable pathShapeTransform;
82
83 @SuppressWarnings("UnusedVariable")
84 private @NotImplemented Spacing spacing;
85 @SuppressWarnings("UnusedVariable")
86 private @NotImplemented GlyphRenderMethod renderMethod;
87 private Side side;
88
89 private Length startOffset;
90
91 @Override
92 public @NotNull String tagName() {
93 return TAG;
94 }
95
96 @Override
97 public void build(@NotNull AttributeNode attributeNode) {
98 super.build(attributeNode);
99 geometryContext = HasGeometryContextImpl.parse(attributeNode);
100
101 renderMethod = attributeNode.getEnum("method", GlyphRenderMethod.Align);
102 side = attributeNode.getEnum("side", Side.Left);
103 spacing = attributeNode.getEnum("spacing", Spacing.Auto);
104 // Todo: Needs to be resolved w.r.t to the paths coordinate system
105 startOffset = attributeNode.getLength("startOffset", PercentageDimension.CUSTOM, 0);
106
107 String pathData = attributeNode.getValue("path");
108 if (pathData != null) {
109 // TODO: If this contains an error, we should use the href attribute instead.
110 pathShape = PathUtil.parseFromPathData(pathData, FillRule.EvenOdd);
111 pathShapeTransform = null;
112 } else {
113 String href = attributeNode.getHref();
114 ShapeNode shape =
115 attributeNode.getElementByHref(ShapeNode.class, Category.Shape /* BasicShape or Path */, href,
116 ElementRelation.GEOMETRY_DATA);
117 if (shape != null) {
118 pathShape = shape.shape();
119 pathShapeTransform = shape;
120 }
121 }
122 }
123
124 @Override
125 protected void doAdd(@NotNull SVGNode node) {
126 children.add((TextSegment) node);
127 }
128
129 @Override
130 public void addContent(@NotNull TextContent.Segment content) {
131 if (content.isConstant() && content.text().isEmpty()) return;
132 if (children.isEmpty() && content.isConstant() && AttributeUtil.isBlank(content.text())) return;
133 children.add(new StringTextSegment(this, this, children.size(), content));
134 }
135
136 @Override
137 protected boolean acceptChild(@Nullable String id, @NotNull SVGNode node) {
138 return node instanceof TextSegment;
139 }
140
141 @Override
142 public @NotNull HasGeometryContext geometryContextDelegate() {
143 return geometryContext;
144 }
145
146 @Override
147 public boolean isVisible(@NotNull RenderContext context) {
148 return pathShape != null && super.isVisible(context);
149 }
150
151 @Override
152 public @NotNull List<? extends TextSegment> segments() {
153 return children();
154 }
155
156 @Override
157 public @NotNull Point2D renderText(@Nullable Point2D start, @NotNull RenderContext context,
158 @NotNull Output output) {
159 PathGlyphCursor cursor = createCursorWithAnchorAdjustment(context);
160 TextOutput textOutput = output.textOutput();
161 textOutput.beginText();
162 asSegment.prepareSegmentForRendering(cursor, context, textOutput);
163 asSegment.renderSegmentWithoutLayout(cursor, context, output);
164 textOutput.endText();
165 if (DEBUG) {
166 output.debugPaint(g -> paintDebugPath(context, g));
167 }
168 return GeometryUtil.lastPointOnPath(cursor.pathIterator());
169 }
170
171 @Override
172 public @NotNull Point2D appendGlyphShape(@Nullable Point2D start, @NotNull RenderContext context,
173 @NotNull Path2D shape) {
174 PathGlyphCursor cursor = createCursorWithAnchorAdjustment(context);
175 shape.append(glyphShape(cursor, context), false);
176 return GeometryUtil.lastPointOnPath(cursor.pathIterator());
177 }
178
179 @Override
180 @NotNull
181 Shape glyphShape(@NotNull RenderContext context) {
182 return glyphShape(createCursorWithAnchorAdjustment(context), context);
183 }
184
185 private @NotNull Shape glyphShape(PathGlyphCursor cursor, @NotNull RenderContext context) {
186 MutableGlyphRun glyphRun = new MutableGlyphRun();
187 asSegment.appendTextShape(cursor, glyphRun, context);
188 return glyphRun.shape();
189 }
190
191 @Override
192 public @Nullable Length fixedLength() {
193 if (textLength.isSpecified()) return textLength;
194 return null;
195 }
196
197 private @NotNull PathGlyphCursor createCursorWithAnchorAdjustment(@NotNull RenderContext context) {
198 return new PathGlyphCursor(
199 createPathIterator(context),
200 computeAnchorAdjustedStartOffset(context));
201 }
202
203 private float computeAnchorAdjustedStartOffset(@NotNull RenderContext context) {
204 float offset = computeStartOffset(context);
205 TextAnchor textAnchor = textAnchor(context);
206 switch (textAnchor) {
207 case Start:
208 return offset;
209 case Middle:
210 return offset - computeTotalTextLength(context) / 2f;
211 case End:
212 return offset - computeTotalTextLength(context);
213 default:
214 throw new IllegalStateException("Unexpected value: " + textAnchor);
215 }
216 }
217
218 private float computeTotalTextLength(@NotNull RenderContext context) {
219 return (float) asSegment.computeTextMetrics(context, UseTextLengthForCalculation.YES).totalAdjustableLength();
220 }
221
222 private float computeStartOffset(@NotNull RenderContext context) {
223 float offset = startOffset.resolve(context.measureContext());
224 if (startOffset.unit().isPercentage()) {
225 if (pathShape.isClosed(context)) {
226 // Modulo 1 to obtain value inside [0, 1]
227 offset = (offset % 1 + 1) % 1;
228 }
229 return (float) (offset * pathShape.pathLength(context));
230 }
231 return offset;
232 }
233
234 private void paintDebugPath(@NotNull RenderContext context, @NotNull Graphics2D g) {
235 PathIterator pathIterator = createPathIterator(context);
236 float startX = 0;
237 float startY = 0;
238 float curX = 0;
239 float curY = 0;
240 g.setStroke(new BasicStroke(0.5f));
241 float[] cord = new float[2];
242 while (!pathIterator.isDone()) {
243 switch (pathIterator.currentSegment(cord)) {
244 case PathIterator.SEG_LINETO:
245 g.setColor(Color.MAGENTA);
246 g.draw(new Line2D.Float(curX, curY, cord[0], cord[1]));
247 g.setColor(Color.RED);
248 g.fillRect((int) curX - 2, (int) curY - 2, 4, 4);
249 g.fillRect((int) cord[0] - 2, (int) cord[1] - 2, 4, 4);
250 curX = cord[0];
251 curY = cord[1];
252 break;
253 case PathIterator.SEG_MOVETO:
254 curX = cord[0];
255 curY = cord[1];
256 startX = curX;
257 startY = curY;
258 break;
259 case PathIterator.SEG_CLOSE:
260 g.setColor(Color.MAGENTA);
261 g.draw(new Line2D.Float(curX, curY, startX, startY));
262 g.setColor(Color.RED);
263 g.fillRect((int) curX - 2, (int) curY - 2, 4, 4);
264 g.fillRect((int) startX - 2, (int) startY - 2, 4, 4);
265 curX = startX;
266 curY = startY;
267 break;
268 default:
269 throw new IllegalStateException();
270 }
271 pathIterator.next();
272 }
273 }
274
275 private @NotNull PathIterator createPathIterator(@NotNull RenderContext context) {
276 MeasureContext measureContext = context.measureContext();
277 Shape path = pathShape.shape(context);
278 if (pathShapeTransform != null) {
279 path = pathShapeTransform.transformShape(path, context,
280 ElementBounds.fromUntransformedBounds(this, context, path.getBounds2D(), Box.BoundingBox));
281 }
282 // For fonts this is a good enough approximation
283 float flatness = 0.1f * measureContext.ex();
284 switch (side) {
285 case Left:
286 return path.getPathIterator(null, flatness);
287 case Right:
288 return new ReversePathIterator(path.getPathIterator(null, flatness));
289 default:
290 throw new IllegalStateException();
291 }
292 }
293
294 @Override
295 public @NotNull GlyphCursor createLocalCursor(boolean isInitial, @NotNull GlyphCursor current) {
296 return current;
297 }
298
299 @Override
300 public void cleanUpLocalCursor(@NotNull GlyphCursor current, @NotNull GlyphCursor local) {
301 current.updateFrom(local);
302 }
303 }