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