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