bench_text_layout.dart 12.8 KB
Newer Older
1 2 3 4
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5
import 'dart:math';
6
import 'dart:ui' as ui;
7

8
import 'package:flutter/material.dart';
9

10 11
import 'recorder.dart';

12 13 14 15
const String chars = '1234567890'
    'abcdefghijklmnopqrstuvwxyz'
    'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
    '!@#%^&()[]{}<>,./?;:"`~-_=+|';
16

17 18 19 20 21 22 23 24 25 26 27 28 29
String _randomize(String text) {
  return text.replaceAllMapped(
    '*',
    // Passing a seed so the results are reproducible.
    (_) => chars[Random(0).nextInt(chars.length)],
  );
}

class ParagraphGenerator {
  int _counter = 0;

  /// Randomizes the given [text] and creates a paragraph with a unique
  /// font-size so that the engine doesn't reuse a cached ruler.
30
  ui.Paragraph generate(
31
    String text, {
32
    int? maxLines,
33 34
    bool hasEllipsis = false,
  }) {
35
    final ui.ParagraphBuilder builder = ui.ParagraphBuilder(ui.ParagraphStyle(
36 37 38 39 40
      fontFamily: 'sans-serif',
      maxLines: maxLines,
      ellipsis: hasEllipsis ? '...' : null,
    ))
      // Start from a font-size of 8.0 and go up by 0.01 each time.
41
      ..pushStyle(ui.TextStyle(fontSize: 8.0 + _counter * 0.01))
42 43 44 45 46 47
      ..addText(_randomize(text));
    _counter++;
    return builder.build();
  }
}

48 49 50 51 52 53 54 55 56 57
/// Which mode to run [BenchBuildColorsGrid] in.
enum _TestMode {
  /// Uses the HTML rendering backend with the canvas 2D text layout.
  useCanvasTextLayout,

  /// Uses CanvasKit for everything.
  useCanvasKit,
}

/// Repeatedly lays out a paragraph.
58 59
///
/// Creates a different paragraph each time in order to avoid hitting the cache.
60
class BenchTextLayout extends RawRecorder {
61
  BenchTextLayout.canvas()
62
      : super(name: canvasBenchmarkName);
63 64

  BenchTextLayout.canvasKit()
65
      : super(name: canvasKitBenchmarkName);
66 67

  static const String canvasBenchmarkName = 'text_canvas_layout';
68
  static const String canvasKitBenchmarkName = 'text_canvaskit_layout';
69

70 71 72 73 74 75 76
  final ParagraphGenerator generator = ParagraphGenerator();

  static const String singleLineText = '*** ** ****';
  static const String multiLineText = '*** ****** **** *** ******** * *** '
      '******* **** ********** *** ******* '
      '**** ***** *** ******** *** ********* '
      '** * *** ******* ***********';
77 78 79

  @override
  void body(Profile profile) {
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
    recordParagraphOperations(
      profile: profile,
      paragraph: generator.generate(singleLineText),
      text: singleLineText,
      keyPrefix: 'single_line',
      maxWidth: 800.0,
    );

    recordParagraphOperations(
      profile: profile,
      paragraph: generator.generate(multiLineText),
      text: multiLineText,
      keyPrefix: 'multi_line',
      maxWidth: 200.0,
    );

    recordParagraphOperations(
      profile: profile,
      paragraph: generator.generate(multiLineText, maxLines: 2),
      text: multiLineText,
      keyPrefix: 'max_lines',
      maxWidth: 200.0,
    );

    recordParagraphOperations(
      profile: profile,
      paragraph: generator.generate(multiLineText, hasEllipsis: true),
      text: multiLineText,
      keyPrefix: 'ellipsis',
      maxWidth: 200.0,
    );
  }

  void recordParagraphOperations({
114 115 116 117 118
    required Profile profile,
    required ui.Paragraph paragraph,
    required String text,
    required String keyPrefix,
    required double maxWidth,
119 120
  }) {
    profile.record('$keyPrefix.layout', () {
121
      paragraph.layout(ui.ParagraphConstraints(width: maxWidth));
122
    }, reported: true);
123 124 125 126 127 128
    profile.record('$keyPrefix.getBoxesForRange', () {
      for (int start = 0; start < text.length; start += 3) {
        for (int end = start + 1; end < text.length; end *= 2) {
          paragraph.getBoxesForRange(start, end);
        }
      }
129
    }, reported: true);
130 131 132 133 134 135
    profile.record('$keyPrefix.getPositionForOffset', () {
      for (double dx = 0.0; dx < paragraph.width; dx += 10.0) {
        for (double dy = 0.0; dy < paragraph.height; dy += 10.0) {
          paragraph.getPositionForOffset(Offset(dx, dy));
        }
      }
136
    }, reported: true);
137 138 139
  }
}

140
/// Repeatedly lays out the same paragraph.
141 142 143 144
///
/// Uses the same paragraph content to make sure we hit the cache. It doesn't
/// use the same paragraph instance because the layout method will shortcircuit
/// in that case.
145
class BenchTextCachedLayout extends RawRecorder {
146
  BenchTextCachedLayout.canvas()
147
      : super(name: canvasBenchmarkName);
148 149

  BenchTextCachedLayout.canvasKit()
150
      : super(name: canvasKitBenchmarkName);
151 152

  static const String canvasBenchmarkName = 'text_canvas_cached_layout';
153
  static const String canvasKitBenchmarkName = 'text_canvas_kit_cached_layout';
154

155 156 157
  @override
  void body(Profile profile) {
    final ui.ParagraphBuilder builder = ui.ParagraphBuilder(ui.ParagraphStyle(fontFamily: 'sans-serif'))
158
        ..pushStyle(ui.TextStyle(fontSize: 12.0))
159 160 161 162
        ..addText(
          'Lorem ipsum dolor sit amet, consectetur adipiscing elit, '
          'sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.',
        );
163
    final ui.Paragraph paragraph = builder.build();
164
    profile.record('layout', () {
165
      paragraph.layout(const ui.ParagraphConstraints(width: double.infinity));
166
    }, reported: true);
167 168 169 170 171 172 173 174 175 176
  }
}

/// Global counter incremented every time the benchmark is asked to
/// [createWidget].
///
/// The purpose of this counter is to make sure the rendered paragraphs on each
/// build are unique.
int _counter = 0;

177
/// Measures how expensive it is to construct a realistic text-heavy piece of UI.
178
///
179 180
/// The benchmark constructs a tabbed view, where each tab displays a list of
/// colors. Each color's description is made of several [Text] nodes.
181
class BenchBuildColorsGrid extends WidgetBuildRecorder {
182
  BenchBuildColorsGrid.canvas()
183
      : _mode = _TestMode.useCanvasTextLayout, super(name: canvasBenchmarkName);
184

185
  BenchBuildColorsGrid.canvasKit()
186
      : _mode = _TestMode.useCanvasKit, super(name: canvasKitBenchmarkName);
187

188 189 190 191 192 193 194 195
  /// Disables tracing for this benchmark.
  ///
  /// When tracing is enabled, DOM layout takes longer to complete. This has a
  /// significant effect on the benchmark since we do a lot of text layout
  /// operations that trigger synchronous DOM layout.
  @override
  bool get isTracingEnabled => false;

196
  static const String canvasBenchmarkName = 'text_canvas_color_grid';
197
  static const String canvasKitBenchmarkName = 'text_canvas_kit_color_grid';
198 199

  /// Whether to use the new canvas-based text measurement implementation.
200
  final _TestMode _mode;
201 202 203 204

  num _textLayoutMicros = 0;

  @override
205
  Future<void> setUpAll() async {
206
    registerEngineBenchmarkValueListener('text_layout', (num value) {
207
      _textLayoutMicros += value;
208
    });
209 210 211
  }

  @override
212
  Future<void> tearDownAll() async {
213
    stopListeningToEngineBenchmarkValues('text_layout');
214 215 216 217 218 219 220 221 222 223 224 225
  }

  @override
  void frameWillDraw() {
    super.frameWillDraw();
    _textLayoutMicros = 0;
  }

  @override
  void frameDidDraw() {
    // We need to do this before calling [super.frameDidDraw] because the latter
    // updates the value of [showWidget] in preparation for the next frame.
226
    // TODO(yjbanov): https://github.com/flutter/flutter/issues/53877
227
    if (showWidget && _mode != _TestMode.useCanvasKit) {
228
      profile!.addDataPoint(
229 230
        'text_layout',
        Duration(microseconds: _textLayoutMicros.toInt()),
231
        reported: true,
232 233 234 235 236 237 238 239
      );
    }
    super.frameDidDraw();
  }

  @override
  Widget createWidget() {
    _counter++;
240
    return const MaterialApp(home: ColorsDemo());
241 242 243 244 245 246 247 248 249
  }
}

// The code below was copied from `colors_demo.dart` in the `flutter_gallery`
// example.

const double kColorItemHeight = 48.0;

class Palette {
250
  Palette({required this.name, required this.primary, this.accent, this.threshold = 900});
251 252 253

  final String name;
  final MaterialColor primary;
254
  final MaterialAccentColor? accent;
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
  final int
      threshold; // titles for indices > threshold are white, otherwise black
}

final List<Palette> allPalettes = <Palette>[
  Palette(
      name: 'RED',
      primary: Colors.red,
      accent: Colors.redAccent,
      threshold: 300),
  Palette(
      name: 'PINK',
      primary: Colors.pink,
      accent: Colors.pinkAccent,
      threshold: 200),
  Palette(
      name: 'PURPLE',
      primary: Colors.purple,
      accent: Colors.purpleAccent,
      threshold: 200),
  Palette(
      name: 'DEEP PURPLE',
      primary: Colors.deepPurple,
      accent: Colors.deepPurpleAccent,
      threshold: 200),
  Palette(
      name: 'INDIGO',
      primary: Colors.indigo,
      accent: Colors.indigoAccent,
      threshold: 200),
  Palette(
      name: 'BLUE',
      primary: Colors.blue,
      accent: Colors.blueAccent,
      threshold: 400),
  Palette(
      name: 'LIGHT BLUE',
      primary: Colors.lightBlue,
      accent: Colors.lightBlueAccent,
      threshold: 500),
  Palette(
      name: 'CYAN',
      primary: Colors.cyan,
      accent: Colors.cyanAccent,
      threshold: 600),
  Palette(
      name: 'TEAL',
      primary: Colors.teal,
      accent: Colors.tealAccent,
      threshold: 400),
  Palette(
      name: 'GREEN',
      primary: Colors.green,
      accent: Colors.greenAccent,
      threshold: 500),
  Palette(
      name: 'LIGHT GREEN',
      primary: Colors.lightGreen,
      accent: Colors.lightGreenAccent,
      threshold: 600),
  Palette(
      name: 'LIME',
      primary: Colors.lime,
      accent: Colors.limeAccent,
      threshold: 800),
  Palette(name: 'YELLOW', primary: Colors.yellow, accent: Colors.yellowAccent),
  Palette(name: 'AMBER', primary: Colors.amber, accent: Colors.amberAccent),
  Palette(
      name: 'ORANGE',
      primary: Colors.orange,
      accent: Colors.orangeAccent,
      threshold: 700),
  Palette(
      name: 'DEEP ORANGE',
      primary: Colors.deepOrange,
      accent: Colors.deepOrangeAccent,
      threshold: 400),
  Palette(name: 'BROWN', primary: Colors.brown, threshold: 200),
  Palette(name: 'GREY', primary: Colors.grey, threshold: 500),
  Palette(name: 'BLUE GREY', primary: Colors.blueGrey, threshold: 500),
];

class ColorItem extends StatelessWidget {
  const ColorItem({
339
    super.key,
340 341
    required this.index,
    required this.color,
342
    this.prefix = '',
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

  final int index;
  final Color color;
  final String prefix;

  String colorString() =>
      "$_counter:#${color.value.toRadixString(16).padLeft(8, '0').toUpperCase()}";

  @override
  Widget build(BuildContext context) {
    return Semantics(
      container: true,
      child: Container(
        height: kColorItemHeight,
        padding: const EdgeInsets.symmetric(horizontal: 16.0),
        color: color,
        child: SafeArea(
          top: false,
          bottom: false,
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              Text('$_counter:$prefix$index'),
              Text(colorString()),
            ],
          ),
        ),
      ),
    );
  }
}

class PaletteTabView extends StatelessWidget {
377
  const PaletteTabView({
378
    super.key,
379
    required this.colors,
380
  });
381 382 383 384 385 386 387 388 389 390 391 392 393

  final Palette colors;

  static const List<int> primaryKeys = <int>[
    50,
    100,
    200,
    300,
    400,
    500,
    600,
    700,
    800,
394
    900,
395 396 397 398 399 400 401
  ];
  static const List<int> accentKeys = <int>[100, 200, 400, 700];

  @override
  Widget build(BuildContext context) {
    final TextTheme textTheme = Theme.of(context).textTheme;
    final TextStyle whiteTextStyle =
402
        textTheme.bodyMedium!.copyWith(color: Colors.white);
403
    final TextStyle blackTextStyle =
404
        textTheme.bodyMedium!.copyWith(color: Colors.black);
405 406 407 408 409 410 411
    return Scrollbar(
      child: ListView(
        itemExtent: kColorItemHeight,
        children: <Widget>[
          ...primaryKeys.map<Widget>((int index) {
            return DefaultTextStyle(
              style: index > colors.threshold ? whiteTextStyle : blackTextStyle,
412
              child: ColorItem(index: index, color: colors.primary[index]!),
413 414 415 416 417 418 419 420
            );
          }),
          if (colors.accent != null)
            ...accentKeys.map<Widget>((int index) {
              return DefaultTextStyle(
                style:
                    index > colors.threshold ? whiteTextStyle : blackTextStyle,
                child: ColorItem(
421
                    index: index, color: colors.accent![index]!, prefix: 'A'),
422 423 424 425 426 427 428 429 430
              );
            }),
        ],
      ),
    );
  }
}

class ColorsDemo extends StatelessWidget {
431
  const ColorsDemo({super.key});
432

433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455
  @override
  Widget build(BuildContext context) {
    return DefaultTabController(
      length: allPalettes.length,
      child: Scaffold(
        appBar: AppBar(
          elevation: 0.0,
          title: const Text('Colors'),
          bottom: TabBar(
            isScrollable: true,
            tabs: allPalettes
                .map<Widget>(
                    (Palette swatch) => Tab(text: '$_counter:${swatch.name}'))
                .toList(),
          ),
        ),
        body: TabBarView(
          children: allPalettes.map<Widget>((Palette colors) {
            return PaletteTabView(colors: colors);
          }).toList(),
        ),
      ),
    );
456 457
  }
}