forked from ajshort/vscode-ros
-
Notifications
You must be signed in to change notification settings - Fork 95
/
extension.ts
380 lines (327 loc) · 13.1 KB
/
extension.ts
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
// Copyright (c) Andrew Short. All rights reserved.
// Licensed under the MIT License.
import * as path from "path";
import * as vscode from "vscode";
import * as cpp_formatter from "./cpp-formatter";
import * as pfs from "./promise-fs";
import * as telemetry from "./telemetry-helper";
import * as vscode_utils from "./vscode-utils";
import * as buildtool from "./build-tool/build-tool";
import * as ros_build_utils from "./ros/build-env-utils";
import * as ros_cli from "./ros/cli";
import * as ros_utils from "./ros/utils";
import { rosApi, selectROSApi } from "./ros/ros";
import URDFPreviewManager from "./urdfPreview/previewManager"
import * as debug_manager from "./debugger/manager";
import * as debug_utils from "./debugger/utils";
import { registerRosShellTaskProvider } from "./build-tool/ros-shell";
/**
* The catkin workspace base dir.
*/
export let baseDir: string;
export function setBaseDir(dir: string) {
baseDir = dir;
}
/**
* The sourced ROS environment.
*/
export let env: any;
export let extPath: string;
export let outputChannel: vscode.OutputChannel;
let onEnvChanged = new vscode.EventEmitter<void>();
/**
* Triggered when the env is soured.
*/
export let onDidChangeEnv = onEnvChanged.event;
export async function resolvedEnv() {
if (env === undefined) { // Env reload in progress
await debug_utils.oneTimePromiseFromEvent(onDidChangeEnv, () => env !== undefined);
}
return env
}
/**
* Subscriptions to dispose when the environment is changed.
*/
let subscriptions = <vscode.Disposable[]>[];
export enum Commands {
CreateCatkinPackage = "ros.createCatkinPackage",
CreateTerminal = "ros.createTerminal",
GetDebugSettings = "ros.getDebugSettings",
Rosrun = "ros.rosrun",
Roslaunch = "ros.roslaunch",
Rostest = "ros.rostest",
Rosdep = "ros.rosdep",
ShowCoreStatus = "ros.showCoreStatus",
StartRosCore = "ros.startCore",
TerminateRosCore = "ros.stopCore",
UpdateCppProperties = "ros.updateCppProperties",
UpdatePythonPath = "ros.updatePythonPath",
PreviewURDF = "ros.previewUrdf",
}
export async function activate(context: vscode.ExtensionContext) {
let init = vscode.window.withProgress({
location: vscode.ProgressLocation.Notification,
title: "ROS Extension Initializing...",
cancellable: false
}, async (progress, token) => {
const reporter = telemetry.getReporter();
extPath = context.extensionPath;
outputChannel = vscode_utils.createOutputChannel();
context.subscriptions.push(outputChannel);
// Activate components when the ROS env is changed.
context.subscriptions.push(onDidChangeEnv(activateEnvironment.bind(null, context)));
// Activate components which don't require the ROS env.
context.subscriptions.push(vscode.languages.registerDocumentFormattingEditProvider(
"cpp", new cpp_formatter.CppFormatter()
));
URDFPreviewManager.INSTANCE.setContext(context);
// Source the environment, and re-source on config change.
let config = vscode_utils.getExtensionConfiguration();
context.subscriptions.push(vscode.workspace.onDidChangeConfiguration(() => {
const updatedConfig = vscode_utils.getExtensionConfiguration();
const fields = Object.keys(config).filter(k => !(config[k] instanceof Function));
const changed = fields.some(key => updatedConfig[key] !== config[key]);
if (changed) {
sourceRosAndWorkspace();
}
config = updatedConfig;
}));
await sourceRosAndWorkspace().then(() =>
{
vscode.window.registerWebviewPanelSerializer('urdfPreview', URDFPreviewManager.INSTANCE);
});
reporter.sendTelemetryActivate();
return {
getBaseDir: () => baseDir,
getEnv: () => env,
onDidChangeEnv: (listener: () => any, thisArg: any) => onDidChangeEnv(listener, thisArg),
};
});
return await init;
}
export async function deactivate() {
subscriptions.forEach(disposable => disposable.dispose());
await telemetry.clearReporter();
}
async function ensureErrorMessageOnException(callback: (...args: any[]) => any) {
try {
await callback();
} catch (err) {
vscode.window.showErrorMessage(err.message);
}
}
/**
* Activates components which require a ROS env.
*/
async function activateEnvironment(context: vscode.ExtensionContext) {
// Clear existing disposables.
while (subscriptions.length > 0) {
subscriptions.pop().dispose();
}
if (typeof env.ROS_DISTRO === "undefined") {
return;
}
if (typeof env.ROS_VERSION === "undefined") {
return;
}
// Determine if we're in a catkin workspace.
let buildToolDetected = await buildtool.determineBuildTool(vscode.workspace.rootPath);
// http://www.ros.org/reps/rep-0149.html#environment-variables
// Learn more about ROS_VERSION definition.
selectROSApi(env.ROS_VERSION);
rosApi.setContext(context, env);
subscriptions.push(rosApi.activateCoreMonitor());
if (buildToolDetected) {
subscriptions.push(...buildtool.BuildTool.registerTaskProvider());
}
subscriptions.push(...registerRosShellTaskProvider());
debug_manager.registerRosDebugManager(context);
// register plugin commands
subscriptions.push(
vscode.commands.registerCommand(Commands.CreateTerminal, () => {
ensureErrorMessageOnException(() => {
ros_utils.createTerminal(context);
});
}),
vscode.commands.registerCommand(Commands.GetDebugSettings, () => {
ensureErrorMessageOnException(() => {
return debug_utils.getDebugSettings(context);
});
}),
vscode.commands.registerCommand(Commands.ShowCoreStatus, () => {
ensureErrorMessageOnException(() => {
rosApi.showCoreMonitor();
});
}),
vscode.commands.registerCommand(Commands.StartRosCore, () => {
ensureErrorMessageOnException(() => {
rosApi.startCore();
});
}),
vscode.commands.registerCommand(Commands.TerminateRosCore, () => {
ensureErrorMessageOnException(() => {
rosApi.stopCore();
});
}),
vscode.commands.registerCommand(Commands.UpdateCppProperties, () => {
ensureErrorMessageOnException(() => {
return ros_build_utils.updateCppProperties(context);
});
}),
vscode.commands.registerCommand(Commands.UpdatePythonPath, () => {
ensureErrorMessageOnException(() => {
ros_build_utils.updatePythonPath(context);
});
}),
vscode.commands.registerCommand(Commands.Rosrun, () => {
ensureErrorMessageOnException(() => {
return ros_cli.rosrun(context);
});
}),
vscode.commands.registerCommand(Commands.Roslaunch, () => {
ensureErrorMessageOnException(() => {
return ros_cli.roslaunch(context);
});
}),
vscode.commands.registerCommand(Commands.Rostest, () => {
ensureErrorMessageOnException(() => {
return ros_cli.rostest(context);
});
}),
vscode.commands.registerCommand(Commands.PreviewURDF, () => {
ensureErrorMessageOnException(() => {
URDFPreviewManager.INSTANCE.preview(vscode.window.activeTextEditor.document.uri);
});
}),
);
// Register commands dependent on a workspace
if (buildToolDetected) {
subscriptions.push(
vscode.commands.registerCommand(Commands.CreateCatkinPackage, () => {
ensureErrorMessageOnException(() => {
return buildtool.BuildTool.createPackage(context);
});
}),
vscode.commands.registerCommand(Commands.Rosdep, () => {
ensureErrorMessageOnException(() => {
rosApi.rosdep();
});
}),
vscode.tasks.onDidEndTask((event: vscode.TaskEndEvent) => {
if (buildtool.isROSBuildTask(event.execution.task)) {
sourceRosAndWorkspace();
}
}),
);
}
else {
subscriptions.push(
vscode.commands.registerCommand(Commands.CreateCatkinPackage, () => {
vscode.window.showErrorMessage(`${Commands.CreateCatkinPackage} requires a ROS workspace to be opened`);
}),
vscode.commands.registerCommand(Commands.Rosdep, () => {
vscode.window.showErrorMessage(`${Commands.Rosdep} requires a ROS workspace to be opened`);
}),
);
}
// Generate config files if they don't already exist, but only for catkin workspaces
if (buildToolDetected) {
ros_build_utils.createConfigFiles();
}
}
/**
* Loads the ROS environment, and prompts the user to select a distro if required.
*/
async function sourceRosAndWorkspace(): Promise<void> {
env = undefined;
const kWorkspaceConfigTimeout = 30000; // ms
let setupScriptExt: string;
if (process.platform === "win32") {
setupScriptExt = ".bat";
} else {
setupScriptExt = ".bash";
}
const config = vscode_utils.getExtensionConfiguration();
let isolateEnvironment = config.get("isolateEnvironment", "");
if (!isolateEnvironment) {
// Capture the host environment unless specifically isolated
env = process.env;
}
let rosSetupScript = config.get("rosSetupScript", "");
// If the workspace setup script is not set, try to find the ROS setup script in the environment
let attemptWorkspaceDiscovery = true;
if (rosSetupScript) {
// Try to support cases where the setup script doesn't make sense on different environments, such as host vs container.
if (await pfs.exists(rosSetupScript)){
try {
env = await ros_utils.sourceSetupFile(rosSetupScript, env);
attemptWorkspaceDiscovery = false;
} catch (err) {
vscode.window.showErrorMessage(`A workspace setup script was provided in the configuration, but could not source "${rosSetupScript}". Attempting standard discovery.`);
}
}
}
if (attemptWorkspaceDiscovery) {
let distro = config.get("distro", "");
// Is there a distro defined either by setting or environment?
if (!distro && !process.env.ROS_DISTRO)
{
// No? Try to find one.
const installedDistros = await ros_utils.getDistros();
if (!installedDistros.length) {
throw new Error("ROS has not been found on this system.");
} else if (installedDistros.length === 1) {
// if there is only one distro installed, directly choose it
config.update("distro", installedDistros[0]);
} else {
const message = "Unable to determine ROS distribution, please configure this workspace by adding \"ros.distro\": \"<ROS Distro>\" in settings.json";
await vscode.window.setStatusBarMessage(message, kWorkspaceConfigTimeout);
}
}
if (distro) {
let setupScript: string;
try {
let globalInstallPath: string;
if (process.platform === "win32") {
globalInstallPath = path.join("C:", "opt", "ros", `${distro}`, "x64");
} else {
globalInstallPath = path.join("/", "opt", "ros", `${distro}`);
}
setupScript = path.format({
dir: globalInstallPath,
name: "setup",
ext: setupScriptExt,
});
env = await ros_utils.sourceSetupFile(setupScript, env);
} catch (err) {
vscode.window.showErrorMessage(`Could not source ROS setup script at "${setupScript}".`);
}
} else if (process.env.ROS_DISTRO) {
env = process.env;
}
}
// Source the workspace setup over the top.
// TODO: we should test what's the build tool (catkin vs colcon).
let workspaceOverlayPath: string;
workspaceOverlayPath = path.join(`${baseDir}`, "devel_isolated");
if (!await pfs.exists(workspaceOverlayPath)) {
workspaceOverlayPath = path.join(`${baseDir}`, "devel");
}
if (!await pfs.exists(workspaceOverlayPath)) {
workspaceOverlayPath = path.join(`${baseDir}`, "install");
}
let wsSetupScript: string = path.format({
dir: workspaceOverlayPath,
name: "setup",
ext: setupScriptExt,
});
if (env && typeof env.ROS_DISTRO !== "undefined" && await pfs.exists(wsSetupScript)) {
try {
env = await ros_utils.sourceSetupFile(wsSetupScript, env);
} catch (_err) {
vscode.window.showErrorMessage("Failed to source the workspace setup file.");
}
}
// Notify listeners the environment has changed.
onEnvChanged.fire();
}