-
Notifications
You must be signed in to change notification settings - Fork 5.9k
/
platform_dispatcher.dart
1438 lines (1291 loc) · 51.4 KB
/
platform_dispatcher.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
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
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
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
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
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
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart:convert';
import 'dart:js_interop';
import 'dart:typed_data';
import 'package:ui/ui.dart' as ui;
import 'package:ui/ui_web/src/ui_web.dart' as ui_web;
import '../engine.dart';
/// Requests that the browser schedule a frame.
///
/// This may be overridden in tests, for example, to pump fake frames.
ui.VoidCallback? scheduleFrameCallback;
/// Signature of functions added as a listener to high contrast changes
typedef HighContrastListener = void Function(bool enabled);
typedef _KeyDataResponseCallback = void Function(bool handled);
const StandardMethodCodec standardCodec = StandardMethodCodec();
const JSONMethodCodec jsonCodec = JSONMethodCodec();
/// Determines if high contrast is enabled using media query 'forced-colors: active' for Windows
class HighContrastSupport {
static HighContrastSupport instance = HighContrastSupport();
static const String _highContrastMediaQueryString = '(forced-colors: active)';
final List<HighContrastListener> _listeners = <HighContrastListener>[];
/// Reference to css media query that indicates whether high contrast is on.
final DomMediaQueryList _highContrastMediaQuery = domWindow.matchMedia(_highContrastMediaQueryString);
late final DomEventListener _onHighContrastChangeListener =
createDomEventListener(_onHighContrastChange);
bool get isHighContrastEnabled => _highContrastMediaQuery.matches;
/// Adds function to the list of listeners on high contrast changes
void addListener(HighContrastListener listener) {
if (_listeners.isEmpty) {
_highContrastMediaQuery.addListener(_onHighContrastChangeListener);
}
_listeners.add(listener);
}
/// Removes function from the list of listeners on high contrast changes
void removeListener(HighContrastListener listener) {
_listeners.remove(listener);
if (_listeners.isEmpty) {
_highContrastMediaQuery.removeListener(_onHighContrastChangeListener);
}
}
JSVoid _onHighContrastChange(DomEvent event) {
final DomMediaQueryListEvent mqEvent = event as DomMediaQueryListEvent;
final bool isHighContrastEnabled = mqEvent.matches!;
for (final HighContrastListener listener in _listeners) {
listener(isHighContrastEnabled);
}
}
}
/// Platform event dispatcher.
///
/// This is the central entry point for platform messages and configuration
/// events from the platform.
class EnginePlatformDispatcher extends ui.PlatformDispatcher {
/// Private constructor, since only dart:ui is supposed to create one of
/// these.
EnginePlatformDispatcher() {
_addBrightnessMediaQueryListener();
HighContrastSupport.instance.addListener(_updateHighContrast);
_addFontSizeObserver();
_addLocaleChangedListener();
registerHotRestartListener(dispose);
_setAppLifecycleState(ui.AppLifecycleState.resumed);
}
/// The [EnginePlatformDispatcher] singleton.
static EnginePlatformDispatcher get instance => _instance;
static final EnginePlatformDispatcher _instance = EnginePlatformDispatcher();
PlatformConfiguration configuration = PlatformConfiguration(
locales: parseBrowserLanguages(),
textScaleFactor: findBrowserTextScaleFactor(),
accessibilityFeatures: computeAccessibilityFeatures(),
);
/// Compute accessibility features based on the current value of high contrast flag
static EngineAccessibilityFeatures computeAccessibilityFeatures() {
final EngineAccessibilityFeaturesBuilder builder =
EngineAccessibilityFeaturesBuilder(0);
if (HighContrastSupport.instance.isHighContrastEnabled) {
builder.highContrast = true;
}
return builder.build();
}
void dispose() {
_removeBrightnessMediaQueryListener();
_disconnectFontSizeObserver();
_removeLocaleChangedListener();
HighContrastSupport.instance.removeListener(_updateHighContrast);
}
/// Receives all events related to platform configuration changes.
@override
ui.VoidCallback? get onPlatformConfigurationChanged =>
_onPlatformConfigurationChanged;
ui.VoidCallback? _onPlatformConfigurationChanged;
Zone? _onPlatformConfigurationChangedZone;
@override
set onPlatformConfigurationChanged(ui.VoidCallback? callback) {
_onPlatformConfigurationChanged = callback;
_onPlatformConfigurationChangedZone = Zone.current;
}
/// Engine code should use this method instead of the callback directly.
/// Otherwise zones won't work properly.
void invokeOnPlatformConfigurationChanged() {
invoke(
_onPlatformConfigurationChanged, _onPlatformConfigurationChangedZone);
}
@override
Iterable<EngineFlutterDisplay> displays = <EngineFlutterDisplay>[
EngineFlutterDisplay.instance,
];
/// Adds [view] to the platform dispatcher's registry of [views].
void registerView(EngineFlutterView view) {
viewData[view.viewId] = view;
}
/// The current list of windows.
@override
Iterable<EngineFlutterView> get views => viewData.values;
final Map<int, EngineFlutterView> viewData = <int, EngineFlutterView>{};
/// Returns the [EngineFlutterView] with the provided ID if one exists, or null
/// otherwise.
@override
EngineFlutterView? view({required int id}) => viewData[id];
/// The [FlutterView] provided by the engine if the platform is unable to
/// create windows, or, for backwards compatibility.
///
/// If the platform provides an implicit view, it can be used to bootstrap
/// the framework. This is common for platforms designed for single-view
/// applications like mobile devices with a single display.
///
/// Applications and libraries must not rely on this property being set
/// as it may be null depending on the engine's configuration. Instead,
/// consider using [View.of] to lookup the [FlutterView] the current
/// [BuildContext] is drawing into.
///
/// While the properties on the referenced [FlutterView] may change,
/// the reference itself is guaranteed to never change over the lifetime
/// of the application: if this property is null at startup, it will remain
/// so throughout the entire lifetime of the application. If it points to a
/// specific [FlutterView], it will continue to point to the same view until
/// the application is shut down (although the engine may replace or remove
/// the underlying backing surface of the view at its discretion).
///
/// See also:
///
/// * [View.of], for accessing the current view.
/// * [PlatformDisptacher.views] for a list of all [FlutterView]s provided
/// by the platform.
@override
EngineFlutterWindow? get implicitView => viewData[kImplicitViewId] as EngineFlutterWindow?;
/// A callback that is invoked whenever the platform's [devicePixelRatio],
/// [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).
///
/// 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.
@override
ui.VoidCallback? get onMetricsChanged => _onMetricsChanged;
ui.VoidCallback? _onMetricsChanged;
Zone? _onMetricsChangedZone;
@override
set onMetricsChanged(ui.VoidCallback? callback) {
_onMetricsChanged = callback;
_onMetricsChangedZone = Zone.current;
}
/// Engine code should use this method instead of the callback directly.
/// Otherwise zones won't work properly.
void invokeOnMetricsChanged() {
if (_onMetricsChanged != null) {
invoke(_onMetricsChanged, _onMetricsChangedZone);
}
}
/// A callback invoked when any window begins a frame.
///
/// 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
/// [PlatformWindow.render] method.
/// When possible, this is driven by the hardware VSync signal of the attached
/// screen with the highest VSync rate. This is only called if
/// [PlatformWindow.scheduleFrame] has been called since the last time this
/// callback was invoked.
@override
ui.FrameCallback? get onBeginFrame => _onBeginFrame;
ui.FrameCallback? _onBeginFrame;
Zone? _onBeginFrameZone;
@override
set onBeginFrame(ui.FrameCallback? callback) {
_onBeginFrame = callback;
_onBeginFrameZone = Zone.current;
}
/// Engine code should use this method instead of the callback directly.
/// Otherwise zones won't work properly.
void invokeOnBeginFrame(Duration duration) {
invoke1<Duration>(_onBeginFrame, _onBeginFrameZone, duration);
}
/// A callback that is invoked for each frame after [onBeginFrame] has
/// completed and after the microtask queue has been drained.
///
/// This can be used to implement a second phase of frame rendering that
/// happens after any deferred work queued by the [onBeginFrame] phase.
@override
ui.VoidCallback? get onDrawFrame => _onDrawFrame;
ui.VoidCallback? _onDrawFrame;
Zone? _onDrawFrameZone;
@override
set onDrawFrame(ui.VoidCallback? callback) {
_onDrawFrame = callback;
_onDrawFrameZone = Zone.current;
}
/// Engine code should use this method instead of the callback directly.
/// Otherwise zones won't work properly.
void invokeOnDrawFrame() {
invoke(_onDrawFrame, _onDrawFrameZone);
}
/// A callback that is invoked when pointer data is available.
///
/// The framework invokes this callback in the same zone in which the
/// callback was set.
///
/// See also:
///
/// * [GestureBinding], the Flutter framework class which manages pointer
/// events.
@override
ui.PointerDataPacketCallback? get onPointerDataPacket => _onPointerDataPacket;
ui.PointerDataPacketCallback? _onPointerDataPacket;
Zone? _onPointerDataPacketZone;
@override
set onPointerDataPacket(ui.PointerDataPacketCallback? callback) {
_onPointerDataPacket = callback;
_onPointerDataPacketZone = Zone.current;
}
/// Engine code should use this method instead of the callback directly.
/// Otherwise zones won't work properly.
void invokeOnPointerDataPacket(ui.PointerDataPacket dataPacket) {
invoke1<ui.PointerDataPacket>(
_onPointerDataPacket, _onPointerDataPacketZone, dataPacket);
}
/// A callback that is invoked when key data is available.
///
/// The framework invokes this callback in the same zone in which the
/// callback was set.
///
/// See also:
///
/// * [GestureBinding], the Flutter framework class which manages pointer
/// events.
@override
ui.KeyDataCallback? get onKeyData => _onKeyData;
ui.KeyDataCallback? _onKeyData;
Zone? _onKeyDataZone;
@override
set onKeyData(ui.KeyDataCallback? callback) {
_onKeyData = callback;
_onKeyDataZone = Zone.current;
}
/// Engine code should use this method instead of the callback directly.
/// Otherwise zones won't work properly.
void invokeOnKeyData(ui.KeyData data, _KeyDataResponseCallback callback) {
final ui.KeyDataCallback? onKeyData = _onKeyData;
if (onKeyData != null) {
invoke(
() => callback(onKeyData(data)),
_onKeyDataZone,
);
} else {
callback(false);
}
}
/// A callback that is invoked to report the [FrameTiming] of recently
/// rasterized frames.
///
/// It's preferred to use [SchedulerBinding.addTimingsCallback] than to use
/// [PlatformDispatcher.onReportTimings] directly because
/// [SchedulerBinding.addTimingsCallback] allows multiple callbacks.
///
/// 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.
@override
ui.TimingsCallback? get onReportTimings => _onReportTimings;
ui.TimingsCallback? _onReportTimings;
Zone? _onReportTimingsZone;
@override
set onReportTimings(ui.TimingsCallback? callback) {
_onReportTimings = callback;
_onReportTimingsZone = Zone.current;
}
/// Engine code should use this method instead of the callback directly.
/// Otherwise zones won't work properly.
void invokeOnReportTimings(List<ui.FrameTiming> timings) {
invoke1<List<ui.FrameTiming>>(
_onReportTimings, _onReportTimingsZone, timings);
}
@override
void sendPlatformMessage(
String name,
ByteData? data,
ui.PlatformMessageResponseCallback? callback,
) {
_sendPlatformMessage(
name, data, _zonedPlatformMessageResponseCallback(callback));
}
@override
void sendPortPlatformMessage(
String name,
ByteData? data,
int identifier,
Object port,
) {
throw Exception("Isolates aren't supported in web.");
}
@override
void registerBackgroundIsolate(ui.RootIsolateToken token) {
throw Exception("Isolates aren't supported in web.");
}
// TODO(ianh): Deprecate onPlatformMessage once the framework is moved over
// to using channel buffers exclusively.
@override
ui.PlatformMessageCallback? get onPlatformMessage => _onPlatformMessage;
ui.PlatformMessageCallback? _onPlatformMessage;
Zone? _onPlatformMessageZone;
@override
set onPlatformMessage(ui.PlatformMessageCallback? callback) {
_onPlatformMessage = callback;
_onPlatformMessageZone = Zone.current;
}
/// Engine code should use this method instead of the callback directly.
/// Otherwise zones won't work properly.
void invokeOnPlatformMessage(
String name,
ByteData? data,
ui.PlatformMessageResponseCallback callback,
) {
if (name == ui.ChannelBuffers.kControlChannelName) {
// TODO(ianh): move this logic into ChannelBuffers once we remove onPlatformMessage
try {
ui.channelBuffers.handleMessage(data!);
} finally {
callback(null);
}
} else if (_onPlatformMessage != null) {
invoke3<String, ByteData?, ui.PlatformMessageResponseCallback>(
_onPlatformMessage,
_onPlatformMessageZone,
name,
data,
callback,
);
} else {
ui.channelBuffers.push(name, data, callback);
}
}
/// Wraps the given [callback] in another callback that ensures that the
/// original callback is called in the zone it was registered in.
static ui.PlatformMessageResponseCallback?
_zonedPlatformMessageResponseCallback(
ui.PlatformMessageResponseCallback? callback) {
if (callback == null) {
return null;
}
// Store the zone in which the callback is being registered.
final Zone registrationZone = Zone.current;
return (ByteData? data) {
registrationZone.runUnaryGuarded(callback, data);
};
}
void _sendPlatformMessage(
String name,
ByteData? data,
ui.PlatformMessageResponseCallback? callback,
) {
// In widget tests we want to bypass processing of platform messages.
bool returnImmediately = false;
assert(() {
if (ui_web.debugEmulateFlutterTesterEnvironment) {
returnImmediately = true;
}
return true;
}());
if (returnImmediately) {
return;
}
if (debugPrintPlatformMessages) {
print('Sent platform message on channel: "$name"');
}
bool allowDebugEcho = false;
assert(() {
allowDebugEcho = true;
return true;
}());
if (allowDebugEcho && name == 'flutter/debug-echo') {
// Echoes back the data unchanged. Used for testing purposes.
replyToPlatformMessage(callback, data);
return;
}
switch (name) {
/// This should be in sync with shell/common/shell.cc
case 'flutter/skia':
final MethodCall decoded = jsonCodec.decodeMethodCall(data);
switch (decoded.method) {
case 'Skia.setResourceCacheMaxBytes':
if (renderer is CanvasKitRenderer) {
assert(
decoded.arguments is int,
'Argument to Skia.setResourceCacheMaxBytes must be an int, but was ${decoded.arguments.runtimeType}',
);
final int cacheSizeInBytes = decoded.arguments as int;
CanvasKitRenderer.instance.resourceCacheMaxBytes = cacheSizeInBytes;
}
// Also respond in HTML mode. Otherwise, apps would have to detect
// CanvasKit vs HTML before invoking this method.
replyToPlatformMessage(
callback, jsonCodec.encodeSuccessEnvelope(<bool>[true]));
}
return;
case 'flutter/assets':
final String url = utf8.decode(data!.buffer.asUint8List());
_handleFlutterAssetsMessage(url, callback);
return;
case 'flutter/platform':
final MethodCall decoded = jsonCodec.decodeMethodCall(data);
switch (decoded.method) {
case 'SystemNavigator.pop':
// TODO(a-wallen): As multi-window support expands, the pop call
// will need to include the view ID. Right now only one view is
// supported.
implicitView!.browserHistory.exit().then((_) {
replyToPlatformMessage(
callback, jsonCodec.encodeSuccessEnvelope(true));
});
return;
case 'HapticFeedback.vibrate':
final String? type = decoded.arguments as String?;
vibrate(_getHapticFeedbackDuration(type));
replyToPlatformMessage(callback, jsonCodec.encodeSuccessEnvelope(true));
return;
case 'SystemChrome.setApplicationSwitcherDescription':
final Map<String, Object?> arguments = decoded.arguments as Map<String, Object?>;
final String label = arguments['label'] as String? ?? '';
// TODO(web): Stop setting the color from here, https://github.com/flutter/flutter/issues/123365
final int primaryColor = arguments['primaryColor'] as int? ?? 0xFF000000;
domDocument.title = label;
setThemeColor(ui.Color(primaryColor));
replyToPlatformMessage(callback, jsonCodec.encodeSuccessEnvelope(true));
return;
case 'SystemChrome.setSystemUIOverlayStyle':
final Map<String, Object?> arguments = decoded.arguments as Map<String, Object?>;
final int? statusBarColor = arguments['statusBarColor'] as int?;
setThemeColor(statusBarColor == null ? null : ui.Color(statusBarColor));
replyToPlatformMessage(callback, jsonCodec.encodeSuccessEnvelope(true));
return;
case 'SystemChrome.setPreferredOrientations':
final List<dynamic> arguments = decoded.arguments as List<dynamic>;
ScreenOrientation.instance.setPreferredOrientation(arguments).then((bool success) {
replyToPlatformMessage(
callback, jsonCodec.encodeSuccessEnvelope(success));
});
return;
case 'SystemSound.play':
// There are no default system sounds on web.
replyToPlatformMessage(callback, jsonCodec.encodeSuccessEnvelope(true));
return;
case 'Clipboard.setData':
ClipboardMessageHandler().setDataMethodCall(decoded, callback);
return;
case 'Clipboard.getData':
ClipboardMessageHandler().getDataMethodCall(callback);
return;
case 'Clipboard.hasStrings':
ClipboardMessageHandler().hasStringsMethodCall(callback);
return;
}
// Dispatched by the bindings to delay service worker initialization.
case 'flutter/service_worker':
domWindow.dispatchEvent(createDomEvent('Event', 'flutter-first-frame'));
return;
case 'flutter/textinput':
textEditing.channel.handleTextInput(data, callback);
return;
case 'flutter/contextmenu':
final MethodCall decoded = jsonCodec.decodeMethodCall(data);
switch (decoded.method) {
case 'enableContextMenu':
implicitView!.contextMenu.enable();
replyToPlatformMessage(callback, jsonCodec.encodeSuccessEnvelope(true));
return;
case 'disableContextMenu':
implicitView!.contextMenu.disable();
replyToPlatformMessage(callback, jsonCodec.encodeSuccessEnvelope(true));
return;
}
return;
case 'flutter/mousecursor':
final MethodCall decoded = standardCodec.decodeMethodCall(data);
final Map<dynamic, dynamic> arguments = decoded.arguments as Map<dynamic, dynamic>;
switch (decoded.method) {
case 'activateSystemCursor':
implicitView!.mouseCursor.activateSystemCursor(arguments.tryString('kind'));
}
return;
case 'flutter/web_test_e2e':
replyToPlatformMessage(
callback,
jsonCodec.encodeSuccessEnvelope(
_handleWebTestEnd2EndMessage(jsonCodec, data)));
return;
case 'flutter/platform_views':
final MethodCall(:String method, :dynamic arguments) = standardCodec.decodeMethodCall(data);
final int? flutterViewId = tryViewId(arguments);
if (flutterViewId == null) {
implicitView!.platformViewMessageHandler.handleLegacyPlatformViewCall(method, arguments, callback!);
return;
}
arguments as Map<dynamic, dynamic>;
viewData[flutterViewId]!.platformViewMessageHandler.handlePlatformViewCall(method, arguments, callback!);
return;
case 'flutter/accessibility':
// In widget tests we want to bypass processing of platform messages.
const StandardMessageCodec codec = StandardMessageCodec();
flutterViewEmbedder.accessibilityAnnouncements.handleMessage(codec, data);
replyToPlatformMessage(callback, codec.encodeMessage(true));
return;
case 'flutter/navigation':
// TODO(a-wallen): As multi-window support expands, the navigation call
// will need to include the view ID. Right now only one view is
// supported.
implicitView!.handleNavigationMessage(data).then((bool handled) {
if (handled) {
replyToPlatformMessage(callback, jsonCodec.encodeSuccessEnvelope(true));
} else {
callback?.call(null);
}
});
// As soon as Flutter starts taking control of the app navigation, we
// should reset _defaultRouteName to "/" so it doesn't have any
// further effect after this point.
_defaultRouteName = '/';
return;
}
if (pluginMessageCallHandler != null) {
pluginMessageCallHandler!(name, data, callback);
return;
}
// Passing [null] to [callback] indicates that the platform message isn't
// implemented. Look at [MethodChannel.invokeMethod] to see how [null] is
// handled.
replyToPlatformMessage(callback, null);
}
Future<void> _handleFlutterAssetsMessage(String url, ui.PlatformMessageResponseCallback? callback) async {
try {
final HttpFetchResponse response = await ui_web.assetManager.loadAsset(url) as HttpFetchResponse;
final ByteBuffer assetData = await response.asByteBuffer();
replyToPlatformMessage(callback, assetData.asByteData());
} catch (error) {
printWarning('Error while trying to load an asset: $error');
replyToPlatformMessage(callback, null);
}
}
int _getHapticFeedbackDuration(String? type) {
const int vibrateLongPress = 50;
const int vibrateLightImpact = 10;
const int vibrateMediumImpact = 20;
const int vibrateHeavyImpact = 30;
const int vibrateSelectionClick = 10;
switch (type) {
case 'HapticFeedbackType.lightImpact':
return vibrateLightImpact;
case 'HapticFeedbackType.mediumImpact':
return vibrateMediumImpact;
case 'HapticFeedbackType.heavyImpact':
return vibrateHeavyImpact;
case 'HapticFeedbackType.selectionClick':
return vibrateSelectionClick;
default:
return vibrateLongPress;
}
}
/// Requests that, at the next appropriate opportunity, the [onBeginFrame]
/// and [onDrawFrame] callbacks be invoked.
///
/// See also:
///
/// * [SchedulerBinding], the Flutter framework class which manages the
/// scheduling of frames.
@override
void scheduleFrame() {
if (scheduleFrameCallback == null) {
throw Exception('scheduleFrameCallback must be initialized first.');
}
scheduleFrameCallback!();
}
/// Updates the application's rendering on the GPU with the newly provided
/// [Scene]. This function must be called within the scope of the
/// [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.
///
/// 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.
///
/// Next, create a [SceneBuilder], and add the [Picture] to it using
/// [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.
///
/// See also:
///
/// * [SchedulerBinding], the Flutter framework class which manages the
/// scheduling of frames.
/// * [RendererBinding], the Flutter framework class which manages layout and
/// painting.
@override
void render(ui.Scene scene, [ui.FlutterView? view]) {
renderer.renderScene(scene);
}
/// Additional accessibility features that may be enabled by the platform.
@override
ui.AccessibilityFeatures get accessibilityFeatures =>
configuration.accessibilityFeatures;
/// A callback that is invoked when the value of [accessibilityFeatures] changes.
///
/// The framework invokes this callback in the same zone in which the
/// callback was set.
@override
ui.VoidCallback? get onAccessibilityFeaturesChanged =>
_onAccessibilityFeaturesChanged;
ui.VoidCallback? _onAccessibilityFeaturesChanged;
Zone? _onAccessibilityFeaturesChangedZone;
@override
set onAccessibilityFeaturesChanged(ui.VoidCallback? callback) {
_onAccessibilityFeaturesChanged = callback;
_onAccessibilityFeaturesChangedZone = Zone.current;
}
/// Engine code should use this method instead of the callback directly.
/// Otherwise zones won't work properly.
void invokeOnAccessibilityFeaturesChanged() {
invoke(
_onAccessibilityFeaturesChanged, _onAccessibilityFeaturesChangedZone);
}
/// Change the retained semantics data about this window.
///
/// If [semanticsEnabled] is true, the user has requested that this function
/// 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.
@override
@Deprecated('''
In a multi-view world, the platform dispatcher can no longer provide apis
to update semantics since each view will host its own semantics tree.
Semantics updates must be passed to an individual [FlutterView]. To update
semantics, use PlatformDispatcher.instance.views to get a [FlutterView] and
call `updateSemantics`.
''')
void updateSemantics(ui.SemanticsUpdate update) {
EngineSemanticsOwner.instance.updateSemantics(update);
}
/// This is equivalent to `locales.first`, except that it will provide an
/// undefined (using the language tag "und") non-null locale if the [locales]
/// list has not been set or is empty.
///
/// We use the first locale in the [locales] list instead of the browser's
/// built-in `navigator.language` because browsers do not agree on the
/// implementation.
///
/// See also:
///
/// * https://developer.mozilla.org/en-US/docs/Web/API/NavigatorLanguage/languages,
/// which explains browser quirks in the implementation notes.
@override
ui.Locale get locale =>
locales.isEmpty ? const ui.Locale.fromSubtags() : locales.first;
/// The full system-reported supported locales of the device.
///
/// This establishes the language and formatting conventions that application
/// should, if possible, use to render their user interface.
///
/// 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].
///
/// The [onLocaleChanged] callback is called whenever this value changes.
///
/// See also:
///
/// * [WidgetsBindingObserver], for a mechanism at the widgets layer to
/// observe when this value changes.
@override
List<ui.Locale> get locales => configuration.locales;
// A subscription to the 'languagechange' event of 'window'.
DomSubscription? _onLocaleChangedSubscription;
/// Configures the [_onLocaleChangedSubscription].
void _addLocaleChangedListener() {
if (_onLocaleChangedSubscription != null) {
return;
}
updateLocales(); // First time, for good measure.
_onLocaleChangedSubscription =
DomSubscription(domWindow, 'languagechange', (DomEvent _) {
// Update internal config, then propagate the changes.
updateLocales();
invokeOnLocaleChanged();
});
}
/// Removes the [_onLocaleChangedSubscription].
void _removeLocaleChangedListener() {
_onLocaleChangedSubscription?.cancel();
_onLocaleChangedSubscription = null;
}
/// 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.
@override
ui.Locale? computePlatformResolvedLocale(List<ui.Locale> supportedLocales) {
// TODO(garyq): Implement on web.
return null;
}
/// A callback that is invoked whenever [locale] 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.
@override
ui.VoidCallback? get onLocaleChanged => _onLocaleChanged;
ui.VoidCallback? _onLocaleChanged;
Zone? _onLocaleChangedZone;
@override
set onLocaleChanged(ui.VoidCallback? callback) {
_onLocaleChanged = callback;
_onLocaleChangedZone = Zone.current;
}
/// The locale used when we fail to get the list from the browser.
static const ui.Locale _defaultLocale = ui.Locale('en', 'US');
/// Sets locales to an empty list.
///
/// The empty list is not a valid value for locales. This is only used for
/// testing locale update logic.
void debugResetLocales() {
configuration = configuration.copyWith(locales: const <ui.Locale>[]);
}
// Called by FlutterViewEmbedder when browser languages change.
void updateLocales() {
configuration = configuration.copyWith(locales: parseBrowserLanguages());
}
static List<ui.Locale> parseBrowserLanguages() {
// TODO(yjbanov): find a solution for IE
final List<String>? languages = domWindow.navigator.languages;
if (languages == null || languages.isEmpty) {
// To make it easier for the app code, let's not leave the locales list
// empty. This way there's fewer corner cases for apps to handle.
return const <ui.Locale>[_defaultLocale];
}
final List<ui.Locale> locales = <ui.Locale>[];
for (final String language in languages) {
final List<String> parts = language.split('-');
if (parts.length > 1) {
locales.add(ui.Locale(parts.first, parts.last));
} else {
locales.add(ui.Locale(language));
}
}
assert(locales.isNotEmpty);
return locales;
}
/// Engine code should use this method instead of the callback directly.
/// Otherwise zones won't work properly.
void invokeOnLocaleChanged() {
invoke(_onLocaleChanged, _onLocaleChangedZone);
}
/// 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.
@override
double get textScaleFactor => configuration.textScaleFactor;
/// The setting indicating whether time should always be shown in the 24-hour
/// format.
///
/// This option is used by [showTimePicker].
@override
bool get alwaysUse24HourFormat => configuration.alwaysUse24HourFormat;
/// Updates [textScaleFactor] and invokes [onTextScaleFactorChanged] and
/// [onPlatformConfigurationChanged] callbacks if [textScaleFactor] changed.
void _updateTextScaleFactor(double value) {
if (configuration.textScaleFactor != value) {
configuration = configuration.copyWith(textScaleFactor: value);
invokeOnPlatformConfigurationChanged();
invokeOnTextScaleFactorChanged();
}
}
/// Watches for font-size changes in the browser's <html> element to
/// recalculate [textScaleFactor].
///
/// Updates [textScaleFactor] with the new value.
DomMutationObserver? _fontSizeObserver;
/// Set the callback function for updating [textScaleFactor] based on
/// font-size changes in the browser's <html> element.
void _addFontSizeObserver() {
const String styleAttribute = 'style';
_fontSizeObserver = createDomMutationObserver(
(JSArray mutations, DomMutationObserver _) {
for (final JSAny? mutation in mutations.toDart) {
final DomMutationRecord record = mutation! as DomMutationRecord;
if (record.type == 'attributes' &&
record.attributeName == styleAttribute) {
final double newTextScaleFactor = findBrowserTextScaleFactor();
_updateTextScaleFactor(newTextScaleFactor);
}
}
});
_fontSizeObserver!.observe(
domDocument.documentElement!,
attributes: true,
attributeFilter: <String>[styleAttribute],
);
}
/// Remove the observer for font-size changes in the browser's <html> element.
void _disconnectFontSizeObserver() {
_fontSizeObserver?.disconnect();
_fontSizeObserver = null;
}
void _setAppLifecycleState(ui.AppLifecycleState state) {
sendPlatformMessage(
'flutter/lifecycle',
ByteData.sublistView(utf8.encode(state.toString())),
null,
);
}
/// 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.
@override
ui.VoidCallback? get onTextScaleFactorChanged => _onTextScaleFactorChanged;
ui.VoidCallback? _onTextScaleFactorChanged;
Zone? _onTextScaleFactorChangedZone;
@override
set onTextScaleFactorChanged(ui.VoidCallback? callback) {
_onTextScaleFactorChanged = callback;
_onTextScaleFactorChangedZone = Zone.current;
}
/// Engine code should use this method instead of the callback directly.
/// Otherwise zones won't work properly.
void invokeOnTextScaleFactorChanged() {
invoke(_onTextScaleFactorChanged, _onTextScaleFactorChangedZone);
}
void updateSemanticsEnabled(bool semanticsEnabled) {
if (semanticsEnabled != this.semanticsEnabled) {
configuration = configuration.copyWith(semanticsEnabled: semanticsEnabled);
if (_onSemanticsEnabledChanged != null) {
invokeOnSemanticsEnabledChanged();
}