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