-
Notifications
You must be signed in to change notification settings - Fork 984
Expand file tree
/
Copy pathcommon.ts
More file actions
471 lines (417 loc) · 16.2 KB
/
Copy pathcommon.ts
File metadata and controls
471 lines (417 loc) · 16.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
// Copyright © SixtyFPS GmbH <info@slint.dev>
// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0
// cSpell: ignore codespaces
// This file is common code shared by both vscode plugin entry points
import * as vscode from "vscode";
import * as wasm_preview from "./wasm_preview";
import * as lsp_commands from "./lsp_commands";
import * as snippets from "./snippets";
import type {
BaseLanguageClient,
LanguageClientOptions,
} from "vscode-languageclient";
export class ClientHandle {
#client: BaseLanguageClient | null = null;
#updaters: ((c: BaseLanguageClient | null) => void)[] = [];
get client(): BaseLanguageClient | null {
return this.#client;
}
set client(c: BaseLanguageClient | null) {
this.#client = c;
for (const u of this.#updaters) {
u(this.#client);
}
}
public add_updater(u: (c: BaseLanguageClient | null) => void) {
u(this.#client);
this.#updaters.push(u);
}
async stop() {
const to_stop = this.client;
this.client = null;
for (const u of this.#updaters) {
u(this.#client);
}
if (to_stop) {
// mark as stopped so that we don't detect it as a crash
Object.defineProperty(to_stop, "slint_stopped", {
value: true,
});
await to_stop.stop();
}
}
}
const client = new ClientHandle();
export type RemoteViewerInfo = {
id: string;
label: string;
detail: string;
value: {
addresses: string[];
port: number;
};
timer?: NodeJS.Timeout;
};
export const remote_viewers = new Map<string, RemoteViewerInfo>();
let remoteViewerStatusBarItem: vscode.StatusBarItem | undefined;
export function updateRemoteViewerStatusBarItem(newItem: vscode.StatusBarItem) {
remoteViewerStatusBarItem = newItem;
}
export enum RemoteViewerStatusBarItemState {
disconnected = 0,
connecting = 1,
connected = 2,
}
export function setRemoteViewerStatusBarItemState(
state: RemoteViewerStatusBarItemState,
) {
if (remoteViewerStatusBarItem) {
switch (state) {
case RemoteViewerStatusBarItemState.disconnected:
remoteViewerStatusBarItem.text = "$(vm) Slint Remote Preview";
remoteViewerStatusBarItem.command = "slint.selectRemotePreview";
break;
case RemoteViewerStatusBarItemState.connecting:
remoteViewerStatusBarItem.text =
"$(vm-connect) Slint Remote Preview";
remoteViewerStatusBarItem.command =
"slint.disconnectRemotePreview";
break;
case RemoteViewerStatusBarItemState.connected:
remoteViewerStatusBarItem.text =
"$(vm-active) Slint Remote Preview";
remoteViewerStatusBarItem.command =
"slint.disconnectRemotePreview";
break;
}
}
}
// LSP related:
// Set up our middleware. It is used to redirect/forward to the WASM preview
// as needed and makes the triggering side so much simpler!
export function languageClientOptions(
schemes: string[],
telemetryLogger: vscode.TelemetryLogger,
): LanguageClientOptions {
var document_selector = [];
for (var scheme of schemes) {
document_selector.push({ scheme: scheme, language: "slint" });
document_selector.push({ scheme: scheme, language: "rust" });
}
return {
documentSelector: document_selector,
middleware: {
async provideCodeActions(
document: vscode.TextDocument,
range: vscode.Range,
context: vscode.CodeActionContext,
token: vscode.CancellationToken,
next: any,
) {
const actions = await next(document, range, context, token);
if (actions) {
snippets.detectSnippetCodeActions(actions);
}
return actions;
},
window: {
async showDocument(params, next: any) {
const cl = client.client;
if (!params.external && cl) {
// If the preview panel is open, the default behavior would be to open a document on the same column.
// But we want to open the document next to it instead.
const panel = wasm_preview.panel();
if (panel && panel.active) {
const uri = cl.protocol2CodeConverter.asUri(
params.uri,
);
const col = panel.viewColumn || 1;
const options: vscode.TextDocumentShowOptions = {
viewColumn: col > 1 ? col - 1 : col + 1,
preserveFocus: !params.takeFocus,
};
if (params.selection !== undefined) {
options.selection =
cl.protocol2CodeConverter.asRange(
params.selection,
);
}
await vscode.window.showTextDocument(uri, options);
return { success: true };
}
}
return await next(params);
},
},
async provideCodeLenses(document, token, next) {
const lenses = await next(document, token);
if (lenses && lenses.length > 0) {
await maybeSendStartupTelemetryEvent(telemetryLogger);
}
return lenses;
},
},
};
}
// Setup code to be run *before* the client is started.
// Use the ClientHandle for code that runs after the client is started.
export function prepare_client(client: BaseLanguageClient) {
client.registerFeature(new snippets.SnippetTextEditFeature());
}
// VSCode Plugin lifecycle related:
export function activate(
context: vscode.ExtensionContext,
startClient: (_client: ClientHandle, _ctx: vscode.ExtensionContext) => void,
): vscode.StatusBarItem {
const statusBar = vscode.window.createStatusBarItem(
vscode.StatusBarAlignment.Left,
);
context.subscriptions.push(statusBar);
statusBar.text = "Slint";
client.add_updater((cl) => {
wasm_preview.initClientForPreview(context, cl);
cl?.onNotification("slint/remote_viewer_discovered", (params) => {
vscode.window.showInformationMessage(
`Received update for remote viewers: ${JSON.stringify(params)}`,
);
cl.outputChannel.appendLine(
`Received update for remote viewers: ${JSON.stringify(params)}`,
);
const old_entry = remote_viewers.get(params.host);
if (old_entry) {
clearTimeout(old_entry.timer);
}
const remote_viewer_entry = {
id: params.host,
label: params.host,
detail: params.addresses.join(", "),
value: params,
timer: setTimeout(() => {
remote_viewers.delete(params.host);
}, 60000),
};
remote_viewers.set(params.host, remote_viewer_entry);
});
cl?.onNotification("slint/remote_viewer_connection_state", (params) => {
switch (params.state) {
case "connected":
vscode.window.showInformationMessage(
`Remote viewer connected: ${params.address}:${params.port}, remoteViewerStatusBarItem ${remoteViewerStatusBarItem ? "available" : "undefined"}`,
);
cl.outputChannel.appendLine(
`Remote viewer connected: ${params.address}:${params.port}`,
);
setRemoteViewerStatusBarItemState(
RemoteViewerStatusBarItemState.connected,
);
break;
case "disconnected":
vscode.window.showInformationMessage(
`Remote viewer disconnected: ${params.address}:${params.port}`,
);
cl.outputChannel.appendLine(
`Remote viewer disconnected: ${params.address}:${params.port}`,
);
setRemoteViewerStatusBarItemState(
RemoteViewerStatusBarItemState.disconnected,
);
break;
}
// TODO
});
});
vscode.workspace.onDidChangeConfiguration(async (ev) => {
if (ev.affectsConfiguration("slint")) {
await client.client?.sendNotification(
"workspace/didChangeConfiguration",
{ settings: "" },
);
wasm_preview.update_configuration();
}
});
startClient(client, context);
context.subscriptions.push(
vscode.commands.registerCommand("slint.showPreview", async function () {
const ae = vscode.window.activeTextEditor;
if (!ae) {
return;
}
await lsp_commands.showPreview(ae.document.uri.toString(), "");
}),
);
const command = vscode.commands.registerCommand(
"slint.openHelp",
(word) => {
const helpUrl = getHelpUrlForElement(context, word);
if (helpUrl) {
vscode.env.openExternal(vscode.Uri.parse(helpUrl));
}
},
);
const hoverProvider = vscode.languages.registerHoverProvider(
{ language: "slint" },
{
provideHover(document, position) {
const range = document.getWordRangeAtPosition(position);
const word = document.getText(range);
if (getHelpUrlForElement(context, word)) {
const commandUri = vscode.Uri.parse(
`command:slint.openHelp?${encodeURIComponent(JSON.stringify([word]))}`,
);
const markdown = new vscode.MarkdownString(
`[${word} docs](${commandUri})`,
);
markdown.isTrusted = true;
return new vscode.Hover(markdown, range);
}
},
},
);
context.subscriptions.push(hoverProvider, command);
context.subscriptions.push(
vscode.commands.registerCommand("slint.reload", async function () {
statusBar.hide();
await client.stop();
startClient(client, context);
}),
);
vscode.window.registerWebviewPanelSerializer(
"slint-preview",
new wasm_preview.PreviewSerializer(context),
);
vscode.workspace.onDidChangeConfiguration(async (ev) => {
if (ev.affectsConfiguration("slint")) {
await client.client?.sendNotification(
"workspace/didChangeConfiguration",
{ settings: "" },
);
}
});
return statusBar;
}
export function deactivate(): Thenable<void> | undefined {
if (!client.client) {
return undefined;
}
for (const viewer of remote_viewers.values()) {
clearTimeout(viewer.timer);
}
remote_viewers.clear();
return client.stop();
}
let telemetryEventSent = false;
async function maybeSendStartupTelemetryEvent(
telemetryLogger: vscode.TelemetryLogger,
) {
if (telemetryEventSent) {
return;
}
telemetryEventSent = true;
let usageData = {};
enum ProgrammingLanguage {
Rust = "Rust",
Cpp = "Cpp",
JavaScript = "JavaScript",
Python = "Python",
}
const projectLanguages = new Set<ProgrammingLanguage>();
if (vscode.workspace.workspaceFolders) {
const workspaceFolderContents = await Promise.all(
vscode.workspace.workspaceFolders.map((workspaceFolder) => {
return vscode.workspace.fs.readDirectory(workspaceFolder.uri);
}),
);
for (const path of workspaceFolderContents.flatMap((fileEntries) =>
fileEntries.map((fileEntry) => fileEntry[0].toLowerCase()),
)) {
if (path.endsWith("cargo.toml")) {
projectLanguages.add(ProgrammingLanguage.Rust);
} else if (path.endsWith("cmakelists.txt")) {
projectLanguages.add(ProgrammingLanguage.Cpp);
} else if (path.endsWith("package.json")) {
projectLanguages.add(ProgrammingLanguage.JavaScript);
} else if (
path.endsWith("pyproject.toml") ||
path.endsWith("requirements.txt")
) {
projectLanguages.add(ProgrammingLanguage.Python);
}
}
}
if (projectLanguages.size > 0) {
usageData = Object.assign(usageData, {
projectLanguages: Array.from(projectLanguages.values()),
});
}
telemetryLogger.logUsage("extension-activated", usageData);
}
function helpBaseUrl(context: vscode.ExtensionContext): string {
if (
context.extensionMode === vscode.ExtensionMode.Development ||
context.extension.packageJSON.name.endsWith("-nightly")
) {
return "https://snapshots.slint.dev/master/docs/slint/reference/";
}
return `https://releases.slint.dev/${context.extension.packageJSON.version}/docs/slint/reference/`;
}
function getHelpUrlForElement(
context: vscode.ExtensionContext,
elementName: string,
): string | null {
const elementPaths: Record<string, string> = {
// elements
Image: "elements/image",
Path: "elements/path",
Text: "elements/text",
Rectangle: "elements/rectangle",
// gestures
Flickable: "gestures/flickable",
SwipeGestureHandler: "gestures/swipegesturehandler",
TouchArea: "gestures/toucharea",
// keyboard-input
FocusScope: "keyboard-input/focusscope",
TextInput: "keyboard-input/textinput",
TextInputInterface: "keyboard-input/textinputinterface",
// layouts
GridLayout: "layouts/gridlayout",
HorizontalLayout: "layouts/horizontallayout",
VerticalLayout: "layouts/verticallayout",
// window
ContextMenuArea: "window/contextmenuarea",
Dialog: "window/dialog",
MenuBar: "window/menubar",
PopupWindow: "window/popupwindow",
Window: "window/window",
// reference
Timer: "timer",
// std-widgets/basic-widgets/
Button: "std-widgets/basic-widgets/button",
CheckBox: "std-widgets/basic-widgets/checkbox",
ComboBox: "std-widgets/basic-widgets/combobox",
ProgressIndicator: "std-widgets/basic-widgets/progressindicator",
Slider: "std-widgets/basic-widgets/slider",
SpinBox: "std-widgets/basic-widgets/spinbox",
Spinner: "std-widgets/basic-widgets/spinner",
StandardButton: "std-widgets/basic-widgets/standardbutton",
Switch: "std-widgets/basic-widgets/switch",
//std-widgets/views
LineEdit: "std-widgets/views/lineedit",
ListView: "std-widgets/views/listview",
ScrollView: "std-widgets/views/scrollview",
StandardListView: "std-widgets/views/standardlistview",
StandardTableView: "std-widgets/views/standardtableview",
TabWidget: "std-widgets/views/tabwidget",
TextEdit: "std-widgets/views/textedit",
//std-widgets/layouts
GridBox: "std-widgets/layouts/gridbox",
GroupBox: "std-widgets/layouts/groupbox",
HorizontalBox: "std-widgets/layouts/horizontalbox",
VerticalBox: "std-widgets/layouts/verticalbox",
//std-widgets/misc
AboutSlint: "std-widgets/misc/aboutslint",
DatePickerPopup: "std-widgets/misc/datepickerpopup",
TimerPickerPopup: "std-widgets/misc/timerpickerpopup",
};
const path = elementPaths[elementName];
return path ? `${helpBaseUrl(context)}${path}/` : null;
}