-
Notifications
You must be signed in to change notification settings - Fork 29.5k
/
event.ts
1747 lines (1498 loc) · 52.7 KB
/
event.ts
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) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { CancellationToken } from 'vs/base/common/cancellation';
import { onUnexpectedError } from 'vs/base/common/errors';
import { createSingleCallFunction } from 'vs/base/common/functional';
import { combinedDisposable, Disposable, DisposableMap, DisposableStore, IDisposable, toDisposable } from 'vs/base/common/lifecycle';
import { LinkedList } from 'vs/base/common/linkedList';
import { IObservable, IObserver } from 'vs/base/common/observable';
import { StopWatch } from 'vs/base/common/stopwatch';
import { MicrotaskDelay } from 'vs/base/common/symbols';
// -----------------------------------------------------------------------------------------------------------------------
// Uncomment the next line to print warnings whenever a listener is GC'ed without having been disposed. This is a LEAK.
// -----------------------------------------------------------------------------------------------------------------------
const _enableListenerGCedWarning = false
// || Boolean("TRUE") // causes a linter warning so that it cannot be pushed
;
// -----------------------------------------------------------------------------------------------------------------------
// Uncomment the next line to print warnings whenever an emitter with listeners is disposed. That is a sign of code smell.
// -----------------------------------------------------------------------------------------------------------------------
const _enableDisposeWithListenerWarning = false
// || Boolean("TRUE") // causes a linter warning so that it cannot be pushed
;
// -----------------------------------------------------------------------------------------------------------------------
// Uncomment the next line to print warnings whenever a snapshotted event is used repeatedly without cleanup.
// See https://github.com/microsoft/vscode/issues/142851
// -----------------------------------------------------------------------------------------------------------------------
const _enableSnapshotPotentialLeakWarning = false
// || Boolean("TRUE") // causes a linter warning so that it cannot be pushed
;
/**
* An event with zero or one parameters that can be subscribed to. The event is a function itself.
*/
export interface Event<T> {
(listener: (e: T) => any, thisArgs?: any, disposables?: IDisposable[] | DisposableStore): IDisposable;
}
export namespace Event {
export const None: Event<any> = () => Disposable.None;
function _addLeakageTraceLogic(options: EmitterOptions) {
if (_enableSnapshotPotentialLeakWarning) {
const { onDidAddListener: origListenerDidAdd } = options;
const stack = Stacktrace.create();
let count = 0;
options.onDidAddListener = () => {
if (++count === 2) {
console.warn('snapshotted emitter LIKELY used public and SHOULD HAVE BEEN created with DisposableStore. snapshotted here');
stack.print();
}
origListenerDidAdd?.();
};
}
}
/**
* Given an event, returns another event which debounces calls and defers the listeners to a later task via a shared
* `setTimeout`. The event is converted into a signal (`Event<void>`) to avoid additional object creation as a
* result of merging events and to try prevent race conditions that could arise when using related deferred and
* non-deferred events.
*
* This is useful for deferring non-critical work (eg. general UI updates) to ensure it does not block critical work
* (eg. latency of keypress to text rendered).
*
* *NOTE* that this function returns an `Event` and it MUST be called with a `DisposableStore` whenever the returned
* event is accessible to "third parties", e.g the event is a public property. Otherwise a leaked listener on the
* returned event causes this utility to leak a listener on the original event.
*
* @param event The event source for the new event.
* @param disposable A disposable store to add the new EventEmitter to.
*/
export function defer(event: Event<unknown>, disposable?: DisposableStore): Event<void> {
return debounce<unknown, void>(event, () => void 0, 0, undefined, true, undefined, disposable);
}
/**
* Given an event, returns another event which only fires once.
*
* @param event The event source for the new event.
*/
export function once<T>(event: Event<T>): Event<T> {
return (listener, thisArgs = null, disposables?) => {
// we need this, in case the event fires during the listener call
let didFire = false;
let result: IDisposable | undefined = undefined;
result = event(e => {
if (didFire) {
return;
} else if (result) {
result.dispose();
} else {
didFire = true;
}
return listener.call(thisArgs, e);
}, null, disposables);
if (didFire) {
result.dispose();
}
return result;
};
}
/**
* Maps an event of one type into an event of another type using a mapping function, similar to how
* `Array.prototype.map` works.
*
* *NOTE* that this function returns an `Event` and it MUST be called with a `DisposableStore` whenever the returned
* event is accessible to "third parties", e.g the event is a public property. Otherwise a leaked listener on the
* returned event causes this utility to leak a listener on the original event.
*
* @param event The event source for the new event.
* @param map The mapping function.
* @param disposable A disposable store to add the new EventEmitter to.
*/
export function map<I, O>(event: Event<I>, map: (i: I) => O, disposable?: DisposableStore): Event<O> {
return snapshot((listener, thisArgs = null, disposables?) => event(i => listener.call(thisArgs, map(i)), null, disposables), disposable);
}
/**
* Wraps an event in another event that performs some function on the event object before firing.
*
* *NOTE* that this function returns an `Event` and it MUST be called with a `DisposableStore` whenever the returned
* event is accessible to "third parties", e.g the event is a public property. Otherwise a leaked listener on the
* returned event causes this utility to leak a listener on the original event.
*
* @param event The event source for the new event.
* @param each The function to perform on the event object.
* @param disposable A disposable store to add the new EventEmitter to.
*/
export function forEach<I>(event: Event<I>, each: (i: I) => void, disposable?: DisposableStore): Event<I> {
return snapshot((listener, thisArgs = null, disposables?) => event(i => { each(i); listener.call(thisArgs, i); }, null, disposables), disposable);
}
/**
* Wraps an event in another event that fires only when some condition is met.
*
* *NOTE* that this function returns an `Event` and it MUST be called with a `DisposableStore` whenever the returned
* event is accessible to "third parties", e.g the event is a public property. Otherwise a leaked listener on the
* returned event causes this utility to leak a listener on the original event.
*
* @param event The event source for the new event.
* @param filter The filter function that defines the condition. The event will fire for the object if this function
* returns true.
* @param disposable A disposable store to add the new EventEmitter to.
*/
export function filter<T, U>(event: Event<T | U>, filter: (e: T | U) => e is T, disposable?: DisposableStore): Event<T>;
export function filter<T>(event: Event<T>, filter: (e: T) => boolean, disposable?: DisposableStore): Event<T>;
export function filter<T, R>(event: Event<T | R>, filter: (e: T | R) => e is R, disposable?: DisposableStore): Event<R>;
export function filter<T>(event: Event<T>, filter: (e: T) => boolean, disposable?: DisposableStore): Event<T> {
return snapshot((listener, thisArgs = null, disposables?) => event(e => filter(e) && listener.call(thisArgs, e), null, disposables), disposable);
}
/**
* Given an event, returns the same event but typed as `Event<void>`.
*/
export function signal<T>(event: Event<T>): Event<void> {
return event as Event<any> as Event<void>;
}
/**
* Given a collection of events, returns a single event which emits whenever any of the provided events emit.
*/
export function any<T>(...events: Event<T>[]): Event<T>;
export function any(...events: Event<any>[]): Event<void>;
export function any<T>(...events: Event<T>[]): Event<T> {
return (listener, thisArgs = null, disposables?) => {
const disposable = combinedDisposable(...events.map(event => event(e => listener.call(thisArgs, e))));
return addAndReturnDisposable(disposable, disposables);
};
}
/**
* *NOTE* that this function returns an `Event` and it MUST be called with a `DisposableStore` whenever the returned
* event is accessible to "third parties", e.g the event is a public property. Otherwise a leaked listener on the
* returned event causes this utility to leak a listener on the original event.
*/
export function reduce<I, O>(event: Event<I>, merge: (last: O | undefined, event: I) => O, initial?: O, disposable?: DisposableStore): Event<O> {
let output: O | undefined = initial;
return map<I, O>(event, e => {
output = merge(output, e);
return output;
}, disposable);
}
function snapshot<T>(event: Event<T>, disposable: DisposableStore | undefined): Event<T> {
let listener: IDisposable | undefined;
const options: EmitterOptions | undefined = {
onWillAddFirstListener() {
listener = event(emitter.fire, emitter);
},
onDidRemoveLastListener() {
listener?.dispose();
}
};
if (!disposable) {
_addLeakageTraceLogic(options);
}
const emitter = new Emitter<T>(options);
disposable?.add(emitter);
return emitter.event;
}
/**
* Adds the IDisposable to the store if it's set, and returns it. Useful to
* Event function implementation.
*/
function addAndReturnDisposable<T extends IDisposable>(d: T, store: DisposableStore | IDisposable[] | undefined): T {
if (store instanceof Array) {
store.push(d);
} else if (store) {
store.add(d);
}
return d;
}
/**
* Given an event, creates a new emitter that event that will debounce events based on {@link delay} and give an
* array event object of all events that fired.
*
* *NOTE* that this function returns an `Event` and it MUST be called with a `DisposableStore` whenever the returned
* event is accessible to "third parties", e.g the event is a public property. Otherwise a leaked listener on the
* returned event causes this utility to leak a listener on the original event.
*
* @param event The original event to debounce.
* @param merge A function that reduces all events into a single event.
* @param delay The number of milliseconds to debounce.
* @param leading Whether to fire a leading event without debouncing.
* @param flushOnListenerRemove Whether to fire all debounced events when a listener is removed. If this is not
* specified, some events could go missing. Use this if it's important that all events are processed, even if the
* listener gets disposed before the debounced event fires.
* @param leakWarningThreshold See {@link EmitterOptions.leakWarningThreshold}.
* @param disposable A disposable store to register the debounce emitter to.
*/
export function debounce<T>(event: Event<T>, merge: (last: T | undefined, event: T) => T, delay?: number | typeof MicrotaskDelay, leading?: boolean, flushOnListenerRemove?: boolean, leakWarningThreshold?: number, disposable?: DisposableStore): Event<T>;
export function debounce<I, O>(event: Event<I>, merge: (last: O | undefined, event: I) => O, delay?: number | typeof MicrotaskDelay, leading?: boolean, flushOnListenerRemove?: boolean, leakWarningThreshold?: number, disposable?: DisposableStore): Event<O>;
export function debounce<I, O>(event: Event<I>, merge: (last: O | undefined, event: I) => O, delay: number | typeof MicrotaskDelay = 100, leading = false, flushOnListenerRemove = false, leakWarningThreshold?: number, disposable?: DisposableStore): Event<O> {
let subscription: IDisposable;
let output: O | undefined = undefined;
let handle: any = undefined;
let numDebouncedCalls = 0;
let doFire: (() => void) | undefined;
const options: EmitterOptions | undefined = {
leakWarningThreshold,
onWillAddFirstListener() {
subscription = event(cur => {
numDebouncedCalls++;
output = merge(output, cur);
if (leading && !handle) {
emitter.fire(output);
output = undefined;
}
doFire = () => {
const _output = output;
output = undefined;
handle = undefined;
if (!leading || numDebouncedCalls > 1) {
emitter.fire(_output!);
}
numDebouncedCalls = 0;
};
if (typeof delay === 'number') {
clearTimeout(handle);
handle = setTimeout(doFire, delay);
} else {
if (handle === undefined) {
handle = 0;
queueMicrotask(doFire);
}
}
});
},
onWillRemoveListener() {
if (flushOnListenerRemove && numDebouncedCalls > 0) {
doFire?.();
}
},
onDidRemoveLastListener() {
doFire = undefined;
subscription.dispose();
}
};
if (!disposable) {
_addLeakageTraceLogic(options);
}
const emitter = new Emitter<O>(options);
disposable?.add(emitter);
return emitter.event;
}
/**
* Debounces an event, firing after some delay (default=0) with an array of all event original objects.
*
* *NOTE* that this function returns an `Event` and it MUST be called with a `DisposableStore` whenever the returned
* event is accessible to "third parties", e.g the event is a public property. Otherwise a leaked listener on the
* returned event causes this utility to leak a listener on the original event.
*/
export function accumulate<T>(event: Event<T>, delay: number = 0, disposable?: DisposableStore): Event<T[]> {
return Event.debounce<T, T[]>(event, (last, e) => {
if (!last) {
return [e];
}
last.push(e);
return last;
}, delay, undefined, true, undefined, disposable);
}
/**
* Filters an event such that some condition is _not_ met more than once in a row, effectively ensuring duplicate
* event objects from different sources do not fire the same event object.
*
* *NOTE* that this function returns an `Event` and it MUST be called with a `DisposableStore` whenever the returned
* event is accessible to "third parties", e.g the event is a public property. Otherwise a leaked listener on the
* returned event causes this utility to leak a listener on the original event.
*
* @param event The event source for the new event.
* @param equals The equality condition.
* @param disposable A disposable store to add the new EventEmitter to.
*
* @example
* ```
* // Fire only one time when a single window is opened or focused
* Event.latch(Event.any(onDidOpenWindow, onDidFocusWindow))
* ```
*/
export function latch<T>(event: Event<T>, equals: (a: T, b: T) => boolean = (a, b) => a === b, disposable?: DisposableStore): Event<T> {
let firstCall = true;
let cache: T;
return filter(event, value => {
const shouldEmit = firstCall || !equals(value, cache);
firstCall = false;
cache = value;
return shouldEmit;
}, disposable);
}
/**
* Splits an event whose parameter is a union type into 2 separate events for each type in the union.
*
* *NOTE* that this function returns an `Event` and it MUST be called with a `DisposableStore` whenever the returned
* event is accessible to "third parties", e.g the event is a public property. Otherwise a leaked listener on the
* returned event causes this utility to leak a listener on the original event.
*
* @example
* ```
* const event = new EventEmitter<number | undefined>().event;
* const [numberEvent, undefinedEvent] = Event.split(event, isUndefined);
* ```
*
* @param event The event source for the new event.
* @param isT A function that determines what event is of the first type.
* @param disposable A disposable store to add the new EventEmitter to.
*/
export function split<T, U>(event: Event<T | U>, isT: (e: T | U) => e is T, disposable?: DisposableStore): [Event<T>, Event<U>] {
return [
Event.filter(event, isT, disposable),
Event.filter(event, e => !isT(e), disposable) as Event<U>,
];
}
/**
* Buffers an event until it has a listener attached.
*
* *NOTE* that this function returns an `Event` and it MUST be called with a `DisposableStore` whenever the returned
* event is accessible to "third parties", e.g the event is a public property. Otherwise a leaked listener on the
* returned event causes this utility to leak a listener on the original event.
*
* @param event The event source for the new event.
* @param flushAfterTimeout Determines whether to flush the buffer after a timeout immediately or after a
* `setTimeout` when the first event listener is added.
* @param _buffer Internal: A source event array used for tests.
*
* @example
* ```
* // Start accumulating events, when the first listener is attached, flush
* // the event after a timeout such that multiple listeners attached before
* // the timeout would receive the event
* this.onInstallExtension = Event.buffer(service.onInstallExtension, true);
* ```
*/
export function buffer<T>(event: Event<T>, flushAfterTimeout = false, _buffer: T[] = [], disposable?: DisposableStore): Event<T> {
let buffer: T[] | null = _buffer.slice();
let listener: IDisposable | null = event(e => {
if (buffer) {
buffer.push(e);
} else {
emitter.fire(e);
}
});
if (disposable) {
disposable.add(listener);
}
const flush = () => {
buffer?.forEach(e => emitter.fire(e));
buffer = null;
};
const emitter = new Emitter<T>({
onWillAddFirstListener() {
if (!listener) {
listener = event(e => emitter.fire(e));
if (disposable) {
disposable.add(listener);
}
}
},
onDidAddFirstListener() {
if (buffer) {
if (flushAfterTimeout) {
setTimeout(flush);
} else {
flush();
}
}
},
onDidRemoveLastListener() {
if (listener) {
listener.dispose();
}
listener = null;
}
});
if (disposable) {
disposable.add(emitter);
}
return emitter.event;
}
/**
* Wraps the event in an {@link IChainableEvent}, allowing a more functional programming style.
*
* @example
* ```
* // Normal
* const onEnterPressNormal = Event.filter(
* Event.map(onKeyPress.event, e => new StandardKeyboardEvent(e)),
* e.keyCode === KeyCode.Enter
* ).event;
*
* // Using chain
* const onEnterPressChain = Event.chain(onKeyPress.event, $ => $
* .map(e => new StandardKeyboardEvent(e))
* .filter(e => e.keyCode === KeyCode.Enter)
* );
* ```
*/
export function chain<T, R>(event: Event<T>, sythensize: ($: IChainableSythensis<T>) => IChainableSythensis<R>): Event<R> {
const fn: Event<R> = (listener, thisArgs, disposables) => {
const cs = sythensize(new ChainableSynthesis()) as ChainableSynthesis;
return event(function (value) {
const result = cs.evaluate(value);
if (result !== HaltChainable) {
listener.call(thisArgs, result);
}
}, undefined, disposables);
};
return fn;
}
const HaltChainable = Symbol('HaltChainable');
class ChainableSynthesis implements IChainableSythensis<any> {
private readonly steps: ((input: any) => any)[] = [];
map<O>(fn: (i: any) => O): this {
this.steps.push(fn);
return this;
}
forEach(fn: (i: any) => void): this {
this.steps.push(v => {
fn(v);
return v;
});
return this;
}
filter(fn: (e: any) => boolean): this {
this.steps.push(v => fn(v) ? v : HaltChainable);
return this;
}
reduce<R>(merge: (last: R | undefined, event: any) => R, initial?: R | undefined): this {
let last = initial;
this.steps.push(v => {
last = merge(last, v);
return last;
});
return this;
}
latch(equals: (a: any, b: any) => boolean = (a, b) => a === b): ChainableSynthesis {
let firstCall = true;
let cache: any;
this.steps.push(value => {
const shouldEmit = firstCall || !equals(value, cache);
firstCall = false;
cache = value;
return shouldEmit ? value : HaltChainable;
});
return this;
}
public evaluate(value: any) {
for (const step of this.steps) {
value = step(value);
if (value === HaltChainable) {
break;
}
}
return value;
}
}
export interface IChainableSythensis<T> {
map<O>(fn: (i: T) => O): IChainableSythensis<O>;
forEach(fn: (i: T) => void): IChainableSythensis<T>;
filter<R extends T>(fn: (e: T) => e is R): IChainableSythensis<R>;
filter(fn: (e: T) => boolean): IChainableSythensis<T>;
reduce<R>(merge: (last: R, event: T) => R, initial: R): IChainableSythensis<R>;
reduce<R>(merge: (last: R | undefined, event: T) => R): IChainableSythensis<R>;
latch(equals?: (a: T, b: T) => boolean): IChainableSythensis<T>;
}
export interface NodeEventEmitter {
on(event: string | symbol, listener: Function): unknown;
removeListener(event: string | symbol, listener: Function): unknown;
}
/**
* Creates an {@link Event} from a node event emitter.
*/
export function fromNodeEventEmitter<T>(emitter: NodeEventEmitter, eventName: string, map: (...args: any[]) => T = id => id): Event<T> {
const fn = (...args: any[]) => result.fire(map(...args));
const onFirstListenerAdd = () => emitter.on(eventName, fn);
const onLastListenerRemove = () => emitter.removeListener(eventName, fn);
const result = new Emitter<T>({ onWillAddFirstListener: onFirstListenerAdd, onDidRemoveLastListener: onLastListenerRemove });
return result.event;
}
export interface DOMEventEmitter {
addEventListener(event: string | symbol, listener: Function): void;
removeEventListener(event: string | symbol, listener: Function): void;
}
/**
* Creates an {@link Event} from a DOM event emitter.
*/
export function fromDOMEventEmitter<T>(emitter: DOMEventEmitter, eventName: string, map: (...args: any[]) => T = id => id): Event<T> {
const fn = (...args: any[]) => result.fire(map(...args));
const onFirstListenerAdd = () => emitter.addEventListener(eventName, fn);
const onLastListenerRemove = () => emitter.removeEventListener(eventName, fn);
const result = new Emitter<T>({ onWillAddFirstListener: onFirstListenerAdd, onDidRemoveLastListener: onLastListenerRemove });
return result.event;
}
/**
* Creates a promise out of an event, using the {@link Event.once} helper.
*/
export function toPromise<T>(event: Event<T>): Promise<T> {
return new Promise(resolve => once(event)(resolve));
}
/**
* Creates an event out of a promise that fires once when the promise is
* resolved with the result of the promise or `undefined`.
*/
export function fromPromise<T>(promise: Promise<T>): Event<T | undefined> {
const result = new Emitter<T | undefined>();
promise.then(res => {
result.fire(res);
}, () => {
result.fire(undefined);
}).finally(() => {
result.dispose();
});
return result.event;
}
/**
* Adds a listener to an event and calls the listener immediately with undefined as the event object.
*
* @example
* ```
* // Initialize the UI and update it when dataChangeEvent fires
* runAndSubscribe(dataChangeEvent, () => this._updateUI());
* ```
*/
export function runAndSubscribe<T>(event: Event<T>, handler: (e: T) => any, initial: T): IDisposable;
export function runAndSubscribe<T>(event: Event<T>, handler: (e: T | undefined) => any): IDisposable;
export function runAndSubscribe<T>(event: Event<T>, handler: (e: T | undefined) => any, initial?: T): IDisposable {
handler(initial);
return event(e => handler(e));
}
class EmitterObserver<T> implements IObserver {
readonly emitter: Emitter<T>;
private _counter = 0;
private _hasChanged = false;
constructor(readonly _observable: IObservable<T, any>, store: DisposableStore | undefined) {
const options: EmitterOptions = {
onWillAddFirstListener: () => {
_observable.addObserver(this);
},
onDidRemoveLastListener: () => {
_observable.removeObserver(this);
}
};
if (!store) {
_addLeakageTraceLogic(options);
}
this.emitter = new Emitter<T>(options);
if (store) {
store.add(this.emitter);
}
}
beginUpdate<T>(_observable: IObservable<T, void>): void {
// assert(_observable === this.obs);
this._counter++;
}
handlePossibleChange<T>(_observable: IObservable<T, unknown>): void {
// assert(_observable === this.obs);
}
handleChange<T, TChange>(_observable: IObservable<T, TChange>, _change: TChange): void {
// assert(_observable === this.obs);
this._hasChanged = true;
}
endUpdate<T>(_observable: IObservable<T, void>): void {
// assert(_observable === this.obs);
this._counter--;
if (this._counter === 0) {
this._observable.reportChanges();
if (this._hasChanged) {
this._hasChanged = false;
this.emitter.fire(this._observable.get());
}
}
}
}
/**
* Creates an event emitter that is fired when the observable changes.
* Each listeners subscribes to the emitter.
*/
export function fromObservable<T>(obs: IObservable<T, any>, store?: DisposableStore): Event<T> {
const observer = new EmitterObserver(obs, store);
return observer.emitter.event;
}
/**
* Each listener is attached to the observable directly.
*/
export function fromObservableLight(observable: IObservable<any>): Event<void> {
return (listener, thisArgs, disposables) => {
let count = 0;
let didChange = false;
const observer: IObserver = {
beginUpdate() {
count++;
},
endUpdate() {
count--;
if (count === 0) {
observable.reportChanges();
if (didChange) {
didChange = false;
listener.call(thisArgs);
}
}
},
handlePossibleChange() {
// noop
},
handleChange() {
didChange = true;
}
};
observable.addObserver(observer);
observable.reportChanges();
const disposable = {
dispose() {
observable.removeObserver(observer);
}
};
if (disposables instanceof DisposableStore) {
disposables.add(disposable);
} else if (Array.isArray(disposables)) {
disposables.push(disposable);
}
return disposable;
};
}
}
export interface EmitterOptions {
/**
* Optional function that's called *before* the very first listener is added
*/
onWillAddFirstListener?: Function;
/**
* Optional function that's called *after* the very first listener is added
*/
onDidAddFirstListener?: Function;
/**
* Optional function that's called after a listener is added
*/
onDidAddListener?: Function;
/**
* Optional function that's called *after* remove the very last listener
*/
onDidRemoveLastListener?: Function;
/**
* Optional function that's called *before* a listener is removed
*/
onWillRemoveListener?: Function;
/**
* Optional function that's called when a listener throws an error. Defaults to
* {@link onUnexpectedError}
*/
onListenerError?: (e: any) => void;
/**
* Number of listeners that are allowed before assuming a leak. Default to
* a globally configured value
*
* @see setGlobalLeakWarningThreshold
*/
leakWarningThreshold?: number;
/**
* Pass in a delivery queue, which is useful for ensuring
* in order event delivery across multiple emitters.
*/
deliveryQueue?: EventDeliveryQueue;
/** ONLY enable this during development */
_profName?: string;
}
export class EventProfiling {
static readonly all = new Set<EventProfiling>();
private static _idPool = 0;
readonly name: string;
public listenerCount: number = 0;
public invocationCount = 0;
public elapsedOverall = 0;
public durations: number[] = [];
private _stopWatch?: StopWatch;
constructor(name: string) {
this.name = `${name}_${EventProfiling._idPool++}`;
EventProfiling.all.add(this);
}
start(listenerCount: number): void {
this._stopWatch = new StopWatch();
this.listenerCount = listenerCount;
}
stop(): void {
if (this._stopWatch) {
const elapsed = this._stopWatch.elapsed();
this.durations.push(elapsed);
this.elapsedOverall += elapsed;
this.invocationCount += 1;
this._stopWatch = undefined;
}
}
}
let _globalLeakWarningThreshold = -1;
export function setGlobalLeakWarningThreshold(n: number): IDisposable {
const oldValue = _globalLeakWarningThreshold;
_globalLeakWarningThreshold = n;
return {
dispose() {
_globalLeakWarningThreshold = oldValue;
}
};
}
class LeakageMonitor {
private _stacks: Map<string, number> | undefined;
private _warnCountdown: number = 0;
constructor(
private readonly _errorHandler: (err: Error) => void,
readonly threshold: number,
readonly name: string = Math.random().toString(18).slice(2, 5),
) { }
dispose(): void {
this._stacks?.clear();
}
check(stack: Stacktrace, listenerCount: number): undefined | (() => void) {
const threshold = this.threshold;
if (threshold <= 0 || listenerCount < threshold) {
return undefined;
}
if (!this._stacks) {
this._stacks = new Map();
}
const count = (this._stacks.get(stack.value) || 0);
this._stacks.set(stack.value, count + 1);
this._warnCountdown -= 1;
if (this._warnCountdown <= 0) {
// only warn on first exceed and then every time the limit
// is exceeded by 50% again
this._warnCountdown = threshold * 0.5;
const [topStack, topCount] = this.getMostFrequentStack()!;
const message = `[${this.name}] potential listener LEAK detected, having ${listenerCount} listeners already. MOST frequent listener (${topCount}):`;
console.warn(message);
console.warn(topStack!);
const error = new ListenerLeakError(message, topStack);
this._errorHandler(error);
}
return () => {
const count = (this._stacks!.get(stack.value) || 0);
this._stacks!.set(stack.value, count - 1);
};
}
getMostFrequentStack(): [string, number] | undefined {
if (!this._stacks) {
return undefined;
}
let topStack: [string, number] | undefined;
let topCount: number = 0;
for (const [stack, count] of this._stacks) {
if (!topStack || topCount < count) {
topStack = [stack, count];
topCount = count;
}
}
return topStack;
}
}
class Stacktrace {
static create() {
const err = new Error();
return new Stacktrace(err.stack ?? '');
}
private constructor(readonly value: string) { }
print() {
console.warn(this.value.split('\n').slice(2).join('\n'));
}
}
// error that is logged when going over the configured listener threshold
export class ListenerLeakError extends Error {
constructor(message: string, stack: string) {
super(message);
this.name = 'ListenerLeakError';
this.stack = stack;
}
}
// SEVERE error that is logged when having gone way over the configured listener
// threshold so that the emitter refuses to accept more listeners
export class ListenerRefusalError extends Error {
constructor(message: string, stack: string) {
super(message);
this.name = 'ListenerRefusalError';
this.stack = stack;
}
}
let id = 0;
class UniqueContainer<T> {
stack?: Stacktrace;
public id = id++;
constructor(public readonly value: T) { }
}
const compactionThreshold = 2;
type ListenerContainer<T> = UniqueContainer<(data: T) => void>;
type ListenerOrListeners<T> = (ListenerContainer<T> | undefined)[] | ListenerContainer<T>;
const forEachListener = <T>(listeners: ListenerOrListeners<T>, fn: (c: ListenerContainer<T>) => void) => {
if (listeners instanceof UniqueContainer) {
fn(listeners);
} else {
for (let i = 0; i < listeners.length; i++) {
const l = listeners[i];
if (l) {
fn(l);
}
}
}
};
const _listenerFinalizers = _enableListenerGCedWarning
? new FinalizationRegistry(heldValue => {
if (typeof heldValue === 'string') {
console.warn('[LEAKING LISTENER] GC\'ed a listener that was NOT yet disposed. This is where is was created:');
console.warn(heldValue);
}
})
: undefined;
/**
* The Emitter can be used to expose an Event to the public
* to fire it from the insides.
* Sample:
class Document {
private readonly _onDidChange = new Emitter<(value:string)=>any>();
public onDidChange = this._onDidChange.event;
// getter-style
// get onDidChange(): Event<(value:string)=>any> {
// return this._onDidChange.event;
// }
private _doIt() {
//...
this._onDidChange.fire(value);
}
}
*/
export class Emitter<T> {
private readonly _options?: EmitterOptions;
private readonly _leakageMon?: LeakageMonitor;
private readonly _perfMon?: EventProfiling;
private _disposed?: true;
private _event?: Event<T>;
/**
* A listener, or list of listeners. A single listener is the most common
* for event emitters (#185789), so we optimize that special case to avoid
* wrapping it in an array (just like Node.js itself.)
*
* A list of listeners never 'downgrades' back to a plain function if
* listeners are removed, for two reasons:
*