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