Web Inspector: Clicking source location link in Console unexpectedly jumps to Network tab
[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", "canvas", "console"]);
162     this._selectedTabIndexSetting = new WI.Setting("selected-tab-index", 0);
163
164     this.showShadowDOMSetting = new WI.Setting("show-shadow-dom", false);
165
166     // COMPATIBILITY (iOS 8): Page.enableTypeProfiler did not exist.
167     this.showJavaScriptTypeInformationSetting = new WI.Setting("show-javascript-type-information", false);
168     this.showJavaScriptTypeInformationSetting.addEventListener(WI.Setting.Event.Changed, this._showJavaScriptTypeInformationSettingChanged, this);
169     if (this.showJavaScriptTypeInformationSetting.value && window.RuntimeAgent && RuntimeAgent.enableTypeProfiler)
170         RuntimeAgent.enableTypeProfiler();
171
172     this.enableControlFlowProfilerSetting = new WI.Setting("enable-control-flow-profiler", false);
173     this.enableControlFlowProfilerSetting.addEventListener(WI.Setting.Event.Changed, this._enableControlFlowProfilerSettingChanged, this);
174     if (this.enableControlFlowProfilerSetting.value && window.RuntimeAgent && RuntimeAgent.enableControlFlowProfiler)
175         RuntimeAgent.enableControlFlowProfiler();
176
177     // COMPATIBILITY (iOS 8): Page.setShowPaintRects did not exist.
178     this.showPaintRectsSetting = new WI.Setting("show-paint-rects", false);
179     if (this.showPaintRectsSetting.value && window.PageAgent && PageAgent.setShowPaintRects)
180         PageAgent.setShowPaintRects(true);
181
182     this.showPrintStylesSetting = new WI.Setting("show-print-styles", false);
183     if (this.showPrintStylesSetting.value && window.PageAgent)
184         PageAgent.setEmulatedMedia("print");
185
186     // COMPATIBILITY (iOS 10.3): Network.setDisableResourceCaching did not exist.
187     this.resourceCachingDisabledSetting = new WI.Setting("disable-resource-caching", false);
188     if (window.NetworkAgent && NetworkAgent.setResourceCachingDisabled) {
189         if (this.resourceCachingDisabledSetting.value)
190             NetworkAgent.setResourceCachingDisabled(true);
191         this.resourceCachingDisabledSetting.addEventListener(WI.Setting.Event.Changed, this._resourceCachingDisabledSettingChanged, this);
192     }
193
194     this.setZoomFactor(WI.settings.zoomFactor.value);
195
196     this.mouseCoords = {
197         x: 0,
198         y: 0
199     };
200
201     this.visible = false;
202
203     this._windowKeydownListeners = [];
204 };
205
206 WI.contentLoaded = function()
207 {
208     // If there was an uncaught exception earlier during loading, then
209     // abort loading more content. We could be in an inconsistent state.
210     if (window.__uncaughtExceptions)
211         return;
212
213     // Register for global events.
214     document.addEventListener("beforecopy", this._beforecopy.bind(this));
215     document.addEventListener("copy", this._copy.bind(this));
216
217     document.addEventListener("click", this._mouseWasClicked.bind(this));
218     document.addEventListener("dragover", this._dragOver.bind(this));
219     document.addEventListener("focus", WI._focusChanged.bind(this), true);
220
221     window.addEventListener("focus", this._windowFocused.bind(this));
222     window.addEventListener("blur", this._windowBlurred.bind(this));
223     window.addEventListener("resize", this._windowResized.bind(this));
224     window.addEventListener("keydown", this._windowKeyDown.bind(this));
225     window.addEventListener("keyup", this._windowKeyUp.bind(this));
226     window.addEventListener("mousedown", this._mouseDown.bind(this), true);
227     window.addEventListener("mousemove", this._mouseMoved.bind(this), true);
228     window.addEventListener("pagehide", this._pageHidden.bind(this));
229     window.addEventListener("contextmenu", this._contextMenuRequested.bind(this));
230
231     // Add platform style classes so the UI can be tweaked per-platform.
232     document.body.classList.add(WI.Platform.name + "-platform");
233     if (WI.Platform.isNightlyBuild)
234         document.body.classList.add("nightly-build");
235
236     if (WI.Platform.name === "mac") {
237         document.body.classList.add(WI.Platform.version.name);
238
239         if (WI.Platform.version.release >= 11)
240             document.body.classList.add("latest-mac");
241         else
242             document.body.classList.add("legacy-mac");
243     }
244
245     document.body.classList.add(WI.sharedApp.debuggableType);
246     document.body.setAttribute("dir", this.resolvedLayoutDirection());
247
248     function setTabSize() {
249         document.body.style.tabSize = WI.settings.tabSize.value;
250     }
251     WI.settings.tabSize.addEventListener(WI.Setting.Event.Changed, setTabSize);
252     setTabSize();
253
254     function setInvalidCharacterClassName() {
255         document.body.classList.toggle("show-invalid-characters", WI.settings.showInvalidCharacters.value);
256     }
257     WI.settings.showInvalidCharacters.addEventListener(WI.Setting.Event.Changed, setInvalidCharacterClassName);
258     setInvalidCharacterClassName();
259
260     function setWhitespaceCharacterClassName() {
261         document.body.classList.toggle("show-whitespace-characters", WI.settings.showWhitespaceCharacters.value);
262     }
263     WI.settings.showWhitespaceCharacters.addEventListener(WI.Setting.Event.Changed, setWhitespaceCharacterClassName);
264     setWhitespaceCharacterClassName();
265
266     this.settingsTabContentView = new WI.SettingsTabContentView;
267
268     this._settingsKeyboardShortcut = new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl, WI.KeyboardShortcut.Key.Comma, this._showSettingsTab.bind(this));
269
270     // Create the user interface elements.
271     this.toolbar = new WI.Toolbar(document.getElementById("toolbar"));
272
273     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     let anchorElement = event.target.enclosingNodeOrSelfWithNodeName("a");
779     if (!anchorElement || !anchorElement.href)
780         return false;
781
782     if (WI.isBeingEdited(anchorElement)) {
783         // Don't follow the link when it is being edited.
784         return false;
785     }
786
787     // Prevent the link from navigating, since we don't do any navigation by following links normally.
788     event.preventDefault();
789     event.stopPropagation();
790
791     this.openURL(anchorElement.href, frame, Object.shallowMerge(options, {
792         lineNumber: anchorElement.lineNumber,
793         ignoreSearchTab: !WI.isShowingSearchTab(),
794     }));
795
796     return true;
797 };
798
799 WI.openURL = function(url, frame, options = {})
800 {
801     console.assert(url);
802     if (!url)
803         return;
804
805     console.assert(typeof options.lineNumber === "undefined" || typeof options.lineNumber === "number", "lineNumber should be a number.");
806
807     // If alwaysOpenExternally is not defined, base it off the command/meta key for the current event.
808     if (options.alwaysOpenExternally === undefined || options.alwaysOpenExternally === null)
809         options.alwaysOpenExternally = window.event ? window.event.metaKey : false;
810
811     if (options.alwaysOpenExternally) {
812         InspectorFrontendHost.openInNewTab(url);
813         return;
814     }
815
816     let searchChildFrames = false;
817     if (!frame) {
818         frame = this.frameResourceManager.mainFrame;
819         searchChildFrames = true;
820     }
821
822     let resource;
823     let simplifiedURL = removeURLFragment(url);
824     if (frame) {
825         // WI.Frame.resourceForURL does not check the main resource, only sub-resources. So check both.
826         resource = frame.url === simplifiedURL ? frame.mainResource : frame.resourceForURL(simplifiedURL, searchChildFrames);
827     } else if (WI.sharedApp.debuggableType === WI.DebuggableType.ServiceWorker)
828         resource = WI.mainTarget.resourceCollection.resourceForURL(removeURLFragment(url));
829
830     if (resource) {
831         let positionToReveal = new WI.SourceCodePosition(options.lineNumber, 0);
832         this.showSourceCode(resource, Object.shallowMerge(options, {positionToReveal}));
833         return;
834     }
835
836     InspectorFrontendHost.openInNewTab(url);
837 };
838
839 WI.close = function()
840 {
841     if (this._isClosing)
842         return;
843
844     this._isClosing = true;
845
846     InspectorFrontendHost.closeWindow();
847 };
848
849 WI.isConsoleFocused = function()
850 {
851     return this.quickConsole.prompt.focused;
852 };
853
854 WI.isShowingSplitConsole = function()
855 {
856     return !this.consoleDrawer.collapsed;
857 };
858
859 WI.dockedConfigurationSupportsSplitContentBrowser = function()
860 {
861     return this._dockConfiguration !== WI.DockConfiguration.Bottom;
862 };
863
864 WI.doesCurrentTabSupportSplitContentBrowser = function()
865 {
866     var currentContentView = this.tabBrowser.selectedTabContentView;
867     return !currentContentView || currentContentView.supportsSplitContentBrowser;
868 };
869
870 WI.toggleSplitConsole = function()
871 {
872     if (!this.doesCurrentTabSupportSplitContentBrowser()) {
873         this.showConsoleTab();
874         return;
875     }
876
877     if (this.isShowingSplitConsole())
878         this.hideSplitConsole();
879     else
880         this.showSplitConsole();
881 };
882
883 WI.showSplitConsole = function()
884 {
885     if (!this.doesCurrentTabSupportSplitContentBrowser()) {
886         this.showConsoleTab();
887         return;
888     }
889
890     this.consoleDrawer.collapsed = false;
891
892     if (this.consoleDrawer.currentContentView === this.consoleContentView)
893         return;
894
895     this.consoleDrawer.showContentView(this.consoleContentView);
896 };
897
898 WI.hideSplitConsole = function()
899 {
900     if (!this.isShowingSplitConsole())
901         return;
902
903     this.consoleDrawer.collapsed = true;
904 };
905
906 WI.showConsoleTab = function(requestedScope)
907 {
908     requestedScope = requestedScope || WI.LogContentView.Scopes.All;
909
910     this.hideSplitConsole();
911
912     this.consoleContentView.scopeBar.item(requestedScope).selected = true;
913
914     this.showRepresentedObject(this._consoleRepresentedObject);
915
916     console.assert(this.isShowingConsoleTab());
917 };
918
919 WI.isShowingConsoleTab = function()
920 {
921     return this.tabBrowser.selectedTabContentView instanceof WI.ConsoleTabContentView;
922 };
923
924 WI.showElementsTab = function()
925 {
926     var tabContentView = this.tabBrowser.bestTabContentViewForClass(WI.ElementsTabContentView);
927     if (!tabContentView)
928         tabContentView = new WI.ElementsTabContentView;
929     this.tabBrowser.showTabForContentView(tabContentView);
930 };
931
932 WI.showDebuggerTab = function(options)
933 {
934     var tabContentView = this.tabBrowser.bestTabContentViewForClass(WI.DebuggerTabContentView);
935     if (!tabContentView)
936         tabContentView = new WI.DebuggerTabContentView;
937
938     if (options.breakpointToSelect instanceof WI.Breakpoint)
939         tabContentView.revealAndSelectBreakpoint(options.breakpointToSelect);
940
941     if (options.showScopeChainSidebar)
942         tabContentView.showScopeChainDetailsSidebarPanel();
943
944     this.tabBrowser.showTabForContentView(tabContentView);
945 };
946
947 WI.isShowingDebuggerTab = function()
948 {
949     return this.tabBrowser.selectedTabContentView instanceof WI.DebuggerTabContentView;
950 };
951
952 WI.showResourcesTab = function()
953 {
954     var tabContentView = this.tabBrowser.bestTabContentViewForClass(WI.ResourcesTabContentView);
955     if (!tabContentView)
956         tabContentView = new WI.ResourcesTabContentView;
957     this.tabBrowser.showTabForContentView(tabContentView);
958 };
959
960 WI.isShowingResourcesTab = function()
961 {
962     return this.tabBrowser.selectedTabContentView instanceof WI.ResourcesTabContentView;
963 };
964
965 WI.showStorageTab = function()
966 {
967     var tabContentView = this.tabBrowser.bestTabContentViewForClass(WI.StorageTabContentView);
968     if (!tabContentView)
969         tabContentView = new WI.StorageTabContentView;
970     this.tabBrowser.showTabForContentView(tabContentView);
971 };
972
973 WI.showNetworkTab = function()
974 {
975     let tabContentView = this.tabBrowser.bestTabContentViewForClass(WI.NetworkTabContentView);
976     if (!tabContentView)
977         tabContentView = new WI.NetworkTabContentView;
978
979     this.tabBrowser.showTabForContentView(tabContentView);
980 };
981
982 WI.isShowingNetworkTab = function()
983 {
984     return this.tabBrowser.selectedTabContentView instanceof WI.NetworkTabContentView;
985 };
986
987 WI.isShowingSearchTab = function()
988 {
989     return this.tabBrowser.selectedTabContentView instanceof WI.SearchTabContentView;
990 };
991
992 WI.showTimelineTab = function()
993 {
994     var tabContentView = this.tabBrowser.bestTabContentViewForClass(WI.TimelineTabContentView);
995     if (!tabContentView)
996         tabContentView = new WI.TimelineTabContentView;
997     this.tabBrowser.showTabForContentView(tabContentView);
998 };
999
1000 WI.indentString = function()
1001 {
1002     if (WI.settings.indentWithTabs.value)
1003         return "\t";
1004     return " ".repeat(WI.settings.indentUnit.value);
1005 };
1006
1007 WI.restoreFocusFromElement = function(element)
1008 {
1009     if (element && element.isSelfOrAncestor(this.currentFocusElement))
1010         this.previousFocusElement.focus();
1011 };
1012
1013 WI.toggleNavigationSidebar = function(event)
1014 {
1015     if (!this.navigationSidebar.collapsed || !this.navigationSidebar.sidebarPanels.length) {
1016         this.navigationSidebar.collapsed = true;
1017         return;
1018     }
1019
1020     if (!this.navigationSidebar.selectedSidebarPanel)
1021         this.navigationSidebar.selectedSidebarPanel = this.navigationSidebar.sidebarPanels[0];
1022     this.navigationSidebar.collapsed = false;
1023 };
1024
1025 WI.toggleDetailsSidebar = function(event)
1026 {
1027     if (!this.detailsSidebar.collapsed || !this.detailsSidebar.sidebarPanels.length) {
1028         this.detailsSidebar.collapsed = true;
1029         return;
1030     }
1031
1032     if (!this.detailsSidebar.selectedSidebarPanel)
1033         this.detailsSidebar.selectedSidebarPanel = this.detailsSidebar.sidebarPanels[0];
1034     this.detailsSidebar.collapsed = false;
1035 };
1036
1037 WI.getMaximumSidebarWidth = function(sidebar)
1038 {
1039     console.assert(sidebar instanceof WI.Sidebar);
1040
1041     const minimumContentBrowserWidth = 100;
1042
1043     let minimumWidth = window.innerWidth - minimumContentBrowserWidth;
1044     let tabContentView = this.tabBrowser.selectedTabContentView;
1045     console.assert(tabContentView);
1046     if (!tabContentView)
1047         return minimumWidth;
1048
1049     let otherSidebar = null;
1050     if (sidebar === this.navigationSidebar)
1051         otherSidebar = tabContentView.detailsSidebarPanels.length ? this.detailsSidebar : null;
1052     else
1053         otherSidebar = tabContentView.navigationSidebarPanel ? this.navigationSidebar : null;
1054
1055     if (otherSidebar)
1056         minimumWidth -= otherSidebar.width;
1057
1058     return minimumWidth;
1059 };
1060
1061 WI.tabContentViewClassForRepresentedObject = function(representedObject)
1062 {
1063     if (representedObject instanceof WI.DOMTree)
1064         return WI.ElementsTabContentView;
1065
1066     if (representedObject instanceof WI.TimelineRecording)
1067         return WI.TimelineTabContentView;
1068
1069     // We only support one console tab right now. So this isn't an instanceof check.
1070     if (representedObject === this._consoleRepresentedObject)
1071         return WI.ConsoleTabContentView;
1072
1073     if (WI.debuggerManager.paused) {
1074         if (representedObject instanceof WI.Script)
1075             return WI.DebuggerTabContentView;
1076
1077         if (representedObject instanceof WI.Resource && (representedObject.type === WI.Resource.Type.Document || representedObject.type === WI.Resource.Type.Script))
1078             return WI.DebuggerTabContentView;
1079     }
1080
1081     if (representedObject instanceof WI.Frame
1082         || representedObject instanceof WI.Resource
1083         || representedObject instanceof WI.Script
1084         || representedObject instanceof WI.CSSStyleSheet
1085         || (representedObject instanceof WI.Collection && !(representedObject instanceof WI.CanvasCollection)))
1086         return WI.ResourcesTabContentView;
1087
1088     // FIXME: Move these to a Storage tab.
1089     if (representedObject instanceof WI.DOMStorageObject || representedObject instanceof WI.CookieStorageObject ||
1090         representedObject instanceof WI.DatabaseTableObject || representedObject instanceof WI.DatabaseObject ||
1091         representedObject instanceof WI.ApplicationCacheFrame || representedObject instanceof WI.IndexedDatabaseObjectStore ||
1092         representedObject instanceof WI.IndexedDatabaseObjectStoreIndex)
1093         return WI.ResourcesTabContentView;
1094
1095     if (representedObject instanceof WI.CanvasCollection)
1096         return WI.CanvasTabContentView;
1097
1098     if (representedObject instanceof WI.Recording)
1099         return WI.CanvasTabContentView;
1100
1101     return null;
1102 };
1103
1104 WI.tabContentViewForRepresentedObject = function(representedObject, options = {})
1105 {
1106     let tabContentView = this.tabBrowser.bestTabContentViewForRepresentedObject(representedObject, options);
1107     if (tabContentView)
1108         return tabContentView;
1109
1110     var tabContentViewClass = this.tabContentViewClassForRepresentedObject(representedObject);
1111     if (!tabContentViewClass) {
1112         console.error("Unknown representedObject, couldn't create TabContentView.", representedObject);
1113         return null;
1114     }
1115
1116     tabContentView = new tabContentViewClass;
1117
1118     this.tabBrowser.addTabForContentView(tabContentView);
1119
1120     return tabContentView;
1121 };
1122
1123 WI.showRepresentedObject = function(representedObject, cookie, options = {})
1124 {
1125     let tabContentView = this.tabContentViewForRepresentedObject(representedObject, options);
1126     console.assert(tabContentView);
1127     if (!tabContentView)
1128         return;
1129
1130     this.tabBrowser.showTabForContentView(tabContentView, options);
1131     tabContentView.showRepresentedObject(representedObject, cookie);
1132 };
1133
1134 WI.showMainFrameDOMTree = function(nodeToSelect, options = {})
1135 {
1136     console.assert(WI.frameResourceManager.mainFrame);
1137     if (!WI.frameResourceManager.mainFrame)
1138         return;
1139     this.showRepresentedObject(WI.frameResourceManager.mainFrame.domTree, {nodeToSelect}, options);
1140 };
1141
1142 WI.showSourceCodeForFrame = function(frameIdentifier, options = {})
1143 {
1144     var frame = WI.frameResourceManager.frameForIdentifier(frameIdentifier);
1145     if (!frame) {
1146         this._frameIdentifierToShowSourceCodeWhenAvailable = frameIdentifier;
1147         return;
1148     }
1149
1150     this._frameIdentifierToShowSourceCodeWhenAvailable = undefined;
1151
1152     this.showRepresentedObject(frame, null, options);
1153 };
1154
1155 WI.showSourceCode = function(sourceCode, options = {})
1156 {
1157     const positionToReveal = options.positionToReveal;
1158
1159     console.assert(!positionToReveal || positionToReveal instanceof WI.SourceCodePosition, positionToReveal);
1160     var representedObject = sourceCode;
1161
1162     if (representedObject instanceof WI.Script) {
1163         // A script represented by a resource should always show the resource.
1164         representedObject = representedObject.resource || representedObject;
1165     }
1166
1167     var cookie = positionToReveal ? {lineNumber: positionToReveal.lineNumber, columnNumber: positionToReveal.columnNumber} : {};
1168     this.showRepresentedObject(representedObject, cookie, options);
1169 };
1170
1171 WI.showSourceCodeLocation = function(sourceCodeLocation, options = {})
1172 {
1173     this.showSourceCode(sourceCodeLocation.displaySourceCode, Object.shallowMerge(options, {
1174         positionToReveal: sourceCodeLocation.displayPosition(),
1175     }));
1176 };
1177
1178 WI.showOriginalUnformattedSourceCodeLocation = function(sourceCodeLocation, options = {})
1179 {
1180     this.showSourceCode(sourceCodeLocation.sourceCode, Object.shallowMerge(options, {
1181         positionToReveal: sourceCodeLocation.position(),
1182         forceUnformatted: true,
1183     }));
1184 };
1185
1186 WI.showOriginalOrFormattedSourceCodeLocation = function(sourceCodeLocation, options = {})
1187 {
1188     this.showSourceCode(sourceCodeLocation.sourceCode, Object.shallowMerge(options, {
1189         positionToReveal: sourceCodeLocation.formattedPosition(),
1190     }));
1191 };
1192
1193 WI.showOriginalOrFormattedSourceCodeTextRange = function(sourceCodeTextRange, options = {})
1194 {
1195     var textRangeToSelect = sourceCodeTextRange.formattedTextRange;
1196     this.showSourceCode(sourceCodeTextRange.sourceCode, Object.shallowMerge(options, {
1197         positionToReveal: textRangeToSelect.startPosition(),
1198         textRangeToSelect,
1199     }));
1200 };
1201
1202 WI.showResourceRequest = function(resource, options = {})
1203 {
1204     this.showRepresentedObject(resource, {[WI.ResourceClusterContentView.ContentViewIdentifierCookieKey]: WI.ResourceClusterContentView.RequestIdentifier}, options);
1205 };
1206
1207 WI.debuggerToggleBreakpoints = function(event)
1208 {
1209     WI.debuggerManager.breakpointsEnabled = !WI.debuggerManager.breakpointsEnabled;
1210 };
1211
1212 WI.debuggerPauseResumeToggle = function(event)
1213 {
1214     if (WI.debuggerManager.paused)
1215         WI.debuggerManager.resume();
1216     else
1217         WI.debuggerManager.pause();
1218 };
1219
1220 WI.debuggerStepOver = function(event)
1221 {
1222     WI.debuggerManager.stepOver();
1223 };
1224
1225 WI.debuggerStepInto = function(event)
1226 {
1227     WI.debuggerManager.stepInto();
1228 };
1229
1230 WI.debuggerStepOut = function(event)
1231 {
1232     WI.debuggerManager.stepOut();
1233 };
1234
1235 WI._searchTextDidChange = function(event)
1236 {
1237     var tabContentView = this.tabBrowser.bestTabContentViewForClass(WI.SearchTabContentView);
1238     if (!tabContentView)
1239         tabContentView = new WI.SearchTabContentView;
1240
1241     var searchQuery = this._searchToolbarItem.text;
1242     this._searchToolbarItem.text = "";
1243
1244     this.tabBrowser.showTabForContentView(tabContentView);
1245
1246     tabContentView.performSearch(searchQuery);
1247 };
1248
1249 WI._focusSearchField = function(event)
1250 {
1251     if (this.tabBrowser.selectedTabContentView instanceof WI.SearchTabContentView) {
1252         this.tabBrowser.selectedTabContentView.focusSearchField();
1253         return;
1254     }
1255
1256     this._searchToolbarItem.focus();
1257 };
1258
1259 WI._focusChanged = function(event)
1260 {
1261     // Make a caret selection inside the focused element if there isn't a range selection and there isn't already
1262     // a caret selection inside. This is needed (at least) to remove caret from console when focus is moved.
1263     // The selection change should not apply to text fields and text areas either.
1264
1265     if (WI.isEventTargetAnEditableField(event)) {
1266         // Still update the currentFocusElement if inside of a CodeMirror editor.
1267         var codeMirrorEditorElement = event.target.enclosingNodeOrSelfWithClass("CodeMirror");
1268         if (codeMirrorEditorElement && codeMirrorEditorElement !== this.currentFocusElement) {
1269             this.previousFocusElement = this.currentFocusElement;
1270             this.currentFocusElement = codeMirrorEditorElement;
1271         }
1272
1273         // Due to the change in WI.isEventTargetAnEditableField (r196271), this return
1274         // will also get run when WI.startEditing is called on an element. We do not want
1275         // to return early in this case, as WI.EditingConfig handles its own editing
1276         // completion, so only return early if the focus change target is not from WI.startEditing.
1277         if (!WI.isBeingEdited(event.target))
1278             return;
1279     }
1280
1281     var selection = window.getSelection();
1282     if (!selection.isCollapsed)
1283         return;
1284
1285     var element = event.target;
1286
1287     if (element !== this.currentFocusElement) {
1288         this.previousFocusElement = this.currentFocusElement;
1289         this.currentFocusElement = element;
1290     }
1291
1292     if (element.isInsertionCaretInside())
1293         return;
1294
1295     var selectionRange = element.ownerDocument.createRange();
1296     selectionRange.setStart(element, 0);
1297     selectionRange.setEnd(element, 0);
1298
1299     selection.removeAllRanges();
1300     selection.addRange(selectionRange);
1301 };
1302
1303 WI._mouseWasClicked = function(event)
1304 {
1305     this.handlePossibleLinkClick(event);
1306 };
1307
1308 WI._dragOver = function(event)
1309 {
1310     // Do nothing if another event listener handled the event already.
1311     if (event.defaultPrevented)
1312         return;
1313
1314     // Allow dropping into editable areas.
1315     if (WI.isEventTargetAnEditableField(event))
1316         return;
1317
1318     // Prevent the drop from being accepted.
1319     event.dataTransfer.dropEffect = "none";
1320     event.preventDefault();
1321 };
1322
1323 WI._debuggerDidPause = function(event)
1324 {
1325     this.showDebuggerTab({showScopeChainSidebar: WI.settings.showScopeChainOnPause.value});
1326
1327     this._dashboardContainer.showDashboardViewForRepresentedObject(this.dashboardManager.dashboards.debugger);
1328
1329     InspectorFrontendHost.bringToFront();
1330 };
1331
1332 WI._debuggerDidResume = function(event)
1333 {
1334     this._dashboardContainer.closeDashboardViewForRepresentedObject(this.dashboardManager.dashboards.debugger);
1335 };
1336
1337 WI._frameWasAdded = function(event)
1338 {
1339     if (!this._frameIdentifierToShowSourceCodeWhenAvailable)
1340         return;
1341
1342     var frame = event.data.frame;
1343     if (frame.id !== this._frameIdentifierToShowSourceCodeWhenAvailable)
1344         return;
1345
1346     function delayedWork()
1347     {
1348         const options = {
1349             ignoreNetworkTab: true,
1350             ignoreSearchTab: true,
1351         };
1352         this.showSourceCodeForFrame(frame.id, options);
1353     }
1354
1355     // Delay showing the frame since FrameWasAdded is called before MainFrameChanged.
1356     // Calling showSourceCodeForFrame before MainFrameChanged will show the frame then close it.
1357     setTimeout(delayedWork.bind(this));
1358 };
1359
1360 WI._mainFrameDidChange = function(event)
1361 {
1362     this._updateDownloadToolbarButton();
1363
1364     this.updateWindowTitle();
1365 };
1366
1367 WI._mainResourceDidChange = function(event)
1368 {
1369     if (!event.target.isMainFrame())
1370         return;
1371
1372     this._inProvisionalLoad = false;
1373
1374     // Run cookie restoration after we are sure all of the Tabs and NavigationSidebarPanels
1375     // have updated with respect to the main resource change.
1376     setTimeout(this._restoreCookieForOpenTabs.bind(this, WI.StateRestorationType.Navigation));
1377
1378     this._updateDownloadToolbarButton();
1379
1380     this.updateWindowTitle();
1381 };
1382
1383 WI._provisionalLoadStarted = function(event)
1384 {
1385     if (!event.target.isMainFrame())
1386         return;
1387
1388     this._saveCookieForOpenTabs();
1389
1390     this._inProvisionalLoad = true;
1391 };
1392
1393 WI._restoreCookieForOpenTabs = function(restorationType)
1394 {
1395     for (var tabBarItem of this.tabBar.tabBarItems) {
1396         var tabContentView = tabBarItem.representedObject;
1397         if (!(tabContentView instanceof WI.TabContentView))
1398             continue;
1399         tabContentView.restoreStateFromCookie(restorationType);
1400     }
1401 };
1402
1403 WI._saveCookieForOpenTabs = function()
1404 {
1405     for (var tabBarItem of this.tabBar.tabBarItems) {
1406         var tabContentView = tabBarItem.representedObject;
1407         if (!(tabContentView instanceof WI.TabContentView))
1408             continue;
1409         tabContentView.saveStateToCookie();
1410     }
1411 };
1412
1413 WI._windowFocused = function(event)
1414 {
1415     if (event.target.document.nodeType !== Node.DOCUMENT_NODE)
1416         return;
1417
1418     // FIXME: We should use the :window-inactive pseudo class once https://webkit.org/b/38927 is fixed.
1419     document.body.classList.remove(this.docked ? "window-docked-inactive" : "window-inactive");
1420 };
1421
1422 WI._windowBlurred = function(event)
1423 {
1424     if (event.target.document.nodeType !== Node.DOCUMENT_NODE)
1425         return;
1426
1427     // FIXME: We should use the :window-inactive pseudo class once https://webkit.org/b/38927 is fixed.
1428     document.body.classList.add(this.docked ? "window-docked-inactive" : "window-inactive");
1429 };
1430
1431 WI._windowResized = function(event)
1432 {
1433     this.toolbar.updateLayout(WI.View.LayoutReason.Resize);
1434     this.tabBar.updateLayout(WI.View.LayoutReason.Resize);
1435     this._tabBrowserSizeDidChange();
1436 };
1437
1438 WI._updateModifierKeys = function(event)
1439 {
1440     let metaKeyDidChange = this.modifierKeys.metaKey !== event.metaKey;
1441     let didChange = this.modifierKeys.altKey !== event.altKey || metaKeyDidChange || this.modifierKeys.shiftKey !== event.shiftKey;
1442
1443     this.modifierKeys = {altKey: event.altKey, metaKey: event.metaKey, shiftKey: event.shiftKey};
1444
1445     if (metaKeyDidChange)
1446         document.body.classList.toggle("meta-key-pressed", this.modifierKeys.metaKey);
1447
1448     if (didChange)
1449         this.notifications.dispatchEventToListeners(WI.Notification.GlobalModifierKeysDidChange, event);
1450 };
1451
1452 WI._windowKeyDown = function(event)
1453 {
1454     this._updateModifierKeys(event);
1455 };
1456
1457 WI._windowKeyUp = function(event)
1458 {
1459     this._updateModifierKeys(event);
1460 };
1461
1462 WI._mouseDown = function(event)
1463 {
1464     if (this.toolbar.element.isSelfOrAncestor(event.target))
1465         this._toolbarMouseDown(event);
1466 };
1467
1468 WI._mouseMoved = function(event)
1469 {
1470     this._updateModifierKeys(event);
1471     this.mouseCoords = {
1472         x: event.pageX,
1473         y: event.pageY
1474     };
1475 };
1476
1477 WI._pageHidden = function(event)
1478 {
1479     this._saveCookieForOpenTabs();
1480 };
1481
1482 WI._contextMenuRequested = function(event)
1483 {
1484     let proposedContextMenu;
1485
1486     // This is setting is only defined in engineering builds.
1487     if (WI.isDebugUIEnabled()) {
1488         proposedContextMenu = WI.ContextMenu.createFromEvent(event);
1489         proposedContextMenu.appendSeparator();
1490         proposedContextMenu.appendItem(WI.unlocalizedString("Reload Web Inspector"), () => {
1491             window.location.reload();
1492         });
1493
1494         let protocolSubMenu = proposedContextMenu.appendSubMenuItem(WI.unlocalizedString("Protocol Debugging"), null, false);
1495         let isCapturingTraffic = InspectorBackend.activeTracer instanceof WI.CapturingProtocolTracer;
1496
1497         protocolSubMenu.appendCheckboxItem(WI.unlocalizedString("Capture Trace"), () => {
1498             if (isCapturingTraffic)
1499                 InspectorBackend.activeTracer = null;
1500             else
1501                 InspectorBackend.activeTracer = new WI.CapturingProtocolTracer;
1502         }, isCapturingTraffic);
1503
1504         protocolSubMenu.appendSeparator();
1505
1506         protocolSubMenu.appendItem(WI.unlocalizedString("Export Trace\u2026"), () => {
1507             const forceSaveAs = true;
1508             WI.saveDataToFile(InspectorBackend.activeTracer.trace.saveData, forceSaveAs);
1509         }, !isCapturingTraffic);
1510     } else {
1511         const onlyExisting = true;
1512         proposedContextMenu = WI.ContextMenu.createFromEvent(event, onlyExisting);
1513     }
1514
1515     if (proposedContextMenu)
1516         proposedContextMenu.show();
1517 };
1518
1519 WI.isDebugUIEnabled = function()
1520 {
1521     return WI.showDebugUISetting && WI.showDebugUISetting.value;
1522 };
1523
1524 WI._undock = function(event)
1525 {
1526     InspectorFrontendHost.requestSetDockSide(WI.DockConfiguration.Undocked);
1527 };
1528
1529 WI._dockBottom = function(event)
1530 {
1531     InspectorFrontendHost.requestSetDockSide(WI.DockConfiguration.Bottom);
1532 };
1533
1534 WI._dockRight = function(event)
1535 {
1536     InspectorFrontendHost.requestSetDockSide(WI.DockConfiguration.Right);
1537 };
1538
1539 WI._dockLeft = function(event)
1540 {
1541     InspectorFrontendHost.requestSetDockSide(WI.DockConfiguration.Left);
1542 };
1543
1544 WI._togglePreviousDockConfiguration = function(event)
1545 {
1546     InspectorFrontendHost.requestSetDockSide(this._previousDockConfiguration);
1547 };
1548
1549 WI._updateDockNavigationItems = function()
1550 {
1551     if (this._dockingAvailable || this.docked) {
1552         this._closeToolbarButton.hidden = !this.docked;
1553         this._undockToolbarButton.hidden = this._dockConfiguration === WI.DockConfiguration.Undocked;
1554         this._dockBottomToolbarButton.hidden = this._dockConfiguration === WI.DockConfiguration.Bottom;
1555         this._dockToSideToolbarButton.hidden = this._dockConfiguration === WI.DockConfiguration.Right || this._dockConfiguration === WI.DockConfiguration.Left;
1556     } else {
1557         this._closeToolbarButton.hidden = true;
1558         this._undockToolbarButton.hidden = true;
1559         this._dockBottomToolbarButton.hidden = true;
1560         this._dockToSideToolbarButton.hidden = true;
1561     }
1562 };
1563
1564 WI._tabBrowserSizeDidChange = function()
1565 {
1566     this.tabBrowser.updateLayout(WI.View.LayoutReason.Resize);
1567     this.consoleDrawer.updateLayout(WI.View.LayoutReason.Resize);
1568     this.quickConsole.updateLayout(WI.View.LayoutReason.Resize);
1569 };
1570
1571 WI._consoleDrawerCollapsedStateDidChange = function(event)
1572 {
1573     this._showingSplitConsoleSetting.value = WI.isShowingSplitConsole();
1574
1575     WI._consoleDrawerDidResize();
1576 };
1577
1578 WI._consoleDrawerDidResize = function(event)
1579 {
1580     this.tabBrowser.updateLayout(WI.View.LayoutReason.Resize);
1581 };
1582
1583 WI._sidebarWidthDidChange = function(event)
1584 {
1585     this._tabBrowserSizeDidChange();
1586 };
1587
1588 WI._setupViewHierarchy = function()
1589 {
1590     let rootView = WI.View.rootView();
1591     rootView.addSubview(this.toolbar);
1592     rootView.addSubview(this.tabBar);
1593     rootView.addSubview(this.navigationSidebar);
1594     rootView.addSubview(this.tabBrowser);
1595     rootView.addSubview(this.consoleDrawer);
1596     rootView.addSubview(this.quickConsole);
1597     rootView.addSubview(this.detailsSidebar);
1598 };
1599
1600 WI._tabBrowserSelectedTabContentViewDidChange = function(event)
1601 {
1602     if (this.tabBar.selectedTabBarItem && this.tabBar.selectedTabBarItem.representedObject.constructor.shouldSaveTab())
1603         this._selectedTabIndexSetting.value = this.tabBar.tabBarItems.indexOf(this.tabBar.selectedTabBarItem);
1604
1605     if (this.doesCurrentTabSupportSplitContentBrowser()) {
1606         if (this._shouldRevealSpitConsoleIfSupported) {
1607             this._shouldRevealSpitConsoleIfSupported = false;
1608             this.showSplitConsole();
1609         }
1610         return;
1611     }
1612
1613     this._shouldRevealSpitConsoleIfSupported = this.isShowingSplitConsole();
1614     this.hideSplitConsole();
1615 };
1616
1617 WI._toolbarMouseDown = function(event)
1618 {
1619     if (event.ctrlKey)
1620         return;
1621
1622     if (this._dockConfiguration === WI.DockConfiguration.Right || this._dockConfiguration === WI.DockConfiguration.Left)
1623         return;
1624
1625     if (this.docked)
1626         this._dockedResizerMouseDown(event);
1627     else
1628         this._moveWindowMouseDown(event);
1629 };
1630
1631 WI._dockedResizerMouseDown = function(event)
1632 {
1633     if (event.button !== 0 || event.ctrlKey)
1634         return;
1635
1636     if (!this.docked)
1637         return;
1638
1639     // Only start dragging if the target is one of the elements that we expect.
1640     if (event.target.id !== "docked-resizer" && !event.target.classList.contains("toolbar") &&
1641         !event.target.classList.contains("flexible-space") && !event.target.classList.contains("item-section"))
1642         return;
1643
1644     event[WI.Popover.EventPreventDismissSymbol] = true;
1645
1646     let windowProperty = this._dockConfiguration === WI.DockConfiguration.Bottom ? "innerHeight" : "innerWidth";
1647     let eventScreenProperty = this._dockConfiguration === WI.DockConfiguration.Bottom ? "screenY" : "screenX";
1648     let eventClientProperty = this._dockConfiguration === WI.DockConfiguration.Bottom ? "clientY" : "clientX";
1649
1650     var resizerElement = event.target;
1651     var firstClientPosition = event[eventClientProperty];
1652     var lastScreenPosition = event[eventScreenProperty];
1653
1654     function dockedResizerDrag(event)
1655     {
1656         if (event.button !== 0)
1657             return;
1658
1659         var position = event[eventScreenProperty];
1660         var delta = position - lastScreenPosition;
1661         var clientPosition = event[eventClientProperty];
1662
1663         lastScreenPosition = position;
1664
1665         if (this._dockConfiguration === WI.DockConfiguration.Left) {
1666             // If the mouse is travelling rightward but is positioned left of the resizer, ignore the event.
1667             if (delta > 0 && clientPosition < firstClientPosition)
1668                 return;
1669
1670             // If the mouse is travelling leftward but is positioned to the right of the resizer, ignore the event.
1671             if (delta < 0 && clientPosition > window[windowProperty])
1672                 return;
1673
1674             // We later subtract the delta from the current position, but since the inspected view and inspector view
1675             // are flipped when docked to left, we want dragging to have the opposite effect from docked to right.
1676             delta *= -1;
1677         } else {
1678             // If the mouse is travelling downward/rightward but is positioned above/left of the resizer, ignore the event.
1679             if (delta > 0 && clientPosition < firstClientPosition)
1680                 return;
1681
1682             // If the mouse is travelling upward/leftward but is positioned below/right of the resizer, ignore the event.
1683             if (delta < 0 && clientPosition > firstClientPosition)
1684                 return;
1685         }
1686
1687         let dimension = Math.max(0, window[windowProperty] - delta);
1688         // If zoomed in/out, there be greater/fewer document pixels shown, but the inspector's
1689         // width or height should be the same in device pixels regardless of the document zoom.
1690         dimension *= this.getZoomFactor();
1691
1692         if (this._dockConfiguration === WI.DockConfiguration.Bottom)
1693             InspectorFrontendHost.setAttachedWindowHeight(dimension);
1694         else
1695             InspectorFrontendHost.setAttachedWindowWidth(dimension);
1696     }
1697
1698     function dockedResizerDragEnd(event)
1699     {
1700         if (event.button !== 0)
1701             return;
1702
1703         WI.elementDragEnd(event);
1704     }
1705
1706     WI.elementDragStart(resizerElement, dockedResizerDrag.bind(this), dockedResizerDragEnd.bind(this), event, this._dockConfiguration === WI.DockConfiguration.Bottom ? "row-resize" : "col-resize");
1707 };
1708
1709 WI._moveWindowMouseDown = function(event)
1710 {
1711     console.assert(!this.docked);
1712
1713     if (event.button !== 0 || event.ctrlKey)
1714         return;
1715
1716     // Only start dragging if the target is one of the elements that we expect.
1717     if (!event.target.classList.contains("toolbar") && !event.target.classList.contains("flexible-space") &&
1718         !event.target.classList.contains("item-section"))
1719         return;
1720
1721     event[WI.Popover.EventPreventDismissSymbol] = true;
1722
1723     if (WI.Platform.name === "mac") {
1724         // New Mac releases can start a window drag.
1725         if (WI.Platform.version.release >= 11) {
1726             InspectorFrontendHost.startWindowDrag();
1727             event.preventDefault();
1728             return;
1729         }
1730
1731         // Ignore dragging on the top of the toolbar on Mac if the system handles it.
1732         if (WI.Platform.version.release === 10) {
1733             const windowDragHandledTitleBarHeight = 22;
1734             if (event.pageY < windowDragHandledTitleBarHeight) {
1735                 event.preventDefault();
1736                 return;
1737             }
1738         }
1739     }
1740
1741     var lastScreenX = event.screenX;
1742     var lastScreenY = event.screenY;
1743
1744     function toolbarDrag(event)
1745     {
1746         if (event.button !== 0)
1747             return;
1748
1749         var x = event.screenX - lastScreenX;
1750         var y = event.screenY - lastScreenY;
1751
1752         InspectorFrontendHost.moveWindowBy(x, y);
1753
1754         lastScreenX = event.screenX;
1755         lastScreenY = event.screenY;
1756     }
1757
1758     function toolbarDragEnd(event)
1759     {
1760         if (event.button !== 0)
1761             return;
1762
1763         WI.elementDragEnd(event);
1764     }
1765
1766     WI.elementDragStart(event.target, toolbarDrag, toolbarDragEnd, event, "default");
1767 };
1768
1769 WI._storageWasInspected = function(event)
1770 {
1771     this.showStorageTab();
1772 };
1773
1774 WI._domNodeWasInspected = function(event)
1775 {
1776     this.domTreeManager.highlightDOMNodeForTwoSeconds(event.data.node.id);
1777
1778     InspectorFrontendHost.bringToFront();
1779
1780     this.showElementsTab();
1781     this.showMainFrameDOMTree(event.data.node, {ignoreSearchTab: true});
1782 };
1783
1784 WI._inspectModeStateChanged = function(event)
1785 {
1786     this._inspectModeToolbarButton.activated = this.domTreeManager.inspectModeEnabled;
1787 };
1788
1789 WI._toggleInspectMode = function(event)
1790 {
1791     this.domTreeManager.inspectModeEnabled = !this.domTreeManager.inspectModeEnabled;
1792 };
1793
1794 WI._downloadWebArchive = function(event)
1795 {
1796     this.archiveMainFrame();
1797 };
1798
1799 WI._reloadPage = function(event)
1800 {
1801     if (!window.PageAgent)
1802         return;
1803
1804     PageAgent.reload();
1805     event.preventDefault();
1806 };
1807
1808 WI._reloadToolbarButtonClicked = function(event)
1809 {
1810     // Reload page from origin if the button is clicked while the shift key is pressed down.
1811     PageAgent.reload.invoke({ignoreCache: this.modifierKeys.shiftKey});
1812 };
1813
1814 WI._reloadPageFromOrigin = function(event)
1815 {
1816     if (!window.PageAgent)
1817         return;
1818
1819     PageAgent.reload.invoke({ignoreCache: true});
1820     event.preventDefault();
1821 };
1822
1823 WI._updateReloadToolbarButton = function()
1824 {
1825     if (!window.PageAgent) {
1826         this._reloadToolbarButton.hidden = true;
1827         return;
1828     }
1829
1830     this._reloadToolbarButton.hidden = false;
1831 };
1832
1833 WI._updateDownloadToolbarButton = function()
1834 {
1835     // COMPATIBILITY (iOS 7): Page.archive did not exist yet.
1836     if (!window.PageAgent || !PageAgent.archive || this.sharedApp.debuggableType !== WI.DebuggableType.Web) {
1837         this._downloadToolbarButton.hidden = true;
1838         return;
1839     }
1840
1841     if (this._downloadingPage) {
1842         this._downloadToolbarButton.enabled = false;
1843         return;
1844     }
1845
1846     this._downloadToolbarButton.enabled = this.canArchiveMainFrame();
1847 };
1848
1849 WI._updateInspectModeToolbarButton = function()
1850 {
1851     if (!window.DOMAgent || !DOMAgent.setInspectModeEnabled) {
1852         this._inspectModeToolbarButton.hidden = true;
1853         return;
1854     }
1855
1856     this._inspectModeToolbarButton.hidden = false;
1857 };
1858
1859 WI._toggleInspectMode = function(event)
1860 {
1861     this.domTreeManager.inspectModeEnabled = !this.domTreeManager.inspectModeEnabled;
1862 };
1863
1864 WI._showConsoleTab = function(event)
1865 {
1866     this.showConsoleTab();
1867 };
1868
1869 WI._focusConsolePrompt = function(event)
1870 {
1871     this.quickConsole.prompt.focus();
1872 };
1873
1874 WI._focusedContentBrowser = function()
1875 {
1876     if (this.currentFocusElement) {
1877         let contentBrowserElement = this.currentFocusElement.enclosingNodeOrSelfWithClass("content-browser");
1878         if (contentBrowserElement && contentBrowserElement.__view && contentBrowserElement.__view instanceof WI.ContentBrowser)
1879             return contentBrowserElement.__view;
1880     }
1881
1882     if (this.tabBrowser.element.isSelfOrAncestor(this.currentFocusElement) || document.activeElement === document.body) {
1883         let tabContentView = this.tabBrowser.selectedTabContentView;
1884         if (tabContentView.contentBrowser)
1885             return tabContentView.contentBrowser;
1886         return null;
1887     }
1888
1889     if (this.consoleDrawer.element.isSelfOrAncestor(this.currentFocusElement)
1890         || (WI.isShowingSplitConsole() && this.quickConsole.element.isSelfOrAncestor(this.currentFocusElement)))
1891         return this.consoleDrawer;
1892
1893     return null;
1894 };
1895
1896 WI._focusedContentView = function()
1897 {
1898     if (this.tabBrowser.element.isSelfOrAncestor(this.currentFocusElement) || document.activeElement === document.body) {
1899         var tabContentView = this.tabBrowser.selectedTabContentView;
1900         if (tabContentView.contentBrowser)
1901             return tabContentView.contentBrowser.currentContentView;
1902         return tabContentView;
1903     }
1904
1905     if (this.consoleDrawer.element.isSelfOrAncestor(this.currentFocusElement)
1906         || (WI.isShowingSplitConsole() && this.quickConsole.element.isSelfOrAncestor(this.currentFocusElement)))
1907         return this.consoleDrawer.currentContentView;
1908
1909     return null;
1910 };
1911
1912 WI._focusedOrVisibleContentBrowser = function()
1913 {
1914     let focusedContentBrowser = this._focusedContentBrowser();
1915     if (focusedContentBrowser)
1916         return focusedContentBrowser;
1917
1918     var tabContentView = this.tabBrowser.selectedTabContentView;
1919     if (tabContentView.contentBrowser)
1920         return tabContentView.contentBrowser;
1921
1922     return null;
1923 };
1924
1925 WI.focusedOrVisibleContentView = function()
1926 {
1927     let focusedContentView = this._focusedContentView();
1928     if (focusedContentView)
1929         return focusedContentView;
1930
1931     var tabContentView = this.tabBrowser.selectedTabContentView;
1932     if (tabContentView.contentBrowser)
1933         return tabContentView.contentBrowser.currentContentView;
1934     return tabContentView;
1935 };
1936
1937 WI._beforecopy = function(event)
1938 {
1939     var selection = window.getSelection();
1940
1941     // If there is no selection, see if the focused element or focused ContentView can handle the copy event.
1942     if (selection.isCollapsed && !WI.isEventTargetAnEditableField(event)) {
1943         var focusedCopyHandler = this.currentFocusElement && this.currentFocusElement.copyHandler;
1944         if (focusedCopyHandler && typeof focusedCopyHandler.handleBeforeCopyEvent === "function") {
1945             focusedCopyHandler.handleBeforeCopyEvent(event);
1946             if (event.defaultPrevented)
1947                 return;
1948         }
1949
1950         var focusedContentView = this._focusedContentView();
1951         if (focusedContentView && typeof focusedContentView.handleCopyEvent === "function") {
1952             event.preventDefault();
1953             return;
1954         }
1955
1956         return;
1957     }
1958
1959     if (selection.isCollapsed)
1960         return;
1961
1962     // Say we can handle it (by preventing default) to remove word break characters.
1963     event.preventDefault();
1964 };
1965
1966 WI._find = function(event)
1967 {
1968     let contentBrowser = this._focusedOrVisibleContentBrowser();
1969     if (!contentBrowser)
1970         return;
1971
1972     contentBrowser.showFindBanner();
1973 };
1974
1975 WI._save = function(event)
1976 {
1977     var contentView = this.focusedOrVisibleContentView();
1978     if (!contentView || !contentView.supportsSave)
1979         return;
1980
1981     WI.saveDataToFile(contentView.saveData);
1982 };
1983
1984 WI._saveAs = function(event)
1985 {
1986     var contentView = this.focusedOrVisibleContentView();
1987     if (!contentView || !contentView.supportsSave)
1988         return;
1989
1990     WI.saveDataToFile(contentView.saveData, true);
1991 };
1992
1993 WI._clear = function(event)
1994 {
1995     let contentView = this.focusedOrVisibleContentView();
1996     if (!contentView || typeof contentView.handleClearShortcut !== "function") {
1997         // If the current content view is unable to handle this event, clear the console to reset
1998         // the dashboard counters.
1999         this.logManager.requestClearMessages();
2000         return;
2001     }
2002
2003     contentView.handleClearShortcut(event);
2004 };
2005
2006 WI._populateFind = function(event)
2007 {
2008     let focusedContentView = this._focusedContentView();
2009     if (!focusedContentView)
2010         return;
2011
2012     if (focusedContentView.supportsCustomFindBanner) {
2013         focusedContentView.handlePopulateFindShortcut();
2014         return;
2015     }
2016
2017     let contentBrowser = this._focusedOrVisibleContentBrowser();
2018     if (!contentBrowser)
2019         return;
2020
2021     contentBrowser.handlePopulateFindShortcut();
2022 };
2023
2024 WI._findNext = function(event)
2025 {
2026     let focusedContentView = this._focusedContentView();
2027     if (!focusedContentView)
2028         return;
2029
2030     if (focusedContentView.supportsCustomFindBanner) {
2031         focusedContentView.handleFindNextShortcut();
2032         return;
2033     }
2034
2035     let contentBrowser = this._focusedOrVisibleContentBrowser();
2036     if (!contentBrowser)
2037         return;
2038
2039     contentBrowser.handleFindNextShortcut();
2040 };
2041
2042 WI._findPrevious = function(event)
2043 {
2044     let focusedContentView = this._focusedContentView();
2045     if (!focusedContentView)
2046         return;
2047
2048     if (focusedContentView.supportsCustomFindBanner) {
2049         focusedContentView.handleFindPreviousShortcut();
2050         return;
2051     }
2052
2053     let contentBrowser = this._focusedOrVisibleContentBrowser();
2054     if (!contentBrowser)
2055         return;
2056
2057     contentBrowser.handleFindPreviousShortcut();
2058 };
2059
2060 WI._copy = function(event)
2061 {
2062     var selection = window.getSelection();
2063
2064     // If there is no selection, pass the copy event on to the focused element or focused ContentView.
2065     if (selection.isCollapsed && !WI.isEventTargetAnEditableField(event)) {
2066         var focusedCopyHandler = this.currentFocusElement && this.currentFocusElement.copyHandler;
2067         if (focusedCopyHandler && typeof focusedCopyHandler.handleCopyEvent === "function") {
2068             focusedCopyHandler.handleCopyEvent(event);
2069             if (event.defaultPrevented)
2070                 return;
2071         }
2072
2073         var focusedContentView = this._focusedContentView();
2074         if (focusedContentView && typeof focusedContentView.handleCopyEvent === "function") {
2075             focusedContentView.handleCopyEvent(event);
2076             return;
2077         }
2078
2079         let tabContentView = this.tabBrowser.selectedTabContentView;
2080         if (tabContentView && typeof tabContentView.handleCopyEvent === "function") {
2081             tabContentView.handleCopyEvent(event);
2082             return;
2083         }
2084
2085         return;
2086     }
2087
2088     if (selection.isCollapsed)
2089         return;
2090
2091     // Remove word break characters from the selection before putting it on the pasteboard.
2092     var selectionString = selection.toString().removeWordBreakCharacters();
2093     event.clipboardData.setData("text/plain", selectionString);
2094     event.preventDefault();
2095 };
2096
2097 WI._increaseZoom = function(event)
2098 {
2099     const epsilon = 0.0001;
2100     const maximumZoom = 2.4;
2101     let currentZoom = this.getZoomFactor();
2102     if (currentZoom + epsilon >= maximumZoom) {
2103         InspectorFrontendHost.beep();
2104         return;
2105     }
2106
2107     this.setZoomFactor(Math.min(maximumZoom, currentZoom + 0.2));
2108 };
2109
2110 WI._decreaseZoom = function(event)
2111 {
2112     const epsilon = 0.0001;
2113     const minimumZoom = 0.6;
2114     let currentZoom = this.getZoomFactor();
2115     if (currentZoom - epsilon <= minimumZoom) {
2116         InspectorFrontendHost.beep();
2117         return;
2118     }
2119
2120     this.setZoomFactor(Math.max(minimumZoom, currentZoom - 0.2));
2121 };
2122
2123 WI._resetZoom = function(event)
2124 {
2125     this.setZoomFactor(1);
2126 };
2127
2128 WI.getZoomFactor = function()
2129 {
2130     return WI.settings.zoomFactor.value;
2131 };
2132
2133 WI.setZoomFactor = function(factor)
2134 {
2135     InspectorFrontendHost.setZoomFactor(factor);
2136     // Round-trip through the frontend host API in case the requested factor is not used.
2137     WI.settings.zoomFactor.value = InspectorFrontendHost.zoomFactor();
2138 };
2139
2140 WI.resolvedLayoutDirection = function()
2141 {
2142     let layoutDirection = WI.settings.layoutDirection.value;
2143     if (layoutDirection === WI.LayoutDirection.System)
2144         layoutDirection = InspectorFrontendHost.userInterfaceLayoutDirection();
2145
2146     return layoutDirection;
2147 };
2148
2149 WI.setLayoutDirection = function(value)
2150 {
2151     if (!Object.values(WI.LayoutDirection).includes(value))
2152         WI.reportInternalError("Unknown layout direction requested: " + value);
2153
2154     if (value === WI.settings.layoutDirection.value)
2155         return;
2156
2157     WI.settings.layoutDirection.value = value;
2158
2159     if (WI.resolvedLayoutDirection() === WI.LayoutDirection.RTL && this._dockConfiguration === WI.DockConfiguration.Right)
2160         this._dockLeft();
2161
2162     if (WI.resolvedLayoutDirection() === WI.LayoutDirection.LTR && this._dockConfiguration === WI.DockConfiguration.Left)
2163         this._dockRight();
2164
2165     window.location.reload();
2166 };
2167
2168 WI._showTabAtIndex = function(i, event)
2169 {
2170     if (i <= WI.tabBar.tabBarItems.length)
2171         WI.tabBar.selectedTabBarItem = i - 1;
2172 };
2173
2174 WI._showJavaScriptTypeInformationSettingChanged = function(event)
2175 {
2176     if (this.showJavaScriptTypeInformationSetting.value) {
2177         for (let target of WI.targets)
2178             target.RuntimeAgent.enableTypeProfiler();
2179     } else {
2180         for (let target of WI.targets)
2181             target.RuntimeAgent.disableTypeProfiler();
2182     }
2183 };
2184
2185 WI._enableControlFlowProfilerSettingChanged = function(event)
2186 {
2187     if (this.enableControlFlowProfilerSetting.value) {
2188         for (let target of WI.targets)
2189             target.RuntimeAgent.enableControlFlowProfiler();
2190     } else {
2191         for (let target of WI.targets)
2192             target.RuntimeAgent.disableControlFlowProfiler();
2193     }
2194 };
2195
2196 WI._resourceCachingDisabledSettingChanged = function(event)
2197 {
2198     NetworkAgent.setResourceCachingDisabled(this.resourceCachingDisabledSetting.value);
2199 };
2200
2201 WI.elementDragStart = function(element, dividerDrag, elementDragEnd, event, cursor, eventTarget)
2202 {
2203     if (WI._elementDraggingEventListener || WI._elementEndDraggingEventListener)
2204         WI.elementDragEnd(event);
2205
2206     if (element) {
2207         // Install glass pane
2208         if (WI._elementDraggingGlassPane)
2209             WI._elementDraggingGlassPane.remove();
2210
2211         var glassPane = document.createElement("div");
2212         glassPane.style.cssText = "position:absolute;top:0;bottom:0;left:0;right:0;opacity:0;z-index:1";
2213         glassPane.id = "glass-pane-for-drag";
2214         element.ownerDocument.body.appendChild(glassPane);
2215         WI._elementDraggingGlassPane = glassPane;
2216     }
2217
2218     WI._elementDraggingEventListener = dividerDrag;
2219     WI._elementEndDraggingEventListener = elementDragEnd;
2220
2221     var targetDocument = event.target.ownerDocument;
2222
2223     WI._elementDraggingEventTarget = eventTarget || targetDocument;
2224     WI._elementDraggingEventTarget.addEventListener("mousemove", dividerDrag, true);
2225     WI._elementDraggingEventTarget.addEventListener("mouseup", elementDragEnd, true);
2226
2227     targetDocument.body.style.cursor = cursor;
2228
2229     event.preventDefault();
2230 };
2231
2232 WI.elementDragEnd = function(event)
2233 {
2234     WI._elementDraggingEventTarget.removeEventListener("mousemove", WI._elementDraggingEventListener, true);
2235     WI._elementDraggingEventTarget.removeEventListener("mouseup", WI._elementEndDraggingEventListener, true);
2236
2237     event.target.ownerDocument.body.style.removeProperty("cursor");
2238
2239     if (WI._elementDraggingGlassPane)
2240         WI._elementDraggingGlassPane.remove();
2241
2242     delete WI._elementDraggingGlassPane;
2243     delete WI._elementDraggingEventTarget;
2244     delete WI._elementDraggingEventListener;
2245     delete WI._elementEndDraggingEventListener;
2246
2247     event.preventDefault();
2248 };
2249
2250 WI.createMessageTextView = function(message, isError)
2251 {
2252     var messageElement = document.createElement("div");
2253     messageElement.className = "message-text-view";
2254     if (isError)
2255         messageElement.classList.add("error");
2256
2257     let textElement = messageElement.appendChild(document.createElement("div"));
2258     textElement.className = "message";
2259     textElement.textContent = message;
2260
2261     return messageElement;
2262 };
2263
2264 WI.createNavigationItemHelp = function(formatString, navigationItem)
2265 {
2266     console.assert(typeof formatString === "string");
2267     console.assert(navigationItem instanceof WI.NavigationItem);
2268
2269     function append(a, b) {
2270         a.append(b);
2271         return a;
2272     }
2273
2274     let containerElement = document.createElement("div");
2275     containerElement.className = "navigation-item-help";
2276     containerElement.__navigationItem = navigationItem;
2277
2278     let wrapperElement = document.createElement("div");
2279     wrapperElement.className = "navigation-bar";
2280     wrapperElement.appendChild(navigationItem.element);
2281
2282     String.format(formatString, [wrapperElement], String.standardFormatters, containerElement, append);
2283     return containerElement;
2284 };
2285
2286 WI.createGoToArrowButton = function()
2287 {
2288     var button = document.createElement("button");
2289     button.addEventListener("mousedown", (event) => { event.stopPropagation(); }, true);
2290     button.className = "go-to-arrow";
2291     button.tabIndex = -1;
2292     return button;
2293 };
2294
2295 WI.createSourceCodeLocationLink = function(sourceCodeLocation, options = {})
2296 {
2297     console.assert(sourceCodeLocation);
2298     if (!sourceCodeLocation)
2299         return null;
2300
2301     var linkElement = document.createElement("a");
2302     linkElement.className = "go-to-link";
2303     WI.linkifyElement(linkElement, sourceCodeLocation, options);
2304     sourceCodeLocation.populateLiveDisplayLocationTooltip(linkElement);
2305
2306     if (options.useGoToArrowButton)
2307         linkElement.appendChild(WI.createGoToArrowButton());
2308     else
2309         sourceCodeLocation.populateLiveDisplayLocationString(linkElement, "textContent", options.columnStyle, options.nameStyle, options.prefix);
2310
2311     if (options.dontFloat)
2312         linkElement.classList.add("dont-float");
2313
2314     return linkElement;
2315 };
2316
2317 WI.linkifyLocation = function(url, sourceCodePosition, options = {})
2318 {
2319     var sourceCode = WI.sourceCodeForURL(url);
2320
2321     if (!sourceCode) {
2322         var anchor = document.createElement("a");
2323         anchor.href = url;
2324         anchor.lineNumber = sourceCodePosition.lineNumber;
2325         if (options.className)
2326             anchor.className = options.className;
2327         anchor.append(WI.displayNameForURL(url) + ":" + sourceCodePosition.lineNumber);
2328         return anchor;
2329     }
2330
2331     let sourceCodeLocation = sourceCode.createSourceCodeLocation(sourceCodePosition.lineNumber, sourceCodePosition.columnNumber);
2332     let linkElement = WI.createSourceCodeLocationLink(sourceCodeLocation, Object.shallowMerge(options, {dontFloat: true}));
2333     if (options.className)
2334         linkElement.classList.add(options.className);
2335     return linkElement;
2336 };
2337
2338 WI.linkifyElement = function(linkElement, sourceCodeLocation, options = {}) {
2339     console.assert(sourceCodeLocation);
2340
2341     function showSourceCodeLocation(event)
2342     {
2343         event.stopPropagation();
2344         event.preventDefault();
2345
2346         if (event.metaKey)
2347             this.showOriginalUnformattedSourceCodeLocation(sourceCodeLocation, options);
2348         else
2349             this.showSourceCodeLocation(sourceCodeLocation, options);
2350     }
2351
2352     linkElement.addEventListener("click", showSourceCodeLocation.bind(this));
2353     linkElement.addEventListener("contextmenu", (event) => {
2354         let contextMenu = WI.ContextMenu.createFromEvent(event);
2355         WI.appendContextMenuItemsForSourceCode(contextMenu, sourceCodeLocation);
2356     });
2357 };
2358
2359 WI.sourceCodeForURL = function(url)
2360 {
2361     var sourceCode = WI.frameResourceManager.resourceForURL(url);
2362     if (!sourceCode) {
2363         sourceCode = WI.debuggerManager.scriptsForURL(url, WI.assumingMainTarget())[0];
2364         if (sourceCode)
2365             sourceCode = sourceCode.resource || sourceCode;
2366     }
2367     return sourceCode || null;
2368 };
2369
2370 WI.linkifyURLAsNode = function(url, linkText, className)
2371 {
2372     let a = document.createElement("a");
2373     a.href = url;
2374     a.className = className || "";
2375     a.textContent = linkText || url;
2376     a.style.maxWidth = "100%";
2377     return a;
2378 };
2379
2380 WI.linkifyStringAsFragmentWithCustomLinkifier = function(string, linkifier)
2381 {
2382     var container = document.createDocumentFragment();
2383     var linkStringRegEx = /(?:[a-zA-Z][a-zA-Z0-9+.-]{2,}:\/\/|www\.)[\w$\-_+*'=\|\/\\(){}[\]%@&#~,:;.!?]{2,}[\w$\-_+*=\|\/\\({%@&#~]/;
2384     var lineColumnRegEx = /:(\d+)(:(\d+))?$/;
2385
2386     while (string) {
2387         var linkString = linkStringRegEx.exec(string);
2388         if (!linkString)
2389             break;
2390
2391         linkString = linkString[0];
2392         var linkIndex = string.indexOf(linkString);
2393         var nonLink = string.substring(0, linkIndex);
2394         container.append(nonLink);
2395
2396         if (linkString.startsWith("data:") || linkString.startsWith("javascript:") || linkString.startsWith("mailto:")) {
2397             container.append(linkString);
2398             string = string.substring(linkIndex + linkString.length, string.length);
2399             continue;
2400         }
2401
2402         var title = linkString;
2403         var realURL = linkString.startsWith("www.") ? "http://" + linkString : linkString;
2404         var lineColumnMatch = lineColumnRegEx.exec(realURL);
2405         if (lineColumnMatch)
2406             realURL = realURL.substring(0, realURL.length - lineColumnMatch[0].length);
2407
2408         var lineNumber;
2409         if (lineColumnMatch)
2410             lineNumber = parseInt(lineColumnMatch[1]) - 1;
2411
2412         var linkNode = linkifier(title, realURL, lineNumber);
2413         container.appendChild(linkNode);
2414         string = string.substring(linkIndex + linkString.length, string.length);
2415     }
2416
2417     if (string)
2418         container.append(string);
2419
2420     return container;
2421 };
2422
2423 WI.linkifyStringAsFragment = function(string)
2424 {
2425     function linkifier(title, url, lineNumber)
2426     {
2427         var urlNode = WI.linkifyURLAsNode(url, title, undefined);
2428         if (lineNumber !== undefined)
2429             urlNode.lineNumber = lineNumber;
2430
2431         return urlNode;
2432     }
2433
2434     return WI.linkifyStringAsFragmentWithCustomLinkifier(string, linkifier);
2435 };
2436
2437 WI.createResourceLink = function(resource, className)
2438 {
2439     function handleClick(event)
2440     {
2441         event.stopPropagation();
2442         event.preventDefault();
2443
2444         WI.showRepresentedObject(resource);
2445     }
2446
2447     let linkNode = document.createElement("a");
2448     linkNode.classList.add("resource-link", className);
2449     linkNode.title = resource.url;
2450     linkNode.textContent = (resource.urlComponents.lastPathComponent || resource.url).insertWordBreakCharacters();
2451     linkNode.addEventListener("click", handleClick.bind(this));
2452     return linkNode;
2453 };
2454
2455 WI._undoKeyboardShortcut = function(event)
2456 {
2457     if (!this.isEditingAnyField() && !this.isEventTargetAnEditableField(event)) {
2458         this.undo();
2459         event.preventDefault();
2460     }
2461 };
2462
2463 WI._redoKeyboardShortcut = function(event)
2464 {
2465     if (!this.isEditingAnyField() && !this.isEventTargetAnEditableField(event)) {
2466         this.redo();
2467         event.preventDefault();
2468     }
2469 };
2470
2471 WI.undo = function()
2472 {
2473     DOMAgent.undo();
2474 };
2475
2476 WI.redo = function()
2477 {
2478     DOMAgent.redo();
2479 };
2480
2481 WI.highlightRangesWithStyleClass = function(element, resultRanges, styleClass, changes)
2482 {
2483     changes = changes || [];
2484     var highlightNodes = [];
2485     var lineText = element.textContent;
2486     var ownerDocument = element.ownerDocument;
2487     var textNodeSnapshot = ownerDocument.evaluate(".//text()", element, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
2488
2489     var snapshotLength = textNodeSnapshot.snapshotLength;
2490     if (snapshotLength === 0)
2491         return highlightNodes;
2492
2493     var nodeRanges = [];
2494     var rangeEndOffset = 0;
2495     for (var i = 0; i < snapshotLength; ++i) {
2496         var range = {};
2497         range.offset = rangeEndOffset;
2498         range.length = textNodeSnapshot.snapshotItem(i).textContent.length;
2499         rangeEndOffset = range.offset + range.length;
2500         nodeRanges.push(range);
2501     }
2502
2503     var startIndex = 0;
2504     for (var i = 0; i < resultRanges.length; ++i) {
2505         var startOffset = resultRanges[i].offset;
2506         var endOffset = startOffset + resultRanges[i].length;
2507
2508         while (startIndex < snapshotLength && nodeRanges[startIndex].offset + nodeRanges[startIndex].length <= startOffset)
2509             startIndex++;
2510         var endIndex = startIndex;
2511         while (endIndex < snapshotLength && nodeRanges[endIndex].offset + nodeRanges[endIndex].length < endOffset)
2512             endIndex++;
2513         if (endIndex === snapshotLength)
2514             break;
2515
2516         var highlightNode = ownerDocument.createElement("span");
2517         highlightNode.className = styleClass;
2518         highlightNode.textContent = lineText.substring(startOffset, endOffset);
2519
2520         var lastTextNode = textNodeSnapshot.snapshotItem(endIndex);
2521         var lastText = lastTextNode.textContent;
2522         lastTextNode.textContent = lastText.substring(endOffset - nodeRanges[endIndex].offset);
2523         changes.push({node: lastTextNode, type: "changed", oldText: lastText, newText: lastTextNode.textContent});
2524
2525         if (startIndex === endIndex) {
2526             lastTextNode.parentElement.insertBefore(highlightNode, lastTextNode);
2527             changes.push({node: highlightNode, type: "added", nextSibling: lastTextNode, parent: lastTextNode.parentElement});
2528             highlightNodes.push(highlightNode);
2529
2530             var prefixNode = ownerDocument.createTextNode(lastText.substring(0, startOffset - nodeRanges[startIndex].offset));
2531             lastTextNode.parentElement.insertBefore(prefixNode, highlightNode);
2532             changes.push({node: prefixNode, type: "added", nextSibling: highlightNode, parent: lastTextNode.parentElement});
2533         } else {
2534             var firstTextNode = textNodeSnapshot.snapshotItem(startIndex);
2535             var firstText = firstTextNode.textContent;
2536             var anchorElement = firstTextNode.nextSibling;
2537
2538             firstTextNode.parentElement.insertBefore(highlightNode, anchorElement);
2539             changes.push({node: highlightNode, type: "added", nextSibling: anchorElement, parent: firstTextNode.parentElement});
2540             highlightNodes.push(highlightNode);
2541
2542             firstTextNode.textContent = firstText.substring(0, startOffset - nodeRanges[startIndex].offset);
2543             changes.push({node: firstTextNode, type: "changed", oldText: firstText, newText: firstTextNode.textContent});
2544
2545             for (var j = startIndex + 1; j < endIndex; j++) {
2546                 var textNode = textNodeSnapshot.snapshotItem(j);
2547                 var text = textNode.textContent;
2548                 textNode.textContent = "";
2549                 changes.push({node: textNode, type: "changed", oldText: text, newText: textNode.textContent});
2550             }
2551         }
2552         startIndex = endIndex;
2553         nodeRanges[startIndex].offset = endOffset;
2554         nodeRanges[startIndex].length = lastTextNode.textContent.length;
2555
2556     }
2557     return highlightNodes;
2558 };
2559
2560 WI.revertDOMChanges = function(domChanges)
2561 {
2562     for (var i = domChanges.length - 1; i >= 0; --i) {
2563         var entry = domChanges[i];
2564         switch (entry.type) {
2565         case "added":
2566             entry.node.remove();
2567             break;
2568         case "changed":
2569             entry.node.textContent = entry.oldText;
2570             break;
2571         }
2572     }
2573 };
2574
2575 WI.archiveMainFrame = function()
2576 {
2577     this._downloadingPage = true;
2578     this._updateDownloadToolbarButton();
2579
2580     PageAgent.archive((error, data) => {
2581         this._downloadingPage = false;
2582         this._updateDownloadToolbarButton();
2583
2584         if (error)
2585             return;
2586
2587         let mainFrame = WI.frameResourceManager.mainFrame;
2588         let archiveName = mainFrame.mainResource.urlComponents.host || mainFrame.mainResource.displayName || "Archive";
2589         let url = "web-inspector:///" + encodeURI(archiveName) + ".webarchive";
2590
2591         InspectorFrontendHost.save(url, data, true, true);
2592     });
2593 };
2594
2595 WI.canArchiveMainFrame = function()
2596 {
2597     // COMPATIBILITY (iOS 7): Page.archive did not exist yet.
2598     if (!PageAgent.archive || this.sharedApp.debuggableType !== WI.DebuggableType.Web)
2599         return false;
2600
2601     if (!WI.frameResourceManager.mainFrame || !WI.frameResourceManager.mainFrame.mainResource)
2602         return false;
2603
2604     return WI.Resource.typeFromMIMEType(WI.frameResourceManager.mainFrame.mainResource.mimeType) === WI.Resource.Type.Document;
2605 };
2606
2607 WI.addWindowKeydownListener = function(listener)
2608 {
2609     if (typeof listener.handleKeydownEvent !== "function")
2610         return;
2611
2612     this._windowKeydownListeners.push(listener);
2613
2614     this._updateWindowKeydownListener();
2615 };
2616
2617 WI.removeWindowKeydownListener = function(listener)
2618 {
2619     this._windowKeydownListeners.remove(listener);
2620
2621     this._updateWindowKeydownListener();
2622 };
2623
2624 WI._updateWindowKeydownListener = function()
2625 {
2626     if (this._windowKeydownListeners.length === 1)
2627         window.addEventListener("keydown", WI._sharedWindowKeydownListener, true);
2628     else if (!this._windowKeydownListeners.length)
2629         window.removeEventListener("keydown", WI._sharedWindowKeydownListener, true);
2630 };
2631
2632 WI._sharedWindowKeydownListener = function(event)
2633 {
2634     for (var i = WI._windowKeydownListeners.length - 1; i >= 0; --i) {
2635         if (WI._windowKeydownListeners[i].handleKeydownEvent(event)) {
2636             event.stopImmediatePropagation();
2637             event.preventDefault();
2638             break;
2639         }
2640     }
2641 };
2642
2643 WI.reportInternalError = function(errorOrString, details = {})
2644 {
2645     // The 'details' object includes additional information from the caller as free-form string keys and values.
2646     // Each key and value will be shown in the uncaught exception reporter, console error message, or in
2647     // a pre-filled bug report generated for this internal error.
2648
2649     let error = errorOrString instanceof Error ? errorOrString : new Error(errorOrString);
2650     error.details = details;
2651
2652     // The error will be displayed in the Uncaught Exception Reporter sheet if DebugUI is enabled.
2653     if (WI.isDebugUIEnabled()) {
2654         // This assert allows us to stop the debugger at an internal exception. It doesn't re-throw
2655         // exceptions because the original exception would be lost through window.onerror.
2656         // This workaround can be removed once <https://webkit.org/b/158192> is fixed.
2657         console.assert(false, "An internal exception was thrown.", error);
2658         handleInternalException(error);
2659     } else
2660         console.error(error);
2661 };
2662
2663 Object.defineProperty(WI, "targets",
2664 {
2665     get() { return this.targetManager.targets; }
2666 });
2667
2668 // Many places assume the main target because they cannot yet be
2669 // used by reached by Worker debugging. Eventually, once all
2670 // Worker domains have been implemented, all of these must be
2671 // handled properly.
2672 WI.assumingMainTarget = function()
2673 {
2674     return WI.mainTarget;
2675 };
2676
2677 // OpenResourceDialog delegate
2678
2679 WI.dialogWasDismissed = function(dialog)
2680 {
2681     let representedObject = dialog.representedObject;
2682     if (!representedObject)
2683         return;
2684
2685     WI.showRepresentedObject(representedObject, dialog.cookie);
2686 };
2687
2688 WI.DockConfiguration = {
2689     Right: "right",
2690     Left: "left",
2691     Bottom: "bottom",
2692     Undocked: "undocked",
2693 };