]> git.lizzy.rs Git - rust.git/blob - editors/code/src/ctx.ts
Merge #3614
[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 } from './client';
6 import { isRustEditor, RustEditor } from './util';
7 import { PersistentState } from './persistent_state';
8
9 export class Ctx {
10     private constructor(
11         readonly config: Config,
12         readonly state: PersistentState,
13         private readonly extCtx: vscode.ExtensionContext,
14         readonly client: lc.LanguageClient
15     ) {
16
17     }
18
19     static async create(config: Config, state: PersistentState, extCtx: vscode.ExtensionContext, serverPath: string): Promise<Ctx> {
20         const client = await createClient(config, serverPath);
21         const res = new Ctx(config, state, extCtx, client);
22         res.pushCleanup(client.start());
23         await client.onReady();
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;