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