custom_paint.dart 39.9 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:collection';

import 'package:flutter/foundation.dart';
import 'package:flutter/semantics.dart';

import 'box.dart';
import 'object.dart';
import 'proxy_box.dart';

/// Signature of the function returned by [CustomPainter.semanticsBuilder].
///
/// Builds semantics information describing the picture drawn by a
/// [CustomPainter]. Each [CustomPainterSemantics] in the returned list is
/// converted into a [SemanticsNode] by copying its properties.
///
/// The returned list must not be mutated after this function completes. To
/// change the semantic information, the function must return a new list
/// instead.
23
typedef SemanticsBuilderCallback = List<CustomPainterSemantics> Function(Size size);
24 25 26 27 28

/// The interface used by [CustomPaint] (in the widgets library) and
/// [RenderCustomPaint] (in the rendering library).
///
/// To implement a custom painter, either subclass or implement this interface
29
/// to define your custom paint delegate. [CustomPainter] subclasses must
30 31 32 33 34 35 36 37 38 39
/// implement the [paint] and [shouldRepaint] methods, and may optionally also
/// implement the [hitTest] and [shouldRebuildSemantics] methods, and the
/// [semanticsBuilder] getter.
///
/// The [paint] method is called whenever the custom object needs to be repainted.
///
/// The [shouldRepaint] method is called when a new instance of the class
/// is provided, to check if the new instance actually represents different
/// information.
///
40 41
/// {@youtube 560 315 https://www.youtube.com/watch?v=vvI_NUXK00s}
///
42 43 44 45 46 47 48 49 50 51
/// The most efficient way to trigger a repaint is to either:
///
/// * Extend this class and supply a `repaint` argument to the constructor of
///   the [CustomPainter], where that object notifies its listeners when it is
///   time to repaint.
/// * Extend [Listenable] (e.g. via [ChangeNotifier]) and implement
///   [CustomPainter], so that the object itself provides the notifications
///   directly.
///
/// In either case, the [CustomPaint] widget or [RenderCustomPaint]
52 53 54 55 56 57 58 59 60 61 62 63 64
/// render object will listen to the [Listenable] and repaint whenever the
/// animation ticks, avoiding both the build and layout phases of the pipeline.
///
/// The [hitTest] method is called when the user interacts with the underlying
/// render object, to determine if the user hit the object or missed it.
///
/// The [semanticsBuilder] is called whenever the custom object needs to rebuild
/// its semantics information.
///
/// The [shouldRebuildSemantics] method is called when a new instance of the
/// class is provided, to check if the new instance contains different
/// information that affects the semantics tree.
///
65
/// {@tool snippet}
66 67 68 69 70 71 72 73
///
/// This sample extends the same code shown for [RadialGradient] to create a
/// custom painter that paints a sky.
///
/// ```dart
/// class Sky extends CustomPainter {
///   @override
///   void paint(Canvas canvas, Size size) {
74 75 76
///     final Rect rect = Offset.zero & size;
///     const RadialGradient gradient = RadialGradient(
///       center: Alignment(0.7, -0.6),
77
///       radius: 0.2,
78 79
///       colors: <Color>[Color(0xFFFFFF00), Color(0xFF0099FF)],
///       stops: <double>[0.4, 1.0],
80 81 82
///     );
///     canvas.drawRect(
///       rect,
83
///       Paint()..shader = gradient.createShader(rect),
84 85 86 87 88 89 90 91 92 93
///     );
///   }
///
///   @override
///   SemanticsBuilderCallback get semanticsBuilder {
///     return (Size size) {
///       // Annotate a rectangle containing the picture of the sun
///       // with the label "Sun". When text to speech feature is enabled on the
///       // device, a user will be able to locate the sun on this picture by
///       // touch.
94 95
///       Rect rect = Offset.zero & size;
///       final double width = size.shortestSide * 0.4;
96
///       rect = const Alignment(0.8, -0.9).inscribe(Size(width, width), rect);
97
///       return <CustomPainterSemantics>[
98
///         CustomPainterSemantics(
99
///           rect: rect,
100
///           properties: const SemanticsProperties(
101 102 103 104 105 106 107 108 109 110 111 112 113
///             label: 'Sun',
///             textDirection: TextDirection.ltr,
///           ),
///         ),
///       ];
///     };
///   }
///
///   // Since this Sky painter has no fields, it always paints
///   // the same thing and semantics information is the same.
///   // Therefore we return false here. If we had fields (set
///   // from the constructor) then we would return true if any
///   // of them differed from the same fields on the oldDelegate.
114
///   @override
115
///   bool shouldRepaint(Sky oldDelegate) => false;
116
///   @override
117 118 119
///   bool shouldRebuildSemantics(Sky oldDelegate) => false;
/// }
/// ```
120
/// {@end-tool}
121 122 123 124 125 126 127 128 129 130 131 132
///
/// See also:
///
///  * [Canvas], the class that a custom painter uses to paint.
///  * [CustomPaint], the widget that uses [CustomPainter], and whose sample
///    code shows how to use the above `Sky` class.
///  * [RadialGradient], whose sample code section shows a different take
///    on the sample code above.
abstract class CustomPainter extends Listenable {
  /// Creates a custom painter.
  ///
  /// The painter will repaint whenever `repaint` notifies its listeners.
133
  const CustomPainter({ Listenable? repaint }) : _repaint = repaint;
134

135
  final Listenable? _repaint;
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157

  /// Register a closure to be notified when it is time to repaint.
  ///
  /// The [CustomPainter] implementation merely forwards to the same method on
  /// the [Listenable] provided to the constructor in the `repaint` argument, if
  /// it was not null.
  @override
  void addListener(VoidCallback listener) => _repaint?.addListener(listener);

  /// Remove a previously registered closure from the list of closures that the
  /// object notifies when it is time to repaint.
  ///
  /// The [CustomPainter] implementation merely forwards to the same method on
  /// the [Listenable] provided to the constructor in the `repaint` argument, if
  /// it was not null.
  @override
  void removeListener(VoidCallback listener) => _repaint?.removeListener(listener);

  /// Called whenever the object needs to paint. The given [Canvas] has its
  /// coordinate space configured such that the origin is at the top left of the
  /// box. The area of the box is the size of the [size] argument.
  ///
158 159 160 161 162 163 164
  /// Paint operations should remain inside the given area. Graphical
  /// operations outside the bounds may be silently ignored, clipped, or not
  /// clipped. It may sometimes be difficult to guarantee that a certain
  /// operation is inside the bounds (e.g., drawing a rectangle whose size is
  /// determined by user inputs). In that case, consider calling
  /// [Canvas.clipRect] at the beginning of [paint] so everything that follows
  /// will be guaranteed to only draw within the clipped area.
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
  ///
  /// Implementations should be wary of correctly pairing any calls to
  /// [Canvas.save]/[Canvas.saveLayer] and [Canvas.restore], otherwise all
  /// subsequent painting on this canvas may be affected, with potentially
  /// hilarious but confusing results.
  ///
  /// To paint text on a [Canvas], use a [TextPainter].
  ///
  /// To paint an image on a [Canvas]:
  ///
  /// 1. Obtain an [ImageStream], for example by calling [ImageProvider.resolve]
  ///    on an [AssetImage] or [NetworkImage] object.
  ///
  /// 2. Whenever the [ImageStream]'s underlying [ImageInfo] object changes
  ///    (see [ImageStream.addListener]), create a new instance of your custom
  ///    paint delegate, giving it the new [ImageInfo] object.
  ///
  /// 3. In your delegate's [paint] method, call the [Canvas.drawImage],
  ///    [Canvas.drawImageRect], or [Canvas.drawImageNine] methods to paint the
  ///    [ImageInfo.image] object, applying the [ImageInfo.scale] value to
  ///    obtain the correct rendering size.
  void paint(Canvas canvas, Size size);

  /// Returns a function that builds semantic information for the picture drawn
  /// by this painter.
  ///
  /// If the returned function is null, this painter will not contribute new
  /// [SemanticsNode]s to the semantics tree and the [CustomPaint] corresponding
193 194 195
  /// to this painter will not create a semantics boundary. However, if the
  /// child of a [CustomPaint] is not null, the child may contribute
  /// [SemanticsNode]s to the tree.
196 197 198
  ///
  /// See also:
  ///
199 200 201
  ///  * [SemanticsConfiguration.isSemanticBoundary], which causes new
  ///    [SemanticsNode]s to be added to the semantics tree.
  ///  * [RenderCustomPaint], which uses this getter to build semantics.
202
  SemanticsBuilderCallback? get semanticsBuilder => null;
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

  /// Called whenever a new instance of the custom painter delegate class is
  /// provided to the [RenderCustomPaint] object, or any time that a new
  /// [CustomPaint] object is created with a new instance of the custom painter
  /// delegate class (which amounts to the same thing, because the latter is
  /// implemented in terms of the former).
  ///
  /// If the new instance would cause [semanticsBuilder] to create different
  /// semantics information, then this method should return true, otherwise it
  /// should return false.
  ///
  /// If the method returns false, then the [semanticsBuilder] call might be
  /// optimized away.
  ///
  /// It's possible that the [semanticsBuilder] will get called even if
  /// [shouldRebuildSemantics] would return false. For example, it is called
  /// when the [CustomPaint] is rendered for the very first time, or when the
  /// box changes its size.
  ///
  /// By default this method delegates to [shouldRepaint] under the assumption
  /// that in most cases semantics change when something new is drawn.
  bool shouldRebuildSemantics(covariant CustomPainter oldDelegate) => shouldRepaint(oldDelegate);

  /// Called whenever a new instance of the custom painter delegate class is
  /// provided to the [RenderCustomPaint] object, or any time that a new
  /// [CustomPaint] object is created with a new instance of the custom painter
  /// delegate class (which amounts to the same thing, because the latter is
  /// implemented in terms of the former).
  ///
  /// If the new instance represents different information than the old
  /// instance, then the method should return true, otherwise it should return
  /// false.
  ///
  /// If the method returns false, then the [paint] call might be optimized
  /// away.
  ///
  /// It's possible that the [paint] method will get called even if
  /// [shouldRepaint] returns false (e.g. if an ancestor or descendant needed to
  /// be repainted). It's also possible that the [paint] method will get called
  /// without [shouldRepaint] being called at all (e.g. if the box changes
  /// size).
  ///
  /// If a custom delegate has a particularly expensive paint function such that
  /// repaints should be avoided as much as possible, a [RepaintBoundary] or
  /// [RenderRepaintBoundary] (or other render object with
  /// [RenderObject.isRepaintBoundary] set to true) might be helpful.
249 250
  ///
  /// The `oldDelegate` argument will never be null.
251 252 253 254 255 256 257 258 259 260 261 262 263 264 265
  bool shouldRepaint(covariant CustomPainter oldDelegate);

  /// Called whenever a hit test is being performed on an object that is using
  /// this custom paint delegate.
  ///
  /// The given point is relative to the same coordinate space as the last
  /// [paint] call.
  ///
  /// The default behavior is to consider all points to be hits for
  /// background painters, and no points to be hits for foreground painters.
  ///
  /// Return true if the given position corresponds to a point on the drawn
  /// image that should be considered a "hit", false if it corresponds to a
  /// point that should be considered outside the painted image, and null to use
  /// the default behavior.
266
  bool? hitTest(Offset position) => null;
267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283

  @override
  String toString() => '${describeIdentity(this)}(${ _repaint?.toString() ?? "" })';
}

/// Contains properties describing information drawn in a rectangle contained by
/// the [Canvas] used by a [CustomPaint].
///
/// This information is used, for example, by assistive technologies to improve
/// the accessibility of applications.
///
/// Implement [CustomPainter.semanticsBuilder] to build the semantic
/// description of the whole picture drawn by a [CustomPaint], rather that one
/// particular rectangle.
///
/// See also:
///
284 285
///  * [SemanticsNode], which is created using the properties of this class.
///  * [CustomPainter], which creates instances of this class.
286 287 288 289 290 291 292
@immutable
class CustomPainterSemantics {
  /// Creates semantics information describing a rectangle on a canvas.
  ///
  /// Arguments `rect` and `properties` must not be null.
  const CustomPainterSemantics({
    this.key,
293 294
    required this.rect,
    required this.properties,
295 296 297 298 299 300 301 302 303 304 305 306 307 308 309
    this.transform,
    this.tags,
  }) : assert(rect != null),
       assert(properties != null);

  /// Identifies this object in a list of siblings.
  ///
  /// [SemanticsNode] inherits this key, so that when the list of nodes is
  /// updated, its nodes are updated from [CustomPainterSemantics] with matching
  /// keys.
  ///
  /// If this is null, the update algorithm does not guarantee which
  /// [SemanticsNode] will be updated using this instance.
  ///
  /// This value is assigned to [SemanticsNode.key] during update.
310
  final Key? key;
311 312 313 314 315 316 317 318 319 320 321

  /// The location and size of the box on the canvas where this piece of semantic
  /// information applies.
  ///
  /// This value is assigned to [SemanticsNode.rect] during update.
  final Rect rect;

  /// The transform from the canvas' coordinate system to its parent's
  /// coordinate system.
  ///
  /// This value is assigned to [SemanticsNode.transform] during update.
322
  final Matrix4? transform;
323 324 325 326 327 328

  /// Contains properties that are assigned to the [SemanticsNode] created or
  /// updated from this object.
  ///
  /// See also:
  ///
329 330
  ///  * [Semantics], which is a widget that also uses [SemanticsProperties] to
  ///    annotate.
331 332 333 334 335 336
  final SemanticsProperties properties;

  /// Tags used by the parent [SemanticsNode] to determine the layout of the
  /// semantics tree.
  ///
  /// This value is assigned to [SemanticsNode.tags] during update.
337
  final Set<SemanticsTag>? tags;
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
}

/// Provides a canvas on which to draw during the paint phase.
///
/// When asked to paint, [RenderCustomPaint] first asks its [painter] to paint
/// on the current canvas, then it paints its child, and then, after painting
/// its child, it asks its [foregroundPainter] to paint. The coordinate system of
/// the canvas matches the coordinate system of the [CustomPaint] object. The
/// painters are expected to paint within a rectangle starting at the origin and
/// encompassing a region of the given size. (If the painters paint outside
/// those bounds, there might be insufficient memory allocated to rasterize the
/// painting commands and the resulting behavior is undefined.)
///
/// Painters are implemented by subclassing or implementing [CustomPainter].
///
/// Because custom paint calls its painters during paint, you cannot mark the
/// tree as needing a new layout during the callback (the layout for this frame
/// has already happened).
///
/// Custom painters normally size themselves to their child. If they do not have
/// a child, they attempt to size themselves to the [preferredSize], which
/// defaults to [Size.zero].
///
/// See also:
///
///  * [CustomPainter], the class that custom painter delegates should extend.
///  * [Canvas], the API provided to custom painter delegates.
class RenderCustomPaint extends RenderProxyBox {
  /// Creates a render object that delegates its painting.
  RenderCustomPaint({
368 369
    CustomPainter? painter,
    CustomPainter? foregroundPainter,
370 371 372
    Size preferredSize = Size.zero,
    this.isComplex = false,
    this.willChange = false,
373
    RenderBox? child,
374 375 376 377 378 379 380 381 382
  }) : assert(preferredSize != null),
       _painter = painter,
       _foregroundPainter = foregroundPainter,
       _preferredSize = preferredSize,
       super(child);

  /// The background custom paint delegate.
  ///
  /// This painter, if non-null, is called to paint behind the children.
383 384
  CustomPainter? get painter => _painter;
  CustomPainter? _painter;
385 386 387 388 389 390 391 392 393 394 395 396
  /// Set a new background custom paint delegate.
  ///
  /// If the new delegate is the same as the previous one, this does nothing.
  ///
  /// If the new delegate is the same class as the previous one, then the new
  /// delegate has its [CustomPainter.shouldRepaint] called; if the result is
  /// true, then the delegate will be called.
  ///
  /// If the new delegate is a different class than the previous one, then the
  /// delegate will be called.
  ///
  /// If the new value is null, then there is no background custom painter.
397
  set painter(CustomPainter? value) {
398
    if (_painter == value) {
399
      return;
400
    }
401
    final CustomPainter? oldPainter = _painter;
402 403 404 405 406 407 408
    _painter = value;
    _didUpdatePainter(_painter, oldPainter);
  }

  /// The foreground custom paint delegate.
  ///
  /// This painter, if non-null, is called to paint in front of the children.
409 410
  CustomPainter? get foregroundPainter => _foregroundPainter;
  CustomPainter? _foregroundPainter;
411 412 413 414 415 416 417 418 419 420 421 422
  /// Set a new foreground custom paint delegate.
  ///
  /// If the new delegate is the same as the previous one, this does nothing.
  ///
  /// If the new delegate is the same class as the previous one, then the new
  /// delegate has its [CustomPainter.shouldRepaint] called; if the result is
  /// true, then the delegate will be called.
  ///
  /// If the new delegate is a different class than the previous one, then the
  /// delegate will be called.
  ///
  /// If the new value is null, then there is no foreground custom painter.
423
  set foregroundPainter(CustomPainter? value) {
424
    if (_foregroundPainter == value) {
425
      return;
426
    }
427
    final CustomPainter? oldPainter = _foregroundPainter;
428 429 430 431
    _foregroundPainter = value;
    _didUpdatePainter(_foregroundPainter, oldPainter);
  }

432
  void _didUpdatePainter(CustomPainter? newPainter, CustomPainter? oldPainter) {
433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449
    // Check if we need to repaint.
    if (newPainter == null) {
      assert(oldPainter != null); // We should be called only for changes.
      markNeedsPaint();
    } else if (oldPainter == null ||
        newPainter.runtimeType != oldPainter.runtimeType ||
        newPainter.shouldRepaint(oldPainter)) {
      markNeedsPaint();
    }
    if (attached) {
      oldPainter?.removeListener(markNeedsPaint);
      newPainter?.addListener(markNeedsPaint);
    }

    // Check if we need to rebuild semantics.
    if (newPainter == null) {
      assert(oldPainter != null); // We should be called only for changes.
450
      if (attached) {
451
        markNeedsSemanticsUpdate();
452
      }
453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470
    } else if (oldPainter == null ||
        newPainter.runtimeType != oldPainter.runtimeType ||
        newPainter.shouldRebuildSemantics(oldPainter)) {
      markNeedsSemanticsUpdate();
    }
  }

  /// The size that this [RenderCustomPaint] should aim for, given the layout
  /// constraints, if there is no child.
  ///
  /// Defaults to [Size.zero].
  ///
  /// If there's a child, this is ignored, and the size of the child is used
  /// instead.
  Size get preferredSize => _preferredSize;
  Size _preferredSize;
  set preferredSize(Size value) {
    assert(value != null);
471
    if (preferredSize == value) {
472
      return;
473
    }
474 475 476 477 478 479 480 481
    _preferredSize = value;
    markNeedsLayout();
  }

  /// Whether to hint that this layer's painting should be cached.
  ///
  /// The compositor contains a raster cache that holds bitmaps of layers in
  /// order to avoid the cost of repeatedly rendering those layers on each
482
  /// frame. If this flag is not set, then the compositor will apply its own
483 484 485 486 487 488 489 490
  /// heuristics to decide whether the this layer is complex enough to benefit
  /// from caching.
  bool isComplex;

  /// Whether the raster cache should be told that this painting is likely
  /// to change in the next frame.
  bool willChange;

491 492
  @override
  double computeMinIntrinsicWidth(double height) {
493
    if (child == null) {
494
      return preferredSize.width.isFinite ? preferredSize.width : 0;
495
    }
496 497 498 499 500
    return super.computeMinIntrinsicWidth(height);
  }

  @override
  double computeMaxIntrinsicWidth(double height) {
501
    if (child == null) {
502
      return preferredSize.width.isFinite ? preferredSize.width : 0;
503
    }
504 505 506 507 508
    return super.computeMaxIntrinsicWidth(height);
  }

  @override
  double computeMinIntrinsicHeight(double width) {
509
    if (child == null) {
510
      return preferredSize.height.isFinite ? preferredSize.height : 0;
511
    }
512 513 514 515 516
    return super.computeMinIntrinsicHeight(width);
  }

  @override
  double computeMaxIntrinsicHeight(double width) {
517
    if (child == null) {
518
      return preferredSize.height.isFinite ? preferredSize.height : 0;
519
    }
520 521 522
    return super.computeMaxIntrinsicHeight(width);
  }

523 524 525 526 527 528 529 530 531 532 533 534 535 536 537
  @override
  void attach(PipelineOwner owner) {
    super.attach(owner);
    _painter?.addListener(markNeedsPaint);
    _foregroundPainter?.addListener(markNeedsPaint);
  }

  @override
  void detach() {
    _painter?.removeListener(markNeedsPaint);
    _foregroundPainter?.removeListener(markNeedsPaint);
    super.detach();
  }

  @override
538
  bool hitTestChildren(BoxHitTestResult result, { required Offset position }) {
539
    if (_foregroundPainter != null && (_foregroundPainter!.hitTest(position) ?? false)) {
540
      return true;
541
    }
542 543 544 545 546
    return super.hitTestChildren(result, position: position);
  }

  @override
  bool hitTestSelf(Offset position) {
547
    return _painter != null && (_painter!.hitTest(position) ?? true);
548 549 550
  }

  @override
551 552
  void performLayout() {
    super.performLayout();
553 554 555
    markNeedsSemanticsUpdate();
  }

556 557 558 559 560
  @override
  Size computeSizeForNoChild(BoxConstraints constraints) {
    return constraints.constrain(preferredSize);
  }

561 562
  void _paintWithPainter(Canvas canvas, Offset offset, CustomPainter painter) {
    late int debugPreviousCanvasSaveCount;
563
    canvas.save();
564 565 566 567
    assert(() {
      debugPreviousCanvasSaveCount = canvas.getSaveCount();
      return true;
    }());
568
    if (offset != Offset.zero) {
569
      canvas.translate(offset.dx, offset.dy);
570
    }
571 572 573 574 575 576 577 578 579 580 581
    painter.paint(canvas, size);
    assert(() {
      // This isn't perfect. For example, we can't catch the case of
      // someone first restoring, then setting a transform or whatnot,
      // then saving.
      // If this becomes a real problem, we could add logic to the
      // Canvas class to lock the canvas at a particular save count
      // such that restore() fails if it would take the lock count
      // below that number.
      final int debugNewCanvasSaveCount = canvas.getSaveCount();
      if (debugNewCanvasSaveCount > debugPreviousCanvasSaveCount) {
582 583 584 585 586
        throw FlutterError.fromParts(<DiagnosticsNode>[
          ErrorSummary(
            'The $painter custom painter called canvas.save() or canvas.saveLayer() at least '
            '${debugNewCanvasSaveCount - debugPreviousCanvasSaveCount} more '
            'time${debugNewCanvasSaveCount - debugPreviousCanvasSaveCount == 1 ? '' : 's' } '
587
            'than it called canvas.restore().',
588 589
          ),
          ErrorDescription('This leaves the canvas in an inconsistent state and will probably result in a broken display.'),
590
          ErrorHint('You must pair each call to save()/saveLayer() with a later matching call to restore().'),
591
        ]);
592 593
      }
      if (debugNewCanvasSaveCount < debugPreviousCanvasSaveCount) {
594
        throw FlutterError.fromParts(<DiagnosticsNode>[
595 596
          ErrorSummary(
            'The $painter custom painter called canvas.restore() '
597 598
            '${debugPreviousCanvasSaveCount - debugNewCanvasSaveCount} more '
            'time${debugPreviousCanvasSaveCount - debugNewCanvasSaveCount == 1 ? '' : 's' } '
599
            'than it called canvas.save() or canvas.saveLayer().',
600 601
          ),
          ErrorDescription('This leaves the canvas in an inconsistent state and will result in a broken display.'),
602
          ErrorHint('You should only call restore() if you first called save() or saveLayer().'),
603
        ]);
604 605 606 607 608 609 610 611 612
      }
      return debugNewCanvasSaveCount == debugPreviousCanvasSaveCount;
    }());
    canvas.restore();
  }

  @override
  void paint(PaintingContext context, Offset offset) {
    if (_painter != null) {
613
      _paintWithPainter(context.canvas, offset, _painter!);
614 615 616 617
      _setRasterCacheHints(context);
    }
    super.paint(context, offset);
    if (_foregroundPainter != null) {
618
      _paintWithPainter(context.canvas, offset, _foregroundPainter!);
619 620 621 622 623
      _setRasterCacheHints(context);
    }
  }

  void _setRasterCacheHints(PaintingContext context) {
624
    if (isComplex) {
625
      context.setIsComplexHint();
626 627
    }
    if (willChange) {
628
      context.setWillChangeHint();
629
    }
630 631 632
  }

  /// Builds semantics for the picture drawn by [painter].
633
  SemanticsBuilderCallback? _backgroundSemanticsBuilder;
634 635

  /// Builds semantics for the picture drawn by [foregroundPainter].
636
  SemanticsBuilderCallback? _foregroundSemanticsBuilder;
637 638 639 640 641 642 643 644 645 646

  @override
  void describeSemanticsConfiguration(SemanticsConfiguration config) {
    super.describeSemanticsConfiguration(config);
    _backgroundSemanticsBuilder = painter?.semanticsBuilder;
    _foregroundSemanticsBuilder = foregroundPainter?.semanticsBuilder;
    config.isSemanticBoundary = _backgroundSemanticsBuilder != null || _foregroundSemanticsBuilder != null;
  }

  /// Describe the semantics of the picture painted by the [painter].
647
  List<SemanticsNode>? _backgroundSemanticsNodes;
648 649

  /// Describe the semantics of the picture painted by the [foregroundPainter].
650
  List<SemanticsNode>? _foregroundSemanticsNodes;
651 652 653 654 655 656 657 658 659

  @override
  void assembleSemanticsNode(
    SemanticsNode node,
    SemanticsConfiguration config,
    Iterable<SemanticsNode> children,
  ) {
    assert(() {
      if (child == null && children.isNotEmpty) {
660 661 662
        throw FlutterError.fromParts(<DiagnosticsNode>[
          ErrorSummary(
            '$runtimeType does not have a child widget but received a non-empty list of child SemanticsNode:\n'
663 664
            '${children.join('\n')}',
          ),
665
        ]);
666 667 668 669 670
      }
      return true;
    }());

    final List<CustomPainterSemantics> backgroundSemantics = _backgroundSemanticsBuilder != null
671
      ? _backgroundSemanticsBuilder!(size)
672 673 674 675
      : const <CustomPainterSemantics>[];
    _backgroundSemanticsNodes = _updateSemanticsChildren(_backgroundSemanticsNodes, backgroundSemantics);

    final List<CustomPainterSemantics> foregroundSemantics = _foregroundSemanticsBuilder != null
676
      ? _foregroundSemanticsBuilder!(size)
677 678 679
      : const <CustomPainterSemantics>[];
    _foregroundSemanticsNodes = _updateSemanticsChildren(_foregroundSemanticsNodes, foregroundSemantics);

680 681
    final bool hasBackgroundSemantics = _backgroundSemanticsNodes != null && _backgroundSemanticsNodes!.isNotEmpty;
    final bool hasForegroundSemantics = _foregroundSemanticsNodes != null && _foregroundSemanticsNodes!.isNotEmpty;
682
    final List<SemanticsNode> finalChildren = <SemanticsNode>[
683
      if (hasBackgroundSemantics) ..._backgroundSemanticsNodes!,
684
      ...children,
685
      if (hasForegroundSemantics) ..._foregroundSemanticsNodes!,
686
    ];
687 688 689
    super.assembleSemanticsNode(node, config, finalChildren);
  }

690 691 692 693 694 695 696
  @override
  void clearSemantics() {
    super.clearSemantics();
    _backgroundSemanticsNodes = null;
    _foregroundSemanticsNodes = null;
  }

697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718
  /// Updates the nodes of `oldSemantics` using data in `newChildSemantics`, and
  /// returns a new list containing child nodes sorted according to the order
  /// specified by `newChildSemantics`.
  ///
  /// [SemanticsNode]s that match [CustomPainterSemantics] by [Key]s preserve
  /// their [SemanticsNode.key] field. If a node with the same key appears in
  /// a different position in the list, it is moved to the new position, but the
  /// same object is reused.
  ///
  /// [SemanticsNode]s whose `key` is null may be updated from
  /// [CustomPainterSemantics] whose `key` is also null. However, the algorithm
  /// does not guarantee it. If your semantics require that specific nodes are
  /// updated from specific [CustomPainterSemantics], it is recommended to match
  /// them by specifying non-null keys.
  ///
  /// The algorithm tries to be as close to [RenderObjectElement.updateChildren]
  /// as possible, deviating only where the concepts diverge between widgets and
  /// semantics. For example, a [SemanticsNode] can be updated from a
  /// [CustomPainterSemantics] based on `Key` alone; their types are not
  /// considered because there is only one type of [SemanticsNode]. There is no
  /// concept of a "forgotten" node in semantics, deactivated nodes, or global
  /// keys.
719 720 721
  static List<SemanticsNode> _updateSemanticsChildren(
    List<SemanticsNode>? oldSemantics,
    List<CustomPainterSemantics>? newChildSemantics,
722 723 724 725 726
  ) {
    oldSemantics = oldSemantics ?? const <SemanticsNode>[];
    newChildSemantics = newChildSemantics ?? const <CustomPainterSemantics>[];

    assert(() {
727
      final Map<Key, int> keys = HashMap<Key, int>();
728
      final List<DiagnosticsNode> information = <DiagnosticsNode>[];
729
      for (int i = 0; i < newChildSemantics!.length; i += 1) {
730 731 732
        final CustomPainterSemantics child = newChildSemantics[i];
        if (child.key != null) {
          if (keys.containsKey(child.key)) {
733
            information.add(ErrorDescription('- duplicate key ${child.key} found at position $i'));
734
          }
735
          keys[child.key!] = i;
736 737 738
        }
      }

739 740 741
      if (information.isNotEmpty) {
        information.insert(0, ErrorSummary('Failed to update the list of CustomPainterSemantics:'));
        throw FlutterError.fromParts(information);
742 743 744 745 746 747 748 749 750 751
      }

      return true;
    }());

    int newChildrenTop = 0;
    int oldChildrenTop = 0;
    int newChildrenBottom = newChildSemantics.length - 1;
    int oldChildrenBottom = oldSemantics.length - 1;

752
    final List<SemanticsNode?> newChildren = List<SemanticsNode?>.filled(newChildSemantics.length, null);
753 754 755 756 757

    // Update the top of the list.
    while ((oldChildrenTop <= oldChildrenBottom) && (newChildrenTop <= newChildrenBottom)) {
      final SemanticsNode oldChild = oldSemantics[oldChildrenTop];
      final CustomPainterSemantics newSemantics = newChildSemantics[newChildrenTop];
758
      if (!_canUpdateSemanticsChild(oldChild, newSemantics)) {
759
        break;
760
      }
761 762 763 764 765 766 767 768 769 770
      final SemanticsNode newChild = _updateSemanticsChild(oldChild, newSemantics);
      newChildren[newChildrenTop] = newChild;
      newChildrenTop += 1;
      oldChildrenTop += 1;
    }

    // Scan the bottom of the list.
    while ((oldChildrenTop <= oldChildrenBottom) && (newChildrenTop <= newChildrenBottom)) {
      final SemanticsNode oldChild = oldSemantics[oldChildrenBottom];
      final CustomPainterSemantics newChild = newChildSemantics[newChildrenBottom];
771
      if (!_canUpdateSemanticsChild(oldChild, newChild)) {
772
        break;
773
      }
774 775 776 777 778 779
      oldChildrenBottom -= 1;
      newChildrenBottom -= 1;
    }

    // Scan the old children in the middle of the list.
    final bool haveOldChildren = oldChildrenTop <= oldChildrenBottom;
780
    late final Map<Key, SemanticsNode> oldKeyedChildren;
781 782 783 784
    if (haveOldChildren) {
      oldKeyedChildren = <Key, SemanticsNode>{};
      while (oldChildrenTop <= oldChildrenBottom) {
        final SemanticsNode oldChild = oldSemantics[oldChildrenTop];
785
        if (oldChild.key != null) {
786
          oldKeyedChildren[oldChild.key!] = oldChild;
787
        }
788 789 790 791 792 793
        oldChildrenTop += 1;
      }
    }

    // Update the middle of the list.
    while (newChildrenTop <= newChildrenBottom) {
794
      SemanticsNode? oldChild;
795 796
      final CustomPainterSemantics newSemantics = newChildSemantics[newChildrenTop];
      if (haveOldChildren) {
797
        final Key? key = newSemantics.key;
798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838
        if (key != null) {
          oldChild = oldKeyedChildren[key];
          if (oldChild != null) {
            if (_canUpdateSemanticsChild(oldChild, newSemantics)) {
              // we found a match!
              // remove it from oldKeyedChildren so we don't unsync it later
              oldKeyedChildren.remove(key);
            } else {
              // Not a match, let's pretend we didn't see it for now.
              oldChild = null;
            }
          }
        }
      }
      assert(oldChild == null || _canUpdateSemanticsChild(oldChild, newSemantics));
      final SemanticsNode newChild = _updateSemanticsChild(oldChild, newSemantics);
      assert(oldChild == newChild || oldChild == null);
      newChildren[newChildrenTop] = newChild;
      newChildrenTop += 1;
    }

    // We've scanned the whole list.
    assert(oldChildrenTop == oldChildrenBottom + 1);
    assert(newChildrenTop == newChildrenBottom + 1);
    assert(newChildSemantics.length - newChildrenTop == oldSemantics.length - oldChildrenTop);
    newChildrenBottom = newChildSemantics.length - 1;
    oldChildrenBottom = oldSemantics.length - 1;

    // Update the bottom of the list.
    while ((oldChildrenTop <= oldChildrenBottom) && (newChildrenTop <= newChildrenBottom)) {
      final SemanticsNode oldChild = oldSemantics[oldChildrenTop];
      final CustomPainterSemantics newSemantics = newChildSemantics[newChildrenTop];
      assert(_canUpdateSemanticsChild(oldChild, newSemantics));
      final SemanticsNode newChild = _updateSemanticsChild(oldChild, newSemantics);
      assert(oldChild == newChild);
      newChildren[newChildrenTop] = newChild;
      newChildrenTop += 1;
      oldChildrenTop += 1;
    }

    assert(() {
839
      for (final SemanticsNode? node in newChildren) {
840 841 842 843 844
        assert(node != null);
      }
      return true;
    }());

845
    return newChildren.cast<SemanticsNode>();
846 847 848 849 850 851 852 853 854 855 856 857 858 859
  }

  /// Whether `oldChild` can be updated with properties from `newSemantics`.
  ///
  /// If `oldChild` can be updated, it is updated using [_updateSemanticsChild].
  /// Otherwise, the node is replaced by a new instance of [SemanticsNode].
  static bool _canUpdateSemanticsChild(SemanticsNode oldChild, CustomPainterSemantics newSemantics) {
    return oldChild.key == newSemantics.key;
  }

  /// Updates `oldChild` using the properties of `newSemantics`.
  ///
  /// This method requires that `_canUpdateSemanticsChild(oldChild, newSemantics)`
  /// is true prior to calling it.
860
  static SemanticsNode _updateSemanticsChild(SemanticsNode? oldChild, CustomPainterSemantics newSemantics) {
861 862
    assert(oldChild == null || _canUpdateSemanticsChild(oldChild, newSemantics));

863
    final SemanticsNode newChild = oldChild ?? SemanticsNode(
864 865 866 867
      key: newSemantics.key,
    );

    final SemanticsProperties properties = newSemantics.properties;
868
    final SemanticsConfiguration config = SemanticsConfiguration();
869 870 871
    if (properties.sortKey != null) {
      config.sortKey = properties.sortKey;
    }
872 873 874
    if (properties.checked != null) {
      config.isChecked = properties.checked;
    }
875 876 877
    if (properties.mixed != null) {
      config.isCheckStateMixed = properties.mixed;
    }
878
    if (properties.selected != null) {
879
      config.isSelected = properties.selected!;
880 881
    }
    if (properties.button != null) {
882
      config.isButton = properties.button!;
883
    }
884
    if (properties.link != null) {
885
      config.isLink = properties.link!;
886
    }
887
    if (properties.textField != null) {
888
      config.isTextField = properties.textField!;
889
    }
890 891 892
    if (properties.slider != null) {
      config.isSlider = properties.slider!;
    }
893 894 895
    if (properties.keyboardKey != null) {
      config.isKeyboardKey = properties.keyboardKey!;
    }
896
    if (properties.readOnly != null) {
897
      config.isReadOnly = properties.readOnly!;
898
    }
899
    if (properties.focusable != null) {
900
      config.isFocusable = properties.focusable!;
901
    }
902
    if (properties.focused != null) {
903
      config.isFocused = properties.focused!;
904 905 906 907 908
    }
    if (properties.enabled != null) {
      config.isEnabled = properties.enabled;
    }
    if (properties.inMutuallyExclusiveGroup != null) {
909
      config.isInMutuallyExclusiveGroup = properties.inMutuallyExclusiveGroup!;
910
    }
911
    if (properties.obscured != null) {
912
      config.isObscured = properties.obscured!;
913
    }
914
    if (properties.multiline != null) {
915
      config.isMultiline = properties.multiline!;
916
    }
917
    if (properties.hidden != null) {
918
      config.isHidden = properties.hidden!;
919
    }
920
    if (properties.header != null) {
921
      config.isHeader = properties.header!;
922
    }
923
    if (properties.scopesRoute != null) {
924
      config.scopesRoute = properties.scopesRoute!;
925 926
    }
    if (properties.namesRoute != null) {
927
      config.namesRoute = properties.namesRoute!;
928
    }
929
    if (properties.liveRegion != null) {
930
      config.liveRegion = properties.liveRegion!;
931
    }
932 933 934 935 936 937
    if (properties.maxValueLength != null) {
      config.maxValueLength = properties.maxValueLength;
    }
    if (properties.currentValueLength != null) {
      config.currentValueLength = properties.currentValueLength;
    }
938 939 940 941
    if (properties.toggled != null) {
      config.isToggled = properties.toggled;
    }
    if (properties.image != null) {
942
      config.isImage = properties.image!;
943
    }
944
    if (properties.label != null) {
945
      config.label = properties.label!;
946 947
    }
    if (properties.value != null) {
948
      config.value = properties.value!;
949 950
    }
    if (properties.increasedValue != null) {
951
      config.increasedValue = properties.increasedValue!;
952 953
    }
    if (properties.decreasedValue != null) {
954
      config.decreasedValue = properties.decreasedValue!;
955 956
    }
    if (properties.hint != null) {
957
      config.hint = properties.hint!;
958 959 960 961 962
    }
    if (properties.textDirection != null) {
      config.textDirection = properties.textDirection;
    }
    if (properties.onTap != null) {
963
      config.onTap = properties.onTap;
964 965
    }
    if (properties.onLongPress != null) {
966
      config.onLongPress = properties.onLongPress;
967 968
    }
    if (properties.onScrollLeft != null) {
969
      config.onScrollLeft = properties.onScrollLeft;
970 971
    }
    if (properties.onScrollRight != null) {
972
      config.onScrollRight = properties.onScrollRight;
973 974
    }
    if (properties.onScrollUp != null) {
975
      config.onScrollUp = properties.onScrollUp;
976 977
    }
    if (properties.onScrollDown != null) {
978
      config.onScrollDown = properties.onScrollDown;
979 980
    }
    if (properties.onIncrease != null) {
981
      config.onIncrease = properties.onIncrease;
982 983
    }
    if (properties.onDecrease != null) {
984
      config.onDecrease = properties.onDecrease;
985
    }
986 987 988 989 990 991 992 993 994
    if (properties.onCopy != null) {
      config.onCopy = properties.onCopy;
    }
    if (properties.onCut != null) {
      config.onCut = properties.onCut;
    }
    if (properties.onPaste != null) {
      config.onPaste = properties.onPaste;
    }
995
    if (properties.onMoveCursorForwardByCharacter != null) {
996
      config.onMoveCursorForwardByCharacter = properties.onMoveCursorForwardByCharacter;
997 998
    }
    if (properties.onMoveCursorBackwardByCharacter != null) {
999
      config.onMoveCursorBackwardByCharacter = properties.onMoveCursorBackwardByCharacter;
1000
    }
1001 1002 1003 1004 1005 1006
    if (properties.onMoveCursorForwardByWord != null) {
      config.onMoveCursorForwardByWord = properties.onMoveCursorForwardByWord;
    }
    if (properties.onMoveCursorBackwardByWord != null) {
      config.onMoveCursorBackwardByWord = properties.onMoveCursorBackwardByWord;
    }
1007 1008 1009
    if (properties.onSetSelection != null) {
      config.onSetSelection = properties.onSetSelection;
    }
1010 1011 1012
    if (properties.onSetText != null) {
      config.onSetText = properties.onSetText;
    }
1013 1014 1015 1016 1017 1018
    if (properties.onDidGainAccessibilityFocus != null) {
      config.onDidGainAccessibilityFocus = properties.onDidGainAccessibilityFocus;
    }
    if (properties.onDidLoseAccessibilityFocus != null) {
      config.onDidLoseAccessibilityFocus = properties.onDidLoseAccessibilityFocus;
    }
1019 1020 1021
    if (properties.onDismiss != null) {
      config.onDismiss = properties.onDismiss;
    }
1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035

    newChild.updateWith(
      config: config,
      // As of now CustomPainter does not support multiple tree levels.
      childrenInInversePaintOrder: const <SemanticsNode>[],
    );

    newChild
      ..rect = newSemantics.rect
      ..transform = newSemantics.transform
      ..tags = newSemantics.tags;

    return newChild;
  }
Ian Hickson's avatar
Ian Hickson committed
1036 1037 1038 1039 1040 1041 1042 1043 1044 1045

  @override
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
    properties.add(MessageProperty('painter', '$painter'));
    properties.add(MessageProperty('foregroundPainter', '$foregroundPainter', level: foregroundPainter != null ? DiagnosticLevel.info : DiagnosticLevel.fine));
    properties.add(DiagnosticsProperty<Size>('preferredSize', preferredSize, defaultValue: Size.zero));
    properties.add(DiagnosticsProperty<bool>('isComplex', isComplex, defaultValue: false));
    properties.add(DiagnosticsProperty<bool>('willChange', willChange, defaultValue: false));
  }
1046
}