2 * Copyright (C) 2013-2017 Apple Inc. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
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.
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.
26 WI.ContentViewCookieType = {
27 ApplicationCache: "application-cache",
28 CookieStorage: "cookie-storage",
30 DatabaseTable: "database-table",
31 DOMStorage: "dom-storage",
32 Resource: "resource", // includes Frame too.
33 Timelines: "timelines"
38 JavaScript: "javascript"
41 WI.SelectedSidebarPanelCookieKey = "selected-sidebar-panel";
42 WI.TypeIdentifierCookieKey = "represented-object-type";
44 WI.StateRestorationType = {
45 Load: "state-restoration-load",
46 Navigation: "state-restoration-navigation",
47 Delayed: "state-restoration-delayed",
50 WI.LayoutDirection = {
56 WI.loaded = function()
58 this.debuggableType = InspectorFrontendHost.debuggableType() === "web" ? WI.DebuggableType.Web : WI.DebuggableType.JavaScript;
59 this.hasExtraDomains = false;
61 // Register observers for events from the InspectorBackend.
62 if (InspectorBackend.registerInspectorDispatcher)
63 InspectorBackend.registerInspectorDispatcher(new WI.InspectorObserver);
64 if (InspectorBackend.registerPageDispatcher)
65 InspectorBackend.registerPageDispatcher(new WI.PageObserver);
66 if (InspectorBackend.registerConsoleDispatcher)
67 InspectorBackend.registerConsoleDispatcher(new WI.ConsoleObserver);
68 if (InspectorBackend.registerNetworkDispatcher)
69 InspectorBackend.registerNetworkDispatcher(new WI.NetworkObserver);
70 if (InspectorBackend.registerDOMDispatcher)
71 InspectorBackend.registerDOMDispatcher(new WI.DOMObserver);
72 if (InspectorBackend.registerDebuggerDispatcher)
73 InspectorBackend.registerDebuggerDispatcher(new WI.DebuggerObserver);
74 if (InspectorBackend.registerHeapDispatcher)
75 InspectorBackend.registerHeapDispatcher(new WI.HeapObserver);
76 if (InspectorBackend.registerMemoryDispatcher)
77 InspectorBackend.registerMemoryDispatcher(new WI.MemoryObserver);
78 if (InspectorBackend.registerDatabaseDispatcher)
79 InspectorBackend.registerDatabaseDispatcher(new WI.DatabaseObserver);
80 if (InspectorBackend.registerDOMStorageDispatcher)
81 InspectorBackend.registerDOMStorageDispatcher(new WI.DOMStorageObserver);
82 if (InspectorBackend.registerApplicationCacheDispatcher)
83 InspectorBackend.registerApplicationCacheDispatcher(new WI.ApplicationCacheObserver);
84 if (InspectorBackend.registerScriptProfilerDispatcher)
85 InspectorBackend.registerScriptProfilerDispatcher(new WI.ScriptProfilerObserver);
86 if (InspectorBackend.registerTimelineDispatcher)
87 InspectorBackend.registerTimelineDispatcher(new WI.TimelineObserver);
88 if (InspectorBackend.registerCSSDispatcher)
89 InspectorBackend.registerCSSDispatcher(new WI.CSSObserver);
90 if (InspectorBackend.registerLayerTreeDispatcher)
91 InspectorBackend.registerLayerTreeDispatcher(new WI.LayerTreeObserver);
92 if (InspectorBackend.registerRuntimeDispatcher)
93 InspectorBackend.registerRuntimeDispatcher(new WI.RuntimeObserver);
94 if (InspectorBackend.registerWorkerDispatcher)
95 InspectorBackend.registerWorkerDispatcher(new WI.WorkerObserver);
96 if (InspectorBackend.registerCanvasDispatcher)
97 InspectorBackend.registerCanvasDispatcher(new WI.CanvasObserver);
99 // Main backend target.
100 WI.mainTarget = new WI.MainTarget;
103 InspectorAgent.enable();
105 // Perform one-time tasks.
106 WI.CSSCompletions.requestCSSCompletions();
108 // Listen for the ProvisionalLoadStarted event before registering for events so our code gets called before any managers or sidebars.
109 // This lets us save a state cookie before any managers or sidebars do any resets that would affect state (namely TimelineManager).
110 WI.Frame.addEventListener(WI.Frame.Event.ProvisionalLoadStarted, this._provisionalLoadStarted, this);
112 // Populate any UIStrings that must be done early after localized strings have loaded.
113 WI.KeyboardShortcut.Key.Space._displayName = WI.UIString("Space");
115 // Create the singleton managers next, before the user interface elements, so the user interface can register
116 // as event listeners on these managers.
117 this.targetManager = new WI.TargetManager;
118 this.branchManager = new WI.BranchManager;
119 this.frameResourceManager = new WI.FrameResourceManager;
120 this.storageManager = new WI.StorageManager;
121 this.domTreeManager = new WI.DOMTreeManager;
122 this.cssStyleManager = new WI.CSSStyleManager;
123 this.logManager = new WI.LogManager;
124 this.issueManager = new WI.IssueManager;
125 this.analyzerManager = new WI.AnalyzerManager;
126 this.runtimeManager = new WI.RuntimeManager;
127 this.heapManager = new WI.HeapManager;
128 this.memoryManager = new WI.MemoryManager;
129 this.applicationCacheManager = new WI.ApplicationCacheManager;
130 this.timelineManager = new WI.TimelineManager;
131 this.debuggerManager = new WI.DebuggerManager;
132 this.sourceMapManager = new WI.SourceMapManager;
133 this.layerTreeManager = new WI.LayerTreeManager;
134 this.dashboardManager = new WI.DashboardManager;
135 this.probeManager = new WI.ProbeManager;
136 this.workerManager = new WI.WorkerManager;
137 this.domDebuggerManager = new WI.DOMDebuggerManager;
138 this.canvasManager = new WI.CanvasManager;
140 // Enable the Console Agent after creating the singleton managers.
141 ConsoleAgent.enable();
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();
150 // Register for events.
151 this.debuggerManager.addEventListener(WI.DebuggerManager.Event.Paused, this._debuggerDidPause, this);
152 this.debuggerManager.addEventListener(WI.DebuggerManager.Event.Resumed, this._debuggerDidResume, this);
153 this.domTreeManager.addEventListener(WI.DOMTreeManager.Event.InspectModeStateChanged, this._inspectModeStateChanged, this);
154 this.domTreeManager.addEventListener(WI.DOMTreeManager.Event.DOMNodeWasInspected, this._domNodeWasInspected, this);
155 this.storageManager.addEventListener(WI.StorageManager.Event.DOMStorageObjectWasInspected, this._storageWasInspected, this);
156 this.storageManager.addEventListener(WI.StorageManager.Event.DatabaseWasInspected, this._storageWasInspected, this);
157 this.frameResourceManager.addEventListener(WI.FrameResourceManager.Event.MainFrameDidChange, this._mainFrameDidChange, this);
158 this.frameResourceManager.addEventListener(WI.FrameResourceManager.Event.FrameWasAdded, this._frameWasAdded, this);
160 WI.Frame.addEventListener(WI.Frame.Event.MainResourceDidChange, this._mainResourceDidChange, this);
162 document.addEventListener("DOMContentLoaded", this.contentLoaded.bind(this));
165 this._showingSplitConsoleSetting = new WI.Setting("showing-split-console", false);
167 this._openTabsSetting = new WI.Setting("open-tab-types", ["elements", "network", "resources", "timeline", "debugger", "storage", "console"]);
168 this._selectedTabIndexSetting = new WI.Setting("selected-tab-index", 0);
170 this.showShadowDOMSetting = new WI.Setting("show-shadow-dom", false);
172 // COMPATIBILITY (iOS 8): Page.enableTypeProfiler did not exist.
173 this.showJavaScriptTypeInformationSetting = new WI.Setting("show-javascript-type-information", false);
174 this.showJavaScriptTypeInformationSetting.addEventListener(WI.Setting.Event.Changed, this._showJavaScriptTypeInformationSettingChanged, this);
175 if (this.showJavaScriptTypeInformationSetting.value && window.RuntimeAgent && RuntimeAgent.enableTypeProfiler)
176 RuntimeAgent.enableTypeProfiler();
178 this.enableControlFlowProfilerSetting = new WI.Setting("enable-control-flow-profiler", false);
179 this.enableControlFlowProfilerSetting.addEventListener(WI.Setting.Event.Changed, this._enableControlFlowProfilerSettingChanged, this);
180 if (this.enableControlFlowProfilerSetting.value && window.RuntimeAgent && RuntimeAgent.enableControlFlowProfiler)
181 RuntimeAgent.enableControlFlowProfiler();
183 // COMPATIBILITY (iOS 8): Page.setShowPaintRects did not exist.
184 this.showPaintRectsSetting = new WI.Setting("show-paint-rects", false);
185 if (this.showPaintRectsSetting.value && window.PageAgent && PageAgent.setShowPaintRects)
186 PageAgent.setShowPaintRects(true);
188 this.showPrintStylesSetting = new WI.Setting("show-print-styles", false);
189 if (this.showPrintStylesSetting.value && window.PageAgent)
190 PageAgent.setEmulatedMedia("print");
192 // COMPATIBILITY (iOS 10.3): Network.setDisableResourceCaching did not exist.
193 this.resourceCachingDisabledSetting = new WI.Setting("disable-resource-caching", false);
194 if (window.NetworkAgent && NetworkAgent.setResourceCachingDisabled && this.resourceCachingDisabledSetting.value) {
195 NetworkAgent.setResourceCachingDisabled(true);
196 this.resourceCachingDisabledSetting.addEventListener(WI.Setting.Event.Changed, this._resourceCachingDisabledSettingChanged, this);
199 this.setZoomFactor(WI.settings.zoomFactor.value);
206 this.visible = false;
208 this._windowKeydownListeners = [];
211 WI.contentLoaded = function()
213 // If there was an uncaught exception earlier during loading, then
214 // abort loading more content. We could be in an inconsistent state.
215 if (window.__uncaughtExceptions)
218 // Register for global events.
219 document.addEventListener("beforecopy", this._beforecopy.bind(this));
220 document.addEventListener("copy", this._copy.bind(this));
222 document.addEventListener("click", this._mouseWasClicked.bind(this));
223 document.addEventListener("dragover", this._dragOver.bind(this));
224 document.addEventListener("focus", WI._focusChanged.bind(this), true);
226 window.addEventListener("focus", this._windowFocused.bind(this));
227 window.addEventListener("blur", this._windowBlurred.bind(this));
228 window.addEventListener("resize", this._windowResized.bind(this));
229 window.addEventListener("keydown", this._windowKeyDown.bind(this));
230 window.addEventListener("keyup", this._windowKeyUp.bind(this));
231 window.addEventListener("mousedown", this._mouseDown.bind(this), true);
232 window.addEventListener("mousemove", this._mouseMoved.bind(this), true);
233 window.addEventListener("pagehide", this._pageHidden.bind(this));
234 window.addEventListener("contextmenu", this._contextMenuRequested.bind(this));
236 // Add platform style classes so the UI can be tweaked per-platform.
237 document.body.classList.add(WI.Platform.name + "-platform");
238 if (WI.Platform.isNightlyBuild)
239 document.body.classList.add("nightly-build");
241 if (WI.Platform.name === "mac") {
242 document.body.classList.add(WI.Platform.version.name);
244 if (WI.Platform.version.release >= 11)
245 document.body.classList.add("latest-mac");
247 document.body.classList.add("legacy-mac");
250 document.body.classList.add(this.debuggableType);
251 document.body.setAttribute("dir", this.resolvedLayoutDirection());
253 function setTabSize() {
254 document.body.style.tabSize = WI.settings.tabSize.value;
256 WI.settings.tabSize.addEventListener(WI.Setting.Event.Changed, setTabSize);
259 function setInvalidCharacterClassName() {
260 document.body.classList.toggle("show-invalid-characters", WI.settings.showInvalidCharacters.value);
262 WI.settings.showInvalidCharacters.addEventListener(WI.Setting.Event.Changed, setInvalidCharacterClassName);
263 setInvalidCharacterClassName();
265 function setWhitespaceCharacterClassName() {
266 document.body.classList.toggle("show-whitespace-characters", WI.settings.showWhitespaceCharacters.value);
268 WI.settings.showWhitespaceCharacters.addEventListener(WI.Setting.Event.Changed, setWhitespaceCharacterClassName);
269 setWhitespaceCharacterClassName();
271 this.settingsTabContentView = new WI.SettingsTabContentView;
273 this._settingsKeyboardShortcut = new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl, WI.KeyboardShortcut.Key.Comma, this._showSettingsTab.bind(this));
275 // Create the user interface elements.
276 this.toolbar = new WI.Toolbar(document.getElementById("toolbar"));
278 this.tabBar = new WI.TabBar(document.getElementById("tab-bar"));
279 this.tabBar.addEventListener(WI.TabBar.Event.OpenDefaultTab, this._openDefaultTab, this);
281 this._contentElement = document.getElementById("content");
282 this._contentElement.setAttribute("role", "main");
283 this._contentElement.setAttribute("aria-label", WI.UIString("Content"));
285 this.consoleDrawer = new WI.ConsoleDrawer(document.getElementById("console-drawer"));
286 this.consoleDrawer.addEventListener(WI.ConsoleDrawer.Event.CollapsedStateChanged, this._consoleDrawerCollapsedStateDidChange, this);
287 this.consoleDrawer.addEventListener(WI.ConsoleDrawer.Event.Resized, this._consoleDrawerDidResize, this);
289 this.clearKeyboardShortcut = new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl, "K", this._clear.bind(this));
291 this.quickConsole = new WI.QuickConsole(document.getElementById("quick-console"));
293 this._consoleRepresentedObject = new WI.LogObject;
294 this.consoleContentView = this.consoleDrawer.contentViewForRepresentedObject(this._consoleRepresentedObject);
295 this.consoleLogViewController = this.consoleContentView.logViewController;
296 this.breakpointPopoverController = new WI.BreakpointPopoverController;
298 // FIXME: The sidebars should be flipped in RTL languages.
299 this.navigationSidebar = new WI.Sidebar(document.getElementById("navigation-sidebar"), WI.Sidebar.Sides.Left);
300 this.navigationSidebar.addEventListener(WI.Sidebar.Event.WidthDidChange, this._sidebarWidthDidChange, this);
302 this.detailsSidebar = new WI.Sidebar(document.getElementById("details-sidebar"), WI.Sidebar.Sides.Right, null, null, WI.UIString("Details"), true);
303 this.detailsSidebar.addEventListener(WI.Sidebar.Event.WidthDidChange, this._sidebarWidthDidChange, this);
305 this.searchKeyboardShortcut = new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl | WI.KeyboardShortcut.Modifier.Shift, "F", this._focusSearchField.bind(this));
306 this._findKeyboardShortcut = new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl, "F", this._find.bind(this));
307 this._saveKeyboardShortcut = new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl, "S", this._save.bind(this));
308 this._saveAsKeyboardShortcut = new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.Shift | WI.KeyboardShortcut.Modifier.CommandOrControl, "S", this._saveAs.bind(this));
310 this.openResourceKeyboardShortcut = new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl | WI.KeyboardShortcut.Modifier.Shift, "O", this._showOpenResourceDialog.bind(this));
311 new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl, "P", this._showOpenResourceDialog.bind(this));
313 this.navigationSidebarKeyboardShortcut = new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl | WI.KeyboardShortcut.Modifier.Shift, "0", this.toggleNavigationSidebar.bind(this));
314 this.detailsSidebarKeyboardShortcut = new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl | WI.KeyboardShortcut.Modifier.Option, "0", this.toggleDetailsSidebar.bind(this));
316 let boundIncreaseZoom = this._increaseZoom.bind(this);
317 let boundDecreaseZoom = this._decreaseZoom.bind(this);
318 this._increaseZoomKeyboardShortcut = new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl, WI.KeyboardShortcut.Key.Plus, boundIncreaseZoom);
319 this._decreaseZoomKeyboardShortcut = new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl, WI.KeyboardShortcut.Key.Minus, boundDecreaseZoom);
320 this._increaseZoomKeyboardShortcut2 = new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl | WI.KeyboardShortcut.Modifier.Shift, WI.KeyboardShortcut.Key.Plus, boundIncreaseZoom);
321 this._decreaseZoomKeyboardShortcut2 = new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl | WI.KeyboardShortcut.Modifier.Shift, WI.KeyboardShortcut.Key.Minus, boundDecreaseZoom);
322 this._resetZoomKeyboardShortcut = new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl, "0", this._resetZoom.bind(this));
324 this._showTabAtIndexKeyboardShortcuts = [1, 2, 3, 4, 5, 6, 7, 8, 9].map((i) => new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl | WI.KeyboardShortcut.Modifier.Option, `${i}`, this._showTabAtIndex.bind(this, i)));
325 this._openNewTabKeyboardShortcut = new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl | WI.KeyboardShortcut.Modifier.Option, "T", this.showNewTabTab.bind(this));
327 this.tabBrowser = new WI.TabBrowser(document.getElementById("tab-browser"), this.tabBar, this.navigationSidebar, this.detailsSidebar);
328 this.tabBrowser.addEventListener(WI.TabBrowser.Event.SelectedTabContentViewDidChange, this._tabBrowserSelectedTabContentViewDidChange, this);
330 this._reloadPageKeyboardShortcut = new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl, "R", this._reloadPage.bind(this));
331 this._reloadPageIgnoringCacheKeyboardShortcut = new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl | WI.KeyboardShortcut.Modifier.Shift, "R", this._reloadPageIgnoringCache.bind(this));
332 this._reloadPageKeyboardShortcut.implicitlyPreventsDefault = this._reloadPageIgnoringCacheKeyboardShortcut.implicitlyPreventsDefault = false;
334 this._consoleTabKeyboardShortcut = new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.Option | WI.KeyboardShortcut.Modifier.CommandOrControl, "C", this._showConsoleTab.bind(this));
335 this._quickConsoleKeyboardShortcut = new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.Control, WI.KeyboardShortcut.Key.Apostrophe, this._focusConsolePrompt.bind(this));
337 this._inspectModeKeyboardShortcut = new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl | WI.KeyboardShortcut.Modifier.Shift, "C", this._toggleInspectMode.bind(this));
339 this._undoKeyboardShortcut = new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl, "Z", this._undoKeyboardShortcut.bind(this));
340 this._redoKeyboardShortcut = new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl | WI.KeyboardShortcut.Modifier.Shift, "Z", this._redoKeyboardShortcut.bind(this));
341 this._undoKeyboardShortcut.implicitlyPreventsDefault = this._redoKeyboardShortcut.implicitlyPreventsDefault = false;
343 this.toggleBreakpointsKeyboardShortcut = new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl, "Y", this.debuggerToggleBreakpoints.bind(this));
344 this.pauseOrResumeKeyboardShortcut = new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.Control | WI.KeyboardShortcut.Modifier.CommandOrControl, "Y", this.debuggerPauseResumeToggle.bind(this));
345 this.stepOverKeyboardShortcut = new WI.KeyboardShortcut(null, WI.KeyboardShortcut.Key.F6, this.debuggerStepOver.bind(this));
346 this.stepIntoKeyboardShortcut = new WI.KeyboardShortcut(null, WI.KeyboardShortcut.Key.F7, this.debuggerStepInto.bind(this));
347 this.stepOutKeyboardShortcut = new WI.KeyboardShortcut(null, WI.KeyboardShortcut.Key.F8, this.debuggerStepOut.bind(this));
349 this.pauseOrResumeAlternateKeyboardShortcut = new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl, WI.KeyboardShortcut.Key.Backslash, this.debuggerPauseResumeToggle.bind(this));
350 this.stepOverAlternateKeyboardShortcut = new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl, WI.KeyboardShortcut.Key.SingleQuote, this.debuggerStepOver.bind(this));
351 this.stepIntoAlternateKeyboardShortcut = new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl, WI.KeyboardShortcut.Key.Semicolon, this.debuggerStepInto.bind(this));
352 this.stepOutAlternateKeyboardShortcut = new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.Shift | WI.KeyboardShortcut.Modifier.CommandOrControl, WI.KeyboardShortcut.Key.Semicolon, this.debuggerStepOut.bind(this));
354 this._closeToolbarButton = new WI.ControlToolbarItem("dock-close", WI.UIString("Close"), "Images/Close.svg", 16, 14);
355 this._closeToolbarButton.addEventListener(WI.ButtonNavigationItem.Event.Clicked, this.close, this);
357 this._undockToolbarButton = new WI.ButtonToolbarItem("undock", WI.UIString("Detach into separate window"), null, "Images/Undock.svg");
358 this._undockToolbarButton.element.classList.add(WI.Popover.IgnoreAutoDismissClassName);
359 this._undockToolbarButton.addEventListener(WI.ButtonNavigationItem.Event.Clicked, this._undock, this);
361 let dockImage = WI.resolvedLayoutDirection() === WI.LayoutDirection.RTL ? "Images/DockLeft.svg" : "Images/DockRight.svg";
362 this._dockToSideToolbarButton = new WI.ButtonToolbarItem("dock-right", WI.UIString("Dock to side of window"), null, dockImage);
363 this._dockToSideToolbarButton.element.classList.add(WI.Popover.IgnoreAutoDismissClassName);
365 let dockToSideCallback = WI.resolvedLayoutDirection() === WI.LayoutDirection.RTL ? this._dockLeft : this._dockRight;
366 this._dockToSideToolbarButton.addEventListener(WI.ButtonNavigationItem.Event.Clicked, dockToSideCallback, this);
368 this._dockBottomToolbarButton = new WI.ButtonToolbarItem("dock-bottom", WI.UIString("Dock to bottom of window"), null, "Images/DockBottom.svg");
369 this._dockBottomToolbarButton.element.classList.add(WI.Popover.IgnoreAutoDismissClassName);
370 this._dockBottomToolbarButton.addEventListener(WI.ButtonNavigationItem.Event.Clicked, this._dockBottom, this);
372 this._togglePreviousDockConfigurationKeyboardShortcut = new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl | WI.KeyboardShortcut.Modifier.Shift, "D", this._togglePreviousDockConfiguration.bind(this));
375 if (WI.debuggableType === WI.DebuggableType.JavaScript)
376 toolTip = WI.UIString("Restart (%s)").format(this._reloadPageKeyboardShortcut.displayName);
378 toolTip = WI.UIString("Reload this page (%s)\nReload ignoring cache (%s)").format(this._reloadPageKeyboardShortcut.displayName, this._reloadPageIgnoringCacheKeyboardShortcut.displayName);
380 this._reloadToolbarButton = new WI.ButtonToolbarItem("reload", toolTip, null, "Images/ReloadToolbar.svg");
381 this._reloadToolbarButton.addEventListener(WI.ButtonNavigationItem.Event.Clicked, this._reloadPageClicked, this);
383 this._downloadToolbarButton = new WI.ButtonToolbarItem("download", WI.UIString("Download Web Archive"), null, "Images/DownloadArrow.svg");
384 this._downloadToolbarButton.addEventListener(WI.ButtonNavigationItem.Event.Clicked, this._downloadWebArchive, this);
386 this._updateReloadToolbarButton();
387 this._updateDownloadToolbarButton();
389 // The toolbar button for node inspection.
390 if (this.debuggableType === WI.DebuggableType.Web) {
391 var toolTip = WI.UIString("Start element selection (%s)").format(WI._inspectModeKeyboardShortcut.displayName);
392 var activatedToolTip = WI.UIString("Stop element selection (%s)").format(WI._inspectModeKeyboardShortcut.displayName);
393 this._inspectModeToolbarButton = new WI.ActivateButtonToolbarItem("inspect", toolTip, activatedToolTip, null, "Images/Crosshair.svg");
394 this._inspectModeToolbarButton.addEventListener(WI.ButtonNavigationItem.Event.Clicked, this._toggleInspectMode, this);
397 this._dashboardContainer = new WI.DashboardContainerView;
398 this._dashboardContainer.showDashboardViewForRepresentedObject(this.dashboardManager.dashboards.default);
400 this._searchToolbarItem = new WI.SearchBar("inspector-search", WI.UIString("Search"), null, true);
401 this._searchToolbarItem.addEventListener(WI.SearchBar.Event.TextChanged, this._searchTextDidChange, this);
403 this.toolbar.addToolbarItem(this._closeToolbarButton, WI.Toolbar.Section.Control);
405 this.toolbar.addToolbarItem(this._undockToolbarButton, WI.Toolbar.Section.Left);
406 this.toolbar.addToolbarItem(this._dockToSideToolbarButton, WI.Toolbar.Section.Left);
407 this.toolbar.addToolbarItem(this._dockBottomToolbarButton, WI.Toolbar.Section.Left);
409 this.toolbar.addToolbarItem(this._reloadToolbarButton, WI.Toolbar.Section.CenterLeft);
410 this.toolbar.addToolbarItem(this._downloadToolbarButton, WI.Toolbar.Section.CenterLeft);
412 this.toolbar.addToolbarItem(this._dashboardContainer.toolbarItem, WI.Toolbar.Section.Center);
414 if (this._inspectModeToolbarButton)
415 this.toolbar.addToolbarItem(this._inspectModeToolbarButton, WI.Toolbar.Section.CenterRight);
417 this.toolbar.addToolbarItem(this._searchToolbarItem, WI.Toolbar.Section.Right);
419 this.modifierKeys = {altKey: false, metaKey: false, shiftKey: false};
421 let dockedResizerElement = document.getElementById("docked-resizer");
422 dockedResizerElement.classList.add(WI.Popover.IgnoreAutoDismissClassName);
423 dockedResizerElement.addEventListener("mousedown", this._dockedResizerMouseDown.bind(this));
425 this._dockingAvailable = false;
427 this._updateDockNavigationItems();
428 this._setupViewHierarchy();
430 // These tabs are always available for selecting, modulo isTabAllowed().
431 // Other tabs may be engineering-only or toggled at runtime if incomplete.
432 let productionTabClasses = [
433 WI.ConsoleTabContentView,
434 WI.DebuggerTabContentView,
435 WI.ElementsTabContentView,
436 WI.NetworkTabContentView,
437 WI.NewTabContentView,
438 WI.RecordingTabContentView,
439 WI.ResourcesTabContentView,
440 WI.SearchTabContentView,
441 WI.SettingsTabContentView,
442 WI.StorageTabContentView,
443 WI.TimelineTabContentView,
446 this._knownTabClassesByType = new Map;
447 // Set tab classes directly. The public API triggers other updates and
448 // notifications that won't work or have no listeners at this point.
449 for (let tabClass of productionTabClasses)
450 this._knownTabClassesByType.set(tabClass.Type, tabClass);
452 this._pendingOpenTabs = [];
454 // Previously we may have stored duplicates in this setting. Avoid creating duplicate tabs.
455 let openTabTypes = this._openTabsSetting.value;
456 let seenTabTypes = new Set;
458 for (let i = 0; i < openTabTypes.length; ++i) {
459 let tabType = openTabTypes[i];
461 if (seenTabTypes.has(tabType))
463 seenTabTypes.add(tabType);
465 if (!this.isTabTypeAllowed(tabType)) {
466 this._pendingOpenTabs.push({tabType, index: i});
470 let tabContentView = this._createTabContentViewForType(tabType);
473 this.tabBrowser.addTabForContentView(tabContentView, {suppressAnimations: true});
476 this._restoreCookieForOpenTabs(WI.StateRestorationType.Load);
478 this.tabBar.selectedTabBarItem = this._selectedTabIndexSetting.value;
480 if (!this.tabBar.selectedTabBarItem)
481 this.tabBar.selectedTabBarItem = 0;
483 if (!this.tabBar.normalTabCount)
484 this.showNewTabTab({suppressAnimations: true});
486 // Listen to the events after restoring the saved tabs to avoid recursion.
487 this.tabBar.addEventListener(WI.TabBar.Event.TabBarItemAdded, this._rememberOpenTabs, this);
488 this.tabBar.addEventListener(WI.TabBar.Event.TabBarItemRemoved, this._rememberOpenTabs, this);
489 this.tabBar.addEventListener(WI.TabBar.Event.TabBarItemsReordered, this._rememberOpenTabs, this);
491 // Signal that the frontend is now ready to receive messages.
492 InspectorFrontendAPI.loadCompleted();
494 // Tell the InspectorFrontendHost we loaded, which causes the window to display
495 // and pending InspectorFrontendAPI commands to be sent.
496 InspectorFrontendHost.loaded();
498 if (this._showingSplitConsoleSetting.value)
499 this.showSplitConsole();
501 // Store this on the window in case the WebInspector global gets corrupted.
502 window.__frontendCompletedLoad = true;
504 if (this.runBootstrapOperations)
505 this.runBootstrapOperations();
508 // This function returns a lazily constructed instance of a class scoped to this WebInspector
509 // instance. In the unlikely event that we ever need to construct multiple WebInspector instances
510 // this allows us to scope objects within the WI.
511 // Classes can prevent usage of this function via a static `disallowInstanceForClass` function that
512 // returns true. It is then their responsibility to ensure that the returned value is tracked.
513 // Currently it is only used for sidebars.
514 WI.instanceForClass = function(constructor)
516 console.assert(typeof constructor === "function");
517 if (typeof constructor.disallowInstanceForClass === "function" && constructor.disallowInstanceForClass())
518 return new constructor;
520 let key = `__${constructor.name}`;
522 WI[key] = new constructor;
526 WI.isTabTypeAllowed = function(tabType)
528 let tabClass = this._knownTabClassesByType.get(tabType);
532 return tabClass.isTabAllowed();
535 WI.knownTabClasses = function()
537 return new Set(this._knownTabClassesByType.values());
540 WI._showOpenResourceDialog = function()
542 if (!this._openResourceDialog)
543 this._openResourceDialog = new WI.OpenResourceDialog(this);
545 if (this._openResourceDialog.visible)
548 this._openResourceDialog.present(this._contentElement);
551 WI._createTabContentViewForType = function(tabType)
553 let tabClass = this._knownTabClassesByType.get(tabType);
555 console.error("Unknown tab type", tabType);
559 console.assert(WI.TabContentView.isPrototypeOf(tabClass));
563 WI._rememberOpenTabs = function()
565 let seenTabTypes = new Set;
568 for (let tabBarItem of this.tabBar.tabBarItems) {
569 let tabContentView = tabBarItem.representedObject;
570 if (!(tabContentView instanceof WI.TabContentView))
572 if (!tabContentView.constructor.shouldSaveTab())
574 console.assert(tabContentView.type, "Tab type can't be null, undefined, or empty string", tabContentView.type, tabContentView);
575 openTabs.push(tabContentView.type);
576 seenTabTypes.add(tabContentView.type);
579 // Keep currently unsupported tabs in the setting at their previous index.
580 for (let {tabType, index} of this._pendingOpenTabs) {
581 if (seenTabTypes.has(tabType))
583 openTabs.insertAtIndex(tabType, index);
584 seenTabTypes.add(tabType);
587 this._openTabsSetting.value = openTabs;
590 WI._openDefaultTab = function(event)
592 this.showNewTabTab({suppressAnimations: true});
595 WI._showSettingsTab = function(event)
597 this.tabBrowser.showTabForContentView(this.settingsTabContentView);
600 WI._tryToRestorePendingTabs = function()
602 let stillPendingOpenTabs = [];
603 for (let {tabType, index} of this._pendingOpenTabs) {
604 if (!this.isTabTypeAllowed(tabType)) {
605 stillPendingOpenTabs.push({tabType, index});
609 let tabContentView = this._createTabContentViewForType(tabType);
613 this.tabBrowser.addTabForContentView(tabContentView, {
614 suppressAnimations: true,
615 insertionIndex: index,
618 tabContentView.restoreStateFromCookie(WI.StateRestorationType.Load);
621 this._pendingOpenTabs = stillPendingOpenTabs;
623 this.tabBrowser.tabBar.updateNewTabTabBarItemState();
626 WI.showNewTabTab = function(options)
628 if (!this.isNewTabWithTypeAllowed(WI.NewTabContentView.Type))
631 let tabContentView = this.tabBrowser.bestTabContentViewForClass(WI.NewTabContentView);
633 tabContentView = new WI.NewTabContentView;
634 this.tabBrowser.showTabForContentView(tabContentView, options);
637 WI.isNewTabWithTypeAllowed = function(tabType)
639 let tabClass = this._knownTabClassesByType.get(tabType);
640 if (!tabClass || !tabClass.isTabAllowed())
643 // Only allow one tab per class for now.
644 for (let tabBarItem of this.tabBar.tabBarItems) {
645 let tabContentView = tabBarItem.representedObject;
646 if (!(tabContentView instanceof WI.TabContentView))
648 if (tabContentView.constructor === tabClass)
652 if (tabClass === WI.NewTabContentView) {
653 let allTabs = Array.from(this.knownTabClasses());
654 let addableTabs = allTabs.filter((tabClass) => !tabClass.isEphemeral());
655 let canMakeNewTab = addableTabs.some((tabClass) => WI.isNewTabWithTypeAllowed(tabClass.Type));
656 return canMakeNewTab;
662 WI.createNewTabWithType = function(tabType, options = {})
664 console.assert(this.isNewTabWithTypeAllowed(tabType));
666 let {referencedView, shouldReplaceTab, shouldShowNewTab} = options;
667 console.assert(!referencedView || referencedView instanceof WI.TabContentView, referencedView);
668 console.assert(!shouldReplaceTab || referencedView, "Must provide a reference view to replace a tab.");
670 let tabContentView = this._createTabContentViewForType(tabType);
671 const suppressAnimations = true;
672 this.tabBrowser.addTabForContentView(tabContentView, {
674 insertionIndex: referencedView ? this.tabBar.tabBarItems.indexOf(referencedView.tabBarItem) : undefined,
677 if (shouldReplaceTab)
678 this.tabBrowser.closeTabForContentView(referencedView, {suppressAnimations});
680 if (shouldShowNewTab)
681 this.tabBrowser.showTabForContentView(tabContentView);
684 WI.registerTabClass = function(tabClass)
686 console.assert(WI.TabContentView.isPrototypeOf(tabClass));
687 if (!WI.TabContentView.isPrototypeOf(tabClass))
690 if (this._knownTabClassesByType.has(tabClass.Type))
693 this._knownTabClassesByType.set(tabClass.Type, tabClass);
695 this._tryToRestorePendingTabs();
696 this.notifications.dispatchEventToListeners(WI.Notification.TabTypesChanged);
699 WI.activateExtraDomains = function(domains)
701 this.hasExtraDomains = true;
703 for (var domain of domains) {
704 var agent = InspectorBackend.activateDomain(domain);
709 this.notifications.dispatchEventToListeners(WI.Notification.ExtraDomainsActivated, {"domains": domains});
711 WI.CSSCompletions.requestCSSCompletions();
713 this._updateReloadToolbarButton();
714 this._updateDownloadToolbarButton();
715 this._tryToRestorePendingTabs();
718 WI.updateWindowTitle = function()
720 var mainFrame = this.frameResourceManager.mainFrame;
724 var urlComponents = mainFrame.mainResource.urlComponents;
726 var lastPathComponent;
728 lastPathComponent = decodeURIComponent(urlComponents.lastPathComponent || "");
730 lastPathComponent = urlComponents.lastPathComponent;
733 // Build a title based on the URL components.
734 if (urlComponents.host && lastPathComponent)
735 var title = this.displayNameForHost(urlComponents.host) + " \u2014 " + lastPathComponent;
736 else if (urlComponents.host)
737 var title = this.displayNameForHost(urlComponents.host);
738 else if (lastPathComponent)
739 var title = lastPathComponent;
741 var title = mainFrame.url;
743 // The name "inspectedURLChanged" sounds like the whole URL is required, however this is only
744 // used for updating the window title and it can be any string.
745 InspectorFrontendHost.inspectedURLChanged(title);
748 WI.updateDockingAvailability = function(available)
750 this._dockingAvailable = available;
752 this._updateDockNavigationItems();
755 WI.updateDockedState = function(side)
757 if (this._dockConfiguration === side)
760 this._previousDockConfiguration = this._dockConfiguration;
762 if (!this._previousDockConfiguration) {
763 if (side === WI.DockConfiguration.Right || side === WI.DockConfiguration.Left)
764 this._previousDockConfiguration = WI.DockConfiguration.Bottom;
766 this._previousDockConfiguration = WI.resolvedLayoutDirection() === WI.LayoutDirection.RTL ? WI.DockConfiguration.Left : WI.DockConfiguration.Right;
769 this._dockConfiguration = side;
771 this.docked = side !== WI.DockConfiguration.Undocked;
773 this._ignoreToolbarModeDidChangeEvents = true;
775 if (side === WI.DockConfiguration.Bottom) {
776 document.body.classList.add("docked", WI.DockConfiguration.Bottom);
777 document.body.classList.remove("window-inactive", WI.DockConfiguration.Right, WI.DockConfiguration.Left);
778 } else if (side === WI.DockConfiguration.Right) {
779 document.body.classList.add("docked", WI.DockConfiguration.Right);
780 document.body.classList.remove("window-inactive", WI.DockConfiguration.Bottom, WI.DockConfiguration.Left);
781 } else if (side === WI.DockConfiguration.Left) {
782 document.body.classList.add("docked", WI.DockConfiguration.Left);
783 document.body.classList.remove("window-inactive", WI.DockConfiguration.Bottom, WI.DockConfiguration.Right);
785 document.body.classList.remove("docked", WI.DockConfiguration.Right, WI.DockConfiguration.Left, WI.DockConfiguration.Bottom);
787 this._ignoreToolbarModeDidChangeEvents = false;
789 this._updateDockNavigationItems();
791 if (!this.dockedConfigurationSupportsSplitContentBrowser() && !this.doesCurrentTabSupportSplitContentBrowser())
792 this.hideSplitConsole();
795 WI.updateVisibilityState = function(visible)
797 this.visible = visible;
798 this.notifications.dispatchEventToListeners(WI.Notification.VisibilityStateDidChange);
801 WI.handlePossibleLinkClick = function(event, frame, options = {})
803 var anchorElement = event.target.enclosingNodeOrSelfWithNodeName("a");
804 if (!anchorElement || !anchorElement.href)
807 if (WI.isBeingEdited(anchorElement)) {
808 // Don't follow the link when it is being edited.
812 // Prevent the link from navigating, since we don't do any navigation by following links normally.
813 event.preventDefault();
814 event.stopPropagation();
816 this.openURL(anchorElement.href, frame, Object.shallowMerge(options, {lineNumber: anchorElement.lineNumber}));
821 WI.openURL = function(url, frame, options = {})
827 console.assert(typeof options.lineNumber === "undefined" || typeof options.lineNumber === "number", "lineNumber should be a number.");
829 // If alwaysOpenExternally is not defined, base it off the command/meta key for the current event.
830 if (options.alwaysOpenExternally === undefined || options.alwaysOpenExternally === null)
831 options.alwaysOpenExternally = window.event ? window.event.metaKey : false;
833 if (options.alwaysOpenExternally) {
834 InspectorFrontendHost.openInNewTab(url);
838 var searchChildFrames = false;
840 frame = this.frameResourceManager.mainFrame;
841 searchChildFrames = true;
844 console.assert(frame);
846 // WI.Frame.resourceForURL does not check the main resource, only sub-resources. So check both.
847 let simplifiedURL = removeURLFragment(url);
848 var resource = frame.url === simplifiedURL ? frame.mainResource : frame.resourceForURL(simplifiedURL, searchChildFrames);
850 let positionToReveal = new WI.SourceCodePosition(options.lineNumber, 0);
851 this.showSourceCode(resource, Object.shallowMerge(options, {positionToReveal}));
855 InspectorFrontendHost.openInNewTab(url);
858 WI.close = function()
863 this._isClosing = true;
865 InspectorFrontendHost.closeWindow();
868 WI.isConsoleFocused = function()
870 return this.quickConsole.prompt.focused;
873 WI.isShowingSplitConsole = function()
875 return !this.consoleDrawer.collapsed;
878 WI.dockedConfigurationSupportsSplitContentBrowser = function()
880 return this._dockConfiguration !== WI.DockConfiguration.Bottom;
883 WI.doesCurrentTabSupportSplitContentBrowser = function()
885 var currentContentView = this.tabBrowser.selectedTabContentView;
886 return !currentContentView || currentContentView.supportsSplitContentBrowser;
889 WI.toggleSplitConsole = function()
891 if (!this.doesCurrentTabSupportSplitContentBrowser()) {
892 this.showConsoleTab();
896 if (this.isShowingSplitConsole())
897 this.hideSplitConsole();
899 this.showSplitConsole();
902 WI.showSplitConsole = function()
904 if (!this.doesCurrentTabSupportSplitContentBrowser()) {
905 this.showConsoleTab();
909 this.consoleDrawer.collapsed = false;
911 if (this.consoleDrawer.currentContentView === this.consoleContentView)
914 // Be sure to close the view in the tab content browser before showing it in the
915 // split content browser. We can only show a content view in one browser at a time.
916 if (this.consoleContentView.parentContainer)
917 this.consoleContentView.parentContainer.closeContentView(this.consoleContentView);
918 this.consoleDrawer.showContentView(this.consoleContentView);
921 WI.hideSplitConsole = function()
923 if (!this.isShowingSplitConsole())
926 this.consoleDrawer.collapsed = true;
929 WI.showConsoleTab = function(requestedScope)
931 requestedScope = requestedScope || WI.LogContentView.Scopes.All;
933 this.hideSplitConsole();
935 this.consoleContentView.scopeBar.item(requestedScope).selected = true;
937 this.showRepresentedObject(this._consoleRepresentedObject);
939 console.assert(this.isShowingConsoleTab());
942 WI.isShowingConsoleTab = function()
944 return this.tabBrowser.selectedTabContentView instanceof WI.ConsoleTabContentView;
947 WI.showElementsTab = function()
949 var tabContentView = this.tabBrowser.bestTabContentViewForClass(WI.ElementsTabContentView);
951 tabContentView = new WI.ElementsTabContentView;
952 this.tabBrowser.showTabForContentView(tabContentView);
955 WI.showDebuggerTab = function(options)
957 var tabContentView = this.tabBrowser.bestTabContentViewForClass(WI.DebuggerTabContentView);
959 tabContentView = new WI.DebuggerTabContentView;
961 if (options.breakpointToSelect instanceof WI.Breakpoint)
962 tabContentView.revealAndSelectBreakpoint(options.breakpointToSelect);
964 if (options.showScopeChainSidebar)
965 tabContentView.showScopeChainDetailsSidebarPanel();
967 this.tabBrowser.showTabForContentView(tabContentView);
970 WI.isShowingDebuggerTab = function()
972 return this.tabBrowser.selectedTabContentView instanceof WI.DebuggerTabContentView;
975 WI.showResourcesTab = function()
977 var tabContentView = this.tabBrowser.bestTabContentViewForClass(WI.ResourcesTabContentView);
979 tabContentView = new WI.ResourcesTabContentView;
980 this.tabBrowser.showTabForContentView(tabContentView);
983 WI.isShowingResourcesTab = function()
985 return this.tabBrowser.selectedTabContentView instanceof WI.ResourcesTabContentView;
988 WI.showStorageTab = function()
990 var tabContentView = this.tabBrowser.bestTabContentViewForClass(WI.StorageTabContentView);
992 tabContentView = new WI.StorageTabContentView;
993 this.tabBrowser.showTabForContentView(tabContentView);
996 WI.showNetworkTab = function()
998 var tabContentView = this.tabBrowser.bestTabContentViewForClass(WI.NetworkTabContentView);
1000 tabContentView = new WI.NetworkTabContentView;
1001 this.tabBrowser.showTabForContentView(tabContentView);
1004 WI.showTimelineTab = function()
1006 var tabContentView = this.tabBrowser.bestTabContentViewForClass(WI.TimelineTabContentView);
1007 if (!tabContentView)
1008 tabContentView = new WI.TimelineTabContentView;
1009 this.tabBrowser.showTabForContentView(tabContentView);
1012 WI.indentString = function()
1014 if (WI.settings.indentWithTabs.value)
1016 return " ".repeat(WI.settings.indentUnit.value);
1019 WI.restoreFocusFromElement = function(element)
1021 if (element && element.isSelfOrAncestor(this.currentFocusElement))
1022 this.previousFocusElement.focus();
1025 WI.toggleNavigationSidebar = function(event)
1027 if (!this.navigationSidebar.collapsed || !this.navigationSidebar.sidebarPanels.length) {
1028 this.navigationSidebar.collapsed = true;
1032 if (!this.navigationSidebar.selectedSidebarPanel)
1033 this.navigationSidebar.selectedSidebarPanel = this.navigationSidebar.sidebarPanels[0];
1034 this.navigationSidebar.collapsed = false;
1037 WI.toggleDetailsSidebar = function(event)
1039 if (!this.detailsSidebar.collapsed || !this.detailsSidebar.sidebarPanels.length) {
1040 this.detailsSidebar.collapsed = true;
1044 if (!this.detailsSidebar.selectedSidebarPanel)
1045 this.detailsSidebar.selectedSidebarPanel = this.detailsSidebar.sidebarPanels[0];
1046 this.detailsSidebar.collapsed = false;
1049 WI.tabContentViewClassForRepresentedObject = function(representedObject)
1051 if (representedObject instanceof WI.DOMTree)
1052 return WI.ElementsTabContentView;
1054 if (representedObject instanceof WI.TimelineRecording)
1055 return WI.TimelineTabContentView;
1057 // We only support one console tab right now. So this isn't an instanceof check.
1058 if (representedObject === this._consoleRepresentedObject)
1059 return WI.ConsoleTabContentView;
1061 if (WI.debuggerManager.paused) {
1062 if (representedObject instanceof WI.Script)
1063 return WI.DebuggerTabContentView;
1065 if (representedObject instanceof WI.Resource && (representedObject.type === WI.Resource.Type.Document || representedObject.type === WI.Resource.Type.Script))
1066 return WI.DebuggerTabContentView;
1069 if (representedObject instanceof WI.Frame
1070 || representedObject instanceof WI.Resource
1071 || representedObject instanceof WI.Script
1072 || representedObject instanceof WI.CSSStyleSheet
1073 || representedObject instanceof WI.Canvas)
1074 return WI.ResourcesTabContentView;
1076 // FIXME: Move Content Flows to the Elements tab?
1077 if (representedObject instanceof WI.ContentFlow)
1078 return WI.ResourcesTabContentView;
1080 // FIXME: Move these to a Storage tab.
1081 if (representedObject instanceof WI.DOMStorageObject || representedObject instanceof WI.CookieStorageObject ||
1082 representedObject instanceof WI.DatabaseTableObject || representedObject instanceof WI.DatabaseObject ||
1083 representedObject instanceof WI.ApplicationCacheFrame || representedObject instanceof WI.IndexedDatabaseObjectStore ||
1084 representedObject instanceof WI.IndexedDatabaseObjectStoreIndex)
1085 return WI.ResourcesTabContentView;
1087 if (representedObject instanceof WI.Recording)
1088 return WI.RecordingTabContentView;
1093 WI.tabContentViewForRepresentedObject = function(representedObject, options = {})
1095 let tabContentView = this.tabBrowser.bestTabContentViewForRepresentedObject(representedObject, options);
1097 return tabContentView;
1099 var tabContentViewClass = this.tabContentViewClassForRepresentedObject(representedObject);
1100 if (!tabContentViewClass) {
1101 console.error("Unknown representedObject, couldn't create TabContentView.", representedObject);
1105 tabContentView = new tabContentViewClass;
1107 this.tabBrowser.addTabForContentView(tabContentView);
1109 return tabContentView;
1112 WI.showRepresentedObject = function(representedObject, cookie, options = {})
1114 let tabContentView = this.tabContentViewForRepresentedObject(representedObject, options);
1115 console.assert(tabContentView);
1116 if (!tabContentView)
1119 this.tabBrowser.showTabForContentView(tabContentView, options);
1120 tabContentView.showRepresentedObject(representedObject, cookie);
1123 WI.showMainFrameDOMTree = function(nodeToSelect, options = {})
1125 console.assert(WI.frameResourceManager.mainFrame);
1126 if (!WI.frameResourceManager.mainFrame)
1128 this.showRepresentedObject(WI.frameResourceManager.mainFrame.domTree, {nodeToSelect}, options);
1131 WI.showSourceCodeForFrame = function(frameIdentifier, options = {})
1133 var frame = WI.frameResourceManager.frameForIdentifier(frameIdentifier);
1135 this._frameIdentifierToShowSourceCodeWhenAvailable = frameIdentifier;
1139 this._frameIdentifierToShowSourceCodeWhenAvailable = undefined;
1141 this.showRepresentedObject(frame, null, options);
1144 WI.showSourceCode = function(sourceCode, options = {})
1146 const positionToReveal = options.positionToReveal;
1148 console.assert(!positionToReveal || positionToReveal instanceof WI.SourceCodePosition, positionToReveal);
1149 var representedObject = sourceCode;
1151 if (representedObject instanceof WI.Script) {
1152 // A script represented by a resource should always show the resource.
1153 representedObject = representedObject.resource || representedObject;
1156 var cookie = positionToReveal ? {lineNumber: positionToReveal.lineNumber, columnNumber: positionToReveal.columnNumber} : {};
1157 this.showRepresentedObject(representedObject, cookie, options);
1160 WI.showSourceCodeLocation = function(sourceCodeLocation, options = {})
1162 this.showSourceCode(sourceCodeLocation.displaySourceCode, Object.shallowMerge(options, {
1163 positionToReveal: sourceCodeLocation.displayPosition(),
1167 WI.showOriginalUnformattedSourceCodeLocation = function(sourceCodeLocation, options = {})
1169 this.showSourceCode(sourceCodeLocation.sourceCode, Object.shallowMerge(options, {
1170 positionToReveal: sourceCodeLocation.position(),
1171 forceUnformatted: true,
1175 WI.showOriginalOrFormattedSourceCodeLocation = function(sourceCodeLocation, options = {})
1177 this.showSourceCode(sourceCodeLocation.sourceCode, Object.shallowMerge(options, {
1178 positionToReveal: sourceCodeLocation.formattedPosition(),
1182 WI.showOriginalOrFormattedSourceCodeTextRange = function(sourceCodeTextRange, options = {})
1184 var textRangeToSelect = sourceCodeTextRange.formattedTextRange;
1185 this.showSourceCode(sourceCodeTextRange.sourceCode, Object.shallowMerge(options, {
1186 positionToReveal: textRangeToSelect.startPosition(),
1191 WI.showResourceRequest = function(resource, options = {})
1193 this.showRepresentedObject(resource, {[WI.ResourceClusterContentView.ContentViewIdentifierCookieKey]: WI.ResourceClusterContentView.RequestIdentifier}, options);
1196 WI.debuggerToggleBreakpoints = function(event)
1198 WI.debuggerManager.breakpointsEnabled = !WI.debuggerManager.breakpointsEnabled;
1201 WI.debuggerPauseResumeToggle = function(event)
1203 if (WI.debuggerManager.paused)
1204 WI.debuggerManager.resume();
1206 WI.debuggerManager.pause();
1209 WI.debuggerStepOver = function(event)
1211 WI.debuggerManager.stepOver();
1214 WI.debuggerStepInto = function(event)
1216 WI.debuggerManager.stepInto();
1219 WI.debuggerStepOut = function(event)
1221 WI.debuggerManager.stepOut();
1224 WI._searchTextDidChange = function(event)
1226 var tabContentView = this.tabBrowser.bestTabContentViewForClass(WI.SearchTabContentView);
1227 if (!tabContentView)
1228 tabContentView = new WI.SearchTabContentView;
1230 var searchQuery = this._searchToolbarItem.text;
1231 this._searchToolbarItem.text = "";
1233 this.tabBrowser.showTabForContentView(tabContentView);
1235 tabContentView.performSearch(searchQuery);
1238 WI._focusSearchField = function(event)
1240 if (this.tabBrowser.selectedTabContentView instanceof WI.SearchTabContentView) {
1241 this.tabBrowser.selectedTabContentView.focusSearchField();
1245 this._searchToolbarItem.focus();
1248 WI._focusChanged = function(event)
1250 // Make a caret selection inside the focused element if there isn't a range selection and there isn't already
1251 // a caret selection inside. This is needed (at least) to remove caret from console when focus is moved.
1252 // The selection change should not apply to text fields and text areas either.
1254 if (WI.isEventTargetAnEditableField(event)) {
1255 // Still update the currentFocusElement if inside of a CodeMirror editor.
1256 var codeMirrorEditorElement = event.target.enclosingNodeOrSelfWithClass("CodeMirror");
1257 if (codeMirrorEditorElement && codeMirrorEditorElement !== this.currentFocusElement) {
1258 this.previousFocusElement = this.currentFocusElement;
1259 this.currentFocusElement = codeMirrorEditorElement;
1262 // Due to the change in WI.isEventTargetAnEditableField (r196271), this return
1263 // will also get run when WI.startEditing is called on an element. We do not want
1264 // to return early in this case, as WI.EditingConfig handles its own editing
1265 // completion, so only return early if the focus change target is not from WI.startEditing.
1266 if (!WI.isBeingEdited(event.target))
1270 var selection = window.getSelection();
1271 if (!selection.isCollapsed)
1274 var element = event.target;
1276 if (element !== this.currentFocusElement) {
1277 this.previousFocusElement = this.currentFocusElement;
1278 this.currentFocusElement = element;
1281 if (element.isInsertionCaretInside())
1284 var selectionRange = element.ownerDocument.createRange();
1285 selectionRange.setStart(element, 0);
1286 selectionRange.setEnd(element, 0);
1288 selection.removeAllRanges();
1289 selection.addRange(selectionRange);
1292 WI._mouseWasClicked = function(event)
1294 this.handlePossibleLinkClick(event);
1297 WI._dragOver = function(event)
1299 // Do nothing if another event listener handled the event already.
1300 if (event.defaultPrevented)
1303 // Allow dropping into editable areas.
1304 if (WI.isEventTargetAnEditableField(event))
1307 // Prevent the drop from being accepted.
1308 event.dataTransfer.dropEffect = "none";
1309 event.preventDefault();
1312 WI._debuggerDidPause = function(event)
1314 this.showDebuggerTab({showScopeChainSidebar: WI.settings.showScopeChainOnPause.value});
1316 this._dashboardContainer.showDashboardViewForRepresentedObject(this.dashboardManager.dashboards.debugger);
1318 InspectorFrontendHost.bringToFront();
1321 WI._debuggerDidResume = function(event)
1323 this._dashboardContainer.closeDashboardViewForRepresentedObject(this.dashboardManager.dashboards.debugger);
1326 WI._frameWasAdded = function(event)
1328 if (!this._frameIdentifierToShowSourceCodeWhenAvailable)
1331 var frame = event.data.frame;
1332 if (frame.id !== this._frameIdentifierToShowSourceCodeWhenAvailable)
1335 function delayedWork()
1338 ignoreNetworkTab: true,
1339 ignoreSearchTab: true,
1341 this.showSourceCodeForFrame(frame.id, options);
1344 // Delay showing the frame since FrameWasAdded is called before MainFrameChanged.
1345 // Calling showSourceCodeForFrame before MainFrameChanged will show the frame then close it.
1346 setTimeout(delayedWork.bind(this));
1349 WI._mainFrameDidChange = function(event)
1351 this._updateDownloadToolbarButton();
1353 this.updateWindowTitle();
1356 WI._mainResourceDidChange = function(event)
1358 if (!event.target.isMainFrame())
1361 this._inProvisionalLoad = false;
1363 // Run cookie restoration after we are sure all of the Tabs and NavigationSidebarPanels
1364 // have updated with respect to the main resource change.
1365 setTimeout(this._restoreCookieForOpenTabs.bind(this, WI.StateRestorationType.Navigation));
1367 this._updateDownloadToolbarButton();
1369 this.updateWindowTitle();
1372 WI._provisionalLoadStarted = function(event)
1374 if (!event.target.isMainFrame())
1377 this._saveCookieForOpenTabs();
1379 this._inProvisionalLoad = true;
1382 WI._restoreCookieForOpenTabs = function(restorationType)
1384 for (var tabBarItem of this.tabBar.tabBarItems) {
1385 var tabContentView = tabBarItem.representedObject;
1386 if (!(tabContentView instanceof WI.TabContentView))
1388 tabContentView.restoreStateFromCookie(restorationType);
1392 WI._saveCookieForOpenTabs = function()
1394 for (var tabBarItem of this.tabBar.tabBarItems) {
1395 var tabContentView = tabBarItem.representedObject;
1396 if (!(tabContentView instanceof WI.TabContentView))
1398 tabContentView.saveStateToCookie();
1402 WI._windowFocused = function(event)
1404 if (event.target.document.nodeType !== Node.DOCUMENT_NODE)
1407 // FIXME: We should use the :window-inactive pseudo class once https://webkit.org/b/38927 is fixed.
1408 document.body.classList.remove(this.docked ? "window-docked-inactive" : "window-inactive");
1411 WI._windowBlurred = function(event)
1413 if (event.target.document.nodeType !== Node.DOCUMENT_NODE)
1416 // FIXME: We should use the :window-inactive pseudo class once https://webkit.org/b/38927 is fixed.
1417 document.body.classList.add(this.docked ? "window-docked-inactive" : "window-inactive");
1420 WI._windowResized = function(event)
1422 this.toolbar.updateLayout(WI.View.LayoutReason.Resize);
1423 this.tabBar.updateLayout(WI.View.LayoutReason.Resize);
1424 this._tabBrowserSizeDidChange();
1427 WI._updateModifierKeys = function(event)
1429 var didChange = this.modifierKeys.altKey !== event.altKey || this.modifierKeys.metaKey !== event.metaKey || this.modifierKeys.shiftKey !== event.shiftKey;
1431 this.modifierKeys = {altKey: event.altKey, metaKey: event.metaKey, shiftKey: event.shiftKey};
1434 this.notifications.dispatchEventToListeners(WI.Notification.GlobalModifierKeysDidChange, event);
1437 WI._windowKeyDown = function(event)
1439 this._updateModifierKeys(event);
1442 WI._windowKeyUp = function(event)
1444 this._updateModifierKeys(event);
1447 WI._mouseDown = function(event)
1449 if (this.toolbar.element.isSelfOrAncestor(event.target))
1450 this._toolbarMouseDown(event);
1453 WI._mouseMoved = function(event)
1455 this._updateModifierKeys(event);
1456 this.mouseCoords = {
1462 WI._pageHidden = function(event)
1464 this._saveCookieForOpenTabs();
1467 WI._contextMenuRequested = function(event)
1469 let proposedContextMenu;
1471 // This is setting is only defined in engineering builds.
1472 if (WI.isDebugUIEnabled()) {
1473 proposedContextMenu = WI.ContextMenu.createFromEvent(event);
1474 proposedContextMenu.appendSeparator();
1475 proposedContextMenu.appendItem(WI.unlocalizedString("Reload Web Inspector"), () => {
1476 window.location.reload();
1479 let protocolSubMenu = proposedContextMenu.appendSubMenuItem(WI.unlocalizedString("Protocol Debugging"), null, false);
1480 let isCapturingTraffic = InspectorBackend.activeTracer instanceof WI.CapturingProtocolTracer;
1482 protocolSubMenu.appendCheckboxItem(WI.unlocalizedString("Capture Trace"), () => {
1483 if (isCapturingTraffic)
1484 InspectorBackend.activeTracer = null;
1486 InspectorBackend.activeTracer = new WI.CapturingProtocolTracer;
1487 }, isCapturingTraffic);
1489 protocolSubMenu.appendSeparator();
1491 protocolSubMenu.appendItem(WI.unlocalizedString("Export Trace\u2026"), () => {
1492 const forceSaveAs = true;
1493 WI.saveDataToFile(InspectorBackend.activeTracer.trace.saveData, forceSaveAs);
1494 }, !isCapturingTraffic);
1496 const onlyExisting = true;
1497 proposedContextMenu = WI.ContextMenu.createFromEvent(event, onlyExisting);
1500 if (proposedContextMenu)
1501 proposedContextMenu.show();
1504 WI.isDebugUIEnabled = function()
1506 return WI.showDebugUISetting && WI.showDebugUISetting.value;
1509 WI._undock = function(event)
1511 InspectorFrontendHost.requestSetDockSide(WI.DockConfiguration.Undocked);
1514 WI._dockBottom = function(event)
1516 InspectorFrontendHost.requestSetDockSide(WI.DockConfiguration.Bottom);
1519 WI._dockRight = function(event)
1521 InspectorFrontendHost.requestSetDockSide(WI.DockConfiguration.Right);
1524 WI._dockLeft = function(event)
1526 InspectorFrontendHost.requestSetDockSide(WI.DockConfiguration.Left);
1529 WI._togglePreviousDockConfiguration = function(event)
1531 InspectorFrontendHost.requestSetDockSide(this._previousDockConfiguration);
1534 WI._updateDockNavigationItems = function()
1536 if (this._dockingAvailable || this.docked) {
1537 this._closeToolbarButton.hidden = !this.docked;
1538 this._undockToolbarButton.hidden = this._dockConfiguration === WI.DockConfiguration.Undocked;
1539 this._dockBottomToolbarButton.hidden = this._dockConfiguration === WI.DockConfiguration.Bottom;
1540 this._dockToSideToolbarButton.hidden = this._dockConfiguration === WI.DockConfiguration.Right || this._dockConfiguration === WI.DockConfiguration.Left;
1542 this._closeToolbarButton.hidden = true;
1543 this._undockToolbarButton.hidden = true;
1544 this._dockBottomToolbarButton.hidden = true;
1545 this._dockToSideToolbarButton.hidden = true;
1549 WI._tabBrowserSizeDidChange = function()
1551 this.tabBrowser.updateLayout(WI.View.LayoutReason.Resize);
1552 this.consoleDrawer.updateLayout(WI.View.LayoutReason.Resize);
1553 this.quickConsole.updateLayout(WI.View.LayoutReason.Resize);
1556 WI._consoleDrawerCollapsedStateDidChange = function(event)
1558 this._showingSplitConsoleSetting.value = WI.isShowingSplitConsole();
1560 WI._consoleDrawerDidResize();
1563 WI._consoleDrawerDidResize = function(event)
1565 this.tabBrowser.updateLayout(WI.View.LayoutReason.Resize);
1568 WI._sidebarWidthDidChange = function(event)
1570 this._tabBrowserSizeDidChange();
1573 WI._setupViewHierarchy = function()
1575 let rootView = WI.View.rootView();
1576 rootView.addSubview(this.toolbar);
1577 rootView.addSubview(this.tabBar);
1578 rootView.addSubview(this.navigationSidebar);
1579 rootView.addSubview(this.tabBrowser);
1580 rootView.addSubview(this.consoleDrawer);
1581 rootView.addSubview(this.quickConsole);
1582 rootView.addSubview(this.detailsSidebar);
1585 WI._tabBrowserSelectedTabContentViewDidChange = function(event)
1587 if (this.tabBar.selectedTabBarItem && this.tabBar.selectedTabBarItem.representedObject.constructor.shouldSaveTab())
1588 this._selectedTabIndexSetting.value = this.tabBar.tabBarItems.indexOf(this.tabBar.selectedTabBarItem);
1590 if (this.doesCurrentTabSupportSplitContentBrowser()) {
1591 if (this._shouldRevealSpitConsoleIfSupported) {
1592 this._shouldRevealSpitConsoleIfSupported = false;
1593 this.showSplitConsole();
1598 this._shouldRevealSpitConsoleIfSupported = this.isShowingSplitConsole();
1599 this.hideSplitConsole();
1602 WI._toolbarMouseDown = function(event)
1607 if (this._dockConfiguration === WI.DockConfiguration.Right || this._dockConfiguration === WI.DockConfiguration.Left)
1611 this._dockedResizerMouseDown(event);
1613 this._moveWindowMouseDown(event);
1616 WI._dockedResizerMouseDown = function(event)
1618 if (event.button !== 0 || event.ctrlKey)
1624 // Only start dragging if the target is one of the elements that we expect.
1625 if (event.target.id !== "docked-resizer" && !event.target.classList.contains("toolbar") &&
1626 !event.target.classList.contains("flexible-space") && !event.target.classList.contains("item-section"))
1629 event[WI.Popover.EventPreventDismissSymbol] = true;
1631 let windowProperty = this._dockConfiguration === WI.DockConfiguration.Bottom ? "innerHeight" : "innerWidth";
1632 let eventScreenProperty = this._dockConfiguration === WI.DockConfiguration.Bottom ? "screenY" : "screenX";
1633 let eventClientProperty = this._dockConfiguration === WI.DockConfiguration.Bottom ? "clientY" : "clientX";
1635 var resizerElement = event.target;
1636 var firstClientPosition = event[eventClientProperty];
1637 var lastScreenPosition = event[eventScreenProperty];
1639 function dockedResizerDrag(event)
1641 if (event.button !== 0)
1644 var position = event[eventScreenProperty];
1645 var delta = position - lastScreenPosition;
1646 var clientPosition = event[eventClientProperty];
1648 lastScreenPosition = position;
1650 if (this._dockConfiguration === WI.DockConfiguration.Left) {
1651 // If the mouse is travelling rightward but is positioned left of the resizer, ignore the event.
1652 if (delta > 0 && clientPosition < firstClientPosition)
1655 // If the mouse is travelling leftward but is positioned to the right of the resizer, ignore the event.
1656 if (delta < 0 && clientPosition > window[windowProperty])
1659 // We later subtract the delta from the current position, but since the inspected view and inspector view
1660 // are flipped when docked to left, we want dragging to have the opposite effect from docked to right.
1663 // If the mouse is travelling downward/rightward but is positioned above/left of the resizer, ignore the event.
1664 if (delta > 0 && clientPosition < firstClientPosition)
1667 // If the mouse is travelling upward/leftward but is positioned below/right of the resizer, ignore the event.
1668 if (delta < 0 && clientPosition > firstClientPosition)
1672 let dimension = Math.max(0, window[windowProperty] - delta);
1673 // If zoomed in/out, there be greater/fewer document pixels shown, but the inspector's
1674 // width or height should be the same in device pixels regardless of the document zoom.
1675 dimension *= this.getZoomFactor();
1677 if (this._dockConfiguration === WI.DockConfiguration.Bottom)
1678 InspectorFrontendHost.setAttachedWindowHeight(dimension);
1680 InspectorFrontendHost.setAttachedWindowWidth(dimension);
1683 function dockedResizerDragEnd(event)
1685 if (event.button !== 0)
1688 WI.elementDragEnd(event);
1691 WI.elementDragStart(resizerElement, dockedResizerDrag.bind(this), dockedResizerDragEnd.bind(this), event, this._dockConfiguration === WI.DockConfiguration.Bottom ? "row-resize" : "col-resize");
1694 WI._moveWindowMouseDown = function(event)
1696 console.assert(!this.docked);
1698 if (event.button !== 0 || event.ctrlKey)
1701 // Only start dragging if the target is one of the elements that we expect.
1702 if (!event.target.classList.contains("toolbar") && !event.target.classList.contains("flexible-space") &&
1703 !event.target.classList.contains("item-section"))
1706 event[WI.Popover.EventPreventDismissSymbol] = true;
1708 if (WI.Platform.name === "mac") {
1709 // New Mac releases can start a window drag.
1710 if (WI.Platform.version.release >= 11) {
1711 InspectorFrontendHost.startWindowDrag();
1712 event.preventDefault();
1716 // Ignore dragging on the top of the toolbar on Mac if the system handles it.
1717 if (WI.Platform.version.release === 10) {
1718 const windowDragHandledTitleBarHeight = 22;
1719 if (event.pageY < windowDragHandledTitleBarHeight) {
1720 event.preventDefault();
1726 var lastScreenX = event.screenX;
1727 var lastScreenY = event.screenY;
1729 function toolbarDrag(event)
1731 if (event.button !== 0)
1734 var x = event.screenX - lastScreenX;
1735 var y = event.screenY - lastScreenY;
1737 InspectorFrontendHost.moveWindowBy(x, y);
1739 lastScreenX = event.screenX;
1740 lastScreenY = event.screenY;
1743 function toolbarDragEnd(event)
1745 if (event.button !== 0)
1748 WI.elementDragEnd(event);
1751 WI.elementDragStart(event.target, toolbarDrag, toolbarDragEnd, event, "default");
1754 WI._storageWasInspected = function(event)
1756 this.showStorageTab();
1759 WI._domNodeWasInspected = function(event)
1761 this.domTreeManager.highlightDOMNodeForTwoSeconds(event.data.node.id);
1763 InspectorFrontendHost.bringToFront();
1765 this.showElementsTab();
1766 this.showMainFrameDOMTree(event.data.node);
1769 WI._inspectModeStateChanged = function(event)
1771 this._inspectModeToolbarButton.activated = this.domTreeManager.inspectModeEnabled;
1774 WI._toggleInspectMode = function(event)
1776 this.domTreeManager.inspectModeEnabled = !this.domTreeManager.inspectModeEnabled;
1779 WI._downloadWebArchive = function(event)
1781 this.archiveMainFrame();
1784 WI._reloadPage = function(event)
1786 if (!window.PageAgent)
1790 event.preventDefault();
1793 WI._reloadPageClicked = function(event)
1795 // Ignore cache when the shift key is pressed.
1796 PageAgent.reload.invoke({shouldIgnoreCache: window.event ? window.event.shiftKey : false});
1799 WI._reloadPageIgnoringCache = function(event)
1801 if (!window.PageAgent)
1804 PageAgent.reload(true);
1805 event.preventDefault();
1808 WI._updateReloadToolbarButton = function()
1810 if (!window.PageAgent) {
1811 this._reloadToolbarButton.hidden = true;
1815 this._reloadToolbarButton.hidden = false;
1818 WI._updateDownloadToolbarButton = function()
1820 // COMPATIBILITY (iOS 7): Page.archive did not exist yet.
1821 if (!window.PageAgent || !PageAgent.archive || this.debuggableType !== WI.DebuggableType.Web) {
1822 this._downloadToolbarButton.hidden = true;
1826 if (this._downloadingPage) {
1827 this._downloadToolbarButton.enabled = false;
1831 this._downloadToolbarButton.enabled = this.canArchiveMainFrame();
1834 WI._toggleInspectMode = function(event)
1836 this.domTreeManager.inspectModeEnabled = !this.domTreeManager.inspectModeEnabled;
1839 WI._showConsoleTab = function(event)
1841 this.showConsoleTab();
1844 WI._focusConsolePrompt = function(event)
1846 this.quickConsole.prompt.focus();
1849 WI._focusedContentBrowser = function()
1851 if (this.tabBrowser.element.isSelfOrAncestor(this.currentFocusElement) || document.activeElement === document.body) {
1852 var tabContentView = this.tabBrowser.selectedTabContentView;
1853 if (tabContentView instanceof WI.ContentBrowserTabContentView)
1854 return tabContentView.contentBrowser;
1858 if (this.consoleDrawer.element.isSelfOrAncestor(this.currentFocusElement)
1859 || (WI.isShowingSplitConsole() && this.quickConsole.element.isSelfOrAncestor(this.currentFocusElement)))
1860 return this.consoleDrawer;
1865 WI._focusedContentView = function()
1867 if (this.tabBrowser.element.isSelfOrAncestor(this.currentFocusElement) || document.activeElement === document.body) {
1868 var tabContentView = this.tabBrowser.selectedTabContentView;
1869 if (tabContentView instanceof WI.ContentBrowserTabContentView)
1870 return tabContentView.contentBrowser.currentContentView;
1871 return tabContentView;
1874 if (this.consoleDrawer.element.isSelfOrAncestor(this.currentFocusElement)
1875 || (WI.isShowingSplitConsole() && this.quickConsole.element.isSelfOrAncestor(this.currentFocusElement)))
1876 return this.consoleDrawer.currentContentView;
1881 WI._focusedOrVisibleContentBrowser = function()
1883 let focusedContentBrowser = this._focusedContentBrowser();
1884 if (focusedContentBrowser)
1885 return focusedContentBrowser;
1887 var tabContentView = this.tabBrowser.selectedTabContentView;
1888 if (tabContentView instanceof WI.ContentBrowserTabContentView)
1889 return tabContentView.contentBrowser;
1894 WI.focusedOrVisibleContentView = function()
1896 let focusedContentView = this._focusedContentView();
1897 if (focusedContentView)
1898 return focusedContentView;
1900 var tabContentView = this.tabBrowser.selectedTabContentView;
1901 if (tabContentView instanceof WI.ContentBrowserTabContentView)
1902 return tabContentView.contentBrowser.currentContentView;
1903 return tabContentView;
1906 WI._beforecopy = function(event)
1908 var selection = window.getSelection();
1910 // If there is no selection, see if the focused element or focused ContentView can handle the copy event.
1911 if (selection.isCollapsed && !WI.isEventTargetAnEditableField(event)) {
1912 var focusedCopyHandler = this.currentFocusElement && this.currentFocusElement.copyHandler;
1913 if (focusedCopyHandler && typeof focusedCopyHandler.handleBeforeCopyEvent === "function") {
1914 focusedCopyHandler.handleBeforeCopyEvent(event);
1915 if (event.defaultPrevented)
1919 var focusedContentView = this._focusedContentView();
1920 if (focusedContentView && typeof focusedContentView.handleCopyEvent === "function") {
1921 event.preventDefault();
1928 if (selection.isCollapsed)
1931 // Say we can handle it (by preventing default) to remove word break characters.
1932 event.preventDefault();
1935 WI._find = function(event)
1937 let contentBrowser = this._focusedOrVisibleContentBrowser();
1938 if (!contentBrowser)
1941 contentBrowser.showFindBanner();
1944 WI._save = function(event)
1946 var contentView = this.focusedOrVisibleContentView();
1947 if (!contentView || !contentView.supportsSave)
1950 WI.saveDataToFile(contentView.saveData);
1953 WI._saveAs = function(event)
1955 var contentView = this.focusedOrVisibleContentView();
1956 if (!contentView || !contentView.supportsSave)
1959 WI.saveDataToFile(contentView.saveData, true);
1962 WI._clear = function(event)
1964 let contentView = this.focusedOrVisibleContentView();
1965 if (!contentView || typeof contentView.handleClearShortcut !== "function") {
1966 // If the current content view is unable to handle this event, clear the console to reset
1967 // the dashboard counters.
1968 this.logManager.requestClearMessages();
1972 contentView.handleClearShortcut(event);
1975 WI._copy = function(event)
1977 var selection = window.getSelection();
1979 // If there is no selection, pass the copy event on to the focused element or focused ContentView.
1980 if (selection.isCollapsed && !WI.isEventTargetAnEditableField(event)) {
1981 var focusedCopyHandler = this.currentFocusElement && this.currentFocusElement.copyHandler;
1982 if (focusedCopyHandler && typeof focusedCopyHandler.handleCopyEvent === "function") {
1983 focusedCopyHandler.handleCopyEvent(event);
1984 if (event.defaultPrevented)
1988 var focusedContentView = this._focusedContentView();
1989 if (focusedContentView && typeof focusedContentView.handleCopyEvent === "function") {
1990 focusedContentView.handleCopyEvent(event);
1994 let tabContentView = this.tabBrowser.selectedTabContentView;
1995 if (tabContentView && typeof tabContentView.handleCopyEvent === "function") {
1996 tabContentView.handleCopyEvent(event);
2003 if (selection.isCollapsed)
2006 // Remove word break characters from the selection before putting it on the pasteboard.
2007 var selectionString = selection.toString().removeWordBreakCharacters();
2008 event.clipboardData.setData("text/plain", selectionString);
2009 event.preventDefault();
2012 WI._increaseZoom = function(event)
2014 const epsilon = 0.0001;
2015 const maximumZoom = 2.4;
2016 let currentZoom = this.getZoomFactor();
2017 if (currentZoom + epsilon >= maximumZoom) {
2018 InspectorFrontendHost.beep();
2022 this.setZoomFactor(Math.min(maximumZoom, currentZoom + 0.2));
2025 WI._decreaseZoom = function(event)
2027 const epsilon = 0.0001;
2028 const minimumZoom = 0.6;
2029 let currentZoom = this.getZoomFactor();
2030 if (currentZoom - epsilon <= minimumZoom) {
2031 InspectorFrontendHost.beep();
2035 this.setZoomFactor(Math.max(minimumZoom, currentZoom - 0.2));
2038 WI._resetZoom = function(event)
2040 this.setZoomFactor(1);
2043 WI.getZoomFactor = function()
2045 return WI.settings.zoomFactor.value;
2048 WI.setZoomFactor = function(factor)
2050 InspectorFrontendHost.setZoomFactor(factor);
2051 // Round-trip through the frontend host API in case the requested factor is not used.
2052 WI.settings.zoomFactor.value = InspectorFrontendHost.zoomFactor();
2055 WI.resolvedLayoutDirection = function()
2057 let layoutDirection = WI.settings.layoutDirection.value;
2058 if (layoutDirection === WI.LayoutDirection.System)
2059 layoutDirection = InspectorFrontendHost.userInterfaceLayoutDirection();
2061 return layoutDirection;
2064 WI.setLayoutDirection = function(value)
2066 if (!Object.values(WI.LayoutDirection).includes(value))
2067 WI.reportInternalError("Unknown layout direction requested: " + value);
2069 if (value === WI.settings.layoutDirection.value)
2072 WI.settings.layoutDirection.value = value;
2074 if (WI.resolvedLayoutDirection() === WI.LayoutDirection.RTL && this._dockConfiguration === WI.DockConfiguration.Right)
2077 if (WI.resolvedLayoutDirection() === WI.LayoutDirection.LTR && this._dockConfiguration === WI.DockConfiguration.Left)
2080 window.location.reload();
2083 WI._showTabAtIndex = function(i, event)
2085 if (i <= WI.tabBar.tabBarItems.length)
2086 WI.tabBar.selectedTabBarItem = i - 1;
2089 WI._showJavaScriptTypeInformationSettingChanged = function(event)
2091 if (this.showJavaScriptTypeInformationSetting.value) {
2092 for (let target of WI.targets)
2093 target.RuntimeAgent.enableTypeProfiler();
2095 for (let target of WI.targets)
2096 target.RuntimeAgent.disableTypeProfiler();
2100 WI._enableControlFlowProfilerSettingChanged = function(event)
2102 if (this.enableControlFlowProfilerSetting.value) {
2103 for (let target of WI.targets)
2104 target.RuntimeAgent.enableControlFlowProfiler();
2106 for (let target of WI.targets)
2107 target.RuntimeAgent.disableControlFlowProfiler();
2111 WI._resourceCachingDisabledSettingChanged = function(event)
2113 NetworkAgent.setResourceCachingDisabled(this.resourceCachingDisabledSetting.value);
2116 WI.elementDragStart = function(element, dividerDrag, elementDragEnd, event, cursor, eventTarget)
2118 if (WI._elementDraggingEventListener || WI._elementEndDraggingEventListener)
2119 WI.elementDragEnd(event);
2122 // Install glass pane
2123 if (WI._elementDraggingGlassPane)
2124 WI._elementDraggingGlassPane.remove();
2126 var glassPane = document.createElement("div");
2127 glassPane.style.cssText = "position:absolute;top:0;bottom:0;left:0;right:0;opacity:0;z-index:1";
2128 glassPane.id = "glass-pane-for-drag";
2129 element.ownerDocument.body.appendChild(glassPane);
2130 WI._elementDraggingGlassPane = glassPane;
2133 WI._elementDraggingEventListener = dividerDrag;
2134 WI._elementEndDraggingEventListener = elementDragEnd;
2136 var targetDocument = event.target.ownerDocument;
2138 WI._elementDraggingEventTarget = eventTarget || targetDocument;
2139 WI._elementDraggingEventTarget.addEventListener("mousemove", dividerDrag, true);
2140 WI._elementDraggingEventTarget.addEventListener("mouseup", elementDragEnd, true);
2142 targetDocument.body.style.cursor = cursor;
2144 event.preventDefault();
2147 WI.elementDragEnd = function(event)
2149 WI._elementDraggingEventTarget.removeEventListener("mousemove", WI._elementDraggingEventListener, true);
2150 WI._elementDraggingEventTarget.removeEventListener("mouseup", WI._elementEndDraggingEventListener, true);
2152 event.target.ownerDocument.body.style.removeProperty("cursor");
2154 if (WI._elementDraggingGlassPane)
2155 WI._elementDraggingGlassPane.remove();
2157 delete WI._elementDraggingGlassPane;
2158 delete WI._elementDraggingEventTarget;
2159 delete WI._elementDraggingEventListener;
2160 delete WI._elementEndDraggingEventListener;
2162 event.preventDefault();
2165 WI.createMessageTextView = function(message, isError)
2167 var messageElement = document.createElement("div");
2168 messageElement.className = "message-text-view";
2170 messageElement.classList.add("error");
2172 messageElement.textContent = message;
2174 return messageElement;
2177 WI.createGoToArrowButton = function()
2179 var button = document.createElement("button");
2180 button.addEventListener("mousedown", (event) => { event.stopPropagation(); }, true);
2181 button.className = "go-to-arrow";
2182 button.tabIndex = -1;
2186 WI.createSourceCodeLocationLink = function(sourceCodeLocation, options = {})
2188 console.assert(sourceCodeLocation);
2189 if (!sourceCodeLocation)
2192 var linkElement = document.createElement("a");
2193 linkElement.className = "go-to-link";
2194 WI.linkifyElement(linkElement, sourceCodeLocation, options);
2195 sourceCodeLocation.populateLiveDisplayLocationTooltip(linkElement);
2197 if (options.useGoToArrowButton)
2198 linkElement.appendChild(WI.createGoToArrowButton());
2200 sourceCodeLocation.populateLiveDisplayLocationString(linkElement, "textContent", options.columnStyle, options.nameStyle, options.prefix);
2202 if (options.dontFloat)
2203 linkElement.classList.add("dont-float");
2208 WI.linkifyLocation = function(url, sourceCodePosition, options = {})
2210 var sourceCode = WI.sourceCodeForURL(url);
2213 var anchor = document.createElement("a");
2215 anchor.lineNumber = sourceCodePosition.lineNumber;
2216 if (options.className)
2217 anchor.className = options.className;
2218 anchor.append(WI.displayNameForURL(url) + ":" + sourceCodePosition.lineNumber);
2222 let sourceCodeLocation = sourceCode.createSourceCodeLocation(sourceCodePosition.lineNumber, sourceCodePosition.columnNumber);
2223 let linkElement = WI.createSourceCodeLocationLink(sourceCodeLocation, Object.shallowMerge(options, {dontFloat: true}));
2224 if (options.className)
2225 linkElement.classList.add(options.className);
2229 WI.linkifyElement = function(linkElement, sourceCodeLocation, options = {}) {
2230 console.assert(sourceCodeLocation);
2232 function showSourceCodeLocation(event)
2234 event.stopPropagation();
2235 event.preventDefault();
2238 this.showOriginalUnformattedSourceCodeLocation(sourceCodeLocation, options);
2240 this.showSourceCodeLocation(sourceCodeLocation, options);
2243 linkElement.addEventListener("click", showSourceCodeLocation.bind(this));
2244 linkElement.addEventListener("contextmenu", (event) => {
2245 let contextMenu = WI.ContextMenu.createFromEvent(event);
2246 WI.appendContextMenuItemsForSourceCode(contextMenu, sourceCodeLocation);
2250 WI.sourceCodeForURL = function(url)
2252 var sourceCode = WI.frameResourceManager.resourceForURL(url);
2254 sourceCode = WI.debuggerManager.scriptsForURL(url, WI.assumingMainTarget())[0];
2256 sourceCode = sourceCode.resource || sourceCode;
2258 return sourceCode || null;
2261 WI.linkifyURLAsNode = function(url, linkText, classes)
2266 classes = (classes ? classes + " " : "");
2268 var a = document.createElement("a");
2270 a.className = classes;
2272 a.textContent = linkText;
2273 a.style.maxWidth = "100%";
2278 WI.linkifyStringAsFragmentWithCustomLinkifier = function(string, linkifier)
2280 var container = document.createDocumentFragment();
2281 var linkStringRegEx = /(?:[a-zA-Z][a-zA-Z0-9+.-]{2,}:\/\/|www\.)[\w$\-_+*'=\|\/\\(){}[\]%@&#~,:;.!?]{2,}[\w$\-_+*=\|\/\\({%@&#~]/;
2282 var lineColumnRegEx = /:(\d+)(:(\d+))?$/;
2285 var linkString = linkStringRegEx.exec(string);
2289 linkString = linkString[0];
2290 var linkIndex = string.indexOf(linkString);
2291 var nonLink = string.substring(0, linkIndex);
2292 container.append(nonLink);
2294 if (linkString.startsWith("data:") || linkString.startsWith("javascript:") || linkString.startsWith("mailto:")) {
2295 container.append(linkString);
2296 string = string.substring(linkIndex + linkString.length, string.length);
2300 var title = linkString;
2301 var realURL = linkString.startsWith("www.") ? "http://" + linkString : linkString;
2302 var lineColumnMatch = lineColumnRegEx.exec(realURL);
2303 if (lineColumnMatch)
2304 realURL = realURL.substring(0, realURL.length - lineColumnMatch[0].length);
2307 if (lineColumnMatch)
2308 lineNumber = parseInt(lineColumnMatch[1]) - 1;
2310 var linkNode = linkifier(title, realURL, lineNumber);
2311 container.appendChild(linkNode);
2312 string = string.substring(linkIndex + linkString.length, string.length);
2316 container.append(string);
2321 WI.linkifyStringAsFragment = function(string)
2323 function linkifier(title, url, lineNumber)
2325 var urlNode = WI.linkifyURLAsNode(url, title, undefined);
2326 if (lineNumber !== undefined)
2327 urlNode.lineNumber = lineNumber;
2332 return WI.linkifyStringAsFragmentWithCustomLinkifier(string, linkifier);
2335 WI.createResourceLink = function(resource, className)
2337 function handleClick(event)
2339 event.stopPropagation();
2340 event.preventDefault();
2342 WI.showRepresentedObject(resource);
2345 let linkNode = document.createElement("a");
2346 linkNode.classList.add("resource-link", className);
2347 linkNode.title = resource.url;
2348 linkNode.textContent = (resource.urlComponents.lastPathComponent || resource.url).insertWordBreakCharacters();
2349 linkNode.addEventListener("click", handleClick.bind(this));
2353 WI._undoKeyboardShortcut = function(event)
2355 if (!this.isEditingAnyField() && !this.isEventTargetAnEditableField(event)) {
2357 event.preventDefault();
2361 WI._redoKeyboardShortcut = function(event)
2363 if (!this.isEditingAnyField() && !this.isEventTargetAnEditableField(event)) {
2365 event.preventDefault();
2369 WI.undo = function()
2374 WI.redo = function()
2379 WI.highlightRangesWithStyleClass = function(element, resultRanges, styleClass, changes)
2381 changes = changes || [];
2382 var highlightNodes = [];
2383 var lineText = element.textContent;
2384 var ownerDocument = element.ownerDocument;
2385 var textNodeSnapshot = ownerDocument.evaluate(".//text()", element, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
2387 var snapshotLength = textNodeSnapshot.snapshotLength;
2388 if (snapshotLength === 0)
2389 return highlightNodes;
2391 var nodeRanges = [];
2392 var rangeEndOffset = 0;
2393 for (var i = 0; i < snapshotLength; ++i) {
2395 range.offset = rangeEndOffset;
2396 range.length = textNodeSnapshot.snapshotItem(i).textContent.length;
2397 rangeEndOffset = range.offset + range.length;
2398 nodeRanges.push(range);
2402 for (var i = 0; i < resultRanges.length; ++i) {
2403 var startOffset = resultRanges[i].offset;
2404 var endOffset = startOffset + resultRanges[i].length;
2406 while (startIndex < snapshotLength && nodeRanges[startIndex].offset + nodeRanges[startIndex].length <= startOffset)
2408 var endIndex = startIndex;
2409 while (endIndex < snapshotLength && nodeRanges[endIndex].offset + nodeRanges[endIndex].length < endOffset)
2411 if (endIndex === snapshotLength)
2414 var highlightNode = ownerDocument.createElement("span");
2415 highlightNode.className = styleClass;
2416 highlightNode.textContent = lineText.substring(startOffset, endOffset);
2418 var lastTextNode = textNodeSnapshot.snapshotItem(endIndex);
2419 var lastText = lastTextNode.textContent;
2420 lastTextNode.textContent = lastText.substring(endOffset - nodeRanges[endIndex].offset);
2421 changes.push({node: lastTextNode, type: "changed", oldText: lastText, newText: lastTextNode.textContent});
2423 if (startIndex === endIndex) {
2424 lastTextNode.parentElement.insertBefore(highlightNode, lastTextNode);
2425 changes.push({node: highlightNode, type: "added", nextSibling: lastTextNode, parent: lastTextNode.parentElement});
2426 highlightNodes.push(highlightNode);
2428 var prefixNode = ownerDocument.createTextNode(lastText.substring(0, startOffset - nodeRanges[startIndex].offset));
2429 lastTextNode.parentElement.insertBefore(prefixNode, highlightNode);
2430 changes.push({node: prefixNode, type: "added", nextSibling: highlightNode, parent: lastTextNode.parentElement});
2432 var firstTextNode = textNodeSnapshot.snapshotItem(startIndex);
2433 var firstText = firstTextNode.textContent;
2434 var anchorElement = firstTextNode.nextSibling;
2436 firstTextNode.parentElement.insertBefore(highlightNode, anchorElement);
2437 changes.push({node: highlightNode, type: "added", nextSibling: anchorElement, parent: firstTextNode.parentElement});
2438 highlightNodes.push(highlightNode);
2440 firstTextNode.textContent = firstText.substring(0, startOffset - nodeRanges[startIndex].offset);
2441 changes.push({node: firstTextNode, type: "changed", oldText: firstText, newText: firstTextNode.textContent});
2443 for (var j = startIndex + 1; j < endIndex; j++) {
2444 var textNode = textNodeSnapshot.snapshotItem(j);
2445 var text = textNode.textContent;
2446 textNode.textContent = "";
2447 changes.push({node: textNode, type: "changed", oldText: text, newText: textNode.textContent});
2450 startIndex = endIndex;
2451 nodeRanges[startIndex].offset = endOffset;
2452 nodeRanges[startIndex].length = lastTextNode.textContent.length;
2455 return highlightNodes;
2458 WI.revertDomChanges = function(domChanges)
2460 for (var i = domChanges.length - 1; i >= 0; --i) {
2461 var entry = domChanges[i];
2462 switch (entry.type) {
2464 entry.node.remove();
2467 entry.node.textContent = entry.oldText;
2473 WI.archiveMainFrame = function()
2475 this._downloadingPage = true;
2476 this._updateDownloadToolbarButton();
2478 PageAgent.archive((error, data) => {
2479 this._downloadingPage = false;
2480 this._updateDownloadToolbarButton();
2485 let mainFrame = WI.frameResourceManager.mainFrame;
2486 let archiveName = mainFrame.mainResource.urlComponents.host || mainFrame.mainResource.displayName || "Archive";
2487 let url = "web-inspector:///" + encodeURI(archiveName) + ".webarchive";
2489 InspectorFrontendHost.save(url, data, true, true);
2493 WI.canArchiveMainFrame = function()
2495 // COMPATIBILITY (iOS 7): Page.archive did not exist yet.
2496 if (!PageAgent.archive || this.debuggableType !== WI.DebuggableType.Web)
2499 if (!WI.frameResourceManager.mainFrame || !WI.frameResourceManager.mainFrame.mainResource)
2502 return WI.Resource.typeFromMIMEType(WI.frameResourceManager.mainFrame.mainResource.mimeType) === WI.Resource.Type.Document;
2505 WI.addWindowKeydownListener = function(listener)
2507 if (typeof listener.handleKeydownEvent !== "function")
2510 this._windowKeydownListeners.push(listener);
2512 this._updateWindowKeydownListener();
2515 WI.removeWindowKeydownListener = function(listener)
2517 this._windowKeydownListeners.remove(listener);
2519 this._updateWindowKeydownListener();
2522 WI._updateWindowKeydownListener = function()
2524 if (this._windowKeydownListeners.length === 1)
2525 window.addEventListener("keydown", WI._sharedWindowKeydownListener, true);
2526 else if (!this._windowKeydownListeners.length)
2527 window.removeEventListener("keydown", WI._sharedWindowKeydownListener, true);
2530 WI._sharedWindowKeydownListener = function(event)
2532 for (var i = WI._windowKeydownListeners.length - 1; i >= 0; --i) {
2533 if (WI._windowKeydownListeners[i].handleKeydownEvent(event)) {
2534 event.stopImmediatePropagation();
2535 event.preventDefault();
2541 WI.reportInternalError = function(errorOrString, details={})
2543 // The 'details' object includes additional information from the caller as free-form string keys and values.
2544 // Each key and value will be shown in the uncaught exception reporter, console error message, or in
2545 // a pre-filled bug report generated for this internal error.
2547 let error = (errorOrString instanceof Error) ? errorOrString : new Error(errorOrString);
2548 error.details = details;
2550 // The error will be displayed in the Uncaught Exception Reporter sheet if DebugUI is enabled.
2551 if (WI.isDebugUIEnabled()) {
2552 // This assert allows us to stop the debugger at an internal exception. It doesn't re-throw
2553 // exceptions because the original exception would be lost through window.onerror.
2554 // This workaround can be removed once <https://webkit.org/b/158192> is fixed.
2555 console.assert(false, "An internal exception was thrown.", error);
2556 handleInternalException(error);
2558 console.error(error);
2561 Object.defineProperty(WI, "targets",
2563 get() { return this.targetManager.targets; }
2566 // Many places assume the main target because they cannot yet be
2567 // used by reached by Worker debugging. Eventually, once all
2568 // Worker domains have been implemented, all of these must be
2569 // handled properly.
2570 WI.assumingMainTarget = function()
2572 return WI.mainTarget;
2575 // OpenResourceDialog delegate
2577 WI.dialogWasDismissed = function(dialog)
2579 let representedObject = dialog.representedObject;
2580 if (!representedObject)
2583 WI.showRepresentedObject(representedObject, dialog.cookie);
2586 WI.DockConfiguration = {
2590 Undocked: "undocked",