overlay.dart 18 KB
Newer Older
1 2 3 4
// 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.

5 6
import 'dart:collection';

7
import 'package:meta/meta.dart';
8
import 'package:flutter/rendering.dart';
9

10
import 'basic.dart';
11
import 'debug.dart';
12 13
import 'framework.dart';

14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
/// A place in an [Overlay] that can contain a widget.
///
/// Overlay entries are inserted into an [Overlay] using the
/// [OverlayState.insert] or [OverlayState.insertAll] functions. To find the
/// closest enclosing overlay for a given [BuildContext], use the [Overlay.of]
/// function.
///
/// An overlay entry can be in at most one overlay at a time. To remove an entry
/// from its overlay, call the [remove] function on the overlay entry.
///
/// Because an [Overlay] uses a [Stack] layout, overlay entries can use
/// [Positioned] and [AnimatedPositioned] to position themselves within the
/// overlay.
///
/// For example, [Draggable] uses an [OverlayEntry] to show the drag avatar that
/// follows the user's finger across the screen after the drag begins. Using the
/// overlay to display the drag avatar lets the avatar float over the other
/// widgets in the app. As the user's finger moves, draggable calls
/// [markNeedsBuild] on the overlay entry to cause it to rebuild. It its build,
/// the entry includes a [Positioned] with its top and left property set to
/// position the drag avatar near the user's finger. When the drag is over,
/// [Draggable] removes the entry from the overlay to remove the drag avatar
/// from view.
///
38 39 40 41 42 43 44 45
/// By default, if there is an entirely [opaque] entry over this one, then this
/// one will not be included in the widget tree (in particular, stateful widgets
/// within the overlay entry will not be instantiated). To ensure that your
/// overlay entry is still built even if it is not visible, set [maintainState]
/// to true. This is more expensive, so should be done with care. In particular,
/// if widgets in an overlay entry with [maintainState] set to true repeatedly
/// call [setState], the user's battery will be drained unnecessarily.
///
46 47 48 49 50 51
/// See also:
///
///  * [Overlay]
///  * [OverlayState]
///  * [WidgetsApp]
///  * [MaterialApp]
52
class OverlayEntry {
53 54 55 56 57
  /// Creates an overlay entry.
  ///
  /// To insert the entry into an [Overlay], first find the overlay using
  /// [Overlay.of] and then call [OverlayState.insert]. To remove the entry,
  /// call [remove] on the overlay entry itself.
58
  OverlayEntry({
59
    @required this.builder,
60 61 62
    bool opaque: false,
    bool maintainState: false,
  }) : _opaque = opaque, _maintainState = maintainState {
63
    assert(builder != null);
64 65
    assert(opaque != null);
    assert(maintainState != null);
66
  }
67

68 69
  /// This entry will include the widget built by this builder in the overlay at
  /// the entry's position.
70
  ///
71
  /// To cause this builder to be called again, call [markNeedsBuild] on this
72
  /// overlay entry.
73
  final WidgetBuilder builder;
74

75 76
  /// Whether this entry occludes the entire overlay.
  ///
77 78 79
  /// If an entry claims to be opaque, then, for efficiency, the overlay will
  /// skip building entries below that entry unless they have [maintainState]
  /// set.
80 81
  bool get opaque => _opaque;
  bool _opaque;
82
  set opaque (bool value) {
Adam Barth's avatar
Adam Barth committed
83
    if (_opaque == value)
84
      return;
85
    _opaque = value;
86
    assert(_overlay != null);
87
    _overlay._didChangeEntryOpacity();
88 89
  }

90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
  /// Whether this entry must be included in the tree even if there is a fully
  /// [opaque] entry above it.
  ///
  /// By default, if there is an entirely [opaque] entry over this one, then this
  /// one will not be included in the widget tree (in particular, stateful widgets
  /// within the overlay entry will not be instantiated). To ensure that your
  /// overlay entry is still built even if it is not visible, set [maintainState]
  /// to true. This is more expensive, so should be done with care. In particular,
  /// if widgets in an overlay entry with [maintainState] set to true repeatedly
  /// call [setState], the user's battery will be drained unnecessarily.
  ///
  /// This is used by the [Navigator] and [Route] objects to ensure that routes
  /// are kept around even when in the background, so that [Future]s promised
  /// from subsequent routes will be handled properly when they complete.
  bool get maintainState => _maintainState;
  bool _maintainState;
  set maintainState (bool value) {
    assert(_maintainState != null);
    if (_maintainState == value)
      return;
    _maintainState = value;
    assert(_overlay != null);
    _overlay._didChangeEntryOpacity();
  }

115
  OverlayState _overlay;
116
  final GlobalKey<_OverlayEntryState> _key = new GlobalKey<_OverlayEntryState>();
117

118
  /// Remove this entry from the overlay.
119
  void remove() {
120 121
    _overlay?._remove(this);
    _overlay = null;
122
  }
123

124 125 126
  /// Cause this entry to rebuild during the next pipeline flush.
  ///
  /// You need to call this function if the output of [builder] has changed.
127
  void markNeedsBuild() {
128
    _key.currentState?._markNeedsBuild();
129
  }
130

131
  @override
132
  String toString() => '$runtimeType@$hashCode(opaque: $opaque; maintainState: $maintainState)';
133 134
}

135
class _OverlayEntry extends StatefulWidget {
136 137 138
  _OverlayEntry(OverlayEntry entry) : entry = entry, super(key: entry._key) {
    assert(entry != null);
  }
139

140
  final OverlayEntry entry;
141 142

  @override
143 144
  _OverlayEntryState createState() => new _OverlayEntryState();
}
145

146
class _OverlayEntryState extends State<_OverlayEntry> {
147
  @override
148 149 150
  Widget build(BuildContext context) {
    return config.entry.builder(context);
  }
151 152 153 154

  void _markNeedsBuild() {
    setState(() { /* the state that changed is in the builder */ });
  }
155 156
}

157
/// A [Stack] of entries that can be managed independently.
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173
///
/// Overlays let independent child widgets "float" visual elements on top of
/// other widgets by inserting them into the overlay's [Stack]. The overlay lets
/// each of these widgets manage their participation in the overlay using
/// [OverlayEntry] objects.
///
/// Although you can create an [Overlay] directly, it's most common to use the
/// overlay created by the [Navigator] in a [WidgetsApp] or a [MaterialApp]. The
/// navigator uses its overlay to manage the visual appearance of its routes.
///
/// See also:
///
///  * [OverlayEntry]
///  * [OverlayState]
///  * [WidgetsApp]
///  * [MaterialApp]
174
class Overlay extends StatefulWidget {
175 176 177 178 179 180 181 182
  /// Creates an overlay.
  ///
  /// The initial entries will be inserted into the overlay when its associated
  /// [OverlayState] is initialized.
  ///
  /// Rather than creating an overlay, consider using the overlay that has
  /// already been created by the [WidgetsApp] or the [MaterialApp] for this
  /// application.
183 184
  Overlay({
    Key key,
Adam Barth's avatar
Adam Barth committed
185 186 187 188
    this.initialEntries: const <OverlayEntry>[]
  }) : super(key: key) {
    assert(initialEntries != null);
  }
189

190
  /// The entries to include in the overlay initially.
191 192
  final List<OverlayEntry> initialEntries;

193
  /// The state from the closest instance of this class that encloses the given context.
194 195 196 197 198 199 200 201 202 203 204 205 206
  ///
  /// In checked mode, if the [debugRequiredFor] argument is provided then this
  /// function will assert that an overlay was found and will throw an exception
  /// if not. The exception attempts to explain that the calling [Widget] (the
  /// one given by the [debugRequiredFor] argument) needs an [Overlay] to be
  /// present to function.
  static OverlayState of(BuildContext context, { Widget debugRequiredFor }) {
    OverlayState result = context.ancestorStateOfType(const TypeMatcher<OverlayState>());
    assert(() {
      if (debugRequiredFor != null && result == null) {
        String additional = context.widget != debugRequiredFor
          ? '\nThe context from which that widget was searching for an overlay was:\n  $context'
          : '';
207
        throw new FlutterError(
208 209 210 211 212 213 214 215 216 217 218 219
          'No Overlay widget found.\n'
          '${debugRequiredFor.runtimeType} widgets require an Overlay widget ancestor for correct operation.\n'
          'The most common way to add an Overlay to an application is to include a MaterialApp or Navigator widget in the runApp() call.\n'
          'The specific widget that failed to find an overlay was:\n'
          '  $debugRequiredFor'
          '$additional'
        );
      }
      return true;
    });
    return result;
  }
Hixie's avatar
Hixie committed
220

221
  @override
222 223 224
  OverlayState createState() => new OverlayState();
}

225
/// The current state of an [Overlay].
226 227 228
///
/// Used to insert [OverlayEntry]s into the overlay using the [insert] and
/// [insertAll] functions.
229 230 231
class OverlayState extends State<Overlay> {
  final List<OverlayEntry> _entries = new List<OverlayEntry>();

232
  @override
233 234
  void initState() {
    super.initState();
235
    insertAll(config.initialEntries);
236 237
  }

238 239 240 241
  /// Insert the given entry into the overlay.
  ///
  /// If [above] is non-null, the entry is inserted just above [above].
  /// Otherwise, the entry is inserted on top.
242
  void insert(OverlayEntry entry, { OverlayEntry above }) {
243 244 245
    assert(entry._overlay == null);
    assert(above == null || (above._overlay == this && _entries.contains(above)));
    entry._overlay = this;
246 247 248 249 250 251
    setState(() {
      int index = above == null ? _entries.length : _entries.indexOf(above) + 1;
      _entries.insert(index, entry);
    });
  }

252 253 254 255
  /// Insert all the entries in the given iterable.
  ///
  /// If [above] is non-null, the entries are inserted just above [above].
  /// Otherwise, the entries are inserted on top.
256
  void insertAll(Iterable<OverlayEntry> entries, { OverlayEntry above }) {
257
    assert(above == null || (above._overlay == this && _entries.contains(above)));
Adam Barth's avatar
Adam Barth committed
258 259
    if (entries.isEmpty)
      return;
260
    for (OverlayEntry entry in entries) {
261 262
      assert(entry._overlay == null);
      entry._overlay = this;
263 264 265 266 267 268 269
    }
    setState(() {
      int index = above == null ? _entries.length : _entries.indexOf(above) + 1;
      _entries.insertAll(index, entries);
    });
  }

270
  void _remove(OverlayEntry entry) {
271 272 273
    _entries.remove(entry);
    if (mounted)
      setState(() { /* entry was removed */ });
274 275
  }

276 277
  /// (DEBUG ONLY) Check whether a given entry is visible (i.e., not behind an
  /// opaque entry).
278
  ///
279 280 281
  /// This is an O(N) algorithm, and should not be necessary except for debug
  /// asserts. To avoid people depending on it, this function is implemented
  /// only in checked mode.
282 283 284 285 286 287 288 289 290 291
  bool debugIsVisible(OverlayEntry entry) {
    bool result = false;
    assert(_entries.contains(entry));
    assert(() {
      for (int i = _entries.length - 1; i > 0; i -= 1) {
        OverlayEntry candidate = _entries[i];
        if (candidate == entry) {
          result = true;
          break;
        }
Hixie's avatar
Hixie committed
292
        if (candidate.opaque)
293 294 295 296 297 298 299
          break;
      }
      return true;
    });
    return result;
  }

300 301 302 303 304 305 306
  void _didChangeEntryOpacity() {
    setState(() {
      // We use the opacity of the entry in our build function, which means we
      // our state has changed.
    });
  }

307
  @override
308
  Widget build(BuildContext context) {
309 310 311 312 313 314 315
    // These lists are filled backwards. For the offstage children that
    // does not matter since they aren't rendered, but for the onstage
    // children we reverse the list below before adding it to the tree.
    final List<Widget> onstageChildren = <Widget>[];
    final List<Widget> offstageChildren = <Widget>[];
    bool onstage = true;
    for (int i = _entries.length - 1; i >= 0; i -= 1) {
316
      OverlayEntry entry = _entries[i];
317 318 319 320 321 322 323
      if (onstage) {
        onstageChildren.add(new _OverlayEntry(entry));
        if (entry.opaque)
          onstage = false;
      } else if (entry.maintainState) {
        offstageChildren.add(new _OverlayEntry(entry));
      }
324
    }
325 326 327 328
    return new _Theatre(
      onstage: new Stack(children: onstageChildren.reversed.toList(growable: false)),
      offstage: offstageChildren,
    );
329
  }
330

331
  @override
332 333 334 335
  void debugFillDescription(List<String> description) {
    super.debugFillDescription(description);
    description.add('entries: $_entries');
  }
336
}
337 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 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547

/// A widget that has one [onstage] child which is visible, and one or more
/// [offstage] widgets which are kept alive, and are built, but are not laid out
/// or painted.
///
/// The onstage widget must be a Stack.
///
/// For convenience, it is legal to use [Positioned] widgets around the offstage
/// widgets.
class _Theatre extends RenderObjectWidget {
  _Theatre({
    this.onstage,
    this.offstage,
  }) {
    assert(offstage != null);
    assert(!offstage.any((Widget child) => child == null));
  }

  final Stack onstage;

  final List<Widget> offstage;

  @override
  _TheatreElement createElement() => new _TheatreElement(this);

  @override
  _RenderTheatre createRenderObject(BuildContext context) => new _RenderTheatre();
}

class _TheatreElement extends RenderObjectElement {
  _TheatreElement(_Theatre widget) : super(widget) {
    assert(!debugChildrenHaveDuplicateKeys(widget, widget.offstage));
  }

  @override
  _Theatre get widget => super.widget;

  @override
  _RenderTheatre get renderObject => super.renderObject;

  Element _onstage;
  static final Object _onstageSlot = new Object();

  List<Element> _offstage;
  final Set<Element> _detachedOffstageChildren = new HashSet<Element>();

  @override
  void insertChildRenderObject(RenderBox child, dynamic slot) {
    if (slot == _onstageSlot) {
      assert(child is RenderStack);
      renderObject.child = child;
    } else {
      assert(slot == null || slot is Element);
      renderObject.insert(child, after: slot?.renderObject);
    }
  }

  @override
  void moveChildRenderObject(RenderBox child, dynamic slot) {
    if (slot == _onstageSlot) {
      renderObject.remove(child);
      assert(child is RenderStack);
      renderObject.child = child;
    } else {
      assert(slot == null || slot is Element);
      if (renderObject.child == child) {
        renderObject.child = null;
        renderObject.insert(child, after: slot?.renderObject);
      } else {
        renderObject.move(child, after: slot?.renderObject);
      }
    }
  }

  @override
  void removeChildRenderObject(RenderBox child) {
    if (renderObject.child == child) {
      renderObject.child = null;
    } else {
      renderObject.remove(child);
    }
  }

  @override
  void visitChildren(ElementVisitor visitor) {
    if (_onstage != null)
      visitor(_onstage);
    for (Element child in _offstage) {
      if (!_detachedOffstageChildren.contains(child))
        visitor(child);
    }
  }

  @override
  void visitChildrenForSemantics(ElementVisitor visitor) {
    if (_onstage != null)
      visitor(_onstage);
  }

  @override
  bool detachChild(Element child) {
    if (child == _onstage) {
      _onstage = null;
    } else {
      _detachedOffstageChildren.add(child);
    }
    deactivateChild(child);
    return true;
  }

  @override
  void mount(Element parent, dynamic newSlot) {
    super.mount(parent, newSlot);
    _onstage = updateChild(_onstage, widget.onstage, _onstageSlot);
    _offstage = new List<Element>(widget.offstage.length);
    Element previousChild;
    for (int i = 0; i < _offstage.length; i += 1) {
      final Element newChild = inflateWidget(widget.offstage[i], previousChild);
      _offstage[i] = newChild;
      previousChild = newChild;
    }
  }

  @override
  void update(_Theatre newWidget) {
    super.update(newWidget);
    assert(widget == newWidget);
    _onstage = updateChild(_onstage, widget.onstage, _onstageSlot);
    _offstage = updateChildren(_offstage, widget.offstage, detachedChildren: _detachedOffstageChildren);
    _detachedOffstageChildren.clear();
  }
}

// A render object which lays out and paints one subtree while keeping a list
// of other subtrees alive but not laid out or painted (the "zombie" children).
//
// The subtree that is laid out and painted must be a [RenderStack].
//
// This class uses [StackParentData] objects for its parent data so that the
// children of its primary subtree's stack can be moved to this object's list
// of zombie children without changing their parent data objects.
class _RenderTheatre extends RenderBox
  with RenderObjectWithChildMixin<RenderStack>, RenderProxyBoxMixin,
       ContainerRenderObjectMixin<RenderBox, StackParentData> {

  @override
  void setupParentData(RenderObject child) {
    if (child.parentData is! StackParentData)
      child.parentData = new StackParentData();
  }

  // Because both RenderObjectWithChildMixin and ContainerRenderObjectMixin
  // define redepthChildren, visitChildren and debugDescribeChildren and don't
  // call super, we have to define them again here to make sure the work of both
  // is done.
  //
  // We chose to put ContainerRenderObjectMixin last in the inheritance chain so
  // that we can call super to hit its more complex definitions of
  // redepthChildren and visitChildren, and then duplicate the more trivial
  // definition from RenderObjectWithChildMixin inline in our version here.
  //
  // This code duplication is suboptimal.
  // TODO(ianh): Replace this with a better solution once https://github.com/dart-lang/sdk/issues/27100 is fixed
  //
  // For debugDescribeChildren we just roll our own because otherwise the line
  // drawings won't really work as well.

  @override
  void redepthChildren() {
    if (child != null)
      redepthChild(child);
    super.redepthChildren();
  }

  @override
  void visitChildren(RenderObjectVisitor visitor) {
    if (child != null)
      visitor(child);
    super.visitChildren(visitor);
  }

  @override
  String debugDescribeChildren(String prefix) {
    String result = '';
    if (child != null)
      result += '$prefix \u2502\n${child.toStringDeep('$prefix \u251C\u2500onstage: ', '$prefix \u254E')}';
    if (firstChild != null) {
      RenderBox child = firstChild;
      int count = 1;
      while (child != lastChild) {
        result += '${child.toStringDeep("$prefix \u254E\u254Coffstage $count: ", "$prefix \u254E")}';
        count += 1;
        final StackParentData childParentData = child.parentData;
        child = childParentData.nextSibling;
      }
      if (child != null) {
        assert(child == lastChild);
        result += '${child.toStringDeep("$prefix \u2514\u254Coffstage $count: ", "$prefix  ")}';
      }
    } else {
      result += '$prefix \u2514\u254Cno offstage children';
    }
    return result;
  }

  @override
  void visitChildrenForSemantics(RenderObjectVisitor visitor) {
    if (child != null)
      visitor(child);
  }
}