Web Inspector: simplify WebInspector with WI
[WebKit-https.git] / Source / WebInspectorUI / UserInterface / Controllers / DebuggerManager.js
1 /*
2  * Copyright (C) 2013-2016 Apple Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
14  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
15  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
17  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
18  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
19  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
20  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
21  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
22  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
23  * THE POSSIBILITY OF SUCH DAMAGE.
24  */
25
26 WI.DebuggerManager = class DebuggerManager extends WI.Object
27 {
28     constructor()
29     {
30         super();
31
32         DebuggerAgent.enable();
33
34         WI.notifications.addEventListener(WI.Notification.DebugUIEnabledDidChange, this._debugUIEnabledDidChange, this);
35
36         WI.Breakpoint.addEventListener(WI.Breakpoint.Event.DisplayLocationDidChange, this._breakpointDisplayLocationDidChange, this);
37         WI.Breakpoint.addEventListener(WI.Breakpoint.Event.DisabledStateDidChange, this._breakpointDisabledStateDidChange, this);
38         WI.Breakpoint.addEventListener(WI.Breakpoint.Event.ConditionDidChange, this._breakpointEditablePropertyDidChange, this);
39         WI.Breakpoint.addEventListener(WI.Breakpoint.Event.IgnoreCountDidChange, this._breakpointEditablePropertyDidChange, this);
40         WI.Breakpoint.addEventListener(WI.Breakpoint.Event.AutoContinueDidChange, this._breakpointEditablePropertyDidChange, this);
41         WI.Breakpoint.addEventListener(WI.Breakpoint.Event.ActionsDidChange, this._breakpointEditablePropertyDidChange, this);
42
43         WI.timelineManager.addEventListener(WI.TimelineManager.Event.CapturingWillStart, this._timelineCapturingWillStart, this);
44         WI.timelineManager.addEventListener(WI.TimelineManager.Event.CapturingStopped, this._timelineCapturingStopped, this);
45
46         WI.targetManager.addEventListener(WI.TargetManager.Event.TargetRemoved, this._targetRemoved, this);
47
48         WI.Frame.addEventListener(WI.Frame.Event.MainResourceDidChange, this._mainResourceDidChange, this);
49
50         this._breakpointsSetting = new WI.Setting("breakpoints", []);
51         this._breakpointsEnabledSetting = new WI.Setting("breakpoints-enabled", true);
52         this._allExceptionsBreakpointEnabledSetting = new WI.Setting("break-on-all-exceptions", false);
53         this._allUncaughtExceptionsBreakpointEnabledSetting = new WI.Setting("break-on-all-uncaught-exceptions", false);
54         this._assertionsBreakpointEnabledSetting = new WI.Setting("break-on-assertions", false);
55         this._asyncStackTraceDepthSetting = new WI.Setting("async-stack-trace-depth", 200);
56
57         let specialBreakpointLocation = new WI.SourceCodeLocation(null, Infinity, Infinity);
58
59         this._allExceptionsBreakpoint = new WI.Breakpoint(specialBreakpointLocation, !this._allExceptionsBreakpointEnabledSetting.value);
60         this._allExceptionsBreakpoint.resolved = true;
61
62         this._allUncaughtExceptionsBreakpoint = new WI.Breakpoint(specialBreakpointLocation, !this._allUncaughtExceptionsBreakpointEnabledSetting.value);
63
64         this._assertionsBreakpoint = new WI.Breakpoint(specialBreakpointLocation, !this._assertionsBreakpointEnabledSetting.value);
65         this._assertionsBreakpoint.resolved = true;
66
67         this._breakpoints = [];
68         this._breakpointContentIdentifierMap = new Map;
69         this._breakpointScriptIdentifierMap = new Map;
70         this._breakpointIdMap = new Map;
71
72         this._breakOnExceptionsState = "none";
73         this._updateBreakOnExceptionsState();
74
75         this._nextBreakpointActionIdentifier = 1;
76
77         this._activeCallFrame = null;
78
79         this._internalWebKitScripts = [];
80         this._targetDebuggerDataMap = new Map;
81         this._targetDebuggerDataMap.set(WI.mainTarget, new WI.DebuggerData(WI.mainTarget));
82
83         // Restore the correct breakpoints enabled setting if Web Inspector had
84         // previously been left in a state where breakpoints were temporarily disabled.
85         this._temporarilyDisabledBreakpointsRestoreSetting = new WI.Setting("temporarily-disabled-breakpoints-restore", null);
86         if (this._temporarilyDisabledBreakpointsRestoreSetting.value !== null) {
87             this._breakpointsEnabledSetting.value = this._temporarilyDisabledBreakpointsRestoreSetting.value;
88             this._temporarilyDisabledBreakpointsRestoreSetting.value = null;
89         }
90
91         DebuggerAgent.setBreakpointsActive(this._breakpointsEnabledSetting.value);
92         DebuggerAgent.setPauseOnExceptions(this._breakOnExceptionsState);
93
94         // COMPATIBILITY (iOS 10): DebuggerAgent.setPauseOnAssertions did not exist yet.
95         if (DebuggerAgent.setPauseOnAssertions)
96             DebuggerAgent.setPauseOnAssertions(this._assertionsBreakpointEnabledSetting.value);
97
98         // COMPATIBILITY (iOS 10): Debugger.setAsyncStackTraceDepth did not exist yet.
99         if (DebuggerAgent.setAsyncStackTraceDepth)
100             DebuggerAgent.setAsyncStackTraceDepth(this._asyncStackTraceDepthSetting.value);
101
102         this._ignoreBreakpointDisplayLocationDidChangeEvent = false;
103
104         function restoreBreakpointsSoon() {
105             this._restoringBreakpoints = true;
106             for (let cookie of this._breakpointsSetting.value)
107                 this.addBreakpoint(new WI.Breakpoint(cookie));
108             this._restoringBreakpoints = false;
109         }
110
111         // Ensure that all managers learn about restored breakpoints,
112         // regardless of their initialization order.
113         setTimeout(restoreBreakpointsSoon.bind(this), 0);
114     }
115
116     // Public
117
118     get paused()
119     {
120         for (let [target, targetData] of this._targetDebuggerDataMap) {
121             if (targetData.paused)
122                 return true;
123         }
124
125         return false;
126     }
127
128     get activeCallFrame()
129     {
130         return this._activeCallFrame;
131     }
132
133     set activeCallFrame(callFrame)
134     {
135         if (callFrame === this._activeCallFrame)
136             return;
137
138         this._activeCallFrame = callFrame || null;
139
140         this.dispatchEventToListeners(WI.DebuggerManager.Event.ActiveCallFrameDidChange);
141     }
142
143     dataForTarget(target)
144     {
145         let targetData = this._targetDebuggerDataMap.get(target);
146         if (targetData)
147             return targetData;
148
149         targetData = new WI.DebuggerData(target);
150         this._targetDebuggerDataMap.set(target, targetData);
151         return targetData;
152     }
153
154     get allExceptionsBreakpoint()
155     {
156         return this._allExceptionsBreakpoint;
157     }
158
159     get allUncaughtExceptionsBreakpoint()
160     {
161         return this._allUncaughtExceptionsBreakpoint;
162     }
163
164     get assertionsBreakpoint()
165     {
166         return this._assertionsBreakpoint;
167     }
168
169     get breakpoints()
170     {
171         return this._breakpoints;
172     }
173
174     breakpointForIdentifier(id)
175     {
176         return this._breakpointIdMap.get(id) || null;
177     }
178
179     breakpointsForSourceCode(sourceCode)
180     {
181         console.assert(sourceCode instanceof WI.Resource || sourceCode instanceof WI.Script);
182
183         if (sourceCode instanceof WI.SourceMapResource) {
184             let originalSourceCodeBreakpoints = this.breakpointsForSourceCode(sourceCode.sourceMap.originalSourceCode);
185             return originalSourceCodeBreakpoints.filter(function(breakpoint) {
186                 return breakpoint.sourceCodeLocation.displaySourceCode === sourceCode;
187             });
188         }
189
190         let contentIdentifierBreakpoints = this._breakpointContentIdentifierMap.get(sourceCode.contentIdentifier);
191         if (contentIdentifierBreakpoints) {
192             this._associateBreakpointsWithSourceCode(contentIdentifierBreakpoints, sourceCode);
193             return contentIdentifierBreakpoints;
194         }
195
196         if (sourceCode instanceof WI.Script) {
197             let scriptIdentifierBreakpoints = this._breakpointScriptIdentifierMap.get(sourceCode.id);
198             if (scriptIdentifierBreakpoints) {
199                 this._associateBreakpointsWithSourceCode(scriptIdentifierBreakpoints, sourceCode);
200                 return scriptIdentifierBreakpoints;
201             }
202         }
203
204         return [];
205     }
206
207     breakpointForSourceCodeLocation(sourceCodeLocation)
208     {
209         console.assert(sourceCodeLocation instanceof WI.SourceCodeLocation);
210
211         for (let breakpoint of this.breakpointsForSourceCode(sourceCodeLocation.sourceCode)) {
212             if (breakpoint.sourceCodeLocation.isEqual(sourceCodeLocation))
213                 return breakpoint;
214         }
215
216         return null;
217     }
218
219     isBreakpointRemovable(breakpoint)
220     {
221         return breakpoint !== this._allExceptionsBreakpoint
222             && breakpoint !== this._allUncaughtExceptionsBreakpoint
223             && breakpoint !== this._assertionsBreakpoint;
224     }
225
226     isBreakpointEditable(breakpoint)
227     {
228         return this.isBreakpointRemovable(breakpoint);
229     }
230
231     get breakpointsEnabled()
232     {
233         return this._breakpointsEnabledSetting.value;
234     }
235
236     set breakpointsEnabled(enabled)
237     {
238         if (this._breakpointsEnabledSetting.value === enabled)
239             return;
240
241         console.assert(!(enabled && this.breakpointsDisabledTemporarily), "Should not enable breakpoints when we are temporarily disabling breakpoints.");
242         if (enabled && this.breakpointsDisabledTemporarily)
243             return;
244
245         this._breakpointsEnabledSetting.value = enabled;
246
247         this._updateBreakOnExceptionsState();
248
249         for (let target of WI.targets) {
250             target.DebuggerAgent.setBreakpointsActive(enabled);
251             target.DebuggerAgent.setPauseOnExceptions(this._breakOnExceptionsState);
252         }
253
254         this.dispatchEventToListeners(WI.DebuggerManager.Event.BreakpointsEnabledDidChange);
255     }
256
257     get breakpointsDisabledTemporarily()
258     {
259         return this._temporarilyDisabledBreakpointsRestoreSetting.value !== null;
260     }
261
262     scriptForIdentifier(id, target)
263     {
264         console.assert(target instanceof WI.Target);
265         return this.dataForTarget(target).scriptForIdentifier(id);
266     }
267
268     scriptsForURL(url, target)
269     {
270         // FIXME: This may not be safe. A Resource's URL may differ from a Script's URL.
271         console.assert(target instanceof WI.Target);
272         return this.dataForTarget(target).scriptsForURL(url);
273     }
274
275     get searchableScripts()
276     {
277         return this.knownNonResourceScripts.filter((script) => !!script.contentIdentifier);
278     }
279
280     get knownNonResourceScripts()
281     {
282         let knownScripts = [];
283
284         for (let [target, targetData] of this._targetDebuggerDataMap) {
285             for (let script of targetData.scripts) {
286                 if (script.resource)
287                     continue;
288                 if (!WI.isDebugUIEnabled() && isWebKitInternalScript(script.sourceURL))
289                     continue;
290                 knownScripts.push(script);
291             }
292         }
293
294         return knownScripts;
295     }
296
297     get asyncStackTraceDepth()
298     {
299         return this._asyncStackTraceDepthSetting.value;
300     }
301
302     set asyncStackTraceDepth(x)
303     {
304         if (this._asyncStackTraceDepthSetting.value === x)
305             return;
306
307         this._asyncStackTraceDepthSetting.value = x;
308
309         for (let target of WI.targets)
310             target.DebuggerAgent.setAsyncStackTraceDepth(this._asyncStackTraceDepthSetting.value);
311     }
312
313     pause()
314     {
315         if (this.paused)
316             return Promise.resolve();
317
318         this.dispatchEventToListeners(WI.DebuggerManager.Event.WaitingToPause);
319
320         let listener = new WI.EventListener(this, true);
321
322         let managerResult = new Promise(function(resolve, reject) {
323             listener.connect(WI.debuggerManager, WI.DebuggerManager.Event.Paused, resolve);
324         });
325
326         let promises = [];
327         for (let [target, targetData] of this._targetDebuggerDataMap)
328             promises.push(targetData.pauseIfNeeded());
329
330         return Promise.all([managerResult, ...promises]);
331     }
332
333     resume()
334     {
335         if (!this.paused)
336             return Promise.resolve();
337
338         let listener = new WI.EventListener(this, true);
339
340         let managerResult = new Promise(function(resolve, reject) {
341             listener.connect(WI.debuggerManager, WI.DebuggerManager.Event.Resumed, resolve);
342         });
343
344         let promises = [];
345         for (let [target, targetData] of this._targetDebuggerDataMap)
346             promises.push(targetData.resumeIfNeeded());
347
348         return Promise.all([managerResult, ...promises]);
349     }
350
351     stepOver()
352     {
353         if (!this.paused)
354             return Promise.reject(new Error("Cannot step over because debugger is not paused."));
355
356         let listener = new WI.EventListener(this, true);
357
358         let managerResult = new Promise(function(resolve, reject) {
359             listener.connect(WI.debuggerManager, WI.DebuggerManager.Event.ActiveCallFrameDidChange, resolve);
360         });
361
362         let protocolResult = this._activeCallFrame.target.DebuggerAgent.stepOver()
363             .catch(function(error) {
364                 listener.disconnect();
365                 console.error("DebuggerManager.stepOver failed: ", error);
366                 throw error;
367             });
368
369         return Promise.all([managerResult, protocolResult]);
370     }
371
372     stepInto()
373     {
374         if (!this.paused)
375             return Promise.reject(new Error("Cannot step into because debugger is not paused."));
376
377         let listener = new WI.EventListener(this, true);
378
379         let managerResult = new Promise(function(resolve, reject) {
380             listener.connect(WI.debuggerManager, WI.DebuggerManager.Event.ActiveCallFrameDidChange, resolve);
381         });
382
383         let protocolResult = this._activeCallFrame.target.DebuggerAgent.stepInto()
384             .catch(function(error) {
385                 listener.disconnect();
386                 console.error("DebuggerManager.stepInto failed: ", error);
387                 throw error;
388             });
389
390         return Promise.all([managerResult, protocolResult]);
391     }
392
393     stepOut()
394     {
395         if (!this.paused)
396             return Promise.reject(new Error("Cannot step out because debugger is not paused."));
397
398         let listener = new WI.EventListener(this, true);
399
400         let managerResult = new Promise(function(resolve, reject) {
401             listener.connect(WI.debuggerManager, WI.DebuggerManager.Event.ActiveCallFrameDidChange, resolve);
402         });
403
404         let protocolResult = this._activeCallFrame.target.DebuggerAgent.stepOut()
405             .catch(function(error) {
406                 listener.disconnect();
407                 console.error("DebuggerManager.stepOut failed: ", error);
408                 throw error;
409             });
410
411         return Promise.all([managerResult, protocolResult]);
412     }
413
414     continueUntilNextRunLoop(target)
415     {
416         return this.dataForTarget(target).continueUntilNextRunLoop();
417     }
418
419     continueToLocation(script, lineNumber, columnNumber)
420     {
421         return script.target.DebuggerAgent.continueToLocation({scriptId: script.id, lineNumber, columnNumber});
422     }
423
424     addBreakpoint(breakpoint, shouldSpeculativelyResolve)
425     {
426         console.assert(breakpoint instanceof WI.Breakpoint);
427         if (!breakpoint)
428             return;
429
430         if (breakpoint.contentIdentifier) {
431             let contentIdentifierBreakpoints = this._breakpointContentIdentifierMap.get(breakpoint.contentIdentifier);
432             if (!contentIdentifierBreakpoints) {
433                 contentIdentifierBreakpoints = [];
434                 this._breakpointContentIdentifierMap.set(breakpoint.contentIdentifier, contentIdentifierBreakpoints);
435             }
436             contentIdentifierBreakpoints.push(breakpoint);
437         }
438
439         if (breakpoint.scriptIdentifier) {
440             let scriptIdentifierBreakpoints = this._breakpointScriptIdentifierMap.get(breakpoint.scriptIdentifier);
441             if (!scriptIdentifierBreakpoints) {
442                 scriptIdentifierBreakpoints = [];
443                 this._breakpointScriptIdentifierMap.set(breakpoint.scriptIdentifier, scriptIdentifierBreakpoints);
444             }
445             scriptIdentifierBreakpoints.push(breakpoint);
446         }
447
448         this._breakpoints.push(breakpoint);
449
450         if (!breakpoint.disabled) {
451             const specificTarget = undefined;
452             this._setBreakpoint(breakpoint, specificTarget, () => {
453                 if (shouldSpeculativelyResolve)
454                     breakpoint.resolved = true;
455             });
456         }
457
458         this._saveBreakpoints();
459
460         this.dispatchEventToListeners(WI.DebuggerManager.Event.BreakpointAdded, {breakpoint});
461     }
462
463     removeBreakpoint(breakpoint)
464     {
465         console.assert(breakpoint instanceof WI.Breakpoint);
466         if (!breakpoint)
467             return;
468
469         console.assert(this.isBreakpointRemovable(breakpoint));
470         if (!this.isBreakpointRemovable(breakpoint))
471             return;
472
473         this._breakpoints.remove(breakpoint);
474
475         if (breakpoint.identifier)
476             this._removeBreakpoint(breakpoint);
477
478         if (breakpoint.contentIdentifier) {
479             let contentIdentifierBreakpoints = this._breakpointContentIdentifierMap.get(breakpoint.contentIdentifier);
480             if (contentIdentifierBreakpoints) {
481                 contentIdentifierBreakpoints.remove(breakpoint);
482                 if (!contentIdentifierBreakpoints.length)
483                     this._breakpointContentIdentifierMap.delete(breakpoint.contentIdentifier);
484             }
485         }
486
487         if (breakpoint.scriptIdentifier) {
488             let scriptIdentifierBreakpoints = this._breakpointScriptIdentifierMap.get(breakpoint.scriptIdentifier);
489             if (scriptIdentifierBreakpoints) {
490                 scriptIdentifierBreakpoints.remove(breakpoint);
491                 if (!scriptIdentifierBreakpoints.length)
492                     this._breakpointScriptIdentifierMap.delete(breakpoint.scriptIdentifier);
493             }
494         }
495
496         // Disable the breakpoint first, so removing actions doesn't re-add the breakpoint.
497         breakpoint.disabled = true;
498         breakpoint.clearActions();
499
500         this._saveBreakpoints();
501
502         this.dispatchEventToListeners(WI.DebuggerManager.Event.BreakpointRemoved, {breakpoint});
503     }
504
505     nextBreakpointActionIdentifier()
506     {
507         return this._nextBreakpointActionIdentifier++;
508     }
509
510     initializeTarget(target)
511     {
512         let DebuggerAgent = target.DebuggerAgent;
513         let targetData = this.dataForTarget(target);
514
515         // Initialize global state.
516         DebuggerAgent.enable();
517         DebuggerAgent.setBreakpointsActive(this._breakpointsEnabledSetting.value);
518         DebuggerAgent.setPauseOnAssertions(this._assertionsBreakpointEnabledSetting.value);
519         DebuggerAgent.setPauseOnExceptions(this._breakOnExceptionsState);
520         DebuggerAgent.setAsyncStackTraceDepth(this._asyncStackTraceDepthSetting.value);
521
522         if (this.paused)
523             targetData.pauseIfNeeded();
524
525         // Initialize breakpoints.
526         this._restoringBreakpoints = true;
527         for (let breakpoint of this._breakpoints) {
528             if (breakpoint.disabled)
529                 continue;
530             if (!breakpoint.contentIdentifier)
531                 continue;
532             this._setBreakpoint(breakpoint, target);
533         }
534         this._restoringBreakpoints = false;
535     }
536
537     // Protected (Called from WI.DebuggerObserver)
538
539     breakpointResolved(target, breakpointIdentifier, location)
540     {
541         // Called from WI.DebuggerObserver.
542
543         let breakpoint = this._breakpointIdMap.get(breakpointIdentifier);
544         console.assert(breakpoint);
545         if (!breakpoint)
546             return;
547
548         console.assert(breakpoint.identifier === breakpointIdentifier);
549
550         if (!breakpoint.sourceCodeLocation.sourceCode) {
551             let sourceCodeLocation = this._sourceCodeLocationFromPayload(target, location);
552             breakpoint.sourceCodeLocation.sourceCode = sourceCodeLocation.sourceCode;
553         }
554
555         breakpoint.resolved = true;
556     }
557
558     reset()
559     {
560         // Called from WI.DebuggerObserver.
561
562         let wasPaused = this.paused;
563
564         WI.Script.resetUniqueDisplayNameNumbers();
565
566         this._internalWebKitScripts = [];
567         this._targetDebuggerDataMap.clear();
568
569         this._ignoreBreakpointDisplayLocationDidChangeEvent = true;
570
571         // Mark all the breakpoints as unresolved. They will be reported as resolved when
572         // breakpointResolved is called as the page loads.
573         for (let breakpoint of this._breakpoints) {
574             breakpoint.resolved = false;
575             if (breakpoint.sourceCodeLocation.sourceCode)
576                 breakpoint.sourceCodeLocation.sourceCode = null;
577         }
578
579         this._ignoreBreakpointDisplayLocationDidChangeEvent = false;
580
581         this.dispatchEventToListeners(WI.DebuggerManager.Event.ScriptsCleared);
582
583         if (wasPaused)
584             this.dispatchEventToListeners(WI.DebuggerManager.Event.Resumed);
585     }
586
587     debuggerDidPause(target, callFramesPayload, reason, data, asyncStackTracePayload)
588     {
589         // Called from WI.DebuggerObserver.
590
591         if (this._delayedResumeTimeout) {
592             clearTimeout(this._delayedResumeTimeout);
593             this._delayedResumeTimeout = undefined;
594         }
595
596         let wasPaused = this.paused;
597         let targetData = this._targetDebuggerDataMap.get(target);
598
599         let callFrames = [];
600         let pauseReason = this._pauseReasonFromPayload(reason);
601         let pauseData = data || null;
602
603         for (var i = 0; i < callFramesPayload.length; ++i) {
604             var callFramePayload = callFramesPayload[i];
605             var sourceCodeLocation = this._sourceCodeLocationFromPayload(target, callFramePayload.location);
606             // FIXME: There may be useful call frames without a source code location (native callframes), should we include them?
607             if (!sourceCodeLocation)
608                 continue;
609             if (!sourceCodeLocation.sourceCode)
610                 continue;
611
612             // Exclude the case where the call frame is in the inspector code.
613             if (!WI.isDebugUIEnabled() && isWebKitInternalScript(sourceCodeLocation.sourceCode.sourceURL))
614                 continue;
615
616             let scopeChain = this._scopeChainFromPayload(target, callFramePayload.scopeChain);
617             let callFrame = WI.CallFrame.fromDebuggerPayload(target, callFramePayload, scopeChain, sourceCodeLocation);
618             callFrames.push(callFrame);
619         }
620
621         let activeCallFrame = callFrames[0];
622
623         if (!activeCallFrame) {
624             // FIXME: This may not be safe for multiple threads/targets.
625             // This indicates we were pausing in internal scripts only (Injected Scripts).
626             // Just resume and skip past this pause. We should be fixing the backend to
627             // not send such pauses.
628             if (wasPaused)
629                 target.DebuggerAgent.continueUntilNextRunLoop();
630             else
631                 target.DebuggerAgent.resume();
632             this._didResumeInternal(target);
633             return;
634         }
635
636         let asyncStackTrace = WI.StackTrace.fromPayload(target, asyncStackTracePayload);
637         targetData.updateForPause(callFrames, pauseReason, pauseData, asyncStackTrace);
638
639         // Pause other targets because at least one target has paused.
640         // FIXME: Should this be done on the backend?
641         for (let [otherTarget, otherTargetData] of this._targetDebuggerDataMap)
642             otherTargetData.pauseIfNeeded();
643
644         let activeCallFrameDidChange = this._activeCallFrame && this._activeCallFrame.target === target;
645         if (activeCallFrameDidChange)
646             this._activeCallFrame = activeCallFrame;
647         else if (!wasPaused) {
648             this._activeCallFrame = activeCallFrame;
649             activeCallFrameDidChange = true;
650         }
651
652         if (!wasPaused)
653             this.dispatchEventToListeners(WI.DebuggerManager.Event.Paused);
654
655         this.dispatchEventToListeners(WI.DebuggerManager.Event.CallFramesDidChange, {target});
656
657         if (activeCallFrameDidChange)
658             this.dispatchEventToListeners(WI.DebuggerManager.Event.ActiveCallFrameDidChange);
659     }
660
661     debuggerDidResume(target)
662     {
663         // Called from WI.DebuggerObserver.
664
665         // COMPATIBILITY (iOS 10): Debugger.resumed event was ambiguous. When stepping
666         // we would receive a Debugger.resumed and we would not know if it really meant
667         // the backend resumed or would pause again due to a step. Legacy backends wait
668         // 50ms, and treat it as a real resume if we haven't paused in that time frame.
669         // This delay ensures the user interface does not flash between brief steps
670         // or successive breakpoints.
671         if (!DebuggerAgent.setPauseOnAssertions) {
672             this._delayedResumeTimeout = setTimeout(this._didResumeInternal.bind(this, target), 50);
673             return;
674         }
675
676         this._didResumeInternal(target);
677     }
678
679     playBreakpointActionSound(breakpointActionIdentifier)
680     {
681         // Called from WI.DebuggerObserver.
682
683         InspectorFrontendHost.beep();
684     }
685
686     scriptDidParse(target, scriptIdentifier, url, startLine, startColumn, endLine, endColumn, isModule, isContentScript, sourceURL, sourceMapURL)
687     {
688         // Called from WI.DebuggerObserver.
689
690         // Don't add the script again if it is already known.
691         let targetData = this.dataForTarget(target);
692         let existingScript = targetData.scriptForIdentifier(scriptIdentifier);
693         if (existingScript) {
694             console.assert(existingScript.url === (url || null));
695             console.assert(existingScript.range.startLine === startLine);
696             console.assert(existingScript.range.startColumn === startColumn);
697             console.assert(existingScript.range.endLine === endLine);
698             console.assert(existingScript.range.endColumn === endColumn);
699             return;
700         }
701
702         if (!WI.isDebugUIEnabled() && isWebKitInternalScript(sourceURL))
703             return;
704
705         let range = new WI.TextRange(startLine, startColumn, endLine, endColumn);
706         let sourceType = isModule ? WI.Script.SourceType.Module : WI.Script.SourceType.Program;
707         let script = new WI.Script(target, scriptIdentifier, range, url, sourceType, isContentScript, sourceURL, sourceMapURL);
708
709         targetData.addScript(script);
710
711         if (target !== WI.mainTarget && !target.mainResource) {
712             // FIXME: <https://webkit.org/b/164427> Web Inspector: WorkerTarget's mainResource should be a Resource not a Script
713             // We make the main resource of a WorkerTarget the Script instead of the Resource
714             // because the frontend may not be informed of the Resource. We should guarantee
715             // the frontend is informed of the Resource.
716             if (script.url === target.name) {
717                 target.mainResource = script;
718                 if (script.resource)
719                     target.resourceCollection.remove(script.resource);
720             }
721         }
722
723         if (isWebKitInternalScript(script.sourceURL)) {
724             this._internalWebKitScripts.push(script);
725             if (!WI.isDebugUIEnabled())
726                 return;
727         }
728
729         // Console expressions are not added to the UI by default.
730         if (isWebInspectorConsoleEvaluationScript(script.sourceURL))
731             return;
732
733         this.dispatchEventToListeners(WI.DebuggerManager.Event.ScriptAdded, {script});
734
735         if (target !== WI.mainTarget && !script.isMainResource() && !script.resource)
736             target.addScript(script);
737     }
738
739     // Private
740
741     _sourceCodeLocationFromPayload(target, payload)
742     {
743         let targetData = this.dataForTarget(target);
744         let script = targetData.scriptForIdentifier(payload.scriptId);
745         if (!script)
746             return null;
747
748         return script.createSourceCodeLocation(payload.lineNumber, payload.columnNumber);
749     }
750
751     _scopeChainFromPayload(target, payload)
752     {
753         let scopeChain = [];
754         for (let i = 0; i < payload.length; ++i)
755             scopeChain.push(this._scopeChainNodeFromPayload(target, payload[i]));
756         return scopeChain;
757     }
758
759     _scopeChainNodeFromPayload(target, payload)
760     {
761         var type = null;
762         switch (payload.type) {
763         case DebuggerAgent.ScopeType.Global:
764             type = WI.ScopeChainNode.Type.Global;
765             break;
766         case DebuggerAgent.ScopeType.With:
767             type = WI.ScopeChainNode.Type.With;
768             break;
769         case DebuggerAgent.ScopeType.Closure:
770             type = WI.ScopeChainNode.Type.Closure;
771             break;
772         case DebuggerAgent.ScopeType.Catch:
773             type = WI.ScopeChainNode.Type.Catch;
774             break;
775         case DebuggerAgent.ScopeType.FunctionName:
776             type = WI.ScopeChainNode.Type.FunctionName;
777             break;
778         case DebuggerAgent.ScopeType.NestedLexical:
779             type = WI.ScopeChainNode.Type.Block;
780             break;
781         case DebuggerAgent.ScopeType.GlobalLexicalEnvironment:
782             type = WI.ScopeChainNode.Type.GlobalLexicalEnvironment;
783             break;
784
785         // COMPATIBILITY (iOS 9): Debugger.ScopeType.Local used to be provided by the backend.
786         // Newer backends no longer send this enum value, it should be computed by the frontend.
787         // Map this to "Closure" type. The frontend can recalculate this when needed.
788         case DebuggerAgent.ScopeType.Local:
789             type = WI.ScopeChainNode.Type.Closure;
790             break;
791
792         default:
793             console.error("Unknown type: " + payload.type);
794         }
795
796         let object = WI.RemoteObject.fromPayload(payload.object, target);
797         return new WI.ScopeChainNode(type, [object], payload.name, payload.location, payload.empty);
798     }
799
800     _pauseReasonFromPayload(payload)
801     {
802         // FIXME: Handle other backend pause reasons.
803         switch (payload) {
804         case DebuggerAgent.PausedReason.Assert:
805             return WI.DebuggerManager.PauseReason.Assertion;
806         case DebuggerAgent.PausedReason.Breakpoint:
807             return WI.DebuggerManager.PauseReason.Breakpoint;
808         case DebuggerAgent.PausedReason.CSPViolation:
809             return WI.DebuggerManager.PauseReason.CSPViolation;
810         case DebuggerAgent.PausedReason.DOM:
811             return WI.DebuggerManager.PauseReason.DOM;
812         case DebuggerAgent.PausedReason.DebuggerStatement:
813             return WI.DebuggerManager.PauseReason.DebuggerStatement;
814         case DebuggerAgent.PausedReason.Exception:
815             return WI.DebuggerManager.PauseReason.Exception;
816         case DebuggerAgent.PausedReason.PauseOnNextStatement:
817             return WI.DebuggerManager.PauseReason.PauseOnNextStatement;
818         case DebuggerAgent.PausedReason.XHR:
819             return WI.DebuggerManager.PauseReason.XHR;
820         default:
821             return WI.DebuggerManager.PauseReason.Other;
822         }
823     }
824
825     _debuggerBreakpointActionType(type)
826     {
827         switch (type) {
828         case WI.BreakpointAction.Type.Log:
829             return DebuggerAgent.BreakpointActionType.Log;
830         case WI.BreakpointAction.Type.Evaluate:
831             return DebuggerAgent.BreakpointActionType.Evaluate;
832         case WI.BreakpointAction.Type.Sound:
833             return DebuggerAgent.BreakpointActionType.Sound;
834         case WI.BreakpointAction.Type.Probe:
835             return DebuggerAgent.BreakpointActionType.Probe;
836         default:
837             console.assert(false);
838             return DebuggerAgent.BreakpointActionType.Log;
839         }
840     }
841
842     _debuggerBreakpointOptions(breakpoint)
843     {
844         const templatePlaceholderRegex = /\$\{.*?\}/;
845
846         let options = breakpoint.options;
847         let invalidActions = [];
848
849         for (let action of options.actions) {
850             if (action.type !== WI.BreakpointAction.Type.Log)
851                 continue;
852
853             if (!templatePlaceholderRegex.test(action.data))
854                 continue;
855
856             let lexer = new WI.BreakpointLogMessageLexer;
857             let tokens = lexer.tokenize(action.data);
858             if (!tokens) {
859                 invalidActions.push(action);
860                 continue;
861             }
862
863             let templateLiteral = tokens.reduce((text, token) => {
864                 if (token.type === WI.BreakpointLogMessageLexer.TokenType.PlainText)
865                     return text + token.data.escapeCharacters("`\\");
866                 if (token.type === WI.BreakpointLogMessageLexer.TokenType.Expression)
867                     return text + "${" + token.data + "}";
868                 return text;
869             }, "");
870
871             action.data = "console.log(`" + templateLiteral + "`)";
872             action.type = WI.BreakpointAction.Type.Evaluate;
873         }
874
875         const onlyFirst = true;
876         for (let invalidAction of invalidActions)
877             options.actions.remove(invalidAction, onlyFirst);
878
879         return options;
880     }
881
882     _setBreakpoint(breakpoint, specificTarget, callback)
883     {
884         console.assert(!breakpoint.disabled);
885
886         if (breakpoint.disabled)
887             return;
888
889         if (!this._restoringBreakpoints && !this.breakpointsDisabledTemporarily) {
890             // Enable breakpoints since a breakpoint is being set. This eliminates
891             // a multi-step process for the user that can be confusing.
892             this.breakpointsEnabled = true;
893         }
894
895         function didSetBreakpoint(target, error, breakpointIdentifier, locations)
896         {
897             if (error)
898                 return;
899
900             this._breakpointIdMap.set(breakpointIdentifier, breakpoint);
901
902             breakpoint.identifier = breakpointIdentifier;
903
904             // Debugger.setBreakpoint returns a single location.
905             if (!(locations instanceof Array))
906                 locations = [locations];
907
908             for (let location of locations)
909                 this.breakpointResolved(target, breakpointIdentifier, location);
910
911             if (typeof callback === "function")
912                 callback();
913         }
914
915         // The breakpoint will be resolved again by calling DebuggerAgent, so mark it as unresolved.
916         // If something goes wrong it will stay unresolved and show up as such in the user interface.
917         // When setting for a new target, don't change the resolved target.
918         if (!specificTarget)
919             breakpoint.resolved = false;
920
921         // Convert BreakpointAction types to DebuggerAgent protocol types.
922         // NOTE: Breakpoint.options returns new objects each time, so it is safe to modify.
923         // COMPATIBILITY (iOS 7): Debugger.BreakpointActionType did not exist yet.
924         let options;
925         if (DebuggerAgent.BreakpointActionType) {
926             options = this._debuggerBreakpointOptions(breakpoint);
927             if (options.actions.length) {
928                 for (let action of options.actions)
929                     action.type = this._debuggerBreakpointActionType(action.type);
930             }
931         }
932
933         // COMPATIBILITY (iOS 7): iOS 7 and earlier, DebuggerAgent.setBreakpoint* took a "condition" string argument.
934         // This has been replaced with an "options" BreakpointOptions object.
935         if (breakpoint.contentIdentifier) {
936             let targets = specificTarget ? [specificTarget] : WI.targets;
937             for (let target of targets) {
938                 target.DebuggerAgent.setBreakpointByUrl.invoke({
939                     lineNumber: breakpoint.sourceCodeLocation.lineNumber,
940                     url: breakpoint.contentIdentifier,
941                     urlRegex: undefined,
942                     columnNumber: breakpoint.sourceCodeLocation.columnNumber,
943                     condition: breakpoint.condition,
944                     options
945                 }, didSetBreakpoint.bind(this, target), target.DebuggerAgent);
946             }
947         } else if (breakpoint.scriptIdentifier) {
948             let target = breakpoint.target;
949             target.DebuggerAgent.setBreakpoint.invoke({
950                 location: {scriptId: breakpoint.scriptIdentifier, lineNumber: breakpoint.sourceCodeLocation.lineNumber, columnNumber: breakpoint.sourceCodeLocation.columnNumber},
951                 condition: breakpoint.condition,
952                 options
953             }, didSetBreakpoint.bind(this, target), target.DebuggerAgent);
954         }
955     }
956
957     _removeBreakpoint(breakpoint, callback)
958     {
959         if (!breakpoint.identifier)
960             return;
961
962         function didRemoveBreakpoint(error)
963         {
964             if (error)
965                 console.error(error);
966
967             this._breakpointIdMap.delete(breakpoint.identifier);
968
969             breakpoint.identifier = null;
970
971             // Don't reset resolved here since we want to keep disabled breakpoints looking like they
972             // are resolved in the user interface. They will get marked as unresolved in reset.
973
974             if (typeof callback === "function")
975                 callback();
976         }
977
978         if (breakpoint.contentIdentifier) {
979             for (let target of WI.targets)
980                 target.DebuggerAgent.removeBreakpoint(breakpoint.identifier, didRemoveBreakpoint.bind(this));
981         } else if (breakpoint.scriptIdentifier) {
982             let target = breakpoint.target;
983             target.DebuggerAgent.removeBreakpoint(breakpoint.identifier, didRemoveBreakpoint.bind(this));
984         }
985     }
986
987     _breakpointDisplayLocationDidChange(event)
988     {
989         if (this._ignoreBreakpointDisplayLocationDidChangeEvent)
990             return;
991
992         let breakpoint = event.target;
993         if (!breakpoint.identifier || breakpoint.disabled)
994             return;
995
996         // Remove the breakpoint with its old id.
997         this._removeBreakpoint(breakpoint, breakpointRemoved.bind(this));
998
999         function breakpointRemoved()
1000         {
1001             // Add the breakpoint at its new lineNumber and get a new id.
1002             this._setBreakpoint(breakpoint);
1003
1004             this.dispatchEventToListeners(WI.DebuggerManager.Event.BreakpointMoved, {breakpoint});
1005         }
1006     }
1007
1008     _breakpointDisabledStateDidChange(event)
1009     {
1010         this._saveBreakpoints();
1011
1012         let breakpoint = event.target;
1013         if (breakpoint === this._allExceptionsBreakpoint) {
1014             if (!breakpoint.disabled && !this.breakpointsDisabledTemporarily)
1015                 this.breakpointsEnabled = true;
1016             this._allExceptionsBreakpointEnabledSetting.value = !breakpoint.disabled;
1017             this._updateBreakOnExceptionsState();
1018             for (let target of WI.targets)
1019                 target.DebuggerAgent.setPauseOnExceptions(this._breakOnExceptionsState);
1020             return;
1021         }
1022
1023         if (breakpoint === this._allUncaughtExceptionsBreakpoint) {
1024             if (!breakpoint.disabled && !this.breakpointsDisabledTemporarily)
1025                 this.breakpointsEnabled = true;
1026             this._allUncaughtExceptionsBreakpointEnabledSetting.value = !breakpoint.disabled;
1027             this._updateBreakOnExceptionsState();
1028             for (let target of WI.targets)
1029                 target.DebuggerAgent.setPauseOnExceptions(this._breakOnExceptionsState);
1030             return;
1031         }
1032
1033         if (breakpoint === this._assertionsBreakpoint) {
1034             if (!breakpoint.disabled && !this.breakpointsDisabledTemporarily)
1035                 this.breakpointsEnabled = true;
1036             this._assertionsBreakpointEnabledSetting.value = !breakpoint.disabled;
1037             for (let target of WI.targets)
1038                 target.DebuggerAgent.setPauseOnAssertions(this._assertionsBreakpointEnabledSetting.value);
1039             return;
1040         }
1041
1042         if (breakpoint.disabled)
1043             this._removeBreakpoint(breakpoint);
1044         else
1045             this._setBreakpoint(breakpoint);
1046     }
1047
1048     _breakpointEditablePropertyDidChange(event)
1049     {
1050         this._saveBreakpoints();
1051
1052         let breakpoint = event.target;
1053         if (breakpoint.disabled)
1054             return;
1055
1056         console.assert(this.isBreakpointEditable(breakpoint));
1057         if (!this.isBreakpointEditable(breakpoint))
1058             return;
1059
1060         // Remove the breakpoint with its old id.
1061         this._removeBreakpoint(breakpoint, breakpointRemoved.bind(this));
1062
1063         function breakpointRemoved()
1064         {
1065             // Add the breakpoint with its new properties and get a new id.
1066             this._setBreakpoint(breakpoint);
1067         }
1068     }
1069
1070     _startDisablingBreakpointsTemporarily()
1071     {
1072         console.assert(!this.breakpointsDisabledTemporarily, "Already temporarily disabling breakpoints.");
1073         if (this.breakpointsDisabledTemporarily)
1074             return;
1075
1076         this._temporarilyDisabledBreakpointsRestoreSetting.value = this._breakpointsEnabledSetting.value;
1077
1078         this.breakpointsEnabled = false;
1079     }
1080
1081     _stopDisablingBreakpointsTemporarily()
1082     {
1083         console.assert(this.breakpointsDisabledTemporarily, "Was not temporarily disabling breakpoints.");
1084         if (!this.breakpointsDisabledTemporarily)
1085             return;
1086
1087         let restoreState = this._temporarilyDisabledBreakpointsRestoreSetting.value;
1088         this._temporarilyDisabledBreakpointsRestoreSetting.value = null;
1089
1090         this.breakpointsEnabled = restoreState;
1091     }
1092
1093     _timelineCapturingWillStart(event)
1094     {
1095         this._startDisablingBreakpointsTemporarily();
1096
1097         if (this.paused)
1098             this.resume();
1099     }
1100
1101     _timelineCapturingStopped(event)
1102     {
1103         this._stopDisablingBreakpointsTemporarily();
1104     }
1105
1106     _targetRemoved(event)
1107     {
1108         let wasPaused = this.paused;
1109
1110         this._targetDebuggerDataMap.delete(event.data.target);
1111
1112         if (!this.paused && wasPaused)
1113             this.dispatchEventToListeners(WI.DebuggerManager.Event.Resumed);
1114     }
1115
1116     _mainResourceDidChange(event)
1117     {
1118         if (!event.target.isMainFrame())
1119             return;
1120
1121         this._didResumeInternal(WI.mainTarget);
1122     }
1123
1124     _didResumeInternal(target)
1125     {
1126         if (!this.paused)
1127             return;
1128
1129         if (this._delayedResumeTimeout) {
1130             clearTimeout(this._delayedResumeTimeout);
1131             this._delayedResumeTimeout = undefined;
1132         }
1133
1134         let activeCallFrameDidChange = false;
1135         if (this._activeCallFrame && this._activeCallFrame.target === target) {
1136             this._activeCallFrame = null;
1137             activeCallFrameDidChange = true;
1138         }
1139
1140         this.dataForTarget(target).updateForResume();
1141
1142         if (!this.paused)
1143             this.dispatchEventToListeners(WI.DebuggerManager.Event.Resumed);
1144
1145         this.dispatchEventToListeners(WI.DebuggerManager.Event.CallFramesDidChange, {target});
1146
1147         if (activeCallFrameDidChange)
1148             this.dispatchEventToListeners(WI.DebuggerManager.Event.ActiveCallFrameDidChange);
1149     }
1150
1151     _updateBreakOnExceptionsState()
1152     {
1153         let state = "none";
1154
1155         if (this._breakpointsEnabledSetting.value) {
1156             if (!this._allExceptionsBreakpoint.disabled)
1157                 state = "all";
1158             else if (!this._allUncaughtExceptionsBreakpoint.disabled)
1159                 state = "uncaught";
1160         }
1161
1162         this._breakOnExceptionsState = state;
1163
1164         switch (state) {
1165         case "all":
1166             // Mark the uncaught breakpoint as unresolved since "all" includes "uncaught".
1167             // That way it is clear in the user interface that the breakpoint is ignored.
1168             this._allUncaughtExceptionsBreakpoint.resolved = false;
1169             break;
1170         case "uncaught":
1171         case "none":
1172             // Mark the uncaught breakpoint as resolved again.
1173             this._allUncaughtExceptionsBreakpoint.resolved = true;
1174             break;
1175         }
1176     }
1177
1178     _saveBreakpoints()
1179     {
1180         if (this._restoringBreakpoints)
1181             return;
1182
1183         let breakpointsToSave = this._breakpoints.filter((breakpoint) => !!breakpoint.contentIdentifier);
1184         let serializedBreakpoints = breakpointsToSave.map((breakpoint) => breakpoint.info);
1185         this._breakpointsSetting.value = serializedBreakpoints;
1186     }
1187
1188     _associateBreakpointsWithSourceCode(breakpoints, sourceCode)
1189     {
1190         this._ignoreBreakpointDisplayLocationDidChangeEvent = true;
1191
1192         for (let breakpoint of breakpoints) {
1193             if (!breakpoint.sourceCodeLocation.sourceCode)
1194                 breakpoint.sourceCodeLocation.sourceCode = sourceCode;
1195             // SourceCodes can be unequal if the SourceCodeLocation is associated with a Script and we are looking at the Resource.
1196             console.assert(breakpoint.sourceCodeLocation.sourceCode === sourceCode || breakpoint.sourceCodeLocation.sourceCode.contentIdentifier === sourceCode.contentIdentifier);
1197         }
1198
1199         this._ignoreBreakpointDisplayLocationDidChangeEvent = false;
1200     }
1201
1202     _debugUIEnabledDidChange()
1203     {
1204         let eventType = WI.isDebugUIEnabled() ? WI.DebuggerManager.Event.ScriptAdded : WI.DebuggerManager.Event.ScriptRemoved;
1205         for (let script of this._internalWebKitScripts)
1206             this.dispatchEventToListeners(eventType, {script});
1207     }
1208 };
1209
1210 WI.DebuggerManager.Event = {
1211     BreakpointAdded: "debugger-manager-breakpoint-added",
1212     BreakpointRemoved: "debugger-manager-breakpoint-removed",
1213     BreakpointMoved: "debugger-manager-breakpoint-moved",
1214     WaitingToPause: "debugger-manager-waiting-to-pause",
1215     Paused: "debugger-manager-paused",
1216     Resumed: "debugger-manager-resumed",
1217     CallFramesDidChange: "debugger-manager-call-frames-did-change",
1218     ActiveCallFrameDidChange: "debugger-manager-active-call-frame-did-change",
1219     ScriptAdded: "debugger-manager-script-added",
1220     ScriptRemoved: "debugger-manager-script-removed",
1221     ScriptsCleared: "debugger-manager-scripts-cleared",
1222     BreakpointsEnabledDidChange: "debugger-manager-breakpoints-enabled-did-change"
1223 };
1224
1225 WI.DebuggerManager.PauseReason = {
1226     Assertion: "assertion",
1227     Breakpoint: "breakpoint",
1228     CSPViolation: "CSP-violation",
1229     DebuggerStatement: "debugger-statement",
1230     DOM: "DOM",
1231     Exception: "exception",
1232     PauseOnNextStatement: "pause-on-next-statement",
1233     XHR: "xhr",
1234     Other: "other",
1235 };