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