abd80817b22f70b98dd19fd78d39f34752021926
[WebKit-https.git] / Source / WebInspectorUI / UserInterface / Base / Main.js
1 /*
2  * Copyright (C) 2013-2014 Apple Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
14  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
15  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
17  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
18  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
19  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
20  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
21  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
22  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
23  * THE POSSIBILITY OF SUCH DAMAGE.
24  */
25
26 WebInspector.ContentViewCookieType = {
27     ApplicationCache: "application-cache",
28     CookieStorage: "cookie-storage",
29     Database: "database",
30     DatabaseTable: "database-table",
31     DOMStorage: "dom-storage",
32     Resource: "resource", // includes Frame too.
33     Timelines: "timelines"
34 };
35
36 WebInspector.DebuggableType = {
37     Web: "web",
38     JavaScript: "javascript"
39 };
40
41 WebInspector.SelectedSidebarPanelCookieKey = "selected-sidebar-panel";
42 WebInspector.TypeIdentifierCookieKey = "represented-object-type";
43
44 WebInspector.StateRestorationType = {
45     Load: "state-restoration-load",
46     Navigation: "state-restoration-navigation",
47     Delayed: "state-restoration-delayed",
48 };
49
50 WebInspector.loaded = function()
51 {
52     // Initialize WebSocket to communication.
53     this._initializeWebSocketIfNeeded();
54
55     this.debuggableType = InspectorFrontendHost.debuggableType() === "web" ? WebInspector.DebuggableType.Web : WebInspector.DebuggableType.JavaScript;
56     this.hasExtraDomains = false;
57
58     // Register observers for events from the InspectorBackend.
59     if (InspectorBackend.registerInspectorDispatcher)
60         InspectorBackend.registerInspectorDispatcher(new WebInspector.InspectorObserver);
61     if (InspectorBackend.registerPageDispatcher)
62         InspectorBackend.registerPageDispatcher(new WebInspector.PageObserver);
63     if (InspectorBackend.registerConsoleDispatcher)
64         InspectorBackend.registerConsoleDispatcher(new WebInspector.ConsoleObserver);
65     if (InspectorBackend.registerNetworkDispatcher)
66         InspectorBackend.registerNetworkDispatcher(new WebInspector.NetworkObserver);
67     if (InspectorBackend.registerDOMDispatcher)
68         InspectorBackend.registerDOMDispatcher(new WebInspector.DOMObserver);
69     if (InspectorBackend.registerDebuggerDispatcher)
70         InspectorBackend.registerDebuggerDispatcher(new WebInspector.DebuggerObserver);
71     if (InspectorBackend.registerDatabaseDispatcher)
72         InspectorBackend.registerDatabaseDispatcher(new WebInspector.DatabaseObserver);
73     if (InspectorBackend.registerDOMStorageDispatcher)
74         InspectorBackend.registerDOMStorageDispatcher(new WebInspector.DOMStorageObserver);
75     if (InspectorBackend.registerApplicationCacheDispatcher)
76         InspectorBackend.registerApplicationCacheDispatcher(new WebInspector.ApplicationCacheObserver);
77     if (InspectorBackend.registerTimelineDispatcher)
78         InspectorBackend.registerTimelineDispatcher(new WebInspector.TimelineObserver);
79     if (InspectorBackend.registerCSSDispatcher)
80         InspectorBackend.registerCSSDispatcher(new WebInspector.CSSObserver);
81     if (InspectorBackend.registerLayerTreeDispatcher)
82         InspectorBackend.registerLayerTreeDispatcher(new WebInspector.LayerTreeObserver);
83     if (InspectorBackend.registerRuntimeDispatcher)
84         InspectorBackend.registerRuntimeDispatcher(new WebInspector.RuntimeObserver);
85     if (InspectorBackend.registerReplayDispatcher)
86         InspectorBackend.registerReplayDispatcher(new WebInspector.ReplayObserver);
87
88     // Enable agents.
89     if (window.InspectorAgent)
90         InspectorAgent.enable();
91
92     // Perform one-time tasks.
93     WebInspector.CSSCompletions.requestCSSNameCompletions();
94     this._generateDisclosureTriangleImages();
95
96     // Listen for the ProvisionalLoadStarted event before registering for events so our code gets called before any managers or sidebars.
97     // This lets us save a state cookie before any managers or sidebars do any resets that would affect state (namely TimelineManager).
98     WebInspector.Frame.addEventListener(WebInspector.Frame.Event.ProvisionalLoadStarted, this._provisionalLoadStarted, this);
99
100     // Create the singleton managers next, before the user interface elements, so the user interface can register
101     // as event listeners on these managers.
102     this.branchManager = new WebInspector.BranchManager;
103     this.frameResourceManager = new WebInspector.FrameResourceManager;
104     this.storageManager = new WebInspector.StorageManager;
105     this.domTreeManager = new WebInspector.DOMTreeManager;
106     this.cssStyleManager = new WebInspector.CSSStyleManager;
107     this.logManager = new WebInspector.LogManager;
108     this.issueManager = new WebInspector.IssueManager;
109     this.analyzerManager = new WebInspector.AnalyzerManager;
110     this.runtimeManager = new WebInspector.RuntimeManager;
111     this.applicationCacheManager = new WebInspector.ApplicationCacheManager;
112     this.timelineManager = new WebInspector.TimelineManager;
113     this.debuggerManager = new WebInspector.DebuggerManager;
114     this.sourceMapManager = new WebInspector.SourceMapManager;
115     this.layerTreeManager = new WebInspector.LayerTreeManager;
116     this.dashboardManager = new WebInspector.DashboardManager;
117     this.probeManager = new WebInspector.ProbeManager;
118     this.replayManager = new WebInspector.ReplayManager;
119
120     // Enable the Console Agent after creating the singleton managers.
121     if (window.ConsoleAgent)
122         ConsoleAgent.enable();
123
124     // Tell the backend we are initialized after all our initialization messages have been sent.
125     setTimeout(function() {
126         if (window.InspectorAgent && InspectorAgent.initialized)
127             InspectorAgent.initialized();
128     }, 0);
129
130     // Register for events.
131     this.replayManager.addEventListener(WebInspector.ReplayManager.Event.CaptureStarted, this._captureDidStart, this);
132     this.debuggerManager.addEventListener(WebInspector.DebuggerManager.Event.Paused, this._debuggerDidPause, this);
133     this.debuggerManager.addEventListener(WebInspector.DebuggerManager.Event.Resumed, this._debuggerDidResume, this);
134     this.domTreeManager.addEventListener(WebInspector.DOMTreeManager.Event.InspectModeStateChanged, this._inspectModeStateChanged, this);
135     this.domTreeManager.addEventListener(WebInspector.DOMTreeManager.Event.DOMNodeWasInspected, this._domNodeWasInspected, this);
136     this.storageManager.addEventListener(WebInspector.StorageManager.Event.DOMStorageObjectWasInspected, this._storageWasInspected, this);
137     this.storageManager.addEventListener(WebInspector.StorageManager.Event.DatabaseWasInspected, this._storageWasInspected, this);
138     this.frameResourceManager.addEventListener(WebInspector.FrameResourceManager.Event.MainFrameDidChange, this._mainFrameDidChange, this);
139     this.frameResourceManager.addEventListener(WebInspector.FrameResourceManager.Event.FrameWasAdded, this._frameWasAdded, this);
140
141     WebInspector.Frame.addEventListener(WebInspector.Frame.Event.MainResourceDidChange, this._mainResourceDidChange, this);
142
143     document.addEventListener("DOMContentLoaded", this.contentLoaded.bind(this));
144
145     // Create settings.
146     this._showingSplitConsoleSetting = new WebInspector.Setting("showing-split-console", false);
147     this._splitConsoleHeightSetting = new WebInspector.Setting("split-console-height", 150);
148
149     this._openTabsSetting = new WebInspector.Setting("open-tabs", ["elements", "resources", "timeline", "debugger", "storage", "console"]);
150     this._selectedTabIndexSetting = new WebInspector.Setting("selected-tab-index", 0);
151
152     this.showShadowDOMSetting = new WebInspector.Setting("show-shadow-dom", false);
153     this.showReplayInterfaceSetting = new WebInspector.Setting("show-web-replay", false);
154
155     this.showJavaScriptTypeInformationSetting = new WebInspector.Setting("show-javascript-type-information", false);
156     if (this.showJavaScriptTypeInformationSetting.value && window.RuntimeAgent && RuntimeAgent.enableTypeProfiler)
157         RuntimeAgent.enableTypeProfiler();
158
159     this.showPaintRectsSetting = new WebInspector.Setting("show-paint-rects", false);
160     if (this.showPaintRectsSetting.value && window.PageAgent && PageAgent.setShowPaintRects)
161         PageAgent.setShowPaintRects(true);
162
163     this.mouseCoords = {
164         x: 0,
165         y: 0
166     };
167
168     this._windowKeydownListeners = [];
169 };
170
171 WebInspector.contentLoaded = function()
172 {
173     // Register for global events.
174     document.addEventListener("beforecopy", this._beforecopy.bind(this));
175     document.addEventListener("copy", this._copy.bind(this));
176
177     document.addEventListener("click", this._mouseWasClicked.bind(this));
178     document.addEventListener("dragover", this._dragOver.bind(this));
179     document.addEventListener("focus", WebInspector._focusChanged.bind(this), true);
180
181     window.addEventListener("focus", this._windowFocused.bind(this));
182     window.addEventListener("blur", this._windowBlurred.bind(this));
183     window.addEventListener("resize", this._windowResized.bind(this));
184     window.addEventListener("keydown", this._windowKeyDown.bind(this));
185     window.addEventListener("keyup", this._windowKeyUp.bind(this));
186     window.addEventListener("mousemove", this._mouseMoved.bind(this), true);
187     window.addEventListener("pagehide", this._pageHidden.bind(this));
188
189     // Add platform style classes so the UI can be tweaked per-platform.
190     document.body.classList.add(WebInspector.Platform.name + "-platform");
191     if (WebInspector.Platform.isNightlyBuild)
192         document.body.classList.add("nightly-build");
193     if (WebInspector.Platform.version.name)
194         document.body.classList.add(WebInspector.Platform.version.name);
195
196     document.body.classList.add(this.debuggableType);
197
198     // Create the user interface elements.
199     this.toolbar = new WebInspector.Toolbar(document.getElementById("toolbar"), null, true);
200     this.toolbar.displayMode = WebInspector.Toolbar.DisplayMode.IconOnly;
201     this.toolbar.sizeMode = WebInspector.Toolbar.SizeMode.Small;
202
203     this.tabBar = new WebInspector.TabBar(document.getElementById("tab-bar"));
204     this.tabBar.addEventListener(WebInspector.TabBar.Event.NewTabItemClicked, this._newTabItemClicked, this);
205
206     var contentElement = document.getElementById("content");
207     contentElement.setAttribute("role", "main");
208     contentElement.setAttribute("aria-label", WebInspector.UIString("Content"));
209
210     this.splitContentBrowser = new WebInspector.ContentBrowser(document.getElementById("split-content-browser"), this, true);
211     this.splitContentBrowser.navigationBar.element.addEventListener("mousedown", this._consoleResizerMouseDown.bind(this));
212
213     this.quickConsole = new WebInspector.QuickConsole(document.getElementById("quick-console"));
214     this.quickConsole.addEventListener(WebInspector.QuickConsole.Event.DidResize, this._quickConsoleDidResize, this);
215
216     this._consoleRepresentedObject = new WebInspector.LogObject;
217     this._consoleTreeElement = new WebInspector.LogTreeElement(this._consoleRepresentedObject);
218     this.consoleContentView = WebInspector.splitContentBrowser.contentViewForRepresentedObject(this._consoleRepresentedObject);
219     this.consoleLogViewController = this.consoleContentView.logViewController;
220
221     // FIXME: The sidebars should be flipped in RTL languages.
222     this.navigationSidebar = new WebInspector.Sidebar(document.getElementById("navigation-sidebar"), WebInspector.Sidebar.Sides.Left);
223     this.navigationSidebar.addEventListener(WebInspector.Sidebar.Event.WidthDidChange, this._sidebarWidthDidChange, this);
224
225     this.detailsSidebar = new WebInspector.Sidebar(document.getElementById("details-sidebar"), WebInspector.Sidebar.Sides.Right, null, null, WebInspector.UIString("Details"), true);
226     this.detailsSidebar.addEventListener(WebInspector.Sidebar.Event.WidthDidChange, this._sidebarWidthDidChange, this);
227
228     this.searchKeyboardShortcut = new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.CommandOrControl | WebInspector.KeyboardShortcut.Modifier.Shift, "F", this._focusSearchField.bind(this));
229
230     this.navigationSidebarKeyboardShortcut = new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.CommandOrControl, "0", this.toggleNavigationSidebar.bind(this));
231     this.detailsSidebarKeyboardShortcut = new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.CommandOrControl | WebInspector.KeyboardShortcut.Modifier.Option, "0", this.toggleDetailsSidebar.bind(this));
232
233     this.tabBrowser = new WebInspector.TabBrowser(document.getElementById("tab-browser"), this.tabBar, this.navigationSidebar, this.detailsSidebar);
234     this.tabBrowser.addEventListener(WebInspector.TabBrowser.Event.SelectedTabContentViewDidChange, this._tabBrowserSelectedTabContentViewDidChange, this);
235
236     this.tabBar.addEventListener(WebInspector.TabBar.Event.TabBarItemAdded, this._updateNewTabButtonState, this);
237     this.tabBar.addEventListener(WebInspector.TabBar.Event.TabBarItemRemoved, this._updateNewTabButtonState, this);
238
239     this._reloadPageKeyboardShortcut = new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.CommandOrControl, "R", this._reloadPage.bind(this));
240     this._reloadPageIgnoringCacheKeyboardShortcut = new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.CommandOrControl | WebInspector.KeyboardShortcut.Modifier.Shift, "R", this._reloadPageIgnoringCache.bind(this));
241
242     this._consoleKeyboardShortcut = new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.Option | WebInspector.KeyboardShortcut.Modifier.CommandOrControl, "C", this._showConsoleTab.bind(this));
243
244     this._inspectModeKeyboardShortcut = new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.CommandOrControl | WebInspector.KeyboardShortcut.Modifier.Shift, "C", this._toggleInspectMode.bind(this));
245
246     this._undoKeyboardShortcut = new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.CommandOrControl, "Z", this._undoKeyboardShortcut.bind(this));
247     this._redoKeyboardShortcut = new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.CommandOrControl | WebInspector.KeyboardShortcut.Modifier.Shift, "Z", this._redoKeyboardShortcut.bind(this));
248     this._undoKeyboardShortcut.implicitlyPreventsDefault = this._redoKeyboardShortcut.implicitlyPreventsDefault = false;
249
250     this.toggleBreakpointsKeyboardShortcut = new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.CommandOrControl, "Y", this.debuggerToggleBreakpoints.bind(this));
251     this.pauseOrResumeKeyboardShortcut = new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.Control | WebInspector.KeyboardShortcut.Modifier.CommandOrControl, "Y", this.debuggerPauseResumeToggle.bind(this));
252     this.stepOverKeyboardShortcut = new WebInspector.KeyboardShortcut(null, WebInspector.KeyboardShortcut.Key.F6, this.debuggerStepOver.bind(this));
253     this.stepIntoKeyboardShortcut = new WebInspector.KeyboardShortcut(null, WebInspector.KeyboardShortcut.Key.F7, this.debuggerStepInto.bind(this));
254     this.stepOutKeyboardShortcut = new WebInspector.KeyboardShortcut(null, WebInspector.KeyboardShortcut.Key.F8, this.debuggerStepOut.bind(this));
255
256     this.pauseOrResumeAlternateKeyboardShortcut = new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.CommandOrControl, WebInspector.KeyboardShortcut.Key.Backslash, this.debuggerPauseResumeToggle.bind(this));
257     this.stepOverAlternateKeyboardShortcut = new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.CommandOrControl, WebInspector.KeyboardShortcut.Key.SingleQuote, this.debuggerStepOver.bind(this));
258     this.stepIntoAlternateKeyboardShortcut = new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.CommandOrControl, WebInspector.KeyboardShortcut.Key.Semicolon, this.debuggerStepInto.bind(this));
259     this.stepOutAlternateKeyboardShortcut = new WebInspector.KeyboardShortcut(WebInspector.KeyboardShortcut.Modifier.Shift | WebInspector.KeyboardShortcut.Modifier.CommandOrControl, WebInspector.KeyboardShortcut.Key.Semicolon, this.debuggerStepOut.bind(this));
260
261     this._closeToolbarButton = new WebInspector.ControlToolbarItem("dock-close", WebInspector.UIString("Close"), "Images/Close.svg", 16, 14);
262     this._closeToolbarButton.addEventListener(WebInspector.ButtonNavigationItem.Event.Clicked, this.close, this);
263
264     this._undockToolbarButton = new WebInspector.ButtonToolbarItem("undock", WebInspector.UIString("Detach into separate window"), null, "Images/Undock.svg");
265     this._undockToolbarButton.addEventListener(WebInspector.ButtonNavigationItem.Event.Clicked, this._undock, this);
266
267     this._dockRightToolbarButton = new WebInspector.ButtonToolbarItem("dock-right", WebInspector.UIString("Dock to right of window"), null, "Images/DockRight.svg");
268     this._dockRightToolbarButton.addEventListener(WebInspector.ButtonNavigationItem.Event.Clicked, this._dockRight, this);
269
270     this._dockBottomToolbarButton = new WebInspector.ButtonToolbarItem("dock-bottom", WebInspector.UIString("Dock to bottom of window"), null, "Images/DockBottom.svg");
271     this._dockBottomToolbarButton.addEventListener(WebInspector.ButtonNavigationItem.Event.Clicked, this._dockBottom, this);
272
273     var toolTip;
274     if (WebInspector.debuggableType === WebInspector.DebuggableType.JavaScript)
275         toolTip = WebInspector.UIString("Restart (%s)").format(this._reloadPageKeyboardShortcut.displayName);
276     else
277         toolTip = WebInspector.UIString("Reload page (%s)\nReload ignoring cache (%s)").format(this._reloadPageKeyboardShortcut.displayName, this._reloadPageIgnoringCacheKeyboardShortcut.displayName);
278
279     this._reloadToolbarButton = new WebInspector.ButtonToolbarItem("reload", toolTip, null, "Images/ReloadToolbar.svg");
280     this._reloadToolbarButton.addEventListener(WebInspector.ButtonNavigationItem.Event.Clicked, this._reloadPageClicked, this);
281
282     this._downloadToolbarButton = new WebInspector.ButtonToolbarItem("download", WebInspector.UIString("Download Web Archive"), null, "Images/DownloadArrow.svg");
283     this._downloadToolbarButton.addEventListener(WebInspector.ButtonNavigationItem.Event.Clicked, this._downloadWebArchive, this);
284
285     this._updateReloadToolbarButton();
286     this._updateDownloadToolbarButton();
287
288     // The toolbar button for node inspection.
289     if (this.debuggableType === WebInspector.DebuggableType.Web) {
290         var toolTip = WebInspector.UIString("Enable point to inspect mode (%s)").format(WebInspector._inspectModeKeyboardShortcut.displayName);
291         var activatedToolTip = WebInspector.UIString("Disable point to inspect mode (%s)").format(WebInspector._inspectModeKeyboardShortcut.displayName);
292         this._inspectModeToolbarButton = new WebInspector.ActivateButtonToolbarItem("inspect", toolTip, activatedToolTip, null, "Images/Crosshair.svg");
293         this._inspectModeToolbarButton.addEventListener(WebInspector.ButtonNavigationItem.Event.Clicked, this._toggleInspectMode, this);
294     }
295
296     this._dashboardContainer = new WebInspector.DashboardContainerView;
297     this._dashboardContainer.showDashboardViewForRepresentedObject(this.dashboardManager.dashboards.default);
298
299     this._searchToolbarItem = new WebInspector.SearchBar("inspector-search", WebInspector.UIString("Search"), null, true);
300     this._searchToolbarItem.addEventListener(WebInspector.SearchBar.Event.TextChanged, this._searchTextDidChange, this);
301
302     this.toolbar.addToolbarItem(this._closeToolbarButton, WebInspector.Toolbar.Section.Control);
303
304     this.toolbar.addToolbarItem(this._undockToolbarButton, WebInspector.Toolbar.Section.Left);
305     this.toolbar.addToolbarItem(this._dockRightToolbarButton, WebInspector.Toolbar.Section.Left);
306     this.toolbar.addToolbarItem(this._dockBottomToolbarButton, WebInspector.Toolbar.Section.Left);
307
308     this.toolbar.addToolbarItem(this._reloadToolbarButton, WebInspector.Toolbar.Section.CenterLeft);
309     this.toolbar.addToolbarItem(this._downloadToolbarButton, WebInspector.Toolbar.Section.CenterLeft);
310
311     this.toolbar.addToolbarItem(this._dashboardContainer.toolbarItem, WebInspector.Toolbar.Section.Center);
312
313     if (this._inspectModeToolbarButton)
314         this.toolbar.addToolbarItem(this._inspectModeToolbarButton, WebInspector.Toolbar.Section.CenterRight);
315
316     this.toolbar.addToolbarItem(this._searchToolbarItem, WebInspector.Toolbar.Section.Right);
317
318     this.resourceDetailsSidebarPanel = new WebInspector.ResourceDetailsSidebarPanel;
319     this.domNodeDetailsSidebarPanel = new WebInspector.DOMNodeDetailsSidebarPanel;
320     this.cssStyleDetailsSidebarPanel = new WebInspector.CSSStyleDetailsSidebarPanel;
321     this.applicationCacheDetailsSidebarPanel = new WebInspector.ApplicationCacheDetailsSidebarPanel;
322     this.scopeChainDetailsSidebarPanel = new WebInspector.ScopeChainDetailsSidebarPanel;
323     this.probeDetailsSidebarPanel = new WebInspector.ProbeDetailsSidebarPanel;
324
325     if (window.LayerTreeAgent)
326         this.layerTreeDetailsSidebarPanel = new WebInspector.LayerTreeDetailsSidebarPanel;
327
328     this.modifierKeys = {altKey: false, metaKey: false, shiftKey: false};
329
330     this.toolbar.element.addEventListener("mousedown", this._toolbarMouseDown.bind(this));
331     document.getElementById("docked-resizer").addEventListener("mousedown", this._dockedResizerMouseDown.bind(this));
332
333     this._dockingAvailable = false;
334
335     this._updateDockNavigationItems();
336     this._updateToolbarHeight();
337
338     this._pendingOpenTabTypes = [];
339
340     for (var tabType of this._openTabsSetting.value) {
341         if (!this.isTabTypeAllowed(tabType)) {
342             this._pendingOpenTabTypes.push(tabType);
343             continue;
344         }
345
346         var tabContentView = this._tabContentViewForType(tabType);
347         if (!tabContentView)
348             continue;
349         this.tabBrowser.addTabForContentView(tabContentView, true);
350     }
351
352     this._restoreCookieForOpenTabs(WebInspector.StateRestorationType.Load);
353
354     this.tabBar.selectedTabBarItem = this._selectedTabIndexSetting.value;
355
356     if (!this.tabBar.selectedTabBarItem)
357         this.tabBar.selectedTabBarItem = 0;
358
359     // Listen to the events after restoring the saved tabs to avoid recursion.
360     this.tabBar.addEventListener(WebInspector.TabBar.Event.TabBarItemAdded, this._rememberOpenTabs, this);
361     this.tabBar.addEventListener(WebInspector.TabBar.Event.TabBarItemRemoved, this._rememberOpenTabs, this);
362     this.tabBar.addEventListener(WebInspector.TabBar.Event.TabBarItemsReordered, this._rememberOpenTabs, this);
363
364     // Signal that the frontend is now ready to receive messages.
365     InspectorFrontendAPI.loadCompleted();
366
367     // Tell the InspectorFrontendHost we loaded, which causes the window to display
368     // and pending InspectorFrontendAPI commands to be sent.
369     InspectorFrontendHost.loaded();
370
371     this._updateSplitConsoleHeight(this._splitConsoleHeightSetting.value);
372
373     if (this._showingSplitConsoleSetting.value)
374         this.showSplitConsole();
375
376     this._contentLoaded = true;
377
378     this.runBootstrapOperations();
379 };
380
381 WebInspector.isTabTypeAllowed = function(tabType)
382 {
383     switch (tabType) {
384     case WebInspector.ElementsTabContentView.Type:
385         return !!window.DOMAgent;
386     case WebInspector.StorageTabContentView.Type:
387         return !!window.DOMStorageAgent || !!window.DatabaseAgent || !!window.IndexedDBAgent;
388     case WebInspector.TimelineTabContentView.Type:
389         return !!window.TimelineAgent;
390     }
391
392     return true;
393 };
394
395 WebInspector._tabContentViewForType = function(tabType)
396 {
397     switch (tabType) {
398     case WebInspector.ConsoleTabContentView.Type:
399         return new WebInspector.ConsoleTabContentView;
400     case WebInspector.DebuggerTabContentView.Type:
401         return new WebInspector.DebuggerTabContentView;
402     case WebInspector.ElementsTabContentView.Type:
403         return new WebInspector.ElementsTabContentView;
404     case WebInspector.NewTabContentView.Type:
405         return new WebInspector.NewTabContentView;
406     case WebInspector.ResourcesTabContentView.Type:
407         return new WebInspector.ResourcesTabContentView;
408     case WebInspector.SearchTabContentView.Type:
409         return new WebInspector.SearchTabContentView;
410     case WebInspector.StorageTabContentView.Type:
411         return new WebInspector.StorageTabContentView;
412     case WebInspector.TimelineTabContentView.Type:
413         return new WebInspector.TimelineTabContentView;
414     default:
415         console.error("Unknown tab type", tabType);
416     }
417
418     return null;
419 };
420
421 WebInspector._rememberOpenTabs = function()
422 {
423     var openTabs = [];
424
425     for (var tabBarItem of this.tabBar.tabBarItems) {
426         var tabContentView = tabBarItem.representedObject;
427         if (!(tabContentView instanceof WebInspector.TabContentView))
428             continue;
429         if (tabContentView instanceof WebInspector.SettingsTabContentView || tabContentView instanceof WebInspector.NewTabContentView)
430             continue;
431         console.assert(tabContentView.type, "Tab type can't be null, undefined, or empty string", tabContentView.type, tabContentView);
432         openTabs.push(tabContentView.type);
433     }
434
435     this._openTabsSetting.value = openTabs;
436 };
437
438 WebInspector._updateNewTabButtonState = function(event)
439 {
440     var newTabAllowed = this.isNewTabWithTypeAllowed(WebInspector.ConsoleTabContentView.Type) || this.isNewTabWithTypeAllowed(WebInspector.ElementsTabContentView.Type)
441         || this.isNewTabWithTypeAllowed(WebInspector.ResourcesTabContentView.Type) || this.isNewTabWithTypeAllowed(WebInspector.StorageTabContentView.Type)
442         || this.isNewTabWithTypeAllowed(WebInspector.TimelineTabContentView.Type) || this.isNewTabWithTypeAllowed(WebInspector.DebuggerTabContentView.Type);
443     this.tabBar.newTabItem.disabled = !newTabAllowed;
444 };
445
446 WebInspector._newTabItemClicked = function(event)
447 {
448     var tabContentView = this.tabBrowser.bestTabContentViewForClass(WebInspector.NewTabContentView);
449     if (!tabContentView)
450         tabContentView = new WebInspector.NewTabContentView;
451     this.tabBrowser.showTabForContentView(tabContentView);
452 };
453
454 WebInspector.isNewTabWithTypeAllowed = function(tabType)
455 {
456     if (!this.isTabTypeAllowed(tabType))
457         return false;
458
459     // Only allow one tab per class for now.
460     for (var tabBarItem of this.tabBar.tabBarItems) {
461         var tabContentView = tabBarItem.representedObject;
462         if (!(tabContentView instanceof WebInspector.TabContentView))
463             continue;
464         if (tabContentView.type === tabType)
465             return false;
466     }
467
468     return true;
469 };
470
471 WebInspector.createNewTab = function(tabType, newTabContentViewToReplace)
472 {
473     console.assert(this.isNewTabWithTypeAllowed(tabType));
474
475     var tabContentView = this._tabContentViewForType(tabType);
476
477     if (newTabContentViewToReplace) {
478         var insertionIndex = this.tabBar.tabBarItems.indexOf(newTabContentViewToReplace.tabBarItem);
479         this.tabBrowser.closeTabForContentView(newTabContentViewToReplace, true);
480         this.tabBrowser.showTabForContentView(tabContentView, true, insertionIndex);
481         return;
482     }
483
484     this.tabBrowser.showTabForContentView(tabContentView);
485 };
486
487 WebInspector.activateExtraDomains = function(domains)
488 {
489     this.hasExtraDomains = true;
490
491     for (var domain of domains) {
492         var agent = InspectorBackend.activateDomain(domain);
493         if (agent.enable)
494             agent.enable();
495     }
496
497     this.notifications.dispatchEventToListeners(WebInspector.Notification.ExtraDomainsActivated, {"domains": domains});
498
499     WebInspector.CSSCompletions.requestCSSNameCompletions();
500
501     this._updateReloadToolbarButton();
502     this._updateDownloadToolbarButton();
503
504     var stillPendingOpenTabTypes = [];
505     for (var tabType of this._pendingOpenTabTypes) {
506         if (!this.isTabTypeAllowed(tabType)) {
507             stillPendingOpenTabTypes.push(tabType);
508             continue;
509         }
510
511         var tabContentView = this._tabContentViewForType(tabType);
512         if (!tabContentView)
513             continue;
514
515         this.tabBrowser.addTabForContentView(tabContentView, true);
516
517         tabContentView.restoreStateFromCookie(WebInspector.StateRestorationType.Load);
518     }
519
520     this._pendingOpenTabTypes = stillPendingOpenTabTypes;
521
522     this._updateNewTabButtonState();
523 };
524
525 WebInspector.contentBrowserTreeElementForRepresentedObject = function(contentBrowser, representedObject)
526 {
527     // The console does not have a sidebar, so return a tree element here so something is shown.
528     if (representedObject === this._consoleRepresentedObject)
529         return this._consoleTreeElement;
530     return null;
531 };
532
533 WebInspector.updateWindowTitle = function()
534 {
535     var mainFrame = this.frameResourceManager.mainFrame;
536     console.assert(mainFrame);
537
538     var urlComponents = mainFrame.mainResource.urlComponents;
539
540     var lastPathComponent;
541     try {
542         lastPathComponent = decodeURIComponent(urlComponents.lastPathComponent || "");
543     } catch (e) {
544         lastPathComponent = urlComponents.lastPathComponent;
545     }
546
547     // Build a title based on the URL components.
548     if (urlComponents.host && lastPathComponent)
549         var title = this.displayNameForHost(urlComponents.host) + " \u2014 " + lastPathComponent;
550     else if (urlComponents.host)
551         var title = this.displayNameForHost(urlComponents.host);
552     else if (lastPathComponent)
553         var title = lastPathComponent;
554     else
555         var title = mainFrame.url;
556
557     // The name "inspectedURLChanged" sounds like the whole URL is required, however this is only
558     // used for updating the window title and it can be any string.
559     InspectorFrontendHost.inspectedURLChanged(title);
560 };
561
562 WebInspector.updateDockingAvailability = function(available)
563 {
564     this._dockingAvailable = available;
565
566     this._updateDockNavigationItems();
567 };
568
569 WebInspector.updateDockedState = function(side)
570 {
571     if (this._dockSide === side)
572         return;
573
574     this._dockSide = side;
575
576     this.docked = side !== "undocked";
577
578     this._ignoreToolbarModeDidChangeEvents = true;
579
580     if (side === "bottom") {
581         document.body.classList.add("docked", "bottom");
582         document.body.classList.remove("window-inactive", "right");
583     } else if (side === "right") {
584         document.body.classList.add("docked", "right");
585         document.body.classList.remove("window-inactive", "bottom");
586     } else
587         document.body.classList.remove("docked", "right", "bottom");
588
589     this._ignoreToolbarModeDidChangeEvents = false;
590
591     this._updateDockNavigationItems();
592 };
593
594 WebInspector.handlePossibleLinkClick = function(event, frame, alwaysOpenExternally)
595 {
596     var anchorElement = event.target.enclosingNodeOrSelfWithNodeName("a");
597     if (!anchorElement || !anchorElement.href)
598         return false;
599
600     if (WebInspector.isBeingEdited(anchorElement)) {
601         // Don't follow the link when it is being edited.
602         return false;
603     }
604
605     // Prevent the link from navigating, since we don't do any navigation by following links normally.
606     event.preventDefault();
607     event.stopPropagation();
608
609     this.openURL(anchorElement.href, frame, false, anchorElement.lineNumber);
610
611     return true;
612 };
613
614 WebInspector.openURL = function(url, frame, alwaysOpenExternally, lineNumber)
615 {
616     console.assert(url);
617     if (!url)
618         return;
619
620     // If alwaysOpenExternally is not defined, base it off the command/meta key for the current event.
621     if (alwaysOpenExternally === undefined || alwaysOpenExternally === null)
622         alwaysOpenExternally = window.event ? window.event.metaKey : false;
623
624     if (alwaysOpenExternally) {
625         InspectorFrontendHost.openInNewTab(url);
626         return;
627     }
628
629     var searchChildFrames = false;
630     if (!frame) {
631         frame = this.frameResourceManager.mainFrame;
632         searchChildFrames = true;
633     }
634
635     console.assert(frame);
636
637     // WebInspector.Frame.resourceForURL does not check the main resource, only sub-resources. So check both.
638     var resource = frame.url === url ? frame.mainResource : frame.resourceForURL(url, searchChildFrames);
639     if (resource) {
640         var position = new WebInspector.SourceCodePosition(lineNumber, 0);
641         this.showSourceCode(resource, position);
642         return;
643     }
644
645     InspectorFrontendHost.openInNewTab(url);
646 };
647
648 WebInspector.close = function()
649 {
650     if (this._isClosing)
651         return;
652
653     this._isClosing = true;
654
655     InspectorFrontendHost.closeWindow();
656 };
657
658 WebInspector.saveDataToFile = function(saveData, forceSaveAs)
659 {
660     console.assert(saveData);
661     if (!saveData)
662         return;
663
664     if (typeof saveData.customSaveHandler === "function") {
665         saveData.customSaveHandler(forceSaveAs);
666         return;
667     }
668
669     console.assert(saveData.url);
670     console.assert(typeof saveData.content === "string");
671     if (!saveData.url || typeof saveData.content !== "string")
672         return;
673
674     InspectorFrontendHost.save(saveData.url, saveData.content, false, forceSaveAs || saveData.forceSaveAs);
675 };
676
677 WebInspector.isConsoleFocused = function()
678 {
679     return this.quickConsole.prompt.focused;
680 };
681
682 WebInspector.isShowingSplitConsole = function()
683 {
684     return !this.splitContentBrowser.element.classList.contains("hidden");
685 };
686
687 WebInspector.doesCurrentTabSupportSplitContentBrowser = function()
688 {
689     var currentContentView = this.tabBrowser.selectedTabContentView;
690     return !currentContentView || currentContentView.supportsSplitContentBrowser;
691 };
692
693 WebInspector.toggleSplitConsole = function()
694 {
695     if (!this.doesCurrentTabSupportSplitContentBrowser()) {
696         this.showConsoleTab();
697         return;
698     }
699
700     if (this.isShowingSplitConsole())
701         this.hideSplitConsole();
702     else
703         this.showSplitConsole();
704 };
705
706 WebInspector.showSplitConsole = function()
707 {
708     if (!this.doesCurrentTabSupportSplitContentBrowser()) {
709         this.showConsoleTab();
710         return;
711     }
712
713     this.splitContentBrowser.element.classList.remove("hidden");
714
715     this._showingSplitConsoleSetting.value = true;
716
717     if (this.splitContentBrowser.currentContentView !== this.consoleContentView) {
718         // Be sure to close the view in the tab content browser before showing it in the
719         // split content browser. We can only show a content view in one browser at a time.
720         if (this.consoleContentView.parentContainer)
721             this.consoleContentView.parentContainer.closeContentView(this.consoleContentView);
722         this.splitContentBrowser.showContentView(this.consoleContentView);
723     } else {
724         // This causes the view to know it was shown and focus the prompt.
725         this.splitContentBrowser.shown();
726     }
727
728     this.quickConsole.consoleLogVisibilityChanged(true);
729 };
730
731 WebInspector.hideSplitConsole = function()
732 {
733     if (!this.isShowingSplitConsole())
734         return;
735
736     this.splitContentBrowser.element.classList.add("hidden");
737
738     this._showingSplitConsoleSetting.value = false;
739
740     // This causes the view to know it was hidden.
741     this.splitContentBrowser.hidden();
742
743     this.quickConsole.consoleLogVisibilityChanged(false);
744 };
745
746 WebInspector.showConsoleTab = function(requestedScope)
747 {
748     this.hideSplitConsole();
749
750     var scope = requestedScope || WebInspector.LogContentView.Scopes.All;
751
752     // If the requested scope is already selected and the console is showing, then switch back to All.
753     if (this.isShowingConsoleTab() && this.consoleContentView.scopeBar.item(scope).selected)
754         scope = WebInspector.LogContentView.Scopes.All;
755
756     if (requestedScope || !this.consoleContentView.scopeBar.selectedItems.length)
757         this.consoleContentView.scopeBar.item(scope).selected = true;
758
759     this.showRepresentedObject(this._consoleRepresentedObject);
760
761     console.assert(this.isShowingConsoleTab());
762 };
763
764 WebInspector.isShowingConsoleTab = function()
765 {
766     return this.tabBrowser.selectedTabContentView instanceof WebInspector.ConsoleTabContentView;
767 };
768
769 WebInspector.showElementsTab = function()
770 {
771     var tabContentView = this.tabBrowser.bestTabContentViewForClass(WebInspector.ElementsTabContentView);
772     if (!tabContentView)
773         tabContentView = new WebInspector.ElementsTabContentView;
774     this.tabBrowser.showTabForContentView(tabContentView);
775 };
776
777 WebInspector.showDebuggerTab = function(breakpointToSelect, showScopeChainDetailsSidebarPanel)
778 {
779     var tabContentView = this.tabBrowser.bestTabContentViewForClass(WebInspector.DebuggerTabContentView);
780     if (!tabContentView)
781         tabContentView = new WebInspector.DebuggerTabContentView;
782
783     if (breakpointToSelect instanceof WebInspector.Breakpoint)
784         tabContentView.revealAndSelectBreakpoint(breakpointToSelect);
785
786     if (showScopeChainDetailsSidebarPanel)
787         tabContentView.showScopeChainDetailsSidebarPanel();
788
789     this.tabBrowser.showTabForContentView(tabContentView);
790 };
791
792 WebInspector.showResourcesTab = function()
793 {
794     var tabContentView = this.tabBrowser.bestTabContentViewForClass(WebInspector.ResourcesTabContentView);
795     if (!tabContentView)
796         tabContentView = new WebInspector.ResourcesTabContentView;
797     this.tabBrowser.showTabForContentView(tabContentView);
798 };
799
800 WebInspector.showStorageTab = function()
801 {
802     var tabContentView = this.tabBrowser.bestTabContentViewForClass(WebInspector.StorageTabContentView);
803     if (!tabContentView)
804         tabContentView = new WebInspector.StorageTabContentView;
805     this.tabBrowser.showTabForContentView(tabContentView);
806 };
807
808 WebInspector.showTimelineTab = function()
809 {
810     var tabContentView = this.tabBrowser.bestTabContentViewForClass(WebInspector.TimelineTabContentView);
811     if (!tabContentView)
812         tabContentView = new WebInspector.TimelineTabContentView;
813     this.tabBrowser.showTabForContentView(tabContentView);
814 };
815
816 WebInspector.UIString = function(string, vararg)
817 {
818     if (WebInspector.dontLocalizeUserInterface)
819         return string;
820
821     if (window.localizedStrings && string in window.localizedStrings)
822         return window.localizedStrings[string];
823
824     if (!this._missingLocalizedStrings)
825         this._missingLocalizedStrings = {};
826
827     if (!(string in this._missingLocalizedStrings)) {
828         console.error("Localized string \"" + string + "\" was not found.");
829         this._missingLocalizedStrings[string] = true;
830     }
831
832     return "LOCALIZED STRING NOT FOUND";
833 };
834
835 WebInspector.restoreFocusFromElement = function(element)
836 {
837     if (element && element.isSelfOrAncestor(this.currentFocusElement))
838         this.previousFocusElement.focus();
839 };
840
841 WebInspector.toggleNavigationSidebar = function(event)
842 {
843     if (!this.navigationSidebar.collapsed || !this.navigationSidebar.sidebarPanels.length) {
844         this.navigationSidebar.collapsed = true;
845         return;
846     }
847
848     if (!this.navigationSidebar.selectedSidebarPanel)
849         this.navigationSidebar.selectedSidebarPanel = this.navigationSidebar.sidebarPanels[0];
850     this.navigationSidebar.collapsed = false;
851 };
852
853 WebInspector.toggleDetailsSidebar = function(event)
854 {
855     if (!this.detailsSidebar.collapsed || !this.detailsSidebar.sidebarPanels.length) {
856         this.detailsSidebar.collapsed = true;
857         return;
858     }
859
860     if (!this.detailsSidebar.selectedSidebarPanel)
861         this.detailsSidebar.selectedSidebarPanel = this.detailsSidebar.sidebarPanels[0];
862     this.detailsSidebar.collapsed = false;
863 };
864
865 WebInspector.tabContentViewClassForRepresentedObject = function(representedObject)
866 {
867     if (representedObject instanceof WebInspector.DOMTree)
868         return WebInspector.ElementsTabContentView;
869
870     if (representedObject instanceof WebInspector.TimelineRecording)
871         return WebInspector.TimelineTabContentView;
872
873     // We only support one console tab right now. So this isn't an instanceof check.
874     if (representedObject === this._consoleRepresentedObject)
875         return WebInspector.ConsoleTabContentView;
876
877     if (WebInspector.debuggerManager.paused) {
878         if (representedObject instanceof WebInspector.Script)
879             return WebInspector.DebuggerTabContentView;
880
881         if (representedObject instanceof WebInspector.Resource && (representedObject.type === WebInspector.Resource.Type.Document || representedObject.type === WebInspector.Resource.Type.Script))
882             return WebInspector.DebuggerTabContentView;
883     }
884
885     if (representedObject instanceof WebInspector.Frame || representedObject instanceof WebInspector.Resource || representedObject instanceof WebInspector.Script)
886         return WebInspector.ResourcesTabContentView;
887
888     // FIXME: Move Content Flows to the Elements tab?
889     if (representedObject instanceof WebInspector.ContentFlow)
890         return WebInspector.ResourcesTabContentView;
891
892     // FIXME: Move these to a Storage tab.
893     if (representedObject instanceof WebInspector.DOMStorageObject || representedObject instanceof WebInspector.CookieStorageObject ||
894         representedObject instanceof WebInspector.DatabaseTableObject || representedObject instanceof WebInspector.DatabaseObject ||
895         representedObject instanceof WebInspector.ApplicationCacheFrame || representedObject instanceof WebInspector.IndexedDatabaseObjectStore ||
896         representedObject instanceof WebInspector.IndexedDatabaseObjectStoreIndex)
897         return WebInspector.ResourcesTabContentView;
898
899     return null;
900 };
901
902 WebInspector.tabContentViewForRepresentedObject = function(representedObject)
903 {
904     var tabContentView = this.tabBrowser.bestTabContentViewForRepresentedObject(representedObject);
905     if (tabContentView)
906         return tabContentView;
907
908     var tabContentViewClass = this.tabContentViewClassForRepresentedObject(representedObject);
909     if (!tabContentViewClass) {
910         console.error("Unknown representedObject, couldn't create TabContentView.", representedObject);
911         return null;
912     }
913
914     tabContentView = new tabContentViewClass;
915
916     this.tabBrowser.addTabForContentView(tabContentView);
917
918     return tabContentView;
919 };
920
921 WebInspector.showRepresentedObject = function(representedObject, cookie, forceShowTab)
922 {
923     var tabContentView = this.tabContentViewForRepresentedObject(representedObject);
924     console.assert(tabContentView);
925     if (!tabContentView)
926         return;
927
928     if (window.event || forceShowTab)
929         this.tabBrowser.showTabForContentView(tabContentView);
930
931     tabContentView.showRepresentedObject(representedObject, cookie);
932 };
933
934 WebInspector.showMainFrameDOMTree = function(nodeToSelect, forceShowTab)
935 {
936     console.assert(WebInspector.frameResourceManager.mainFrame);
937     if (!WebInspector.frameResourceManager.mainFrame)
938         return;
939     this.showRepresentedObject(WebInspector.frameResourceManager.mainFrame.domTree, {nodeToSelect}, forceShowTab);
940 };
941
942 WebInspector.showContentFlowDOMTree = function(contentFlow, nodeToSelect, forceShowTab)
943 {
944     this.showRepresentedObject(contentFlow, {nodeToSelect}, forceShowTab);
945 };
946
947 WebInspector.showSourceCodeForFrame = function(frameIdentifier, forceShowTab)
948 {
949     var frame = WebInspector.frameResourceManager.frameForIdentifier(frameIdentifier);
950     if (!frame) {
951         this._frameIdentifierToShowSourceCodeWhenAvailable = frameIdentifier;
952         return;
953     }
954
955     this._frameIdentifierToShowSourceCodeWhenAvailable = undefined;
956
957     this.showRepresentedObject(frame, null, forceShowTab);
958 };
959
960 WebInspector.showSourceCode = function(sourceCode, positionToReveal, textRangeToSelect, forceUnformatted, forceShowTab)
961 {
962     console.assert(!positionToReveal || positionToReveal instanceof WebInspector.SourceCodePosition, positionToReveal);
963     var representedObject = sourceCode;
964
965     if (representedObject instanceof WebInspector.Script) {
966         // A script represented by a resource should always show the resource.
967         representedObject = representedObject.resource || representedObject;
968     }
969
970     var cookie = positionToReveal ? {lineNumber: positionToReveal.lineNumber, columnNumber: positionToReveal.columnNumber} : {};
971     this.showRepresentedObject(representedObject, cookie, forceShowTab);
972 };
973
974 WebInspector.showSourceCodeLocation = function(sourceCodeLocation, forceShowTab)
975 {
976     this.showSourceCode(sourceCodeLocation.displaySourceCode, sourceCodeLocation.displayPosition(), null, false, forceShowTab);
977 };
978
979 WebInspector.showOriginalUnformattedSourceCodeLocation = function(sourceCodeLocation, forceShowTab)
980 {
981     this.showSourceCode(sourceCodeLocation.sourceCode, sourceCodeLocation.position(), null, true);
982 };
983
984 WebInspector.showOriginalOrFormattedSourceCodeLocation = function(sourceCodeLocation, forceShowTab)
985 {
986     this.showSourceCode(sourceCodeLocation.sourceCode, sourceCodeLocation.formattedPosition(), null, false, forceShowTab);
987 };
988
989 WebInspector.showOriginalOrFormattedSourceCodeTextRange = function(sourceCodeTextRange, forceShowTab)
990 {
991     var textRangeToSelect = sourceCodeTextRange.formattedTextRange;
992     this.showSourceCode(sourceCodeTextRange.sourceCode, textRangeToSelect.startPosition(), textRangeToSelect, false, forceShowTab);
993 };
994
995 WebInspector.showResourceRequest = function(resource, forceShowTab)
996 {
997     this.showRepresentedObject(resource, {[WebInspector.ResourceClusterContentView.ContentViewIdentifierCookieKey]: WebInspector.ResourceClusterContentView.RequestIdentifier}, forceShowTab);
998 };
999
1000 WebInspector.debuggerToggleBreakpoints = function(event)
1001 {
1002     WebInspector.debuggerManager.breakpointsEnabled = !WebInspector.debuggerManager.breakpointsEnabled;
1003 };
1004
1005 WebInspector.debuggerPauseResumeToggle = function(event)
1006 {
1007     if (WebInspector.debuggerManager.paused)
1008         WebInspector.debuggerManager.resume();
1009     else
1010         WebInspector.debuggerManager.pause();
1011 };
1012
1013 WebInspector.debuggerStepOver = function(event)
1014 {
1015     WebInspector.debuggerManager.stepOver();
1016 };
1017
1018 WebInspector.debuggerStepInto = function(event)
1019 {
1020     WebInspector.debuggerManager.stepInto();
1021 };
1022
1023 WebInspector.debuggerStepOut = function(event)
1024 {
1025     WebInspector.debuggerManager.stepOut();
1026 };
1027
1028 WebInspector._searchTextDidChange = function(event)
1029 {
1030     var tabContentView = this.tabBrowser.bestTabContentViewForClass(WebInspector.SearchTabContentView);
1031     if (!tabContentView)
1032         tabContentView = new WebInspector.SearchTabContentView;
1033
1034     var searchQuery = this._searchToolbarItem.text;
1035     this._searchToolbarItem.text = "";
1036
1037     this.tabBrowser.showTabForContentView(tabContentView);
1038
1039     tabContentView.performSearch(searchQuery);
1040 };
1041
1042 WebInspector._focusSearchField = function(event)
1043 {
1044     if (this.tabBrowser.selectedTabContentView instanceof WebInspector.SearchTabContentView) {
1045         this.tabBrowser.selectedTabContentView.focusSearchField();
1046         return;
1047     }
1048
1049     this._searchToolbarItem.focus();
1050 };
1051
1052 WebInspector._focusChanged = function(event)
1053 {
1054     // Make a caret selection inside the focused element if there isn't a range selection and there isn't already
1055     // a caret selection inside. This is needed (at least) to remove caret from console when focus is moved.
1056     // The selection change should not apply to text fields and text areas either.
1057
1058     if (WebInspector.isEventTargetAnEditableField(event))
1059         return;
1060
1061     var selection = window.getSelection();
1062     if (!selection.isCollapsed)
1063         return;
1064
1065     var element = event.target;
1066
1067     if (element !== this.currentFocusElement) {
1068         this.previousFocusElement = this.currentFocusElement;
1069         this.currentFocusElement = element;
1070     }
1071
1072     if (element.isInsertionCaretInside())
1073         return;
1074
1075     var selectionRange = element.ownerDocument.createRange();
1076     selectionRange.setStart(element, 0);
1077     selectionRange.setEnd(element, 0);
1078
1079     selection.removeAllRanges();
1080     selection.addRange(selectionRange);
1081 };
1082
1083 WebInspector._mouseWasClicked = function(event)
1084 {
1085     this.handlePossibleLinkClick(event);
1086 };
1087
1088 WebInspector._dragOver = function(event)
1089 {
1090     // Do nothing if another event listener handled the event already.
1091     if (event.defaultPrevented)
1092         return;
1093
1094     // Allow dropping into editable areas.
1095     if (WebInspector.isEventTargetAnEditableField(event))
1096         return;
1097
1098     // Prevent the drop from being accepted.
1099     event.dataTransfer.dropEffect = "none";
1100     event.preventDefault();
1101 };
1102
1103 WebInspector._captureDidStart = function(event)
1104 {
1105     this._dashboardContainer.showDashboardViewForRepresentedObject(this.dashboardManager.dashboards.replay);
1106 };
1107
1108 WebInspector._debuggerDidPause = function(event)
1109 {
1110     this.showDebuggerTab(null, true);
1111
1112     this._dashboardContainer.showDashboardViewForRepresentedObject(this.dashboardManager.dashboards.debugger);
1113
1114     InspectorFrontendHost.bringToFront();
1115 };
1116
1117 WebInspector._debuggerDidResume = function(event)
1118 {
1119     this._dashboardContainer.closeDashboardViewForRepresentedObject(this.dashboardManager.dashboards.debugger);
1120 };
1121
1122 WebInspector._frameWasAdded = function(event)
1123 {
1124     if (!this._frameIdentifierToShowSourceCodeWhenAvailable)
1125         return;
1126
1127     var frame = event.data.frame;
1128     if (frame.id !== this._frameIdentifierToShowSourceCodeWhenAvailable)
1129         return;
1130
1131     function delayedWork()
1132     {
1133         this.showSourceCodeForFrame(frame.id, true);
1134     }
1135
1136     // Delay showing the frame since FrameWasAdded is called before MainFrameChanged.
1137     // Calling showSourceCodeForFrame before MainFrameChanged will show the frame then close it.
1138     setTimeout(delayedWork.bind(this));
1139 };
1140
1141 WebInspector._mainFrameDidChange = function(event)
1142 {
1143     this._updateDownloadToolbarButton();
1144
1145     this.updateWindowTitle();
1146 };
1147
1148 WebInspector._mainResourceDidChange = function(event)
1149 {
1150     if (!event.target.isMainFrame())
1151         return;
1152
1153     this._inProvisionalLoad = false;
1154
1155     // Run cookie restoration after we are sure all of the Tabs and NavigationSidebarPanels
1156     // have updated with respect to the main resource change.
1157     setTimeout(this._restoreCookieForOpenTabs.bind(this, WebInspector.StateRestorationType.Navigation));
1158
1159     this._updateDownloadToolbarButton();
1160
1161     this.updateWindowTitle();
1162 };
1163
1164 WebInspector._provisionalLoadStarted = function(event)
1165 {
1166     if (!event.target.isMainFrame())
1167         return;
1168
1169     this._saveCookieForOpenTabs();
1170
1171     this._inProvisionalLoad = true;
1172 };
1173
1174 WebInspector._restoreCookieForOpenTabs = function(restorationType)
1175 {
1176     for (var tabBarItem of this.tabBar.tabBarItems) {
1177         var tabContentView = tabBarItem.representedObject;
1178         if (!(tabContentView instanceof WebInspector.TabContentView))
1179             continue;
1180         tabContentView.restoreStateFromCookie(restorationType);
1181     }
1182 };
1183
1184 WebInspector._saveCookieForOpenTabs = function()
1185 {
1186     for (var tabBarItem of this.tabBar.tabBarItems) {
1187         var tabContentView = tabBarItem.representedObject;
1188         if (!(tabContentView instanceof WebInspector.TabContentView))
1189             continue;
1190         tabContentView.saveStateToCookie();
1191     }
1192 };
1193
1194 WebInspector._windowFocused = function(event)
1195 {
1196     if (event.target.document.nodeType !== Node.DOCUMENT_NODE || this.docked)
1197         return;
1198
1199     // FIXME: We should use the :window-inactive pseudo class once https://webkit.org/b/38927 is fixed.
1200     document.body.classList.remove("window-inactive");
1201 };
1202
1203 WebInspector._windowBlurred = function(event)
1204 {
1205     if (event.target.document.nodeType !== Node.DOCUMENT_NODE || this.docked)
1206         return;
1207
1208     // FIXME: We should use the :window-inactive pseudo class once https://webkit.org/b/38927 is fixed.
1209     document.body.classList.add("window-inactive");
1210 };
1211
1212 WebInspector._windowResized = function(event)
1213 {
1214     this.toolbar.updateLayout();
1215     this._tabBrowserSizeDidChange();
1216 };
1217
1218 WebInspector._updateModifierKeys = function(event)
1219 {
1220     var didChange = this.modifierKeys.altKey !== event.altKey || this.modifierKeys.metaKey !== event.metaKey || this.modifierKeys.shiftKey !== event.shiftKey;
1221
1222     this.modifierKeys = {altKey: event.altKey, metaKey: event.metaKey, shiftKey: event.shiftKey};
1223
1224     if (didChange)
1225         this.notifications.dispatchEventToListeners(WebInspector.Notification.GlobalModifierKeysDidChange, event);
1226 };
1227
1228 WebInspector._windowKeyDown = function(event)
1229 {
1230     this._updateModifierKeys(event);
1231 };
1232
1233 WebInspector._windowKeyUp = function(event)
1234 {
1235     this._updateModifierKeys(event);
1236 };
1237
1238 WebInspector._mouseMoved = function(event)
1239 {
1240     this._updateModifierKeys(event);
1241     this.mouseCoords = {
1242         x: event.pageX,
1243         y: event.pageY
1244     };
1245 };
1246
1247 WebInspector._pageHidden = function(event)
1248 {
1249     this._saveCookieForOpenTabs();
1250 };
1251
1252 WebInspector._undock = function(event)
1253 {
1254     InspectorFrontendHost.requestSetDockSide("undocked");
1255 };
1256
1257 WebInspector._dockBottom = function(event)
1258 {
1259     InspectorFrontendHost.requestSetDockSide("bottom");
1260 };
1261
1262 WebInspector._dockRight = function(event)
1263 {
1264     InspectorFrontendHost.requestSetDockSide("right");
1265 };
1266
1267 WebInspector._updateDockNavigationItems = function()
1268 {
1269     if (this._dockingAvailable || this.docked) {
1270         this._closeToolbarButton.hidden = !this.docked;
1271         this._undockToolbarButton.hidden = this._dockSide === "undocked";
1272         this._dockBottomToolbarButton.hidden = this._dockSide === "bottom";
1273         this._dockRightToolbarButton.hidden = this._dockSide === "right";
1274     } else {
1275         this._closeToolbarButton.hidden = true;
1276         this._undockToolbarButton.hidden = true;
1277         this._dockBottomToolbarButton.hidden = true;
1278         this._dockRightToolbarButton.hidden = true;
1279     }
1280 };
1281
1282 WebInspector._tabBrowserSizeDidChange = function()
1283 {
1284     this.tabBrowser.updateLayout();
1285     this.splitContentBrowser.updateLayout();
1286     this.quickConsole.updateLayout();
1287 };
1288
1289 WebInspector._quickConsoleDidResize = function(event)
1290 {
1291     this.tabBrowser.updateLayout();
1292 };
1293
1294 WebInspector._sidebarWidthDidChange = function(event)
1295 {
1296     this._tabBrowserSizeDidChange();
1297 };
1298
1299 WebInspector._updateToolbarHeight = function()
1300 {
1301     if (WebInspector.Platform.name === "mac" && WebInspector.Platform.version.release < 10)
1302         InspectorFrontendHost.setToolbarHeight(this.toolbar.element.offsetHeight);
1303 };
1304
1305 WebInspector._tabBrowserSelectedTabContentViewDidChange = function(event)
1306 {
1307     if (this.tabBar.selectedTabBarItem)
1308         this._selectedTabIndexSetting.value = this.tabBar.tabBarItems.indexOf(this.tabBar.selectedTabBarItem);
1309
1310     if (!this.doesCurrentTabSupportSplitContentBrowser())
1311         this.hideSplitConsole();
1312
1313     if (!this.isShowingSplitConsole())
1314         this.quickConsole.consoleLogVisibilityChanged(this.isShowingConsoleTab());
1315 };
1316
1317 WebInspector._initializeWebSocketIfNeeded = function()
1318 {
1319     if (!InspectorFrontendHost.initializeWebSocket)
1320         return;
1321
1322     var queryParams = parseLocationQueryParameters();
1323
1324     if ("ws" in queryParams)
1325         var url = "ws://" + queryParams.ws;
1326     else if ("page" in queryParams) {
1327         var page = queryParams.page;
1328         var host = "host" in queryParams ? queryParams.host : window.location.host;
1329         var url = "ws://" + host + "/devtools/page/" + page;
1330     }
1331
1332     if (!url)
1333         return;
1334
1335     InspectorFrontendHost.initializeWebSocket(url);
1336 };
1337
1338 WebInspector._updateSplitConsoleHeight = function(height)
1339 {
1340     const minimumHeight = 64;
1341     const maximumHeight = window.innerHeight * 0.55;
1342
1343     height = Math.max(minimumHeight, Math.min(height, maximumHeight));
1344
1345     this.splitContentBrowser.element.style.height = height + "px";
1346 };
1347
1348 WebInspector._consoleResizerMouseDown = function(event)
1349 {
1350     if (event.button !== 0 || event.ctrlKey)
1351         return;
1352
1353     // Only start dragging if the target is one of the elements that we expect.
1354     if (!event.target.classList.contains("navigation-bar") && !event.target.classList.contains("flexible-space"))
1355         return;
1356
1357     var resizerElement = event.target;
1358     var mouseOffset = resizerElement.offsetHeight - (event.pageY - resizerElement.totalOffsetTop);
1359
1360     function dockedResizerDrag(event)
1361     {
1362         if (event.button !== 0)
1363             return;
1364
1365         var height = window.innerHeight - event.pageY - mouseOffset;
1366
1367         this._splitConsoleHeightSetting.value = height;
1368
1369         this._updateSplitConsoleHeight(height);
1370
1371         this.quickConsole.dispatchEventToListeners(WebInspector.QuickConsole.Event.DidResize);
1372     }
1373
1374     function dockedResizerDragEnd(event)
1375     {
1376         if (event.button !== 0)
1377             return;
1378
1379         this.elementDragEnd(event);
1380     }
1381
1382     this.elementDragStart(resizerElement, dockedResizerDrag.bind(this), dockedResizerDragEnd.bind(this), event, "row-resize");
1383 };
1384
1385 WebInspector._toolbarMouseDown = function(event)
1386 {
1387     if (event.ctrlKey)
1388         return;
1389
1390     if (this._dockSide === "right")
1391         return;
1392
1393     if (this.docked)
1394         this._dockedResizerMouseDown(event);
1395     else
1396         this._moveWindowMouseDown(event);
1397 };
1398
1399 WebInspector._dockedResizerMouseDown = function(event)
1400 {
1401     if (event.button !== 0 || event.ctrlKey)
1402         return;
1403
1404     if (!this.docked)
1405         return;
1406
1407     // Only start dragging if the target is one of the elements that we expect.
1408     if (event.target.id !== "docked-resizer" && !event.target.classList.contains("toolbar") &&
1409         !event.target.classList.contains("flexible-space") && !event.target.classList.contains("item-section"))
1410         return;
1411
1412     var windowProperty = this._dockSide === "bottom" ? "innerHeight" : "innerWidth";
1413     var eventScreenProperty = this._dockSide === "bottom" ? "screenY" : "screenX";
1414     var eventClientProperty = this._dockSide === "bottom" ? "clientY" : "clientX";
1415
1416     var resizerElement = event.target;
1417     var firstClientPosition = event[eventClientProperty];
1418     var lastScreenPosition = event[eventScreenProperty];
1419
1420     function dockedResizerDrag(event)
1421     {
1422         if (event.button !== 0)
1423             return;
1424
1425         var position = event[eventScreenProperty];
1426         var delta = position - lastScreenPosition;
1427         var clientPosition = event[eventClientProperty];
1428
1429         lastScreenPosition = position;
1430
1431         // If delta is positive the docked Inspector size is decreasing, in which case the cursor client position
1432         // with respect to the target cannot be less than the first mouse down position within the target.
1433         if (delta > 0 && clientPosition < firstClientPosition)
1434             return;
1435
1436         // If delta is negative the docked Inspector size is increasing, in which case the cursor client position
1437         // with respect to the target cannot be greater than the first mouse down position within the target.
1438         if (delta < 0 && clientPosition > firstClientPosition)
1439             return;
1440
1441         var dimension = Math.max(0, window[windowProperty] - delta);
1442
1443         if (this._dockSide === "bottom")
1444             InspectorFrontendHost.setAttachedWindowHeight(dimension);
1445         else
1446             InspectorFrontendHost.setAttachedWindowWidth(dimension);
1447     }
1448
1449     function dockedResizerDragEnd(event)
1450     {
1451         if (event.button !== 0)
1452             return;
1453
1454         WebInspector.elementDragEnd(event);
1455     }
1456
1457     WebInspector.elementDragStart(resizerElement, dockedResizerDrag.bind(this), dockedResizerDragEnd.bind(this), event, this._dockSide === "bottom" ? "row-resize" : "col-resize");
1458 };
1459
1460 WebInspector._moveWindowMouseDown = function(event)
1461 {
1462     console.assert(!this.docked);
1463
1464     if (event.button !== 0 || event.ctrlKey)
1465         return;
1466
1467     // Only start dragging if the target is one of the elements that we expect.
1468     if (!event.target.classList.contains("toolbar") && !event.target.classList.contains("flexible-space") &&
1469         !event.target.classList.contains("item-section"))
1470         return;
1471
1472     if (WebInspector.Platform.name === "mac") {
1473         // New Mac releases can start a window drag.
1474         if (WebInspector.Platform.version.release >= 11) {
1475             InspectorFrontendHost.startWindowDrag();
1476             event.preventDefault();
1477             return;
1478         }
1479
1480         // Ignore dragging on the top of the toolbar on Mac if the system handles it.
1481         if (WebInspector.Platform.version.release === 10) {
1482             const windowDragHandledTitleBarHeight = 22;
1483             if (event.pageY < windowDragHandledTitleBarHeight) {
1484                 event.preventDefault();
1485                 return;
1486             }
1487         }
1488     }
1489
1490     var lastScreenX = event.screenX;
1491     var lastScreenY = event.screenY;
1492
1493     function toolbarDrag(event)
1494     {
1495         if (event.button !== 0)
1496             return;
1497
1498         var x = event.screenX - lastScreenX;
1499         var y = event.screenY - lastScreenY;
1500
1501         InspectorFrontendHost.moveWindowBy(x, y);
1502
1503         lastScreenX = event.screenX;
1504         lastScreenY = event.screenY;
1505     }
1506
1507     function toolbarDragEnd(event)
1508     {
1509         if (event.button !== 0)
1510             return;
1511
1512         WebInspector.elementDragEnd(event);
1513     }
1514
1515     WebInspector.elementDragStart(event.target, toolbarDrag, toolbarDragEnd, event, "default");
1516 };
1517
1518 WebInspector._storageWasInspected = function(event)
1519 {
1520     this.showStorageTab();
1521 };
1522
1523 WebInspector._domNodeWasInspected = function(event)
1524 {
1525     this.domTreeManager.highlightDOMNodeForTwoSeconds(event.data.node.id);
1526
1527     InspectorFrontendHost.bringToFront();
1528
1529     this.showElementsTab();
1530     this.showMainFrameDOMTree(event.data.node, true);
1531 };
1532
1533 WebInspector._inspectModeStateChanged = function(event)
1534 {
1535     this._inspectModeToolbarButton.activated = this.domTreeManager.inspectModeEnabled;
1536 };
1537
1538 WebInspector._toggleInspectMode = function(event)
1539 {
1540     this.domTreeManager.inspectModeEnabled = !this.domTreeManager.inspectModeEnabled;
1541 };
1542
1543 WebInspector._downloadWebArchive = function(event)
1544 {
1545     this.archiveMainFrame();
1546 };
1547
1548 WebInspector._reloadPage = function(event)
1549 {
1550     PageAgent.reload();
1551 };
1552
1553 WebInspector._reloadPageClicked = function(event)
1554 {
1555     // Ignore cache when the shift key is pressed.
1556     PageAgent.reload(window.event ? window.event.shiftKey : false);
1557 };
1558
1559 WebInspector._reloadPageIgnoringCache = function(event)
1560 {
1561     PageAgent.reload(true);
1562 };
1563
1564 WebInspector._updateReloadToolbarButton = function()
1565 {
1566     if (!window.PageAgent || !PageAgent.reload) {
1567         this._reloadToolbarButton.hidden = true;
1568         return;
1569     }
1570
1571     this._reloadToolbarButton.hidden = false;
1572 };
1573
1574 WebInspector._updateDownloadToolbarButton = function()
1575 {
1576     if (!window.PageAgent || !PageAgent.archive || this.debuggableType !== WebInspector.DebuggableType.Web) {
1577         this._downloadToolbarButton.hidden = true;
1578         return;
1579     }
1580
1581     if (this._downloadingPage) {
1582         this._downloadToolbarButton.enabled = false;
1583         return;
1584     }
1585
1586     this._downloadToolbarButton.enabled = this.canArchiveMainFrame();
1587 };
1588
1589 WebInspector._toggleInspectMode = function(event)
1590 {
1591     this.domTreeManager.inspectModeEnabled = !this.domTreeManager.inspectModeEnabled;
1592 };
1593
1594 WebInspector._showConsoleTab = function(event)
1595 {
1596     this.showConsoleTab();
1597 };
1598
1599 WebInspector._focusedContentView = function()
1600 {
1601     if (this.tabBrowser.element.isSelfOrAncestor(this.currentFocusElement)) {
1602         var tabContentView = this.tabBrowser.selectedTabContentView;
1603         if (tabContentView instanceof WebInspector.ContentBrowserTabContentView)
1604             return tabContentView.contentBrowser.currentContentView;
1605         return tabContentView;
1606     }
1607     if (this.splitContentBrowser.element.isSelfOrAncestor(this.currentFocusElement))
1608         return  this.splitContentBrowser.currentContentView;
1609     return null;
1610 };
1611
1612 WebInspector._beforecopy = function(event)
1613 {
1614     var selection = window.getSelection();
1615
1616     // If there is no selection, see if the focused element or focused ContentView can handle the copy event.
1617     if (selection.isCollapsed && !WebInspector.isEventTargetAnEditableField(event)) {
1618         var focusedCopyHandler = this.currentFocusElement && this.currentFocusElement.copyHandler;
1619         if (focusedCopyHandler && typeof focusedCopyHandler.handleBeforeCopyEvent === "function") {
1620             focusedCopyHandler.handleBeforeCopyEvent(event);
1621             if (event.defaultPrevented)
1622                 return;
1623         }
1624
1625         var focusedContentView = this._focusedContentView();
1626         if (focusedContentView && typeof focusedContentView.handleCopyEvent === "function") {
1627             event.preventDefault();
1628             return;
1629         }
1630
1631         return;
1632     }
1633
1634     if (selection.isCollapsed)
1635         return;
1636
1637     // Say we can handle it (by preventing default) to remove word break characters.
1638     event.preventDefault();
1639 };
1640
1641 WebInspector._copy = function(event)
1642 {
1643     var selection = window.getSelection();
1644
1645     // If there is no selection, pass the copy event on to the focused element or focused ContentView.
1646     if (selection.isCollapsed && !WebInspector.isEventTargetAnEditableField(event)) {
1647         var focusedCopyHandler = this.currentFocusElement && this.currentFocusElement.copyHandler;
1648         if (focusedCopyHandler && typeof focusedCopyHandler.handleCopyEvent === "function") {
1649             focusedCopyHandler.handleCopyEvent(event);
1650             if (event.defaultPrevented)
1651                 return;
1652         }
1653
1654         var focusedContentView = this._focusedContentView();
1655         if (focusedContentView && typeof focusedContentView.handleCopyEvent === "function") {
1656             focusedContentView.handleCopyEvent(event);
1657             return;
1658         }
1659
1660         return;
1661     }
1662
1663     if (selection.isCollapsed)
1664         return;
1665
1666     // Remove word break characters from the selection before putting it on the pasteboard.
1667     var selectionString = selection.toString().removeWordBreakCharacters();
1668     event.clipboardData.setData("text/plain", selectionString);
1669     event.preventDefault();
1670 };
1671
1672 WebInspector._generateDisclosureTriangleImages = function()
1673 {
1674     var specifications = {};
1675     specifications["normal"] = {fillColor: [140, 140, 140, 1]};
1676     specifications["normal-active"] = {fillColor: [128, 128, 128, 1]};
1677
1678     generateColoredImagesForCSS("Images/DisclosureTriangleSmallOpen.svg", specifications, 13, 13, "disclosure-triangle-small-open-");
1679     generateColoredImagesForCSS("Images/DisclosureTriangleSmallClosed.svg", specifications, 13, 13, "disclosure-triangle-small-closed-");
1680
1681     specifications["selected"] = {fillColor: [255, 255, 255, 1]};
1682
1683     generateColoredImagesForCSS("Images/DisclosureTriangleTinyOpen.svg", specifications, 8, 8, "disclosure-triangle-tiny-open-");
1684     generateColoredImagesForCSS("Images/DisclosureTriangleTinyClosed.svg", specifications, 8, 8, "disclosure-triangle-tiny-closed-");
1685 };
1686
1687 WebInspector.elementDragStart = function(element, dividerDrag, elementDragEnd, event, cursor, eventTarget)
1688 {
1689     if (WebInspector._elementDraggingEventListener || WebInspector._elementEndDraggingEventListener)
1690         WebInspector.elementDragEnd(event);
1691
1692     if (element) {
1693         // Install glass pane
1694         if (WebInspector._elementDraggingGlassPane)
1695             WebInspector._elementDraggingGlassPane.parentElement.removeChild(WebInspector._elementDraggingGlassPane);
1696
1697         var glassPane = document.createElement("div");
1698         glassPane.style.cssText = "position:absolute;top:0;bottom:0;left:0;right:0;opacity:0;z-index:1";
1699         glassPane.id = "glass-pane-for-drag";
1700         element.ownerDocument.body.appendChild(glassPane);
1701         WebInspector._elementDraggingGlassPane = glassPane;
1702     }
1703
1704     WebInspector._elementDraggingEventListener = dividerDrag;
1705     WebInspector._elementEndDraggingEventListener = elementDragEnd;
1706
1707     var targetDocument = event.target.ownerDocument;
1708
1709     WebInspector._elementDraggingEventTarget = eventTarget || targetDocument;
1710     WebInspector._elementDraggingEventTarget.addEventListener("mousemove", dividerDrag, true);
1711     WebInspector._elementDraggingEventTarget.addEventListener("mouseup", elementDragEnd, true);
1712
1713     targetDocument.body.style.cursor = cursor;
1714
1715     event.preventDefault();
1716 };
1717
1718 WebInspector.elementDragEnd = function(event)
1719 {
1720     WebInspector._elementDraggingEventTarget.removeEventListener("mousemove", WebInspector._elementDraggingEventListener, true);
1721     WebInspector._elementDraggingEventTarget.removeEventListener("mouseup", WebInspector._elementEndDraggingEventListener, true);
1722
1723     event.target.ownerDocument.body.style.removeProperty("cursor");
1724
1725     if (WebInspector._elementDraggingGlassPane)
1726         WebInspector._elementDraggingGlassPane.parentElement.removeChild(WebInspector._elementDraggingGlassPane);
1727
1728     delete WebInspector._elementDraggingGlassPane;
1729     delete WebInspector._elementDraggingEventTarget;
1730     delete WebInspector._elementDraggingEventListener;
1731     delete WebInspector._elementEndDraggingEventListener;
1732
1733     event.preventDefault();
1734 };
1735
1736 WebInspector.createMessageTextView = function(message, isError)
1737 {
1738     var messageElement = document.createElement("div");
1739     messageElement.className = "message-text-view";
1740     if (isError)
1741         messageElement.classList.add("error");
1742
1743     messageElement.textContent = message;
1744
1745     return messageElement;
1746 };
1747
1748 WebInspector.createGoToArrowButton = function()
1749 {
1750     if (!WebInspector._generatedGoToArrowButtonImages) {
1751         WebInspector._generatedGoToArrowButtonImages = true;
1752
1753         var specifications = {};
1754         specifications["go-to-arrow-normal"] = {fillColor: [0, 0, 0, 0.5]};
1755         specifications["go-to-arrow-normal-active"] = {fillColor: [0, 0, 0, 0.7]};
1756         specifications["go-to-arrow-selected"] = {fillColor: [255, 255, 255, 0.8]};
1757         specifications["go-to-arrow-selected-active"] = {fillColor: [255, 255, 255, 1]};
1758
1759         generateColoredImagesForCSS("Images/GoToArrow.svg", specifications, 10, 10);
1760     }
1761
1762     function stopPropagation(event)
1763     {
1764         event.stopPropagation()
1765     }
1766
1767     var button = document.createElement("button");
1768     button.addEventListener("mousedown", stopPropagation, true);
1769     button.className = "go-to-arrow";
1770     button.tabIndex = -1;
1771     return button;
1772 };
1773
1774 WebInspector.createSourceCodeLocationLink = function(sourceCodeLocation, dontFloat, useGoToArrowButton)
1775 {
1776     console.assert(sourceCodeLocation);
1777     if (!sourceCodeLocation)
1778         return null;
1779
1780     var linkElement = document.createElement("a");
1781     linkElement.className = "go-to-link";
1782     WebInspector.linkifyElement(linkElement, sourceCodeLocation);
1783     sourceCodeLocation.populateLiveDisplayLocationTooltip(linkElement);
1784
1785     if (useGoToArrowButton)
1786         linkElement.appendChild(WebInspector.createGoToArrowButton());
1787     else
1788         sourceCodeLocation.populateLiveDisplayLocationString(linkElement, "textContent");
1789
1790     if (dontFloat)
1791         linkElement.classList.add("dont-float");
1792
1793     return linkElement;
1794 };
1795
1796 WebInspector.linkifyLocation = function(url, lineNumber, columnNumber, className)
1797 {
1798     var sourceCode = WebInspector.sourceCodeForURL(url);
1799
1800     if (!sourceCode) {
1801         var anchor = document.createElement("a");
1802         anchor.href  = url;
1803         anchor.lineNumber = lineNumber;
1804         if (className)
1805             anchor.className = className;
1806         anchor.appendChild(document.createTextNode(WebInspector.displayNameForURL(url) + ":" + lineNumber));
1807         return anchor;
1808     }
1809
1810     var sourceCodeLocation = sourceCode.createSourceCodeLocation(lineNumber, columnNumber);
1811     var linkElement = WebInspector.createSourceCodeLocationLink(sourceCodeLocation, true);
1812     if (className)
1813         linkElement.classList.add(className);
1814     return linkElement;
1815 };
1816
1817 WebInspector.linkifyElement = function(linkElement, sourceCodeLocation) {
1818     console.assert(sourceCodeLocation);
1819
1820     function showSourceCodeLocation(event)
1821     {
1822         event.stopPropagation();
1823         event.preventDefault();
1824
1825         if (event.metaKey)
1826             this.showOriginalUnformattedSourceCodeLocation(sourceCodeLocation);
1827         else
1828             this.showSourceCodeLocation(sourceCodeLocation);
1829     }
1830
1831     linkElement.addEventListener("click", showSourceCodeLocation.bind(this));
1832 };
1833
1834 WebInspector.sourceCodeForURL = function(url) {
1835     var sourceCode = WebInspector.frameResourceManager.resourceForURL(url);
1836     if (!sourceCode) {
1837         sourceCode = WebInspector.debuggerManager.scriptsForURL(url)[0];
1838         if (sourceCode)
1839             sourceCode = sourceCode.resource || sourceCode;
1840     }
1841     return sourceCode || null;
1842 };
1843
1844 WebInspector.linkifyURLAsNode = function(url, linkText, classes)
1845 {
1846     if (!linkText)
1847         linkText = url;
1848
1849     classes = (classes ? classes + " " : "");
1850
1851     var a = document.createElement("a");
1852     a.href = url;
1853     a.className = classes;
1854
1855     a.textContent = linkText;
1856     a.style.maxWidth = "100%";
1857
1858     return a;
1859 };
1860
1861 WebInspector.linkifyStringAsFragmentWithCustomLinkifier = function(string, linkifier)
1862 {
1863     var container = document.createDocumentFragment();
1864     var linkStringRegEx = /(?:[a-zA-Z][a-zA-Z0-9+.-]{2,}:\/\/|www\.)[\w$\-_+*'=\|\/\\(){}[\]%@&#~,:;.!?]{2,}[\w$\-_+*=\|\/\\({%@&#~]/;
1865     var lineColumnRegEx = /:(\d+)(:(\d+))?$/;
1866
1867     while (string) {
1868         var linkString = linkStringRegEx.exec(string);
1869         if (!linkString)
1870             break;
1871
1872         linkString = linkString[0];
1873         var linkIndex = string.indexOf(linkString);
1874         var nonLink = string.substring(0, linkIndex);
1875         container.appendChild(document.createTextNode(nonLink));
1876
1877         var title = linkString;
1878         var realURL = (linkString.startsWith("www.") ? "http://" + linkString : linkString);
1879         var lineColumnMatch = lineColumnRegEx.exec(realURL);
1880         if (lineColumnMatch)
1881             realURL = realURL.substring(0, realURL.length - lineColumnMatch[0].length);
1882
1883         var linkNode = linkifier(title, realURL, lineColumnMatch ? lineColumnMatch[1] : undefined);
1884         container.appendChild(linkNode);
1885         string = string.substring(linkIndex + linkString.length, string.length);
1886     }
1887
1888     if (string)
1889         container.appendChild(document.createTextNode(string));
1890
1891     return container;
1892 };
1893
1894 WebInspector.linkifyStringAsFragment = function(string)
1895 {
1896     function linkifier(title, url, lineNumber)
1897     {
1898         var urlNode = WebInspector.linkifyURLAsNode(url, title, undefined);
1899         if (lineNumber !== undefined)
1900             urlNode.lineNumber = lineNumber;
1901
1902         return urlNode;
1903     }
1904
1905     return WebInspector.linkifyStringAsFragmentWithCustomLinkifier(string, linkifier);
1906 };
1907
1908 WebInspector._undoKeyboardShortcut = function(event)
1909 {
1910     if (!this.isEditingAnyField() && !this.isEventTargetAnEditableField(event)) {
1911         this.undo();
1912         event.preventDefault();
1913     }
1914 };
1915
1916 WebInspector._redoKeyboardShortcut = function(event)
1917 {
1918     if (!this.isEditingAnyField() && !this.isEventTargetAnEditableField(event)) {
1919         this.redo();
1920         event.preventDefault();
1921     }
1922 };
1923
1924 WebInspector.undo = function()
1925 {
1926     DOMAgent.undo();
1927 };
1928
1929 WebInspector.redo = function()
1930 {
1931     DOMAgent.redo();
1932 };
1933
1934 WebInspector.highlightRangesWithStyleClass = function(element, resultRanges, styleClass, changes)
1935 {
1936     changes = changes || [];
1937     var highlightNodes = [];
1938     var lineText = element.textContent;
1939     var ownerDocument = element.ownerDocument;
1940     var textNodeSnapshot = ownerDocument.evaluate(".//text()", element, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
1941
1942     var snapshotLength = textNodeSnapshot.snapshotLength;
1943     if (snapshotLength === 0)
1944         return highlightNodes;
1945
1946     var nodeRanges = [];
1947     var rangeEndOffset = 0;
1948     for (var i = 0; i < snapshotLength; ++i) {
1949         var range = {};
1950         range.offset = rangeEndOffset;
1951         range.length = textNodeSnapshot.snapshotItem(i).textContent.length;
1952         rangeEndOffset = range.offset + range.length;
1953         nodeRanges.push(range);
1954     }
1955
1956     var startIndex = 0;
1957     for (var i = 0; i < resultRanges.length; ++i) {
1958         var startOffset = resultRanges[i].offset;
1959         var endOffset = startOffset + resultRanges[i].length;
1960
1961         while (startIndex < snapshotLength && nodeRanges[startIndex].offset + nodeRanges[startIndex].length <= startOffset)
1962             startIndex++;
1963         var endIndex = startIndex;
1964         while (endIndex < snapshotLength && nodeRanges[endIndex].offset + nodeRanges[endIndex].length < endOffset)
1965             endIndex++;
1966         if (endIndex === snapshotLength)
1967             break;
1968
1969         var highlightNode = ownerDocument.createElement("span");
1970         highlightNode.className = styleClass;
1971         highlightNode.textContent = lineText.substring(startOffset, endOffset);
1972
1973         var lastTextNode = textNodeSnapshot.snapshotItem(endIndex);
1974         var lastText = lastTextNode.textContent;
1975         lastTextNode.textContent = lastText.substring(endOffset - nodeRanges[endIndex].offset);
1976         changes.push({ node: lastTextNode, type: "changed", oldText: lastText, newText: lastTextNode.textContent });
1977
1978         if (startIndex === endIndex) {
1979             lastTextNode.parentElement.insertBefore(highlightNode, lastTextNode);
1980             changes.push({ node: highlightNode, type: "added", nextSibling: lastTextNode, parent: lastTextNode.parentElement });
1981             highlightNodes.push(highlightNode);
1982
1983             var prefixNode = ownerDocument.createTextNode(lastText.substring(0, startOffset - nodeRanges[startIndex].offset));
1984             lastTextNode.parentElement.insertBefore(prefixNode, highlightNode);
1985             changes.push({ node: prefixNode, type: "added", nextSibling: highlightNode, parent: lastTextNode.parentElement });
1986         } else {
1987             var firstTextNode = textNodeSnapshot.snapshotItem(startIndex);
1988             var firstText = firstTextNode.textContent;
1989             var anchorElement = firstTextNode.nextSibling;
1990
1991             firstTextNode.parentElement.insertBefore(highlightNode, anchorElement);
1992             changes.push({ node: highlightNode, type: "added", nextSibling: anchorElement, parent: firstTextNode.parentElement });
1993             highlightNodes.push(highlightNode);
1994
1995             firstTextNode.textContent = firstText.substring(0, startOffset - nodeRanges[startIndex].offset);
1996             changes.push({ node: firstTextNode, type: "changed", oldText: firstText, newText: firstTextNode.textContent });
1997
1998             for (var j = startIndex + 1; j < endIndex; j++) {
1999                 var textNode = textNodeSnapshot.snapshotItem(j);
2000                 var text = textNode.textContent;
2001                 textNode.textContent = "";
2002                 changes.push({ node: textNode, type: "changed", oldText: text, newText: textNode.textContent });
2003             }
2004         }
2005         startIndex = endIndex;
2006         nodeRanges[startIndex].offset = endOffset;
2007         nodeRanges[startIndex].length = lastTextNode.textContent.length;
2008
2009     }
2010     return highlightNodes;
2011 };
2012
2013 WebInspector.revertDomChanges = function(domChanges)
2014 {
2015     for (var i = domChanges.length - 1; i >= 0; --i) {
2016         var entry = domChanges[i];
2017         switch (entry.type) {
2018         case "added":
2019             if (entry.node.parentElement)
2020                 entry.node.parentElement.removeChild(entry.node);
2021             break;
2022         case "changed":
2023             entry.node.textContent = entry.oldText;
2024             break;
2025         }
2026     }
2027 };
2028
2029 WebInspector.archiveMainFrame = function()
2030 {
2031     this._downloadingPage = true;
2032     this._updateDownloadToolbarButton();
2033
2034     PageAgent.archive(function(error, data) {
2035         this._downloadingPage = false;
2036         this._updateDownloadToolbarButton();
2037
2038         if (error)
2039             return;
2040
2041         var mainFrame = WebInspector.frameResourceManager.mainFrame;
2042         var archiveName = mainFrame.mainResource.urlComponents.host || mainFrame.mainResource.displayName || "Archive";
2043         var url = "web-inspector:///" + encodeURI(archiveName) + ".webarchive";
2044
2045         InspectorFrontendHost.save(url, data, true, true);
2046     }.bind(this));
2047 };
2048
2049 WebInspector.canArchiveMainFrame = function()
2050 {
2051     if (!PageAgent.archive || this.debuggableType !== WebInspector.DebuggableType.Web)
2052         return false;
2053
2054     if (!WebInspector.frameResourceManager.mainFrame || !WebInspector.frameResourceManager.mainFrame.mainResource)
2055         return;
2056
2057     return WebInspector.Resource.typeFromMIMEType(WebInspector.frameResourceManager.mainFrame.mainResource.mimeType) === WebInspector.Resource.Type.Document;
2058 };
2059
2060 WebInspector.addWindowKeydownListener = function(listener)
2061 {
2062     if (typeof listener.handleKeydownEvent !== "function")
2063         return;
2064
2065     this._windowKeydownListeners.push(listener);
2066
2067     this._updateWindowKeydownListener();
2068 };
2069
2070 WebInspector.removeWindowKeydownListener = function(listener)
2071 {
2072     this._windowKeydownListeners.remove(listener);
2073
2074     this._updateWindowKeydownListener();
2075 };
2076
2077 WebInspector._updateWindowKeydownListener = function()
2078 {
2079     if (this._windowKeydownListeners.length > 0)
2080         window.addEventListener("keydown", WebInspector._sharedWindowKeydownListener, true);
2081     else
2082         window.removeEventListener("keydown", WebInspector._sharedWindowKeydownListener, true);
2083 };
2084
2085 WebInspector._sharedWindowKeydownListener = function(event)
2086 {
2087     for (var i = WebInspector._windowKeydownListeners.length - 1; i >= 0; --i) {
2088         if (WebInspector._windowKeydownListeners[i].handleKeydownEvent(event)) {
2089             event.stopImmediatePropagation();
2090             event.preventDefault();
2091             break;
2092         }
2093     }
2094 };