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

rokucommunity / vscode-brightscript-language / 30100866380

24 Jul 2026 02:24PM UTC coverage: 60.103% (+0.2%) from 59.908%
30100866380

Pull #802

github

web-flow
Merge b867dd73f into e465804e3
Pull Request #802: Route extension logs through the BrightScript Extension output channel

2593 of 4745 branches covered (54.65%)

Branch coverage included in aggregate %.

64 of 102 new or added lines in 20 files covered. (62.75%)

4073 of 6346 relevant lines covered (64.18%)

43.71 hits per line

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

34.47
/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
import { createLogger } from './logging';
1✔
26

27
const logger = createLogger('BrightScriptCommands');
1✔
28

29
export class BrightScriptCommands {
1✔
30

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

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

49
    public registerCommands() {
50

51
        brighterScriptPreviewCommand.register(this.context);
16✔
52
        languageServerInfoCommand.register(this.context, this.localPackageManager);
16✔
53
        captureScreenshotCommand.register(this.context, this);
16✔
54
        rekeyAndPackageCommand.register(this.context, this, this.userInputManager);
16✔
55
        clearNpmPackageCacheCommand.register(this.context, this.localPackageManager);
16✔
56
        profilingCommands.register(this.context);
16✔
57

58
        this.registerGeneralCommands();
16✔
59

60
        this.registerCommand('sendRemoteCommand', async (key: string) => {
16✔
61
            await this.sendRemoteCommand(key);
×
62
        });
63

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

69
        this.registerCommand('rescanDevices', () => {
16✔
70
            this.deviceManager.refresh(true);
×
71
        });
72

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

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

84
            const stuffUserTyped = await util.showQuickPickInputBox({
×
85
                placeholder: 'Press enter to send all typed characters to the Roku',
86
                items: items
87
            });
NEW
88
            logger.log('userInput', stuffUserTyped);
×
89

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

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

115
        this.registerCommand('toggleRemoteControlMode', (initiator: RemoteControlModeInitiator) => {
16✔
116
            return this.remoteControlManager.toggleRemoteControlMode(initiator);
×
117
        });
118

119
        this.registerCommand('enableRemoteControlMode', () => {
16✔
120
            return this.remoteControlManager.setRemoteControlMode(true, 'command');
×
121
        });
122

123
        this.registerCommand('disableRemoteControlMode', () => {
16✔
124
            return this.remoteControlManager.setRemoteControlMode(false, 'command');
×
125
        });
126

127
        this.registerCommand('pressBackButton', async () => {
16✔
128
            await this.sendRemoteCommand('Back');
×
129
        });
130

131
        this.registerCommand('pressBackspaceButton', async () => {
16✔
132
            await this.sendRemoteCommand('Backspace');
×
133
        });
134

135
        this.registerCommand('pressHomeButton', async () => {
16✔
136
            await this.sendRemoteCommand('Home');
×
137
        });
138

139
        this.registerCommand('restartDevApplication', async () => {
16✔
140
            await this.restartDevApplication();
×
141
        });
142

143
        this.registerCommand('pressUpButton', async () => {
16✔
144
            await this.sendRemoteCommand('Up');
×
145
        });
146

147
        this.registerCommand('pressDownButton', async () => {
16✔
148
            await this.sendRemoteCommand('Down');
×
149
        });
150

151
        this.registerCommand('pressRightButton', async () => {
16✔
152
            await this.sendRemoteCommand('Right');
×
153
        });
154

155
        this.registerCommand('pressLeftButton', async () => {
16✔
156
            await this.sendRemoteCommand('Left');
×
157
        });
158

159
        this.registerCommand('pressSelectButton', async () => {
16✔
160
            await this.sendRemoteCommand('Select');
×
161
        });
162

163
        this.registerCommand('pressPlayButton', async () => {
16✔
164
            await this.sendRemoteCommand('Play');
×
165
        });
166

167
        this.registerCommand('pressRevButton', async () => {
16✔
168
            await this.sendRemoteCommand('Rev');
×
169
        });
170

171
        this.registerCommand('pressFwdButton', async () => {
16✔
172
            await this.sendRemoteCommand('Fwd');
×
173
        });
174

175
        this.registerCommand('pressStarButton', async () => {
16✔
176
            await this.sendRemoteCommand('Info');
×
177
        });
178

179
        this.registerCommand('pressInstantReplayButton', async () => {
16✔
180
            await this.sendRemoteCommand('InstantReplay');
×
181
        });
182

183
        this.registerCommand('pressSearchButton', async () => {
16✔
184
            await this.sendRemoteCommand('Search');
×
185
        });
186

187
        this.registerCommand('pressEnterButton', async () => {
16✔
188
            await this.sendRemoteCommand('Enter');
×
189
        });
190

191
        this.registerCommand('pressFindRemote', async () => {
16✔
192
            await this.sendRemoteCommand('FindRemote');
×
193
        });
194

195
        this.registerCommand('pressVolumeDown', async () => {
16✔
196
            await this.sendRemoteCommand('VolumeDown');
×
197
        });
198

199
        this.registerCommand('pressVolumeMute', async () => {
16✔
200
            await this.sendRemoteCommand('VolumeMute');
×
201
        });
202

203
        this.registerCommand('pressVolumeUp', async () => {
16✔
204
            await this.sendRemoteCommand('VolumeUp');
×
205
        });
206

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

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

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

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

247
        this.registerCommand('pressPowerOff', async () => {
16✔
248
            await this.sendRemoteCommand('PowerOff');
×
249
        });
250

251
        this.registerCommand('pressPowerOn', async () => {
16✔
252
            await this.sendRemoteCommand('PowerOn');
×
253
        });
254

255
        this.registerCommand('pressChannelUp', async () => {
16✔
256
            await this.sendRemoteCommand('ChannelUp');
×
257
        });
258

259
        this.registerCommand('pressChannelDown', async () => {
16✔
260
            await this.sendRemoteCommand('ChannelDown');
×
261
        });
262

263
        this.registerCommand('pressBlue', async () => {
16✔
264
            await this.sendRemoteCommand('Blue');
×
265
        });
266

267
        this.registerCommand('pressGreen', async () => {
16✔
268
            await this.sendRemoteCommand('Green');
×
269
        });
270

271
        this.registerCommand('pressRed', async () => {
16✔
272
            await this.sendRemoteCommand('Red');
×
273
        });
274

275
        this.registerCommand('pressYellow', async () => {
16✔
276
            await this.sendRemoteCommand('Yellow');
×
277
        });
278

279
        this.registerCommand('pressExit', async () => {
16✔
280
            await this.sendRemoteCommand('Exit');
×
281
        });
282

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

293
            if (selectedInput) {
×
294
                await this.sendRemoteCommand(selectedInput, host);
×
295
            }
296
        });
297

298
        this.registerKeyboardInputs();
16✔
299
    }
300

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

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

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

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

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

334
        this.registerCommand('toggleXML', async () => {
16✔
335
            await this.onToggleXml();
×
336
        });
337

338
        this.registerCommand('goToParentComponent', async () => {
16✔
339
            await this.onGoToParentComponent();
×
340
        });
341

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

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

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

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

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

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

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

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

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

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

400
            const parsed = await xml2js.parseStringPromise(responseText);
×
401

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

517
            const storedPassword = device.serialNumber
×
518
                ? await this.credentialStore.getPassword(device.serialNumber)
519
                : undefined;
520

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

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

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

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

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

548
            if (password === undefined) {
3✔
549
                return;
1✔
550
            }
551

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

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

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

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

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

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

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

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

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

597
        this.registerCommand('showReleaseNotes', () => {
16✔
598
            this.whatsNewManager.showReleaseNotes();
×
599
        });
600
    }
601

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

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

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

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

656
        if (!isXml && !isBrs) {
3✔
657
            return;
1✔
658
        }
659

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

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

683
        const extendsPosition = this.getExtendsValuePosition(xmlContent, xmlDoc);
1✔
684
        if (!extendsPosition) {
1!
685
            return;
×
686
        }
687

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

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

700
        const parentXmlPath = locations[0].uri.fsPath;
1✔
701

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

901
        if (literalCharacter) {
×
902
            key = 'Lit_' + encodeURIComponent(key);
×
903
        }
904

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

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

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

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

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

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

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

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

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

1035
        let found = false;
×
1036

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

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

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

1061
        return found;
×
1062
    }
1063

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

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

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

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

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

1127
        const text = editor.document.getText();
×
1128

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

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

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

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

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

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

1185
        this.registerDeviceContextMenuCommands();
14✔
1186
    }
1187

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

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

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

© 2026 Coveralls, Inc