Skip to content

Commit 10f15b3

Browse files
[vector_graphics_compiler] Fix em units in text positions (flutter#13388)
Text `x`, `y`, `dx` and `dy` values in `em` were treated as pixels. For example, `dy=".35em"` with `font-size="425px"` moved the text down by 0.35 pixels instead of about 149, so text centered this way was drawn too high. `DoubleOrPercentage.fromString` stripped the unit with `parseDouble`, so an `em` value ended up the same as a plain number. Now it remembers that the value is in `em`, and `computeTextPosition` multiplies it by the element's font size, including one inherited from a parent. Without a font size it uses `kDefaultFontSize` (16), the same default `computeTextConfig` uses when drawing the text. The bug is in `vector_graphics_compiler`, which `flutter_svg` uses to parse SVGs. Fixes flutter/flutter#158758 ## Pre-Review Checklist **Note**: The Flutter team is currently trialing the use of [Gemini Code Assist for GitHub](https://developers.google.com/gemini-code-assist/docs/review-github-code). Comments from the `gemini-code-assist` bot should not be taken as authoritative feedback from the Flutter team. If you find its comments useful you can update your code accordingly, but if you are unsure or disagree with the feedback, please feel free to wait for a Flutter team member's review for guidance on which automated comments should be addressed. [^1]: Regular contributors who have demonstrated familiarity with the repository guidelines only need to comment if the PR is not auto-exempted by repo tooling.
1 parent 0b72e92 commit 10f15b3

8 files changed

Lines changed: 99 additions & 23 deletions

File tree

‎packages/vector_graphics_compiler/CHANGELOG.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
1+
## 1.3.4
2+
3+
* Fixes `em` units in text `x`, `y`, `dx` and `dy` being treated as pixels.
4+
15
## 1.3.3
26

37
* Throws an `UnimplementedError` instead of a `FormatException` when `text` or

‎packages/vector_graphics_compiler/lib/src/svg/constants.dart‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,3 +8,8 @@ const int kMaxReferenceExpansions = 1000;
88
/// The error message thrown when the nested reference expansions limit is exceeded.
99
const String kMaxReferenceExpansionsErrorMessage =
1010
'SVG contains too many nested reference expansions (possible Denial of Service exploit).';
11+
12+
/// The font size used for text without a `font-size`.
13+
///
14+
/// This is the size of the CSS initial value `medium` in browsers.
15+
const double kDefaultFontSize = 16;

‎packages/vector_graphics_compiler/lib/src/svg/node.dart‎

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import '../geometry/matrix.dart';
1111
import '../geometry/path.dart';
1212
import '../image/image_info.dart';
1313
import '../paint.dart';
14+
import 'constants.dart';
1415
import 'parser.dart' show SvgAttributes;
1516
import 'visitor.dart';
1617

@@ -241,10 +242,11 @@ class TextPositionNode extends ParentNode {
241242
TextPosition computeTextPosition(Rect bounds, AffineMatrix transform, {TextPosition? parent}) {
242243
final AffineMatrix computedTransform = concatTransform(transform);
243244

244-
double? x = attributes.x?.calculate(bounds.width);
245-
double? y = attributes.y?.calculate(bounds.height);
246-
double? dx = attributes.dx?.calculate(bounds.width);
247-
double? dy = attributes.dy?.calculate(bounds.height);
245+
final double fontSize = attributes.fontSize ?? kDefaultFontSize;
246+
double? x = attributes.x?.calculate(bounds.width, fontSize: fontSize);
247+
double? y = attributes.y?.calculate(bounds.height, fontSize: fontSize);
248+
double? dx = attributes.dx?.calculate(bounds.width, fontSize: fontSize);
249+
double? dy = attributes.dy?.calculate(bounds.height, fontSize: fontSize);
248250

249251
final bool hasXY = x != null && y != null;
250252
final bool hasDxDy = dx != null && dy != null;
@@ -509,7 +511,7 @@ class TextNode extends AttributedNode {
509511
attributes.textAnchorMultiplier ?? 0,
510512
attributes.fontFamily,
511513
attributes.fontWeight ?? normalFontWeight,
512-
attributes.fontSize ?? 16, // default in many browsers
514+
attributes.fontSize ?? kDefaultFontSize,
513515
attributes.textDecoration ?? TextDecoration.none,
514516
attributes.textDecorationStyle ?? TextDecorationStyle.solid,
515517
attributes.textDecorationColor ?? Color.opaqueBlack,

‎packages/vector_graphics_compiler/lib/src/svg/parser.dart‎

Lines changed: 32 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -2085,11 +2085,23 @@ class SvgAttributes {
20852085
}
20862086
}
20872087

2088-
/// A value that represents either an absolute pixel coordinate or a percentage
2089-
/// of a bounding dimension.
2088+
/// The unit of a [DoubleOrPercentage].
2089+
enum _DoubleOrPercentageUnit {
2090+
/// An absolute pixel coordinate.
2091+
pixels,
2092+
2093+
/// A fraction of a bounding dimension.
2094+
percentage,
2095+
2096+
/// A multiple of the font size.
2097+
em,
2098+
}
2099+
2100+
/// A value that represents either an absolute pixel coordinate, a percentage
2101+
/// of a bounding dimension, or a multiple of the font size (`em`).
20902102
@immutable
20912103
class DoubleOrPercentage {
2092-
const DoubleOrPercentage._(this._value, this._isPercentage);
2104+
const DoubleOrPercentage._(this._value, this._unit);
20932105

20942106
/// Constructs a [DoubleOrPercentage] from a raw SVG attribute string.
20952107
static DoubleOrPercentage? fromString(String? raw) {
@@ -2098,33 +2110,36 @@ class DoubleOrPercentage {
20982110
}
20992111

21002112
if (isPercentage(raw)) {
2101-
return DoubleOrPercentage._(parsePercentage(raw), true);
2113+
return DoubleOrPercentage._(parsePercentage(raw), _DoubleOrPercentageUnit.percentage);
21022114
}
2103-
return DoubleOrPercentage._(parseDouble(raw)!, false);
2115+
if (isEm(raw)) {
2116+
return DoubleOrPercentage._(parseEm(raw), _DoubleOrPercentageUnit.em);
2117+
}
2118+
return DoubleOrPercentage._(parseDouble(raw)!, _DoubleOrPercentageUnit.pixels);
21042119
}
21052120

21062121
final double _value;
2107-
final bool _isPercentage;
2122+
final _DoubleOrPercentageUnit _unit;
21082123

21092124
/// Calculates the result of applying this dimension within [bound].
21102125
///
2111-
/// If this is a percentage, it will return a percentage of bound. Otherwise,
2112-
/// it returns the value of this.
2113-
double calculate(double bound) {
2114-
if (_isPercentage) {
2115-
return _value * bound;
2116-
}
2117-
return _value;
2126+
/// If this is a percentage, it will return a percentage of bound. If this is
2127+
/// an `em` value, it will return a multiple of [fontSize]. Otherwise, it
2128+
/// returns the value of this.
2129+
double calculate(double bound, {double fontSize = kDefaultFontSize}) {
2130+
return switch (_unit) {
2131+
_DoubleOrPercentageUnit.pixels => _value,
2132+
_DoubleOrPercentageUnit.percentage => _value * bound,
2133+
_DoubleOrPercentageUnit.em => _value * fontSize,
2134+
};
21182135
}
21192136

21202137
@override
2121-
int get hashCode => Object.hash(_value, _isPercentage);
2138+
int get hashCode => Object.hash(_value, _unit);
21222139

21232140
@override
21242141
bool operator ==(Object other) {
2125-
return other is DoubleOrPercentage &&
2126-
other._isPercentage == _isPercentage &&
2127-
other._value == _value;
2142+
return other is DoubleOrPercentage && other._unit == _unit && other._value == _value;
21282143
}
21292144
}
21302145

‎packages/vector_graphics_compiler/lib/src/svg/parsers.dart‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -167,6 +167,23 @@ double parsePercentage(String val, {double multiplier = 1.0}) {
167167
/// Whether a string should be treated as a percentage (i.e. if it ends with a `'%'`).
168168
bool isPercentage(String? val) => val?.endsWith('%') ?? false;
169169

170+
/// Parses values in the form of '1.5em' as a multiple of the font size.
171+
double parseEm(String val) {
172+
final String trimmed = val.trim();
173+
return double.parse(trimmed.substring(0, trimmed.length - 2));
174+
}
175+
176+
/// Whether a string should be treated as an `em` value (i.e. if it is a number
177+
/// followed by `'em'`, in any case).
178+
bool isEm(String? val) {
179+
if (val == null) {
180+
return false;
181+
}
182+
final String trimmed = val.trim();
183+
return trimmed.toLowerCase().endsWith('em') &&
184+
double.tryParse(trimmed.substring(0, trimmed.length - 2)) != null;
185+
}
186+
170187
/// Parses value from the form '25%', 0.25 or 25.0 as a double.
171188
/// Note: Percentage or decimals will be multiplied by the total
172189
/// view box size, where as doubles will be returned as is.

‎packages/vector_graphics_compiler/pubspec.yaml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ name: vector_graphics_compiler
22
description: A compiler to convert SVGs to the binary format used by `package:vector_graphics`.
33
repository: https://github.com/flutter/packages/tree/main/packages/vector_graphics_compiler
44
issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+vector_graphics%22
5-
version: 1.3.3
5+
version: 1.3.4
66

77
executables:
88
vector_graphics_compiler:

‎packages/vector_graphics_compiler/test/parser_test.dart‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -470,6 +470,26 @@ ${[for (var i = 2; i <= 30; i++) ' <pattern id="lvl$i" width="10" height="10"
470470
]);
471471
});
472472

473+
test('em units in text positions are relative to the font size', () {
474+
final VectorInstructions instructions = parseWithoutOptimizers('''
475+
<svg width="1000" height="500" xmlns="http://www.w3.org/2000/svg">
476+
<text x="500" y="250" dy=".5em" font-size="400">21</text>
477+
<g font-size="20">
478+
<text x="1em" y="2em" dx="1em" dy="-1em">inherited</text>
479+
</g>
480+
<text x="10" y="10" dy="1em">default</text>
481+
<text x="10" y="10" dy="1EM" font-size="10">upper case</text>
482+
</svg>
483+
''');
484+
485+
expect(instructions.textPositions, const <TextPosition>[
486+
TextPosition(x: 500, y: 250, dy: 200, reset: true),
487+
TextPosition(x: 20, y: 40, dx: 20, dy: -20, reset: true),
488+
TextPosition(x: 10, y: 10, dy: 16, reset: true),
489+
TextPosition(x: 10, y: 10, dy: 10, reset: true),
490+
]);
491+
});
492+
473493
test('Non-standard root font-weight="regular" uses initial weight', () {
474494
final VectorInstructions instructions = parseWithoutOptimizers('''
475495
<svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">

‎packages/vector_graphics_compiler/test/parsers_test.dart‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -478,6 +478,19 @@ void main() {
478478
expect(parser.parseMaskType(' luminance '), MaskType.luminance);
479479
expect(parser.parseMaskType('unknown'), null);
480480
});
481+
482+
test('em parsing', () {
483+
expect(isEm(null), false);
484+
expect(isEm('1'), false);
485+
expect(isEm('em'), false);
486+
expect(isEm('1rem'), false);
487+
expect(isEm('1xem'), false);
488+
expect(isEm('1em'), true);
489+
expect(isEm(' -.5EM '), true);
490+
expect(parseEm('1em'), 1);
491+
expect(parseEm(' -.5EM '), -0.5);
492+
expect(parseEm('1e2em'), 100);
493+
});
481494
}
482495

483496
class TestColorMapper extends ColorMapper {

0 commit comments

Comments
 (0)