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