51145cfe0d33a1567a9f6c7267a4b21f97aad39e
[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.extensionServer.notifyPageDOMContentLoaded((time - WebInspector.mainResource.startTime) * 1000);
1235     this.mainResourceDOMContentTime = time;
1236 }
1237
1238 WebInspector.loadEventFired = function(time)
1239 {
1240     this.panels.audits.mainResourceLoadTime = time;
1241     if (this.panels.network)
1242         this.panels.network.mainResourceLoadTime = time;
1243     this.extensionServer.notifyPageLoaded((time - WebInspector.mainResource.startTime) * 1000);
1244     this.mainResourceLoadTime = time;
1245 }
1246
1247 WebInspector.addDatabase = function(payload)
1248 {
1249     if (!this.panels.resources)
1250         return;
1251     var database = new WebInspector.Database(
1252         payload.id,
1253         payload.domain,
1254         payload.name,
1255         payload.version);
1256     this.panels.resources.addDatabase(database);
1257 }
1258
1259 WebInspector.addDOMStorage = function(payload)
1260 {
1261     if (!this.panels.resources)
1262         return;
1263     var domStorage = new WebInspector.DOMStorage(
1264         payload.id,
1265         payload.host,
1266         payload.isLocalStorage);
1267     this.panels.resources.addDOMStorage(domStorage);
1268 }
1269
1270 WebInspector.updateDOMStorage = function(storageId)
1271 {
1272     this.panels.resources.updateDOMStorage(storageId);
1273 }
1274
1275 WebInspector.updateApplicationCacheStatus = function(status)
1276 {
1277     this.panels.resources.updateApplicationCacheStatus(status);
1278 }
1279
1280 WebInspector.didGetFileSystemPath = function(root, type, origin)
1281 {
1282     this.panels.resources.updateFileSystemPath(root, type, origin);
1283 }
1284
1285 WebInspector.didGetFileSystemError = function(type, origin)
1286 {
1287     this.panels.resources.updateFileSystemError(type, origin);
1288 }
1289
1290 WebInspector.didGetFileSystemDisabled = function()
1291 {
1292     this.panels.resources.setFileSystemDisabled();
1293 }
1294
1295 WebInspector.updateNetworkState = function(isNowOnline)
1296 {
1297     this.panels.resources.updateNetworkState(isNowOnline);
1298 }
1299
1300 WebInspector.searchingForNodeWasEnabled = function()
1301 {
1302     this.panels.elements.searchingForNodeWasEnabled();
1303 }
1304
1305 WebInspector.searchingForNodeWasDisabled = function()
1306 {
1307     this.panels.elements.searchingForNodeWasDisabled();
1308 }
1309
1310 WebInspector.attachDebuggerWhenShown = function()
1311 {
1312     this.panels.scripts.attachDebuggerWhenShown();
1313 }
1314
1315 WebInspector.debuggerWasEnabled = function()
1316 {
1317     this.panels.scripts.debuggerWasEnabled();
1318 }
1319
1320 WebInspector.debuggerWasDisabled = function()
1321 {
1322     this.panels.scripts.debuggerWasDisabled();
1323 }
1324
1325 WebInspector.profilerWasEnabled = function()
1326 {
1327     this.panels.profiles.profilerWasEnabled();
1328 }
1329
1330 WebInspector.profilerWasDisabled = function()
1331 {
1332     this.panels.profiles.profilerWasDisabled();
1333 }
1334
1335 WebInspector.parsedScriptSource = function(sourceID, sourceURL, source, startingLine, scriptWorldType)
1336 {
1337     this.panels.scripts.addScript(sourceID, sourceURL, source, startingLine, undefined, undefined, scriptWorldType);
1338 }
1339
1340 WebInspector.restoredBreakpoint = function(sourceID, sourceURL, line, enabled, condition)
1341 {
1342     this.breakpointManager.restoredBreakpoint(sourceID, sourceURL, line, enabled, condition);
1343 }
1344
1345 WebInspector.failedToParseScriptSource = function(sourceURL, source, startingLine, errorLine, errorMessage)
1346 {
1347     this.panels.scripts.addScript(null, sourceURL, source, startingLine, errorLine, errorMessage);
1348 }
1349
1350 WebInspector.pausedScript = function(details)
1351 {
1352     this.panels.scripts.debuggerPaused(details.callFrames);
1353     this.breakpointManager.debuggerPaused(details);
1354     InspectorFrontendHost.bringToFront();
1355 }
1356
1357 WebInspector.resumedScript = function()
1358 {
1359     this.breakpointManager.debuggerResumed();
1360     this.panels.scripts.debuggerResumed();
1361 }
1362
1363 WebInspector.reset = function()
1364 {
1365     this.breakpointManager.reset();
1366
1367     for (var panelName in this.panels) {
1368         var panel = this.panels[panelName];
1369         if ("reset" in panel)
1370             panel.reset();
1371     }
1372
1373     this.resources = {};
1374     this.highlightDOMNode(0);
1375
1376     this.console.clearMessages();
1377     this.extensionServer.notifyInspectorReset();
1378
1379     this.breakpointManager.restoreBreakpoints();
1380 }
1381
1382 WebInspector.resetProfilesPanel = function()
1383 {
1384     if (WebInspector.panels.profiles)
1385         WebInspector.panels.profiles.resetProfiles();
1386 }
1387
1388 WebInspector.bringToFront = function()
1389 {
1390     InspectorFrontendHost.bringToFront();
1391 }
1392
1393 WebInspector.inspectedURLChanged = function(url)
1394 {
1395     InspectorFrontendHost.inspectedURLChanged(url);
1396     this.settings.inspectedURLChanged(url);
1397     this.extensionServer.notifyInspectedURLChanged();
1398     if (!this._breakpointsRestored) {
1399         this.breakpointManager.restoreBreakpoints();
1400         this._breakpointsRestored = true;
1401     }
1402 }
1403
1404 WebInspector.didCommitLoad = function()
1405 {
1406     // Cleanup elements panel early on inspected page refresh.
1407     WebInspector.setDocument(null);
1408 }
1409
1410 WebInspector.updateConsoleMessageExpiredCount = function(count)
1411 {
1412     var message = String.sprintf(WebInspector.UIString("%d console messages are not shown."), count);
1413     WebInspector.console.addMessage(WebInspector.ConsoleMessage.createTextMessage(message, WebInspector.ConsoleMessage.MessageLevel.Warning));
1414 }
1415
1416 WebInspector.addConsoleMessage = function(payload)
1417 {
1418     var consoleMessage = new WebInspector.ConsoleMessage(
1419         payload.source,
1420         payload.type,
1421         payload.level,
1422         payload.line,
1423         payload.url,
1424         payload.groupLevel,
1425         payload.repeatCount,
1426         payload.message,
1427         payload.parameters,
1428         payload.stackTrace);
1429     this.console.addMessage(consoleMessage);
1430 }
1431
1432 WebInspector.updateConsoleMessageRepeatCount = function(count)
1433 {
1434     this.console.updateMessageRepeatCount(count);
1435 }
1436
1437 WebInspector.log = function(message, messageLevel)
1438 {
1439     // remember 'this' for setInterval() callback
1440     var self = this;
1441
1442     // return indication if we can actually log a message
1443     function isLogAvailable()
1444     {
1445         return WebInspector.ConsoleMessage && WebInspector.RemoteObject && self.console;
1446     }
1447
1448     // flush the queue of pending messages
1449     function flushQueue()
1450     {
1451         var queued = WebInspector.log.queued;
1452         if (!queued)
1453             return;
1454
1455         for (var i = 0; i < queued.length; ++i)
1456             logMessage(queued[i]);
1457
1458         delete WebInspector.log.queued;
1459     }
1460
1461     // flush the queue if it console is available
1462     // - this function is run on an interval
1463     function flushQueueIfAvailable()
1464     {
1465         if (!isLogAvailable())
1466             return;
1467
1468         clearInterval(WebInspector.log.interval);
1469         delete WebInspector.log.interval;
1470
1471         flushQueue();
1472     }
1473
1474     // actually log the message
1475     function logMessage(message)
1476     {
1477         var repeatCount = 1;
1478         if (message == WebInspector.log.lastMessage)
1479             repeatCount = WebInspector.log.repeatCount + 1;
1480
1481         WebInspector.log.lastMessage = message;
1482         WebInspector.log.repeatCount = repeatCount;
1483
1484         // ConsoleMessage expects a proxy object
1485         message = new WebInspector.RemoteObject.fromPrimitiveValue(message);
1486
1487         // post the message
1488         var msg = new WebInspector.ConsoleMessage(
1489             WebInspector.ConsoleMessage.MessageSource.Other,
1490             WebInspector.ConsoleMessage.MessageType.Log,
1491             messageLevel || WebInspector.ConsoleMessage.MessageLevel.Debug,
1492             -1,
1493             null,
1494             null,
1495             repeatCount,
1496             null,
1497             [message],
1498             null);
1499
1500         self.console.addMessage(msg);
1501     }
1502
1503     // if we can't log the message, queue it
1504     if (!isLogAvailable()) {
1505         if (!WebInspector.log.queued)
1506             WebInspector.log.queued = [];
1507
1508         WebInspector.log.queued.push(message);
1509
1510         if (!WebInspector.log.interval)
1511             WebInspector.log.interval = setInterval(flushQueueIfAvailable, 1000);
1512
1513         return;
1514     }
1515
1516     // flush the pending queue if any
1517     flushQueue();
1518
1519     // log the message
1520     logMessage(message);
1521 }
1522
1523 WebInspector.addProfileHeader = function(profile)
1524 {
1525     this.panels.profiles.addProfileHeader(profile);
1526 }
1527
1528 WebInspector.setRecordingProfile = function(isProfiling)
1529 {
1530     this.panels.profiles.getProfileType(WebInspector.CPUProfileType.TypeId).setRecordingProfile(isProfiling);
1531     if (this.panels.profiles.hasTemporaryProfile(WebInspector.CPUProfileType.TypeId) !== isProfiling) {
1532         if (!this._temporaryRecordingProfile) {
1533             this._temporaryRecordingProfile = {
1534                 typeId: WebInspector.CPUProfileType.TypeId,
1535                 title: WebInspector.UIString("Recording…"),
1536                 uid: -1,
1537                 isTemporary: true
1538             };
1539         }
1540         if (isProfiling)
1541             this.panels.profiles.addProfileHeader(this._temporaryRecordingProfile);
1542         else
1543             this.panels.profiles.removeProfileHeader(this._temporaryRecordingProfile);
1544     }
1545     this.panels.profiles.updateProfileTypeButtons();
1546 }
1547
1548 WebInspector.addHeapSnapshotChunk = function(uid, chunk)
1549 {
1550     this.panels.profiles.addHeapSnapshotChunk(uid, chunk);
1551 }
1552
1553 WebInspector.finishHeapSnapshot = function(uid)
1554 {
1555     this.panels.profiles.finishHeapSnapshot(uid);
1556 }
1557
1558 WebInspector.drawLoadingPieChart = function(canvas, percent) {
1559     var g = canvas.getContext("2d");
1560     var darkColor = "rgb(122, 168, 218)";
1561     var lightColor = "rgb(228, 241, 251)";
1562     var cx = 8;
1563     var cy = 8;
1564     var r = 7;
1565
1566     g.beginPath();
1567     g.arc(cx, cy, r, 0, Math.PI * 2, false);
1568     g.closePath();
1569
1570     g.lineWidth = 1;
1571     g.strokeStyle = darkColor;
1572     g.fillStyle = lightColor;
1573     g.fill();
1574     g.stroke();
1575
1576     var startangle = -Math.PI / 2;
1577     var endangle = startangle + (percent * Math.PI * 2);
1578
1579     g.beginPath();
1580     g.moveTo(cx, cy);
1581     g.arc(cx, cy, r, startangle, endangle, false);
1582     g.closePath();
1583
1584     g.fillStyle = darkColor;
1585     g.fill();
1586 }
1587
1588 WebInspector.updateFocusedNode = function(nodeId)
1589 {
1590     this._updateFocusedNode(nodeId);
1591     this.highlightDOMNodeForTwoSeconds(nodeId);
1592 }
1593
1594 WebInspector.displayNameForURL = function(url)
1595 {
1596     if (!url)
1597         return "";
1598
1599     var resource = this.resourceForURL(url);
1600     if (resource)
1601         return resource.displayName;
1602
1603     if (!WebInspector.mainResource)
1604         return url.trimURL("");
1605
1606     var lastPathComponent = WebInspector.mainResource.lastPathComponent;
1607     var index = WebInspector.mainResource.url.indexOf(lastPathComponent);
1608     if (index !== -1 && index + lastPathComponent.length === WebInspector.mainResource.url.length) {
1609         var baseURL = WebInspector.mainResource.url.substring(0, index);
1610         if (url.indexOf(baseURL) === 0)
1611             return url.substring(index);
1612     }
1613
1614     return url.trimURL(WebInspector.mainResource.domain);
1615 }
1616
1617 WebInspector._choosePanelToShowSourceLine = function(url, line, preferredPanel)
1618 {
1619     preferredPanel = preferredPanel || "resources";
1620
1621     var panel = this.panels[preferredPanel];
1622     if (panel && panel.canShowSourceLine(url, line))
1623         return panel;
1624     panel = this.panels.resources;
1625     return panel.canShowSourceLine(url, line) ? panel : null;
1626 }
1627
1628 WebInspector.canShowSourceLine = function(url, line, preferredPanel)
1629 {
1630     return !!this._choosePanelToShowSourceLine(url, line, preferredPanel);
1631 }
1632
1633 WebInspector.showSourceLine = function(url, line, preferredPanel)
1634 {
1635     this.currentPanel = this._choosePanelToShowSourceLine(url, line, preferredPanel);
1636     if (!this.currentPanel)
1637         return false;
1638     this.currentPanel.showSourceLine(url, line);
1639     return true;
1640 }
1641
1642 WebInspector.linkifyStringAsFragment = function(string)
1643 {
1644     var container = document.createDocumentFragment();
1645     var linkStringRegEx = /(?:[a-zA-Z][a-zA-Z0-9+.-]{2,}:\/\/|www\.)[\w$\-_+*'=\|\/\\(){}[\]%@&#~,:;.!?]{2,}[\w$\-_+*=\|\/\\({%@&#~]/;
1646     var lineColumnRegEx = /:(\d+)(:(\d+))?$/;
1647
1648     while (string) {
1649         var linkString = linkStringRegEx.exec(string);
1650         if (!linkString)
1651             break;
1652
1653         linkString = linkString[0];
1654         var title = linkString;
1655         var linkIndex = string.indexOf(linkString);
1656         var nonLink = string.substring(0, linkIndex);
1657         container.appendChild(document.createTextNode(nonLink));
1658
1659         var profileStringMatches = WebInspector.ProfileType.URLRegExp.exec(title);
1660         if (profileStringMatches)
1661             title = WebInspector.panels.profiles.displayTitleForProfileLink(profileStringMatches[2], profileStringMatches[1]);
1662
1663         var realURL = (linkString.indexOf("www.") === 0 ? "http://" + linkString : linkString);
1664         var lineColumnMatch = lineColumnRegEx.exec(realURL);
1665         if (lineColumnMatch)
1666             realURL = realURL.substring(0, realURL.length - lineColumnMatch[0].length);
1667
1668         var hasResourceWithURL = !!WebInspector.resourceForURL(realURL);
1669         var urlNode = WebInspector.linkifyURLAsNode(realURL, title, null, hasResourceWithURL);
1670         container.appendChild(urlNode);
1671         if (lineColumnMatch) {
1672             urlNode.setAttribute("line_number", lineColumnMatch[1]);
1673             urlNode.setAttribute("preferred_panel", "scripts");
1674         }
1675         string = string.substring(linkIndex + linkString.length, string.length);
1676     }
1677
1678     if (string)
1679         container.appendChild(document.createTextNode(string));
1680
1681     return container;
1682 }
1683
1684 WebInspector.showProfileForURL = function(url)
1685 {
1686     WebInspector.showPanel("profiles");
1687     WebInspector.panels.profiles.showProfileForURL(url);
1688 }
1689
1690 WebInspector.linkifyURLAsNode = function(url, linkText, classes, isExternal, tooltipText)
1691 {
1692     if (!linkText)
1693         linkText = url;
1694     classes = (classes ? classes + " " : "");
1695     classes += isExternal ? "webkit-html-external-link" : "webkit-html-resource-link";
1696
1697     var a = document.createElement("a");
1698     a.href = url;
1699     a.className = classes;
1700     if (typeof tooltipText === "undefined")
1701         a.title = url;
1702     else if (typeof tooltipText !== "string" || tooltipText.length)
1703         a.title = tooltipText;
1704     a.textContent = linkText;
1705
1706     return a;
1707 }
1708
1709 WebInspector.linkifyURL = function(url, linkText, classes, isExternal, tooltipText)
1710 {
1711     // Use the DOM version of this function so as to avoid needing to escape attributes.
1712     // FIXME:  Get rid of linkifyURL entirely.
1713     return WebInspector.linkifyURLAsNode(url, linkText, classes, isExternal, tooltipText).outerHTML;
1714 }
1715
1716 WebInspector.linkifyResourceAsNode = function(url, preferredPanel, lineNumber, classes, tooltipText)
1717 {
1718     var linkText = WebInspector.displayNameForURL(url);
1719     if (lineNumber)
1720         linkText += ":" + lineNumber;
1721     var node = WebInspector.linkifyURLAsNode(url, linkText, classes, false, tooltipText);
1722     node.setAttribute("line_number", lineNumber);
1723     node.setAttribute("preferred_panel", preferredPanel);
1724     return node;
1725 }
1726
1727 WebInspector.resourceURLForRelatedNode = function(node, url)
1728 {
1729     if (!url || url.indexOf("://") > 0)
1730         return url;
1731
1732     for (var frameOwnerCandidate = node; frameOwnerCandidate; frameOwnerCandidate = frameOwnerCandidate.parentNode) {
1733         if (frameOwnerCandidate.documentURL) {
1734             var result = WebInspector.completeURL(frameOwnerCandidate.documentURL, url);
1735             if (result)
1736                 return result;
1737             break;
1738         }
1739     }
1740
1741     // documentURL not found or has bad value
1742     var resourceURL = url;
1743     function callback(resource)
1744     {
1745         if (resource.path === url) {
1746             resourceURL = resource.url;
1747             return true;
1748         }
1749     }
1750     WebInspector.forAllResources(callback);
1751     return resourceURL;
1752 }
1753
1754 WebInspector.completeURL = function(baseURL, href)
1755 {
1756     var parsedURL = baseURL.asParsedURL();
1757     if (parsedURL) {
1758         var path = href;
1759         if (path.charAt(0) !== "/") {
1760             var basePath = parsedURL.path;
1761             path = basePath.substring(0, basePath.lastIndexOf("/")) + "/" + path;
1762         } else if (path.length > 1 && path.charAt(1) === "/") {
1763             // href starts with "//" which is a full URL with the protocol dropped (use the baseURL protocol).
1764             return parsedURL.scheme + ":" + path;
1765         }
1766         return parsedURL.scheme + "://" + parsedURL.host + (parsedURL.port ? (":" + parsedURL.port) : "") + path;
1767     }
1768     return null;
1769 }
1770
1771 WebInspector.addMainEventListeners = function(doc)
1772 {
1773     doc.defaultView.addEventListener("focus", this.windowFocused.bind(this), false);
1774     doc.defaultView.addEventListener("blur", this.windowBlurred.bind(this), false);
1775     doc.addEventListener("click", this.documentClick.bind(this), true);
1776 }
1777
1778 WebInspector._searchFieldManualFocus = function(event)
1779 {
1780     this.currentFocusElement = event.target;
1781     this._previousFocusElement = event.target;
1782 }
1783
1784 WebInspector._searchKeyDown = function(event)
1785 {
1786     // Escape Key will clear the field and clear the search results
1787     if (event.keyCode === WebInspector.KeyboardShortcut.Keys.Esc.code) {
1788         // If focus belongs here and text is empty - nothing to do, return unhandled.
1789         if (event.target.value === "" && this.currentFocusElement === this.previousFocusElement)
1790             return;
1791         event.preventDefault();
1792         event.stopPropagation();
1793         // When search was selected manually and is currently blank, we'd like Esc stay unhandled
1794         // and hit console drawer handler.
1795         event.target.value = "";
1796
1797         this.performSearch(event);
1798         this.currentFocusElement = this.previousFocusElement;
1799         if (this.currentFocusElement === event.target)
1800             this.currentFocusElement.select();
1801         return false;
1802     }
1803
1804     if (!isEnterKey(event))
1805         return false;
1806
1807     // Select all of the text so the user can easily type an entirely new query.
1808     event.target.select();
1809
1810     // Only call performSearch if the Enter key was pressed. Otherwise the search
1811     // performance is poor because of searching on every key. The search field has
1812     // the incremental attribute set, so we still get incremental searches.
1813     this.performSearch(event);
1814
1815     // Call preventDefault since this was the Enter key. This prevents a "search" event
1816     // from firing for key down. This stops performSearch from being called twice in a row.
1817     event.preventDefault();
1818 }
1819
1820 WebInspector.performSearch = function(event)
1821 {
1822     var forceSearch = event.keyIdentifier === "Enter";
1823     this.doPerformSearch(event.target.value, forceSearch, event.shiftKey, false);
1824 }
1825
1826 WebInspector.doPerformSearch = function(query, forceSearch, isBackwardSearch, repeatSearch)
1827 {
1828     var isShortSearch = (query.length < 3);
1829
1830     // Clear a leftover short search flag due to a non-conflicting forced search.
1831     if (isShortSearch && this.shortSearchWasForcedByKeyEvent && this.currentQuery !== query)
1832         delete this.shortSearchWasForcedByKeyEvent;
1833
1834     // Indicate this was a forced search on a short query.
1835     if (isShortSearch && forceSearch)
1836         this.shortSearchWasForcedByKeyEvent = true;
1837
1838     if (!query || !query.length || (!forceSearch && isShortSearch)) {
1839         // Prevent clobbering a short search forced by the user.
1840         if (this.shortSearchWasForcedByKeyEvent) {
1841             delete this.shortSearchWasForcedByKeyEvent;
1842             return;
1843         }
1844
1845         delete this.currentQuery;
1846
1847         for (var panelName in this.panels) {
1848             var panel = this.panels[panelName];
1849             var hadCurrentQuery = !!panel.currentQuery;
1850             delete panel.currentQuery;
1851             if (hadCurrentQuery && panel.searchCanceled)
1852                 panel.searchCanceled();
1853         }
1854
1855         this.updateSearchMatchesCount();
1856
1857         return;
1858     }
1859
1860     if (!repeatSearch && query === this.currentPanel.currentQuery && this.currentPanel.currentQuery === this.currentQuery) {
1861         // When this is the same query and a forced search, jump to the next
1862         // search result for a good user experience.
1863         if (forceSearch) {
1864             if (!isBackwardSearch && this.currentPanel.jumpToNextSearchResult)
1865                 this.currentPanel.jumpToNextSearchResult();
1866             else if (isBackwardSearch && this.currentPanel.jumpToPreviousSearchResult)
1867                 this.currentPanel.jumpToPreviousSearchResult();
1868         }
1869         return;
1870     }
1871
1872     this.currentQuery = query;
1873
1874     this.updateSearchMatchesCount();
1875
1876     if (!this.currentPanel.performSearch)
1877         return;
1878
1879     this.currentPanel.currentQuery = query;
1880     this.currentPanel.performSearch(query);
1881 }
1882
1883 WebInspector.addNodesToSearchResult = function(nodeIds)
1884 {
1885     WebInspector.panels.elements.addNodesToSearchResult(nodeIds);
1886 }
1887
1888 WebInspector.updateSearchMatchesCount = function(matches, panel)
1889 {
1890     if (!panel)
1891         panel = this.currentPanel;
1892
1893     panel.currentSearchMatches = matches;
1894
1895     if (panel !== this.currentPanel)
1896         return;
1897
1898     if (!this.currentPanel.currentQuery) {
1899         document.getElementById("search-results-matches").addStyleClass("hidden");
1900         return;
1901     }
1902
1903     if (matches) {
1904         if (matches === 1)
1905             var matchesString = WebInspector.UIString("1 match");
1906         else
1907             var matchesString = WebInspector.UIString("%d matches", matches);
1908     } else
1909         var matchesString = WebInspector.UIString("Not Found");
1910
1911     var matchesToolbarElement = document.getElementById("search-results-matches");
1912     matchesToolbarElement.removeStyleClass("hidden");
1913     matchesToolbarElement.textContent = matchesString;
1914 }
1915
1916 WebInspector.UIString = function(string)
1917 {
1918     if (window.localizedStrings && string in window.localizedStrings)
1919         string = window.localizedStrings[string];
1920     else {
1921         if (!(string in WebInspector.missingLocalizedStrings)) {
1922             if (!WebInspector.InspectorBackendStub)
1923                 console.error("Localized string \"" + string + "\" not found.");
1924             WebInspector.missingLocalizedStrings[string] = true;
1925         }
1926
1927         if (Preferences.showMissingLocalizedStrings)
1928             string += " (not localized)";
1929     }
1930
1931     return String.vsprintf(string, Array.prototype.slice.call(arguments, 1));
1932 }
1933
1934 WebInspector.formatLocalized = function(format, substitutions, formatters, initialValue, append)
1935 {
1936     return String.format(WebInspector.UIString(format), substitutions, formatters, initialValue, append);
1937 }
1938
1939 WebInspector.isMac = function()
1940 {
1941     if (!("_isMac" in this))
1942         this._isMac = WebInspector.platform === "mac";
1943
1944     return this._isMac;
1945 }
1946
1947 WebInspector.isBeingEdited = function(element)
1948 {
1949     return element.__editing;
1950 }
1951
1952 WebInspector.isEditingAnyField = function()
1953 {
1954     return this.__editing;
1955 }
1956
1957 WebInspector.startEditing = function(element, committedCallback, cancelledCallback, context, multiline)
1958 {
1959     if (element.__editing)
1960         return;
1961     element.__editing = true;
1962     WebInspector.__editing = true;
1963
1964     var oldText = getContent(element);
1965     var moveDirection = "";
1966
1967     element.addStyleClass("editing");
1968
1969     var oldTabIndex = element.tabIndex;
1970     if (element.tabIndex < 0)
1971         element.tabIndex = 0;
1972
1973     function blurEventListener() {
1974         editingCommitted.call(element);
1975     }
1976
1977     function getContent(element) {
1978         if (element.tagName === "INPUT" && element.type === "text")
1979             return element.value;
1980         else
1981             return element.textContent;
1982     }
1983
1984     function cleanUpAfterEditing() {
1985         delete this.__editing;
1986         delete WebInspector.__editing;
1987
1988         this.removeStyleClass("editing");
1989         this.tabIndex = oldTabIndex;
1990         this.scrollTop = 0;
1991         this.scrollLeft = 0;
1992
1993         element.removeEventListener("blur", blurEventListener, false);
1994         element.removeEventListener("keydown", keyDownEventListener, true);
1995
1996         if (element === WebInspector.currentFocusElement || element.isAncestor(WebInspector.currentFocusElement))
1997             WebInspector.currentFocusElement = WebInspector.previousFocusElement;
1998     }
1999
2000     function editingCancelled() {
2001         if (this.tagName === "INPUT" && this.type === "text")
2002             this.value = oldText;
2003         else
2004             this.textContent = oldText;
2005
2006         cleanUpAfterEditing.call(this);
2007
2008         if (cancelledCallback)
2009             cancelledCallback(this, context);
2010     }
2011
2012     function editingCommitted() {
2013         cleanUpAfterEditing.call(this);
2014
2015         if (committedCallback)
2016             committedCallback(this, getContent(this), oldText, context, moveDirection);
2017     }
2018
2019     function keyDownEventListener(event) {
2020         var isMetaOrCtrl = WebInspector.isMac() ?
2021             event.metaKey && !event.shiftKey && !event.ctrlKey && !event.altKey :
2022             event.ctrlKey && !event.shiftKey && !event.metaKey && !event.altKey;
2023         if (isEnterKey(event) && (!multiline || isMetaOrCtrl)) {
2024             editingCommitted.call(element);
2025             event.preventDefault();
2026             event.stopPropagation();
2027         } else if (event.keyCode === WebInspector.KeyboardShortcut.Keys.Esc.code) {
2028             editingCancelled.call(element);
2029             event.preventDefault();
2030             event.stopPropagation();
2031         } else if (event.keyIdentifier === "U+0009") // Tab key
2032             moveDirection = (event.shiftKey ? "backward" : "forward");
2033     }
2034
2035     element.addEventListener("blur", blurEventListener, false);
2036     element.addEventListener("keydown", keyDownEventListener, true);
2037
2038     WebInspector.currentFocusElement = element;
2039     return {
2040         cancel: editingCancelled.bind(element),
2041         commit: editingCommitted.bind(element)
2042     };
2043 }
2044
2045 WebInspector._toolbarItemClicked = function(event)
2046 {
2047     var toolbarItem = event.currentTarget;
2048     this.currentPanel = toolbarItem.panel;
2049 }
2050
2051 // This table maps MIME types to the Resource.Types which are valid for them.
2052 // The following line:
2053 //    "text/html":                {0: 1},
2054 // means that text/html is a valid MIME type for resources that have type
2055 // WebInspector.Resource.Type.Document (which has a value of 0).
2056 WebInspector.MIMETypes = {
2057     "text/html":                   {0: true},
2058     "text/xml":                    {0: true},
2059     "text/plain":                  {0: true},
2060     "application/xhtml+xml":       {0: true},
2061     "text/css":                    {1: true},
2062     "text/xsl":                    {1: true},
2063     "image/jpeg":                  {2: true},
2064     "image/png":                   {2: true},
2065     "image/gif":                   {2: true},
2066     "image/bmp":                   {2: true},
2067     "image/vnd.microsoft.icon":    {2: true},
2068     "image/x-icon":                {2: true},
2069     "image/x-xbitmap":             {2: true},
2070     "font/ttf":                    {3: true},
2071     "font/opentype":               {3: true},
2072     "application/x-font-type1":    {3: true},
2073     "application/x-font-ttf":      {3: true},
2074     "application/x-truetype-font": {3: true},
2075     "text/javascript":             {4: true},
2076     "text/ecmascript":             {4: true},
2077     "application/javascript":      {4: true},
2078     "application/ecmascript":      {4: true},
2079     "application/x-javascript":    {4: true},
2080     "text/javascript1.1":          {4: true},
2081     "text/javascript1.2":          {4: true},
2082     "text/javascript1.3":          {4: true},
2083     "text/jscript":                {4: true},
2084     "text/livescript":             {4: true},
2085 }
2086
2087 WebInspector.PanelHistory = function()
2088 {
2089     this._history = [];
2090     this._historyIterator = -1;
2091 }
2092
2093 WebInspector.PanelHistory.prototype = {
2094     canGoBack: function()
2095     {
2096         return this._historyIterator > 0;
2097     },
2098
2099     goBack: function()
2100     {
2101         this._inHistory = true;
2102         WebInspector.currentPanel = WebInspector.panels[this._history[--this._historyIterator]];
2103         delete this._inHistory;
2104     },
2105
2106     canGoForward: function()
2107     {
2108         return this._historyIterator < this._history.length - 1;
2109     },
2110
2111     goForward: function()
2112     {
2113         this._inHistory = true;
2114         WebInspector.currentPanel = WebInspector.panels[this._history[++this._historyIterator]];
2115         delete this._inHistory;
2116     },
2117
2118     setPanel: function(panelName)
2119     {
2120         if (this._inHistory)
2121             return;
2122
2123         this._history.splice(this._historyIterator + 1, this._history.length - this._historyIterator - 1);
2124         if (!this._history.length || this._history[this._history.length - 1] !== panelName)
2125             this._history.push(panelName);
2126         this._historyIterator = this._history.length - 1;
2127     }
2128 }