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