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