]> git.lizzy.rs Git - rust.git/blob - editors/code/src/ctx.ts
Merge #3277
[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
7 export class Ctx {
8     private constructor(
9         readonly config: Config,
10         private readonly extCtx: vscode.ExtensionContext,
11         readonly client: lc.LanguageClient
12     ) {
13
14     }
15
16     static async create(config: Config, extCtx: vscode.ExtensionContext, serverPath: string): Promise<Ctx> {
17         const client = await createClient(config, serverPath);
18         const res = new Ctx(config, extCtx, client);
19         res.pushCleanup(client.start());
20         await client.onReady();
21         return res;
22     }
23
24     get activeRustEditor(): vscode.TextEditor | undefined {
25         const editor = vscode.window.activeTextEditor;
26         return editor && editor.document.languageId === 'rust'
27             ? editor
28             : undefined;
29     }
30
31     registerCommand(name: string, factory: (ctx: Ctx) => Cmd) {
32         const fullName = `rust-analyzer.${name}`;
33         const cmd = factory(this);
34         const d = vscode.commands.registerCommand(fullName, cmd);
35         this.pushCleanup(d);
36     }
37
38     get globalState(): vscode.Memento {
39         return this.extCtx.globalState;
40     }
41
42     get subscriptions(): Disposable[] {
43         return this.extCtx.subscriptions;
44     }
45
46     pushCleanup(d: Disposable) {
47         this.extCtx.subscriptions.push(d);
48     }
49 }
50
51 export interface Disposable {
52     dispose(): void;
53 }
54 export type Cmd = (...args: any[]) => unknown;