custom_layout.dart 9.82 KB
Newer Older
1 2 3 4 5 6 7
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

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

Hixie's avatar
Hixie committed
8 9
// For OneChildLayoutDelegate and RenderCustomOneChildLayoutBox, see shifted_box.dart

10
/// [ParentData] used by [RenderCustomMultiChildLayoutBox].
11
class MultiChildLayoutParentData extends ContainerBoxParentDataMixin<RenderBox> {
12
  /// An object representing the identity of this child.
13
  Object id;
Adam Barth's avatar
Adam Barth committed
14 15

  String toString() => '${super.toString()}; id=$id';
16
}
17

18
/// A delegate that controls the layout of multiple children.
19 20 21 22 23 24 25
///
/// Used with [MultiChildCustomLayout], the widget for the
/// [RenderCustomMultiChildLayoutBox] render object.
///
/// Subclasses must override some or all of the methods
/// marked "Override this method to..." to provide the constraints and
/// positions of the children.
26
abstract class MultiChildLayoutDelegate {
27
  Map<Object, RenderBox> _idToChild;
28
  Set<RenderBox> _debugChildrenNeedingLayout;
29

30
  /// True if a non-null LayoutChild was provided for the specified id.
31 32 33 34
  ///
  /// Call this from the [performLayout] or [getSize] methods to
  /// determine which children are available, if the child list might
  /// vary.
35 36
  bool isChild(Object childId) => _idToChild[childId] != null;

37 38
  /// Ask the child to update its layout within the limits specified by
  /// the constraints parameter. The child's size is returned.
39 40 41 42
  ///
  /// Call this from your [performLayout] function to lay out each
  /// child. Every child must be laid out using this function exactly
  /// once each time the [performLayout] function is invoked.
43 44
  Size layoutChild(Object childId, BoxConstraints constraints) {
    final RenderBox child = _idToChild[childId];
45
    assert(() {
Hixie's avatar
Hixie committed
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
      if (child == null) {
        throw new RenderingError(
          'The $this custom multichild layout delegate tried to lay out a non-existent child:\n'
          'There is no child with the id "$childId".'
        );
      }
      if (!_debugChildrenNeedingLayout.remove(child)) {
        throw new RenderingError(
          'The $this custom multichild layout delegate tried to lay out the child with id "$childId" more than once.\n'
          'Each child must be laid out exactly once.'
        );
      }
      try {
        assert(constraints.debugAssertIsNormalized);
      } on AssertionError catch (exception) {
        throw new RenderingError(
          'The $this custom multichild layout delegate provided invalid box constraints for the child with id "$childId":\n'
          '$exception\n'
          'The minimum width and height must be greater than or equal to zero.\n'
          'The maximum width must be greater than or equal to the minimum width.\n'
          'The maximum height must be greater than or equal to the minimum height.'
        );
      }
      return true;
70
    });
71 72 73 74 75
    child.layout(constraints, parentUsesSize: true);
    return child.size;
  }

  /// Specify the child's origin relative to this origin.
76 77 78 79 80
  ///
  /// Call this from your [performLayout] function to position each
  /// child. If you do not call this for a child, its position will
  /// remain unchanged. Children initially have their position set to
  /// (0,0), i.e. the top left of the [RenderCustomMultiChildLayoutBox].
81
  void positionChild(Object childId, Offset offset) {
82
    final RenderBox child = _idToChild[childId];
Hixie's avatar
Hixie committed
83 84 85 86 87 88 89 90 91 92 93 94 95 96
    assert(() {
      if (child == null) {
        throw new RenderingError(
          'The $this custom multichild layout delegate tried to position out a non-existent child:\n'
          'There is no child with the id "$childId".'
        );
      }
      if (offset == null) {
        throw new RenderingError(
          'The $this custom multichild layout delegate provided a null position for the child with id "$childId".'
        );
      }
      return true;
    });
97
    final MultiChildLayoutParentData childParentData = child.parentData;
98
    childParentData.offset = offset;
99 100
  }

Hixie's avatar
Hixie committed
101 102 103 104 105
  String _debugDescribeChild(RenderBox child) {
    final MultiChildLayoutParentData childParentData = child.parentData;
    return '${childParentData.id}: $child';
  }

106
  void _callPerformLayout(Size size, RenderBox firstChild) {
107 108 109
    // A particular layout delegate could be called reentrantly, e.g. if it used
    // by both a parent and a child. So, we must restore the _idToChild map when
    // we return.
110
    final Map<Object, RenderBox> previousIdToChild = _idToChild;
111 112 113 114 115 116 117 118

    Set<RenderBox> debugPreviousChildrenNeedingLayout;
    assert(() {
      debugPreviousChildrenNeedingLayout = _debugChildrenNeedingLayout;
      _debugChildrenNeedingLayout = new Set<RenderBox>();
      return true;
    });

119 120 121 122 123
    try {
      _idToChild = new Map<Object, RenderBox>();
      RenderBox child = firstChild;
      while (child != null) {
        final MultiChildLayoutParentData childParentData = child.parentData;
Hixie's avatar
Hixie committed
124 125 126 127 128 129 130 131 132 133
        assert(() {
          if (childParentData.id == null) {
            throw new RenderingError(
              'The following child has no ID:\n'
              '  $child\n'
              'Every child of a RenderCustomMultiChildLayoutBox must have an ID in its parent data.'
            );
          }
          return true;
        });
134
        _idToChild[childParentData.id] = child;
135 136 137 138
        assert(() {
          _debugChildrenNeedingLayout.add(child);
          return true;
        });
139 140
        child = childParentData.nextSibling;
      }
141
      performLayout(size);
142
      assert(() {
Hixie's avatar
Hixie committed
143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
        if (_debugChildrenNeedingLayout.isNotEmpty) {
          if (_debugChildrenNeedingLayout.length > 1) {
            throw new RenderingError(
              'The $this custom multichild layout delegate forgot to lay out the following children:\n'
              '  ${_debugChildrenNeedingLayout.map(_debugDescribeChild).join("\n  ")}\n'
              'Each child must be laid out exactly once.'
            );
          } else {
            throw new RenderingError(
              'The $this custom multichild layout delegate forgot to lay out the following child:\n'
              '  ${_debugDescribeChild(_debugChildrenNeedingLayout.single)}\n'
              'Each child must be laid out exactly once.'
            );
          }
        }
        return true;
159
      });
160 161
    } finally {
      _idToChild = previousIdToChild;
162 163 164 165
      assert(() {
        _debugChildrenNeedingLayout = debugPreviousChildrenNeedingLayout;
        return true;
      });
166 167 168
    }
  }

169 170 171 172 173 174 175 176 177
  /// Override this method to return the size of this object given the
  /// incoming constraints. The size cannot reflect the instrinsic
  /// sizes of the children. If this layout has a fixed width or
  /// height the returned size can reflect that; the size will be
  /// constrained to the given constraints.
  ///
  /// By default, attempts to size the box to the biggest size
  /// possible given the constraints.
  Size getSize(BoxConstraints constraints) => constraints.biggest;
178

179 180 181 182
  /// Override this method to lay out and position all children given this
  /// widget's size. This method must call [layoutChild] for each child. It
  /// should also specify the final position of each child with [positionChild].
  void performLayout(Size size);
Hixie's avatar
Hixie committed
183

184 185 186 187 188 189 190 191 192 193
  /// 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.
  bool shouldRelayout(MultiChildLayoutDelegate oldDelegate);

  /// Override this method to include additional information in the
  /// debugging data printed by [debugDumpRenderTree] and friends.
  ///
  /// By default, returns the [runtimeType] of the class.
Hixie's avatar
Hixie committed
194
  String toString() => '$runtimeType';
195 196
}

197 198 199 200 201 202
/// Defers the layout of multiple children to a delegate.
///
/// The delegate can determine the layout constraints for each child and can
/// decide where to position each child. The delegate can also determine the
/// size of the parent, but the size of the parent cannot depend on the sizes of
/// the children.
203
class RenderCustomMultiChildLayoutBox extends RenderBox
204 205
  with ContainerRenderObjectMixin<RenderBox, MultiChildLayoutParentData>,
       RenderBoxContainerDefaultsMixin<RenderBox, MultiChildLayoutParentData> {
206 207 208 209 210 211 212 213 214
  RenderCustomMultiChildLayoutBox({
    List<RenderBox> children,
    MultiChildLayoutDelegate delegate
  }) : _delegate = delegate {
    assert(delegate != null);
    addAll(children);
  }

  void setupParentData(RenderBox child) {
215 216
    if (child.parentData is! MultiChildLayoutParentData)
      child.parentData = new MultiChildLayoutParentData();
217 218
  }

219
  /// The delegate that controls the layout of the children.
220 221 222 223 224 225
  MultiChildLayoutDelegate get delegate => _delegate;
  MultiChildLayoutDelegate _delegate;
  void set delegate (MultiChildLayoutDelegate newDelegate) {
    assert(newDelegate != null);
    if (_delegate == newDelegate)
      return;
226 227
    if (newDelegate.runtimeType != _delegate.runtimeType || newDelegate.shouldRelayout(_delegate))
      markNeedsLayout();
228 229 230 231
    _delegate = newDelegate;
  }

  Size _getSize(BoxConstraints constraints) {
Hixie's avatar
Hixie committed
232
    assert(constraints.debugAssertIsNormalized);
233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252
    return constraints.constrain(_delegate.getSize(constraints));
  }

  double getMinIntrinsicWidth(BoxConstraints constraints) {
    return _getSize(constraints).width;
  }

  double getMaxIntrinsicWidth(BoxConstraints constraints) {
    return _getSize(constraints).width;
  }

  double getMinIntrinsicHeight(BoxConstraints constraints) {
    return _getSize(constraints).height;
  }

  double getMaxIntrinsicHeight(BoxConstraints constraints) {
    return _getSize(constraints).height;
  }

  void performLayout() {
253
    size = _getSize(constraints);
254
    delegate._callPerformLayout(size, firstChild);
255 256 257 258 259 260
  }

  void paint(PaintingContext context, Offset offset) {
    defaultPaint(context, offset);
  }

Adam Barth's avatar
Adam Barth committed
261 262
  bool hitTestChildren(HitTestResult result, { Point position }) {
    return defaultHitTestChildren(result, position: position);
263 264
  }
}