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