Web Inspector: "Reload Web Inspector" button no longer partially works
[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             InspectorFrontendHost.reopen();
1588         });
1589
1590         let protocolSubMenu = proposedContextMenu.appendSubMenuItem(WI.unlocalizedString("Protocol Debugging"), null, false);
1591         let isCapturingTraffic = InspectorBackend.activeTracer instanceof WI.CapturingProtocolTracer;
1592
1593         protocolSubMenu.appendCheckboxItem(WI.unlocalizedString("Capture Trace"), () => {
1594             if (isCapturingTraffic)
1595                 InspectorBackend.activeTracer = null;
1596             else
1597                 InspectorBackend.activeTracer = new WI.CapturingProtocolTracer;
1598         }, isCapturingTraffic);
1599
1600         protocolSubMenu.appendSeparator();
1601
1602         protocolSubMenu.appendItem(WI.unlocalizedString("Export Trace\u2026"), () => {
1603             const forceSaveAs = true;
1604             WI.FileUtilities.save(InspectorBackend.activeTracer.trace.saveData, forceSaveAs);
1605         }, !isCapturingTraffic);
1606     } else {
1607         const onlyExisting = true;
1608         proposedContextMenu = WI.ContextMenu.createFromEvent(event, onlyExisting);
1609     }
1610
1611     if (proposedContextMenu)
1612         proposedContextMenu.show();
1613 };
1614
1615 WI.isDebugUIEnabled = function()
1616 {
1617     return WI.showDebugUISetting && WI.showDebugUISetting.value;
1618 };
1619
1620 WI._undock = function(event)
1621 {
1622     InspectorFrontendHost.requestSetDockSide(WI.DockConfiguration.Undocked);
1623 };
1624
1625 WI._dockBottom = function(event)
1626 {
1627     InspectorFrontendHost.requestSetDockSide(WI.DockConfiguration.Bottom);
1628 };
1629
1630 WI._dockRight = function(event)
1631 {
1632     InspectorFrontendHost.requestSetDockSide(WI.DockConfiguration.Right);
1633 };
1634
1635 WI._dockLeft = function(event)
1636 {
1637     InspectorFrontendHost.requestSetDockSide(WI.DockConfiguration.Left);
1638 };
1639
1640 WI._togglePreviousDockConfiguration = function(event)
1641 {
1642     InspectorFrontendHost.requestSetDockSide(this._previousDockConfiguration);
1643 };
1644
1645 WI._updateDockNavigationItems = function()
1646 {
1647     if (this._dockingAvailable || this.docked) {
1648         this._closeToolbarButton.hidden = !this.docked;
1649         this._undockToolbarButton.hidden = this._dockConfiguration === WI.DockConfiguration.Undocked;
1650         this._dockBottomToolbarButton.hidden = this._dockConfiguration === WI.DockConfiguration.Bottom;
1651         this._dockToSideToolbarButton.hidden = this._dockConfiguration === WI.DockConfiguration.Right || this._dockConfiguration === WI.DockConfiguration.Left;
1652     } else {
1653         this._closeToolbarButton.hidden = true;
1654         this._undockToolbarButton.hidden = true;
1655         this._dockBottomToolbarButton.hidden = true;
1656         this._dockToSideToolbarButton.hidden = true;
1657     }
1658 };
1659
1660 WI._tabBrowserSizeDidChange = function()
1661 {
1662     this.tabBrowser.updateLayout(WI.View.LayoutReason.Resize);
1663     this.consoleDrawer.updateLayout(WI.View.LayoutReason.Resize);
1664     this.quickConsole.updateLayout(WI.View.LayoutReason.Resize);
1665 };
1666
1667 WI._consoleDrawerCollapsedStateDidChange = function(event)
1668 {
1669     this._showingSplitConsoleSetting.value = WI.isShowingSplitConsole();
1670
1671     WI._consoleDrawerDidResize();
1672 };
1673
1674 WI._consoleDrawerDidResize = function(event)
1675 {
1676     this.tabBrowser.updateLayout(WI.View.LayoutReason.Resize);
1677 };
1678
1679 WI._sidebarWidthDidChange = function(event)
1680 {
1681     this._tabBrowserSizeDidChange();
1682 };
1683
1684 WI._setupViewHierarchy = function()
1685 {
1686     let rootView = WI.View.rootView();
1687     rootView.addSubview(this.toolbar);
1688     rootView.addSubview(this.tabBar);
1689     rootView.addSubview(this.navigationSidebar);
1690     rootView.addSubview(this.tabBrowser);
1691     rootView.addSubview(this.consoleDrawer);
1692     rootView.addSubview(this.quickConsole);
1693     rootView.addSubview(this.detailsSidebar);
1694 };
1695
1696 WI._tabBrowserSelectedTabContentViewDidChange = function(event)
1697 {
1698     if (this.tabBar.selectedTabBarItem && this.tabBar.selectedTabBarItem.representedObject.constructor.shouldSaveTab())
1699         this._selectedTabIndexSetting.value = this.tabBar.tabBarItems.indexOf(this.tabBar.selectedTabBarItem);
1700
1701     if (this.doesCurrentTabSupportSplitContentBrowser()) {
1702         if (this._shouldRevealSpitConsoleIfSupported) {
1703             this._shouldRevealSpitConsoleIfSupported = false;
1704             this.showSplitConsole();
1705         }
1706         return;
1707     }
1708
1709     this._shouldRevealSpitConsoleIfSupported = this.isShowingSplitConsole();
1710     this.hideSplitConsole();
1711 };
1712
1713 WI._toolbarMouseDown = function(event)
1714 {
1715     if (event.ctrlKey)
1716         return;
1717
1718     if (this._dockConfiguration === WI.DockConfiguration.Right || this._dockConfiguration === WI.DockConfiguration.Left)
1719         return;
1720
1721     if (this.docked)
1722         this._dockedResizerMouseDown(event);
1723     else
1724         this._moveWindowMouseDown(event);
1725 };
1726
1727 WI._dockedResizerMouseDown = function(event)
1728 {
1729     if (event.button !== 0 || event.ctrlKey)
1730         return;
1731
1732     if (!this.docked)
1733         return;
1734
1735     // Only start dragging if the target is one of the elements that we expect.
1736     if (event.target.id !== "docked-resizer" && !event.target.classList.contains("toolbar") &&
1737         !event.target.classList.contains("flexible-space") && !event.target.classList.contains("item-section"))
1738         return;
1739
1740     event[WI.Popover.EventPreventDismissSymbol] = true;
1741
1742     let windowProperty = this._dockConfiguration === WI.DockConfiguration.Bottom ? "innerHeight" : "innerWidth";
1743     let eventScreenProperty = this._dockConfiguration === WI.DockConfiguration.Bottom ? "screenY" : "screenX";
1744     let eventClientProperty = this._dockConfiguration === WI.DockConfiguration.Bottom ? "clientY" : "clientX";
1745
1746     var resizerElement = event.target;
1747     var firstClientPosition = event[eventClientProperty];
1748     var lastScreenPosition = event[eventScreenProperty];
1749
1750     function dockedResizerDrag(event)
1751     {
1752         if (event.button !== 0)
1753             return;
1754
1755         var position = event[eventScreenProperty];
1756         var delta = position - lastScreenPosition;
1757         var clientPosition = event[eventClientProperty];
1758
1759         lastScreenPosition = position;
1760
1761         if (this._dockConfiguration === WI.DockConfiguration.Left) {
1762             // If the mouse is travelling rightward but is positioned left of the resizer, ignore the event.
1763             if (delta > 0 && clientPosition < firstClientPosition)
1764                 return;
1765
1766             // If the mouse is travelling leftward but is positioned to the right of the resizer, ignore the event.
1767             if (delta < 0 && clientPosition > window[windowProperty])
1768                 return;
1769
1770             // We later subtract the delta from the current position, but since the inspected view and inspector view
1771             // are flipped when docked to left, we want dragging to have the opposite effect from docked to right.
1772             delta *= -1;
1773         } else {
1774             // If the mouse is travelling downward/rightward but is positioned above/left of the resizer, ignore the event.
1775             if (delta > 0 && clientPosition < firstClientPosition)
1776                 return;
1777
1778             // If the mouse is travelling upward/leftward but is positioned below/right of the resizer, ignore the event.
1779             if (delta < 0 && clientPosition > firstClientPosition)
1780                 return;
1781         }
1782
1783         let dimension = Math.max(0, window[windowProperty] - delta);
1784         // If zoomed in/out, there be greater/fewer document pixels shown, but the inspector's
1785         // width or height should be the same in device pixels regardless of the document zoom.
1786         dimension *= this.getZoomFactor();
1787
1788         if (this._dockConfiguration === WI.DockConfiguration.Bottom)
1789             InspectorFrontendHost.setAttachedWindowHeight(dimension);
1790         else
1791             InspectorFrontendHost.setAttachedWindowWidth(dimension);
1792     }
1793
1794     function dockedResizerDragEnd(event)
1795     {
1796         if (event.button !== 0)
1797             return;
1798
1799         WI.elementDragEnd(event);
1800     }
1801
1802     WI.elementDragStart(resizerElement, dockedResizerDrag.bind(this), dockedResizerDragEnd.bind(this), event, this._dockConfiguration === WI.DockConfiguration.Bottom ? "row-resize" : "col-resize");
1803 };
1804
1805 WI._moveWindowMouseDown = function(event)
1806 {
1807     console.assert(!this.docked);
1808
1809     if (event.button !== 0 || event.ctrlKey)
1810         return;
1811
1812     // Only start dragging if the target is one of the elements that we expect.
1813     if (!event.target.classList.contains("toolbar") && !event.target.classList.contains("flexible-space") &&
1814         !event.target.classList.contains("item-section"))
1815         return;
1816
1817     event[WI.Popover.EventPreventDismissSymbol] = true;
1818
1819     if (WI.Platform.name === "mac") {
1820         InspectorFrontendHost.startWindowDrag();
1821         event.preventDefault();
1822         return;
1823     }
1824
1825     var lastScreenX = event.screenX;
1826     var lastScreenY = event.screenY;
1827
1828     function toolbarDrag(event)
1829     {
1830         if (event.button !== 0)
1831             return;
1832
1833         var x = event.screenX - lastScreenX;
1834         var y = event.screenY - lastScreenY;
1835
1836         InspectorFrontendHost.moveWindowBy(x, y);
1837
1838         lastScreenX = event.screenX;
1839         lastScreenY = event.screenY;
1840     }
1841
1842     function toolbarDragEnd(event)
1843     {
1844         if (event.button !== 0)
1845             return;
1846
1847         WI.elementDragEnd(event);
1848     }
1849
1850     WI.elementDragStart(event.target, toolbarDrag, toolbarDragEnd, event, "default");
1851 };
1852
1853 WI._domStorageWasInspected = function(event)
1854 {
1855     this.showStorageTab();
1856     this.showRepresentedObject(event.data.domStorage, null, {ignoreSearchTab: true});
1857 };
1858
1859 WI._databaseWasInspected = function(event)
1860 {
1861     this.showStorageTab();
1862     this.showRepresentedObject(event.data.database, null, {ignoreSearchTab: true});
1863 };
1864
1865 WI._domNodeWasInspected = function(event)
1866 {
1867     this.domManager.highlightDOMNodeForTwoSeconds(event.data.node.id);
1868
1869     InspectorFrontendHost.bringToFront();
1870
1871     this.showElementsTab();
1872     this.showMainFrameDOMTree(event.data.node, {ignoreSearchTab: true});
1873 };
1874
1875 WI._inspectModeStateChanged = function(event)
1876 {
1877     this._inspectModeToolbarButton.activated = this.domManager.inspectModeEnabled;
1878 };
1879
1880 WI._toggleInspectMode = function(event)
1881 {
1882     this.domManager.inspectModeEnabled = !this.domManager.inspectModeEnabled;
1883 };
1884
1885 WI._downloadWebArchive = function(event)
1886 {
1887     this.archiveMainFrame();
1888 };
1889
1890 WI._reloadPage = function(event)
1891 {
1892     if (!window.PageAgent)
1893         return;
1894
1895     PageAgent.reload();
1896     event.preventDefault();
1897 };
1898
1899 WI._reloadToolbarButtonClicked = function(event)
1900 {
1901     // Reload page from origin if the button is clicked while the shift key is pressed down.
1902     PageAgent.reload.invoke({ignoreCache: this.modifierKeys.shiftKey});
1903 };
1904
1905 WI._reloadPageFromOrigin = function(event)
1906 {
1907     if (!window.PageAgent)
1908         return;
1909
1910     PageAgent.reload.invoke({ignoreCache: true});
1911     event.preventDefault();
1912 };
1913
1914 WI._updateReloadToolbarButton = function()
1915 {
1916     if (!window.PageAgent) {
1917         this._reloadToolbarButton.hidden = true;
1918         return;
1919     }
1920
1921     this._reloadToolbarButton.hidden = false;
1922 };
1923
1924 WI._updateDownloadToolbarButton = function()
1925 {
1926     if (!window.PageAgent || this.sharedApp.debuggableType !== WI.DebuggableType.Web) {
1927         this._downloadToolbarButton.hidden = true;
1928         return;
1929     }
1930
1931     if (this._downloadingPage) {
1932         this._downloadToolbarButton.enabled = false;
1933         return;
1934     }
1935
1936     this._downloadToolbarButton.enabled = this.canArchiveMainFrame();
1937 };
1938
1939 WI._updateInspectModeToolbarButton = function()
1940 {
1941     if (!window.DOMAgent || !DOMAgent.setInspectModeEnabled) {
1942         this._inspectModeToolbarButton.hidden = true;
1943         return;
1944     }
1945
1946     this._inspectModeToolbarButton.hidden = false;
1947 };
1948
1949 WI._toggleInspectMode = function(event)
1950 {
1951     this.domManager.inspectModeEnabled = !this.domManager.inspectModeEnabled;
1952 };
1953
1954 WI._showConsoleTab = function(event)
1955 {
1956     this.showConsoleTab();
1957 };
1958
1959 WI._focusConsolePrompt = function(event)
1960 {
1961     this.quickConsole.prompt.focus();
1962 };
1963
1964 WI._focusedContentBrowser = function()
1965 {
1966     if (this.currentFocusElement) {
1967         let contentBrowserElement = this.currentFocusElement.enclosingNodeOrSelfWithClass("content-browser");
1968         if (contentBrowserElement && contentBrowserElement.__view && contentBrowserElement.__view instanceof WI.ContentBrowser)
1969             return contentBrowserElement.__view;
1970     }
1971
1972     if (this.tabBrowser.element.contains(this.currentFocusElement) || document.activeElement === document.body) {
1973         let tabContentView = this.tabBrowser.selectedTabContentView;
1974         if (tabContentView.contentBrowser)
1975             return tabContentView.contentBrowser;
1976         return null;
1977     }
1978
1979     if (this.consoleDrawer.element.contains(this.currentFocusElement)
1980         || (WI.isShowingSplitConsole() && this.quickConsole.element.contains(this.currentFocusElement)))
1981         return this.consoleDrawer;
1982
1983     return null;
1984 };
1985
1986 WI._focusedContentView = function()
1987 {
1988     if (this.tabBrowser.element.contains(this.currentFocusElement) || document.activeElement === document.body) {
1989         var tabContentView = this.tabBrowser.selectedTabContentView;
1990         if (tabContentView.contentBrowser)
1991             return tabContentView.contentBrowser.currentContentView;
1992         return tabContentView;
1993     }
1994
1995     if (this.consoleDrawer.element.contains(this.currentFocusElement)
1996         || (WI.isShowingSplitConsole() && this.quickConsole.element.contains(this.currentFocusElement)))
1997         return this.consoleDrawer.currentContentView;
1998
1999     return null;
2000 };
2001
2002 WI._focusedOrVisibleContentBrowser = function()
2003 {
2004     let focusedContentBrowser = this._focusedContentBrowser();
2005     if (focusedContentBrowser)
2006         return focusedContentBrowser;
2007
2008     var tabContentView = this.tabBrowser.selectedTabContentView;
2009     if (tabContentView.contentBrowser)
2010         return tabContentView.contentBrowser;
2011
2012     return null;
2013 };
2014
2015 WI.focusedOrVisibleContentView = function()
2016 {
2017     let focusedContentView = this._focusedContentView();
2018     if (focusedContentView)
2019         return focusedContentView;
2020
2021     var tabContentView = this.tabBrowser.selectedTabContentView;
2022     if (tabContentView.contentBrowser)
2023         return tabContentView.contentBrowser.currentContentView;
2024     return tabContentView;
2025 };
2026
2027 WI._beforecopy = function(event)
2028 {
2029     var selection = window.getSelection();
2030
2031     // If there is no selection, see if the focused element or focused ContentView can handle the copy event.
2032     if (selection.isCollapsed && !WI.isEventTargetAnEditableField(event)) {
2033         var focusedCopyHandler = this.currentFocusElement && this.currentFocusElement.copyHandler;
2034         if (focusedCopyHandler && typeof focusedCopyHandler.handleBeforeCopyEvent === "function") {
2035             focusedCopyHandler.handleBeforeCopyEvent(event);
2036             if (event.defaultPrevented)
2037                 return;
2038         }
2039
2040         var focusedContentView = this._focusedContentView();
2041         if (focusedContentView && typeof focusedContentView.handleCopyEvent === "function") {
2042             event.preventDefault();
2043             return;
2044         }
2045
2046         return;
2047     }
2048
2049     if (selection.isCollapsed)
2050         return;
2051
2052     // Say we can handle it (by preventing default) to remove word break characters.
2053     event.preventDefault();
2054 };
2055
2056 WI._find = function(event)
2057 {
2058     let contentBrowser = this._focusedOrVisibleContentBrowser();
2059     if (!contentBrowser)
2060         return;
2061
2062     contentBrowser.showFindBanner();
2063 };
2064
2065 WI._save = function(event)
2066 {
2067     var contentView = this.focusedOrVisibleContentView();
2068     if (!contentView || !contentView.supportsSave)
2069         return;
2070
2071     WI.FileUtilities.save(contentView.saveData);
2072 };
2073
2074 WI._saveAs = function(event)
2075 {
2076     var contentView = this.focusedOrVisibleContentView();
2077     if (!contentView || !contentView.supportsSave)
2078         return;
2079
2080     WI.FileUtilities.save(contentView.saveData, true);
2081 };
2082
2083 WI._clear = function(event)
2084 {
2085     let contentView = this.focusedOrVisibleContentView();
2086     if (!contentView || typeof contentView.handleClearShortcut !== "function") {
2087         // If the current content view is unable to handle this event, clear the console to reset
2088         // the dashboard counters.
2089         this.consoleManager.requestClearMessages();
2090         return;
2091     }
2092
2093     contentView.handleClearShortcut(event);
2094 };
2095
2096 WI._populateFind = function(event)
2097 {
2098     let focusedContentView = this._focusedContentView();
2099     if (!focusedContentView)
2100         return;
2101
2102     if (focusedContentView.supportsCustomFindBanner) {
2103         focusedContentView.handlePopulateFindShortcut();
2104         return;
2105     }
2106
2107     let contentBrowser = this._focusedOrVisibleContentBrowser();
2108     if (!contentBrowser)
2109         return;
2110
2111     contentBrowser.handlePopulateFindShortcut();
2112 };
2113
2114 WI._findNext = function(event)
2115 {
2116     let focusedContentView = this._focusedContentView();
2117     if (!focusedContentView)
2118         return;
2119
2120     if (focusedContentView.supportsCustomFindBanner) {
2121         focusedContentView.handleFindNextShortcut();
2122         return;
2123     }
2124
2125     let contentBrowser = this._focusedOrVisibleContentBrowser();
2126     if (!contentBrowser)
2127         return;
2128
2129     contentBrowser.handleFindNextShortcut();
2130 };
2131
2132 WI._findPrevious = function(event)
2133 {
2134     let focusedContentView = this._focusedContentView();
2135     if (!focusedContentView)
2136         return;
2137
2138     if (focusedContentView.supportsCustomFindBanner) {
2139         focusedContentView.handleFindPreviousShortcut();
2140         return;
2141     }
2142
2143     let contentBrowser = this._focusedOrVisibleContentBrowser();
2144     if (!contentBrowser)
2145         return;
2146
2147     contentBrowser.handleFindPreviousShortcut();
2148 };
2149
2150 WI._copy = function(event)
2151 {
2152     var selection = window.getSelection();
2153
2154     // If there is no selection, pass the copy event on to the focused element or focused ContentView.
2155     if (selection.isCollapsed && !WI.isEventTargetAnEditableField(event)) {
2156         var focusedCopyHandler = this.currentFocusElement && this.currentFocusElement.copyHandler;
2157         if (focusedCopyHandler && typeof focusedCopyHandler.handleCopyEvent === "function") {
2158             focusedCopyHandler.handleCopyEvent(event);
2159             if (event.defaultPrevented)
2160                 return;
2161         }
2162
2163         var focusedContentView = this._focusedContentView();
2164         if (focusedContentView && typeof focusedContentView.handleCopyEvent === "function") {
2165             focusedContentView.handleCopyEvent(event);
2166             return;
2167         }
2168
2169         let tabContentView = this.tabBrowser.selectedTabContentView;
2170         if (tabContentView && typeof tabContentView.handleCopyEvent === "function") {
2171             tabContentView.handleCopyEvent(event);
2172             return;
2173         }
2174
2175         return;
2176     }
2177
2178     if (selection.isCollapsed)
2179         return;
2180
2181     // Remove word break characters from the selection before putting it on the pasteboard.
2182     var selectionString = selection.toString().removeWordBreakCharacters();
2183     event.clipboardData.setData("text/plain", selectionString);
2184     event.preventDefault();
2185 };
2186
2187 WI._increaseZoom = function(event)
2188 {
2189     const epsilon = 0.0001;
2190     const maximumZoom = 2.4;
2191     let currentZoom = this.getZoomFactor();
2192     if (currentZoom + epsilon >= maximumZoom) {
2193         InspectorFrontendHost.beep();
2194         return;
2195     }
2196
2197     this.setZoomFactor(Math.min(maximumZoom, currentZoom + 0.2));
2198 };
2199
2200 WI._decreaseZoom = function(event)
2201 {
2202     const epsilon = 0.0001;
2203     const minimumZoom = 0.6;
2204     let currentZoom = this.getZoomFactor();
2205     if (currentZoom - epsilon <= minimumZoom) {
2206         InspectorFrontendHost.beep();
2207         return;
2208     }
2209
2210     this.setZoomFactor(Math.max(minimumZoom, currentZoom - 0.2));
2211 };
2212
2213 WI._resetZoom = function(event)
2214 {
2215     this.setZoomFactor(1);
2216 };
2217
2218 WI.getZoomFactor = function()
2219 {
2220     return WI.settings.zoomFactor.value;
2221 };
2222
2223 WI.setZoomFactor = function(factor)
2224 {
2225     InspectorFrontendHost.setZoomFactor(factor);
2226     // Round-trip through the frontend host API in case the requested factor is not used.
2227     WI.settings.zoomFactor.value = InspectorFrontendHost.zoomFactor();
2228 };
2229
2230 WI.resolvedLayoutDirection = function()
2231 {
2232     let layoutDirection = WI.settings.layoutDirection.value;
2233     if (layoutDirection === WI.LayoutDirection.System)
2234         layoutDirection = InspectorFrontendHost.userInterfaceLayoutDirection();
2235
2236     return layoutDirection;
2237 };
2238
2239 WI.setLayoutDirection = function(value)
2240 {
2241     if (!Object.values(WI.LayoutDirection).includes(value))
2242         WI.reportInternalError("Unknown layout direction requested: " + value);
2243
2244     if (value === WI.settings.layoutDirection.value)
2245         return;
2246
2247     WI.settings.layoutDirection.value = value;
2248
2249     if (WI.resolvedLayoutDirection() === WI.LayoutDirection.RTL && this._dockConfiguration === WI.DockConfiguration.Right)
2250         this._dockLeft();
2251
2252     if (WI.resolvedLayoutDirection() === WI.LayoutDirection.LTR && this._dockConfiguration === WI.DockConfiguration.Left)
2253         this._dockRight();
2254
2255     InspectorFrontendHost.reopen();
2256 };
2257
2258 WI._showTabAtIndex = function(i, event)
2259 {
2260     if (i <= WI.tabBar.tabBarItems.length)
2261         WI.tabBar.selectedTabBarItem = i - 1;
2262 };
2263
2264 WI._showJavaScriptTypeInformationSettingChanged = function(event)
2265 {
2266     if (WI.settings.showJavaScriptTypeInformation.value) {
2267         for (let target of WI.targets)
2268             target.RuntimeAgent.enableTypeProfiler();
2269     } else {
2270         for (let target of WI.targets)
2271             target.RuntimeAgent.disableTypeProfiler();
2272     }
2273 };
2274
2275 WI._enableControlFlowProfilerSettingChanged = function(event)
2276 {
2277     if (WI.settings.enableControlFlowProfiler.value) {
2278         for (let target of WI.targets)
2279             target.RuntimeAgent.enableControlFlowProfiler();
2280     } else {
2281         for (let target of WI.targets)
2282             target.RuntimeAgent.disableControlFlowProfiler();
2283     }
2284 };
2285
2286 WI._resourceCachingDisabledSettingChanged = function(event)
2287 {
2288     NetworkAgent.setResourceCachingDisabled(WI.settings.resourceCachingDisabled.value);
2289 };
2290
2291 WI.elementDragStart = function(element, dividerDrag, elementDragEnd, event, cursor, eventTarget)
2292 {
2293     if (WI._elementDraggingEventListener || WI._elementEndDraggingEventListener)
2294         WI.elementDragEnd(event);
2295
2296     if (element) {
2297         // Install glass pane
2298         if (WI._elementDraggingGlassPane)
2299             WI._elementDraggingGlassPane.remove();
2300
2301         var glassPane = document.createElement("div");
2302         glassPane.style.cssText = "position:absolute;top:0;bottom:0;left:0;right:0;opacity:0;z-index:1";
2303         glassPane.id = "glass-pane-for-drag";
2304         element.ownerDocument.body.appendChild(glassPane);
2305         WI._elementDraggingGlassPane = glassPane;
2306     }
2307
2308     WI._elementDraggingEventListener = dividerDrag;
2309     WI._elementEndDraggingEventListener = elementDragEnd;
2310
2311     var targetDocument = event.target.ownerDocument;
2312
2313     WI._elementDraggingEventTarget = eventTarget || targetDocument;
2314     WI._elementDraggingEventTarget.addEventListener("mousemove", dividerDrag, true);
2315     WI._elementDraggingEventTarget.addEventListener("mouseup", elementDragEnd, true);
2316
2317     targetDocument.body.style.cursor = cursor;
2318
2319     event.preventDefault();
2320 };
2321
2322 WI.elementDragEnd = function(event)
2323 {
2324     WI._elementDraggingEventTarget.removeEventListener("mousemove", WI._elementDraggingEventListener, true);
2325     WI._elementDraggingEventTarget.removeEventListener("mouseup", WI._elementEndDraggingEventListener, true);
2326
2327     event.target.ownerDocument.body.style.removeProperty("cursor");
2328
2329     if (WI._elementDraggingGlassPane)
2330         WI._elementDraggingGlassPane.remove();
2331
2332     delete WI._elementDraggingGlassPane;
2333     delete WI._elementDraggingEventTarget;
2334     delete WI._elementDraggingEventListener;
2335     delete WI._elementEndDraggingEventListener;
2336
2337     event.preventDefault();
2338 };
2339
2340 WI.createMessageTextView = function(message, isError)
2341 {
2342     var messageElement = document.createElement("div");
2343     messageElement.className = "message-text-view";
2344     if (isError)
2345         messageElement.classList.add("error");
2346
2347     let textElement = messageElement.appendChild(document.createElement("div"));
2348     textElement.className = "message";
2349     textElement.textContent = message;
2350
2351     return messageElement;
2352 };
2353
2354 WI.createNavigationItemHelp = function(formatString, navigationItem)
2355 {
2356     console.assert(typeof formatString === "string");
2357     console.assert(navigationItem instanceof WI.NavigationItem);
2358
2359     function append(a, b) {
2360         a.append(b);
2361         return a;
2362     }
2363
2364     let containerElement = document.createElement("div");
2365     containerElement.className = "navigation-item-help";
2366     containerElement.__navigationItem = navigationItem;
2367
2368     let wrapperElement = document.createElement("div");
2369     wrapperElement.className = "navigation-bar";
2370     wrapperElement.appendChild(navigationItem.element);
2371
2372     String.format(formatString, [wrapperElement], String.standardFormatters, containerElement, append);
2373     return containerElement;
2374 };
2375
2376 WI.createGoToArrowButton = function()
2377 {
2378     var button = document.createElement("button");
2379     button.addEventListener("mousedown", (event) => { event.stopPropagation(); }, true);
2380     button.className = "go-to-arrow";
2381     button.tabIndex = -1;
2382     return button;
2383 };
2384
2385 WI.createSourceCodeLocationLink = function(sourceCodeLocation, options = {})
2386 {
2387     console.assert(sourceCodeLocation);
2388     if (!sourceCodeLocation)
2389         return null;
2390
2391     var linkElement = document.createElement("a");
2392     linkElement.className = "go-to-link";
2393     WI.linkifyElement(linkElement, sourceCodeLocation, options);
2394     sourceCodeLocation.populateLiveDisplayLocationTooltip(linkElement);
2395
2396     if (options.useGoToArrowButton)
2397         linkElement.appendChild(WI.createGoToArrowButton());
2398     else
2399         sourceCodeLocation.populateLiveDisplayLocationString(linkElement, "textContent", options.columnStyle, options.nameStyle, options.prefix);
2400
2401     if (options.dontFloat)
2402         linkElement.classList.add("dont-float");
2403
2404     return linkElement;
2405 };
2406
2407 WI.linkifyLocation = function(url, sourceCodePosition, options = {})
2408 {
2409     var sourceCode = WI.sourceCodeForURL(url);
2410
2411     if (!sourceCode) {
2412         var anchor = document.createElement("a");
2413         anchor.href = url;
2414         anchor.lineNumber = sourceCodePosition.lineNumber;
2415         if (options.className)
2416             anchor.className = options.className;
2417         anchor.append(WI.displayNameForURL(url) + ":" + sourceCodePosition.lineNumber);
2418         return anchor;
2419     }
2420
2421     let sourceCodeLocation = sourceCode.createSourceCodeLocation(sourceCodePosition.lineNumber, sourceCodePosition.columnNumber);
2422     let linkElement = WI.createSourceCodeLocationLink(sourceCodeLocation, {
2423         ...options,
2424         dontFloat: true,
2425     });
2426
2427     if (options.className)
2428         linkElement.classList.add(options.className);
2429
2430     return linkElement;
2431 };
2432
2433 WI.linkifyElement = function(linkElement, sourceCodeLocation, options = {}) {
2434     console.assert(sourceCodeLocation);
2435
2436     function showSourceCodeLocation(event)
2437     {
2438         event.stopPropagation();
2439         event.preventDefault();
2440
2441         if (event.metaKey)
2442             this.showOriginalUnformattedSourceCodeLocation(sourceCodeLocation, options);
2443         else
2444             this.showSourceCodeLocation(sourceCodeLocation, options);
2445     }
2446
2447     linkElement.addEventListener("click", showSourceCodeLocation.bind(this));
2448     linkElement.addEventListener("contextmenu", (event) => {
2449         let contextMenu = WI.ContextMenu.createFromEvent(event);
2450         WI.appendContextMenuItemsForSourceCode(contextMenu, sourceCodeLocation);
2451     });
2452 };
2453
2454 WI.sourceCodeForURL = function(url)
2455 {
2456     var sourceCode = WI.networkManager.resourceForURL(url);
2457     if (!sourceCode) {
2458         sourceCode = WI.debuggerManager.scriptsForURL(url, WI.assumingMainTarget())[0];
2459         if (sourceCode)
2460             sourceCode = sourceCode.resource || sourceCode;
2461     }
2462     return sourceCode || null;
2463 };
2464
2465 WI.linkifyURLAsNode = function(url, linkText, className)
2466 {
2467     let a = document.createElement("a");
2468     a.href = url;
2469     a.className = className || "";
2470     a.textContent = linkText || url;
2471     a.style.maxWidth = "100%";
2472     return a;
2473 };
2474
2475 WI.linkifyStringAsFragmentWithCustomLinkifier = function(string, linkifier)
2476 {
2477     var container = document.createDocumentFragment();
2478     var linkStringRegEx = /(?:[a-zA-Z][a-zA-Z0-9+.-]{2,}:\/\/|www\.)[\w$\-_+*'=\|\/\\(){}[\]%@&#~,:;.!?]{2,}[\w$\-_+*=\|\/\\({%@&#~]/;
2479     var lineColumnRegEx = /:(\d+)(:(\d+))?$/;
2480
2481     while (string) {
2482         var linkString = linkStringRegEx.exec(string);
2483         if (!linkString)
2484             break;
2485
2486         linkString = linkString[0];
2487         var linkIndex = string.indexOf(linkString);
2488         var nonLink = string.substring(0, linkIndex);
2489         container.append(nonLink);
2490
2491         if (linkString.startsWith("data:") || linkString.startsWith("javascript:") || linkString.startsWith("mailto:")) {
2492             container.append(linkString);
2493             string = string.substring(linkIndex + linkString.length, string.length);
2494             continue;
2495         }
2496
2497         var title = linkString;
2498         var realURL = linkString.startsWith("www.") ? "http://" + linkString : linkString;
2499         var lineColumnMatch = lineColumnRegEx.exec(realURL);
2500         if (lineColumnMatch)
2501             realURL = realURL.substring(0, realURL.length - lineColumnMatch[0].length);
2502
2503         var lineNumber;
2504         if (lineColumnMatch)
2505             lineNumber = parseInt(lineColumnMatch[1]) - 1;
2506
2507         var linkNode = linkifier(title, realURL, lineNumber);
2508         container.appendChild(linkNode);
2509         string = string.substring(linkIndex + linkString.length, string.length);
2510     }
2511
2512     if (string)
2513         container.append(string);
2514
2515     return container;
2516 };
2517
2518 WI.linkifyStringAsFragment = function(string)
2519 {
2520     function linkifier(title, url, lineNumber)
2521     {
2522         var urlNode = WI.linkifyURLAsNode(url, title, undefined);
2523         if (lineNumber !== undefined)
2524             urlNode.lineNumber = lineNumber;
2525
2526         return urlNode;
2527     }
2528
2529     return WI.linkifyStringAsFragmentWithCustomLinkifier(string, linkifier);
2530 };
2531
2532 WI.createResourceLink = function(resource, className)
2533 {
2534     function handleClick(event)
2535     {
2536         event.stopPropagation();
2537         event.preventDefault();
2538
2539         WI.showRepresentedObject(resource);
2540     }
2541
2542     let linkNode = document.createElement("a");
2543     linkNode.classList.add("resource-link", className);
2544     linkNode.title = resource.url;
2545     linkNode.textContent = (resource.urlComponents.lastPathComponent || resource.url).insertWordBreakCharacters();
2546     linkNode.addEventListener("click", handleClick.bind(this));
2547     return linkNode;
2548 };
2549
2550 WI._undoKeyboardShortcut = function(event)
2551 {
2552     if (!this.isEditingAnyField() && !this.isEventTargetAnEditableField(event)) {
2553         this.undo();
2554         event.preventDefault();
2555     }
2556 };
2557
2558 WI._redoKeyboardShortcut = function(event)
2559 {
2560     if (!this.isEditingAnyField() && !this.isEventTargetAnEditableField(event)) {
2561         this.redo();
2562         event.preventDefault();
2563     }
2564 };
2565
2566 WI.undo = function()
2567 {
2568     DOMAgent.undo();
2569 };
2570
2571 WI.redo = function()
2572 {
2573     DOMAgent.redo();
2574 };
2575
2576 WI.highlightRangesWithStyleClass = function(element, resultRanges, styleClass, changes)
2577 {
2578     changes = changes || [];
2579     var highlightNodes = [];
2580     var lineText = element.textContent;
2581     var ownerDocument = element.ownerDocument;
2582     var textNodeSnapshot = ownerDocument.evaluate(".//text()", element, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
2583
2584     var snapshotLength = textNodeSnapshot.snapshotLength;
2585     if (snapshotLength === 0)
2586         return highlightNodes;
2587
2588     var nodeRanges = [];
2589     var rangeEndOffset = 0;
2590     for (var i = 0; i < snapshotLength; ++i) {
2591         var range = {};
2592         range.offset = rangeEndOffset;
2593         range.length = textNodeSnapshot.snapshotItem(i).textContent.length;
2594         rangeEndOffset = range.offset + range.length;
2595         nodeRanges.push(range);
2596     }
2597
2598     var startIndex = 0;
2599     for (var i = 0; i < resultRanges.length; ++i) {
2600         var startOffset = resultRanges[i].offset;
2601         var endOffset = startOffset + resultRanges[i].length;
2602
2603         while (startIndex < snapshotLength && nodeRanges[startIndex].offset + nodeRanges[startIndex].length <= startOffset)
2604             startIndex++;
2605         var endIndex = startIndex;
2606         while (endIndex < snapshotLength && nodeRanges[endIndex].offset + nodeRanges[endIndex].length < endOffset)
2607             endIndex++;
2608         if (endIndex === snapshotLength)
2609             break;
2610
2611         var highlightNode = ownerDocument.createElement("span");
2612         highlightNode.className = styleClass;
2613         highlightNode.textContent = lineText.substring(startOffset, endOffset);
2614
2615         var lastTextNode = textNodeSnapshot.snapshotItem(endIndex);
2616         var lastText = lastTextNode.textContent;
2617         lastTextNode.textContent = lastText.substring(endOffset - nodeRanges[endIndex].offset);
2618         changes.push({node: lastTextNode, type: "changed", oldText: lastText, newText: lastTextNode.textContent});
2619
2620         if (startIndex === endIndex) {
2621             lastTextNode.parentElement.insertBefore(highlightNode, lastTextNode);
2622             changes.push({node: highlightNode, type: "added", nextSibling: lastTextNode, parent: lastTextNode.parentElement});
2623             highlightNodes.push(highlightNode);
2624
2625             var prefixNode = ownerDocument.createTextNode(lastText.substring(0, startOffset - nodeRanges[startIndex].offset));
2626             lastTextNode.parentElement.insertBefore(prefixNode, highlightNode);
2627             changes.push({node: prefixNode, type: "added", nextSibling: highlightNode, parent: lastTextNode.parentElement});
2628         } else {
2629             var firstTextNode = textNodeSnapshot.snapshotItem(startIndex);
2630             var firstText = firstTextNode.textContent;
2631             var anchorElement = firstTextNode.nextSibling;
2632
2633             firstTextNode.parentElement.insertBefore(highlightNode, anchorElement);
2634             changes.push({node: highlightNode, type: "added", nextSibling: anchorElement, parent: firstTextNode.parentElement});
2635             highlightNodes.push(highlightNode);
2636
2637             firstTextNode.textContent = firstText.substring(0, startOffset - nodeRanges[startIndex].offset);
2638             changes.push({node: firstTextNode, type: "changed", oldText: firstText, newText: firstTextNode.textContent});
2639
2640             for (var j = startIndex + 1; j < endIndex; j++) {
2641                 var textNode = textNodeSnapshot.snapshotItem(j);
2642                 var text = textNode.textContent;
2643                 textNode.textContent = "";
2644                 changes.push({node: textNode, type: "changed", oldText: text, newText: textNode.textContent});
2645             }
2646         }
2647         startIndex = endIndex;
2648         nodeRanges[startIndex].offset = endOffset;
2649         nodeRanges[startIndex].length = lastTextNode.textContent.length;
2650
2651     }
2652     return highlightNodes;
2653 };
2654
2655 WI.revertDOMChanges = function(domChanges)
2656 {
2657     for (var i = domChanges.length - 1; i >= 0; --i) {
2658         var entry = domChanges[i];
2659         switch (entry.type) {
2660         case "added":
2661             entry.node.remove();
2662             break;
2663         case "changed":
2664             entry.node.textContent = entry.oldText;
2665             break;
2666         }
2667     }
2668 };
2669
2670 WI.archiveMainFrame = function()
2671 {
2672     this._downloadingPage = true;
2673     this._updateDownloadToolbarButton();
2674
2675     PageAgent.archive((error, data) => {
2676         this._downloadingPage = false;
2677         this._updateDownloadToolbarButton();
2678
2679         if (error)
2680             return;
2681
2682         let mainFrame = WI.networkManager.mainFrame;
2683         let archiveName = mainFrame.mainResource.urlComponents.host || mainFrame.mainResource.displayName || "Archive";
2684         let url = "web-inspector:///" + encodeURI(archiveName) + ".webarchive";
2685
2686         InspectorFrontendHost.save(url, data, true, true);
2687     });
2688 };
2689
2690 WI.canArchiveMainFrame = function()
2691 {
2692     if (this.sharedApp.debuggableType !== WI.DebuggableType.Web)
2693         return false;
2694
2695     if (!WI.networkManager.mainFrame || !WI.networkManager.mainFrame.mainResource)
2696         return false;
2697
2698     return WI.Resource.typeFromMIMEType(WI.networkManager.mainFrame.mainResource.mimeType) === WI.Resource.Type.Document;
2699 };
2700
2701 WI.addWindowKeydownListener = function(listener)
2702 {
2703     if (typeof listener.handleKeydownEvent !== "function")
2704         return;
2705
2706     this._windowKeydownListeners.push(listener);
2707
2708     this._updateWindowKeydownListener();
2709 };
2710
2711 WI.removeWindowKeydownListener = function(listener)
2712 {
2713     this._windowKeydownListeners.remove(listener);
2714
2715     this._updateWindowKeydownListener();
2716 };
2717
2718 WI._updateWindowKeydownListener = function()
2719 {
2720     if (this._windowKeydownListeners.length === 1)
2721         window.addEventListener("keydown", WI._sharedWindowKeydownListener, true);
2722     else if (!this._windowKeydownListeners.length)
2723         window.removeEventListener("keydown", WI._sharedWindowKeydownListener, true);
2724 };
2725
2726 WI._sharedWindowKeydownListener = function(event)
2727 {
2728     for (var i = WI._windowKeydownListeners.length - 1; i >= 0; --i) {
2729         if (WI._windowKeydownListeners[i].handleKeydownEvent(event)) {
2730             event.stopImmediatePropagation();
2731             event.preventDefault();
2732             break;
2733         }
2734     }
2735 };
2736
2737 WI.reportInternalError = function(errorOrString, details = {})
2738 {
2739     // The 'details' object includes additional information from the caller as free-form string keys and values.
2740     // Each key and value will be shown in the uncaught exception reporter, console error message, or in
2741     // a pre-filled bug report generated for this internal error.
2742
2743     let error = errorOrString instanceof Error ? errorOrString : new Error(errorOrString);
2744     error.details = details;
2745
2746     // The error will be displayed in the Uncaught Exception Reporter sheet if DebugUI is enabled.
2747     if (WI.isDebugUIEnabled()) {
2748         // This assert allows us to stop the debugger at an internal exception. It doesn't re-throw
2749         // exceptions because the original exception would be lost through window.onerror.
2750         // This workaround can be removed once <https://webkit.org/b/158192> is fixed.
2751         console.assert(false, "An internal exception was thrown.", error);
2752         handleInternalException(error);
2753     } else
2754         console.error(error);
2755 };
2756
2757 // Many places assume the "main" target has resources.
2758 // In the case where the main backend target is a MultiplexingBackendTarget
2759 // that target has essentially nothing. In that case defer to the page
2760 // target, since that is the real "main" target the frontend is assuming.
2761 Object.defineProperty(WI, "mainTarget",
2762 {
2763     get() { return WI.pageTarget || WI.backendTarget; }
2764 });
2765
2766 // This list of targets are non-Multiplexing targets.
2767 // So if there is a multiplexing target, and multiple sub-targets
2768 // this is just the list of sub-targets. Almost no code expects
2769 // to actually interact with the Multiplexing target.
2770 Object.defineProperty(WI, "targets",
2771 {
2772     get() { return WI.targetManager.targets; }
2773 });
2774
2775 // Many places assume the main target because they cannot yet be
2776 // used by reached by Worker debugging. Eventually, once all
2777 // Worker domains have been implemented, all of these must be
2778 // handled properly.
2779 WI.assumingMainTarget = function()
2780 {
2781     return WI.mainTarget;
2782 };
2783
2784 WI.isEngineeringBuild = false;
2785
2786 // OpenResourceDialog delegate
2787
2788 WI.dialogWasDismissedWithRepresentedObject = function(dialog, representedObject)
2789 {
2790     if (!representedObject)
2791         return;
2792
2793     WI.showRepresentedObject(representedObject, dialog.cookie);
2794 };
2795
2796 WI.DockConfiguration = {
2797     Right: "right",
2798     Left: "left",
2799     Bottom: "bottom",
2800     Undocked: "undocked",
2801 };