2010-12-01 Ilya Tikhonovsky <loislo@chromium.org>
[WebKit-https.git] / WebCore / inspector / front-end / inspector.js
1 /*
2  * Copyright (C) 2006, 2007, 2008 Apple Inc.  All rights reserved.
3  * Copyright (C) 2007 Matt Lilek (pewtermoose@gmail.com).
4  * Copyright (C) 2009 Joseph Pecoraro
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  *
10  * 1.  Redistributions of source code must retain the above copyright
11  *     notice, this list of conditions and the following disclaimer.
12  * 2.  Redistributions in binary form must reproduce the above copyright
13  *     notice, this list of conditions and the following disclaimer in the
14  *     documentation and/or other materials provided with the distribution.
15  * 3.  Neither the name of Apple Computer, Inc. ("Apple") nor the names of
16  *     its contributors may be used to endorse or promote products derived
17  *     from this software without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
20  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
21  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22  * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
23  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
24  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
25  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
26  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
28  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29  */
30
31 // Keep this ; so that concatenated version of the script worked.
32 ;(function preloadImages()
33 {
34     (new Image()).src = "Images/clearConsoleButtonGlyph.png";
35     (new Image()).src = "Images/consoleButtonGlyph.png";
36     (new Image()).src = "Images/dockButtonGlyph.png";
37     (new Image()).src = "Images/enableOutlineButtonGlyph.png";
38     (new Image()).src = "Images/enableSolidButtonGlyph.png";
39     (new Image()).src = "Images/excludeButtonGlyph.png";
40     (new Image()).src = "Images/focusButtonGlyph.png";
41     (new Image()).src = "Images/largerResourcesButtonGlyph.png";
42     (new Image()).src = "Images/nodeSearchButtonGlyph.png";
43     (new Image()).src = "Images/pauseOnExceptionButtonGlyph.png";
44     (new Image()).src = "Images/percentButtonGlyph.png";
45     (new Image()).src = "Images/recordButtonGlyph.png";
46     (new Image()).src = "Images/recordToggledButtonGlyph.png";
47     (new Image()).src = "Images/reloadButtonGlyph.png";
48     (new Image()).src = "Images/undockButtonGlyph.png";
49 })();
50
51 var WebInspector = {
52     resources: {},
53     missingLocalizedStrings: {},
54     pendingDispatches: 0,
55
56     get platform()
57     {
58         if (!("_platform" in this))
59             this._platform = InspectorFrontendHost.platform();
60
61         return this._platform;
62     },
63
64     get platformFlavor()
65     {
66         if (!("_platformFlavor" in this))
67             this._platformFlavor = this._detectPlatformFlavor();
68
69         return this._platformFlavor;
70     },
71
72     _detectPlatformFlavor: function()
73     {
74         const userAgent = navigator.userAgent;
75
76         if (this.platform === "windows") {
77             var match = userAgent.match(/Windows NT (\d+)\.(?:\d+)/);
78             if (match && match[1] >= 6)
79                 return WebInspector.PlatformFlavor.WindowsVista;
80             return null;
81         } else if (this.platform === "mac") {
82             var match = userAgent.match(/Mac OS X\s*(?:(\d+)_(\d+))?/);
83             if (!match || match[1] != 10)
84                 return WebInspector.PlatformFlavor.MacSnowLeopard;
85             switch (Number(match[2])) {
86                 case 4:
87                     return WebInspector.PlatformFlavor.MacTiger;
88                 case 5:
89                     return WebInspector.PlatformFlavor.MacLeopard;
90                 case 6:
91                 default:
92                     return WebInspector.PlatformFlavor.MacSnowLeopard;
93             }
94         }
95
96         return null;
97     },
98
99     get port()
100     {
101         if (!("_port" in this))
102             this._port = InspectorFrontendHost.port();
103
104         return this._port;
105     },
106
107     get previousFocusElement()
108     {
109         return this._previousFocusElement;
110     },
111
112     get currentFocusElement()
113     {
114         return this._currentFocusElement;
115     },
116
117     set currentFocusElement(x)
118     {
119         if (this._currentFocusElement !== x)
120             this._previousFocusElement = this._currentFocusElement;
121         this._currentFocusElement = x;
122
123         if (this._currentFocusElement) {
124             this._currentFocusElement.focus();
125
126             // Make a caret selection inside the new element if there isn't a range selection and
127             // there isn't already a caret selection inside.
128             var selection = window.getSelection();
129             if (selection.isCollapsed && !this._currentFocusElement.isInsertionCaretInside()) {
130                 var selectionRange = this._currentFocusElement.ownerDocument.createRange();
131                 selectionRange.setStart(this._currentFocusElement, 0);
132                 selectionRange.setEnd(this._currentFocusElement, 0);
133
134                 selection.removeAllRanges();
135                 selection.addRange(selectionRange);
136             }
137         } else if (this._previousFocusElement)
138             this._previousFocusElement.blur();
139     },
140
141     get currentPanel()
142     {
143         return this._currentPanel;
144     },
145
146     set currentPanel(x)
147     {
148         if (this._currentPanel === x)
149             return;
150
151         if (this._currentPanel)
152             this._currentPanel.hide();
153
154         this._currentPanel = x;
155
156         this.updateSearchLabel();
157
158         if (x) {
159             x.show();
160
161             if (this.currentQuery) {
162                 if (x.performSearch) {
163                     function performPanelSearch()
164                     {
165                         this.updateSearchMatchesCount();
166
167                         x.currentQuery = this.currentQuery;
168                         x.performSearch(this.currentQuery);
169                     }
170
171                     // Perform the search on a timeout so the panel switches fast.
172                     setTimeout(performPanelSearch.bind(this), 0);
173                 } else {
174                     // Update to show Not found for panels that can't be searched.
175                     this.updateSearchMatchesCount();
176                 }
177             }
178         }
179
180         for (var panelName in WebInspector.panels) {
181             if (WebInspector.panels[panelName] === x) {
182                 WebInspector.settings.lastActivePanel = panelName;
183                 this._panelHistory.setPanel(panelName);
184             }
185         }
186     },
187
188     createJSBreakpointsSidebarPane: function()
189     {
190         var pane = new WebInspector.BreakpointsSidebarPane(WebInspector.UIString("Breakpoints"));
191         function breakpointAdded(event)
192         {
193             pane.addBreakpointItem(new WebInspector.BreakpointItem(event.data));
194         }
195         WebInspector.breakpointManager.addEventListener("breakpoint-added", breakpointAdded);
196         return pane;
197     },
198
199     createDOMBreakpointsSidebarPane: function()
200     {
201         var pane = new WebInspector.BreakpointsSidebarPane(WebInspector.UIString("DOM Breakpoints"));
202         function breakpointAdded(event)
203         {
204             pane.addBreakpointItem(new WebInspector.BreakpointItem(event.data));
205         }
206         WebInspector.breakpointManager.addEventListener("dom-breakpoint-added", breakpointAdded);
207         return pane;
208     },
209
210     createXHRBreakpointsSidebarPane: function()
211     {
212         var pane = new WebInspector.XHRBreakpointsSidebarPane();
213         function breakpointAdded(event)
214         {
215             pane.addBreakpointItem(new WebInspector.BreakpointItem(event.data));
216         }
217         WebInspector.breakpointManager.addEventListener("xhr-breakpoint-added", breakpointAdded);
218         return pane;
219     },
220
221     _createPanels: function()
222     {
223         var hiddenPanels = (InspectorFrontendHost.hiddenPanels() || "").split(',');
224         if (hiddenPanels.indexOf("elements") === -1)
225             this.panels.elements = new WebInspector.ElementsPanel();
226         if (hiddenPanels.indexOf("resources") === -1)
227             this.panels.resources = new WebInspector.ResourcesPanel();
228         if (hiddenPanels.indexOf("network") === -1)
229             this.panels.network = new WebInspector.NetworkPanel();
230         if (hiddenPanels.indexOf("scripts") === -1)
231             this.panels.scripts = new WebInspector.ScriptsPanel();
232         if (hiddenPanels.indexOf("timeline") === -1)
233             this.panels.timeline = new WebInspector.TimelinePanel();
234         if (hiddenPanels.indexOf("profiles") === -1) {
235             this.panels.profiles = new WebInspector.ProfilesPanel();
236             this.panels.profiles.registerProfileType(new WebInspector.CPUProfileType());
237             if (Preferences.heapProfilerPresent)
238                 this.panels.profiles.registerProfileType(new WebInspector.HeapSnapshotProfileType());
239         }
240         if (hiddenPanels.indexOf("audits") === -1)
241             this.panels.audits = new WebInspector.AuditsPanel();
242         if (hiddenPanels.indexOf("console") === -1)
243             this.panels.console = new WebInspector.ConsolePanel();
244     },
245
246     get attached()
247     {
248         return this._attached;
249     },
250
251     set attached(x)
252     {
253         if (this._attached === x)
254             return;
255
256         this._attached = x;
257
258         this.updateSearchLabel();
259
260         var dockToggleButton = document.getElementById("dock-status-bar-item");
261         var body = document.body;
262
263         if (x) {
264             body.removeStyleClass("detached");
265             body.addStyleClass("attached");
266             dockToggleButton.title = WebInspector.UIString("Undock into separate window.");
267         } else {
268             body.removeStyleClass("attached");
269             body.addStyleClass("detached");
270             dockToggleButton.title = WebInspector.UIString("Dock to main window.");
271         }
272         if (this.drawer)
273             this.drawer.resize();
274     },
275
276     get errors()
277     {
278         return this._errors || 0;
279     },
280
281     set errors(x)
282     {
283         x = Math.max(x, 0);
284
285         if (this._errors === x)
286             return;
287         this._errors = x;
288         this._updateErrorAndWarningCounts();
289     },
290
291     get warnings()
292     {
293         return this._warnings || 0;
294     },
295
296     set warnings(x)
297     {
298         x = Math.max(x, 0);
299
300         if (this._warnings === x)
301             return;
302         this._warnings = x;
303         this._updateErrorAndWarningCounts();
304     },
305
306     _updateErrorAndWarningCounts: function()
307     {
308         var errorWarningElement = document.getElementById("error-warning-count");
309         if (!errorWarningElement)
310             return;
311
312         if (!this.errors && !this.warnings) {
313             errorWarningElement.addStyleClass("hidden");
314             return;
315         }
316
317         errorWarningElement.removeStyleClass("hidden");
318
319         errorWarningElement.removeChildren();
320
321         if (this.errors) {
322             var errorElement = document.createElement("span");
323             errorElement.id = "error-count";
324             errorElement.textContent = this.errors;
325             errorWarningElement.appendChild(errorElement);
326         }
327
328         if (this.warnings) {
329             var warningsElement = document.createElement("span");
330             warningsElement.id = "warning-count";
331             warningsElement.textContent = this.warnings;
332             errorWarningElement.appendChild(warningsElement);
333         }
334
335         if (this.errors) {
336             if (this.warnings) {
337                 if (this.errors == 1) {
338                     if (this.warnings == 1)
339                         errorWarningElement.title = WebInspector.UIString("%d error, %d warning", this.errors, this.warnings);
340                     else
341                         errorWarningElement.title = WebInspector.UIString("%d error, %d warnings", this.errors, this.warnings);
342                 } else if (this.warnings == 1)
343                     errorWarningElement.title = WebInspector.UIString("%d errors, %d warning", this.errors, this.warnings);
344                 else
345                     errorWarningElement.title = WebInspector.UIString("%d errors, %d warnings", this.errors, this.warnings);
346             } else if (this.errors == 1)
347                 errorWarningElement.title = WebInspector.UIString("%d error", this.errors);
348             else
349                 errorWarningElement.title = WebInspector.UIString("%d errors", this.errors);
350         } else if (this.warnings == 1)
351             errorWarningElement.title = WebInspector.UIString("%d warning", this.warnings);
352         else if (this.warnings)
353             errorWarningElement.title = WebInspector.UIString("%d warnings", this.warnings);
354         else
355             errorWarningElement.title = null;
356     },
357
358     get styleChanges()
359     {
360         return this._styleChanges;
361     },
362
363     set styleChanges(x)
364     {
365         x = Math.max(x, 0);
366
367         if (this._styleChanges === x)
368             return;
369         this._styleChanges = x;
370         this._updateChangesCount();
371     },
372
373     _updateChangesCount: function()
374     {
375         // TODO: Remove immediate return when enabling the Changes Panel
376         return;
377
378         var changesElement = document.getElementById("changes-count");
379         if (!changesElement)
380             return;
381
382         if (!this.styleChanges) {
383             changesElement.addStyleClass("hidden");
384             return;
385         }
386
387         changesElement.removeStyleClass("hidden");
388         changesElement.removeChildren();
389
390         if (this.styleChanges) {
391             var styleChangesElement = document.createElement("span");
392             styleChangesElement.id = "style-changes-count";
393             styleChangesElement.textContent = this.styleChanges;
394             changesElement.appendChild(styleChangesElement);
395         }
396
397         if (this.styleChanges) {
398             if (this.styleChanges === 1)
399                 changesElement.title = WebInspector.UIString("%d style change", this.styleChanges);
400             else
401                 changesElement.title = WebInspector.UIString("%d style changes", this.styleChanges);
402         }
403     },
404
405     highlightDOMNode: function(nodeId)
406     {
407         if ("_hideDOMNodeHighlightTimeout" in this) {
408             clearTimeout(this._hideDOMNodeHighlightTimeout);
409             delete this._hideDOMNodeHighlightTimeout;
410         }
411
412         if (this._highlightedDOMNodeId === nodeId)
413             return;
414
415         this._highlightedDOMNodeId = nodeId;
416         if (nodeId)
417             InspectorBackend.highlightDOMNode(nodeId);
418         else
419             InspectorBackend.hideDOMNodeHighlight();
420     },
421
422     highlightDOMNodeForTwoSeconds: function(nodeId)
423     {
424         this.highlightDOMNode(nodeId);
425         this._hideDOMNodeHighlightTimeout = setTimeout(this.highlightDOMNode.bind(this, 0), 2000);
426     },
427
428     wireElementWithDOMNode: function(element, nodeId)
429     {
430         element.addEventListener("click", this._updateFocusedNode.bind(this, nodeId), false);
431         element.addEventListener("mouseover", this.highlightDOMNode.bind(this, nodeId), false);
432         element.addEventListener("mouseout", this.highlightDOMNode.bind(this, 0), false);
433     },
434
435     _updateFocusedNode: function(nodeId)
436     {
437         this.currentPanel = this.panels.elements;
438         this.panels.elements.updateFocusedNode(nodeId);
439     },
440
441     get networkResources()
442     {
443         return this.panels.network.resources;
444     },
445
446     forAllResources: function(callback)
447     {
448         WebInspector.resourceManager.forAllResources(callback);
449     },
450
451     resourceForURL: function(url)
452     {
453         return this.resourceManager.resourceForURL(url);
454     }
455 }
456
457 WebInspector.PlatformFlavor = {
458     WindowsVista: "windows-vista",
459     MacTiger: "mac-tiger",
460     MacLeopard: "mac-leopard",
461     MacSnowLeopard: "mac-snowleopard"
462 };
463
464 (function parseQueryParameters()
465 {
466     WebInspector.queryParamsObject = {};
467     var queryParams = window.location.search;
468     if (!queryParams)
469         return;
470     var params = queryParams.substring(1).split("&");
471     for (var i = 0; i < params.length; ++i) {
472         var pair = params[i].split("=");
473         WebInspector.queryParamsObject[pair[0]] = pair[1];
474     }
475 })();
476
477 WebInspector.loaded = function()
478 {
479     if ("page" in WebInspector.queryParamsObject) {
480         WebInspector.socket = new WebSocket("ws://" + window.location.host + "/devtools/page/" + WebInspector.queryParamsObject.page);
481         WebInspector.socket.onmessage = function(message) { InspectorBackend.dispatch(message.data); }
482         WebInspector.socket.onerror = function(error) { console.error(error); }
483         WebInspector.socket.onopen = function() {
484             InspectorFrontendHost.sendMessageToBackend = WebInspector.socket.send.bind(WebInspector.socket);
485             InspectorFrontendHost.loaded = WebInspector.socket.send.bind(WebInspector.socket, "loaded");
486             WebInspector.doLoadedDone();
487         }
488         return;
489     }
490     WebInspector.doLoadedDone();
491 }
492
493 WebInspector.doLoadedDone = function()
494 {
495     InspectorBackend.setInjectedScriptSource("(" + injectedScriptConstructor + ");");
496
497     var platform = WebInspector.platform;
498     document.body.addStyleClass("platform-" + platform);
499     var flavor = WebInspector.platformFlavor;
500     if (flavor)
501         document.body.addStyleClass("platform-" + flavor);
502     var port = WebInspector.port;
503     document.body.addStyleClass("port-" + port);
504
505     InspectorFrontendHost.loaded();
506     WebInspector.settings = new WebInspector.Settings();
507
508     this._registerShortcuts();
509
510     // set order of some sections explicitly
511     WebInspector.shortcutsHelp.section(WebInspector.UIString("Console"));
512     WebInspector.shortcutsHelp.section(WebInspector.UIString("Elements Panel"));
513
514     this.drawer = new WebInspector.Drawer();
515     this.console = new WebInspector.ConsoleView(this.drawer);
516     // TODO: Uncomment when enabling the Changes Panel
517     // this.changes = new WebInspector.ChangesView(this.drawer);
518     // TODO: Remove class="hidden" from inspector.html on button#changes-status-bar-item
519     this.drawer.visibleView = this.console;
520     this.resourceManager = new WebInspector.ResourceManager();
521     this.domAgent = new WebInspector.DOMAgent();
522
523     InspectorBackend.registerDomainDispatcher("Inspector", this);
524
525     this.resourceCategories = {
526         documents: new WebInspector.ResourceCategory("documents", WebInspector.UIString("Documents"), "rgb(47,102,236)"),
527         stylesheets: new WebInspector.ResourceCategory("stylesheets", WebInspector.UIString("Stylesheets"), "rgb(157,231,119)"),
528         images: new WebInspector.ResourceCategory("images", WebInspector.UIString("Images"), "rgb(164,60,255)"),
529         scripts: new WebInspector.ResourceCategory("scripts", WebInspector.UIString("Scripts"), "rgb(255,121,0)"),
530         xhr: new WebInspector.ResourceCategory("xhr", WebInspector.UIString("XHR"), "rgb(231,231,10)"),
531         fonts: new WebInspector.ResourceCategory("fonts", WebInspector.UIString("Fonts"), "rgb(255,82,62)"),
532         websockets: new WebInspector.ResourceCategory("websockets", WebInspector.UIString("WebSocket"), "rgb(186,186,186)"), // FIXME: Decide the color.
533         other: new WebInspector.ResourceCategory("other", WebInspector.UIString("Other"), "rgb(186,186,186)")
534     };
535
536     this.breakpointManager = new WebInspector.BreakpointManager();
537     this.cssModel = new WebInspector.CSSStyleModel();
538
539     this.panels = {};
540     this._createPanels();
541     this._panelHistory = new WebInspector.PanelHistory();
542
543     var toolbarElement = document.getElementById("toolbar");
544     var previousToolbarItem = toolbarElement.children[0];
545
546     this.panelOrder = [];
547     for (var panelName in this.panels)
548         previousToolbarItem = WebInspector.addPanelToolbarIcon(toolbarElement, this.panels[panelName], previousToolbarItem);
549
550     this.Tips = {
551         ResourceNotCompressed: {id: 0, message: WebInspector.UIString("You could save bandwidth by having your web server compress this transfer with gzip or zlib.")}
552     };
553
554     this.Warnings = {
555         IncorrectMIMEType: {id: 0, message: WebInspector.UIString("Resource interpreted as %s but transferred with MIME type %s.")}
556     };
557
558     this.addMainEventListeners(document);
559
560     window.addEventListener("resize", this.windowResize.bind(this), true);
561
562     document.addEventListener("focus", this.focusChanged.bind(this), true);
563     document.addEventListener("keydown", this.documentKeyDown.bind(this), false);
564     document.addEventListener("beforecopy", this.documentCanCopy.bind(this), true);
565     document.addEventListener("copy", this.documentCopy.bind(this), true);
566     document.addEventListener("contextmenu", this.contextMenuEventFired.bind(this), true);
567
568     var dockToggleButton = document.getElementById("dock-status-bar-item");
569     dockToggleButton.addEventListener("click", this.toggleAttach.bind(this), false);
570
571     if (this.attached)
572         dockToggleButton.title = WebInspector.UIString("Undock into separate window.");
573     else
574         dockToggleButton.title = WebInspector.UIString("Dock to main window.");
575
576     var errorWarningCount = document.getElementById("error-warning-count");
577     errorWarningCount.addEventListener("click", this.showConsole.bind(this), false);
578     this._updateErrorAndWarningCounts();
579
580     this.styleChanges = 0;
581     // TODO: Uncomment when enabling the Changes Panel
582     // var changesElement = document.getElementById("changes-count");
583     // changesElement.addEventListener("click", this.showChanges.bind(this), false);
584     // this._updateErrorAndWarningCounts();
585
586     var searchField = document.getElementById("search");
587     searchField.addEventListener("search", this.performSearch.bind(this), false); // when the search is emptied
588     searchField.addEventListener("mousedown", this._searchFieldManualFocus.bind(this), false); // when the search field is manually selected
589     searchField.addEventListener("keydown", this._searchKeyDown.bind(this), true);
590
591     toolbarElement.addEventListener("mousedown", this.toolbarDragStart, true);
592     document.getElementById("close-button-left").addEventListener("click", this.close, true);
593     document.getElementById("close-button-right").addEventListener("click", this.close, true);
594
595     this.extensionServer.initExtensions();
596
597     function populateInspectorState(inspectorState)
598     {
599         WebInspector.monitoringXHREnabled = inspectorState.monitoringXHREnabled;
600         if ("pauseOnExceptionsState" in inspectorState)
601             WebInspector.panels.scripts.updatePauseOnExceptionsState(inspectorState.pauseOnExceptionsState);
602     }
603     InspectorBackend.getInspectorState(populateInspectorState);
604
605     function onPopulateScriptObjects()
606     {
607         if (!WebInspector.currentPanel)
608             WebInspector.showPanel(WebInspector.settings.lastActivePanel);
609     }
610     InspectorBackend.populateScriptObjects(onPopulateScriptObjects);
611
612     InspectorBackend.setConsoleMessagesEnabled(true);
613
614     // As a DOMAgent method, this needs to happen after the frontend has loaded and the agent is available.
615     InspectorBackend.getSupportedCSSProperties(WebInspector.CSSCompletions._load);
616 }
617
618 WebInspector.addPanelToolbarIcon = function(toolbarElement, panel, previousToolbarItem)
619 {
620     var panelToolbarItem = panel.toolbarItem;
621     this.panelOrder.push(panel);
622     panelToolbarItem.addEventListener("click", this._toolbarItemClicked.bind(this));
623     if (previousToolbarItem)
624         toolbarElement.insertBefore(panelToolbarItem, previousToolbarItem.nextSibling);
625     else
626         toolbarElement.insertBefore(panelToolbarItem, toolbarElement.firstChild);
627     return panelToolbarItem;
628 }
629
630 var windowLoaded = function()
631 {
632     var localizedStringsURL = InspectorFrontendHost.localizedStringsURL();
633     if (localizedStringsURL) {
634         var localizedStringsScriptElement = document.createElement("script");
635         localizedStringsScriptElement.addEventListener("load", WebInspector.loaded.bind(WebInspector), false);
636         localizedStringsScriptElement.type = "text/javascript";
637         localizedStringsScriptElement.src = localizedStringsURL;
638         document.head.appendChild(localizedStringsScriptElement);
639     } else
640         WebInspector.loaded();
641
642     window.removeEventListener("DOMContentLoaded", windowLoaded, false);
643     delete windowLoaded;
644 };
645
646 window.addEventListener("DOMContentLoaded", windowLoaded, false);
647
648 WebInspector.dispatch = function(message) {
649     // We'd like to enforce asynchronous interaction between the inspector controller and the frontend.
650     // This is important to LayoutTests.
651     function delayDispatch()
652     {
653         InspectorBackend.dispatch(message);
654         WebInspector.pendingDispatches--;
655     }
656     WebInspector.pendingDispatches++;
657     setTimeout(delayDispatch, 0);
658 }
659
660 WebInspector.dispatchMessageFromBackend = function(messageObject)
661 {
662     WebInspector.dispatch(messageObject);
663 }
664
665 WebInspector.windowResize = function(event)
666 {
667     if (this.currentPanel)
668         this.currentPanel.resize();
669     this.drawer.resize();
670 }
671
672 WebInspector.windowFocused = function(event)
673 {
674     // Fires after blur, so when focusing on either the main inspector
675     // or an <iframe> within the inspector we should always remove the
676     // "inactive" class.
677     if (event.target.document.nodeType === Node.DOCUMENT_NODE)
678         document.body.removeStyleClass("inactive");
679 }
680
681 WebInspector.windowBlurred = function(event)
682 {
683     // Leaving the main inspector or an <iframe> within the inspector.
684     // We can add "inactive" now, and if we are moving the focus to another
685     // part of the inspector then windowFocused will correct this.
686     if (event.target.document.nodeType === Node.DOCUMENT_NODE)
687         document.body.addStyleClass("inactive");
688 }
689
690 WebInspector.focusChanged = function(event)
691 {
692     this.currentFocusElement = event.target;
693 }
694
695 WebInspector.setAttachedWindow = function(attached)
696 {
697     this.attached = attached;
698 }
699
700 WebInspector.close = function(event)
701 {
702     if (this._isClosing)
703         return;
704     this._isClosing = true;
705     InspectorFrontendHost.closeWindow();
706 }
707
708 WebInspector.disconnectFromBackend = function()
709 {
710     InspectorFrontendHost.disconnectFromBackend();
711 }
712
713 WebInspector.documentClick = function(event)
714 {
715     var anchor = event.target.enclosingNodeOrSelfWithNodeName("a");
716     if (!anchor || anchor.target === "_blank")
717         return;
718
719     // Prevent the link from navigating, since we don't do any navigation by following links normally.
720     event.preventDefault();
721     event.stopPropagation();
722
723     function followLink()
724     {
725         // FIXME: support webkit-html-external-link links here.
726         if (WebInspector.canShowSourceLine(anchor.href, anchor.getAttribute("line_number"), anchor.getAttribute("preferred_panel"))) {
727             if (anchor.hasStyleClass("webkit-html-external-link")) {
728                 anchor.removeStyleClass("webkit-html-external-link");
729                 anchor.addStyleClass("webkit-html-resource-link");
730             }
731
732             WebInspector.showSourceLine(anchor.href, anchor.getAttribute("line_number"), anchor.getAttribute("preferred_panel"));
733             return;
734         }
735
736         const profileMatch = WebInspector.ProfileType.URLRegExp.exec(anchor.href);
737         if (profileMatch) {
738             WebInspector.showProfileForURL(anchor.href);
739             return;
740         }
741
742         var parsedURL = anchor.href.asParsedURL();
743         if (parsedURL && parsedURL.scheme === "webkit-link-action") {
744             if (parsedURL.host === "show-panel") {
745                 var panel = parsedURL.path.substring(1);
746                 if (WebInspector.panels[panel])
747                     WebInspector.showPanel(panel);
748             }
749             return;
750         }
751
752         WebInspector.showPanel("resources");
753     }
754
755     if (WebInspector.followLinkTimeout)
756         clearTimeout(WebInspector.followLinkTimeout);
757
758     if (anchor.preventFollowOnDoubleClick) {
759         // Start a timeout if this is the first click, if the timeout is canceled
760         // before it fires, then a double clicked happened or another link was clicked.
761         if (event.detail === 1)
762             WebInspector.followLinkTimeout = setTimeout(followLink, 333);
763         return;
764     }
765
766     followLink();
767 }
768
769 WebInspector.openResource = function(resourceURL, inResourcesPanel)
770 {
771     var resource = WebInspector.resourceForURL(resourceURL);
772     if (inResourcesPanel && resource) {
773         WebInspector.panels.resources.showResource(resource);
774         WebInspector.showPanel("resources");
775     } else
776         InspectorBackend.openInInspectedWindow(resource ? resource.url : resourceURL);
777 }
778
779 WebInspector._registerShortcuts = function()
780 {
781     var shortcut = WebInspector.KeyboardShortcut;
782     var section = WebInspector.shortcutsHelp.section(WebInspector.UIString("All Panels"));
783     var keys = [
784         shortcut.shortcutToString("]", shortcut.Modifiers.CtrlOrMeta),
785         shortcut.shortcutToString("[", shortcut.Modifiers.CtrlOrMeta)
786     ];
787     section.addRelatedKeys(keys, WebInspector.UIString("Next/previous panel"));
788     section.addKey(shortcut.shortcutToString(shortcut.Keys.Esc), WebInspector.UIString("Toggle console"));
789     section.addKey(shortcut.shortcutToString("f", shortcut.Modifiers.CtrlOrMeta), WebInspector.UIString("Search"));
790     keys = [
791         shortcut.shortcutToString("g", shortcut.Modifiers.CtrlOrMeta),
792         shortcut.shortcutToString("g", shortcut.Modifiers.CtrlOrMeta | shortcut.Modifiers.Shift)
793     ];
794     section.addRelatedKeys(keys, WebInspector.UIString("Find next/previous"));
795 }
796
797 WebInspector.documentKeyDown = function(event)
798 {
799     var isInputElement = event.target.nodeName === "INPUT";
800     var isInEditMode = event.target.enclosingNodeOrSelfWithClass("text-prompt") || WebInspector.isEditingAnyField();
801     const helpKey = WebInspector.isMac() ? "U+003F" : "U+00BF"; // "?" for both platforms
802
803     if (event.keyIdentifier === "F1" ||
804         (event.keyIdentifier === helpKey && event.shiftKey && (!isInEditMode && !isInputElement || event.metaKey))) {
805         WebInspector.shortcutsHelp.show();
806         event.stopPropagation();
807         event.preventDefault();
808         return;
809     }
810
811     if (WebInspector.isEditingAnyField())
812         return;
813
814     if (this.currentFocusElement && this.currentFocusElement.handleKeyEvent) {
815         this.currentFocusElement.handleKeyEvent(event);
816         if (event.handled) {
817             event.preventDefault();
818             return;
819         }
820     }
821
822     if (this.currentPanel && this.currentPanel.handleShortcut) {
823         this.currentPanel.handleShortcut(event);
824         if (event.handled) {
825             event.preventDefault();
826             return;
827         }
828     }
829
830     var isMac = WebInspector.isMac();
831     switch (event.keyIdentifier) {
832         case "Left":
833             var isBackKey = !isInEditMode && (isMac ? event.metaKey : event.ctrlKey);
834             if (isBackKey && this._panelHistory.canGoBack()) {
835                 this._panelHistory.goBack();
836                 event.preventDefault();
837             }
838             break;
839
840         case "Right":
841             var isForwardKey = !isInEditMode && (isMac ? event.metaKey : event.ctrlKey);
842             if (isForwardKey && this._panelHistory.canGoForward()) {
843                 this._panelHistory.goForward();
844                 event.preventDefault();
845             }
846             break;
847
848         case "U+001B": // Escape key
849             event.preventDefault();
850             if (this.drawer.fullPanel)
851                 return;
852
853             this.drawer.visible = !this.drawer.visible;
854             break;
855
856         case "U+0046": // F key
857             if (isMac)
858                 var isFindKey = event.metaKey && !event.ctrlKey && !event.altKey && !event.shiftKey;
859             else
860                 var isFindKey = event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey;
861
862             if (isFindKey) {
863                 WebInspector.focusSearchField();
864                 event.preventDefault();
865             }
866             break;
867
868         case "F3":
869             if (!isMac) {
870                 WebInspector.focusSearchField();
871                 event.preventDefault();
872             }
873             break;
874
875         case "U+0047": // G key
876             if (isMac)
877                 var isFindAgainKey = event.metaKey && !event.ctrlKey && !event.altKey;
878             else
879                 var isFindAgainKey = event.ctrlKey && !event.metaKey && !event.altKey;
880
881             if (isFindAgainKey) {
882                 if (event.shiftKey) {
883                     if (this.currentPanel.jumpToPreviousSearchResult)
884                         this.currentPanel.jumpToPreviousSearchResult();
885                 } else if (this.currentPanel.jumpToNextSearchResult)
886                     this.currentPanel.jumpToNextSearchResult();
887                 event.preventDefault();
888             }
889
890             break;
891
892         // Windows and Mac have two different definitions of [, so accept both.
893         case "U+005B":
894         case "U+00DB": // [ key
895             if (isMac)
896                 var isRotateLeft = event.metaKey && !event.shiftKey && !event.ctrlKey && !event.altKey;
897             else
898                 var isRotateLeft = event.ctrlKey && !event.shiftKey && !event.metaKey && !event.altKey;
899
900             if (isRotateLeft) {
901                 var index = this.panelOrder.indexOf(this.currentPanel);
902                 index = (index === 0) ? this.panelOrder.length - 1 : index - 1;
903                 this.panelOrder[index].toolbarItem.click();
904                 event.preventDefault();
905             }
906
907             break;
908
909         // Windows and Mac have two different definitions of ], so accept both.
910         case "U+005D":
911         case "U+00DD":  // ] key
912             if (isMac)
913                 var isRotateRight = event.metaKey && !event.shiftKey && !event.ctrlKey && !event.altKey;
914             else
915                 var isRotateRight = event.ctrlKey && !event.shiftKey && !event.metaKey && !event.altKey;
916
917             if (isRotateRight) {
918                 var index = this.panelOrder.indexOf(this.currentPanel);
919                 index = (index + 1) % this.panelOrder.length;
920                 this.panelOrder[index].toolbarItem.click();
921                 event.preventDefault();
922             }
923
924             break;
925
926         case "U+0052": // R key
927             if ((event.metaKey && isMac) || (event.ctrlKey && !isMac)) {
928                 InspectorBackend.reloadPage();
929                 event.preventDefault();
930             }
931             break;
932         case "F5":
933             if (!isMac)
934                 InspectorBackend.reloadPage();
935             break;
936     }
937 }
938
939 WebInspector.documentCanCopy = function(event)
940 {
941     if (this.currentPanel && this.currentPanel.handleCopyEvent)
942         event.preventDefault();
943 }
944
945 WebInspector.documentCopy = function(event)
946 {
947     if (this.currentPanel && this.currentPanel.handleCopyEvent)
948         this.currentPanel.handleCopyEvent(event);
949 }
950
951 WebInspector.contextMenuEventFired = function(event)
952 {
953     if (event.handled || event.target.hasStyleClass("popup-glasspane"))
954         event.preventDefault();
955 }
956
957 WebInspector.animateStyle = function(animations, duration, callback)
958 {
959     var interval;
960     var complete = 0;
961
962     const intervalDuration = (1000 / 30); // 30 frames per second.
963     const animationsLength = animations.length;
964     const propertyUnit = {opacity: ""};
965     const defaultUnit = "px";
966
967     function cubicInOut(t, b, c, d)
968     {
969         if ((t/=d/2) < 1) return c/2*t*t*t + b;
970         return c/2*((t-=2)*t*t + 2) + b;
971     }
972
973     // Pre-process animations.
974     for (var i = 0; i < animationsLength; ++i) {
975         var animation = animations[i];
976         var element = null, start = null, end = null, key = null;
977         for (key in animation) {
978             if (key === "element")
979                 element = animation[key];
980             else if (key === "start")
981                 start = animation[key];
982             else if (key === "end")
983                 end = animation[key];
984         }
985
986         if (!element || !end)
987             continue;
988
989         if (!start) {
990             var computedStyle = element.ownerDocument.defaultView.getComputedStyle(element);
991             start = {};
992             for (key in end)
993                 start[key] = parseInt(computedStyle.getPropertyValue(key));
994             animation.start = start;
995         } else
996             for (key in start)
997                 element.style.setProperty(key, start[key] + (key in propertyUnit ? propertyUnit[key] : defaultUnit));
998     }
999
1000     function animateLoop()
1001     {
1002         // Advance forward.
1003         complete += intervalDuration;
1004         var next = complete + intervalDuration;
1005
1006         // Make style changes.
1007         for (var i = 0; i < animationsLength; ++i) {
1008             var animation = animations[i];
1009             var element = animation.element;
1010             var start = animation.start;
1011             var end = animation.end;
1012             if (!element || !end)
1013                 continue;
1014
1015             var style = element.style;
1016             for (key in end) {
1017                 var endValue = end[key];
1018                 if (next < duration) {
1019                     var startValue = start[key];
1020                     var newValue = cubicInOut(complete, startValue, endValue - startValue, duration);
1021                     style.setProperty(key, newValue + (key in propertyUnit ? propertyUnit[key] : defaultUnit));
1022                 } else
1023                     style.setProperty(key, endValue + (key in propertyUnit ? propertyUnit[key] : defaultUnit));
1024             }
1025         }
1026
1027         // End condition.
1028         if (complete >= duration) {
1029             clearInterval(interval);
1030             if (callback)
1031                 callback();
1032         }
1033     }
1034
1035     interval = setInterval(animateLoop, intervalDuration);
1036     return interval;
1037 }
1038
1039 WebInspector.updateSearchLabel = function()
1040 {
1041     if (!this.currentPanel)
1042         return;
1043
1044     var newLabel = WebInspector.UIString("Search %s", this.currentPanel.toolbarItemLabel);
1045     if (this.attached)
1046         document.getElementById("search").setAttribute("placeholder", newLabel);
1047     else {
1048         document.getElementById("search").removeAttribute("placeholder");
1049         document.getElementById("search-toolbar-label").textContent = newLabel;
1050     }
1051 }
1052
1053 WebInspector.focusSearchField = function()
1054 {
1055     var searchField = document.getElementById("search");
1056     searchField.focus();
1057     searchField.select();
1058 }
1059
1060 WebInspector.toggleAttach = function()
1061 {
1062     if (!this.attached)
1063         InspectorFrontendHost.requestAttachWindow();
1064     else
1065         InspectorFrontendHost.requestDetachWindow();
1066 }
1067
1068 WebInspector.toolbarDragStart = function(event)
1069 {
1070     if ((!WebInspector.attached && WebInspector.platformFlavor !== WebInspector.PlatformFlavor.MacLeopard && WebInspector.platformFlavor !== WebInspector.PlatformFlavor.MacSnowLeopard) || WebInspector.port == "qt")
1071         return;
1072
1073     var target = event.target;
1074     if (target.hasStyleClass("toolbar-item") && target.hasStyleClass("toggleable"))
1075         return;
1076
1077     var toolbar = document.getElementById("toolbar");
1078     if (target !== toolbar && !target.hasStyleClass("toolbar-item"))
1079         return;
1080
1081     toolbar.lastScreenX = event.screenX;
1082     toolbar.lastScreenY = event.screenY;
1083
1084     WebInspector.elementDragStart(toolbar, WebInspector.toolbarDrag, WebInspector.toolbarDragEnd, event, (WebInspector.attached ? "row-resize" : "default"));
1085 }
1086
1087 WebInspector.toolbarDragEnd = function(event)
1088 {
1089     var toolbar = document.getElementById("toolbar");
1090
1091     WebInspector.elementDragEnd(event);
1092
1093     delete toolbar.lastScreenX;
1094     delete toolbar.lastScreenY;
1095 }
1096
1097 WebInspector.toolbarDrag = function(event)
1098 {
1099     var toolbar = document.getElementById("toolbar");
1100
1101     if (WebInspector.attached) {
1102         var height = window.innerHeight - (event.screenY - toolbar.lastScreenY);
1103
1104         InspectorFrontendHost.setAttachedWindowHeight(height);
1105     } else {
1106         var x = event.screenX - toolbar.lastScreenX;
1107         var y = event.screenY - toolbar.lastScreenY;
1108
1109         // We cannot call window.moveBy here because it restricts the movement
1110         // of the window at the edges.
1111         InspectorFrontendHost.moveWindowBy(x, y);
1112     }
1113
1114     toolbar.lastScreenX = event.screenX;
1115     toolbar.lastScreenY = event.screenY;
1116
1117     event.preventDefault();
1118 }
1119
1120 WebInspector.elementDragStart = function(element, dividerDrag, elementDragEnd, event, cursor)
1121 {
1122     if (this._elementDraggingEventListener || this._elementEndDraggingEventListener)
1123         this.elementDragEnd(event);
1124
1125     this._elementDraggingEventListener = dividerDrag;
1126     this._elementEndDraggingEventListener = elementDragEnd;
1127
1128     document.addEventListener("mousemove", dividerDrag, true);
1129     document.addEventListener("mouseup", elementDragEnd, true);
1130
1131     document.body.style.cursor = cursor;
1132
1133     event.preventDefault();
1134 }
1135
1136 WebInspector.elementDragEnd = function(event)
1137 {
1138     document.removeEventListener("mousemove", this._elementDraggingEventListener, true);
1139     document.removeEventListener("mouseup", this._elementEndDraggingEventListener, true);
1140
1141     document.body.style.removeProperty("cursor");
1142
1143     delete this._elementDraggingEventListener;
1144     delete this._elementEndDraggingEventListener;
1145
1146     event.preventDefault();
1147 }
1148
1149 WebInspector.toggleSearchingForNode = function()
1150 {
1151     if (this.panels.elements) {
1152         this.showPanel("elements");
1153         this.panels.elements.toggleSearchingForNode();
1154     }
1155 }
1156
1157 WebInspector.showConsole = function()
1158 {
1159     this.drawer.showView(this.console);
1160 }
1161
1162 WebInspector.showChanges = function()
1163 {
1164     this.drawer.showView(this.changes);
1165 }
1166
1167 WebInspector.showPanel = function(panel)
1168 {
1169     if (!(panel in this.panels))
1170         panel = "elements";
1171     this.currentPanel = this.panels[panel];
1172 }
1173
1174 WebInspector.selectDatabase = function(o)
1175 {
1176     WebInspector.showPanel("resources");
1177     WebInspector.panels.resources.selectDatabase(o);
1178 }
1179
1180 WebInspector.consoleMessagesCleared = function()
1181 {
1182     WebInspector.console.clearMessages();
1183 }
1184
1185 WebInspector.selectDOMStorage = function(o)
1186 {
1187     WebInspector.showPanel("resources");
1188     WebInspector.panels.resources.selectDOMStorage(o);
1189 }
1190
1191 WebInspector.domContentEventFired = function(time)
1192 {
1193     this.panels.audits.mainResourceDOMContentTime = time;
1194     if (this.panels.network)
1195         this.panels.network.mainResourceDOMContentTime = time;
1196     this.extensionServer.notifyPageDOMContentLoaded((time - WebInspector.mainResource.startTime) * 1000);
1197     this.mainResourceDOMContentTime = time;
1198 }
1199
1200 WebInspector.loadEventFired = function(time)
1201 {
1202     this.panels.audits.mainResourceLoadTime = time;
1203     if (this.panels.network)
1204         this.panels.network.mainResourceLoadTime = time;
1205     this.extensionServer.notifyPageLoaded((time - WebInspector.mainResource.startTime) * 1000);
1206     this.mainResourceLoadTime = time;
1207 }
1208
1209 WebInspector.addDatabase = function(payload)
1210 {
1211     if (!this.panels.resources)
1212         return;
1213     var database = new WebInspector.Database(
1214         payload.id,
1215         payload.domain,
1216         payload.name,
1217         payload.version);
1218     this.panels.resources.addDatabase(database);
1219 }
1220
1221 WebInspector.addDOMStorage = function(payload)
1222 {
1223     if (!this.panels.resources)
1224         return;
1225     var domStorage = new WebInspector.DOMStorage(
1226         payload.id,
1227         payload.host,
1228         payload.isLocalStorage);
1229     this.panels.resources.addDOMStorage(domStorage);
1230 }
1231
1232 WebInspector.updateDOMStorage = function(storageId)
1233 {
1234     this.panels.resources.updateDOMStorage(storageId);
1235 }
1236
1237 WebInspector.updateApplicationCacheStatus = function(status)
1238 {
1239     this.panels.resources.updateApplicationCacheStatus(status);
1240 }
1241
1242 WebInspector.didGetFileSystemPath = function(root, type, origin)
1243 {
1244     this.panels.resources.updateFileSystemPath(root, type, origin);
1245 }
1246
1247 WebInspector.didGetFileSystemError = function(type, origin)
1248 {
1249     this.panels.resources.updateFileSystemError(type, origin);
1250 }
1251
1252 WebInspector.didGetFileSystemDisabled = function()
1253 {
1254     this.panels.resources.setFileSystemDisabled();
1255 }
1256
1257 WebInspector.updateNetworkState = function(isNowOnline)
1258 {
1259     this.panels.resources.updateNetworkState(isNowOnline);
1260 }
1261
1262 WebInspector.searchingForNodeWasEnabled = function()
1263 {
1264     this.panels.elements.searchingForNodeWasEnabled();
1265 }
1266
1267 WebInspector.searchingForNodeWasDisabled = function()
1268 {
1269     this.panels.elements.searchingForNodeWasDisabled();
1270 }
1271
1272 WebInspector.attachDebuggerWhenShown = function()
1273 {
1274     this.panels.scripts.attachDebuggerWhenShown();
1275 }
1276
1277 WebInspector.debuggerWasEnabled = function()
1278 {
1279     this.panels.scripts.debuggerWasEnabled();
1280 }
1281
1282 WebInspector.debuggerWasDisabled = function()
1283 {
1284     this.panels.scripts.debuggerWasDisabled();
1285 }
1286
1287 WebInspector.profilerWasEnabled = function()
1288 {
1289     this.panels.profiles.profilerWasEnabled();
1290 }
1291
1292 WebInspector.profilerWasDisabled = function()
1293 {
1294     this.panels.profiles.profilerWasDisabled();
1295 }
1296
1297 WebInspector.parsedScriptSource = function(sourceID, sourceURL, source, startingLine, scriptWorldType)
1298 {
1299     this.panels.scripts.addScript(sourceID, sourceURL, source, startingLine, undefined, undefined, scriptWorldType);
1300 }
1301
1302 WebInspector.restoredBreakpoint = function(sourceID, sourceURL, line, enabled, condition)
1303 {
1304     this.breakpointManager.restoredBreakpoint(sourceID, sourceURL, line, enabled, condition);
1305 }
1306
1307 WebInspector.failedToParseScriptSource = function(sourceURL, source, startingLine, errorLine, errorMessage)
1308 {
1309     this.panels.scripts.addScript(null, sourceURL, source, startingLine, errorLine, errorMessage);
1310 }
1311
1312 WebInspector.pausedScript = function(details)
1313 {
1314     this.panels.scripts.debuggerPaused(details.callFrames);
1315     this.breakpointManager.debuggerPaused(details);
1316     InspectorFrontendHost.bringToFront();
1317 }
1318
1319 WebInspector.resumedScript = function()
1320 {
1321     this.breakpointManager.debuggerResumed();
1322     this.panels.scripts.debuggerResumed();
1323 }
1324
1325 WebInspector.reset = function()
1326 {
1327     this.breakpointManager.reset();
1328
1329     for (var panelName in this.panels) {
1330         var panel = this.panels[panelName];
1331         if ("reset" in panel)
1332             panel.reset();
1333     }
1334
1335     this.resources = {};
1336     this.highlightDOMNode(0);
1337
1338     this.console.clearMessages();
1339     this.extensionServer.notifyInspectorReset();
1340
1341     this.breakpointManager.restoreBreakpoints();
1342 }
1343
1344 WebInspector.resetProfilesPanel = function()
1345 {
1346     if (WebInspector.panels.profiles)
1347         WebInspector.panels.profiles.resetProfiles();
1348 }
1349
1350 WebInspector.bringToFront = function()
1351 {
1352     InspectorFrontendHost.bringToFront();
1353 }
1354
1355 WebInspector.inspectedURLChanged = function(url)
1356 {
1357     InspectorFrontendHost.inspectedURLChanged(url);
1358     this.settings.inspectedURLChanged(url);
1359     this.extensionServer.notifyInspectedURLChanged();
1360     if (!this._breakpointsRestored) {
1361         this.breakpointManager.restoreBreakpoints();
1362         this._breakpointsRestored = true;
1363     }
1364 }
1365
1366 WebInspector.didCommitLoad = function()
1367 {
1368     // Cleanup elements panel early on inspected page refresh.
1369     WebInspector.setDocument(null);
1370 }
1371
1372 WebInspector.updateConsoleMessageExpiredCount = function(count)
1373 {
1374     var message = String.sprintf(WebInspector.UIString("%d console messages are not shown."), count);
1375     WebInspector.console.addMessage(WebInspector.ConsoleMessage.createTextMessage(message, WebInspector.ConsoleMessage.MessageLevel.Warning));
1376 }
1377
1378 WebInspector.addConsoleMessage = function(payload)
1379 {
1380     var consoleMessage = new WebInspector.ConsoleMessage(
1381         payload.source,
1382         payload.type,
1383         payload.level,
1384         payload.line,
1385         payload.url,
1386         payload.groupLevel,
1387         payload.repeatCount,
1388         payload.message,
1389         payload.parameters,
1390         payload.stackTrace);
1391     this.console.addMessage(consoleMessage);
1392 }
1393
1394 WebInspector.updateConsoleMessageRepeatCount = function(count)
1395 {
1396     this.console.updateMessageRepeatCount(count);
1397 }
1398
1399 WebInspector.log = function(message, messageLevel)
1400 {
1401     // remember 'this' for setInterval() callback
1402     var self = this;
1403
1404     // return indication if we can actually log a message
1405     function isLogAvailable()
1406     {
1407         return WebInspector.ConsoleMessage && WebInspector.RemoteObject && self.console;
1408     }
1409
1410     // flush the queue of pending messages
1411     function flushQueue()
1412     {
1413         var queued = WebInspector.log.queued;
1414         if (!queued)
1415             return;
1416
1417         for (var i = 0; i < queued.length; ++i)
1418             logMessage(queued[i]);
1419
1420         delete WebInspector.log.queued;
1421     }
1422
1423     // flush the queue if it console is available
1424     // - this function is run on an interval
1425     function flushQueueIfAvailable()
1426     {
1427         if (!isLogAvailable())
1428             return;
1429
1430         clearInterval(WebInspector.log.interval);
1431         delete WebInspector.log.interval;
1432
1433         flushQueue();
1434     }
1435
1436     // actually log the message
1437     function logMessage(message)
1438     {
1439         var repeatCount = 1;
1440         if (message == WebInspector.log.lastMessage)
1441             repeatCount = WebInspector.log.repeatCount + 1;
1442
1443         WebInspector.log.lastMessage = message;
1444         WebInspector.log.repeatCount = repeatCount;
1445
1446         // ConsoleMessage expects a proxy object
1447         message = new WebInspector.RemoteObject.fromPrimitiveValue(message);
1448
1449         // post the message
1450         var msg = new WebInspector.ConsoleMessage(
1451             WebInspector.ConsoleMessage.MessageSource.Other,
1452             WebInspector.ConsoleMessage.MessageType.Log,
1453             messageLevel || WebInspector.ConsoleMessage.MessageLevel.Debug,
1454             -1,
1455             null,
1456             null,
1457             repeatCount,
1458             null,
1459             [message],
1460             null);
1461
1462         self.console.addMessage(msg);
1463     }
1464
1465     // if we can't log the message, queue it
1466     if (!isLogAvailable()) {
1467         if (!WebInspector.log.queued)
1468             WebInspector.log.queued = [];
1469
1470         WebInspector.log.queued.push(message);
1471
1472         if (!WebInspector.log.interval)
1473             WebInspector.log.interval = setInterval(flushQueueIfAvailable, 1000);
1474
1475         return;
1476     }
1477
1478     // flush the pending queue if any
1479     flushQueue();
1480
1481     // log the message
1482     logMessage(message);
1483 }
1484
1485 WebInspector.addProfileHeader = function(profile)
1486 {
1487     this.panels.profiles.addProfileHeader(profile);
1488 }
1489
1490 WebInspector.setRecordingProfile = function(isProfiling)
1491 {
1492     this.panels.profiles.getProfileType(WebInspector.CPUProfileType.TypeId).setRecordingProfile(isProfiling);
1493     if (this.panels.profiles.hasTemporaryProfile(WebInspector.CPUProfileType.TypeId) !== isProfiling) {
1494         if (!this._temporaryRecordingProfile) {
1495             this._temporaryRecordingProfile = {
1496                 typeId: WebInspector.CPUProfileType.TypeId,
1497                 title: WebInspector.UIString("Recording…"),
1498                 uid: -1,
1499                 isTemporary: true
1500             };
1501         }
1502         if (isProfiling)
1503             this.panels.profiles.addProfileHeader(this._temporaryRecordingProfile);
1504         else
1505             this.panels.profiles.removeProfileHeader(this._temporaryRecordingProfile);
1506     }
1507     this.panels.profiles.updateProfileTypeButtons();
1508 }
1509
1510 WebInspector.addHeapSnapshotChunk = function(uid, chunk)
1511 {
1512     this.panels.profiles.addHeapSnapshotChunk(uid, chunk);
1513 }
1514
1515 WebInspector.finishHeapSnapshot = function(uid)
1516 {
1517     this.panels.profiles.finishHeapSnapshot(uid);
1518 }
1519
1520 WebInspector.drawLoadingPieChart = function(canvas, percent) {
1521     var g = canvas.getContext("2d");
1522     var darkColor = "rgb(122, 168, 218)";
1523     var lightColor = "rgb(228, 241, 251)";
1524     var cx = 8;
1525     var cy = 8;
1526     var r = 7;
1527
1528     g.beginPath();
1529     g.arc(cx, cy, r, 0, Math.PI * 2, false);
1530     g.closePath();
1531
1532     g.lineWidth = 1;
1533     g.strokeStyle = darkColor;
1534     g.fillStyle = lightColor;
1535     g.fill();
1536     g.stroke();
1537
1538     var startangle = -Math.PI / 2;
1539     var endangle = startangle + (percent * Math.PI * 2);
1540
1541     g.beginPath();
1542     g.moveTo(cx, cy);
1543     g.arc(cx, cy, r, startangle, endangle, false);
1544     g.closePath();
1545
1546     g.fillStyle = darkColor;
1547     g.fill();
1548 }
1549
1550 WebInspector.updateFocusedNode = function(nodeId)
1551 {
1552     this._updateFocusedNode(nodeId);
1553     this.highlightDOMNodeForTwoSeconds(nodeId);
1554 }
1555
1556 WebInspector.displayNameForURL = function(url)
1557 {
1558     if (!url)
1559         return "";
1560
1561     var resource = this.resourceForURL(url);
1562     if (resource)
1563         return resource.displayName;
1564
1565     if (!WebInspector.mainResource)
1566         return url.trimURL("");
1567
1568     var lastPathComponent = WebInspector.mainResource.lastPathComponent;
1569     var index = WebInspector.mainResource.url.indexOf(lastPathComponent);
1570     if (index !== -1 && index + lastPathComponent.length === WebInspector.mainResource.url.length) {
1571         var baseURL = WebInspector.mainResource.url.substring(0, index);
1572         if (url.indexOf(baseURL) === 0)
1573             return url.substring(index);
1574     }
1575
1576     return url.trimURL(WebInspector.mainResource.domain);
1577 }
1578
1579 WebInspector._choosePanelToShowSourceLine = function(url, line, preferredPanel)
1580 {
1581     preferredPanel = preferredPanel || "resources";
1582
1583     var panel = this.panels[preferredPanel];
1584     if (panel && panel.canShowSourceLine(url, line))
1585         return panel;
1586     panel = this.panels.resources;
1587     return panel.canShowSourceLine(url, line) ? panel : null;
1588 }
1589
1590 WebInspector.canShowSourceLine = function(url, line, preferredPanel)
1591 {
1592     return !!this._choosePanelToShowSourceLine(url, line, preferredPanel);
1593 }
1594
1595 WebInspector.showSourceLine = function(url, line, preferredPanel)
1596 {
1597     this.currentPanel = this._choosePanelToShowSourceLine(url, line, preferredPanel);
1598     if (!this.currentPanel)
1599         return false;
1600     this.currentPanel.showSourceLine(url, line);
1601     return true;
1602 }
1603
1604 WebInspector.linkifyStringAsFragment = function(string)
1605 {
1606     var container = document.createDocumentFragment();
1607     var linkStringRegEx = /(?:[a-zA-Z][a-zA-Z0-9+.-]{2,}:\/\/|www\.)[\w$\-_+*'=\|\/\\(){}[\]%@&#~,:;.!?]{2,}[\w$\-_+*=\|\/\\({%@&#~]/;
1608     var lineColumnRegEx = /:(\d+)(:(\d+))?$/;
1609
1610     while (string) {
1611         var linkString = linkStringRegEx.exec(string);
1612         if (!linkString)
1613             break;
1614
1615         linkString = linkString[0];
1616         var title = linkString;
1617         var linkIndex = string.indexOf(linkString);
1618         var nonLink = string.substring(0, linkIndex);
1619         container.appendChild(document.createTextNode(nonLink));
1620
1621         var profileStringMatches = WebInspector.ProfileType.URLRegExp.exec(title);
1622         if (profileStringMatches)
1623             title = WebInspector.panels.profiles.displayTitleForProfileLink(profileStringMatches[2], profileStringMatches[1]);
1624
1625         var realURL = (linkString.indexOf("www.") === 0 ? "http://" + linkString : linkString);
1626         var lineColumnMatch = lineColumnRegEx.exec(realURL);
1627         if (lineColumnMatch)
1628             realURL = realURL.substring(0, realURL.length - lineColumnMatch[0].length);
1629
1630         var hasResourceWithURL = !!WebInspector.resourceForURL(realURL);
1631         var urlNode = WebInspector.linkifyURLAsNode(realURL, title, null, hasResourceWithURL);
1632         container.appendChild(urlNode);
1633         if (lineColumnMatch) {
1634             urlNode.setAttribute("line_number", lineColumnMatch[1]);
1635             urlNode.setAttribute("preferred_panel", "scripts");
1636         }
1637         string = string.substring(linkIndex + linkString.length, string.length);
1638     }
1639
1640     if (string)
1641         container.appendChild(document.createTextNode(string));
1642
1643     return container;
1644 }
1645
1646 WebInspector.showProfileForURL = function(url)
1647 {
1648     WebInspector.showPanel("profiles");
1649     WebInspector.panels.profiles.showProfileForURL(url);
1650 }
1651
1652 WebInspector.linkifyURLAsNode = function(url, linkText, classes, isExternal, tooltipText)
1653 {
1654     if (!linkText)
1655         linkText = url;
1656     classes = (classes ? classes + " " : "");
1657     classes += isExternal ? "webkit-html-external-link" : "webkit-html-resource-link";
1658
1659     var a = document.createElement("a");
1660     a.href = url;
1661     a.className = classes;
1662     if (typeof tooltipText === "undefined")
1663         a.title = url;
1664     else if (typeof tooltipText !== "string" || tooltipText.length)
1665         a.title = tooltipText;
1666     a.textContent = linkText;
1667
1668     return a;
1669 }
1670
1671 WebInspector.linkifyURL = function(url, linkText, classes, isExternal, tooltipText)
1672 {
1673     // Use the DOM version of this function so as to avoid needing to escape attributes.
1674     // FIXME:  Get rid of linkifyURL entirely.
1675     return WebInspector.linkifyURLAsNode(url, linkText, classes, isExternal, tooltipText).outerHTML;
1676 }
1677
1678 WebInspector.linkifyResourceAsNode = function(url, preferredPanel, lineNumber, classes, tooltipText)
1679 {
1680     var linkText = WebInspector.displayNameForURL(url);
1681     if (lineNumber)
1682         linkText += ":" + lineNumber;
1683     var node = WebInspector.linkifyURLAsNode(url, linkText, classes, false, tooltipText);
1684     node.setAttribute("line_number", lineNumber);
1685     node.setAttribute("preferred_panel", preferredPanel);
1686     return node;
1687 }
1688
1689 WebInspector.resourceURLForRelatedNode = function(node, url)
1690 {
1691     if (!url || url.indexOf("://") > 0)
1692         return url;
1693
1694     for (var frameOwnerCandidate = node; frameOwnerCandidate; frameOwnerCandidate = frameOwnerCandidate.parentNode) {
1695         if (frameOwnerCandidate.documentURL) {
1696             var result = WebInspector.completeURL(frameOwnerCandidate.documentURL, url);
1697             if (result)
1698                 return result;
1699             break;
1700         }
1701     }
1702
1703     // documentURL not found or has bad value
1704     var resourceURL = url;
1705     function callback(resource)
1706     {
1707         if (resource.path === url) {
1708             resourceURL = resource.url;
1709             return true;
1710         }
1711     }
1712     WebInspector.forAllResources(callback);
1713     return resourceURL;
1714 }
1715
1716 WebInspector.completeURL = function(baseURL, href)
1717 {
1718     var parsedURL = baseURL.asParsedURL();
1719     if (parsedURL) {
1720         var path = href;
1721         if (path.charAt(0) !== "/") {
1722             var basePath = parsedURL.path;
1723             path = basePath.substring(0, basePath.lastIndexOf("/")) + "/" + path;
1724         } else if (path.length > 1 && path.charAt(1) === "/") {
1725             // href starts with "//" which is a full URL with the protocol dropped (use the baseURL protocol).
1726             return parsedURL.scheme + ":" + path;
1727         }
1728         return parsedURL.scheme + "://" + parsedURL.host + (parsedURL.port ? (":" + parsedURL.port) : "") + path;
1729     }
1730     return null;
1731 }
1732
1733 WebInspector.addMainEventListeners = function(doc)
1734 {
1735     doc.defaultView.addEventListener("focus", this.windowFocused.bind(this), false);
1736     doc.defaultView.addEventListener("blur", this.windowBlurred.bind(this), false);
1737     doc.addEventListener("click", this.documentClick.bind(this), true);
1738 }
1739
1740 WebInspector._searchFieldManualFocus = function(event)
1741 {
1742     this.currentFocusElement = event.target;
1743     this._previousFocusElement = event.target;
1744 }
1745
1746 WebInspector._searchKeyDown = function(event)
1747 {
1748     // Escape Key will clear the field and clear the search results
1749     if (event.keyCode === WebInspector.KeyboardShortcut.Keys.Esc.code) {
1750         // If focus belongs here and text is empty - nothing to do, return unhandled.
1751         if (event.target.value === "" && this.currentFocusElement === this.previousFocusElement)
1752             return;
1753         event.preventDefault();
1754         event.stopPropagation();
1755         // When search was selected manually and is currently blank, we'd like Esc stay unhandled
1756         // and hit console drawer handler.
1757         event.target.value = "";
1758
1759         this.performSearch(event);
1760         this.currentFocusElement = this.previousFocusElement;
1761         if (this.currentFocusElement === event.target)
1762             this.currentFocusElement.select();
1763         return false;
1764     }
1765
1766     if (!isEnterKey(event))
1767         return false;
1768
1769     // Select all of the text so the user can easily type an entirely new query.
1770     event.target.select();
1771
1772     // Only call performSearch if the Enter key was pressed. Otherwise the search
1773     // performance is poor because of searching on every key. The search field has
1774     // the incremental attribute set, so we still get incremental searches.
1775     this.performSearch(event);
1776
1777     // Call preventDefault since this was the Enter key. This prevents a "search" event
1778     // from firing for key down. This stops performSearch from being called twice in a row.
1779     event.preventDefault();
1780 }
1781
1782 WebInspector.performSearch = function(event)
1783 {
1784     var forceSearch = event.keyIdentifier === "Enter";
1785     this.doPerformSearch(event.target.value, forceSearch, event.shiftKey, false);
1786 }
1787
1788 WebInspector.doPerformSearch = function(query, forceSearch, isBackwardSearch, repeatSearch)
1789 {
1790     var isShortSearch = (query.length < 3);
1791
1792     // Clear a leftover short search flag due to a non-conflicting forced search.
1793     if (isShortSearch && this.shortSearchWasForcedByKeyEvent && this.currentQuery !== query)
1794         delete this.shortSearchWasForcedByKeyEvent;
1795
1796     // Indicate this was a forced search on a short query.
1797     if (isShortSearch && forceSearch)
1798         this.shortSearchWasForcedByKeyEvent = true;
1799
1800     if (!query || !query.length || (!forceSearch && isShortSearch)) {
1801         // Prevent clobbering a short search forced by the user.
1802         if (this.shortSearchWasForcedByKeyEvent) {
1803             delete this.shortSearchWasForcedByKeyEvent;
1804             return;
1805         }
1806
1807         delete this.currentQuery;
1808
1809         for (var panelName in this.panels) {
1810             var panel = this.panels[panelName];
1811             var hadCurrentQuery = !!panel.currentQuery;
1812             delete panel.currentQuery;
1813             if (hadCurrentQuery && panel.searchCanceled)
1814                 panel.searchCanceled();
1815         }
1816
1817         this.updateSearchMatchesCount();
1818
1819         return;
1820     }
1821
1822     if (!repeatSearch && query === this.currentPanel.currentQuery && this.currentPanel.currentQuery === this.currentQuery) {
1823         // When this is the same query and a forced search, jump to the next
1824         // search result for a good user experience.
1825         if (forceSearch) {
1826             if (!isBackwardSearch && this.currentPanel.jumpToNextSearchResult)
1827                 this.currentPanel.jumpToNextSearchResult();
1828             else if (isBackwardSearch && this.currentPanel.jumpToPreviousSearchResult)
1829                 this.currentPanel.jumpToPreviousSearchResult();
1830         }
1831         return;
1832     }
1833
1834     this.currentQuery = query;
1835
1836     this.updateSearchMatchesCount();
1837
1838     if (!this.currentPanel.performSearch)
1839         return;
1840
1841     this.currentPanel.currentQuery = query;
1842     this.currentPanel.performSearch(query);
1843 }
1844
1845 WebInspector.addNodesToSearchResult = function(nodeIds)
1846 {
1847     WebInspector.panels.elements.addNodesToSearchResult(nodeIds);
1848 }
1849
1850 WebInspector.updateSearchMatchesCount = function(matches, panel)
1851 {
1852     if (!panel)
1853         panel = this.currentPanel;
1854
1855     panel.currentSearchMatches = matches;
1856
1857     if (panel !== this.currentPanel)
1858         return;
1859
1860     if (!this.currentPanel.currentQuery) {
1861         document.getElementById("search-results-matches").addStyleClass("hidden");
1862         return;
1863     }
1864
1865     if (matches) {
1866         if (matches === 1)
1867             var matchesString = WebInspector.UIString("1 match");
1868         else
1869             var matchesString = WebInspector.UIString("%d matches", matches);
1870     } else
1871         var matchesString = WebInspector.UIString("Not Found");
1872
1873     var matchesToolbarElement = document.getElementById("search-results-matches");
1874     matchesToolbarElement.removeStyleClass("hidden");
1875     matchesToolbarElement.textContent = matchesString;
1876 }
1877
1878 WebInspector.UIString = function(string)
1879 {
1880     if (window.localizedStrings && string in window.localizedStrings)
1881         string = window.localizedStrings[string];
1882     else {
1883         if (!(string in WebInspector.missingLocalizedStrings)) {
1884             if (!WebInspector.InspectorBackendStub)
1885                 console.error("Localized string \"" + string + "\" not found.");
1886             WebInspector.missingLocalizedStrings[string] = true;
1887         }
1888
1889         if (Preferences.showMissingLocalizedStrings)
1890             string += " (not localized)";
1891     }
1892
1893     return String.vsprintf(string, Array.prototype.slice.call(arguments, 1));
1894 }
1895
1896 WebInspector.formatLocalized = function(format, substitutions, formatters, initialValue, append)
1897 {
1898     return String.format(WebInspector.UIString(format), substitutions, formatters, initialValue, append);
1899 }
1900
1901 WebInspector.isMac = function()
1902 {
1903     if (!("_isMac" in this))
1904         this._isMac = WebInspector.platform === "mac";
1905
1906     return this._isMac;
1907 }
1908
1909 WebInspector.isBeingEdited = function(element)
1910 {
1911     return element.__editing;
1912 }
1913
1914 WebInspector.isEditingAnyField = function()
1915 {
1916     return this.__editing;
1917 }
1918
1919 WebInspector.startEditing = function(element, committedCallback, cancelledCallback, context, multiline)
1920 {
1921     if (element.__editing)
1922         return;
1923     element.__editing = true;
1924     WebInspector.__editing = true;
1925
1926     var oldText = getContent(element);
1927     var moveDirection = "";
1928
1929     element.addStyleClass("editing");
1930
1931     var oldTabIndex = element.tabIndex;
1932     if (element.tabIndex < 0)
1933         element.tabIndex = 0;
1934
1935     function blurEventListener() {
1936         editingCommitted.call(element);
1937     }
1938
1939     function getContent(element) {
1940         if (element.tagName === "INPUT" && element.type === "text")
1941             return element.value;
1942         else
1943             return element.textContent;
1944     }
1945
1946     function cleanUpAfterEditing() {
1947         delete this.__editing;
1948         delete WebInspector.__editing;
1949
1950         this.removeStyleClass("editing");
1951         this.tabIndex = oldTabIndex;
1952         this.scrollTop = 0;
1953         this.scrollLeft = 0;
1954
1955         element.removeEventListener("blur", blurEventListener, false);
1956         element.removeEventListener("keydown", keyDownEventListener, true);
1957
1958         if (element === WebInspector.currentFocusElement || element.isAncestor(WebInspector.currentFocusElement))
1959             WebInspector.currentFocusElement = WebInspector.previousFocusElement;
1960     }
1961
1962     function editingCancelled() {
1963         if (this.tagName === "INPUT" && this.type === "text")
1964             this.value = oldText;
1965         else
1966             this.textContent = oldText;
1967
1968         cleanUpAfterEditing.call(this);
1969
1970         if (cancelledCallback)
1971             cancelledCallback(this, context);
1972     }
1973
1974     function editingCommitted() {
1975         cleanUpAfterEditing.call(this);
1976
1977         if (committedCallback)
1978             committedCallback(this, getContent(this), oldText, context, moveDirection);
1979     }
1980
1981     function keyDownEventListener(event) {
1982         var isMetaOrCtrl = WebInspector.isMac() ?
1983             event.metaKey && !event.shiftKey && !event.ctrlKey && !event.altKey :
1984             event.ctrlKey && !event.shiftKey && !event.metaKey && !event.altKey;
1985         if (isEnterKey(event) && (!multiline || isMetaOrCtrl)) {
1986             editingCommitted.call(element);
1987             event.preventDefault();
1988             event.stopPropagation();
1989         } else if (event.keyCode === WebInspector.KeyboardShortcut.Keys.Esc.code) {
1990             editingCancelled.call(element);
1991             event.preventDefault();
1992             event.stopPropagation();
1993         } else if (event.keyIdentifier === "U+0009") // Tab key
1994             moveDirection = (event.shiftKey ? "backward" : "forward");
1995     }
1996
1997     element.addEventListener("blur", blurEventListener, false);
1998     element.addEventListener("keydown", keyDownEventListener, true);
1999
2000     WebInspector.currentFocusElement = element;
2001     return {
2002         cancel: editingCancelled.bind(element),
2003         commit: editingCommitted.bind(element)
2004     };
2005 }
2006
2007 WebInspector._toolbarItemClicked = function(event)
2008 {
2009     var toolbarItem = event.currentTarget;
2010     this.currentPanel = toolbarItem.panel;
2011 }
2012
2013 // This table maps MIME types to the Resource.Types which are valid for them.
2014 // The following line:
2015 //    "text/html":                {0: 1},
2016 // means that text/html is a valid MIME type for resources that have type
2017 // WebInspector.Resource.Type.Document (which has a value of 0).
2018 WebInspector.MIMETypes = {
2019     "text/html":                   {0: true},
2020     "text/xml":                    {0: true},
2021     "text/plain":                  {0: true},
2022     "application/xhtml+xml":       {0: true},
2023     "text/css":                    {1: true},
2024     "text/xsl":                    {1: true},
2025     "image/jpeg":                  {2: true},
2026     "image/png":                   {2: true},
2027     "image/gif":                   {2: true},
2028     "image/bmp":                   {2: true},
2029     "image/vnd.microsoft.icon":    {2: true},
2030     "image/x-icon":                {2: true},
2031     "image/x-xbitmap":             {2: true},
2032     "font/ttf":                    {3: true},
2033     "font/opentype":               {3: true},
2034     "application/x-font-type1":    {3: true},
2035     "application/x-font-ttf":      {3: true},
2036     "application/x-truetype-font": {3: true},
2037     "text/javascript":             {4: true},
2038     "text/ecmascript":             {4: true},
2039     "application/javascript":      {4: true},
2040     "application/ecmascript":      {4: true},
2041     "application/x-javascript":    {4: true},
2042     "text/javascript1.1":          {4: true},
2043     "text/javascript1.2":          {4: true},
2044     "text/javascript1.3":          {4: true},
2045     "text/jscript":                {4: true},
2046     "text/livescript":             {4: true},
2047 }
2048
2049 WebInspector.PanelHistory = function()
2050 {
2051     this._history = [];
2052     this._historyIterator = -1;
2053 }
2054
2055 WebInspector.PanelHistory.prototype = {
2056     canGoBack: function()
2057     {
2058         return this._historyIterator > 0;
2059     },
2060
2061     goBack: function()
2062     {
2063         this._inHistory = true;
2064         WebInspector.currentPanel = WebInspector.panels[this._history[--this._historyIterator]];
2065         delete this._inHistory;
2066     },
2067
2068     canGoForward: function()
2069     {
2070         return this._historyIterator < this._history.length - 1;
2071     },
2072
2073     goForward: function()
2074     {
2075         this._inHistory = true;
2076         WebInspector.currentPanel = WebInspector.panels[this._history[++this._historyIterator]];
2077         delete this._inHistory;
2078     },
2079
2080     setPanel: function(panelName)
2081     {
2082         if (this._inHistory)
2083             return;
2084
2085         this._history.splice(this._historyIterator + 1, this._history.length - this._historyIterator - 1);
2086         if (!this._history.length || this._history[this._history.length - 1] !== panelName)
2087             this._history.push(panelName);
2088         this._historyIterator = this._history.length - 1;
2089     }
2090 }