view.dart 10.2 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
import 'dart:developer';
6
import 'dart:io' show Platform;
7
import 'dart:ui' as ui show Scene, SceneBuilder, Window;
8

9
import 'package:flutter/foundation.dart';
10
import 'package:flutter/gestures.dart' show MouseTrackerAnnotation;
11
import 'package:flutter/services.dart';
12
import 'package:vector_math/vector_math_64.dart';
13

14
import 'binding.dart';
15
import 'box.dart';
16
import 'debug.dart';
17 18 19
import 'layer.dart';
import 'object.dart';

20
/// The layout constraints for the root render object.
21
@immutable
22
class ViewConfiguration {
23 24 25
  /// Creates a view configuration.
  ///
  /// By default, the view has zero [size] and a [devicePixelRatio] of 1.0.
26
  const ViewConfiguration({
27 28
    this.size = Size.zero,
    this.devicePixelRatio = 1.0,
29
  });
30

31
  /// The size of the output surface.
32
  final Size size;
33

34 35 36 37 38
  /// The pixel density of the output surface.
  final double devicePixelRatio;

  /// Creates a transformation matrix that applies the [devicePixelRatio].
  Matrix4 toMatrix() {
39
    return Matrix4.diagonal3Values(devicePixelRatio, devicePixelRatio, 1.0);
40 41
  }

42
  @override
43
  String toString() => '$size at ${debugFormatDouble(devicePixelRatio)}x';
44 45
}

46
/// The root of the render tree.
47 48
///
/// The view represents the total output surface of the render tree and handles
49
/// bootstrapping the rendering pipeline. The view has a unique child
50
/// [RenderBox], which is required to fill the entire output surface.
51
class RenderView extends RenderObject with RenderObjectWithChildMixin<RenderBox> {
52 53 54
  /// Creates the root of the render tree.
  ///
  /// Typically created by the binding (e.g., [RendererBinding]).
55 56
  ///
  /// The [configuration] must not be null.
57 58
  RenderView({
    RenderBox child,
59
    @required ViewConfiguration configuration,
60
    @required ui.Window window,
61
  }) : assert(configuration != null),
62 63
       _configuration = configuration,
       _window = window {
64 65 66
    this.child = child;
  }

67
  /// The current layout size of the view.
68
  Size get size => _size;
69
  Size _size = Size.zero;
70

71
  /// The constraints used for the root layout.
72 73
  ViewConfiguration get configuration => _configuration;
  ViewConfiguration _configuration;
74 75 76 77
  /// The configuration is initially set by the `configuration` argument
  /// passed to the constructor.
  ///
  /// Always call [scheduleInitialFrame] before changing the configuration.
78
  set configuration(ViewConfiguration value) {
79
    assert(value != null);
80
    if (configuration == value)
81
      return;
82
    _configuration = value;
83 84
    replaceRootLayer(_updateMatricesAndCreateNewRootLayer());
    assert(_rootTransform != null);
85 86 87
    markNeedsLayout();
  }

88
  final ui.Window _window;
89

90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
  /// Whether Flutter should automatically compute the desired system UI.
  ///
  /// When this setting is enabled, Flutter will hit-test the layer tree at the
  /// top and bottom of the screen on each frame looking for an
  /// [AnnotatedRegionLayer] with an instance of a [SystemUiOverlayStyle]. The
  /// hit-test result from the top of the screen provides the status bar settings
  /// and the hit-test result from the bottom of the screen provides the system
  /// nav bar settings.
  ///
  /// Setting this to false does not cause previous automatic adjustments to be
  /// reset, nor does setting it to true cause the app to update immediately.
  ///
  /// If you want to imperatively set the system ui style instead, it is
  /// recommended that [automaticSystemUiAdjustment] is set to false.
  ///
  /// See also:
  ///
107 108
  ///  * [AnnotatedRegion], for placing [SystemUiOverlayStyle] in the layer tree.
  ///  * [SystemChrome.setSystemUIOverlayStyle], for imperatively setting the system ui style.
109 110
  bool automaticSystemUiAdjustment = true;

111
  /// Bootstrap the rendering pipeline by scheduling the first frame.
112 113 114 115
  ///
  /// This should only be called once, and must be called before changing
  /// [configuration]. It is typically called immediately after calling the
  /// constructor.
116
  void scheduleInitialFrame() {
117
    assert(owner != null);
118
    assert(_rootTransform == null);
119
    scheduleInitialLayout();
120 121
    scheduleInitialPaint(_updateMatricesAndCreateNewRootLayer());
    assert(_rootTransform != null);
122
    owner.requestVisualUpdate();
123 124
  }

125 126 127 128
  Matrix4 _rootTransform;

  Layer _updateMatricesAndCreateNewRootLayer() {
    _rootTransform = configuration.toMatrix();
129
    final ContainerLayer rootLayer = TransformLayer(transform: _rootTransform);
130 131 132 133 134
    rootLayer.attach(this);
    assert(_rootTransform != null);
    return rootLayer;
  }

135 136
  // We never call layout() on this class, so this should never get
  // checked. (This class is laid out using scheduleInitialLayout().)
137
  @override
138
  void debugAssertDoesMeetConstraints() { assert(false); }
139

140
  @override
141 142 143 144
  void performResize() {
    assert(false);
  }

145
  @override
146
  void performLayout() {
147
    assert(_rootTransform != null);
148
    _size = configuration.size;
149
    assert(_size.isFinite);
150 151

    if (child != null)
152
      child.layout(BoxConstraints.tight(_size));
153 154
  }

155
  @override
156 157 158 159
  void rotate({ int oldAngle, int newAngle, Duration time }) {
    assert(false); // nobody tells the screen to rotate, the whole rotate() dance is started from our performResize()
  }

160 161 162 163 164 165
  /// Determines the set of render objects located at the given position.
  ///
  /// Returns true if the given point is contained in this render object or one
  /// of its descendants. Adds any render objects that contain the point to the
  /// given hit test result.
  ///
166 167 168 169
  /// The [position] argument is in the coordinate system of the render view,
  /// which is to say, in logical pixels. This is not necessarily the same
  /// coordinate system as that expected by the root [Layer], which will
  /// normally be in physical (device) pixels.
170
  bool hitTest(HitTestResult result, { Offset position }) {
171
    if (child != null)
172
      child.hitTest(BoxHitTestResult.wrap(result), position: position);
173
    result.add(HitTestEntry(this));
174 175 176
    return true;
  }

177 178 179 180 181 182 183 184 185 186 187 188 189
  /// Determines the set of mouse tracker annotations at the given position.
  ///
  /// See also:
  ///
  /// * [Layer.findAll], which is used by this method to find all
  ///   [AnnotatedRegionLayer]s annotated for mouse tracking.
  Iterable<MouseTrackerAnnotation> hitTestMouseTrackers(Offset position) {
    // Layer hit testing is done using device pixels, so we have to convert
    // the logical coordinates of the event location back to device pixels
    // here.
    return layer.findAll<MouseTrackerAnnotation>(position * configuration.devicePixelRatio);
  }

190
  @override
191
  bool get isRepaintBoundary => true;
Hixie's avatar
Hixie committed
192

193
  @override
194 195
  void paint(PaintingContext context, Offset offset) {
    if (child != null)
Adam Barth's avatar
Adam Barth committed
196
      context.paintChild(child, offset);
197 198
  }

199 200 201 202 203 204 205
  @override
  void applyPaintTransform(RenderBox child, Matrix4 transform) {
    assert(_rootTransform != null);
    transform.multiply(_rootTransform);
    super.applyPaintTransform(child, transform);
  }

206
  /// Uploads the composited layer tree to the engine.
207 208
  ///
  /// Actually causes the output of the rendering pipeline to appear on screen.
209
  void compositeFrame() {
210
    Timeline.startSync('Compositing', arguments: timelineWhitelistArguments);
211
    try {
212
      final ui.SceneBuilder builder = ui.SceneBuilder();
213
      final ui.Scene scene = layer.buildScene(builder);
214 215
      if (automaticSystemUiAdjustment)
        _updateSystemChrome();
216
      _window.render(scene);
217
      scene.dispose();
218
      assert(() {
219
        if (debugRepaintRainbowEnabled || debugRepaintTextRainbowEnabled)
220
          debugCurrentRepaintColor = debugCurrentRepaintColor.withHue((debugCurrentRepaintColor.hue + 2.0) % 360.0);
221
        return true;
222
      }());
223
    } finally {
224
      Timeline.finishSync();
225 226 227
    }
  }

228 229
  void _updateSystemChrome() {
    final Rect bounds = paintBounds;
230 231
    final Offset top = Offset(bounds.center.dx, _window.padding.top / _window.devicePixelRatio);
    final Offset bottom = Offset(bounds.center.dx, bounds.center.dy - _window.padding.bottom / _window.devicePixelRatio);
232 233
    final SystemUiOverlayStyle upperOverlayStyle = layer.find<SystemUiOverlayStyle>(top);
    // Only android has a customizable system navigation bar.
234
    SystemUiOverlayStyle lowerOverlayStyle;
235 236 237 238 239 240 241 242 243 244
    switch (defaultTargetPlatform) {
      case TargetPlatform.android:
        lowerOverlayStyle = layer.find<SystemUiOverlayStyle>(bottom);
        break;
      case TargetPlatform.iOS:
      case TargetPlatform.fuchsia:
        break;
    }
    // If there are no overlay styles in the UI don't bother updating.
    if (upperOverlayStyle != null || lowerOverlayStyle != null) {
245
      final SystemUiOverlayStyle overlayStyle = SystemUiOverlayStyle(
246 247 248 249 250 251 252 253 254 255 256
        statusBarBrightness: upperOverlayStyle?.statusBarBrightness,
        statusBarIconBrightness: upperOverlayStyle?.statusBarIconBrightness,
        statusBarColor: upperOverlayStyle?.statusBarColor,
        systemNavigationBarColor: lowerOverlayStyle?.systemNavigationBarColor,
        systemNavigationBarDividerColor: lowerOverlayStyle?.systemNavigationBarDividerColor,
        systemNavigationBarIconBrightness: lowerOverlayStyle?.systemNavigationBarIconBrightness,
      );
      SystemChrome.setSystemUIOverlayStyle(overlayStyle);
    }
  }

257
  @override
258
  Rect get paintBounds => Offset.zero & (size * configuration.devicePixelRatio);
259 260

  @override
261 262 263 264
  Rect get semanticBounds {
    assert(_rootTransform != null);
    return MatrixUtils.transformRect(_rootTransform, Offset.zero & size);
  }
Hixie's avatar
Hixie committed
265

266
  @override
267
  // ignore: MUST_CALL_SUPER
268
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
269 270 271
    // call to ${super.debugFillProperties(description)} is omitted because the
    // root superclasses don't include any interesting information for this
    // class
272
    assert(() {
273
      properties.add(DiagnosticsNode.message('debug mode enabled - ${kIsWeb ? 'Web' :  Platform.operatingSystem}'));
274
      return true;
275
    }());
276 277
    properties.add(DiagnosticsProperty<Size>('window size', _window.physicalSize, tooltip: 'in physical pixels'));
    properties.add(DoubleProperty('device pixel ratio', _window.devicePixelRatio, tooltip: 'physical pixels per logical pixel'));
278
    properties.add(DiagnosticsProperty<ViewConfiguration>('configuration', configuration, tooltip: 'in logical pixels'));
279
    if (_window.semanticsEnabled)
280
      properties.add(DiagnosticsNode.message('semantics enabled'));
281
  }
282
}