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