Welcome to mirror list, hosted at ThFree Co, Russian Federation.

debugCommands.ts « browser « debug « contrib « workbench « vs « src - github.com/microsoft/vscode.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 4a022554117847d4ce48beea5be9d67ecbac4d68 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

import * as nls from 'vs/nls';
import { KeyCode, KeyMod } from 'vs/base/common/keyCodes';
import { List } from 'vs/base/browser/ui/list/listWidget';
import { KeybindingsRegistry, KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry';
import { IListService } from 'vs/platform/list/browser/listService';
import { IDebugService, IEnablement, CONTEXT_BREAKPOINTS_FOCUSED, CONTEXT_WATCH_EXPRESSIONS_FOCUSED, CONTEXT_VARIABLES_FOCUSED, EDITOR_CONTRIBUTION_ID, IDebugEditorContribution, CONTEXT_IN_DEBUG_MODE, CONTEXT_EXPRESSION_SELECTED, IConfig, IStackFrame, IThread, IDebugSession, CONTEXT_DEBUG_STATE, IDebugConfiguration, CONTEXT_JUMP_TO_CURSOR_SUPPORTED, REPL_VIEW_ID, CONTEXT_DEBUGGERS_AVAILABLE, State, getStateLabel, CONTEXT_BREAKPOINT_INPUT_FOCUSED, CONTEXT_FOCUSED_SESSION_IS_ATTACH, VIEWLET_ID, CONTEXT_DISASSEMBLY_VIEW_FOCUS } from 'vs/workbench/contrib/debug/common/debug';
import { Expression, Variable, Breakpoint, FunctionBreakpoint, DataBreakpoint } from 'vs/workbench/contrib/debug/common/debugModel';
import { IExtensionsViewPaneContainer, VIEWLET_ID as EXTENSIONS_VIEWLET_ID } from 'vs/workbench/contrib/extensions/common/extensions';
import { ICodeEditor, isCodeEditor } from 'vs/editor/browser/editorBrowser';
import { MenuRegistry, MenuId } from 'vs/platform/actions/common/actions';
import { IEditorService } from 'vs/workbench/services/editor/common/editorService';
import { EditorContextKeys } from 'vs/editor/common/editorContextKeys';
import { ContextKeyExpr, IContextKeyService } from 'vs/platform/contextkey/common/contextkey';
import { openBreakpointSource } from 'vs/workbench/contrib/debug/browser/breakpointsView';
import { INotificationService } from 'vs/platform/notification/common/notification';
import { InputFocusedContext } from 'vs/platform/contextkey/common/contextkeys';
import { ServicesAccessor } from 'vs/editor/browser/editorExtensions';
import { PanelFocusContext } from 'vs/workbench/common/contextkeys';
import { CommandsRegistry, ICommandService } from 'vs/platform/commands/common/commands';
import { ITextResourcePropertiesService } from 'vs/editor/common/services/textResourceConfiguration';
import { IClipboardService } from 'vs/platform/clipboard/common/clipboardService';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IQuickInputService } from 'vs/platform/quickinput/common/quickInput';
import { IViewsService, ViewContainerLocation } from 'vs/workbench/common/views';
import { deepClone } from 'vs/base/common/objects';
import { isWeb, isWindows } from 'vs/base/common/platform';
import { saveAllBeforeDebugStart } from 'vs/workbench/contrib/debug/common/debugUtils';
import { IPaneCompositePartService } from 'vs/workbench/services/panecomposite/browser/panecomposite';

export const ADD_CONFIGURATION_ID = 'debug.addConfiguration';
export const TOGGLE_INLINE_BREAKPOINT_ID = 'editor.debug.action.toggleInlineBreakpoint';
export const COPY_STACK_TRACE_ID = 'debug.copyStackTrace';
export const REVERSE_CONTINUE_ID = 'workbench.action.debug.reverseContinue';
export const STEP_BACK_ID = 'workbench.action.debug.stepBack';
export const RESTART_SESSION_ID = 'workbench.action.debug.restart';
export const TERMINATE_THREAD_ID = 'workbench.action.debug.terminateThread';
export const STEP_OVER_ID = 'workbench.action.debug.stepOver';
export const STEP_INTO_ID = 'workbench.action.debug.stepInto';
export const STEP_OUT_ID = 'workbench.action.debug.stepOut';
export const PAUSE_ID = 'workbench.action.debug.pause';
export const DISCONNECT_ID = 'workbench.action.debug.disconnect';
export const STOP_ID = 'workbench.action.debug.stop';
export const RESTART_FRAME_ID = 'workbench.action.debug.restartFrame';
export const CONTINUE_ID = 'workbench.action.debug.continue';
export const FOCUS_REPL_ID = 'workbench.debug.action.focusRepl';
export const JUMP_TO_CURSOR_ID = 'debug.jumpToCursor';
export const FOCUS_SESSION_ID = 'workbench.action.debug.focusProcess';
export const SELECT_AND_START_ID = 'workbench.action.debug.selectandstart';
export const DEBUG_CONFIGURE_COMMAND_ID = 'workbench.action.debug.configure';
export const DEBUG_START_COMMAND_ID = 'workbench.action.debug.start';
export const DEBUG_RUN_COMMAND_ID = 'workbench.action.debug.run';
export const EDIT_EXPRESSION_COMMAND_ID = 'debug.renameWatchExpression';
export const SET_EXPRESSION_COMMAND_ID = 'debug.setWatchExpression';
export const REMOVE_EXPRESSION_COMMAND_ID = 'debug.removeWatchExpression';

export const RESTART_LABEL = nls.localize('restartDebug', "Restart");
export const STEP_OVER_LABEL = nls.localize('stepOverDebug', "Step Over");
export const STEP_INTO_LABEL = nls.localize('stepIntoDebug', "Step Into");
export const STEP_OUT_LABEL = nls.localize('stepOutDebug', "Step Out");
export const PAUSE_LABEL = nls.localize('pauseDebug', "Pause");
export const DISCONNECT_LABEL = nls.localize('disconnect', "Disconnect");
export const STOP_LABEL = nls.localize('stop', "Stop");
export const CONTINUE_LABEL = nls.localize('continueDebug', "Continue");
export const FOCUS_SESSION_LABEL = nls.localize('focusSession', "Focus Session");
export const SELECT_AND_START_LABEL = nls.localize('selectAndStartDebugging', "Select and Start Debugging");
export const DEBUG_CONFIGURE_LABEL = nls.localize('openLaunchJson', "Open '{0}'", 'launch.json');
export const DEBUG_START_LABEL = nls.localize('startDebug', "Start Debugging");
export const DEBUG_RUN_LABEL = nls.localize('startWithoutDebugging', "Start Without Debugging");

interface CallStackContext {
	sessionId: string;
	threadId: string;
	frameId: string;
}

function isThreadContext(obj: any): obj is CallStackContext {
	return obj && typeof obj.sessionId === 'string' && typeof obj.threadId === 'string';
}

async function getThreadAndRun(accessor: ServicesAccessor, sessionAndThreadId: CallStackContext | unknown, run: (thread: IThread) => Promise<void>): Promise<void> {
	const debugService = accessor.get(IDebugService);
	let thread: IThread | undefined;
	if (isThreadContext(sessionAndThreadId)) {
		const session = debugService.getModel().getSession(sessionAndThreadId.sessionId);
		if (session) {
			thread = session.getAllThreads().find(t => t.getId() === sessionAndThreadId.threadId);
		}
	} else if (isSessionContext(sessionAndThreadId)) {
		const session = debugService.getModel().getSession(sessionAndThreadId.sessionId);
		if (session) {
			const threads = session.getAllThreads();
			thread = threads.length > 0 ? threads[0] : undefined;
		}
	}

	if (!thread) {
		thread = debugService.getViewModel().focusedThread;
		if (!thread) {
			const focusedSession = debugService.getViewModel().focusedSession;
			const threads = focusedSession ? focusedSession.getAllThreads() : undefined;
			thread = threads && threads.length ? threads[0] : undefined;
		}
	}

	if (thread) {
		await run(thread);
	}
}

function isStackFrameContext(obj: any): obj is CallStackContext {
	return obj && typeof obj.sessionId === 'string' && typeof obj.threadId === 'string' && typeof obj.frameId === 'string';
}

function getFrame(debugService: IDebugService, context: CallStackContext | unknown): IStackFrame | undefined {
	if (isStackFrameContext(context)) {
		const session = debugService.getModel().getSession(context.sessionId);
		if (session) {
			const thread = session.getAllThreads().find(t => t.getId() === context.threadId);
			if (thread) {
				return thread.getCallStack().find(sf => sf.getId() === context.frameId);
			}
		}
	}

	return undefined;
}

function isSessionContext(obj: any): obj is CallStackContext {
	return obj && typeof obj.sessionId === 'string';
}


// These commands are used in call stack context menu, call stack inline actions, command palette, debug toolbar, mac native touch bar
// When the command is exectued in the context of a thread(context menu on a thread, inline call stack action) we pass the thread id
// Otherwise when it is executed "globaly"(using the touch bar, debug toolbar, command palette) we do not pass any id and just take whatever is the focussed thread
// Same for stackFrame commands and session commands.
CommandsRegistry.registerCommand({
	id: COPY_STACK_TRACE_ID,
	handler: async (accessor: ServicesAccessor, _: string, context: CallStackContext | unknown) => {
		const textResourcePropertiesService = accessor.get(ITextResourcePropertiesService);
		const clipboardService = accessor.get(IClipboardService);
		const frame = getFrame(accessor.get(IDebugService), context);
		if (frame) {
			const eol = textResourcePropertiesService.getEOL(frame.source.uri);
			await clipboardService.writeText(frame.thread.getCallStack().map(sf => sf.toString()).join(eol));
		}
	}
});

CommandsRegistry.registerCommand({
	id: REVERSE_CONTINUE_ID,
	handler: (accessor: ServicesAccessor, _: string, context: CallStackContext | unknown) => {
		getThreadAndRun(accessor, context, thread => thread.reverseContinue());
	}
});

CommandsRegistry.registerCommand({
	id: STEP_BACK_ID,
	handler: (accessor: ServicesAccessor, _: string, context: CallStackContext | unknown) => {
		const contextKeyService = accessor.get(IContextKeyService);
		if (CONTEXT_DISASSEMBLY_VIEW_FOCUS.getValue(contextKeyService)) {
			getThreadAndRun(accessor, context, (thread: IThread) => thread.stepBack('instruction'));
		} else {
			getThreadAndRun(accessor, context, (thread: IThread) => thread.stepBack());
		}
	}
});

CommandsRegistry.registerCommand({
	id: TERMINATE_THREAD_ID,
	handler: (accessor: ServicesAccessor, _: string, context: CallStackContext | unknown) => {
		getThreadAndRun(accessor, context, thread => thread.terminate());
	}
});

CommandsRegistry.registerCommand({
	id: JUMP_TO_CURSOR_ID,
	handler: async (accessor: ServicesAccessor) => {
		const debugService = accessor.get(IDebugService);
		const stackFrame = debugService.getViewModel().focusedStackFrame;
		const editorService = accessor.get(IEditorService);
		const activeEditorControl = editorService.activeTextEditorControl;
		const notificationService = accessor.get(INotificationService);
		const quickInputService = accessor.get(IQuickInputService);

		if (stackFrame && isCodeEditor(activeEditorControl) && activeEditorControl.hasModel()) {
			const position = activeEditorControl.getPosition();
			const resource = activeEditorControl.getModel().uri;
			const source = stackFrame.thread.session.getSourceForUri(resource);
			if (source) {
				const response = await stackFrame.thread.session.gotoTargets(source.raw, position.lineNumber, position.column);
				const targets = response?.body.targets;
				if (targets && targets.length) {
					let id = targets[0].id;
					if (targets.length > 1) {
						const picks = targets.map(t => ({ label: t.label, _id: t.id }));
						const pick = await quickInputService.pick(picks, { placeHolder: nls.localize('chooseLocation', "Choose the specific location") });
						if (!pick) {
							return;
						}

						id = pick._id;
					}

					return await stackFrame.thread.session.goto(stackFrame.thread.threadId, id).catch(e => notificationService.warn(e));
				}
			}
		}

		return notificationService.warn(nls.localize('noExecutableCode', "No executable code is associated at the current cursor position."));
	}
});

MenuRegistry.appendMenuItem(MenuId.EditorContext, {
	command: {
		id: JUMP_TO_CURSOR_ID,
		title: nls.localize('jumpToCursor', "Jump to Cursor"),
		category: { value: nls.localize('debug', "Debug"), original: 'Debug' }
	},
	when: ContextKeyExpr.and(CONTEXT_JUMP_TO_CURSOR_SUPPORTED, EditorContextKeys.editorTextFocus),
	group: 'debug',
	order: 3
});

KeybindingsRegistry.registerCommandAndKeybindingRule({
	id: RESTART_SESSION_ID,
	weight: KeybindingWeight.WorkbenchContrib,
	primary: KeyMod.Shift | KeyMod.CtrlCmd | KeyCode.F5,
	when: CONTEXT_IN_DEBUG_MODE,
	handler: async (accessor: ServicesAccessor, _: string, context: CallStackContext | unknown) => {
		const debugService = accessor.get(IDebugService);
		const configurationService = accessor.get(IConfigurationService);
		let session: IDebugSession | undefined;
		if (isSessionContext(context)) {
			session = debugService.getModel().getSession(context.sessionId);
		} else {
			session = debugService.getViewModel().focusedSession;
		}

		if (!session) {
			const { launch, name } = debugService.getConfigurationManager().selectedConfiguration;
			await debugService.startDebugging(launch, name, { noDebug: false, startedByUser: true });
		} else {
			const showSubSessions = configurationService.getValue<IDebugConfiguration>('debug').showSubSessionsInToolBar;
			// Stop should be sent to the root parent session
			while (!showSubSessions && session && session.parentSession) {
				session = session.parentSession;
			}
			session.removeReplExpressions();
			await debugService.restartSession(session);
		}
	}
});

KeybindingsRegistry.registerCommandAndKeybindingRule({
	id: STEP_OVER_ID,
	weight: KeybindingWeight.WorkbenchContrib,
	primary: isWeb ? (KeyMod.Alt | KeyCode.F10) : KeyCode.F10, // Browsers do not allow F10 to be binded so we have to bind an alternative
	when: CONTEXT_DEBUG_STATE.isEqualTo('stopped'),
	handler: (accessor: ServicesAccessor, _: string, context: CallStackContext | unknown) => {
		const contextKeyService = accessor.get(IContextKeyService);
		if (CONTEXT_DISASSEMBLY_VIEW_FOCUS.getValue(contextKeyService)) {
			getThreadAndRun(accessor, context, (thread: IThread) => thread.next('instruction'));
		} else {
			getThreadAndRun(accessor, context, (thread: IThread) => thread.next());
		}
	}
});

KeybindingsRegistry.registerCommandAndKeybindingRule({
	id: STEP_INTO_ID,
	weight: KeybindingWeight.WorkbenchContrib + 10, // Have a stronger weight to have priority over full screen when debugging
	primary: (isWeb && isWindows) ? (KeyMod.Alt | KeyCode.F11) : KeyCode.F11, // Windows browsers use F11 for full screen, thus use alt+F11 as the default shortcut
	// Use a more flexible when clause to not allow full screen command to take over when F11 pressed a lot of times
	when: CONTEXT_DEBUG_STATE.notEqualsTo('inactive'),
	handler: (accessor: ServicesAccessor, _: string, context: CallStackContext | unknown) => {
		const contextKeyService = accessor.get(IContextKeyService);
		if (CONTEXT_DISASSEMBLY_VIEW_FOCUS.getValue(contextKeyService)) {
			getThreadAndRun(accessor, context, (thread: IThread) => thread.stepIn('instruction'));
		} else {
			getThreadAndRun(accessor, context, (thread: IThread) => thread.stepIn());
		}
	}
});

KeybindingsRegistry.registerCommandAndKeybindingRule({
	id: STEP_OUT_ID,
	weight: KeybindingWeight.WorkbenchContrib,
	primary: KeyMod.Shift | KeyCode.F11,
	when: CONTEXT_DEBUG_STATE.isEqualTo('stopped'),
	handler: (accessor: ServicesAccessor, _: string, context: CallStackContext | unknown) => {
		const contextKeyService = accessor.get(IContextKeyService);
		if (CONTEXT_DISASSEMBLY_VIEW_FOCUS.getValue(contextKeyService)) {
			getThreadAndRun(accessor, context, (thread: IThread) => thread.stepOut('instruction'));
		} else {
			getThreadAndRun(accessor, context, (thread: IThread) => thread.stepOut());
		}
	}
});

KeybindingsRegistry.registerCommandAndKeybindingRule({
	id: PAUSE_ID,
	weight: KeybindingWeight.WorkbenchContrib + 2, // take priority over focus next part while we are debugging
	primary: KeyCode.F6,
	when: CONTEXT_DEBUG_STATE.isEqualTo('running'),
	handler: (accessor: ServicesAccessor, _: string, context: CallStackContext | unknown) => {
		getThreadAndRun(accessor, context, thread => thread.pause());
	}
});

async function stopHandler(accessor: ServicesAccessor, _: string, context: CallStackContext | unknown, disconnect: boolean): Promise<void> {
	const debugService = accessor.get(IDebugService);
	let session: IDebugSession | undefined;
	if (isSessionContext(context)) {
		session = debugService.getModel().getSession(context.sessionId);
	} else {
		session = debugService.getViewModel().focusedSession;
	}

	const configurationService = accessor.get(IConfigurationService);
	const showSubSessions = configurationService.getValue<IDebugConfiguration>('debug').showSubSessionsInToolBar;
	// Stop should be sent to the root parent session
	while (!showSubSessions && session && session.parentSession) {
		session = session.parentSession;
	}

	await debugService.stopSession(session, disconnect);
}

KeybindingsRegistry.registerCommandAndKeybindingRule({
	id: DISCONNECT_ID,
	weight: KeybindingWeight.WorkbenchContrib,
	primary: KeyMod.Shift | KeyCode.F5,
	when: ContextKeyExpr.and(CONTEXT_FOCUSED_SESSION_IS_ATTACH, CONTEXT_IN_DEBUG_MODE),
	handler: (accessor, _, context) => stopHandler(accessor, _, context, true)
});

KeybindingsRegistry.registerCommandAndKeybindingRule({
	id: STOP_ID,
	weight: KeybindingWeight.WorkbenchContrib,
	primary: KeyMod.Shift | KeyCode.F5,
	when: ContextKeyExpr.and(CONTEXT_FOCUSED_SESSION_IS_ATTACH.toNegated(), CONTEXT_IN_DEBUG_MODE),
	handler: (accessor, _, context) => stopHandler(accessor, _, context, false)
});

CommandsRegistry.registerCommand({
	id: RESTART_FRAME_ID,
	handler: async (accessor: ServicesAccessor, _: string, context: CallStackContext | unknown) => {
		const debugService = accessor.get(IDebugService);
		const notificationService = accessor.get(INotificationService);
		const frame = getFrame(debugService, context);
		if (frame) {
			try {
				await frame.restart();
			} catch (e) {
				notificationService.error(e);
			}
		}
	}
});

KeybindingsRegistry.registerCommandAndKeybindingRule({
	id: CONTINUE_ID,
	weight: KeybindingWeight.WorkbenchContrib + 10, // Use a stronger weight to get priority over start debugging F5 shortcut
	primary: KeyCode.F5,
	when: CONTEXT_DEBUG_STATE.isEqualTo('stopped'),
	handler: (accessor: ServicesAccessor, _: string, context: CallStackContext | unknown) => {
		getThreadAndRun(accessor, context, thread => thread.continue());
	}
});

CommandsRegistry.registerCommand({
	id: FOCUS_REPL_ID,
	handler: async (accessor) => {
		const viewsService = accessor.get(IViewsService);
		await viewsService.openView(REPL_VIEW_ID, true);
	}
});

CommandsRegistry.registerCommand({
	id: 'debug.startFromConfig',
	handler: async (accessor, config: IConfig) => {
		const debugService = accessor.get(IDebugService);
		await debugService.startDebugging(undefined, config);
	}
});

CommandsRegistry.registerCommand({
	id: FOCUS_SESSION_ID,
	handler: async (accessor: ServicesAccessor, session: IDebugSession) => {
		const debugService = accessor.get(IDebugService);
		const editorService = accessor.get(IEditorService);
		const stoppedChildSession = debugService.getModel().getSessions().find(s => s.parentSession === session && s.state === State.Stopped);
		if (stoppedChildSession && session.state !== State.Stopped) {
			session = stoppedChildSession;
		}
		await debugService.focusStackFrame(undefined, undefined, session, true);
		const stackFrame = debugService.getViewModel().focusedStackFrame;
		if (stackFrame) {
			await stackFrame.openInEditor(editorService, true);
		}
	}
});

CommandsRegistry.registerCommand({
	id: SELECT_AND_START_ID,
	handler: async (accessor: ServicesAccessor) => {
		const quickInputService = accessor.get(IQuickInputService);
		quickInputService.quickAccess.show('debug ');
	}
});

KeybindingsRegistry.registerCommandAndKeybindingRule({
	id: DEBUG_START_COMMAND_ID,
	weight: KeybindingWeight.WorkbenchContrib,
	primary: KeyCode.F5,
	when: ContextKeyExpr.and(CONTEXT_DEBUGGERS_AVAILABLE, CONTEXT_DEBUG_STATE.isEqualTo('inactive')),
	handler: async (accessor: ServicesAccessor, debugStartOptions?: { config?: Partial<IConfig>; noDebug?: boolean }) => {
		const debugService = accessor.get(IDebugService);
		await saveAllBeforeDebugStart(accessor.get(IConfigurationService), accessor.get(IEditorService));
		const { launch, name, getConfig } = debugService.getConfigurationManager().selectedConfiguration;
		const config = await getConfig();
		const configOrName = config ? Object.assign(deepClone(config), debugStartOptions?.config) : name;
		await debugService.startDebugging(launch, configOrName, { noDebug: debugStartOptions?.noDebug, startedByUser: true }, false);
	}
});

KeybindingsRegistry.registerCommandAndKeybindingRule({
	id: DEBUG_RUN_COMMAND_ID,
	weight: KeybindingWeight.WorkbenchContrib,
	primary: KeyMod.CtrlCmd | KeyCode.F5,
	mac: { primary: KeyMod.WinCtrl | KeyCode.F5 },
	when: ContextKeyExpr.and(CONTEXT_DEBUGGERS_AVAILABLE, CONTEXT_DEBUG_STATE.notEqualsTo(getStateLabel(State.Initializing))),
	handler: async (accessor: ServicesAccessor) => {
		const commandService = accessor.get(ICommandService);
		await commandService.executeCommand(DEBUG_START_COMMAND_ID, { noDebug: true });
	}
});

KeybindingsRegistry.registerCommandAndKeybindingRule({
	id: 'debug.toggleBreakpoint',
	weight: KeybindingWeight.WorkbenchContrib + 5,
	when: ContextKeyExpr.and(CONTEXT_BREAKPOINTS_FOCUSED, InputFocusedContext.toNegated()),
	primary: KeyCode.Space,
	handler: (accessor) => {
		const listService = accessor.get(IListService);
		const debugService = accessor.get(IDebugService);
		const list = listService.lastFocusedList;
		if (list instanceof List) {
			const focused = <IEnablement[]>list.getFocusedElements();
			if (focused && focused.length) {
				debugService.enableOrDisableBreakpoints(!focused[0].enabled, focused[0]);
			}
		}
	}
});

KeybindingsRegistry.registerCommandAndKeybindingRule({
	id: 'debug.enableOrDisableBreakpoint',
	weight: KeybindingWeight.WorkbenchContrib,
	primary: undefined,
	when: EditorContextKeys.editorTextFocus,
	handler: (accessor) => {
		const debugService = accessor.get(IDebugService);
		const editorService = accessor.get(IEditorService);
		const control = editorService.activeTextEditorControl;
		if (isCodeEditor(control)) {
			const model = control.getModel();
			if (model) {
				const position = control.getPosition();
				if (position) {
					const bps = debugService.getModel().getBreakpoints({ uri: model.uri, lineNumber: position.lineNumber });
					if (bps.length) {
						debugService.enableOrDisableBreakpoints(!bps[0].enabled, bps[0]);
					}
				}
			}
		}
	}
});

KeybindingsRegistry.registerCommandAndKeybindingRule({
	id: EDIT_EXPRESSION_COMMAND_ID,
	weight: KeybindingWeight.WorkbenchContrib + 5,
	when: CONTEXT_WATCH_EXPRESSIONS_FOCUSED,
	primary: KeyCode.F2,
	mac: { primary: KeyCode.Enter },
	handler: (accessor: ServicesAccessor, expression: Expression | unknown) => {
		const debugService = accessor.get(IDebugService);
		if (!(expression instanceof Expression)) {
			const listService = accessor.get(IListService);
			const focused = listService.lastFocusedList;
			if (focused) {
				const elements = focused.getFocus();
				if (Array.isArray(elements) && elements[0] instanceof Expression) {
					expression = elements[0];
				}
			}
		}

		if (expression instanceof Expression) {
			debugService.getViewModel().setSelectedExpression(expression, false);
		}
	}
});

CommandsRegistry.registerCommand({
	id: SET_EXPRESSION_COMMAND_ID,
	handler: async (accessor: ServicesAccessor, expression: Expression | unknown) => {
		const debugService = accessor.get(IDebugService);
		if (expression instanceof Expression || expression instanceof Variable) {
			debugService.getViewModel().setSelectedExpression(expression, true);
		}
	}
});

KeybindingsRegistry.registerCommandAndKeybindingRule({
	id: 'debug.setVariable',
	weight: KeybindingWeight.WorkbenchContrib + 5,
	when: CONTEXT_VARIABLES_FOCUSED,
	primary: KeyCode.F2,
	mac: { primary: KeyCode.Enter },
	handler: (accessor) => {
		const listService = accessor.get(IListService);
		const debugService = accessor.get(IDebugService);
		const focused = listService.lastFocusedList;

		if (focused) {
			const elements = focused.getFocus();
			if (Array.isArray(elements) && elements[0] instanceof Variable) {
				debugService.getViewModel().setSelectedExpression(elements[0], false);
			}
		}
	}
});

KeybindingsRegistry.registerCommandAndKeybindingRule({
	id: REMOVE_EXPRESSION_COMMAND_ID,
	weight: KeybindingWeight.WorkbenchContrib,
	when: ContextKeyExpr.and(CONTEXT_WATCH_EXPRESSIONS_FOCUSED, CONTEXT_EXPRESSION_SELECTED.toNegated()),
	primary: KeyCode.Delete,
	mac: { primary: KeyMod.CtrlCmd | KeyCode.Backspace },
	handler: (accessor: ServicesAccessor, expression: Expression | unknown) => {
		const debugService = accessor.get(IDebugService);

		if (expression instanceof Expression) {
			debugService.removeWatchExpressions(expression.getId());
			return;
		}

		const listService = accessor.get(IListService);
		const focused = listService.lastFocusedList;
		if (focused) {
			let elements = focused.getFocus();
			if (Array.isArray(elements) && elements[0] instanceof Expression) {
				const selection = focused.getSelection();
				if (selection && selection.indexOf(elements[0]) >= 0) {
					elements = selection;
				}
				elements.forEach((e: Expression) => debugService.removeWatchExpressions(e.getId()));
			}
		}
	}
});

KeybindingsRegistry.registerCommandAndKeybindingRule({
	id: 'debug.removeBreakpoint',
	weight: KeybindingWeight.WorkbenchContrib,
	when: ContextKeyExpr.and(CONTEXT_BREAKPOINTS_FOCUSED, CONTEXT_BREAKPOINT_INPUT_FOCUSED.toNegated()),
	primary: KeyCode.Delete,
	mac: { primary: KeyMod.CtrlCmd | KeyCode.Backspace },
	handler: (accessor) => {
		const listService = accessor.get(IListService);
		const debugService = accessor.get(IDebugService);
		const list = listService.lastFocusedList;

		if (list instanceof List) {
			const focused = list.getFocusedElements();
			const element = focused.length ? focused[0] : undefined;
			if (element instanceof Breakpoint) {
				debugService.removeBreakpoints(element.getId());
			} else if (element instanceof FunctionBreakpoint) {
				debugService.removeFunctionBreakpoints(element.getId());
			} else if (element instanceof DataBreakpoint) {
				debugService.removeDataBreakpoints(element.getId());
			}
		}
	}
});

KeybindingsRegistry.registerCommandAndKeybindingRule({
	id: 'debug.installAdditionalDebuggers',
	weight: KeybindingWeight.WorkbenchContrib,
	when: undefined,
	primary: undefined,
	handler: async (accessor, query: string) => {
		const paneCompositeService = accessor.get(IPaneCompositePartService);
		const viewlet = (await paneCompositeService.openPaneComposite(EXTENSIONS_VIEWLET_ID, ViewContainerLocation.Sidebar, true))?.getViewPaneContainer() as IExtensionsViewPaneContainer;
		let searchFor = `@category:debuggers`;
		if (typeof query === 'string') {
			searchFor += ` ${query}`;
		}
		viewlet.search(searchFor);
		viewlet.focus();
	}
});

KeybindingsRegistry.registerCommandAndKeybindingRule({
	id: ADD_CONFIGURATION_ID,
	weight: KeybindingWeight.WorkbenchContrib,
	when: undefined,
	primary: undefined,
	handler: async (accessor, launchUri: string) => {
		const manager = accessor.get(IDebugService).getConfigurationManager();

		const launch = manager.getLaunches().find(l => l.uri.toString() === launchUri) || manager.selectedConfiguration.launch;
		if (launch) {
			const { editor, created } = await launch.openConfigFile(false);
			if (editor && !created) {
				const codeEditor = <ICodeEditor>editor.getControl();
				if (codeEditor) {
					await codeEditor.getContribution<IDebugEditorContribution>(EDITOR_CONTRIBUTION_ID)?.addLaunchConfiguration();
				}
			}
		}
	}
});

const inlineBreakpointHandler = (accessor: ServicesAccessor) => {
	const debugService = accessor.get(IDebugService);
	const editorService = accessor.get(IEditorService);
	const control = editorService.activeTextEditorControl;
	if (isCodeEditor(control)) {
		const position = control.getPosition();
		if (position && control.hasModel() && debugService.canSetBreakpointsIn(control.getModel())) {
			const modelUri = control.getModel().uri;
			const breakpointAlreadySet = debugService.getModel().getBreakpoints({ lineNumber: position.lineNumber, uri: modelUri })
				.some(bp => (bp.sessionAgnosticData.column === position.column || (!bp.column && position.column <= 1)));

			if (!breakpointAlreadySet) {
				debugService.addBreakpoints(modelUri, [{ lineNumber: position.lineNumber, column: position.column > 1 ? position.column : undefined }]);
			}
		}
	}
};

KeybindingsRegistry.registerCommandAndKeybindingRule({
	weight: KeybindingWeight.WorkbenchContrib,
	primary: KeyMod.Shift | KeyCode.F9,
	when: EditorContextKeys.editorTextFocus,
	id: TOGGLE_INLINE_BREAKPOINT_ID,
	handler: inlineBreakpointHandler
});

MenuRegistry.appendMenuItem(MenuId.EditorContext, {
	command: {
		id: TOGGLE_INLINE_BREAKPOINT_ID,
		title: nls.localize('addInlineBreakpoint', "Add Inline Breakpoint"),
		category: { value: nls.localize('debug', "Debug"), original: 'Debug' }
	},
	when: ContextKeyExpr.and(CONTEXT_IN_DEBUG_MODE, PanelFocusContext.toNegated(), EditorContextKeys.editorTextFocus),
	group: 'debug',
	order: 1
});

KeybindingsRegistry.registerCommandAndKeybindingRule({
	id: 'debug.openBreakpointToSide',
	weight: KeybindingWeight.WorkbenchContrib,
	when: CONTEXT_BREAKPOINTS_FOCUSED,
	primary: KeyMod.CtrlCmd | KeyCode.Enter,
	secondary: [KeyMod.Alt | KeyCode.Enter],
	handler: (accessor) => {
		const listService = accessor.get(IListService);
		const list = listService.lastFocusedList;
		if (list instanceof List) {
			const focus = list.getFocusedElements();
			if (focus.length && focus[0] instanceof Breakpoint) {
				return openBreakpointSource(focus[0], true, false, true, accessor.get(IDebugService), accessor.get(IEditorService));
			}
		}

		return undefined;
	}
});

// When there are no debug extensions, open the debug viewlet when F5 is pressed so the user can read the limitations
KeybindingsRegistry.registerCommandAndKeybindingRule({
	id: 'debug.openView',
	weight: KeybindingWeight.WorkbenchContrib,
	when: CONTEXT_DEBUGGERS_AVAILABLE.toNegated(),
	primary: KeyCode.F5,
	secondary: [KeyMod.CtrlCmd | KeyCode.F5],
	handler: async (accessor) => {
		const paneCompositeService = accessor.get(IPaneCompositePartService);
		await paneCompositeService.openPaneComposite(VIEWLET_ID, ViewContainerLocation.Sidebar, true);
	}
});