view.dart 12.4 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4
// 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, FlutterView;
8

9
import 'package:flutter/foundation.dart';
10
import 'package:flutter/services.dart';
11

12
import 'binding.dart';
13
import 'box.dart';
14
import 'debug.dart';
15 16 17
import 'layer.dart';
import 'object.dart';

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

29
  /// The size of the output surface.
30
  final Size size;
31

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

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

40 41
  @override
  bool operator ==(Object other) {
42
    if (other.runtimeType != runtimeType) {
43
      return false;
44
    }
45 46 47 48 49 50
    return other is ViewConfiguration
        && other.size == size
        && other.devicePixelRatio == devicePixelRatio;
  }

  @override
51
  int get hashCode => Object.hash(size, devicePixelRatio);
52

53
  @override
54
  String toString() => '$size at ${debugFormatDouble(devicePixelRatio)}x';
55 56
}

57
/// The root of the render tree.
58 59
///
/// The view represents the total output surface of the render tree and handles
60
/// bootstrapping the rendering pipeline. The view has a unique child
61
/// [RenderBox], which is required to fill the entire output surface.
62
class RenderView extends RenderObject with RenderObjectWithChildMixin<RenderBox> {
63 64 65
  /// Creates the root of the render tree.
  ///
  /// Typically created by the binding (e.g., [RendererBinding]).
66 67
  ///
  /// The [configuration] must not be null.
68
  RenderView({
69 70
    RenderBox? child,
    required ViewConfiguration configuration,
71
    required ui.FlutterView window,
72
  }) : assert(configuration != null),
73 74
       _configuration = configuration,
       _window = window {
75 76 77
    this.child = child;
  }

78
  /// The current layout size of the view.
79
  Size get size => _size;
80
  Size _size = Size.zero;
81

82
  /// The constraints used for the root layout.
83 84
  ViewConfiguration get configuration => _configuration;
  ViewConfiguration _configuration;
85

86 87 88
  /// The configuration is initially set by the `configuration` argument
  /// passed to the constructor.
  ///
89
  /// Always call [prepareInitialFrame] before changing the configuration.
90
  set configuration(ViewConfiguration value) {
91
    assert(value != null);
92
    if (configuration == value) {
93
      return;
94
    }
95
    final ViewConfiguration oldConfiguration = _configuration;
96
    _configuration = value;
97 98 99
    if (oldConfiguration.toMatrix() != _configuration.toMatrix()) {
      replaceRootLayer(_updateMatricesAndCreateNewRootLayer());
    }
100
    assert(_rootTransform != null);
101 102 103
    markNeedsLayout();
  }

104
  final ui.FlutterView _window;
105

106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
  /// 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:
  ///
123 124
  ///  * [AnnotatedRegion], for placing [SystemUiOverlayStyle] in the layer tree.
  ///  * [SystemChrome.setSystemUIOverlayStyle], for imperatively setting the system ui style.
125 126
  bool automaticSystemUiAdjustment = true;

127 128
  /// Bootstrap the rendering pipeline by preparing the first frame.
  ///
129 130 131
  /// This should only be called once, and must be called before changing
  /// [configuration]. It is typically called immediately after calling the
  /// constructor.
132 133 134 135
  ///
  /// This does not actually schedule the first frame. Call
  /// [PipelineOwner.requestVisualUpdate] on [owner] to do that.
  void prepareInitialFrame() {
136
    assert(owner != null);
137
    assert(_rootTransform == null);
138
    scheduleInitialLayout();
139 140
    scheduleInitialPaint(_updateMatricesAndCreateNewRootLayer());
    assert(_rootTransform != null);
141 142
  }

143
  Matrix4? _rootTransform;
144

145
  TransformLayer _updateMatricesAndCreateNewRootLayer() {
146
    _rootTransform = configuration.toMatrix();
147
    final TransformLayer rootLayer = TransformLayer(transform: _rootTransform);
148 149 150 151 152
    rootLayer.attach(this);
    assert(_rootTransform != null);
    return rootLayer;
  }

153 154
  // We never call layout() on this class, so this should never get
  // checked. (This class is laid out using scheduleInitialLayout().)
155
  @override
156
  void debugAssertDoesMeetConstraints() { assert(false); }
157

158
  @override
159 160 161 162
  void performResize() {
    assert(false);
  }

163
  @override
164
  void performLayout() {
165
    assert(_rootTransform != null);
166
    _size = configuration.size;
167
    assert(_size.isFinite);
168

169
    if (child != null) {
170
      child!.layout(BoxConstraints.tight(_size));
171
    }
172 173
  }

174 175 176 177 178 179
  /// 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.
  ///
180 181 182 183
  /// 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.
184
  bool hitTest(HitTestResult result, { required Offset position }) {
185
    if (child != null) {
186
      child!.hitTest(BoxHitTestResult.wrap(result), position: position);
187
    }
188
    result.add(HitTestEntry(this));
189 190 191
    return true;
  }

192 193 194 195
  /// Determines the set of mouse tracker annotations at the given position.
  ///
  /// See also:
  ///
196 197
  ///  * [Layer.findAllAnnotations], which is used by this method to find all
  ///    [AnnotatedRegionLayer]s annotated for mouse tracking.
198
  HitTestResult hitTestMouseTrackers(Offset position) {
199
    assert(position != null);
200
    final BoxHitTestResult result = BoxHitTestResult();
201 202
    hitTest(result, position: position);
    return result;
203 204
  }

205
  @override
206
  bool get isRepaintBoundary => true;
Hixie's avatar
Hixie committed
207

208
  @override
209
  void paint(PaintingContext context, Offset offset) {
210
    if (child != null) {
211
      context.paintChild(child!, offset);
212
    }
213 214
  }

215 216 217
  @override
  void applyPaintTransform(RenderBox child, Matrix4 transform) {
    assert(_rootTransform != null);
218
    transform.multiply(_rootTransform!);
219 220 221
    super.applyPaintTransform(child, transform);
  }

222
  /// Uploads the composited layer tree to the engine.
223 224
  ///
  /// Actually causes the output of the rendering pipeline to appear on screen.
225
  void compositeFrame() {
Ian Hickson's avatar
Ian Hickson committed
226
    if (!kReleaseMode) {
227
      Timeline.startSync('COMPOSITING');
Ian Hickson's avatar
Ian Hickson committed
228
    }
229
    try {
230
      final ui.SceneBuilder builder = ui.SceneBuilder();
231
      final ui.Scene scene = layer!.buildScene(builder);
232
      if (automaticSystemUiAdjustment) {
233
        _updateSystemChrome();
234
      }
235
      _window.render(scene);
236
      scene.dispose();
237
      assert(() {
238
        if (debugRepaintRainbowEnabled || debugRepaintTextRainbowEnabled) {
239
          debugCurrentRepaintColor = debugCurrentRepaintColor.withHue((debugCurrentRepaintColor.hue + 2.0) % 360.0);
240
        }
241
        return true;
242
      }());
243
    } finally {
Ian Hickson's avatar
Ian Hickson committed
244 245 246
      if (!kReleaseMode) {
        Timeline.finishSync();
      }
247 248 249
    }
  }

250
  void _updateSystemChrome() {
251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271
    // Take overlay style from the place where a system status bar and system
    // navigation bar are placed to update system style overlay.
    // The center of the system navigation bar and the center of the status bar
    // are used to get SystemUiOverlayStyle's to update system overlay appearance.
    //
    //         Horizontal center of the screen
    //                 V
    //    ++++++++++++++++++++++++++
    //    |                        |
    //    |    System status bar   |  <- Vertical center of the status bar
    //    |                        |
    //    ++++++++++++++++++++++++++
    //    |                        |
    //    |        Content         |
    //    ~                        ~
    //    |                        |
    //    ++++++++++++++++++++++++++
    //    |                        |
    //    |  System navigation bar | <- Vertical center of the navigation bar
    //    |                        |
    //    ++++++++++++++++++++++++++ <- bounds.bottom
272
    final Rect bounds = paintBounds;
273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293
    // Center of the status bar
    final Offset top = Offset(
      // Horizontal center of the screen
      bounds.center.dx,
      // The vertical center of the system status bar. The system status bar
      // height is kept as top window padding.
      _window.padding.top / 2.0,
    );
    // Center of the navigation bar
    final Offset bottom = Offset(
      // Horizontal center of the screen
      bounds.center.dx,
      // Vertical center of the system navigation bar. The system navigation bar
      // height is kept as bottom window padding. The "1" needs to be subtracted
      // from the bottom because available pixels are in (0..bottom) range.
      // I.e. for a device with 1920 height, bound.bottom is 1920, but the most
      // bottom drawn pixel is at 1919 position.
      bounds.bottom - 1.0 - _window.padding.bottom / 2.0,
    );
    final SystemUiOverlayStyle? upperOverlayStyle = layer!.find<SystemUiOverlayStyle>(top);
    // Only android has a customizable system navigation bar.
294
    SystemUiOverlayStyle? lowerOverlayStyle;
295 296
    switch (defaultTargetPlatform) {
      case TargetPlatform.android:
297
        lowerOverlayStyle = layer!.find<SystemUiOverlayStyle>(bottom);
298 299
        break;
      case TargetPlatform.fuchsia:
300
      case TargetPlatform.iOS:
301
      case TargetPlatform.linux:
302
      case TargetPlatform.macOS:
303
      case TargetPlatform.windows:
304 305 306 307
        break;
    }
    // If there are no overlay styles in the UI don't bother updating.
    if (upperOverlayStyle != null || lowerOverlayStyle != null) {
308
      final SystemUiOverlayStyle overlayStyle = SystemUiOverlayStyle(
309 310 311
        statusBarBrightness: upperOverlayStyle?.statusBarBrightness,
        statusBarIconBrightness: upperOverlayStyle?.statusBarIconBrightness,
        statusBarColor: upperOverlayStyle?.statusBarColor,
312
        systemStatusBarContrastEnforced: upperOverlayStyle?.systemStatusBarContrastEnforced,
313 314 315
        systemNavigationBarColor: lowerOverlayStyle?.systemNavigationBarColor,
        systemNavigationBarDividerColor: lowerOverlayStyle?.systemNavigationBarDividerColor,
        systemNavigationBarIconBrightness: lowerOverlayStyle?.systemNavigationBarIconBrightness,
316
        systemNavigationBarContrastEnforced: lowerOverlayStyle?.systemNavigationBarContrastEnforced,
317 318 319 320 321
      );
      SystemChrome.setSystemUIOverlayStyle(overlayStyle);
    }
  }

322
  @override
323
  Rect get paintBounds => Offset.zero & (size * configuration.devicePixelRatio);
324 325

  @override
326 327
  Rect get semanticBounds {
    assert(_rootTransform != null);
328
    return MatrixUtils.transformRect(_rootTransform!, Offset.zero & size);
329
  }
Hixie's avatar
Hixie committed
330

331
  @override
332
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
333 334 335
    // call to ${super.debugFillProperties(description)} is omitted because the
    // root superclasses don't include any interesting information for this
    // class
336
    assert(() {
337
      properties.add(DiagnosticsNode.message('debug mode enabled - ${kIsWeb ? 'Web' :  Platform.operatingSystem}'));
338
      return true;
339
    }());
340 341
    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'));
342
    properties.add(DiagnosticsProperty<ViewConfiguration>('configuration', configuration, tooltip: 'in logical pixels'));
343
    if (_window.platformDispatcher.semanticsEnabled) {
344
      properties.add(DiagnosticsNode.message('semantics enabled'));
345
    }
346
  }
347
}