• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

rokucommunity / vscode-brightscript-language / 29273502824

13 Jul 2026 06:11PM UTC coverage: 59.908% (+0.3%) from 59.619%
29273502824

push

github

web-flow
Show an indicator for the active device in the Devices panel (#856)

2591 of 4743 branches covered (54.63%)

Branch coverage included in aggregate %.

31 of 34 new or added lines in 3 files covered. (91.18%)

4021 of 6294 relevant lines covered (63.89%)

43.9 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

34.34
/src/BrightScriptCommands.ts
1
import * as request from 'postman-request';
1✔
2
import * as vscode from 'vscode';
1✔
3
import BrightScriptFileUtils from './BrightScriptFileUtils';
1✔
4
import { GlobalStateManager } from './GlobalStateManager';
1✔
5
import { brighterScriptPreviewCommand } from './commands/BrighterScriptPreviewCommand';
1✔
6
import { captureScreenshotCommand } from './commands/CaptureScreenshotCommand';
1✔
7
import { rekeyAndPackageCommand } from './commands/RekeyAndPackageCommand';
1✔
8
import { languageServerInfoCommand } from './commands/LanguageServerInfoCommand';
1✔
9
import { util } from './util';
1✔
10
import { util as rokuDebugUtil } from 'roku-debug/dist/util';
1✔
11
import type { RemoteControlManager, RemoteControlModeInitiator } from './managers/RemoteControlManager';
12
import type { WhatsNewManager } from './managers/WhatsNewManager';
13
import type { ConfiguredDevice, DeviceManager, HostWithDeviceInfo, RokuDevice } from './deviceDiscovery/DeviceManager';
14
import * as xml2js from 'xml2js';
1✔
15
import { firstBy } from 'thenby';
1✔
16
import type { UserInputManager } from './managers/UserInputManager';
17
import { clearNpmPackageCacheCommand } from './commands/ClearNpmPackageCacheCommand';
1✔
18
import type { LocalPackageManager } from './managers/LocalPackageManager';
19
import { profilingCommands } from './commands/ProfilingCommands';
1✔
20
import { vscodeContextManager } from './managers/VscodeContextManager';
1✔
21
import type { CredentialStore } from './managers/CredentialStore';
22
import type { DevicesViewProvider } from './viewProviders/DevicesViewProvider';
23
import { DEVICE_FILTER_KEYS } from './deviceFilters';
1✔
24
import { rokuDeploy } from 'roku-deploy';
1✔
25

26
export class BrightScriptCommands {
1✔
27

28
    constructor(
29
        private remoteControlManager: RemoteControlManager,
74✔
30
        private whatsNewManager: WhatsNewManager,
74✔
31
        private context: vscode.ExtensionContext,
74✔
32
        private deviceManager: DeviceManager,
74✔
33
        private userInputManager: UserInputManager,
74✔
34
        private localPackageManager: LocalPackageManager,
74✔
35
        private credentialStore: CredentialStore
74✔
36
    ) {
37
        this.fileUtils = new BrightScriptFileUtils();
74✔
38
    }
39

40
    private fileUtils: BrightScriptFileUtils;
41
    public host: string;
42
    public password: string;
43
    public workspacePath: string;
44
    private keypressNotifiers = [] as ((key: string, literalCharacter: boolean) => void)[];
74✔
45

46
    public registerCommands() {
47

48
        brighterScriptPreviewCommand.register(this.context);
16✔
49
        languageServerInfoCommand.register(this.context, this.localPackageManager);
16✔
50
        captureScreenshotCommand.register(this.context, this);
16✔
51
        rekeyAndPackageCommand.register(this.context, this, this.userInputManager);
16✔
52
        clearNpmPackageCacheCommand.register(this.context, this.localPackageManager);
16✔
53
        profilingCommands.register(this.context);
16✔
54

55
        this.registerGeneralCommands();
16✔
56

57
        this.registerCommand('sendRemoteCommand', async (key: string) => {
16✔
58
            await this.sendRemoteCommand(key);
×
59
        });
60

61
        //the "Refresh" button in the Devices list
62
        this.registerCommand('refreshDeviceList', (key: string) => {
16✔
63
            this.deviceManager.refresh(true);
×
64
        });
65

66
        this.registerCommand('rescanDevices', () => {
16✔
67
            this.deviceManager.refresh(true);
×
68
        });
69

70
        // Refresh a single device (inline button on hover in devices panel)
71
        this.registerCommand('refreshDevice', async (item: { key: string }) => {
16✔
72
            await this.deviceManager.healthCheckDevice({ serialNumber: item.key }, true);
×
73
        });
74

75
        this.registerCommand('sendRemoteText', async () => {
16✔
76
            let items: vscode.QuickPickItem[] = [];
×
77
            for (const item of new GlobalStateManager(this.context).sendRemoteTextHistory) {
×
78
                items.push({ label: item });
×
79
            }
80

81
            const stuffUserTyped = await util.showQuickPickInputBox({
×
82
                placeholder: 'Press enter to send all typed characters to the Roku',
83
                items: items
84
            });
85
            console.log('userInput', stuffUserTyped);
×
86

87
            if (stuffUserTyped) {
×
88
                new GlobalStateManager(this.context).addTextHistory(stuffUserTyped);
×
89
                let fallbackToHttp = true;
×
90
                await this.getRemoteHost();
×
91
                //TODO fix SceneGraphDebugCommandController to not timeout so quickly
92
                // try {
93
                //     let commandController = new SceneGraphDebugCommandController(this.host);
94
                //     let response = await commandController.type(stuffUserTyped);
95
                //     if (!response.error) {
96
                //         fallbackToHttp = false;
97
                //     }
98
                // } catch (error) {
99
                //     console.error(error);
100
                //     // Let this fallback to the old HTTP based logic
101
                // }
102

103
                if (fallbackToHttp) {
×
104
                    for (let character of stuffUserTyped) {
×
105
                        await this.sendAsciiToDevice(character);
×
106
                    }
107
                }
108
            }
109
            await vscode.commands.executeCommand('workbench.action.focusPanel');
×
110
        });
111

112
        this.registerCommand('toggleRemoteControlMode', (initiator: RemoteControlModeInitiator) => {
16✔
113
            return this.remoteControlManager.toggleRemoteControlMode(initiator);
×
114
        });
115

116
        this.registerCommand('enableRemoteControlMode', () => {
16✔
117
            return this.remoteControlManager.setRemoteControlMode(true, 'command');
×
118
        });
119

120
        this.registerCommand('disableRemoteControlMode', () => {
16✔
121
            return this.remoteControlManager.setRemoteControlMode(false, 'command');
×
122
        });
123

124
        this.registerCommand('pressBackButton', async () => {
16✔
125
            await this.sendRemoteCommand('Back');
×
126
        });
127

128
        this.registerCommand('pressBackspaceButton', async () => {
16✔
129
            await this.sendRemoteCommand('Backspace');
×
130
        });
131

132
        this.registerCommand('pressHomeButton', async () => {
16✔
133
            await this.sendRemoteCommand('Home');
×
134
        });
135

136
        this.registerCommand('restartDevApplication', async () => {
16✔
137
            await this.restartDevApplication();
×
138
        });
139

140
        this.registerCommand('pressUpButton', async () => {
16✔
141
            await this.sendRemoteCommand('Up');
×
142
        });
143

144
        this.registerCommand('pressDownButton', async () => {
16✔
145
            await this.sendRemoteCommand('Down');
×
146
        });
147

148
        this.registerCommand('pressRightButton', async () => {
16✔
149
            await this.sendRemoteCommand('Right');
×
150
        });
151

152
        this.registerCommand('pressLeftButton', async () => {
16✔
153
            await this.sendRemoteCommand('Left');
×
154
        });
155

156
        this.registerCommand('pressSelectButton', async () => {
16✔
157
            await this.sendRemoteCommand('Select');
×
158
        });
159

160
        this.registerCommand('pressPlayButton', async () => {
16✔
161
            await this.sendRemoteCommand('Play');
×
162
        });
163

164
        this.registerCommand('pressRevButton', async () => {
16✔
165
            await this.sendRemoteCommand('Rev');
×
166
        });
167

168
        this.registerCommand('pressFwdButton', async () => {
16✔
169
            await this.sendRemoteCommand('Fwd');
×
170
        });
171

172
        this.registerCommand('pressStarButton', async () => {
16✔
173
            await this.sendRemoteCommand('Info');
×
174
        });
175

176
        this.registerCommand('pressInstantReplayButton', async () => {
16✔
177
            await this.sendRemoteCommand('InstantReplay');
×
178
        });
179

180
        this.registerCommand('pressSearchButton', async () => {
16✔
181
            await this.sendRemoteCommand('Search');
×
182
        });
183

184
        this.registerCommand('pressEnterButton', async () => {
16✔
185
            await this.sendRemoteCommand('Enter');
×
186
        });
187

188
        this.registerCommand('pressFindRemote', async () => {
16✔
189
            await this.sendRemoteCommand('FindRemote');
×
190
        });
191

192
        this.registerCommand('pressVolumeDown', async () => {
16✔
193
            await this.sendRemoteCommand('VolumeDown');
×
194
        });
195

196
        this.registerCommand('pressVolumeMute', async () => {
16✔
197
            await this.sendRemoteCommand('VolumeMute');
×
198
        });
199

200
        this.registerCommand('pressVolumeUp', async () => {
16✔
201
            await this.sendRemoteCommand('VolumeUp');
×
202
        });
203

204
        this.registerCommand('setVolume', async () => {
16✔
205
            let result = await vscode.window.showInputBox({
×
206
                placeHolder: 'The target volume level (0-100)',
207
                value: '',
208
                validateInput: (text: string) => {
209
                    const num = Number(text);
×
210
                    if (isNaN(num)) {
×
211
                        return 'Value must be a number';
×
212
                    } else if (num < 0 || num > 100) {
×
213
                        return 'Please enter a number between 0 and 100';
×
214
                    }
215
                    return null;
×
216
                }
217
            });
218
            const targetVolume = Number(result);
×
219

220
            if (!isNaN(targetVolume)) {
×
221
                await vscode.window.withProgress({
×
222
                    location: vscode.ProgressLocation.Notification,
223
                    title: 'Setting volume'
224
                }, async (progress) => {
225
                    const totalCommands = 100 + targetVolume;
×
226
                    const incrementValue = 100 / totalCommands;
×
227
                    let executedCommands = 0;
×
228

229
                    for (let i = 0; i < 100; i++) {
×
230
                        await this.sendRemoteCommand('VolumeDown');
×
231
                        executedCommands++;
×
232
                        progress.report({ increment: incrementValue, message: `decreasing volume - ${Math.round((executedCommands / totalCommands) * 100)}%` });
×
233
                    }
234

235
                    for (let i = 0; i < targetVolume; i++) {
×
236
                        await this.sendRemoteCommand('VolumeUp');
×
237
                        executedCommands++;
×
238
                        progress.report({ increment: incrementValue, message: `increasing volume - ${Math.round((executedCommands / totalCommands) * 100)}%` });
×
239
                    }
240
                });
241
            }
242
        });
243

244
        this.registerCommand('pressPowerOff', async () => {
16✔
245
            await this.sendRemoteCommand('PowerOff');
×
246
        });
247

248
        this.registerCommand('pressPowerOn', async () => {
16✔
249
            await this.sendRemoteCommand('PowerOn');
×
250
        });
251

252
        this.registerCommand('pressChannelUp', async () => {
16✔
253
            await this.sendRemoteCommand('ChannelUp');
×
254
        });
255

256
        this.registerCommand('pressChannelDown', async () => {
16✔
257
            await this.sendRemoteCommand('ChannelDown');
×
258
        });
259

260
        this.registerCommand('pressBlue', async () => {
16✔
261
            await this.sendRemoteCommand('Blue');
×
262
        });
263

264
        this.registerCommand('pressGreen', async () => {
16✔
265
            await this.sendRemoteCommand('Green');
×
266
        });
267

268
        this.registerCommand('pressRed', async () => {
16✔
269
            await this.sendRemoteCommand('Red');
×
270
        });
271

272
        this.registerCommand('pressYellow', async () => {
16✔
273
            await this.sendRemoteCommand('Yellow');
×
274
        });
275

276
        this.registerCommand('pressExit', async () => {
16✔
277
            await this.sendRemoteCommand('Exit');
×
278
        });
279

280
        this.registerCommand('changeTvInput', async (host?: string) => {
16✔
281
            const selectedInput = await vscode.window.showQuickPick([
×
282
                'InputHDMI1',
283
                'InputHDMI2',
284
                'InputHDMI3',
285
                'InputHDMI4',
286
                'InputAV1',
287
                'InputTuner'
288
            ]);
289

290
            if (selectedInput) {
×
291
                await this.sendRemoteCommand(selectedInput, host);
×
292
            }
293
        });
294

295
        this.registerKeyboardInputs();
16✔
296
    }
297

298
    /**
299
     * Registers all the commands for a-z, A-Z, 0-9, and all the primary character such as !, @, #, ', ", etc...
300
     */
301
    private registerKeyboardInputs() {
302
        // Get all the keybindings from our package.json
303
        const extension = vscode.extensions.getExtension('RokuCommunity.brightscript');
16✔
304
        const keybindings = (extension.packageJSON.contributes.keybindings as Array<{
16✔
305
            key: string;
306
            command: string;
307
            when: string;
308
            args: any;
309
        }>);
310

311
        for (let keybinding of keybindings) {
16✔
312
            // Find every keybinding that is related to sending text characters to the device
313
            if (keybinding.command.includes('.sendAscii+')) {
2,320✔
314

315
                if (!keybinding.args) {
1,536!
316
                    throw new Error(`Can not register command: ${keybinding.command}. Missing Arguments.`);
×
317
                }
318

319
                // Dynamically register the the command defined in the keybinding
320
                this.registerCommand(keybinding.command, async (character: string) => {
1,536✔
321
                    await this.sendAsciiToDevice(character);
×
322
                });
323
            }
324
        }
325
    }
326

327
    private registerGeneralCommands() {
328
        //a command that does absolutely nothing. It's here to allow us to absorb unsupported keypresses when in **remote control mode**.
329
        this.registerCommand('doNothing', () => { });
16✔
330

331
        this.registerCommand('toggleXML', async () => {
16✔
332
            await this.onToggleXml();
×
333
        });
334

335
        this.registerCommand('goToParentComponent', async () => {
16✔
336
            await this.onGoToParentComponent();
×
337
        });
338

339
        this.registerCommand('clearGlobalState', async () => {
16✔
340
            new GlobalStateManager(this.context).clear();
×
341
            await vscode.window.showInformationMessage('BrightScript Language extension global state cleared');
×
342
        });
343

344
        this.registerCommand('clearCurrentDeviceList', async () => {
16✔
345
            const toatsPromise = util.showTimedNotification('Clearing device list');
×
346
            await this.deviceManager.clearCurrentDeviceList();
×
347
            await toatsPromise;
×
348
        });
349

350
        this.registerCommand('enableDeviceDiscovery', async () => {
16✔
351
            await util.setConfigurationValueAtUserOrClosestScope('brightscript.deviceDiscovery.enabled', true);
×
352
        });
353

354
        this.registerCommand('disableDeviceDiscovery', async () => {
16✔
355
            await util.setConfigurationValueAtUserOrClosestScope('brightscript.deviceDiscovery.enabled', false);
×
356
        });
357

358
        this.registerCommand('clearDeviceCache', async () => {
16✔
359
            this.deviceManager.clearAllCache();
×
360
            await util.showTimedNotification('Clearing device cache');
×
361
        });
362

363
        this.registerCommand('clearLastSeenDevices', async () => {
16✔
364
            new GlobalStateManager(this.context).clearLastSeenDevices();
×
365
            await vscode.window.showInformationMessage('Last seen devices cleared');
×
366
        });
367

368
        this.registerCommand('copyToClipboard', async (value: string) => {
16✔
369
            try {
×
370
                if (util.isNullish(value)) {
×
371
                    throw new Error('Cannot copy ${value} to clipboard');
×
372
                }
373
                await vscode.env.clipboard.writeText(value?.toString());
×
374
                await vscode.window.showInformationMessage(`Copied to clipboard: ${value}`);
×
375
            } catch (error) {
376
                await vscode.window.showErrorMessage(`Could not copy value to clipboard`);
×
377
            }
378
        });
379

380
        this.registerCommand('openUrl', async (url: string) => {
16✔
381
            try {
×
382
                await vscode.env.openExternal(vscode.Uri.parse(url));
×
383
            } catch (error) {
384
                await vscode.window.showErrorMessage(`Tried to open url but failed: ${url}`);
×
385
            }
386
        });
387

388
        this.registerCommand('openRegistryInBrowser', async (host: string) => {
16✔
389
            if (!host) {
×
390
                host = (await this.userInputManager.promptForHost())?.host;
×
391
            }
392

393
            let responseText = await util.spinAsync('Fetching app list', async () => {
×
394
                return (await util.httpGet(`http://${host}:8060/query/apps`, { timeout: 4_000 })).body as string;
×
395
            });
396

397
            const parsed = await xml2js.parseStringPromise(responseText);
×
398

399
            //convert the items to QuickPick items
400
            const items: Array<vscode.QuickPickItem & { appId?: string }> = parsed.apps.app.map((appData: any) => {
×
401
                return {
×
402
                    label: appData._,
403
                    detail: `ID: ${appData.$.id}`,
404
                    description: `${appData.$.version}`,
405
                    appId: `${appData.$.id}`
406
                } as vscode.QuickPickItem;
407
                //sort the items alphabetically
408
            }).sort(firstBy('label'));
409

410
            //move the dev app to the top (and add a label/section to differentiate it)
411
            const devApp = items.find(x => x.appId === 'dev');
×
412
            if (devApp) {
×
413
                items.splice(items.indexOf(devApp), 1);
×
414
                items.unshift(
×
415
                    { kind: vscode.QuickPickItemKind.Separator, label: 'dev' },
416
                    devApp,
417
                    { kind: vscode.QuickPickItemKind.Separator, label: ' ' }
418
                );
419
            }
420

421
            const selectedApp: typeof items[0] = await vscode.window.showQuickPick(items, { placeHolder: 'Which app would you like to see the registry for?' });
×
422

423
            if (selectedApp) {
×
424
                const appId = selectedApp.appId;
×
425
                let url = `http://${host}:8060/query/registry/${appId}`;
×
426
                try {
×
427
                    await vscode.env.openExternal(vscode.Uri.parse(url));
×
428
                } catch (error) {
429
                    await vscode.window.showErrorMessage(`Tried to open url but failed: ${url}`);
×
430
                }
431
            }
432
        });
433

434
        this.registerCommand('setActiveDevice', async (deviceOrItem: string | { key: string }) => {
16✔
435
            let ip: string;
436
            if (typeof deviceOrItem === 'object' && deviceOrItem?.key) {
×
437
                ip = this.deviceManager.getDevice(deviceOrItem.key)?.ip;
×
438
            } else if (typeof deviceOrItem === 'string') {
×
439
                ip = deviceOrItem;
×
440
            }
441
            if (!ip) {
×
442
                ip = (await this.userInputManager.promptForHost())?.host;
×
443
            }
444
            if (!ip) {
×
445
                throw new Error('Tried to set active device but failed.');
×
446
            } else {
447
                await this.deviceManager.setActiveDevice(ip);
×
448
                await util.showTimedNotification(`'${ip}' set as active device`);
×
449
            }
450
        });
451

452
        this.registerCommand('editDeviceInUserSettings', async (deviceOrItem: { key: string }) => {
16✔
453
            const device = this.deviceManager.getDevice(deviceOrItem?.key);
×
454
            await this.openSettingsJsonAtDevice(device, 'user');
×
455
        });
456

457
        this.registerCommand('editDeviceInWorkspaceSettings', async (deviceOrItem: { key: string }) => {
16✔
458
            const device = this.deviceManager.getDevice(deviceOrItem?.key);
×
459
            await this.openSettingsJsonAtDevice(device, 'workspace');
×
460
        });
461

462
        this.registerCommand('addDeviceToUserSettings', async (deviceOrItem: { key: string }) => {
16✔
463
            const device = this.deviceManager.getDevice(deviceOrItem?.key);
×
464
            if (!device) {
×
465
                void vscode.window.showErrorMessage('Could not find device to add to settings.');
×
466
                return;
×
467
            }
468

469
            const config = vscode.workspace.getConfiguration('brightscript');
×
470
            const inspection = config.inspect<ConfiguredDevice[]>('devices');
×
471
            const userDevices = inspection?.globalValue || [];
×
472

473
            if (userDevices.some(d => d.host === device.ip || (device.serialNumber && d.serialNumber === device.serialNumber))) {
×
474
                void vscode.window.showInformationMessage('Device is already in your user settings.');
×
475
                return;
×
476
            }
477

478
            // Copy any cred-store-cached password into the settings entry so the device
479
            // is portable across machines via Settings Sync. The cred store keeps its own
480
            // copy — it's a running cache of validated passwords that gets refreshed on
481
            // each successful password validation.
482
            const storedPassword = device.serialNumber
×
483
                ? await this.credentialStore.getPassword(device.serialNumber)
484
                : undefined;
485

486
            const newDevice = {
×
487
                host: device.ip,
488
                ...(device.serialNumber && { serialNumber: device.serialNumber }),
×
489
                ...(storedPassword && { password: storedPassword })
×
490
            };
491
            userDevices.push(newDevice);
×
492

493
            await config.update('devices', userDevices, vscode.ConfigurationTarget.Global);
×
494
            const displayName = device.deviceInfo['user-device-name'] || device.deviceInfo['default-device-name'] || device.ip;
×
495
            void vscode.window.showInformationMessage(`Added "${displayName}" to user settings.`);
×
496
        });
497

498
        this.registerCommand('addDeviceToWorkspaceSettings', async (deviceOrItem: { key: string }) => {
16✔
499
            const device = this.deviceManager.getDevice(deviceOrItem?.key);
×
500
            if (!device) {
×
501
                void vscode.window.showErrorMessage('Could not find device to add to settings.');
×
502
                return;
×
503
            }
504

505
            const config = vscode.workspace.getConfiguration('brightscript');
×
506
            const inspection = config.inspect<ConfiguredDevice[]>('devices');
×
507
            const workspaceDevices = inspection?.workspaceValue || [];
×
508

509
            if (workspaceDevices.some(d => (device.serialNumber && d.serialNumber === device.serialNumber))) {
×
510
                void vscode.window.showInformationMessage('Device is already in your workspace settings.');
×
511
                return;
×
512
            }
513

514
            const storedPassword = device.serialNumber
×
515
                ? await this.credentialStore.getPassword(device.serialNumber)
516
                : undefined;
517

518
            const newDevice = {
×
519
                host: device.ip,
520
                ...(device.serialNumber && { serialNumber: device.serialNumber }),
×
521
                ...(storedPassword && { password: storedPassword })
×
522
            };
523
            workspaceDevices.push(newDevice);
×
524

525
            await config.update('devices', workspaceDevices, vscode.ConfigurationTarget.Workspace);
×
526
            const displayName = device.deviceInfo['user-device-name'] || device.deviceInfo['default-device-name'] || device.ip;
×
527
            void vscode.window.showInformationMessage(`Added "${displayName}" to workspace settings.`);
×
528
        });
529

530
        this.registerCommand('clearDefaultDevicePassword', async () => {
16✔
531
            await vscode.workspace.getConfiguration('brightscript').update('defaultDevicePassword', undefined, vscode.ConfigurationTarget.Global);
2✔
532
            await util.showTimedNotification('Default device password cleared.');
2✔
533
        });
534

535
        this.registerCommand('setDefaultDevicePassword', async () => {
16✔
536
            const currentValue = vscode.workspace.getConfiguration('brightscript').get<string>('defaultDevicePassword') ?? '';
3!
537

538
            const password = await vscode.window.showInputBox({
3✔
539
                placeHolder: 'Enter the default developer password (applied to devices without their own password)',
540
                password: true,
541
                value: currentValue,
542
                prompt: 'Set default device password'
543
            });
544

545
            if (password === undefined) {
3✔
546
                return;
1✔
547
            }
548

549
            //this value is only supported at the global level, so just always write it there
550
            await vscode.workspace.getConfiguration('brightscript').update('defaultDevicePassword', password, vscode.ConfigurationTarget.Global);
2✔
551
        });
552

553
        this.registerCommand('setDevicePassword', async (serialNumber: string) => {
16✔
554
            if (!serialNumber) {
×
555
                throw new Error('Device serial number is required to set password.');
×
556
            }
557

558
            const device = this.deviceManager.getDevice({ serialNumber: serialNumber });
×
559
            const displayName = device?.deviceInfo?.['user-device-name'] || device?.deviceInfo?.['default-device-name'] || device?.ip || serialNumber;
×
560

561
            const password = await vscode.window.showInputBox({
×
562
                placeHolder: 'Enter the developer account password for this device',
563
                password: true,
564
                prompt: `Set password for device: ${displayName}`,
565
                // Roku's own webserver UI enforces the same 4-character minimum.
566
                validateInput: (value) => {
567
                    return value.length < 4 ? 'Password must be at least 4 characters' : undefined;
×
568
                }
569
            });
570

571
            if (password !== undefined) {
×
572
                await this.setDevicePassword(serialNumber, password);
×
573
                await vscode.window.showInformationMessage(`Password set for device: ${displayName}`);
×
574
            }
575
        });
576

577
        this.registerCommand('clearDevicePassword', async (serialNumber: string) => {
16✔
578
            if (!serialNumber) {
×
579
                throw new Error('Device serial number is required to clear password.');
×
580
            }
581

582
            const device = this.deviceManager.getDevice({ serialNumber: serialNumber });
×
583
            const displayName = device?.deviceInfo?.['user-device-name'] || device?.deviceInfo?.['default-device-name'] || device?.ip || serialNumber;
×
584

585
            await this.setDevicePassword(serialNumber, '');
×
586
            await vscode.window.showInformationMessage(`Password cleared for device: ${displayName}`);
×
587
        });
588

589
        this.registerCommand('clearActiveDevice', async () => {
16✔
590
            await this.deviceManager.clearActiveDevice();
×
591
            await util.showTimedNotification('Active device cleared');
×
592
        });
593

594
        this.registerCommand('showReleaseNotes', () => {
16✔
595
            this.whatsNewManager.showReleaseNotes();
×
596
        });
597
    }
598

599
    public async openFile(filename: string, range: vscode.Range = null, preview = false): Promise<boolean> {
×
600
        let uri = vscode.Uri.file(filename);
×
601
        try {
×
602
            let doc = await vscode.workspace.openTextDocument(uri); // calls back into the provider
×
603
            await vscode.window.showTextDocument(doc, { preview: preview });
×
604
            if (range) {
×
605
                await this.gotoRange(range);
×
606
            }
607
        } catch (e) {
608
            return false;
×
609
        }
610
        return true;
×
611
    }
612

613
    private async gotoRange(range: vscode.Range) {
614
        let editor = vscode.window.activeTextEditor;
×
615
        editor.selection = new vscode.Selection(
×
616
            range.start.line,
617
            range.start.character,
618
            range.start.line,
619
            range.start.character
620
        );
621
        await vscode.commands.executeCommand('revealLine', {
×
622
            lineNumber: range.start.line,
623
            at: 'center'
624
        });
625
    }
626

627
    public async onToggleXml() {
628
        if (vscode.window.activeTextEditor) {
3✔
629
            const currentDocument = vscode.window.activeTextEditor.document;
2✔
630
            let alternateFileName = this.fileUtils.getAlternateFileName(currentDocument.fileName);
2✔
631
            if (alternateFileName) {
2✔
632
                if (
1!
633
                    !await this.openFile(alternateFileName) &&
2✔
634
                    alternateFileName.toLowerCase().endsWith('.brs')
635
                ) {
636
                    await this.openFile(this.fileUtils.getBsFileName(alternateFileName));
×
637
                }
638
            }
639
        }
640
    }
641

642
    public async onGoToParentComponent() {
643
        const editor = vscode.window.activeTextEditor;
4✔
644
        if (!editor) {
4✔
645
            return;
1✔
646
        }
647
        const currentDocument = editor.document;
3✔
648
        const fileName = currentDocument.fileName;
3✔
649
        const lowerFileName = fileName.toLowerCase();
3✔
650
        const isXml = lowerFileName.endsWith('.xml');
3✔
651
        const isBrs = lowerFileName.endsWith('.brs') || lowerFileName.endsWith('.bs');
3✔
652

653
        if (!isXml && !isBrs) {
3✔
654
            return;
1✔
655
        }
656

657
        // Get or open the XML document
658
        let xmlDoc: vscode.TextDocument;
659
        if (isXml) {
2!
660
            xmlDoc = currentDocument;
2✔
661
        } else {
662
            const xmlFileName = this.fileUtils.getAlternateFileName(fileName);
×
663
            if (!xmlFileName) {
×
664
                return;
×
665
            }
666
            try {
×
667
                xmlDoc = await vscode.workspace.openTextDocument(vscode.Uri.file(xmlFileName));
×
668
            } catch (e) {
669
                return;
×
670
            }
671
        }
672

673
        const xmlContent = xmlDoc.getText();
2✔
674
        const parentName = this.fileUtils.getParentComponentName(xmlContent);
2✔
675
        if (!parentName) {
2✔
676
            await vscode.window.showInformationMessage('No parent component found');
1✔
677
            return;
1✔
678
        }
679

680
        const extendsPosition = this.getExtendsValuePosition(xmlContent, xmlDoc);
1✔
681
        if (!extendsPosition) {
1!
682
            return;
×
683
        }
684

685
        // Delegate to the definition provider via the LSP
686
        const locations = await vscode.commands.executeCommand<vscode.Location[]>(
1✔
687
            'vscode.executeDefinitionProvider',
688
            xmlDoc.uri,
689
            extendsPosition
690
        );
691

692
        if (!locations || locations.length === 0) {
1!
693
            await vscode.window.showInformationMessage(`Could not find parent component: ${parentName}`);
×
694
            return;
×
695
        }
696

697
        const parentXmlPath = locations[0].uri.fsPath;
1✔
698

699
        if (isBrs) {
1!
700
            const parentBrsPath = this.fileUtils.getAlternateFileName(parentXmlPath);
×
701
            if (parentBrsPath && !await this.openFile(parentBrsPath)) {
×
702
                await this.openFile(this.fileUtils.getBsFileName(parentBrsPath));
×
703
            }
704
        } else {
705
            await this.openFile(parentXmlPath);
1✔
706
        }
707
    }
708

709
    private getExtendsValuePosition(xmlContent: string, xmlDoc: vscode.TextDocument): vscode.Position | undefined {
710
        // Match extends="VALUE" capturing the VALUE portion; [^>]+ spans across lines since [^>] matches \n
711
        const match = /<component[^>]+extends\s*=\s*["']([^"']+)/i.exec(xmlContent);
1✔
712
        if (!match) {
1!
713
            return undefined;
×
714
        }
715
        // Offset to first character of the value (after the opening quote)
716
        const valueOffset = match.index + match[0].length - match[1].length;
1✔
717
        return xmlDoc.positionAt(valueOffset);
1✔
718
    }
719

720
    public async restartDevApplication() {
721
        await this.getRemoteHost();
3✔
722
        const host = this.host;
3✔
723
        if (!host) {
3!
724
            return;
×
725
        }
726

727
        await util.spinAsync('Restarting dev app', async () => {
3✔
728
            const appsResponse = await util.httpGet(`http://${host}:8060/query/apps`, { timeout: 5_000 });
3✔
729
            const appsParsed = await xml2js.parseStringPromise(appsResponse.body as string);
3✔
730
            const appList: Array<{ $?: { id?: string } }> = appsParsed?.apps?.app ?? [];
3!
731
            const hasDev = appList.some(entry => entry.$?.id === 'dev');
3!
732
            if (!hasDev) {
3✔
733
                await vscode.window.showErrorMessage(`No dev channel sideloaded on ${host}. Sideload your project before restarting.`);
1✔
734
                return;
1✔
735
            }
736

737
            // `/true` forces a full terminate even if the channel is suspended in the background via Instant Resume.
738
            // Harmless if dev isn't running — the device just returns FAILED in the body.
739
            await this.ecpPost(host, 'exit-app/dev/true');
2✔
740

741
            const launchResponse = await this.ecpPost(host, 'launch/dev');
2✔
742
            if (launchResponse.statusCode !== 200) {
2!
743
                await vscode.window.showErrorMessage(`Failed to launch dev channel on ${host} (HTTP ${launchResponse.statusCode}).`);
×
744
                return;
×
745
            }
746

747
            // give a little bit of time to let the app boot up before checking its status
748
            await util.sleep(1000);
2✔
749
            const verifyResponse = await util.httpGet(`http://${host}:8060/query/active-app`, { timeout: 5_000 });
2✔
750
            const verifyParsed = await xml2js.parseStringPromise(verifyResponse.body as string);
2✔
751
            const verifyAppId: string | undefined = verifyParsed?.['active-app']?.app?.[0]?.$?.id;
2!
752
            if (verifyAppId === 'dev') {
2✔
753
                void util.showTimedNotification('Dev app restarted', 2000);
1✔
754
            } else {
755
                await vscode.window.showWarningMessage(`Sent the dev launch command, but the foreground app is "${verifyAppId ?? 'unknown'}". The dev app may still be loading.`);
1!
756
            }
757
        });
758
    }
759

760
    private ecpPost(host: string, path: string) {
761
        return new Promise<request.Response>((resolve, reject) => {
×
762
            request.post(`http://${host}:8060/${path}`, (err: Error | null, response: request.Response) => {
×
763
                return err ? reject(err) : resolve(response);
×
764
            });
765
        });
766
    }
767

768
    /**
769
     * Restart a Roku device. When `host` is omitted (e.g. invoked from the command palette)
770
     * a device picker is shown. Resolves and validates the developer password the same way a
771
     * debug launch does before issuing the reboot.
772
     */
773
    public async restartDevice(host?: string): Promise<void> {
774
        const target = await this.resolveDeviceHost(host);
8✔
775
        if (!target) {
8✔
776
            return;
1✔
777
        }
778

779
        const confirm = await vscode.window.showWarningMessage(
7✔
780
            `Restart Device?`,
781
            {
782
                detail: `Any running apps or processes will be terminated.\n\n${target.label}`,
783
                modal: true
784
            },
785
            'Restart'
786
        );
787
        if (confirm !== 'Restart') {
7✔
788
            return;
1✔
789
        }
790

791
        const password = await this.resolveValidatedPassword(target.host, target.serialNumber);
6✔
792
        if (password === undefined) {
6✔
793
            return;
2✔
794
        }
795

796
        try {
4✔
797
            await vscode.window.withProgress({
4✔
798
                location: vscode.ProgressLocation.Notification,
799
                title: `Requesting restarting ${target.label}`
800
            }, () => rokuDeploy.rebootDevice({ host: target.host, password: password, timeout: 10000 }));
4✔
801
        } catch (e) {
802
            void vscode.window.showErrorMessage(`Failed to restart device: ${e.message}`);
1✔
803
        }
804
    }
805

806
    /**
807
     * Ask a Roku device to check for and install any available software updates. Host and
808
     * password are resolved the same way as `restartDevice`.
809
     */
810
    public async checkForUpdates(host?: string): Promise<void> {
811
        const target = await this.resolveDeviceHost(host);
2✔
812
        if (!target) {
2!
813
            return;
×
814
        }
815

816
        const confirm = await vscode.window.showInformationMessage(
2✔
817
            `Check for Updates?`,
818
            {
819
                detail: `Device will check for app and Roku OS updates.\n\nAny running apps or processes will be terminated.\n\n${target.label}`,
820
                modal: true
821
            },
822
            `Check for Updates`
823
        );
824
        if (confirm !== 'Check for Updates') {
2✔
825
            return;
1✔
826
        }
827

828
        const password = await this.resolveValidatedPassword(target.host, target.serialNumber);
1✔
829
        if (password === undefined) {
1!
830
            return;
×
831
        }
832

833
        try {
1✔
834
            await vscode.window.withProgress({
1✔
835
                location: vscode.ProgressLocation.Notification,
836
                title: `Checking for updates: ${target.label}`
837
            }, () => rokuDeploy.checkForUpdate({ host: target.host, password: password, timeout: 10000 }));
1✔
838
        } catch (e) {
839
            void vscode.window.showErrorMessage(`Failed to check for updates: ${e.message}`);
×
840
        }
841
    }
842

843
    /**
844
     * Resolve the device a device-targeted command should act on.
845
     *
846
     * When `host` is provided (e.g. from a Devices view tree item) it is used directly.
847
     * Otherwise the device picker is always shown; these are device-specific actions, so we
848
     * never silently fall back to the active device. The resolved host is probed so the caller
849
     * has a fresh serial number for password lookup and a friendly display label for prompts.
850
     *
851
     * Returns undefined when the user cancels device selection.
852
     */
853
    private async resolveDeviceHost(host?: string): Promise<{ host: string; serialNumber: string | undefined; label: string } | undefined> {
854
        if (!host) {
10✔
855
            try {
2✔
856
                host = (await this.userInputManager.promptForHost())?.host;
2!
857
            } catch {
858
                // promptForHost rejects when the user dismisses the picker; treat as a cancel.
859
                return undefined;
1✔
860
            }
861
        }
862
        if (!host) {
9!
863
            return undefined;
×
864
        }
865

866
        const device = await this.deviceManager.validateAndAddDevice(host);
9✔
867
        const label = device ? this.deviceManager.getDeviceDisplayName(device, true) : host;
9!
868
        return { host: host, serialNumber: device?.serialNumber, label: label };
9!
869
    }
870

871
    /**
872
     * Resolve a developer password the device accepts, delegating the candidate/validate/prompt/
873
     * persist flow to the shared resolver. The global `remotePassword` fallback is offered as an
874
     * extra candidate. Shows an error and returns undefined when the device is unreachable, and
875
     * returns undefined when the user cancels the prompt.
876
     */
877
    private async resolveValidatedPassword(host: string, serialNumber: string | undefined): Promise<string | undefined> {
878
        const resolution = await this.userInputManager.resolveDevicePassword({
7✔
879
            host: host,
880
            serialNumber: serialNumber,
881
            extraCandidates: [await this.context.workspaceState.get('remotePassword')]
882
        });
883
        if (resolution.status === 'unreachable') {
7✔
884
            void vscode.window.showErrorMessage(`Device at ${host} is unreachable.`);
1✔
885
            return undefined;
1✔
886
        }
887
        if (resolution.status === 'cancelled') {
6✔
888
            return undefined;
1✔
889
        }
890
        return resolution.password;
5✔
891
    }
892

893
    public async sendRemoteCommand(key: string, host?: string, literalCharacter = false) {
×
894
        for (const notifier of this.keypressNotifiers) {
×
895
            notifier(key, literalCharacter);
×
896
        }
897

898
        if (literalCharacter) {
×
899
            key = 'Lit_' + encodeURIComponent(key);
×
900
        }
901

902
        // do we have a temporary override?
903
        if (!host) {
×
904
            // Get the long lived host ip
905
            await this.getRemoteHost();
×
906
            host = this.host;
×
907
        }
908

909
        if (host) {
×
910
            let clickUrl = `http://${host}:8060/keypress/${key}`;
×
911
            console.log(`send ${clickUrl}`);
×
912
            return new Promise((resolve, reject) => {
×
913
                request.post(clickUrl, (err, response) => {
×
914
                    if (err) {
×
915
                        return reject(err);
×
916
                    }
917
                    return resolve(response);
×
918
                });
919
            });
920
        }
921
    }
922

923
    public async getRemoteHost(showPrompt = true) {
×
924
        this.host = await this.context.workspaceState.get('remoteHost');
×
925
        if (!this.host) {
×
926
            let config = util.getConfiguration('brightscript.remoteControl');
×
927
            this.host = config.get('host');
×
928
            // eslint-disable-next-line no-template-curly-in-string
929
            if ((!this.host || this.host === '${promptForHost}') && showPrompt) {
×
930
                this.host = (await this.userInputManager.promptForHost())?.host;
×
931
            }
932
        }
933
        if (!this.host) {
×
934
            throw new Error('Can\'t send command: host is required.');
×
935
        } else {
936
            await this.context.workspaceState.update('remoteHost', this.host);
×
937
        }
938
        if (this.host) {
×
939
            //try resolving the hostname. (sometimes it fails for no reason, so just ignore the crash if it does)
940
            try {
×
941
                this.host = await rokuDebugUtil.dnsLookup(this.host);
×
942
            } catch (e) {
943
                console.error('Error doing dns lookup for host ', this.host, e);
×
944
            }
945
        }
946
        return this.host;
×
947
    }
948

949
    public async getRemotePassword(showPrompt = true) {
×
950
        this.password = await this.context.workspaceState.get('remotePassword');
×
951
        if (!this.password) {
×
952
            let config = util.getConfiguration('brightscript.remoteControl');
×
953
            this.password = config.get('password');
×
954
            // eslint-disable-next-line no-template-curly-in-string
955
            if ((!this.password || this.password === '${promptForPassword}') && showPrompt) {
×
956
                this.password = await vscode.window.showInputBox({
×
957
                    placeHolder: 'The developer account password for your Roku device',
958
                    value: ''
959
                });
960
            }
961
        }
962
        if (!this.password) {
×
963
            throw new Error(`Can't send command: password is required.`);
×
964
        } else {
965
            await this.context.workspaceState.update('remotePassword', this.password);
×
966
        }
967
        return this.password;
×
968
    }
969

970
    public async getWorkspacePath() {
971
        this.workspacePath = await this.context.workspaceState.get('workspacePath');
×
972
        //let folderUri: vscode.Uri;
973
        if (!this.workspacePath) {
×
974
            if (vscode.workspace.workspaceFolders?.length === 1) {
×
975
                this.workspacePath = vscode.workspace.workspaceFolders?.[0].uri.fsPath;
×
976
            } else {
977
                //there are multiple workspaces, ask the user to specify which one they want to use
978
                let workspaceFolder = await vscode.window.showWorkspaceFolderPick();
×
979
                if (workspaceFolder) {
×
980
                    this.workspacePath = workspaceFolder.uri.fsPath;
×
981
                }
982
            }
983
        }
984
        return this.workspacePath;
×
985
    }
986

987
    /**
988
     * Store a password for a specific device, keyed by serial number.
989
     * An empty password clears the stored entry.
990
     *
991
     * Writes the password to every `brightscript.devices[]` settings entry that
992
     * matches the SN (user/workspace/workspace-folder scopes) and also keeps the
993
     * cred store updated. The cred store acts as a running cache of passwords —
994
     * kept fresh alongside settings here, and refreshed on each successful
995
     * password validation elsewhere.
996
     */
997
    public async setDevicePassword(serialNumber: string, password: string) {
998
        await this.writeDevicePasswordToSettings(serialNumber, password);
×
999
        if (password) {
×
1000
            await this.credentialStore.setPassword(serialNumber, password);
×
1001
        } else {
1002
            await this.credentialStore.clearPassword(serialNumber);
×
1003
        }
1004
    }
1005

1006
    /**
1007
     * Update/clear the `password` field on any `brightscript.devices[]` entries
1008
     * whose `serialNumber` matches. Writes to every writable scope that contains
1009
     * a matching entry — user (Global), workspace, and each workspace folder.
1010
     * The default (package.json) scope is read-only and is never written.
1011
     * Empty password removes the field rather than writing an empty string.
1012
     * Returns true when at least one scope contained a matching entry.
1013
     */
1014
    private async writeDevicePasswordToSettings(serialNumber: string, password: string): Promise<boolean> {
1015
        if (!serialNumber) {
×
1016
            return false;
×
1017
        }
1018

1019
        const scopeHasMatch = (devices: ConfiguredDevice[] | undefined): boolean => !!devices?.some(entry => entry.serialNumber === serialNumber);
×
1020

1021
        const rewriteEntries = (devices: ConfiguredDevice[]): ConfiguredDevice[] => devices.map(entry => {
×
1022
            if (entry.serialNumber !== serialNumber) {
×
1023
                return entry;
×
1024
            }
1025
            if (password) {
×
1026
                return { ...entry, password: password };
×
1027
            }
1028
            const { password: _existingPassword, ...entryWithoutPassword } = entry;
×
1029
            return entryWithoutPassword;
×
1030
        });
1031

1032
        let found = false;
×
1033

1034
        // User (Global) + workspace scopes — resource-agnostic
1035
        const rootConfig = vscode.workspace.getConfiguration('brightscript');
×
1036
        const rootInspection = rootConfig.inspect<ConfiguredDevice[]>('devices');
×
1037

1038
        if (scopeHasMatch(rootInspection?.globalValue)) {
×
1039
            found = true;
×
1040
            await rootConfig.update('devices', rewriteEntries(rootInspection.globalValue), vscode.ConfigurationTarget.Global);
×
1041
        }
1042
        if (scopeHasMatch(rootInspection?.workspaceValue)) {
×
1043
            found = true;
×
1044
            await rootConfig.update('devices', rewriteEntries(rootInspection.workspaceValue), vscode.ConfigurationTarget.Workspace);
×
1045
        }
1046

1047
        // Workspace-folder scope — one setting per folder in multi-root workspaces
1048
        const workspaceFolders = vscode.workspace.workspaceFolders ?? [];
×
1049
        for (const folder of workspaceFolders) {
×
1050
            const folderConfig = vscode.workspace.getConfiguration('brightscript', folder.uri);
×
1051
            const folderInspection = folderConfig.inspect<ConfiguredDevice[]>('devices');
×
1052
            if (scopeHasMatch(folderInspection?.workspaceFolderValue)) {
×
1053
                found = true;
×
1054
                await folderConfig.update('devices', rewriteEntries(folderInspection.workspaceFolderValue), vscode.ConfigurationTarget.WorkspaceFolder);
×
1055
            }
1056
        }
1057

1058
        return found;
×
1059
    }
1060

1061
    /**
1062
     * Get the stored password for a specific device by serial number.
1063
     */
1064
    public async getDevicePassword(serialNumber: string | undefined): Promise<string | undefined> {
1065
        return this.credentialStore.getPassword(serialNumber);
×
1066
    }
1067

1068
    /**
1069
     * Get the password for the currently active device.
1070
     * Resolves the active host's IP to a serial number via DeviceManager,
1071
     * then reads from the SN-keyed credential store. Falls back to the
1072
     * workspace-global password when no per-device entry exists.
1073
     */
1074
    public async getActiveHostPassword(): Promise<string | undefined> {
1075
        const activeHost = this.context.workspaceState.get<string>('remoteHost');
×
1076
        if (activeHost && typeof activeHost === 'string') {
×
1077
            const serialNumber = this.deviceManager.getDevice({ ip: activeHost })?.serialNumber;
×
1078
            const devicePassword = await this.credentialStore.getPassword(serialNumber);
×
1079
            if (devicePassword) {
×
1080
                return devicePassword;
×
1081
            }
1082
        }
1083
        return this.getRemotePassword(false);
×
1084
    }
1085

1086
    /**
1087
     * Return the active host (paired with its raw device-info) if one is set and passes a health
1088
     * check; otherwise undefined. The health check refreshes the device in the device manager, so
1089
     * the device-info is read back from there without an extra request.
1090
     */
1091
    public async getHealthyActiveHost(): Promise<HostWithDeviceInfo | undefined> {
1092
        const activeHost = vscodeContextManager.get<string>('activeHost');
4✔
1093
        if (!activeHost) {
4✔
1094
            return undefined;
1✔
1095
        }
1096
        const isHealthy = await this.deviceManager.healthCheckDevice({ ip: activeHost }, true, false);
3✔
1097
        if (!isHealthy) {
3✔
1098
            return undefined;
1✔
1099
        }
1100
        const deviceInfo = this.deviceManager.getDevice({ ip: activeHost })?.deviceInfo;
2✔
1101
        //deviceInfo is required on HostWithDeviceInfo, so if we couldn't read it back, report no healthy active host
1102
        if (!deviceInfo) {
2✔
1103
            return undefined;
1✔
1104
        }
1105
        return { host: activeHost, deviceInfo: deviceInfo };
1✔
1106
    }
1107

1108
    /**
1109
     * Open the settings JSON file and position cursor at the specified device entry
1110
     */
1111
    private async openSettingsJsonAtDevice(device: RokuDevice | undefined, scope: 'user' | 'workspace'): Promise<void> {
1112
        // Open the appropriate settings JSON file
1113
        const command = scope === 'user'
×
1114
            ? 'workbench.action.openSettingsJson'
1115
            : 'workbench.action.openWorkspaceSettingsFile';
1116
        await vscode.commands.executeCommand(command);
×
1117

1118
        // Get the active editor (should be the settings file we just opened)
1119
        const editor = vscode.window.activeTextEditor;
×
1120
        if (!editor || !device) {
×
1121
            return;
×
1122
        }
1123

1124
        const text = editor.document.getText();
×
1125

1126
        // Search for the device by IP or serial number
1127
        const searchTerms = [device.ip];
×
1128
        if (device.serialNumber) {
×
1129
            searchTerms.push(device.serialNumber);
×
1130
        }
1131

1132
        let matchIndex = -1;
×
1133
        for (const term of searchTerms) {
×
1134
            const index = text.indexOf(`"${term}"`);
×
1135
            if (index !== -1) {
×
1136
                matchIndex = index;
×
1137
                break;
×
1138
            }
1139
        }
1140

1141
        if (matchIndex !== -1) {
×
1142
            const position = editor.document.positionAt(matchIndex + 1); // +1 to skip opening quote
×
1143
            const selection = new vscode.Selection(position, position);
×
1144
            editor.selection = selection;
×
1145
            editor.revealRange(new vscode.Range(position, position), vscode.TextEditorRevealType.InCenter);
×
1146
        }
1147
    }
1148

1149
    public registerKeypressNotifier(notifier: (key: string, literalCharacter: boolean) => void) {
1150
        this.keypressNotifiers.push(notifier);
14✔
1151
    }
1152

1153
    private registerCommand(name: string, callback: (...args: any[]) => any, thisArg?: any) {
1154
        const prefix = 'extension.brightscript.';
3,046✔
1155
        const commandName = name.startsWith(prefix) ? name : prefix + name;
3,046✔
1156
        this.context.subscriptions.push(vscode.commands.registerCommand(commandName, callback, thisArg));
3,046✔
1157
    }
1158

1159
    /**
1160
     * Register the per-facet toggle commands plus the reset command backing the Devices
1161
     * view filter submenu. Each facet has two command variants (unchecked + ".active");
1162
     * the submenu picks which to render via a `when` clause on the per-facet context key.
1163
     * Both call the same toggle handler.
1164
     */
1165
    public registerDevicesViewCommands(devicesViewProvider: DevicesViewProvider) {
1166
        for (const key of DEVICE_FILTER_KEYS) {
14✔
1167
            const handler = () => devicesViewProvider.toggleFilter(key);
126✔
1168
            this.registerCommand(`devicesView.toggleFilter.${key}`, handler);
126✔
1169
            this.registerCommand(`devicesView.toggleFilter.${key}.active`, handler);
126✔
1170
        }
1171
        this.registerCommand('devicesView.resetFilters', () => devicesViewProvider.resetFilters());
14✔
1172
        // These also appear in the command palette, where there's no tree element; resolving
1173
        // a missing/unknown key to undefined lets `restartDevice`/`checkForUpdates` fall back
1174
        // to the active device or device picker.
1175
        this.registerCommand('devicesView.restartDevice', (element?: { key?: string }) => {
14✔
1176
            return this.restartDevice(element?.key ? this.deviceManager.getDevice(element.key)?.ip : undefined);
2!
1177
        });
1178
        this.registerCommand('devicesView.checkAndInstallUpdates', (element?: { key?: string }) => {
14✔
1179
            return this.checkForUpdates(element?.key ? this.deviceManager.getDevice(element.key)?.ip : undefined);
1!
1180
        });
1181

1182
        this.registerDeviceContextMenuCommands();
14✔
1183
    }
1184

1185
    /**
1186
     * Register the commands behind the right-click context menu on a device in the Devices view.
1187
     * Each receives the clicked tree element and resolves it into the argument shape its
1188
     * underlying command expects. These are hidden from the command palette (they only make
1189
     * sense with a tree element), which also lets their titles carry the emoji icons shown
1190
     * in the context menu.
1191
     */
1192
    private registerDeviceContextMenuCommands() {
1193
        const getDevice = (element?: { key?: string }) => {
14✔
1194
            return element?.key ? this.deviceManager.getDevice(element.key) : undefined;
×
1195
        };
1196

1197
        this.registerCommand('devicesView.deviceMenu.setActiveDevice', (element?: { key?: string }) => {
14✔
1198
            return vscode.commands.executeCommand('extension.brightscript.setActiveDevice', element);
×
1199
        });
1200
        this.registerCommand('devicesView.deviceMenu.clearActiveDevice', () => {
14✔
NEW
1201
            return vscode.commands.executeCommand('extension.brightscript.clearActiveDevice');
×
1202
        });
1203
        this.registerCommand('devicesView.deviceMenu.captureScreenshot', (element?: { key?: string }) => {
14✔
1204
            return vscode.commands.executeCommand('extension.brightscript.captureScreenshot', getDevice(element)?.ip);
×
1205
        });
1206
        this.registerCommand('devicesView.deviceMenu.switchTvInput', (element?: { key?: string }) => {
14✔
1207
            return vscode.commands.executeCommand('extension.brightscript.changeTvInput', getDevice(element)?.ip);
×
1208
        });
1209
        this.registerCommand('devicesView.deviceMenu.refreshDevice', (element?: { key?: string }) => {
14✔
1210
            return vscode.commands.executeCommand('extension.brightscript.refreshDevice', element);
×
1211
        });
1212
        this.registerCommand('devicesView.deviceMenu.restartDevice', (element?: { key?: string }) => {
14✔
1213
            return this.restartDevice(getDevice(element)?.ip);
×
1214
        });
1215
        this.registerCommand('devicesView.deviceMenu.checkAndInstallUpdates', (element?: { key?: string }) => {
14✔
1216
            return this.checkForUpdates(getDevice(element)?.ip);
×
1217
        });
1218
        this.registerCommand('devicesView.deviceMenu.openWebPortal', (element?: { key?: string }) => {
14✔
1219
            const ip = getDevice(element)?.ip;
×
1220
            if (!ip) {
×
1221
                return vscode.window.showErrorMessage('Could not determine the IP address for this device');
×
1222
            }
1223
            return vscode.commands.executeCommand('extension.brightscript.openUrl', `http://${ip}`);
×
1224
        });
1225
        this.registerCommand('devicesView.deviceMenu.viewRegistry', (element?: { key?: string }) => {
14✔
1226
            return vscode.commands.executeCommand('extension.brightscript.openRegistryInBrowser', getDevice(element)?.ip);
×
1227
        });
1228
        // Set and Change share a handler; the menu shows one or the other based on whether a password is stored
1229
        for (const commandName of ['devicesView.deviceMenu.setDevicePassword', 'devicesView.deviceMenu.changeDevicePassword']) {
14✔
1230
            this.registerCommand(commandName, (element?: { key?: string }) => {
28✔
1231
                return vscode.commands.executeCommand('extension.brightscript.setDevicePassword', getDevice(element)?.serialNumber);
×
1232
            });
1233
        }
1234
        this.registerCommand('devicesView.deviceMenu.clearDevicePassword', (element?: { key?: string }) => {
14✔
1235
            return vscode.commands.executeCommand('extension.brightscript.clearDevicePassword', getDevice(element)?.serialNumber);
×
1236
        });
1237
        this.registerCommand('devicesView.deviceMenu.addToUserSettings', (element?: { key?: string }) => {
14✔
1238
            return vscode.commands.executeCommand('extension.brightscript.addDeviceToUserSettings', element);
×
1239
        });
1240
        this.registerCommand('devicesView.deviceMenu.editInUserSettings', (element?: { key?: string }) => {
14✔
1241
            return vscode.commands.executeCommand('extension.brightscript.editDeviceInUserSettings', element);
×
1242
        });
1243
        this.registerCommand('devicesView.deviceMenu.addToWorkspaceSettings', (element?: { key?: string }) => {
14✔
1244
            return vscode.commands.executeCommand('extension.brightscript.addDeviceToWorkspaceSettings', element);
×
1245
        });
1246
        this.registerCommand('devicesView.deviceMenu.editInWorkspaceSettings', (element?: { key?: string }) => {
14✔
1247
            return vscode.commands.executeCommand('extension.brightscript.editDeviceInWorkspaceSettings', element);
×
1248
        });
1249
    }
1250

1251
    private async sendAsciiToDevice(character: string) {
1252
        await this.sendRemoteCommand(character, undefined, true);
×
1253
    }
1254
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc