From 3a51eb12d3f2208778e1214386606b225be985a9 Mon Sep 17 00:00:00 2001 From: Jason Simmons Date: Thu, 24 Jun 2021 12:31:05 -0700 Subject: [PATCH] Substitute a replacement character for invalid UTF-16 text in a TextSpan (#84887) --- .../flutter/lib/src/painting/text_span.dart | 16 ++++++++++++++-- .../test/painting/text_painter_test.dart | 19 +++++++++++++++++++ 2 files changed, 33 insertions(+), 2 deletions(-) diff --git a/packages/flutter/lib/src/painting/text_span.dart b/packages/flutter/lib/src/painting/text_span.dart index bada320117..cd6d43a1a4 100644 --- a/packages/flutter/lib/src/painting/text_span.dart +++ b/packages/flutter/lib/src/painting/text_span.dart @@ -244,8 +244,20 @@ class TextSpan extends InlineSpan implements HitTestTarget, MouseTrackerAnnotati final bool hasStyle = style != null; if (hasStyle) builder.pushStyle(style!.getTextStyle(textScaleFactor: textScaleFactor)); - if (text != null) - builder.addText(text!); + if (text != null) { + try { + builder.addText(text!); + } on ArgumentError catch (exception, stack) { + FlutterError.reportError(FlutterErrorDetails( + exception: exception, + stack: stack, + library: 'painting library', + context: ErrorDescription('while building a TextSpan'), + )); + // Use a Unicode replacement character as a substitute for invalid text. + builder.addText('\uFFFD'); + } + } if (children != null) { for (final InlineSpan child in children!) { assert(child != null); diff --git a/packages/flutter/test/painting/text_painter_test.dart b/packages/flutter/test/painting/text_painter_test.dart index be70a4f93f..4a16b7122d 100644 --- a/packages/flutter/test/painting/text_painter_test.dart +++ b/packages/flutter/test/painting/text_painter_test.dart @@ -4,6 +4,7 @@ import 'dart:ui' as ui; +import 'package:flutter/foundation.dart'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; @@ -952,6 +953,24 @@ void main() { expect(glyphBox, newGlyphBox); }); }, skip: isBrowser); + + test('TextPainter handles invalid UTF-16', () { + Object? exception; + FlutterError.onError = (FlutterErrorDetails details) { + exception = details.exception; + }; + + final TextPainter painter = TextPainter() + ..textDirection = TextDirection.ltr; + + const String text = 'Hello\uD83DWorld'; + const double fontSize = 20.0; + painter.text = const TextSpan(text: text, style: TextStyle(fontSize: fontSize)); + painter.layout(); + // The layout should include one replacement character. + expect(painter.width, equals(fontSize)); + expect(exception, isNotNull); + }, skip: kIsWeb); } class MockCanvas extends Fake implements Canvas {