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