forked from ChromeDevTools/devtools-frontend
-
Notifications
You must be signed in to change notification settings - Fork 8
/
DebuggerPlugin.ts
2560 lines (2336 loc) · 104 KB
/
DebuggerPlugin.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
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
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2011 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import * as Common from '../../core/common/common.js';
import * as Host from '../../core/host/host.js';
import * as i18n from '../../core/i18n/i18n.js';
import * as Platform from '../../core/platform/platform.js';
import * as Root from '../../core/root/root.js';
import * as SDK from '../../core/sdk/sdk.js';
import * as Protocol from '../../generated/protocol.js';
import * as Bindings from '../../models/bindings/bindings.js';
import * as Breakpoints from '../../models/breakpoints/breakpoints.js';
import * as Formatter from '../../models/formatter/formatter.js';
import * as SourceMapScopes from '../../models/source_map_scopes/source_map_scopes.js';
import * as TextUtils from '../../models/text_utils/text_utils.js';
import * as Workspace from '../../models/workspace/workspace.js';
import * as CodeMirror from '../../third_party/codemirror.next/codemirror.next.js';
import type * as TextEditor from '../../ui/components/text_editor/text_editor.js';
import * as ObjectUI from '../../ui/legacy/components/object_ui/object_ui.js';
import * as SourceFrame from '../../ui/legacy/components/source_frame/source_frame.js';
import * as UI from '../../ui/legacy/legacy.js';
import * as VisualLogging from '../../ui/visual_logging/visual_logging.js';
import {AddDebugInfoURLDialog} from './AddSourceMapURLDialog.js';
import {BreakpointEditDialog, type BreakpointEditDialogResult} from './BreakpointEditDialog.js';
import * as SourceComponents from './components/components.js';
import {Plugin} from './Plugin.js';
import {SourcesPanel} from './SourcesPanel.js';
const {EMPTY_BREAKPOINT_CONDITION, NEVER_PAUSE_HERE_CONDITION} = Breakpoints.BreakpointManager;
const UIStrings = {
/**
*@description Text in Debugger Plugin of the Sources panel
*/
thisScriptIsOnTheDebuggersIgnore: 'This script is on the debugger\'s ignore list',
/**
*@description Text to stop preventing the debugger from stepping into library code
*/
removeFromIgnoreList: 'Remove from ignore list',
/**
*@description Text of a button in the Sources panel Debugger Plugin to configure ignore listing in Settings
*/
configure: 'Configure',
/**
*@description Text to add a breakpoint
*/
addBreakpoint: 'Add breakpoint',
/**
*@description A context menu item in the Debugger Plugin of the Sources panel
*/
addConditionalBreakpoint: 'Add conditional breakpoint…',
/**
*@description A context menu item in the Debugger Plugin of the Sources panel
*/
addLogpoint: 'Add logpoint…',
/**
*@description A context menu item in the Debugger Plugin of the Sources panel
*/
neverPauseHere: 'Never pause here',
/**
*@description Context menu command to delete/remove a breakpoint that the user
*has set. One line of code can have multiple breakpoints. Always >= 1 breakpoint.
*/
removeBreakpoint: '{n, plural, =1 {Remove breakpoint} other {Remove all breakpoints in line}}',
/**
*@description A context menu item in the Debugger Plugin of the Sources panel
*/
editBreakpoint: 'Edit breakpoint…',
/**
*@description Context menu command to disable (but not delete) a breakpoint
*that the user has set. One line of code can have multiple breakpoints. Always
*>= 1 breakpoint.
*/
disableBreakpoint: '{n, plural, =1 {Disable breakpoint} other {Disable all breakpoints in line}}',
/**
*@description Context menu command to enable a breakpoint that the user has
*set. One line of code can have multiple breakpoints. Always >= 1 breakpoint.
*/
enableBreakpoint: '{n, plural, =1 {Enable breakpoint} other {Enable all breakpoints in line}}',
/**
*@description Text in Debugger Plugin of the Sources panel
*/
addSourceMap: 'Add source map…',
/**
*@description Text in Debugger Plugin of the Sources panel
*/
addWasmDebugInfo: 'Add DWARF debug info…',
/**
*@description Text in Debugger Plugin of the Sources panel
*/
sourceMapLoaded: 'Source map loaded.',
/**
*@description Title of the Filtered List WidgetProvider of Quick Open
*@example {Ctrl+P Ctrl+O} PH1
*/
associatedFilesAreAvailable: 'Associated files are available via file tree or {PH1}.',
/**
*@description Text in Debugger Plugin of the Sources panel
*/
associatedFilesShouldBeAdded:
'Associated files should be added to the file tree. You can debug these resolved source files as regular JavaScript files.',
/**
*@description Text in Debugger Plugin of the Sources panel
*/
theDebuggerWillSkipStepping: 'The debugger will skip stepping through this script, and will not stop on exceptions.',
/**
*@description Text in Debugger Plugin of the Sources panel
*/
sourceMapSkipped: 'Source map skipped for this file.',
/**
*@description Text in Debugger Plugin of the Sources panel
*/
sourceMapFailed: 'Source map failed to load.',
/**
*@description Text in Debugger Plugin of the Sources panel
*/
debuggingPowerReduced: 'DevTools can\'t show authored sources, but you can debug the deployed code.',
/**
*@description Text in Debugger Plugin of the Sources panel
*/
reloadForSourceMap: 'To enable again, make sure the file isn\'t on the ignore list and reload.',
/**
*@description Text in Debugger Plugin of the Sources panel
*@example {http://site.com/lib.js.map} PH1
*@example {HTTP error: status code 404, net::ERR_UNKNOWN_URL_SCHEME} PH2
*/
errorLoading: 'Error loading url {PH1}: {PH2}',
/**
*@description Text in Debugger Plugin of the Sources panel
*/
ignoreScript: 'Ignore this file',
/**
*@description Text in Debugger Plugin of the Sources panel
*/
ignoreContentScripts: 'Ignore extension scripts',
/**
*@description Error message that is displayed in UI when a file needed for debugging information for a call frame is missing
*@example {src/myapp.debug.wasm.dwp} PH1
*/
debugFileNotFound: 'Failed to load debug file "{PH1}".',
/**
*@description Error message that is displayed when no debug info could be loaded
*@example {app.wasm} PH1
*/
debugInfoNotFound: 'Failed to load any debug info for {PH1}.',
};
const str_ = i18n.i18n.registerUIStrings('panels/sources/DebuggerPlugin.ts', UIStrings);
const i18nString = i18n.i18n.getLocalizedString.bind(undefined, str_);
// Note: Line numbers are passed around as zero-based numbers (though
// CodeMirror numbers them from 1).
// Don't scan for possible breakpoints on a line beyond this position;
const MAX_POSSIBLE_BREAKPOINT_LINE = 2500;
// Limits on inline variable view computation.
const MAX_CODE_SIZE_FOR_VALUE_DECORATIONS = 10000;
const MAX_PROPERTIES_IN_SCOPE_FOR_VALUE_DECORATIONS = 500;
type BreakpointDescription = {
position: number,
breakpoint: Breakpoints.BreakpointManager.Breakpoint,
};
type BreakpointEditRequest = {
line: CodeMirror.Line,
breakpoint: Breakpoints.BreakpointManager.Breakpoint|null,
location: {lineNumber: number, columnNumber: number}|null,
isLogpoint?: boolean,
};
const debuggerPluginForUISourceCode = new Map<Workspace.UISourceCode.UISourceCode, DebuggerPlugin>();
export class DebuggerPlugin extends Plugin {
private editor: TextEditor.TextEditor.TextEditor|undefined = undefined;
// Set if the debugger is stopped on a breakpoint in this file
private executionLocation: Workspace.UISourceCode.UILocation|null = null;
// Track state of the control key because holding it makes debugger
// target locations show up in the editor
private controlDown: boolean = false;
private controlTimeout: number|undefined = undefined;
private sourceMapInfobar: UI.Infobar.Infobar|null = null;
private readonly scriptsPanel: SourcesPanel;
private readonly breakpointManager: Breakpoints.BreakpointManager.BreakpointManager;
// Manages pop-overs shown when the debugger is active and the user
// hovers over an expression
private popoverHelper: UI.PopoverHelper.PopoverHelper|null = null;
private scriptFileForDebuggerModel:
Map<SDK.DebuggerModel.DebuggerModel, Bindings.ResourceScriptMapping.ResourceScriptFile>;
// The current set of breakpoints for this file. The locations in
// here are kept in sync with their editor position. When a file's
// content is edited and later saved, these are used as a source of
// truth for re-creating the breakpoints.
private breakpoints: BreakpointDescription[] = [];
private continueToLocations: {from: number, to: number, async: boolean, click: () => void}[]|null = null;
private readonly liveLocationPool: Bindings.LiveLocation.LiveLocationPool;
// When the editor content is changed by the user, this becomes
// true. When the plugin is muted, breakpoints show up as disabled
// and can't be manipulated. It is cleared again when the content is
// saved.
private muted: boolean;
// If the plugin is initialized in muted state, we cannot correlated
// breakpoint position in the breakpoint manager with editor
// locations, so breakpoint manipulation is permanently disabled.
private initializedMuted: boolean;
private ignoreListInfobar: UI.Infobar.Infobar|null;
private refreshBreakpointsTimeout: undefined|number = undefined;
private activeBreakpointDialog: BreakpointEditDialog|null = null;
#activeBreakpointEditRequest?: BreakpointEditRequest = undefined;
#scheduledFinishingActiveDialog = false;
private missingDebugInfoBar: UI.Infobar.Infobar|null = null;
#sourcesPanelDebuggedMetricsRecorded = false;
private readonly loader: SDK.PageResourceLoader.PageResourceLoader;
private readonly ignoreListCallback: () => void;
constructor(
uiSourceCode: Workspace.UISourceCode.UISourceCode,
private readonly transformer: SourceFrame.SourceFrame.Transformer) {
super(uiSourceCode);
debuggerPluginForUISourceCode.set(uiSourceCode, this);
this.scriptsPanel = SourcesPanel.instance();
this.breakpointManager = Breakpoints.BreakpointManager.BreakpointManager.instance();
this.breakpointManager.addEventListener(
Breakpoints.BreakpointManager.Events.BreakpointAdded, this.breakpointChange, this);
this.breakpointManager.addEventListener(
Breakpoints.BreakpointManager.Events.BreakpointRemoved, this.breakpointChange, this);
this.uiSourceCode.addEventListener(Workspace.UISourceCode.Events.WorkingCopyChanged, this.workingCopyChanged, this);
this.uiSourceCode.addEventListener(
Workspace.UISourceCode.Events.WorkingCopyCommitted, this.workingCopyCommitted, this);
this.scriptFileForDebuggerModel = new Map();
this.loader = SDK.PageResourceLoader.PageResourceLoader.instance();
this.loader.addEventListener(
SDK.PageResourceLoader.Events.Update, this.showSourceMapInfobarIfNeeded.bind(this), this);
this.ignoreListCallback = this.showIgnoreListInfobarIfNeeded.bind(this);
Bindings.IgnoreListManager.IgnoreListManager.instance().addChangeListener(this.ignoreListCallback);
UI.Context.Context.instance().addFlavorChangeListener(SDK.DebuggerModel.CallFrame, this.callFrameChanged, this);
this.liveLocationPool = new Bindings.LiveLocation.LiveLocationPool();
this.updateScriptFiles();
this.muted = this.uiSourceCode.isDirty();
this.initializedMuted = this.muted;
this.ignoreListInfobar = null;
this.showIgnoreListInfobarIfNeeded();
for (const scriptFile of this.scriptFileForDebuggerModel.values()) {
scriptFile.checkMapping();
}
}
override editorExtension(): CodeMirror.Extension {
// Kludge to hook editor keyboard events into the ShortcutRegistry
// system.
const handlers = this.shortcutHandlers();
return [
CodeMirror.EditorView.updateListener.of(update => this.onEditorUpdate(update)),
CodeMirror.EditorView.domEventHandlers({
keydown: event => {
if (this.onKeyDown(event)) {
return true;
}
handlers(event);
return event.defaultPrevented;
},
keyup: event => this.onKeyUp(event),
mousemove: event => this.onMouseMove(event),
mousedown: event => this.onMouseDown(event),
focusout: event => this.onBlur(event),
wheel: event => this.onWheel(event),
}),
CodeMirror.lineNumbers({
domEventHandlers: {
mousedown: (view, block, event) =>
this.handleGutterClick(view.state.doc.lineAt(block.from), event as MouseEvent),
},
}),
infobarState,
breakpointMarkers,
CodeMirror.Prec.highest(executionLine.field),
CodeMirror.Prec.lowest(continueToMarkers.field),
markIfContinueTo,
valueDecorations.field,
CodeMirror.Prec.lowest(evalExpression.field),
theme,
this.uiSourceCode.project().type() === Workspace.Workspace.projectTypes.Debugger ?
CodeMirror.EditorView.editorAttributes.of({class: 'source-frame-debugger-script'}) :
[],
];
}
private shortcutHandlers(): (event: KeyboardEvent) => void {
const selectionLine = (editor: TextEditor.TextEditor.TextEditor): CodeMirror.Line => {
return editor.state.doc.lineAt(editor.state.selection.main.head);
};
return UI.ShortcutRegistry.ShortcutRegistry.instance().getShortcutListener({
'debugger.toggle-breakpoint': async () => {
if (this.muted || !this.editor) {
return false;
}
await this.toggleBreakpoint(selectionLine(this.editor), false);
return true;
},
'debugger.toggle-breakpoint-enabled': async () => {
if (this.muted || !this.editor) {
return false;
}
await this.toggleBreakpoint(selectionLine(this.editor), true);
return true;
},
'debugger.breakpoint-input-window': async () => {
if (this.muted || !this.editor) {
return false;
}
const line = selectionLine(this.editor);
Host.userMetrics.breakpointEditDialogRevealedFrom(
Host.UserMetrics.BreakpointEditDialogRevealedFrom.KeyboardShortcut);
this.#openEditDialogForLine(line);
return true;
},
});
}
#openEditDialogForLine(line: CodeMirror.Line, isLogpoint?: boolean): void {
if (this.muted) {
return;
}
if (this.activeBreakpointDialog) {
this.activeBreakpointDialog.finishEditing(false, '');
}
const breakpoint = this.breakpoints.find(b => b.position >= line.from && b.position <= line.to)?.breakpoint || null;
if (isLogpoint === undefined && breakpoint !== null) {
isLogpoint = breakpoint.isLogpoint();
}
this.editBreakpointCondition({line, breakpoint, location: null, isLogpoint});
}
override editorInitialized(editor: TextEditor.TextEditor.TextEditor): void {
// Start asynchronous actions that require access to the editor
// instance
this.editor = editor;
computeNonBreakableLines(editor.state, this.transformer, this.uiSourceCode).then(linePositions => {
if (linePositions.length) {
editor.dispatch({effects: SourceFrame.SourceFrame.addNonBreakableLines.of(linePositions)});
}
}, console.error);
if (this.ignoreListInfobar) {
this.attachInfobar(this.ignoreListInfobar);
}
if (this.missingDebugInfoBar) {
this.attachInfobar(this.missingDebugInfoBar);
}
if (this.sourceMapInfobar) {
this.attachInfobar(this.sourceMapInfobar);
}
if (!this.muted) {
void this.refreshBreakpoints();
}
void this.callFrameChanged();
this.popoverHelper?.dispose();
this.popoverHelper =
new UI.PopoverHelper.PopoverHelper(editor, this.getPopoverRequest.bind(this), 'sources.object-properties');
this.popoverHelper.setDisableOnClick(true);
this.popoverHelper.setTimeout(250, 250);
this.popoverHelper.setHasPadding(true);
}
static override accepts(uiSourceCode: Workspace.UISourceCode.UISourceCode): boolean {
return uiSourceCode.contentType().hasScripts();
}
private showIgnoreListInfobarIfNeeded(): void {
const uiSourceCode = this.uiSourceCode;
if (!uiSourceCode.contentType().hasScripts()) {
return;
}
if (!Bindings.IgnoreListManager.IgnoreListManager.instance().isUserOrSourceMapIgnoreListedUISourceCode(
uiSourceCode)) {
this.hideIgnoreListInfobar();
return;
}
if (this.ignoreListInfobar) {
this.ignoreListInfobar.dispose();
}
function unIgnoreList(): void {
Bindings.IgnoreListManager.IgnoreListManager.instance().unIgnoreListUISourceCode(uiSourceCode);
}
const infobar = new UI.Infobar.Infobar(
UI.Infobar.Type.Warning, i18nString(UIStrings.thisScriptIsOnTheDebuggersIgnore),
[
{
text: i18nString(UIStrings.removeFromIgnoreList),
highlight: false,
delegate: unIgnoreList,
dismiss: true,
jslogContext: 'remove-from-ignore-list',
},
{
text: i18nString(UIStrings.configure),
highlight: false,
delegate:
UI.ViewManager.ViewManager.instance().showView.bind(UI.ViewManager.ViewManager.instance(), 'blackbox'),
dismiss: false,
jslogContext: 'configure',
},
],
undefined, undefined, 'script-on-ignore-list');
this.ignoreListInfobar = infobar;
infobar.setCloseCallback(() => this.removeInfobar(this.ignoreListInfobar));
infobar.createDetailsRowMessage(i18nString(UIStrings.theDebuggerWillSkipStepping));
this.attachInfobar(this.ignoreListInfobar);
}
attachInfobar(bar: UI.Infobar.Infobar): void {
if (this.editor) {
this.editor.dispatch({effects: addInfobar.of(bar)});
}
}
removeInfobar(bar: UI.Infobar.Infobar|null): void {
if (this.editor && bar) {
this.editor.dispatch({effects: removeInfobar.of(bar)});
}
}
private hideIgnoreListInfobar(): void {
if (!this.ignoreListInfobar) {
return;
}
this.ignoreListInfobar.dispose();
this.ignoreListInfobar = null;
}
override willHide(): void {
this.popoverHelper?.hidePopover();
}
editBreakpointLocation({breakpoint, uiLocation}: Breakpoints.BreakpointManager.BreakpointLocation): void {
const {lineNumber} = this.transformer.uiLocationToEditorLocation(uiLocation.lineNumber, uiLocation.columnNumber);
const line = this.editor?.state.doc.line(lineNumber + 1);
if (!line) {
return;
}
this.editBreakpointCondition({line, breakpoint, location: null, isLogpoint: breakpoint.isLogpoint()});
}
override populateLineGutterContextMenu(contextMenu: UI.ContextMenu.ContextMenu, editorLineNumber: number): void {
const uiLocation = new Workspace.UISourceCode.UILocation(this.uiSourceCode, editorLineNumber, 0);
this.scriptsPanel.appendUILocationItems(contextMenu, uiLocation);
if (this.muted || !this.editor) {
return;
}
const line = this.editor.state.doc.line(editorLineNumber + 1);
const breakpoints = this.lineBreakpoints(line);
const supportsConditionalBreakpoints =
Bindings.DebuggerWorkspaceBinding.DebuggerWorkspaceBinding.instance().supportsConditionalBreakpoints(
this.uiSourceCode);
if (!breakpoints.length) {
if (this.editor && SourceFrame.SourceFrame.isBreakableLine(this.editor.state, line)) {
contextMenu.debugSection().appendItem(
i18nString(UIStrings.addBreakpoint),
this.createNewBreakpoint.bind(
this, line, EMPTY_BREAKPOINT_CONDITION, /* enabled */ true, /* isLogpoint */ false),
{jslogContext: 'add-breakpoint'});
if (supportsConditionalBreakpoints) {
contextMenu.debugSection().appendItem(i18nString(UIStrings.addConditionalBreakpoint), () => {
Host.userMetrics.breakpointEditDialogRevealedFrom(
Host.UserMetrics.BreakpointEditDialogRevealedFrom.LineGutterContextMenu);
this.editBreakpointCondition({line, breakpoint: null, location: null, isLogpoint: false});
}, {jslogContext: 'add-cnd-breakpoint'});
contextMenu.debugSection().appendItem(i18nString(UIStrings.addLogpoint), () => {
Host.userMetrics.breakpointEditDialogRevealedFrom(
Host.UserMetrics.BreakpointEditDialogRevealedFrom.LineGutterContextMenu);
this.editBreakpointCondition({line, breakpoint: null, location: null, isLogpoint: true});
}, {jslogContext: 'add-logpoint'});
contextMenu.debugSection().appendItem(
i18nString(UIStrings.neverPauseHere),
this.createNewBreakpoint.bind(
this, line, NEVER_PAUSE_HERE_CONDITION, /* enabled */ true, /* isLogpoint */ false),
{jslogContext: 'never-pause-here'});
}
}
} else {
const removeTitle = i18nString(UIStrings.removeBreakpoint, {n: breakpoints.length});
contextMenu.debugSection().appendItem(
removeTitle, () => breakpoints.forEach(breakpoint => {
Host.userMetrics.actionTaken(Host.UserMetrics.Action.BreakpointRemovedFromGutterContextMenu);
void breakpoint.remove(false);
}),
{jslogContext: 'remove-breakpoint'});
if (breakpoints.length === 1 && supportsConditionalBreakpoints) {
// Editing breakpoints only make sense for conditional breakpoints
// and logpoints and both are currently only available for JavaScript
// debugging.
contextMenu.debugSection().appendItem(i18nString(UIStrings.editBreakpoint), () => {
Host.userMetrics.breakpointEditDialogRevealedFrom(
Host.UserMetrics.BreakpointEditDialogRevealedFrom.BreakpointMarkerContextMenu);
this.editBreakpointCondition({line, breakpoint: breakpoints[0], location: null});
}, {jslogContext: 'edit-breakpoint'});
}
const hasEnabled = breakpoints.some(breakpoint => breakpoint.enabled());
if (hasEnabled) {
const title = i18nString(UIStrings.disableBreakpoint, {n: breakpoints.length});
contextMenu.debugSection().appendItem(
title, () => breakpoints.forEach(breakpoint => breakpoint.setEnabled(false)),
{jslogContext: 'enable-breakpoint'});
}
const hasDisabled = breakpoints.some(breakpoint => !breakpoint.enabled());
if (hasDisabled) {
const title = i18nString(UIStrings.enableBreakpoint, {n: breakpoints.length});
contextMenu.debugSection().appendItem(
title, () => breakpoints.forEach(breakpoint => breakpoint.setEnabled(true)),
{jslogContext: 'disable-breakpoint'});
}
}
}
override populateTextAreaContextMenu(contextMenu: UI.ContextMenu.ContextMenu): void {
function addSourceMapURL(scriptFile: Bindings.ResourceScriptMapping.ResourceScriptFile): void {
const dialog =
AddDebugInfoURLDialog.createAddSourceMapURLDialog(addSourceMapURLDialogCallback.bind(null, scriptFile));
dialog.show();
}
function addSourceMapURLDialogCallback(
scriptFile: Bindings.ResourceScriptMapping.ResourceScriptFile, url: Platform.DevToolsPath.UrlString): void {
if (!url) {
return;
}
scriptFile.addSourceMapURL(url);
}
function addDebugInfoURL(scriptFile: Bindings.ResourceScriptMapping.ResourceScriptFile): void {
const dialog =
AddDebugInfoURLDialog.createAddDWARFSymbolsURLDialog(addDebugInfoURLDialogCallback.bind(null, scriptFile));
dialog.show();
}
function addDebugInfoURLDialogCallback(
scriptFile: Bindings.ResourceScriptMapping.ResourceScriptFile, url: Platform.DevToolsPath.UrlString): void {
if (!url) {
return;
}
scriptFile.addDebugInfoURL(url);
}
if (this.uiSourceCode.project().type() === Workspace.Workspace.projectTypes.Network &&
Common.Settings.Settings.instance().moduleSetting('js-source-maps-enabled').get() &&
!Bindings.IgnoreListManager.IgnoreListManager.instance().isUserIgnoreListedURL(this.uiSourceCode.url())) {
if (this.scriptFileForDebuggerModel.size) {
const scriptFile: Bindings.ResourceScriptMapping.ResourceScriptFile =
this.scriptFileForDebuggerModel.values().next().value;
const addSourceMapURLLabel = i18nString(UIStrings.addSourceMap);
contextMenu.debugSection().appendItem(
addSourceMapURLLabel, addSourceMapURL.bind(null, scriptFile), {jslogContext: 'add-source-map'});
if (scriptFile.script?.isWasm() &&
!Bindings.DebuggerWorkspaceBinding.DebuggerWorkspaceBinding.instance().pluginManager.hasPluginForScript(
scriptFile.script)) {
contextMenu.debugSection().appendItem(
i18nString(UIStrings.addWasmDebugInfo), addDebugInfoURL.bind(null, scriptFile),
{jslogContext: 'add-wasm-debug-info'});
}
}
}
}
private workingCopyChanged(): void {
if (!this.scriptFileForDebuggerModel.size) {
this.setMuted(this.uiSourceCode.isDirty());
}
}
private workingCopyCommitted(): void {
this.scriptsPanel.updateLastModificationTime();
if (!this.scriptFileForDebuggerModel.size) {
this.setMuted(false);
}
}
private didMergeToVM(): void {
if (this.consistentScripts()) {
this.setMuted(false);
}
}
private didDivergeFromVM(): void {
this.setMuted(true);
}
private setMuted(value: boolean): void {
if (this.initializedMuted) {
return;
}
if (value !== this.muted) {
this.muted = value;
if (!value) {
void this.restoreBreakpointsAfterEditing();
} else if (this.editor) {
this.editor.dispatch({effects: muteBreakpoints.of(null)});
}
}
}
private consistentScripts(): boolean {
for (const scriptFile of this.scriptFileForDebuggerModel.values()) {
if (scriptFile.hasDivergedFromVM() || scriptFile.isMergingToVM()) {
return false;
}
}
return true;
}
private isVariableIdentifier(tokenType: string): boolean {
return tokenType === 'VariableName' || tokenType === 'VariableDefinition';
}
private isIdentifier(tokenType: string): boolean {
return tokenType === 'VariableName' || tokenType === 'VariableDefinition' || tokenType === 'PropertyName' ||
tokenType === 'PropertyDefinition';
}
private getPopoverRequest(event: MouseEvent): UI.PopoverHelper.PopoverRequest|null {
if (UI.KeyboardShortcut.KeyboardShortcut.eventHasCtrlEquivalentKey(event)) {
return null;
}
const target = UI.Context.Context.instance().flavor(SDK.Target.Target);
const debuggerModel = target ? target.model(SDK.DebuggerModel.DebuggerModel) : null;
const {editor} = this;
if (!debuggerModel || !debuggerModel.isPaused() || !editor) {
return null;
}
const selectedCallFrame =
(UI.Context.Context.instance().flavor(SDK.DebuggerModel.CallFrame) as SDK.DebuggerModel.CallFrame);
if (!selectedCallFrame) {
return null;
}
let textPosition = editor.editor.posAtCoords(event);
if (!textPosition) {
return null;
}
const positionCoords = editor.editor.coordsAtPos(textPosition);
if (!positionCoords || event.clientY < positionCoords.top || event.clientY > positionCoords.bottom ||
event.clientX < positionCoords.left - 30 || event.clientX > positionCoords.right + 30) {
return null;
}
if (event.clientX < positionCoords.left && textPosition > editor.state.doc.lineAt(textPosition).from) {
textPosition -= 1;
}
const highlightRange = computePopoverHighlightRange(editor.state, this.uiSourceCode.mimeType(), textPosition);
if (!highlightRange) {
return null;
}
const highlightLine = editor.state.doc.lineAt(highlightRange.from);
if (highlightRange.to > highlightLine.to) {
return null;
}
const leftCorner = editor.editor.coordsAtPos(highlightRange.from);
const rightCorner = editor.editor.coordsAtPos(highlightRange.to);
if (!leftCorner || !rightCorner) {
return null;
}
const box = new AnchorBox(
leftCorner.left, leftCorner.top - 2, rightCorner.right - leftCorner.left, rightCorner.bottom - leftCorner.top);
const evaluationText = editor.state.sliceDoc(highlightRange.from, highlightRange.to);
let objectPopoverHelper: ObjectUI.ObjectPopoverHelper.ObjectPopoverHelper|null = null;
return {
box,
show: async (popover: UI.GlassPane.GlassPane) => {
let resolvedText: string = '';
if (Root.Runtime.experiments.isEnabled('evaluate-expressions-with-source-maps')) {
const nameMap = await SourceMapScopes.NamesResolver.allVariablesInCallFrame(selectedCallFrame);
try {
resolvedText =
await Formatter.FormatterWorkerPool.formatterWorkerPool().javaScriptSubstitute(evaluationText, nameMap);
} catch {
}
} else {
resolvedText = await SourceMapScopes.NamesResolver.resolveExpression(
selectedCallFrame, evaluationText, this.uiSourceCode, highlightLine.number - 1,
highlightRange.from - highlightLine.from, highlightRange.to - highlightLine.from);
}
// We use side-effect free debug-evaluate when the highlighted expression contains a
// function/method call. Otherwise we allow side-effects. The motiviation here are
// frameworks like Vue, that heavily use proxies for caching:
//
// * We deem a simple property access of a proxy as deterministic so it should be
// successful even if V8 thinks its side-effecting.
// * Explicit function calls on the other hand must be side-effect free. The canonical
// example is hovering over {Math.random()} which would result in a different value
// each time the user hovers over it.
const throwOnSideEffect = Root.Runtime.experiments.isEnabled('evaluate-expressions-with-source-maps') &&
highlightRange.containsSideEffects;
const result = await selectedCallFrame.evaluate({
expression: resolvedText || evaluationText,
objectGroup: 'popover',
includeCommandLineAPI: false,
silent: true,
returnByValue: false,
generatePreview: false,
throwOnSideEffect,
timeout: undefined,
disableBreaks: undefined,
replMode: undefined,
allowUnsafeEvalBlockedByCSP: undefined,
});
if (!result || 'error' in result || !result.object ||
(result.object.type === 'object' && result.object.subtype === 'error')) {
return false;
}
objectPopoverHelper =
await ObjectUI.ObjectPopoverHelper.ObjectPopoverHelper.buildObjectPopover(result.object, popover);
const potentiallyUpdatedCallFrame = UI.Context.Context.instance().flavor(SDK.DebuggerModel.CallFrame);
if (!objectPopoverHelper || selectedCallFrame !== potentiallyUpdatedCallFrame) {
debuggerModel.runtimeModel().releaseObjectGroup('popover');
if (objectPopoverHelper) {
objectPopoverHelper.dispose();
}
return false;
}
const decoration = CodeMirror.Decoration.set(evalExpressionMark.range(highlightRange.from, highlightRange.to));
editor.dispatch({effects: evalExpression.update.of(decoration)});
return true;
},
hide: () => {
if (objectPopoverHelper) {
objectPopoverHelper.dispose();
}
debuggerModel.runtimeModel().releaseObjectGroup('popover');
editor.dispatch({effects: evalExpression.update.of(CodeMirror.Decoration.none)});
},
};
}
private onEditorUpdate(update: CodeMirror.ViewUpdate): void {
if (!update.changes.empty) {
// If the document changed, adjust known breakpoint positions
// for that change
for (const breakpointDesc of this.breakpoints) {
breakpointDesc.position = update.changes.mapPos(breakpointDesc.position);
}
}
}
private onWheel(event: WheelEvent): void {
if (this.executionLocation && UI.KeyboardShortcut.KeyboardShortcut.eventHasCtrlEquivalentKey(event)) {
event.preventDefault();
}
}
private onKeyDown(event: KeyboardEvent): boolean {
const ctrlDown = UI.KeyboardShortcut.KeyboardShortcut.eventHasCtrlEquivalentKey(event);
if (!ctrlDown) {
this.setControlDown(false);
}
if (event.key === Platform.KeyboardUtilities.ESCAPE_KEY) {
if (this.popoverHelper && this.popoverHelper.isPopoverVisible()) {
this.popoverHelper.hidePopover();
event.consume();
return true;
}
}
if (ctrlDown && this.executionLocation) {
this.setControlDown(true);
}
return false;
}
private onMouseMove(event: MouseEvent): void {
if (this.executionLocation && this.controlDown &&
UI.KeyboardShortcut.KeyboardShortcut.eventHasCtrlEquivalentKey(event)) {
if (!this.continueToLocations) {
void this.showContinueToLocations();
}
}
}
private onMouseDown(event: MouseEvent): void {
if (!this.executionLocation || !UI.KeyboardShortcut.KeyboardShortcut.eventHasCtrlEquivalentKey(event)) {
return;
}
if (!this.continueToLocations || !this.editor) {
return;
}
event.consume();
const textPosition = this.editor.editor.posAtCoords(event);
if (textPosition === null) {
return;
}
for (const {from, to, click} of this.continueToLocations) {
if (from <= textPosition && to >= textPosition) {
click();
break;
}
}
}
private onBlur(_event: Event): void {
this.setControlDown(false);
}
private onKeyUp(_event: KeyboardEvent): void {
this.setControlDown(false);
}
private setControlDown(state: boolean): void {
if (state !== this.controlDown) {
this.controlDown = state;
clearTimeout(this.controlTimeout);
this.controlTimeout = undefined;
if (state && this.executionLocation) {
this.controlTimeout = window.setTimeout(() => {
if (this.executionLocation && this.controlDown) {
void this.showContinueToLocations();
}
}, 150);
} else {
this.clearContinueToLocations();
}
}
}
private editBreakpointCondition(breakpointEditRequest: BreakpointEditRequest): void {
const {line, breakpoint, location, isLogpoint} = breakpointEditRequest;
if (breakpoint?.isRemoved) {
// This method can get called for stale breakpoints, e.g. via the revealer.
// In that case we don't show the edit dialog as to not resurrect the breakpoint
// unintentionally.
return;
}
this.#scheduledFinishingActiveDialog = false;
const isRepeatedEditRequest = this.#activeBreakpointEditRequest &&
isSameEditRequest(this.#activeBreakpointEditRequest, breakpointEditRequest);
if (isRepeatedEditRequest) {
// Do not re-show the same edit dialog, instead use the already open one.
return;
}
if (this.activeBreakpointDialog) {
// If this a request to edit a different dialog, make sure to close the current active one
// to avoid showing two dialogs at the same time.
this.activeBreakpointDialog.saveAndFinish();
}
const editor = this.editor as TextEditor.TextEditor.TextEditor;
const oldCondition = breakpoint ? breakpoint.condition() : '';
const isLogpointForDialog = breakpoint?.isLogpoint() ?? Boolean(isLogpoint);
const decorationElement = document.createElement('div');
const compartment = new CodeMirror.Compartment();
const dialog = new BreakpointEditDialog(line.number - 1, oldCondition, isLogpointForDialog, async result => {
this.activeBreakpointDialog = null;
this.#activeBreakpointEditRequest = undefined;
dialog.detach();
editor.dispatch({effects: compartment.reconfigure([])});
if (!result.committed) {
SourceComponents.BreakpointsView.BreakpointsSidebarController.instance().breakpointEditFinished(
breakpoint, false);
return;
}
SourceComponents.BreakpointsView.BreakpointsSidebarController.instance().breakpointEditFinished(
breakpoint, oldCondition !== result.condition);
recordBreakpointWithConditionAdded(result);
if (breakpoint) {
breakpoint.setCondition(result.condition, result.isLogpoint);
} else if (location) {
await this.setBreakpoint(
location.lineNumber, location.columnNumber, result.condition, /* enabled */ true, result.isLogpoint);
} else {
await this.createNewBreakpoint(line, result.condition, /* enabled */ true, result.isLogpoint);
}
});
editor.dispatch({
effects: CodeMirror.StateEffect.appendConfig.of(compartment.of(CodeMirror.EditorView.decorations.of(
CodeMirror.Decoration.set([CodeMirror.Decoration
.widget({
block: true, widget: new class extends CodeMirror.WidgetType {
toDOM(): HTMLElement {
return decorationElement;
}
}(),
side: 1,
})
.range(line.to)])))),
});
dialog.element.addEventListener('blur', async event => {
if (!event.relatedTarget ||
(event.relatedTarget && !(event.relatedTarget as Node).isSelfOrDescendant(dialog.element))) {
this.#scheduledFinishingActiveDialog = true;
// Debounce repeated clicks on opening the edit dialog. Wait for a short amount of time
// in order to see whether we get a request to open the exact same dialog again.
setTimeout(() => {
if (this.activeBreakpointDialog === dialog) {
if (this.#scheduledFinishingActiveDialog) {
dialog.saveAndFinish();
this.#scheduledFinishingActiveDialog = false;
} else {
dialog.focusEditor();
}
}
}, 200);
}
}, true);
dialog.markAsExternallyManaged();
dialog.show(decorationElement);
dialog.focusEditor();
this.activeBreakpointDialog = dialog;
this.#activeBreakpointEditRequest = breakpointEditRequest;
// This counts new conditional breakpoints or logpoints that are added.
function recordBreakpointWithConditionAdded(result: BreakpointEditDialogResult): void {
const {condition: newCondition, isLogpoint} = result;
const isConditionalBreakpoint = newCondition.length !== 0 && !isLogpoint;
const wasLogpoint = breakpoint?.isLogpoint();
const wasConditionalBreakpoint = oldCondition && oldCondition.length !== 0 && !wasLogpoint;
if (isLogpoint && !wasLogpoint) {
Host.userMetrics.breakpointWithConditionAdded(Host.UserMetrics.BreakpointWithConditionAdded.Logpoint);
} else if (isConditionalBreakpoint && !wasConditionalBreakpoint) {
Host.userMetrics.breakpointWithConditionAdded(
Host.UserMetrics.BreakpointWithConditionAdded.ConditionalBreakpoint);
}
}
function isSameEditRequest(editA: BreakpointEditRequest, editB: BreakpointEditRequest): boolean {
if (editA.line.number !== editB.line.number) {
return false;
}
if (editA.line.from !== editB.line.from) {
return false;
}
if (editA.line.text !== editB.line.text) {
return false;
}
if (editA.breakpoint !== editB.breakpoint) {
return false;
}
if (editA.location !== editB.location) {
return false;
}
return editA.isLogpoint === editB.isLogpoint;
}
}
// Show widgets with variable's values after lines that mention the
// variables, if the debugger is paused in this file.
private async updateValueDecorations(): Promise<void> {
if (!this.editor) {