view.dart 12.5 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
import 'package:vector_math/vector_math_64.dart';
12

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

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

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

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

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

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

  @override
  int get hashCode => hashValues(size, devicePixelRatio);

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
  /// The configuration is initially set by the `configuration` argument
  /// passed to the constructor.
  ///
88
  /// Always call [prepareInitialFrame] before changing the configuration.
89
  set configuration(ViewConfiguration value) {
90
    assert(value != null);
91
    if (configuration == value)
92
      return;
93
    _configuration = value;
94 95
    replaceRootLayer(_updateMatricesAndCreateNewRootLayer());
    assert(_rootTransform != null);
96 97 98
    markNeedsLayout();
  }

99
  final ui.FlutterView _window;
100

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

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

138
  Matrix4? _rootTransform;
139

140
  TransformLayer _updateMatricesAndCreateNewRootLayer() {
141
    _rootTransform = configuration.toMatrix();
142
    final TransformLayer rootLayer = TransformLayer(transform: _rootTransform);
143 144 145 146 147
    rootLayer.attach(this);
    assert(_rootTransform != null);
    return rootLayer;
  }

148 149
  // We never call layout() on this class, so this should never get
  // checked. (This class is laid out using scheduleInitialLayout().)
150
  @override
151
  void debugAssertDoesMeetConstraints() { assert(false); }
152

153
  @override
154 155 156 157
  void performResize() {
    assert(false);
  }

158
  @override
159
  void performLayout() {
160
    assert(_rootTransform != null);
161
    _size = configuration.size;
162
    assert(_size.isFinite);
163 164

    if (child != null)
165
      child!.layout(BoxConstraints.tight(_size));
166 167
  }

168
  @override
169
  void rotate({ int? oldAngle, int? newAngle, Duration? time }) {
170 171 172
    assert(false); // nobody tells the screen to rotate, the whole rotate() dance is started from our performResize()
  }

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

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

203
  @override
204
  bool get isRepaintBoundary => true;
Hixie's avatar
Hixie committed
205

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

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

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

245
  void _updateSystemChrome() {
246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
    // 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
267
    final Rect bounds = paintBounds;
268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286
    // 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,
    );
287
    final SystemUiOverlayStyle? upperOverlayStyle = layer!.find<SystemUiOverlayStyle>(top);
288
    // Only android has a customizable system navigation bar.
289
    SystemUiOverlayStyle? lowerOverlayStyle;
290 291
    switch (defaultTargetPlatform) {
      case TargetPlatform.android:
292
        lowerOverlayStyle = layer!.find<SystemUiOverlayStyle>(bottom);
293 294
        break;
      case TargetPlatform.fuchsia:
295
      case TargetPlatform.iOS:
296
      case TargetPlatform.linux:
297
      case TargetPlatform.macOS:
298
      case TargetPlatform.windows:
299 300 301 302
        break;
    }
    // If there are no overlay styles in the UI don't bother updating.
    if (upperOverlayStyle != null || lowerOverlayStyle != null) {
303
      final SystemUiOverlayStyle overlayStyle = SystemUiOverlayStyle(
304 305 306
        statusBarBrightness: upperOverlayStyle?.statusBarBrightness,
        statusBarIconBrightness: upperOverlayStyle?.statusBarIconBrightness,
        statusBarColor: upperOverlayStyle?.statusBarColor,
307
        systemStatusBarContrastEnforced: upperOverlayStyle?.systemStatusBarContrastEnforced,
308 309 310
        systemNavigationBarColor: lowerOverlayStyle?.systemNavigationBarColor,
        systemNavigationBarDividerColor: lowerOverlayStyle?.systemNavigationBarDividerColor,
        systemNavigationBarIconBrightness: lowerOverlayStyle?.systemNavigationBarIconBrightness,
311
        systemNavigationBarContrastEnforced: lowerOverlayStyle?.systemNavigationBarContrastEnforced,
312 313 314 315 316
      );
      SystemChrome.setSystemUIOverlayStyle(overlayStyle);
    }
  }

317
  @override
318
  Rect get paintBounds => Offset.zero & (size * configuration.devicePixelRatio);
319 320

  @override
321 322
  Rect get semanticBounds {
    assert(_rootTransform != null);
323
    return MatrixUtils.transformRect(_rootTransform!, Offset.zero & size);
324
  }
Hixie's avatar
Hixie committed
325

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