2011-02-25 Andrey Kosyakov <caseq@chromium.org>
[WebKit-https.git] / Source / 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         if (x) {
157             x.show();
158             WebInspector.searchController.activePanelChanged();
159         }
160         for (var panelName in WebInspector.panels) {
161             if (WebInspector.panels[panelName] === x) {
162                 WebInspector.settings.lastActivePanel = panelName;
163                 this._panelHistory.setPanel(panelName);
164             }
165         }
166     },
167
168     createDOMBreakpointsSidebarPane: function()
169     {
170         var pane = new WebInspector.NativeBreakpointsSidebarPane(WebInspector.UIString("DOM Breakpoints"));
171         function breakpointAdded(event)
172         {
173             pane.addBreakpointItem(new WebInspector.BreakpointItem(event.data));
174         }
175         WebInspector.breakpointManager.addEventListener(WebInspector.BreakpointManager.Events.DOMBreakpointAdded, breakpointAdded);
176         return pane;
177     },
178
179     createXHRBreakpointsSidebarPane: function()
180     {
181         var pane = new WebInspector.XHRBreakpointsSidebarPane();
182         function breakpointAdded(event)
183         {
184             pane.addBreakpointItem(new WebInspector.BreakpointItem(event.data));
185         }
186         WebInspector.breakpointManager.addEventListener(WebInspector.BreakpointManager.Events.XHRBreakpointAdded, breakpointAdded);
187         return pane;
188     },
189
190     _createPanels: function()
191     {
192         var hiddenPanels = (InspectorFrontendHost.hiddenPanels() || "").split(',');
193         if (hiddenPanels.indexOf("elements") === -1)
194             this.panels.elements = new WebInspector.ElementsPanel();
195         if (hiddenPanels.indexOf("resources") === -1)
196             this.panels.resources = new WebInspector.ResourcesPanel();
197         if (hiddenPanels.indexOf("network") === -1)
198             this.panels.network = new WebInspector.NetworkPanel();
199         if (hiddenPanels.indexOf("scripts") === -1)
200             this.panels.scripts = new WebInspector.ScriptsPanel();
201         if (hiddenPanels.indexOf("timeline") === -1)
202             this.panels.timeline = new WebInspector.TimelinePanel();
203         if (hiddenPanels.indexOf("profiles") === -1) {
204             this.panels.profiles = new WebInspector.ProfilesPanel();
205             this.panels.profiles.registerProfileType(new WebInspector.CPUProfileType());
206             if (Preferences.heapProfilerPresent) {
207                 if (!Preferences.detailedHeapProfiles)
208                     this.panels.profiles.registerProfileType(new WebInspector.HeapSnapshotProfileType());
209                 else
210                     this.panels.profiles.registerProfileType(new WebInspector.DetailedHeapshotProfileType());
211             }
212         }
213         if (hiddenPanels.indexOf("audits") === -1)
214             this.panels.audits = new WebInspector.AuditsPanel();
215         if (hiddenPanels.indexOf("console") === -1)
216             this.panels.console = new WebInspector.ConsolePanel();
217     },
218
219     get attached()
220     {
221         return this._attached;
222     },
223
224     set attached(x)
225     {
226         if (this._attached === x)
227             return;
228
229         this._attached = x;
230
231         var dockToggleButton = document.getElementById("dock-status-bar-item");
232         var body = document.body;
233
234         if (x) {
235             body.removeStyleClass("detached");
236             body.addStyleClass("attached");
237             dockToggleButton.title = WebInspector.UIString("Undock into separate window.");
238         } else {
239             body.removeStyleClass("attached");
240             body.addStyleClass("detached");
241             dockToggleButton.title = WebInspector.UIString("Dock to main window.");
242         }
243
244         // This may be called before onLoadedDone, hence the bulk of inspector objects may 
245         // not be created yet.
246         if (WebInspector.searchController)
247             WebInspector.searchController.updateSearchLabel();
248     },
249
250     get errors()
251     {
252         return this._errors || 0;
253     },
254
255     set errors(x)
256     {
257         x = Math.max(x, 0);
258
259         if (this._errors === x)
260             return;
261         this._errors = x;
262         this._updateErrorAndWarningCounts();
263     },
264
265     get warnings()
266     {
267         return this._warnings || 0;
268     },
269
270     set warnings(x)
271     {
272         x = Math.max(x, 0);
273
274         if (this._warnings === x)
275             return;
276         this._warnings = x;
277         this._updateErrorAndWarningCounts();
278     },
279
280     _updateErrorAndWarningCounts: function()
281     {
282         var errorWarningElement = document.getElementById("error-warning-count");
283         if (!errorWarningElement)
284             return;
285
286         if (!this.errors && !this.warnings) {
287             errorWarningElement.addStyleClass("hidden");
288             return;
289         }
290
291         errorWarningElement.removeStyleClass("hidden");
292
293         errorWarningElement.removeChildren();
294
295         if (this.errors) {
296             var errorElement = document.createElement("span");
297             errorElement.id = "error-count";
298             errorElement.textContent = this.errors;
299             errorWarningElement.appendChild(errorElement);
300         }
301
302         if (this.warnings) {
303             var warningsElement = document.createElement("span");
304             warningsElement.id = "warning-count";
305             warningsElement.textContent = this.warnings;
306             errorWarningElement.appendChild(warningsElement);
307         }
308
309         if (this.errors) {
310             if (this.warnings) {
311                 if (this.errors == 1) {
312                     if (this.warnings == 1)
313                         errorWarningElement.title = WebInspector.UIString("%d error, %d warning", this.errors, this.warnings);
314                     else
315                         errorWarningElement.title = WebInspector.UIString("%d error, %d warnings", this.errors, this.warnings);
316                 } else if (this.warnings == 1)
317                     errorWarningElement.title = WebInspector.UIString("%d errors, %d warning", this.errors, this.warnings);
318                 else
319                     errorWarningElement.title = WebInspector.UIString("%d errors, %d warnings", this.errors, this.warnings);
320             } else if (this.errors == 1)
321                 errorWarningElement.title = WebInspector.UIString("%d error", this.errors);
322             else
323                 errorWarningElement.title = WebInspector.UIString("%d errors", this.errors);
324         } else if (this.warnings == 1)
325             errorWarningElement.title = WebInspector.UIString("%d warning", this.warnings);
326         else if (this.warnings)
327             errorWarningElement.title = WebInspector.UIString("%d warnings", this.warnings);
328         else
329             errorWarningElement.title = null;
330     },
331
332     highlightDOMNode: function(nodeId)
333     {
334         if ("_hideDOMNodeHighlightTimeout" in this) {
335             clearTimeout(this._hideDOMNodeHighlightTimeout);
336             delete this._hideDOMNodeHighlightTimeout;
337         }
338
339         if (this._highlightedDOMNodeId === nodeId)
340             return;
341
342         this._highlightedDOMNodeId = nodeId;
343         if (nodeId)
344             InspectorAgent.highlightDOMNode(nodeId);
345         else
346             InspectorAgent.hideDOMNodeHighlight();
347     },
348
349     highlightDOMNodeForTwoSeconds: function(nodeId)
350     {
351         this.highlightDOMNode(nodeId);
352         this._hideDOMNodeHighlightTimeout = setTimeout(this.highlightDOMNode.bind(this, 0), 2000);
353     },
354
355     wireElementWithDOMNode: function(element, nodeId)
356     {
357         element.addEventListener("click", this._updateFocusedNode.bind(this, nodeId), false);
358         element.addEventListener("mouseover", this.highlightDOMNode.bind(this, nodeId), false);
359         element.addEventListener("mouseout", this.highlightDOMNode.bind(this, 0), false);
360     },
361
362     _updateFocusedNode: function(nodeId)
363     {
364         this.currentPanel = this.panels.elements;
365         this.panels.elements.updateFocusedNode(nodeId);
366     },
367
368     get networkResources()
369     {
370         return this.panels.network.resources;
371     },
372
373     networkResourceById: function(id)
374     {
375         return this.panels.network.resourceById(id);
376     },
377
378     forAllResources: function(callback)
379     {
380         WebInspector.resourceTreeModel.forAllResources(callback);
381     },
382
383     resourceForURL: function(url)
384     {
385         return this.resourceTreeModel.resourceForURL(url);
386     },
387
388     openLinkExternallyLabel: function()
389     {
390         return WebInspector.UIString("Open Link in New Window");
391     }
392 }
393
394 WebInspector.PlatformFlavor = {
395     WindowsVista: "windows-vista",
396     MacTiger: "mac-tiger",
397     MacLeopard: "mac-leopard",
398     MacSnowLeopard: "mac-snowleopard"
399 };
400
401 (function parseQueryParameters()
402 {
403     WebInspector.queryParamsObject = {};
404     var queryParams = window.location.search;
405     if (!queryParams)
406         return;
407     var params = queryParams.substring(1).split("&");
408     for (var i = 0; i < params.length; ++i) {
409         var pair = params[i].split("=");
410         WebInspector.queryParamsObject[pair[0]] = pair[1];
411     }
412 })();
413
414 WebInspector.loaded = function()
415 {
416     if ("page" in WebInspector.queryParamsObject) {
417         var page = WebInspector.queryParamsObject.page;
418         var host = "host" in WebInspector.queryParamsObject ? WebInspector.queryParamsObject.host : window.location.host;
419         WebInspector.socket = new WebSocket("ws://" + host + "/devtools/page/" + page);
420         WebInspector.socket.onmessage = function(message) { InspectorBackend.dispatch(message.data); }
421         WebInspector.socket.onerror = function(error) { console.error(error); }
422         WebInspector.socket.onopen = function() {
423             InspectorFrontendHost.sendMessageToBackend = WebInspector.socket.send.bind(WebInspector.socket);
424             InspectorFrontendHost.loaded = WebInspector.socket.send.bind(WebInspector.socket, "loaded");
425             WebInspector.doLoadedDone();
426         }
427         return;
428     }
429     WebInspector.doLoadedDone();
430 }
431
432 WebInspector.doLoadedDone = function()
433 {
434     InspectorFrontendHost.loaded();
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     WebInspector.settings = new WebInspector.Settings();
445
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     this.drawer.visibleView = this.console;
455     this.resourceTreeModel = new WebInspector.ResourceTreeModel();
456     this.networkManager = new WebInspector.NetworkManager(this.resourceTreeModel);
457     this.domAgent = new WebInspector.DOMAgent();
458
459     InspectorBackend.registerDomainDispatcher("Inspector", this);
460
461     this.resourceCategories = {
462         documents: new WebInspector.ResourceCategory("documents", WebInspector.UIString("Documents"), "rgb(47,102,236)"),
463         stylesheets: new WebInspector.ResourceCategory("stylesheets", WebInspector.UIString("Stylesheets"), "rgb(157,231,119)"),
464         images: new WebInspector.ResourceCategory("images", WebInspector.UIString("Images"), "rgb(164,60,255)"),
465         scripts: new WebInspector.ResourceCategory("scripts", WebInspector.UIString("Scripts"), "rgb(255,121,0)"),
466         xhr: new WebInspector.ResourceCategory("xhr", WebInspector.UIString("XHR"), "rgb(231,231,10)"),
467         fonts: new WebInspector.ResourceCategory("fonts", WebInspector.UIString("Fonts"), "rgb(255,82,62)"),
468         websockets: new WebInspector.ResourceCategory("websockets", WebInspector.UIString("WebSockets"), "rgb(186,186,186)"), // FIXME: Decide the color.
469         other: new WebInspector.ResourceCategory("other", WebInspector.UIString("Other"), "rgb(186,186,186)")
470     };
471
472     this.cssModel = new WebInspector.CSSStyleModel();
473     this.debuggerModel = new WebInspector.DebuggerModel();
474
475     this.breakpointManager = new WebInspector.BreakpointManager();
476     this.searchController = new WebInspector.SearchController();
477
478     this.panels = {};
479     this._createPanels();
480     this._panelHistory = new WebInspector.PanelHistory();
481     this.toolbar = new WebInspector.Toolbar();
482
483     this.panelOrder = [];
484     for (var panelName in this.panels)
485         this.addPanel(this.panels[panelName]);
486
487     this.Tips = {
488         ResourceNotCompressed: {id: 0, message: WebInspector.UIString("You could save bandwidth by having your web server compress this transfer with gzip or zlib.")}
489     };
490
491     this.Warnings = {
492         IncorrectMIMEType: {id: 0, message: WebInspector.UIString("Resource interpreted as %s but transferred with MIME type %s.")}
493     };
494
495     this.addMainEventListeners(document);
496
497     window.addEventListener("resize", this.windowResize.bind(this), true);
498
499     document.addEventListener("focus", this.focusChanged.bind(this), true);
500     document.addEventListener("keydown", this.documentKeyDown.bind(this), false);
501     document.addEventListener("beforecopy", this.documentCanCopy.bind(this), true);
502     document.addEventListener("copy", this.documentCopy.bind(this), true);
503     document.addEventListener("contextmenu", this.contextMenuEventFired.bind(this), true);
504
505     var dockToggleButton = document.getElementById("dock-status-bar-item");
506     dockToggleButton.addEventListener("click", this.toggleAttach.bind(this), false);
507
508     if (this.attached)
509         dockToggleButton.title = WebInspector.UIString("Undock into separate window.");
510     else
511         dockToggleButton.title = WebInspector.UIString("Dock to main window.");
512
513     var errorWarningCount = document.getElementById("error-warning-count");
514     errorWarningCount.addEventListener("click", this.showConsole.bind(this), false);
515     this._updateErrorAndWarningCounts();
516
517     this.extensionServer.initExtensions();
518
519     function onPopulateScriptObjects()
520     {
521         if (!WebInspector.currentPanel)
522             WebInspector.showPanel(WebInspector.settings.lastActivePanel);
523     }
524     InspectorAgent.populateScriptObjects(onPopulateScriptObjects);
525
526     if (Preferences.debuggerAlwaysEnabled || WebInspector.settings.debuggerEnabled)
527         this.debuggerModel.enableDebugger();
528     if (Preferences.profilerAlwaysEnabled || WebInspector.settings.profilerEnabled)
529         InspectorAgent.enableProfiler();
530     if (WebInspector.settings.monitoringXHREnabled)
531         ConsoleAgent.setMonitoringXHREnabled(true);
532
533     ConsoleAgent.setConsoleMessagesEnabled(true);
534
535     function propertyNamesCallback(names)
536     {
537         WebInspector.cssNameCompletions = new WebInspector.CSSCompletions(names);
538     }
539     // As a DOMAgent method, this needs to happen after the frontend has loaded and the agent is available.
540     CSSAgent.getSupportedCSSProperties(propertyNamesCallback);
541 }
542
543 WebInspector.addPanel = function(panel)
544 {
545     this.panelOrder.push(panel);
546     this.toolbar.addPanel(panel);
547 }
548
549 var windowLoaded = function()
550 {
551     var localizedStringsURL = InspectorFrontendHost.localizedStringsURL();
552     if (localizedStringsURL) {
553         var localizedStringsScriptElement = document.createElement("script");
554         localizedStringsScriptElement.addEventListener("load", WebInspector.loaded.bind(WebInspector), false);
555         localizedStringsScriptElement.type = "text/javascript";
556         localizedStringsScriptElement.src = localizedStringsURL;
557         document.head.appendChild(localizedStringsScriptElement);
558     } else
559         WebInspector.loaded();
560
561     window.removeEventListener("DOMContentLoaded", windowLoaded, false);
562     delete windowLoaded;
563 };
564
565 window.addEventListener("DOMContentLoaded", windowLoaded, false);
566
567 WebInspector.dispatch = function(message) {
568     // We'd like to enforce asynchronous interaction between the inspector controller and the frontend.
569     // This is important to LayoutTests.
570     setTimeout(InspectorBackend.dispatch.bind(InspectorBackend), 0, message);
571 }
572
573 WebInspector.dispatchMessageFromBackend = function(messageObject)
574 {
575     WebInspector.dispatch(messageObject);
576 }
577
578 WebInspector.windowResize = function(event)
579 {
580     if (this.currentPanel)
581         this.currentPanel.resize();
582     this.drawer.resize();
583     this.toolbar.resize();
584 }
585
586 WebInspector.windowFocused = function(event)
587 {
588     // Fires after blur, so when focusing on either the main inspector
589     // or an <iframe> within the inspector we should always remove the
590     // "inactive" class.
591     if (event.target.document.nodeType === Node.DOCUMENT_NODE)
592         document.body.removeStyleClass("inactive");
593 }
594
595 WebInspector.windowBlurred = function(event)
596 {
597     // Leaving the main inspector or an <iframe> within the inspector.
598     // We can add "inactive" now, and if we are moving the focus to another
599     // part of the inspector then windowFocused will correct this.
600     if (event.target.document.nodeType === Node.DOCUMENT_NODE)
601         document.body.addStyleClass("inactive");
602 }
603
604 WebInspector.focusChanged = function(event)
605 {
606     this.currentFocusElement = event.target;
607 }
608
609 WebInspector.setAttachedWindow = function(attached)
610 {
611     this.attached = attached;
612 }
613
614 WebInspector.close = function(event)
615 {
616     if (this._isClosing)
617         return;
618     this._isClosing = true;
619     InspectorFrontendHost.closeWindow();
620 }
621
622 WebInspector.disconnectFromBackend = function()
623 {
624     InspectorFrontendHost.disconnectFromBackend();
625 }
626
627 WebInspector.documentClick = function(event)
628 {
629     var anchor = event.target.enclosingNodeOrSelfWithNodeName("a");
630     if (!anchor || anchor.target === "_blank")
631         return;
632
633     // Prevent the link from navigating, since we don't do any navigation by following links normally.
634     event.preventDefault();
635     event.stopPropagation();
636
637     function followLink()
638     {
639         // FIXME: support webkit-html-external-link links here.
640         if (WebInspector.canShowSourceLine(anchor.href, anchor.getAttribute("line_number"), anchor.getAttribute("preferred_panel"))) {
641             if (anchor.hasStyleClass("webkit-html-external-link")) {
642                 anchor.removeStyleClass("webkit-html-external-link");
643                 anchor.addStyleClass("webkit-html-resource-link");
644             }
645
646             WebInspector.showSourceLine(anchor.href, anchor.getAttribute("line_number"), anchor.getAttribute("preferred_panel"));
647             return;
648         }
649
650         const profileMatch = WebInspector.ProfileType.URLRegExp.exec(anchor.href);
651         if (profileMatch) {
652             WebInspector.showProfileForURL(anchor.href);
653             return;
654         }
655
656         var parsedURL = anchor.href.asParsedURL();
657         if (parsedURL && parsedURL.scheme === "webkit-link-action") {
658             if (parsedURL.host === "show-panel") {
659                 var panel = parsedURL.path.substring(1);
660                 if (WebInspector.panels[panel])
661                     WebInspector.showPanel(panel);
662             }
663             return;
664         }
665
666         WebInspector.showPanel("resources");
667     }
668
669     if (WebInspector.followLinkTimeout)
670         clearTimeout(WebInspector.followLinkTimeout);
671
672     if (anchor.preventFollowOnDoubleClick) {
673         // Start a timeout if this is the first click, if the timeout is canceled
674         // before it fires, then a double clicked happened or another link was clicked.
675         if (event.detail === 1)
676             WebInspector.followLinkTimeout = setTimeout(followLink, 333);
677         return;
678     }
679
680     followLink();
681 }
682
683 WebInspector.openResource = function(resourceURL, inResourcesPanel)
684 {
685     var resource = WebInspector.resourceForURL(resourceURL);
686     if (inResourcesPanel && resource) {
687         WebInspector.panels.resources.showResource(resource);
688         WebInspector.showPanel("resources");
689     } else
690         InspectorAgent.openInInspectedWindow(resource ? resource.url : resourceURL);
691 }
692
693 WebInspector._registerShortcuts = function()
694 {
695     var shortcut = WebInspector.KeyboardShortcut;
696     var section = WebInspector.shortcutsHelp.section(WebInspector.UIString("All Panels"));
697     var keys = [
698         shortcut.shortcutToString("]", shortcut.Modifiers.CtrlOrMeta),
699         shortcut.shortcutToString("[", shortcut.Modifiers.CtrlOrMeta)
700     ];
701     section.addRelatedKeys(keys, WebInspector.UIString("Next/previous panel"));
702     section.addKey(shortcut.shortcutToString(shortcut.Keys.Esc), WebInspector.UIString("Toggle console"));
703     section.addKey(shortcut.shortcutToString("f", shortcut.Modifiers.CtrlOrMeta), WebInspector.UIString("Search"));
704     if (WebInspector.isMac()) {
705         keys = [
706             shortcut.shortcutToString("g", shortcut.Modifiers.Meta),
707             shortcut.shortcutToString("g", shortcut.Modifiers.Meta | shortcut.Modifiers.Shift)
708         ];
709         section.addRelatedKeys(keys, WebInspector.UIString("Find next/previous"));
710     }
711 }
712
713 WebInspector.documentKeyDown = function(event)
714 {
715     var isInputElement = event.target.nodeName === "INPUT";
716     var isInEditMode = event.target.enclosingNodeOrSelfWithClass("text-prompt") || WebInspector.isEditingAnyField();
717     const helpKey = WebInspector.isMac() ? "U+003F" : "U+00BF"; // "?" for both platforms
718
719     if (event.keyIdentifier === "F1" ||
720         (event.keyIdentifier === helpKey && event.shiftKey && (!isInEditMode && !isInputElement || event.metaKey))) {
721         WebInspector.shortcutsHelp.show();
722         event.stopPropagation();
723         event.preventDefault();
724         return;
725     }
726
727     if (WebInspector.isEditingAnyField())
728         return;
729
730     if (this.currentFocusElement && this.currentFocusElement.handleKeyEvent) {
731         this.currentFocusElement.handleKeyEvent(event);
732         if (event.handled) {
733             event.preventDefault();
734             return;
735         }
736     }
737
738     if (this.currentPanel && this.currentPanel.handleShortcut) {
739         this.currentPanel.handleShortcut(event);
740         if (event.handled) {
741             event.preventDefault();
742             return;
743         }
744     }
745
746     WebInspector.searchController.handleShortcut(event);
747     if (event.handled) {
748         event.preventDefault();
749         return;
750     }
751
752     var isMac = WebInspector.isMac();
753     switch (event.keyIdentifier) {
754         case "Left":
755             var isBackKey = !isInEditMode && (isMac ? event.metaKey : event.ctrlKey);
756             if (isBackKey && this._panelHistory.canGoBack()) {
757                 this._panelHistory.goBack();
758                 event.preventDefault();
759             }
760             break;
761
762         case "Right":
763             var isForwardKey = !isInEditMode && (isMac ? event.metaKey : event.ctrlKey);
764             if (isForwardKey && this._panelHistory.canGoForward()) {
765                 this._panelHistory.goForward();
766                 event.preventDefault();
767             }
768             break;
769
770         case "U+001B": // Escape key
771             event.preventDefault();
772             if (this.drawer.fullPanel)
773                 return;
774
775             this.drawer.visible = !this.drawer.visible;
776             break;
777
778         // Windows and Mac have two different definitions of [, so accept both.
779         case "U+005B":
780         case "U+00DB": // [ key
781             if (isMac)
782                 var isRotateLeft = event.metaKey && !event.shiftKey && !event.ctrlKey && !event.altKey;
783             else
784                 var isRotateLeft = event.ctrlKey && !event.shiftKey && !event.metaKey && !event.altKey;
785
786             if (isRotateLeft) {
787                 var index = this.panelOrder.indexOf(this.currentPanel);
788                 index = (index === 0) ? this.panelOrder.length - 1 : index - 1;
789                 this.panelOrder[index].toolbarItem.click();
790                 event.preventDefault();
791             }
792
793             break;
794
795         // Windows and Mac have two different definitions of ], so accept both.
796         case "U+005D":
797         case "U+00DD":  // ] key
798             if (isMac)
799                 var isRotateRight = event.metaKey && !event.shiftKey && !event.ctrlKey && !event.altKey;
800             else
801                 var isRotateRight = event.ctrlKey && !event.shiftKey && !event.metaKey && !event.altKey;
802
803             if (isRotateRight) {
804                 var index = this.panelOrder.indexOf(this.currentPanel);
805                 index = (index + 1) % this.panelOrder.length;
806                 this.panelOrder[index].toolbarItem.click();
807                 event.preventDefault();
808             }
809
810             break;
811
812         case "U+0052": // R key
813             if ((event.metaKey && isMac) || (event.ctrlKey && !isMac)) {
814                 InspectorAgent.reloadPage(event.shiftKey);
815                 event.preventDefault();
816             }
817             break;
818         case "F5":
819             if (!isMac)
820                 InspectorAgent.reloadPage(event.ctrlKey || event.shiftKey);
821             break;
822     }
823 }
824
825 WebInspector.documentCanCopy = function(event)
826 {
827     if (this.currentPanel && this.currentPanel.handleCopyEvent)
828         event.preventDefault();
829 }
830
831 WebInspector.documentCopy = function(event)
832 {
833     if (this.currentPanel && this.currentPanel.handleCopyEvent)
834         this.currentPanel.handleCopyEvent(event);
835 }
836
837 WebInspector.contextMenuEventFired = function(event)
838 {
839     if (event.handled || event.target.hasStyleClass("popup-glasspane"))
840         event.preventDefault();
841 }
842
843 WebInspector.animateStyle = function(animations, duration, callback)
844 {
845     var interval;
846     var complete = 0;
847     var hasCompleted = false;
848
849     const intervalDuration = (1000 / 30); // 30 frames per second.
850     const animationsLength = animations.length;
851     const propertyUnit = {opacity: ""};
852     const defaultUnit = "px";
853
854     function cubicInOut(t, b, c, d)
855     {
856         if ((t/=d/2) < 1) return c/2*t*t*t + b;
857         return c/2*((t-=2)*t*t + 2) + b;
858     }
859
860     // Pre-process animations.
861     for (var i = 0; i < animationsLength; ++i) {
862         var animation = animations[i];
863         var element = null, start = null, end = null, key = null;
864         for (key in animation) {
865             if (key === "element")
866                 element = animation[key];
867             else if (key === "start")
868                 start = animation[key];
869             else if (key === "end")
870                 end = animation[key];
871         }
872
873         if (!element || !end)
874             continue;
875
876         if (!start) {
877             var computedStyle = element.ownerDocument.defaultView.getComputedStyle(element);
878             start = {};
879             for (key in end)
880                 start[key] = parseInt(computedStyle.getPropertyValue(key));
881             animation.start = start;
882         } else
883             for (key in start)
884                 element.style.setProperty(key, start[key] + (key in propertyUnit ? propertyUnit[key] : defaultUnit));
885     }
886
887     function animateLoop()
888     {
889         // Advance forward.
890         complete += intervalDuration;
891         var next = complete + intervalDuration;
892
893         // Make style changes.
894         for (var i = 0; i < animationsLength; ++i) {
895             var animation = animations[i];
896             var element = animation.element;
897             var start = animation.start;
898             var end = animation.end;
899             if (!element || !end)
900                 continue;
901
902             var style = element.style;
903             for (key in end) {
904                 var endValue = end[key];
905                 if (next < duration) {
906                     var startValue = start[key];
907                     var newValue = cubicInOut(complete, startValue, endValue - startValue, duration);
908                     style.setProperty(key, newValue + (key in propertyUnit ? propertyUnit[key] : defaultUnit));
909                 } else
910                     style.setProperty(key, endValue + (key in propertyUnit ? propertyUnit[key] : defaultUnit));
911             }
912         }
913
914         // End condition.
915         if (complete >= duration) {
916             hasCompleted = true;
917             clearInterval(interval);
918             if (callback)
919                 callback();
920         }
921     }
922
923     function forceComplete()
924     {
925         if (!hasCompleted) {
926             complete = duration;
927             animateLoop();
928         }
929     }
930
931     function cancel()
932     {
933         hasCompleted = true;
934         clearInterval(interval);
935     }
936
937     interval = setInterval(animateLoop, intervalDuration);
938     return {
939         cancel: cancel,
940         forceComplete: forceComplete
941     };
942 }
943
944 WebInspector.toggleAttach = function()
945 {
946     if (!this.attached)
947         InspectorFrontendHost.requestAttachWindow();
948     else
949         InspectorFrontendHost.requestDetachWindow();
950 }
951
952 WebInspector.elementDragStart = function(element, dividerDrag, elementDragEnd, event, cursor)
953 {
954     if (this._elementDraggingEventListener || this._elementEndDraggingEventListener)
955         this.elementDragEnd(event);
956
957     this._elementDraggingEventListener = dividerDrag;
958     this._elementEndDraggingEventListener = elementDragEnd;
959
960     document.addEventListener("mousemove", dividerDrag, true);
961     document.addEventListener("mouseup", elementDragEnd, true);
962
963     document.body.style.cursor = cursor;
964
965     event.preventDefault();
966 }
967
968 WebInspector.elementDragEnd = function(event)
969 {
970     document.removeEventListener("mousemove", this._elementDraggingEventListener, true);
971     document.removeEventListener("mouseup", this._elementEndDraggingEventListener, true);
972
973     document.body.style.removeProperty("cursor");
974
975     delete this._elementDraggingEventListener;
976     delete this._elementEndDraggingEventListener;
977
978     event.preventDefault();
979 }
980
981 WebInspector.toggleSearchingForNode = function()
982 {
983     if (this.panels.elements) {
984         this.showPanel("elements");
985         this.panels.elements.toggleSearchingForNode();
986     }
987 }
988
989 WebInspector.showConsole = function()
990 {
991     this.drawer.showView(this.console);
992 }
993
994 WebInspector.showPanel = function(panel)
995 {
996     if (!(panel in this.panels))
997         panel = "elements";
998     this.currentPanel = this.panels[panel];
999 }
1000
1001 WebInspector.domContentEventFired = function(time)
1002 {
1003     this.panels.audits.mainResourceDOMContentTime = time;
1004     if (this.panels.network)
1005         this.panels.network.mainResourceDOMContentTime = time;
1006     this.extensionServer.notifyPageDOMContentLoaded((time - WebInspector.mainResource.startTime) * 1000);
1007     this.mainResourceDOMContentTime = time;
1008 }
1009
1010 WebInspector.loadEventFired = function(time)
1011 {
1012     this.panels.audits.mainResourceLoadTime = time;
1013     this.panels.network.mainResourceLoadTime = time;
1014     this.panels.resources.loadEventFired();
1015     this.extensionServer.notifyPageLoaded((time - WebInspector.mainResource.startTime) * 1000);
1016     this.mainResourceLoadTime = time;
1017 }
1018
1019 WebInspector.searchingForNodeWasEnabled = function()
1020 {
1021     this.panels.elements.searchingForNodeWasEnabled();
1022 }
1023
1024 WebInspector.searchingForNodeWasDisabled = function()
1025 {
1026     this.panels.elements.searchingForNodeWasDisabled();
1027 }
1028
1029 WebInspector.reset = function()
1030 {
1031     this.debuggerModel.reset();
1032
1033     for (var panelName in this.panels) {
1034         var panel = this.panels[panelName];
1035         if ("reset" in panel)
1036             panel.reset();
1037     }
1038
1039     this.resources = {};
1040     this.highlightDOMNode(0);
1041
1042     this.console.clearMessages();
1043     this.extensionServer.notifyInspectorReset();
1044 }
1045
1046 WebInspector.bringToFront = function()
1047 {
1048     InspectorFrontendHost.bringToFront();
1049 }
1050
1051 WebInspector.inspectedURLChanged = function(url)
1052 {
1053     InspectorFrontendHost.inspectedURLChanged(url);
1054     this.settings.inspectedURLChanged(url);
1055     this.extensionServer.notifyInspectedURLChanged();
1056 }
1057
1058 WebInspector.log = function(message, messageLevel)
1059 {
1060     // remember 'this' for setInterval() callback
1061     var self = this;
1062
1063     // return indication if we can actually log a message
1064     function isLogAvailable()
1065     {
1066         return WebInspector.ConsoleMessage && WebInspector.RemoteObject && self.console;
1067     }
1068
1069     // flush the queue of pending messages
1070     function flushQueue()
1071     {
1072         var queued = WebInspector.log.queued;
1073         if (!queued)
1074             return;
1075
1076         for (var i = 0; i < queued.length; ++i)
1077             logMessage(queued[i]);
1078
1079         delete WebInspector.log.queued;
1080     }
1081
1082     // flush the queue if it console is available
1083     // - this function is run on an interval
1084     function flushQueueIfAvailable()
1085     {
1086         if (!isLogAvailable())
1087             return;
1088
1089         clearInterval(WebInspector.log.interval);
1090         delete WebInspector.log.interval;
1091
1092         flushQueue();
1093     }
1094
1095     // actually log the message
1096     function logMessage(message)
1097     {
1098         var repeatCount = 1;
1099         if (message == WebInspector.log.lastMessage)
1100             repeatCount = WebInspector.log.repeatCount + 1;
1101
1102         WebInspector.log.lastMessage = message;
1103         WebInspector.log.repeatCount = repeatCount;
1104
1105         // ConsoleMessage expects a proxy object
1106         message = new WebInspector.RemoteObject.fromPrimitiveValue(message);
1107
1108         // post the message
1109         var msg = new WebInspector.ConsoleMessage(
1110             WebInspector.ConsoleMessage.MessageSource.Other,
1111             WebInspector.ConsoleMessage.MessageType.Log,
1112             messageLevel || WebInspector.ConsoleMessage.MessageLevel.Debug,
1113             -1,
1114             null,
1115             repeatCount,
1116             null,
1117             [message],
1118             null);
1119
1120         self.console.addMessage(msg);
1121     }
1122
1123     // if we can't log the message, queue it
1124     if (!isLogAvailable()) {
1125         if (!WebInspector.log.queued)
1126             WebInspector.log.queued = [];
1127
1128         WebInspector.log.queued.push(message);
1129
1130         if (!WebInspector.log.interval)
1131             WebInspector.log.interval = setInterval(flushQueueIfAvailable, 1000);
1132
1133         return;
1134     }
1135
1136     // flush the pending queue if any
1137     flushQueue();
1138
1139     // log the message
1140     logMessage(message);
1141 }
1142
1143 WebInspector.drawLoadingPieChart = function(canvas, percent) {
1144     var g = canvas.getContext("2d");
1145     var darkColor = "rgb(122, 168, 218)";
1146     var lightColor = "rgb(228, 241, 251)";
1147     var cx = 8;
1148     var cy = 8;
1149     var r = 7;
1150
1151     g.beginPath();
1152     g.arc(cx, cy, r, 0, Math.PI * 2, false);
1153     g.closePath();
1154
1155     g.lineWidth = 1;
1156     g.strokeStyle = darkColor;
1157     g.fillStyle = lightColor;
1158     g.fill();
1159     g.stroke();
1160
1161     var startangle = -Math.PI / 2;
1162     var endangle = startangle + (percent * Math.PI * 2);
1163
1164     g.beginPath();
1165     g.moveTo(cx, cy);
1166     g.arc(cx, cy, r, startangle, endangle, false);
1167     g.closePath();
1168
1169     g.fillStyle = darkColor;
1170     g.fill();
1171 }
1172
1173 WebInspector.inspect = function(objectId, hints)
1174 {
1175     var object = WebInspector.RemoteObject.fromPayload(objectId);
1176     if (object.type === "node") {
1177         // Request node from backend and focus it.
1178         object.pushNodeToFrontend(WebInspector.updateFocusedNode.bind(WebInspector));
1179     } else if (hints.databaseId) {
1180         WebInspector.currentPanel = WebInspector.panels.resources;
1181         WebInspector.panels.resources.selectDatabase(hints.databaseId);
1182     } else if (hints.domStorageId) {
1183         WebInspector.currentPanel = WebInspector.panels.resources;
1184         WebInspector.panels.resources.selectDOMStorage(hints.domStorageId);
1185     }
1186
1187     RuntimeAgent.releaseObject(objectId);
1188 }
1189
1190 WebInspector.updateFocusedNode = function(nodeId)
1191 {
1192     this._updateFocusedNode(nodeId);
1193     this.highlightDOMNodeForTwoSeconds(nodeId);
1194 }
1195
1196 WebInspector.displayNameForURL = function(url)
1197 {
1198     if (!url)
1199         return "";
1200
1201     var resource = this.resourceForURL(url);
1202     if (resource)
1203         return resource.displayName;
1204
1205     if (!WebInspector.mainResource)
1206         return url.trimURL("");
1207
1208     var lastPathComponent = WebInspector.mainResource.lastPathComponent;
1209     var index = WebInspector.mainResource.url.indexOf(lastPathComponent);
1210     if (index !== -1 && index + lastPathComponent.length === WebInspector.mainResource.url.length) {
1211         var baseURL = WebInspector.mainResource.url.substring(0, index);
1212         if (url.indexOf(baseURL) === 0)
1213             return url.substring(index);
1214     }
1215
1216     return url.trimURL(WebInspector.mainResource.domain);
1217 }
1218
1219 WebInspector._choosePanelToShowSourceLine = function(url, line, preferredPanel)
1220 {
1221     preferredPanel = preferredPanel || "resources";
1222
1223     var panel = this.panels[preferredPanel];
1224     if (panel && panel.canShowSourceLine(url, line))
1225         return panel;
1226     panel = this.panels.resources;
1227     return panel.canShowSourceLine(url, line) ? panel : null;
1228 }
1229
1230 WebInspector.canShowSourceLine = function(url, line, preferredPanel)
1231 {
1232     return !!this._choosePanelToShowSourceLine(url, line, preferredPanel);
1233 }
1234
1235 WebInspector.showSourceLine = function(url, line, preferredPanel)
1236 {
1237     this.currentPanel = this._choosePanelToShowSourceLine(url, line, preferredPanel);
1238     if (!this.currentPanel)
1239         return false;
1240     if (this.drawer)
1241         this.drawer.immediatelyFinishAnimation();
1242     this.currentPanel.showSourceLine(url, line);
1243     return true;
1244 }
1245
1246 WebInspector.linkifyStringAsFragment = function(string)
1247 {
1248     var container = document.createDocumentFragment();
1249     var linkStringRegEx = /(?:[a-zA-Z][a-zA-Z0-9+.-]{2,}:\/\/|www\.)[\w$\-_+*'=\|\/\\(){}[\]%@&#~,:;.!?]{2,}[\w$\-_+*=\|\/\\({%@&#~]/;
1250     var lineColumnRegEx = /:(\d+)(:(\d+))?$/;
1251
1252     while (string) {
1253         var linkString = linkStringRegEx.exec(string);
1254         if (!linkString)
1255             break;
1256
1257         linkString = linkString[0];
1258         var title = linkString;
1259         var linkIndex = string.indexOf(linkString);
1260         var nonLink = string.substring(0, linkIndex);
1261         container.appendChild(document.createTextNode(nonLink));
1262
1263         var profileStringMatches = WebInspector.ProfileType.URLRegExp.exec(title);
1264         if (profileStringMatches)
1265             title = WebInspector.panels.profiles.displayTitleForProfileLink(profileStringMatches[2], profileStringMatches[1]);
1266
1267         var realURL = (linkString.indexOf("www.") === 0 ? "http://" + linkString : linkString);
1268         var lineColumnMatch = lineColumnRegEx.exec(realURL);
1269         if (lineColumnMatch)
1270             realURL = realURL.substring(0, realURL.length - lineColumnMatch[0].length);
1271
1272         var hasResourceWithURL = !!WebInspector.resourceForURL(realURL);
1273         var urlNode = WebInspector.linkifyURLAsNode(realURL, title, null, hasResourceWithURL);
1274         container.appendChild(urlNode);
1275         if (lineColumnMatch) {
1276             urlNode.setAttribute("line_number", lineColumnMatch[1]);
1277             urlNode.setAttribute("preferred_panel", "scripts");
1278         }
1279         string = string.substring(linkIndex + linkString.length, string.length);
1280     }
1281
1282     if (string)
1283         container.appendChild(document.createTextNode(string));
1284
1285     return container;
1286 }
1287
1288 WebInspector.showProfileForURL = function(url)
1289 {
1290     WebInspector.showPanel("profiles");
1291     WebInspector.panels.profiles.showProfileForURL(url);
1292 }
1293
1294 WebInspector.linkifyURLAsNode = function(url, linkText, classes, isExternal, tooltipText)
1295 {
1296     if (!linkText)
1297         linkText = url;
1298     classes = (classes ? classes + " " : "");
1299     classes += isExternal ? "webkit-html-external-link" : "webkit-html-resource-link";
1300
1301     var a = document.createElement("a");
1302     a.href = url;
1303     a.className = classes;
1304     if (typeof tooltipText === "undefined")
1305         a.title = url;
1306     else if (typeof tooltipText !== "string" || tooltipText.length)
1307         a.title = tooltipText;
1308     a.textContent = linkText;
1309
1310     return a;
1311 }
1312
1313 WebInspector.linkifyURL = function(url, linkText, classes, isExternal, tooltipText)
1314 {
1315     // Use the DOM version of this function so as to avoid needing to escape attributes.
1316     // FIXME:  Get rid of linkifyURL entirely.
1317     return WebInspector.linkifyURLAsNode(url, linkText, classes, isExternal, tooltipText).outerHTML;
1318 }
1319
1320 WebInspector.linkifyResourceAsNode = function(url, preferredPanel, lineNumber, classes, tooltipText)
1321 {
1322     var linkText = WebInspector.displayNameForURL(url);
1323     if (lineNumber)
1324         linkText += ":" + lineNumber;
1325     var node = WebInspector.linkifyURLAsNode(url, linkText, classes, false, tooltipText);
1326     node.setAttribute("line_number", lineNumber);
1327     node.setAttribute("preferred_panel", preferredPanel);
1328     return node;
1329 }
1330
1331 WebInspector.resourceURLForRelatedNode = function(node, url)
1332 {
1333     if (!url || url.indexOf("://") > 0)
1334         return url;
1335
1336     for (var frameOwnerCandidate = node; frameOwnerCandidate; frameOwnerCandidate = frameOwnerCandidate.parentNode) {
1337         if (frameOwnerCandidate.documentURL) {
1338             var result = WebInspector.completeURL(frameOwnerCandidate.documentURL, url);
1339             if (result)
1340                 return result;
1341             break;
1342         }
1343     }
1344
1345     // documentURL not found or has bad value
1346     var resourceURL = url;
1347     function callback(resource)
1348     {
1349         if (resource.path === url) {
1350             resourceURL = resource.url;
1351             return true;
1352         }
1353     }
1354     WebInspector.forAllResources(callback);
1355     return resourceURL;
1356 }
1357
1358 WebInspector.completeURL = function(baseURL, href)
1359 {
1360     if (href) {
1361         // Return absolute URLs as-is.
1362         var parsedHref = href.asParsedURL();
1363         if (parsedHref && parsedHref.scheme)
1364             return href;
1365     }
1366
1367     var parsedURL = baseURL.asParsedURL();
1368     if (parsedURL) {
1369         var path = href;
1370         if (path.charAt(0) !== "/") {
1371             var basePath = parsedURL.path;
1372             // A href of "?foo=bar" implies "basePath?foo=bar".
1373             // With "basePath?a=b" and "?foo=bar" we should get "basePath?foo=bar".
1374             var prefix;
1375             if (path.charAt(0) === "?") {
1376                 var basePathCutIndex = basePath.indexOf("?");
1377                 if (basePathCutIndex !== -1)
1378                     prefix = basePath.substring(0, basePathCutIndex);
1379                 else
1380                     prefix = basePath;
1381             } else
1382                 prefix = basePath.substring(0, basePath.lastIndexOf("/")) + "/";
1383
1384             path = prefix + path;
1385         } else if (path.length > 1 && path.charAt(1) === "/") {
1386             // href starts with "//" which is a full URL with the protocol dropped (use the baseURL protocol).
1387             return parsedURL.scheme + ":" + path;
1388         }
1389         return parsedURL.scheme + "://" + parsedURL.host + (parsedURL.port ? (":" + parsedURL.port) : "") + path;
1390     }
1391     return null;
1392 }
1393
1394 WebInspector.addMainEventListeners = function(doc)
1395 {
1396     doc.defaultView.addEventListener("focus", this.windowFocused.bind(this), false);
1397     doc.defaultView.addEventListener("blur", this.windowBlurred.bind(this), false);
1398     doc.addEventListener("click", this.documentClick.bind(this), true);
1399 }
1400
1401 WebInspector.frontendReused = function()
1402 {
1403     this.networkManager.reset();
1404     this.reset();
1405 }
1406
1407 WebInspector.addNodesToSearchResult = function(nodeIds)
1408 {
1409     WebInspector.panels.elements.addNodesToSearchResult(nodeIds);
1410 }
1411
1412 WebInspector.UIString = function(string)
1413 {
1414     if (window.localizedStrings && string in window.localizedStrings)
1415         string = window.localizedStrings[string];
1416     else {
1417         if (!(string in WebInspector.missingLocalizedStrings)) {
1418             if (!WebInspector.InspectorBackendStub)
1419                 console.warn("Localized string \"" + string + "\" not found.");
1420             WebInspector.missingLocalizedStrings[string] = true;
1421         }
1422
1423         if (Preferences.showMissingLocalizedStrings)
1424             string += " (not localized)";
1425     }
1426
1427     return String.vsprintf(string, Array.prototype.slice.call(arguments, 1));
1428 }
1429
1430 WebInspector.formatLocalized = function(format, substitutions, formatters, initialValue, append)
1431 {
1432     return String.format(WebInspector.UIString(format), substitutions, formatters, initialValue, append);
1433 }
1434
1435 WebInspector.isMac = function()
1436 {
1437     if (!("_isMac" in this))
1438         this._isMac = WebInspector.platform === "mac";
1439
1440     return this._isMac;
1441 }
1442
1443 WebInspector.isBeingEdited = function(element)
1444 {
1445     return element.__editing;
1446 }
1447
1448 WebInspector.isEditingAnyField = function()
1449 {
1450     return this.__editing;
1451 }
1452
1453 // Available config fields (all optional):
1454 // context: Object - an arbitrary context object to be passed to the commit and cancel handlers
1455 // commitHandler: Function - handles editing "commit" outcome
1456 // cancelHandler: Function - handles editing "cancel" outcome
1457 // customFinishHandler: Function - custom finish handler for the editing session (invoked on keydown)
1458 // pasteHandler: Function - handles the "paste" event, return values are the same as those for customFinishHandler
1459 // multiline: Boolean - whether the edited element is multiline
1460 WebInspector.startEditing = function(element, config)
1461 {
1462     if (element.__editing)
1463         return;
1464     element.__editing = true;
1465     WebInspector.__editing = true;
1466
1467     config = config || {};
1468     var committedCallback = config.commitHandler;
1469     var cancelledCallback = config.cancelHandler;
1470     var pasteCallback = config.pasteHandler;
1471     var context = config.context;
1472     var oldText = getContent(element);
1473     var moveDirection = "";
1474
1475     element.addStyleClass("editing");
1476
1477     var oldTabIndex = element.tabIndex;
1478     if (element.tabIndex < 0)
1479         element.tabIndex = 0;
1480
1481     function blurEventListener() {
1482         editingCommitted.call(element);
1483     }
1484
1485     function getContent(element) {
1486         if (element.tagName === "INPUT" && element.type === "text")
1487             return element.value;
1488         else
1489             return element.textContent;
1490     }
1491
1492     function cleanUpAfterEditing() {
1493         delete this.__editing;
1494         delete WebInspector.__editing;
1495
1496         this.removeStyleClass("editing");
1497         this.tabIndex = oldTabIndex;
1498         this.scrollTop = 0;
1499         this.scrollLeft = 0;
1500
1501         element.removeEventListener("blur", blurEventListener, false);
1502         element.removeEventListener("keydown", keyDownEventListener, true);
1503         if (pasteCallback)
1504             element.removeEventListener("paste", pasteEventListener, true);
1505
1506         if (element === WebInspector.currentFocusElement || element.isAncestor(WebInspector.currentFocusElement))
1507             WebInspector.currentFocusElement = WebInspector.previousFocusElement;
1508     }
1509
1510     function editingCancelled() {
1511         if (this.tagName === "INPUT" && this.type === "text")
1512             this.value = oldText;
1513         else
1514             this.textContent = oldText;
1515
1516         cleanUpAfterEditing.call(this);
1517
1518         if (cancelledCallback)
1519             cancelledCallback(this, context);
1520     }
1521
1522     function editingCommitted() {
1523         cleanUpAfterEditing.call(this);
1524
1525         if (committedCallback)
1526             committedCallback(this, getContent(this), oldText, context, moveDirection);
1527     }
1528
1529     function defaultFinishHandler(event)
1530     {
1531         var isMetaOrCtrl = WebInspector.isMac() ?
1532             event.metaKey && !event.shiftKey && !event.ctrlKey && !event.altKey :
1533             event.ctrlKey && !event.shiftKey && !event.metaKey && !event.altKey;
1534         if (isEnterKey(event) && (!config.multiline || isMetaOrCtrl))
1535             return "commit";
1536         else if (event.keyCode === WebInspector.KeyboardShortcut.Keys.Esc.code)
1537             return "cancel";
1538         else if (event.keyIdentifier === "U+0009") // Tab key
1539             return "move-" + (event.shiftKey ? "backward" : "forward");
1540     }
1541
1542     function handleEditingResult(result, event)
1543     {
1544         if (result === "commit") {
1545             editingCommitted.call(element);
1546             event.preventDefault();
1547             event.stopPropagation();
1548         } else if (result === "cancel") {
1549             editingCancelled.call(element);
1550             event.preventDefault();
1551             event.stopPropagation();
1552         } else if (result && result.indexOf("move-") === 0) {
1553             moveDirection = result.substring(5);
1554             if (event.keyIdentifier !== "U+0009")
1555                 blurEventListener();
1556         }
1557     }
1558
1559     function pasteEventListener(event)
1560     {
1561         var result = pasteCallback(event);
1562         handleEditingResult(result, event);
1563     }
1564
1565     function keyDownEventListener(event)
1566     {
1567         var handler = config.customFinishHandler || defaultFinishHandler;
1568         var result = handler(event);
1569         handleEditingResult(result, event);
1570     }
1571
1572     element.addEventListener("blur", blurEventListener, false);
1573     element.addEventListener("keydown", keyDownEventListener, true);
1574     if (pasteCallback)
1575         element.addEventListener("paste", pasteEventListener, true);
1576
1577     WebInspector.currentFocusElement = element;
1578     return {
1579         cancel: editingCancelled.bind(element),
1580         commit: editingCommitted.bind(element)
1581     };
1582 }
1583
1584 WebInspector._toolbarItemClicked = function(event)
1585 {
1586     var toolbarItem = event.currentTarget;
1587     this.currentPanel = toolbarItem.panel;
1588 }
1589
1590 // This table maps MIME types to the Resource.Types which are valid for them.
1591 // The following line:
1592 //    "text/html":                {0: 1},
1593 // means that text/html is a valid MIME type for resources that have type
1594 // WebInspector.Resource.Type.Document (which has a value of 0).
1595 WebInspector.MIMETypes = {
1596     "text/html":                   {0: true},
1597     "text/xml":                    {0: true},
1598     "text/plain":                  {0: true},
1599     "application/xhtml+xml":       {0: true},
1600     "text/css":                    {1: true},
1601     "text/xsl":                    {1: true},
1602     "image/jpeg":                  {2: true},
1603     "image/png":                   {2: true},
1604     "image/gif":                   {2: true},
1605     "image/bmp":                   {2: true},
1606     "image/vnd.microsoft.icon":    {2: true},
1607     "image/x-icon":                {2: true},
1608     "image/x-xbitmap":             {2: true},
1609     "font/ttf":                    {3: true},
1610     "font/opentype":               {3: true},
1611     "application/x-font-type1":    {3: true},
1612     "application/x-font-ttf":      {3: true},
1613     "application/x-font-woff":     {3: true},
1614     "application/x-truetype-font": {3: true},
1615     "text/javascript":             {4: true},
1616     "text/ecmascript":             {4: true},
1617     "application/javascript":      {4: true},
1618     "application/ecmascript":      {4: true},
1619     "application/x-javascript":    {4: true},
1620     "text/javascript1.1":          {4: true},
1621     "text/javascript1.2":          {4: true},
1622     "text/javascript1.3":          {4: true},
1623     "text/jscript":                {4: true},
1624     "text/livescript":             {4: true},
1625 }
1626
1627 WebInspector.PanelHistory = function()
1628 {
1629     this._history = [];
1630     this._historyIterator = -1;
1631 }
1632
1633 WebInspector.PanelHistory.prototype = {
1634     canGoBack: function()
1635     {
1636         return this._historyIterator > 0;
1637     },
1638
1639     goBack: function()
1640     {
1641         this._inHistory = true;
1642         WebInspector.currentPanel = WebInspector.panels[this._history[--this._historyIterator]];
1643         delete this._inHistory;
1644     },
1645
1646     canGoForward: function()
1647     {
1648         return this._historyIterator < this._history.length - 1;
1649     },
1650
1651     goForward: function()
1652     {
1653         this._inHistory = true;
1654         WebInspector.currentPanel = WebInspector.panels[this._history[++this._historyIterator]];
1655         delete this._inHistory;
1656     },
1657
1658     setPanel: function(panelName)
1659     {
1660         if (this._inHistory)
1661             return;
1662
1663         this._history.splice(this._historyIterator + 1, this._history.length - this._historyIterator - 1);
1664         if (!this._history.length || this._history[this._history.length - 1] !== panelName)
1665             this._history.push(panelName);
1666         this._historyIterator = this._history.length - 1;
1667     }
1668 }