82c1b393eb47b877bd6800a0701ab8b32b5549c5
[WebKit-https.git] / Source / WebCore / inspector / front-end / ScriptsPanel.js
1 /*
2  * Copyright (C) 2008 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. ``AS IS'' AND ANY
14  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE INC. OR
17  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
18  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
19  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
20  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
21  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
23  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24  */
25
26 WebInspector.ScriptsPanel = function()
27 {
28     WebInspector.Panel.call(this, "scripts");
29
30     this.topStatusBar = document.createElement("div");
31     this.topStatusBar.className = "status-bar";
32     this.topStatusBar.id = "scripts-status-bar";
33     this.element.appendChild(this.topStatusBar);
34
35     this.backButton = document.createElement("button");
36     this.backButton.className = "status-bar-item";
37     this.backButton.id = "scripts-back";
38     this.backButton.title = WebInspector.UIString("Show the previous script resource.");
39     this.backButton.disabled = true;
40     this.backButton.appendChild(document.createElement("img"));
41     this.backButton.addEventListener("click", this._goBack.bind(this), false);
42     this.topStatusBar.appendChild(this.backButton);
43
44     this.forwardButton = document.createElement("button");
45     this.forwardButton.className = "status-bar-item";
46     this.forwardButton.id = "scripts-forward";
47     this.forwardButton.title = WebInspector.UIString("Show the next script resource.");
48     this.forwardButton.disabled = true;
49     this.forwardButton.appendChild(document.createElement("img"));
50     this.forwardButton.addEventListener("click", this._goForward.bind(this), false);
51     this.topStatusBar.appendChild(this.forwardButton);
52
53     this.filesSelectElement = document.createElement("select");
54     this.filesSelectElement.className = "status-bar-item";
55     this.filesSelectElement.id = "scripts-files";
56     this.filesSelectElement.addEventListener("change", this._changeVisibleFile.bind(this), false);
57     this.topStatusBar.appendChild(this.filesSelectElement);
58
59     this.functionsSelectElement = document.createElement("select");
60     this.functionsSelectElement.className = "status-bar-item";
61     this.functionsSelectElement.id = "scripts-functions";
62
63     // FIXME: append the functions select element to the top status bar when it is implemented.
64     // this.topStatusBar.appendChild(this.functionsSelectElement);
65
66     this.sidebarButtonsElement = document.createElement("div");
67     this.sidebarButtonsElement.id = "scripts-sidebar-buttons";
68     this.topStatusBar.appendChild(this.sidebarButtonsElement);
69
70     this.pauseButton = document.createElement("button");
71     this.pauseButton.className = "status-bar-item";
72     this.pauseButton.id = "scripts-pause";
73     this.pauseButton.title = WebInspector.UIString("Pause script execution.");
74     this.pauseButton.disabled = true;
75     this.pauseButton.appendChild(document.createElement("img"));
76     this.pauseButton.addEventListener("click", this._togglePause.bind(this), false);
77     this.sidebarButtonsElement.appendChild(this.pauseButton);
78
79     this.stepOverButton = document.createElement("button");
80     this.stepOverButton.className = "status-bar-item";
81     this.stepOverButton.id = "scripts-step-over";
82     this.stepOverButton.title = WebInspector.UIString("Step over next function call.");
83     this.stepOverButton.disabled = true;
84     this.stepOverButton.addEventListener("click", this._stepOverClicked.bind(this), false);
85     this.stepOverButton.appendChild(document.createElement("img"));
86     this.sidebarButtonsElement.appendChild(this.stepOverButton);
87
88     this.stepIntoButton = document.createElement("button");
89     this.stepIntoButton.className = "status-bar-item";
90     this.stepIntoButton.id = "scripts-step-into";
91     this.stepIntoButton.title = WebInspector.UIString("Step into next function call.");
92     this.stepIntoButton.disabled = true;
93     this.stepIntoButton.addEventListener("click", this._stepIntoClicked.bind(this), false);
94     this.stepIntoButton.appendChild(document.createElement("img"));
95     this.sidebarButtonsElement.appendChild(this.stepIntoButton);
96
97     this.stepOutButton = document.createElement("button");
98     this.stepOutButton.className = "status-bar-item";
99     this.stepOutButton.id = "scripts-step-out";
100     this.stepOutButton.title = WebInspector.UIString("Step out of current function.");
101     this.stepOutButton.disabled = true;
102     this.stepOutButton.addEventListener("click", this._stepOutClicked.bind(this), false);
103     this.stepOutButton.appendChild(document.createElement("img"));
104     this.sidebarButtonsElement.appendChild(this.stepOutButton);
105
106     this.toggleBreakpointsButton = new WebInspector.StatusBarButton(WebInspector.UIString("Deactivate all breakpoints."), "toggle-breakpoints");
107     this.toggleBreakpointsButton.toggled = true;
108     this.toggleBreakpointsButton.addEventListener("click", this.toggleBreakpointsClicked.bind(this), false);
109     this.sidebarButtonsElement.appendChild(this.toggleBreakpointsButton.element);
110
111     this.debuggerStatusElement = document.createElement("div");
112     this.debuggerStatusElement.id = "scripts-debugger-status";
113     this.sidebarButtonsElement.appendChild(this.debuggerStatusElement);
114
115     this.viewsContainerElement = document.createElement("div");
116     this.viewsContainerElement.id = "script-resource-views";
117
118     this.sidebarElement = document.createElement("div");
119     this.sidebarElement.id = "scripts-sidebar";
120
121     this.sidebarResizeElement = document.createElement("div");
122     this.sidebarResizeElement.className = "sidebar-resizer-vertical";
123     this.sidebarResizeElement.addEventListener("mousedown", this._startSidebarResizeDrag.bind(this), false);
124
125     this.sidebarResizeWidgetElement = document.createElement("div");
126     this.sidebarResizeWidgetElement.id = "scripts-sidebar-resizer-widget";
127     this.sidebarResizeWidgetElement.addEventListener("mousedown", this._startSidebarResizeDrag.bind(this), false);
128     this.topStatusBar.appendChild(this.sidebarResizeWidgetElement);
129
130     this.sidebarPanes = {};
131     this.sidebarPanes.watchExpressions = new WebInspector.WatchExpressionsSidebarPane();
132     this.sidebarPanes.callstack = new WebInspector.CallStackSidebarPane();
133     this.sidebarPanes.scopechain = new WebInspector.ScopeChainSidebarPane();
134     this.sidebarPanes.jsBreakpoints = WebInspector.createJSBreakpointsSidebarPane();
135     if (Preferences.nativeInstrumentationEnabled) {
136         this.sidebarPanes.domBreakpoints = WebInspector.createDOMBreakpointsSidebarPane();
137         this.sidebarPanes.xhrBreakpoints = WebInspector.createXHRBreakpointsSidebarPane();
138         this.sidebarPanes.eventListenerBreakpoints = new WebInspector.EventListenerBreakpointsSidebarPane();
139     }
140
141     this.sidebarPanes.workers = new WebInspector.WorkersSidebarPane();
142
143     for (var pane in this.sidebarPanes)
144         this.sidebarElement.appendChild(this.sidebarPanes[pane].element);
145
146     this.sidebarPanes.callstack.expanded = true;
147     this.sidebarPanes.callstack.addEventListener("call frame selected", this._callFrameSelected, this);
148
149     this.sidebarPanes.scopechain.expanded = true;
150     this.sidebarPanes.jsBreakpoints.expanded = true;
151
152     var panelEnablerHeading = WebInspector.UIString("You need to enable debugging before you can use the Scripts panel.");
153     var panelEnablerDisclaimer = WebInspector.UIString("Enabling debugging will make scripts run slower.");
154     var panelEnablerButton = WebInspector.UIString("Enable Debugging");
155
156     this.panelEnablerView = new WebInspector.PanelEnablerView("scripts", panelEnablerHeading, panelEnablerDisclaimer, panelEnablerButton);
157     this.panelEnablerView.addEventListener("enable clicked", this._enableDebugging, this);
158
159     this.element.appendChild(this.panelEnablerView.element);
160     this.element.appendChild(this.viewsContainerElement);
161     this.element.appendChild(this.sidebarElement);
162     this.element.appendChild(this.sidebarResizeElement);
163
164     this.enableToggleButton = new WebInspector.StatusBarButton("", "enable-toggle-status-bar-item");
165     this.enableToggleButton.addEventListener("click", this._toggleDebugging.bind(this), false);
166     if (Preferences.debuggerAlwaysEnabled)
167         this.enableToggleButton.element.addStyleClass("hidden");
168
169     this._pauseOnExceptionButton = new WebInspector.StatusBarButton("", "scripts-pause-on-exceptions-status-bar-item", 3);
170     this._pauseOnExceptionButton.addEventListener("click", this._togglePauseOnExceptions.bind(this), false);
171     this._pauseOnExceptionButton.state = WebInspector.ScriptsPanel.PauseOnExceptionsState.DontPauseOnExceptions;
172     this._pauseOnExceptionButton.title = WebInspector.UIString("Don't pause on exceptions.\nClick to Pause on all exceptions.");
173
174     this._registerShortcuts();
175
176     this._debuggerEnabled = Preferences.debuggerAlwaysEnabled;
177
178     this.reset();
179
180     WebInspector.debuggerModel.addEventListener(WebInspector.DebuggerModel.Events.ParsedScriptSource, this._parsedScriptSource, this);
181     WebInspector.debuggerModel.addEventListener(WebInspector.DebuggerModel.Events.FailedToParseScriptSource, this._failedToParseScriptSource, this);
182     WebInspector.debuggerModel.addEventListener(WebInspector.DebuggerModel.Events.DebuggerPaused, this._debuggerPaused, this);
183     WebInspector.debuggerModel.addEventListener(WebInspector.DebuggerModel.Events.DebuggerResumed, this._debuggerResumed, this);
184 }
185
186 // Keep these in sync with WebCore::ScriptDebugServer
187 WebInspector.ScriptsPanel.PauseOnExceptionsState = {
188     DontPauseOnExceptions : 0,
189     PauseOnAllExceptions : 1,
190     PauseOnUncaughtExceptions: 2
191 };
192
193 WebInspector.ScriptsPanel.prototype = {
194     get toolbarItemLabel()
195     {
196         return WebInspector.UIString("Scripts");
197     },
198
199     get statusBarItems()
200     {
201         return [this.enableToggleButton.element, this._pauseOnExceptionButton.element];
202     },
203
204     get defaultFocusedElement()
205     {
206         return this.filesSelectElement;
207     },
208
209     get paused()
210     {
211         return this._paused;
212     },
213
214     show: function()
215     {
216         WebInspector.Panel.prototype.show.call(this);
217         this.sidebarResizeElement.style.right = (this.sidebarElement.offsetWidth - 3) + "px";
218
219         if (this.visibleView)
220             this.visibleView.show(this.viewsContainerElement);
221
222         if (this._attachDebuggerWhenShown) {
223             InspectorBackend.enableDebuggerFromFrontend(false);
224             delete this._attachDebuggerWhenShown;
225         }
226     },
227
228     hide: function()
229     {
230         if (this.visibleView)
231             this.visibleView.hide();
232         WebInspector.Panel.prototype.hide.call(this);
233     },
234
235     get breakpointsActivated()
236     {
237         return this.toggleBreakpointsButton.toggled;
238     },
239
240     _parsedScriptSource: function(event)
241     {
242         var sourceID = event.data;
243         var script = WebInspector.debuggerModel.scriptForSourceID(sourceID);
244         this._addScript(script);
245     },
246
247     _failedToParseScriptSource: function(event)
248     {
249         this._addScript(event.data);
250     },
251
252     _addScript: function(script)
253     {
254         var resource = WebInspector.resourceForURL(script.sourceURL);
255         if (resource) {
256             if (resource.finished) {
257                 // Resource is finished, bind the script right away.
258                 script.resource = resource;
259             } else {
260                 // Resource is not finished, bind the script later.
261                 if (!resource._scriptsPendingResourceLoad) {
262                     resource._scriptsPendingResourceLoad = [];
263                     resource.addEventListener("finished", this._resourceLoadingFinished, this);
264                 }
265                 resource._scriptsPendingResourceLoad.push(script);
266             }
267         }
268         this._addScriptToFilesMenu(script);
269     },
270
271     _resourceLoadingFinished: function(e)
272     {
273         var resource = e.target;
274         for (var i = 0; i < resource._scriptsPendingResourceLoad.length; ++i) {
275             // Bind script to resource.
276             var script = resource._scriptsPendingResourceLoad[i];
277             script.resource = resource;
278
279             // Remove script from the files list.
280             script.filesSelectOption.parentElement.removeChild(script.filesSelectOption);
281         }
282         // Adding first script will add resource.
283         this._addScriptToFilesMenu(resource._scriptsPendingResourceLoad[0]);
284         delete resource._scriptsPendingResourceLoad;
285     },
286
287     canEditScripts: function()
288     {
289         return Preferences.canEditScriptSource;
290     },
291
292     editScriptSource: function(editData, revertEditingCallback, cancelEditingCallback)
293     {
294         if (!this.canEditScripts())
295             return;
296
297         // Need to clear breakpoints and re-create them later when editing source.
298         var breakpoints = WebInspector.debuggerModel.queryBreakpoints(function(b) { return b.sourceID === editData.sourceID });
299         for (var i = 0; i < breakpoints.length; ++i)
300             breakpoints[i].remove();
301
302         function mycallback(success, newBodyOrErrorMessage, callFrames)
303         {
304             if (success) {
305                 var script = WebInspector.debuggerModel.scriptForSourceID(editData.sourceID);
306                 script.source = newBodyOrErrorMessage;
307                 var oldView = script._scriptView
308                 if (oldView) {
309                     script._scriptView = new WebInspector.ScriptView(script);
310                     this.viewRecreated(oldView, script._scriptView);
311                 }
312                 if (script.resource)
313                     script.resource.setContent(newBodyOrErrorMessage, revertEditingCallback);
314
315                 if (callFrames && callFrames.length)
316                     this._debuggerPaused({ data: { callFrames: callFrames } });
317             } else {
318                 if (cancelEditingCallback)
319                     cancelEditingCallback();
320                 WebInspector.log(newBodyOrErrorMessage, WebInspector.ConsoleMessage.MessageLevel.Warning);
321             }
322             for (var i = 0; i < breakpoints.length; ++i) {
323                 var breakpoint = breakpoints[i];
324                 var newLine = breakpoint.line;
325                 if (success && breakpoint.line >= editData.line)
326                     newLine += editData.linesCountToShift;
327                 WebInspector.debuggerModel.setBreakpoint(editData.sourceID, newLine, breakpoint.enabled, breakpoint.condition);
328             }
329         };
330         InspectorBackend.editScriptSource(editData.sourceID, editData.content, mycallback.bind(this));
331     },
332
333     selectedCallFrameId: function()
334     {
335         var selectedCallFrame = this.sidebarPanes.callstack.selectedCallFrame;
336         if (!selectedCallFrame)
337             return null;
338         return selectedCallFrame.id;
339     },
340
341     evaluateInSelectedCallFrame: function(code, updateInterface, objectGroup, callback)
342     {
343         var selectedCallFrame = this.sidebarPanes.callstack.selectedCallFrame;
344         if (!this._paused || !selectedCallFrame)
345             return;
346
347         if (typeof updateInterface === "undefined")
348             updateInterface = true;
349
350         var self = this;
351         function updatingCallbackWrapper(result)
352         {
353             callback(result);
354             if (updateInterface)
355                 self.sidebarPanes.scopechain.update(selectedCallFrame);
356         }
357         this.doEvalInCallFrame(selectedCallFrame, code, objectGroup, updatingCallbackWrapper);
358     },
359
360     doEvalInCallFrame: function(callFrame, code, objectGroup, callback)
361     {
362         function evalCallback(result)
363         {
364             if (result)
365                 callback(WebInspector.RemoteObject.fromPayload(result));
366         }
367         InjectedScriptAccess.get(callFrame.worldId).evaluateInCallFrame(callFrame.id, code, objectGroup, evalCallback);
368     },
369
370     _debuggerPaused: function(event)
371     {
372         var callFrames = event.data.callFrames;
373
374         this._paused = true;
375         this._waitingToPause = false;
376         this._stepping = false;
377
378         this._updateDebuggerButtons();
379
380         WebInspector.currentPanel = this;
381
382         this.sidebarPanes.callstack.update(callFrames, event.data.eventType, event.data.eventData);
383         this.sidebarPanes.callstack.selectedCallFrame = callFrames[0];
384
385         window.focus();
386         InspectorFrontendHost.bringToFront();
387     },
388
389     _debuggerResumed: function()
390     {
391         this._paused = false;
392         this._waitingToPause = false;
393         this._stepping = false;
394
395         this._clearInterface();
396     },
397
398     attachDebuggerWhenShown: function()
399     {
400         if (this.element.parentElement) {
401             InspectorBackend.enableDebuggerFromFrontend(false);
402         } else {
403             this._attachDebuggerWhenShown = true;
404         }
405     },
406
407     debuggerWasEnabled: function()
408     {
409         if (this._debuggerEnabled)
410             return;
411
412         this._debuggerEnabled = true;
413         this.reset(true);
414     },
415
416     debuggerWasDisabled: function()
417     {
418         if (!this._debuggerEnabled)
419             return;
420
421         this._debuggerEnabled = false;
422         this.reset(true);
423     },
424
425     reset: function(preserveItems)
426     {
427         this.visibleView = null;
428
429         delete this.currentQuery;
430         this.searchCanceled();
431
432         this._debuggerResumed();
433
434         this._backForwardList = [];
435         this._currentBackForwardIndex = -1;
436         this._updateBackAndForwardButtons();
437
438         this._resourceForURLInFilesSelect = {};
439         this.filesSelectElement.removeChildren();
440         this.functionsSelectElement.removeChildren();
441         this.viewsContainerElement.removeChildren();
442
443         this.sidebarPanes.watchExpressions.refreshExpressions();
444         if (!preserveItems)
445             this.sidebarPanes.workers.reset();
446     },
447
448     get visibleView()
449     {
450         return this._visibleView;
451     },
452
453     set visibleView(x)
454     {
455         if (this._visibleView === x)
456             return;
457
458         if (this._visibleView)
459             this._visibleView.hide();
460
461         this._visibleView = x;
462
463         if (x)
464             x.show(this.viewsContainerElement);
465     },
466
467     viewRecreated: function(oldView, newView)
468     {
469         if (this.visibleView === oldView)
470             this.visibleView = newView;
471     },
472
473     canShowSourceLine: function(url, line)
474     {
475         if (!this._debuggerEnabled)
476             return false;
477         return !!this._scriptOrResourceForURLAndLine(url, line);
478     },
479
480     showSourceLine: function(url, line)
481     {
482         var scriptOrResource = this._scriptOrResourceForURLAndLine(url, line);
483         this._showScriptOrResource(scriptOrResource, {line: line, shouldHighlightLine: true});
484     },
485
486     _scriptOrResourceForURLAndLine: function(url, line)
487     {
488         var scripts = WebInspector.debuggerModel.scriptsForURL(url);
489         for (var i = 0; i < scripts.length; ++i) {
490             var script = scripts[i];
491             if (script.resource)
492                 return script.resource;
493             if (script.startingLine <= line && script.startingLine + script.linesCount > line)
494                 return script;
495         }
496         return null;
497     },
498
499     showView: function(view)
500     {
501         if (!view)
502             return;
503         this._showScriptOrResource(view.resource || view.script);
504     },
505
506     handleShortcut: function(event)
507     {
508         var shortcut = WebInspector.KeyboardShortcut.makeKeyFromEvent(event);
509         var handler = this._shortcuts[shortcut];
510         if (handler) {
511             handler(event);
512             event.handled = true;
513         } else
514             this.sidebarPanes.callstack.handleShortcut(event);
515     },
516
517     scriptViewForScript: function(script)
518     {
519         if (!script)
520             return null;
521         if (!script._scriptView)
522             script._scriptView = new WebInspector.ScriptView(script);
523         return script._scriptView;
524     },
525
526     sourceFrameForScript: function(script)
527     {
528         var view = this.scriptViewForScript(script);
529         if (!view)
530             return null;
531
532         // Setting up the source frame requires that we be attached.
533         if (!this.element.parentNode)
534             this.attach();
535
536         return view.sourceFrame;
537     },
538
539     _sourceFrameForScriptOrResource: function(scriptOrResource)
540     {
541         if (scriptOrResource instanceof WebInspector.Resource)
542             return this._sourceFrameForResource(scriptOrResource);
543         if (scriptOrResource instanceof WebInspector.Script)
544             return this.sourceFrameForScript(scriptOrResource);
545     },
546
547     _sourceFrameForResource: function(resource)
548     {
549         var view = WebInspector.ResourceView.resourceViewForResource(resource);
550         if (!view)
551             return null;
552
553         return view.sourceFrame;
554     },
555
556     _showScriptOrResource: function(scriptOrResource, options)
557     {
558         // options = {line:, shouldHighlightLine:, fromBackForwardAction:, initialLoad:}
559         options = options || {};
560
561         if (!scriptOrResource)
562             return;
563
564         var view;
565         if (scriptOrResource instanceof WebInspector.Resource)
566             view = WebInspector.ResourceView.resourceViewForResource(scriptOrResource);
567         else if (scriptOrResource instanceof WebInspector.Script)
568             view = this.scriptViewForScript(scriptOrResource);
569
570         if (!view)
571             return;
572
573         var url = scriptOrResource.url || scriptOrResource.sourceURL;
574         if (url && !options.initialLoad)
575             WebInspector.settings.lastViewedScriptFile = url;
576
577         if (!options.fromBackForwardAction) {
578             var oldIndex = this._currentBackForwardIndex;
579             if (oldIndex >= 0)
580                 this._backForwardList.splice(oldIndex + 1, this._backForwardList.length - oldIndex);
581
582             // Check for a previous entry of the same object in _backForwardList.
583             // If one is found, remove it and update _currentBackForwardIndex to match.
584             var previousEntryIndex = this._backForwardList.indexOf(scriptOrResource);
585             if (previousEntryIndex !== -1) {
586                 this._backForwardList.splice(previousEntryIndex, 1);
587                 --this._currentBackForwardIndex;
588             }
589
590             this._backForwardList.push(scriptOrResource);
591             ++this._currentBackForwardIndex;
592
593             this._updateBackAndForwardButtons();
594         }
595
596         this.visibleView = view;
597
598         if (options.line) {
599             if (view.revealLine)
600                 view.revealLine(options.line);
601             if (view.highlightLine && options.shouldHighlightLine)
602                 view.highlightLine(options.line);
603         }
604
605         var option;
606         if (scriptOrResource instanceof WebInspector.Script) {
607             option = scriptOrResource.filesSelectOption;
608
609             // hasn't been added yet - happens for stepping in evals,
610             // so use the force option to force the script into the menu.
611             if (!option) {
612                 this._addScriptToFilesMenu(scriptOrResource, true);
613                 option = scriptOrResource.filesSelectOption;
614             }
615
616             console.assert(option);
617         } else
618             option = scriptOrResource.filesSelectOption;
619
620         if (option)
621             this.filesSelectElement.selectedIndex = option.index;
622     },
623
624     _addScriptToFilesMenu: function(script, force)
625     {
626         if (!script.sourceURL && !force)
627             return;
628
629         if (script.resource) {
630             if (this._resourceForURLInFilesSelect[script.resource.url])
631                 return;
632             this._resourceForURLInFilesSelect[script.resource.url] = script.resource;
633         }
634
635         var displayName = script.sourceURL ? WebInspector.displayNameForURL(script.sourceURL) : WebInspector.UIString("(program)");
636
637         var select = this.filesSelectElement;
638         var option = document.createElement("option");
639         option.representedObject = script.resource || script;
640         option.url = displayName;
641         option.startingLine = script.startingLine;
642         option.text = script.resource || script.startingLine === 1 ? displayName : String.sprintf("%s:%d", displayName, script.startingLine);
643
644         function optionCompare(a, b)
645         {
646             if (a.url < b.url)
647                 return -1;
648             else if (a.url > b.url)
649                 return 1;
650
651             if (typeof a.startingLine !== "number")
652                 return -1;
653             if (typeof b.startingLine !== "number")
654                 return -1;
655             return a.startingLine - b.startingLine;
656         }
657
658         var insertionIndex = insertionIndexForObjectInListSortedByFunction(option, select.childNodes, optionCompare);
659         if (insertionIndex < 0)
660             select.appendChild(option);
661         else
662             select.insertBefore(option, select.childNodes.item(insertionIndex));
663
664         if (script.resource)
665             script.resource.filesSelectOption = option;
666         else
667             script.filesSelectOption = option;
668
669         if (select.options[select.selectedIndex] === option) {
670             // Call _showScriptOrResource if the option we just appended ended up being selected.
671             // This will happen for the first item added to the menu.
672             this._showScriptOrResource(option.representedObject, {initialLoad: true});
673         } else {
674             // If not first item, check to see if this was the last viewed
675             var url = option.representedObject.url || option.representedObject.sourceURL;
676             var lastURL = WebInspector.settings.lastViewedScriptFile;
677             if (url && url === lastURL) {
678                 // For resources containing multiple <script> tags, we first report them separately and
679                 // then glue them all together. They all share url and there is no need to show them all one
680                 // by one.
681                 var isResource = !!option.representedObject.url;
682                 if (isResource || !this.visibleView || !this.visibleView.script || this.visibleView.script.sourceURL !== url)
683                     this._showScriptOrResource(option.representedObject, {initialLoad: true});
684             }
685         }
686
687         if (script.worldType === WebInspector.Script.WorldType.EXTENSIONS_WORLD)
688             script.filesSelectOption.addStyleClass("extension-script");
689     },
690
691     _clearCurrentExecutionLine: function()
692     {
693         if (this._executionSourceFrame)
694             this._executionSourceFrame.executionLine = 0;
695         delete this._executionSourceFrame;
696     },
697
698     _callFrameSelected: function()
699     {
700         this._clearCurrentExecutionLine();
701
702         var callStackPane = this.sidebarPanes.callstack;
703         var currentFrame = callStackPane.selectedCallFrame;
704         if (!currentFrame)
705             return;
706
707         this.sidebarPanes.scopechain.update(currentFrame);
708         this.sidebarPanes.watchExpressions.refreshExpressions();
709
710         var script = WebInspector.debuggerModel.scriptForSourceID(currentFrame.sourceID);
711         var scriptOrResource = script.resource || script;
712         this._showScriptOrResource(scriptOrResource, {line: currentFrame.line});
713
714         this._executionSourceFrame = this._sourceFrameForScriptOrResource(scriptOrResource);
715         if (this._executionSourceFrame)
716             this._executionSourceFrame.executionLine = currentFrame.line;
717     },
718
719     _changeVisibleFile: function(event)
720     {
721         var select = this.filesSelectElement;
722         this._showScriptOrResource(select.options[select.selectedIndex].representedObject);
723     },
724
725     _startSidebarResizeDrag: function(event)
726     {
727         WebInspector.elementDragStart(this.sidebarElement, this._sidebarResizeDrag.bind(this), this._endSidebarResizeDrag.bind(this), event, "col-resize");
728
729         if (event.target === this.sidebarResizeWidgetElement)
730             this._dragOffset = (event.target.offsetWidth - (event.pageX - event.target.totalOffsetLeft));
731         else
732             this._dragOffset = 0;
733     },
734
735     _endSidebarResizeDrag: function(event)
736     {
737         WebInspector.elementDragEnd(event);
738         delete this._dragOffset;
739         this.saveSidebarWidth();
740     },
741
742     _sidebarResizeDrag: function(event)
743     {
744         var x = event.pageX + this._dragOffset;
745         var newWidth = Number.constrain(window.innerWidth - x, Preferences.minScriptsSidebarWidth, window.innerWidth * 0.66);
746         this.setSidebarWidth(newWidth);
747         event.preventDefault();
748     },
749
750     setSidebarWidth: function(newWidth)
751     {
752         this.sidebarElement.style.width = newWidth + "px";
753         this.sidebarButtonsElement.style.width = newWidth + "px";
754         this.viewsContainerElement.style.right = newWidth + "px";
755         this.sidebarResizeWidgetElement.style.right = newWidth + "px";
756         this.sidebarResizeElement.style.right = (newWidth - 3) + "px";
757
758         this.resize();
759     },
760
761     updatePauseOnExceptionsState: function(pauseOnExceptionsState)
762     {
763         if (pauseOnExceptionsState == WebInspector.ScriptsPanel.PauseOnExceptionsState.DontPauseOnExceptions)
764             this._pauseOnExceptionButton.title = WebInspector.UIString("Don't pause on exceptions.\nClick to Pause on all exceptions.");
765         else if (pauseOnExceptionsState == WebInspector.ScriptsPanel.PauseOnExceptionsState.PauseOnAllExceptions)
766             this._pauseOnExceptionButton.title = WebInspector.UIString("Pause on all exceptions.\nClick to Pause on uncaught exceptions.");
767         else if (pauseOnExceptionsState == WebInspector.ScriptsPanel.PauseOnExceptionsState.PauseOnUncaughtExceptions)
768             this._pauseOnExceptionButton.title = WebInspector.UIString("Pause on uncaught exceptions.\nClick to Not pause on exceptions.");
769
770         this._pauseOnExceptionButton.state = pauseOnExceptionsState;
771     },
772
773     _updateDebuggerButtons: function()
774     {
775         if (this._debuggerEnabled) {
776             this.enableToggleButton.title = WebInspector.UIString("Debugging enabled. Click to disable.");
777             this.enableToggleButton.toggled = true;
778             this._pauseOnExceptionButton.visible = true;
779             this.panelEnablerView.visible = false;
780         } else {
781             this.enableToggleButton.title = WebInspector.UIString("Debugging disabled. Click to enable.");
782             this.enableToggleButton.toggled = false;
783             this._pauseOnExceptionButton.visible = false;
784             this.panelEnablerView.visible = true;
785         }
786
787         if (this._paused) {
788             this.pauseButton.addStyleClass("paused");
789
790             this.pauseButton.disabled = false;
791             this.stepOverButton.disabled = false;
792             this.stepIntoButton.disabled = false;
793             this.stepOutButton.disabled = false;
794
795             this.debuggerStatusElement.textContent = WebInspector.UIString("Paused");
796         } else {
797             this.pauseButton.removeStyleClass("paused");
798
799             this.pauseButton.disabled = this._waitingToPause;
800             this.stepOverButton.disabled = true;
801             this.stepIntoButton.disabled = true;
802             this.stepOutButton.disabled = true;
803
804             if (this._waitingToPause)
805                 this.debuggerStatusElement.textContent = WebInspector.UIString("Pausing");
806             else if (this._stepping)
807                 this.debuggerStatusElement.textContent = WebInspector.UIString("Stepping");
808             else
809                 this.debuggerStatusElement.textContent = "";
810         }
811     },
812
813     _updateBackAndForwardButtons: function()
814     {
815         this.backButton.disabled = this._currentBackForwardIndex <= 0;
816         this.forwardButton.disabled = this._currentBackForwardIndex >= (this._backForwardList.length - 1);
817     },
818
819     _clearInterface: function()
820     {
821         this.sidebarPanes.callstack.update(null);
822         this.sidebarPanes.scopechain.update(null);
823
824         this._clearCurrentExecutionLine();
825         this._updateDebuggerButtons();
826     },
827
828     _goBack: function()
829     {
830         if (this._currentBackForwardIndex <= 0) {
831             console.error("Can't go back from index " + this._currentBackForwardIndex);
832             return;
833         }
834
835         this._showScriptOrResource(this._backForwardList[--this._currentBackForwardIndex], {fromBackForwardAction: true});
836         this._updateBackAndForwardButtons();
837     },
838
839     _goForward: function()
840     {
841         if (this._currentBackForwardIndex >= this._backForwardList.length - 1) {
842             console.error("Can't go forward from index " + this._currentBackForwardIndex);
843             return;
844         }
845
846         this._showScriptOrResource(this._backForwardList[++this._currentBackForwardIndex], {fromBackForwardAction: true});
847         this._updateBackAndForwardButtons();
848     },
849
850     _enableDebugging: function()
851     {
852         if (this._debuggerEnabled)
853             return;
854         this._toggleDebugging(this.panelEnablerView.alwaysEnabled);
855     },
856
857     _toggleDebugging: function(optionalAlways)
858     {
859         this._paused = false;
860         this._waitingToPause = false;
861         this._stepping = false;
862
863         if (this._debuggerEnabled)
864             InspectorBackend.disableDebugger(true);
865         else
866             InspectorBackend.enableDebuggerFromFrontend(!!optionalAlways);
867     },
868
869     _togglePauseOnExceptions: function()
870     {
871         InspectorBackend.setPauseOnExceptionsState((this._pauseOnExceptionButton.state + 1) % this._pauseOnExceptionButton.states, this.updatePauseOnExceptionsState.bind(this));
872     },
873
874     _togglePause: function()
875     {
876         if (this._paused) {
877             this._paused = false;
878             this._waitingToPause = false;
879             InspectorBackend.resume();
880         } else {
881             this._stepping = false;
882             this._waitingToPause = true;
883             InspectorBackend.pause();
884         }
885
886         this._clearInterface();
887     },
888
889     _stepOverClicked: function()
890     {
891         this._paused = false;
892         this._stepping = true;
893
894         this._clearInterface();
895
896         InspectorBackend.stepOver();
897     },
898
899     _stepIntoClicked: function()
900     {
901         this._paused = false;
902         this._stepping = true;
903
904         this._clearInterface();
905
906         InspectorBackend.stepInto();
907     },
908
909     _stepOutClicked: function()
910     {
911         this._paused = false;
912         this._stepping = true;
913
914         this._clearInterface();
915
916         InspectorBackend.stepOut();
917     },
918
919     toggleBreakpointsClicked: function()
920     {
921         this.toggleBreakpointsButton.toggled = !this.toggleBreakpointsButton.toggled;
922         if (this.toggleBreakpointsButton.toggled) {
923             InspectorBackend.activateBreakpoints();
924             this.toggleBreakpointsButton.title = WebInspector.UIString("Deactivate all breakpoints.");
925             document.getElementById("main-panels").removeStyleClass("breakpoints-deactivated");
926         } else {
927             InspectorBackend.deactivateBreakpoints();
928             this.toggleBreakpointsButton.title = WebInspector.UIString("Activate all breakpoints.");
929             document.getElementById("main-panels").addStyleClass("breakpoints-deactivated");
930         }
931     },
932
933     elementsToRestoreScrollPositionsFor: function()
934     {
935         return [ this.sidebarElement ];
936     },
937
938     _registerShortcuts: function()
939     {
940         var section = WebInspector.shortcutsHelp.section(WebInspector.UIString("Scripts Panel"));
941         var handler, shortcut1, shortcut2;
942         var platformSpecificModifier = WebInspector.KeyboardShortcut.Modifiers.CtrlOrMeta;
943
944         this._shortcuts = {};
945
946         // Continue.
947         handler = this.pauseButton.click.bind(this.pauseButton);
948         shortcut1 = WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.F8);
949         this._shortcuts[shortcut1.key] = handler;
950         shortcut2 = WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.Slash, platformSpecificModifier);
951         this._shortcuts[shortcut2.key] = handler;
952         section.addAlternateKeys([ shortcut1.name, shortcut2.name ], WebInspector.UIString("Continue"));
953
954         // Step over.
955         handler = this.stepOverButton.click.bind(this.stepOverButton);
956         shortcut1 = WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.F10);
957         this._shortcuts[shortcut1.key] = handler;
958         shortcut2 = WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.SingleQuote, platformSpecificModifier);
959         this._shortcuts[shortcut2.key] = handler;
960         section.addAlternateKeys([ shortcut1.name, shortcut2.name ], WebInspector.UIString("Step over"));
961
962         // Step into.
963         handler = this.stepIntoButton.click.bind(this.stepIntoButton);
964         shortcut1 = WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.F11);
965         this._shortcuts[shortcut1.key] = handler;
966         shortcut2 = WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.Semicolon, platformSpecificModifier);
967         this._shortcuts[shortcut2.key] = handler;
968         section.addAlternateKeys([ shortcut1.name, shortcut2.name ], WebInspector.UIString("Step into"));
969
970         // Step out.
971         handler = this.stepOutButton.click.bind(this.stepOutButton);
972         shortcut1 = WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.F11, WebInspector.KeyboardShortcut.Modifiers.Shift);
973         this._shortcuts[shortcut1.key] = handler;
974         shortcut2 = WebInspector.KeyboardShortcut.makeDescriptor(WebInspector.KeyboardShortcut.Keys.Semicolon, WebInspector.KeyboardShortcut.Modifiers.Shift, platformSpecificModifier);
975         this._shortcuts[shortcut2.key] = handler;
976         section.addAlternateKeys([ shortcut1.name, shortcut2.name ], WebInspector.UIString("Step out"));
977
978         var isMac = WebInspector.isMac();
979         if (isMac)
980             shortcut1 = WebInspector.KeyboardShortcut.makeDescriptor("l", WebInspector.KeyboardShortcut.Modifiers.Meta);
981         else
982             shortcut1 = WebInspector.KeyboardShortcut.makeDescriptor("g", WebInspector.KeyboardShortcut.Modifiers.Ctrl);
983         this._shortcuts[shortcut1.key] = this.showGoToLineDialog.bind(this);
984         section.addAlternateKeys([ shortcut1.name ], WebInspector.UIString("Go to Line"));
985         this.sidebarPanes.callstack.registerShortcuts(section);
986     },
987
988     searchCanceled: function()
989     {
990         WebInspector.updateSearchMatchesCount(0, this);
991
992         if (this._searchView)
993             this._searchView.searchCanceled();
994
995         delete this._searchView;
996         delete this._searchQuery;
997     },
998
999     performSearch: function(query)
1000     {
1001         if (!this.visibleView)
1002             return;
1003
1004         // Call searchCanceled since it will reset everything we need before doing a new search.
1005         this.searchCanceled();
1006
1007         this._searchView = this.visibleView;
1008         this._searchQuery = query;
1009
1010         function finishedCallback(view, searchMatches)
1011         {
1012             if (!searchMatches)
1013                 return;
1014
1015             WebInspector.updateSearchMatchesCount(searchMatches, this);
1016             view.jumpToFirstSearchResult();
1017         }
1018
1019         this._searchView.performSearch(query, finishedCallback.bind(this));
1020     },
1021
1022     jumpToNextSearchResult: function()
1023     {
1024         if (!this._searchView)
1025             return;
1026
1027         if (this._searchView !== this.visibleView) {
1028             this.performSearch(this._searchQuery);
1029             return;
1030         }
1031
1032         if (this._searchView.showingLastSearchResult())
1033             this._searchView.jumpToFirstSearchResult();
1034         else
1035             this._searchView.jumpToNextSearchResult();
1036     },
1037
1038     jumpToPreviousSearchResult: function()
1039     {
1040         if (!this._searchView)
1041             return;
1042
1043         if (this._searchView !== this.visibleView) {
1044             this.performSearch(this._searchQuery);
1045             if (this._searchView)
1046                 this._searchView.jumpToLastSearchResult();
1047             return;
1048         }
1049
1050         if (this._searchView.showingFirstSearchResult())
1051             this._searchView.jumpToLastSearchResult();
1052         else
1053             this._searchView.jumpToPreviousSearchResult();
1054     },
1055
1056     showGoToLineDialog: function(e)
1057     {
1058          var view = this.visibleView;
1059          if (view)
1060              WebInspector.GoToLineDialog.show(view);
1061     }
1062 }
1063
1064 WebInspector.ScriptsPanel.prototype.__proto__ = WebInspector.Panel.prototype;