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