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