flow.dart 15.6 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
Adam Barth's avatar
Adam Barth committed
2 3 4
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

Kate Lovett's avatar
Kate Lovett committed
5
import 'dart:ui' as ui show Color;
6

Kate Lovett's avatar
Kate Lovett committed
7
import 'package:flutter/foundation.dart';
Adam Barth's avatar
Adam Barth committed
8 9 10
import 'package:vector_math/vector_math_64.dart';

import 'box.dart';
11
import 'layer.dart';
Adam Barth's avatar
Adam Barth committed
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
import 'object.dart';

/// A context in which a [FlowDelegate] paints.
///
/// Provides information about the current size of the container and the
/// children and a mechanism for painting children.
///
/// See also:
///
///  * [FlowDelegate]
///  * [Flow]
///  * [RenderFlow]
abstract class FlowPaintingContext {
  /// The size of the container in which the children can be painted.
  Size get size;

  /// The number of children available to paint.
  int get childCount;

  /// The size of the [i]th child.
  ///
  /// If [i] is negative or exceeds [childCount], returns null.
34
  Size? getChildSize(int i);
Adam Barth's avatar
Adam Barth committed
35 36 37 38 39 40 41 42 43

  /// Paint the [i]th child using the given transform.
  ///
  /// The child will be painted in a coordinate system that concatenates the
  /// container's coordinate system with the given transform. The origin of the
  /// parent's coordinate system is the upper left corner of the parent, with
  /// x increasing rightward and y increasing downward.
  ///
  /// The container will clip the children to its bounds.
44
  void paintChild(int i, { Matrix4 transform, double opacity = 1.0 });
Adam Barth's avatar
Adam Barth committed
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
}

/// A delegate that controls the appearance of a flow layout.
///
/// Flow layouts are optimized for moving children around the screen using
/// transformation matrices. For optimal performance, construct the
/// [FlowDelegate] with an [Animation] that ticks whenever the delegate wishes
/// to change the transformation matrices for the children and avoid rebuilding
/// the [Flow] widget itself every animation frame.
///
/// See also:
///
///  * [Flow]
///  * [RenderFlow]
abstract class FlowDelegate {
60
  /// The flow will repaint whenever [repaint] notifies its listeners.
61
  const FlowDelegate({ Listenable? repaint }) : _repaint = repaint;
Adam Barth's avatar
Adam Barth committed
62

63
  final Listenable? _repaint;
Adam Barth's avatar
Adam Barth committed
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79

  /// Override to control the size of the container for the children.
  ///
  /// By default, the flow will be as large as possible. If this function
  /// returns a size that does not respect the given constraints, the size will
  /// be adjusted to be as close to the returned size as possible while still
  /// respecting the constraints.
  ///
  /// If this function depends on information other than the given constraints,
  /// override [shouldRelayout] to indicate when when the container should
  /// relayout.
  Size getSize(BoxConstraints constraints) => constraints.biggest;

  /// Override to control the layout constraints given to each child.
  ///
  /// By default, the children will receive the given constraints, which are the
80
  /// constraints used to size the container. The children need
Adam Barth's avatar
Adam Barth committed
81
  /// not respect the given constraints, but they are required to respect the
82
  /// returned constraints. For example, the incoming constraints might require
Adam Barth's avatar
Adam Barth committed
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
  /// the container to have a width of exactly 100.0 and a height of exactly
  /// 100.0, but this function might give the children looser constraints that
  /// let them be larger or smaller than 100.0 by 100.0.
  ///
  /// If this function depends on information other than the given constraints,
  /// override [shouldRelayout] to indicate when when the container should
  /// relayout.
  BoxConstraints getConstraintsForChild(int i, BoxConstraints constraints) => constraints;

  /// Override to paint the children of the flow.
  ///
  /// Children can be painted in any order, but each child can be painted at
  /// most once. Although the container clips the children to its own bounds, it
  /// is more efficient to skip painting a child altogether rather than having
  /// it paint entirely outside the container's clip.
  ///
  /// To paint a child, call [FlowPaintingContext.paintChild] on the given
Ian Hickson's avatar
Ian Hickson committed
100 101 102 103
  /// [FlowPaintingContext] (the `context` argument). The given context is valid
  /// only within the scope of this function call and contains information (such
  /// as the size of the container) that is useful for picking transformation
  /// matrices for the children.
Adam Barth's avatar
Adam Barth committed
104 105 106 107 108 109 110 111 112 113
  ///
  /// If this function depends on information other than the given context,
  /// override [shouldRepaint] to indicate when when the container should
  /// relayout.
  void paintChildren(FlowPaintingContext context);

  /// Override this method to return true when the children need to be laid out.
  /// This should compare the fields of the current delegate and the given
  /// oldDelegate and return true if the fields are such that the layout would
  /// be different.
114
  bool shouldRelayout(covariant FlowDelegate oldDelegate) => false;
Adam Barth's avatar
Adam Barth committed
115 116 117 118 119 120 121 122 123 124 125 126 127 128

  /// Override this method to return true when the children need to be
  /// repainted. This should compare the fields of the current delegate and the
  /// given oldDelegate and return true if the fields are such that
  /// paintChildren would act differently.
  ///
  /// The delegate can also trigger a repaint if the delegate provides the
  /// repaint animation argument to this object's constructor and that animation
  /// ticks. Triggering a repaint using this animation-based mechanism is more
  /// efficient than rebuilding the [Flow] widget to change its delegate.
  ///
  /// The flow container might repaint even if this function returns false, for
  /// example if layout triggers painting (e.g., if [shouldRelayout] returns
  /// true).
129
  bool shouldRepaint(covariant FlowDelegate oldDelegate);
Adam Barth's avatar
Adam Barth committed
130 131 132 133 134 135

  /// Override this method to include additional information in the
  /// debugging data printed by [debugDumpRenderTree] and friends.
  ///
  /// By default, returns the [runtimeType] of the class.
  @override
136
  String toString() => objectRuntimeType(this, 'FlowDelegate');
Adam Barth's avatar
Adam Barth committed
137 138 139 140 141 142 143 144 145
}

/// Parent data for use with [RenderFlow].
///
/// The [offset] property is ignored by [RenderFlow] and is always set to
/// [Offset.zero]. Children of a [RenderFlow] are positioned using a
/// transformation matrix, which is private to the [RenderFlow]. To set the
/// matrix, use the [FlowPaintingContext.paintChild] function from an override
/// of the [FlowDelegate.paintChildren] function.
146
class FlowParentData extends ContainerBoxParentData<RenderBox> {
147
  Matrix4? _transform;
Adam Barth's avatar
Adam Barth committed
148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
}

/// Implements the flow layout algorithm.
///
/// Flow layouts are optimized for repositioning children using transformation
/// matrices.
///
/// The flow container is sized independently from the children by the
/// [FlowDelegate.getSize] function of the delegate. The children are then sized
/// independently given the constraints from the
/// [FlowDelegate.getConstraintsForChild] function.
///
/// Rather than positioning the children during layout, the children are
/// positioned using transformation matrices during the paint phase using the
/// matrices from the [FlowDelegate.paintChildren] function. The children can be
/// repositioned efficiently by simply repainting the flow.
///
/// The most efficient way to trigger a repaint of the flow is to supply a
/// repaint argument to the constructor of the [FlowDelegate]. The flow will
/// listen to this animation and repaint whenever the animation ticks, avoiding
/// both the build and layout phases of the pipeline.
///
/// See also:
///
///  * [FlowDelegate]
///  * [RenderStack]
class RenderFlow extends RenderBox
    with ContainerRenderObjectMixin<RenderBox, FlowParentData>,
         RenderBoxContainerDefaultsMixin<RenderBox, FlowParentData>
    implements FlowPaintingContext {
  /// Creates a render object for a flow layout.
  ///
  /// For optimal performance, consider using children that return true from
181
  /// [isRepaintBoundary].
Adam Barth's avatar
Adam Barth committed
182
  RenderFlow({
183 184
    List<RenderBox>? children,
    required FlowDelegate delegate,
185
    Clip clipBehavior = Clip.hardEdge,
186
  }) : assert(delegate != null),
187 188 189
       assert(clipBehavior != null),
       _delegate = delegate,
       _clipBehavior = clipBehavior {
Adam Barth's avatar
Adam Barth committed
190 191 192 193 194
    addAll(children);
  }

  @override
  void setupParentData(RenderBox child) {
195
    final ParentData? childParentData = child.parentData;
Adam Barth's avatar
Adam Barth committed
196 197 198
    if (childParentData is FlowParentData)
      childParentData._transform = null;
    else
199
      child.parentData = FlowParentData();
Adam Barth's avatar
Adam Barth committed
200 201 202 203 204 205 206 207 208 209
  }

  /// The delegate that controls the transformation matrices of the children.
  FlowDelegate get delegate => _delegate;
  FlowDelegate _delegate;
  /// When the delegate is changed to a new delegate with the same runtimeType
  /// as the old delegate, this object will call the delegate's
  /// [FlowDelegate.shouldRelayout] and [FlowDelegate.shouldRepaint] functions
  /// to determine whether the new delegate requires this object to update its
  /// layout or painting.
210
  set delegate(FlowDelegate newDelegate) {
Adam Barth's avatar
Adam Barth committed
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
    assert(newDelegate != null);
    if (_delegate == newDelegate)
      return;
    final FlowDelegate oldDelegate = _delegate;
    _delegate = newDelegate;

    if (newDelegate.runtimeType != oldDelegate.runtimeType || newDelegate.shouldRelayout(oldDelegate))
      markNeedsLayout();
    else if (newDelegate.shouldRepaint(oldDelegate))
      markNeedsPaint();

    if (attached) {
      oldDelegate._repaint?.removeListener(markNeedsPaint);
      newDelegate._repaint?.addListener(markNeedsPaint);
    }
  }

228
  /// {@macro flutter.material.Material.clipBehavior}
229 230 231 232 233 234 235 236 237 238 239 240 241
  ///
  /// Defaults to [Clip.hardEdge], and must not be null.
  Clip get clipBehavior => _clipBehavior;
  Clip _clipBehavior = Clip.hardEdge;
  set clipBehavior(Clip value) {
    assert(value != null);
    if (value != _clipBehavior) {
      _clipBehavior = value;
      markNeedsPaint();
      markNeedsSemanticsUpdate();
    }
  }

Adam Barth's avatar
Adam Barth committed
242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261
  @override
  void attach(PipelineOwner owner) {
    super.attach(owner);
    _delegate._repaint?.addListener(markNeedsPaint);
  }

  @override
  void detach() {
    _delegate._repaint?.removeListener(markNeedsPaint);
    super.detach();
  }

  Size _getSize(BoxConstraints constraints) {
    assert(constraints.debugAssertIsValid());
    return constraints.constrain(_delegate.getSize(constraints));
  }

  @override
  bool get isRepaintBoundary => true;

262 263 264 265
  // TODO(ianh): It's a bit dubious to be using the getSize function from the delegate to
  // figure out the intrinsic dimensions. We really should either not support intrinsics,
  // or we should expose intrinsic delegate callbacks and throw if they're not implemented.

Adam Barth's avatar
Adam Barth committed
266
  @override
267
  double computeMinIntrinsicWidth(double height) {
268
    final double width = _getSize(BoxConstraints.tightForFinite(height: height)).width;
269 270 271
    if (width.isFinite)
      return width;
    return 0.0;
Adam Barth's avatar
Adam Barth committed
272 273 274
  }

  @override
275
  double computeMaxIntrinsicWidth(double height) {
276
    final double width = _getSize(BoxConstraints.tightForFinite(height: height)).width;
277 278 279
    if (width.isFinite)
      return width;
    return 0.0;
Adam Barth's avatar
Adam Barth committed
280 281 282
  }

  @override
283
  double computeMinIntrinsicHeight(double width) {
284
    final double height = _getSize(BoxConstraints.tightForFinite(width: width)).height;
285 286 287
    if (height.isFinite)
      return height;
    return 0.0;
Adam Barth's avatar
Adam Barth committed
288 289 290
  }

  @override
291
  double computeMaxIntrinsicHeight(double width) {
292
    final double height = _getSize(BoxConstraints.tightForFinite(width: width)).height;
293 294 295
    if (height.isFinite)
      return height;
    return 0.0;
Adam Barth's avatar
Adam Barth committed
296 297
  }

298 299 300 301 302
  @override
  Size computeDryLayout(BoxConstraints constraints) {
    return _getSize(constraints);
  }

Adam Barth's avatar
Adam Barth committed
303 304
  @override
  void performLayout() {
305
    final BoxConstraints constraints = this.constraints;
Adam Barth's avatar
Adam Barth committed
306 307 308
    size = _getSize(constraints);
    int i = 0;
    _randomAccessChildren.clear();
309
    RenderBox? child = firstChild;
Adam Barth's avatar
Adam Barth committed
310 311
    while (child != null) {
      _randomAccessChildren.add(child);
312
      final BoxConstraints innerConstraints = _delegate.getConstraintsForChild(i, constraints);
Adam Barth's avatar
Adam Barth committed
313
      child.layout(innerConstraints, parentUsesSize: true);
314
      final FlowParentData childParentData = child.parentData! as FlowParentData;
Adam Barth's avatar
Adam Barth committed
315 316 317 318 319 320 321 322 323 324 325 326 327
      childParentData.offset = Offset.zero;
      child = childParentData.nextSibling;
      i += 1;
    }
  }

  // Updated during layout. Only valid if layout is not dirty.
  final List<RenderBox> _randomAccessChildren = <RenderBox>[];

  // Updated during paint.
  final List<int> _lastPaintOrder = <int>[];

  // Only valid during paint.
328 329
  PaintingContext? _paintingContext;
  Offset? _paintingOffset;
Adam Barth's avatar
Adam Barth committed
330 331

  @override
332
  Size? getChildSize(int i) {
Adam Barth's avatar
Adam Barth committed
333 334 335 336 337 338
    if (i < 0 || i >= _randomAccessChildren.length)
      return null;
    return _randomAccessChildren[i].size;
  }

  @override
339
  void paintChild(int i, { Matrix4? transform, double opacity = 1.0 }) {
340
    transform ??= Matrix4.identity();
341
    final RenderBox child = _randomAccessChildren[i];
342
    final FlowParentData childParentData = child.parentData! as FlowParentData;
Adam Barth's avatar
Adam Barth committed
343 344
    assert(() {
      if (childParentData._transform != null) {
345 346 347 348 349
        throw FlutterError(
          'Cannot call paintChild twice for the same child.\n'
          'The flow delegate of type ${_delegate.runtimeType} attempted to '
          'paint child $i multiple times, which is not permitted.'
        );
Adam Barth's avatar
Adam Barth committed
350 351
      }
      return true;
352
    }());
Adam Barth's avatar
Adam Barth committed
353 354 355 356 357 358 359 360 361 362
    _lastPaintOrder.add(i);
    childParentData._transform = transform;

    // We return after assigning _transform so that the transparent child can
    // still be hit tested at the correct location.
    if (opacity == 0.0)
      return;

    void painter(PaintingContext context, Offset offset) {
      context.paintChild(child, offset);
pq's avatar
pq committed
363
    }
Adam Barth's avatar
Adam Barth committed
364
    if (opacity == 1.0) {
365
      _paintingContext!.pushTransform(needsCompositing, _paintingOffset!, transform, painter);
Adam Barth's avatar
Adam Barth committed
366
    } else {
367 368
      _paintingContext!.pushOpacity(_paintingOffset!, ui.Color.getAlphaFromOpacity(opacity), (PaintingContext context, Offset offset) {
        context.pushTransform(needsCompositing, offset, transform!, painter);
Adam Barth's avatar
Adam Barth committed
369 370 371 372 373 374 375 376
      });
    }
  }

  void _paintWithDelegate(PaintingContext context, Offset offset) {
    _lastPaintOrder.clear();
    _paintingContext = context;
    _paintingOffset = offset;
377
    for (final RenderBox child in _randomAccessChildren) {
378
      final FlowParentData childParentData = child.parentData! as FlowParentData;
Adam Barth's avatar
Adam Barth committed
379 380 381 382 383 384 385 386 387 388 389 390
      childParentData._transform = null;
    }
    try {
      _delegate.paintChildren(this);
    } finally {
      _paintingContext = null;
      _paintingOffset = null;
    }
  }

  @override
  void paint(PaintingContext context, Offset offset) {
391
    if (clipBehavior == Clip.none) {
392
      _clipRectLayer = null;
393 394
      _paintWithDelegate(context, offset);
    } else {
395 396
      _clipRectLayer = context.pushClipRect(needsCompositing, offset, Offset.zero & size, _paintWithDelegate,
          clipBehavior: clipBehavior, oldLayer: _clipRectLayer);
397
    }
Adam Barth's avatar
Adam Barth committed
398 399
  }

400 401
  ClipRectLayer? _clipRectLayer;

Adam Barth's avatar
Adam Barth committed
402
  @override
403
  bool hitTestChildren(BoxHitTestResult result, { required Offset position }) {
Adam Barth's avatar
Adam Barth committed
404 405 406 407 408 409
    final List<RenderBox> children = getChildrenAsList();
    for (int i = _lastPaintOrder.length - 1; i >= 0; --i) {
      final int childIndex = _lastPaintOrder[i];
      if (childIndex >= children.length)
        continue;
      final RenderBox child = children[childIndex];
410
      final FlowParentData childParentData = child.parentData! as FlowParentData;
411
      final Matrix4? transform = childParentData._transform;
Adam Barth's avatar
Adam Barth committed
412 413
      if (transform == null)
        continue;
414 415 416
      final bool absorbed = result.addWithPaintTransform(
        transform: transform,
        position: position,
417 418
        hitTest: (BoxHitTestResult result, Offset? position) {
          return child.hitTest(result, position: position!);
419 420 421
        },
      );
      if (absorbed)
Adam Barth's avatar
Adam Barth committed
422 423 424 425 426 427 428
        return true;
    }
    return false;
  }

  @override
  void applyPaintTransform(RenderBox child, Matrix4 transform) {
429
    final FlowParentData childParentData = child.parentData! as FlowParentData;
Adam Barth's avatar
Adam Barth committed
430
    if (childParentData._transform != null)
431
      transform.multiply(childParentData._transform!);
Adam Barth's avatar
Adam Barth committed
432 433 434
    super.applyPaintTransform(child, transform);
  }
}