|
| 1 | +// Copyright 2025 The MathWorks, Inc. |
| 2 | + |
| 3 | +import * as fs from 'fs'; |
| 4 | +import * as os from 'os'; |
| 5 | +import { exec } from 'child_process'; |
| 6 | +import * as path from 'path' |
| 7 | +import * as vscode from 'vscode' |
| 8 | +import { LanguageClient } from 'vscode-languageclient/node'; |
| 9 | +import { MatlabState, MVM } from './commandwindow/MVM' |
| 10 | +import Notification from './Notifications' |
| 11 | + |
| 12 | +export default class DefaultEditorService { |
| 13 | + private initialized = false; |
| 14 | + |
| 15 | + constructor (private readonly context: vscode.ExtensionContext, private readonly client: LanguageClient, private readonly mvm: MVM) { |
| 16 | + context.subscriptions.push( |
| 17 | + vscode.workspace.onDidChangeConfiguration(() => { |
| 18 | + void this.handleConfigChanged() |
| 19 | + }) |
| 20 | + ) |
| 21 | + |
| 22 | + mvm.on(MVM.Events.stateChanged, (oldState: MatlabState, newState: MatlabState) => { |
| 23 | + if (oldState === newState) { |
| 24 | + return; |
| 25 | + } |
| 26 | + |
| 27 | + if (newState === MatlabState.READY || newState === MatlabState.BUSY) { |
| 28 | + if (!this.initialized) { |
| 29 | + this.initialized = true |
| 30 | + void this.handleConfigChanged() |
| 31 | + } |
| 32 | + } else { |
| 33 | + this.initialized = false |
| 34 | + } |
| 35 | + }); |
| 36 | + } |
| 37 | + |
| 38 | + /** Helper function: checks if a specific path from array of path strings exists and returns true if a path string is found in file system else returns false |
| 39 | + * @param paths array of string paths to be checked in file system |
| 40 | + * @returns path string if it exists in file system else null |
| 41 | + */ |
| 42 | + private checkPath (paths: string[]): string | null { |
| 43 | + for (const p of paths) { |
| 44 | + if (fs.existsSync(p)) { |
| 45 | + return p; |
| 46 | + } |
| 47 | + } |
| 48 | + return null; |
| 49 | + } |
| 50 | + |
| 51 | + private getFallbackExecutablePaths (): string[] { |
| 52 | + const appRoot = vscode.env.appRoot; |
| 53 | + const platform = process.platform; |
| 54 | + const fallbackPaths: string[] = []; |
| 55 | + |
| 56 | + if (platform === 'win32') { |
| 57 | + // appRoot: C:\Program Files\Microsoft VS Code\resources\app |
| 58 | + // Executable: C:\Program Files\Microsoft VS Code\Code.exe |
| 59 | + fallbackPaths.push( |
| 60 | + path.join(path.dirname(path.dirname(appRoot)), 'Code.exe') |
| 61 | + ); |
| 62 | + } else if (platform === 'darwin') { |
| 63 | + // appRoot: /Applications/Visual Studio Code.app/Contents/Resources/app |
| 64 | + // Executable: /Applications/Visual Studio Code.app/Contents/MacOS/Electron |
| 65 | + // or /Applications/Visual Studio Code.app/Contents/MacOS/Visual Studio Code |
| 66 | + // Try both |
| 67 | + const appDir = path.dirname(path.dirname(appRoot)); // .../Visual Studio Code.app/Contents |
| 68 | + fallbackPaths.push( |
| 69 | + path.join(appDir, 'MacOS', 'Visual Studio Code'), |
| 70 | + path.join(appDir, 'MacOS', 'Electron') |
| 71 | + ); |
| 72 | + } else { |
| 73 | + // Linux |
| 74 | + // appRoot: /usr/share/code/resources/app |
| 75 | + // Executable: /usr/share/code/code |
| 76 | + fallbackPaths.push( |
| 77 | + path.join(path.dirname(path.dirname(appRoot)), 'code') |
| 78 | + ); |
| 79 | + } |
| 80 | + return fallbackPaths |
| 81 | + } |
| 82 | + |
| 83 | + /** Look into most probable installation paths based on OS to find VS Code executable path |
| 84 | + * @returns path string found for VS Code executable |
| 85 | + */ |
| 86 | + public getVSCodePath (): Promise<string> { |
| 87 | + return new Promise((resolve, reject) => { |
| 88 | + const fallbackPaths = this.getFallbackExecutablePaths() |
| 89 | + |
| 90 | + const platform = os.platform(); |
| 91 | + |
| 92 | + const command = platform === 'win32' ? 'where code' : 'which code'; |
| 93 | + |
| 94 | + exec(command, (error, stdout, stderr) => { |
| 95 | + if ((error == null) && typeof stdout === 'string' && stdout !== '') { |
| 96 | + resolve(stdout.trim().split('\n').filter(Boolean)[0].trim()); |
| 97 | + } else { |
| 98 | + const fallback = this.checkPath(fallbackPaths); |
| 99 | + if (typeof fallback === 'string' && fallback.length > 0) { |
| 100 | + resolve(fallback); |
| 101 | + } else { |
| 102 | + reject(new Error('MATLAB Default Editor: Error getting VS Code executable path')); |
| 103 | + } |
| 104 | + } |
| 105 | + }); |
| 106 | + }); |
| 107 | + } |
| 108 | + |
| 109 | + /** |
| 110 | + * Handles the notification that MATLAB failed to set VS Code as default editor successfully. This most likely indicates that |
| 111 | + * either VS Code is not installed in a default location and 'code' is not added to PATH. |
| 112 | + * @param matlabConfig VsCode Workspace object for MATLAB extension configuration |
| 113 | + */ |
| 114 | + public async handleVsCodePathError (matlabConfig: vscode.WorkspaceConfiguration): Promise<void> { |
| 115 | + const message = 'Unable to set MATLAB default editor to Visual Studio Code. Check that VS Code is installed in a default location or add it to the system PATH.' |
| 116 | + const availableCmds = await vscode.commands.getCommands() |
| 117 | + const options = ['Add VS Code to PATH'] |
| 118 | + |
| 119 | + if (availableCmds.includes('workbench.action.installCommandLine')) { |
| 120 | + vscode.window.showErrorMessage(message, ...options).then(choice => { |
| 121 | + switch (choice) { |
| 122 | + case options[0]: |
| 123 | + void vscode.commands.executeCommand('workbench.action.installCommandLine') |
| 124 | + break |
| 125 | + } |
| 126 | + }, reject => console.error(reject)) |
| 127 | + } else { |
| 128 | + vscode.window.showErrorMessage(message).then(choice => { /* empty */ }, reject => console.error(reject)) |
| 129 | + } |
| 130 | + void matlabConfig.update('defaultEditor', false, true); |
| 131 | + } |
| 132 | + |
| 133 | + /** |
| 134 | + * Handles config state management. Finds VS Code executable path when defaultEditor config is enabled and displays an error message if path not found. |
| 135 | + */ |
| 136 | + public handleConfigChanged (): void { |
| 137 | + const configuration = vscode.workspace.getConfiguration('MATLAB') |
| 138 | + if ((configuration.get<boolean>('defaultEditor') ?? true)) { |
| 139 | + this.getVSCodePath().then(validPath => { |
| 140 | + void this.sendExecutablePathNotification(validPath) |
| 141 | + }).catch(err => { |
| 142 | + console.error(err) |
| 143 | + void this.handleVsCodePathError(configuration) |
| 144 | + }); |
| 145 | + } |
| 146 | + } |
| 147 | + |
| 148 | + /** |
| 149 | + * Sends notification to language server to update default editor to VS Code. |
| 150 | + * @param executablePath The path to VS Code |
| 151 | + */ |
| 152 | + public sendExecutablePathNotification (executablePath: string): void { |
| 153 | + void this.client.sendNotification(Notification.EditorExecutablePath, executablePath) |
| 154 | + } |
| 155 | +} |
0 commit comments