Skip to content

Commit 8041cca

Browse files
authored
[various] Support SVG filters (blur, offset, feMerge) (flutter#11909)
[various] Support SVG filters (blur, offset, feMerge) Fixes flutter/flutter#158592 This PR introduces support for basic SVG filters (`feGaussianBlur`, `feOffset`, and `feMerge`) to the `vector_graphics` ecosystem. (Alpha mask support has been split out into a separate PR per review feedback.) Key Features: * Added parsing, resolution, and encoding of SVG filters including `feGaussianBlur`, `feOffset`, and `feMerge` in `vector_graphics_compiler`. * Updated the binary format and `vector_graphics_codec` to support encoding and decoding paint blurs. * Updated `vector_graphics` to render paint blurs using Flutter's `ui.ImageFilter.blur`. * Enhanced `SourceAlpha` filters to preserve opacity variations in gradient stops by mapping gradient colors to black while maintaining their alpha values. Implementation Details: * **Filter Chaining**: Filters are parsed into a directed acyclic graph (DAG) of primitives. The resolver traces these primitives from the filter outputs back to `SourceGraphic`/`SourceAlpha` to determine the necessary rendering layers. * **Multi-layer Filter Resolution**: Handles multi-layer filters (e.g. from `feMerge`) by duplicating the target rendering nodes for each layer in the AST. * **Text Filter Resolution**: Resolves filters at the `TextPositionNode` level (rather than leaf `TextNode`s) to maintain correct text chunk alignment and cursor positioning. * **Nested Filter Propagation**: Enhanced nested parent nodes (groups), inner path filters, and text position nodes to correctly inherit and propagate the outer `SourceAlpha` state down the tree. * **Blur Scaling**: Scales the blur standard deviations by the accumulated transform's scale factors at both the group and path/text levels to ensure correct rendering when scaled (since the compiler bakes geometry transforms at compile time, the blur sigmas must also be scaled to match). * **Compiler Optimizer & Tessellator Compatibility**: * Preserves `blurSigmaX`/`blurSigmaY` when `TessellationVisitor` and `PathOps` convert `PathNode`s to `VerticesNode`s. * Prevents `MaskingOptimizer`, `ClippingOptimizer`, and `OverdrawOptimizer` from collapsing or intersecting paths that carry a blur filter (since blurred paint extends beyond geometric path bounds). * **Spec Compliance**: * Supports both comma and space-separated `stdDeviation` values. * Defaults omitted `stdDeviation` attributes to `0.0` (as per SVG spec). * Automatically resolves default `in` attributes for `feMergeNode`s (falling back to the previous sibling primitive's result or `SourceGraphic`). * Preserves original fill/stroke opacity when applying `SourceAlpha` filters. * Handles self-closing `<feMerge />` elements. * **Robustness, Performance & Optimizations**: * Added cycle detection during filter tracing to prevent stack overflow on circular filter references. * Skips rendering node recreation for filter layers that do not affect the paint (e.g. plain `SourceGraphic` branches in a merge). * Wrapped current layer state restoration in `try-finally` blocks inside parent node and text position node visitors to guarantee robust recovery in case of exceptions. * Caches blackened gradients in `ResolvingVisitor` to prevent redundant object allocations for shared SVG gradients. * Guarded against setting paint `imageFilter` when blur standard deviations are `0.0` to avoid unnecessary rendering overhead in Flutter. * Defensively clamped blur standard deviations to non-negative values in the rendering listener to prevent crashes when processing malformed SVG files. ## 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. TAG=agy CONV=27cb188a-9ad9-4434-8918-8ef71bdba17c
1 parent 653628e commit 8041cca

23 files changed

Lines changed: 2043 additions & 69 deletions

‎packages/vector_graphics/CHANGELOG.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
1+
## 1.3.0
2+
3+
* Adds support for SVG filters (`feGaussianBlur`, `feOffset`, `feMerge`, and `feMergeNode`).
4+
15
## 1.2.7
26

37
* Fixes uncaught surface-creation throwables (such as bare JavaScript strings

‎packages/vector_graphics/lib/src/listener.dart‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -393,6 +393,16 @@ class FlutterVectorGraphicsListener extends VectorGraphicsCodecListener {
393393
_paints.add(paint);
394394
}
395395

396+
/// Sets an image blur filter on the paint with [paintId].
397+
@override
398+
void onPaintBlur(int paintId, double sigmaX, double sigmaY) {
399+
final clampedX = sigmaX > 0.0 ? sigmaX : 0.0;
400+
final clampedY = sigmaY > 0.0 ? sigmaY : 0.0;
401+
if (clampedX > 0.0 || clampedY > 0.0) {
402+
_paints[paintId].imageFilter = ImageFilter.blur(sigmaX: clampedX, sigmaY: clampedY);
403+
}
404+
}
405+
396406
@override
397407
void onPathClose() {
398408
_currentPath!.close();

‎packages/vector_graphics/pubspec.yaml‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ name: vector_graphics
22
description: A vector graphics rendering package for Flutter using a binary encoding.
33
repository: https://github.com/flutter/packages/tree/main/packages/vector_graphics
44
issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+vector_graphics%22
5-
version: 1.2.7
5+
version: 1.3.0
66

77
environment:
88
sdk: ^3.11.0
@@ -12,7 +12,7 @@ dependencies:
1212
flutter:
1313
sdk: flutter
1414
http: ^1.0.0
15-
vector_graphics_codec: ^1.1.11+1
15+
vector_graphics_codec: ^1.2.0
1616

1717
dev_dependencies:
1818
flutter_test:

‎packages/vector_graphics/test/listener_test.dart‎

Lines changed: 230 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -216,6 +216,236 @@ void main() {
216216
await listener.waitForImageDecode();
217217
expect(() => listener.onDrawImage(2, 10, 10, 100, 100, null), throwsAssertionError);
218218
});
219+
220+
test('Paint blur is applied to paint', () async {
221+
final factory = TestPictureFactory();
222+
final listener = FlutterVectorGraphicsListener(pictureFactory: factory);
223+
224+
listener.onPaintObject(
225+
color: const ui.Color(0xff000000).toARGB32(),
226+
strokeCap: null,
227+
strokeJoin: null,
228+
blendMode: BlendMode.srcIn.index,
229+
strokeMiterLimit: null,
230+
strokeWidth: null,
231+
paintStyle: ui.PaintingStyle.fill.index,
232+
id: 0,
233+
shaderId: null,
234+
);
235+
236+
listener.onPaintBlur(0, 5.0, 10.0);
237+
238+
listener.onPathStart(0, 0);
239+
listener.onPathMoveTo(0, 0);
240+
listener.onPathLineTo(10, 10);
241+
listener.onPathFinished();
242+
243+
await listener.onDrawPath(0, 0, null);
244+
245+
final Invocation drawPath = factory.fakeCanvases.single.invocations.single;
246+
expect(drawPath.isMethod, true);
247+
expect(drawPath.memberName, #drawPath);
248+
final paint = drawPath.positionalArguments[1] as ui.Paint;
249+
expect(paint.imageFilter, isNotNull);
250+
expect(paint.imageFilter, ui.ImageFilter.blur(sigmaX: 5.0, sigmaY: 10.0));
251+
});
252+
253+
test('onPaintBlur with 0.0 standard deviations does not set imageFilter', () async {
254+
final factory = TestPictureFactory();
255+
final listener = FlutterVectorGraphicsListener(pictureFactory: factory);
256+
257+
listener.onPaintObject(
258+
color: const ui.Color(0xff000000).toARGB32(),
259+
strokeCap: null,
260+
strokeJoin: null,
261+
blendMode: BlendMode.srcIn.index,
262+
strokeMiterLimit: null,
263+
strokeWidth: null,
264+
paintStyle: ui.PaintingStyle.fill.index,
265+
id: 0,
266+
shaderId: null,
267+
);
268+
269+
listener.onPaintBlur(0, 0.0, 0.0);
270+
271+
listener.onPathStart(0, 0);
272+
listener.onPathMoveTo(0, 0);
273+
listener.onPathLineTo(10, 10);
274+
listener.onPathFinished();
275+
276+
await listener.onDrawPath(0, 0, null);
277+
278+
final Invocation drawPath = factory.fakeCanvases.single.invocations.single;
279+
expect(drawPath.isMethod, true);
280+
expect(drawPath.memberName, #drawPath);
281+
final paint = drawPath.positionalArguments[1] as ui.Paint;
282+
expect(paint.imageFilter, isNull);
283+
});
284+
285+
test('onPaintBlur with negative standard deviations clamps them to 0.0', () async {
286+
final factory = TestPictureFactory();
287+
final listener = FlutterVectorGraphicsListener(pictureFactory: factory);
288+
289+
listener.onPaintObject(
290+
color: const ui.Color(0xff000000).toARGB32(),
291+
strokeCap: null,
292+
strokeJoin: null,
293+
blendMode: BlendMode.srcIn.index,
294+
strokeMiterLimit: null,
295+
strokeWidth: null,
296+
paintStyle: ui.PaintingStyle.fill.index,
297+
id: 0,
298+
shaderId: null,
299+
);
300+
301+
// One negative, one positive -> positive preserved, negative clamped to 0.0
302+
listener.onPaintBlur(0, -5.0, 10.0);
303+
304+
listener.onPathStart(0, 0);
305+
listener.onPathMoveTo(0, 0);
306+
listener.onPathLineTo(10, 10);
307+
listener.onPathFinished();
308+
309+
await listener.onDrawPath(0, 0, null);
310+
311+
final Invocation drawPath = factory.fakeCanvases.single.invocations.single;
312+
expect(drawPath.isMethod, true);
313+
expect(drawPath.memberName, #drawPath);
314+
final paint = drawPath.positionalArguments[1] as ui.Paint;
315+
expect(paint.imageFilter, isNotNull);
316+
expect(paint.imageFilter, ui.ImageFilter.blur(sigmaY: 10.0));
317+
});
318+
319+
test('onPaintBlur with both negative standard deviations does not set imageFilter', () async {
320+
final factory = TestPictureFactory();
321+
final listener = FlutterVectorGraphicsListener(pictureFactory: factory);
322+
323+
listener.onPaintObject(
324+
color: const ui.Color(0xff000000).toARGB32(),
325+
strokeCap: null,
326+
strokeJoin: null,
327+
blendMode: BlendMode.srcIn.index,
328+
strokeMiterLimit: null,
329+
strokeWidth: null,
330+
paintStyle: ui.PaintingStyle.fill.index,
331+
id: 0,
332+
shaderId: null,
333+
);
334+
335+
// Both negative -> both clamped to 0.0 -> no filter
336+
listener.onPaintBlur(0, -5.0, -10.0);
337+
338+
listener.onPathStart(0, 0);
339+
listener.onPathMoveTo(0, 0);
340+
listener.onPathLineTo(10, 10);
341+
listener.onPathFinished();
342+
343+
await listener.onDrawPath(0, 0, null);
344+
345+
final Invocation drawPath = factory.fakeCanvases.single.invocations.single;
346+
expect(drawPath.isMethod, true);
347+
expect(drawPath.memberName, #drawPath);
348+
final paint = drawPath.positionalArguments[1] as ui.Paint;
349+
expect(paint.imageFilter, isNull);
350+
});
351+
352+
test('onPaintBlur with NaN sigmaX clamps sigmaX to 0.0', () async {
353+
final factory = TestPictureFactory();
354+
final listener = FlutterVectorGraphicsListener(pictureFactory: factory);
355+
356+
listener.onPaintObject(
357+
color: const ui.Color(0xff000000).toARGB32(),
358+
strokeCap: null,
359+
strokeJoin: null,
360+
blendMode: BlendMode.srcIn.index,
361+
strokeMiterLimit: null,
362+
strokeWidth: null,
363+
paintStyle: ui.PaintingStyle.fill.index,
364+
id: 0,
365+
shaderId: null,
366+
);
367+
368+
listener.onPaintBlur(0, double.nan, 10.0);
369+
370+
listener.onPathStart(0, 0);
371+
listener.onPathMoveTo(0, 0);
372+
listener.onPathLineTo(10, 10);
373+
listener.onPathFinished();
374+
375+
await listener.onDrawPath(0, 0, null);
376+
377+
final Invocation drawPath = factory.fakeCanvases.single.invocations.single;
378+
expect(drawPath.isMethod, true);
379+
expect(drawPath.memberName, #drawPath);
380+
final paint = drawPath.positionalArguments[1] as ui.Paint;
381+
expect(paint.imageFilter, isNotNull);
382+
expect(paint.imageFilter, ui.ImageFilter.blur(sigmaY: 10.0));
383+
});
384+
385+
test('onPaintBlur with NaN sigmaY clamps sigmaY to 0.0', () async {
386+
final factory = TestPictureFactory();
387+
final listener = FlutterVectorGraphicsListener(pictureFactory: factory);
388+
389+
listener.onPaintObject(
390+
color: const ui.Color(0xff000000).toARGB32(),
391+
strokeCap: null,
392+
strokeJoin: null,
393+
blendMode: BlendMode.srcIn.index,
394+
strokeMiterLimit: null,
395+
strokeWidth: null,
396+
paintStyle: ui.PaintingStyle.fill.index,
397+
id: 0,
398+
shaderId: null,
399+
);
400+
401+
listener.onPaintBlur(0, 5.0, double.nan);
402+
403+
listener.onPathStart(0, 0);
404+
listener.onPathMoveTo(0, 0);
405+
listener.onPathLineTo(10, 10);
406+
listener.onPathFinished();
407+
408+
await listener.onDrawPath(0, 0, null);
409+
410+
final Invocation drawPath = factory.fakeCanvases.single.invocations.single;
411+
expect(drawPath.isMethod, true);
412+
expect(drawPath.memberName, #drawPath);
413+
final paint = drawPath.positionalArguments[1] as ui.Paint;
414+
expect(paint.imageFilter, isNotNull);
415+
expect(paint.imageFilter, ui.ImageFilter.blur(sigmaX: 5.0));
416+
});
417+
418+
test('onPaintBlur with both NaN standard deviations does not set imageFilter', () async {
419+
final factory = TestPictureFactory();
420+
final listener = FlutterVectorGraphicsListener(pictureFactory: factory);
421+
422+
listener.onPaintObject(
423+
color: const ui.Color(0xff000000).toARGB32(),
424+
strokeCap: null,
425+
strokeJoin: null,
426+
blendMode: BlendMode.srcIn.index,
427+
strokeMiterLimit: null,
428+
strokeWidth: null,
429+
paintStyle: ui.PaintingStyle.fill.index,
430+
id: 0,
431+
shaderId: null,
432+
);
433+
434+
listener.onPaintBlur(0, double.nan, double.nan);
435+
436+
listener.onPathStart(0, 0);
437+
listener.onPathMoveTo(0, 0);
438+
listener.onPathLineTo(10, 10);
439+
listener.onPathFinished();
440+
441+
await listener.onDrawPath(0, 0, null);
442+
443+
final Invocation drawPath = factory.fakeCanvases.single.invocations.single;
444+
expect(drawPath.isMethod, true);
445+
expect(drawPath.memberName, #drawPath);
446+
final paint = drawPath.positionalArguments[1] as ui.Paint;
447+
expect(paint.imageFilter, isNull);
448+
});
219449
}
220450

221451
class TestPictureFactory implements PictureFactory {

‎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.6
2+
3+
* Adds support for SVG filters (`feGaussianBlur`, `feOffset`, `feMerge`, and `feMergeNode`).
4+
15
## 1.3.5
26

37
* Resolves the Flutter artifact cache using `package:cli_util` when running as a

‎packages/vector_graphics_compiler/lib/src/geometry/matrix.dart‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -43,16 +43,19 @@ class AffineMatrix {
4343
/// Translations can affect this value, so we have to track it.
4444
final double _m4_10;
4545

46+
/// The scale factor along the X axis, including rotation.
47+
double get xScale => math.sqrt(a * a + c * c);
48+
49+
/// The scale factor along the Y axis, including rotation.
50+
double get yScale => math.sqrt(b * b + d * d);
51+
4652
/// Calculates the scale for a stroke width based on the average of the x- and
4753
/// y-axis scales of this matrix.
4854
double? scaleStrokeWidth(double? width) {
4955
if (width == null || (a == 1 && d == 1)) {
5056
return width;
5157
}
5258

53-
final double xScale = math.sqrt(a * a + c * c);
54-
final double yScale = math.sqrt(b * b + d * d);
55-
5659
return (xScale + yScale) / 2 * width;
5760
}
5861

‎packages/vector_graphics_compiler/lib/src/paint.dart‎

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -397,7 +397,7 @@ class Paint {
397397
/// Creates a new collection of painting attributes.
398398
///
399399
/// See [Paint].
400-
const Paint({BlendMode? blendMode, this.stroke, this.fill})
400+
const Paint({BlendMode? blendMode, this.stroke, this.fill, this.filterBlurX, this.filterBlurY})
401401
: blendMode = blendMode ?? BlendMode.srcOver;
402402

403403
/// The Porter-Duff algorithm to use when compositing this painting object
@@ -418,15 +418,23 @@ class Paint {
418418
/// followed by stroke.
419419
final Fill? fill;
420420

421+
/// The Gaussian blur sigma X to apply to this paint, if any.
422+
final double? filterBlurX;
423+
424+
/// The Gaussian blur sigma Y to apply to this paint, if any.
425+
final double? filterBlurY;
426+
421427
@override
422-
int get hashCode => Object.hash(blendMode, stroke, fill);
428+
int get hashCode => Object.hash(blendMode, stroke, fill, filterBlurX, filterBlurY);
423429

424430
@override
425431
bool operator ==(Object other) {
426432
return other is Paint &&
427433
other.blendMode == blendMode &&
428434
other.stroke == stroke &&
429-
other.fill == fill;
435+
other.fill == fill &&
436+
other.filterBlurX == filterBlurX &&
437+
other.filterBlurY == filterBlurY;
430438
}
431439

432440
/// Apply the bounds to the given paint.
@@ -443,6 +451,8 @@ class Paint {
443451
blendMode: blendMode,
444452
stroke: stroke,
445453
fill: Fill(color: fill!.color, shader: newShader),
454+
filterBlurX: filterBlurX,
455+
filterBlurY: filterBlurY,
446456
);
447457
}
448458

@@ -456,6 +466,12 @@ class Paint {
456466
if (fill != null) {
457467
buffer.write('${leading}fill: $fill');
458468
}
469+
if (filterBlurX != null) {
470+
buffer.write('${leading}filterBlurX: $filterBlurX');
471+
}
472+
if (filterBlurY != null) {
473+
buffer.write('${leading}filterBlurY: $filterBlurY');
474+
}
459475
buffer.write(')');
460476
return buffer.toString();
461477
}

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

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -104,7 +104,12 @@ class Tessellator extends Visitor<Node, void>
104104
final IndexedVertices indexedVertices = vertices.createIndex();
105105
children.add(
106106
ResolvedVerticesNode(
107-
paint: Paint(blendMode: pathNode.paint.blendMode, fill: fill),
107+
paint: Paint(
108+
blendMode: pathNode.paint.blendMode,
109+
fill: fill,
110+
filterBlurX: pathNode.paint.filterBlurX,
111+
filterBlurY: pathNode.paint.filterBlurY,
112+
),
108113
vertices: indexedVertices,
109114
bounds: pathNode.bounds,
110115
),
@@ -114,7 +119,12 @@ class Tessellator extends Visitor<Node, void>
114119
if (stroke != null) {
115120
children.add(
116121
ResolvedPathNode(
117-
paint: Paint(blendMode: pathNode.paint.blendMode, stroke: stroke),
122+
paint: Paint(
123+
blendMode: pathNode.paint.blendMode,
124+
stroke: stroke,
125+
filterBlurX: pathNode.paint.filterBlurX,
126+
filterBlurY: pathNode.paint.filterBlurY,
127+
),
118128
bounds: pathNode.bounds,
119129
path: pathNode.path,
120130
),

0 commit comments

Comments
 (0)