Web Inspector: Cmd-+ doesn't "zoom in" to increase text size in the Web Inspector
[WebKit-https.git] / Source / WebInspectorUI / UserInterface / Base / Main.js
1 /*
2  * Copyright (C) 2013-2016 Apple Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
14  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
15  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
17  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
18  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
19  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
20  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
21  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
22  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
23  * THE POSSIBILITY OF SUCH DAMAGE.
24  */
25
26 WebInspector.ContentViewCookieType = {
27     ApplicationCache: "application-cache",
28     CookieStorage: "cookie-storage",
29     Database: "database",
30     DatabaseTable: "database-table",
31     DOMStorage: "dom-storage",
32     Resource: "resource", // includes Frame too.
33     Timelines: "timelines"
34 };
35
36 WebInspector.DebuggableType = {
37     Web: "web",
38     JavaScript: "javascript"
39 };
40
41 WebInspector.SelectedSidebarPanelCookieKey = "selected-sidebar-panel";
42 WebInspector.TypeIdentifierCookieKey = "represented-object-type";
43
44 WebInspector.StateRestorationType = {
45     Load: "state-restoration-load",
46     Navigation: "state-restoration-navigation",
47     Delayed: "state-restoration-delayed",
48 };
49
50 WebInspector.loaded = function()
51 {
52     // Initialize WebSocket to communication.
53     this._initializeWebSocketIfNeeded();
54
55     this.debuggableType = InspectorFrontendHost.debuggableType() === "web" ? WebInspector.DebuggableType.Web : WebInspector.DebuggableType.JavaScript;
56     this.hasExtraDomains = false;
57
58     // Register observers for events from the InspectorBackend.
59     if (InspectorBackend.registerInspectorDispatcher)
60         InspectorBackend.registerInspectorDispatcher(new WebInspector.InspectorObserver);
61     if (InspectorBackend.registerPageDispatcher)
62         InspectorBackend.registerPageDispatcher(new WebInspector.PageObserver);
63     if (InspectorBackend.registerConsoleDispatcher)
64         InspectorBackend.registerConsoleDispatcher(new WebInspector.ConsoleObserver);
65     if (InspectorBackend.registerNetworkDispatcher)
66         InspectorBackend.registerNetworkDispatcher(new WebInspector.NetworkObserver);
67     if (InspectorBackend.registerDOMDispatcher)
68         InspectorBackend.registerDOMDispatcher(new WebInspector.DOMObserver);
69     if (InspectorBackend.registerDebuggerDispatcher)
70         InspectorBackend.registerDebuggerDispatcher(new WebInspector.DebuggerObserver);
71     if (InspectorBackend.registerHeapDispatcher)
72         InspectorBackend.registerHeapDispatcher(new WebInspector.HeapObserver);
73     if (InspectorBackend.registerMemoryDispatcher)
74         InspectorBackend.registerMemoryDispatcher(new WebInspector.MemoryObserver);
75     if (InspectorBackend.registerDatabaseDispatcher)
76         InspectorBackend.registerDatabaseDispatcher(new WebInspector.DatabaseObserver);
77     if (InspectorBackend.registerDOMStorageDispatcher)
78         InspectorBackend.registerDOMStorageDispatcher(new WebInspector.DOMStorageObserver);
79     if (InspectorBackend.registerApplicationCacheDispatcher)
80         InspectorBackend.registerApplicationCacheDispatcher(new WebInspector.ApplicationCacheObserver);
81     if (InspectorBackend.registerScriptProfilerDispatcher)
82         InspectorBackend.registerScriptProfilerDispatcher(new WebInspector.ScriptProfilerObserver);
83     if (InspectorBackend.registerTimelineDispatcher)
84         InspectorBackend.registerTimelineDispatcher(new WebInspector.TimelineObserver);
85     if (InspectorBackend.registerCSSDispatcher)
86         InspectorBackend.registerCSSDispatcher(new WebInspector.CSSObserver);
87     if (InspectorBackend.registerLayerTreeDispatcher)
88         InspectorBackend.registerLayerTreeDispatcher(new WebInspector.LayerTreeObserver);
89     if (InspectorBackend.registerRuntimeDispatcher)
90         InspectorBackend.registerRuntimeDispatcher(new WebInspector.RuntimeObserver);
91     if (InspectorBackend.registerReplayDispatcher)
92         InspectorBackend.registerReplayDispatcher(new WebInspector.ReplayObserver);
93
94     // Enable agents.
95     InspectorAgent.enable();
96
97     // Perform one-time tasks.
98     WebInspector.CSSCompletions.requestCSSCompletions();
99
100     // Listen for the ProvisionalLoadStarted event before registering for events so our code gets called before any managers or sidebars.
101     // This lets us save a state cookie before any managers or sidebars do any resets that would affect state (namely TimelineManager).
102     WebInspector.Frame.addEventListener(WebInspector.Frame.Event.ProvisionalLoadStarted, this._provisionalLoadStarted, this);
103
104     // Create the singleton managers next, before the user interface elements, so the user interface can register
105     // as event listeners on these managers.
106     this.branchManager = new WebInspector.BranchManager;
107     this.frameResourceManager = new WebInspector.FrameResourceManager;
108     this.storageManager = new WebInspector.StorageManager;
109     this.domTreeManager = new WebInspector.DOMTreeManager;
110     this.cssStyleManager = new WebInspector.CSSStyleManager;
111     this.logManager = new WebInspector.LogManager;
112     this.issueManager = new WebInspector.IssueManager;
113     this.analyzerManager = new WebInspector.AnalyzerManager;
114     this.runtimeManager = new WebInspector.RuntimeManager;
115     this.heapManager = new WebInspector.HeapManager;
116     this.memoryManager = new WebInspector.MemoryManager;
117     this.applicationCacheManager = new WebInspector.ApplicationCacheManager;
118     this.timelineManager = new WebInspector.TimelineManager;
119     this.debuggerManager = new WebInspector.DebuggerManager;
120     this.sourceMapManager = new WebInspector.SourceMapManager;
121     this.layerTreeManager = new WebInspector.LayerTreeManager;
122     this.dashboardManager = new WebInspector.DashboardManager;
123     this.probeManager = new WebInspector.ProbeManager;
124     this.replayManager = new WebInspector.ReplayManager;
125
126     // Enable the Console Agent after creating the singleton managers.
127     ConsoleAgent.enable();
128
129     // Tell the backend we are initialized after all our initialization messages have been sent.
130     setTimeout(function() {
131         // COMPATIBILITY (iOS 8): Inspector.initialized did not exist yet.
132         if (InspectorAgent.initialized)
133             InspectorAgent.initialized();
134     }, 0);
135
136     // Register for events.
137     this.replayManager.addEventListener(WebInspector.ReplayManager.Event.CaptureStarted, this._captureDidStart, this);
138     this.debuggerManager.addEventListener(WebInspector.DebuggerManager.Event.Paused, this._debuggerDidPause, this);
139     this.debuggerManager.addEventListener(WebInspector.DebuggerManager.Event.Resumed, this._debuggerDidResume, this);
140     this.domTreeManager.addEventListener(WebInspector.DOMTreeManager.Event.InspectModeStateChanged, this._inspectModeStateChanged, this);
141     this.domTreeManager.addEventListener(WebInspector.DOMTreeManager.Event.DOMNodeWasInspected, this._domNodeWasInspected, this);
142     this.storageManager.addEventListener(WebInspector.StorageManager.Event.DOMStorageObjectWasInspected, this._storageWasInspected, this);
143     this.storageManager.addEventListener(WebInspector.StorageManager.Event.DatabaseWasInspected, this._storageWasInspected, this);
144     this.frameResourceManager.addEventListener(WebInspector.FrameResourceManager.Event.MainFrameDidChange, this._mainFrameDidChange, this);
145     this.frameResourceManager.addEventListener(WebInspector.FrameResourceManager.Event.FrameWasAdded, this._frameWasAdded, this);
146
147     WebInspector.Frame.addEventListener(WebInspector.Frame.Event.MainResourceDidChange, this._mainResourceDidChange, this);
148
149     document.addEventListener("DOMContentLoaded", this.contentLoaded.bind(this));
150
151     // Create settings.
152     this._showingSplitConsoleSetting = new WebInspector.Setting("showing-split-console", false);
153     this._splitConsoleHeightSetting = new WebInspector.Setting("split-console-height", 150);
154
155     this._openTabsSetting = new WebInspector.Setting("open-tab-types", ["elements", "network", "resources", "timeline", "debugger", "storage", "console"]);
156     this._selectedTabIndexSetting = new WebInspector.Setting("selected-tab-index", 0);
157
158     this.showShadowDOMSetting = new WebInspector.Setting("show-shadow-dom", false);
159     this.showReplayInterfaceSetting = new WebInspector.Setting("show-web-replay", false);
160
161     // COMPATIBILITY (iOS 8): Page.enableTypeProfiler did not exist.
162     this.showJavaScriptTypeInformationSetting = new WebInspector.Setting("show-javascript-type-information", false);
163     if (this.showJavaScriptTypeInformationSetting.value && window.RuntimeAgent && RuntimeAgent.enableTypeProfiler) {
164         RuntimeAgent.enableTypeProfiler();
165     }
166
167     this.enableControlFlowProfilerSetting = new WebInspector.Setting("enable-control-flow-profiler", false);
168     if (this.enableControlFlowProfilerSetting.value && window.RuntimeAgent && RuntimeAgent.enableControlFlowProfiler)
169         RuntimeAgent.enableControlFlowProfiler();
170
171     // COMPATIBILITY (iOS 8): Page.setShowPaintRects did not exist.
172     this.showPaintRectsSetting = new WebInspector.Setting("show-paint-rects", false);
173     if (this.showPaintRectsSetting.value && window.PageAgent && PageAgent.setShowPaintRects)
174         PageAgent.setShowPaintRects(true);
175
176     this._zoomFactorSetting = new WebInspector.Setting("zoom-factor", 1);
177     this._setZoomFactor(this._zoomFactorSetting.value);
178
179     this.mouseCoords = {
180         x: 0,
181         y: 0
182     };
183
184     this.visible = false;
185
186     this._windowKeydownListeners = [];
187 };
188
189 WebInspector.contentLoaded = function()
190 {
191     // If there was an uncaught exception earlier during loading, then
192     // abort loading more content. We could be in an inconsistent state.
193     if (window.__uncaughtExceptions)
194         return;
195
196     // Register for global events.
197     document.addEventListener("beforecopy", this._beforecopy.bind(this));
198     document.addEventListener("copy", this._copy.bind(this));
199
200     document.addEventListener("click", this._mouseWasClicked.bind(this));
201     document.addEventListener("dragover", this._dragOver.bind(this));
202     document.addEventListener("focus", WebInspector._focusChanged.bind(this), true);
203
204     window.addEventListener("focus", this._windowFocused.bind(this));
205     window.addEventListener("blur", this._windowBlurred.bind(this));
206     window.addEventListener("resize", this._windowResized.bind(this));
207     window.addEventListener("keydown", this._windowKeyDown.bind(this));
208     window.addEventListener("keyup", this._windowKeyUp.bind(this));
209     window.addEventListener("mousemove", this._mouseMoved.bind(this), true);
210     window.addEventListener("pagehide", this._pageHidden.bind(this));
211     window.addEventListener("contextmenu", this._contextMenuRequested.bind(this));
212
213     // Add platform style classes so the UI can be tweaked per-platform.
214     document.body.classList.add(WebInspector.Platform.name + "-platform");
215     if (WebInspector.Platform.isNightlyBuild)
216         document.body.classList.add("nightly-build");
217
218     if (WebInspector.Platform.name === "mac") {
219         document.body.classList.add(WebInspector.Platform.version.name);
220
221         if (WebInspector.Platform.version.release >= 11)
222             document.body.classList.add("latest-mac");
223         else
224             document.body.classList.add("legacy-mac");
225     }
226
227     document.body.classList.add(this.debuggableType);
228
229     // Create the user interface elements.
230     this.toolbar = new WebInspector.Toolbar(document.getElementById("toolbar"), null, true);
231     this.toolbar.displayMode = WebInspector.Toolbar.DisplayMode.IconOnly;
232     this.toolbar.sizeMode = WebInspector.Toolbar.SizeMode.Small;
233
234     this.tabBar = new WebInspector.TabBar(document.getElementById("tab-bar"));
235     this.tabBar.addEventListener(WebInspector.TabBar.Event.NewTabItemClicked, this._newTabItemClicked, this);
236     this.tabBar.addEventListener(WebInspector.TabBar.Event.OpenDefaultTab, this._openDefaultTab, this);
237
238     this._contentElement = document.getElementById("content");
239     this._contentElement.setAttribute("role", "main");
240     this._contentElement.setAttribute("aria-label", WebInspector.UIString("Content"));
241
242     this.splitContentBrowser = new WebInspector.ContentBrowser(document.getElementById("split-content-browser"), this, true, true);
243     this.splitContentBrowser.navigationBar.element.addEventListener("mousedown", this._consoleResizerMouseDown.bind(this));
244
245     this.quickConsole = new WebInspector.QuickConsole(document.getElementById("quick-console"));
246     this.quickConsole.addEventListener(WebInspector.QuickConsole.Event.DidResize, this._quickConsoleDidResize, this);
247
248     this._consoleRepresentedObject = new WebInspector.LogObject;
249     this._consoleTreeElement = new WebInspector.LogTreeElement(this._consoleRepresentedObject);
250     this.consoleContentView = WebInspector.splitContentBrowser.contentViewForRepresentedObject(this._consoleRepresentedObject);
251     this.consoleLogViewController = this.consoleContentView.logViewController;
252     this.breakpointPopoverController = new WebInspector.BreakpointPopoverController;
253
254     // FIXME: The sidebars should be flipped in RTL languages.
255     this.navigationSidebar = new WebInspector.Sidebar(document.getElementById("navigation-sidebar"), WebInspector.Sidebar.Sides.Left);
256     this.navigationSidebar.addEventListener(WebInspector.Sidebar.Event.WidthDidChange, this._sidebarWidthDidChange, this);
257
258     this.detailsSidebar = new WebInspector.Sidebar(document.getElementById("details-sidebar"), WebInspector.Sidebar.Sides.Right, null, null, WebInspector.UIString("Details"), true);
259     this.detailsSidebar.addEventListener(WebInspector.Sidebar.Event.WidthDidChange, this._sidebarWidthDidChange, this);
260
261     this.searchKeyboardShortcut = new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.CommandOrControl | WebInspector.KeyboardShortcut.Modifier.Shift, "F", this._focusSearchField.bind(this));
262     this._findKeyboardShortcut = new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.CommandOrControl, "F", this._find.bind(this));
263     this._saveKeyboardShortcut = new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.CommandOrControl, "S", this._save.bind(this));
264     this._saveAsKeyboardShortcut = new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.Shift | WebInspector.KeyboardShortcut.Modifier.CommandOrControl, "S", this._saveAs.bind(this));
265
266     this.openResourceKeyboardShortcut = new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.Command | WebInspector.KeyboardShortcut.Modifier.Shift, "O", this._showOpenResourceDialog.bind(this));
267     new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.Command, "P", this._showOpenResourceDialog.bind(this));
268
269     this.navigationSidebarKeyboardShortcut = new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.CommandOrControl | WebInspector.KeyboardShortcut.Modifier.Shift, "0", this.toggleNavigationSidebar.bind(this));
270     this.detailsSidebarKeyboardShortcut = new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.CommandOrControl | WebInspector.KeyboardShortcut.Modifier.Option, "0", this.toggleDetailsSidebar.bind(this));
271
272     let boundIncreaseZoom = this._increaseZoom.bind(this);
273     let boundDecreaseZoom = this._decreaseZoom.bind(this);
274     this._increaseZoomKeyboardShortcut = new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.CommandOrControl, WebInspector.KeyboardShortcut.Key.Plus, boundIncreaseZoom);
275     this._decreaseZoomKeyboardShortcut = new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.CommandOrControl, WebInspector.KeyboardShortcut.Key.Minus, boundDecreaseZoom);
276     this._increaseZoomKeyboardShortcut2 = new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.CommandOrControl | WebInspector.KeyboardShortcut.Modifier.Shift, WebInspector.KeyboardShortcut.Key.Plus, boundIncreaseZoom);
277     this._decreaseZoomKeyboardShortcut2 = new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.CommandOrControl | WebInspector.KeyboardShortcut.Modifier.Shift, WebInspector.KeyboardShortcut.Key.Minus, boundDecreaseZoom);
278     this._resetZoomKeyboardShortcut = new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.CommandOrControl, "0", this._resetZoom.bind(this));
279
280     this._showTabAtIndexKeyboardShortcuts = [1, 2, 3, 4, 5, 6, 7, 8, 9].map((i) => new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.CommandOrControl | WebInspector.KeyboardShortcut.Modifier.Option, `${i}`, this._showTabAtIndex.bind(this, i)));
281     this._openNewTabKeyboardShortcut = new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.CommandOrControl | WebInspector.KeyboardShortcut.Modifier.Option, "T", this.showNewTabTab.bind(this));
282
283     this.tabBrowser = new WebInspector.TabBrowser(document.getElementById("tab-browser"), this.tabBar, this.navigationSidebar, this.detailsSidebar);
284     this.tabBrowser.addEventListener(WebInspector.TabBrowser.Event.SelectedTabContentViewDidChange, this._tabBrowserSelectedTabContentViewDidChange, this);
285
286     this.tabBar.addEventListener(WebInspector.TabBar.Event.TabBarItemAdded, this._updateNewTabButtonState, this);
287     this.tabBar.addEventListener(WebInspector.TabBar.Event.TabBarItemRemoved, this._updateNewTabButtonState, this);
288
289     this._reloadPageKeyboardShortcut = new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.CommandOrControl, "R", this._reloadPage.bind(this));
290     this._reloadPageIgnoringCacheKeyboardShortcut = new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.CommandOrControl | WebInspector.KeyboardShortcut.Modifier.Shift, "R", this._reloadPageIgnoringCache.bind(this));
291     this._reloadPageKeyboardShortcut.implicitlyPreventsDefault = this._reloadPageIgnoringCacheKeyboardShortcut.implicitlyPreventsDefault = false;
292
293     this._consoleTabKeyboardShortcut = new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.Option | WebInspector.KeyboardShortcut.Modifier.CommandOrControl, "C", this._showConsoleTab.bind(this));
294     this._quickConsoleKeyboardShortcut = new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.Control, WebInspector.KeyboardShortcut.Key.Apostrophe, this._focusConsolePrompt.bind(this));
295
296     this._inspectModeKeyboardShortcut = new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.CommandOrControl | WebInspector.KeyboardShortcut.Modifier.Shift, "C", this._toggleInspectMode.bind(this));
297
298     this._undoKeyboardShortcut = new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.CommandOrControl, "Z", this._undoKeyboardShortcut.bind(this));
299     this._redoKeyboardShortcut = new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.CommandOrControl | WebInspector.KeyboardShortcut.Modifier.Shift, "Z", this._redoKeyboardShortcut.bind(this));
300     this._undoKeyboardShortcut.implicitlyPreventsDefault = this._redoKeyboardShortcut.implicitlyPreventsDefault = false;
301
302     this.toggleBreakpointsKeyboardShortcut = new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.CommandOrControl, "Y", this.debuggerToggleBreakpoints.bind(this));
303     this.pauseOrResumeKeyboardShortcut = new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.Control | WebInspector.KeyboardShortcut.Modifier.CommandOrControl, "Y", this.debuggerPauseResumeToggle.bind(this));
304     this.stepOverKeyboardShortcut = new WebInspector.KeyboardShortcut(null, WebInspector.KeyboardShortcut.Key.F6, this.debuggerStepOver.bind(this));
305     this.stepIntoKeyboardShortcut = new WebInspector.KeyboardShortcut(null, WebInspector.KeyboardShortcut.Key.F7, this.debuggerStepInto.bind(this));
306     this.stepOutKeyboardShortcut = new WebInspector.KeyboardShortcut(null, WebInspector.KeyboardShortcut.Key.F8, this.debuggerStepOut.bind(this));
307
308     this.pauseOrResumeAlternateKeyboardShortcut = new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.CommandOrControl, WebInspector.KeyboardShortcut.Key.Backslash, this.debuggerPauseResumeToggle.bind(this));
309     this.stepOverAlternateKeyboardShortcut = new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.CommandOrControl, WebInspector.KeyboardShortcut.Key.SingleQuote, this.debuggerStepOver.bind(this));
310     this.stepIntoAlternateKeyboardShortcut = new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.CommandOrControl, WebInspector.KeyboardShortcut.Key.Semicolon, this.debuggerStepInto.bind(this));
311     this.stepOutAlternateKeyboardShortcut = new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.Shift | WebInspector.KeyboardShortcut.Modifier.CommandOrControl, WebInspector.KeyboardShortcut.Key.Semicolon, this.debuggerStepOut.bind(this));
312
313     this._closeToolbarButton = new WebInspector.ControlToolbarItem("dock-close", WebInspector.UIString("Close"), "Images/Close.svg", 16, 14);
314     this._closeToolbarButton.addEventListener(WebInspector.ButtonNavigationItem.Event.Clicked, this.close, this);
315
316     this._undockToolbarButton = new WebInspector.ButtonToolbarItem("undock", WebInspector.UIString("Detach into separate window"), null, "Images/Undock.svg");
317     this._undockToolbarButton.addEventListener(WebInspector.ButtonNavigationItem.Event.Clicked, this._undock, this);
318
319     this._dockRightToolbarButton = new WebInspector.ButtonToolbarItem("dock-right", WebInspector.UIString("Dock to right of window"), null, "Images/DockRight.svg");
320     this._dockRightToolbarButton.addEventListener(WebInspector.ButtonNavigationItem.Event.Clicked, this._dockRight, this);
321
322     this._dockBottomToolbarButton = new WebInspector.ButtonToolbarItem("dock-bottom", WebInspector.UIString("Dock to bottom of window"), null, "Images/DockBottom.svg");
323     this._dockBottomToolbarButton.addEventListener(WebInspector.ButtonNavigationItem.Event.Clicked, this._dockBottom, this);
324
325     this._togglePreviousDockConfigurationKeyboardShortcut = new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.CommandOrControl | WebInspector.KeyboardShortcut.Modifier.Shift, "D", this._togglePreviousDockConfiguration.bind(this));
326
327     var toolTip;
328     if (WebInspector.debuggableType === WebInspector.DebuggableType.JavaScript)
329         toolTip = WebInspector.UIString("Restart (%s)").format(this._reloadPageKeyboardShortcut.displayName);
330     else
331         toolTip = WebInspector.UIString("Reload page (%s)\nReload ignoring cache (%s)").format(this._reloadPageKeyboardShortcut.displayName, this._reloadPageIgnoringCacheKeyboardShortcut.displayName);
332
333     this._reloadToolbarButton = new WebInspector.ButtonToolbarItem("reload", toolTip, null, "Images/ReloadToolbar.svg");
334     this._reloadToolbarButton.addEventListener(WebInspector.ButtonNavigationItem.Event.Clicked, this._reloadPageClicked, this);
335
336     this._downloadToolbarButton = new WebInspector.ButtonToolbarItem("download", WebInspector.UIString("Download Web Archive"), null, "Images/DownloadArrow.svg");
337     this._downloadToolbarButton.addEventListener(WebInspector.ButtonNavigationItem.Event.Clicked, this._downloadWebArchive, this);
338
339     this._updateReloadToolbarButton();
340     this._updateDownloadToolbarButton();
341
342     // The toolbar button for node inspection.
343     if (this.debuggableType === WebInspector.DebuggableType.Web) {
344         var toolTip = WebInspector.UIString("Start element selection (%s)").format(WebInspector._inspectModeKeyboardShortcut.displayName);
345         var activatedToolTip = WebInspector.UIString("Stop element selection (%s)").format(WebInspector._inspectModeKeyboardShortcut.displayName);
346         this._inspectModeToolbarButton = new WebInspector.ActivateButtonToolbarItem("inspect", toolTip, activatedToolTip, null, "Images/Crosshair.svg");
347         this._inspectModeToolbarButton.addEventListener(WebInspector.ButtonNavigationItem.Event.Clicked, this._toggleInspectMode, this);
348     }
349
350     this._dashboardContainer = new WebInspector.DashboardContainerView;
351     this._dashboardContainer.showDashboardViewForRepresentedObject(this.dashboardManager.dashboards.default);
352
353     this._searchToolbarItem = new WebInspector.SearchBar("inspector-search", WebInspector.UIString("Search"), null, true);
354     this._searchToolbarItem.addEventListener(WebInspector.SearchBar.Event.TextChanged, this._searchTextDidChange, this);
355
356     this.toolbar.addToolbarItem(this._closeToolbarButton, WebInspector.Toolbar.Section.Control);
357
358     this.toolbar.addToolbarItem(this._undockToolbarButton, WebInspector.Toolbar.Section.Left);
359     this.toolbar.addToolbarItem(this._dockRightToolbarButton, WebInspector.Toolbar.Section.Left);
360     this.toolbar.addToolbarItem(this._dockBottomToolbarButton, WebInspector.Toolbar.Section.Left);
361
362     this.toolbar.addToolbarItem(this._reloadToolbarButton, WebInspector.Toolbar.Section.CenterLeft);
363     this.toolbar.addToolbarItem(this._downloadToolbarButton, WebInspector.Toolbar.Section.CenterLeft);
364
365     this.toolbar.addToolbarItem(this._dashboardContainer.toolbarItem, WebInspector.Toolbar.Section.Center);
366
367     if (this._inspectModeToolbarButton)
368         this.toolbar.addToolbarItem(this._inspectModeToolbarButton, WebInspector.Toolbar.Section.CenterRight);
369
370     this.toolbar.addToolbarItem(this._searchToolbarItem, WebInspector.Toolbar.Section.Right);
371
372     this.resourceDetailsSidebarPanel = new WebInspector.ResourceDetailsSidebarPanel;
373     this.domNodeDetailsSidebarPanel = new WebInspector.DOMNodeDetailsSidebarPanel;
374     this.cssStyleDetailsSidebarPanel = new WebInspector.CSSStyleDetailsSidebarPanel;
375     this.applicationCacheDetailsSidebarPanel = new WebInspector.ApplicationCacheDetailsSidebarPanel;
376     this.indexedDatabaseDetailsSidebarPanel = new WebInspector.IndexedDatabaseDetailsSidebarPanel;
377     this.scopeChainDetailsSidebarPanel = new WebInspector.ScopeChainDetailsSidebarPanel;
378     this.probeDetailsSidebarPanel = new WebInspector.ProbeDetailsSidebarPanel;
379
380     if (window.LayerTreeAgent)
381         this.layerTreeDetailsSidebarPanel = new WebInspector.LayerTreeDetailsSidebarPanel;
382
383     this.modifierKeys = {altKey: false, metaKey: false, shiftKey: false};
384
385     this.toolbar.element.addEventListener("mousedown", this._toolbarMouseDown.bind(this));
386     document.getElementById("docked-resizer").addEventListener("mousedown", this._dockedResizerMouseDown.bind(this));
387
388     this._dockingAvailable = false;
389
390     this._updateDockNavigationItems();
391     this._setupViewHierarchy();
392
393     // These tabs are always available for selecting, modulo isTabAllowed().
394     // Other tabs may be engineering-only or toggled at runtime if incomplete.
395     let productionTabClasses = [
396         WebInspector.ConsoleTabContentView,
397         WebInspector.DebuggerTabContentView,
398         WebInspector.ElementsTabContentView,
399         WebInspector.NetworkTabContentView,
400         WebInspector.NewTabContentView,
401         WebInspector.ResourcesTabContentView,
402         WebInspector.SearchTabContentView,
403         WebInspector.StorageTabContentView,
404         WebInspector.TimelineTabContentView,
405     ];
406
407     this._knownTabClassesByType = new Map;
408     // Set tab classes directly. The public API triggers other updates and
409     // notifications that won't work or have no listeners at this point.
410     for (let tabClass of productionTabClasses)
411         this._knownTabClassesByType.set(tabClass.Type, tabClass);
412
413     this._pendingOpenTabs = [];
414
415     // Previously we may have stored duplicates in this setting. Avoid creating duplicate tabs.
416     let openTabTypes = this._openTabsSetting.value;
417     let seenTabTypes = new Set;
418
419     for (let i = 0; i < openTabTypes.length; ++i) {
420         let tabType = openTabTypes[i];
421
422         if (seenTabTypes.has(tabType))
423             continue;
424         seenTabTypes.add(tabType);
425
426         if (!this.isTabTypeAllowed(tabType)) {
427             this._pendingOpenTabs.push({tabType, index: i});
428             continue;
429         }
430
431         let tabContentView = this._createTabContentViewForType(tabType);
432         if (!tabContentView)
433             continue;
434         this.tabBrowser.addTabForContentView(tabContentView, true);
435     }
436
437     this._restoreCookieForOpenTabs(WebInspector.StateRestorationType.Load);
438
439     this.tabBar.selectedTabBarItem = this._selectedTabIndexSetting.value;
440
441     if (!this.tabBar.selectedTabBarItem)
442         this.tabBar.selectedTabBarItem = 0;
443
444     if (!this.tabBar.hasNormalTab())
445         this.showNewTabTab();
446
447     // Listen to the events after restoring the saved tabs to avoid recursion.
448     this.tabBar.addEventListener(WebInspector.TabBar.Event.TabBarItemAdded, this._rememberOpenTabs, this);
449     this.tabBar.addEventListener(WebInspector.TabBar.Event.TabBarItemRemoved, this._rememberOpenTabs, this);
450     this.tabBar.addEventListener(WebInspector.TabBar.Event.TabBarItemsReordered, this._rememberOpenTabs, this);
451
452     // Signal that the frontend is now ready to receive messages.
453     InspectorFrontendAPI.loadCompleted();
454
455     // Tell the InspectorFrontendHost we loaded, which causes the window to display
456     // and pending InspectorFrontendAPI commands to be sent.
457     InspectorFrontendHost.loaded();
458
459     this._updateSplitConsoleHeight(this._splitConsoleHeightSetting.value);
460
461     if (this._showingSplitConsoleSetting.value)
462         this.showSplitConsole();
463
464     // Store this on the window in case the WebInspector global gets corrupted.
465     window.__frontendCompletedLoad = true;
466
467     if (this.runBootstrapOperations)
468         this.runBootstrapOperations();
469 };
470
471 WebInspector.isTabTypeAllowed = function(tabType)
472 {
473     let tabClass = this._knownTabClassesByType.get(tabType);
474     if (!tabClass)
475         return false;
476
477     return tabClass.isTabAllowed();
478 };
479
480 WebInspector.knownTabClasses = function()
481 {
482     return new Set(this._knownTabClassesByType.values());
483 };
484
485 WebInspector._showOpenResourceDialog = function()
486 {
487     if (!this._openResourceDialog)
488         this._openResourceDialog = new WebInspector.OpenResourceDialog(this);
489
490     if (this._openResourceDialog.visible)
491         return;
492
493     this._openResourceDialog.present(this._contentElement);
494 };
495
496 WebInspector._createTabContentViewForType = function(tabType)
497 {
498     let tabClass = this._knownTabClassesByType.get(tabType);
499     if (!tabClass) {
500         console.error("Unknown tab type", tabType);
501         return null;
502     }
503
504     console.assert(WebInspector.TabContentView.isPrototypeOf(tabClass));
505     return new tabClass;
506 };
507
508 WebInspector._rememberOpenTabs = function()
509 {
510     let seenTabTypes = new Set;
511     let openTabs = [];
512
513     for (let tabBarItem of this.tabBar.tabBarItems) {
514         let tabContentView = tabBarItem.representedObject;
515         if (!(tabContentView instanceof WebInspector.TabContentView))
516             continue;
517         if (!tabContentView.constructor.shouldSaveTab())
518             continue;
519         console.assert(tabContentView.type, "Tab type can't be null, undefined, or empty string", tabContentView.type, tabContentView);
520         openTabs.push(tabContentView.type);
521         seenTabTypes.add(tabContentView.type);
522     }
523
524     // Keep currently unsupported tabs in the setting at their previous index.
525     for (let {tabType, index} of this._pendingOpenTabs) {
526         if (seenTabTypes.has(tabType))
527             continue;
528         openTabs.insertAtIndex(tabType, index);
529         seenTabTypes.add(tabType);
530     }
531
532     this._openTabsSetting.value = openTabs;
533 };
534
535 WebInspector._updateNewTabButtonState = function(event)
536 {
537     this.tabBar.newTabItem.disabled = !this.isNewTabWithTypeAllowed(WebInspector.NewTabContentView.Type);
538 };
539
540 WebInspector._newTabItemClicked = function(event)
541 {
542     const shouldAnimate = true;
543     this.showNewTabTab(shouldAnimate);
544 };
545
546 WebInspector._openDefaultTab = function(event)
547 {
548     this.showNewTabTab();
549 };
550
551 WebInspector._tryToRestorePendingTabs = function()
552 {
553     let stillPendingOpenTabs = [];
554     for (let {tabType, index} of this._pendingOpenTabs) {
555         if (!this.isTabTypeAllowed(tabType)) {
556             stillPendingOpenTabs.push({tabType, index});
557             continue;
558         }
559
560         let tabContentView = this._createTabContentViewForType(tabType);
561         if (!tabContentView)
562             continue;
563
564         this.tabBrowser.addTabForContentView(tabContentView, true, index);
565
566         tabContentView.restoreStateFromCookie(WebInspector.StateRestorationType.Load);
567     }
568
569     this._pendingOpenTabs = stillPendingOpenTabs;
570
571     this._updateNewTabButtonState();
572 };
573
574 WebInspector.showNewTabTab = function(shouldAnimate)
575 {
576     if (!this.isNewTabWithTypeAllowed(WebInspector.NewTabContentView.Type))
577         return;
578
579     let tabContentView = this.tabBrowser.bestTabContentViewForClass(WebInspector.NewTabContentView);
580     if (!tabContentView)
581         tabContentView = new WebInspector.NewTabContentView;
582     this.tabBrowser.showTabForContentView(tabContentView, !shouldAnimate);
583 };
584
585 WebInspector.isNewTabWithTypeAllowed = function(tabType)
586 {
587     let tabClass = this._knownTabClassesByType.get(tabType);
588     if (!tabClass || !tabClass.isTabAllowed())
589         return false;
590
591     // Only allow one tab per class for now.
592     for (let tabBarItem of this.tabBar.tabBarItems) {
593         let tabContentView = tabBarItem.representedObject;
594         if (!(tabContentView instanceof WebInspector.TabContentView))
595             continue;
596         if (tabContentView.constructor === tabClass)
597             return false;
598     }
599
600     if (tabClass === WebInspector.NewTabContentView) {
601         let allTabs = Array.from(this.knownTabClasses());
602         let addableTabs = allTabs.filter((tabClass) => !tabClass.isEphemeral());
603         let canMakeNewTab = addableTabs.some((tabClass) => WebInspector.isNewTabWithTypeAllowed(tabClass.Type));
604         return canMakeNewTab;
605     }
606
607     return true;
608 };
609
610 WebInspector.createNewTabWithType = function(tabType, options = {})
611 {
612     console.assert(this.isNewTabWithTypeAllowed(tabType));
613
614     let {referencedView, shouldReplaceTab, shouldShowNewTab} = options;
615     console.assert(!referencedView || referencedView instanceof WebInspector.TabContentView, referencedView);
616     console.assert(!shouldReplaceTab || referencedView, "Must provide a reference view to replace a tab.");
617
618     let tabContentView = this._createTabContentViewForType(tabType);
619     const suppressAnimations = true;
620     let insertionIndex = referencedView ? this.tabBar.tabBarItems.indexOf(referencedView.tabBarItem) : undefined;
621     this.tabBrowser.addTabForContentView(tabContentView, suppressAnimations, insertionIndex);
622
623     if (shouldReplaceTab)
624         this.tabBrowser.closeTabForContentView(referencedView, suppressAnimations);
625
626     if (shouldShowNewTab)
627         this.tabBrowser.showTabForContentView(tabContentView);
628 };
629
630 WebInspector.registerTabClass = function(tabClass)
631 {
632     console.assert(WebInspector.TabContentView.isPrototypeOf(tabClass));
633     if (!WebInspector.TabContentView.isPrototypeOf(tabClass))
634         return;
635
636     if (this._knownTabClassesByType.has(tabClass.Type))
637         return;
638
639     this._knownTabClassesByType.set(tabClass.Type, tabClass);
640
641     this._tryToRestorePendingTabs();
642     this.notifications.dispatchEventToListeners(WebInspector.Notification.TabTypesChanged);
643 };
644
645 WebInspector.activateExtraDomains = function(domains)
646 {
647     this.hasExtraDomains = true;
648
649     for (var domain of domains) {
650         var agent = InspectorBackend.activateDomain(domain);
651         if (agent.enable)
652             agent.enable();
653     }
654
655     this.notifications.dispatchEventToListeners(WebInspector.Notification.ExtraDomainsActivated, {"domains": domains});
656
657     WebInspector.CSSCompletions.requestCSSCompletions();
658
659     this._updateReloadToolbarButton();
660     this._updateDownloadToolbarButton();
661     this._tryToRestorePendingTabs();
662 };
663
664 WebInspector.contentBrowserTreeElementForRepresentedObject = function(contentBrowser, representedObject)
665 {
666     // The console does not have a sidebar, so return a tree element here so something is shown.
667     if (representedObject === this._consoleRepresentedObject)
668         return this._consoleTreeElement;
669     return null;
670 };
671
672 WebInspector.updateWindowTitle = function()
673 {
674     var mainFrame = this.frameResourceManager.mainFrame;
675     console.assert(mainFrame);
676
677     var urlComponents = mainFrame.mainResource.urlComponents;
678
679     var lastPathComponent;
680     try {
681         lastPathComponent = decodeURIComponent(urlComponents.lastPathComponent || "");
682     } catch (e) {
683         lastPathComponent = urlComponents.lastPathComponent;
684     }
685
686     // Build a title based on the URL components.
687     if (urlComponents.host && lastPathComponent)
688         var title = this.displayNameForHost(urlComponents.host) + " \u2014 " + lastPathComponent;
689     else if (urlComponents.host)
690         var title = this.displayNameForHost(urlComponents.host);
691     else if (lastPathComponent)
692         var title = lastPathComponent;
693     else
694         var title = mainFrame.url;
695
696     // The name "inspectedURLChanged" sounds like the whole URL is required, however this is only
697     // used for updating the window title and it can be any string.
698     InspectorFrontendHost.inspectedURLChanged(title);
699 };
700
701 WebInspector.updateDockingAvailability = function(available)
702 {
703     this._dockingAvailable = available;
704
705     this._updateDockNavigationItems();
706 };
707
708 WebInspector.updateDockedState = function(side)
709 {
710     if (this._dockConfiguration === side)
711         return;
712
713     this._previousDockConfiguration = this._dockConfiguration;
714     if (!this._previousDockConfiguration) {
715         if (side === WebInspector.DockConfiguration.Right)
716             this._previousDockConfiguration = WebInspector.DockConfiguration.Bottom;
717         else
718             this._previousDockConfiguration = WebInspector.DockConfiguration.Right;
719     }
720
721     this._dockConfiguration = side;
722
723     this.docked = side !== WebInspector.DockConfiguration.Undocked;
724
725     this._ignoreToolbarModeDidChangeEvents = true;
726
727     if (side === WebInspector.DockConfiguration.Bottom) {
728         document.body.classList.add("docked", WebInspector.DockConfiguration.Bottom);
729         document.body.classList.remove("window-inactive", WebInspector.DockConfiguration.Right);
730     } else if (side === WebInspector.DockConfiguration.Right) {
731         document.body.classList.add("docked", WebInspector.DockConfiguration.Right);
732         document.body.classList.remove("window-inactive", WebInspector.DockConfiguration.Bottom);
733     } else
734         document.body.classList.remove("docked", WebInspector.DockConfiguration.Right, WebInspector.DockConfiguration.Bottom);
735
736     this._ignoreToolbarModeDidChangeEvents = false;
737
738     this._updateDockNavigationItems();
739 };
740
741 WebInspector.updateVisibilityState = function(visible)
742 {
743     this.visible = visible;
744     this.notifications.dispatchEventToListeners(WebInspector.Notification.VisibilityStateDidChange);
745 };
746
747 WebInspector.handlePossibleLinkClick = function(event, frame, alwaysOpenExternally)
748 {
749     var anchorElement = event.target.enclosingNodeOrSelfWithNodeName("a");
750     if (!anchorElement || !anchorElement.href)
751         return false;
752
753     if (WebInspector.isBeingEdited(anchorElement)) {
754         // Don't follow the link when it is being edited.
755         return false;
756     }
757
758     // Prevent the link from navigating, since we don't do any navigation by following links normally.
759     event.preventDefault();
760     event.stopPropagation();
761
762     this.openURL(anchorElement.href, frame, false, anchorElement.lineNumber);
763
764     return true;
765 };
766
767 WebInspector.openURL = function(url, frame, alwaysOpenExternally, lineNumber)
768 {
769     console.assert(url);
770     if (!url)
771         return;
772
773     console.assert(typeof lineNumber === "undefined" || typeof lineNumber === "number", "lineNumber should be a number.");
774
775     // If alwaysOpenExternally is not defined, base it off the command/meta key for the current event.
776     if (alwaysOpenExternally === undefined || alwaysOpenExternally === null)
777         alwaysOpenExternally = window.event ? window.event.metaKey : false;
778
779     if (alwaysOpenExternally) {
780         InspectorFrontendHost.openInNewTab(url);
781         return;
782     }
783
784     var searchChildFrames = false;
785     if (!frame) {
786         frame = this.frameResourceManager.mainFrame;
787         searchChildFrames = true;
788     }
789
790     console.assert(frame);
791
792     // WebInspector.Frame.resourceForURL does not check the main resource, only sub-resources. So check both.
793     let simplifiedURL = removeURLFragment(url);
794     var resource = frame.url === simplifiedURL ? frame.mainResource : frame.resourceForURL(simplifiedURL, searchChildFrames);
795     if (resource) {
796         var position = new WebInspector.SourceCodePosition(lineNumber, 0);
797         this.showSourceCode(resource, position);
798         return;
799     }
800
801     InspectorFrontendHost.openInNewTab(url);
802 };
803
804 WebInspector.close = function()
805 {
806     if (this._isClosing)
807         return;
808
809     this._isClosing = true;
810
811     InspectorFrontendHost.closeWindow();
812 };
813
814 WebInspector.saveDataToFile = function(saveData, forceSaveAs)
815 {
816     console.assert(saveData);
817     if (!saveData)
818         return;
819
820     if (typeof saveData.customSaveHandler === "function") {
821         saveData.customSaveHandler(forceSaveAs);
822         return;
823     }
824
825     console.assert(saveData.url);
826     console.assert(saveData.content);
827     if (!saveData.url || !saveData.content)
828         return;
829
830     let suggestedName = parseURL(saveData.url).lastPathComponent;
831     if (!suggestedName) {
832         suggestedName = WebInspector.UIString("Untitled");
833         let dataURLTypeMatch = /^data:([^;]+)/.exec(saveData.url);
834         if (dataURLTypeMatch)
835             suggestedName += WebInspector.fileExtensionForMIMEType(dataURLTypeMatch[1]) || "";
836     }
837
838     if (typeof saveData.content === "string") {
839         const base64Encoded = false;
840         InspectorFrontendHost.save(suggestedName, saveData.content, base64Encoded, forceSaveAs || saveData.forceSaveAs);
841         return;
842     }
843
844     let fileReader = new FileReader;
845     fileReader.readAsDataURL(saveData.content);
846     fileReader.addEventListener("loadend", () => {
847         let dataURLComponents = parseDataURL(fileReader.result);
848
849         const base64Encoded = true;
850         InspectorFrontendHost.save(suggestedName, dataURLComponents.data, base64Encoded, forceSaveAs || saveData.forceSaveAs);
851     });
852 };
853
854 WebInspector.isConsoleFocused = function()
855 {
856     return this.quickConsole.prompt.focused;
857 };
858
859 WebInspector.isShowingSplitConsole = function()
860 {
861     return !this.splitContentBrowser.element.classList.contains("hidden");
862 };
863
864 WebInspector.doesCurrentTabSupportSplitContentBrowser = function()
865 {
866     var currentContentView = this.tabBrowser.selectedTabContentView;
867     return !currentContentView || currentContentView.supportsSplitContentBrowser;
868 };
869
870 WebInspector.toggleSplitConsole = function()
871 {
872     if (!this.doesCurrentTabSupportSplitContentBrowser()) {
873         this.showConsoleTab();
874         return;
875     }
876
877     if (this.isShowingSplitConsole())
878         this.hideSplitConsole();
879     else
880         this.showSplitConsole();
881 };
882
883 WebInspector.showSplitConsole = function()
884 {
885     if (!this.doesCurrentTabSupportSplitContentBrowser()) {
886         this.showConsoleTab();
887         return;
888     }
889
890     this.splitContentBrowser.element.classList.remove("hidden");
891
892     this._showingSplitConsoleSetting.value = true;
893
894     if (this.splitContentBrowser.currentContentView !== this.consoleContentView) {
895         // Be sure to close the view in the tab content browser before showing it in the
896         // split content browser. We can only show a content view in one browser at a time.
897         if (this.consoleContentView.parentContainer)
898             this.consoleContentView.parentContainer.closeContentView(this.consoleContentView);
899         this.splitContentBrowser.showContentView(this.consoleContentView);
900     } else {
901         // This causes the view to know it was shown and focus the prompt.
902         this.splitContentBrowser.shown();
903     }
904
905     this.quickConsole.consoleLogVisibilityChanged(true);
906 };
907
908 WebInspector.hideSplitConsole = function()
909 {
910     if (!this.isShowingSplitConsole())
911         return;
912
913     this.splitContentBrowser.element.classList.add("hidden");
914
915     this._showingSplitConsoleSetting.value = false;
916
917     // This causes the view to know it was hidden.
918     this.splitContentBrowser.hidden();
919
920     this.quickConsole.consoleLogVisibilityChanged(false);
921 };
922
923 WebInspector.showConsoleTab = function(requestedScope)
924 {
925     this.hideSplitConsole();
926
927     var scope = requestedScope || WebInspector.LogContentView.Scopes.All;
928
929     // If the requested scope is already selected and the console is showing, then switch back to All.
930     if (this.isShowingConsoleTab() && this.consoleContentView.scopeBar.item(scope).selected)
931         scope = WebInspector.LogContentView.Scopes.All;
932
933     if (requestedScope || !this.consoleContentView.scopeBar.selectedItems.length)
934         this.consoleContentView.scopeBar.item(scope).selected = true;
935
936     this.showRepresentedObject(this._consoleRepresentedObject);
937
938     console.assert(this.isShowingConsoleTab());
939 };
940
941 WebInspector.isShowingConsoleTab = function()
942 {
943     return this.tabBrowser.selectedTabContentView instanceof WebInspector.ConsoleTabContentView;
944 };
945
946 WebInspector.showElementsTab = function()
947 {
948     var tabContentView = this.tabBrowser.bestTabContentViewForClass(WebInspector.ElementsTabContentView);
949     if (!tabContentView)
950         tabContentView = new WebInspector.ElementsTabContentView;
951     this.tabBrowser.showTabForContentView(tabContentView);
952 };
953
954 WebInspector.showDebuggerTab = function(breakpointToSelect)
955 {
956     var tabContentView = this.tabBrowser.bestTabContentViewForClass(WebInspector.DebuggerTabContentView);
957     if (!tabContentView)
958         tabContentView = new WebInspector.DebuggerTabContentView;
959
960     if (breakpointToSelect instanceof WebInspector.Breakpoint)
961         tabContentView.revealAndSelectBreakpoint(breakpointToSelect);
962
963     this.tabBrowser.showTabForContentView(tabContentView);
964 };
965
966 WebInspector.isShowingDebuggerTab = function()
967 {
968     return this.tabBrowser.selectedTabContentView instanceof WebInspector.DebuggerTabContentView;
969 };
970
971 WebInspector.showResourcesTab = function()
972 {
973     var tabContentView = this.tabBrowser.bestTabContentViewForClass(WebInspector.ResourcesTabContentView);
974     if (!tabContentView)
975         tabContentView = new WebInspector.ResourcesTabContentView;
976     this.tabBrowser.showTabForContentView(tabContentView);
977 };
978
979 WebInspector.showStorageTab = function()
980 {
981     var tabContentView = this.tabBrowser.bestTabContentViewForClass(WebInspector.StorageTabContentView);
982     if (!tabContentView)
983         tabContentView = new WebInspector.StorageTabContentView;
984     this.tabBrowser.showTabForContentView(tabContentView);
985 };
986
987 WebInspector.showNetworkTab = function()
988 {
989     var tabContentView = this.tabBrowser.bestTabContentViewForClass(WebInspector.NetworkTabContentView);
990     if (!tabContentView)
991         tabContentView = new WebInspector.NetworkTabContentView;
992     this.tabBrowser.showTabForContentView(tabContentView);
993 };
994
995 WebInspector.showTimelineTab = function()
996 {
997     var tabContentView = this.tabBrowser.bestTabContentViewForClass(WebInspector.TimelineTabContentView);
998     if (!tabContentView)
999         tabContentView = new WebInspector.TimelineTabContentView;
1000     this.tabBrowser.showTabForContentView(tabContentView);
1001 };
1002
1003 WebInspector.unlocalizedString = function(string)
1004 {
1005     // Intentionally do nothing, since this is for engineering builds
1006     // (such as in Debug UI) or in text that is standardized in English.
1007     // For example, CSS property names and values are never localized.
1008     return string;
1009 };
1010
1011 WebInspector.UIString = function(string, vararg)
1012 {
1013     if (WebInspector.dontLocalizeUserInterface)
1014         return string;
1015
1016     if (window.localizedStrings && string in window.localizedStrings)
1017         return window.localizedStrings[string];
1018
1019     if (!this._missingLocalizedStrings)
1020         this._missingLocalizedStrings = {};
1021
1022     if (!(string in this._missingLocalizedStrings)) {
1023         console.error("Localized string \"" + string + "\" was not found.");
1024         this._missingLocalizedStrings[string] = true;
1025     }
1026
1027     return "LOCALIZED STRING NOT FOUND";
1028 };
1029
1030 WebInspector.restoreFocusFromElement = function(element)
1031 {
1032     if (element && element.isSelfOrAncestor(this.currentFocusElement))
1033         this.previousFocusElement.focus();
1034 };
1035
1036 WebInspector.toggleNavigationSidebar = function(event)
1037 {
1038     if (!this.navigationSidebar.collapsed || !this.navigationSidebar.sidebarPanels.length) {
1039         this.navigationSidebar.collapsed = true;
1040         return;
1041     }
1042
1043     if (!this.navigationSidebar.selectedSidebarPanel)
1044         this.navigationSidebar.selectedSidebarPanel = this.navigationSidebar.sidebarPanels[0];
1045     this.navigationSidebar.collapsed = false;
1046 };
1047
1048 WebInspector.toggleDetailsSidebar = function(event)
1049 {
1050     if (!this.detailsSidebar.collapsed || !this.detailsSidebar.sidebarPanels.length) {
1051         this.detailsSidebar.collapsed = true;
1052         return;
1053     }
1054
1055     if (!this.detailsSidebar.selectedSidebarPanel)
1056         this.detailsSidebar.selectedSidebarPanel = this.detailsSidebar.sidebarPanels[0];
1057     this.detailsSidebar.collapsed = false;
1058 };
1059
1060 WebInspector.tabContentViewClassForRepresentedObject = function(representedObject)
1061 {
1062     if (representedObject instanceof WebInspector.DOMTree)
1063         return WebInspector.ElementsTabContentView;
1064
1065     if (representedObject instanceof WebInspector.TimelineRecording)
1066         return WebInspector.TimelineTabContentView;
1067
1068     // We only support one console tab right now. So this isn't an instanceof check.
1069     if (representedObject === this._consoleRepresentedObject)
1070         return WebInspector.ConsoleTabContentView;
1071
1072     if (WebInspector.debuggerManager.paused) {
1073         if (representedObject instanceof WebInspector.Script)
1074             return WebInspector.DebuggerTabContentView;
1075
1076         if (representedObject instanceof WebInspector.Resource && (representedObject.type === WebInspector.Resource.Type.Document || representedObject.type === WebInspector.Resource.Type.Script))
1077             return WebInspector.DebuggerTabContentView;
1078     }
1079
1080     if (representedObject instanceof WebInspector.Frame || representedObject instanceof WebInspector.Resource || representedObject instanceof WebInspector.Script)
1081         return WebInspector.ResourcesTabContentView;
1082
1083     // FIXME: Move Content Flows to the Elements tab?
1084     if (representedObject instanceof WebInspector.ContentFlow)
1085         return WebInspector.ResourcesTabContentView;
1086
1087     // FIXME: Move these to a Storage tab.
1088     if (representedObject instanceof WebInspector.DOMStorageObject || representedObject instanceof WebInspector.CookieStorageObject ||
1089         representedObject instanceof WebInspector.DatabaseTableObject || representedObject instanceof WebInspector.DatabaseObject ||
1090         representedObject instanceof WebInspector.ApplicationCacheFrame || representedObject instanceof WebInspector.IndexedDatabaseObjectStore ||
1091         representedObject instanceof WebInspector.IndexedDatabaseObjectStoreIndex)
1092         return WebInspector.ResourcesTabContentView;
1093
1094     return null;
1095 };
1096
1097 WebInspector.tabContentViewForRepresentedObject = function(representedObject)
1098 {
1099     var tabContentView = this.tabBrowser.bestTabContentViewForRepresentedObject(representedObject);
1100     if (tabContentView)
1101         return tabContentView;
1102
1103     var tabContentViewClass = this.tabContentViewClassForRepresentedObject(representedObject);
1104     if (!tabContentViewClass) {
1105         console.error("Unknown representedObject, couldn't create TabContentView.", representedObject);
1106         return null;
1107     }
1108
1109     tabContentView = new tabContentViewClass;
1110
1111     this.tabBrowser.addTabForContentView(tabContentView);
1112
1113     return tabContentView;
1114 };
1115
1116 WebInspector.showRepresentedObject = function(representedObject, cookie)
1117 {
1118     var tabContentView = this.tabContentViewForRepresentedObject(representedObject);
1119     console.assert(tabContentView);
1120     if (!tabContentView)
1121         return;
1122
1123     this.tabBrowser.showTabForContentView(tabContentView);
1124     tabContentView.showRepresentedObject(representedObject, cookie);
1125 };
1126
1127 WebInspector.showMainFrameDOMTree = function(nodeToSelect)
1128 {
1129     console.assert(WebInspector.frameResourceManager.mainFrame);
1130     if (!WebInspector.frameResourceManager.mainFrame)
1131         return;
1132     this.showRepresentedObject(WebInspector.frameResourceManager.mainFrame.domTree, {nodeToSelect});
1133 };
1134
1135 WebInspector.showContentFlowDOMTree = function(contentFlow, nodeToSelect)
1136 {
1137     this.showRepresentedObject(contentFlow, {nodeToSelect});
1138 };
1139
1140 WebInspector.showSourceCodeForFrame = function(frameIdentifier)
1141 {
1142     var frame = WebInspector.frameResourceManager.frameForIdentifier(frameIdentifier);
1143     if (!frame) {
1144         this._frameIdentifierToShowSourceCodeWhenAvailable = frameIdentifier;
1145         return;
1146     }
1147
1148     this._frameIdentifierToShowSourceCodeWhenAvailable = undefined;
1149
1150     this.showRepresentedObject(frame);
1151 };
1152
1153 WebInspector.showSourceCode = function(sourceCode, positionToReveal, textRangeToSelect, forceUnformatted)
1154 {
1155     console.assert(!positionToReveal || positionToReveal instanceof WebInspector.SourceCodePosition, positionToReveal);
1156     var representedObject = sourceCode;
1157
1158     if (representedObject instanceof WebInspector.Script) {
1159         // A script represented by a resource should always show the resource.
1160         representedObject = representedObject.resource || representedObject;
1161     }
1162
1163     var cookie = positionToReveal ? {lineNumber: positionToReveal.lineNumber, columnNumber: positionToReveal.columnNumber} : {};
1164     this.showRepresentedObject(representedObject, cookie);
1165 };
1166
1167 WebInspector.showSourceCodeLocation = function(sourceCodeLocation)
1168 {
1169     this.showSourceCode(sourceCodeLocation.displaySourceCode, sourceCodeLocation.displayPosition());
1170 };
1171
1172 WebInspector.showOriginalUnformattedSourceCodeLocation = function(sourceCodeLocation)
1173 {
1174     this.showSourceCode(sourceCodeLocation.sourceCode, sourceCodeLocation.position(), null, true);
1175 };
1176
1177 WebInspector.showOriginalOrFormattedSourceCodeLocation = function(sourceCodeLocation)
1178 {
1179     this.showSourceCode(sourceCodeLocation.sourceCode, sourceCodeLocation.formattedPosition());
1180 };
1181
1182 WebInspector.showOriginalOrFormattedSourceCodeTextRange = function(sourceCodeTextRange)
1183 {
1184     var textRangeToSelect = sourceCodeTextRange.formattedTextRange;
1185     this.showSourceCode(sourceCodeTextRange.sourceCode, textRangeToSelect.startPosition(), textRangeToSelect);
1186 };
1187
1188 WebInspector.showResourceRequest = function(resource)
1189 {
1190     this.showRepresentedObject(resource, {[WebInspector.ResourceClusterContentView.ContentViewIdentifierCookieKey]: WebInspector.ResourceClusterContentView.RequestIdentifier});
1191 };
1192
1193 WebInspector.debuggerToggleBreakpoints = function(event)
1194 {
1195     WebInspector.debuggerManager.breakpointsEnabled = !WebInspector.debuggerManager.breakpointsEnabled;
1196 };
1197
1198 WebInspector.debuggerPauseResumeToggle = function(event)
1199 {
1200     if (WebInspector.debuggerManager.paused)
1201         WebInspector.debuggerManager.resume();
1202     else
1203         WebInspector.debuggerManager.pause();
1204 };
1205
1206 WebInspector.debuggerStepOver = function(event)
1207 {
1208     WebInspector.debuggerManager.stepOver();
1209 };
1210
1211 WebInspector.debuggerStepInto = function(event)
1212 {
1213     WebInspector.debuggerManager.stepInto();
1214 };
1215
1216 WebInspector.debuggerStepOut = function(event)
1217 {
1218     WebInspector.debuggerManager.stepOut();
1219 };
1220
1221 WebInspector._searchTextDidChange = function(event)
1222 {
1223     var tabContentView = this.tabBrowser.bestTabContentViewForClass(WebInspector.SearchTabContentView);
1224     if (!tabContentView)
1225         tabContentView = new WebInspector.SearchTabContentView;
1226
1227     var searchQuery = this._searchToolbarItem.text;
1228     this._searchToolbarItem.text = "";
1229
1230     this.tabBrowser.showTabForContentView(tabContentView);
1231
1232     tabContentView.performSearch(searchQuery);
1233 };
1234
1235 WebInspector._focusSearchField = function(event)
1236 {
1237     if (this.tabBrowser.selectedTabContentView instanceof WebInspector.SearchTabContentView) {
1238         this.tabBrowser.selectedTabContentView.focusSearchField();
1239         return;
1240     }
1241
1242     this._searchToolbarItem.focus();
1243 };
1244
1245 WebInspector._focusChanged = function(event)
1246 {
1247     // Make a caret selection inside the focused element if there isn't a range selection and there isn't already
1248     // a caret selection inside. This is needed (at least) to remove caret from console when focus is moved.
1249     // The selection change should not apply to text fields and text areas either.
1250
1251     if (WebInspector.isEventTargetAnEditableField(event)) {
1252         // Still update the currentFocusElement if inside of a CodeMirror editor.
1253         var codeMirrorEditorElement = event.target.enclosingNodeOrSelfWithClass("CodeMirror");
1254         if (codeMirrorEditorElement && codeMirrorEditorElement !== this.currentFocusElement) {
1255             this.previousFocusElement = this.currentFocusElement;
1256             this.currentFocusElement = codeMirrorEditorElement;
1257         }
1258         return;
1259     }
1260
1261     var selection = window.getSelection();
1262     if (!selection.isCollapsed)
1263         return;
1264
1265     var element = event.target;
1266
1267     if (element !== this.currentFocusElement) {
1268         this.previousFocusElement = this.currentFocusElement;
1269         this.currentFocusElement = element;
1270     }
1271
1272     if (element.isInsertionCaretInside())
1273         return;
1274
1275     var selectionRange = element.ownerDocument.createRange();
1276     selectionRange.setStart(element, 0);
1277     selectionRange.setEnd(element, 0);
1278
1279     selection.removeAllRanges();
1280     selection.addRange(selectionRange);
1281 };
1282
1283 WebInspector._mouseWasClicked = function(event)
1284 {
1285     this.handlePossibleLinkClick(event);
1286 };
1287
1288 WebInspector._dragOver = function(event)
1289 {
1290     // Do nothing if another event listener handled the event already.
1291     if (event.defaultPrevented)
1292         return;
1293
1294     // Allow dropping into editable areas.
1295     if (WebInspector.isEventTargetAnEditableField(event))
1296         return;
1297
1298     // Prevent the drop from being accepted.
1299     event.dataTransfer.dropEffect = "none";
1300     event.preventDefault();
1301 };
1302
1303 WebInspector._captureDidStart = function(event)
1304 {
1305     this._dashboardContainer.showDashboardViewForRepresentedObject(this.dashboardManager.dashboards.replay);
1306 };
1307
1308 WebInspector._debuggerDidPause = function(event)
1309 {
1310     // FIXME: <webkit.org/b/###> Web Inspector: Preference for Auto Showing Scope Chain sidebar on pause
1311     this.showDebuggerTab();
1312
1313     this._dashboardContainer.showDashboardViewForRepresentedObject(this.dashboardManager.dashboards.debugger);
1314
1315     InspectorFrontendHost.bringToFront();
1316 };
1317
1318 WebInspector._debuggerDidResume = function(event)
1319 {
1320     this._dashboardContainer.closeDashboardViewForRepresentedObject(this.dashboardManager.dashboards.debugger);
1321 };
1322
1323 WebInspector._frameWasAdded = function(event)
1324 {
1325     if (!this._frameIdentifierToShowSourceCodeWhenAvailable)
1326         return;
1327
1328     var frame = event.data.frame;
1329     if (frame.id !== this._frameIdentifierToShowSourceCodeWhenAvailable)
1330         return;
1331
1332     function delayedWork()
1333     {
1334         this.showSourceCodeForFrame(frame.id);
1335     }
1336
1337     // Delay showing the frame since FrameWasAdded is called before MainFrameChanged.
1338     // Calling showSourceCodeForFrame before MainFrameChanged will show the frame then close it.
1339     setTimeout(delayedWork.bind(this));
1340 };
1341
1342 WebInspector._mainFrameDidChange = function(event)
1343 {
1344     this._updateDownloadToolbarButton();
1345
1346     this.updateWindowTitle();
1347 };
1348
1349 WebInspector._mainResourceDidChange = function(event)
1350 {
1351     if (!event.target.isMainFrame())
1352         return;
1353
1354     this._inProvisionalLoad = false;
1355
1356     // Run cookie restoration after we are sure all of the Tabs and NavigationSidebarPanels
1357     // have updated with respect to the main resource change.
1358     setTimeout(this._restoreCookieForOpenTabs.bind(this, WebInspector.StateRestorationType.Navigation));
1359
1360     this._updateDownloadToolbarButton();
1361
1362     this.updateWindowTitle();
1363 };
1364
1365 WebInspector._provisionalLoadStarted = function(event)
1366 {
1367     if (!event.target.isMainFrame())
1368         return;
1369
1370     this._saveCookieForOpenTabs();
1371
1372     this._inProvisionalLoad = true;
1373 };
1374
1375 WebInspector._restoreCookieForOpenTabs = function(restorationType)
1376 {
1377     for (var tabBarItem of this.tabBar.tabBarItems) {
1378         var tabContentView = tabBarItem.representedObject;
1379         if (!(tabContentView instanceof WebInspector.TabContentView))
1380             continue;
1381         tabContentView.restoreStateFromCookie(restorationType);
1382     }
1383 };
1384
1385 WebInspector._saveCookieForOpenTabs = function()
1386 {
1387     for (var tabBarItem of this.tabBar.tabBarItems) {
1388         var tabContentView = tabBarItem.representedObject;
1389         if (!(tabContentView instanceof WebInspector.TabContentView))
1390             continue;
1391         tabContentView.saveStateToCookie();
1392     }
1393 };
1394
1395 WebInspector._windowFocused = function(event)
1396 {
1397     if (event.target.document.nodeType !== Node.DOCUMENT_NODE)
1398         return;
1399
1400     // FIXME: We should use the :window-inactive pseudo class once https://webkit.org/b/38927 is fixed.
1401     document.body.classList.remove(this.docked ? "window-docked-inactive" : "window-inactive");
1402 };
1403
1404 WebInspector._windowBlurred = function(event)
1405 {
1406     if (event.target.document.nodeType !== Node.DOCUMENT_NODE)
1407         return;
1408
1409     // FIXME: We should use the :window-inactive pseudo class once https://webkit.org/b/38927 is fixed.
1410     document.body.classList.add(this.docked ? "window-docked-inactive" : "window-inactive");
1411 };
1412
1413 WebInspector._windowResized = function(event)
1414 {
1415     this.toolbar.updateLayout(WebInspector.View.LayoutReason.Resize);
1416     this.tabBar.updateLayout(WebInspector.View.LayoutReason.Resize);
1417     this._tabBrowserSizeDidChange();
1418 };
1419
1420 WebInspector._updateModifierKeys = function(event)
1421 {
1422     var didChange = this.modifierKeys.altKey !== event.altKey || this.modifierKeys.metaKey !== event.metaKey || this.modifierKeys.shiftKey !== event.shiftKey;
1423
1424     this.modifierKeys = {altKey: event.altKey, metaKey: event.metaKey, shiftKey: event.shiftKey};
1425
1426     if (didChange)
1427         this.notifications.dispatchEventToListeners(WebInspector.Notification.GlobalModifierKeysDidChange, event);
1428 };
1429
1430 WebInspector._windowKeyDown = function(event)
1431 {
1432     this._updateModifierKeys(event);
1433 };
1434
1435 WebInspector._windowKeyUp = function(event)
1436 {
1437     this._updateModifierKeys(event);
1438 };
1439
1440 WebInspector._mouseMoved = function(event)
1441 {
1442     this._updateModifierKeys(event);
1443     this.mouseCoords = {
1444         x: event.pageX,
1445         y: event.pageY
1446     };
1447 };
1448
1449 WebInspector._pageHidden = function(event)
1450 {
1451     this._saveCookieForOpenTabs();
1452 };
1453
1454 WebInspector._contextMenuRequested = function(event)
1455 {
1456     let proposedContextMenu;
1457
1458     // This is setting is only defined in engineering builds.
1459     if (WebInspector.isDebugUIEnabled()) {
1460         proposedContextMenu = WebInspector.ContextMenu.createFromEvent(event);
1461         proposedContextMenu.appendSeparator();
1462         proposedContextMenu.appendItem(WebInspector.unlocalizedString("Reload Web Inspector"), () => {
1463             window.location.reload();
1464         });
1465
1466         let protocolSubMenu = proposedContextMenu.appendSubMenuItem(WebInspector.unlocalizedString("Protocol Debugging"), null, false);
1467         let isCapturingTraffic = InspectorBackend.activeTracer instanceof WebInspector.CapturingProtocolTracer;
1468
1469         protocolSubMenu.appendCheckboxItem(WebInspector.unlocalizedString("Capture Trace"), () => {
1470             if (isCapturingTraffic)
1471                 InspectorBackend.activeTracer = null;
1472             else
1473                 InspectorBackend.activeTracer = new WebInspector.CapturingProtocolTracer;
1474         }, isCapturingTraffic);
1475
1476         protocolSubMenu.appendSeparator();
1477
1478         protocolSubMenu.appendItem(WebInspector.unlocalizedString("Export Trace\u2026"), () => {
1479             const forceSaveAs = true;
1480             WebInspector.saveDataToFile(InspectorBackend.activeTracer.trace.saveData, forceSaveAs);
1481         }, !isCapturingTraffic);
1482     } else {
1483         const onlyExisting = true;
1484         proposedContextMenu = WebInspector.ContextMenu.createFromEvent(event, onlyExisting);
1485     }
1486
1487     if (proposedContextMenu)
1488         proposedContextMenu.show();
1489 };
1490
1491 WebInspector.isDebugUIEnabled = function()
1492 {
1493     return WebInspector.showDebugUISetting && WebInspector.showDebugUISetting.value;
1494 };
1495
1496 WebInspector._undock = function(event)
1497 {
1498     InspectorFrontendHost.requestSetDockSide(WebInspector.DockConfiguration.Undocked);
1499 };
1500
1501 WebInspector._dockBottom = function(event)
1502 {
1503     InspectorFrontendHost.requestSetDockSide(WebInspector.DockConfiguration.Bottom);
1504 };
1505
1506 WebInspector._dockRight = function(event)
1507 {
1508     InspectorFrontendHost.requestSetDockSide(WebInspector.DockConfiguration.Right);
1509 };
1510
1511 WebInspector._togglePreviousDockConfiguration = function(event)
1512 {
1513     InspectorFrontendHost.requestSetDockSide(this._previousDockConfiguration);
1514 };
1515
1516 WebInspector._updateDockNavigationItems = function()
1517 {
1518     if (this._dockingAvailable || this.docked) {
1519         this._closeToolbarButton.hidden = !this.docked;
1520         this._undockToolbarButton.hidden = this._dockConfiguration === WebInspector.DockConfiguration.Undocked;
1521         this._dockBottomToolbarButton.hidden = this._dockConfiguration === WebInspector.DockConfiguration.Bottom;
1522         this._dockRightToolbarButton.hidden = this._dockConfiguration === WebInspector.DockConfiguration.Right;
1523     } else {
1524         this._closeToolbarButton.hidden = true;
1525         this._undockToolbarButton.hidden = true;
1526         this._dockBottomToolbarButton.hidden = true;
1527         this._dockRightToolbarButton.hidden = true;
1528     }
1529 };
1530
1531 WebInspector._tabBrowserSizeDidChange = function()
1532 {
1533     this.tabBrowser.updateLayout(WebInspector.View.LayoutReason.Resize);
1534     this.splitContentBrowser.updateLayout(WebInspector.View.LayoutReason.Resize);
1535     this.quickConsole.updateLayout(WebInspector.View.LayoutReason.Resize);
1536 };
1537
1538 WebInspector._quickConsoleDidResize = function(event)
1539 {
1540     this.tabBrowser.updateLayout(WebInspector.View.LayoutReason.Resize);
1541 };
1542
1543 WebInspector._sidebarWidthDidChange = function(event)
1544 {
1545     this._tabBrowserSizeDidChange();
1546 };
1547
1548 WebInspector._setupViewHierarchy = function()
1549 {
1550     let rootView = WebInspector.View.rootView();
1551     rootView.addSubview(this.toolbar);
1552     rootView.addSubview(this.tabBar);
1553     rootView.addSubview(this.navigationSidebar);
1554     rootView.addSubview(this.tabBrowser);
1555     rootView.addSubview(this.splitContentBrowser);
1556     rootView.addSubview(this.quickConsole);
1557     rootView.addSubview(this.detailsSidebar);
1558 };
1559
1560 WebInspector._tabBrowserSelectedTabContentViewDidChange = function(event)
1561 {
1562     if (this.tabBar.selectedTabBarItem)
1563         this._selectedTabIndexSetting.value = this.tabBar.tabBarItems.indexOf(this.tabBar.selectedTabBarItem);
1564
1565     if (!this.doesCurrentTabSupportSplitContentBrowser())
1566         this.hideSplitConsole();
1567
1568     if (!this.isShowingSplitConsole())
1569         this.quickConsole.consoleLogVisibilityChanged(this.isShowingConsoleTab());
1570 };
1571
1572 WebInspector._initializeWebSocketIfNeeded = function()
1573 {
1574     if (!InspectorFrontendHost.initializeWebSocket)
1575         return;
1576
1577     var queryParams = parseLocationQueryParameters();
1578
1579     if ("ws" in queryParams)
1580         var url = "ws://" + queryParams.ws;
1581     else if ("page" in queryParams) {
1582         var page = queryParams.page;
1583         var host = "host" in queryParams ? queryParams.host : window.location.host;
1584         var url = "ws://" + host + "/devtools/page/" + page;
1585     }
1586
1587     if (!url)
1588         return;
1589
1590     InspectorFrontendHost.initializeWebSocket(url);
1591 };
1592
1593 WebInspector._updateSplitConsoleHeight = function(height)
1594 {
1595     const minimumHeight = 64;
1596     const maximumHeight = window.innerHeight * 0.55;
1597
1598     height = Math.max(minimumHeight, Math.min(height, maximumHeight));
1599
1600     this.splitContentBrowser.element.style.height = height + "px";
1601 };
1602
1603 WebInspector._consoleResizerMouseDown = function(event)
1604 {
1605     if (event.button !== 0 || event.ctrlKey)
1606         return;
1607
1608     // Only start dragging if the target is one of the elements that we expect.
1609     if (!event.target.classList.contains("navigation-bar") && !event.target.classList.contains("flexible-space"))
1610         return;
1611
1612     var resizerElement = event.target;
1613     var mouseOffset = resizerElement.offsetHeight - (event.pageY - resizerElement.totalOffsetTop);
1614
1615     function dockedResizerDrag(event)
1616     {
1617         if (event.button !== 0)
1618             return;
1619
1620         var height = window.innerHeight - event.pageY - mouseOffset;
1621
1622         this._splitConsoleHeightSetting.value = height;
1623
1624         this._updateSplitConsoleHeight(height);
1625
1626         this.quickConsole.dispatchEventToListeners(WebInspector.QuickConsole.Event.DidResize);
1627     }
1628
1629     function dockedResizerDragEnd(event)
1630     {
1631         if (event.button !== 0)
1632             return;
1633
1634         this.elementDragEnd(event);
1635     }
1636
1637     this.elementDragStart(resizerElement, dockedResizerDrag.bind(this), dockedResizerDragEnd.bind(this), event, "row-resize");
1638 };
1639
1640 WebInspector._toolbarMouseDown = function(event)
1641 {
1642     if (event.ctrlKey)
1643         return;
1644
1645     if (this._dockConfiguration === WebInspector.DockConfiguration.Right)
1646         return;
1647
1648     if (this.docked)
1649         this._dockedResizerMouseDown(event);
1650     else
1651         this._moveWindowMouseDown(event);
1652 };
1653
1654 WebInspector._dockedResizerMouseDown = function(event)
1655 {
1656     if (event.button !== 0 || event.ctrlKey)
1657         return;
1658
1659     if (!this.docked)
1660         return;
1661
1662     // Only start dragging if the target is one of the elements that we expect.
1663     if (event.target.id !== "docked-resizer" && !event.target.classList.contains("toolbar") &&
1664         !event.target.classList.contains("flexible-space") && !event.target.classList.contains("item-section"))
1665         return;
1666
1667     let windowProperty = this._dockConfiguration === WebInspector.DockConfiguration.Bottom ? "innerHeight" : "innerWidth";
1668     let eventScreenProperty = this._dockConfiguration === WebInspector.DockConfiguration.Bottom ? "screenY" : "screenX";
1669     let eventClientProperty = this._dockConfiguration === WebInspector.DockConfiguration.Bottom ? "clientY" : "clientX";
1670
1671     var resizerElement = event.target;
1672     var firstClientPosition = event[eventClientProperty];
1673     var lastScreenPosition = event[eventScreenProperty];
1674
1675     function dockedResizerDrag(event)
1676     {
1677         if (event.button !== 0)
1678             return;
1679
1680         var position = event[eventScreenProperty];
1681         var delta = position - lastScreenPosition;
1682         var clientPosition = event[eventClientProperty];
1683
1684         lastScreenPosition = position;
1685
1686         // If delta is positive the docked Inspector size is decreasing, in which case the cursor client position
1687         // with respect to the target cannot be less than the first mouse down position within the target.
1688         if (delta > 0 && clientPosition < firstClientPosition)
1689             return;
1690
1691         // If delta is negative the docked Inspector size is increasing, in which case the cursor client position
1692         // with respect to the target cannot be greater than the first mouse down position within the target.
1693         if (delta < 0 && clientPosition > firstClientPosition)
1694             return;
1695
1696         let dimension = Math.max(0, window[windowProperty] - delta);
1697         // If zoomed in/out, there be greater/fewer document pixels shown, but the inspector's
1698         // width or height should be the same in device pixels regardless of the document zoom.
1699         dimension *= this._zoomFactor();
1700
1701         if (this._dockConfiguration === WebInspector.DockConfiguration.Bottom)
1702             InspectorFrontendHost.setAttachedWindowHeight(dimension);
1703         else
1704             InspectorFrontendHost.setAttachedWindowWidth(dimension);
1705     }
1706
1707     function dockedResizerDragEnd(event)
1708     {
1709         if (event.button !== 0)
1710             return;
1711
1712         WebInspector.elementDragEnd(event);
1713     }
1714
1715     WebInspector.elementDragStart(resizerElement, dockedResizerDrag.bind(this), dockedResizerDragEnd.bind(this), event, this._dockConfiguration === WebInspector.DockConfiguration.Bottom ? "row-resize" : "col-resize");
1716 };
1717
1718 WebInspector._moveWindowMouseDown = function(event)
1719 {
1720     console.assert(!this.docked);
1721
1722     if (event.button !== 0 || event.ctrlKey)
1723         return;
1724
1725     // Only start dragging if the target is one of the elements that we expect.
1726     if (!event.target.classList.contains("toolbar") && !event.target.classList.contains("flexible-space") &&
1727         !event.target.classList.contains("item-section"))
1728         return;
1729
1730     if (WebInspector.Platform.name === "mac") {
1731         // New Mac releases can start a window drag.
1732         if (WebInspector.Platform.version.release >= 11) {
1733             InspectorFrontendHost.startWindowDrag();
1734             event.preventDefault();
1735             return;
1736         }
1737
1738         // Ignore dragging on the top of the toolbar on Mac if the system handles it.
1739         if (WebInspector.Platform.version.release === 10) {
1740             const windowDragHandledTitleBarHeight = 22;
1741             if (event.pageY < windowDragHandledTitleBarHeight) {
1742                 event.preventDefault();
1743                 return;
1744             }
1745         }
1746     }
1747
1748     var lastScreenX = event.screenX;
1749     var lastScreenY = event.screenY;
1750
1751     function toolbarDrag(event)
1752     {
1753         if (event.button !== 0)
1754             return;
1755
1756         var x = event.screenX - lastScreenX;
1757         var y = event.screenY - lastScreenY;
1758
1759         InspectorFrontendHost.moveWindowBy(x, y);
1760
1761         lastScreenX = event.screenX;
1762         lastScreenY = event.screenY;
1763     }
1764
1765     function toolbarDragEnd(event)
1766     {
1767         if (event.button !== 0)
1768             return;
1769
1770         WebInspector.elementDragEnd(event);
1771     }
1772
1773     WebInspector.elementDragStart(event.target, toolbarDrag, toolbarDragEnd, event, "default");
1774 };
1775
1776 WebInspector._storageWasInspected = function(event)
1777 {
1778     this.showStorageTab();
1779 };
1780
1781 WebInspector._domNodeWasInspected = function(event)
1782 {
1783     this.domTreeManager.highlightDOMNodeForTwoSeconds(event.data.node.id);
1784
1785     InspectorFrontendHost.bringToFront();
1786
1787     this.showElementsTab();
1788     this.showMainFrameDOMTree(event.data.node);
1789 };
1790
1791 WebInspector._inspectModeStateChanged = function(event)
1792 {
1793     this._inspectModeToolbarButton.activated = this.domTreeManager.inspectModeEnabled;
1794 };
1795
1796 WebInspector._toggleInspectMode = function(event)
1797 {
1798     this.domTreeManager.inspectModeEnabled = !this.domTreeManager.inspectModeEnabled;
1799 };
1800
1801 WebInspector._downloadWebArchive = function(event)
1802 {
1803     this.archiveMainFrame();
1804 };
1805
1806 WebInspector._reloadPage = function(event)
1807 {
1808     if (!window.PageAgent)
1809         return;
1810
1811     PageAgent.reload();
1812     event.preventDefault();
1813 };
1814
1815 WebInspector._reloadPageClicked = function(event)
1816 {
1817     // Ignore cache when the shift key is pressed.
1818     PageAgent.reload(window.event ? window.event.shiftKey : false);
1819 };
1820
1821 WebInspector._reloadPageIgnoringCache = function(event)
1822 {
1823     if (!window.PageAgent)
1824         return;
1825
1826     PageAgent.reload(true);
1827     event.preventDefault();
1828 };
1829
1830 WebInspector._updateReloadToolbarButton = function()
1831 {
1832     if (!window.PageAgent) {
1833         this._reloadToolbarButton.hidden = true;
1834         return;
1835     }
1836
1837     this._reloadToolbarButton.hidden = false;
1838 };
1839
1840 WebInspector._updateDownloadToolbarButton = function()
1841 {
1842     // COMPATIBILITY (iOS 7): Page.archive did not exist yet.
1843     if (!window.PageAgent || !PageAgent.archive || this.debuggableType !== WebInspector.DebuggableType.Web) {
1844         this._downloadToolbarButton.hidden = true;
1845         return;
1846     }
1847
1848     if (this._downloadingPage) {
1849         this._downloadToolbarButton.enabled = false;
1850         return;
1851     }
1852
1853     this._downloadToolbarButton.enabled = this.canArchiveMainFrame();
1854 };
1855
1856 WebInspector._toggleInspectMode = function(event)
1857 {
1858     this.domTreeManager.inspectModeEnabled = !this.domTreeManager.inspectModeEnabled;
1859 };
1860
1861 WebInspector._showConsoleTab = function(event)
1862 {
1863     this.showConsoleTab();
1864 };
1865
1866 WebInspector._focusConsolePrompt = function(event)
1867 {
1868     this.quickConsole.prompt.focus();
1869 };
1870
1871 WebInspector._focusedContentBrowser = function()
1872 {
1873     if (this.tabBrowser.element.isSelfOrAncestor(this.currentFocusElement) || document.activeElement === document.body) {
1874         var tabContentView = this.tabBrowser.selectedTabContentView;
1875         if (tabContentView instanceof WebInspector.ContentBrowserTabContentView)
1876             return tabContentView.contentBrowser;
1877         return null;
1878     }
1879
1880     if (this.splitContentBrowser.element.isSelfOrAncestor(this.currentFocusElement)
1881         || (WebInspector.isShowingSplitConsole() && this.quickConsole.element.isSelfOrAncestor(this.currentFocusElement)))
1882         return this.splitContentBrowser;
1883
1884     return null;
1885 };
1886
1887 WebInspector._focusedContentView = function()
1888 {
1889     if (this.tabBrowser.element.isSelfOrAncestor(this.currentFocusElement) || document.activeElement === document.body) {
1890         var tabContentView = this.tabBrowser.selectedTabContentView;
1891         if (tabContentView instanceof WebInspector.ContentBrowserTabContentView)
1892             return tabContentView.contentBrowser.currentContentView;
1893         return tabContentView;
1894     }
1895
1896     if (this.splitContentBrowser.element.isSelfOrAncestor(this.currentFocusElement)
1897         || (WebInspector.isShowingSplitConsole() && this.quickConsole.element.isSelfOrAncestor(this.currentFocusElement)))
1898         return this.splitContentBrowser.currentContentView;
1899
1900     return null;
1901 };
1902
1903 WebInspector._focusedOrVisibleContentBrowser = function()
1904 {
1905     let focusedContentBrowser = this._focusedContentBrowser();
1906     if (focusedContentBrowser)
1907         return focusedContentBrowser;
1908
1909     var tabContentView = this.tabBrowser.selectedTabContentView;
1910     if (tabContentView instanceof WebInspector.ContentBrowserTabContentView)
1911         return tabContentView.contentBrowser;
1912
1913     return null;
1914 };
1915
1916 WebInspector.focusedOrVisibleContentView = function()
1917 {
1918     let focusedContentView = this._focusedContentView();
1919     if (focusedContentView)
1920         return focusedContentView;
1921
1922     var tabContentView = this.tabBrowser.selectedTabContentView;
1923     if (tabContentView instanceof WebInspector.ContentBrowserTabContentView)
1924         return tabContentView.contentBrowser.currentContentView;
1925     return tabContentView;
1926 };
1927
1928 WebInspector._beforecopy = function(event)
1929 {
1930     var selection = window.getSelection();
1931
1932     // If there is no selection, see if the focused element or focused ContentView can handle the copy event.
1933     if (selection.isCollapsed && !WebInspector.isEventTargetAnEditableField(event)) {
1934         var focusedCopyHandler = this.currentFocusElement && this.currentFocusElement.copyHandler;
1935         if (focusedCopyHandler && typeof focusedCopyHandler.handleBeforeCopyEvent === "function") {
1936             focusedCopyHandler.handleBeforeCopyEvent(event);
1937             if (event.defaultPrevented)
1938                 return;
1939         }
1940
1941         var focusedContentView = this._focusedContentView();
1942         if (focusedContentView && typeof focusedContentView.handleCopyEvent === "function") {
1943             event.preventDefault();
1944             return;
1945         }
1946
1947         return;
1948     }
1949
1950     if (selection.isCollapsed)
1951         return;
1952
1953     // Say we can handle it (by preventing default) to remove word break characters.
1954     event.preventDefault();
1955 };
1956
1957 WebInspector._find = function(event)
1958 {
1959     var contentBrowser = this._focusedOrVisibleContentBrowser();
1960     if (!contentBrowser || typeof contentBrowser.handleFindEvent !== "function")
1961         return;
1962
1963     contentBrowser.handleFindEvent(event);
1964 };
1965
1966 WebInspector._save = function(event)
1967 {
1968     var contentView = this.focusedOrVisibleContentView();
1969     if (!contentView || !contentView.supportsSave)
1970         return;
1971
1972     WebInspector.saveDataToFile(contentView.saveData);
1973 };
1974
1975 WebInspector._saveAs = function(event)
1976 {
1977     var contentView = this.focusedOrVisibleContentView();
1978     if (!contentView || !contentView.supportsSave)
1979         return;
1980
1981     WebInspector.saveDataToFile(contentView.saveData, true);
1982 };
1983
1984 WebInspector._copy = function(event)
1985 {
1986     var selection = window.getSelection();
1987
1988     // If there is no selection, pass the copy event on to the focused element or focused ContentView.
1989     if (selection.isCollapsed && !WebInspector.isEventTargetAnEditableField(event)) {
1990         var focusedCopyHandler = this.currentFocusElement && this.currentFocusElement.copyHandler;
1991         if (focusedCopyHandler && typeof focusedCopyHandler.handleCopyEvent === "function") {
1992             focusedCopyHandler.handleCopyEvent(event);
1993             if (event.defaultPrevented)
1994                 return;
1995         }
1996
1997         var focusedContentView = this._focusedContentView();
1998         if (focusedContentView && typeof focusedContentView.handleCopyEvent === "function") {
1999             focusedContentView.handleCopyEvent(event);
2000             return;
2001         }
2002
2003         return;
2004     }
2005
2006     if (selection.isCollapsed)
2007         return;
2008
2009     // Remove word break characters from the selection before putting it on the pasteboard.
2010     var selectionString = selection.toString().removeWordBreakCharacters();
2011     event.clipboardData.setData("text/plain", selectionString);
2012     event.preventDefault();
2013 };
2014
2015 WebInspector._increaseZoom = function(event)
2016 {
2017     const epsilon = 0.0001;
2018     const maximumZoom = 2.4;
2019     let currentZoom = this._zoomFactor();
2020     if (currentZoom + epsilon >= maximumZoom) {
2021         InspectorFrontendHost.beep();
2022         return;
2023     }
2024
2025     let newZoom = Math.min(maximumZoom, currentZoom + 0.2);
2026     this._setZoomFactor(newZoom);
2027 };
2028
2029 WebInspector._decreaseZoom = function(event)
2030 {
2031     const epsilon = 0.0001;
2032     const minimumZoom = 0.6;
2033     let currentZoom = this._zoomFactor();
2034     if (currentZoom - epsilon <= minimumZoom) {
2035         InspectorFrontendHost.beep();
2036         return;
2037     }
2038
2039     let newZoom = Math.max(minimumZoom, currentZoom - 0.2);
2040     this._setZoomFactor(newZoom);
2041 };
2042
2043 WebInspector._resetZoom = function(event)
2044 {
2045     this._setZoomFactor(1);
2046 };
2047
2048 WebInspector._zoomFactor = function()
2049 {
2050     return this._zoomFactorSetting.value;
2051 };
2052
2053 WebInspector._setZoomFactor = function(factor)
2054 {
2055     InspectorFrontendHost.setZoomFactor(factor);
2056     // Round-trip through the frontend host API in case the requested factor is not used.
2057     this._zoomFactorSetting.value = InspectorFrontendHost.zoomFactor();
2058 };
2059
2060 WebInspector._showTabAtIndex = function(i, event)
2061 {
2062     if (i <= WebInspector.tabBar.tabBarItems.length)
2063         WebInspector.tabBar.selectedTabBarItem = i - 1;
2064 };
2065
2066 WebInspector.elementDragStart = function(element, dividerDrag, elementDragEnd, event, cursor, eventTarget)
2067 {
2068     if (WebInspector._elementDraggingEventListener || WebInspector._elementEndDraggingEventListener)
2069         WebInspector.elementDragEnd(event);
2070
2071     if (element) {
2072         // Install glass pane
2073         if (WebInspector._elementDraggingGlassPane)
2074             WebInspector._elementDraggingGlassPane.remove();
2075
2076         var glassPane = document.createElement("div");
2077         glassPane.style.cssText = "position:absolute;top:0;bottom:0;left:0;right:0;opacity:0;z-index:1";
2078         glassPane.id = "glass-pane-for-drag";
2079         element.ownerDocument.body.appendChild(glassPane);
2080         WebInspector._elementDraggingGlassPane = glassPane;
2081     }
2082
2083     WebInspector._elementDraggingEventListener = dividerDrag;
2084     WebInspector._elementEndDraggingEventListener = elementDragEnd;
2085
2086     var targetDocument = event.target.ownerDocument;
2087
2088     WebInspector._elementDraggingEventTarget = eventTarget || targetDocument;
2089     WebInspector._elementDraggingEventTarget.addEventListener("mousemove", dividerDrag, true);
2090     WebInspector._elementDraggingEventTarget.addEventListener("mouseup", elementDragEnd, true);
2091
2092     targetDocument.body.style.cursor = cursor;
2093
2094     event.preventDefault();
2095 };
2096
2097 WebInspector.elementDragEnd = function(event)
2098 {
2099     WebInspector._elementDraggingEventTarget.removeEventListener("mousemove", WebInspector._elementDraggingEventListener, true);
2100     WebInspector._elementDraggingEventTarget.removeEventListener("mouseup", WebInspector._elementEndDraggingEventListener, true);
2101
2102     event.target.ownerDocument.body.style.removeProperty("cursor");
2103
2104     if (WebInspector._elementDraggingGlassPane)
2105         WebInspector._elementDraggingGlassPane.remove();
2106
2107     delete WebInspector._elementDraggingGlassPane;
2108     delete WebInspector._elementDraggingEventTarget;
2109     delete WebInspector._elementDraggingEventListener;
2110     delete WebInspector._elementEndDraggingEventListener;
2111
2112     event.preventDefault();
2113 };
2114
2115 WebInspector.createMessageTextView = function(message, isError)
2116 {
2117     var messageElement = document.createElement("div");
2118     messageElement.className = "message-text-view";
2119     if (isError)
2120         messageElement.classList.add("error");
2121
2122     messageElement.textContent = message;
2123
2124     return messageElement;
2125 };
2126
2127 WebInspector.createGoToArrowButton = function()
2128 {
2129     var button = document.createElement("button");
2130     button.addEventListener("mousedown", (event) => { event.stopPropagation(); }, true);
2131     button.className = "go-to-arrow";
2132     button.tabIndex = -1;
2133     return button;
2134 };
2135
2136 WebInspector.createSourceCodeLocationLink = function(sourceCodeLocation, dontFloat, useGoToArrowButton)
2137 {
2138     console.assert(sourceCodeLocation);
2139     if (!sourceCodeLocation)
2140         return null;
2141
2142     var linkElement = document.createElement("a");
2143     linkElement.className = "go-to-link";
2144     WebInspector.linkifyElement(linkElement, sourceCodeLocation);
2145     sourceCodeLocation.populateLiveDisplayLocationTooltip(linkElement);
2146
2147     if (useGoToArrowButton)
2148         linkElement.appendChild(WebInspector.createGoToArrowButton());
2149     else
2150         sourceCodeLocation.populateLiveDisplayLocationString(linkElement, "textContent");
2151
2152     if (dontFloat)
2153         linkElement.classList.add("dont-float");
2154
2155     return linkElement;
2156 };
2157
2158 WebInspector.linkifyLocation = function(url, lineNumber, columnNumber, className)
2159 {
2160     var sourceCode = WebInspector.sourceCodeForURL(url);
2161
2162     if (!sourceCode) {
2163         var anchor = document.createElement("a");
2164         anchor.href = url;
2165         anchor.lineNumber = lineNumber;
2166         if (className)
2167             anchor.className = className;
2168         anchor.append(WebInspector.displayNameForURL(url) + ":" + lineNumber);
2169         return anchor;
2170     }
2171
2172     var sourceCodeLocation = sourceCode.createSourceCodeLocation(lineNumber, columnNumber);
2173     var linkElement = WebInspector.createSourceCodeLocationLink(sourceCodeLocation, true);
2174     if (className)
2175         linkElement.classList.add(className);
2176     return linkElement;
2177 };
2178
2179 WebInspector.linkifyElement = function(linkElement, sourceCodeLocation) {
2180     console.assert(sourceCodeLocation);
2181
2182     function showSourceCodeLocation(event)
2183     {
2184         event.stopPropagation();
2185         event.preventDefault();
2186
2187         if (event.metaKey)
2188             this.showOriginalUnformattedSourceCodeLocation(sourceCodeLocation);
2189         else
2190             this.showSourceCodeLocation(sourceCodeLocation);
2191     }
2192
2193     linkElement.addEventListener("click", showSourceCodeLocation.bind(this));
2194 };
2195
2196 WebInspector.sourceCodeForURL = function(url) {
2197     var sourceCode = WebInspector.frameResourceManager.resourceForURL(url);
2198     if (!sourceCode) {
2199         sourceCode = WebInspector.debuggerManager.scriptsForURL(url)[0];
2200         if (sourceCode)
2201             sourceCode = sourceCode.resource || sourceCode;
2202     }
2203     return sourceCode || null;
2204 };
2205
2206 WebInspector.linkifyURLAsNode = function(url, linkText, classes)
2207 {
2208     if (!linkText)
2209         linkText = url;
2210
2211     classes = (classes ? classes + " " : "");
2212
2213     var a = document.createElement("a");
2214     a.href = url;
2215     a.className = classes;
2216
2217     a.textContent = linkText;
2218     a.style.maxWidth = "100%";
2219
2220     return a;
2221 };
2222
2223 WebInspector.linkifyStringAsFragmentWithCustomLinkifier = function(string, linkifier)
2224 {
2225     var container = document.createDocumentFragment();
2226     var linkStringRegEx = /(?:[a-zA-Z][a-zA-Z0-9+.-]{2,}:\/\/|www\.)[\w$\-_+*'=\|\/\\(){}[\]%@&#~,:;.!?]{2,}[\w$\-_+*=\|\/\\({%@&#~]/;
2227     var lineColumnRegEx = /:(\d+)(:(\d+))?$/;
2228
2229     while (string) {
2230         var linkString = linkStringRegEx.exec(string);
2231         if (!linkString)
2232             break;
2233
2234         linkString = linkString[0];
2235         var linkIndex = string.indexOf(linkString);
2236         var nonLink = string.substring(0, linkIndex);
2237         container.append(nonLink);
2238
2239         if (linkString.startsWith("data:") || linkString.startsWith("javascript:") || linkString.startsWith("mailto:")) {
2240             container.append(linkString);
2241             string = string.substring(linkIndex + linkString.length, string.length);
2242             continue;
2243         }
2244
2245         var title = linkString;
2246         var realURL = linkString.startsWith("www.") ? "http://" + linkString : linkString;
2247         var lineColumnMatch = lineColumnRegEx.exec(realURL);
2248         if (lineColumnMatch)
2249             realURL = realURL.substring(0, realURL.length - lineColumnMatch[0].length);
2250
2251         var lineNumber;
2252         if (lineColumnMatch)
2253             lineNumber = parseInt(lineColumnMatch[1]) - 1;
2254
2255         var linkNode = linkifier(title, realURL, lineNumber);
2256         container.appendChild(linkNode);
2257         string = string.substring(linkIndex + linkString.length, string.length);
2258     }
2259
2260     if (string)
2261         container.append(string);
2262
2263     return container;
2264 };
2265
2266 WebInspector.linkifyStringAsFragment = function(string)
2267 {
2268     function linkifier(title, url, lineNumber)
2269     {
2270         var urlNode = WebInspector.linkifyURLAsNode(url, title, undefined);
2271         if (lineNumber !== undefined)
2272             urlNode.lineNumber = lineNumber;
2273
2274         return urlNode;
2275     }
2276
2277     return WebInspector.linkifyStringAsFragmentWithCustomLinkifier(string, linkifier);
2278 };
2279
2280 WebInspector.createResourceLink = function(resource, className)
2281 {
2282     function handleClick(event)
2283     {
2284         event.stopPropagation();
2285         event.preventDefault();
2286
2287         WebInspector.showRepresentedObject(resource);
2288     }
2289
2290     let linkNode = document.createElement("a");
2291     linkNode.classList.add("resource-link", className);
2292     linkNode.title = resource.url;
2293     linkNode.textContent = (resource.urlComponents.lastPathComponent || resource.url).insertWordBreakCharacters();
2294     linkNode.addEventListener("click", handleClick.bind(this));
2295     return linkNode;
2296 };
2297
2298 WebInspector._undoKeyboardShortcut = function(event)
2299 {
2300     if (!this.isEditingAnyField() && !this.isEventTargetAnEditableField(event)) {
2301         this.undo();
2302         event.preventDefault();
2303     }
2304 };
2305
2306 WebInspector._redoKeyboardShortcut = function(event)
2307 {
2308     if (!this.isEditingAnyField() && !this.isEventTargetAnEditableField(event)) {
2309         this.redo();
2310         event.preventDefault();
2311     }
2312 };
2313
2314 WebInspector.undo = function()
2315 {
2316     DOMAgent.undo();
2317 };
2318
2319 WebInspector.redo = function()
2320 {
2321     DOMAgent.redo();
2322 };
2323
2324 WebInspector.highlightRangesWithStyleClass = function(element, resultRanges, styleClass, changes)
2325 {
2326     changes = changes || [];
2327     var highlightNodes = [];
2328     var lineText = element.textContent;
2329     var ownerDocument = element.ownerDocument;
2330     var textNodeSnapshot = ownerDocument.evaluate(".//text()", element, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
2331
2332     var snapshotLength = textNodeSnapshot.snapshotLength;
2333     if (snapshotLength === 0)
2334         return highlightNodes;
2335
2336     var nodeRanges = [];
2337     var rangeEndOffset = 0;
2338     for (var i = 0; i < snapshotLength; ++i) {
2339         var range = {};
2340         range.offset = rangeEndOffset;
2341         range.length = textNodeSnapshot.snapshotItem(i).textContent.length;
2342         rangeEndOffset = range.offset + range.length;
2343         nodeRanges.push(range);
2344     }
2345
2346     var startIndex = 0;
2347     for (var i = 0; i < resultRanges.length; ++i) {
2348         var startOffset = resultRanges[i].offset;
2349         var endOffset = startOffset + resultRanges[i].length;
2350
2351         while (startIndex < snapshotLength && nodeRanges[startIndex].offset + nodeRanges[startIndex].length <= startOffset)
2352             startIndex++;
2353         var endIndex = startIndex;
2354         while (endIndex < snapshotLength && nodeRanges[endIndex].offset + nodeRanges[endIndex].length < endOffset)
2355             endIndex++;
2356         if (endIndex === snapshotLength)
2357             break;
2358
2359         var highlightNode = ownerDocument.createElement("span");
2360         highlightNode.className = styleClass;
2361         highlightNode.textContent = lineText.substring(startOffset, endOffset);
2362
2363         var lastTextNode = textNodeSnapshot.snapshotItem(endIndex);
2364         var lastText = lastTextNode.textContent;
2365         lastTextNode.textContent = lastText.substring(endOffset - nodeRanges[endIndex].offset);
2366         changes.push({node: lastTextNode, type: "changed", oldText: lastText, newText: lastTextNode.textContent});
2367
2368         if (startIndex === endIndex) {
2369             lastTextNode.parentElement.insertBefore(highlightNode, lastTextNode);
2370             changes.push({node: highlightNode, type: "added", nextSibling: lastTextNode, parent: lastTextNode.parentElement});
2371             highlightNodes.push(highlightNode);
2372
2373             var prefixNode = ownerDocument.createTextNode(lastText.substring(0, startOffset - nodeRanges[startIndex].offset));
2374             lastTextNode.parentElement.insertBefore(prefixNode, highlightNode);
2375             changes.push({node: prefixNode, type: "added", nextSibling: highlightNode, parent: lastTextNode.parentElement});
2376         } else {
2377             var firstTextNode = textNodeSnapshot.snapshotItem(startIndex);
2378             var firstText = firstTextNode.textContent;
2379             var anchorElement = firstTextNode.nextSibling;
2380
2381             firstTextNode.parentElement.insertBefore(highlightNode, anchorElement);
2382             changes.push({node: highlightNode, type: "added", nextSibling: anchorElement, parent: firstTextNode.parentElement});
2383             highlightNodes.push(highlightNode);
2384
2385             firstTextNode.textContent = firstText.substring(0, startOffset - nodeRanges[startIndex].offset);
2386             changes.push({node: firstTextNode, type: "changed", oldText: firstText, newText: firstTextNode.textContent});
2387
2388             for (var j = startIndex + 1; j < endIndex; j++) {
2389                 var textNode = textNodeSnapshot.snapshotItem(j);
2390                 var text = textNode.textContent;
2391                 textNode.textContent = "";
2392                 changes.push({node: textNode, type: "changed", oldText: text, newText: textNode.textContent});
2393             }
2394         }
2395         startIndex = endIndex;
2396         nodeRanges[startIndex].offset = endOffset;
2397         nodeRanges[startIndex].length = lastTextNode.textContent.length;
2398
2399     }
2400     return highlightNodes;
2401 };
2402
2403 WebInspector.revertDomChanges = function(domChanges)
2404 {
2405     for (var i = domChanges.length - 1; i >= 0; --i) {
2406         var entry = domChanges[i];
2407         switch (entry.type) {
2408         case "added":
2409             entry.node.remove();
2410             break;
2411         case "changed":
2412             entry.node.textContent = entry.oldText;
2413             break;
2414         }
2415     }
2416 };
2417
2418 WebInspector.archiveMainFrame = function()
2419 {
2420     this._downloadingPage = true;
2421     this._updateDownloadToolbarButton();
2422
2423     PageAgent.archive((error, data) => {
2424         this._downloadingPage = false;
2425         this._updateDownloadToolbarButton();
2426
2427         if (error)
2428             return;
2429
2430         let mainFrame = WebInspector.frameResourceManager.mainFrame;
2431         let archiveName = mainFrame.mainResource.urlComponents.host || mainFrame.mainResource.displayName || "Archive";
2432         let url = "web-inspector:///" + encodeURI(archiveName) + ".webarchive";
2433
2434         InspectorFrontendHost.save(url, data, true, true);
2435     });
2436 };
2437
2438 WebInspector.canArchiveMainFrame = function()
2439 {
2440     // COMPATIBILITY (iOS 7): Page.archive did not exist yet.
2441     if (!PageAgent.archive || this.debuggableType !== WebInspector.DebuggableType.Web)
2442         return false;
2443
2444     if (!WebInspector.frameResourceManager.mainFrame || !WebInspector.frameResourceManager.mainFrame.mainResource)
2445         return false;
2446
2447     return WebInspector.Resource.typeFromMIMEType(WebInspector.frameResourceManager.mainFrame.mainResource.mimeType) === WebInspector.Resource.Type.Document;
2448 };
2449
2450 WebInspector.addWindowKeydownListener = function(listener)
2451 {
2452     if (typeof listener.handleKeydownEvent !== "function")
2453         return;
2454
2455     this._windowKeydownListeners.push(listener);
2456
2457     this._updateWindowKeydownListener();
2458 };
2459
2460 WebInspector.removeWindowKeydownListener = function(listener)
2461 {
2462     this._windowKeydownListeners.remove(listener);
2463
2464     this._updateWindowKeydownListener();
2465 };
2466
2467 WebInspector._updateWindowKeydownListener = function()
2468 {
2469     if (this._windowKeydownListeners.length === 1)
2470         window.addEventListener("keydown", WebInspector._sharedWindowKeydownListener, true);
2471     else if (!this._windowKeydownListeners.length)
2472         window.removeEventListener("keydown", WebInspector._sharedWindowKeydownListener, true);
2473 };
2474
2475 WebInspector._sharedWindowKeydownListener = function(event)
2476 {
2477     for (var i = WebInspector._windowKeydownListeners.length - 1; i >= 0; --i) {
2478         if (WebInspector._windowKeydownListeners[i].handleKeydownEvent(event)) {
2479             event.stopImmediatePropagation();
2480             event.preventDefault();
2481             break;
2482         }
2483     }
2484 };
2485
2486 WebInspector.reportInternalError = function(errorOrString, details={})
2487 {
2488     // The 'details' object includes additional information from the caller as free-form string keys and values.
2489     // Each key and value will be shown in the uncaught exception reporter, console error message, or in
2490     // a pre-filled bug report generated for this internal error.
2491
2492     let error = (errorOrString instanceof Error) ? errorOrString : new Error(errorOrString);
2493     error.details = details;
2494
2495     // The error will be displayed in the Uncaught Exception Reporter sheet if DebugUI is enabled.
2496     if (WebInspector.isDebugUIEnabled()) {
2497         // This assert allows us to stop the debugger at an internal exception. It doesn't re-throw
2498         // exceptions because the original exception would be lost through window.onerror.
2499         // This workaround can be removed once <https://webkit.org/b/158192> is fixed.
2500         console.assert(false, "An internal exception was thrown.", error);
2501         handleInternalException(error);
2502     } else
2503         console.error(error);
2504 };
2505
2506 // OpenResourceDialog delegate
2507
2508 WebInspector.dialogWasDismissed = function(dialog)
2509 {
2510     let representedObject = dialog.representedObject;
2511     if (!representedObject)
2512         return;
2513
2514     WebInspector.showRepresentedObject(representedObject, dialog.cookie);
2515 };
2516
2517 WebInspector.DockConfiguration = {
2518     Right: "right",
2519     Bottom: "bottom",
2520     Undocked: "undocked",
2521 };