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