vscode#window TypeScript Examples

The following examples show how to use vscode#window. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: util.ts    From cloudmusic-vscode with MIT License 7 votes vote down vote up
export async function likeMusic(
  input: MultiStepInput,
  step: number,
  id: number
): Promise<InputStep> {
  const title = i18n.word.like;
  const accounts = [...AccountManager.accounts].map(
    ([uid, { nickname: name }]) => ({ uid, name })
  );

  const items = (
    await Promise.allSettled(
      accounts.map(({ uid }) => IPC.netease("likelist", [uid]))
    )
  ).map((res, i) => {
    const { uid, name } = accounts[i];
    return res.status === "fulfilled" && res.value.includes(id)
      ? { label: `$(star-empty) ${name}`, uid, like: false }
      : { label: `$(star-full) ${name}`, uid, like: true };
  });
  const { uid, like } = await input.showQuickPick({ title, step, items });
  if (await IPC.netease("like", [uid, id, like])) {
    IPC.deleteCache(`likelist${uid}`);
    void window.showInformationMessage(
      like ? i18n.word.like : i18n.word.dislike
    );
  } else void window.showErrorMessage(i18n.sentence.fail.addToPlaylist);
  return input.stay();
}
Example #2
Source File: project-utils.ts    From plugin-vscode with Apache License 2.0 7 votes vote down vote up
function getCurrentBallerinaProject(): Promise<BallerinaProject> {
    return new Promise((resolve, reject) => {
        const activeEditor = window.activeTextEditor;
        // if currently opened file is a bal file
        if (activeEditor) {
            // get path of the current bal file
            const uri = activeEditor.document.uri.toString();
            if (ballerinaExtInstance.langClient) {
                // get Ballerina Project path for current Ballerina file
                ballerinaExtInstance.langClient.getBallerinaProject({
                    documentIdentifier: {
                        uri,
                    }
                }).then((project) => {
                    if (ballerinaExtInstance.isSwanLake && !project.kind ||
                        ballerinaExtInstance.is12x && !project.path && !activeEditor.document.fileName.endsWith('.bal')) {
                        reject(`Current file does not belong to a ballerina project.`);
                    }
                    resolve(project);
                });
            } else {
                reject("Language Client is not available.");
            }
        } else {
            reject("There is no active editor.");
        }
    });
}
Example #3
Source File: decoration-utils.ts    From vscode-code-review with MIT License 7 votes vote down vote up
readonly decorationDeclarationType = window.createTextEditorDecorationType({
    isWholeLine: false,
    opacity: '0.9',
    borderWidth: '1px',
    borderColor: '#0f0f0f',
    borderStyle: 'none none dashed none',
    dark: {
      borderColor: '#F6F6F6',
    },
  });
Example #4
Source File: DoComment.ts    From vscode-alxmldocumentation with MIT License 6 votes vote down vote up
/**
     * DoComment constructor
     */
    constructor() {       
        const subscriptions: Disposable[] = [];

        workspace.onDidChangeTextDocument(event => {            
            const activeEditor = window.activeTextEditor;

            if (event.document.languageId !== 'al') {
                return;
            }

            if (activeEditor && event.document === activeEditor.document) {
                this.DoComment(activeEditor, event.contentChanges[0]);
            }
        }, this, subscriptions);
        
        this.disposable = Disposable.from(...subscriptions);
    }
Example #5
Source File: driveAuthenticator.ts    From google-drive-vscode with MIT License 6 votes vote down vote up
private showMissingCredentialsMessage(): void {
    const configureButton = 'Configure credentials';
    window.showWarningMessage(`The operation cannot proceed since Google Drive API credentials haven't been configured. Please configure the credentials and try again.`, configureButton)
      .then(selectedButton => {
        if (selectedButton === configureButton) {
          commands.executeCommand(CONFIGURE_CREDENTIALS_COMMAND);
        }
      });
  }
Example #6
Source File: coverage.ts    From gnucobol-debug with GNU General Public License v3.0 6 votes vote down vote up
private updateStatus() {
        const editor = window.activeTextEditor;
        if (editor === undefined) {
            this.statusBar.hide();
            return;
        }
        const red: Range[] = [];
        const green: Range[] = [];
        for (const coverage of this.coverages) {
            for (const line of coverage.lines) {
                if (this.sourceMap.hasLineCobol(coverage.file, line.line)) {
                    const map = this.sourceMap.getLineCobol(coverage.file, line.line);
                    if (editor.document.uri.fsPath !== map.fileCobol) {
                        continue;
                    }
                    const range = new Range(map.lineCobol - 1, 0, map.lineCobol - 1, Number.MAX_VALUE);
                    if (line.executed) {
                        green.push(range);
                    } else {
                        red.push(range);
                    }
                }
            }
        }
        if (red.length === 0 || !this.highlight) {
            editor.setDecorations(this.RED, []);
        } else {
            editor.setDecorations(this.RED, red);
        }
        if (green.length === 0 || !this.highlight) {
            editor.setDecorations(this.GREEN, []);
        } else {
            editor.setDecorations(this.GREEN, green);
        }
        this.statusBar.text = (this.highlight ? `$(eye) ` : `$(eye-closed) `) + Math.ceil(green.length * 100 / Math.max(1, red.length + green.length)) + '%';
        this.statusBar.tooltip = `Covered ${green.length} of ${red.length} lines`;
        this.statusBar.show();
    }
Example #7
Source File: changeSMApi.ts    From sourcepawn-vscode with MIT License 6 votes vote down vote up
export async function run(args: any) {
  const optionalSMHomes: OptionalSMAPI[] = Workspace.getConfiguration(
    "sourcepawn"
  ).get("availableAPIs");
  let newSMHomeChoices: QuickPickItem[] = optionalSMHomes.map(
    (optionalHome) => {
      return {
        label: optionalHome.name,
        detail: optionalHome.SMHomePath,
      };
    }
  );

  const QuickPickOptions: QuickPickOptions = {
    canPickMany: false,
  };
  window
    .showQuickPick(newSMHomeChoices, QuickPickOptions)
    .then(async (newSMHome) => {
      if (newSMHome.detail == undefined) {
        return;
      }
      await Workspace.getConfiguration("sourcepawn").update(
        "SourcemodHome",
        newSMHome.detail
      );
      let spCompPath = optionalSMHomes.find((e) => e.name === newSMHome.label)
        .compilerPath;
      await Workspace.getConfiguration("sourcepawn").update(
        "SpcompPath",
        spCompPath
      );
      commands.executeCommand("workbench.action.reloadWindow");
    });
  return 0;
}
Example #8
Source File: account.ts    From cloudmusic-vscode with MIT License 6 votes vote down vote up
export async function initAccount(context: ExtensionContext): Promise<void> {
  context.subscriptions.push(
    commands.registerCommand("cloudmusic.addAccount", () =>
      AccountManager.loginQuickPick()
    ),

    commands.registerCommand(
      "cloudmusic.account",
      () =>
        void MultiStepInput.run(async (input) => {
          const pick = await input.showQuickPick({
            title: i18n.word.account,
            step: 1,
            items: [...AccountManager.accounts].map(([uid, { nickname }]) => ({
              label: `$(account) ${nickname}`,
              uid,
            })),
          });
          AccountManager.accountQuickPick(pick.uid);
        })
    ),

    commands.registerCommand(
      "cloudmusic.dailyCheck",
      async () =>
        void window.showInformationMessage(
          (await AccountManager.dailyCheck())
            ? i18n.sentence.success.dailyCheck
            : i18n.sentence.error.needSignIn
        )
    )
  );

  await AccountManager.init();
}
Example #9
Source File: extension.ts    From plugin-vscode with Apache License 2.0 6 votes vote down vote up
showMessageInstallBallerina(): any {
        const download: string = 'Download';
        const openSettings: string = 'Open Settings';
        const viewLogs: string = 'View Logs';
        window.showWarningMessage(INSTALL_BALLERINA, download, openSettings, viewLogs).then((selection) => {
            if (openSettings === selection) {
                commands.executeCommand('workbench.action.openGlobalSettings');
            } else if (download === selection) {
                commands.executeCommand('vscode.open', Uri.parse(DOWNLOAD_BALLERINA));
            } else if (viewLogs === selection) {
                const balOutput = ballerinaExtInstance.getOutPutChannel();
                if (balOutput) {
                    balOutput.show();
                }
            }

        });
    }
Example #10
Source File: index.ts    From flatpak-vscode with MIT License 6 votes vote down vote up
export async function loadIntegrations(manifest: Manifest) {
    for (const integration of INTEGRATIONS) {
        console.log(`Trying to load integration ${integration.extensionId}`)
        if (integration.isApplicable(manifest) && integration.isExtensionEnabled()) {
            try {
                await integration.load(manifest)
                console.log(`Loaded integration ${integration.constructor.name}`)
            } catch (err) {
                void window.showErrorMessage(`Failed to load ${integration.constructor.name} integration: ${err as string}`)
            }
        } else {
            console.log(`Integration ${integration.extensionId} is not applicable`)
        }
    }
}
Example #11
Source File: export-factory.ts    From vscode-code-review with MIT License 6 votes vote down vote up
/**
   * Enable/Disable filtering comments by filename
   * @param state The state of the filter
   * @param force Force the state change, even if it was already correctly set
   * @returns True if the state changed, False otherwise
   */
  public setFilterByFilename(state: boolean, force: boolean = false): boolean {
    let changedState = this.filterByFilename !== state || force;
    this.filterByFilename = state;
    let changedFile = false;

    if (this.filterByFilename) {
      let filename = window.activeTextEditor?.document.fileName;
      if (filename) {
        filename = standardizeFilename(this.workspaceRoot, filename);
        if (this.currentFilename !== filename) {
          changedFile = true;
          this.currentFilename = filename;
        }
      }
    } else {
      this.currentFilename = null;
    }

    if (changedState) {
      commands.executeCommand('setContext', 'isFilteredByFilename', this.filterByFilename);
    }

    return changedState || changedFile;
  }
Example #12
Source File: extension.ts    From ide-vscode with MIT License 6 votes vote down vote up
public async initialize(): Promise<void> {
    if(!this.installer.isCustomInstallation() && !await this.installer.isLanguageServerRuntimeAccessible()) {
      if(!await this.installer.install()) {
        window.showErrorMessage(Messages.Installation.Error);
        return;
      }
    }
    await this.initializeClient();
    if(!await this.updateDafnyIfNecessary(this.languageServerVersion!)) {
      this.statusOutput.appendLine('Dafny initialization failed');
      return;
    }
    await createAndRegisterDafnyIntegration(this.context, this.client!, this.languageServerVersion!);
    this.statusOutput.appendLine('Dafny is ready');
  }
Example #13
Source File: format.ts    From format-imports-vscode with MIT License 6 votes vote down vote up
export async function formatDocument(document: TextDocument, from: TriggeredFrom) {
  const log = logger('vscode.formatDocument');
  if (!isSupported(document)) return undefined;
  const { uri: fileUri, languageId, eol } = document;
  const { fsPath: fileName } = fileUri;
  log.debug('Triggered from:', from);
  try {
    const config = resolveConfig(fileUri, languageId, eol, from === 'onCommand');
    if (from === 'onSave' && config.autoFormat !== 'onSave') {
      log.info('Auto format is', config.autoFormat);
      return undefined;
    }
    if (isFileExcludedByConfig(fileName, config)) {
      const { exclude, excludeGlob } = config;
      log.info('Excluded fileName:', fileName, 'via config:', { exclude, excludeGlob });
      return undefined;
    }
    const sourceText = document.getText();
    const newText = await formatSourceFromFile(sourceText, fileName, config);
    log.info('Finished', newText === undefined ? 'format with no-op' : 'format');
    return newText;
  } catch (e: unknown) {
    log.error('Found exception:', e);
    void window
      .showErrorMessage(
        'Something is wrong. Please open the logs and report an issue.',
        'Open logs & report an issue',
      )
      .then(v => {
        if (!v) return;
        vscChannel.show();
        const p = new URLSearchParams({
          title: `Exception: ${e instanceof Error ? e.message : e}`,
        });
        void commands.executeCommand('vscode.open', Uri.parse(ISSUE_URL + p.toString()));
      });
  }
  return undefined;
}
Example #14
Source File: WorkspaceWatcher.ts    From dendron with GNU Affero General Public License v3.0 6 votes vote down vote up
/** This version of `onDidChangeTextDocument` is debounced for a shorter time, and is useful for UI updates that should happen quickly. */
  async quickOnDidChangeTextDocument(event: TextDocumentChangeEvent) {
    try {
      // `workspace.onDidChangeTextDocument` fires 2 events for every change
      // the second one changing the dirty state of the page from `true` to `false`
      if (event.document.isDirty === false) {
        return;
      }

      const ctx = {
        ctx: "WorkspaceWatcher:quickOnDidChangeTextDocument",
        uri: event.document.uri.fsPath,
      };
      Logger.debug({ ...ctx, state: "enter" });
      this._quickDebouncedOnDidChangeTextDocument.cancel();
      const uri = event.document.uri;
      const { wsRoot, vaults } = this._extension.getDWorkspace();
      if (
        !WorkspaceUtils.isPathInWorkspace({
          wsRoot,
          vaults,
          fpath: uri.fsPath,
        })
      ) {
        Logger.debug({ ...ctx, state: "uri not in workspace" });
        return;
      }
      Logger.debug({ ...ctx, state: "trigger change handlers" });
      const activeEditor = window.activeTextEditor;
      if (activeEditor?.document.uri.fsPath === event.document.uri.fsPath) {
        this._windowWatcher.triggerUpdateDecorations(activeEditor);
      }
      Logger.debug({ ...ctx, state: "exit" });
      return;
    } catch (error) {
      Sentry.captureException(error);
      throw error;
    }
  }