1 | "use strict";
|
2 |
|
3 |
|
4 |
|
5 |
|
6 | Object.defineProperty(exports, "__esModule", { value: true });
|
7 | exports.CancellationTokenSource = exports.CancellationToken = void 0;
|
8 | const ral_1 = require("./ral");
|
9 | const Is = require("./is");
|
10 | const events_1 = require("./events");
|
11 | var CancellationToken;
|
12 | (function (CancellationToken) {
|
13 | CancellationToken.None = Object.freeze({
|
14 | isCancellationRequested: false,
|
15 | onCancellationRequested: events_1.Event.None
|
16 | });
|
17 | CancellationToken.Cancelled = Object.freeze({
|
18 | isCancellationRequested: true,
|
19 | onCancellationRequested: events_1.Event.None
|
20 | });
|
21 | function is(value) {
|
22 | const candidate = value;
|
23 | return candidate && (candidate === CancellationToken.None
|
24 | || candidate === CancellationToken.Cancelled
|
25 | || (Is.boolean(candidate.isCancellationRequested) && !!candidate.onCancellationRequested));
|
26 | }
|
27 | CancellationToken.is = is;
|
28 | })(CancellationToken || (exports.CancellationToken = CancellationToken = {}));
|
29 | const shortcutEvent = Object.freeze(function (callback, context) {
|
30 | const handle = (0, ral_1.default)().timer.setTimeout(callback.bind(context), 0);
|
31 | return { dispose() { handle.dispose(); } };
|
32 | });
|
33 | class MutableToken {
|
34 | constructor() {
|
35 | this._isCancelled = false;
|
36 | }
|
37 | cancel() {
|
38 | if (!this._isCancelled) {
|
39 | this._isCancelled = true;
|
40 | if (this._emitter) {
|
41 | this._emitter.fire(undefined);
|
42 | this.dispose();
|
43 | }
|
44 | }
|
45 | }
|
46 | get isCancellationRequested() {
|
47 | return this._isCancelled;
|
48 | }
|
49 | get onCancellationRequested() {
|
50 | if (this._isCancelled) {
|
51 | return shortcutEvent;
|
52 | }
|
53 | if (!this._emitter) {
|
54 | this._emitter = new events_1.Emitter();
|
55 | }
|
56 | return this._emitter.event;
|
57 | }
|
58 | dispose() {
|
59 | if (this._emitter) {
|
60 | this._emitter.dispose();
|
61 | this._emitter = undefined;
|
62 | }
|
63 | }
|
64 | }
|
65 | class CancellationTokenSource {
|
66 | get token() {
|
67 | if (!this._token) {
|
68 |
|
69 |
|
70 | this._token = new MutableToken();
|
71 | }
|
72 | return this._token;
|
73 | }
|
74 | cancel() {
|
75 | if (!this._token) {
|
76 |
|
77 |
|
78 |
|
79 | this._token = CancellationToken.Cancelled;
|
80 | }
|
81 | else {
|
82 | this._token.cancel();
|
83 | }
|
84 | }
|
85 | dispose() {
|
86 | if (!this._token) {
|
87 |
|
88 | this._token = CancellationToken.None;
|
89 | }
|
90 | else if (this._token instanceof MutableToken) {
|
91 |
|
92 | this._token.dispose();
|
93 | }
|
94 | }
|
95 | }
|
96 | exports.CancellationTokenSource = CancellationTokenSource;
|