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