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