"use strict";
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const async = require("../../../../base/common/async.js");
const cancellation = require("../../../../base/common/cancellation.js");
const errors = require("../../../../base/common/errors.js");
const htmlContent = require("../../../../base/common/htmlContent.js");
const lifecycle = require("../../../../base/common/lifecycle.js");
const network = require("../../../../base/common/network.js");
const platform = require("../../../../base/common/platform.js");
const resources = require("../../../../base/common/resources.js");
const stopwatch = require("../../../../base/common/stopwatch.js");
const uri = require("../../../../base/common/uri.js");
require("./links.css.js");
const editorExtensions = require("../../../browser/editorExtensions.js");
const textModel = require("../../../common/model/textModel.js");
const languageFeatureDebounce = require("../../../common/services/languageFeatureDebounce.js");
const languageFeatures = require("../../../common/services/languageFeatures.js");
const clickLinkGesture = require("../../gotoSymbol/browser/link/clickLinkGesture.js");
const getLinks = require("./getLinks.js");
const nls = require("../../../../nls.js");
const notification = require("../../../../platform/notification/common/notification.js");
const opener = require("../../../../platform/opener/common/opener.js");
const colorRegistry = require("../../../../platform/theme/common/colorRegistry.js");
const themeService = require("../../../../platform/theme/common/themeService.js");
var __decorate = globalThis && globalThis.__decorate || function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1; i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __param = globalThis && globalThis.__param || function(paramIndex, decorator) {
  return function(target, key) {
    decorator(target, key, paramIndex);
  };
};
var __awaiter = globalThis && globalThis.__awaiter || function(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve) {
      resolve(value);
    });
  }
  return new (P || (P = Promise))(function(resolve, reject) {
    function fulfilled(value) {
      try {
        step(generator.next(value));
      } catch (e) {
        reject(e);
      }
    }
    function rejected(value) {
      try {
        step(generator["throw"](value));
      } catch (e) {
        reject(e);
      }
    }
    function step(result) {
      result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, _arguments || [])).next());
  });
};
exports.LinkDetector = class LinkDetector extends lifecycle.Disposable {
  constructor(editor, openerService, notificationService, languageFeaturesService, languageFeatureDebounceService) {
    super();
    this.editor = editor;
    this.openerService = openerService;
    this.notificationService = notificationService;
    this.languageFeaturesService = languageFeaturesService;
    this.providers = this.languageFeaturesService.linkProvider;
    this.debounceInformation = languageFeatureDebounceService.for(this.providers, "Links", { min: 1e3, max: 4e3 });
    this.computeLinks = this._register(new async.RunOnceScheduler(() => this.computeLinksNow(), 1e3));
    this.computePromise = null;
    this.activeLinksList = null;
    this.currentOccurrences = {};
    this.activeLinkDecorationId = null;
    const clickLinkGesture$1 = this._register(new clickLinkGesture.ClickLinkGesture(editor));
    this._register(clickLinkGesture$1.onMouseMoveOrRelevantKeyDown(([mouseEvent, keyboardEvent]) => {
      this._onEditorMouseMove(mouseEvent, keyboardEvent);
    }));
    this._register(clickLinkGesture$1.onExecute((e) => {
      this.onEditorMouseUp(e);
    }));
    this._register(clickLinkGesture$1.onCancel((e) => {
      this.cleanUpActiveLinkDecoration();
    }));
    this._register(editor.onDidChangeConfiguration((e) => {
      if (!e.hasChanged(
        63
        /* links */
      )) {
        return;
      }
      this.updateDecorations([]);
      this.stop();
      this.computeLinks.schedule(0);
    }));
    this._register(editor.onDidChangeModelContent((e) => {
      if (!this.editor.hasModel()) {
        return;
      }
      this.computeLinks.schedule(this.debounceInformation.get(this.editor.getModel()));
    }));
    this._register(editor.onDidChangeModel((e) => {
      this.currentOccurrences = {};
      this.activeLinkDecorationId = null;
      this.stop();
      this.computeLinks.schedule(0);
    }));
    this._register(editor.onDidChangeModelLanguage((e) => {
      this.stop();
      this.computeLinks.schedule(0);
    }));
    this._register(this.providers.onDidChange((e) => {
      this.stop();
      this.computeLinks.schedule(0);
    }));
    this.computeLinks.schedule(0);
  }
  static get(editor) {
    return editor.getContribution(LinkDetector.ID);
  }
  computeLinksNow() {
    return __awaiter(this, void 0, void 0, function* () {
      if (!this.editor.hasModel() || !this.editor.getOption(
        63
        /* links */
      )) {
        return;
      }
      const model = this.editor.getModel();
      if (!this.providers.has(model)) {
        return;
      }
      if (this.activeLinksList) {
        this.activeLinksList.dispose();
        this.activeLinksList = null;
      }
      this.computePromise = async.createCancelablePromise((token) => getLinks.getLinks(this.providers, model, token));
      try {
        const sw = new stopwatch.StopWatch(false);
        this.activeLinksList = yield this.computePromise;
        this.debounceInformation.update(model, sw.elapsed());
        if (model.isDisposed()) {
          return;
        }
        this.updateDecorations(this.activeLinksList.links);
      } catch (err) {
        errors.onUnexpectedError(err);
      } finally {
        this.computePromise = null;
      }
    });
  }
  updateDecorations(links) {
    const useMetaKey = this.editor.getOption(
      70
      /* multiCursorModifier */
    ) === "altKey";
    const oldDecorations = [];
    const keys = Object.keys(this.currentOccurrences);
    for (const decorationId of keys) {
      const occurence = this.currentOccurrences[decorationId];
      oldDecorations.push(occurence.decorationId);
    }
    const newDecorations = [];
    if (links) {
      for (const link of links) {
        newDecorations.push(LinkOccurrence.decoration(link, useMetaKey));
      }
    }
    const decorations = this.editor.deltaDecorations(oldDecorations, newDecorations);
    this.currentOccurrences = {};
    this.activeLinkDecorationId = null;
    for (let i = 0, len = decorations.length; i < len; i++) {
      const occurence = new LinkOccurrence(links[i], decorations[i]);
      this.currentOccurrences[occurence.decorationId] = occurence;
    }
  }
  _onEditorMouseMove(mouseEvent, withKey) {
    const useMetaKey = this.editor.getOption(
      70
      /* multiCursorModifier */
    ) === "altKey";
    if (this.isEnabled(mouseEvent, withKey)) {
      this.cleanUpActiveLinkDecoration();
      const occurrence = this.getLinkOccurrence(mouseEvent.target.position);
      if (occurrence) {
        this.editor.changeDecorations((changeAccessor) => {
          occurrence.activate(changeAccessor, useMetaKey);
          this.activeLinkDecorationId = occurrence.decorationId;
        });
      }
    } else {
      this.cleanUpActiveLinkDecoration();
    }
  }
  cleanUpActiveLinkDecoration() {
    const useMetaKey = this.editor.getOption(
      70
      /* multiCursorModifier */
    ) === "altKey";
    if (this.activeLinkDecorationId) {
      const occurrence = this.currentOccurrences[this.activeLinkDecorationId];
      if (occurrence) {
        this.editor.changeDecorations((changeAccessor) => {
          occurrence.deactivate(changeAccessor, useMetaKey);
        });
      }
      this.activeLinkDecorationId = null;
    }
  }
  onEditorMouseUp(mouseEvent) {
    if (!this.isEnabled(mouseEvent)) {
      return;
    }
    const occurrence = this.getLinkOccurrence(mouseEvent.target.position);
    if (!occurrence) {
      return;
    }
    this.openLinkOccurrence(
      occurrence,
      mouseEvent.hasSideBySideModifier,
      true
      /* from user gesture */
    );
  }
  openLinkOccurrence(occurrence, openToSide, fromUserGesture = false) {
    if (!this.openerService) {
      return;
    }
    const { link } = occurrence;
    link.resolve(cancellation.CancellationToken.None).then((uri$1) => {
      if (typeof uri$1 === "string" && this.editor.hasModel()) {
        const modelUri = this.editor.getModel().uri;
        if (modelUri.scheme === network.Schemas.file && uri$1.startsWith(`${network.Schemas.file}:`)) {
          const parsedUri = uri.URI.parse(uri$1);
          if (parsedUri.scheme === network.Schemas.file) {
            const fsPath = resources.originalFSPath(parsedUri);
            let relativePath = null;
            if (fsPath.startsWith("/./")) {
              relativePath = `.${fsPath.substr(1)}`;
            } else if (fsPath.startsWith("//./")) {
              relativePath = `.${fsPath.substr(2)}`;
            }
            if (relativePath) {
              uri$1 = resources.joinPath(modelUri, relativePath);
            }
          }
        }
      }
      return this.openerService.open(uri$1, { openToSide, fromUserGesture, allowContributedOpeners: true, allowCommands: true });
    }, (err) => {
      const messageOrError = err instanceof Error ? err.message : err;
      if (messageOrError === "invalid") {
        this.notificationService.warn(nls.localize("invalid.url", "Failed to open this link because it is not well-formed: {0}", link.url.toString()));
      } else if (messageOrError === "missing") {
        this.notificationService.warn(nls.localize("missing.url", "Failed to open this link because its target is missing."));
      } else {
        errors.onUnexpectedError(err);
      }
    });
  }
  getLinkOccurrence(position) {
    if (!this.editor.hasModel() || !position) {
      return null;
    }
    const decorations = this.editor.getModel().getDecorationsInRange({
      startLineNumber: position.lineNumber,
      startColumn: position.column,
      endLineNumber: position.lineNumber,
      endColumn: position.column
    }, 0, true);
    for (const decoration2 of decorations) {
      const currentOccurrence = this.currentOccurrences[decoration2.id];
      if (currentOccurrence) {
        return currentOccurrence;
      }
    }
    return null;
  }
  isEnabled(mouseEvent, withKey) {
    return Boolean(mouseEvent.target.type === 6 && (mouseEvent.hasTriggerModifier || withKey && withKey.keyCodeIsTriggerKey));
  }
  stop() {
    var _a;
    this.computeLinks.cancel();
    if (this.activeLinksList) {
      (_a = this.activeLinksList) === null || _a === void 0 ? void 0 : _a.dispose();
      this.activeLinksList = null;
    }
    if (this.computePromise) {
      this.computePromise.cancel();
      this.computePromise = null;
    }
  }
  dispose() {
    super.dispose();
    this.stop();
  }
};
exports.LinkDetector.ID = "editor.linkDetector";
exports.LinkDetector = __decorate([
  __param(1, opener.IOpenerService),
  __param(2, notification.INotificationService),
  __param(3, languageFeatures.ILanguageFeaturesService),
  __param(4, languageFeatureDebounce.ILanguageFeatureDebounceService)
], exports.LinkDetector);
const decoration = {
  general: textModel.ModelDecorationOptions.register({
    description: "detected-link",
    stickiness: 1,
    collapseOnReplaceEdit: true,
    inlineClassName: "detected-link"
  }),
  active: textModel.ModelDecorationOptions.register({
    description: "detected-link-active",
    stickiness: 1,
    collapseOnReplaceEdit: true,
    inlineClassName: "detected-link-active"
  })
};
class LinkOccurrence {
  constructor(link, decorationId) {
    this.link = link;
    this.decorationId = decorationId;
  }
  static decoration(link, useMetaKey) {
    return {
      range: link.range,
      options: LinkOccurrence._getOptions(link, useMetaKey, false)
    };
  }
  static _getOptions(link, useMetaKey, isActive) {
    const options = Object.assign({}, isActive ? decoration.active : decoration.general);
    options.hoverMessage = getHoverMessage(link, useMetaKey);
    return options;
  }
  activate(changeAccessor, useMetaKey) {
    changeAccessor.changeDecorationOptions(this.decorationId, LinkOccurrence._getOptions(this.link, useMetaKey, true));
  }
  deactivate(changeAccessor, useMetaKey) {
    changeAccessor.changeDecorationOptions(this.decorationId, LinkOccurrence._getOptions(this.link, useMetaKey, false));
  }
}
function getHoverMessage(link, useMetaKey) {
  const executeCmd = link.url && /^command:/i.test(link.url.toString());
  const label = link.tooltip ? link.tooltip : executeCmd ? nls.localize("links.navigate.executeCmd", "Execute command") : nls.localize("links.navigate.follow", "Follow link");
  const kb = useMetaKey ? platform.isMacintosh ? nls.localize("links.navigate.kb.meta.mac", "cmd + click") : nls.localize("links.navigate.kb.meta", "ctrl + click") : platform.isMacintosh ? nls.localize("links.navigate.kb.alt.mac", "option + click") : nls.localize("links.navigate.kb.alt", "alt + click");
  if (link.url) {
    let nativeLabel = "";
    if (/^command:/i.test(link.url.toString())) {
      const match = link.url.toString().match(/^command:([^?#]+)/);
      if (match) {
        const commandId = match[1];
        const nativeLabelText = nls.localize("tooltip.explanation", "Execute command {0}", commandId);
        nativeLabel = ` "${nativeLabelText}"`;
      }
    }
    const hoverMessage = new htmlContent.MarkdownString("", true).appendMarkdown(`[${label}](${link.url.toString(true).replace(/ /g, "%20")}${nativeLabel}) (${kb})`);
    return hoverMessage;
  } else {
    return new htmlContent.MarkdownString().appendText(`${label} (${kb})`);
  }
}
class OpenLinkAction extends editorExtensions.EditorAction {
  constructor() {
    super({
      id: "editor.action.openLink",
      label: nls.localize("label", "Open Link"),
      alias: "Open Link",
      precondition: void 0
    });
  }
  run(accessor, editor) {
    const linkDetector = exports.LinkDetector.get(editor);
    if (!linkDetector) {
      return;
    }
    if (!editor.hasModel()) {
      return;
    }
    const selections = editor.getSelections();
    for (const sel of selections) {
      const link = linkDetector.getLinkOccurrence(sel.getEndPosition());
      if (link) {
        linkDetector.openLinkOccurrence(link, false);
      }
    }
  }
}
editorExtensions.registerEditorContribution(exports.LinkDetector.ID, exports.LinkDetector);
editorExtensions.registerEditorAction(OpenLinkAction);
themeService.registerThemingParticipant((theme, collector) => {
  const activeLinkForeground = theme.getColor(colorRegistry.editorActiveLinkForeground);
  if (activeLinkForeground) {
    collector.addRule(`.monaco-editor .detected-link-active { color: ${activeLinkForeground} !important; }`);
  }
});
