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