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