Web Inspector: drag/drop over the sidebar should load an imported file in Canvas...
[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
273     document.addEventListener("click", WI._mouseWasClicked);
274     document.addEventListener("dragover", WI._handleDragOver);
275     document.addEventListener("drop", WI._handleDrop);
276     document.addEventListener("focus", WI._focusChanged, true);
277
278     window.addEventListener("focus", WI._windowFocused);
279     window.addEventListener("blur", WI._windowBlurred);
280     window.addEventListener("resize", WI._windowResized);
281     window.addEventListener("keydown", WI._windowKeyDown);
282     window.addEventListener("keyup", WI._windowKeyUp);
283     window.addEventListener("mousedown", WI._mouseDown, true);
284     window.addEventListener("mousemove", WI._mouseMoved, true);
285     window.addEventListener("pagehide", WI._pageHidden);
286     window.addEventListener("contextmenu", WI._contextMenuRequested);
287
288     // Add platform style classes so the UI can be tweaked per-platform.
289     document.body.classList.add(WI.Platform.name + "-platform");
290     if (WI.Platform.isNightlyBuild)
291         document.body.classList.add("nightly-build");
292
293     if (WI.Platform.name === "mac") {
294         document.body.classList.add(WI.Platform.version.name);
295
296         if (WI.Platform.version.release >= 11)
297             document.body.classList.add("latest-mac");
298         else
299             document.body.classList.add("legacy-mac");
300     }
301
302     document.body.classList.add(WI.sharedApp.debuggableType);
303     document.body.setAttribute("dir", WI.resolvedLayoutDirection());
304
305     WI.settings.showJavaScriptTypeInformation.addEventListener(WI.Setting.Event.Changed, WI._showJavaScriptTypeInformationSettingChanged);
306     WI.settings.enableControlFlowProfiler.addEventListener(WI.Setting.Event.Changed, WI._enableControlFlowProfilerSettingChanged);
307     WI.settings.resourceCachingDisabled.addEventListener(WI.Setting.Event.Changed, WI._resourceCachingDisabledSettingChanged);
308
309     function setTabSize() {
310         document.body.style.tabSize = WI.settings.tabSize.value;
311     }
312     WI.settings.tabSize.addEventListener(WI.Setting.Event.Changed, setTabSize);
313     setTabSize();
314
315     function setInvalidCharacterClassName() {
316         document.body.classList.toggle("show-invalid-characters", WI.settings.showInvalidCharacters.value);
317     }
318     WI.settings.showInvalidCharacters.addEventListener(WI.Setting.Event.Changed, setInvalidCharacterClassName);
319     setInvalidCharacterClassName();
320
321     function setWhitespaceCharacterClassName() {
322         document.body.classList.toggle("show-whitespace-characters", WI.settings.showWhitespaceCharacters.value);
323     }
324     WI.settings.showWhitespaceCharacters.addEventListener(WI.Setting.Event.Changed, setWhitespaceCharacterClassName);
325     setWhitespaceCharacterClassName();
326
327     WI.settingsTabContentView = new WI.SettingsTabContentView;
328
329     WI._settingsKeyboardShortcut = new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl, WI.KeyboardShortcut.Key.Comma, WI._showSettingsTab);
330
331     // Create the user interface elements.
332     WI.toolbar = new WI.Toolbar(document.getElementById("toolbar"));
333
334     if (WI.settings.experimentalEnableNewTabBar.value)
335         WI.tabBar = new WI.TabBar(document.getElementById("tab-bar"));
336     else {
337         WI.tabBar = new WI.LegacyTabBar(document.getElementById("tab-bar"));
338         WI.tabBar.addEventListener(WI.TabBar.Event.OpenDefaultTab, WI._openDefaultTab);
339     }
340
341     WI._contentElement = document.getElementById("content");
342     WI._contentElement.setAttribute("role", "main");
343     WI._contentElement.setAttribute("aria-label", WI.UIString("Content"));
344
345     WI.clearKeyboardShortcut = new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl, "K", WI._clear);
346
347     // FIXME: <https://webkit.org/b/151310> Web Inspector: Command-E should propagate to other search fields (including the system)
348     WI.populateFindKeyboardShortcut = new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl, "E", WI._populateFind);
349     WI.populateFindKeyboardShortcut.implicitlyPreventsDefault = false;
350     WI.findNextKeyboardShortcut = new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl, "G", WI._findNext);
351     WI.findPreviousKeyboardShortcut = new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.Shift | WI.KeyboardShortcut.Modifier.CommandOrControl, "G", WI._findPrevious);
352
353     WI.consoleDrawer = new WI.ConsoleDrawer(document.getElementById("console-drawer"));
354     WI.consoleDrawer.addEventListener(WI.ConsoleDrawer.Event.CollapsedStateChanged, WI._consoleDrawerCollapsedStateDidChange);
355     WI.consoleDrawer.addEventListener(WI.ConsoleDrawer.Event.Resized, WI._consoleDrawerDidResize);
356
357     WI.quickConsole = new WI.QuickConsole(document.getElementById("quick-console"));
358
359     WI._consoleRepresentedObject = new WI.LogObject;
360     WI.consoleContentView = WI.consoleDrawer.contentViewForRepresentedObject(WI._consoleRepresentedObject);
361     WI.consoleLogViewController = WI.consoleContentView.logViewController;
362     WI.breakpointPopoverController = new WI.BreakpointPopoverController;
363
364     // FIXME: The sidebars should be flipped in RTL languages.
365     WI.navigationSidebar = new WI.Sidebar(document.getElementById("navigation-sidebar"), WI.Sidebar.Sides.Left);
366     WI.navigationSidebar.addEventListener(WI.Sidebar.Event.WidthDidChange, WI._sidebarWidthDidChange);
367
368     WI.detailsSidebar = new WI.Sidebar(document.getElementById("details-sidebar"), WI.Sidebar.Sides.Right, null, null, WI.UIString("Details"), true);
369     WI.detailsSidebar.addEventListener(WI.Sidebar.Event.WidthDidChange, WI._sidebarWidthDidChange);
370
371     WI.searchKeyboardShortcut = new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl | WI.KeyboardShortcut.Modifier.Shift, "F", WI._focusSearchField);
372     WI._findKeyboardShortcut = new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl, "F", WI._find);
373     WI.saveKeyboardShortcut = new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl, "S", WI._save);
374     WI._saveAsKeyboardShortcut = new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.Shift | WI.KeyboardShortcut.Modifier.CommandOrControl, "S", WI._saveAs);
375
376     WI.openResourceKeyboardShortcut = new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl | WI.KeyboardShortcut.Modifier.Shift, "O", WI._showOpenResourceDialog);
377     new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl, "P", WI._showOpenResourceDialog);
378
379     WI.navigationSidebarKeyboardShortcut = new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl | WI.KeyboardShortcut.Modifier.Shift, "0", WI.toggleNavigationSidebar);
380     WI.detailsSidebarKeyboardShortcut = new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl | WI.KeyboardShortcut.Modifier.Option, "0", WI.toggleDetailsSidebar);
381
382     let boundIncreaseZoom = WI._increaseZoom;
383     let boundDecreaseZoom = WI._decreaseZoom;
384     WI._increaseZoomKeyboardShortcut = new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl, WI.KeyboardShortcut.Key.Plus, boundIncreaseZoom);
385     WI._decreaseZoomKeyboardShortcut = new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl, WI.KeyboardShortcut.Key.Minus, boundDecreaseZoom);
386     WI._increaseZoomKeyboardShortcut2 = new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl | WI.KeyboardShortcut.Modifier.Shift, WI.KeyboardShortcut.Key.Plus, boundIncreaseZoom);
387     WI._decreaseZoomKeyboardShortcut2 = new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl | WI.KeyboardShortcut.Modifier.Shift, WI.KeyboardShortcut.Key.Minus, boundDecreaseZoom);
388     WI._resetZoomKeyboardShortcut = new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl, "0", WI._resetZoom);
389
390     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); }));
391     WI._openNewTabKeyboardShortcut = new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl | WI.KeyboardShortcut.Modifier.Option, "T", WI.showNewTabTab);
392
393     WI.tabBrowser = new WI.TabBrowser(document.getElementById("tab-browser"), WI.tabBar, WI.navigationSidebar, WI.detailsSidebar);
394     WI.tabBrowser.addEventListener(WI.TabBrowser.Event.SelectedTabContentViewDidChange, WI._tabBrowserSelectedTabContentViewDidChange);
395
396     WI._reloadPageKeyboardShortcut = new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl, "R", WI._reloadPage);
397     WI._reloadPageFromOriginKeyboardShortcut = new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl | WI.KeyboardShortcut.Modifier.Option, "R", WI._reloadPageFromOrigin);
398     WI._reloadPageKeyboardShortcut.implicitlyPreventsDefault = WI._reloadPageFromOriginKeyboardShortcut.implicitlyPreventsDefault = false;
399
400     WI._consoleTabKeyboardShortcut = new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.Option | WI.KeyboardShortcut.Modifier.CommandOrControl, "C", WI._showConsoleTab);
401     WI._quickConsoleKeyboardShortcut = new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.Control, WI.KeyboardShortcut.Key.Apostrophe, WI._focusConsolePrompt);
402
403     WI._inspectModeKeyboardShortcut = new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl | WI.KeyboardShortcut.Modifier.Shift, "C", WI._toggleInspectMode);
404
405     WI._undoKeyboardShortcut = new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl, "Z", WI._undoKeyboardShortcut);
406     WI._redoKeyboardShortcut = new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl | WI.KeyboardShortcut.Modifier.Shift, "Z", WI._redoKeyboardShortcut);
407     WI._undoKeyboardShortcut.implicitlyPreventsDefault = WI._redoKeyboardShortcut.implicitlyPreventsDefault = false;
408
409     WI.toggleBreakpointsKeyboardShortcut = new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl, "Y", WI.debuggerToggleBreakpoints);
410     WI.pauseOrResumeKeyboardShortcut = new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.Control | WI.KeyboardShortcut.Modifier.CommandOrControl, "Y", WI.debuggerPauseResumeToggle);
411     WI.stepOverKeyboardShortcut = new WI.KeyboardShortcut(null, WI.KeyboardShortcut.Key.F6, WI.debuggerStepOver);
412     WI.stepIntoKeyboardShortcut = new WI.KeyboardShortcut(null, WI.KeyboardShortcut.Key.F7, WI.debuggerStepInto);
413     WI.stepOutKeyboardShortcut = new WI.KeyboardShortcut(null, WI.KeyboardShortcut.Key.F8, WI.debuggerStepOut);
414
415     WI.pauseOrResumeAlternateKeyboardShortcut = new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl, WI.KeyboardShortcut.Key.Backslash, WI.debuggerPauseResumeToggle);
416     WI.stepOverAlternateKeyboardShortcut = new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl, WI.KeyboardShortcut.Key.SingleQuote, WI.debuggerStepOver);
417     WI.stepIntoAlternateKeyboardShortcut = new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl, WI.KeyboardShortcut.Key.Semicolon, WI.debuggerStepInto);
418     WI.stepOutAlternateKeyboardShortcut = new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.Shift | WI.KeyboardShortcut.Modifier.CommandOrControl, WI.KeyboardShortcut.Key.Semicolon, WI.debuggerStepOut);
419
420     WI._closeToolbarButton = new WI.ControlToolbarItem("dock-close", WI.UIString("Close"), "Images/Close.svg", 16, 14);
421     WI._closeToolbarButton.addEventListener(WI.ButtonNavigationItem.Event.Clicked, WI.close);
422
423     WI._undockToolbarButton = new WI.ButtonToolbarItem("undock", WI.UIString("Detach into separate window"), "Images/Undock.svg");
424     WI._undockToolbarButton.element.classList.add(WI.Popover.IgnoreAutoDismissClassName);
425     WI._undockToolbarButton.addEventListener(WI.ButtonNavigationItem.Event.Clicked, WI._undock);
426
427     let dockImage = WI.resolvedLayoutDirection() === WI.LayoutDirection.RTL ? "Images/DockLeft.svg" : "Images/DockRight.svg";
428     WI._dockToSideToolbarButton = new WI.ButtonToolbarItem("dock-right", WI.UIString("Dock to side of window"), dockImage);
429     WI._dockToSideToolbarButton.element.classList.add(WI.Popover.IgnoreAutoDismissClassName);
430
431     let dockToSideCallback = WI.resolvedLayoutDirection() === WI.LayoutDirection.RTL ? WI._dockLeft : WI._dockRight;
432     WI._dockToSideToolbarButton.addEventListener(WI.ButtonNavigationItem.Event.Clicked, dockToSideCallback);
433
434     WI._dockBottomToolbarButton = new WI.ButtonToolbarItem("dock-bottom", WI.UIString("Dock to bottom of window"), "Images/DockBottom.svg");
435     WI._dockBottomToolbarButton.element.classList.add(WI.Popover.IgnoreAutoDismissClassName);
436     WI._dockBottomToolbarButton.addEventListener(WI.ButtonNavigationItem.Event.Clicked, WI._dockBottom);
437
438     WI._togglePreviousDockConfigurationKeyboardShortcut = new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl | WI.KeyboardShortcut.Modifier.Shift, "D", WI._togglePreviousDockConfiguration);
439
440     let reloadToolTip;
441     if (WI.sharedApp.debuggableType === WI.DebuggableType.JavaScript)
442         reloadToolTip = WI.UIString("Restart (%s)").format(WI._reloadPageKeyboardShortcut.displayName);
443     else
444         reloadToolTip = WI.UIString("Reload page (%s)\nReload page ignoring cache (%s)").format(WI._reloadPageKeyboardShortcut.displayName, WI._reloadPageFromOriginKeyboardShortcut.displayName);
445     WI._reloadToolbarButton = new WI.ButtonToolbarItem("reload", reloadToolTip, "Images/ReloadToolbar.svg");
446     WI._reloadToolbarButton.addEventListener(WI.ButtonNavigationItem.Event.Clicked, WI._reloadToolbarButtonClicked);
447
448     WI._downloadToolbarButton = new WI.ButtonToolbarItem("download", WI.UIString("Download Web Archive"), "Images/DownloadArrow.svg");
449     WI._downloadToolbarButton.addEventListener(WI.ButtonNavigationItem.Event.Clicked, WI._downloadWebArchive);
450
451     let elementSelectionToolTip = WI.UIString("Start element selection (%s)").format(WI._inspectModeKeyboardShortcut.displayName);
452     let activatedElementSelectionToolTip = WI.UIString("Stop element selection (%s)").format(WI._inspectModeKeyboardShortcut.displayName);
453     WI._inspectModeToolbarButton = new WI.ActivateButtonToolbarItem("inspect", elementSelectionToolTip, activatedElementSelectionToolTip, "Images/Crosshair.svg");
454     WI._inspectModeToolbarButton.addEventListener(WI.ButtonNavigationItem.Event.Clicked, WI._toggleInspectMode);
455
456     // COMPATIBILITY (iOS 12.2): Page.overrideSetting did not exist.
457     if (InspectorFrontendHost.isRemote && WI.sharedApp.debuggableType === WI.DebuggableType.Web && InspectorBackend.domains.Page && InspectorBackend.domains.Page.overrideUserAgent && InspectorBackend.domains.Page.overrideSetting) {
458         const deviceSettingsTooltip = WI.UIString("Device Settings");
459         WI._deviceSettingsToolbarButton = new WI.ActivateButtonToolbarItem("device-settings", deviceSettingsTooltip, deviceSettingsTooltip, "Images/Device.svg");
460         WI._deviceSettingsToolbarButton.addEventListener(WI.ButtonNavigationItem.Event.Clicked, WI._handleDeviceSettingsToolbarButtonClicked);
461
462         WI._deviceSettingsPopover = null;
463     }
464
465     WI._updateReloadToolbarButton();
466     WI._updateDownloadToolbarButton();
467     WI._updateInspectModeToolbarButton();
468
469     WI._dashboards = {
470         default: new WI.DefaultDashboard,
471         debugger: new WI.DebuggerDashboard,
472     };
473
474     WI._dashboardContainer = new WI.DashboardContainerView;
475     WI._dashboardContainer.showDashboardViewForRepresentedObject(WI._dashboards.default);
476
477     WI.toolbar.addToolbarItem(WI._closeToolbarButton, WI.Toolbar.Section.Control);
478
479     WI.toolbar.addToolbarItem(WI._undockToolbarButton, WI.Toolbar.Section.Left);
480     WI.toolbar.addToolbarItem(WI._dockToSideToolbarButton, WI.Toolbar.Section.Left);
481     WI.toolbar.addToolbarItem(WI._dockBottomToolbarButton, WI.Toolbar.Section.Left);
482
483     WI.toolbar.addToolbarItem(WI._reloadToolbarButton, WI.Toolbar.Section.CenterLeft);
484     WI.toolbar.addToolbarItem(WI._downloadToolbarButton, WI.Toolbar.Section.CenterLeft);
485
486     WI.toolbar.addToolbarItem(WI._dashboardContainer.toolbarItem, WI.Toolbar.Section.Center);
487
488     WI.toolbar.addToolbarItem(WI._inspectModeToolbarButton, WI.Toolbar.Section.CenterRight);
489
490     if (WI._deviceSettingsToolbarButton)
491         WI.toolbar.addToolbarItem(WI._deviceSettingsToolbarButton, WI.Toolbar.Section.CenterRight);
492
493     WI._searchTabContentView = new WI.SearchTabContentView;
494
495     if (WI.settings.experimentalEnableNewTabBar.value) {
496         WI.tabBrowser.addTabForContentView(WI._searchTabContentView, {suppressAnimations: true});
497         WI.tabBar.addTabBarItem(WI.settingsTabContentView.tabBarItem, {suppressAnimations: true});
498     } else {
499         const incremental = false;
500         WI._searchToolbarItem = new WI.SearchBar("inspector-search", WI.UIString("Search"), incremental);
501         WI._searchToolbarItem.addEventListener(WI.SearchBar.Event.TextChanged, WI._searchTextDidChange);
502         WI.toolbar.addToolbarItem(WI._searchToolbarItem, WI.Toolbar.Section.Right);
503     }
504
505     let dockedResizerElement = document.getElementById("docked-resizer");
506     dockedResizerElement.classList.add(WI.Popover.IgnoreAutoDismissClassName);
507     dockedResizerElement.addEventListener("mousedown", WI._dockedResizerMouseDown);
508
509     WI._dockingAvailable = false;
510
511     WI._updateDockNavigationItems();
512     WI._setupViewHierarchy();
513
514     // These tabs are always available for selecting, modulo isTabAllowed().
515     // Other tabs may be engineering-only or toggled at runtime if incomplete.
516     let productionTabClasses = [
517         WI.ElementsTabContentView,
518         WI.NetworkTabContentView,
519         WI.SourcesTabContentView,
520         WI.DebuggerTabContentView,
521         WI.ResourcesTabContentView,
522         WI.TimelineTabContentView,
523         WI.StorageTabContentView,
524         WI.CanvasTabContentView,
525         WI.LayersTabContentView,
526         WI.AuditTabContentView,
527         WI.ConsoleTabContentView,
528         WI.SearchTabContentView,
529         WI.NewTabContentView,
530         WI.SettingsTabContentView,
531     ];
532
533     WI._knownTabClassesByType = new Map;
534     // Set tab classes directly. The public API triggers other updates and
535     // notifications that won't work or have no listeners at WI point.
536     for (let tabClass of productionTabClasses)
537         WI._knownTabClassesByType.set(tabClass.Type, tabClass);
538
539     WI._pendingOpenTabs = [];
540
541     // Previously we may have stored duplicates in WI setting. Avoid creating duplicate tabs.
542     let openTabTypes = WI._openTabsSetting.value;
543     let seenTabTypes = new Set;
544
545     for (let i = 0; i < openTabTypes.length; ++i) {
546         let tabType = openTabTypes[i];
547
548         if (seenTabTypes.has(tabType))
549             continue;
550         seenTabTypes.add(tabType);
551
552         if (!WI.isTabTypeAllowed(tabType)) {
553             WI._pendingOpenTabs.push({tabType, index: i});
554             continue;
555         }
556
557         if (!WI.isNewTabWithTypeAllowed(tabType))
558             continue;
559
560         let tabContentView = WI._createTabContentViewForType(tabType);
561         if (!tabContentView)
562             continue;
563         WI.tabBrowser.addTabForContentView(tabContentView, {suppressAnimations: true});
564     }
565
566     WI._restoreCookieForOpenTabs(WI.StateRestorationType.Load);
567
568     WI.tabBar.selectedTabBarItem = WI._selectedTabIndexSetting.value;
569
570     if (!WI.tabBar.selectedTabBarItem)
571         WI.tabBar.selectedTabBarItem = 0;
572
573     if (!WI.tabBar.normalTabCount)
574         WI.showNewTabTab({suppressAnimations: true});
575
576     // Listen to the events after restoring the saved tabs to avoid recursion.
577     WI.tabBar.addEventListener(WI.TabBar.Event.TabBarItemAdded, WI._rememberOpenTabs);
578     WI.tabBar.addEventListener(WI.TabBar.Event.TabBarItemRemoved, WI._rememberOpenTabs);
579     WI.tabBar.addEventListener(WI.TabBar.Event.TabBarItemsReordered, WI._rememberOpenTabs);
580
581     // Signal that the frontend is now ready to receive messages.
582     WI.whenTargetsAvailable().then(() => {
583         InspectorFrontendAPI.loadCompleted();
584     });
585
586     let mainElementRect = document.getElementById("main").getBoundingClientRect();
587     InspectorFrontendHost.setSheetRect(mainElementRect.x, mainElementRect.y, mainElementRect.width, mainElementRect.height);
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.RequestIdentifier}, 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 };
1682
1683 WI._updateModifierKeys = function(event)
1684 {
1685     let keys = {
1686         altKey: event.altKey,
1687         metaKey: event.metaKey,
1688         ctrlKey: event.ctrlKey,
1689         shiftKey: event.shiftKey,
1690     };
1691
1692     let changed = !Object.shallowEqual(WI.modifierKeys, keys);
1693
1694     WI.modifierKeys = keys;
1695
1696     document.body.classList.toggle("alt-key-pressed", WI.modifierKeys.altKey);
1697     document.body.classList.toggle("ctrl-key-pressed", WI.modifierKeys.ctrlKey);
1698     document.body.classList.toggle("meta-key-pressed", WI.modifierKeys.metaKey);
1699     document.body.classList.toggle("shift-key-pressed", WI.modifierKeys.shiftKey);
1700
1701     if (changed)
1702         WI.notifications.dispatchEventToListeners(WI.Notification.GlobalModifierKeysDidChange, event);
1703 };
1704
1705 WI._windowKeyDown = function(event)
1706 {
1707     WI._updateModifierKeys(event);
1708 };
1709
1710 WI._windowKeyUp = function(event)
1711 {
1712     WI._updateModifierKeys(event);
1713 };
1714
1715 WI._mouseDown = function(event)
1716 {
1717     if (WI.toolbar.element.contains(event.target))
1718         WI._toolbarMouseDown(event);
1719 };
1720
1721 WI._mouseMoved = function(event)
1722 {
1723     WI._updateModifierKeys(event);
1724     WI.mouseCoords = {
1725         x: event.pageX,
1726         y: event.pageY
1727     };
1728 };
1729
1730 WI._pageHidden = function(event)
1731 {
1732     WI._saveCookieForOpenTabs();
1733 };
1734
1735 WI._contextMenuRequested = function(event)
1736 {
1737     let proposedContextMenu;
1738
1739     // This is setting is only defined in engineering builds.
1740     if (WI.isDebugUIEnabled()) {
1741         proposedContextMenu = WI.ContextMenu.createFromEvent(event);
1742         proposedContextMenu.appendSeparator();
1743         proposedContextMenu.appendItem(WI.unlocalizedString("Reload Web Inspector"), () => {
1744             InspectorFrontendHost.reopen();
1745         });
1746
1747         let protocolSubMenu = proposedContextMenu.appendSubMenuItem(WI.unlocalizedString("Protocol Debugging"), null, false);
1748         let isCapturingTraffic = InspectorBackend.activeTracer instanceof WI.CapturingProtocolTracer;
1749
1750         protocolSubMenu.appendCheckboxItem(WI.unlocalizedString("Capture Trace"), () => {
1751             if (isCapturingTraffic)
1752                 InspectorBackend.activeTracer = null;
1753             else
1754                 InspectorBackend.activeTracer = new WI.CapturingProtocolTracer;
1755         }, isCapturingTraffic);
1756
1757         protocolSubMenu.appendSeparator();
1758
1759         protocolSubMenu.appendItem(WI.unlocalizedString("Export Trace\u2026"), () => {
1760             const forceSaveAs = true;
1761             WI.FileUtilities.save(InspectorBackend.activeTracer.trace.saveData, forceSaveAs);
1762         }, !isCapturingTraffic);
1763     } else {
1764         const onlyExisting = true;
1765         proposedContextMenu = WI.ContextMenu.createFromEvent(event, onlyExisting);
1766     }
1767
1768     if (proposedContextMenu)
1769         proposedContextMenu.show();
1770 };
1771
1772 WI.isDebugUIEnabled = function()
1773 {
1774     return WI.showDebugUISetting && WI.showDebugUISetting.value;
1775 };
1776
1777 WI._undock = function(event)
1778 {
1779     InspectorFrontendHost.requestSetDockSide(WI.DockConfiguration.Undocked);
1780 };
1781
1782 WI._dockBottom = function(event)
1783 {
1784     InspectorFrontendHost.requestSetDockSide(WI.DockConfiguration.Bottom);
1785 };
1786
1787 WI._dockRight = function(event)
1788 {
1789     InspectorFrontendHost.requestSetDockSide(WI.DockConfiguration.Right);
1790 };
1791
1792 WI._dockLeft = function(event)
1793 {
1794     InspectorFrontendHost.requestSetDockSide(WI.DockConfiguration.Left);
1795 };
1796
1797 WI._togglePreviousDockConfiguration = function(event)
1798 {
1799     InspectorFrontendHost.requestSetDockSide(WI._previousDockConfiguration);
1800 };
1801
1802 WI._updateDockNavigationItems = function()
1803 {
1804     if (WI._dockingAvailable || WI.docked) {
1805         WI._closeToolbarButton.hidden = !WI.docked;
1806         WI._undockToolbarButton.hidden = WI._dockConfiguration === WI.DockConfiguration.Undocked;
1807         WI._dockBottomToolbarButton.hidden = WI._dockConfiguration === WI.DockConfiguration.Bottom;
1808         WI._dockToSideToolbarButton.hidden = WI._dockConfiguration === WI.DockConfiguration.Right || WI._dockConfiguration === WI.DockConfiguration.Left;
1809     } else {
1810         WI._closeToolbarButton.hidden = true;
1811         WI._undockToolbarButton.hidden = true;
1812         WI._dockBottomToolbarButton.hidden = true;
1813         WI._dockToSideToolbarButton.hidden = true;
1814     }
1815 };
1816
1817 WI._tabBrowserSizeDidChange = function()
1818 {
1819     WI.tabBrowser.updateLayout(WI.View.LayoutReason.Resize);
1820     WI.consoleDrawer.updateLayout(WI.View.LayoutReason.Resize);
1821     WI.quickConsole.updateLayout(WI.View.LayoutReason.Resize);
1822 };
1823
1824 WI._consoleDrawerCollapsedStateDidChange = function(event)
1825 {
1826     WI._showingSplitConsoleSetting.value = WI.isShowingSplitConsole();
1827
1828     WI._consoleDrawerDidResize();
1829 };
1830
1831 WI._consoleDrawerDidResize = function(event)
1832 {
1833     WI.tabBrowser.updateLayout(WI.View.LayoutReason.Resize);
1834 };
1835
1836 WI._sidebarWidthDidChange = function(event)
1837 {
1838     WI._tabBrowserSizeDidChange();
1839 };
1840
1841 WI._setupViewHierarchy = function()
1842 {
1843     let rootView = WI.View.rootView();
1844     rootView.addSubview(WI.toolbar);
1845     rootView.addSubview(WI.tabBar);
1846     rootView.addSubview(WI.navigationSidebar);
1847     rootView.addSubview(WI.tabBrowser);
1848     rootView.addSubview(WI.consoleDrawer);
1849     rootView.addSubview(WI.quickConsole);
1850     rootView.addSubview(WI.detailsSidebar);
1851 };
1852
1853 WI._tabBrowserSelectedTabContentViewDidChange = function(event)
1854 {
1855     if (WI.tabBar.selectedTabBarItem && WI.tabBar.selectedTabBarItem.representedObject.constructor.shouldSaveTab())
1856         WI._selectedTabIndexSetting.value = WI.tabBar.tabBarItems.indexOf(WI.tabBar.selectedTabBarItem);
1857
1858     if (WI.doesCurrentTabSupportSplitContentBrowser()) {
1859         if (WI._shouldRevealSpitConsoleIfSupported) {
1860             WI._shouldRevealSpitConsoleIfSupported = false;
1861             WI.showSplitConsole();
1862         }
1863         return;
1864     }
1865
1866     WI._shouldRevealSpitConsoleIfSupported = WI.isShowingSplitConsole();
1867     WI.hideSplitConsole();
1868 };
1869
1870 WI._toolbarMouseDown = function(event)
1871 {
1872     if (event.ctrlKey)
1873         return;
1874
1875     if (WI._dockConfiguration === WI.DockConfiguration.Right || WI._dockConfiguration === WI.DockConfiguration.Left)
1876         return;
1877
1878     if (WI.docked)
1879         WI._dockedResizerMouseDown(event);
1880     else
1881         WI._moveWindowMouseDown(event);
1882 };
1883
1884 WI._dockedResizerMouseDown = function(event)
1885 {
1886     if (event.button !== 0 || event.ctrlKey)
1887         return;
1888
1889     if (!WI.docked)
1890         return;
1891
1892     // Only start dragging if the target is one of the elements that we expect.
1893     if (event.target.id !== "docked-resizer" && !event.target.classList.contains("toolbar") &&
1894         !event.target.classList.contains("flexible-space") && !event.target.classList.contains("item-section"))
1895         return;
1896
1897     event[WI.Popover.EventPreventDismissSymbol] = true;
1898
1899     let windowProperty = WI._dockConfiguration === WI.DockConfiguration.Bottom ? "innerHeight" : "innerWidth";
1900     let eventScreenProperty = WI._dockConfiguration === WI.DockConfiguration.Bottom ? "screenY" : "screenX";
1901     let eventClientProperty = WI._dockConfiguration === WI.DockConfiguration.Bottom ? "clientY" : "clientX";
1902
1903     var resizerElement = event.target;
1904     var firstClientPosition = event[eventClientProperty];
1905     var lastScreenPosition = event[eventScreenProperty];
1906
1907     function dockedResizerDrag(event)
1908     {
1909         if (event.button !== 0)
1910             return;
1911
1912         var position = event[eventScreenProperty];
1913         var delta = position - lastScreenPosition;
1914         var clientPosition = event[eventClientProperty];
1915
1916         lastScreenPosition = position;
1917
1918         if (WI._dockConfiguration === WI.DockConfiguration.Left) {
1919             // If the mouse is travelling rightward but is positioned left of the resizer, ignore the event.
1920             if (delta > 0 && clientPosition < firstClientPosition)
1921                 return;
1922
1923             // If the mouse is travelling leftward but is positioned to the right of the resizer, ignore the event.
1924             if (delta < 0 && clientPosition > window[windowProperty])
1925                 return;
1926
1927             // We later subtract the delta from the current position, but since the inspected view and inspector view
1928             // are flipped when docked to left, we want dragging to have the opposite effect from docked to right.
1929             delta *= -1;
1930         } else {
1931             // If the mouse is travelling downward/rightward but is positioned above/left of the resizer, ignore the event.
1932             if (delta > 0 && clientPosition < firstClientPosition)
1933                 return;
1934
1935             // If the mouse is travelling upward/leftward but is positioned below/right of the resizer, ignore the event.
1936             if (delta < 0 && clientPosition > firstClientPosition)
1937                 return;
1938         }
1939
1940         let dimension = Math.max(0, window[windowProperty] - delta);
1941         // If zoomed in/out, there be greater/fewer document pixels shown, but the inspector's
1942         // width or height should be the same in device pixels regardless of the document zoom.
1943         dimension *= WI.getZoomFactor();
1944
1945         if (WI._dockConfiguration === WI.DockConfiguration.Bottom)
1946             InspectorFrontendHost.setAttachedWindowHeight(dimension);
1947         else
1948             InspectorFrontendHost.setAttachedWindowWidth(dimension);
1949     }
1950
1951     function dockedResizerDragEnd(event)
1952     {
1953         if (event.button !== 0)
1954             return;
1955
1956         WI.elementDragEnd(event);
1957     }
1958
1959     WI.elementDragStart(resizerElement, dockedResizerDrag, dockedResizerDragEnd, event, WI._dockConfiguration === WI.DockConfiguration.Bottom ? "row-resize" : "col-resize");
1960 };
1961
1962 WI._moveWindowMouseDown = function(event)
1963 {
1964     console.assert(!WI.docked);
1965
1966     if (event.button !== 0 || event.ctrlKey)
1967         return;
1968
1969     // Only start dragging if the target is one of the elements that we expect.
1970     if (!event.target.classList.contains("toolbar") && !event.target.classList.contains("flexible-space") &&
1971         !event.target.classList.contains("item-section"))
1972         return;
1973
1974     event[WI.Popover.EventPreventDismissSymbol] = true;
1975
1976     if (WI.Platform.name === "mac") {
1977         InspectorFrontendHost.startWindowDrag();
1978         event.preventDefault();
1979         return;
1980     }
1981
1982     var lastScreenX = event.screenX;
1983     var lastScreenY = event.screenY;
1984
1985     function toolbarDrag(event)
1986     {
1987         if (event.button !== 0)
1988             return;
1989
1990         var x = event.screenX - lastScreenX;
1991         var y = event.screenY - lastScreenY;
1992
1993         InspectorFrontendHost.moveWindowBy(x, y);
1994
1995         lastScreenX = event.screenX;
1996         lastScreenY = event.screenY;
1997     }
1998
1999     function toolbarDragEnd(event)
2000     {
2001         if (event.button !== 0)
2002             return;
2003
2004         WI.elementDragEnd(event);
2005     }
2006
2007     WI.elementDragStart(event.target, toolbarDrag, toolbarDragEnd, event, "default");
2008 };
2009
2010 WI._domStorageWasInspected = function(event)
2011 {
2012     WI.showStorageTab();
2013     WI.showRepresentedObject(event.data.domStorage, null, {ignoreSearchTab: true});
2014 };
2015
2016 WI._databaseWasInspected = function(event)
2017 {
2018     WI.showStorageTab();
2019     WI.showRepresentedObject(event.data.database, null, {ignoreSearchTab: true});
2020 };
2021
2022 WI._domNodeWasInspected = function(event)
2023 {
2024     WI.domManager.highlightDOMNodeForTwoSeconds(event.data.node.id);
2025
2026     InspectorFrontendHost.bringToFront();
2027
2028     WI.showElementsTab();
2029     WI.showMainFrameDOMTree(event.data.node, {ignoreSearchTab: true});
2030 };
2031
2032 WI._inspectModeStateChanged = function(event)
2033 {
2034     WI._inspectModeToolbarButton.activated = WI.domManager.inspectModeEnabled;
2035 };
2036
2037 WI._toggleInspectMode = function(event)
2038 {
2039     WI.domManager.inspectModeEnabled = !WI.domManager.inspectModeEnabled;
2040 };
2041
2042 WI._handleDeviceSettingsToolbarButtonClicked = function(event)
2043 {
2044     if (WI._deviceSettingsPopover) {
2045         WI._deviceSettingsPopover.dismiss();
2046         WI._deviceSettingsPopover = null;
2047         return;
2048     }
2049
2050     function updateActivatedState() {
2051         WI._deviceSettingsToolbarButton.activated = WI._overridenDeviceUserAgent || WI._overridenDeviceSettings.size > 0;
2052     }
2053
2054     function applyOverriddenUserAgent(value, force) {
2055         if (value === WI._overridenDeviceUserAgent)
2056             return;
2057
2058         if (!force && (!value || value === "default")) {
2059             PageAgent.overrideUserAgent((error) => {
2060                 if (error) {
2061                     console.error(error);
2062                     return;
2063                 }
2064
2065                 WI._overridenDeviceUserAgent = null;
2066                 updateActivatedState();
2067                 PageAgent.reload();
2068             });
2069         } else {
2070             PageAgent.overrideUserAgent(value, (error) => {
2071                 if (error) {
2072                     console.error(error);
2073                     return;
2074                 }
2075
2076                 WI._overridenDeviceUserAgent = value;
2077                 updateActivatedState();
2078                 PageAgent.reload();
2079             });
2080         }
2081     }
2082
2083     function applyOverriddenSetting(setting, value, callback) {
2084         if (WI._overridenDeviceSettings.has(setting)) {
2085             // We've just "disabled" the checkbox, so clear the override instead of applying it.
2086             PageAgent.overrideSetting(setting, (error) => {
2087                 if (error) {
2088                     console.error(error);
2089                     return;
2090                 }
2091
2092                 WI._overridenDeviceSettings.delete(setting);
2093                 callback(false);
2094                 updateActivatedState();
2095             });
2096         } else {
2097             PageAgent.overrideSetting(setting, value, (error) => {
2098                 if (error) {
2099                     console.error(error);
2100                     return;
2101                 }
2102
2103                 WI._overridenDeviceSettings.set(setting, value);
2104                 callback(true);
2105                 updateActivatedState();
2106             });
2107         }
2108     }
2109
2110     function createCheckbox(container, label, setting, value) {
2111         if (!setting)
2112             return;
2113
2114         let labelElement = container.appendChild(document.createElement("label"));
2115
2116         let checkboxElement = labelElement.appendChild(document.createElement("input"));
2117         checkboxElement.type = "checkbox";
2118         checkboxElement.checked = WI._overridenDeviceSettings.has(setting);
2119         checkboxElement.addEventListener("change", (event) => {
2120             applyOverriddenSetting(setting, value, (enabled) => {
2121                 checkboxElement.checked = enabled;
2122             });
2123         });
2124
2125         labelElement.append(label);
2126     }
2127
2128     function calculateTargetFrame() {
2129         return WI.Rect.rectFromClientRect(WI._deviceSettingsToolbarButton.element.getBoundingClientRect());
2130     }
2131
2132     const preferredEdges = [WI.RectEdge.MAX_Y, WI.RectEdge.MIN_X, WI.RectEdge.MAX_X];
2133
2134     WI._deviceSettingsPopover = new WI.Popover(WI);
2135     WI._deviceSettingsPopover.windowResizeHandler = function(event) {
2136         WI._deviceSettingsPopover.present(calculateTargetFrame(), preferredEdges);
2137     };
2138
2139     let contentElement = document.createElement("table");
2140     contentElement.classList.add("device-settings-content");
2141
2142     let userAgentRow = contentElement.appendChild(document.createElement("tr"));
2143
2144     let userAgentTitle = userAgentRow.appendChild(document.createElement("td"));
2145     userAgentTitle.textContent = WI.UIString("User Agent:");
2146
2147     let userAgentValue = userAgentRow.appendChild(document.createElement("td"));
2148     userAgentValue.classList.add("user-agent");
2149
2150     let userAgentValueSelect = userAgentValue.appendChild(document.createElement("select"));
2151
2152     let userAgentValueInput = null;
2153
2154     const userAgents = [
2155         [
2156             { name: WI.UIString("Default"), value: "default" },
2157         ],
2158         [
2159             { name: "Safari 12.2", value: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.2 Safari/605.1.15" },
2160         ],
2161         [
2162             { 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" },
2163             { 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" },
2164             { 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" },
2165         ],
2166         [
2167             { 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" },
2168         ],
2169         [
2170             { name: `Internet Explorer 11`, value: "Mozilla/5.0 (Windows NT 6.3; Win64, x64; Trident/7.0; rv:11.0) like Gecko" },
2171             { name: `Internet Explorer 10`, value: "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Win64; x64; Trident/6.0)" },
2172             { name: `Internet Explorer 9`, value: "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)" },
2173             { name: `Internet Explorer 8`, value: "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0)" },
2174             { name: `Internet Explorer 7`, value: "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)" },
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                 ],
2268             ],
2269         },
2270     ];
2271
2272     for (let group of settings) {
2273         if (!group.columns.some((column) => column.some((item) => item.setting)))
2274             continue;
2275
2276         let settingsGroupRow = contentElement.appendChild(document.createElement("tr"));
2277
2278         let settingsGroupTitle = settingsGroupRow.appendChild(document.createElement("td"));
2279         settingsGroupTitle.textContent = group.name;
2280
2281         let settingsGroupValue = settingsGroupRow.appendChild(document.createElement("td"));
2282
2283         let settingsGroupItemContainer = settingsGroupValue.appendChild(document.createElement("div"));
2284         settingsGroupItemContainer.classList.add("container");
2285
2286         for (let column of group.columns) {
2287             let columnElement = settingsGroupItemContainer.appendChild(document.createElement("div"));
2288             columnElement.classList.add("column");
2289
2290             for (let item of column)
2291                 createCheckbox(columnElement, item.name, item.setting, item.value);
2292         }
2293     }
2294
2295     WI._deviceSettingsPopover.presentNewContentWithFrame(contentElement, calculateTargetFrame(), preferredEdges);
2296 };
2297
2298 WI._downloadWebArchive = function(event)
2299 {
2300     WI.archiveMainFrame();
2301 };
2302
2303 WI._reloadInspectedInspector = function()
2304 {
2305     const options = {};
2306     WI.runtimeManager.evaluateInInspectedWindow(`InspectorFrontendHost.reopen()`, options, function(){});
2307 };
2308
2309 WI._reloadPage = function(event)
2310 {
2311     if (!window.PageAgent)
2312         return;
2313
2314     event.preventDefault();
2315
2316     if (InspectorFrontendHost.inspectionLevel() > 1) {
2317         WI._reloadInspectedInspector();
2318         return;
2319     }
2320
2321     PageAgent.reload();
2322 };
2323
2324 WI._reloadPageFromOrigin = function(event)
2325 {
2326     if (!window.PageAgent)
2327         return;
2328
2329     event.preventDefault();
2330
2331     if (InspectorFrontendHost.inspectionLevel() > 1) {
2332         WI._reloadInspectedInspector();
2333         return;
2334     }
2335
2336     PageAgent.reload.invoke({ignoreCache: true});
2337 };
2338
2339 WI._reloadToolbarButtonClicked = function(event)
2340 {
2341     if (InspectorFrontendHost.inspectionLevel() > 1) {
2342         WI._reloadInspectedInspector();
2343         return;
2344     }
2345
2346     // Reload page from origin if the button is clicked while the shift key is pressed down.
2347     PageAgent.reload.invoke({ignoreCache: WI.modifierKeys.shiftKey});
2348 };
2349
2350 WI._updateReloadToolbarButton = function()
2351 {
2352     if (!window.PageAgent) {
2353         WI._reloadToolbarButton.hidden = true;
2354         return;
2355     }
2356
2357     WI._reloadToolbarButton.hidden = false;
2358 };
2359
2360 WI._updateDownloadToolbarButton = function()
2361 {
2362     if (!window.PageAgent || WI.sharedApp.debuggableType !== WI.DebuggableType.Web) {
2363         WI._downloadToolbarButton.hidden = true;
2364         return;
2365     }
2366
2367     if (WI._downloadingPage) {
2368         WI._downloadToolbarButton.enabled = false;
2369         return;
2370     }
2371
2372     WI._downloadToolbarButton.enabled = WI.canArchiveMainFrame();
2373 };
2374
2375 WI._updateInspectModeToolbarButton = function()
2376 {
2377     if (!window.DOMAgent || !DOMAgent.setInspectModeEnabled) {
2378         WI._inspectModeToolbarButton.hidden = true;
2379         return;
2380     }
2381
2382     WI._inspectModeToolbarButton.hidden = false;
2383 };
2384
2385 WI._toggleInspectMode = function(event)
2386 {
2387     WI.domManager.inspectModeEnabled = !WI.domManager.inspectModeEnabled;
2388 };
2389
2390 WI._showConsoleTab = function(event)
2391 {
2392     WI.showConsoleTab();
2393 };
2394
2395 WI._focusConsolePrompt = function(event)
2396 {
2397     WI.quickConsole.prompt.focus();
2398 };
2399
2400 WI._focusedContentBrowser = function()
2401 {
2402     if (WI.currentFocusElement) {
2403         let contentBrowserElement = WI.currentFocusElement.closest(".content-browser");
2404         if (contentBrowserElement && contentBrowserElement.__view && contentBrowserElement.__view instanceof WI.ContentBrowser)
2405             return contentBrowserElement.__view;
2406     }
2407
2408     if (WI.tabBrowser.element.contains(WI.currentFocusElement) || document.activeElement === document.body) {
2409         let tabContentView = WI.tabBrowser.selectedTabContentView;
2410         if (tabContentView.contentBrowser)
2411             return tabContentView.contentBrowser;
2412         return null;
2413     }
2414
2415     if (WI.consoleDrawer.element.contains(WI.currentFocusElement)
2416         || (WI.isShowingSplitConsole() && WI.quickConsole.element.contains(WI.currentFocusElement)))
2417         return WI.consoleDrawer;
2418
2419     return null;
2420 };
2421
2422 WI._focusedContentView = function()
2423 {
2424     if (WI.tabBrowser.element.contains(WI.currentFocusElement) || document.activeElement === document.body) {
2425         var tabContentView = WI.tabBrowser.selectedTabContentView;
2426         if (tabContentView.contentBrowser)
2427             return tabContentView.contentBrowser.currentContentView;
2428         return tabContentView;
2429     }
2430
2431     if (WI.consoleDrawer.element.contains(WI.currentFocusElement)
2432         || (WI.isShowingSplitConsole() && WI.quickConsole.element.contains(WI.currentFocusElement)))
2433         return WI.consoleDrawer.currentContentView;
2434
2435     return null;
2436 };
2437
2438 WI._focusedOrVisibleContentBrowser = function()
2439 {
2440     let focusedContentBrowser = WI._focusedContentBrowser();
2441     if (focusedContentBrowser)
2442         return focusedContentBrowser;
2443
2444     var tabContentView = WI.tabBrowser.selectedTabContentView;
2445     if (tabContentView.contentBrowser)
2446         return tabContentView.contentBrowser;
2447
2448     return null;
2449 };
2450
2451 WI.focusedOrVisibleContentView = function()
2452 {
2453     let focusedContentView = WI._focusedContentView();
2454     if (focusedContentView)
2455         return focusedContentView;
2456
2457     var tabContentView = WI.tabBrowser.selectedTabContentView;
2458     if (tabContentView.contentBrowser)
2459         return tabContentView.contentBrowser.currentContentView;
2460     return tabContentView;
2461 };
2462
2463 WI._beforecopy = function(event)
2464 {
2465     var selection = window.getSelection();
2466
2467     // If there is no selection, see if the focused element or focused ContentView can handle the copy event.
2468     if (selection.isCollapsed && !WI.isEventTargetAnEditableField(event)) {
2469         var focusedCopyHandler = WI.currentFocusElement && WI.currentFocusElement.copyHandler;
2470         if (focusedCopyHandler && typeof focusedCopyHandler.handleBeforeCopyEvent === "function") {
2471             focusedCopyHandler.handleBeforeCopyEvent(event);
2472             if (event.defaultPrevented)
2473                 return;
2474         }
2475
2476         var focusedContentView = WI._focusedContentView();
2477         if (focusedContentView && typeof focusedContentView.handleCopyEvent === "function") {
2478             event.preventDefault();
2479             return;
2480         }
2481
2482         return;
2483     }
2484
2485     if (selection.isCollapsed)
2486         return;
2487
2488     // Say we can handle it (by preventing default) to remove word break characters.
2489     event.preventDefault();
2490 };
2491
2492 WI._find = function(event)
2493 {
2494     let contentBrowser = WI._focusedOrVisibleContentBrowser();
2495     if (!contentBrowser)
2496         return;
2497
2498     contentBrowser.showFindBanner();
2499 };
2500
2501 WI._save = function(event)
2502 {
2503     var contentView = WI.focusedOrVisibleContentView();
2504     if (!contentView || !contentView.supportsSave)
2505         return;
2506
2507     WI.FileUtilities.save(contentView.saveData);
2508 };
2509
2510 WI._saveAs = function(event)
2511 {
2512     var contentView = WI.focusedOrVisibleContentView();
2513     if (!contentView || !contentView.supportsSave)
2514         return;
2515
2516     WI.FileUtilities.save(contentView.saveData, true);
2517 };
2518
2519 WI._clear = function(event)
2520 {
2521     let contentView = WI.focusedOrVisibleContentView();
2522     if (!contentView || typeof contentView.handleClearShortcut !== "function") {
2523         // If the current content view is unable to handle WI event, clear the console to reset
2524         // the dashboard counters.
2525         WI.consoleManager.requestClearMessages();
2526         return;
2527     }
2528
2529     contentView.handleClearShortcut(event);
2530 };
2531
2532 WI._populateFind = function(event)
2533 {
2534     let focusedContentView = WI._focusedContentView();
2535     if (!focusedContentView)
2536         return;
2537
2538     if (focusedContentView.supportsCustomFindBanner) {
2539         focusedContentView.handlePopulateFindShortcut();
2540         return;
2541     }
2542
2543     let contentBrowser = WI._focusedOrVisibleContentBrowser();
2544     if (!contentBrowser)
2545         return;
2546
2547     contentBrowser.handlePopulateFindShortcut();
2548 };
2549
2550 WI._findNext = function(event)
2551 {
2552     let focusedContentView = WI._focusedContentView();
2553     if (!focusedContentView)
2554         return;
2555
2556     if (focusedContentView.supportsCustomFindBanner) {
2557         focusedContentView.handleFindNextShortcut();
2558         return;
2559     }
2560
2561     let contentBrowser = WI._focusedOrVisibleContentBrowser();
2562     if (!contentBrowser)
2563         return;
2564
2565     contentBrowser.handleFindNextShortcut();
2566 };
2567
2568 WI._findPrevious = function(event)
2569 {
2570     let focusedContentView = WI._focusedContentView();
2571     if (!focusedContentView)
2572         return;
2573
2574     if (focusedContentView.supportsCustomFindBanner) {
2575         focusedContentView.handleFindPreviousShortcut();
2576         return;
2577     }
2578
2579     let contentBrowser = WI._focusedOrVisibleContentBrowser();
2580     if (!contentBrowser)
2581         return;
2582
2583     contentBrowser.handleFindPreviousShortcut();
2584 };
2585
2586 WI._copy = function(event)
2587 {
2588     var selection = window.getSelection();
2589
2590     // If there is no selection, pass the copy event on to the focused element or focused ContentView.
2591     if (selection.isCollapsed && !WI.isEventTargetAnEditableField(event)) {
2592         var focusedCopyHandler = WI.currentFocusElement && WI.currentFocusElement.copyHandler;
2593         if (focusedCopyHandler && typeof focusedCopyHandler.handleCopyEvent === "function") {
2594             focusedCopyHandler.handleCopyEvent(event);
2595             if (event.defaultPrevented)
2596                 return;
2597         }
2598
2599         var focusedContentView = WI._focusedContentView();
2600         if (focusedContentView && typeof focusedContentView.handleCopyEvent === "function") {
2601             focusedContentView.handleCopyEvent(event);
2602             return;
2603         }
2604
2605         let tabContentView = WI.tabBrowser.selectedTabContentView;
2606         if (tabContentView && typeof tabContentView.handleCopyEvent === "function") {
2607             tabContentView.handleCopyEvent(event);
2608             return;
2609         }
2610
2611         return;
2612     }
2613
2614     if (selection.isCollapsed)
2615         return;
2616
2617     // Remove word break characters from the selection before putting it on the pasteboard.
2618     var selectionString = selection.toString().removeWordBreakCharacters();
2619     event.clipboardData.setData("text/plain", selectionString);
2620     event.preventDefault();
2621 };
2622
2623 WI._increaseZoom = function(event)
2624 {
2625     const epsilon = 0.0001;
2626     const maximumZoom = 2.4;
2627     let currentZoom = WI.getZoomFactor();
2628     if (currentZoom + epsilon >= maximumZoom) {
2629         InspectorFrontendHost.beep();
2630         return;
2631     }
2632
2633     WI.setZoomFactor(Math.min(maximumZoom, currentZoom + 0.2));
2634 };
2635
2636 WI._decreaseZoom = function(event)
2637 {
2638     const epsilon = 0.0001;
2639     const minimumZoom = 0.6;
2640     let currentZoom = WI.getZoomFactor();
2641     if (currentZoom - epsilon <= minimumZoom) {
2642         InspectorFrontendHost.beep();
2643         return;
2644     }
2645
2646     WI.setZoomFactor(Math.max(minimumZoom, currentZoom - 0.2));
2647 };
2648
2649 WI._resetZoom = function(event)
2650 {
2651     WI.setZoomFactor(1);
2652 };
2653
2654 WI.getZoomFactor = function()
2655 {
2656     return WI.settings.zoomFactor.value;
2657 };
2658
2659 WI.setZoomFactor = function(factor)
2660 {
2661     InspectorFrontendHost.setZoomFactor(factor);
2662     // Round-trip through the frontend host API in case the requested factor is not used.
2663     WI.settings.zoomFactor.value = InspectorFrontendHost.zoomFactor();
2664 };
2665
2666 WI.resolvedLayoutDirection = function()
2667 {
2668     let layoutDirection = WI.settings.layoutDirection.value;
2669     if (layoutDirection === WI.LayoutDirection.System)
2670         layoutDirection = InspectorFrontendHost.userInterfaceLayoutDirection();
2671
2672     return layoutDirection;
2673 };
2674
2675 WI.setLayoutDirection = function(value)
2676 {
2677     if (!Object.values(WI.LayoutDirection).includes(value))
2678         WI.reportInternalError("Unknown layout direction requested: " + value);
2679
2680     if (value === WI.settings.layoutDirection.value)
2681         return;
2682
2683     WI.settings.layoutDirection.value = value;
2684
2685     if (WI.resolvedLayoutDirection() === WI.LayoutDirection.RTL && WI._dockConfiguration === WI.DockConfiguration.Right)
2686         WI._dockLeft();
2687
2688     if (WI.resolvedLayoutDirection() === WI.LayoutDirection.LTR && WI._dockConfiguration === WI.DockConfiguration.Left)
2689         WI._dockRight();
2690
2691     InspectorFrontendHost.reopen();
2692 };
2693
2694 WI._showTabAtIndex = function(i)
2695 {
2696     if (i <= WI.tabBar.tabBarItems.length)
2697         WI.tabBar.selectedTabBarItem = i - 1;
2698 };
2699
2700 WI._showJavaScriptTypeInformationSettingChanged = function(event)
2701 {
2702     if (WI.settings.showJavaScriptTypeInformation.value) {
2703         for (let target of WI.targets)
2704             target.RuntimeAgent.enableTypeProfiler();
2705     } else {
2706         for (let target of WI.targets)
2707             target.RuntimeAgent.disableTypeProfiler();
2708     }
2709 };
2710
2711 WI._enableControlFlowProfilerSettingChanged = function(event)
2712 {
2713     if (WI.settings.enableControlFlowProfiler.value) {
2714         for (let target of WI.targets)
2715             target.RuntimeAgent.enableControlFlowProfiler();
2716     } else {
2717         for (let target of WI.targets)
2718             target.RuntimeAgent.disableControlFlowProfiler();
2719     }
2720 };
2721
2722 WI._resourceCachingDisabledSettingChanged = function(event)
2723 {
2724     NetworkAgent.setResourceCachingDisabled(WI.settings.resourceCachingDisabled.value);
2725 };
2726
2727 WI.elementDragStart = function(element, dividerDrag, elementDragEnd, event, cursor, eventTarget)
2728 {
2729     if (WI._elementDraggingEventListener || WI._elementEndDraggingEventListener)
2730         WI.elementDragEnd(event);
2731
2732     if (element) {
2733         // Install glass pane
2734         if (WI._elementDraggingGlassPane)
2735             WI._elementDraggingGlassPane.remove();
2736
2737         var glassPane = document.createElement("div");
2738         glassPane.style.cssText = "position:absolute;top:0;bottom:0;left:0;right:0;opacity:0;z-index:1";
2739         glassPane.id = "glass-pane-for-drag";
2740         element.ownerDocument.body.appendChild(glassPane);
2741         WI._elementDraggingGlassPane = glassPane;
2742     }
2743
2744     WI._elementDraggingEventListener = dividerDrag;
2745     WI._elementEndDraggingEventListener = elementDragEnd;
2746
2747     var targetDocument = event.target.ownerDocument;
2748
2749     WI._elementDraggingEventTarget = eventTarget || targetDocument;
2750     WI._elementDraggingEventTarget.addEventListener("mousemove", dividerDrag, true);
2751     WI._elementDraggingEventTarget.addEventListener("mouseup", elementDragEnd, true);
2752
2753     targetDocument.body.style.cursor = cursor;
2754
2755     event.preventDefault();
2756 };
2757
2758 WI.elementDragEnd = function(event)
2759 {
2760     WI._elementDraggingEventTarget.removeEventListener("mousemove", WI._elementDraggingEventListener, true);
2761     WI._elementDraggingEventTarget.removeEventListener("mouseup", WI._elementEndDraggingEventListener, true);
2762
2763     event.target.ownerDocument.body.style.removeProperty("cursor");
2764
2765     if (WI._elementDraggingGlassPane)
2766         WI._elementDraggingGlassPane.remove();
2767
2768     delete WI._elementDraggingGlassPane;
2769     delete WI._elementDraggingEventTarget;
2770     delete WI._elementDraggingEventListener;
2771     delete WI._elementEndDraggingEventListener;
2772
2773     event.preventDefault();
2774 };
2775
2776 WI.createMessageTextView = function(message, isError)
2777 {
2778     let messageElement = document.createElement("div");
2779     messageElement.className = "message-text-view";
2780     if (isError)
2781         messageElement.classList.add("error");
2782
2783     let textElement = messageElement.appendChild(document.createElement("div"));
2784     textElement.className = "message";
2785     textElement.textContent = message;
2786
2787     return messageElement;
2788 };
2789
2790 WI.createNavigationItemHelp = function(formatString, navigationItem)
2791 {
2792     console.assert(typeof formatString === "string");
2793     console.assert(navigationItem instanceof WI.NavigationItem);
2794
2795     function append(a, b) {
2796         a.append(b);
2797         return a;
2798     }
2799
2800     let containerElement = document.createElement("div");
2801     containerElement.className = "navigation-item-help";
2802     containerElement.__navigationItem = navigationItem;
2803
2804     let wrapperElement = document.createElement("div");
2805     wrapperElement.className = "navigation-bar";
2806     wrapperElement.appendChild(navigationItem.element);
2807
2808     String.format(formatString, [wrapperElement], String.standardFormatters, containerElement, append);
2809     return containerElement;
2810 };
2811
2812 WI.createGoToArrowButton = function()
2813 {
2814     var button = document.createElement("button");
2815     button.addEventListener("mousedown", (event) => { event.stopPropagation(); }, true);
2816     button.className = "go-to-arrow";
2817     button.tabIndex = -1;
2818     return button;
2819 };
2820
2821 WI.createSourceCodeLocationLink = function(sourceCodeLocation, options = {})
2822 {
2823     console.assert(sourceCodeLocation);
2824     if (!sourceCodeLocation)
2825         return null;
2826
2827     var linkElement = document.createElement("a");
2828     linkElement.className = "go-to-link";
2829     WI.linkifyElement(linkElement, sourceCodeLocation, options);
2830     sourceCodeLocation.populateLiveDisplayLocationTooltip(linkElement);
2831
2832     if (options.useGoToArrowButton)
2833         linkElement.appendChild(WI.createGoToArrowButton());
2834     else
2835         sourceCodeLocation.populateLiveDisplayLocationString(linkElement, "textContent", options.columnStyle, options.nameStyle, options.prefix);
2836
2837     if (options.dontFloat)
2838         linkElement.classList.add("dont-float");
2839
2840     return linkElement;
2841 };
2842
2843 WI.linkifyLocation = function(url, sourceCodePosition, options = {})
2844 {
2845     var sourceCode = WI.sourceCodeForURL(url);
2846
2847     if (!sourceCode) {
2848         var anchor = document.createElement("a");
2849         anchor.href = url;
2850         anchor.lineNumber = sourceCodePosition.lineNumber;
2851         if (options.className)
2852             anchor.className = options.className;
2853         anchor.append(WI.displayNameForURL(url) + ":" + sourceCodePosition.lineNumber);
2854         return anchor;
2855     }
2856
2857     let sourceCodeLocation = sourceCode.createSourceCodeLocation(sourceCodePosition.lineNumber, sourceCodePosition.columnNumber);
2858     let linkElement = WI.createSourceCodeLocationLink(sourceCodeLocation, {
2859         ...options,
2860         dontFloat: true,
2861     });
2862
2863     if (options.className)
2864         linkElement.classList.add(options.className);
2865
2866     return linkElement;
2867 };
2868
2869 WI.linkifyElement = function(linkElement, sourceCodeLocation, options = {}) {
2870     console.assert(sourceCodeLocation);
2871
2872     function showSourceCodeLocation(event)
2873     {
2874         event.stopPropagation();
2875         event.preventDefault();
2876
2877         if (event.metaKey)
2878             WI.showOriginalUnformattedSourceCodeLocation(sourceCodeLocation, options);
2879         else
2880             WI.showSourceCodeLocation(sourceCodeLocation, options);
2881     }
2882
2883     linkElement.addEventListener("click", showSourceCodeLocation);
2884     linkElement.addEventListener("contextmenu", (event) => {
2885         let contextMenu = WI.ContextMenu.createFromEvent(event);
2886         WI.appendContextMenuItemsForSourceCode(contextMenu, sourceCodeLocation);
2887     });
2888 };
2889
2890 WI.sourceCodeForURL = function(url)
2891 {
2892     var sourceCode = WI.networkManager.resourceForURL(url);
2893     if (!sourceCode) {
2894         sourceCode = WI.debuggerManager.scriptsForURL(url, WI.assumingMainTarget())[0];
2895         if (sourceCode)
2896             sourceCode = sourceCode.resource || sourceCode;
2897     }
2898     return sourceCode || null;
2899 };
2900
2901 WI.linkifyURLAsNode = function(url, linkText, className)
2902 {
2903     let a = document.createElement("a");
2904     a.href = url;
2905     a.className = className || "";
2906     a.textContent = linkText || url;
2907     a.style.maxWidth = "100%";
2908     return a;
2909 };
2910
2911 WI.linkifyStringAsFragmentWithCustomLinkifier = function(string, linkifier)
2912 {
2913     var container = document.createDocumentFragment();
2914     var linkStringRegEx = /(?:[a-zA-Z][a-zA-Z0-9+.-]{2,}:\/\/|www\.)[\w$\-_+*'=\|\/\\(){}[\]%@&#~,:;.!?]{2,}[\w$\-_+*=\|\/\\({%@&#~]/;
2915     var lineColumnRegEx = /:(\d+)(:(\d+))?$/;
2916
2917     while (string) {
2918         var linkString = linkStringRegEx.exec(string);
2919         if (!linkString)
2920             break;
2921
2922         linkString = linkString[0];
2923         var linkIndex = string.indexOf(linkString);
2924         var nonLink = string.substring(0, linkIndex);
2925         container.append(nonLink);
2926
2927         if (linkString.startsWith("data:") || linkString.startsWith("javascript:") || linkString.startsWith("mailto:")) {
2928             container.append(linkString);
2929             string = string.substring(linkIndex + linkString.length, string.length);
2930             continue;
2931         }
2932
2933         var title = linkString;
2934         var realURL = linkString.startsWith("www.") ? "http://" + linkString : linkString;
2935         var lineColumnMatch = lineColumnRegEx.exec(realURL);
2936         if (lineColumnMatch)
2937             realURL = realURL.substring(0, realURL.length - lineColumnMatch[0].length);
2938
2939         var lineNumber;
2940         if (lineColumnMatch)
2941             lineNumber = parseInt(lineColumnMatch[1]) - 1;
2942
2943         var linkNode = linkifier(title, realURL, lineNumber);
2944         container.appendChild(linkNode);
2945         string = string.substring(linkIndex + linkString.length, string.length);
2946     }
2947
2948     if (string)
2949         container.append(string);
2950
2951     return container;
2952 };
2953
2954 WI.linkifyStringAsFragment = function(string)
2955 {
2956     function linkifier(title, url, lineNumber)
2957     {
2958         var urlNode = WI.linkifyURLAsNode(url, title, undefined);
2959         if (lineNumber !== undefined)
2960             urlNode.lineNumber = lineNumber;
2961
2962         return urlNode;
2963     }
2964
2965     return WI.linkifyStringAsFragmentWithCustomLinkifier(string, linkifier);
2966 };
2967
2968 WI.createResourceLink = function(resource, className)
2969 {
2970     function handleClick(event)
2971     {
2972         event.stopPropagation();
2973         event.preventDefault();
2974
2975         WI.showRepresentedObject(resource);
2976     }
2977
2978     let linkNode = document.createElement("a");
2979     linkNode.classList.add("resource-link", className);
2980     linkNode.title = resource.url;
2981     linkNode.textContent = (resource.urlComponents.lastPathComponent || resource.url).insertWordBreakCharacters();
2982     linkNode.addEventListener("click", handleClick);
2983     return linkNode;
2984 };
2985
2986 WI._undoKeyboardShortcut = function(event)
2987 {
2988     if (!WI.isEditingAnyField() && !WI.isEventTargetAnEditableField(event)) {
2989         WI.undo();
2990         event.preventDefault();
2991     }
2992 };
2993
2994 WI._redoKeyboardShortcut = function(event)
2995 {
2996     if (!WI.isEditingAnyField() && !WI.isEventTargetAnEditableField(event)) {
2997         WI.redo();
2998         event.preventDefault();
2999     }
3000 };
3001
3002 WI.undo = function()
3003 {
3004     DOMAgent.undo();
3005 };
3006
3007 WI.redo = function()
3008 {
3009     DOMAgent.redo();
3010 };
3011
3012 WI.highlightRangesWithStyleClass = function(element, resultRanges, styleClass, changes)
3013 {
3014     changes = changes || [];
3015     var highlightNodes = [];
3016     var lineText = element.textContent;
3017     var ownerDocument = element.ownerDocument;
3018     var textNodeSnapshot = ownerDocument.evaluate(".//text()", element, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
3019
3020     var snapshotLength = textNodeSnapshot.snapshotLength;
3021     if (snapshotLength === 0)
3022         return highlightNodes;
3023
3024     var nodeRanges = [];
3025     var rangeEndOffset = 0;
3026     for (var i = 0; i < snapshotLength; ++i) {
3027         var range = {};
3028         range.offset = rangeEndOffset;
3029         range.length = textNodeSnapshot.snapshotItem(i).textContent.length;
3030         rangeEndOffset = range.offset + range.length;
3031         nodeRanges.push(range);
3032     }
3033
3034     var startIndex = 0;
3035     for (var i = 0; i < resultRanges.length; ++i) {
3036         var startOffset = resultRanges[i].offset;
3037         var endOffset = startOffset + resultRanges[i].length;
3038
3039         while (startIndex < snapshotLength && nodeRanges[startIndex].offset + nodeRanges[startIndex].length <= startOffset)
3040             startIndex++;
3041         var endIndex = startIndex;
3042         while (endIndex < snapshotLength && nodeRanges[endIndex].offset + nodeRanges[endIndex].length < endOffset)
3043             endIndex++;
3044         if (endIndex === snapshotLength)
3045             break;
3046
3047         var highlightNode = ownerDocument.createElement("span");
3048         highlightNode.className = styleClass;
3049         highlightNode.textContent = lineText.substring(startOffset, endOffset);
3050
3051         var lastTextNode = textNodeSnapshot.snapshotItem(endIndex);
3052         var lastText = lastTextNode.textContent;
3053         lastTextNode.textContent = lastText.substring(endOffset - nodeRanges[endIndex].offset);
3054         changes.push({node: lastTextNode, type: "changed", oldText: lastText, newText: lastTextNode.textContent});
3055
3056         if (startIndex === endIndex) {
3057             lastTextNode.parentElement.insertBefore(highlightNode, lastTextNode);
3058             changes.push({node: highlightNode, type: "added", nextSibling: lastTextNode, parent: lastTextNode.parentElement});
3059             highlightNodes.push(highlightNode);
3060
3061             var prefixNode = ownerDocument.createTextNode(lastText.substring(0, startOffset - nodeRanges[startIndex].offset));
3062             lastTextNode.parentElement.insertBefore(prefixNode, highlightNode);
3063             changes.push({node: prefixNode, type: "added", nextSibling: highlightNode, parent: lastTextNode.parentElement});
3064         } else {
3065             var firstTextNode = textNodeSnapshot.snapshotItem(startIndex);
3066             var firstText = firstTextNode.textContent;
3067             var anchorElement = firstTextNode.nextSibling;
3068
3069             firstTextNode.parentElement.insertBefore(highlightNode, anchorElement);
3070             changes.push({node: highlightNode, type: "added", nextSibling: anchorElement, parent: firstTextNode.parentElement});
3071             highlightNodes.push(highlightNode);
3072
3073             firstTextNode.textContent = firstText.substring(0, startOffset - nodeRanges[startIndex].offset);
3074             changes.push({node: firstTextNode, type: "changed", oldText: firstText, newText: firstTextNode.textContent});
3075
3076             for (var j = startIndex + 1; j < endIndex; j++) {
3077                 var textNode = textNodeSnapshot.snapshotItem(j);
3078                 var text = textNode.textContent;
3079                 textNode.textContent = "";
3080                 changes.push({node: textNode, type: "changed", oldText: text, newText: textNode.textContent});
3081             }
3082         }
3083         startIndex = endIndex;
3084         nodeRanges[startIndex].offset = endOffset;
3085         nodeRanges[startIndex].length = lastTextNode.textContent.length;
3086
3087     }
3088     return highlightNodes;
3089 };
3090
3091 WI.revertDOMChanges = function(domChanges)
3092 {
3093     for (var i = domChanges.length - 1; i >= 0; --i) {
3094         var entry = domChanges[i];
3095         switch (entry.type) {
3096         case "added":
3097             entry.node.remove();
3098             break;
3099         case "changed":
3100             entry.node.textContent = entry.oldText;
3101             break;
3102         }
3103     }
3104 };
3105
3106 WI.archiveMainFrame = function()
3107 {
3108     WI._downloadingPage = true;
3109     WI._updateDownloadToolbarButton();
3110
3111     PageAgent.archive((error, data) => {
3112         WI._downloadingPage = false;
3113         WI._updateDownloadToolbarButton();
3114
3115         if (error)
3116             return;
3117
3118         let mainFrame = WI.networkManager.mainFrame;
3119         let archiveName = mainFrame.mainResource.urlComponents.host || mainFrame.mainResource.displayName || "Archive";
3120         let url = WI.FileUtilities.inspectorURLForFilename(archiveName + ".webarchive");
3121
3122         InspectorFrontendHost.save(url, data, true, true);
3123     });
3124 };
3125
3126 WI.canArchiveMainFrame = function()
3127 {
3128     if (WI.sharedApp.debuggableType !== WI.DebuggableType.Web)
3129         return false;
3130
3131     if (!WI.networkManager.mainFrame || !WI.networkManager.mainFrame.mainResource)
3132         return false;
3133
3134     return WI.Resource.typeFromMIMEType(WI.networkManager.mainFrame.mainResource.mimeType) === WI.Resource.Type.Document;
3135 };
3136
3137 WI.addWindowKeydownListener = function(listener)
3138 {
3139     if (typeof listener.handleKeydownEvent !== "function")
3140         return;
3141
3142     WI._windowKeydownListeners.push(listener);
3143
3144     WI._updateWindowKeydownListener();
3145 };
3146
3147 WI.removeWindowKeydownListener = function(listener)
3148 {
3149     WI._windowKeydownListeners.remove(listener);
3150
3151     WI._updateWindowKeydownListener();
3152 };
3153
3154 WI._updateWindowKeydownListener = function()
3155 {
3156     if (WI._windowKeydownListeners.length === 1)
3157         window.addEventListener("keydown", WI._sharedWindowKeydownListener, true);
3158     else if (!WI._windowKeydownListeners.length)
3159         window.removeEventListener("keydown", WI._sharedWindowKeydownListener, true);
3160 };
3161
3162 WI._sharedWindowKeydownListener = function(event)
3163 {
3164     for (var i = WI._windowKeydownListeners.length - 1; i >= 0; --i) {
3165         if (WI._windowKeydownListeners[i].handleKeydownEvent(event)) {
3166             event.stopImmediatePropagation();
3167             event.preventDefault();
3168             break;
3169         }
3170     }
3171 };
3172
3173 WI.reportInternalError = function(errorOrString, details = {})
3174 {
3175     // The 'details' object includes additional information from the caller as free-form string keys and values.
3176     // Each key and value will be shown in the uncaught exception reporter, console error message, or in
3177     // a pre-filled bug report generated for this internal error.
3178
3179     let error = errorOrString instanceof Error ? errorOrString : new Error(errorOrString);
3180     error.details = details;
3181
3182     // The error will be displayed in the Uncaught Exception Reporter sheet if DebugUI is enabled.
3183     if (WI.isDebugUIEnabled()) {
3184         // This assert allows us to stop the debugger at an internal exception. It doesn't re-throw
3185         // exceptions because the original exception would be lost through window.onerror.
3186         // This workaround can be removed once <https://webkit.org/b/158192> is fixed.
3187         console.assert(false, "An internal exception was thrown.", error);
3188         handleInternalException(error);
3189     } else
3190         console.error(error);
3191 };
3192
3193 // Many places assume the "main" target has resources.
3194 // In the case where the main backend target is a MultiplexingBackendTarget
3195 // that target has essentially nothing. In that case defer to the page
3196 // target, since that is the real "main" target the frontend is assuming.
3197 Object.defineProperty(WI, "mainTarget",
3198 {
3199     get() { return WI.pageTarget || WI.backendTarget; }
3200 });
3201
3202 // This list of targets are non-Multiplexing targets.
3203 // So if there is a multiplexing target, and multiple sub-targets
3204 // this is just the list of sub-targets. Almost no code expects
3205 // to actually interact with the Multiplexing target.
3206 Object.defineProperty(WI, "targets",
3207 {
3208     get() { return WI.targetManager.targets; }
3209 });
3210
3211 // Many places assume the main target because they cannot yet be
3212 // used by reached by Worker debugging. Eventually, once all
3213 // Worker domains have been implemented, all of these must be
3214 // handled properly.
3215 WI.assumingMainTarget = function()
3216 {
3217     return WI.mainTarget;
3218 };
3219
3220 WI.isEngineeringBuild = false;
3221
3222 // OpenResourceDialog delegate
3223
3224 WI.dialogWasDismissedWithRepresentedObject = function(dialog, representedObject)
3225 {
3226     if (!representedObject)
3227         return;
3228
3229     WI.showRepresentedObject(representedObject, dialog.cookie);
3230 };
3231
3232 // Popover delegate
3233
3234 WI.didDismissPopover = function(popover)
3235 {
3236     if (popover === WI._deviceSettingsPopover)
3237         WI._deviceSettingsPopover = null;
3238 };
3239
3240 WI.DockConfiguration = {
3241     Right: "right",
3242     Left: "left",
3243     Bottom: "bottom",
3244     Undocked: "undocked",
3245 };