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