]> git.lizzy.rs Git - rust.git/blob - editors/code/src/ctx.ts
Merge #3666
[rust.git] / editors / code / src / ctx.ts
1 import * as vscode from 'vscode';
2 import * as lc from 'vscode-languageclient';
3
4 import { Config } from './config';
5 import { createClient, configToServerOptions } from './client';
6 import { isRustEditor, RustEditor } from './util';
7
8 export class Ctx {
9     private constructor(
10         readonly config: Config,
11         private readonly extCtx: vscode.ExtensionContext,
12         readonly client: lc.LanguageClient,
13         readonly serverPath: string,
14     ) {
15
16     }
17
18     static async create(config: Config, extCtx: vscode.ExtensionContext, serverPath: string): Promise<Ctx> {
19         const client = await createClient(config, serverPath);
20         const res = new Ctx(config, extCtx, client, serverPath);
21         res.pushCleanup(client.start());
22         await client.onReady();
23         client.onRequest('workspace/configuration', _ => [configToServerOptions(config)]);
24         return res;
25     }
26
27     get activeRustEditor(): RustEditor | undefined {
28         const editor = vscode.window.activeTextEditor;
29         return editor && isRustEditor(editor)
30             ? editor
31             : undefined;
32     }
33
34     get visibleRustEditors(): RustEditor[] {
35         return vscode.window.visibleTextEditors.filter(isRustEditor);
36     }
37
38     registerCommand(name: string, factory: (ctx: Ctx) => Cmd) {
39         const fullName = `rust-analyzer.${name}`;
40         const cmd = factory(this);
41         const d = vscode.commands.registerCommand(fullName, cmd);
42         this.pushCleanup(d);
43     }
44
45     get globalState(): vscode.Memento {
46         return this.extCtx.globalState;
47     }
48
49     get subscriptions(): Disposable[] {
50         return this.extCtx.subscriptions;
51     }
52
53     pushCleanup(d: Disposable) {
54         this.extCtx.subscriptions.push(d);
55     }
56 }
57
58 export interface Disposable {
59     dispose(): void;
60 }
61 export type Cmd = (...args: any[]) => unknown;