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