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