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