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