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