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