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