aboutsummaryrefslogtreecommitdiffstats
path: root/qt-cpp/src/kit-manager.ts
blob: 9cc9bf95e2ba0ca21d5601a50a40ac85ad3abf0b (plain)
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
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
// Copyright (C) 2024 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only

import * as vscode from 'vscode';
import * as path from 'path';
import * as fsSync from 'fs';
import * as fs from 'fs/promises';
import * as os from 'os';
import * as commandExists from 'command-exists';

import {
  PlatformExecutableExtension,
  UserLocalDir,
  createLogger,
  QtInsRootConfigName,
  GlobalWorkspace,
  compareVersions,
  findQtKits,
  isError
} from 'qt-lib';
import * as qtPath from '@util/get-qt-paths';
import { Project } from '@/project';
import { coreAPI } from '@/extension';
import { GlobalStateManager } from '@/state';

const logger = createLogger('kit-manager');

export const CMakeDefaultGenerator = 'Ninja Multi-Config';
const CMakeToolsDir = path.join(UserLocalDir, 'CMakeTools');
export const CMAKE_GLOBAL_KITS_FILEPATH = path.join(
  CMakeToolsDir,
  'cmake-tools-kits.json'
);

type CompilerVendorEnum = 'Clang' | 'GCC' | 'MSVC';

type Environment = Record<string, string | undefined>;

interface CMakeGenerator {
  name: string;
  toolset?: string | undefined;
  platform?: string | undefined;
}

interface KitDetect {
  /**
   * The vendor name of the kit
   */
  vendor?: CompilerVendorEnum;

  /**
   * The triple the kit
   */
  triple?: string;

  /**
   * The version of the kit
   */
  version?: string;

  /**
   * The version of the C runtime for the kit
   * In most case it's equal to version, but for `Clang for MSVC`
   * The Clang version are version
   * The MSVC version are versionRuntime
   */
  versionRuntime?: string;
}

export interface Kit extends KitDetect {
  /**
   * The name of the kit
   */
  name: string;

  /**
   * A description of the kit
   */
  description?: string;

  /**
   * The preferred CMake generator for this kit
   */
  preferredGenerator?: CMakeGenerator | undefined;

  /**
   * Additional settings to pass to CMake
   */
  cmakeSettings?: Record<string, string>;

  /**
   * Additional environment variables for the kit
   */
  environmentVariables?: Environment | undefined;

  /**
   * The language compilers.
   *
   * The key `lang` is the language, as in `CMAKE_<lang>_COMPILER`.
   * The corresponding value is a path to a compiler for that language.
   */
  compilers?: Record<string, string>;

  /**
   * The visual studio name. This corresponds to the installationId returned by `vswhere`.
   */
  visualStudio?: string;

  /**
   * The architecture for the kit. This is used when asking for the architecture
   * from the dev environment batch file.
   */
  visualStudioArchitecture?: string | undefined;

  /**
   * Filename of a shell script which sets environment variables for the kit
   */
  environmentSetupScript?: string;

  /**
   * Path to a CMake toolchain file.
   */
  toolchainFile?: string | undefined;

  /**
   * If `true`, keep this kit around even if it seems out-of-date
   */
  keep?: boolean;

  /**
   * If `true`, this kit comes from a trusted path.
   */
  isTrusted: boolean;
}

export class KitManager {
  projects = new Set<Project>();
  workspaceFile: vscode.Uri | undefined;
  globalStateManager: GlobalStateManager;
  static readonly MapMsvcPlatformToQt: Record<string, string> = {
    x64: '64',
    amd64_x86: '32',
    x86_amd64: '64',
    amd64: '64',
    win32: '32',
    x86: '32'
  };
  static readonly MsvcInfoRegexp = /msvc(\d\d\d\d)_(.+)/; // msvcYEAR_ARCH
  static readonly MsvcInfoNoArchRegexp = /msvc(\d\d\d\d)/; // msvcYEAR
  static readonly MsvcYearRegex = / (\d\d\d\d) /;
  static readonly MsvcMajorVersionNumberRegex = /VisualStudio\.(\d\d)\.\d /;
  static readonly MapMsvcMajorVersionToItsYear: Record<string, string> = {
    11: '2008',
    12: '2010',
    13: '2012',
    14: '2015',
    15: '2017',
    16: '2019',
    17: '2022'
  };

  constructor(readonly context: vscode.ExtensionContext) {
    this.globalStateManager = new GlobalStateManager(context);
  }

  public addProject(project: Project) {
    this.projects.add(project);
    void this.checkForQtInstallations(project);
  }

  public removeProject(project: Project) {
    this.projects.delete(project);
  }

  public async reset() {
    logger.info('Resetting KitManager');
    await this.updateQtKits('', []);
    await this.globalStateManager.reset();
    for (const project of this.projects) {
      await this.updateQtKits('', [], project.getFolder());
      await project.getStateManager().reset();
    }
  }

  public static getCMakeWorkspaceKitsFilepath(folder: vscode.WorkspaceFolder) {
    return path.join(folder.uri.fsPath, '.vscode', 'cmake-kits.json');
  }

  public async checkForAllQtInstallations() {
    await this.checkForGlobalQtInstallations();
    await this.checkForWorkspaceFolderQtInstallations();
  }

  // If the project parameter is undefined, it means that it is a global check
  // otherwise, it is a workspace folder check
  private async checkForQtInstallations(project?: Project) {
    const currentQtInsRoot = project
      ? KitManager.getWorkspaceFolderQtInsRoot(project.getFolder())
      : getCurrentGlobalQtInstallationRoot();
    const newQtInstallations = currentQtInsRoot
      ? await findQtKits(currentQtInsRoot)
      : [];
    project
      ? await this.updateQtKits(
          currentQtInsRoot,
          newQtInstallations,
          project.getFolder()
        )
      : await this.updateQtKits(currentQtInsRoot, newQtInstallations);
  }

  private async checkForGlobalQtInstallations() {
    await this.checkForQtInstallations();
  }

  private async checkForWorkspaceFolderQtInstallations() {
    for (const project of this.projects) {
      await this.checkForQtInstallations(project);
    }
  }

  public async onQtInstallationRootChanged(
    qtInsRoot: string,
    workspaceFolder?: vscode.WorkspaceFolder
  ) {
    const qtInstallations = await findQtKits(qtInsRoot);
    if (qtInsRoot) {
      if (qtInstallations.length === 0) {
        const warningMessage = `Cannot find a Qt installation in "${qtInsRoot}".`;
        void vscode.window.showWarningMessage(warningMessage);
        logger.info(warningMessage);
      } else {
        const infoMessage = `Found ${qtInstallations.length} Qt installation(s) in "${qtInsRoot}".`;
        void vscode.window.showInformationMessage(infoMessage);
        logger.info(infoMessage);
      }
    }
    await this.updateQtKits(qtInsRoot, qtInstallations, workspaceFolder);
  }

  private static async loadCMakeKitsFileJSON(): Promise<Kit[]> {
    if (!fsSync.existsSync(CMAKE_GLOBAL_KITS_FILEPATH)) {
      return [];
    }
    const data = await fs.readFile(CMAKE_GLOBAL_KITS_FILEPATH);
    const stringData = data.toString();
    let kits: Kit[] = [];
    try {
      kits = JSON.parse(stringData) as Kit[];
    } catch (error) {
      if (isError(error)) {
        logger.error('Error parsing cmake-kits.json:', error.message);
      }
    }
    return kits;
  }

  private static generateEnvPathForQtInstallation(installation: string) {
    const installationBinDir = path.join(installation, 'bin');
    const QtPathAddition = [
      installation,
      installationBinDir,
      '${env:PATH}'
    ].join(path.delimiter);
    return QtPathAddition;
  }

  private static async *generateCMakeKitsOfQtInstallationPath(
    qtInsRoot: string,
    installation: string,
    loadedCMakeKits: Kit[]
  ) {
    const promiseCmakeQtToolchainPath =
      qtPath.locateCMakeQtToolchainFile(installation);

    const qtRootDir = qtPath.qtRootByQtInstallation(installation);
    const promiseMingwPath = qtPath.locateMingwBinDirPath(qtRootDir);
    let qtPathEnv = KitManager.generateEnvPathForQtInstallation(installation);
    let locatedNinjaExePath = '';
    if (!commandExists.sync('ninja')) {
      const promiseNinjaExecutable = qtPath.locateNinjaExecutable(qtRootDir);
      locatedNinjaExePath = await promiseNinjaExecutable;
    }
    if (locatedNinjaExePath) {
      qtPathEnv += path.delimiter + path.dirname(locatedNinjaExePath);
    }
    const kitName = qtPath.mangleQtInstallation(qtInsRoot, installation);
    const kitPreferredGenerator = kitName.toLowerCase().includes('wasm_')
      ? 'Ninja'
      : CMakeDefaultGenerator;
    let newKit: Kit = {
      name: kitName,
      environmentVariables: {
        VSCODE_QT_FOLDER: installation,
        PATH: qtPathEnv
      },
      isTrusted: true,
      preferredGenerator: {
        name: kitPreferredGenerator
      }
    };

    const toolchainFilePath = await promiseCmakeQtToolchainPath;
    if (toolchainFilePath) {
      newKit.toolchainFile = toolchainFilePath;
    }
    const toolchain = path.basename(installation);
    const tokens = toolchain.split('_');
    let platform = tokens[0] ?? '';
    if (platform != 'android') {
      if (platform.startsWith('msvc')) {
        newKit = {
          ...newKit,
          ...{
            visualStudio: toolchain,
            visualStudioArchitecture: tokens[-1]
          }
        };
        const msvcKitsClone: Kit[] = JSON.parse(
          JSON.stringify(loadedCMakeKits)
        ) as Kit[];
        logger.info(`MSVC kits clone: ${JSON.stringify(msvcKitsClone)}`);
        yield* KitManager.generateMsvcKits(newKit, msvcKitsClone);
        return;
      } else if (platform.startsWith('mingw')) {
        platform = os.platform();
        logger.info(`Platform: ${platform}`);
        const mingwDirPath = await promiseMingwPath;
        logger.info(`Mingw dir path: ${mingwDirPath}`);
        if (mingwDirPath) {
          if (newKit.environmentVariables == undefined) {
            newKit.environmentVariables = {};
          }
          newKit.environmentVariables.PATH = [
            newKit.environmentVariables.PATH,
            mingwDirPath
          ].join(path.delimiter);
          newKit = {
            ...newKit,
            ...{
              compilers: {
                C: path.join(mingwDirPath, 'gcc' + PlatformExecutableExtension),
                CXX: path.join(
                  mingwDirPath,
                  'g++' + PlatformExecutableExtension
                )
              }
            }
          };
        }
      } else if (platform.startsWith('linux')) {
        platform = 'linux';
      } else if (platform.startsWith('macos')) {
        platform = 'darwin';
        newKit = {
          ...newKit,
          ...{
            compilers: {
              C: '/usr/bin/clang',
              CXX: '/usr/bin/clang++'
            }
          }
        };
      } else if (platform.startsWith('ios')) {
        newKit.preferredGenerator = {
          name: 'Xcode'
        };

        const iosSimulatorKit = {
          ...newKit,
          ...{
            name: newKit.name + '-simulator',
            cmakeSettings: {
              CMAKE_OSX_ARCHITECTURES: 'x86_64',
              CMAKE_OSX_SYSROOT: 'iphonesimulator'
            }
          }
        };
        yield* [newKit, iosSimulatorKit];
        return;
      }
    }
    logger.info('newKit: ' + JSON.stringify(newKit));
    yield newKit;
  }

  private static async cmakeKitsFromQtInstallations(
    qtInstallationRoot: string,
    qtInstallations: string[]
  ) {
    const allCMakeKits = await KitManager.loadCMakeKitsFileJSON();
    logger.info(`qtInstallationRoot: "${qtInstallationRoot}"`);
    logger.info(`Loaded CMake kits: ${JSON.stringify(allCMakeKits)}`);
    // Filter out kits generated by us, since we only want to use Kits
    // that were created by the cmake extension as templates.
    const kitsFromCMakeExtension = allCMakeKits.filter(
      (kit) => kit.environmentVariables?.VSCODE_QT_FOLDER === undefined
    );
    logger.info(
      `Kits from CMake extension: ${JSON.stringify(kitsFromCMakeExtension)}`
    );
    logger.info(`Qt installations: ${JSON.stringify(qtInstallations)}`);
    const kits = [];
    for (const installation of qtInstallations)
      for await (const kit of KitManager.generateCMakeKitsOfQtInstallationPath(
        qtInstallationRoot,
        installation,
        kitsFromCMakeExtension
      ))
        kits.push(kit);
    return kits;
  }

  private async updateQtKits(
    qtInstallationRoot: string,
    qtInstallations: string[],
    workspaceFolder?: vscode.WorkspaceFolder
  ) {
    const newGeneratedKits = await KitManager.cmakeKitsFromQtInstallations(
      qtInstallationRoot,
      qtInstallations
    );
    logger.info(`New generated kits: ${JSON.stringify(newGeneratedKits)}`);
    await this.updateCMakeKitsJson(newGeneratedKits, workspaceFolder);

    if (workspaceFolder) {
      await this.getProject(workspaceFolder)
        ?.getStateManager()
        .setWorkspaceQtKits(newGeneratedKits);
      return;
    }
    await this.globalStateManager.setGlobalQtKits(newGeneratedKits);
  }

  private async updateCMakeKitsJson(
    newGeneratedKits: Kit[],
    workspaceFolder?: vscode.WorkspaceFolder
  ) {
    let previousQtKits: Kit[] = [];
    if (workspaceFolder) {
      const projectStateManager =
        this.getProject(workspaceFolder)?.getStateManager();
      if (projectStateManager) {
        previousQtKits = projectStateManager.getWorkspaceQtKits();
      }
    } else {
      previousQtKits = this.globalStateManager.getGlobalQtKits();
    }
    const cmakeKitsFile = workspaceFolder
      ? path.join(workspaceFolder.uri.fsPath, '.vscode', 'cmake-kits.json')
      : CMAKE_GLOBAL_KITS_FILEPATH;
    const cmakeKitsFileContent = fsSync.existsSync(cmakeKitsFile)
      ? await fs.readFile(cmakeKitsFile, 'utf8')
      : '[]';
    let currentKits: Kit[] = [];
    try {
      currentKits = JSON.parse(cmakeKitsFileContent) as Kit[];
    } catch (error) {
      if (isError(error)) {
        logger.error('Error parsing cmake-kits.json:', error.message);
      }
    }
    const newKits = currentKits.filter((kit) => {
      // filter kits if previousQtKits contains the kit with the same name
      return !previousQtKits.find((prevKit) => prevKit.name === kit.name);
    });
    newKits.push(...newGeneratedKits);
    if (newKits.length !== 0 || fsSync.existsSync(cmakeKitsFile)) {
      await fs.writeFile(cmakeKitsFile, JSON.stringify(newKits, null, 2));
    }
  }

  private getProject(folder: vscode.WorkspaceFolder) {
    for (const project of this.projects) {
      if (project.getFolder() === folder) {
        return project;
      }
    }
    return undefined;
  }

  private static getCMakeGenerator() {
    const cmakeConfig = vscode.workspace.getConfiguration('cmake');
    const generator = cmakeConfig.get<string>('generator');
    return generator ? generator : CMakeDefaultGenerator;
  }

  private static *generateMsvcKits(newKit: Kit, loadedCMakeKits: Kit[]) {
    const msvcInfoMatch =
      newKit.visualStudio?.match(KitManager.MsvcInfoRegexp) ??
      newKit.visualStudio?.match(KitManager.MsvcInfoNoArchRegexp);
    const vsYear = msvcInfoMatch?.at(1) ?? '';
    logger.info('vsYear: ' + vsYear);
    logger.info('newKit.visualStudio: ' + newKit.visualStudio);
    const architecture = msvcInfoMatch?.at(2) ?? '32';
    newKit.preferredGenerator = {
      ...newKit.preferredGenerator,
      ...{
        name: KitManager.getCMakeGenerator()
        // toolset: 'host='+SupportedArchitectureMSVC
      }
    };
    if (architecture) {
      newKit = {
        ...newKit,
        ...{
          visualStudioArchitecture: architecture.toUpperCase()
        }
      };
    }
    logger.info(
      'newKit.visualStudioArchitecture: ' + newKit.visualStudioArchitecture
    );
    const msvcKitsWithArchitectureMatch = loadedCMakeKits.filter((kit) => {
      const version = KitManager.getMsvcYear(kit);
      if (!version) {
        return false;
      }
      logger.info('version: ' + version);
      const msvcTargetArch =
        kit.preferredGenerator?.platform ?? kit.visualStudioArchitecture ?? '';
      logger.info('msvcTargetArch: ' + msvcTargetArch);
      const targetArchitecture = KitManager.MapMsvcPlatformToQt[msvcTargetArch];
      const isArchMatch = targetArchitecture == architecture;
      return isArchMatch && compareVersions(version, vsYear) >= 0;
    });
    for (const kit of msvcKitsWithArchitectureMatch) {
      kit.name = qtPath.mangleMsvcKitName(
        newKit.name + ' - ' + (kit.name || '')
      );
      if (kit.preferredGenerator) {
        if (newKit.preferredGenerator) {
          kit.preferredGenerator.name = newKit.preferredGenerator.name;
          if (kit.preferredGenerator.name == CMakeDefaultGenerator) {
            if (newKit.cmakeSettings) {
              if (kit.cmakeSettings == undefined) {
                kit.cmakeSettings = {};
              }
              kit.cmakeSettings = {
                ...newKit.cmakeSettings,
                ...kit.cmakeSettings
              };
            }
            // Generator 'Ninja Multi-Config' does not support platform & toolset specification
            kit.preferredGenerator.platform = undefined;
            kit.preferredGenerator.toolset = undefined;
          }
        }
      } else {
        kit.preferredGenerator = newKit.preferredGenerator;
      }
      kit.environmentVariables = newKit.environmentVariables;
      kit.toolchainFile = newKit.toolchainFile;
      logger.info('kit: ' + JSON.stringify(kit));
      yield kit;
    }
  }

  private static getMsvcYear(kit: Kit) {
    const year = kit.name.match(KitManager.MsvcYearRegex)?.at(1) ?? '';
    if (year) {
      return year;
    }
    const majorMsvcVersion = kit.name
      .match(KitManager.MsvcMajorVersionNumberRegex)
      ?.at(1);
    if (majorMsvcVersion) {
      return KitManager.MapMsvcMajorVersionToItsYear[majorMsvcVersion] ?? '';
    }
    return '';
  }

  public static getWorkspaceFolderQtInsRoot(folder: vscode.WorkspaceFolder) {
    return coreAPI?.getValue<string>(folder, QtInsRootConfigName) ?? '';
  }
}
export function getCurrentGlobalQtInstallationRoot(): string {
  return coreAPI?.getValue<string>(GlobalWorkspace, QtInsRootConfigName) ?? '';
}