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