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"
36 WI.SelectedSidebarPanelCookieKey = "selected-sidebar-panel";
37 WI.TypeIdentifierCookieKey = "represented-object-type";
39 WI.StateRestorationType = {
40 Load: "state-restoration-load",
41 Navigation: "state-restoration-navigation",
42 Delayed: "state-restoration-delayed",
45 WI.LayoutDirection = {
51 WI.loaded = function()
53 // Register observers for events from the InspectorBackend.
54 if (InspectorBackend.registerTargetDispatcher)
55 InspectorBackend.registerTargetDispatcher(new WI.TargetObserver);
56 if (InspectorBackend.registerInspectorDispatcher)
57 InspectorBackend.registerInspectorDispatcher(new WI.InspectorObserver);
58 if (InspectorBackend.registerPageDispatcher)
59 InspectorBackend.registerPageDispatcher(new WI.PageObserver);
60 if (InspectorBackend.registerConsoleDispatcher)
61 InspectorBackend.registerConsoleDispatcher(new WI.ConsoleObserver);
62 if (InspectorBackend.registerNetworkDispatcher)
63 InspectorBackend.registerNetworkDispatcher(new WI.NetworkObserver);
64 if (InspectorBackend.registerDOMDispatcher)
65 InspectorBackend.registerDOMDispatcher(new WI.DOMObserver);
66 if (InspectorBackend.registerDebuggerDispatcher)
67 InspectorBackend.registerDebuggerDispatcher(new WI.DebuggerObserver);
68 if (InspectorBackend.registerHeapDispatcher)
69 InspectorBackend.registerHeapDispatcher(new WI.HeapObserver);
70 if (InspectorBackend.registerMemoryDispatcher)
71 InspectorBackend.registerMemoryDispatcher(new WI.MemoryObserver);
72 if (InspectorBackend.registerDatabaseDispatcher)
73 InspectorBackend.registerDatabaseDispatcher(new WI.DatabaseObserver);
74 if (InspectorBackend.registerDOMStorageDispatcher)
75 InspectorBackend.registerDOMStorageDispatcher(new WI.DOMStorageObserver);
76 if (InspectorBackend.registerApplicationCacheDispatcher)
77 InspectorBackend.registerApplicationCacheDispatcher(new WI.ApplicationCacheObserver);
78 if (InspectorBackend.registerCPUProfilerDispatcher)
79 InspectorBackend.registerCPUProfilerDispatcher(new WI.CPUProfilerObserver);
80 if (InspectorBackend.registerScriptProfilerDispatcher)
81 InspectorBackend.registerScriptProfilerDispatcher(new WI.ScriptProfilerObserver);
82 if (InspectorBackend.registerTimelineDispatcher)
83 InspectorBackend.registerTimelineDispatcher(new WI.TimelineObserver);
84 if (InspectorBackend.registerCSSDispatcher)
85 InspectorBackend.registerCSSDispatcher(new WI.CSSObserver);
86 if (InspectorBackend.registerLayerTreeDispatcher)
87 InspectorBackend.registerLayerTreeDispatcher(new WI.LayerTreeObserver);
88 if (InspectorBackend.registerRuntimeDispatcher)
89 InspectorBackend.registerRuntimeDispatcher(new WI.RuntimeObserver);
90 if (InspectorBackend.registerWorkerDispatcher)
91 InspectorBackend.registerWorkerDispatcher(new WI.WorkerObserver);
92 if (InspectorBackend.registerCanvasDispatcher)
93 InspectorBackend.registerCanvasDispatcher(new WI.CanvasObserver);
95 // Listen for the ProvisionalLoadStarted event before registering for events so our code gets called before any managers or sidebars.
96 // This lets us save a state cookie before any managers or sidebars do any resets that would affect state (namely TimelineManager).
97 WI.Frame.addEventListener(WI.Frame.Event.ProvisionalLoadStarted, this._provisionalLoadStarted, this);
99 // Populate any UIStrings that must be done early after localized strings have loaded.
100 WI.KeyboardShortcut.Key.Space._displayName = WI.UIString("Space");
102 // Create the singleton managers next, before the user interface elements, so the user interface can register
103 // as event listeners on these managers.
105 WI.targetManager = new WI.TargetManager,
106 WI.branchManager = new WI.BranchManager,
107 WI.networkManager = new WI.NetworkManager,
108 WI.domStorageManager = new WI.DOMStorageManager,
109 WI.databaseManager = new WI.DatabaseManager,
110 WI.indexedDBManager = new WI.IndexedDBManager,
111 WI.domManager = new WI.DOMManager,
112 WI.cssManager = new WI.CSSManager,
113 WI.consoleManager = new WI.ConsoleManager,
114 WI.runtimeManager = new WI.RuntimeManager,
115 WI.heapManager = new WI.HeapManager,
116 WI.memoryManager = new WI.MemoryManager,
117 WI.applicationCacheManager = new WI.ApplicationCacheManager,
118 WI.timelineManager = new WI.TimelineManager,
119 WI.auditManager = new WI.AuditManager,
120 WI.debuggerManager = new WI.DebuggerManager,
121 WI.layerTreeManager = new WI.LayerTreeManager,
122 WI.workerManager = new WI.WorkerManager,
123 WI.domDebuggerManager = new WI.DOMDebuggerManager,
124 WI.canvasManager = new WI.CanvasManager,
127 // Register for events.
128 WI.debuggerManager.addEventListener(WI.DebuggerManager.Event.Paused, this._debuggerDidPause, this);
129 WI.debuggerManager.addEventListener(WI.DebuggerManager.Event.Resumed, this._debuggerDidResume, this);
130 WI.domManager.addEventListener(WI.DOMManager.Event.InspectModeStateChanged, this._inspectModeStateChanged, this);
131 WI.domManager.addEventListener(WI.DOMManager.Event.DOMNodeWasInspected, this._domNodeWasInspected, this);
132 WI.domStorageManager.addEventListener(WI.DOMStorageManager.Event.DOMStorageObjectWasInspected, this._domStorageWasInspected, this);
133 WI.databaseManager.addEventListener(WI.DatabaseManager.Event.DatabaseWasInspected, this._databaseWasInspected, this);
134 WI.networkManager.addEventListener(WI.NetworkManager.Event.MainFrameDidChange, this._mainFrameDidChange, this);
135 WI.networkManager.addEventListener(WI.NetworkManager.Event.FrameWasAdded, this._frameWasAdded, this);
137 WI.Frame.addEventListener(WI.Frame.Event.MainResourceDidChange, this._mainResourceDidChange, this);
139 document.addEventListener("DOMContentLoaded", this.contentLoaded.bind(this));
142 this._showingSplitConsoleSetting = new WI.Setting("showing-split-console", false);
143 this._openTabsSetting = new WI.Setting("open-tab-types", [
144 WI.ElementsTabContentView.Type,
145 WI.NetworkTabContentView.Type,
146 WI.DebuggerTabContentView.Type,
147 WI.ResourcesTabContentView.Type,
148 WI.TimelineTabContentView.Type,
149 WI.StorageTabContentView.Type,
150 WI.CanvasTabContentView.Type,
151 WI.AuditTabContentView.Type,
152 WI.ConsoleTabContentView.Type,
154 this._selectedTabIndexSetting = new WI.Setting("selected-tab-index", 0);
157 this.printStylesEnabled = false;
158 this.setZoomFactor(WI.settings.zoomFactor.value);
159 this.mouseCoords = {x: 0, y: 0};
160 this.modifierKeys = {altKey: false, metaKey: false, shiftKey: false};
161 this.visible = false;
162 this._windowKeydownListeners = [];
163 this._targetsAvailablePromise = new WI.WrappedPromise;
164 WI._overridenDeviceUserAgent = null;
165 WI._overridenDeviceSettings = new Map;
168 WI.backendTarget = null;
169 WI.pageTarget = null;
171 if (!window.TargetAgent)
172 WI.targetManager.createDirectBackendTarget();
174 // FIXME: Eliminate `TargetAgent.exists` once the local inspector
175 // is configured to use the Multiplexing code path.
176 TargetAgent.exists((error) => {
178 WI.targetManager.createDirectBackendTarget();
183 WI.initializeBackendTarget = function(target)
185 console.assert(!WI.mainTarget);
187 WI.backendTarget = target;
189 WI.resetMainExecutionContext();
191 this._targetsAvailablePromise.resolve();
194 WI.initializePageTarget = function(target)
196 console.assert(WI.sharedApp.debuggableType === WI.DebuggableType.Web);
197 console.assert(target.type === WI.Target.Type.Page || target instanceof WI.DirectBackendTarget);
199 WI.pageTarget = target;
201 WI.redirectGlobalAgentsToConnection(WI.pageTarget.connection);
203 WI.resetMainExecutionContext();
206 WI.transitionPageTarget = function(target)
208 console.assert(!WI.pageTarget);
209 console.assert(WI.sharedApp.debuggableType === WI.DebuggableType.Web);
210 console.assert(target.type === WI.Target.Type.Page);
212 WI.pageTarget = target;
214 WI.redirectGlobalAgentsToConnection(WI.pageTarget.connection);
216 WI.resetMainExecutionContext();
218 // Actions to transition the page target.
219 this.notifications.dispatchEventToListeners(WI.Notification.TransitionPageTarget);
220 WI.domManager.transitionPageTarget();
221 WI.networkManager.transitionPageTarget();
222 WI.timelineManager.transitionPageTarget();
225 WI.terminatePageTarget = function(target)
227 console.assert(WI.pageTarget);
228 console.assert(WI.pageTarget === target);
229 console.assert(WI.sharedApp.debuggableType === WI.DebuggableType.Web);
231 // Remove any Worker targets associated with this page.
232 let workerTargets = WI.targets.filter((x) => x.type === WI.Target.Type.Worker);
233 for (let workerTarget of workerTargets)
234 WI.workerManager.workerTerminated(workerTarget.identifier);
236 WI.pageTarget = null;
238 WI.redirectGlobalAgentsToConnection(WI.backendConnection);
241 WI.resetMainExecutionContext = function()
243 if (WI.mainTarget instanceof WI.MultiplexingBackendTarget)
246 if (WI.mainTarget.executionContext) {
247 WI.runtimeManager.activeExecutionContext = WI.mainTarget.executionContext;
249 WI.quickConsole.initializeMainExecutionContextPathComponent();
253 WI.redirectGlobalAgentsToConnection = function(connection)
255 // This makes global window.FooAgent dispatch to the active page target.
256 for (let [domain, agent] of Object.entries(InspectorBackend._agents)) {
257 if (domain !== "Target")
258 agent.connection = connection;
262 WI.contentLoaded = function()
264 // If there was an uncaught exception earlier during loading, then
265 // abort loading more content. We could be in an inconsistent state.
266 if (window.__uncaughtExceptions)
269 // Register for global events.
270 document.addEventListener("beforecopy", this._beforecopy.bind(this));
271 document.addEventListener("copy", this._copy.bind(this));
273 document.addEventListener("click", this._mouseWasClicked.bind(this));
274 document.addEventListener("dragover", this._dragOver.bind(this));
275 document.addEventListener("focus", WI._focusChanged.bind(this), true);
277 window.addEventListener("focus", this._windowFocused.bind(this));
278 window.addEventListener("blur", this._windowBlurred.bind(this));
279 window.addEventListener("resize", this._windowResized.bind(this));
280 window.addEventListener("keydown", this._windowKeyDown.bind(this));
281 window.addEventListener("keyup", this._windowKeyUp.bind(this));
282 window.addEventListener("mousedown", this._mouseDown.bind(this), true);
283 window.addEventListener("mousemove", this._mouseMoved.bind(this), true);
284 window.addEventListener("pagehide", this._pageHidden.bind(this));
285 window.addEventListener("contextmenu", this._contextMenuRequested.bind(this));
287 // Add platform style classes so the UI can be tweaked per-platform.
288 document.body.classList.add(WI.Platform.name + "-platform");
289 if (WI.Platform.isNightlyBuild)
290 document.body.classList.add("nightly-build");
292 if (WI.Platform.name === "mac") {
293 document.body.classList.add(WI.Platform.version.name);
295 if (WI.Platform.version.release >= 11)
296 document.body.classList.add("latest-mac");
298 document.body.classList.add("legacy-mac");
301 document.body.classList.add(WI.sharedApp.debuggableType);
302 document.body.setAttribute("dir", this.resolvedLayoutDirection());
304 WI.settings.showJavaScriptTypeInformation.addEventListener(WI.Setting.Event.Changed, this._showJavaScriptTypeInformationSettingChanged, this);
305 WI.settings.enableControlFlowProfiler.addEventListener(WI.Setting.Event.Changed, this._enableControlFlowProfilerSettingChanged, this);
306 WI.settings.resourceCachingDisabled.addEventListener(WI.Setting.Event.Changed, this._resourceCachingDisabledSettingChanged, this);
308 function setTabSize() {
309 document.body.style.tabSize = WI.settings.tabSize.value;
311 WI.settings.tabSize.addEventListener(WI.Setting.Event.Changed, setTabSize);
314 function setInvalidCharacterClassName() {
315 document.body.classList.toggle("show-invalid-characters", WI.settings.showInvalidCharacters.value);
317 WI.settings.showInvalidCharacters.addEventListener(WI.Setting.Event.Changed, setInvalidCharacterClassName);
318 setInvalidCharacterClassName();
320 function setWhitespaceCharacterClassName() {
321 document.body.classList.toggle("show-whitespace-characters", WI.settings.showWhitespaceCharacters.value);
323 WI.settings.showWhitespaceCharacters.addEventListener(WI.Setting.Event.Changed, setWhitespaceCharacterClassName);
324 setWhitespaceCharacterClassName();
326 this.settingsTabContentView = new WI.SettingsTabContentView;
328 this._settingsKeyboardShortcut = new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl, WI.KeyboardShortcut.Key.Comma, this._showSettingsTab.bind(this));
330 // Create the user interface elements.
331 this.toolbar = new WI.Toolbar(document.getElementById("toolbar"));
333 if (WI.settings.experimentalEnableNewTabBar.value)
334 this.tabBar = new WI.TabBar(document.getElementById("tab-bar"));
336 this.tabBar = new WI.LegacyTabBar(document.getElementById("tab-bar"));
337 this.tabBar.addEventListener(WI.TabBar.Event.OpenDefaultTab, this._openDefaultTab, this);
340 this._contentElement = document.getElementById("content");
341 this._contentElement.setAttribute("role", "main");
342 this._contentElement.setAttribute("aria-label", WI.UIString("Content"));
344 this.clearKeyboardShortcut = new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl, "K", this._clear.bind(this));
346 // FIXME: <https://webkit.org/b/151310> Web Inspector: Command-E should propagate to other search fields (including the system)
347 this.populateFindKeyboardShortcut = new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl, "E", this._populateFind.bind(this));
348 this.populateFindKeyboardShortcut.implicitlyPreventsDefault = false;
349 this.findNextKeyboardShortcut = new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl, "G", this._findNext.bind(this));
350 this.findPreviousKeyboardShortcut = new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.Shift | WI.KeyboardShortcut.Modifier.CommandOrControl, "G", this._findPrevious.bind(this));
352 this.consoleDrawer = new WI.ConsoleDrawer(document.getElementById("console-drawer"));
353 this.consoleDrawer.addEventListener(WI.ConsoleDrawer.Event.CollapsedStateChanged, this._consoleDrawerCollapsedStateDidChange, this);
354 this.consoleDrawer.addEventListener(WI.ConsoleDrawer.Event.Resized, this._consoleDrawerDidResize, this);
356 this.quickConsole = new WI.QuickConsole(document.getElementById("quick-console"));
358 this._consoleRepresentedObject = new WI.LogObject;
359 this.consoleContentView = this.consoleDrawer.contentViewForRepresentedObject(this._consoleRepresentedObject);
360 this.consoleLogViewController = this.consoleContentView.logViewController;
361 this.breakpointPopoverController = new WI.BreakpointPopoverController;
363 // FIXME: The sidebars should be flipped in RTL languages.
364 this.navigationSidebar = new WI.Sidebar(document.getElementById("navigation-sidebar"), WI.Sidebar.Sides.Left);
365 this.navigationSidebar.addEventListener(WI.Sidebar.Event.WidthDidChange, this._sidebarWidthDidChange, this);
367 this.detailsSidebar = new WI.Sidebar(document.getElementById("details-sidebar"), WI.Sidebar.Sides.Right, null, null, WI.UIString("Details"), true);
368 this.detailsSidebar.addEventListener(WI.Sidebar.Event.WidthDidChange, this._sidebarWidthDidChange, this);
370 this.searchKeyboardShortcut = new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl | WI.KeyboardShortcut.Modifier.Shift, "F", this._focusSearchField.bind(this));
371 this._findKeyboardShortcut = new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl, "F", this._find.bind(this));
372 this.saveKeyboardShortcut = new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl, "S", this._save.bind(this));
373 this._saveAsKeyboardShortcut = new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.Shift | WI.KeyboardShortcut.Modifier.CommandOrControl, "S", this._saveAs.bind(this));
375 this.openResourceKeyboardShortcut = new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl | WI.KeyboardShortcut.Modifier.Shift, "O", this._showOpenResourceDialog.bind(this));
376 new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl, "P", this._showOpenResourceDialog.bind(this));
378 this.navigationSidebarKeyboardShortcut = new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl | WI.KeyboardShortcut.Modifier.Shift, "0", this.toggleNavigationSidebar.bind(this));
379 this.detailsSidebarKeyboardShortcut = new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl | WI.KeyboardShortcut.Modifier.Option, "0", this.toggleDetailsSidebar.bind(this));
381 let boundIncreaseZoom = this._increaseZoom.bind(this);
382 let boundDecreaseZoom = this._decreaseZoom.bind(this);
383 this._increaseZoomKeyboardShortcut = new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl, WI.KeyboardShortcut.Key.Plus, boundIncreaseZoom);
384 this._decreaseZoomKeyboardShortcut = new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl, WI.KeyboardShortcut.Key.Minus, boundDecreaseZoom);
385 this._increaseZoomKeyboardShortcut2 = new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl | WI.KeyboardShortcut.Modifier.Shift, WI.KeyboardShortcut.Key.Plus, boundIncreaseZoom);
386 this._decreaseZoomKeyboardShortcut2 = new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl | WI.KeyboardShortcut.Modifier.Shift, WI.KeyboardShortcut.Key.Minus, boundDecreaseZoom);
387 this._resetZoomKeyboardShortcut = new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl, "0", this._resetZoom.bind(this));
389 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)));
390 this._openNewTabKeyboardShortcut = new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl | WI.KeyboardShortcut.Modifier.Option, "T", this.showNewTabTab.bind(this));
392 this.tabBrowser = new WI.TabBrowser(document.getElementById("tab-browser"), this.tabBar, this.navigationSidebar, this.detailsSidebar);
393 this.tabBrowser.addEventListener(WI.TabBrowser.Event.SelectedTabContentViewDidChange, this._tabBrowserSelectedTabContentViewDidChange, this);
395 this._reloadPageKeyboardShortcut = new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl, "R", this._reloadPage.bind(this));
396 this._reloadPageFromOriginKeyboardShortcut = new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl | WI.KeyboardShortcut.Modifier.Option, "R", this._reloadPageFromOrigin.bind(this));
397 this._reloadPageKeyboardShortcut.implicitlyPreventsDefault = this._reloadPageFromOriginKeyboardShortcut.implicitlyPreventsDefault = false;
399 this._consoleTabKeyboardShortcut = new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.Option | WI.KeyboardShortcut.Modifier.CommandOrControl, "C", this._showConsoleTab.bind(this));
400 this._quickConsoleKeyboardShortcut = new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.Control, WI.KeyboardShortcut.Key.Apostrophe, this._focusConsolePrompt.bind(this));
402 this._inspectModeKeyboardShortcut = new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl | WI.KeyboardShortcut.Modifier.Shift, "C", this._toggleInspectMode.bind(this));
404 this._undoKeyboardShortcut = new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl, "Z", this._undoKeyboardShortcut.bind(this));
405 this._redoKeyboardShortcut = new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl | WI.KeyboardShortcut.Modifier.Shift, "Z", this._redoKeyboardShortcut.bind(this));
406 this._undoKeyboardShortcut.implicitlyPreventsDefault = this._redoKeyboardShortcut.implicitlyPreventsDefault = false;
408 this.toggleBreakpointsKeyboardShortcut = new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl, "Y", this.debuggerToggleBreakpoints.bind(this));
409 this.pauseOrResumeKeyboardShortcut = new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.Control | WI.KeyboardShortcut.Modifier.CommandOrControl, "Y", this.debuggerPauseResumeToggle.bind(this));
410 this.stepOverKeyboardShortcut = new WI.KeyboardShortcut(null, WI.KeyboardShortcut.Key.F6, this.debuggerStepOver.bind(this));
411 this.stepIntoKeyboardShortcut = new WI.KeyboardShortcut(null, WI.KeyboardShortcut.Key.F7, this.debuggerStepInto.bind(this));
412 this.stepOutKeyboardShortcut = new WI.KeyboardShortcut(null, WI.KeyboardShortcut.Key.F8, this.debuggerStepOut.bind(this));
414 this.pauseOrResumeAlternateKeyboardShortcut = new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl, WI.KeyboardShortcut.Key.Backslash, this.debuggerPauseResumeToggle.bind(this));
415 this.stepOverAlternateKeyboardShortcut = new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl, WI.KeyboardShortcut.Key.SingleQuote, this.debuggerStepOver.bind(this));
416 this.stepIntoAlternateKeyboardShortcut = new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl, WI.KeyboardShortcut.Key.Semicolon, this.debuggerStepInto.bind(this));
417 this.stepOutAlternateKeyboardShortcut = new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.Shift | WI.KeyboardShortcut.Modifier.CommandOrControl, WI.KeyboardShortcut.Key.Semicolon, this.debuggerStepOut.bind(this));
419 this._closeToolbarButton = new WI.ControlToolbarItem("dock-close", WI.UIString("Close"), "Images/Close.svg", 16, 14);
420 this._closeToolbarButton.addEventListener(WI.ButtonNavigationItem.Event.Clicked, this.close, this);
422 this._undockToolbarButton = new WI.ButtonToolbarItem("undock", WI.UIString("Detach into separate window"), "Images/Undock.svg");
423 this._undockToolbarButton.element.classList.add(WI.Popover.IgnoreAutoDismissClassName);
424 this._undockToolbarButton.addEventListener(WI.ButtonNavigationItem.Event.Clicked, this._undock, this);
426 let dockImage = WI.resolvedLayoutDirection() === WI.LayoutDirection.RTL ? "Images/DockLeft.svg" : "Images/DockRight.svg";
427 this._dockToSideToolbarButton = new WI.ButtonToolbarItem("dock-right", WI.UIString("Dock to side of window"), dockImage);
428 this._dockToSideToolbarButton.element.classList.add(WI.Popover.IgnoreAutoDismissClassName);
430 let dockToSideCallback = WI.resolvedLayoutDirection() === WI.LayoutDirection.RTL ? this._dockLeft : this._dockRight;
431 this._dockToSideToolbarButton.addEventListener(WI.ButtonNavigationItem.Event.Clicked, dockToSideCallback, this);
433 this._dockBottomToolbarButton = new WI.ButtonToolbarItem("dock-bottom", WI.UIString("Dock to bottom of window"), "Images/DockBottom.svg");
434 this._dockBottomToolbarButton.element.classList.add(WI.Popover.IgnoreAutoDismissClassName);
435 this._dockBottomToolbarButton.addEventListener(WI.ButtonNavigationItem.Event.Clicked, this._dockBottom, this);
437 this._togglePreviousDockConfigurationKeyboardShortcut = new WI.KeyboardShortcut(WI.KeyboardShortcut.Modifier.CommandOrControl | WI.KeyboardShortcut.Modifier.Shift, "D", this._togglePreviousDockConfiguration.bind(this));
440 if (WI.sharedApp.debuggableType === WI.DebuggableType.JavaScript)
441 reloadToolTip = WI.UIString("Restart (%s)").format(this._reloadPageKeyboardShortcut.displayName);
443 reloadToolTip = WI.UIString("Reload page (%s)\nReload page ignoring cache (%s)").format(this._reloadPageKeyboardShortcut.displayName, this._reloadPageFromOriginKeyboardShortcut.displayName);
444 this._reloadToolbarButton = new WI.ButtonToolbarItem("reload", reloadToolTip, "Images/ReloadToolbar.svg");
445 this._reloadToolbarButton.addEventListener(WI.ButtonNavigationItem.Event.Clicked, this._reloadToolbarButtonClicked, this);
447 this._downloadToolbarButton = new WI.ButtonToolbarItem("download", WI.UIString("Download Web Archive"), "Images/DownloadArrow.svg");
448 this._downloadToolbarButton.addEventListener(WI.ButtonNavigationItem.Event.Clicked, this._downloadWebArchive, this);
450 let elementSelectionToolTip = WI.UIString("Start element selection (%s)").format(WI._inspectModeKeyboardShortcut.displayName);
451 let activatedElementSelectionToolTip = WI.UIString("Stop element selection (%s)").format(WI._inspectModeKeyboardShortcut.displayName);
452 this._inspectModeToolbarButton = new WI.ActivateButtonToolbarItem("inspect", elementSelectionToolTip, activatedElementSelectionToolTip, "Images/Crosshair.svg");
453 this._inspectModeToolbarButton.addEventListener(WI.ButtonNavigationItem.Event.Clicked, this._toggleInspectMode, this);
455 // COMPATIBILITY (iOS 12.2): Page.overrideSetting did not exist.
456 if (InspectorFrontendHost.isRemote && WI.sharedApp.debuggableType === WI.DebuggableType.Web && InspectorBackend.domains.Page && InspectorBackend.domains.Page.overrideUserAgent && InspectorBackend.domains.Page.overrideSetting) {
457 const deviceSettingsTooltip = WI.UIString("Device Settings");
458 WI._deviceSettingsToolbarButton = new WI.ActivateButtonToolbarItem("device-settings", deviceSettingsTooltip, deviceSettingsTooltip, "Images/Device.svg");
459 WI._deviceSettingsToolbarButton.addEventListener(WI.ButtonNavigationItem.Event.Clicked, this._handleDeviceSettingsToolbarButtonClicked, this);
461 WI._deviceSettingsPopover = null;
464 this._updateReloadToolbarButton();
465 this._updateDownloadToolbarButton();
466 this._updateInspectModeToolbarButton();
469 default: new WI.DefaultDashboard,
470 debugger: new WI.DebuggerDashboard,
473 this._dashboardContainer = new WI.DashboardContainerView;
474 this._dashboardContainer.showDashboardViewForRepresentedObject(this._dashboards.default);
476 this.toolbar.addToolbarItem(this._closeToolbarButton, WI.Toolbar.Section.Control);
478 this.toolbar.addToolbarItem(this._undockToolbarButton, WI.Toolbar.Section.Left);
479 this.toolbar.addToolbarItem(this._dockToSideToolbarButton, WI.Toolbar.Section.Left);
480 this.toolbar.addToolbarItem(this._dockBottomToolbarButton, WI.Toolbar.Section.Left);
482 this.toolbar.addToolbarItem(this._reloadToolbarButton, WI.Toolbar.Section.CenterLeft);
483 this.toolbar.addToolbarItem(this._downloadToolbarButton, WI.Toolbar.Section.CenterLeft);
485 this.toolbar.addToolbarItem(this._dashboardContainer.toolbarItem, WI.Toolbar.Section.Center);
487 this.toolbar.addToolbarItem(this._inspectModeToolbarButton, WI.Toolbar.Section.CenterRight);
489 if (WI._deviceSettingsToolbarButton)
490 this.toolbar.addToolbarItem(WI._deviceSettingsToolbarButton, WI.Toolbar.Section.CenterRight);
492 this._searchTabContentView = new WI.SearchTabContentView;
494 if (WI.settings.experimentalEnableNewTabBar.value) {
495 this.tabBrowser.addTabForContentView(this._searchTabContentView, {suppressAnimations: true});
496 this.tabBar.addTabBarItem(this.settingsTabContentView.tabBarItem, {suppressAnimations: true});
498 const incremental = false;
499 this._searchToolbarItem = new WI.SearchBar("inspector-search", WI.UIString("Search"), incremental);
500 this._searchToolbarItem.addEventListener(WI.SearchBar.Event.TextChanged, this._searchTextDidChange, this);
501 this.toolbar.addToolbarItem(this._searchToolbarItem, WI.Toolbar.Section.Right);
504 let dockedResizerElement = document.getElementById("docked-resizer");
505 dockedResizerElement.classList.add(WI.Popover.IgnoreAutoDismissClassName);
506 dockedResizerElement.addEventListener("mousedown", this._dockedResizerMouseDown.bind(this));
508 this._dockingAvailable = false;
510 this._updateDockNavigationItems();
511 this._setupViewHierarchy();
513 // These tabs are always available for selecting, modulo isTabAllowed().
514 // Other tabs may be engineering-only or toggled at runtime if incomplete.
515 let productionTabClasses = [
516 WI.ElementsTabContentView,
517 WI.NetworkTabContentView,
518 WI.SourcesTabContentView,
519 WI.DebuggerTabContentView,
520 WI.ResourcesTabContentView,
521 WI.TimelineTabContentView,
522 WI.StorageTabContentView,
523 WI.CanvasTabContentView,
524 WI.LayersTabContentView,
525 WI.AuditTabContentView,
526 WI.ConsoleTabContentView,
527 WI.SearchTabContentView,
528 WI.NewTabContentView,
529 WI.SettingsTabContentView,
532 this._knownTabClassesByType = new Map;
533 // Set tab classes directly. The public API triggers other updates and
534 // notifications that won't work or have no listeners at this point.
535 for (let tabClass of productionTabClasses)
536 this._knownTabClassesByType.set(tabClass.Type, tabClass);
538 this._pendingOpenTabs = [];
540 // Previously we may have stored duplicates in this setting. Avoid creating duplicate tabs.
541 let openTabTypes = this._openTabsSetting.value;
542 let seenTabTypes = new Set;
544 for (let i = 0; i < openTabTypes.length; ++i) {
545 let tabType = openTabTypes[i];
547 if (seenTabTypes.has(tabType))
549 seenTabTypes.add(tabType);
551 if (!this.isTabTypeAllowed(tabType)) {
552 this._pendingOpenTabs.push({tabType, index: i});
556 if (!this.isNewTabWithTypeAllowed(tabType))
559 let tabContentView = this._createTabContentViewForType(tabType);
562 this.tabBrowser.addTabForContentView(tabContentView, {suppressAnimations: true});
565 this._restoreCookieForOpenTabs(WI.StateRestorationType.Load);
567 this.tabBar.selectedTabBarItem = this._selectedTabIndexSetting.value;
569 if (!this.tabBar.selectedTabBarItem)
570 this.tabBar.selectedTabBarItem = 0;
572 if (!this.tabBar.normalTabCount)
573 this.showNewTabTab({suppressAnimations: true});
575 // Listen to the events after restoring the saved tabs to avoid recursion.
576 this.tabBar.addEventListener(WI.TabBar.Event.TabBarItemAdded, this._rememberOpenTabs, this);
577 this.tabBar.addEventListener(WI.TabBar.Event.TabBarItemRemoved, this._rememberOpenTabs, this);
578 this.tabBar.addEventListener(WI.TabBar.Event.TabBarItemsReordered, this._rememberOpenTabs, this);
580 // Signal that the frontend is now ready to receive messages.
581 WI.whenTargetsAvailable().then(() => {
582 InspectorFrontendAPI.loadCompleted();
585 // Tell the InspectorFrontendHost we loaded, which causes the window to display
586 // and pending InspectorFrontendAPI commands to be sent.
587 InspectorFrontendHost.loaded();
589 if (this._showingSplitConsoleSetting.value)
590 this.showSplitConsole();
592 // Store this on the window in case the WebInspector global gets corrupted.
593 window.__frontendCompletedLoad = true;
595 if (WI.runBootstrapOperations)
596 WI.runBootstrapOperations();
599 WI.performOneTimeFrontendInitializationsUsingTarget = function(target)
601 if (!WI.__didPerformConsoleInitialization && target.ConsoleAgent) {
602 WI.__didPerformConsoleInitialization = true;
603 WI.consoleManager.initializeLogChannels(target);
606 if (!WI.__didPerformCSSInitialization && target.CSSAgent) {
607 WI.__didPerformCSSInitialization = true;
608 WI.CSSCompletions.initializeCSSCompletions(target);
612 WI.initializeTarget = function(target)
614 if (target.PageAgent) {
615 // COMPATIBILITY (iOS 12.2): Page.overrideUserAgent did not exist.
616 if (target.PageAgent.overrideUserAgent && WI._overridenDeviceUserAgent)
617 target.PageAgent.overrideUserAgent(WI._overridenDeviceUserAgent);
619 // COMPATIBILITY (iOS 12.2): Page.overrideSetting did not exist.
620 if (target.PageAgent.overrideSetting) {
621 for (let [setting, value] of WI._overridenDeviceSettings)
622 target.PageAgent.overrideSetting(setting, value);
625 // COMPATIBILITY (iOS 11.3)
626 if (target.PageAgent.setShowRulers && WI.settings.showRulers.value)
627 target.PageAgent.setShowRulers(true);
629 // COMPATIBILITY (iOS 8): Page.setShowPaintRects did not exist.
630 if (target.PageAgent.setShowPaintRects && WI.settings.showPaintRects.value)
631 target.PageAgent.setShowPaintRects(true);
635 WI.targetsAvailable = function()
637 return this._targetsAvailablePromise.settled;
640 WI.whenTargetsAvailable = function()
642 return this._targetsAvailablePromise.promise;
645 WI.isTabTypeAllowed = function(tabType)
647 let tabClass = this._knownTabClassesByType.get(tabType);
651 return tabClass.isTabAllowed();
654 WI.knownTabClasses = function()
656 return new Set(this._knownTabClassesByType.values());
659 WI._showOpenResourceDialog = function()
661 if (!this._openResourceDialog)
662 this._openResourceDialog = new WI.OpenResourceDialog(this);
664 if (this._openResourceDialog.visible)
667 this._openResourceDialog.present(this._contentElement);
670 WI._createTabContentViewForType = function(tabType)
672 let tabClass = this._knownTabClassesByType.get(tabType);
674 console.error("Unknown tab type", tabType);
678 console.assert(WI.TabContentView.isPrototypeOf(tabClass));
682 WI._rememberOpenTabs = function()
684 let seenTabTypes = new Set;
687 for (let tabBarItem of this.tabBar.tabBarItems) {
688 let tabContentView = tabBarItem.representedObject;
689 if (!(tabContentView instanceof WI.TabContentView))
691 if (!tabContentView.constructor.shouldSaveTab())
693 console.assert(tabContentView.type, "Tab type can't be null, undefined, or empty string", tabContentView.type, tabContentView);
694 openTabs.push(tabContentView.type);
695 seenTabTypes.add(tabContentView.type);
698 // Keep currently unsupported tabs in the setting at their previous index.
699 for (let {tabType, index} of this._pendingOpenTabs) {
700 if (seenTabTypes.has(tabType))
702 openTabs.insertAtIndex(tabType, index);
703 seenTabTypes.add(tabType);
706 this._openTabsSetting.value = openTabs;
709 WI._openDefaultTab = function(event)
711 this.showNewTabTab({suppressAnimations: true});
714 WI._showSettingsTab = function(event)
716 if (event.keyIdentifier === "U+002C") // ","
717 this.tabBrowser.showTabForContentView(this.settingsTabContentView);
720 WI._tryToRestorePendingTabs = function()
722 let stillPendingOpenTabs = [];
723 for (let {tabType, index} of this._pendingOpenTabs) {
724 if (!this.isTabTypeAllowed(tabType)) {
725 stillPendingOpenTabs.push({tabType, index});
729 let tabContentView = this._createTabContentViewForType(tabType);
733 this.tabBrowser.addTabForContentView(tabContentView, {
734 suppressAnimations: true,
735 insertionIndex: index,
738 tabContentView.restoreStateFromCookie(WI.StateRestorationType.Load);
741 this._pendingOpenTabs = stillPendingOpenTabs;
743 if (!WI.settings.experimentalEnableNewTabBar.value)
744 this.tabBar.updateNewTabTabBarItemState();
747 WI.showNewTabTab = function(options)
749 if (!this.isNewTabWithTypeAllowed(WI.NewTabContentView.Type))
752 let tabContentView = this.tabBrowser.bestTabContentViewForClass(WI.NewTabContentView);
754 tabContentView = new WI.NewTabContentView;
755 this.tabBrowser.showTabForContentView(tabContentView, options);
758 WI.isNewTabWithTypeAllowed = function(tabType)
760 let tabClass = this._knownTabClassesByType.get(tabType);
761 if (!tabClass || !tabClass.isTabAllowed())
764 // Only allow one tab per class for now.
765 for (let tabBarItem of this.tabBar.tabBarItems) {
766 let tabContentView = tabBarItem.representedObject;
767 if (!(tabContentView instanceof WI.TabContentView))
769 if (tabContentView.constructor === tabClass)
773 if (tabClass === WI.NewTabContentView) {
774 let allTabs = Array.from(this.knownTabClasses());
775 let addableTabs = allTabs.filter((tabClass) => !tabClass.tabInfo().isEphemeral);
776 let canMakeNewTab = addableTabs.some((tabClass) => WI.isNewTabWithTypeAllowed(tabClass.Type));
777 return canMakeNewTab;
783 WI.createNewTabWithType = function(tabType, options = {})
785 console.assert(this.isNewTabWithTypeAllowed(tabType));
787 let {referencedView, shouldReplaceTab, shouldShowNewTab} = options;
788 console.assert(!referencedView || referencedView instanceof WI.TabContentView, referencedView);
789 console.assert(!shouldReplaceTab || referencedView, "Must provide a reference view to replace a tab.");
791 let tabContentView = this._createTabContentViewForType(tabType);
792 const suppressAnimations = true;
793 this.tabBrowser.addTabForContentView(tabContentView, {
795 insertionIndex: referencedView ? this.tabBar.tabBarItems.indexOf(referencedView.tabBarItem) : undefined,
798 if (shouldReplaceTab)
799 this.tabBrowser.closeTabForContentView(referencedView, {suppressAnimations});
801 if (shouldShowNewTab)
802 this.tabBrowser.showTabForContentView(tabContentView);
805 WI.activateExtraDomains = function(domains)
807 this.notifications.dispatchEventToListeners(WI.Notification.ExtraDomainsActivated, {domains});
810 if (!WI.pageTarget && WI.mainTarget.DOMAgent)
811 WI.pageTarget = WI.mainTarget;
813 if (WI.mainTarget.CSSAgent)
814 WI.CSSCompletions.initializeCSSCompletions(WI.assumingMainTarget());
816 if (WI.mainTarget.DOMAgent)
817 WI.domManager.ensureDocument();
819 if (WI.mainTarget.PageAgent)
820 WI.networkManager.initializeTarget(WI.mainTarget);
823 this._updateReloadToolbarButton();
824 this._updateDownloadToolbarButton();
825 this._updateInspectModeToolbarButton();
827 this._tryToRestorePendingTabs();
830 WI.updateWindowTitle = function()
832 var mainFrame = this.networkManager.mainFrame;
836 var urlComponents = mainFrame.mainResource.urlComponents;
838 var lastPathComponent;
840 lastPathComponent = decodeURIComponent(urlComponents.lastPathComponent || "");
842 lastPathComponent = urlComponents.lastPathComponent;
845 // Build a title based on the URL components.
846 if (urlComponents.host && lastPathComponent)
847 var title = this.displayNameForHost(urlComponents.host) + " \u2014 " + lastPathComponent;
848 else if (urlComponents.host)
849 var title = this.displayNameForHost(urlComponents.host);
850 else if (lastPathComponent)
851 var title = lastPathComponent;
853 var title = mainFrame.url;
855 // The name "inspectedURLChanged" sounds like the whole URL is required, however this is only
856 // used for updating the window title and it can be any string.
857 InspectorFrontendHost.inspectedURLChanged(title);
860 WI.updateDockingAvailability = function(available)
862 this._dockingAvailable = available;
864 this._updateDockNavigationItems();
867 WI.updateDockedState = function(side)
869 if (this._dockConfiguration === side)
872 this._previousDockConfiguration = this._dockConfiguration;
874 if (!this._previousDockConfiguration) {
875 if (side === WI.DockConfiguration.Right || side === WI.DockConfiguration.Left)
876 this._previousDockConfiguration = WI.DockConfiguration.Bottom;
878 this._previousDockConfiguration = WI.resolvedLayoutDirection() === WI.LayoutDirection.RTL ? WI.DockConfiguration.Left : WI.DockConfiguration.Right;
881 this._dockConfiguration = side;
883 this.docked = side !== WI.DockConfiguration.Undocked;
885 this._ignoreToolbarModeDidChangeEvents = true;
887 if (side === WI.DockConfiguration.Bottom) {
888 document.body.classList.add("docked", WI.DockConfiguration.Bottom);
889 document.body.classList.remove("window-inactive", WI.DockConfiguration.Right, WI.DockConfiguration.Left);
890 } else if (side === WI.DockConfiguration.Right) {
891 document.body.classList.add("docked", WI.DockConfiguration.Right);
892 document.body.classList.remove("window-inactive", WI.DockConfiguration.Bottom, WI.DockConfiguration.Left);
893 } else if (side === WI.DockConfiguration.Left) {
894 document.body.classList.add("docked", WI.DockConfiguration.Left);
895 document.body.classList.remove("window-inactive", WI.DockConfiguration.Bottom, WI.DockConfiguration.Right);
897 document.body.classList.remove("docked", WI.DockConfiguration.Right, WI.DockConfiguration.Left, WI.DockConfiguration.Bottom);
899 this._ignoreToolbarModeDidChangeEvents = false;
901 this._updateDockNavigationItems();
903 if (!this.dockedConfigurationSupportsSplitContentBrowser() && !this.doesCurrentTabSupportSplitContentBrowser())
904 this.hideSplitConsole();
907 WI.updateVisibilityState = function(visible)
909 this.visible = visible;
910 this.notifications.dispatchEventToListeners(WI.Notification.VisibilityStateDidChange);
913 WI.handlePossibleLinkClick = function(event, frame, options = {})
915 let anchorElement = event.target.closest("a");
916 if (!anchorElement || !anchorElement.href)
919 if (WI.isBeingEdited(anchorElement)) {
920 // Don't follow the link when it is being edited.
924 // Prevent the link from navigating, since we don't do any navigation by following links normally.
925 event.preventDefault();
926 event.stopPropagation();
928 this.openURL(anchorElement.href, frame, {
930 lineNumber: anchorElement.lineNumber,
931 ignoreSearchTab: !WI.isShowingSearchTab(),
937 WI.openURL = function(url, frame, options = {})
943 console.assert(typeof options.lineNumber === "undefined" || typeof options.lineNumber === "number", "lineNumber should be a number.");
945 // If alwaysOpenExternally is not defined, base it off the command/meta key for the current event.
946 if (options.alwaysOpenExternally === undefined || options.alwaysOpenExternally === null)
947 options.alwaysOpenExternally = window.event ? window.event.metaKey : false;
949 if (options.alwaysOpenExternally) {
950 InspectorFrontendHost.openInNewTab(url);
954 let searchChildFrames = false;
956 frame = this.networkManager.mainFrame;
957 searchChildFrames = true;
961 let simplifiedURL = removeURLFragment(url);
963 // WI.Frame.resourceForURL does not check the main resource, only sub-resources. So check both.
964 resource = frame.url === simplifiedURL ? frame.mainResource : frame.resourceForURL(simplifiedURL, searchChildFrames);
965 } else if (WI.sharedApp.debuggableType === WI.DebuggableType.ServiceWorker)
966 resource = WI.mainTarget.resourceCollection.resourceForURL(removeURLFragment(url));
969 let positionToReveal = new WI.SourceCodePosition(options.lineNumber, 0);
970 this.showSourceCode(resource, {...options, positionToReveal});
974 InspectorFrontendHost.openInNewTab(url);
977 WI.close = function()
982 this._isClosing = true;
984 InspectorFrontendHost.closeWindow();
987 WI.isConsoleFocused = function()
989 return this.quickConsole.prompt.focused;
992 WI.isShowingSplitConsole = function()
994 return !this.consoleDrawer.collapsed;
997 WI.dockedConfigurationSupportsSplitContentBrowser = function()
999 return this._dockConfiguration !== WI.DockConfiguration.Bottom;
1002 WI.doesCurrentTabSupportSplitContentBrowser = function()
1004 var currentContentView = this.tabBrowser.selectedTabContentView;
1005 return !currentContentView || currentContentView.supportsSplitContentBrowser;
1008 WI.toggleSplitConsole = function()
1010 if (!this.doesCurrentTabSupportSplitContentBrowser()) {
1011 this.showConsoleTab();
1015 if (this.isShowingSplitConsole())
1016 this.hideSplitConsole();
1018 this.showSplitConsole();
1021 WI.showSplitConsole = function()
1023 if (!this.doesCurrentTabSupportSplitContentBrowser()) {
1024 this.showConsoleTab();
1028 this.consoleDrawer.collapsed = false;
1030 if (this.consoleDrawer.currentContentView === this.consoleContentView)
1033 this.consoleDrawer.showContentView(this.consoleContentView);
1036 WI.hideSplitConsole = function()
1038 if (!this.isShowingSplitConsole())
1041 this.consoleDrawer.collapsed = true;
1044 WI.showConsoleTab = function(requestedScope)
1046 requestedScope = requestedScope || WI.LogContentView.Scopes.All;
1048 this.hideSplitConsole();
1050 this.consoleContentView.scopeBar.item(requestedScope).selected = true;
1052 this.showRepresentedObject(this._consoleRepresentedObject);
1054 console.assert(this.isShowingConsoleTab());
1057 WI.isShowingConsoleTab = function()
1059 return this.tabBrowser.selectedTabContentView instanceof WI.ConsoleTabContentView;
1062 WI.showElementsTab = function()
1064 var tabContentView = this.tabBrowser.bestTabContentViewForClass(WI.ElementsTabContentView);
1065 if (!tabContentView)
1066 tabContentView = new WI.ElementsTabContentView;
1067 this.tabBrowser.showTabForContentView(tabContentView);
1070 WI.isShowingElementsTab = function()
1072 return this.tabBrowser.selectedTabContentView instanceof WI.ElementsTabContentView;
1075 WI.showSourcesTab = function(options = {})
1077 let tabContentView = this.tabBrowser.bestTabContentViewForClass(WI.SourcesTabContentView);
1078 if (!tabContentView)
1079 tabContentView = new WI.SourcesTabContentView;
1081 if (options.breakpointToSelect instanceof WI.Breakpoint)
1082 tabContentView.revealAndSelectBreakpoint(options.breakpointToSelect);
1084 if (options.showScopeChainSidebar)
1085 tabContentView.showScopeChainDetailsSidebarPanel();
1087 this.tabBrowser.showTabForContentView(tabContentView);
1090 WI.isShowingSourcesTab = function()
1092 return this.tabBrowser.selectedTabContentView instanceof WI.SourcesTabContentView;
1095 WI.showDebuggerTab = function(options)
1097 var tabContentView = this.tabBrowser.bestTabContentViewForClass(WI.DebuggerTabContentView);
1098 if (!tabContentView)
1099 tabContentView = new WI.DebuggerTabContentView;
1101 if (options.breakpointToSelect instanceof WI.Breakpoint)
1102 tabContentView.revealAndSelectBreakpoint(options.breakpointToSelect);
1104 if (options.showScopeChainSidebar)
1105 tabContentView.showScopeChainDetailsSidebarPanel();
1107 this.tabBrowser.showTabForContentView(tabContentView);
1110 WI.isShowingDebuggerTab = function()
1112 return this.tabBrowser.selectedTabContentView instanceof WI.DebuggerTabContentView;
1115 WI.showResourcesTab = function()
1117 var tabContentView = this.tabBrowser.bestTabContentViewForClass(WI.ResourcesTabContentView);
1118 if (!tabContentView)
1119 tabContentView = new WI.ResourcesTabContentView;
1120 this.tabBrowser.showTabForContentView(tabContentView);
1123 WI.isShowingResourcesTab = function()
1125 return this.tabBrowser.selectedTabContentView instanceof WI.ResourcesTabContentView;
1128 WI.showStorageTab = function()
1130 var tabContentView = this.tabBrowser.bestTabContentViewForClass(WI.StorageTabContentView);
1131 if (!tabContentView)
1132 tabContentView = new WI.StorageTabContentView;
1133 this.tabBrowser.showTabForContentView(tabContentView);
1136 WI.showNetworkTab = function()
1138 let tabContentView = this.tabBrowser.bestTabContentViewForClass(WI.NetworkTabContentView);
1139 if (!tabContentView)
1140 tabContentView = new WI.NetworkTabContentView;
1142 this.tabBrowser.showTabForContentView(tabContentView);
1145 WI.isShowingNetworkTab = function()
1147 return this.tabBrowser.selectedTabContentView instanceof WI.NetworkTabContentView;
1150 WI.isShowingSearchTab = function()
1152 return this.tabBrowser.selectedTabContentView instanceof WI.SearchTabContentView;
1155 WI.showTimelineTab = function()
1157 var tabContentView = this.tabBrowser.bestTabContentViewForClass(WI.TimelineTabContentView);
1158 if (!tabContentView)
1159 tabContentView = new WI.TimelineTabContentView;
1160 this.tabBrowser.showTabForContentView(tabContentView);
1163 WI.showLayersTab = function(options = {})
1165 let tabContentView = this.tabBrowser.bestTabContentViewForClass(WI.LayersTabContentView);
1166 if (!tabContentView)
1167 tabContentView = new WI.LayersTabContentView;
1168 if (options.nodeToSelect)
1169 tabContentView.selectLayerForNode(options.nodeToSelect);
1170 this.tabBrowser.showTabForContentView(tabContentView);
1173 WI.isShowingLayersTab = function()
1175 return this.tabBrowser.selectedTabContentView instanceof WI.LayersTabContentView;
1178 WI.indentString = function()
1180 if (WI.settings.indentWithTabs.value)
1182 return " ".repeat(WI.settings.indentUnit.value);
1185 WI.restoreFocusFromElement = function(element)
1187 if (element && element.contains(this.currentFocusElement))
1188 this.previousFocusElement.focus();
1191 WI.toggleNavigationSidebar = function(event)
1193 if (!this.navigationSidebar.collapsed || !this.navigationSidebar.sidebarPanels.length) {
1194 this.navigationSidebar.collapsed = true;
1198 if (!this.navigationSidebar.selectedSidebarPanel)
1199 this.navigationSidebar.selectedSidebarPanel = this.navigationSidebar.sidebarPanels[0];
1200 this.navigationSidebar.collapsed = false;
1203 WI.toggleDetailsSidebar = function(event)
1205 if (!this.detailsSidebar.collapsed || !this.detailsSidebar.sidebarPanels.length) {
1206 this.detailsSidebar.collapsed = true;
1210 if (!this.detailsSidebar.selectedSidebarPanel)
1211 this.detailsSidebar.selectedSidebarPanel = this.detailsSidebar.sidebarPanels[0];
1212 this.detailsSidebar.collapsed = false;
1215 WI.getMaximumSidebarWidth = function(sidebar)
1217 console.assert(sidebar instanceof WI.Sidebar);
1219 const minimumContentBrowserWidth = 100;
1221 let minimumWidth = window.innerWidth - minimumContentBrowserWidth;
1222 let tabContentView = this.tabBrowser.selectedTabContentView;
1223 console.assert(tabContentView);
1224 if (!tabContentView)
1225 return minimumWidth;
1227 let otherSidebar = null;
1228 if (sidebar === this.navigationSidebar)
1229 otherSidebar = tabContentView.detailsSidebarPanels.length ? this.detailsSidebar : null;
1231 otherSidebar = tabContentView.navigationSidebarPanel ? this.navigationSidebar : null;
1234 minimumWidth -= otherSidebar.width;
1236 return minimumWidth;
1239 WI.tabContentViewClassForRepresentedObject = function(representedObject)
1241 if (representedObject instanceof WI.DOMTree)
1242 return WI.ElementsTabContentView;
1244 if (representedObject instanceof WI.TimelineRecording)
1245 return WI.TimelineTabContentView;
1247 // We only support one console tab right now. So this isn't an instanceof check.
1248 if (representedObject === this._consoleRepresentedObject)
1249 return WI.ConsoleTabContentView;
1251 if (WI.settings.experimentalEnableSourcesTab.value) {
1252 if (representedObject instanceof WI.Frame
1253 || representedObject instanceof WI.FrameCollection
1254 || representedObject instanceof WI.Resource
1255 || representedObject instanceof WI.ResourceCollection
1256 || representedObject instanceof WI.Script
1257 || representedObject instanceof WI.ScriptCollection
1258 || representedObject instanceof WI.CSSStyleSheet
1259 || representedObject instanceof WI.CSSStyleSheetCollection)
1260 return WI.SourcesTabContentView;
1262 if (WI.debuggerManager.paused) {
1263 if (representedObject instanceof WI.Script)
1264 return WI.DebuggerTabContentView;
1266 if (representedObject instanceof WI.Resource && (representedObject.type === WI.Resource.Type.Document || representedObject.type === WI.Resource.Type.Script))
1267 return WI.DebuggerTabContentView;
1270 if (representedObject instanceof WI.Frame
1271 || representedObject instanceof WI.FrameCollection
1272 || representedObject instanceof WI.Resource
1273 || representedObject instanceof WI.ResourceCollection
1274 || representedObject instanceof WI.Script
1275 || representedObject instanceof WI.ScriptCollection
1276 || representedObject instanceof WI.CSSStyleSheet
1277 || representedObject instanceof WI.CSSStyleSheetCollection)
1278 return WI.ResourcesTabContentView;
1281 if (representedObject instanceof WI.DOMStorageObject || representedObject instanceof WI.CookieStorageObject ||
1282 representedObject instanceof WI.DatabaseTableObject || representedObject instanceof WI.DatabaseObject ||
1283 representedObject instanceof WI.ApplicationCacheFrame || representedObject instanceof WI.IndexedDatabaseObjectStore ||
1284 representedObject instanceof WI.IndexedDatabase || representedObject instanceof WI.IndexedDatabaseObjectStoreIndex)
1285 return WI.StorageTabContentView;
1287 if (representedObject instanceof WI.AuditTestCase || representedObject instanceof WI.AuditTestGroup
1288 || representedObject instanceof WI.AuditTestCaseResult || representedObject instanceof WI.AuditTestGroupResult)
1289 return WI.AuditTabContentView;
1291 if (representedObject instanceof WI.CanvasCollection)
1292 return WI.CanvasTabContentView;
1294 if (representedObject instanceof WI.Recording)
1295 return WI.CanvasTabContentView;
1300 WI.tabContentViewForRepresentedObject = function(representedObject, options = {})
1302 let tabContentView = this.tabBrowser.bestTabContentViewForRepresentedObject(representedObject, options);
1304 return tabContentView;
1306 var tabContentViewClass = this.tabContentViewClassForRepresentedObject(representedObject);
1307 if (!tabContentViewClass) {
1308 console.error("Unknown representedObject, couldn't create TabContentView.", representedObject);
1312 tabContentView = new tabContentViewClass;
1314 this.tabBrowser.addTabForContentView(tabContentView);
1316 return tabContentView;
1319 WI.showRepresentedObject = function(representedObject, cookie, options = {})
1321 let tabContentView = this.tabContentViewForRepresentedObject(representedObject, options);
1322 console.assert(tabContentView);
1323 if (!tabContentView)
1326 this.tabBrowser.showTabForContentView(tabContentView, options);
1327 tabContentView.showRepresentedObject(representedObject, cookie);
1330 WI.showMainFrameDOMTree = function(nodeToSelect, options = {})
1332 console.assert(WI.networkManager.mainFrame);
1333 if (!WI.networkManager.mainFrame)
1335 this.showRepresentedObject(WI.networkManager.mainFrame.domTree, {nodeToSelect}, options);
1338 WI.showSourceCodeForFrame = function(frameIdentifier, options = {})
1340 var frame = WI.networkManager.frameForIdentifier(frameIdentifier);
1342 this._frameIdentifierToShowSourceCodeWhenAvailable = frameIdentifier;
1346 this._frameIdentifierToShowSourceCodeWhenAvailable = undefined;
1348 this.showRepresentedObject(frame, null, options);
1351 WI.showSourceCode = function(sourceCode, options = {})
1353 const positionToReveal = options.positionToReveal;
1355 console.assert(!positionToReveal || positionToReveal instanceof WI.SourceCodePosition, positionToReveal);
1356 var representedObject = sourceCode;
1358 if (representedObject instanceof WI.Script) {
1359 // A script represented by a resource should always show the resource.
1360 representedObject = representedObject.resource || representedObject;
1363 var cookie = positionToReveal ? {lineNumber: positionToReveal.lineNumber, columnNumber: positionToReveal.columnNumber} : {};
1364 this.showRepresentedObject(representedObject, cookie, options);
1367 WI.showSourceCodeLocation = function(sourceCodeLocation, options = {})
1369 this.showSourceCode(sourceCodeLocation.displaySourceCode, {
1371 positionToReveal: sourceCodeLocation.displayPosition(),
1375 WI.showOriginalUnformattedSourceCodeLocation = function(sourceCodeLocation, options = {})
1377 this.showSourceCode(sourceCodeLocation.sourceCode, {
1379 positionToReveal: sourceCodeLocation.position(),
1380 forceUnformatted: true,
1384 WI.showOriginalOrFormattedSourceCodeLocation = function(sourceCodeLocation, options = {})
1386 this.showSourceCode(sourceCodeLocation.sourceCode, {
1388 positionToReveal: sourceCodeLocation.formattedPosition(),
1392 WI.showOriginalOrFormattedSourceCodeTextRange = function(sourceCodeTextRange, options = {})
1394 var textRangeToSelect = sourceCodeTextRange.formattedTextRange;
1395 this.showSourceCode(sourceCodeTextRange.sourceCode, {
1397 positionToReveal: textRangeToSelect.startPosition(),
1402 WI.showResourceRequest = function(resource, options = {})
1404 this.showRepresentedObject(resource, {[WI.ResourceClusterContentView.ContentViewIdentifierCookieKey]: WI.ResourceClusterContentView.RequestIdentifier}, options);
1407 WI.debuggerToggleBreakpoints = function(event)
1409 WI.debuggerManager.breakpointsEnabled = !WI.debuggerManager.breakpointsEnabled;
1412 WI.debuggerPauseResumeToggle = function(event)
1414 if (WI.debuggerManager.paused)
1415 WI.debuggerManager.resume();
1417 WI.debuggerManager.pause();
1420 WI.debuggerStepOver = function(event)
1422 WI.debuggerManager.stepOver();
1425 WI.debuggerStepInto = function(event)
1427 WI.debuggerManager.stepInto();
1430 WI.debuggerStepOut = function(event)
1432 WI.debuggerManager.stepOut();
1435 WI._searchTextDidChange = function(event)
1437 var tabContentView = this.tabBrowser.bestTabContentViewForClass(WI.SearchTabContentView);
1438 if (!tabContentView)
1439 tabContentView = new WI.SearchTabContentView;
1441 var searchQuery = this._searchToolbarItem.text;
1442 this._searchToolbarItem.text = "";
1444 this.tabBrowser.showTabForContentView(tabContentView);
1446 tabContentView.performSearch(searchQuery);
1449 WI._focusSearchField = function(event)
1451 if (WI.settings.experimentalEnableNewTabBar.value)
1452 this.tabBrowser.showTabForContentView(this._searchTabContentView);
1454 if (this.tabBrowser.selectedTabContentView instanceof WI.SearchTabContentView) {
1455 this.tabBrowser.selectedTabContentView.focusSearchField();
1459 if (this._searchToolbarItem)
1460 this._searchToolbarItem.focus();
1463 WI._focusChanged = function(event)
1465 // Make a caret selection inside the focused element if there isn't a range selection and there isn't already
1466 // a caret selection inside. This is needed (at least) to remove caret from console when focus is moved.
1467 // The selection change should not apply to text fields and text areas either.
1469 if (WI.isEventTargetAnEditableField(event)) {
1470 // Still update the currentFocusElement if inside of a CodeMirror editor or an input element.
1471 let newFocusElement = null;
1472 if (event.target instanceof HTMLInputElement || event.target instanceof HTMLTextAreaElement)
1473 newFocusElement = event.target;
1475 let codeMirror = WI.enclosingCodeMirror(event.target);
1477 let codeMirrorElement = codeMirror.getWrapperElement();
1478 if (codeMirrorElement && codeMirrorElement !== this.currentFocusElement)
1479 newFocusElement = codeMirrorElement;
1483 if (newFocusElement) {
1484 this.previousFocusElement = this.currentFocusElement;
1485 this.currentFocusElement = newFocusElement;
1488 // Due to the change in WI.isEventTargetAnEditableField (r196271), this return
1489 // will also get run when WI.startEditing is called on an element. We do not want
1490 // to return early in this case, as WI.EditingConfig handles its own editing
1491 // completion, so only return early if the focus change target is not from WI.startEditing.
1492 if (!WI.isBeingEdited(event.target))
1496 var selection = window.getSelection();
1497 if (!selection.isCollapsed)
1500 var element = event.target;
1502 if (element !== this.currentFocusElement) {
1503 this.previousFocusElement = this.currentFocusElement;
1504 this.currentFocusElement = element;
1507 if (element.isInsertionCaretInside())
1510 var selectionRange = element.ownerDocument.createRange();
1511 selectionRange.setStart(element, 0);
1512 selectionRange.setEnd(element, 0);
1514 selection.removeAllRanges();
1515 selection.addRange(selectionRange);
1518 WI._mouseWasClicked = function(event)
1520 this.handlePossibleLinkClick(event);
1523 WI._dragOver = function(event)
1525 // Do nothing if another event listener handled the event already.
1526 if (event.defaultPrevented)
1529 // Allow dropping into editable areas.
1530 if (WI.isEventTargetAnEditableField(event))
1533 // Prevent the drop from being accepted.
1534 event.dataTransfer.dropEffect = "none";
1535 event.preventDefault();
1538 WI._debuggerDidPause = function(event)
1540 if (WI.settings.experimentalEnableSourcesTab.value)
1541 WI.showSourcesTab({showScopeChainSidebar: WI.settings.showScopeChainOnPause.value});
1543 WI.showDebuggerTab({showScopeChainSidebar: WI.settings.showScopeChainOnPause.value});
1545 this._dashboardContainer.showDashboardViewForRepresentedObject(this._dashboards.debugger);
1547 InspectorFrontendHost.bringToFront();
1550 WI._debuggerDidResume = function(event)
1552 this._dashboardContainer.closeDashboardViewForRepresentedObject(this._dashboards.debugger);
1555 WI._frameWasAdded = function(event)
1557 if (!this._frameIdentifierToShowSourceCodeWhenAvailable)
1560 var frame = event.data.frame;
1561 if (frame.id !== this._frameIdentifierToShowSourceCodeWhenAvailable)
1564 function delayedWork()
1567 ignoreNetworkTab: true,
1568 ignoreSearchTab: true,
1570 this.showSourceCodeForFrame(frame.id, options);
1573 // Delay showing the frame since FrameWasAdded is called before MainFrameChanged.
1574 // Calling showSourceCodeForFrame before MainFrameChanged will show the frame then close it.
1575 setTimeout(delayedWork.bind(this));
1578 WI._mainFrameDidChange = function(event)
1580 this._updateDownloadToolbarButton();
1582 this.updateWindowTitle();
1585 WI._mainResourceDidChange = function(event)
1587 if (!event.target.isMainFrame())
1590 // Run cookie restoration after we are sure all of the Tabs and NavigationSidebarPanels
1591 // have updated with respect to the main resource change.
1592 setTimeout(this._restoreCookieForOpenTabs.bind(this, WI.StateRestorationType.Navigation));
1594 this._updateDownloadToolbarButton();
1596 this.updateWindowTitle();
1599 WI._provisionalLoadStarted = function(event)
1601 if (!event.target.isMainFrame())
1604 this._saveCookieForOpenTabs();
1607 WI._restoreCookieForOpenTabs = function(restorationType)
1609 for (var tabBarItem of this.tabBar.tabBarItems) {
1610 var tabContentView = tabBarItem.representedObject;
1611 if (!(tabContentView instanceof WI.TabContentView))
1613 tabContentView.restoreStateFromCookie(restorationType);
1617 WI._saveCookieForOpenTabs = function()
1619 for (var tabBarItem of this.tabBar.tabBarItems) {
1620 var tabContentView = tabBarItem.representedObject;
1621 if (!(tabContentView instanceof WI.TabContentView))
1623 tabContentView.saveStateToCookie();
1627 WI._windowFocused = function(event)
1629 if (event.target.document.nodeType !== Node.DOCUMENT_NODE)
1632 // FIXME: We should use the :window-inactive pseudo class once https://webkit.org/b/38927 is fixed.
1633 document.body.classList.remove(this.docked ? "window-docked-inactive" : "window-inactive");
1636 WI._windowBlurred = function(event)
1638 if (event.target.document.nodeType !== Node.DOCUMENT_NODE)
1641 // FIXME: We should use the :window-inactive pseudo class once https://webkit.org/b/38927 is fixed.
1642 document.body.classList.add(this.docked ? "window-docked-inactive" : "window-inactive");
1645 WI._windowResized = function(event)
1647 this.toolbar.updateLayout(WI.View.LayoutReason.Resize);
1648 this.tabBar.updateLayout(WI.View.LayoutReason.Resize);
1649 this._tabBrowserSizeDidChange();
1652 WI._updateModifierKeys = function(event)
1654 let metaKeyDidChange = this.modifierKeys.metaKey !== event.metaKey;
1655 let didChange = this.modifierKeys.altKey !== event.altKey || metaKeyDidChange || this.modifierKeys.shiftKey !== event.shiftKey;
1657 this.modifierKeys = {altKey: event.altKey, metaKey: event.metaKey, shiftKey: event.shiftKey};
1659 if (metaKeyDidChange)
1660 document.body.classList.toggle("meta-key-pressed", this.modifierKeys.metaKey);
1663 this.notifications.dispatchEventToListeners(WI.Notification.GlobalModifierKeysDidChange, event);
1666 WI._windowKeyDown = function(event)
1668 this._updateModifierKeys(event);
1671 WI._windowKeyUp = function(event)
1673 this._updateModifierKeys(event);
1676 WI._mouseDown = function(event)
1678 if (this.toolbar.element.contains(event.target))
1679 this._toolbarMouseDown(event);
1682 WI._mouseMoved = function(event)
1684 this._updateModifierKeys(event);
1685 this.mouseCoords = {
1691 WI._pageHidden = function(event)
1693 this._saveCookieForOpenTabs();
1696 WI._contextMenuRequested = function(event)
1698 let proposedContextMenu;
1700 // This is setting is only defined in engineering builds.
1701 if (WI.isDebugUIEnabled()) {
1702 proposedContextMenu = WI.ContextMenu.createFromEvent(event);
1703 proposedContextMenu.appendSeparator();
1704 proposedContextMenu.appendItem(WI.unlocalizedString("Reload Web Inspector"), () => {
1705 InspectorFrontendHost.reopen();
1708 let protocolSubMenu = proposedContextMenu.appendSubMenuItem(WI.unlocalizedString("Protocol Debugging"), null, false);
1709 let isCapturingTraffic = InspectorBackend.activeTracer instanceof WI.CapturingProtocolTracer;
1711 protocolSubMenu.appendCheckboxItem(WI.unlocalizedString("Capture Trace"), () => {
1712 if (isCapturingTraffic)
1713 InspectorBackend.activeTracer = null;
1715 InspectorBackend.activeTracer = new WI.CapturingProtocolTracer;
1716 }, isCapturingTraffic);
1718 protocolSubMenu.appendSeparator();
1720 protocolSubMenu.appendItem(WI.unlocalizedString("Export Trace\u2026"), () => {
1721 const forceSaveAs = true;
1722 WI.FileUtilities.save(InspectorBackend.activeTracer.trace.saveData, forceSaveAs);
1723 }, !isCapturingTraffic);
1725 const onlyExisting = true;
1726 proposedContextMenu = WI.ContextMenu.createFromEvent(event, onlyExisting);
1729 if (proposedContextMenu)
1730 proposedContextMenu.show();
1733 WI.isDebugUIEnabled = function()
1735 return WI.showDebugUISetting && WI.showDebugUISetting.value;
1738 WI._undock = function(event)
1740 InspectorFrontendHost.requestSetDockSide(WI.DockConfiguration.Undocked);
1743 WI._dockBottom = function(event)
1745 InspectorFrontendHost.requestSetDockSide(WI.DockConfiguration.Bottom);
1748 WI._dockRight = function(event)
1750 InspectorFrontendHost.requestSetDockSide(WI.DockConfiguration.Right);
1753 WI._dockLeft = function(event)
1755 InspectorFrontendHost.requestSetDockSide(WI.DockConfiguration.Left);
1758 WI._togglePreviousDockConfiguration = function(event)
1760 InspectorFrontendHost.requestSetDockSide(this._previousDockConfiguration);
1763 WI._updateDockNavigationItems = function()
1765 if (this._dockingAvailable || this.docked) {
1766 this._closeToolbarButton.hidden = !this.docked;
1767 this._undockToolbarButton.hidden = this._dockConfiguration === WI.DockConfiguration.Undocked;
1768 this._dockBottomToolbarButton.hidden = this._dockConfiguration === WI.DockConfiguration.Bottom;
1769 this._dockToSideToolbarButton.hidden = this._dockConfiguration === WI.DockConfiguration.Right || this._dockConfiguration === WI.DockConfiguration.Left;
1771 this._closeToolbarButton.hidden = true;
1772 this._undockToolbarButton.hidden = true;
1773 this._dockBottomToolbarButton.hidden = true;
1774 this._dockToSideToolbarButton.hidden = true;
1778 WI._tabBrowserSizeDidChange = function()
1780 this.tabBrowser.updateLayout(WI.View.LayoutReason.Resize);
1781 this.consoleDrawer.updateLayout(WI.View.LayoutReason.Resize);
1782 this.quickConsole.updateLayout(WI.View.LayoutReason.Resize);
1785 WI._consoleDrawerCollapsedStateDidChange = function(event)
1787 this._showingSplitConsoleSetting.value = WI.isShowingSplitConsole();
1789 WI._consoleDrawerDidResize();
1792 WI._consoleDrawerDidResize = function(event)
1794 this.tabBrowser.updateLayout(WI.View.LayoutReason.Resize);
1797 WI._sidebarWidthDidChange = function(event)
1799 this._tabBrowserSizeDidChange();
1802 WI._setupViewHierarchy = function()
1804 let rootView = WI.View.rootView();
1805 rootView.addSubview(this.toolbar);
1806 rootView.addSubview(this.tabBar);
1807 rootView.addSubview(this.navigationSidebar);
1808 rootView.addSubview(this.tabBrowser);
1809 rootView.addSubview(this.consoleDrawer);
1810 rootView.addSubview(this.quickConsole);
1811 rootView.addSubview(this.detailsSidebar);
1814 WI._tabBrowserSelectedTabContentViewDidChange = function(event)
1816 if (this.tabBar.selectedTabBarItem && this.tabBar.selectedTabBarItem.representedObject.constructor.shouldSaveTab())
1817 this._selectedTabIndexSetting.value = this.tabBar.tabBarItems.indexOf(this.tabBar.selectedTabBarItem);
1819 if (this.doesCurrentTabSupportSplitContentBrowser()) {
1820 if (this._shouldRevealSpitConsoleIfSupported) {
1821 this._shouldRevealSpitConsoleIfSupported = false;
1822 this.showSplitConsole();
1827 this._shouldRevealSpitConsoleIfSupported = this.isShowingSplitConsole();
1828 this.hideSplitConsole();
1831 WI._toolbarMouseDown = function(event)
1836 if (this._dockConfiguration === WI.DockConfiguration.Right || this._dockConfiguration === WI.DockConfiguration.Left)
1840 this._dockedResizerMouseDown(event);
1842 this._moveWindowMouseDown(event);
1845 WI._dockedResizerMouseDown = function(event)
1847 if (event.button !== 0 || event.ctrlKey)
1853 // Only start dragging if the target is one of the elements that we expect.
1854 if (event.target.id !== "docked-resizer" && !event.target.classList.contains("toolbar") &&
1855 !event.target.classList.contains("flexible-space") && !event.target.classList.contains("item-section"))
1858 event[WI.Popover.EventPreventDismissSymbol] = true;
1860 let windowProperty = this._dockConfiguration === WI.DockConfiguration.Bottom ? "innerHeight" : "innerWidth";
1861 let eventScreenProperty = this._dockConfiguration === WI.DockConfiguration.Bottom ? "screenY" : "screenX";
1862 let eventClientProperty = this._dockConfiguration === WI.DockConfiguration.Bottom ? "clientY" : "clientX";
1864 var resizerElement = event.target;
1865 var firstClientPosition = event[eventClientProperty];
1866 var lastScreenPosition = event[eventScreenProperty];
1868 function dockedResizerDrag(event)
1870 if (event.button !== 0)
1873 var position = event[eventScreenProperty];
1874 var delta = position - lastScreenPosition;
1875 var clientPosition = event[eventClientProperty];
1877 lastScreenPosition = position;
1879 if (this._dockConfiguration === WI.DockConfiguration.Left) {
1880 // If the mouse is travelling rightward but is positioned left of the resizer, ignore the event.
1881 if (delta > 0 && clientPosition < firstClientPosition)
1884 // If the mouse is travelling leftward but is positioned to the right of the resizer, ignore the event.
1885 if (delta < 0 && clientPosition > window[windowProperty])
1888 // We later subtract the delta from the current position, but since the inspected view and inspector view
1889 // are flipped when docked to left, we want dragging to have the opposite effect from docked to right.
1892 // If the mouse is travelling downward/rightward but is positioned above/left of the resizer, ignore the event.
1893 if (delta > 0 && clientPosition < firstClientPosition)
1896 // If the mouse is travelling upward/leftward but is positioned below/right of the resizer, ignore the event.
1897 if (delta < 0 && clientPosition > firstClientPosition)
1901 let dimension = Math.max(0, window[windowProperty] - delta);
1902 // If zoomed in/out, there be greater/fewer document pixels shown, but the inspector's
1903 // width or height should be the same in device pixels regardless of the document zoom.
1904 dimension *= this.getZoomFactor();
1906 if (this._dockConfiguration === WI.DockConfiguration.Bottom)
1907 InspectorFrontendHost.setAttachedWindowHeight(dimension);
1909 InspectorFrontendHost.setAttachedWindowWidth(dimension);
1912 function dockedResizerDragEnd(event)
1914 if (event.button !== 0)
1917 WI.elementDragEnd(event);
1920 WI.elementDragStart(resizerElement, dockedResizerDrag.bind(this), dockedResizerDragEnd.bind(this), event, this._dockConfiguration === WI.DockConfiguration.Bottom ? "row-resize" : "col-resize");
1923 WI._moveWindowMouseDown = function(event)
1925 console.assert(!this.docked);
1927 if (event.button !== 0 || event.ctrlKey)
1930 // Only start dragging if the target is one of the elements that we expect.
1931 if (!event.target.classList.contains("toolbar") && !event.target.classList.contains("flexible-space") &&
1932 !event.target.classList.contains("item-section"))
1935 event[WI.Popover.EventPreventDismissSymbol] = true;
1937 if (WI.Platform.name === "mac") {
1938 InspectorFrontendHost.startWindowDrag();
1939 event.preventDefault();
1943 var lastScreenX = event.screenX;
1944 var lastScreenY = event.screenY;
1946 function toolbarDrag(event)
1948 if (event.button !== 0)
1951 var x = event.screenX - lastScreenX;
1952 var y = event.screenY - lastScreenY;
1954 InspectorFrontendHost.moveWindowBy(x, y);
1956 lastScreenX = event.screenX;
1957 lastScreenY = event.screenY;
1960 function toolbarDragEnd(event)
1962 if (event.button !== 0)
1965 WI.elementDragEnd(event);
1968 WI.elementDragStart(event.target, toolbarDrag, toolbarDragEnd, event, "default");
1971 WI._domStorageWasInspected = function(event)
1973 this.showStorageTab();
1974 this.showRepresentedObject(event.data.domStorage, null, {ignoreSearchTab: true});
1977 WI._databaseWasInspected = function(event)
1979 this.showStorageTab();
1980 this.showRepresentedObject(event.data.database, null, {ignoreSearchTab: true});
1983 WI._domNodeWasInspected = function(event)
1985 this.domManager.highlightDOMNodeForTwoSeconds(event.data.node.id);
1987 InspectorFrontendHost.bringToFront();
1989 this.showElementsTab();
1990 this.showMainFrameDOMTree(event.data.node, {ignoreSearchTab: true});
1993 WI._inspectModeStateChanged = function(event)
1995 this._inspectModeToolbarButton.activated = this.domManager.inspectModeEnabled;
1998 WI._toggleInspectMode = function(event)
2000 this.domManager.inspectModeEnabled = !this.domManager.inspectModeEnabled;
2003 WI._handleDeviceSettingsToolbarButtonClicked = function(event)
2005 if (WI._deviceSettingsPopover) {
2006 WI._deviceSettingsPopover.dismiss();
2007 WI._deviceSettingsPopover = null;
2011 function updateActivatedState() {
2012 WI._deviceSettingsToolbarButton.activated = WI._overridenDeviceUserAgent || WI._overridenDeviceSettings.size > 0;
2015 function applyOverriddenUserAgent(value, force) {
2016 if (value === WI._overridenDeviceUserAgent)
2019 if (!force && (!value || value === "default")) {
2020 PageAgent.overrideUserAgent((error) => {
2022 console.error(error);
2026 WI._overridenDeviceUserAgent = null;
2027 updateActivatedState();
2031 PageAgent.overrideUserAgent(value, (error) => {
2033 console.error(error);
2037 WI._overridenDeviceUserAgent = value;
2038 updateActivatedState();
2044 function applyOverriddenSetting(setting, value, callback) {
2045 if (WI._overridenDeviceSettings.has(setting)) {
2046 // We've just "disabled" the checkbox, so clear the override instead of applying it.
2047 PageAgent.overrideSetting(setting, (error) => {
2049 console.error(error);
2053 WI._overridenDeviceSettings.delete(setting);
2055 updateActivatedState();
2058 PageAgent.overrideSetting(setting, value, (error) => {
2060 console.error(error);
2064 WI._overridenDeviceSettings.set(setting, value);
2066 updateActivatedState();
2071 function createCheckbox(container, label, setting, value) {
2075 let labelElement = container.appendChild(document.createElement("label"));
2077 let checkboxElement = labelElement.appendChild(document.createElement("input"));
2078 checkboxElement.type = "checkbox";
2079 checkboxElement.checked = WI._overridenDeviceSettings.has(setting);
2080 checkboxElement.addEventListener("change", (event) => {
2081 applyOverriddenSetting(setting, value, (enabled) => {
2082 checkboxElement.checked = enabled;
2086 labelElement.append(label);
2089 function calculateTargetFrame() {
2090 return WI.Rect.rectFromClientRect(WI._deviceSettingsToolbarButton.element.getBoundingClientRect());
2093 const preferredEdges = [WI.RectEdge.MAX_Y, WI.RectEdge.MIN_X, WI.RectEdge.MAX_X];
2095 WI._deviceSettingsPopover = new WI.Popover(this);
2096 WI._deviceSettingsPopover.windowResizeHandler = function(event) {
2097 WI._deviceSettingsPopover.present(calculateTargetFrame(), preferredEdges);
2100 let contentElement = document.createElement("table");
2101 contentElement.classList.add("device-settings-content");
2103 let userAgentRow = contentElement.appendChild(document.createElement("tr"));
2105 let userAgentTitle = userAgentRow.appendChild(document.createElement("td"));
2106 userAgentTitle.textContent = WI.UIString("User Agent:");
2108 let userAgentValue = userAgentRow.appendChild(document.createElement("td"));
2109 userAgentValue.classList.add("user-agent");
2111 let userAgentValueSelect = userAgentValue.appendChild(document.createElement("select"));
2113 let userAgentValueInput = null;
2115 const userAgents = [
2117 { name: WI.UIString("Default"), value: "default" },
2120 { name: "Safari 12.2", value: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.2 Safari/605.1.15" },
2123 { name: `Safari ${emDash} iOS 12.1.3 ${emDash} iPhone`, value: "Mozilla/5.0 (iPhone; CPU iPhone OS 12_1_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0 Mobile/15E148 Safari/604.1" },
2124 { name: `Safari ${emDash} iOS 12.1.3 ${emDash} iPod touch`, value: "Mozilla/5.0 (iPod; CPU iPhone OS 12_1_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0 Mobile/15E148 Safari/604.1" },
2125 { name: `Safari ${emDash} iOS 12.1.3 ${emDash} iPad`, value: "Mozilla/5.0 (iPad; CPU iPhone OS 12_1_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.0 Mobile/15E148 Safari/604.1" },
2128 { name: `Microsoft Edge`, value: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 Edge/16.16299" },
2131 { name: `Internet Explorer 11`, value: "Mozilla/5.0 (Windows NT 6.3; Win64, x64; Trident/7.0; rv:11.0) like Gecko" },
2132 { name: `Internet Explorer 10`, value: "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Win64; x64; Trident/6.0)" },
2133 { name: `Internet Explorer 9`, value: "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)" },
2134 { name: `Internet Explorer 8`, value: "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0)" },
2135 { name: `Internet Explorer 7`, value: "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)" },
2138 { name: `Google Chrome ${emDash} macOS`, value: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36" },
2139 { name: `Google Chrome ${emDash} Windows`, value: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36" },
2142 { name: `Firefox ${emDash} macOS`, value: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:63.0) Gecko/20100101 Firefox/63.0" },
2143 { name: `Firefox ${emDash} Windows`, value: "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:63.0) Gecko/20100101 Firefox/63.0" },
2146 { name: WI.UIString("Other\u2026"), value: "other" },
2150 let selectedOptionElement = null;
2152 for (let group of userAgents) {
2153 for (let {name, value} of group) {
2154 let optionElement = userAgentValueSelect.appendChild(document.createElement("option"));
2155 optionElement.value = value;
2156 optionElement.textContent = name;
2158 if (value === WI._overridenDeviceUserAgent)
2159 selectedOptionElement = optionElement;
2162 if (group !== userAgents.lastValue)
2163 userAgentValueSelect.appendChild(document.createElement("hr"));
2166 function showUserAgentInput() {
2167 if (userAgentValueInput)
2170 userAgentValueInput = userAgentValue.appendChild(document.createElement("input"));
2171 userAgentValueInput.value = userAgentValueInput.placeholder = WI._overridenDeviceUserAgent || navigator.userAgent;
2172 userAgentValueInput.addEventListener("click", (clickEvent) => {
2173 clickEvent.preventDefault();
2175 userAgentValueInput.addEventListener("change", (inputEvent) => {
2176 applyOverriddenUserAgent(userAgentValueInput.value, true);
2179 WI._deviceSettingsPopover.update();
2182 if (selectedOptionElement)
2183 userAgentValueSelect.value = selectedOptionElement.value;
2184 else if (WI._overridenDeviceUserAgent) {
2185 userAgentValueSelect.value = "other";
2186 showUserAgentInput();
2189 userAgentValueSelect.addEventListener("change", () => {
2190 let value = userAgentValueSelect.value;
2191 if (value === "other") {
2192 showUserAgentInput();
2193 userAgentValueInput.select();
2195 if (userAgentValueInput) {
2196 userAgentValueInput.remove();
2197 userAgentValueInput = null;
2199 WI._deviceSettingsPopover.update();
2202 applyOverriddenUserAgent(value);
2208 name: WI.UIString("Disable:"),
2211 {name: WI.UIString("Images"), setting: PageAgent.Setting.ImagesEnabled, value: false},
2212 {name: WI.UIString("Styles"), setting: PageAgent.Setting.AuthorAndUserStylesEnabled, value: false},
2213 {name: WI.UIString("JavaScript"), setting: PageAgent.Setting.ScriptEnabled, value: false},
2216 {name: WI.UIString("Site-specific Hacks"), setting: PageAgent.Setting.NeedsSiteSpecificQuirks, value: false},
2217 {name: WI.UIString("Cross-Origin Restrictions"), setting: PageAgent.Setting.WebSecurityEnabled, value: false},
2222 name: WI.UIString("%s:").format(WI.unlocalizedString("WebRTC")),
2225 {name: WI.UIString("Allow Media Capture on Insecure Sites"), setting: PageAgent.Setting.MediaCaptureRequiresSecureConnection, value: false},
2226 {name: WI.UIString("Disable ICE Candidate Restrictions"), setting: PageAgent.Setting.ICECandidateFilteringEnabled, value: false},
2227 {name: WI.UIString("Use Mock Capture Devices"), setting: PageAgent.Setting.MockCaptureDevicesEnabled, value: true},
2233 for (let group of settings) {
2234 if (!group.columns.some((column) => column.some((item) => item.setting)))
2237 let settingsGroupRow = contentElement.appendChild(document.createElement("tr"));
2239 let settingsGroupTitle = settingsGroupRow.appendChild(document.createElement("td"));
2240 settingsGroupTitle.textContent = group.name;
2242 let settingsGroupValue = settingsGroupRow.appendChild(document.createElement("td"));
2244 let settingsGroupItemContainer = settingsGroupValue.appendChild(document.createElement("div"));
2245 settingsGroupItemContainer.classList.add("container");
2247 for (let column of group.columns) {
2248 let columnElement = settingsGroupItemContainer.appendChild(document.createElement("div"));
2249 columnElement.classList.add("column");
2251 for (let item of column)
2252 createCheckbox(columnElement, item.name, item.setting, item.value);
2256 WI._deviceSettingsPopover.presentNewContentWithFrame(contentElement, calculateTargetFrame(), preferredEdges);
2259 WI._downloadWebArchive = function(event)
2261 this.archiveMainFrame();
2264 WI._reloadInspectedInspector = function()
2267 WI.runtimeManager.evaluateInInspectedWindow(`InspectorFrontendHost.reopen()`, options, function(){});
2270 WI._reloadPage = function(event)
2272 if (!window.PageAgent)
2275 event.preventDefault();
2277 if (InspectorFrontendHost.inspectionLevel() > 1) {
2278 WI._reloadInspectedInspector();
2285 WI._reloadPageFromOrigin = function(event)
2287 if (!window.PageAgent)
2290 event.preventDefault();
2292 if (InspectorFrontendHost.inspectionLevel() > 1) {
2293 WI._reloadInspectedInspector();
2297 PageAgent.reload.invoke({ignoreCache: true});
2300 WI._reloadToolbarButtonClicked = function(event)
2302 if (InspectorFrontendHost.inspectionLevel() > 1) {
2303 WI._reloadInspectedInspector();
2307 // Reload page from origin if the button is clicked while the shift key is pressed down.
2308 PageAgent.reload.invoke({ignoreCache: this.modifierKeys.shiftKey});
2311 WI._updateReloadToolbarButton = function()
2313 if (!window.PageAgent) {
2314 this._reloadToolbarButton.hidden = true;
2318 this._reloadToolbarButton.hidden = false;
2321 WI._updateDownloadToolbarButton = function()
2323 if (!window.PageAgent || this.sharedApp.debuggableType !== WI.DebuggableType.Web) {
2324 this._downloadToolbarButton.hidden = true;
2328 if (this._downloadingPage) {
2329 this._downloadToolbarButton.enabled = false;
2333 this._downloadToolbarButton.enabled = this.canArchiveMainFrame();
2336 WI._updateInspectModeToolbarButton = function()
2338 if (!window.DOMAgent || !DOMAgent.setInspectModeEnabled) {
2339 this._inspectModeToolbarButton.hidden = true;
2343 this._inspectModeToolbarButton.hidden = false;
2346 WI._toggleInspectMode = function(event)
2348 this.domManager.inspectModeEnabled = !this.domManager.inspectModeEnabled;
2351 WI._showConsoleTab = function(event)
2353 this.showConsoleTab();
2356 WI._focusConsolePrompt = function(event)
2358 this.quickConsole.prompt.focus();
2361 WI._focusedContentBrowser = function()
2363 if (this.currentFocusElement) {
2364 let contentBrowserElement = this.currentFocusElement.closest(".content-browser");
2365 if (contentBrowserElement && contentBrowserElement.__view && contentBrowserElement.__view instanceof WI.ContentBrowser)
2366 return contentBrowserElement.__view;
2369 if (this.tabBrowser.element.contains(this.currentFocusElement) || document.activeElement === document.body) {
2370 let tabContentView = this.tabBrowser.selectedTabContentView;
2371 if (tabContentView.contentBrowser)
2372 return tabContentView.contentBrowser;
2376 if (this.consoleDrawer.element.contains(this.currentFocusElement)
2377 || (WI.isShowingSplitConsole() && this.quickConsole.element.contains(this.currentFocusElement)))
2378 return this.consoleDrawer;
2383 WI._focusedContentView = function()
2385 if (this.tabBrowser.element.contains(this.currentFocusElement) || document.activeElement === document.body) {
2386 var tabContentView = this.tabBrowser.selectedTabContentView;
2387 if (tabContentView.contentBrowser)
2388 return tabContentView.contentBrowser.currentContentView;
2389 return tabContentView;
2392 if (this.consoleDrawer.element.contains(this.currentFocusElement)
2393 || (WI.isShowingSplitConsole() && this.quickConsole.element.contains(this.currentFocusElement)))
2394 return this.consoleDrawer.currentContentView;
2399 WI._focusedOrVisibleContentBrowser = function()
2401 let focusedContentBrowser = this._focusedContentBrowser();
2402 if (focusedContentBrowser)
2403 return focusedContentBrowser;
2405 var tabContentView = this.tabBrowser.selectedTabContentView;
2406 if (tabContentView.contentBrowser)
2407 return tabContentView.contentBrowser;
2412 WI.focusedOrVisibleContentView = function()
2414 let focusedContentView = this._focusedContentView();
2415 if (focusedContentView)
2416 return focusedContentView;
2418 var tabContentView = this.tabBrowser.selectedTabContentView;
2419 if (tabContentView.contentBrowser)
2420 return tabContentView.contentBrowser.currentContentView;
2421 return tabContentView;
2424 WI._beforecopy = function(event)
2426 var selection = window.getSelection();
2428 // If there is no selection, see if the focused element or focused ContentView can handle the copy event.
2429 if (selection.isCollapsed && !WI.isEventTargetAnEditableField(event)) {
2430 var focusedCopyHandler = this.currentFocusElement && this.currentFocusElement.copyHandler;
2431 if (focusedCopyHandler && typeof focusedCopyHandler.handleBeforeCopyEvent === "function") {
2432 focusedCopyHandler.handleBeforeCopyEvent(event);
2433 if (event.defaultPrevented)
2437 var focusedContentView = this._focusedContentView();
2438 if (focusedContentView && typeof focusedContentView.handleCopyEvent === "function") {
2439 event.preventDefault();
2446 if (selection.isCollapsed)
2449 // Say we can handle it (by preventing default) to remove word break characters.
2450 event.preventDefault();
2453 WI._find = function(event)
2455 let contentBrowser = this._focusedOrVisibleContentBrowser();
2456 if (!contentBrowser)
2459 contentBrowser.showFindBanner();
2462 WI._save = function(event)
2464 var contentView = this.focusedOrVisibleContentView();
2465 if (!contentView || !contentView.supportsSave)
2468 WI.FileUtilities.save(contentView.saveData);
2471 WI._saveAs = function(event)
2473 var contentView = this.focusedOrVisibleContentView();
2474 if (!contentView || !contentView.supportsSave)
2477 WI.FileUtilities.save(contentView.saveData, true);
2480 WI._clear = function(event)
2482 let contentView = this.focusedOrVisibleContentView();
2483 if (!contentView || typeof contentView.handleClearShortcut !== "function") {
2484 // If the current content view is unable to handle this event, clear the console to reset
2485 // the dashboard counters.
2486 this.consoleManager.requestClearMessages();
2490 contentView.handleClearShortcut(event);
2493 WI._populateFind = function(event)
2495 let focusedContentView = this._focusedContentView();
2496 if (!focusedContentView)
2499 if (focusedContentView.supportsCustomFindBanner) {
2500 focusedContentView.handlePopulateFindShortcut();
2504 let contentBrowser = this._focusedOrVisibleContentBrowser();
2505 if (!contentBrowser)
2508 contentBrowser.handlePopulateFindShortcut();
2511 WI._findNext = function(event)
2513 let focusedContentView = this._focusedContentView();
2514 if (!focusedContentView)
2517 if (focusedContentView.supportsCustomFindBanner) {
2518 focusedContentView.handleFindNextShortcut();
2522 let contentBrowser = this._focusedOrVisibleContentBrowser();
2523 if (!contentBrowser)
2526 contentBrowser.handleFindNextShortcut();
2529 WI._findPrevious = function(event)
2531 let focusedContentView = this._focusedContentView();
2532 if (!focusedContentView)
2535 if (focusedContentView.supportsCustomFindBanner) {
2536 focusedContentView.handleFindPreviousShortcut();
2540 let contentBrowser = this._focusedOrVisibleContentBrowser();
2541 if (!contentBrowser)
2544 contentBrowser.handleFindPreviousShortcut();
2547 WI._copy = function(event)
2549 var selection = window.getSelection();
2551 // If there is no selection, pass the copy event on to the focused element or focused ContentView.
2552 if (selection.isCollapsed && !WI.isEventTargetAnEditableField(event)) {
2553 var focusedCopyHandler = this.currentFocusElement && this.currentFocusElement.copyHandler;
2554 if (focusedCopyHandler && typeof focusedCopyHandler.handleCopyEvent === "function") {
2555 focusedCopyHandler.handleCopyEvent(event);
2556 if (event.defaultPrevented)
2560 var focusedContentView = this._focusedContentView();
2561 if (focusedContentView && typeof focusedContentView.handleCopyEvent === "function") {
2562 focusedContentView.handleCopyEvent(event);
2566 let tabContentView = this.tabBrowser.selectedTabContentView;
2567 if (tabContentView && typeof tabContentView.handleCopyEvent === "function") {
2568 tabContentView.handleCopyEvent(event);
2575 if (selection.isCollapsed)
2578 // Remove word break characters from the selection before putting it on the pasteboard.
2579 var selectionString = selection.toString().removeWordBreakCharacters();
2580 event.clipboardData.setData("text/plain", selectionString);
2581 event.preventDefault();
2584 WI._increaseZoom = function(event)
2586 const epsilon = 0.0001;
2587 const maximumZoom = 2.4;
2588 let currentZoom = this.getZoomFactor();
2589 if (currentZoom + epsilon >= maximumZoom) {
2590 InspectorFrontendHost.beep();
2594 this.setZoomFactor(Math.min(maximumZoom, currentZoom + 0.2));
2597 WI._decreaseZoom = function(event)
2599 const epsilon = 0.0001;
2600 const minimumZoom = 0.6;
2601 let currentZoom = this.getZoomFactor();
2602 if (currentZoom - epsilon <= minimumZoom) {
2603 InspectorFrontendHost.beep();
2607 this.setZoomFactor(Math.max(minimumZoom, currentZoom - 0.2));
2610 WI._resetZoom = function(event)
2612 this.setZoomFactor(1);
2615 WI.getZoomFactor = function()
2617 return WI.settings.zoomFactor.value;
2620 WI.setZoomFactor = function(factor)
2622 InspectorFrontendHost.setZoomFactor(factor);
2623 // Round-trip through the frontend host API in case the requested factor is not used.
2624 WI.settings.zoomFactor.value = InspectorFrontendHost.zoomFactor();
2627 WI.resolvedLayoutDirection = function()
2629 let layoutDirection = WI.settings.layoutDirection.value;
2630 if (layoutDirection === WI.LayoutDirection.System)
2631 layoutDirection = InspectorFrontendHost.userInterfaceLayoutDirection();
2633 return layoutDirection;
2636 WI.setLayoutDirection = function(value)
2638 if (!Object.values(WI.LayoutDirection).includes(value))
2639 WI.reportInternalError("Unknown layout direction requested: " + value);
2641 if (value === WI.settings.layoutDirection.value)
2644 WI.settings.layoutDirection.value = value;
2646 if (WI.resolvedLayoutDirection() === WI.LayoutDirection.RTL && this._dockConfiguration === WI.DockConfiguration.Right)
2649 if (WI.resolvedLayoutDirection() === WI.LayoutDirection.LTR && this._dockConfiguration === WI.DockConfiguration.Left)
2652 InspectorFrontendHost.reopen();
2655 WI._showTabAtIndex = function(i, event)
2657 if (i <= WI.tabBar.tabBarItems.length)
2658 WI.tabBar.selectedTabBarItem = i - 1;
2661 WI._showJavaScriptTypeInformationSettingChanged = function(event)
2663 if (WI.settings.showJavaScriptTypeInformation.value) {
2664 for (let target of WI.targets)
2665 target.RuntimeAgent.enableTypeProfiler();
2667 for (let target of WI.targets)
2668 target.RuntimeAgent.disableTypeProfiler();
2672 WI._enableControlFlowProfilerSettingChanged = function(event)
2674 if (WI.settings.enableControlFlowProfiler.value) {
2675 for (let target of WI.targets)
2676 target.RuntimeAgent.enableControlFlowProfiler();
2678 for (let target of WI.targets)
2679 target.RuntimeAgent.disableControlFlowProfiler();
2683 WI._resourceCachingDisabledSettingChanged = function(event)
2685 NetworkAgent.setResourceCachingDisabled(WI.settings.resourceCachingDisabled.value);
2688 WI.elementDragStart = function(element, dividerDrag, elementDragEnd, event, cursor, eventTarget)
2690 if (WI._elementDraggingEventListener || WI._elementEndDraggingEventListener)
2691 WI.elementDragEnd(event);
2694 // Install glass pane
2695 if (WI._elementDraggingGlassPane)
2696 WI._elementDraggingGlassPane.remove();
2698 var glassPane = document.createElement("div");
2699 glassPane.style.cssText = "position:absolute;top:0;bottom:0;left:0;right:0;opacity:0;z-index:1";
2700 glassPane.id = "glass-pane-for-drag";
2701 element.ownerDocument.body.appendChild(glassPane);
2702 WI._elementDraggingGlassPane = glassPane;
2705 WI._elementDraggingEventListener = dividerDrag;
2706 WI._elementEndDraggingEventListener = elementDragEnd;
2708 var targetDocument = event.target.ownerDocument;
2710 WI._elementDraggingEventTarget = eventTarget || targetDocument;
2711 WI._elementDraggingEventTarget.addEventListener("mousemove", dividerDrag, true);
2712 WI._elementDraggingEventTarget.addEventListener("mouseup", elementDragEnd, true);
2714 targetDocument.body.style.cursor = cursor;
2716 event.preventDefault();
2719 WI.elementDragEnd = function(event)
2721 WI._elementDraggingEventTarget.removeEventListener("mousemove", WI._elementDraggingEventListener, true);
2722 WI._elementDraggingEventTarget.removeEventListener("mouseup", WI._elementEndDraggingEventListener, true);
2724 event.target.ownerDocument.body.style.removeProperty("cursor");
2726 if (WI._elementDraggingGlassPane)
2727 WI._elementDraggingGlassPane.remove();
2729 delete WI._elementDraggingGlassPane;
2730 delete WI._elementDraggingEventTarget;
2731 delete WI._elementDraggingEventListener;
2732 delete WI._elementEndDraggingEventListener;
2734 event.preventDefault();
2737 WI.createMessageTextView = function(message, isError)
2739 let messageElement = document.createElement("div");
2740 messageElement.className = "message-text-view";
2742 messageElement.classList.add("error");
2744 let textElement = messageElement.appendChild(document.createElement("div"));
2745 textElement.className = "message";
2746 textElement.textContent = message;
2748 return messageElement;
2751 WI.createNavigationItemHelp = function(formatString, navigationItem)
2753 console.assert(typeof formatString === "string");
2754 console.assert(navigationItem instanceof WI.NavigationItem);
2756 function append(a, b) {
2761 let containerElement = document.createElement("div");
2762 containerElement.className = "navigation-item-help";
2763 containerElement.__navigationItem = navigationItem;
2765 let wrapperElement = document.createElement("div");
2766 wrapperElement.className = "navigation-bar";
2767 wrapperElement.appendChild(navigationItem.element);
2769 String.format(formatString, [wrapperElement], String.standardFormatters, containerElement, append);
2770 return containerElement;
2773 WI.createGoToArrowButton = function()
2775 var button = document.createElement("button");
2776 button.addEventListener("mousedown", (event) => { event.stopPropagation(); }, true);
2777 button.className = "go-to-arrow";
2778 button.tabIndex = -1;
2782 WI.createSourceCodeLocationLink = function(sourceCodeLocation, options = {})
2784 console.assert(sourceCodeLocation);
2785 if (!sourceCodeLocation)
2788 var linkElement = document.createElement("a");
2789 linkElement.className = "go-to-link";
2790 WI.linkifyElement(linkElement, sourceCodeLocation, options);
2791 sourceCodeLocation.populateLiveDisplayLocationTooltip(linkElement);
2793 if (options.useGoToArrowButton)
2794 linkElement.appendChild(WI.createGoToArrowButton());
2796 sourceCodeLocation.populateLiveDisplayLocationString(linkElement, "textContent", options.columnStyle, options.nameStyle, options.prefix);
2798 if (options.dontFloat)
2799 linkElement.classList.add("dont-float");
2804 WI.linkifyLocation = function(url, sourceCodePosition, options = {})
2806 var sourceCode = WI.sourceCodeForURL(url);
2809 var anchor = document.createElement("a");
2811 anchor.lineNumber = sourceCodePosition.lineNumber;
2812 if (options.className)
2813 anchor.className = options.className;
2814 anchor.append(WI.displayNameForURL(url) + ":" + sourceCodePosition.lineNumber);
2818 let sourceCodeLocation = sourceCode.createSourceCodeLocation(sourceCodePosition.lineNumber, sourceCodePosition.columnNumber);
2819 let linkElement = WI.createSourceCodeLocationLink(sourceCodeLocation, {
2824 if (options.className)
2825 linkElement.classList.add(options.className);
2830 WI.linkifyElement = function(linkElement, sourceCodeLocation, options = {}) {
2831 console.assert(sourceCodeLocation);
2833 function showSourceCodeLocation(event)
2835 event.stopPropagation();
2836 event.preventDefault();
2839 this.showOriginalUnformattedSourceCodeLocation(sourceCodeLocation, options);
2841 this.showSourceCodeLocation(sourceCodeLocation, options);
2844 linkElement.addEventListener("click", showSourceCodeLocation.bind(this));
2845 linkElement.addEventListener("contextmenu", (event) => {
2846 let contextMenu = WI.ContextMenu.createFromEvent(event);
2847 WI.appendContextMenuItemsForSourceCode(contextMenu, sourceCodeLocation);
2851 WI.sourceCodeForURL = function(url)
2853 var sourceCode = WI.networkManager.resourceForURL(url);
2855 sourceCode = WI.debuggerManager.scriptsForURL(url, WI.assumingMainTarget())[0];
2857 sourceCode = sourceCode.resource || sourceCode;
2859 return sourceCode || null;
2862 WI.linkifyURLAsNode = function(url, linkText, className)
2864 let a = document.createElement("a");
2866 a.className = className || "";
2867 a.textContent = linkText || url;
2868 a.style.maxWidth = "100%";
2872 WI.linkifyStringAsFragmentWithCustomLinkifier = function(string, linkifier)
2874 var container = document.createDocumentFragment();
2875 var linkStringRegEx = /(?:[a-zA-Z][a-zA-Z0-9+.-]{2,}:\/\/|www\.)[\w$\-_+*'=\|\/\\(){}[\]%@&#~,:;.!?]{2,}[\w$\-_+*=\|\/\\({%@&#~]/;
2876 var lineColumnRegEx = /:(\d+)(:(\d+))?$/;
2879 var linkString = linkStringRegEx.exec(string);
2883 linkString = linkString[0];
2884 var linkIndex = string.indexOf(linkString);
2885 var nonLink = string.substring(0, linkIndex);
2886 container.append(nonLink);
2888 if (linkString.startsWith("data:") || linkString.startsWith("javascript:") || linkString.startsWith("mailto:")) {
2889 container.append(linkString);
2890 string = string.substring(linkIndex + linkString.length, string.length);
2894 var title = linkString;
2895 var realURL = linkString.startsWith("www.") ? "http://" + linkString : linkString;
2896 var lineColumnMatch = lineColumnRegEx.exec(realURL);
2897 if (lineColumnMatch)
2898 realURL = realURL.substring(0, realURL.length - lineColumnMatch[0].length);
2901 if (lineColumnMatch)
2902 lineNumber = parseInt(lineColumnMatch[1]) - 1;
2904 var linkNode = linkifier(title, realURL, lineNumber);
2905 container.appendChild(linkNode);
2906 string = string.substring(linkIndex + linkString.length, string.length);
2910 container.append(string);
2915 WI.linkifyStringAsFragment = function(string)
2917 function linkifier(title, url, lineNumber)
2919 var urlNode = WI.linkifyURLAsNode(url, title, undefined);
2920 if (lineNumber !== undefined)
2921 urlNode.lineNumber = lineNumber;
2926 return WI.linkifyStringAsFragmentWithCustomLinkifier(string, linkifier);
2929 WI.createResourceLink = function(resource, className)
2931 function handleClick(event)
2933 event.stopPropagation();
2934 event.preventDefault();
2936 WI.showRepresentedObject(resource);
2939 let linkNode = document.createElement("a");
2940 linkNode.classList.add("resource-link", className);
2941 linkNode.title = resource.url;
2942 linkNode.textContent = (resource.urlComponents.lastPathComponent || resource.url).insertWordBreakCharacters();
2943 linkNode.addEventListener("click", handleClick.bind(this));
2947 WI._undoKeyboardShortcut = function(event)
2949 if (!this.isEditingAnyField() && !this.isEventTargetAnEditableField(event)) {
2951 event.preventDefault();
2955 WI._redoKeyboardShortcut = function(event)
2957 if (!this.isEditingAnyField() && !this.isEventTargetAnEditableField(event)) {
2959 event.preventDefault();
2963 WI.undo = function()
2968 WI.redo = function()
2973 WI.highlightRangesWithStyleClass = function(element, resultRanges, styleClass, changes)
2975 changes = changes || [];
2976 var highlightNodes = [];
2977 var lineText = element.textContent;
2978 var ownerDocument = element.ownerDocument;
2979 var textNodeSnapshot = ownerDocument.evaluate(".//text()", element, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
2981 var snapshotLength = textNodeSnapshot.snapshotLength;
2982 if (snapshotLength === 0)
2983 return highlightNodes;
2985 var nodeRanges = [];
2986 var rangeEndOffset = 0;
2987 for (var i = 0; i < snapshotLength; ++i) {
2989 range.offset = rangeEndOffset;
2990 range.length = textNodeSnapshot.snapshotItem(i).textContent.length;
2991 rangeEndOffset = range.offset + range.length;
2992 nodeRanges.push(range);
2996 for (var i = 0; i < resultRanges.length; ++i) {
2997 var startOffset = resultRanges[i].offset;
2998 var endOffset = startOffset + resultRanges[i].length;
3000 while (startIndex < snapshotLength && nodeRanges[startIndex].offset + nodeRanges[startIndex].length <= startOffset)
3002 var endIndex = startIndex;
3003 while (endIndex < snapshotLength && nodeRanges[endIndex].offset + nodeRanges[endIndex].length < endOffset)
3005 if (endIndex === snapshotLength)
3008 var highlightNode = ownerDocument.createElement("span");
3009 highlightNode.className = styleClass;
3010 highlightNode.textContent = lineText.substring(startOffset, endOffset);
3012 var lastTextNode = textNodeSnapshot.snapshotItem(endIndex);
3013 var lastText = lastTextNode.textContent;
3014 lastTextNode.textContent = lastText.substring(endOffset - nodeRanges[endIndex].offset);
3015 changes.push({node: lastTextNode, type: "changed", oldText: lastText, newText: lastTextNode.textContent});
3017 if (startIndex === endIndex) {
3018 lastTextNode.parentElement.insertBefore(highlightNode, lastTextNode);
3019 changes.push({node: highlightNode, type: "added", nextSibling: lastTextNode, parent: lastTextNode.parentElement});
3020 highlightNodes.push(highlightNode);
3022 var prefixNode = ownerDocument.createTextNode(lastText.substring(0, startOffset - nodeRanges[startIndex].offset));
3023 lastTextNode.parentElement.insertBefore(prefixNode, highlightNode);
3024 changes.push({node: prefixNode, type: "added", nextSibling: highlightNode, parent: lastTextNode.parentElement});
3026 var firstTextNode = textNodeSnapshot.snapshotItem(startIndex);
3027 var firstText = firstTextNode.textContent;
3028 var anchorElement = firstTextNode.nextSibling;
3030 firstTextNode.parentElement.insertBefore(highlightNode, anchorElement);
3031 changes.push({node: highlightNode, type: "added", nextSibling: anchorElement, parent: firstTextNode.parentElement});
3032 highlightNodes.push(highlightNode);
3034 firstTextNode.textContent = firstText.substring(0, startOffset - nodeRanges[startIndex].offset);
3035 changes.push({node: firstTextNode, type: "changed", oldText: firstText, newText: firstTextNode.textContent});
3037 for (var j = startIndex + 1; j < endIndex; j++) {
3038 var textNode = textNodeSnapshot.snapshotItem(j);
3039 var text = textNode.textContent;
3040 textNode.textContent = "";
3041 changes.push({node: textNode, type: "changed", oldText: text, newText: textNode.textContent});
3044 startIndex = endIndex;
3045 nodeRanges[startIndex].offset = endOffset;
3046 nodeRanges[startIndex].length = lastTextNode.textContent.length;
3049 return highlightNodes;
3052 WI.revertDOMChanges = function(domChanges)
3054 for (var i = domChanges.length - 1; i >= 0; --i) {
3055 var entry = domChanges[i];
3056 switch (entry.type) {
3058 entry.node.remove();
3061 entry.node.textContent = entry.oldText;
3067 WI.archiveMainFrame = function()
3069 this._downloadingPage = true;
3070 this._updateDownloadToolbarButton();
3072 PageAgent.archive((error, data) => {
3073 this._downloadingPage = false;
3074 this._updateDownloadToolbarButton();
3079 let mainFrame = WI.networkManager.mainFrame;
3080 let archiveName = mainFrame.mainResource.urlComponents.host || mainFrame.mainResource.displayName || "Archive";
3081 let url = "web-inspector:///" + encodeURI(archiveName) + ".webarchive";
3083 InspectorFrontendHost.save(url, data, true, true);
3087 WI.canArchiveMainFrame = function()
3089 if (this.sharedApp.debuggableType !== WI.DebuggableType.Web)
3092 if (!WI.networkManager.mainFrame || !WI.networkManager.mainFrame.mainResource)
3095 return WI.Resource.typeFromMIMEType(WI.networkManager.mainFrame.mainResource.mimeType) === WI.Resource.Type.Document;
3098 WI.addWindowKeydownListener = function(listener)
3100 if (typeof listener.handleKeydownEvent !== "function")
3103 this._windowKeydownListeners.push(listener);
3105 this._updateWindowKeydownListener();
3108 WI.removeWindowKeydownListener = function(listener)
3110 this._windowKeydownListeners.remove(listener);
3112 this._updateWindowKeydownListener();
3115 WI._updateWindowKeydownListener = function()
3117 if (this._windowKeydownListeners.length === 1)
3118 window.addEventListener("keydown", WI._sharedWindowKeydownListener, true);
3119 else if (!this._windowKeydownListeners.length)
3120 window.removeEventListener("keydown", WI._sharedWindowKeydownListener, true);
3123 WI._sharedWindowKeydownListener = function(event)
3125 for (var i = WI._windowKeydownListeners.length - 1; i >= 0; --i) {
3126 if (WI._windowKeydownListeners[i].handleKeydownEvent(event)) {
3127 event.stopImmediatePropagation();
3128 event.preventDefault();
3134 WI.reportInternalError = function(errorOrString, details = {})
3136 // The 'details' object includes additional information from the caller as free-form string keys and values.
3137 // Each key and value will be shown in the uncaught exception reporter, console error message, or in
3138 // a pre-filled bug report generated for this internal error.
3140 let error = errorOrString instanceof Error ? errorOrString : new Error(errorOrString);
3141 error.details = details;
3143 // The error will be displayed in the Uncaught Exception Reporter sheet if DebugUI is enabled.
3144 if (WI.isDebugUIEnabled()) {
3145 // This assert allows us to stop the debugger at an internal exception. It doesn't re-throw
3146 // exceptions because the original exception would be lost through window.onerror.
3147 // This workaround can be removed once <https://webkit.org/b/158192> is fixed.
3148 console.assert(false, "An internal exception was thrown.", error);
3149 handleInternalException(error);
3151 console.error(error);
3154 // Many places assume the "main" target has resources.
3155 // In the case where the main backend target is a MultiplexingBackendTarget
3156 // that target has essentially nothing. In that case defer to the page
3157 // target, since that is the real "main" target the frontend is assuming.
3158 Object.defineProperty(WI, "mainTarget",
3160 get() { return WI.pageTarget || WI.backendTarget; }
3163 // This list of targets are non-Multiplexing targets.
3164 // So if there is a multiplexing target, and multiple sub-targets
3165 // this is just the list of sub-targets. Almost no code expects
3166 // to actually interact with the Multiplexing target.
3167 Object.defineProperty(WI, "targets",
3169 get() { return WI.targetManager.targets; }
3172 // Many places assume the main target because they cannot yet be
3173 // used by reached by Worker debugging. Eventually, once all
3174 // Worker domains have been implemented, all of these must be
3175 // handled properly.
3176 WI.assumingMainTarget = function()
3178 return WI.mainTarget;
3181 WI.isEngineeringBuild = false;
3183 // OpenResourceDialog delegate
3185 WI.dialogWasDismissedWithRepresentedObject = function(dialog, representedObject)
3187 if (!representedObject)
3190 WI.showRepresentedObject(representedObject, dialog.cookie);
3195 WI.didDismissPopover = function(popover)
3197 if (popover === WI._deviceSettingsPopover)
3198 WI._deviceSettingsPopover = null;
3201 WI.DockConfiguration = {
3205 Undocked: "undocked",