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

  /// 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,
nt4f04uNd's avatar
nt4f04uNd committed
73
  /// override [shouldRelayout] to indicate when the container should
Adam Barth's avatar
Adam Barth committed
74 75 76 77 78 79
  /// 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
  /// 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,
nt4f04uNd's avatar
nt4f04uNd committed
88
  /// override [shouldRelayout] to indicate when the container should
Adam Barth's avatar
Adam Barth committed
89 90 91 92 93 94 95 96 97 98 99
  /// 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
  ///
  /// If this function depends on information other than the given context,
nt4f04uNd's avatar
nt4f04uNd committed
106
  /// override [shouldRepaint] to indicate when the container should
Adam Barth's avatar
Adam Barth committed
107 108 109 110 111 112 113
  /// 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
}

/// 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
162 163
/// matrices from the [FlowDelegate.paintChildren] function. The children are thus
/// repositioned efficiently by repainting the flow, skipping layout.
Adam Barth's avatar
Adam Barth committed
164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
///
/// 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
  }) : _delegate = delegate,
187
       _clipBehavior = clipBehavior {
Adam Barth's avatar
Adam Barth committed
188 189 190 191 192
    addAll(children);
  }

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

  /// 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.
209
  set delegate(FlowDelegate newDelegate) {
210
    if (_delegate == newDelegate) {
Adam Barth's avatar
Adam Barth committed
211
      return;
212
    }
Adam Barth's avatar
Adam Barth committed
213 214 215
    final FlowDelegate oldDelegate = _delegate;
    _delegate = newDelegate;

216
    if (newDelegate.runtimeType != oldDelegate.runtimeType || newDelegate.shouldRelayout(oldDelegate)) {
Adam Barth's avatar
Adam Barth committed
217
      markNeedsLayout();
218
    } else if (newDelegate.shouldRepaint(oldDelegate)) {
Adam Barth's avatar
Adam Barth committed
219
      markNeedsPaint();
220
    }
Adam Barth's avatar
Adam Barth committed
221 222 223 224 225 226 227

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

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

Adam Barth's avatar
Adam Barth committed
241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260
  @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;

261 262 263 264
  // 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
265
  @override
266
  double computeMinIntrinsicWidth(double height) {
267
    final double width = _getSize(BoxConstraints.tightForFinite(height: height)).width;
268
    if (width.isFinite) {
269
      return width;
270
    }
271
    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
    if (width.isFinite) {
278
      return width;
279
    }
280
    return 0.0;
Adam Barth's avatar
Adam Barth committed
281 282 283
  }

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

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

301
  @override
302 303
  @protected
  Size computeDryLayout(covariant BoxConstraints constraints) {
304 305 306
    return _getSize(constraints);
  }

Adam Barth's avatar
Adam Barth committed
307 308
  @override
  void performLayout() {
309
    final BoxConstraints constraints = this.constraints;
Adam Barth's avatar
Adam Barth committed
310 311 312
    size = _getSize(constraints);
    int i = 0;
    _randomAccessChildren.clear();
313
    RenderBox? child = firstChild;
Adam Barth's avatar
Adam Barth committed
314 315
    while (child != null) {
      _randomAccessChildren.add(child);
316
      final BoxConstraints innerConstraints = _delegate.getConstraintsForChild(i, constraints);
Adam Barth's avatar
Adam Barth committed
317
      child.layout(innerConstraints, parentUsesSize: true);
318
      final FlowParentData childParentData = child.parentData! as FlowParentData;
Adam Barth's avatar
Adam Barth committed
319 320 321 322 323 324 325 326 327 328 329 330 331
      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.
332 333
  PaintingContext? _paintingContext;
  Offset? _paintingOffset;
Adam Barth's avatar
Adam Barth committed
334 335

  @override
336
  Size? getChildSize(int i) {
337
    if (i < 0 || i >= _randomAccessChildren.length) {
Adam Barth's avatar
Adam Barth committed
338
      return null;
339
    }
Adam Barth's avatar
Adam Barth committed
340 341 342 343
    return _randomAccessChildren[i].size;
  }

  @override
344
  void paintChild(int i, { Matrix4? transform, double opacity = 1.0 }) {
345
    transform ??= Matrix4.identity();
346
    final RenderBox child = _randomAccessChildren[i];
347
    final FlowParentData childParentData = child.parentData! as FlowParentData;
Adam Barth's avatar
Adam Barth committed
348 349
    assert(() {
      if (childParentData._transform != null) {
350 351 352
        throw FlutterError(
          'Cannot call paintChild twice for the same child.\n'
          'The flow delegate of type ${_delegate.runtimeType} attempted to '
353
          'paint child $i multiple times, which is not permitted.',
354
        );
Adam Barth's avatar
Adam Barth committed
355 356
      }
      return true;
357
    }());
Adam Barth's avatar
Adam Barth committed
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.
363
    if (opacity == 0.0) {
Adam Barth's avatar
Adam Barth committed
364
      return;
365
    }
Adam Barth's avatar
Adam Barth committed
366 367 368

    void painter(PaintingContext context, Offset offset) {
      context.paintChild(child, offset);
pq's avatar
pq committed
369
    }
Adam Barth's avatar
Adam Barth committed
370
    if (opacity == 1.0) {
371
      _paintingContext!.pushTransform(needsCompositing, _paintingOffset!, transform, painter);
Adam Barth's avatar
Adam Barth committed
372
    } else {
373 374
      _paintingContext!.pushOpacity(_paintingOffset!, ui.Color.getAlphaFromOpacity(opacity), (PaintingContext context, Offset offset) {
        context.pushTransform(needsCompositing, offset, transform!, painter);
Adam Barth's avatar
Adam Barth committed
375 376 377 378 379 380 381 382
      });
    }
  }

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

  @override
  void paint(PaintingContext context, Offset offset) {
397 398 399 400 401 402 403 404
    _clipRectLayer.layer = context.pushClipRect(
      needsCompositing,
      offset,
      Offset.zero & size,
      _paintWithDelegate,
      clipBehavior: clipBehavior,
      oldLayer: _clipRectLayer.layer,
    );
Adam Barth's avatar
Adam Barth committed
405 406
  }

407 408 409 410 411 412 413
  final LayerHandle<ClipRectLayer> _clipRectLayer = LayerHandle<ClipRectLayer>();

  @override
  void dispose() {
    _clipRectLayer.layer = null;
    super.dispose();
  }
414

Adam Barth's avatar
Adam Barth committed
415
  @override
416
  bool hitTestChildren(BoxHitTestResult result, { required Offset position }) {
Adam Barth's avatar
Adam Barth committed
417 418 419
    final List<RenderBox> children = getChildrenAsList();
    for (int i = _lastPaintOrder.length - 1; i >= 0; --i) {
      final int childIndex = _lastPaintOrder[i];
420
      if (childIndex >= children.length) {
Adam Barth's avatar
Adam Barth committed
421
        continue;
422
      }
Adam Barth's avatar
Adam Barth committed
423
      final RenderBox child = children[childIndex];
424
      final FlowParentData childParentData = child.parentData! as FlowParentData;
425
      final Matrix4? transform = childParentData._transform;
426
      if (transform == null) {
Adam Barth's avatar
Adam Barth committed
427
        continue;
428
      }
429 430 431
      final bool absorbed = result.addWithPaintTransform(
        transform: transform,
        position: position,
432 433
        hitTest: (BoxHitTestResult result, Offset position) {
          return child.hitTest(result, position: position);
434 435
        },
      );
436
      if (absorbed) {
Adam Barth's avatar
Adam Barth committed
437
        return true;
438
      }
Adam Barth's avatar
Adam Barth committed
439 440 441 442 443 444
    }
    return false;
  }

  @override
  void applyPaintTransform(RenderBox child, Matrix4 transform) {
445
    final FlowParentData childParentData = child.parentData! as FlowParentData;
446
    if (childParentData._transform != null) {
447
      transform.multiply(childParentData._transform!);
448
    }
Adam Barth's avatar
Adam Barth committed
449 450 451
    super.applyPaintTransform(child, transform);
  }
}