86077cd66dbbaa6f14ba4eea057172d2856b40b2
[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 var WebInspector = {
32     _panelDescriptors: function()
33     {
34         this.panels = {};
35         WebInspector.inspectorView = new WebInspector.InspectorView();
36         var parentElement = document.getElementById("main");
37         WebInspector.inspectorView.show(parentElement);
38         WebInspector.inspectorView.addEventListener(WebInspector.InspectorView.Events.PanelSelected, this._panelSelected, this);
39
40         var elements = new WebInspector.ElementsPanelDescriptor();
41         var resources = new WebInspector.PanelDescriptor("resources", WebInspector.UIString("Resources"), "ResourcesPanel", "ResourcesPanel.js");
42         var network = new WebInspector.NetworkPanelDescriptor();
43         var scripts = new WebInspector.ScriptsPanelDescriptor();
44         var timeline = new WebInspector.TimelinePanelDescriptor();
45         var profiles = new WebInspector.ProfilesPanelDescriptor();
46         var audits = new WebInspector.PanelDescriptor("audits", WebInspector.UIString("Audits"), "AuditsPanel", "AuditsPanel.js");
47         var console = new WebInspector.PanelDescriptor("console", WebInspector.UIString("Console"), "ConsolePanel");
48         var allDescriptors = [elements, resources, network, scripts, timeline, profiles, audits, console];
49         var allProfilers = [profiles];
50         if (WebInspector.experimentsSettings.separateProfilers.isEnabled()) {
51             allProfilers = [];
52             allProfilers.push(new WebInspector.PanelDescriptor("cpu-profiler", WebInspector.UIString("CPU Profiler"), "CPUProfilerPanel", "ProfilesPanel.js"));
53             if (!WebInspector.WorkerManager.isWorkerFrontend())
54                 allProfilers.push(new WebInspector.PanelDescriptor("css-profiler", WebInspector.UIString("CSS Profiler"), "CSSSelectorProfilerPanel", "ProfilesPanel.js"));
55             if (Capabilities.heapProfilerPresent)
56                 allProfilers.push(new WebInspector.PanelDescriptor("heap-profiler", WebInspector.UIString("Heap Profiler"), "HeapProfilerPanel", "ProfilesPanel.js"));
57             if (!WebInspector.WorkerManager.isWorkerFrontend() && WebInspector.experimentsSettings.canvasInspection.isEnabled())
58                 allProfilers.push(new WebInspector.PanelDescriptor("canvas-profiler", WebInspector.UIString("Canvas Profiler"), "CanvasProfilerPanel", "ProfilesPanel.js"));
59             if (!WebInspector.WorkerManager.isWorkerFrontend() && WebInspector.experimentsSettings.nativeMemorySnapshots.isEnabled()) {
60                 allProfilers.push(new WebInspector.PanelDescriptor("memory-chart-profiler", WebInspector.UIString("Memory Distribution"), "MemoryChartProfilerPanel", "ProfilesPanel.js"));
61                 allProfilers.push(new WebInspector.PanelDescriptor("memory-snapshot-profiler", WebInspector.UIString("Memory Snapshots"), "NativeMemoryProfilerPanel", "ProfilesPanel.js"));
62             }
63             Array.prototype.splice.bind(allDescriptors, allDescriptors.indexOf(profiles), 1).apply(null, allProfilers);
64         }
65
66         var panelDescriptors = [];
67         if (WebInspector.WorkerManager.isWorkerFrontend()) {
68             panelDescriptors.push(scripts);
69             panelDescriptors.push(timeline);
70             panelDescriptors = panelDescriptors.concat(allProfilers);
71             panelDescriptors.push(console);
72             return panelDescriptors;
73         }
74         var hiddenPanels = InspectorFrontendHost.hiddenPanels();
75         for (var i = 0; i < allDescriptors.length; ++i) {
76             if (hiddenPanels.indexOf(allDescriptors[i].name()) === -1)
77                 panelDescriptors.push(allDescriptors[i]);
78         }
79         return panelDescriptors;
80     },
81
82     _panelSelected: function()
83     {
84         this._toggleConsoleButton.setEnabled(WebInspector.inspectorView.currentPanel().name !== "console");
85     },
86
87     _createGlobalStatusBarItems: function()
88     {
89         var bottomStatusBarContainer = document.getElementById("bottom-status-bar-container");
90
91         // Create main dock button and options.
92         var mainStatusBar = document.getElementById("main-status-bar");
93         mainStatusBar.insertBefore(this.dockController.element, bottomStatusBarContainer);
94
95         this._toggleConsoleButton = new WebInspector.StatusBarButton(WebInspector.UIString("Show console."), "console-status-bar-item");
96         this._toggleConsoleButton.addEventListener("click", this._toggleConsoleButtonClicked.bind(this), false);
97         mainStatusBar.insertBefore(this._toggleConsoleButton.element, bottomStatusBarContainer);
98
99         if (!WebInspector.WorkerManager.isWorkerFrontend()) {
100             this._nodeSearchButton = new WebInspector.StatusBarButton(WebInspector.UIString("Select an element in the page to inspect it."), "node-search-status-bar-item");
101             this._nodeSearchButton.addEventListener("click", this.toggleSearchingForNode, this);
102             mainStatusBar.insertBefore(this._nodeSearchButton.element, bottomStatusBarContainer);
103         }
104
105         mainStatusBar.appendChild(this.settingsController.statusBarItem);
106     },
107
108     _toggleConsoleButtonClicked: function()
109     {
110         if (!this._toggleConsoleButton.enabled())
111             return;
112
113         this._toggleConsoleButton.toggled = !this._toggleConsoleButton.toggled;
114
115         var animationType = window.event && window.event.shiftKey ? WebInspector.Drawer.AnimationType.Slow : WebInspector.Drawer.AnimationType.Normal;
116         if (this._toggleConsoleButton.toggled) {
117             this._toggleConsoleButton.title = WebInspector.UIString("Hide console.");
118             this.drawer.show(this.consoleView, animationType);
119             this._consoleWasShown = true;
120         } else {
121             this._toggleConsoleButton.title = WebInspector.UIString("Show console.");
122             this.drawer.hide(animationType);
123             delete this._consoleWasShown;
124         }
125     },
126
127     /**
128      * @param {Element} statusBarElement
129      * @param {WebInspector.View} view
130      * @param {function()=} onclose
131      */
132     showViewInDrawer: function(statusBarElement, view, onclose)
133     {
134         this._toggleConsoleButton.title = WebInspector.UIString("Hide console.");
135         this._toggleConsoleButton.toggled = false;
136         this._closePreviousDrawerView();
137
138         var drawerStatusBarHeader = document.createElement("div");
139         drawerStatusBarHeader.className = "drawer-header status-bar-item";
140         drawerStatusBarHeader.appendChild(statusBarElement);
141         drawerStatusBarHeader.onclose = onclose;
142
143         var closeButton = drawerStatusBarHeader.createChild("span");
144         closeButton.textContent = WebInspector.UIString("\u00D7");
145         closeButton.addStyleClass("drawer-header-close-button");
146         closeButton.addEventListener("click", this.closeViewInDrawer.bind(this), false);
147
148         var panelStatusBar = document.getElementById("panel-status-bar");
149         var drawerViewAnchor = document.getElementById("drawer-view-anchor");
150         panelStatusBar.insertBefore(drawerStatusBarHeader, drawerViewAnchor);
151         this._drawerStatusBarHeader = drawerStatusBarHeader;
152         this.drawer.show(view, WebInspector.Drawer.AnimationType.Immediately);
153     },
154
155     closeViewInDrawer: function()
156     {
157         if (this._drawerStatusBarHeader) {
158             this._closePreviousDrawerView();
159
160             // Once drawer is closed console should be shown if it was shown before current view replaced it in drawer. 
161             if (!this._consoleWasShown)
162                 this.drawer.hide(WebInspector.Drawer.AnimationType.Immediately);
163             else
164                 this._toggleConsoleButtonClicked();
165         }
166     },
167
168     _closePreviousDrawerView: function()
169     {
170         if (this._drawerStatusBarHeader) {
171             this._drawerStatusBarHeader.parentElement.removeChild(this._drawerStatusBarHeader);
172             if (this._drawerStatusBarHeader.onclose)
173                 this._drawerStatusBarHeader.onclose();
174             delete this._drawerStatusBarHeader;
175         }
176     },
177
178     _updateErrorAndWarningCounts: function()
179     {
180         var errorWarningElement = document.getElementById("error-warning-count");
181         if (!errorWarningElement)
182             return;
183
184         var errors = WebInspector.console.errors;
185         var warnings = WebInspector.console.warnings;
186         if (!errors && !warnings) {
187             errorWarningElement.addStyleClass("hidden");
188             return;
189         }
190
191         errorWarningElement.removeStyleClass("hidden");
192
193         errorWarningElement.removeChildren();
194
195         if (errors) {
196             var errorImageElement = document.createElement("img");
197             errorImageElement.id = "error-count-img";
198             errorWarningElement.appendChild(errorImageElement);
199             var errorElement = document.createElement("span");
200             errorElement.id = "error-count";
201             errorElement.textContent = errors;
202             errorWarningElement.appendChild(errorElement);
203         }
204
205         if (warnings) {
206             var warningsImageElement = document.createElement("img");
207             warningsImageElement.id = "warning-count-img";
208             errorWarningElement.appendChild(warningsImageElement);
209             var warningsElement = document.createElement("span");
210             warningsElement.id = "warning-count";
211             warningsElement.textContent = warnings;
212             errorWarningElement.appendChild(warningsElement);
213         }
214
215         if (errors) {
216             if (warnings) {
217                 if (errors == 1) {
218                     if (warnings == 1)
219                         errorWarningElement.title = WebInspector.UIString("%d error, %d warning", errors, warnings);
220                     else
221                         errorWarningElement.title = WebInspector.UIString("%d error, %d warnings", errors, warnings);
222                 } else if (warnings == 1)
223                     errorWarningElement.title = WebInspector.UIString("%d errors, %d warning", errors, warnings);
224                 else
225                     errorWarningElement.title = WebInspector.UIString("%d errors, %d warnings", errors, warnings);
226             } else if (errors == 1)
227                 errorWarningElement.title = WebInspector.UIString("%d error", errors);
228             else
229                 errorWarningElement.title = WebInspector.UIString("%d errors", errors);
230         } else if (warnings == 1)
231             errorWarningElement.title = WebInspector.UIString("%d warning", warnings);
232         else if (warnings)
233             errorWarningElement.title = WebInspector.UIString("%d warnings", warnings);
234         else
235             errorWarningElement.title = null;
236     },
237
238     get inspectedPageDomain()
239     {
240         var parsedURL = WebInspector.inspectedPageURL && WebInspector.inspectedPageURL.asParsedURL();
241         return parsedURL ? parsedURL.host : "";
242     },
243
244     _initializeCapability: function(name, callback, error, result)
245     {
246         Capabilities[name] = result;
247         if (callback)
248             callback();
249     },
250
251     _zoomIn: function()
252     {
253         this._zoomLevel = Math.min(this._zoomLevel + 1, WebInspector.Zoom.Table.length - WebInspector.Zoom.DefaultOffset - 1);
254         this._requestZoom();
255     },
256
257     _zoomOut: function()
258     {
259         this._zoomLevel = Math.max(this._zoomLevel - 1, -WebInspector.Zoom.DefaultOffset);
260         this._requestZoom();
261     },
262
263     _resetZoom: function()
264     {
265         this._zoomLevel = 0;
266         this._requestZoom();
267     },
268
269     _requestZoom: function()
270     {
271         WebInspector.settings.zoomLevel.set(this._zoomLevel);
272         // For backwards compatibility, zoomLevel takes integers (with 0 being default zoom).
273         var index = this._zoomLevel + WebInspector.Zoom.DefaultOffset;
274         index = Math.min(WebInspector.Zoom.Table.length - 1, index);
275         index = Math.max(0, index);
276         InspectorFrontendHost.setZoomFactor(WebInspector.Zoom.Table[index]);
277     },
278
279     toggleSearchingForNode: function()
280     {
281         var enabled = !this._nodeSearchButton.toggled;
282         /**
283          * @param {?Protocol.Error} error
284          */
285         function callback(error)
286         {
287             if (!error)
288                 this._nodeSearchButton.toggled = enabled;
289         }
290         WebInspector.domAgent.setInspectModeEnabled(enabled, callback.bind(this));
291     },
292
293     _debuggerPaused: function()
294     {
295         // Create scripts panel upon demand.
296         WebInspector.panel("scripts");
297     }
298 }
299
300 WebInspector.Events = {
301     InspectorLoaded: "InspectorLoaded",
302     InspectorClosing: "InspectorClosing"
303 }
304
305 {(function parseQueryParameters()
306 {
307     WebInspector.queryParamsObject = {};
308     var queryParams = window.location.search;
309     if (!queryParams)
310         return;
311     var params = queryParams.substring(1).split("&");
312     for (var i = 0; i < params.length; ++i) {
313         var pair = params[i].split("=");
314         WebInspector.queryParamsObject[pair[0]] = pair[1];
315     }
316 })();}
317
318 WebInspector.suggestReload = function()
319 {
320     if (window.confirm(WebInspector.UIString("It is recommended to restart inspector after making these changes. Would you like to restart it?")))
321         this.reload();
322 }
323
324 WebInspector.reload = function()
325 {
326     var queryParams = window.location.search;
327     var url = window.location.href;
328     url = url.substring(0, url.length - queryParams.length);
329     var queryParamsObject = {};
330     for (var name in WebInspector.queryParamsObject)
331         queryParamsObject[name] = WebInspector.queryParamsObject[name];
332     if (this.dockController)
333         queryParamsObject["dockSide"] = this.dockController.dockSide();
334     var names = Object.keys(queryParamsObject);
335     for (var i = 0; i < names.length; ++i)
336         url += (i ? "&" : "?") + names[i] + "=" + queryParamsObject[names[i]];
337
338     InspectorBackend.disconnect();
339     document.location = url;
340 }
341
342 WebInspector.loaded = function()
343 {
344     InspectorBackend.loadFromJSONIfNeeded("../Inspector.json");
345     WebInspector.dockController = new WebInspector.DockController();
346
347     if (WebInspector.WorkerManager.isDedicatedWorkerFrontend()) {
348         // Do not create socket for the worker front-end.
349         WebInspector.doLoadedDone();
350         return;
351     }
352
353     var ws;
354     if ("ws" in WebInspector.queryParamsObject)
355         ws = "ws://" + WebInspector.queryParamsObject.ws;
356     else if ("page" in WebInspector.queryParamsObject) {
357         var page = WebInspector.queryParamsObject.page;
358         var host = "host" in WebInspector.queryParamsObject ? WebInspector.queryParamsObject.host : window.location.host;
359         ws = "ws://" + host + "/devtools/page/" + page;
360     }
361
362     if (ws) {
363         WebInspector.socket = new WebSocket(ws);
364         WebInspector.socket.onmessage = function(message) { InspectorBackend.dispatch(message.data); }
365         WebInspector.socket.onerror = function(error) { console.error(error); }
366         WebInspector.socket.onopen = function() {
367             InspectorFrontendHost.sendMessageToBackend = WebInspector.socket.send.bind(WebInspector.socket);
368             WebInspector.doLoadedDone();
369         }
370         WebInspector.socket.onclose = function() {
371             if (!WebInspector.socket._detachReason)
372                 (new WebInspector.RemoteDebuggingTerminatedScreen("websocket_closed")).showModal();
373         }
374         return;
375     }
376
377     WebInspector.doLoadedDone();
378
379     // In case of loading as a web page with no bindings / harness, kick off initialization manually.
380     if (InspectorFrontendHost.isStub) {
381         InspectorFrontendAPI.dispatchQueryParameters();
382         WebInspector._doLoadedDoneWithCapabilities();
383     }
384 }
385
386 WebInspector.doLoadedDone = function()
387 {
388     // Install styles and themes
389     WebInspector.installPortStyles();
390     if (WebInspector.socket)
391         document.body.addStyleClass("remote");
392
393     if (WebInspector.queryParamsObject.toolbarColor && WebInspector.queryParamsObject.textColor)
394         WebInspector.setToolbarColors(WebInspector.queryParamsObject.toolbarColor, WebInspector.queryParamsObject.textColor);
395
396     InspectorFrontendHost.loaded();
397     WebInspector.WorkerManager.loaded();
398
399     DebuggerAgent.causesRecompilation(WebInspector._initializeCapability.bind(WebInspector, "debuggerCausesRecompilation", null));
400     DebuggerAgent.supportsSeparateScriptCompilationAndExecution(WebInspector._initializeCapability.bind(WebInspector, "separateScriptCompilationAndExecutionEnabled", null));
401     ProfilerAgent.causesRecompilation(WebInspector._initializeCapability.bind(WebInspector, "profilerCausesRecompilation", null));
402     ProfilerAgent.isSampling(WebInspector._initializeCapability.bind(WebInspector, "samplingCPUProfiler", null));
403     HeapProfilerAgent.hasHeapProfiler(WebInspector._initializeCapability.bind(WebInspector, "heapProfilerPresent", null));
404     TimelineAgent.supportsFrameInstrumentation(WebInspector._initializeCapability.bind(WebInspector, "timelineSupportsFrameInstrumentation", null));
405     TimelineAgent.canMonitorMainThread(WebInspector._initializeCapability.bind(WebInspector, "timelineCanMonitorMainThread", null));
406     PageAgent.canShowDebugBorders(WebInspector._initializeCapability.bind(WebInspector, "canShowDebugBorders", null));
407     PageAgent.canShowFPSCounter(WebInspector._initializeCapability.bind(WebInspector, "canShowFPSCounter", null));
408     PageAgent.canContinuouslyPaint(WebInspector._initializeCapability.bind(WebInspector, "canContinuouslyPaint", null));
409     PageAgent.canOverrideDeviceMetrics(WebInspector._initializeCapability.bind(WebInspector, "canOverrideDeviceMetrics", null));
410     PageAgent.canOverrideGeolocation(WebInspector._initializeCapability.bind(WebInspector, "canOverrideGeolocation", null));
411     PageAgent.canOverrideDeviceOrientation(WebInspector._initializeCapability.bind(WebInspector, "canOverrideDeviceOrientation", WebInspector._doLoadedDoneWithCapabilities.bind(WebInspector)));
412 }
413
414 WebInspector._doLoadedDoneWithCapabilities = function()
415 {
416     new WebInspector.VersionController().updateVersion();
417
418     WebInspector.shortcutsScreen = new WebInspector.ShortcutsScreen();
419     this._registerShortcuts();
420
421     // set order of some sections explicitly
422     WebInspector.shortcutsScreen.section(WebInspector.UIString("Console"));
423     WebInspector.shortcutsScreen.section(WebInspector.UIString("Elements Panel"));
424
425     var panelDescriptors = this._panelDescriptors();
426     for (var i = 0; i < panelDescriptors.length; ++i)
427         panelDescriptors[i].registerShortcuts();
428
429     this.console = new WebInspector.ConsoleModel();
430     this.console.addEventListener(WebInspector.ConsoleModel.Events.ConsoleCleared, this._updateErrorAndWarningCounts, this);
431     this.console.addEventListener(WebInspector.ConsoleModel.Events.MessageAdded, this._updateErrorAndWarningCounts, this);
432     this.console.addEventListener(WebInspector.ConsoleModel.Events.RepeatCountUpdated, this._updateErrorAndWarningCounts, this);
433
434     WebInspector.CSSMetadata.requestCSSShorthandData();
435
436     this.drawer = new WebInspector.Drawer();
437
438     this.networkManager = new WebInspector.NetworkManager();
439     this.resourceTreeModel = new WebInspector.ResourceTreeModel(this.networkManager);
440     this.debuggerModel = new WebInspector.DebuggerModel();
441     this.debuggerModel.addEventListener(WebInspector.DebuggerModel.Events.DebuggerPaused, this._debuggerPaused, this);
442     this.networkLog = new WebInspector.NetworkLog();
443     this.domAgent = new WebInspector.DOMAgent();
444     this.runtimeModel = new WebInspector.RuntimeModel(this.resourceTreeModel);
445
446     this.consoleView = new WebInspector.ConsoleView(WebInspector.WorkerManager.isWorkerFrontend());
447
448     InspectorBackend.registerInspectorDispatcher(this);
449
450     this.isolatedFileSystemManager = new WebInspector.IsolatedFileSystemManager();
451     this.isolatedFileSystemDispatcher = new WebInspector.IsolatedFileSystemDispatcher(this.isolatedFileSystemManager);
452     this.fileMapping = new WebInspector.FileMapping();
453     this.workspace = new WebInspector.Workspace(this.fileMapping, this.isolatedFileSystemManager.mapping());
454
455     this.cssModel = new WebInspector.CSSStyleModel(this.workspace);
456     this.timelineManager = new WebInspector.TimelineManager();
457     this.userAgentSupport = new WebInspector.UserAgentSupport();
458
459     this.searchController = new WebInspector.SearchController();
460     this.advancedSearchController = new WebInspector.AdvancedSearchController();
461     this.settingsController = new WebInspector.SettingsController();
462
463     this.domBreakpointsSidebarPane = new WebInspector.DOMBreakpointsSidebarPane();
464
465     this._zoomLevel = WebInspector.settings.zoomLevel.get();
466     if (this._zoomLevel)
467         this._requestZoom();
468
469     var autoselectPanel = WebInspector.UIString("a panel chosen automatically");
470     var openAnchorLocationSetting = WebInspector.settings.createSetting("openLinkHandler", autoselectPanel);
471     this.openAnchorLocationRegistry = new WebInspector.HandlerRegistry(openAnchorLocationSetting);
472     this.openAnchorLocationRegistry.registerHandler(autoselectPanel, function() { return false; });
473
474     this.workspaceController = new WebInspector.WorkspaceController(this.workspace);
475
476     this.fileSystemWorkspaceProvider = new WebInspector.FileSystemWorkspaceProvider(this.isolatedFileSystemManager, this.workspace);
477
478     this.networkWorkspaceProvider = new WebInspector.SimpleWorkspaceProvider(this.workspace, WebInspector.projectTypes.Network);
479     new WebInspector.NetworkUISourceCodeProvider(this.networkWorkspaceProvider, this.workspace);
480
481     this.breakpointManager = new WebInspector.BreakpointManager(WebInspector.settings.breakpoints, this.debuggerModel, this.workspace);
482
483     this.scriptSnippetModel = new WebInspector.ScriptSnippetModel(this.workspace);
484
485     new WebInspector.DebuggerScriptMapping(this.workspace, this.networkWorkspaceProvider);
486     this.liveEditSupport = new WebInspector.LiveEditSupport(this.workspace);
487     this.styleContentBinding = new WebInspector.StyleContentBinding(this.cssModel, this.workspace);
488     new WebInspector.StylesSourceMapping(this.cssModel, this.workspace);
489     if (WebInspector.experimentsSettings.sass.isEnabled())
490         new WebInspector.SASSSourceMapping(this.cssModel, this.workspace, this.networkWorkspaceProvider);
491
492     new WebInspector.PresentationConsoleMessageHelper(this.workspace);
493
494     this._createGlobalStatusBarItems();
495
496     this.toolbar = new WebInspector.Toolbar();
497     WebInspector.startBatchUpdate();
498     for (var i = 0; i < panelDescriptors.length; ++i)
499         WebInspector.inspectorView.addPanel(panelDescriptors[i]);
500     WebInspector.endBatchUpdate();
501
502     this.addMainEventListeners(document);
503
504     window.addEventListener("resize", this.windowResize.bind(this), true);
505
506     var errorWarningCount = document.getElementById("error-warning-count");
507     errorWarningCount.addEventListener("click", this.showConsole.bind(this), false);
508     this._updateErrorAndWarningCounts();
509
510     this.extensionServer.initExtensions();
511
512     this.console.enableAgent();
513
514     function showInitialPanel()
515     {
516         if (!WebInspector.inspectorView.currentPanel())
517             WebInspector.showPanel(WebInspector.settings.lastActivePanel.get());
518     }
519
520     InspectorAgent.enable(showInitialPanel);
521     this.databaseModel = new WebInspector.DatabaseModel();
522     this.domStorageModel = new WebInspector.DOMStorageModel();
523
524     if (!Capabilities.profilerCausesRecompilation || WebInspector.settings.profilerEnabled.get())
525         ProfilerAgent.enable();
526
527     if (WebInspector.settings.showPaintRects.get())
528         PageAgent.setShowPaintRects(true);
529
530     if (WebInspector.settings.showDebugBorders.get())
531         PageAgent.setShowDebugBorders(true);
532
533     if (WebInspector.settings.continuousPainting.get())
534         PageAgent.setContinuousPaintingEnabled(true);
535
536     if (WebInspector.settings.javaScriptDisabled.get())
537         PageAgent.setScriptExecutionDisabled(true);
538
539     if (WebInspector.settings.showFPSCounter.get())
540         PageAgent.setShowFPSCounter(true);
541
542     this.domAgent._emulateTouchEventsChanged();
543
544     WebInspector.WorkerManager.loadCompleted();
545     InspectorFrontendAPI.loadCompleted();
546
547     WebInspector.notifications.dispatchEventToListeners(WebInspector.Events.InspectorLoaded);
548 }
549
550 var windowLoaded = function()
551 {
552     var localizedStringsURL = InspectorFrontendHost.localizedStringsURL();
553     if (localizedStringsURL) {
554         var localizedStringsScriptElement = document.createElement("script");
555         localizedStringsScriptElement.addEventListener("load", WebInspector.loaded.bind(WebInspector), false);
556         localizedStringsScriptElement.type = "text/javascript";
557         localizedStringsScriptElement.src = localizedStringsURL;
558         document.head.appendChild(localizedStringsScriptElement);
559     } else
560         WebInspector.loaded();
561
562     window.removeEventListener("DOMContentLoaded", windowLoaded, false);
563     delete windowLoaded;
564 };
565
566 window.addEventListener("DOMContentLoaded", windowLoaded, false);
567
568 // We'd like to enforce asynchronous interaction between the inspector controller and the frontend.
569 // It is needed to prevent re-entering the backend code.
570 // Also, native dispatches do not guarantee setTimeouts to be serialized, so we
571 // enforce serialization using 'messagesToDispatch' queue. It is also important that JSC debugger
572 // tests require that each command was dispatch within individual timeout callback, so we don't batch them.
573
574 var messagesToDispatch = [];
575
576 WebInspector.dispatchQueueIsEmpty = function() {
577     return messagesToDispatch.length == 0;
578 }
579
580 WebInspector.dispatch = function(message) {
581     messagesToDispatch.push(message);
582     setTimeout(function() {
583         InspectorBackend.dispatch(messagesToDispatch.shift());
584     }, 0);
585 }
586
587 WebInspector.windowResize = function(event)
588 {
589     if (WebInspector.inspectorView)
590         WebInspector.inspectorView.doResize();
591     if (WebInspector.drawer)
592         WebInspector.drawer.resize();
593     if (WebInspector.toolbar)
594         WebInspector.toolbar.resize();
595     if (WebInspector.settingsController)
596         WebInspector.settingsController.resize();
597 }
598
599 WebInspector.setDockingUnavailable = function(unavailable)
600 {
601     if (this.dockController)
602         this.dockController.setDockingUnavailable(unavailable);
603 }
604
605 WebInspector.close = function(event)
606 {
607     if (this._isClosing)
608         return;
609     this._isClosing = true;
610     this.notifications.dispatchEventToListeners(WebInspector.Events.InspectorClosing);
611     InspectorFrontendHost.closeWindow();
612 }
613
614 WebInspector.documentClick = function(event)
615 {
616     var anchor = event.target.enclosingNodeOrSelfWithNodeName("a");
617     if (!anchor || (anchor.target === "_blank"))
618         return;
619
620     // Prevent the link from navigating, since we don't do any navigation by following links normally.
621     event.consume(true);
622
623     function followLink()
624     {
625         if (WebInspector.isBeingEdited(event.target) || WebInspector._showAnchorLocation(anchor))
626             return;
627
628         const profileMatch = WebInspector.ProfilesPanelDescriptor.ProfileURLRegExp.exec(anchor.href);
629         if (profileMatch) {
630             WebInspector.showPanel("profiles").showProfile(profileMatch[1], profileMatch[2]);
631             return;
632         }
633
634         var parsedURL = anchor.href.asParsedURL();
635         if (parsedURL && parsedURL.scheme === "webkit-link-action") {
636             if (parsedURL.host === "show-panel") {
637                 var panel = parsedURL.path.substring(1);
638                 if (WebInspector.panel(panel))
639                     WebInspector.showPanel(panel);
640             }
641             return;
642         }
643
644         InspectorFrontendHost.openInNewTab(anchor.href);
645     }
646
647     if (WebInspector.followLinkTimeout)
648         clearTimeout(WebInspector.followLinkTimeout);
649
650     if (anchor.preventFollowOnDoubleClick) {
651         // Start a timeout if this is the first click, if the timeout is canceled
652         // before it fires, then a double clicked happened or another link was clicked.
653         if (event.detail === 1)
654             WebInspector.followLinkTimeout = setTimeout(followLink, 333);
655         return;
656     }
657
658     followLink();
659 }
660
661 WebInspector.openResource = function(resourceURL, inResourcesPanel)
662 {
663     var resource = WebInspector.resourceForURL(resourceURL);
664     if (inResourcesPanel && resource)
665         WebInspector.showPanel("resources").showResource(resource);
666     else
667         InspectorFrontendHost.openInNewTab(resourceURL);
668 }
669
670 WebInspector._registerShortcuts = function()
671 {
672     var shortcut = WebInspector.KeyboardShortcut;
673     var section = WebInspector.shortcutsScreen.section(WebInspector.UIString("All Panels"));
674     var keys = [
675         shortcut.makeDescriptor("[", shortcut.Modifiers.CtrlOrMeta),
676         shortcut.makeDescriptor("]", shortcut.Modifiers.CtrlOrMeta)
677     ];
678     section.addRelatedKeys(keys, WebInspector.UIString("Go to the panel to the left/right"));
679
680     var keys = [
681         shortcut.makeDescriptor("[", shortcut.Modifiers.CtrlOrMeta | shortcut.Modifiers.Alt),
682         shortcut.makeDescriptor("]", shortcut.Modifiers.CtrlOrMeta | shortcut.Modifiers.Alt)
683     ];
684     section.addRelatedKeys(keys, WebInspector.UIString("Go back/forward in panel history"));
685
686     section.addKey(shortcut.makeDescriptor(shortcut.Keys.Esc), WebInspector.UIString("Toggle console"));
687     section.addKey(shortcut.makeDescriptor("f", shortcut.Modifiers.CtrlOrMeta), WebInspector.UIString("Search"));
688
689     var advancedSearchShortcut = WebInspector.AdvancedSearchController.createShortcut();
690     section.addKey(advancedSearchShortcut, WebInspector.UIString("Search across all sources"));
691
692     var openResourceShortcut = WebInspector.KeyboardShortcut.makeDescriptor("o", WebInspector.KeyboardShortcut.Modifiers.CtrlOrMeta);
693     section.addKey(openResourceShortcut, WebInspector.UIString("Go to source"));
694
695     if (WebInspector.isMac()) {
696         keys = [
697             shortcut.makeDescriptor("g", shortcut.Modifiers.Meta),
698             shortcut.makeDescriptor("g", shortcut.Modifiers.Meta | shortcut.Modifiers.Shift)
699         ];
700         section.addRelatedKeys(keys, WebInspector.UIString("Find next/previous"));
701     }
702
703     var goToShortcut = WebInspector.GoToLineDialog.createShortcut();
704     section.addKey(goToShortcut, WebInspector.UIString("Go to line"));
705 }
706
707 /**
708  * @param {KeyboardEvent} event
709  */
710 WebInspector.documentKeyDown = function(event)
711 {
712     const helpKey = WebInspector.isMac() ? "U+003F" : "U+00BF"; // "?" for both platforms
713
714     if (event.keyIdentifier === "F1" ||
715         (event.keyIdentifier === helpKey && event.shiftKey && (!WebInspector.isBeingEdited(event.target) || event.metaKey))) {
716         this.settingsController.showSettingsScreen(WebInspector.SettingsScreen.Tabs.Shortcuts);
717         event.consume(true);
718         return;
719     }
720
721     if (WebInspector.currentFocusElement() && WebInspector.currentFocusElement().handleKeyEvent) {
722         WebInspector.currentFocusElement().handleKeyEvent(event);
723         if (event.handled) {
724             event.consume(true);
725             return;
726         }
727     }
728
729     if (WebInspector.inspectorView.currentPanel()) {
730         WebInspector.inspectorView.currentPanel().handleShortcut(event);
731         if (event.handled) {
732             event.consume(true);
733             return;
734         }
735     }
736
737     if (WebInspector.searchController.handleShortcut(event))
738         return;
739     if (WebInspector.advancedSearchController.handleShortcut(event))
740         return;
741
742     switch (event.keyIdentifier) {
743         case "U+004F": // O key
744             if (!event.shiftKey && !event.altKey && WebInspector.KeyboardShortcut.eventHasCtrlOrMeta(event)) {
745                 WebInspector.showPanel("scripts").showGoToSourceDialog();
746                 event.consume(true);
747             }
748             break;
749         case "U+0052": // R key
750             if (WebInspector.KeyboardShortcut.eventHasCtrlOrMeta(event)) {
751                 PageAgent.reload(event.shiftKey);
752                 event.consume(true);
753             }
754             if (window.DEBUG && event.altKey) {
755                 WebInspector.reload();
756                 return;
757             }
758             break;
759         case "F5":
760             if (!WebInspector.isMac()) {
761                 PageAgent.reload(event.ctrlKey || event.shiftKey);
762                 event.consume(true);
763             }
764             break;
765     }
766
767     var isValidZoomShortcut = WebInspector.KeyboardShortcut.eventHasCtrlOrMeta(event) &&
768         !event.altKey &&
769         !InspectorFrontendHost.isStub;
770     switch (event.keyCode) {
771         case 107: // +
772         case 187: // +
773             if (isValidZoomShortcut) {
774                 WebInspector._zoomIn();
775                 event.consume(true);
776             }
777             break;
778         case 109: // -
779         case 189: // -
780             if (isValidZoomShortcut) {
781                 WebInspector._zoomOut();
782                 event.consume(true);
783             }
784             break;
785         case 48: // 0
786             // Zoom reset shortcut does not allow "Shift" when handled by the browser.
787             if (isValidZoomShortcut && !event.shiftKey) {
788                 WebInspector._resetZoom();
789                 event.consume(true);
790             }
791             break;
792     }
793
794     // Cmd/Control + Shift + C should be a shortcut to clicking the Node Search Button.
795     // This shortcut matches Firebug.
796     if (event.keyIdentifier === "U+0043") { // C key
797         if (WebInspector.isMac())
798             var isNodeSearchKey = event.metaKey && !event.ctrlKey && !event.altKey && event.shiftKey;
799         else
800             var isNodeSearchKey = event.ctrlKey && !event.metaKey && !event.altKey && event.shiftKey;
801
802         if (isNodeSearchKey) {
803             this.toggleSearchingForNode();
804             event.consume(true);
805             return;
806         }
807         return;
808     }
809 }
810
811 WebInspector.postDocumentKeyDown = function(event)
812 {
813     if (event.handled)
814         return;
815
816     if (event.keyCode === WebInspector.KeyboardShortcut.Keys.Esc.code) {
817         // If drawer is open with some view other than console then close it.
818         if (!this._toggleConsoleButton.toggled && WebInspector.drawer.visible)
819             this.closeViewInDrawer();
820         else
821             this._toggleConsoleButtonClicked();
822     }
823 }
824
825 WebInspector.documentCanCopy = function(event)
826 {
827     if (WebInspector.inspectorView.currentPanel() && WebInspector.inspectorView.currentPanel().handleCopyEvent)
828         event.preventDefault();
829 }
830
831 WebInspector.documentCopy = function(event)
832 {
833     if (WebInspector.inspectorView.currentPanel() && WebInspector.inspectorView.currentPanel().handleCopyEvent)
834         WebInspector.inspectorView.currentPanel().handleCopyEvent(event);
835     WebInspector.documentCopyEventFired(event);
836 }
837
838 WebInspector.documentCopyEventFired = function(event)
839 {
840 }
841
842 WebInspector.contextMenuEventFired = function(event)
843 {
844     if (event.handled || event.target.hasStyleClass("popup-glasspane"))
845         event.preventDefault();
846 }
847
848 WebInspector.showConsole = function()
849 {
850     if (WebInspector._toggleConsoleButton && !WebInspector._toggleConsoleButton.toggled) {
851         if (WebInspector.drawer.visible)
852             this._closePreviousDrawerView();
853         WebInspector._toggleConsoleButtonClicked();
854     }
855 }
856
857 WebInspector.showPanel = function(panel)
858 {
859     return WebInspector.inspectorView.showPanel(panel);
860 }
861
862 WebInspector.panel = function(panel)
863 {
864     return WebInspector.inspectorView.panel(panel);
865 }
866
867 WebInspector.bringToFront = function()
868 {
869     InspectorFrontendHost.bringToFront();
870 }
871
872 /**
873  * @param {string=} messageLevel
874  * @param {boolean=} showConsole
875  */
876 WebInspector.log = function(message, messageLevel, showConsole)
877 {
878     // remember 'this' for setInterval() callback
879     var self = this;
880
881     // return indication if we can actually log a message
882     function isLogAvailable()
883     {
884         return WebInspector.ConsoleMessage && WebInspector.RemoteObject && self.console;
885     }
886
887     // flush the queue of pending messages
888     function flushQueue()
889     {
890         var queued = WebInspector.log.queued;
891         if (!queued)
892             return;
893
894         for (var i = 0; i < queued.length; ++i)
895             logMessage(queued[i]);
896
897         delete WebInspector.log.queued;
898     }
899
900     // flush the queue if it console is available
901     // - this function is run on an interval
902     function flushQueueIfAvailable()
903     {
904         if (!isLogAvailable())
905             return;
906
907         clearInterval(WebInspector.log.interval);
908         delete WebInspector.log.interval;
909
910         flushQueue();
911     }
912
913     // actually log the message
914     function logMessage(message)
915     {
916         // post the message
917         var msg = WebInspector.ConsoleMessage.create(
918             WebInspector.ConsoleMessage.MessageSource.Other,
919             messageLevel || WebInspector.ConsoleMessage.MessageLevel.Debug,
920             message);
921
922         self.console.addMessage(msg);
923         if (showConsole)
924             WebInspector.showConsole();
925     }
926
927     // if we can't log the message, queue it
928     if (!isLogAvailable()) {
929         if (!WebInspector.log.queued)
930             WebInspector.log.queued = [];
931
932         WebInspector.log.queued.push(message);
933
934         if (!WebInspector.log.interval)
935             WebInspector.log.interval = setInterval(flushQueueIfAvailable, 1000);
936
937         return;
938     }
939
940     // flush the pending queue if any
941     flushQueue();
942
943     // log the message
944     logMessage(message);
945 }
946
947 WebInspector.showErrorMessage = function(error)
948 {
949     WebInspector.log(error, WebInspector.ConsoleMessage.MessageLevel.Error, true);
950 }
951
952 // Inspector.inspect protocol event
953 WebInspector.inspect = function(payload, hints)
954 {
955     var object = WebInspector.RemoteObject.fromPayload(payload);
956     if (object.subtype === "node") {
957         function callback(nodeId)
958         {
959             WebInspector._updateFocusedNode(nodeId);
960             object.release();
961         }
962         object.pushNodeToFrontend(callback);
963         return;
964     }
965
966     if (hints.databaseId)
967         WebInspector.showPanel("resources").selectDatabase(WebInspector.databaseModel.databaseForId(hints.databaseId));
968     else if (hints.domStorageId)
969         WebInspector.showPanel("resources").selectDOMStorage(WebInspector.domStorageModel.storageForId(hints.domStorageId));
970
971     object.release();
972 }
973
974 // Inspector.detached protocol event
975 WebInspector.detached = function(reason)
976 {
977     WebInspector.socket._detachReason = reason;
978     (new WebInspector.RemoteDebuggingTerminatedScreen(reason)).showModal();
979 }
980
981 WebInspector._updateFocusedNode = function(nodeId)
982 {
983     if (WebInspector._nodeSearchButton.toggled) {
984         InspectorFrontendHost.bringToFront();
985         WebInspector._nodeSearchButton.toggled = false;
986     }
987     WebInspector.showPanel("elements").revealAndSelectNode(nodeId);
988 }
989
990 WebInspector._showAnchorLocation = function(anchor)
991 {
992     if (WebInspector.openAnchorLocationRegistry.dispatch({ url: anchor.href, lineNumber: anchor.lineNumber}))
993         return true;
994     var preferredPanel = this.panels[anchor.preferredPanel];
995     if (preferredPanel && WebInspector._showAnchorLocationInPanel(anchor, preferredPanel))
996         return true;
997     if (WebInspector._showAnchorLocationInPanel(anchor, this.panel("scripts")))
998         return true;
999     if (WebInspector._showAnchorLocationInPanel(anchor, this.panel("resources")))
1000         return true;
1001     if (WebInspector._showAnchorLocationInPanel(anchor, this.panel("network")))
1002         return true;
1003     return false;
1004 }
1005
1006 WebInspector._showAnchorLocationInPanel = function(anchor, panel)
1007 {
1008     if (!panel || !panel.canShowAnchorLocation(anchor))
1009         return false;
1010
1011     // FIXME: support webkit-html-external-link links here.
1012     if (anchor.hasStyleClass("webkit-html-external-link")) {
1013         anchor.removeStyleClass("webkit-html-external-link");
1014         anchor.addStyleClass("webkit-html-resource-link");
1015     }
1016
1017     WebInspector.inspectorView.showPanelForAnchorNavigation(panel);
1018     panel.showAnchorLocation(anchor);
1019     return true;
1020 }
1021
1022 WebInspector.evaluateInConsole = function(expression, showResultOnly)
1023 {
1024     this.showConsole();
1025     this.consoleView.evaluateUsingTextPrompt(expression, showResultOnly);
1026 }
1027
1028 WebInspector.addMainEventListeners = function(doc)
1029 {
1030     doc.addEventListener("keydown", this.documentKeyDown.bind(this), true);
1031     doc.addEventListener("keydown", this.postDocumentKeyDown.bind(this), false);
1032     doc.addEventListener("beforecopy", this.documentCanCopy.bind(this), true);
1033     doc.addEventListener("copy", this.documentCopy.bind(this), true);
1034     doc.addEventListener("contextmenu", this.contextMenuEventFired.bind(this), true);
1035     doc.addEventListener("click", this.documentClick.bind(this), true);
1036 }
1037
1038 WebInspector.Zoom = {
1039     Table: [0.25, 0.33, 0.5, 0.66, 0.75, 0.9, 1, 1.1, 1.25, 1.5, 1.75, 2, 2.5, 3, 4, 5],
1040     DefaultOffset: 6
1041 }