/
xml_parsers.dart
407 lines (371 loc) · 12.3 KB
/
xml_parsers.dart
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
import 'dart:ui';
import 'package:path_drawing/path_drawing.dart';
import 'package:vector_math/vector_math_64.dart';
import 'package:xml/xml_events.dart';
import '../utilities/errors.dart';
import '../utilities/numbers.dart';
import '../utilities/xml.dart';
import '../vector_drawable.dart';
import 'colors.dart';
import 'parsers.dart';
double _parseRawWidthHeight(String raw) {
if (raw == '100%' || raw == '') {
return double.infinity;
}
assert(() {
final RegExp notDigits = RegExp(r'[^\d\.]');
if (!raw.endsWith('px') && raw.contains(notDigits)) {
print(
'Warning: Flutter SVG only supports the following formats for `width` and `height` on the SVG root:\n'
' width="100%"\n'
' width="100px"\n'
' width="100" (where the number will be treated as pixels).\n'
'The supplied value ($raw) will be discarded and treated as if it had not been specified.');
}
return true;
}());
return double.tryParse(raw.replaceAll('px', '')) ?? double.infinity;
}
/// Parses an SVG @viewBox attribute (e.g. 0 0 100 100) to a [Rect].
///
/// The [nullOk] parameter controls whether this function should throw if there is no
/// viewBox or width/height parameters.
///
/// The [respectWidthHeight] parameter specifies whether `width` and `height` attributes
/// on the root SVG element should be treated in accordance with the specification.
DrawableViewport parseViewBox(
List<XmlElementAttribute> svg, {
bool nullOk = false,
}) {
final String viewBox = getAttribute(svg, 'viewBox');
final String rawWidth = getAttribute(svg, 'width');
final String rawHeight = getAttribute(svg, 'height');
if (viewBox == '' && rawWidth == '' && rawHeight == '') {
if (nullOk) {
return null;
}
throw StateError('SVG did not specify dimensions\n\n'
'The SVG library looks for a `viewBox` or `width` and `height` attribute '
'to determine the viewport boundary of the SVG. Note that these attributes, '
'as with all SVG attributes, are case sensitive.\n'
'During processing, the following attributes were found:\n'
' $svg');
}
final double width = _parseRawWidthHeight(rawWidth);
final double height = _parseRawWidthHeight(rawHeight);
if (viewBox == '') {
return DrawableViewport(
Size(width, height),
Size(width, height),
);
}
final List<String> parts = viewBox.split(RegExp(r'[ ,]+'));
if (parts.length < 4) {
throw StateError('viewBox element must be 4 elements long');
}
return DrawableViewport(
Size(width, height),
Size(
parseDouble(parts[2]),
parseDouble(parts[3]),
),
viewBoxOffset: Offset(
-parseDouble(parts[0]),
-parseDouble(parts[1]),
),
);
}
/// Builds an IRI in the form of `'url(#id)'`.
String buildUrlIri(List<XmlElementAttribute> attributes) =>
'url(#${getAttribute(attributes, 'id')})';
/// An empty IRI.
const String emptyUrlIri = 'url(#)';
/// Parses a `spreadMethod` attribute into a [TileMode].
TileMode parseTileMode(List<XmlElementAttribute> attributes) {
final String spreadMethod =
getAttribute(attributes, 'spreadMethod', def: 'pad');
switch (spreadMethod) {
case 'pad':
return TileMode.clamp;
case 'repeat':
return TileMode.repeated;
case 'reflect':
return TileMode.mirror;
default:
return TileMode.clamp;
}
}
/// Parses an @stroke-dasharray attribute into a [CircularIntervalList]
///
/// Does not currently support percentages.
CircularIntervalList<double> parseDashArray(
List<XmlElementAttribute> attributes,
) {
final String rawDashArray = getAttribute(attributes, 'stroke-dasharray');
if (rawDashArray == '') {
return null;
} else if (rawDashArray == 'none') {
return DrawableStyle.emptyDashArray;
}
final List<String> parts = rawDashArray.split(RegExp(r'[ ,]+'));
return CircularIntervalList<double>(
parts.map((String part) => parseDouble(part)).toList());
}
/// Parses a @stroke-dashoffset into a [DashOffset]
DashOffset parseDashOffset(List<XmlElementAttribute> attributes) {
final String rawDashOffset = getAttribute(attributes, 'stroke-dashoffset');
if (rawDashOffset == '') {
return null;
}
if (rawDashOffset.endsWith('%')) {
final double percentage =
parseDouble(rawDashOffset.substring(0, rawDashOffset.length - 1)) / 100;
return DashOffset.percentage(percentage);
} else {
return DashOffset.absolute(parseDouble(rawDashOffset));
}
}
/// Parses an @opacity value into a [double], clamped between 0..1.
double parseOpacity(List<XmlElementAttribute> attributes) {
final String rawOpacity = getAttribute(attributes, 'opacity', def: null);
if (rawOpacity != null) {
return parseDouble(rawOpacity).clamp(0.0, 1.0).toDouble();
}
return null;
}
DrawablePaint _getDefinitionPaint(PaintingStyle paintingStyle, String iri,
DrawableDefinitionServer definitions, Rect bounds,
{double opacity}) {
final Shader shader = definitions.getShader(iri, bounds);
if (shader == null) {
reportMissingDef(iri, '_getDefinitionPaint');
}
return DrawablePaint(
paintingStyle,
shader: shader,
color: opacity != null ? Color.fromRGBO(255, 255, 255, opacity) : null,
);
}
/// Parses a @stroke attribute into a [Paint].
DrawablePaint parseStroke(
List<XmlElementAttribute> attributes,
Rect bounds,
DrawableDefinitionServer definitions,
DrawablePaint parentStroke,
) {
final String rawStroke = getAttribute(attributes, 'stroke');
final String rawStrokeOpacity = getAttribute(
attributes,
'stroke-opacity',
def: '1.0',
);
final String rawOpacity = getAttribute(attributes, 'opacity');
double opacity = parseDouble(rawStrokeOpacity).clamp(0.0, 1.0).toDouble();
if (rawOpacity != '') {
opacity *= parseDouble(rawOpacity).clamp(0.0, 1.0);
}
if (rawStroke.startsWith('url')) {
return _getDefinitionPaint(
PaintingStyle.stroke,
rawStroke,
definitions,
bounds,
opacity: opacity,
);
}
if (rawStroke == '' && DrawablePaint.isEmpty(parentStroke)) {
return null;
}
if (rawStroke == 'none') {
return DrawablePaint.empty;
}
final String rawStrokeCap = getAttribute(attributes, 'stroke-linecap');
final String rawLineJoin = getAttribute(attributes, 'stroke-linejoin');
final String rawMiterLimit = getAttribute(attributes, 'stroke-miterlimit');
final String rawStrokeWidth = getAttribute(attributes, 'stroke-width');
final DrawablePaint paint = DrawablePaint(
PaintingStyle.stroke,
color: rawStroke == ''
? (parentStroke?.color ?? colorBlack).withOpacity(opacity)
: parseColor(rawStroke).withOpacity(opacity),
strokeCap: rawStrokeCap == 'null'
? parentStroke?.strokeCap ?? StrokeCap.butt
: StrokeCap.values.firstWhere(
(StrokeCap sc) => sc.toString() == 'StrokeCap.$rawStrokeCap',
orElse: () => StrokeCap.butt,
),
strokeJoin: rawLineJoin == ''
? parentStroke?.strokeJoin ?? StrokeJoin.miter
: StrokeJoin.values.firstWhere(
(StrokeJoin sj) => sj.toString() == 'StrokeJoin.$rawLineJoin',
orElse: () => StrokeJoin.miter,
),
strokeMiterLimit: rawMiterLimit == ''
? parentStroke?.strokeMiterLimit ?? 4.0
: parseDouble(rawMiterLimit),
strokeWidth: rawStrokeWidth == ''
? parentStroke?.strokeWidth ?? 1.0
: parseDouble(rawStrokeWidth),
);
return paint;
}
/// Parses a `fill` attribute.
DrawablePaint parseFill(
List<XmlElementAttribute> el,
Rect bounds,
DrawableDefinitionServer definitions,
DrawablePaint parentFill,
) {
final String rawFill = getAttribute(el, 'fill');
final String rawFillOpacity = getAttribute(el, 'fill-opacity', def: '1.0');
final String rawOpacity = getAttribute(el, 'opacity');
double opacity = parseDouble(rawFillOpacity).clamp(0.0, 1.0).toDouble();
if (rawOpacity != '') {
opacity *= parseDouble(rawOpacity).clamp(0.0, 1.0);
}
if (rawFill.startsWith('url')) {
return _getDefinitionPaint(
PaintingStyle.fill,
rawFill,
definitions,
bounds,
opacity: opacity,
);
}
if (rawFill == '' && parentFill == DrawablePaint.empty) {
return null;
}
if (rawFill == 'none') {
return DrawablePaint.empty;
}
return DrawablePaint(
PaintingStyle.fill,
color: rawFill == ''
? (parentFill?.color ?? colorBlack).withOpacity(opacity)
: parseColor(rawFill).withOpacity(opacity),
);
}
/// Parses a `fill-rule` attribute into a [PathFillType].
PathFillType parseFillRule(List<XmlElementAttribute> attributes,
[String attr = 'fill-rule', String def = 'nonzero']) {
final String rawFillRule = getAttribute(attributes, attr, def: def);
return parseRawFillRule(rawFillRule);
}
/// Applies a transform to a path if the [attributes] contain a `transform`.
Path applyTransformIfNeeded(Path path, List<XmlElementAttribute> attributes) {
final Matrix4 transform =
parseTransform(getAttribute(attributes, 'transform', def: null));
if (transform != null) {
return path.transform(transform.storage);
} else {
return path;
}
}
/// Parses a `clipPath` element into a list of [Path]s.
List<Path> parseClipPath(
List<XmlElementAttribute> attributes,
DrawableDefinitionServer definitions,
) {
final String rawClipAttribute = getAttribute(attributes, 'clip-path');
if (rawClipAttribute != '') {
return definitions.getClipPath(rawClipAttribute);
}
return null;
}
const Map<String, BlendMode> _blendModes = <String, BlendMode>{
'multiply': BlendMode.multiply,
'screen': BlendMode.screen,
'overlay': BlendMode.overlay,
'darken': BlendMode.darken,
'lighten': BlendMode.lighten,
'color-dodge': BlendMode.colorDodge,
'color-burn': BlendMode.colorBurn,
'hard-light': BlendMode.hardLight,
'soft-light': BlendMode.softLight,
'difference': BlendMode.difference,
'exclusion': BlendMode.exclusion,
'hue': BlendMode.hue,
'saturation': BlendMode.saturation,
'color': BlendMode.color,
'luminosity': BlendMode.luminosity,
};
/// Lookup the mask if the attribute is present
DrawableStyleable parseMask(
List<XmlElementAttribute> attributes,
DrawableDefinitionServer definitions,
) {
final String rawMaskAttribute = getAttribute(attributes, 'mask');
if (rawMaskAttribute != '') {
return definitions.getDrawable(rawMaskAttribute);
}
return null;
}
/// Parses a `font-weight` attribute value into a [FontWeight].
FontWeight parseFontWeight(String fontWeight) {
if (fontWeight == null) {
return null;
}
switch (fontWeight) {
case '100':
return FontWeight.w100;
case '200':
return FontWeight.w200;
case '300':
return FontWeight.w300;
case 'normal':
case '400':
return FontWeight.w400;
case '500':
return FontWeight.w500;
case '600':
return FontWeight.w600;
case 'bold':
case '700':
return FontWeight.w700;
case '800':
return FontWeight.w800;
case '900':
return FontWeight.w900;
}
throw UnsupportedError('Attribute value for font-weight="$fontWeight"'
' is not supported');
}
/// Parses style attributes or @style attribute.
///
/// Remember that @style attribute takes precedence.
DrawableStyle parseStyle(
List<XmlElementAttribute> attributes,
DrawableDefinitionServer definitions,
Rect bounds,
DrawableStyle parentStyle,
) {
return DrawableStyle.mergeAndBlend(
parentStyle,
stroke: parseStroke(attributes, bounds, definitions, parentStyle?.stroke),
dashArray: parseDashArray(attributes),
dashOffset: parseDashOffset(attributes),
fill: parseFill(attributes, bounds, definitions, parentStyle?.fill),
pathFillType: parseFillRule(
attributes,
'fill-rule',
parentStyle != null ? null : 'nonzero',
),
groupOpacity: parseOpacity(attributes),
mask: parseMask(attributes, definitions),
clipPath: parseClipPath(attributes, definitions),
textStyle: DrawableTextStyle(
fontFamily: getAttribute(attributes, 'font-family'),
fontSize: parseFontSize(
getAttribute(attributes, 'font-size'),
parentValue: parentStyle?.textStyle?.fontSize,
),
fontWeight: parseFontWeight(
getAttribute(attributes, 'font-weight', def: null),
),
anchor: parseTextAnchor(
getAttribute(attributes, 'text-anchor', def: 'inherit'),
),
),
blendMode: _blendModes[getAttribute(attributes, 'mix-blend-mode')],
);
}