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