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