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
|
// Copyright (C) 2024 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only
import * as path from 'path';
import * as vscode from 'vscode';
import { spawnSync } from 'child_process';
import {
Trace,
ServerOptions,
LanguageClient,
LanguageClientOptions
} from 'vscode-languageclient/node';
import untildify from 'untildify';
import {
createLogger,
findQtKits,
isError,
exists,
OSExeSuffix,
QtInsRootConfigName,
compareVersions,
GlobalWorkspace
} from 'qt-lib';
import { coreAPI, projectManager } from '@/extension';
import { EXTENSION_ID } from '@/constants';
import * as installer from '@/installer';
const logger = createLogger('qmlls');
const QMLLS_CONFIG = `${EXTENSION_ID}.qmlls`;
interface QmllsExeConfig {
qmllsPath: string;
qtVersion: string;
}
export enum DecisionCode {
NeedToUpdate,
AlreadyUpToDate,
UserDeclined,
ErrorOccured
}
export enum QmllsStatus {
running,
stopped
}
export async function setDoNotAskForDownloadingQmlls(value: boolean) {
await vscode.workspace
.getConfiguration(EXTENSION_ID)
.update(
'doNotAskForQmllsDownload',
value,
vscode.ConfigurationTarget.Global
);
}
export function getDoNotAskForDownloadingQmlls(): boolean {
return (
vscode.workspace
.getConfiguration(EXTENSION_ID)
.get<boolean>('doNotAskForQmllsDownload') ?? false
);
}
export async function fetchAssetAndDecide(options?: {
doNotAsk?: true;
silent?: boolean;
}): Promise<{
code: DecisionCode;
asset?: installer.AssetWithTag;
}> {
const task = async (
_?: vscode.Progress<{ message?: string; increment?: number }>,
token?: vscode.CancellationToken
) => {
try {
logger.info('Fetching release information');
const controller = new AbortController();
token?.onCancellationRequested(() => {
controller.abort();
});
const asset = await installer.fetchAssetToInstall(controller);
if (!asset) {
return { code: DecisionCode.UserDeclined };
}
const status = installer.checkStatusAgainst(asset);
logger.info('Status Check: ', status.message);
if (!status.shouldInstall) {
return { code: DecisionCode.AlreadyUpToDate, asset };
}
if (options?.doNotAsk !== true) {
if (!(await installer.getUserConsent())) {
logger.info('User declined to install qmlls');
return { code: DecisionCode.UserDeclined };
}
}
return { code: DecisionCode.NeedToUpdate, asset };
} catch (error) {
logger.warn(isError(error) ? error.message : String(error));
return { code: DecisionCode.ErrorOccured };
}
};
if (options?.silent === true) {
return task();
}
const progressOptions = {
title: 'Fetching QML Language Server information',
location: vscode.ProgressLocation.Notification,
cancellable: true
};
return vscode.window.withProgress(progressOptions, task);
}
export class Qmlls {
private readonly _disposables: vscode.Disposable[] = [];
private readonly _importPaths = new Set<string>();
private _client: LanguageClient | undefined;
private _channel: vscode.OutputChannel | undefined;
private _buildDir: string | undefined;
constructor(readonly _folder: vscode.WorkspaceFolder) {
const eventHandler = vscode.workspace.onDidChangeConfiguration((event) => {
if (event.affectsConfiguration(QMLLS_CONFIG, _folder)) {
void this.restart();
}
});
this._disposables.push(eventHandler);
}
dispose() {
for (const d of this._disposables) {
d.dispose();
}
void this._client?.dispose();
this._channel?.dispose();
}
set buildDir(buildDir: string | undefined) {
this._buildDir = buildDir;
}
get buildDir() {
return this._buildDir;
}
addImportPath(importPath: string) {
this._importPaths.add(importPath);
}
removeImportPath(importPath: string) {
this._importPaths.delete(importPath);
}
clearImportPaths() {
this._importPaths.clear();
}
public static async install(
asset: installer.AssetWithTag,
options?: { restart: true }
) {
try {
if (options?.restart) {
await projectManager.stopQmlls();
}
logger.info(`Installing: ${asset.name}, ${asset.tag_name}`);
await installer.install(asset);
logger.info('Installation done');
} catch (error) {
logger.warn(isError(error) ? error.message : String(error));
}
if (options?.restart) {
void projectManager.startQmlls();
return QmllsStatus.running;
}
return QmllsStatus.stopped;
}
public static async checkAssetAndDecide() {
// Do not show the progress bar during the startup
const result = await fetchAssetAndDecide({ silent: true });
if (result.code === DecisionCode.NeedToUpdate && result.asset) {
return Qmlls.install(result.asset);
}
return QmllsStatus.stopped;
}
public async start() {
const configs = vscode.workspace.getConfiguration(
QMLLS_CONFIG,
this._folder
);
if (!configs.get<boolean>('enabled', false)) {
return;
}
try {
if (configs.get<string>('customExePath')) {
const customPath = configs.get<string>('customExePath') ?? '';
const untildifiedCustomPath = untildify(customPath);
const res = spawnSync(untildifiedCustomPath, ['--help'], {
timeout: 1000
});
if (res.status !== 0) {
throw res.error ?? new Error(res.stderr.toString());
}
this.startLanguageClient(customPath);
} else {
const installed = installer.getExpectedQmllsPath();
if (await exists(installed)) {
this.startLanguageClient(installed);
return;
}
const qmllsExeConfig = await findMostRecentExecutableQmlLS();
if (!qmllsExeConfig) {
throw new Error('not found');
}
// Don't start the language server if the version is older than 6.7.2
// Because older versions of the qmlls are not stable
if (compareVersions(qmllsExeConfig.qtVersion, '6.7.2') < 0) {
const infoMessage =
'Cannot turn on QML Language Server because the found Qt versions are older than 6.7.2. Please install a newer version of Qt.';
void vscode.window.showInformationMessage(infoMessage);
logger.info(infoMessage);
return;
}
this.startLanguageClient(qmllsExeConfig.qmllsPath);
}
} catch (error) {
if (isError(error)) {
const message =
'Cannot start QML language server. ' + createErrorString(error);
void vscode.window.showErrorMessage(message);
logger.error(message);
}
}
}
private startLanguageClient(qmllsPath: string) {
const configs = vscode.workspace.getConfiguration(
QMLLS_CONFIG,
this._folder
);
const verboseOutput = configs.get<boolean>('verboseOutput', false);
const traceLsp = configs.get<string>('traceLsp', 'off');
if (!this._channel) {
this._channel = vscode.window.createOutputChannel(
`QML Language Server - ${this._folder.name}`
);
}
const args: string[] = [];
if (verboseOutput) {
args.push('--verbose');
}
const useQmlImportPathEnvVar = configs.get<boolean>(
'useQmlImportPathEnvVar',
false
);
if (useQmlImportPathEnvVar) {
args.push('-E');
}
if (this._buildDir) {
args.push(`-b${this._buildDir}`);
}
const additionalImportPaths = configs.get<string[]>(
'additionalImportPaths',
[]
);
const toImportParam = (p: string) => {
return `-I${p}`;
};
additionalImportPaths.forEach((importPath) => {
args.push(toImportParam(importPath));
});
this._importPaths.forEach((importPath) =>
args.push(toImportParam(importPath))
);
logger.info('Starting QML Language Server with:', args.join(';'));
const serverOptions: ServerOptions = {
command: qmllsPath,
args: args
};
const clientOptions: LanguageClientOptions = {
documentSelector: [
{
language: 'qml',
pattern: `${this._folder.uri.fsPath}/**/*`
}
],
workspaceFolder: this._folder,
outputChannel: this._channel
};
if (traceLsp !== 'off') {
clientOptions.traceOutputChannel = this._channel;
}
// create and start the client,
// this will also launch the server
this._client = new LanguageClient('qmlls', serverOptions, clientOptions);
this._client
.start()
.then(async () => {
await this._client?.setTrace(Trace.fromString(traceLsp));
logger.info(
`QML Language Server started for ${this._folder.name} ${qmllsPath}`
);
})
.catch(() => {
void vscode.window.showErrorMessage('Cannot start QML language server');
logger.error(`LanguageClient has failed to start with ${qmllsPath}`);
});
}
public async stop() {
if (this._client) {
if (this._client.isRunning()) {
await this._client
.stop()
.then(() => {
logger.info('QML Language Server stopped');
})
.catch((e) => {
logger.info(`QML Language Server stop failed, ${e}`);
});
}
this._client = undefined;
}
if (this._channel) {
this._channel.dispose();
this._channel = undefined;
}
}
public async restart() {
await this.stop();
await this.start();
}
}
async function findMostRecentExecutableQmlLS(): Promise<
QmllsExeConfig | undefined
> {
const allQtInsRootDirs: string[] = [];
for (const project of projectManager.getProjects()) {
const qtInsRoot = coreAPI?.getValue<string>(
project.folder,
QtInsRootConfigName
);
if (qtInsRoot) {
allQtInsRootDirs.push(qtInsRoot);
}
}
const globalQtInsRoot = coreAPI?.getValue<string>(
GlobalWorkspace,
QtInsRootConfigName
);
if (globalQtInsRoot) {
allQtInsRootDirs.push(globalQtInsRoot);
}
const found: QmllsExeConfig[] = [];
for (const qtInsDir of allQtInsRootDirs) {
const versionRegex = /^\d+\.\d+\.\d+$/;
const allQt = await findQtKits(qtInsDir);
for (const qt of allQt) {
const relative = path.relative(qtInsDir, qt);
const version = path.normalize(relative).split(path.sep)[0];
if (!version || !versionRegex.test(version)) {
continue;
}
found.push({
qtVersion: version,
qmllsPath: path.join(qt, 'bin', 'qmlls' + OSExeSuffix)
});
}
}
found.sort((a, b) => {
return -1 * compareVersions(a.qtVersion, b.qtVersion);
});
for (const item of found) {
const res = spawnSync(item.qmllsPath, ['--help'], { timeout: 1000 });
if (res.status === 0) {
return item;
}
}
return undefined;
}
function createErrorString(e: Error): string {
const casted = e as {
code?: string;
path?: string;
};
if (!casted.code) {
return e.message;
}
const KnownErrors: Record<string, string> = {
EPERM: 'Operation not permitted',
ENOENT: 'No such file or directory',
EACCES: 'Permission denied'
};
return (
casted.path +
', ' +
`${KnownErrors[casted.code] ?? 'Error'} (${casted.code})`
);
}
|