"use strict";
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const editorExtensions = require("../../../browser/editorExtensions.js");
const contextkey = require("../../../../platform/contextkey/common/contextkey.js");
const cancellation = require("../../../../base/common/cancellation.js");
const linkedList = require("../../../../base/common/linkedList.js");
const instantiation = require("../../../../platform/instantiation/common/instantiation.js");
const extensions = require("../../../../platform/instantiation/common/extensions.js");
const nls = require("../../../../nls.js");
const IEditorCancellationTokens = instantiation.createDecorator("IEditorCancelService");
const ctxCancellableOperation = new contextkey.RawContextKey("cancellableOperation", false, nls.localize("cancellableOperation", "Whether the editor runs a cancellable operation, e.g. like 'Peek References'"));
extensions.registerSingleton(IEditorCancellationTokens, class {
  constructor() {
    this._tokens = /* @__PURE__ */ new WeakMap();
  }
  add(editor, cts) {
    let data = this._tokens.get(editor);
    if (!data) {
      data = editor.invokeWithinContext((accessor) => {
        const key = ctxCancellableOperation.bindTo(accessor.get(contextkey.IContextKeyService));
        const tokens = new linkedList.LinkedList();
        return { key, tokens };
      });
      this._tokens.set(editor, data);
    }
    let removeFn;
    data.key.set(true);
    removeFn = data.tokens.push(cts);
    return () => {
      if (removeFn) {
        removeFn();
        data.key.set(!data.tokens.isEmpty());
        removeFn = void 0;
      }
    };
  }
  cancel(editor) {
    const data = this._tokens.get(editor);
    if (!data) {
      return;
    }
    const cts = data.tokens.pop();
    if (cts) {
      cts.cancel();
      data.key.set(!data.tokens.isEmpty());
    }
  }
}, true);
class EditorKeybindingCancellationTokenSource extends cancellation.CancellationTokenSource {
  constructor(editor, parent) {
    super(parent);
    this.editor = editor;
    this._unregister = editor.invokeWithinContext((accessor) => accessor.get(IEditorCancellationTokens).add(editor, this));
  }
  dispose() {
    this._unregister();
    super.dispose();
  }
}
editorExtensions.registerEditorCommand(new class extends editorExtensions.EditorCommand {
  constructor() {
    super({
      id: "editor.cancelOperation",
      kbOpts: {
        weight: 100,
        primary: 9
        /* Escape */
      },
      precondition: ctxCancellableOperation
    });
  }
  runEditorCommand(accessor, editor) {
    accessor.get(IEditorCancellationTokens).cancel(editor);
  }
}());
exports.EditorKeybindingCancellationTokenSource = EditorKeybindingCancellationTokenSource;
