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