window.dart 58.3 KB
Newer Older
M
Michael Goderbauer 已提交
1
// Copyright 2013 The Flutter Authors. All rights reserved.
A
Adam Barth 已提交
2 3 4
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5
// @dart = 2.10
A
Adam Barth 已提交
6
part of dart.ui;
A
Adam Barth 已提交
7

I
Ian Hickson 已提交
8
/// Signature of callbacks that have no arguments and return no data.
9
typedef VoidCallback = void Function();
I
Ian Hickson 已提交
10 11

/// Signature for [Window.onBeginFrame].
12
typedef FrameCallback = void Function(Duration duration);
I
Ian Hickson 已提交
13

14 15
/// Signature for [Window.onReportTimings].
///
16 17 18 19 20 21 22 23 24
/// {@template dart.ui.TimingsCallback.list}
/// The callback takes a list of [FrameTiming] because it may not be
/// immediately triggered after each frame. Instead, Flutter tries to batch
/// frames together and send all their timings at once to decrease the
/// overhead (as this is available in the release mode). The list is sorted in
/// ascending order of time (earliest frame first). The timing of any frame
/// will be sent within about 1 second (100ms if in the profile/debug mode)
/// even if there are no later frames to batch. The timing of the first frame
/// will be sent immediately without batching.
25
/// {@endtemplate}
26
typedef TimingsCallback = void Function(List<FrameTiming> timings);
27

28
/// Signature for [Window.onPointerDataPacket].
29
typedef PointerDataPacketCallback = void Function(PointerDataPacket packet);
30

31
/// Signature for [Window.onSemanticsAction].
32
typedef SemanticsActionCallback = void Function(int id, SemanticsAction action, ByteData? args);
33

A
Adam Barth 已提交
34 35 36 37
/// Signature for responses to platform messages.
///
/// Used as a parameter to [Window.sendPlatformMessage] and
/// [Window.onPlatformMessage].
38
typedef PlatformMessageResponseCallback = void Function(ByteData? data);
39

A
Adam Barth 已提交
40
/// Signature for [Window.onPlatformMessage].
41
typedef PlatformMessageCallback = void Function(String name, ByteData? data, PlatformMessageResponseCallback? callback);
A
Adam Barth 已提交
42

43
// Signature for _setNeedsReportTimings.
44
typedef _SetNeedsReportTimingsFunc = void Function(bool value);
45

46 47 48 49
/// Various important time points in the lifetime of a frame.
///
/// [FrameTiming] records a timestamp of each phase for performance analysis.
enum FramePhase {
50 51 52 53 54
  /// The timestamp of the vsync signal given by the operating system.
  ///
  /// See also [FrameTiming.vsyncOverhead].
  vsyncStart,

55 56 57 58 59 60 61 62 63 64
  /// When the UI thread starts building a frame.
  ///
  /// See also [FrameTiming.buildDuration].
  buildStart,

  /// When the UI thread finishes building a frame.
  ///
  /// See also [FrameTiming.buildDuration].
  buildFinish,

65
  /// When the raster thread starts rasterizing a frame.
66 67 68 69
  ///
  /// See also [FrameTiming.rasterDuration].
  rasterStart,

70
  /// When the raster thread finishes rasterizing a frame.
71 72 73 74 75 76 77
  ///
  /// See also [FrameTiming.rasterDuration].
  rasterFinish,
}

/// Time-related performance metrics of a frame.
///
78 79 80 81 82 83
/// If you're using the whole Flutter framework, please use
/// [SchedulerBinding.addTimingsCallback] to get this. It's preferred over using
/// [Window.onReportTimings] directly because
/// [SchedulerBinding.addTimingsCallback] allows multiple callbacks. If
/// [SchedulerBinding] is unavailable, then see [Window.onReportTimings] for how
/// to get this.
84 85 86 87 88 89
///
/// The metrics in debug mode (`flutter run` without any flags) may be very
/// different from those in profile and release modes due to the debug overhead.
/// Therefore it's recommended to only monitor and analyze performance metrics
/// in profile and release modes.
class FrameTiming {
90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
  /// Construct [FrameTiming] with raw timestamps in microseconds.
  ///
  /// This constructor is used for unit test only. Real [FrameTiming]s should
  /// be retrieved from [Window.onReportTimings].
  factory FrameTiming({
    required int vsyncStart,
    required int buildStart,
    required int buildFinish,
    required int rasterStart,
    required int rasterFinish,
  }) {
    return FrameTiming._(<int>[
      vsyncStart,
      buildStart,
      buildFinish,
      rasterStart,
      rasterFinish
    ]);
  }

110 111 112 113 114 115
  /// Construct [FrameTiming] with raw timestamps in microseconds.
  ///
  /// List [timestamps] must have the same number of elements as
  /// [FramePhase.values].
  ///
  /// This constructor is usually only called by the Flutter engine, or a test.
116
  /// To get the [FrameTiming] of your app, see [Window.onReportTimings].
117
  FrameTiming._(List<int> timestamps)
118 119
      : assert(timestamps.length == FramePhase.values.length), _timestamps = timestamps;

120 121 122 123 124 125 126 127 128 129 130 131 132 133
  /// Construct [FrameTiming] with given timestamp in micrseconds.
  ///
  /// This constructor is used for unit test only. Real [FrameTiming]s should
  /// be retrieved from [Window.onReportTimings].
  ///
  /// TODO(CareF): This is part of #20229. Remove back to default constructor
  /// after #20229 lands and corresponding framwork PRs land.
  factory FrameTiming.fromTimeStamps({
    int? vsyncStart,
    required int buildStart,
    required int buildFinish,
    required int rasterStart,
    required int rasterFinish
  }) {
134 135 136
    return FrameTiming._(<int>[
      // This is for temporarily backward compatiblilty.
      vsyncStart ?? buildStart,
137 138 139 140 141 142 143
      buildStart,
      buildFinish,
      rasterStart,
      rasterFinish
    ]);
  }

144 145
  /// This is a raw timestamp in microseconds from some epoch. The epoch in all
  /// [FrameTiming] is the same, but it may not match [DateTime]'s epoch.
146
  int timestampInMicroseconds(FramePhase phase) => _timestamps[phase.index];
147

148
  Duration _rawDuration(FramePhase phase) => Duration(microseconds: _timestamps[phase.index]);
149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164

  /// The duration to build the frame on the UI thread.
  ///
  /// The build starts approximately when [Window.onBeginFrame] is called. The
  /// [Duration] in the [Window.onBeginFrame] callback is exactly the
  /// `Duration(microseconds: timestampInMicroseconds(FramePhase.buildStart))`.
  ///
  /// The build finishes when [Window.render] is called.
  ///
  /// {@template dart.ui.FrameTiming.fps_smoothness_milliseconds}
  /// To ensure smooth animations of X fps, this should not exceed 1000/X
  /// milliseconds.
  /// {@endtemplate}
  /// {@template dart.ui.FrameTiming.fps_milliseconds}
  /// That's about 16ms for 60fps, and 8ms for 120fps.
  /// {@endtemplate}
165
  Duration get buildDuration => _rawDuration(FramePhase.buildFinish) - _rawDuration(FramePhase.buildStart);
166

167
  /// The duration to rasterize the frame on the raster thread.
168 169 170
  ///
  /// {@macro dart.ui.FrameTiming.fps_smoothness_milliseconds}
  /// {@macro dart.ui.FrameTiming.fps_milliseconds}
171
  Duration get rasterDuration => _rawDuration(FramePhase.rasterFinish) - _rawDuration(FramePhase.rasterStart);
172

173 174 175 176 177
  /// The duration between receiving the vsync signal and starting building the
  /// frame.
  Duration get vsyncOverhead => _rawDuration(FramePhase.buildStart) - _rawDuration(FramePhase.vsyncStart);

  /// The timespan between vsync start and raster finish.
178 179 180 181 182
  ///
  /// To achieve the lowest latency on an X fps display, this should not exceed
  /// 1000/X milliseconds.
  /// {@macro dart.ui.FrameTiming.fps_milliseconds}
  ///
183 184
  /// See also [vsyncOverhead], [buildDuration] and [rasterDuration].
  Duration get totalSpan => _rawDuration(FramePhase.rasterFinish) - _rawDuration(FramePhase.vsyncStart);
185

186
  final List<int> _timestamps;  // in microseconds
187 188 189 190 191

  String _formatMS(Duration duration) => '${duration.inMicroseconds * 0.001}ms';

  @override
  String toString() {
192
    return '$runtimeType(buildDuration: ${_formatMS(buildDuration)}, rasterDuration: ${_formatMS(rasterDuration)}, vsyncOverhead: ${_formatMS(vsyncOverhead)}, totalSpan: ${_formatMS(totalSpan)})';
193 194 195
  }
}

196
/// States that an application can be in.
197 198 199 200 201 202
///
/// The values below describe notifications from the operating system.
/// Applications should not expect to always receive all possible
/// notifications. For example, if the users pulls out the battery from the
/// device, no notification will be sent before the application is suddenly
/// terminated, along with the rest of the operating system.
203 204 205 206 207
///
/// See also:
///
///  * [WidgetsBindingObserver], for a mechanism to observe the lifecycle state
///    from the widgets layer.
208
enum AppLifecycleState {
209 210 211 212 213
  /// The application is visible and responding to user input.
  resumed,

  /// The application is in an inactive state and is not receiving user input.
  ///
214 215 216 217
  /// On iOS, this state corresponds to an app or the Flutter host view running
  /// in the foreground inactive state. Apps transition to this state when in
  /// a phone call, responding to a TouchID request, when entering the app
  /// switcher or the control center, or when the UIViewController hosting the
218
  /// Flutter app is transitioning.
219
  ///
220 221 222 223
  /// On Android, this corresponds to an app or the Flutter host view running
  /// in the foreground inactive state.  Apps transition to this state when
  /// another activity is focused, such as a split-screen app, a phone call,
  /// a picture-in-picture app, a system dialog, or another window.
224
  ///
225
  /// Apps in this state should assume that they may be [paused] at any time.
226 227 228 229 230 231
  inactive,

  /// The application is not currently visible to the user, not responding to
  /// user input, and running in the background.
  ///
  /// When the application is in this state, the engine will not call the
I
Ian Hickson 已提交
232
  /// [Window.onBeginFrame] and [Window.onDrawFrame] callbacks.
233
  paused,
234

C
chunhtai 已提交
235 236
  /// The application is still hosted on a flutter engine but is detached from
  /// any host views.
237
  ///
C
chunhtai 已提交
238 239 240 241 242
  /// When the application is in this state, the engine is running without
  /// a view. It can either be in the progress of attaching a view when engine
  /// was first initializes, or after the view being destroyed due to a Navigator
  /// pop.
  detached,
243
}
A
Adam Barth 已提交
244

245
/// A representation of distances for each of the four edges of a rectangle,
246 247
/// used to encode the view insets and padding that applications should place
/// around their user interface, as exposed by [Window.viewInsets] and
248
/// [Window.padding]. View insets and padding are preferably read via
249
/// [MediaQuery.of].
250 251
///
/// For a generic class that represents distances around a rectangle, see the
I
Ian Hickson 已提交
252
/// [EdgeInsets] class.
253 254 255 256 257
///
/// See also:
///
///  * [WidgetsBindingObserver], for a widgets layer mechanism to receive
///    notifications when the padding changes.
258
///  * [MediaQuery.of], for the preferred mechanism for accessing these values.
259 260
///  * [Scaffold], which automatically applies the padding in material design
///    applications.
261
class WindowPadding {
262
  const WindowPadding._({ required this.left, required this.top, required this.right, required this.bottom });
A
Adam Barth 已提交
263

264
  /// The distance from the left edge to the first unpadded pixel, in physical pixels.
265
  final double left;
A
Adam Barth 已提交
266

267
  /// The distance from the top edge to the first unpadded pixel, in physical pixels.
268
  final double top;
A
Adam Barth 已提交
269

270
  /// The distance from the right edge to the first unpadded pixel, in physical pixels.
271
  final double right;
A
Adam Barth 已提交
272

273
  /// The distance from the bottom edge to the first unpadded pixel, in physical pixels.
274
  final double bottom;
275

A
Adam Barth 已提交
276
  /// A window padding that has zeros for each edge.
D
Dan Field 已提交
277
  static const WindowPadding zero = WindowPadding._(left: 0.0, top: 0.0, right: 0.0, bottom: 0.0);
278 279 280

  @override
  String toString() {
281
    return 'WindowPadding(left: $left, top: $top, right: $right, bottom: $bottom)';
282
  }
A
Adam Barth 已提交
283 284
}

285 286 287 288 289
/// An identifier used to select a user's language and formatting preferences.
///
/// This represents a [Unicode Language
/// Identifier](https://www.unicode.org/reports/tr35/#Unicode_language_identifier)
/// (i.e. without Locale extensions), except variants are not supported.
290
///
291 292 293 294 295 296 297
/// Locales are canonicalized according to the "preferred value" entries in the
/// [IANA Language Subtag
/// Registry](https://www.iana.org/assignments/language-subtag-registry/language-subtag-registry).
/// For example, `const Locale('he')` and `const Locale('iw')` are equal and
/// both have the [languageCode] `he`, because `iw` is a deprecated language
/// subtag that was replaced by the subtag `he`.
///
298 299 300 301
/// See also:
///
///  * [Window.locale], which specifies the system's currently selected
///    [Locale].
302
class Locale {
H
Hixie 已提交
303
  /// Creates a new Locale object. The first argument is the
304 305
  /// primary language subtag, the second is the region (also
  /// referred to as 'country') subtag.
H
Hixie 已提交
306 307 308
  ///
  /// For example:
  ///
309
  /// ```dart
D
Dan Field 已提交
310 311
  /// const Locale swissFrench = Locale('fr', 'CH');
  /// const Locale canadianFrench = Locale('fr', 'CA');
312
  /// ```
313 314
  ///
  /// The primary language subtag must not be null. The region subtag is
315 316
  /// optional. When there is no region/country subtag, the parameter should
  /// be omitted or passed `null` instead of an empty-string.
317
  ///
318 319 320 321 322 323 324 325 326 327 328 329 330 331 332
  /// The subtag values are _case sensitive_ and must be one of the valid
  /// subtags according to CLDR supplemental data:
  /// [language](http://unicode.org/cldr/latest/common/validity/language.xml),
  /// [region](http://unicode.org/cldr/latest/common/validity/region.xml). The
  /// primary language subtag must be at least two and at most eight lowercase
  /// letters, but not four letters. The region region subtag must be two
  /// uppercase letters or three digits. See the [Unicode Language
  /// Identifier](https://www.unicode.org/reports/tr35/#Unicode_language_identifier)
  /// specification.
  ///
  /// Validity is not checked by default, but some methods may throw away
  /// invalid data.
  ///
  /// See also:
  ///
333
  ///  * [Locale.fromSubtags], which also allows a [scriptCode] to be
334 335 336 337
  ///    specified.
  const Locale(
    this._languageCode, [
    this._countryCode,
338
  ]) : assert(_languageCode != null), // ignore: unnecessary_null_comparison
339
       assert(_languageCode != ''),
340
       scriptCode = null;
341 342 343 344 345 346 347 348 349 350 351 352

  /// Creates a new Locale object.
  ///
  /// The keyword arguments specify the subtags of the Locale.
  ///
  /// The subtag values are _case sensitive_ and must be valid subtags according
  /// to CLDR supplemental data:
  /// [language](http://unicode.org/cldr/latest/common/validity/language.xml),
  /// [script](http://unicode.org/cldr/latest/common/validity/script.xml) and
  /// [region](http://unicode.org/cldr/latest/common/validity/region.xml) for
  /// each of languageCode, scriptCode and countryCode respectively.
  ///
353 354 355
  /// The [countryCode] subtag is optional. When there is no country subtag,
  /// the parameter should be omitted or passed `null` instead of an empty-string.
  ///
356 357 358
  /// Validity is not checked by default, but some methods may throw away
  /// invalid data.
  const Locale.fromSubtags({
359
    String languageCode = 'und',
360
    this.scriptCode,
361 362
    String? countryCode,
  }) : assert(languageCode != null), // ignore: unnecessary_null_comparison
363 364 365 366 367
       assert(languageCode != ''),
       _languageCode = languageCode,
       assert(scriptCode != ''),
       assert(countryCode != ''),
       _countryCode = countryCode;
368

369
  /// The primary language subtag for the locale.
370
  ///
371
  /// This must not be null. It may be 'und', representing 'undefined'.
372 373 374 375 376 377 378 379 380 381 382
  ///
  /// This is expected to be string registered in the [IANA Language Subtag
  /// Registry](https://www.iana.org/assignments/language-subtag-registry/language-subtag-registry)
  /// with the type "language". The string specified must match the case of the
  /// string in the registry.
  ///
  /// Language subtags that are deprecated in the registry and have a preferred
  /// code are changed to their preferred code. For example, `const
  /// Locale('he')` and `const Locale('iw')` are equal, and both have the
  /// [languageCode] `he`, because `iw` is a deprecated language subtag that was
  /// replaced by the subtag `he`.
383 384 385 386 387 388 389
  ///
  /// This must be a valid Unicode Language subtag as listed in [Unicode CLDR
  /// supplemental
  /// data](http://unicode.org/cldr/latest/common/validity/language.xml).
  ///
  /// See also:
  ///
390
  ///  * [Locale.fromSubtags], which describes the conventions for creating
391
  ///    [Locale] objects.
392 393
  String get languageCode => _deprecatedLanguageSubtagMap[_languageCode] ?? _languageCode;
  final String _languageCode;
394

395 396
  // This map is generated by //flutter/tools/gen_locale.dart
  // Mappings generated for language subtag registry as of 2019-02-27.
D
Dan Field 已提交
397
  static const Map<String, String> _deprecatedLanguageSubtagMap = <String, String>{
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
    'in': 'id', // Indonesian; deprecated 1989-01-01
    'iw': 'he', // Hebrew; deprecated 1989-01-01
    'ji': 'yi', // Yiddish; deprecated 1989-01-01
    'jw': 'jv', // Javanese; deprecated 2001-08-13
    'mo': 'ro', // Moldavian, Moldovan; deprecated 2008-11-22
    'aam': 'aas', // Aramanik; deprecated 2015-02-12
    'adp': 'dz', // Adap; deprecated 2015-02-12
    'aue': 'ktz', // ǂKxʼauǁʼein; deprecated 2015-02-12
    'ayx': 'nun', // Ayi (China); deprecated 2011-08-16
    'bgm': 'bcg', // Baga Mboteni; deprecated 2016-05-30
    'bjd': 'drl', // Bandjigali; deprecated 2012-08-12
    'ccq': 'rki', // Chaungtha; deprecated 2012-08-12
    'cjr': 'mom', // Chorotega; deprecated 2010-03-11
    'cka': 'cmr', // Khumi Awa Chin; deprecated 2012-08-12
    'cmk': 'xch', // Chimakum; deprecated 2010-03-11
    'coy': 'pij', // Coyaima; deprecated 2016-05-30
    'cqu': 'quh', // Chilean Quechua; deprecated 2016-05-30
    'drh': 'khk', // Darkhat; deprecated 2010-03-11
    'drw': 'prs', // Darwazi; deprecated 2010-03-11
    'gav': 'dev', // Gabutamon; deprecated 2010-03-11
    'gfx': 'vaj', // Mangetti Dune ǃXung; deprecated 2015-02-12
    'ggn': 'gvr', // Eastern Gurung; deprecated 2016-05-30
    'gti': 'nyc', // Gbati-ri; deprecated 2015-02-12
    'guv': 'duz', // Gey; deprecated 2016-05-30
    'hrr': 'jal', // Horuru; deprecated 2012-08-12
    'ibi': 'opa', // Ibilo; deprecated 2012-08-12
    'ilw': 'gal', // Talur; deprecated 2013-09-10
    'jeg': 'oyb', // Jeng; deprecated 2017-02-23
    'kgc': 'tdf', // Kasseng; deprecated 2016-05-30
    'kgh': 'kml', // Upper Tanudan Kalinga; deprecated 2012-08-12
    'koj': 'kwv', // Sara Dunjo; deprecated 2015-02-12
    'krm': 'bmf', // Krim; deprecated 2017-02-23
    'ktr': 'dtp', // Kota Marudu Tinagas; deprecated 2016-05-30
    'kvs': 'gdj', // Kunggara; deprecated 2016-05-30
    'kwq': 'yam', // Kwak; deprecated 2015-02-12
    'kxe': 'tvd', // Kakihum; deprecated 2015-02-12
    'kzj': 'dtp', // Coastal Kadazan; deprecated 2016-05-30
    'kzt': 'dtp', // Tambunan Dusun; deprecated 2016-05-30
    'lii': 'raq', // Lingkhim; deprecated 2015-02-12
    'lmm': 'rmx', // Lamam; deprecated 2014-02-28
    'meg': 'cir', // Mea; deprecated 2013-09-10
    'mst': 'mry', // Cataelano Mandaya; deprecated 2010-03-11
    'mwj': 'vaj', // Maligo; deprecated 2015-02-12
    'myt': 'mry', // Sangab Mandaya; deprecated 2010-03-11
    'nad': 'xny', // Nijadali; deprecated 2016-05-30
    'ncp': 'kdz', // Ndaktup; deprecated 2018-03-08
    'nnx': 'ngv', // Ngong; deprecated 2015-02-12
    'nts': 'pij', // Natagaimas; deprecated 2016-05-30
    'oun': 'vaj', // ǃOǃung; deprecated 2015-02-12
    'pcr': 'adx', // Panang; deprecated 2013-09-10
    'pmc': 'huw', // Palumata; deprecated 2016-05-30
    'pmu': 'phr', // Mirpur Panjabi; deprecated 2015-02-12
    'ppa': 'bfy', // Pao; deprecated 2016-05-30
    'ppr': 'lcq', // Piru; deprecated 2013-09-10
    'pry': 'prt', // Pray 3; deprecated 2016-05-30
    'puz': 'pub', // Purum Naga; deprecated 2014-02-28
    'sca': 'hle', // Sansu; deprecated 2012-08-12
    'skk': 'oyb', // Sok; deprecated 2017-02-23
    'tdu': 'dtp', // Tempasuk Dusun; deprecated 2016-05-30
    'thc': 'tpo', // Tai Hang Tong; deprecated 2016-05-30
    'thx': 'oyb', // The; deprecated 2015-02-12
    'tie': 'ras', // Tingal; deprecated 2011-08-16
    'tkk': 'twm', // Takpa; deprecated 2011-08-16
    'tlw': 'weo', // South Wemale; deprecated 2012-08-12
    'tmp': 'tyj', // Tai Mène; deprecated 2016-05-30
    'tne': 'kak', // Tinoc Kallahan; deprecated 2016-05-30
    'tnf': 'prs', // Tangshewi; deprecated 2010-03-11
    'tsf': 'taj', // Southwestern Tamang; deprecated 2015-02-12
    'uok': 'ema', // Uokha; deprecated 2015-02-12
    'xba': 'cax', // Kamba (Brazil); deprecated 2016-05-30
    'xia': 'acn', // Xiandao; deprecated 2013-09-10
    'xkh': 'waw', // Karahawyana; deprecated 2016-05-30
    'xsj': 'suj', // Subi; deprecated 2015-02-12
    'ybd': 'rki', // Yangbye; deprecated 2012-08-12
    'yma': 'lrr', // Yamphe; deprecated 2012-08-12
    'ymt': 'mtm', // Mator-Taygi-Karagas; deprecated 2015-02-12
    'yos': 'zom', // Yos; deprecated 2013-09-10
    'yuu': 'yug', // Yugh; deprecated 2014-02-28
  };
477

478 479 480 481 482 483 484 485 486 487
  /// The script subtag for the locale.
  ///
  /// This may be null, indicating that there is no specified script subtag.
  ///
  /// This must be a valid Unicode Language Identifier script subtag as listed
  /// in [Unicode CLDR supplemental
  /// data](http://unicode.org/cldr/latest/common/validity/script.xml).
  ///
  /// See also:
  ///
488
  ///  * [Locale.fromSubtags], which describes the conventions for creating
489
  ///    [Locale] objects.
490
  final String? scriptCode;
491

492
  /// The region subtag for the locale.
493
  ///
494
  /// This may be null, indicating that there is no specified region subtag.
495 496 497 498 499 500 501 502 503 504 505
  ///
  /// This is expected to be string registered in the [IANA Language Subtag
  /// Registry](https://www.iana.org/assignments/language-subtag-registry/language-subtag-registry)
  /// with the type "region". The string specified must match the case of the
  /// string in the registry.
  ///
  /// Region subtags that are deprecated in the registry and have a preferred
  /// code are changed to their preferred code. For example, `const Locale('de',
  /// 'DE')` and `const Locale('de', 'DD')` are equal, and both have the
  /// [countryCode] `DE`, because `DD` is a deprecated language subtag that was
  /// replaced by the subtag `DE`.
506 507 508
  ///
  /// See also:
  ///
509
  ///  * [Locale.fromSubtags], which describes the conventions for creating
510
  ///    [Locale] objects.
511 512
  String? get countryCode => _deprecatedRegionSubtagMap[_countryCode] ?? _countryCode;
  final String? _countryCode;
513

514 515
  // This map is generated by //flutter/tools/gen_locale.dart
  // Mappings generated for language subtag registry as of 2019-02-27.
D
Dan Field 已提交
516
  static const Map<String, String> _deprecatedRegionSubtagMap = <String, String>{
517 518 519 520 521 522 523
    'BU': 'MM', // Burma; deprecated 1989-12-05
    'DD': 'DE', // German Democratic Republic; deprecated 1990-10-30
    'FX': 'FR', // Metropolitan France; deprecated 1997-07-14
    'TP': 'TL', // East Timor; deprecated 2002-05-20
    'YD': 'YE', // Democratic Yemen; deprecated 1990-08-14
    'ZR': 'CD', // Zaire; deprecated 1997-07-14
  };
524 525

  @override
A
Alexandre Ardhuin 已提交
526
  bool operator ==(Object other) {
527 528
    if (identical(this, other))
      return true;
529 530 531 532 533 534
    if (other is! Locale) {
      return false;
    }
    final String? countryCode = _countryCode;
    final String? otherCountryCode = other.countryCode;
    return other.languageCode == languageCode
535 536
        && other.scriptCode == scriptCode // scriptCode cannot be ''
        && (other.countryCode == countryCode // Treat '' as equal to null.
537
            || otherCountryCode != null && otherCountryCode.isEmpty && countryCode == null
538
            || countryCode != null && countryCode.isEmpty && other.countryCode == null);
539 540
  }

541
  @override
542
  int get hashCode => hashValues(languageCode, scriptCode, countryCode == '' ? null : countryCode);
543

544 545
  static Locale? _cachedLocale;
  static String? _cachedLocaleString;
546

H
Hugo 已提交
547 548 549 550 551
  /// Returns a string representing the locale.
  ///
  /// This identifier happens to be a valid Unicode Locale Identifier using
  /// underscores as separator, however it is intended to be used for debugging
  /// purposes only. For parseable results, use [toLanguageTag] instead.
552
  @keepToString
553
  @override
554
  String toString() {
555 556 557
    if (!identical(_cachedLocale, this)) {
      _cachedLocale = this;
      _cachedLocaleString = _rawToString('_');
558
    }
559
    return _cachedLocaleString!;
560
  }
H
Hugo 已提交
561 562 563 564 565 566

  /// Returns a syntactically valid Unicode BCP47 Locale Identifier.
  ///
  /// Some examples of such identifiers: "en", "es-419", "hi-Deva-IN" and
  /// "zh-Hans-CN". See http://www.unicode.org/reports/tr35/ for technical
  /// details.
567
  String toLanguageTag() => _rawToString('-');
568

569
  String _rawToString(String separator) {
570
    final StringBuffer out = StringBuffer(languageCode);
571
    if (scriptCode != null && scriptCode!.isNotEmpty)
H
Hugo 已提交
572
      out.write('$separator$scriptCode');
573
    if (_countryCode != null && _countryCode!.isNotEmpty)
H
Hugo 已提交
574
      out.write('$separator$countryCode');
575
    return out.toString();
576
  }
577 578
}

579
/// The most basic interface to the host operating system's user interface.
H
Hixie 已提交
580
///
L
liyuqian 已提交
581 582 583
/// It exposes the size of the display, the core scheduler API, the input event
/// callback, the graphics drawing API, and other such core services.
///
H
Hixie 已提交
584
/// There is a single Window instance in the system, which you can
L
liyuqian 已提交
585 586 587 588 589
/// obtain from `WidgetsBinding.instance.window`.
///
/// There is also a [window] singleton object in `dart:ui` if `WidgetsBinding`
/// is unavailable. But we strongly advise to avoid statically referencing it.
/// See the document of [window] for more details of why it should be avoided.
D
Dan Field 已提交
590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631
///
/// ## Insets and Padding
///
/// {@animation 300 300 https://flutter.github.io/assets-for-api-docs/assets/widgets/window_padding.mp4}
///
/// In this diagram, the black areas represent system UI that the app cannot
/// draw over. The red area represents view padding that the application may not
/// be able to detect gestures in and may not want to draw in. The grey area
/// represents the system keyboard, which can cover over the bottom view
/// padding when visible.
///
/// The [Window.viewInsets] are the physical pixels which the operating
/// system reserves for system UI, such as the keyboard, which would fully
/// obscure any content drawn in that area.
///
/// The [Window.viewPadding] are the physical pixels on each side of the display
/// that may be partially obscured by system UI or by physical intrusions into
/// the display, such as an overscan region on a television or a "notch" on a
/// phone. Unlike the insets, these areas may have portions that show the user
/// application painted pixels without being obscured, such as a notch at the
/// top of a phone that covers only a subset of the area. Insets, on the other
/// hand, either partially or fully obscure the window, such as an opaque
/// keyboard or a partially transluscent statusbar, which cover an area without
/// gaps.
///
/// The [Window.padding] property is computed from both [Window.viewInsets] and
/// [Window.viewPadding]. It will allow a view inset to consume view padding
/// where appropriate, such as when a phone's keyboard is covering the bottom
/// view padding and so "absorbs" it.
///
/// Clients that want to position elements relative to the view padding
/// regardless of the view insets should use the [Window.viewPadding] property,
/// e.g. if you wish to draw a widget at the center of the screen with respect
/// to the iPhone "safe area" regardless of whether the keyboard is showing.
///
/// [Window.padding] is useful for clients that want to know how much padding
/// should be accounted for without concern for the current inset(s) state, e.g.
/// determining whether a gesture should be considered for scrolling purposes.
/// This value varies based on the current state of the insets. For example, a
/// visible keyboard will consume all gestures in the bottom part of the
/// [Window.viewPadding] anyway, so there is no need to account for that in the
/// [Window.padding], which is always safe to use for such calculations.
A
Adam Barth 已提交
632
class Window {
633 634 635
  Window._() {
    _setNeedsReportTimings = _nativeSetNeedsReportTimings;
  }
A
Adam Barth 已提交
636

637 638 639
  /// The number of device pixels for each logical pixel. This number might not
  /// be a power of two. Indeed, it might not even be an integer. For example,
  /// the Nexus 6 has a device pixel ratio of 3.5.
640 641 642 643 644 645 646 647 648 649
  ///
  /// Device pixels are also referred to as physical pixels. Logical pixels are
  /// also referred to as device-independent or resolution-independent pixels.
  ///
  /// By definition, there are roughly 38 logical pixels per centimeter, or
  /// about 96 logical pixels per inch, of the physical display. The value
  /// returned by [devicePixelRatio] is ultimately obtained either from the
  /// hardware itself, the device drivers, or a hard-coded value stored in the
  /// operating system or firmware, and may be inaccurate, sometimes by a
  /// significant margin.
650 651 652 653
  ///
  /// The Flutter framework operates in logical pixels, so it is rarely
  /// necessary to directly deal with this property.
  ///
654 655
  /// When this changes, [onMetricsChanged] is called.
  ///
656 657 658 659
  /// See also:
  ///
  ///  * [WidgetsBindingObserver], for a mechanism at the widgets layer to
  ///    observe when this value changes.
660 661
  double get devicePixelRatio => _devicePixelRatio;
  double _devicePixelRatio = 1.0;
A
Adam Barth 已提交
662

663
  /// The dimensions of the rectangle into which the application will be drawn,
A
Adam Barth 已提交
664
  /// in physical pixels.
665
  ///
666 667
  /// When this changes, [onMetricsChanged] is called.
  ///
668
  /// At startup, the size of the application window may not be known before Dart
669 670 671 672 673 674 675
  /// code runs. If this value is observed early in the application lifecycle,
  /// it may report [Size.zero].
  ///
  /// This value does not take into account any on-screen keyboards or other
  /// system UI. The [padding] and [viewInsets] properties provide a view into
  /// how much of each side of the application may be obscured by system UI.
  ///
676 677 678 679
  /// See also:
  ///
  ///  * [WidgetsBindingObserver], for a mechanism at the widgets layer to
  ///    observe when this value changes.
680 681
  Size get physicalSize => _physicalSize;
  Size _physicalSize = Size.zero;
A
Adam Barth 已提交
682

683 684 685 686 687 688 689 690 691 692 693 694 695 696
  /// The physical depth is the maximum elevation that the Window allows.
  ///
  /// Physical layers drawn at or above this elevation will have their elevation
  /// clamped to this value. This can happen if the physical layer itself has
  /// an elevation larger than available depth, or if some ancestor of the layer
  /// causes it to have a cumulative elevation that is larger than the available
  /// depth.
  ///
  /// The default value is [double.maxFinite], which is used for platforms that
  /// do not specify a maximum elevation. This property is currently on expected
  /// to be set to a non-default value on Fuchsia.
  double get physicalDepth => _physicalDepth;
  double _physicalDepth = double.maxFinite;

A
Adam Barth 已提交
697
  /// The number of physical pixels on each side of the display rectangle into
698 699 700 701
  /// which the application can render, but over which the operating system
  /// will likely place system UI, such as the keyboard, that fully obscures
  /// any content.
  ///
702
  /// When this property changes, [onMetricsChanged] is called.
703
  ///
D
Dan Field 已提交
704 705 706 707
  /// The relationship between this [Window.viewInsets], [Window.viewPadding],
  /// and [Window.padding] are described in more detail in the documentation for
  /// [Window].
  ///
708 709 710 711 712 713 714
  /// See also:
  ///
  ///  * [WidgetsBindingObserver], for a mechanism at the widgets layer to
  ///    observe when this value changes.
  ///  * [MediaQuery.of], a simpler mechanism for the same.
  ///  * [Scaffold], which automatically applies the view insets in material
  ///    design applications.
715 716
  WindowPadding get viewInsets => _viewInsets;
  WindowPadding _viewInsets = WindowPadding.zero;
717 718 719 720 721 722

  /// The number of physical pixels on each side of the display rectangle into
  /// which the application can render, but which may be partially obscured by
  /// system UI (such as the system notification area), or or physical
  /// intrusions in the display (e.g. overscan regions on television screens or
  /// phone sensor housings).
723
  ///
D
Dan Field 已提交
724 725 726 727 728
  /// Unlike [Window.padding], this value does not change relative to
  /// [Window.viewInsets]. For example, on an iPhone X, it will not change in
  /// response to the soft keyboard being visible or hidden, whereas
  /// [Window.padding] will.
  ///
729
  /// When this property changes, [onMetricsChanged] is called.
D
Dan Field 已提交
730 731 732 733 734 735 736 737 738 739 740 741
  ///
  /// The relationship between this [Window.viewInsets], [Window.viewPadding],
  /// and [Window.padding] are described in more detail in the documentation for
  /// [Window].
  ///
  /// See also:
  ///
  ///  * [WidgetsBindingObserver], for a mechanism at the widgets layer to
  ///    observe when this value changes.
  ///  * [MediaQuery.of], a simpler mechanism for the same.
  ///  * [Scaffold], which automatically applies the padding in material design
  ///    applications.
742 743
  WindowPadding get viewPadding => _viewPadding;
  WindowPadding _viewPadding = WindowPadding.zero;
D
Dan Field 已提交
744

745 746 747 748 749 750 751 752 753 754 755 756 757 758 759
  /// The number of physical pixels on each side of the display rectangle into
  /// which the application can render, but where the operating system will
  /// consume input gestures for the sake of system navigation.
  ///
  /// For example, an operating system might use the vertical edges of the
  /// screen, where swiping inwards from the edges takes users backward
  /// through the history of screens they previously visited.
  ///
  /// When this property changes, [onMetricsChanged] is called.
  ///
  /// See also:
  ///
  ///  * [WidgetsBindingObserver], for a mechanism at the widgets layer to
  ///    observe when this value changes.
  ///  * [MediaQuery.of], a simpler mechanism for the same.
760 761
  WindowPadding get systemGestureInsets => _systemGestureInsets;
  WindowPadding _systemGestureInsets = WindowPadding.zero;
762

D
Dan Field 已提交
763 764 765 766 767 768 769 770 771
  /// The number of physical pixels on each side of the display rectangle into
  /// which the application can render, but which may be partially obscured by
  /// system UI (such as the system notification area), or or physical
  /// intrusions in the display (e.g. overscan regions on television screens or
  /// phone sensor housings).
  ///
  /// This value is calculated by taking
  /// `max(0.0, Window.viewPadding - Window.viewInsets)`. This will treat a
  /// system IME that increases the bottom inset as consuming that much of the
772 773 774 775 776
  /// bottom padding. For example, on an iPhone X, [EdgeInsets.bottom] of
  /// [Window.padding] is the same as [EdgeInsets.bottom] of
  /// [Window.viewPadding] when the soft keyboard is not drawn (to account for
  /// the bottom soft button area), but will be `0.0` when the soft keyboard is
  /// visible.
D
Dan Field 已提交
777
  ///
778 779
  /// When this changes, [onMetricsChanged] is called.
  ///
D
Dan Field 已提交
780 781 782 783
  /// The relationship between this [Window.viewInsets], [Window.viewPadding],
  /// and [Window.padding] are described in more detail in the documentation for
  /// [Window].
  ///
784 785 786 787 788 789 790
  /// See also:
  ///
  ///  * [WidgetsBindingObserver], for a mechanism at the widgets layer to
  ///    observe when this value changes.
  ///  * [MediaQuery.of], a simpler mechanism for the same.
  ///  * [Scaffold], which automatically applies the padding in material design
  ///    applications.
791 792
  WindowPadding get padding => _padding;
  WindowPadding _padding = WindowPadding.zero;
A
Adam Barth 已提交
793

A
Adam Barth 已提交
794
  /// A callback that is invoked whenever the [devicePixelRatio],
795 796 797 798
  /// [physicalSize], [padding], [viewInsets], or [systemGestureInsets]
  /// values change, for example when the device is rotated or when the
  /// application is resized (e.g. when showing applications side-by-side
  /// on Android).
Y
Yegor 已提交
799
  ///
800 801 802 803 804 805 806 807 808 809 810
  /// The engine invokes this callback in the same zone in which the callback
  /// was set.
  ///
  /// The framework registers with this callback and updates the layout
  /// appropriately.
  ///
  /// See also:
  ///
  ///  * [WidgetsBindingObserver], for a mechanism at the widgets layer to
  ///    register for notifications when this is called.
  ///  * [MediaQuery.of], a simpler mechanism for the same.
811 812 813 814
  VoidCallback? get onMetricsChanged => _onMetricsChanged;
  VoidCallback? _onMetricsChanged;
  Zone _onMetricsChangedZone = Zone.root;
  set onMetricsChanged(VoidCallback? callback) {
Y
Yegor 已提交
815 816 817
    _onMetricsChanged = callback;
    _onMetricsChangedZone = Zone.current;
  }
818

819 820 821 822 823 824 825 826 827 828
  /// The system-reported default locale of the device.
  ///
  /// This establishes the language and formatting conventions that application
  /// should, if possible, use to render their user interface.
  ///
  /// This is the first locale selected by the user and is the user's
  /// primary locale (the locale the device UI is displayed in)
  ///
  /// This is equivalent to `locales.first` and will provide an empty non-null locale
  /// if the [locales] list has not been set or is empty.
829 830 831
  Locale? get locale {
    if (_locales != null && _locales!.isNotEmpty) {
      return _locales!.first;
832
    }
833
    return null;
834 835 836
  }

  /// The full system-reported supported locales of the device.
837 838 839 840
  ///
  /// This establishes the language and formatting conventions that application
  /// should, if possible, use to render their user interface.
  ///
841 842 843
  /// The list is ordered in order of priority, with lower-indexed locales being
  /// preferred over higher-indexed ones. The first element is the primary [locale].
  ///
844
  /// The [onLocaleChanged] callback is called whenever this value changes.
845 846 847 848 849
  ///
  /// See also:
  ///
  ///  * [WidgetsBindingObserver], for a mechanism at the widgets layer to
  ///    observe when this value changes.
850 851
  List<Locale>? get locales => _locales;
  List<Locale>? _locales;
852

853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878
  /// Performs the platform-native locale resolution.
  ///
  /// Each platform may return different results.
  ///
  /// If the platform fails to resolve a locale, then this will return null.
  ///
  /// This method returns synchronously and is a direct call to
  /// platform specific APIs without invoking method channels.
  Locale? computePlatformResolvedLocale(List<Locale> supportedLocales) {
    final List<String?> supportedLocalesData = <String?>[];
    for (Locale locale in supportedLocales) {
      supportedLocalesData.add(locale.languageCode);
      supportedLocalesData.add(locale.countryCode);
      supportedLocalesData.add(locale.scriptCode);
    }

    final List<String> result = _computePlatformResolvedLocale(supportedLocalesData);

    if (result.isNotEmpty) {
      return Locale.fromSubtags(
        languageCode: result[0],
        countryCode: result[1] == '' ? null : result[1],
        scriptCode: result[2] == '' ? null : result[2]);
    }
    return null;
  }
879
  List<String> _computePlatformResolvedLocale(List<String?> supportedLocalesData) native 'PlatformConfiguration_computePlatformResolvedLocale';
880

881
  /// A callback that is invoked whenever [locale] changes value.
882
  ///
Y
Yegor 已提交
883 884 885
  /// The framework invokes this callback in the same zone in which the
  /// callback was set.
  ///
886 887 888 889
  /// See also:
  ///
  ///  * [WidgetsBindingObserver], for a mechanism at the widgets layer to
  ///    observe when this callback is invoked.
890 891 892 893
  VoidCallback? get onLocaleChanged => _onLocaleChanged;
  VoidCallback? _onLocaleChanged;
  Zone _onLocaleChangedZone = Zone.root;
  set onLocaleChanged(VoidCallback? callback) {
Y
Yegor 已提交
894 895 896
    _onLocaleChanged = callback;
    _onLocaleChangedZone = Zone.current;
  }
897

898 899 900 901 902 903
  /// The lifecycle state immediately after dart isolate initialization.
  ///
  /// This property will not be updated as the lifecycle changes.
  ///
  /// It is used to initialize [SchedulerBinding.lifecycleState] at startup
  /// with any buffered lifecycle state events.
904
  String get initialLifecycleState {
905 906 907
    _initialLifecycleStateAccessed = true;
    return _initialLifecycleState;
  }
908
  late String _initialLifecycleState;
909 910 911
  /// Tracks if the initial state has been accessed. Once accessed, we
  /// will stop updating the [initialLifecycleState], as it is not the
  /// preferred way to access the state.
912
  bool _initialLifecycleStateAccessed = false;
913

914 915 916 917 918 919 920 921 922 923 924 925
  /// The system-reported text scale.
  ///
  /// This establishes the text scaling factor to use when rendering text,
  /// according to the user's platform preferences.
  ///
  /// The [onTextScaleFactorChanged] callback is called whenever this value
  /// changes.
  ///
  /// See also:
  ///
  ///  * [WidgetsBindingObserver], for a mechanism at the widgets layer to
  ///    observe when this value changes.
926 927
  double get textScaleFactor => _textScaleFactor;
  double _textScaleFactor = 1.0;
928

929 930
  /// The setting indicating whether time should always be shown in the 24-hour
  /// format.
931
  ///
932
  /// This option is used by [showTimePicker].
933 934
  bool get alwaysUse24HourFormat => _alwaysUse24HourFormat;
  bool _alwaysUse24HourFormat = false;
935

936 937 938 939 940 941 942 943 944
  /// A callback that is invoked whenever [textScaleFactor] changes value.
  ///
  /// The framework invokes this callback in the same zone in which the
  /// callback was set.
  ///
  /// See also:
  ///
  ///  * [WidgetsBindingObserver], for a mechanism at the widgets layer to
  ///    observe when this callback is invoked.
945 946 947 948
  VoidCallback? get onTextScaleFactorChanged => _onTextScaleFactorChanged;
  VoidCallback? _onTextScaleFactorChanged;
  Zone _onTextScaleFactorChangedZone = Zone.root;
  set onTextScaleFactorChanged(VoidCallback? callback) {
949 950 951 952
    _onTextScaleFactorChanged = callback;
    _onTextScaleFactorChangedZone = Zone.current;
  }

953 954
  /// The setting indicating the current brightness mode of the host platform.
  /// If the platform has no preference, [platformBrightness] defaults to [Brightness.light].
955 956
  Brightness get platformBrightness => _platformBrightness;
  Brightness _platformBrightness = Brightness.light;
957 958 959 960 961 962 963 964 965 966

  /// A callback that is invoked whenever [platformBrightness] changes value.
  ///
  /// The framework invokes this callback in the same zone in which the
  /// callback was set.
  ///
  /// See also:
  ///
  ///  * [WidgetsBindingObserver], for a mechanism at the widgets layer to
  ///    observe when this callback is invoked.
967 968 969 970
  VoidCallback? get onPlatformBrightnessChanged => _onPlatformBrightnessChanged;
  VoidCallback? _onPlatformBrightnessChanged;
  Zone _onPlatformBrightnessChangedZone = Zone.root;
  set onPlatformBrightnessChanged(VoidCallback? callback) {
971 972 973 974
    _onPlatformBrightnessChanged = callback;
    _onPlatformBrightnessChangedZone = Zone.current;
  }

975 976
  /// A callback that is invoked to notify the application that it is an
  /// appropriate time to provide a scene using the [SceneBuilder] API and the
A
Adam Barth 已提交
977 978
  /// [render] method. When possible, this is driven by the hardware VSync
  /// signal. This is only called if [scheduleFrame] has been called since the
979
  /// last time this callback was invoked.
I
Ian Hickson 已提交
980 981 982 983
  ///
  /// The [onDrawFrame] callback is invoked immediately after [onBeginFrame],
  /// after draining any microtasks (e.g. completions of any [Future]s) queued
  /// by the [onBeginFrame] handler.
984
  ///
Y
Yegor 已提交
985 986 987
  /// The framework invokes this callback in the same zone in which the
  /// callback was set.
  ///
988 989 990 991 992 993
  /// See also:
  ///
  ///  * [SchedulerBinding], the Flutter framework class which manages the
  ///    scheduling of frames.
  ///  * [RendererBinding], the Flutter framework class which manages layout and
  ///    painting.
994 995 996 997
  FrameCallback? get onBeginFrame => _onBeginFrame;
  FrameCallback? _onBeginFrame;
  Zone _onBeginFrameZone = Zone.root;
  set onBeginFrame(FrameCallback? callback) {
Y
Yegor 已提交
998 999 1000
    _onBeginFrame = callback;
    _onBeginFrameZone = Zone.current;
  }
1001

I
Ian Hickson 已提交
1002 1003
  /// A callback that is invoked for each frame after [onBeginFrame] has
  /// completed and after the microtask queue has been drained. This can be
1004
  /// used to implement a second phase of frame rendering that happens
I
Ian Hickson 已提交
1005
  /// after any deferred work queued by the [onBeginFrame] phase.
1006
  ///
Y
Yegor 已提交
1007 1008 1009
  /// The framework invokes this callback in the same zone in which the
  /// callback was set.
  ///
1010 1011 1012 1013 1014 1015
  /// See also:
  ///
  ///  * [SchedulerBinding], the Flutter framework class which manages the
  ///    scheduling of frames.
  ///  * [RendererBinding], the Flutter framework class which manages layout and
  ///    painting.
1016 1017 1018 1019
  VoidCallback? get onDrawFrame => _onDrawFrame;
  VoidCallback? _onDrawFrame;
  Zone _onDrawFrameZone = Zone.root;
  set onDrawFrame(VoidCallback? callback) {
Y
Yegor 已提交
1020 1021 1022
    _onDrawFrame = callback;
    _onDrawFrameZone = Zone.current;
  }
1023

1024 1025 1026
  /// A callback that is invoked to report the [FrameTiming] of recently
  /// rasterized frames.
  ///
1027 1028 1029 1030
  /// It's prefered to use [SchedulerBinding.addTimingsCallback] than to use
  /// [Window.onReportTimings] directly because
  /// [SchedulerBinding.addTimingsCallback] allows multiple callbacks.
  ///
1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044
  /// This can be used to see if the application has missed frames (through
  /// [FrameTiming.buildDuration] and [FrameTiming.rasterDuration]), or high
  /// latencies (through [FrameTiming.totalSpan]).
  ///
  /// Unlike [Timeline], the timing information here is available in the release
  /// mode (additional to the profile and the debug mode). Hence this can be
  /// used to monitor the application's performance in the wild.
  ///
  /// {@macro dart.ui.TimingsCallback.list}
  ///
  /// If this is null, no additional work will be done. If this is not null,
  /// Flutter spends less than 0.1ms every 1 second to report the timings
  /// (measured on iPhone6S). The 0.1ms is about 0.6% of 16ms (frame budget for
  /// 60fps), or 0.01% CPU usage per second.
1045 1046 1047 1048
  TimingsCallback? get onReportTimings => _onReportTimings;
  TimingsCallback? _onReportTimings;
  Zone _onReportTimingsZone = Zone.root;
  set onReportTimings(TimingsCallback? callback) {
1049 1050 1051 1052 1053 1054 1055
    if ((callback == null) != (_onReportTimings == null)) {
      _setNeedsReportTimings(callback != null);
    }
    _onReportTimings = callback;
    _onReportTimingsZone = Zone.current;
  }

1056
  late _SetNeedsReportTimingsFunc _setNeedsReportTimings;
1057
  void _nativeSetNeedsReportTimings(bool value) native 'PlatformConfiguration_setNeedsReportTimings';
1058

1059
  /// A callback that is invoked when pointer data is available.
1060
  ///
Y
Yegor 已提交
1061 1062 1063
  /// The framework invokes this callback in the same zone in which the
  /// callback was set.
  ///
1064 1065 1066 1067
  /// See also:
  ///
  ///  * [GestureBinding], the Flutter framework class which manages pointer
  ///    events.
1068 1069 1070 1071
  PointerDataPacketCallback? get onPointerDataPacket => _onPointerDataPacket;
  PointerDataPacketCallback? _onPointerDataPacket;
  Zone _onPointerDataPacketZone = Zone.root;
  set onPointerDataPacket(PointerDataPacketCallback? callback) {
Y
Yegor 已提交
1072 1073 1074
    _onPointerDataPacket = callback;
    _onPointerDataPacketZone = Zone.current;
  }
1075

1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105
  /// The route or path that the embedder requested when the application was
  /// launched.
  ///
  /// This will be the string "`/`" if no particular route was requested.
  ///
  /// ## Android
  ///
  /// On Android, calling
  /// [`FlutterView.setInitialRoute`](/javadoc/io/flutter/view/FlutterView.html#setInitialRoute-java.lang.String-)
  /// will set this value. The value must be set sufficiently early, i.e. before
  /// the [runApp] call is executed in Dart, for this to have any effect on the
  /// framework. The `createFlutterView` method in your `FlutterActivity`
  /// subclass is a suitable time to set the value. The application's
  /// `AndroidManifest.xml` file must also be updated to have a suitable
  /// [`<intent-filter>`](https://developer.android.com/guide/topics/manifest/intent-filter-element.html).
  ///
  /// ## iOS
  ///
  /// On iOS, calling
  /// [`FlutterViewController.setInitialRoute`](/objcdoc/Classes/FlutterViewController.html#/c:objc%28cs%29FlutterViewController%28im%29setInitialRoute:)
  /// will set this value. The value must be set sufficiently early, i.e. before
  /// the [runApp] call is executed in Dart, for this to have any effect on the
  /// framework. The `application:didFinishLaunchingWithOptions:` method is a
  /// suitable time to set this value.
  ///
  /// See also:
  ///
  ///  * [Navigator], a widget that handles routing.
  ///  * [SystemChannels.navigation], which handles subsequent navigation
  ///    requests from the embedder.
1106
  String get defaultRouteName => _defaultRouteName();
1107
  String _defaultRouteName() native 'PlatformConfiguration_defaultRouteName';
1108 1109

  /// Requests that, at the next appropriate opportunity, the [onBeginFrame]
I
Ian Hickson 已提交
1110
  /// and [onDrawFrame] callbacks be invoked.
1111 1112 1113 1114 1115
  ///
  /// See also:
  ///
  ///  * [SchedulerBinding], the Flutter framework class which manages the
  ///    scheduling of frames.
1116
  void scheduleFrame() native 'PlatformConfiguration_scheduleFrame';
1117 1118

  /// Updates the application's rendering on the GPU with the newly provided
1119
  /// [Scene]. This function must be called within the scope of the
I
Ian Hickson 已提交
1120 1121 1122 1123
  /// [onBeginFrame] or [onDrawFrame] callbacks being invoked. If this function
  /// is called a second time during a single [onBeginFrame]/[onDrawFrame]
  /// callback sequence or called outside the scope of those callbacks, the call
  /// will be ignored.
H
Hixie 已提交
1124
  ///
I
Ian Hickson 已提交
1125 1126 1127 1128 1129
  /// To record graphical operations, first create a [PictureRecorder], then
  /// construct a [Canvas], passing that [PictureRecorder] to its constructor.
  /// After issuing all the graphical operations, call the
  /// [PictureRecorder.endRecording] function on the [PictureRecorder] to obtain
  /// the final [Picture] that represents the issued graphical operations.
1130
  ///
H
Hixie 已提交
1131
  /// Next, create a [SceneBuilder], and add the [Picture] to it using
I
Ian Hickson 已提交
1132 1133 1134
  /// [SceneBuilder.addPicture]. With the [SceneBuilder.build] method you can
  /// then obtain a [Scene] object, which you can display to the user via this
  /// [render] function.
1135 1136 1137 1138 1139 1140 1141
  ///
  /// See also:
  ///
  ///  * [SchedulerBinding], the Flutter framework class which manages the
  ///    scheduling of frames.
  ///  * [RendererBinding], the Flutter framework class which manages layout and
  ///    painting.
1142
  void render(Scene scene) native 'PlatformConfiguration_render';
1143 1144 1145 1146 1147 1148

  /// Whether the user has requested that [updateSemantics] be called when
  /// the semantic contents of window changes.
  ///
  /// The [onSemanticsEnabledChanged] callback is called whenever this value
  /// changes.
1149 1150
  bool get semanticsEnabled => _semanticsEnabled;
  bool _semanticsEnabled = false;
1151 1152

  /// A callback that is invoked when the value of [semanticsEnabled] changes.
Y
Yegor 已提交
1153 1154 1155
  ///
  /// The framework invokes this callback in the same zone in which the
  /// callback was set.
1156 1157 1158 1159
  VoidCallback? get onSemanticsEnabledChanged => _onSemanticsEnabledChanged;
  VoidCallback? _onSemanticsEnabledChanged;
  Zone _onSemanticsEnabledChangedZone = Zone.root;
  set onSemanticsEnabledChanged(VoidCallback? callback) {
Y
Yegor 已提交
1160 1161 1162
    _onSemanticsEnabledChanged = callback;
    _onSemanticsEnabledChangedZone = Zone.current;
  }
1163 1164 1165 1166 1167 1168

  /// A callback that is invoked whenever the user requests an action to be
  /// performed.
  ///
  /// This callback is used when the user expresses the action they wish to
  /// perform based on the semantics supplied by [updateSemantics].
Y
Yegor 已提交
1169 1170 1171
  ///
  /// The framework invokes this callback in the same zone in which the
  /// callback was set.
1172 1173 1174 1175
  SemanticsActionCallback? get onSemanticsAction => _onSemanticsAction;
  SemanticsActionCallback? _onSemanticsAction;
  Zone _onSemanticsActionZone = Zone.root;
  set onSemanticsAction(SemanticsActionCallback? callback) {
Y
Yegor 已提交
1176 1177 1178
    _onSemanticsAction = callback;
    _onSemanticsActionZone = Zone.current;
  }
1179

1180
  /// Additional accessibility features that may be enabled by the platform.
1181
  AccessibilityFeatures get accessibilityFeatures => _accessibilityFeatures;
1182
  // The zero value matches the default value in `platform_data.h`.
1183
  AccessibilityFeatures _accessibilityFeatures = const AccessibilityFeatures._(0);
1184

1185
  /// A callback that is invoked when the value of [accessibilityFeatures] changes.
1186 1187 1188
  ///
  /// The framework invokes this callback in the same zone in which the
  /// callback was set.
1189 1190 1191 1192
  VoidCallback? get onAccessibilityFeaturesChanged => _onAccessibilityFeaturesChanged;
  VoidCallback? _onAccessibilityFeaturesChanged;
  Zone _onAccessibilityFeaturesChangedZone = Zone.root;
  set onAccessibilityFeaturesChanged(VoidCallback? callback) {
1193
    _onAccessibilityFeaturesChanged = callback;
1194
    _onAccessibilityFeaturesChangedZone = Zone.current;
1195 1196
  }

1197 1198
  /// Change the retained semantics data about this window.
  ///
C
Chris Bracken 已提交
1199
  /// If [semanticsEnabled] is true, the user has requested that this function
1200 1201 1202 1203
  /// be called whenever the semantic content of this window changes.
  ///
  /// In either case, this function disposes the given update, which means the
  /// semantics update cannot be used further.
1204
  void updateSemantics(SemanticsUpdate update) native 'PlatformConfiguration_updateSemantics';
1205

1206 1207 1208 1209 1210 1211 1212 1213
  /// Set the debug name associated with this window's root isolate.
  ///
  /// Normally debug names are automatically generated from the Dart port, entry
  /// point, and source file. For example: `main.dart$main-1234`.
  ///
  /// This can be combined with flutter tools `--isolate-filter` flag to debug
  /// specific root isolates. For example: `flutter attach --isolate-filter=[name]`.
  /// Note that this does not rename any child isolates of the root.
1214
  void setIsolateDebugName(String name) native 'PlatformConfiguration_setIsolateDebugName';
1215

A
Adam Barth 已提交
1216 1217 1218 1219 1220 1221
  /// Sends a message to a platform-specific plugin.
  ///
  /// The `name` parameter determines which plugin receives the message. The
  /// `data` parameter contains the message payload and is typically UTF-8
  /// encoded JSON but can be arbitrary data. If the plugin replies to the
  /// message, `callback` will be called with the response.
Y
Yegor 已提交
1222 1223 1224
  ///
  /// The framework invokes [callback] in the same zone in which this method
  /// was called.
1225 1226 1227 1228
  void sendPlatformMessage(String name,
                           ByteData? data,
                           PlatformMessageResponseCallback? callback) {
    final String? error =
1229 1230
        _sendPlatformMessage(name, _zonedPlatformMessageResponseCallback(callback), data);
    if (error != null)
D
Dan Field 已提交
1231
      throw Exception(error);
1232
  }
1233 1234
  String? _sendPlatformMessage(String name,
                              PlatformMessageResponseCallback? callback,
1235
                              ByteData? data) native 'PlatformConfiguration_sendPlatformMessage';
1236

A
Adam Barth 已提交
1237 1238 1239 1240 1241 1242 1243 1244
  /// Called whenever this window receives a message from a platform-specific
  /// plugin.
  ///
  /// The `name` parameter determines which plugin sent the message. The `data`
  /// parameter is the payload and is typically UTF-8 encoded JSON but can be
  /// arbitrary data.
  ///
  /// Message handlers must call the function given in the `callback` parameter.
1245
  /// If the handler does not need to respond, the handler should pass null to
A
Adam Barth 已提交
1246
  /// the callback.
Y
Yegor 已提交
1247 1248 1249
  ///
  /// The framework invokes this callback in the same zone in which the
  /// callback was set.
1250 1251 1252 1253
  PlatformMessageCallback? get onPlatformMessage => _onPlatformMessage;
  PlatformMessageCallback? _onPlatformMessage;
  Zone _onPlatformMessageZone = Zone.root;
  set onPlatformMessage(PlatformMessageCallback? callback) {
Y
Yegor 已提交
1254 1255 1256
    _onPlatformMessage = callback;
    _onPlatformMessageZone = Zone.current;
  }
A
Adam Barth 已提交
1257 1258

  /// Called by [_dispatchPlatformMessage].
1259
  void _respondToPlatformMessage(int responseId, ByteData? data)
1260
      native 'PlatformConfiguration_respondToPlatformMessage';
Y
Yegor 已提交
1261 1262 1263

  /// Wraps the given [callback] in another callback that ensures that the
  /// original callback is called in the zone it was registered in.
1264
  static PlatformMessageResponseCallback? _zonedPlatformMessageResponseCallback(PlatformMessageResponseCallback? callback) {
Y
Yegor 已提交
1265 1266 1267 1268 1269 1270
    if (callback == null)
      return null;

    // Store the zone in which the callback is being registered.
    final Zone registrationZone = Zone.current;

1271
    return (ByteData? data) {
1272
      registrationZone.runUnaryGuarded(callback, data);
Y
Yegor 已提交
1273 1274
    };
  }
1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285


  /// The embedder can specify data that the isolate can request synchronously
  /// on launch. This accessor fetches that data.
  ///
  /// This data is persistent for the duration of the Flutter application and is
  /// available even after isolate restarts. Because of this lifecycle, the size
  /// of this data must be kept to a minimum.
  ///
  /// For asynchronous communication between the embedder and isolate, a
  /// platform channel may be used.
1286
  ByteData? getPersistentIsolateData() native 'PlatformConfiguration_getPersistentIsolateData';
A
Adam Barth 已提交
1287 1288
}

1289 1290 1291 1292 1293
/// Additional accessibility features that may be enabled by the platform.
///
/// It is not possible to enable these settings from Flutter, instead they are
/// used by the platform to indicate that additional accessibility features are
/// enabled.
1294 1295 1296
//
// When changes are made to this class, the equivalent APIs in each of the
// embedders *must* be updated.
1297 1298 1299 1300 1301 1302
class AccessibilityFeatures {
  const AccessibilityFeatures._(this._index);

  static const int _kAccessibleNavigation = 1 << 0;
  static const int _kInvertColorsIndex = 1 << 1;
  static const int _kDisableAnimationsIndex = 1 << 2;
1303
  static const int _kBoldTextIndex = 1 << 3;
1304
  static const int _kReduceMotionIndex = 1 << 4;
1305
  static const int _kHighContrastIndex = 1 << 5;
1306 1307

  // A bitfield which represents each enabled feature.
1308
  final int _index;
1309 1310 1311 1312 1313

  /// Whether there is a running accessibility service which is changing the
  /// interaction model of the device.
  ///
  /// For example, TalkBack on Android and VoiceOver on iOS enable this flag.
1314
  bool get accessibleNavigation => _kAccessibleNavigation & _index != 0;
1315 1316

  /// The platform is inverting the colors of the application.
1317
  bool get invertColors => _kInvertColorsIndex & _index != 0;
1318 1319

  /// The platform is requesting that animations be disabled or simplified.
1320
  bool get disableAnimations => _kDisableAnimationsIndex & _index != 0;
1321

1322 1323 1324
  /// The platform is requesting that text be rendered at a bold font weight.
  ///
  /// Only supported on iOS.
1325
  bool get boldText => _kBoldTextIndex & _index != 0;
1326

1327 1328 1329 1330
  /// The platform is requesting that certain animations be simplified and
  /// parallax effects removed.
  ///
  /// Only supported on iOS.
1331
  bool get reduceMotion => _kReduceMotionIndex & _index != 0;
1332

1333 1334 1335
  /// The platform is requesting that UI be rendered with darker colors.
  ///
  /// Only supported on iOS.
1336
  bool get highContrast => _kHighContrastIndex & _index != 0;
1337

1338
  @override
1339
  String toString() {
1340 1341 1342 1343 1344 1345 1346
    final List<String> features = <String>[];
    if (accessibleNavigation)
      features.add('accessibleNavigation');
    if (invertColors)
      features.add('invertColors');
    if (disableAnimations)
      features.add('disableAnimations');
1347 1348
    if (boldText)
      features.add('boldText');
1349 1350
    if (reduceMotion)
      features.add('reduceMotion');
1351 1352
    if (highContrast)
      features.add('highContrast');
1353 1354 1355 1356
    return 'AccessibilityFeatures$features';
  }

  @override
A
Alexandre Ardhuin 已提交
1357
  bool operator ==(Object other) {
1358 1359
    if (other.runtimeType != runtimeType)
      return false;
1360 1361
    return other is AccessibilityFeatures
        && other._index == _index;
1362 1363 1364
  }

  @override
1365
  int get hashCode => _index.hashCode;
1366 1367
}

1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382
/// Describes the contrast of a theme or color palette.
enum Brightness {
  /// The color is dark and will require a light text color to achieve readable
  /// contrast.
  ///
  /// For example, the color might be dark grey, requiring white text.
  dark,

  /// The color is light and will require a dark text color to achieve readable
  /// contrast.
  ///
  /// For example, the color might be bright white, requiring black text.
  light,
}

L
liyuqian 已提交
1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397
/// The [Window] singleton.
///
/// Please try to avoid statically referencing this and instead use a
/// binding for dependency resolution such as `WidgetsBinding.instance.window`.
///
/// Static access of this "window" object means that Flutter has few, if any
/// options to fake or mock the given object in tests. Even in cases where Dart
/// offers special language constructs to forcefully shadow such properties,
/// those mechanisms would only be reasonable for tests and they would not be
/// reasonable for a future of Flutter where we legitimately want to select an
/// appropriate implementation at runtime.
///
/// The only place that `WidgetsBinding.instance.window` is inappropriate is if
/// a `Window` is required before invoking `runApp()`. In that case, it is
/// acceptable (though unfortunate) to use this object statically.
1398
final Window window = Window._();