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