-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathzone.dart
1582 lines (1427 loc) · 56.2 KB
/
zone.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 (c) 2013, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
// @dart = 2.6
part of dart.async;
typedef R ZoneCallback<R>();
typedef R ZoneUnaryCallback<R, T>(T arg);
typedef R ZoneBinaryCallback<R, T1, T2>(T1 arg1, T2 arg2);
typedef HandleUncaughtErrorHandler = void Function(Zone self,
ZoneDelegate parent, Zone zone, Object error, StackTrace stackTrace);
typedef RunHandler = R Function<R>(
Zone self, ZoneDelegate parent, Zone zone, R Function() f);
typedef RunUnaryHandler = R Function<R, T>(
Zone self, ZoneDelegate parent, Zone zone, R Function(T arg) f, T arg);
typedef RunBinaryHandler = R Function<R, T1, T2>(Zone self, ZoneDelegate parent,
Zone zone, R Function(T1 arg1, T2 arg2) f, T1 arg1, T2 arg2);
typedef RegisterCallbackHandler = ZoneCallback<R> Function<R>(
Zone self, ZoneDelegate parent, Zone zone, R Function() f);
typedef RegisterUnaryCallbackHandler = ZoneUnaryCallback<R, T> Function<R, T>(
Zone self, ZoneDelegate parent, Zone zone, R Function(T arg) f);
typedef RegisterBinaryCallbackHandler
= ZoneBinaryCallback<R, T1, T2> Function<R, T1, T2>(Zone self,
ZoneDelegate parent, Zone zone, R Function(T1 arg1, T2 arg2) f);
typedef AsyncError ErrorCallbackHandler(Zone self, ZoneDelegate parent,
Zone zone, Object error, StackTrace stackTrace);
typedef void ScheduleMicrotaskHandler(
Zone self, ZoneDelegate parent, Zone zone, void f());
typedef Timer CreateTimerHandler(
Zone self, ZoneDelegate parent, Zone zone, Duration duration, void f());
typedef Timer CreatePeriodicTimerHandler(Zone self, ZoneDelegate parent,
Zone zone, Duration period, void f(Timer timer));
typedef void PrintHandler(
Zone self, ZoneDelegate parent, Zone zone, String line);
typedef Zone ForkHandler(Zone self, ZoneDelegate parent, Zone zone,
ZoneSpecification specification, Map zoneValues);
/** Pair of error and stack trace. Returned by [Zone.errorCallback]. */
class AsyncError implements Error {
final Object error;
final StackTrace stackTrace;
AsyncError(this.error, StackTrace stackTrace)
: stackTrace = stackTrace ?? defaultStackTrace(error) {
ArgumentError.checkNotNull(error, "error");
}
/// A default stack trace for an error.
///
/// If [error] is an [Error] and it has an [Error.stackTrace],
/// that stack trace is returned.
/// If not, the [StackTrace.empty] default stack trace is returned.
static StackTrace defaultStackTrace(Object error) {
if (error is Error) {
var stackTrace = error.stackTrace;
if (stackTrace != null) return stackTrace;
}
return StackTrace.empty;
}
String toString() => '$error';
}
class _ZoneFunction<T extends Function> {
final _Zone zone;
final T function;
const _ZoneFunction(this.zone, this.function);
}
/**
* This class provides the specification for a forked zone.
*
* When forking a new zone (see [Zone.fork]) one can override the default
* behavior of the zone by providing callbacks. These callbacks must be
* given in an instance of this class.
*
* Handlers have the same signature as the same-named methods on [Zone] but
* receive three additional arguments:
*
* 1. the zone the handlers are attached to (the "self" zone).
* 2. a [ZoneDelegate] to the parent zone.
* 3. the zone that first received the request (before the request was
* bubbled up).
*
* Handlers can either stop propagation the request (by simply not calling the
* parent handler), or forward to the parent zone, potentially modifying the
* arguments on the way.
*/
abstract class ZoneSpecification {
/**
* Creates a specification with the provided handlers.
*/
const factory ZoneSpecification(
{HandleUncaughtErrorHandler handleUncaughtError,
RunHandler run,
RunUnaryHandler runUnary,
RunBinaryHandler runBinary,
RegisterCallbackHandler registerCallback,
RegisterUnaryCallbackHandler registerUnaryCallback,
RegisterBinaryCallbackHandler registerBinaryCallback,
ErrorCallbackHandler errorCallback,
ScheduleMicrotaskHandler scheduleMicrotask,
CreateTimerHandler createTimer,
CreatePeriodicTimerHandler createPeriodicTimer,
PrintHandler print,
ForkHandler fork}) = _ZoneSpecification;
/**
* Creates a specification from [other] with the provided handlers overriding
* the ones in [other].
*/
factory ZoneSpecification.from(ZoneSpecification other,
{HandleUncaughtErrorHandler handleUncaughtError,
RunHandler run,
RunUnaryHandler runUnary,
RunBinaryHandler runBinary,
RegisterCallbackHandler registerCallback,
RegisterUnaryCallbackHandler registerUnaryCallback,
RegisterBinaryCallbackHandler registerBinaryCallback,
ErrorCallbackHandler errorCallback,
ScheduleMicrotaskHandler scheduleMicrotask,
CreateTimerHandler createTimer,
CreatePeriodicTimerHandler createPeriodicTimer,
PrintHandler print,
ForkHandler fork}) {
return new ZoneSpecification(
handleUncaughtError: handleUncaughtError ?? other.handleUncaughtError,
run: run ?? other.run,
runUnary: runUnary ?? other.runUnary,
runBinary: runBinary ?? other.runBinary,
registerCallback: registerCallback ?? other.registerCallback,
registerUnaryCallback:
registerUnaryCallback ?? other.registerUnaryCallback,
registerBinaryCallback:
registerBinaryCallback ?? other.registerBinaryCallback,
errorCallback: errorCallback ?? other.errorCallback,
scheduleMicrotask: scheduleMicrotask ?? other.scheduleMicrotask,
createTimer: createTimer ?? other.createTimer,
createPeriodicTimer: createPeriodicTimer ?? other.createPeriodicTimer,
print: print ?? other.print,
fork: fork ?? other.fork);
}
HandleUncaughtErrorHandler get handleUncaughtError;
RunHandler get run;
RunUnaryHandler get runUnary;
RunBinaryHandler get runBinary;
RegisterCallbackHandler get registerCallback;
RegisterUnaryCallbackHandler get registerUnaryCallback;
RegisterBinaryCallbackHandler get registerBinaryCallback;
ErrorCallbackHandler get errorCallback;
ScheduleMicrotaskHandler get scheduleMicrotask;
CreateTimerHandler get createTimer;
CreatePeriodicTimerHandler get createPeriodicTimer;
PrintHandler get print;
ForkHandler get fork;
}
/**
* Internal [ZoneSpecification] class.
*
* The implementation wants to rely on the fact that the getters cannot change
* dynamically. We thus require users to go through the redirecting
* [ZoneSpecification] constructor which instantiates this class.
*/
class _ZoneSpecification implements ZoneSpecification {
const _ZoneSpecification(
{this.handleUncaughtError,
this.run,
this.runUnary,
this.runBinary,
this.registerCallback,
this.registerUnaryCallback,
this.registerBinaryCallback,
this.errorCallback,
this.scheduleMicrotask,
this.createTimer,
this.createPeriodicTimer,
this.print,
this.fork});
final HandleUncaughtErrorHandler handleUncaughtError;
final RunHandler run;
final RunUnaryHandler runUnary;
final RunBinaryHandler runBinary;
final RegisterCallbackHandler registerCallback;
final RegisterUnaryCallbackHandler registerUnaryCallback;
final RegisterBinaryCallbackHandler registerBinaryCallback;
final ErrorCallbackHandler errorCallback;
final ScheduleMicrotaskHandler scheduleMicrotask;
final CreateTimerHandler createTimer;
final CreatePeriodicTimerHandler createPeriodicTimer;
final PrintHandler print;
final ForkHandler fork;
}
/**
* An adapted view of the parent zone.
*
* This class allows the implementation of a zone method to invoke methods on
* the parent zone while retaining knowledge of the originating zone.
*
* Custom zones (created through [Zone.fork] or [runZoned]) can provide
* implementations of most methods of zones. This is similar to overriding
* methods on [Zone], except that this mechanism doesn't require subclassing.
*
* A custom zone function (provided through a [ZoneSpecification]) typically
* records or wraps its parameters and then delegates the operation to its
* parent zone using the provided [ZoneDelegate].
*
* While zones have access to their parent zone (through [Zone.parent]) it is
* recommended to call the methods on the provided parent delegate for two
* reasons:
* 1. the delegate methods take an additional `zone` argument which is the
* zone the action has been initiated in.
* 2. delegate calls are more efficient, since the implementation knows how
* to skip zones that would just delegate to their parents.
*/
abstract class ZoneDelegate {
void handleUncaughtError(Zone zone, error, StackTrace stackTrace);
R run<R>(Zone zone, R f());
R runUnary<R, T>(Zone zone, R f(T arg), T arg);
R runBinary<R, T1, T2>(Zone zone, R f(T1 arg1, T2 arg2), T1 arg1, T2 arg2);
ZoneCallback<R> registerCallback<R>(Zone zone, R f());
ZoneUnaryCallback<R, T> registerUnaryCallback<R, T>(Zone zone, R f(T arg));
ZoneBinaryCallback<R, T1, T2> registerBinaryCallback<R, T1, T2>(
Zone zone, R f(T1 arg1, T2 arg2));
AsyncError errorCallback(Zone zone, Object error, StackTrace stackTrace);
void scheduleMicrotask(Zone zone, void f());
Timer createTimer(Zone zone, Duration duration, void f());
Timer createPeriodicTimer(Zone zone, Duration period, void f(Timer timer));
void print(Zone zone, String line);
Zone fork(Zone zone, ZoneSpecification specification, Map zoneValues);
}
/**
* A zone represents an environment that remains stable across asynchronous
* calls.
*
* Code is always executed in the context of a zone, available as
* [Zone.current]. The initial `main` function runs in the context of the
* default zone ([Zone.root]). Code can be run in a different zone using either
* [runZoned], to create a new zone, or [Zone.run] to run code in the context of
* an existing zone likely created using [Zone.fork].
*
* Developers can create a new zone that overrides some of the functionality of
* an existing zone. For example, custom zones can replace or modify the
* behavior of `print`, timers, microtasks or how uncaught errors are handled.
*
* The [Zone] class is not subclassable, but users can provide custom zones by
* forking an existing zone (usually [Zone.current]) with a [ZoneSpecification].
* This is similar to creating a new class that extends the base `Zone` class
* and that overrides some methods, except without actually creating a new
* class. Instead the overriding methods are provided as functions that
* explicitly take the equivalent of their own class, the "super" class and the
* `this` object as parameters.
*
* Asynchronous callbacks always run in the context of the zone where they were
* scheduled. This is implemented using two steps:
* 1. the callback is first registered using one of [registerCallback],
* [registerUnaryCallback], or [registerBinaryCallback]. This allows the zone
* to record that a callback exists and potentially modify it (by returning a
* different callback). The code doing the registration (e.g., `Future.then`)
* also remembers the current zone so that it can later run the callback in
* that zone.
* 2. At a later point the registered callback is run in the remembered zone.
*
* This is all handled internally by the platform code and most users don't need
* to worry about it. However, developers of new asynchronous operations,
* provided by the underlying system or through native extensions, must follow
* the protocol to be zone compatible.
*
* For convenience, zones provide [bindCallback] (and the corresponding
* [bindUnaryCallback] and [bindBinaryCallback]) to make it easier to respect
* the zone contract: these functions first invoke the corresponding `register`
* functions and then wrap the returned function so that it runs in the current
* zone when it is later asynchronously invoked.
*
* Similarly, zones provide [bindCallbackGuarded] (and the corresponding
* [bindUnaryCallbackGuarded] and [bindBinaryCallbackGuarded]), when the
* callback should be invoked through [Zone.runGuarded].
*/
abstract class Zone {
// Private constructor so that it is not possible instantiate a Zone class.
Zone._();
/**
* The root zone.
*
* All isolate entry functions (`main` or spawned functions) start running in
* the root zone (that is, [Zone.current] is identical to [Zone.root] when the
* entry function is called). If no custom zone is created, the rest of the
* program always runs in the root zone.
*
* The root zone implements the default behavior of all zone operations.
* Many methods, like [registerCallback] do the bare minimum required of the
* function, and are only provided as a hook for custom zones. Others, like
* [scheduleMicrotask], interact with the underlying system to implement the
* desired behavior.
*/
static const Zone root = _rootZone;
/** The currently running zone. */
static Zone _current = _rootZone;
/** The zone that is currently active. */
static Zone get current => _current;
/**
* Handles uncaught asynchronous errors.
*
* There are two kind of asynchronous errors that are handled by this
* function:
* 1. Uncaught errors that were thrown in asynchronous callbacks, for example,
* a `throw` in the function passed to [Timer.run].
* 2. Asynchronous errors that are pushed through [Future] and [Stream]
* chains, but for which no child registered an error handler.
* Most asynchronous classes, like [Future] or [Stream] push errors to their
* listeners. Errors are propagated this way until either a listener handles
* the error (for example with [Future.catchError]), or no listener is
* available anymore. In the latter case, futures and streams invoke the
* zone's [handleUncaughtError].
*
* By default, when handled by the root zone, uncaught asynchronous errors are
* treated like uncaught synchronous exceptions.
*/
void handleUncaughtError(error, StackTrace stackTrace);
/**
* The parent zone of the this zone.
*
* Is `null` if `this` is the [root] zone.
*
* Zones are created by [fork] on an existing zone, or by [runZoned] which
* forks the [current] zone. The new zone's parent zone is the zone it was
* forked from.
*/
Zone get parent;
/**
* The error zone is the one that is responsible for dealing with uncaught
* errors.
*
* This is the closest parent zone of this zone that provides a
* [handleUncaughtError] method.
*
* Asynchronous errors never cross zone boundaries between zones with
* different error handlers.
*
* Example:
* ```
* import 'dart:async';
*
* main() {
* var future;
* runZoned(() {
* // The asynchronous error is caught by the custom zone which prints
* // 'asynchronous error'.
* future = new Future.error("asynchronous error");
* }, onError: (e) { print(e); }); // Creates a zone with an error handler.
* // The following `catchError` handler is never invoked, because the
* // custom zone created by the call to `runZoned` provides an
* // error handler.
* future.catchError((e) { throw "is never reached"; });
* }
* ```
*
* Note that errors cannot enter a child zone with a different error handler
* either:
* ```
* import 'dart:async';
*
* main() {
* runZoned(() {
* // The following asynchronous error is *not* caught by the `catchError`
* // in the nested zone, since errors are not to cross zone boundaries
* // with different error handlers.
* // Instead the error is handled by the current error handler,
* // printing "Caught by outer zone: asynchronous error".
* var future = new Future.error("asynchronous error");
* runZoned(() {
* future.catchError((e) { throw "is never reached"; });
* }, onError: (e) { throw "is never reached"; });
* }, onError: (e) { print("Caught by outer zone: $e"); });
* }
* ```
*/
Zone get errorZone;
/**
* Returns true if `this` and [otherZone] are in the same error zone.
*
* Two zones are in the same error zone if they have the same [errorZone].
*/
bool inSameErrorZone(Zone otherZone);
/**
* Creates a new zone as a child of `this`.
*
* The new zone uses the closures in the given [specification] to override
* the current's zone behavior. All specification entries that are `null`
* inherit the behavior from the parent zone (`this`).
*
* The new zone inherits the stored values (accessed through [operator []])
* of this zone and updates them with values from [zoneValues], which either
* adds new values or overrides existing ones.
*
* Note that the fork operation is interceptible. A zone can thus change
* the zone specification (or zone values), giving the forking zone full
* control over the child zone.
*/
Zone fork({ZoneSpecification specification, Map zoneValues});
/**
* Executes [action] in this zone.
*
* By default (as implemented in the [root] zone), runs [action]
* with [current] set to this zone.
*
* If [action] throws, the synchronous exception is not caught by the zone's
* error handler. Use [runGuarded] to achieve that.
*
* Since the root zone is the only zone that can modify the value of
* [current], custom zones intercepting run should always delegate to their
* parent zone. They may take actions before and after the call.
*/
R run<R>(R action());
/**
* Executes the given [action] with [argument] in this zone.
*
* As [run] except that [action] is called with one [argument] instead of
* none.
*/
R runUnary<R, T>(R action(T argument), T argument);
/**
* Executes the given [action] with [argument1] and [argument2] in this
* zone.
*
* As [run] except that [action] is called with two arguments instead of none.
*/
R runBinary<R, T1, T2>(
R action(T1 argument1, T2 argument2), T1 argument1, T2 argument2);
/**
* Executes the given [action] in this zone and catches synchronous
* errors.
*
* This function is equivalent to:
* ```
* try {
* this.run(action);
* } catch (e, s) {
* this.handleUncaughtError(e, s);
* }
* ```
*
* See [run].
*/
void runGuarded(void action());
/**
* Executes the given [action] with [argument] in this zone and
* catches synchronous errors.
*
* See [runGuarded].
*/
void runUnaryGuarded<T>(void action(T argument), T argument);
/**
* Executes the given [action] with [argument1] and [argument2] in this
* zone and catches synchronous errors.
*
* See [runGuarded].
*/
void runBinaryGuarded<T1, T2>(
void action(T1 argument1, T2 argument2), T1 argument1, T2 argument2);
/**
* Registers the given callback in this zone.
*
* When implementing an asynchronous primitive that uses callbacks, the
* callback must be registered using [registerCallback] at the point where the
* user provides the callback. This allows zones to record other information
* that they need at the same time, perhaps even wrapping the callback, so
* that the callback is prepared when it is later run in the same zones
* (using [run]). For example, a zone may decide
* to store the stack trace (at the time of the registration) with the
* callback.
*
* Returns the callback that should be used in place of the provided
* [callback]. Frequently zones simply return the original callback.
*
* Custom zones may intercept this operation. The default implementation in
* [Zone.root] returns the original callback unchanged.
*/
ZoneCallback<R> registerCallback<R>(R callback());
/**
* Registers the given callback in this zone.
*
* Similar to [registerCallback] but with a unary callback.
*/
ZoneUnaryCallback<R, T> registerUnaryCallback<R, T>(R callback(T arg));
/**
* Registers the given callback in this zone.
*
* Similar to [registerCallback] but with a unary callback.
*/
ZoneBinaryCallback<R, T1, T2> registerBinaryCallback<R, T1, T2>(
R callback(T1 arg1, T2 arg2));
/**
* Registers the provided [callback] and returns a function that will
* execute in this zone.
*
* Equivalent to:
*
* ZoneCallback registered = this.registerCallback(callback);
* return () => this.run(registered);
*
*/
ZoneCallback<R> bindCallback<R>(R callback());
/**
* Registers the provided [callback] and returns a function that will
* execute in this zone.
*
* Equivalent to:
*
* ZoneCallback registered = this.registerUnaryCallback(callback);
* return (arg) => thin.runUnary(registered, arg);
*/
ZoneUnaryCallback<R, T> bindUnaryCallback<R, T>(R callback(T argument));
/**
* Registers the provided [callback] and returns a function that will
* execute in this zone.
*
* Equivalent to:
*
* ZoneCallback registered = registerBinaryCallback(callback);
* return (arg1, arg2) => thin.runBinary(registered, arg1, arg2);
*/
ZoneBinaryCallback<R, T1, T2> bindBinaryCallback<R, T1, T2>(
R callback(T1 argument1, T2 argument2));
/**
* Registers the provided [callback] and returns a function that will
* execute in this zone.
*
* When the function executes, errors are caught and treated as uncaught
* errors.
*
* Equivalent to:
*
* ZoneCallback registered = this.registerCallback(callback);
* return () => this.runGuarded(registered);
*
*/
void Function() bindCallbackGuarded(void callback());
/**
* Registers the provided [callback] and returns a function that will
* execute in this zone.
*
* When the function executes, errors are caught and treated as uncaught
* errors.
*
* Equivalent to:
*
* ZoneCallback registered = this.registerUnaryCallback(callback);
* return (arg) => this.runUnaryGuarded(registered, arg);
*/
void Function(T) bindUnaryCallbackGuarded<T>(void callback(T argument));
/**
* Registers the provided [callback] and returns a function that will
* execute in this zone.
*
* Equivalent to:
*
* ZoneCallback registered = registerBinaryCallback(callback);
* return (arg1, arg2) => this.runBinaryGuarded(registered, arg1, arg2);
*/
void Function(T1, T2) bindBinaryCallbackGuarded<T1, T2>(
void callback(T1 argument1, T2 argument2));
/**
* Intercepts errors when added programmatically to a `Future` or `Stream`.
*
* When calling [Completer.completeError], [StreamController.addError],
* or some [Future] constructors, the current zone is allowed to intercept
* and replace the error.
*
* Future constructors invoke this function when the error is received
* directly, for example with [Future.error], or when the error is caught
* synchronously, for example with [Future.sync].
*
* There is no guarantee that an error is only sent through [errorCallback]
* once. Libraries that use intermediate controllers or completers might
* end up invoking [errorCallback] multiple times.
*
* Returns `null` if no replacement is desired. Otherwise returns an instance
* of [AsyncError] holding the new pair of error and stack trace.
*
* Although not recommended, the returned instance may have its `error` member
* ([AsyncError.error]) be equal to `null` in which case the error should be
* replaced by a [NullThrownError].
*
* Custom zones may intercept this operation.
*
* Implementations of a new asynchronous primitive that converts synchronous
* errors to asynchronous errors rarely need to invoke [errorCallback], since
* errors are usually reported through future completers or stream
* controllers.
*/
AsyncError errorCallback(Object error, StackTrace stackTrace);
/**
* Runs [callback] asynchronously in this zone.
*
* The global `scheduleMicrotask` delegates to the current zone's
* [scheduleMicrotask]. The root zone's implementation interacts with the
* underlying system to schedule the given callback as a microtask.
*
* Custom zones may intercept this operation (for example to wrap the given
* [callback]).
*/
void scheduleMicrotask(void callback());
/**
* Creates a Timer where the callback is executed in this zone.
*/
Timer createTimer(Duration duration, void callback());
/**
* Creates a periodic Timer where the callback is executed in this zone.
*/
Timer createPeriodicTimer(Duration period, void callback(Timer timer));
/**
* Prints the given [line].
*
* The global `print` function delegates to the current zone's [print]
* function which makes it possible to intercept printing.
*
* Example:
* ```
* import 'dart:async';
*
* main() {
* runZoned(() {
* // Ends up printing: "Intercepted: in zone".
* print("in zone");
* }, zoneSpecification: new ZoneSpecification(
* print: (Zone self, ZoneDelegate parent, Zone zone, String line) {
* parent.print(zone, "Intercepted: $line");
* }));
* }
* ```
*/
void print(String line);
/**
* Call to enter the Zone.
*
* The previous current zone is returned.
*/
static Zone _enter(Zone zone) {
assert(zone != null);
assert(!identical(zone, _current));
Zone previous = _current;
_current = zone;
return previous;
}
/**
* Call to leave the Zone.
*
* The previous Zone must be provided as `previous`.
*/
static void _leave(Zone previous) {
assert(previous != null);
Zone._current = previous;
}
/**
* Retrieves the zone-value associated with [key].
*
* If this zone does not contain the value looks up the same key in the
* parent zone. If the [key] is not found returns `null`.
*
* Any object can be used as key, as long as it has compatible `operator ==`
* and `hashCode` implementations.
* By controlling access to the key, a zone can grant or deny access to the
* zone value.
*/
operator [](Object key);
}
ZoneDelegate _parentDelegate(_Zone zone) {
if (zone.parent == null) return null;
return zone.parent._delegate;
}
class _ZoneDelegate implements ZoneDelegate {
final _Zone _delegationTarget;
_ZoneDelegate(this._delegationTarget);
void handleUncaughtError(Zone zone, error, StackTrace stackTrace) {
var implementation = _delegationTarget._handleUncaughtError;
_Zone implZone = implementation.zone;
HandleUncaughtErrorHandler handler = implementation.function;
return handler(
implZone, _parentDelegate(implZone), zone, error, stackTrace);
}
R run<R>(Zone zone, R f()) {
var implementation = _delegationTarget._run;
_Zone implZone = implementation.zone;
RunHandler handler = implementation.function;
return handler(implZone, _parentDelegate(implZone), zone, f);
}
R runUnary<R, T>(Zone zone, R f(T arg), T arg) {
var implementation = _delegationTarget._runUnary;
_Zone implZone = implementation.zone;
RunUnaryHandler handler = implementation.function;
return handler(implZone, _parentDelegate(implZone), zone, f, arg);
}
R runBinary<R, T1, T2>(Zone zone, R f(T1 arg1, T2 arg2), T1 arg1, T2 arg2) {
var implementation = _delegationTarget._runBinary;
_Zone implZone = implementation.zone;
RunBinaryHandler handler = implementation.function;
return handler(implZone, _parentDelegate(implZone), zone, f, arg1, arg2);
}
ZoneCallback<R> registerCallback<R>(Zone zone, R f()) {
var implementation = _delegationTarget._registerCallback;
_Zone implZone = implementation.zone;
RegisterCallbackHandler handler = implementation.function;
return handler(implZone, _parentDelegate(implZone), zone, f);
}
ZoneUnaryCallback<R, T> registerUnaryCallback<R, T>(Zone zone, R f(T arg)) {
var implementation = _delegationTarget._registerUnaryCallback;
_Zone implZone = implementation.zone;
RegisterUnaryCallbackHandler handler = implementation.function;
return handler(implZone, _parentDelegate(implZone), zone, f);
}
ZoneBinaryCallback<R, T1, T2> registerBinaryCallback<R, T1, T2>(
Zone zone, R f(T1 arg1, T2 arg2)) {
var implementation = _delegationTarget._registerBinaryCallback;
_Zone implZone = implementation.zone;
RegisterBinaryCallbackHandler handler = implementation.function;
return handler(implZone, _parentDelegate(implZone), zone, f);
}
AsyncError errorCallback(Zone zone, Object error, StackTrace stackTrace) {
ArgumentError.checkNotNull(error, "error");
var implementation = _delegationTarget._errorCallback;
_Zone implZone = implementation.zone;
if (identical(implZone, _rootZone)) return null;
ErrorCallbackHandler handler = implementation.function;
return handler(
implZone, _parentDelegate(implZone), zone, error, stackTrace);
}
void scheduleMicrotask(Zone zone, f()) {
var implementation = _delegationTarget._scheduleMicrotask;
_Zone implZone = implementation.zone;
ScheduleMicrotaskHandler handler = implementation.function;
handler(implZone, _parentDelegate(implZone), zone, f);
}
Timer createTimer(Zone zone, Duration duration, void f()) {
var implementation = _delegationTarget._createTimer;
_Zone implZone = implementation.zone;
CreateTimerHandler handler = implementation.function;
return handler(implZone, _parentDelegate(implZone), zone, duration, f);
}
Timer createPeriodicTimer(Zone zone, Duration period, void f(Timer timer)) {
var implementation = _delegationTarget._createPeriodicTimer;
_Zone implZone = implementation.zone;
CreatePeriodicTimerHandler handler = implementation.function;
return handler(implZone, _parentDelegate(implZone), zone, period, f);
}
void print(Zone zone, String line) {
var implementation = _delegationTarget._print;
_Zone implZone = implementation.zone;
PrintHandler handler = implementation.function;
handler(implZone, _parentDelegate(implZone), zone, line);
}
Zone fork(Zone zone, ZoneSpecification specification, Map zoneValues) {
var implementation = _delegationTarget._fork;
_Zone implZone = implementation.zone;
ForkHandler handler = implementation.function;
return handler(
implZone, _parentDelegate(implZone), zone, specification, zoneValues);
}
}
/**
* Base class for Zone implementations.
*/
abstract class _Zone implements Zone {
const _Zone();
// TODO(floitsch): the types of the `_ZoneFunction`s should have a type for
// all fields.
_ZoneFunction<Function> get _run;
_ZoneFunction<Function> get _runUnary;
_ZoneFunction<Function> get _runBinary;
_ZoneFunction<Function> get _registerCallback;
_ZoneFunction<Function> get _registerUnaryCallback;
_ZoneFunction<Function> get _registerBinaryCallback;
_ZoneFunction<ErrorCallbackHandler> get _errorCallback;
_ZoneFunction<ScheduleMicrotaskHandler> get _scheduleMicrotask;
_ZoneFunction<CreateTimerHandler> get _createTimer;
_ZoneFunction<CreatePeriodicTimerHandler> get _createPeriodicTimer;
_ZoneFunction<PrintHandler> get _print;
_ZoneFunction<ForkHandler> get _fork;
_ZoneFunction<HandleUncaughtErrorHandler> get _handleUncaughtError;
_Zone get parent;
ZoneDelegate get _delegate;
Map get _map;
bool inSameErrorZone(Zone otherZone) {
return identical(this, otherZone) ||
identical(errorZone, otherZone.errorZone);
}
}
class _CustomZone extends _Zone {
// The actual zone and implementation of each of these
// inheritable zone functions.
// TODO(floitsch): the types of the `_ZoneFunction`s should have a type for
// all fields.
_ZoneFunction<Function> _run;
_ZoneFunction<Function> _runUnary;
_ZoneFunction<Function> _runBinary;
_ZoneFunction<Function> _registerCallback;
_ZoneFunction<Function> _registerUnaryCallback;
_ZoneFunction<Function> _registerBinaryCallback;
_ZoneFunction<ErrorCallbackHandler> _errorCallback;
_ZoneFunction<ScheduleMicrotaskHandler> _scheduleMicrotask;
_ZoneFunction<CreateTimerHandler> _createTimer;
_ZoneFunction<CreatePeriodicTimerHandler> _createPeriodicTimer;
_ZoneFunction<PrintHandler> _print;
_ZoneFunction<ForkHandler> _fork;
_ZoneFunction<HandleUncaughtErrorHandler> _handleUncaughtError;
// A cached delegate to this zone.
ZoneDelegate _delegateCache;
/// The parent zone.
final _Zone parent;
/// The zone's scoped value declaration map.
///
/// This is always a [HashMap].
final Map _map;
ZoneDelegate get _delegate {
if (_delegateCache != null) return _delegateCache;
_delegateCache = new _ZoneDelegate(this);
return _delegateCache;
}
_CustomZone(this.parent, ZoneSpecification specification, this._map) {
// The root zone will have implementations of all parts of the
// specification, so it will never try to access the (null) parent.
// All other zones have a non-null parent.
_run = (specification.run != null)
? new _ZoneFunction<Function>(this, specification.run)
: parent._run;
_runUnary = (specification.runUnary != null)
? new _ZoneFunction<Function>(this, specification.runUnary)
: parent._runUnary;
_runBinary = (specification.runBinary != null)
? new _ZoneFunction<Function>(this, specification.runBinary)
: parent._runBinary;
_registerCallback = (specification.registerCallback != null)
? new _ZoneFunction<Function>(this, specification.registerCallback)
: parent._registerCallback;
_registerUnaryCallback = (specification.registerUnaryCallback != null)
? new _ZoneFunction<Function>(this, specification.registerUnaryCallback)
: parent._registerUnaryCallback;
_registerBinaryCallback = (specification.registerBinaryCallback != null)
? new _ZoneFunction<Function>(
this, specification.registerBinaryCallback)
: parent._registerBinaryCallback;
_errorCallback = (specification.errorCallback != null)
? new _ZoneFunction<ErrorCallbackHandler>(
this, specification.errorCallback)
: parent._errorCallback;
_scheduleMicrotask = (specification.scheduleMicrotask != null)
? new _ZoneFunction<ScheduleMicrotaskHandler>(
this, specification.scheduleMicrotask)
: parent._scheduleMicrotask;
_createTimer = (specification.createTimer != null)
? new _ZoneFunction<CreateTimerHandler>(this, specification.createTimer)
: parent._createTimer;
_createPeriodicTimer = (specification.createPeriodicTimer != null)
? new _ZoneFunction<CreatePeriodicTimerHandler>(
this, specification.createPeriodicTimer)
: parent._createPeriodicTimer;
_print = (specification.print != null)
? new _ZoneFunction<PrintHandler>(this, specification.print)
: parent._print;
_fork = (specification.fork != null)
? new _ZoneFunction<ForkHandler>(this, specification.fork)
: parent._fork;
_handleUncaughtError = (specification.handleUncaughtError != null)
? new _ZoneFunction<HandleUncaughtErrorHandler>(
this, specification.handleUncaughtError)
: parent._handleUncaughtError;
}
/**
* The closest error-handling zone.
*
* Returns `this` if `this` has an error-handler. Otherwise returns the
* parent's error-zone.
*/
Zone get errorZone => _handleUncaughtError.zone;
void runGuarded(void f()) {
try {
run(f);
} catch (e, s) {
handleUncaughtError(e, s);
}
}
void runUnaryGuarded<T>(void f(T arg), T arg) {
try {
runUnary(f, arg);
} catch (e, s) {
handleUncaughtError(e, s);
}
}
void runBinaryGuarded<T1, T2>(void f(T1 arg1, T2 arg2), T1 arg1, T2 arg2) {
try {
runBinary(f, arg1, arg2);
} catch (e, s) {
handleUncaughtError(e, s);
}
}
ZoneCallback<R> bindCallback<R>(R f()) {
var registered = registerCallback(f);
return () => this.run(registered);
}
ZoneUnaryCallback<R, T> bindUnaryCallback<R, T>(R f(T arg)) {
var registered = registerUnaryCallback(f);
return (arg) => this.runUnary(registered, arg);
}
ZoneBinaryCallback<R, T1, T2> bindBinaryCallback<R, T1, T2>(
R f(T1 arg1, T2 arg2)) {
var registered = registerBinaryCallback(f);
return (arg1, arg2) => this.runBinary(registered, arg1, arg2);
}
void Function() bindCallbackGuarded(void f()) {
var registered = registerCallback(f);
return () => this.runGuarded(registered);
}
void Function(T) bindUnaryCallbackGuarded<T>(void f(T arg)) {
var registered = registerUnaryCallback(f);
return (arg) => this.runUnaryGuarded(registered, arg);
}
void Function(T1, T2) bindBinaryCallbackGuarded<T1, T2>(
void f(T1 arg1, T2 arg2)) {
var registered = registerBinaryCallback(f);
return (arg1, arg2) => this.runBinaryGuarded(registered, arg1, arg2);
}
operator [](Object key) {
var result = _map[key];
if (result != null || _map.containsKey(key)) return result;
// If we are not the root zone, look up in the parent zone.
if (parent != null) {