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