e0d8e65d615824e87f7e63493c9ecb7e065d0f9f
[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.debuggerModel.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.cssModel = new WebInspector.CSSStyleModel();
537     this.debuggerModel = new WebInspector.DebuggerModel();
538
539     this.breakpointManager = new WebInspector.BreakpointManager();
540
541     this.panels = {};
542     this._createPanels();
543     this._panelHistory = new WebInspector.PanelHistory();
544
545     var toolbarElement = document.getElementById("toolbar");
546     var previousToolbarItem = toolbarElement.children[0];
547
548     this.panelOrder = [];
549     for (var panelName in this.panels)
550         previousToolbarItem = WebInspector.addPanelToolbarIcon(toolbarElement, this.panels[panelName], previousToolbarItem);
551
552     this.Tips = {
553         ResourceNotCompressed: {id: 0, message: WebInspector.UIString("You could save bandwidth by having your web server compress this transfer with gzip or zlib.")}
554     };
555
556     this.Warnings = {
557         IncorrectMIMEType: {id: 0, message: WebInspector.UIString("Resource interpreted as %s but transferred with MIME type %s.")}
558     };
559
560     this.addMainEventListeners(document);
561
562     window.addEventListener("resize", this.windowResize.bind(this), true);
563
564     document.addEventListener("focus", this.focusChanged.bind(this), true);
565     document.addEventListener("keydown", this.documentKeyDown.bind(this), false);
566     document.addEventListener("beforecopy", this.documentCanCopy.bind(this), true);
567     document.addEventListener("copy", this.documentCopy.bind(this), true);
568     document.addEventListener("contextmenu", this.contextMenuEventFired.bind(this), true);
569
570     var dockToggleButton = document.getElementById("dock-status-bar-item");
571     dockToggleButton.addEventListener("click", this.toggleAttach.bind(this), false);
572
573     if (this.attached)
574         dockToggleButton.title = WebInspector.UIString("Undock into separate window.");
575     else
576         dockToggleButton.title = WebInspector.UIString("Dock to main window.");
577
578     var errorWarningCount = document.getElementById("error-warning-count");
579     errorWarningCount.addEventListener("click", this.showConsole.bind(this), false);
580     this._updateErrorAndWarningCounts();
581
582     this.styleChanges = 0;
583     // TODO: Uncomment when enabling the Changes Panel
584     // var changesElement = document.getElementById("changes-count");
585     // changesElement.addEventListener("click", this.showChanges.bind(this), false);
586     // this._updateErrorAndWarningCounts();
587
588     var searchField = document.getElementById("search");
589     searchField.addEventListener("search", this.performSearch.bind(this), false); // when the search is emptied
590     searchField.addEventListener("mousedown", this._searchFieldManualFocus.bind(this), false); // when the search field is manually selected
591     searchField.addEventListener("keydown", this._searchKeyDown.bind(this), true);
592
593     toolbarElement.addEventListener("mousedown", this.toolbarDragStart, true);
594     document.getElementById("close-button-left").addEventListener("click", this.close, true);
595     document.getElementById("close-button-right").addEventListener("click", this.close, true);
596
597     this.extensionServer.initExtensions();
598
599     function populateInspectorState(inspectorState)
600     {
601         WebInspector.monitoringXHREnabled = inspectorState.monitoringXHREnabled;
602         if ("pauseOnExceptionsState" in inspectorState)
603             WebInspector.panels.scripts.updatePauseOnExceptionsState(inspectorState.pauseOnExceptionsState);
604     }
605     InspectorBackend.getInspectorState(populateInspectorState);
606
607     function onPopulateScriptObjects()
608     {
609         if (!WebInspector.currentPanel)
610             WebInspector.showPanel(WebInspector.settings.lastActivePanel);
611     }
612     InspectorBackend.populateScriptObjects(onPopulateScriptObjects);
613
614     InspectorBackend.setConsoleMessagesEnabled(true);
615
616     // As a DOMAgent method, this needs to happen after the frontend has loaded and the agent is available.
617     InspectorBackend.getSupportedCSSProperties(WebInspector.CSSCompletions._load);
618 }
619
620 WebInspector.addPanelToolbarIcon = function(toolbarElement, panel, previousToolbarItem)
621 {
622     var panelToolbarItem = panel.toolbarItem;
623     this.panelOrder.push(panel);
624     panelToolbarItem.addEventListener("click", this._toolbarItemClicked.bind(this));
625     if (previousToolbarItem)
626         toolbarElement.insertBefore(panelToolbarItem, previousToolbarItem.nextSibling);
627     else
628         toolbarElement.insertBefore(panelToolbarItem, toolbarElement.firstChild);
629     return panelToolbarItem;
630 }
631
632 var windowLoaded = function()
633 {
634     var localizedStringsURL = InspectorFrontendHost.localizedStringsURL();
635     if (localizedStringsURL) {
636         var localizedStringsScriptElement = document.createElement("script");
637         localizedStringsScriptElement.addEventListener("load", WebInspector.loaded.bind(WebInspector), false);
638         localizedStringsScriptElement.type = "text/javascript";
639         localizedStringsScriptElement.src = localizedStringsURL;
640         document.head.appendChild(localizedStringsScriptElement);
641     } else
642         WebInspector.loaded();
643
644     window.removeEventListener("DOMContentLoaded", windowLoaded, false);
645     delete windowLoaded;
646 };
647
648 window.addEventListener("DOMContentLoaded", windowLoaded, false);
649
650 WebInspector.dispatch = function(message) {
651     // We'd like to enforce asynchronous interaction between the inspector controller and the frontend.
652     // This is important to LayoutTests.
653     function delayDispatch()
654     {
655         InspectorBackend.dispatch(message);
656         WebInspector.pendingDispatches--;
657     }
658     WebInspector.pendingDispatches++;
659     setTimeout(delayDispatch, 0);
660 }
661
662 WebInspector.dispatchMessageFromBackend = function(messageObject)
663 {
664     WebInspector.dispatch(messageObject);
665 }
666
667 WebInspector.windowResize = function(event)
668 {
669     if (this.currentPanel)
670         this.currentPanel.resize();
671     this.drawer.resize();
672 }
673
674 WebInspector.windowFocused = function(event)
675 {
676     // Fires after blur, so when focusing on either the main inspector
677     // or an <iframe> within the inspector we should always remove the
678     // "inactive" class.
679     if (event.target.document.nodeType === Node.DOCUMENT_NODE)
680         document.body.removeStyleClass("inactive");
681 }
682
683 WebInspector.windowBlurred = function(event)
684 {
685     // Leaving the main inspector or an <iframe> within the inspector.
686     // We can add "inactive" now, and if we are moving the focus to another
687     // part of the inspector then windowFocused will correct this.
688     if (event.target.document.nodeType === Node.DOCUMENT_NODE)
689         document.body.addStyleClass("inactive");
690 }
691
692 WebInspector.focusChanged = function(event)
693 {
694     this.currentFocusElement = event.target;
695 }
696
697 WebInspector.setAttachedWindow = function(attached)
698 {
699     this.attached = attached;
700 }
701
702 WebInspector.close = function(event)
703 {
704     if (this._isClosing)
705         return;
706     this._isClosing = true;
707     InspectorFrontendHost.closeWindow();
708 }
709
710 WebInspector.disconnectFromBackend = function()
711 {
712     InspectorFrontendHost.disconnectFromBackend();
713 }
714
715 WebInspector.documentClick = function(event)
716 {
717     var anchor = event.target.enclosingNodeOrSelfWithNodeName("a");
718     if (!anchor || anchor.target === "_blank")
719         return;
720
721     // Prevent the link from navigating, since we don't do any navigation by following links normally.
722     event.preventDefault();
723     event.stopPropagation();
724
725     function followLink()
726     {
727         // FIXME: support webkit-html-external-link links here.
728         if (WebInspector.canShowSourceLine(anchor.href, anchor.getAttribute("line_number"), anchor.getAttribute("preferred_panel"))) {
729             if (anchor.hasStyleClass("webkit-html-external-link")) {
730                 anchor.removeStyleClass("webkit-html-external-link");
731                 anchor.addStyleClass("webkit-html-resource-link");
732             }
733
734             WebInspector.showSourceLine(anchor.href, anchor.getAttribute("line_number"), anchor.getAttribute("preferred_panel"));
735             return;
736         }
737
738         const profileMatch = WebInspector.ProfileType.URLRegExp.exec(anchor.href);
739         if (profileMatch) {
740             WebInspector.showProfileForURL(anchor.href);
741             return;
742         }
743
744         var parsedURL = anchor.href.asParsedURL();
745         if (parsedURL && parsedURL.scheme === "webkit-link-action") {
746             if (parsedURL.host === "show-panel") {
747                 var panel = parsedURL.path.substring(1);
748                 if (WebInspector.panels[panel])
749                     WebInspector.showPanel(panel);
750             }
751             return;
752         }
753
754         WebInspector.showPanel("resources");
755     }
756
757     if (WebInspector.followLinkTimeout)
758         clearTimeout(WebInspector.followLinkTimeout);
759
760     if (anchor.preventFollowOnDoubleClick) {
761         // Start a timeout if this is the first click, if the timeout is canceled
762         // before it fires, then a double clicked happened or another link was clicked.
763         if (event.detail === 1)
764             WebInspector.followLinkTimeout = setTimeout(followLink, 333);
765         return;
766     }
767
768     followLink();
769 }
770
771 WebInspector.openResource = function(resourceURL, inResourcesPanel)
772 {
773     var resource = WebInspector.resourceForURL(resourceURL);
774     if (inResourcesPanel && resource) {
775         WebInspector.panels.resources.showResource(resource);
776         WebInspector.showPanel("resources");
777     } else
778         InspectorBackend.openInInspectedWindow(resource ? resource.url : resourceURL);
779 }
780
781 WebInspector._registerShortcuts = function()
782 {
783     var shortcut = WebInspector.KeyboardShortcut;
784     var section = WebInspector.shortcutsHelp.section(WebInspector.UIString("All Panels"));
785     var keys = [
786         shortcut.shortcutToString("]", shortcut.Modifiers.CtrlOrMeta),
787         shortcut.shortcutToString("[", shortcut.Modifiers.CtrlOrMeta)
788     ];
789     section.addRelatedKeys(keys, WebInspector.UIString("Next/previous panel"));
790     section.addKey(shortcut.shortcutToString(shortcut.Keys.Esc), WebInspector.UIString("Toggle console"));
791     section.addKey(shortcut.shortcutToString("f", shortcut.Modifiers.CtrlOrMeta), WebInspector.UIString("Search"));
792     keys = [
793         shortcut.shortcutToString("g", shortcut.Modifiers.CtrlOrMeta),
794         shortcut.shortcutToString("g", shortcut.Modifiers.CtrlOrMeta | shortcut.Modifiers.Shift)
795     ];
796     section.addRelatedKeys(keys, WebInspector.UIString("Find next/previous"));
797 }
798
799 WebInspector.documentKeyDown = function(event)
800 {
801     var isInputElement = event.target.nodeName === "INPUT";
802     var isInEditMode = event.target.enclosingNodeOrSelfWithClass("text-prompt") || WebInspector.isEditingAnyField();
803     const helpKey = WebInspector.isMac() ? "U+003F" : "U+00BF"; // "?" for both platforms
804
805     if (event.keyIdentifier === "F1" ||
806         (event.keyIdentifier === helpKey && event.shiftKey && (!isInEditMode && !isInputElement || event.metaKey))) {
807         WebInspector.shortcutsHelp.show();
808         event.stopPropagation();
809         event.preventDefault();
810         return;
811     }
812
813     if (WebInspector.isEditingAnyField())
814         return;
815
816     if (this.currentFocusElement && this.currentFocusElement.handleKeyEvent) {
817         this.currentFocusElement.handleKeyEvent(event);
818         if (event.handled) {
819             event.preventDefault();
820             return;
821         }
822     }
823
824     if (this.currentPanel && this.currentPanel.handleShortcut) {
825         this.currentPanel.handleShortcut(event);
826         if (event.handled) {
827             event.preventDefault();
828             return;
829         }
830     }
831
832     var isMac = WebInspector.isMac();
833     switch (event.keyIdentifier) {
834         case "Left":
835             var isBackKey = !isInEditMode && (isMac ? event.metaKey : event.ctrlKey);
836             if (isBackKey && this._panelHistory.canGoBack()) {
837                 this._panelHistory.goBack();
838                 event.preventDefault();
839             }
840             break;
841
842         case "Right":
843             var isForwardKey = !isInEditMode && (isMac ? event.metaKey : event.ctrlKey);
844             if (isForwardKey && this._panelHistory.canGoForward()) {
845                 this._panelHistory.goForward();
846                 event.preventDefault();
847             }
848             break;
849
850         case "U+001B": // Escape key
851             event.preventDefault();
852             if (this.drawer.fullPanel)
853                 return;
854
855             this.drawer.visible = !this.drawer.visible;
856             break;
857
858         case "U+0046": // F key
859             if (isMac)
860                 var isFindKey = event.metaKey && !event.ctrlKey && !event.altKey && !event.shiftKey;
861             else
862                 var isFindKey = event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey;
863
864             if (isFindKey) {
865                 WebInspector.focusSearchField();
866                 event.preventDefault();
867             }
868             break;
869
870         case "F3":
871             if (!isMac) {
872                 WebInspector.focusSearchField();
873                 event.preventDefault();
874             }
875             break;
876
877         case "U+0047": // G key
878             if (isMac)
879                 var isFindAgainKey = event.metaKey && !event.ctrlKey && !event.altKey;
880             else
881                 var isFindAgainKey = event.ctrlKey && !event.metaKey && !event.altKey;
882
883             if (isFindAgainKey) {
884                 if (event.shiftKey) {
885                     if (this.currentPanel.jumpToPreviousSearchResult)
886                         this.currentPanel.jumpToPreviousSearchResult();
887                 } else if (this.currentPanel.jumpToNextSearchResult)
888                     this.currentPanel.jumpToNextSearchResult();
889                 event.preventDefault();
890             }
891
892             break;
893
894         // Windows and Mac have two different definitions of [, so accept both.
895         case "U+005B":
896         case "U+00DB": // [ key
897             if (isMac)
898                 var isRotateLeft = event.metaKey && !event.shiftKey && !event.ctrlKey && !event.altKey;
899             else
900                 var isRotateLeft = event.ctrlKey && !event.shiftKey && !event.metaKey && !event.altKey;
901
902             if (isRotateLeft) {
903                 var index = this.panelOrder.indexOf(this.currentPanel);
904                 index = (index === 0) ? this.panelOrder.length - 1 : index - 1;
905                 this.panelOrder[index].toolbarItem.click();
906                 event.preventDefault();
907             }
908
909             break;
910
911         // Windows and Mac have two different definitions of ], so accept both.
912         case "U+005D":
913         case "U+00DD":  // ] key
914             if (isMac)
915                 var isRotateRight = event.metaKey && !event.shiftKey && !event.ctrlKey && !event.altKey;
916             else
917                 var isRotateRight = event.ctrlKey && !event.shiftKey && !event.metaKey && !event.altKey;
918
919             if (isRotateRight) {
920                 var index = this.panelOrder.indexOf(this.currentPanel);
921                 index = (index + 1) % this.panelOrder.length;
922                 this.panelOrder[index].toolbarItem.click();
923                 event.preventDefault();
924             }
925
926             break;
927
928         case "U+0052": // R key
929             if ((event.metaKey && isMac) || (event.ctrlKey && !isMac)) {
930                 InspectorBackend.reloadPage();
931                 event.preventDefault();
932             }
933             break;
934         case "F5":
935             if (!isMac)
936                 InspectorBackend.reloadPage();
937             break;
938     }
939 }
940
941 WebInspector.documentCanCopy = function(event)
942 {
943     if (this.currentPanel && this.currentPanel.handleCopyEvent)
944         event.preventDefault();
945 }
946
947 WebInspector.documentCopy = function(event)
948 {
949     if (this.currentPanel && this.currentPanel.handleCopyEvent)
950         this.currentPanel.handleCopyEvent(event);
951 }
952
953 WebInspector.contextMenuEventFired = function(event)
954 {
955     if (event.handled || event.target.hasStyleClass("popup-glasspane"))
956         event.preventDefault();
957 }
958
959 WebInspector.animateStyle = function(animations, duration, callback)
960 {
961     var interval;
962     var complete = 0;
963
964     const intervalDuration = (1000 / 30); // 30 frames per second.
965     const animationsLength = animations.length;
966     const propertyUnit = {opacity: ""};
967     const defaultUnit = "px";
968
969     function cubicInOut(t, b, c, d)
970     {
971         if ((t/=d/2) < 1) return c/2*t*t*t + b;
972         return c/2*((t-=2)*t*t + 2) + b;
973     }
974
975     // Pre-process animations.
976     for (var i = 0; i < animationsLength; ++i) {
977         var animation = animations[i];
978         var element = null, start = null, end = null, key = null;
979         for (key in animation) {
980             if (key === "element")
981                 element = animation[key];
982             else if (key === "start")
983                 start = animation[key];
984             else if (key === "end")
985                 end = animation[key];
986         }
987
988         if (!element || !end)
989             continue;
990
991         if (!start) {
992             var computedStyle = element.ownerDocument.defaultView.getComputedStyle(element);
993             start = {};
994             for (key in end)
995                 start[key] = parseInt(computedStyle.getPropertyValue(key));
996             animation.start = start;
997         } else
998             for (key in start)
999                 element.style.setProperty(key, start[key] + (key in propertyUnit ? propertyUnit[key] : defaultUnit));
1000     }
1001
1002     function animateLoop()
1003     {
1004         // Advance forward.
1005         complete += intervalDuration;
1006         var next = complete + intervalDuration;
1007
1008         // Make style changes.
1009         for (var i = 0; i < animationsLength; ++i) {
1010             var animation = animations[i];
1011             var element = animation.element;
1012             var start = animation.start;
1013             var end = animation.end;
1014             if (!element || !end)
1015                 continue;
1016
1017             var style = element.style;
1018             for (key in end) {
1019                 var endValue = end[key];
1020                 if (next < duration) {
1021                     var startValue = start[key];
1022                     var newValue = cubicInOut(complete, startValue, endValue - startValue, duration);
1023                     style.setProperty(key, newValue + (key in propertyUnit ? propertyUnit[key] : defaultUnit));
1024                 } else
1025                     style.setProperty(key, endValue + (key in propertyUnit ? propertyUnit[key] : defaultUnit));
1026             }
1027         }
1028
1029         // End condition.
1030         if (complete >= duration) {
1031             clearInterval(interval);
1032             if (callback)
1033                 callback();
1034         }
1035     }
1036
1037     interval = setInterval(animateLoop, intervalDuration);
1038     return interval;
1039 }
1040
1041 WebInspector.updateSearchLabel = function()
1042 {
1043     if (!this.currentPanel)
1044         return;
1045
1046     var newLabel = WebInspector.UIString("Search %s", this.currentPanel.toolbarItemLabel);
1047     if (this.attached)
1048         document.getElementById("search").setAttribute("placeholder", newLabel);
1049     else {
1050         document.getElementById("search").removeAttribute("placeholder");
1051         document.getElementById("search-toolbar-label").textContent = newLabel;
1052     }
1053 }
1054
1055 WebInspector.focusSearchField = function()
1056 {
1057     var searchField = document.getElementById("search");
1058     searchField.focus();
1059     searchField.select();
1060 }
1061
1062 WebInspector.toggleAttach = function()
1063 {
1064     if (!this.attached)
1065         InspectorFrontendHost.requestAttachWindow();
1066     else
1067         InspectorFrontendHost.requestDetachWindow();
1068 }
1069
1070 WebInspector.toolbarDragStart = function(event)
1071 {
1072     if ((!WebInspector.attached && WebInspector.platformFlavor !== WebInspector.PlatformFlavor.MacLeopard && WebInspector.platformFlavor !== WebInspector.PlatformFlavor.MacSnowLeopard) || WebInspector.port == "qt")
1073         return;
1074
1075     var target = event.target;
1076     if (target.hasStyleClass("toolbar-item") && target.hasStyleClass("toggleable"))
1077         return;
1078
1079     var toolbar = document.getElementById("toolbar");
1080     if (target !== toolbar && !target.hasStyleClass("toolbar-item"))
1081         return;
1082
1083     toolbar.lastScreenX = event.screenX;
1084     toolbar.lastScreenY = event.screenY;
1085
1086     WebInspector.elementDragStart(toolbar, WebInspector.toolbarDrag, WebInspector.toolbarDragEnd, event, (WebInspector.attached ? "row-resize" : "default"));
1087 }
1088
1089 WebInspector.toolbarDragEnd = function(event)
1090 {
1091     var toolbar = document.getElementById("toolbar");
1092
1093     WebInspector.elementDragEnd(event);
1094
1095     delete toolbar.lastScreenX;
1096     delete toolbar.lastScreenY;
1097 }
1098
1099 WebInspector.toolbarDrag = function(event)
1100 {
1101     var toolbar = document.getElementById("toolbar");
1102
1103     if (WebInspector.attached) {
1104         var height = window.innerHeight - (event.screenY - toolbar.lastScreenY);
1105
1106         InspectorFrontendHost.setAttachedWindowHeight(height);
1107     } else {
1108         var x = event.screenX - toolbar.lastScreenX;
1109         var y = event.screenY - toolbar.lastScreenY;
1110
1111         // We cannot call window.moveBy here because it restricts the movement
1112         // of the window at the edges.
1113         InspectorFrontendHost.moveWindowBy(x, y);
1114     }
1115
1116     toolbar.lastScreenX = event.screenX;
1117     toolbar.lastScreenY = event.screenY;
1118
1119     event.preventDefault();
1120 }
1121
1122 WebInspector.elementDragStart = function(element, dividerDrag, elementDragEnd, event, cursor)
1123 {
1124     if (this._elementDraggingEventListener || this._elementEndDraggingEventListener)
1125         this.elementDragEnd(event);
1126
1127     this._elementDraggingEventListener = dividerDrag;
1128     this._elementEndDraggingEventListener = elementDragEnd;
1129
1130     document.addEventListener("mousemove", dividerDrag, true);
1131     document.addEventListener("mouseup", elementDragEnd, true);
1132
1133     document.body.style.cursor = cursor;
1134
1135     event.preventDefault();
1136 }
1137
1138 WebInspector.elementDragEnd = function(event)
1139 {
1140     document.removeEventListener("mousemove", this._elementDraggingEventListener, true);
1141     document.removeEventListener("mouseup", this._elementEndDraggingEventListener, true);
1142
1143     document.body.style.removeProperty("cursor");
1144
1145     delete this._elementDraggingEventListener;
1146     delete this._elementEndDraggingEventListener;
1147
1148     event.preventDefault();
1149 }
1150
1151 WebInspector.toggleSearchingForNode = function()
1152 {
1153     if (this.panels.elements) {
1154         this.showPanel("elements");
1155         this.panels.elements.toggleSearchingForNode();
1156     }
1157 }
1158
1159 WebInspector.showConsole = function()
1160 {
1161     this.drawer.showView(this.console);
1162 }
1163
1164 WebInspector.showChanges = function()
1165 {
1166     this.drawer.showView(this.changes);
1167 }
1168
1169 WebInspector.showPanel = function(panel)
1170 {
1171     if (!(panel in this.panels))
1172         panel = "elements";
1173     this.currentPanel = this.panels[panel];
1174 }
1175
1176 WebInspector.selectDatabase = function(o)
1177 {
1178     WebInspector.showPanel("resources");
1179     WebInspector.panels.resources.selectDatabase(o);
1180 }
1181
1182 WebInspector.consoleMessagesCleared = function()
1183 {
1184     WebInspector.console.clearMessages();
1185 }
1186
1187 WebInspector.selectDOMStorage = function(o)
1188 {
1189     WebInspector.showPanel("resources");
1190     WebInspector.panels.resources.selectDOMStorage(o);
1191 }
1192
1193 WebInspector.domContentEventFired = function(time)
1194 {
1195     this.panels.audits.mainResourceDOMContentTime = time;
1196     if (this.panels.network)
1197         this.panels.network.mainResourceDOMContentTime = time;
1198     this.extensionServer.notifyPageDOMContentLoaded((time - WebInspector.mainResource.startTime) * 1000);
1199     this.mainResourceDOMContentTime = time;
1200 }
1201
1202 WebInspector.loadEventFired = function(time)
1203 {
1204     this.panels.audits.mainResourceLoadTime = time;
1205     if (this.panels.network)
1206         this.panels.network.mainResourceLoadTime = time;
1207     this.extensionServer.notifyPageLoaded((time - WebInspector.mainResource.startTime) * 1000);
1208     this.mainResourceLoadTime = time;
1209 }
1210
1211 WebInspector.addDatabase = function(payload)
1212 {
1213     if (!this.panels.resources)
1214         return;
1215     var database = new WebInspector.Database(
1216         payload.id,
1217         payload.domain,
1218         payload.name,
1219         payload.version);
1220     this.panels.resources.addDatabase(database);
1221 }
1222
1223 WebInspector.addDOMStorage = function(payload)
1224 {
1225     if (!this.panels.resources)
1226         return;
1227     var domStorage = new WebInspector.DOMStorage(
1228         payload.id,
1229         payload.host,
1230         payload.isLocalStorage);
1231     this.panels.resources.addDOMStorage(domStorage);
1232 }
1233
1234 WebInspector.updateDOMStorage = function(storageId)
1235 {
1236     this.panels.resources.updateDOMStorage(storageId);
1237 }
1238
1239 WebInspector.updateApplicationCacheStatus = function(status)
1240 {
1241     this.panels.resources.updateApplicationCacheStatus(status);
1242 }
1243
1244 WebInspector.didGetFileSystemPath = function(root, type, origin)
1245 {
1246     this.panels.resources.updateFileSystemPath(root, type, origin);
1247 }
1248
1249 WebInspector.didGetFileSystemError = function(type, origin)
1250 {
1251     this.panels.resources.updateFileSystemError(type, origin);
1252 }
1253
1254 WebInspector.didGetFileSystemDisabled = function()
1255 {
1256     this.panels.resources.setFileSystemDisabled();
1257 }
1258
1259 WebInspector.updateNetworkState = function(isNowOnline)
1260 {
1261     this.panels.resources.updateNetworkState(isNowOnline);
1262 }
1263
1264 WebInspector.searchingForNodeWasEnabled = function()
1265 {
1266     this.panels.elements.searchingForNodeWasEnabled();
1267 }
1268
1269 WebInspector.searchingForNodeWasDisabled = function()
1270 {
1271     this.panels.elements.searchingForNodeWasDisabled();
1272 }
1273
1274 WebInspector.attachDebuggerWhenShown = function()
1275 {
1276     this.panels.scripts.attachDebuggerWhenShown();
1277 }
1278
1279 WebInspector.debuggerWasEnabled = function()
1280 {
1281     this.panels.scripts.debuggerWasEnabled();
1282 }
1283
1284 WebInspector.debuggerWasDisabled = function()
1285 {
1286     this.panels.scripts.debuggerWasDisabled();
1287 }
1288
1289 WebInspector.profilerWasEnabled = function()
1290 {
1291     this.panels.profiles.profilerWasEnabled();
1292 }
1293
1294 WebInspector.profilerWasDisabled = function()
1295 {
1296     this.panels.profiles.profilerWasDisabled();
1297 }
1298
1299 WebInspector.parsedScriptSource = function(sourceID, sourceURL, source, startingLine, scriptWorldType)
1300 {
1301     this.panels.scripts.addScript(sourceID, sourceURL, source, startingLine, undefined, undefined, scriptWorldType);
1302 }
1303
1304 WebInspector.restoredBreakpoint = function(sourceID, sourceURL, line, enabled, condition)
1305 {
1306     this.debuggerModel.breakpointRestored(sourceID, sourceURL, line, enabled, condition);
1307 }
1308
1309 WebInspector.failedToParseScriptSource = function(sourceURL, source, startingLine, errorLine, errorMessage)
1310 {
1311     this.panels.scripts.addScript(null, sourceURL, source, startingLine, errorLine, errorMessage);
1312 }
1313
1314 WebInspector.pausedScript = function(details)
1315 {
1316     this.debuggerModel.debuggerPaused(details);
1317 }
1318
1319 WebInspector.resumedScript = function()
1320 {
1321     this.debuggerModel.debuggerResumed();
1322 }
1323
1324 WebInspector.reset = function()
1325 {
1326     this.debuggerModel.reset();
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.domAgent.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.repeatCount,
1387         payload.message,
1388         payload.parameters,
1389         payload.stackTrace,
1390         payload.requestId);
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             repeatCount,
1457             null,
1458             [message],
1459             null);
1460
1461         self.console.addMessage(msg);
1462     }
1463
1464     // if we can't log the message, queue it
1465     if (!isLogAvailable()) {
1466         if (!WebInspector.log.queued)
1467             WebInspector.log.queued = [];
1468
1469         WebInspector.log.queued.push(message);
1470
1471         if (!WebInspector.log.interval)
1472             WebInspector.log.interval = setInterval(flushQueueIfAvailable, 1000);
1473
1474         return;
1475     }
1476
1477     // flush the pending queue if any
1478     flushQueue();
1479
1480     // log the message
1481     logMessage(message);
1482 }
1483
1484 WebInspector.addProfileHeader = function(profile)
1485 {
1486     this.panels.profiles.addProfileHeader(profile);
1487 }
1488
1489 WebInspector.setRecordingProfile = function(isProfiling)
1490 {
1491     this.panels.profiles.getProfileType(WebInspector.CPUProfileType.TypeId).setRecordingProfile(isProfiling);
1492     if (this.panels.profiles.hasTemporaryProfile(WebInspector.CPUProfileType.TypeId) !== isProfiling) {
1493         if (!this._temporaryRecordingProfile) {
1494             this._temporaryRecordingProfile = {
1495                 typeId: WebInspector.CPUProfileType.TypeId,
1496                 title: WebInspector.UIString("Recording…"),
1497                 uid: -1,
1498                 isTemporary: true
1499             };
1500         }
1501         if (isProfiling)
1502             this.panels.profiles.addProfileHeader(this._temporaryRecordingProfile);
1503         else
1504             this.panels.profiles.removeProfileHeader(this._temporaryRecordingProfile);
1505     }
1506     this.panels.profiles.updateProfileTypeButtons();
1507 }
1508
1509 WebInspector.addHeapSnapshotChunk = function(uid, chunk)
1510 {
1511     this.panels.profiles.addHeapSnapshotChunk(uid, chunk);
1512 }
1513
1514 WebInspector.finishHeapSnapshot = function(uid)
1515 {
1516     this.panels.profiles.finishHeapSnapshot(uid);
1517 }
1518
1519 WebInspector.drawLoadingPieChart = function(canvas, percent) {
1520     var g = canvas.getContext("2d");
1521     var darkColor = "rgb(122, 168, 218)";
1522     var lightColor = "rgb(228, 241, 251)";
1523     var cx = 8;
1524     var cy = 8;
1525     var r = 7;
1526
1527     g.beginPath();
1528     g.arc(cx, cy, r, 0, Math.PI * 2, false);
1529     g.closePath();
1530
1531     g.lineWidth = 1;
1532     g.strokeStyle = darkColor;
1533     g.fillStyle = lightColor;
1534     g.fill();
1535     g.stroke();
1536
1537     var startangle = -Math.PI / 2;
1538     var endangle = startangle + (percent * Math.PI * 2);
1539
1540     g.beginPath();
1541     g.moveTo(cx, cy);
1542     g.arc(cx, cy, r, startangle, endangle, false);
1543     g.closePath();
1544
1545     g.fillStyle = darkColor;
1546     g.fill();
1547 }
1548
1549 WebInspector.updateFocusedNode = function(nodeId)
1550 {
1551     this._updateFocusedNode(nodeId);
1552     this.highlightDOMNodeForTwoSeconds(nodeId);
1553 }
1554
1555 WebInspector.displayNameForURL = function(url)
1556 {
1557     if (!url)
1558         return "";
1559
1560     var resource = this.resourceForURL(url);
1561     if (resource)
1562         return resource.displayName;
1563
1564     if (!WebInspector.mainResource)
1565         return url.trimURL("");
1566
1567     var lastPathComponent = WebInspector.mainResource.lastPathComponent;
1568     var index = WebInspector.mainResource.url.indexOf(lastPathComponent);
1569     if (index !== -1 && index + lastPathComponent.length === WebInspector.mainResource.url.length) {
1570         var baseURL = WebInspector.mainResource.url.substring(0, index);
1571         if (url.indexOf(baseURL) === 0)
1572             return url.substring(index);
1573     }
1574
1575     return url.trimURL(WebInspector.mainResource.domain);
1576 }
1577
1578 WebInspector._choosePanelToShowSourceLine = function(url, line, preferredPanel)
1579 {
1580     preferredPanel = preferredPanel || "resources";
1581
1582     var panel = this.panels[preferredPanel];
1583     if (panel && panel.canShowSourceLine(url, line))
1584         return panel;
1585     panel = this.panels.resources;
1586     return panel.canShowSourceLine(url, line) ? panel : null;
1587 }
1588
1589 WebInspector.canShowSourceLine = function(url, line, preferredPanel)
1590 {
1591     return !!this._choosePanelToShowSourceLine(url, line, preferredPanel);
1592 }
1593
1594 WebInspector.showSourceLine = function(url, line, preferredPanel)
1595 {
1596     this.currentPanel = this._choosePanelToShowSourceLine(url, line, preferredPanel);
1597     if (!this.currentPanel)
1598         return false;
1599     this.currentPanel.showSourceLine(url, line);
1600     return true;
1601 }
1602
1603 WebInspector.linkifyStringAsFragment = function(string)
1604 {
1605     var container = document.createDocumentFragment();
1606     var linkStringRegEx = /(?:[a-zA-Z][a-zA-Z0-9+.-]{2,}:\/\/|www\.)[\w$\-_+*'=\|\/\\(){}[\]%@&#~,:;.!?]{2,}[\w$\-_+*=\|\/\\({%@&#~]/;
1607     var lineColumnRegEx = /:(\d+)(:(\d+))?$/;
1608
1609     while (string) {
1610         var linkString = linkStringRegEx.exec(string);
1611         if (!linkString)
1612             break;
1613
1614         linkString = linkString[0];
1615         var title = linkString;
1616         var linkIndex = string.indexOf(linkString);
1617         var nonLink = string.substring(0, linkIndex);
1618         container.appendChild(document.createTextNode(nonLink));
1619
1620         var profileStringMatches = WebInspector.ProfileType.URLRegExp.exec(title);
1621         if (profileStringMatches)
1622             title = WebInspector.panels.profiles.displayTitleForProfileLink(profileStringMatches[2], profileStringMatches[1]);
1623
1624         var realURL = (linkString.indexOf("www.") === 0 ? "http://" + linkString : linkString);
1625         var lineColumnMatch = lineColumnRegEx.exec(realURL);
1626         if (lineColumnMatch)
1627             realURL = realURL.substring(0, realURL.length - lineColumnMatch[0].length);
1628
1629         var hasResourceWithURL = !!WebInspector.resourceForURL(realURL);
1630         var urlNode = WebInspector.linkifyURLAsNode(realURL, title, null, hasResourceWithURL);
1631         container.appendChild(urlNode);
1632         if (lineColumnMatch) {
1633             urlNode.setAttribute("line_number", lineColumnMatch[1]);
1634             urlNode.setAttribute("preferred_panel", "scripts");
1635         }
1636         string = string.substring(linkIndex + linkString.length, string.length);
1637     }
1638
1639     if (string)
1640         container.appendChild(document.createTextNode(string));
1641
1642     return container;
1643 }
1644
1645 WebInspector.showProfileForURL = function(url)
1646 {
1647     WebInspector.showPanel("profiles");
1648     WebInspector.panels.profiles.showProfileForURL(url);
1649 }
1650
1651 WebInspector.linkifyURLAsNode = function(url, linkText, classes, isExternal, tooltipText)
1652 {
1653     if (!linkText)
1654         linkText = url;
1655     classes = (classes ? classes + " " : "");
1656     classes += isExternal ? "webkit-html-external-link" : "webkit-html-resource-link";
1657
1658     var a = document.createElement("a");
1659     a.href = url;
1660     a.className = classes;
1661     if (typeof tooltipText === "undefined")
1662         a.title = url;
1663     else if (typeof tooltipText !== "string" || tooltipText.length)
1664         a.title = tooltipText;
1665     a.textContent = linkText;
1666
1667     return a;
1668 }
1669
1670 WebInspector.linkifyURL = function(url, linkText, classes, isExternal, tooltipText)
1671 {
1672     // Use the DOM version of this function so as to avoid needing to escape attributes.
1673     // FIXME:  Get rid of linkifyURL entirely.
1674     return WebInspector.linkifyURLAsNode(url, linkText, classes, isExternal, tooltipText).outerHTML;
1675 }
1676
1677 WebInspector.linkifyResourceAsNode = function(url, preferredPanel, lineNumber, classes, tooltipText)
1678 {
1679     var linkText = WebInspector.displayNameForURL(url);
1680     if (lineNumber)
1681         linkText += ":" + lineNumber;
1682     var node = WebInspector.linkifyURLAsNode(url, linkText, classes, false, tooltipText);
1683     node.setAttribute("line_number", lineNumber);
1684     node.setAttribute("preferred_panel", preferredPanel);
1685     return node;
1686 }
1687
1688 WebInspector.resourceURLForRelatedNode = function(node, url)
1689 {
1690     if (!url || url.indexOf("://") > 0)
1691         return url;
1692
1693     for (var frameOwnerCandidate = node; frameOwnerCandidate; frameOwnerCandidate = frameOwnerCandidate.parentNode) {
1694         if (frameOwnerCandidate.documentURL) {
1695             var result = WebInspector.completeURL(frameOwnerCandidate.documentURL, url);
1696             if (result)
1697                 return result;
1698             break;
1699         }
1700     }
1701
1702     // documentURL not found or has bad value
1703     var resourceURL = url;
1704     function callback(resource)
1705     {
1706         if (resource.path === url) {
1707             resourceURL = resource.url;
1708             return true;
1709         }
1710     }
1711     WebInspector.forAllResources(callback);
1712     return resourceURL;
1713 }
1714
1715 WebInspector.completeURL = function(baseURL, href)
1716 {
1717     var parsedURL = baseURL.asParsedURL();
1718     if (parsedURL) {
1719         var path = href;
1720         if (path.charAt(0) !== "/") {
1721             var basePath = parsedURL.path;
1722             path = basePath.substring(0, basePath.lastIndexOf("/")) + "/" + path;
1723         } else if (path.length > 1 && path.charAt(1) === "/") {
1724             // href starts with "//" which is a full URL with the protocol dropped (use the baseURL protocol).
1725             return parsedURL.scheme + ":" + path;
1726         }
1727         return parsedURL.scheme + "://" + parsedURL.host + (parsedURL.port ? (":" + parsedURL.port) : "") + path;
1728     }
1729     return null;
1730 }
1731
1732 WebInspector.addMainEventListeners = function(doc)
1733 {
1734     doc.defaultView.addEventListener("focus", this.windowFocused.bind(this), false);
1735     doc.defaultView.addEventListener("blur", this.windowBlurred.bind(this), false);
1736     doc.addEventListener("click", this.documentClick.bind(this), true);
1737 }
1738
1739 WebInspector._searchFieldManualFocus = function(event)
1740 {
1741     this.currentFocusElement = event.target;
1742     this._previousFocusElement = event.target;
1743 }
1744
1745 WebInspector._searchKeyDown = function(event)
1746 {
1747     // Escape Key will clear the field and clear the search results
1748     if (event.keyCode === WebInspector.KeyboardShortcut.Keys.Esc.code) {
1749         // If focus belongs here and text is empty - nothing to do, return unhandled.
1750         if (event.target.value === "" && this.currentFocusElement === this.previousFocusElement)
1751             return;
1752         event.preventDefault();
1753         event.stopPropagation();
1754         // When search was selected manually and is currently blank, we'd like Esc stay unhandled
1755         // and hit console drawer handler.
1756         event.target.value = "";
1757
1758         this.performSearch(event);
1759         this.currentFocusElement = this.previousFocusElement;
1760         if (this.currentFocusElement === event.target)
1761             this.currentFocusElement.select();
1762         return false;
1763     }
1764
1765     if (!isEnterKey(event))
1766         return false;
1767
1768     // Select all of the text so the user can easily type an entirely new query.
1769     event.target.select();
1770
1771     // Only call performSearch if the Enter key was pressed. Otherwise the search
1772     // performance is poor because of searching on every key. The search field has
1773     // the incremental attribute set, so we still get incremental searches.
1774     this.performSearch(event);
1775
1776     // Call preventDefault since this was the Enter key. This prevents a "search" event
1777     // from firing for key down. This stops performSearch from being called twice in a row.
1778     event.preventDefault();
1779 }
1780
1781 WebInspector.performSearch = function(event)
1782 {
1783     var forceSearch = event.keyIdentifier === "Enter";
1784     this.doPerformSearch(event.target.value, forceSearch, event.shiftKey, false);
1785 }
1786
1787 WebInspector.doPerformSearch = function(query, forceSearch, isBackwardSearch, repeatSearch)
1788 {
1789     var isShortSearch = (query.length < 3);
1790
1791     // Clear a leftover short search flag due to a non-conflicting forced search.
1792     if (isShortSearch && this.shortSearchWasForcedByKeyEvent && this.currentQuery !== query)
1793         delete this.shortSearchWasForcedByKeyEvent;
1794
1795     // Indicate this was a forced search on a short query.
1796     if (isShortSearch && forceSearch)
1797         this.shortSearchWasForcedByKeyEvent = true;
1798
1799     if (!query || !query.length || (!forceSearch && isShortSearch)) {
1800         // Prevent clobbering a short search forced by the user.
1801         if (this.shortSearchWasForcedByKeyEvent) {
1802             delete this.shortSearchWasForcedByKeyEvent;
1803             return;
1804         }
1805
1806         delete this.currentQuery;
1807
1808         for (var panelName in this.panels) {
1809             var panel = this.panels[panelName];
1810             var hadCurrentQuery = !!panel.currentQuery;
1811             delete panel.currentQuery;
1812             if (hadCurrentQuery && panel.searchCanceled)
1813                 panel.searchCanceled();
1814         }
1815
1816         this.updateSearchMatchesCount();
1817
1818         return;
1819     }
1820
1821     if (!repeatSearch && query === this.currentPanel.currentQuery && this.currentPanel.currentQuery === this.currentQuery) {
1822         // When this is the same query and a forced search, jump to the next
1823         // search result for a good user experience.
1824         if (forceSearch) {
1825             if (!isBackwardSearch && this.currentPanel.jumpToNextSearchResult)
1826                 this.currentPanel.jumpToNextSearchResult();
1827             else if (isBackwardSearch && this.currentPanel.jumpToPreviousSearchResult)
1828                 this.currentPanel.jumpToPreviousSearchResult();
1829         }
1830         return;
1831     }
1832
1833     this.currentQuery = query;
1834
1835     this.updateSearchMatchesCount();
1836
1837     if (!this.currentPanel.performSearch)
1838         return;
1839
1840     this.currentPanel.currentQuery = query;
1841     this.currentPanel.performSearch(query);
1842 }
1843
1844 WebInspector.addNodesToSearchResult = function(nodeIds)
1845 {
1846     WebInspector.panels.elements.addNodesToSearchResult(nodeIds);
1847 }
1848
1849 WebInspector.updateSearchMatchesCount = function(matches, panel)
1850 {
1851     if (!panel)
1852         panel = this.currentPanel;
1853
1854     panel.currentSearchMatches = matches;
1855
1856     if (panel !== this.currentPanel)
1857         return;
1858
1859     if (!this.currentPanel.currentQuery) {
1860         document.getElementById("search-results-matches").addStyleClass("hidden");
1861         return;
1862     }
1863
1864     if (matches) {
1865         if (matches === 1)
1866             var matchesString = WebInspector.UIString("1 match");
1867         else
1868             var matchesString = WebInspector.UIString("%d matches", matches);
1869     } else
1870         var matchesString = WebInspector.UIString("Not Found");
1871
1872     var matchesToolbarElement = document.getElementById("search-results-matches");
1873     matchesToolbarElement.removeStyleClass("hidden");
1874     matchesToolbarElement.textContent = matchesString;
1875 }
1876
1877 WebInspector.UIString = function(string)
1878 {
1879     if (window.localizedStrings && string in window.localizedStrings)
1880         string = window.localizedStrings[string];
1881     else {
1882         if (!(string in WebInspector.missingLocalizedStrings)) {
1883             if (!WebInspector.InspectorBackendStub)
1884                 console.error("Localized string \"" + string + "\" not found.");
1885             WebInspector.missingLocalizedStrings[string] = true;
1886         }
1887
1888         if (Preferences.showMissingLocalizedStrings)
1889             string += " (not localized)";
1890     }
1891
1892     return String.vsprintf(string, Array.prototype.slice.call(arguments, 1));
1893 }
1894
1895 WebInspector.formatLocalized = function(format, substitutions, formatters, initialValue, append)
1896 {
1897     return String.format(WebInspector.UIString(format), substitutions, formatters, initialValue, append);
1898 }
1899
1900 WebInspector.isMac = function()
1901 {
1902     if (!("_isMac" in this))
1903         this._isMac = WebInspector.platform === "mac";
1904
1905     return this._isMac;
1906 }
1907
1908 WebInspector.isBeingEdited = function(element)
1909 {
1910     return element.__editing;
1911 }
1912
1913 WebInspector.isEditingAnyField = function()
1914 {
1915     return this.__editing;
1916 }
1917
1918 // Available config fields (all optional):
1919 // context: Object - an arbitrary context object to be passed to the commit and cancel handlers
1920 // commitHandler: Function - handles editing "commit" outcome
1921 // cancelHandler: Function - handles editing "cancel" outcome
1922 // customFinishHandler: Function - custom finish handler for the editing session (invoked on keydown)
1923 // multiline: Boolean - whether the edited element is multiline
1924 WebInspector.startEditing = function(element, config)
1925 {
1926     if (element.__editing)
1927         return;
1928     element.__editing = true;
1929     WebInspector.__editing = true;
1930
1931     config = config || {};
1932     var committedCallback = config.commitHandler;
1933     var cancelledCallback = config.cancelHandler;
1934     var context = config.context;
1935     var oldText = getContent(element);
1936     var moveDirection = "";
1937
1938     element.addStyleClass("editing");
1939
1940     var oldTabIndex = element.tabIndex;
1941     if (element.tabIndex < 0)
1942         element.tabIndex = 0;
1943
1944     function blurEventListener() {
1945         editingCommitted.call(element);
1946     }
1947
1948     function getContent(element) {
1949         if (element.tagName === "INPUT" && element.type === "text")
1950             return element.value;
1951         else
1952             return element.textContent;
1953     }
1954
1955     function cleanUpAfterEditing() {
1956         delete this.__editing;
1957         delete WebInspector.__editing;
1958
1959         this.removeStyleClass("editing");
1960         this.tabIndex = oldTabIndex;
1961         this.scrollTop = 0;
1962         this.scrollLeft = 0;
1963
1964         element.removeEventListener("blur", blurEventListener, false);
1965         element.removeEventListener("keydown", keyDownEventListener, true);
1966
1967         if (element === WebInspector.currentFocusElement || element.isAncestor(WebInspector.currentFocusElement))
1968             WebInspector.currentFocusElement = WebInspector.previousFocusElement;
1969     }
1970
1971     function editingCancelled() {
1972         if (this.tagName === "INPUT" && this.type === "text")
1973             this.value = oldText;
1974         else
1975             this.textContent = oldText;
1976
1977         cleanUpAfterEditing.call(this);
1978
1979         if (cancelledCallback)
1980             cancelledCallback(this, context);
1981     }
1982
1983     function editingCommitted() {
1984         cleanUpAfterEditing.call(this);
1985
1986         if (committedCallback)
1987             committedCallback(this, getContent(this), oldText, context, moveDirection);
1988     }
1989
1990     function defaultFinishHandler(event)
1991     {
1992         var isMetaOrCtrl = WebInspector.isMac() ?
1993             event.metaKey && !event.shiftKey && !event.ctrlKey && !event.altKey :
1994             event.ctrlKey && !event.shiftKey && !event.metaKey && !event.altKey;
1995         if (isEnterKey(event) && (!config.multiline || isMetaOrCtrl))
1996             return "commit";
1997         else if (event.keyCode === WebInspector.KeyboardShortcut.Keys.Esc.code)
1998             return "cancel";
1999         else if (event.keyIdentifier === "U+0009") // Tab key
2000             return "move-" + (event.shiftKey ? "backward" : "forward");
2001     }
2002
2003     function keyDownEventListener(event)
2004     {
2005         var handler = config.customFinishHandler || defaultFinishHandler;
2006         var result = handler(event);
2007         if (result === "commit") {
2008             editingCommitted.call(element);
2009             event.preventDefault();
2010             event.stopPropagation();
2011         } else if (result === "cancel") {
2012             editingCancelled.call(element);
2013             event.preventDefault();
2014             event.stopPropagation();
2015         } else if (result && result.indexOf("move-") === 0) {
2016             moveDirection = result.substring(5);
2017             if (event.keyIdentifier !== "U+0009")
2018                 blurEventListener();
2019         }
2020     }
2021
2022     element.addEventListener("blur", blurEventListener, false);
2023     element.addEventListener("keydown", keyDownEventListener, true);
2024
2025     WebInspector.currentFocusElement = element;
2026     return {
2027         cancel: editingCancelled.bind(element),
2028         commit: editingCommitted.bind(element)
2029     };
2030 }
2031
2032 WebInspector._toolbarItemClicked = function(event)
2033 {
2034     var toolbarItem = event.currentTarget;
2035     this.currentPanel = toolbarItem.panel;
2036 }
2037
2038 // This table maps MIME types to the Resource.Types which are valid for them.
2039 // The following line:
2040 //    "text/html":                {0: 1},
2041 // means that text/html is a valid MIME type for resources that have type
2042 // WebInspector.Resource.Type.Document (which has a value of 0).
2043 WebInspector.MIMETypes = {
2044     "text/html":                   {0: true},
2045     "text/xml":                    {0: true},
2046     "text/plain":                  {0: true},
2047     "application/xhtml+xml":       {0: true},
2048     "text/css":                    {1: true},
2049     "text/xsl":                    {1: true},
2050     "image/jpeg":                  {2: true},
2051     "image/png":                   {2: true},
2052     "image/gif":                   {2: true},
2053     "image/bmp":                   {2: true},
2054     "image/vnd.microsoft.icon":    {2: true},
2055     "image/x-icon":                {2: true},
2056     "image/x-xbitmap":             {2: true},
2057     "font/ttf":                    {3: true},
2058     "font/opentype":               {3: true},
2059     "application/x-font-type1":    {3: true},
2060     "application/x-font-ttf":      {3: true},
2061     "application/x-truetype-font": {3: true},
2062     "text/javascript":             {4: true},
2063     "text/ecmascript":             {4: true},
2064     "application/javascript":      {4: true},
2065     "application/ecmascript":      {4: true},
2066     "application/x-javascript":    {4: true},
2067     "text/javascript1.1":          {4: true},
2068     "text/javascript1.2":          {4: true},
2069     "text/javascript1.3":          {4: true},
2070     "text/jscript":                {4: true},
2071     "text/livescript":             {4: true},
2072 }
2073
2074 WebInspector.PanelHistory = function()
2075 {
2076     this._history = [];
2077     this._historyIterator = -1;
2078 }
2079
2080 WebInspector.PanelHistory.prototype = {
2081     canGoBack: function()
2082     {
2083         return this._historyIterator > 0;
2084     },
2085
2086     goBack: function()
2087     {
2088         this._inHistory = true;
2089         WebInspector.currentPanel = WebInspector.panels[this._history[--this._historyIterator]];
2090         delete this._inHistory;
2091     },
2092
2093     canGoForward: function()
2094     {
2095         return this._historyIterator < this._history.length - 1;
2096     },
2097
2098     goForward: function()
2099     {
2100         this._inHistory = true;
2101         WebInspector.currentPanel = WebInspector.panels[this._history[++this._historyIterator]];
2102         delete this._inHistory;
2103     },
2104
2105     setPanel: function(panelName)
2106     {
2107         if (this._inHistory)
2108             return;
2109
2110         this._history.splice(this._historyIterator + 1, this._history.length - this._historyIterator - 1);
2111         if (!this._history.length || this._history[this._history.length - 1] !== panelName)
2112             this._history.push(panelName);
2113         this._historyIterator = this._history.length - 1;
2114     }
2115 }