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