view.dart 14.7 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 FlutterView, Scene, SceneBuilder, SemanticsUpdate;
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 view,
72
  }) : _configuration = configuration,
73
       _view = view {
74 75 76
    this.child = child;
  }

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

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

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

102
  final ui.FlutterView _view;
103

104 105 106 107 108 109 110 111 112
  /// 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.
  ///
113 114 115 116 117
  /// If there is no [AnnotatedRegionLayer] on the bottom, the hit-test result
  /// from the top provides the system nav bar settings. If there is no
  /// [AnnotatedRegionLayer] on the top, the hit-test result from the bottom
  /// provides the system status bar settings.
  ///
118 119 120 121 122 123 124 125
  /// 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:
  ///
126 127
  ///  * [AnnotatedRegion], for placing [SystemUiOverlayStyle] in the layer tree.
  ///  * [SystemChrome.setSystemUIOverlayStyle], for imperatively setting the system ui style.
128 129
  bool automaticSystemUiAdjustment = true;

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

146
  Matrix4? _rootTransform;
147

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

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

161
  @override
162 163 164 165
  void performResize() {
    assert(false);
  }

166
  @override
167
  void performLayout() {
168
    assert(_rootTransform != null);
169
    _size = configuration.size;
170
    assert(_size.isFinite);
171

172
    if (child != null) {
173
      child!.layout(BoxConstraints.tight(_size));
174
    }
175 176
  }

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

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

207
  @override
208
  bool get isRepaintBoundary => true;
Hixie's avatar
Hixie committed
209

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

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

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

252 253 254 255 256 257
  /// Sends the provided [SemanticsUpdate] to the [FlutterView] associated with
  /// this [RenderView].
  ///
  /// A [SemanticsUpdate] is produced by a [SemanticsOwner] during the
  /// [EnginePhase.flushSemantics] phase.
  void updateSemantics(ui.SemanticsUpdate update) {
258
    _view.updateSemantics(update);
259 260
  }

261
  void _updateSystemChrome() {
262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
    // 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
283
    final Rect bounds = paintBounds;
284 285 286 287 288 289
    // 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.
290
      _view.padding.top / 2.0,
291 292 293 294 295 296 297 298 299 300
    );
    // 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.
301
      bounds.bottom - 1.0 - _view.padding.bottom / 2.0,
302 303 304
    );
    final SystemUiOverlayStyle? upperOverlayStyle = layer!.find<SystemUiOverlayStyle>(top);
    // Only android has a customizable system navigation bar.
305
    SystemUiOverlayStyle? lowerOverlayStyle;
306 307
    switch (defaultTargetPlatform) {
      case TargetPlatform.android:
308
        lowerOverlayStyle = layer!.find<SystemUiOverlayStyle>(bottom);
309
      case TargetPlatform.fuchsia:
310
      case TargetPlatform.iOS:
311
      case TargetPlatform.linux:
312
      case TargetPlatform.macOS:
313
      case TargetPlatform.windows:
314 315
        break;
    }
316 317 318 319 320 321 322 323 324 325 326
    // If there are no overlay style in the UI don't bother updating.
    if (upperOverlayStyle == null && lowerOverlayStyle == null) {
      return;
    }

    // If both are not null, the upper provides the status bar properties and the lower provides
    // the system navigation bar properties. This is done for advanced use cases where a widget
    // on the top (for instance an app bar) will create an annotated region to set the status bar
    // style and another widget on the bottom will create an annotated region to set the system
    // navigation bar style.
    if (upperOverlayStyle != null && lowerOverlayStyle != null) {
327
      final SystemUiOverlayStyle overlayStyle = SystemUiOverlayStyle(
328 329 330 331 332 333 334 335
        statusBarBrightness: upperOverlayStyle.statusBarBrightness,
        statusBarIconBrightness: upperOverlayStyle.statusBarIconBrightness,
        statusBarColor: upperOverlayStyle.statusBarColor,
        systemStatusBarContrastEnforced: upperOverlayStyle.systemStatusBarContrastEnforced,
        systemNavigationBarColor: lowerOverlayStyle.systemNavigationBarColor,
        systemNavigationBarDividerColor: lowerOverlayStyle.systemNavigationBarDividerColor,
        systemNavigationBarIconBrightness: lowerOverlayStyle.systemNavigationBarIconBrightness,
        systemNavigationBarContrastEnforced: lowerOverlayStyle.systemNavigationBarContrastEnforced,
336 337
      );
      SystemChrome.setSystemUIOverlayStyle(overlayStyle);
338
      return;
339
    }
340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356
    // If only one of the upper or the lower overlay style is not null, it provides all properties.
    // This is done for developer convenience as it allows setting both status bar style and
    // navigation bar style using only one annotated region layer (for instance the one
    // automatically created by an [AppBar]).
    final bool isAndroid = defaultTargetPlatform == TargetPlatform.android;
    final SystemUiOverlayStyle definedOverlayStyle = (upperOverlayStyle ?? lowerOverlayStyle)!;
    final SystemUiOverlayStyle overlayStyle = SystemUiOverlayStyle(
      statusBarBrightness: definedOverlayStyle.statusBarBrightness,
      statusBarIconBrightness: definedOverlayStyle.statusBarIconBrightness,
      statusBarColor: definedOverlayStyle.statusBarColor,
      systemStatusBarContrastEnforced: definedOverlayStyle.systemStatusBarContrastEnforced,
      systemNavigationBarColor: isAndroid ? definedOverlayStyle.systemNavigationBarColor : null,
      systemNavigationBarDividerColor: isAndroid ? definedOverlayStyle.systemNavigationBarDividerColor : null,
      systemNavigationBarIconBrightness: isAndroid ? definedOverlayStyle.systemNavigationBarIconBrightness : null,
      systemNavigationBarContrastEnforced: isAndroid ? definedOverlayStyle.systemNavigationBarContrastEnforced : null,
    );
    SystemChrome.setSystemUIOverlayStyle(overlayStyle);
357 358
  }

359
  @override
360
  Rect get paintBounds => Offset.zero & (size * configuration.devicePixelRatio);
361 362

  @override
363 364
  Rect get semanticBounds {
    assert(_rootTransform != null);
365
    return MatrixUtils.transformRect(_rootTransform!, Offset.zero & size);
366
  }
Hixie's avatar
Hixie committed
367

368
  @override
369
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
370 371 372
    // call to ${super.debugFillProperties(description)} is omitted because the
    // root superclasses don't include any interesting information for this
    // class
373
    assert(() {
374
      properties.add(DiagnosticsNode.message('debug mode enabled - ${kIsWeb ? 'Web' :  Platform.operatingSystem}'));
375
      return true;
376
    }());
377 378
    properties.add(DiagnosticsProperty<Size>('view size', _view.physicalSize, tooltip: 'in physical pixels'));
    properties.add(DoubleProperty('device pixel ratio', _view.devicePixelRatio, tooltip: 'physical pixels per logical pixel'));
379
    properties.add(DiagnosticsProperty<ViewConfiguration>('configuration', configuration, tooltip: 'in logical pixels'));
380
    if (_view.platformDispatcher.semanticsEnabled) {
381
      properties.add(DiagnosticsNode.message('semantics enabled'));
382
    }
383
  }
384
}