2 * Copyright (C) 2006, 2007, 2008 Apple Inc. All rights reserved.
3 * Copyright (C) 2007 Matt Lilek (pewtermoose@gmail.com).
4 * Copyright (C) 2009 Joseph Pecoraro
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
16 * its contributors may be used to endorse or promote products derived
17 * from this software without specific prior written permission.
19 * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
20 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
21 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22 * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
23 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
24 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
25 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
26 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
28 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31 // Keep this ; so that concatenated version of the script worked.
32 ;(function preloadImages()
34 (new Image()).src = "Images/clearConsoleButtonGlyph.png";
35 (new Image()).src = "Images/consoleButtonGlyph.png";
36 (new Image()).src = "Images/dockButtonGlyph.png";
37 (new Image()).src = "Images/enableOutlineButtonGlyph.png";
38 (new Image()).src = "Images/enableSolidButtonGlyph.png";
39 (new Image()).src = "Images/excludeButtonGlyph.png";
40 (new Image()).src = "Images/focusButtonGlyph.png";
41 (new Image()).src = "Images/largerResourcesButtonGlyph.png";
42 (new Image()).src = "Images/nodeSearchButtonGlyph.png";
43 (new Image()).src = "Images/pauseOnExceptionButtonGlyph.png";
44 (new Image()).src = "Images/percentButtonGlyph.png";
45 (new Image()).src = "Images/recordButtonGlyph.png";
46 (new Image()).src = "Images/recordToggledButtonGlyph.png";
47 (new Image()).src = "Images/reloadButtonGlyph.png";
48 (new Image()).src = "Images/undockButtonGlyph.png";
53 missingLocalizedStrings: {},
58 if (!("_platform" in this))
59 this._platform = InspectorFrontendHost.platform();
61 return this._platform;
66 if (!("_platformFlavor" in this))
67 this._platformFlavor = this._detectPlatformFlavor();
69 return this._platformFlavor;
72 _detectPlatformFlavor: function()
74 const userAgent = navigator.userAgent;
76 if (this.platform === "windows") {
77 var match = userAgent.match(/Windows NT (\d+)\.(?:\d+)/);
78 if (match && match[1] >= 6)
79 return WebInspector.PlatformFlavor.WindowsVista;
81 } else if (this.platform === "mac") {
82 var match = userAgent.match(/Mac OS X\s*(?:(\d+)_(\d+))?/);
83 if (!match || match[1] != 10)
84 return WebInspector.PlatformFlavor.MacSnowLeopard;
85 switch (Number(match[2])) {
87 return WebInspector.PlatformFlavor.MacTiger;
89 return WebInspector.PlatformFlavor.MacLeopard;
92 return WebInspector.PlatformFlavor.MacSnowLeopard;
101 if (!("_port" in this))
102 this._port = InspectorFrontendHost.port();
107 get previousFocusElement()
109 return this._previousFocusElement;
112 get currentFocusElement()
114 return this._currentFocusElement;
117 set currentFocusElement(x)
119 if (this._currentFocusElement !== x)
120 this._previousFocusElement = this._currentFocusElement;
121 this._currentFocusElement = x;
123 if (this._currentFocusElement) {
124 this._currentFocusElement.focus();
126 // Make a caret selection inside the new element if there isn't a range selection and
127 // there isn't already a caret selection inside.
128 var selection = window.getSelection();
129 if (selection.isCollapsed && !this._currentFocusElement.isInsertionCaretInside()) {
130 var selectionRange = this._currentFocusElement.ownerDocument.createRange();
131 selectionRange.setStart(this._currentFocusElement, 0);
132 selectionRange.setEnd(this._currentFocusElement, 0);
134 selection.removeAllRanges();
135 selection.addRange(selectionRange);
137 } else if (this._previousFocusElement)
138 this._previousFocusElement.blur();
143 return this._currentPanel;
148 if (this._currentPanel === x)
151 if (this._currentPanel)
152 this._currentPanel.hide();
154 this._currentPanel = x;
156 this.updateSearchLabel();
161 if (this.currentQuery) {
162 if (x.performSearch) {
163 function performPanelSearch()
165 this.updateSearchMatchesCount();
167 x.currentQuery = this.currentQuery;
168 x.performSearch(this.currentQuery);
171 // Perform the search on a timeout so the panel switches fast.
172 setTimeout(performPanelSearch.bind(this), 0);
174 // Update to show Not found for panels that can't be searched.
175 this.updateSearchMatchesCount();
180 for (var panelName in WebInspector.panels) {
181 if (WebInspector.panels[panelName] === x) {
182 WebInspector.settings.lastActivePanel = panelName;
183 this._panelHistory.setPanel(panelName);
188 createJSBreakpointsSidebarPane: function()
190 var pane = new WebInspector.BreakpointsSidebarPane(WebInspector.UIString("Breakpoints"));
191 function breakpointAdded(event)
193 pane.addBreakpointItem(new WebInspector.BreakpointItem(event.data));
195 WebInspector.debuggerModel.addEventListener("breakpoint-added", breakpointAdded);
199 createDOMBreakpointsSidebarPane: function()
201 var pane = new WebInspector.BreakpointsSidebarPane(WebInspector.UIString("DOM Breakpoints"));
202 function breakpointAdded(event)
204 pane.addBreakpointItem(new WebInspector.BreakpointItem(event.data));
206 WebInspector.breakpointManager.addEventListener("dom-breakpoint-added", breakpointAdded);
210 createXHRBreakpointsSidebarPane: function()
212 var pane = new WebInspector.XHRBreakpointsSidebarPane();
213 function breakpointAdded(event)
215 pane.addBreakpointItem(new WebInspector.BreakpointItem(event.data));
217 WebInspector.breakpointManager.addEventListener("xhr-breakpoint-added", breakpointAdded);
221 _createPanels: function()
223 var hiddenPanels = (InspectorFrontendHost.hiddenPanels() || "").split(',');
224 if (hiddenPanels.indexOf("elements") === -1)
225 this.panels.elements = new WebInspector.ElementsPanel();
226 if (hiddenPanels.indexOf("resources") === -1)
227 this.panels.resources = new WebInspector.ResourcesPanel();
228 if (hiddenPanels.indexOf("network") === -1)
229 this.panels.network = new WebInspector.NetworkPanel();
230 if (hiddenPanels.indexOf("scripts") === -1)
231 this.panels.scripts = new WebInspector.ScriptsPanel();
232 if (hiddenPanels.indexOf("timeline") === -1)
233 this.panels.timeline = new WebInspector.TimelinePanel();
234 if (hiddenPanels.indexOf("profiles") === -1) {
235 this.panels.profiles = new WebInspector.ProfilesPanel();
236 this.panels.profiles.registerProfileType(new WebInspector.CPUProfileType());
237 if (Preferences.heapProfilerPresent)
238 this.panels.profiles.registerProfileType(new WebInspector.HeapSnapshotProfileType());
240 if (hiddenPanels.indexOf("audits") === -1)
241 this.panels.audits = new WebInspector.AuditsPanel();
242 if (hiddenPanels.indexOf("console") === -1)
243 this.panels.console = new WebInspector.ConsolePanel();
248 return this._attached;
253 if (this._attached === x)
258 this.updateSearchLabel();
260 var dockToggleButton = document.getElementById("dock-status-bar-item");
261 var body = document.body;
264 body.removeStyleClass("detached");
265 body.addStyleClass("attached");
266 dockToggleButton.title = WebInspector.UIString("Undock into separate window.");
268 body.removeStyleClass("attached");
269 body.addStyleClass("detached");
270 dockToggleButton.title = WebInspector.UIString("Dock to main window.");
273 this.drawer.resize();
278 return this._errors || 0;
285 if (this._errors === x)
288 this._updateErrorAndWarningCounts();
293 return this._warnings || 0;
300 if (this._warnings === x)
303 this._updateErrorAndWarningCounts();
306 _updateErrorAndWarningCounts: function()
308 var errorWarningElement = document.getElementById("error-warning-count");
309 if (!errorWarningElement)
312 if (!this.errors && !this.warnings) {
313 errorWarningElement.addStyleClass("hidden");
317 errorWarningElement.removeStyleClass("hidden");
319 errorWarningElement.removeChildren();
322 var errorElement = document.createElement("span");
323 errorElement.id = "error-count";
324 errorElement.textContent = this.errors;
325 errorWarningElement.appendChild(errorElement);
329 var warningsElement = document.createElement("span");
330 warningsElement.id = "warning-count";
331 warningsElement.textContent = this.warnings;
332 errorWarningElement.appendChild(warningsElement);
337 if (this.errors == 1) {
338 if (this.warnings == 1)
339 errorWarningElement.title = WebInspector.UIString("%d error, %d warning", this.errors, this.warnings);
341 errorWarningElement.title = WebInspector.UIString("%d error, %d warnings", this.errors, this.warnings);
342 } else if (this.warnings == 1)
343 errorWarningElement.title = WebInspector.UIString("%d errors, %d warning", this.errors, this.warnings);
345 errorWarningElement.title = WebInspector.UIString("%d errors, %d warnings", this.errors, this.warnings);
346 } else if (this.errors == 1)
347 errorWarningElement.title = WebInspector.UIString("%d error", this.errors);
349 errorWarningElement.title = WebInspector.UIString("%d errors", this.errors);
350 } else if (this.warnings == 1)
351 errorWarningElement.title = WebInspector.UIString("%d warning", this.warnings);
352 else if (this.warnings)
353 errorWarningElement.title = WebInspector.UIString("%d warnings", this.warnings);
355 errorWarningElement.title = null;
360 return this._styleChanges;
367 if (this._styleChanges === x)
369 this._styleChanges = x;
370 this._updateChangesCount();
373 _updateChangesCount: function()
375 // TODO: Remove immediate return when enabling the Changes Panel
378 var changesElement = document.getElementById("changes-count");
382 if (!this.styleChanges) {
383 changesElement.addStyleClass("hidden");
387 changesElement.removeStyleClass("hidden");
388 changesElement.removeChildren();
390 if (this.styleChanges) {
391 var styleChangesElement = document.createElement("span");
392 styleChangesElement.id = "style-changes-count";
393 styleChangesElement.textContent = this.styleChanges;
394 changesElement.appendChild(styleChangesElement);
397 if (this.styleChanges) {
398 if (this.styleChanges === 1)
399 changesElement.title = WebInspector.UIString("%d style change", this.styleChanges);
401 changesElement.title = WebInspector.UIString("%d style changes", this.styleChanges);
405 highlightDOMNode: function(nodeId)
407 if ("_hideDOMNodeHighlightTimeout" in this) {
408 clearTimeout(this._hideDOMNodeHighlightTimeout);
409 delete this._hideDOMNodeHighlightTimeout;
412 if (this._highlightedDOMNodeId === nodeId)
415 this._highlightedDOMNodeId = nodeId;
417 InspectorBackend.highlightDOMNode(nodeId);
419 InspectorBackend.hideDOMNodeHighlight();
422 highlightDOMNodeForTwoSeconds: function(nodeId)
424 this.highlightDOMNode(nodeId);
425 this._hideDOMNodeHighlightTimeout = setTimeout(this.highlightDOMNode.bind(this, 0), 2000);
428 wireElementWithDOMNode: function(element, nodeId)
430 element.addEventListener("click", this._updateFocusedNode.bind(this, nodeId), false);
431 element.addEventListener("mouseover", this.highlightDOMNode.bind(this, nodeId), false);
432 element.addEventListener("mouseout", this.highlightDOMNode.bind(this, 0), false);
435 _updateFocusedNode: function(nodeId)
437 this.currentPanel = this.panels.elements;
438 this.panels.elements.updateFocusedNode(nodeId);
441 get networkResources()
443 return this.panels.network.resources;
446 forAllResources: function(callback)
448 WebInspector.resourceManager.forAllResources(callback);
451 resourceForURL: function(url)
453 return this.resourceManager.resourceForURL(url);
457 WebInspector.PlatformFlavor = {
458 WindowsVista: "windows-vista",
459 MacTiger: "mac-tiger",
460 MacLeopard: "mac-leopard",
461 MacSnowLeopard: "mac-snowleopard"
464 (function parseQueryParameters()
466 WebInspector.queryParamsObject = {};
467 var queryParams = window.location.search;
470 var params = queryParams.substring(1).split("&");
471 for (var i = 0; i < params.length; ++i) {
472 var pair = params[i].split("=");
473 WebInspector.queryParamsObject[pair[0]] = pair[1];
477 WebInspector.loaded = function()
479 if ("page" in WebInspector.queryParamsObject) {
480 WebInspector.socket = new WebSocket("ws://" + window.location.host + "/devtools/page/" + WebInspector.queryParamsObject.page);
481 WebInspector.socket.onmessage = function(message) { InspectorBackend.dispatch(message.data); }
482 WebInspector.socket.onerror = function(error) { console.error(error); }
483 WebInspector.socket.onopen = function() {
484 InspectorFrontendHost.sendMessageToBackend = WebInspector.socket.send.bind(WebInspector.socket);
485 InspectorFrontendHost.loaded = WebInspector.socket.send.bind(WebInspector.socket, "loaded");
486 WebInspector.doLoadedDone();
490 WebInspector.doLoadedDone();
493 WebInspector.doLoadedDone = function()
495 InspectorBackend.setInjectedScriptSource("(" + injectedScriptConstructor + ");");
497 var platform = WebInspector.platform;
498 document.body.addStyleClass("platform-" + platform);
499 var flavor = WebInspector.platformFlavor;
501 document.body.addStyleClass("platform-" + flavor);
502 var port = WebInspector.port;
503 document.body.addStyleClass("port-" + port);
505 InspectorFrontendHost.loaded();
506 WebInspector.settings = new WebInspector.Settings();
508 this._registerShortcuts();
510 // set order of some sections explicitly
511 WebInspector.shortcutsHelp.section(WebInspector.UIString("Console"));
512 WebInspector.shortcutsHelp.section(WebInspector.UIString("Elements Panel"));
514 this.drawer = new WebInspector.Drawer();
515 this.console = new WebInspector.ConsoleView(this.drawer);
516 // TODO: Uncomment when enabling the Changes Panel
517 // this.changes = new WebInspector.ChangesView(this.drawer);
518 // TODO: Remove class="hidden" from inspector.html on button#changes-status-bar-item
519 this.drawer.visibleView = this.console;
520 this.resourceManager = new WebInspector.ResourceManager();
521 this.domAgent = new WebInspector.DOMAgent();
523 InspectorBackend.registerDomainDispatcher("Inspector", this);
525 this.resourceCategories = {
526 documents: new WebInspector.ResourceCategory("documents", WebInspector.UIString("Documents"), "rgb(47,102,236)"),
527 stylesheets: new WebInspector.ResourceCategory("stylesheets", WebInspector.UIString("Stylesheets"), "rgb(157,231,119)"),
528 images: new WebInspector.ResourceCategory("images", WebInspector.UIString("Images"), "rgb(164,60,255)"),
529 scripts: new WebInspector.ResourceCategory("scripts", WebInspector.UIString("Scripts"), "rgb(255,121,0)"),
530 xhr: new WebInspector.ResourceCategory("xhr", WebInspector.UIString("XHR"), "rgb(231,231,10)"),
531 fonts: new WebInspector.ResourceCategory("fonts", WebInspector.UIString("Fonts"), "rgb(255,82,62)"),
532 websockets: new WebInspector.ResourceCategory("websockets", WebInspector.UIString("WebSocket"), "rgb(186,186,186)"), // FIXME: Decide the color.
533 other: new WebInspector.ResourceCategory("other", WebInspector.UIString("Other"), "rgb(186,186,186)")
536 this.cssModel = new WebInspector.CSSStyleModel();
537 this.debuggerModel = new WebInspector.DebuggerModel();
539 this.breakpointManager = new WebInspector.BreakpointManager();
542 this._createPanels();
543 this._panelHistory = new WebInspector.PanelHistory();
545 var toolbarElement = document.getElementById("toolbar");
546 var previousToolbarItem = toolbarElement.children[0];
548 this.panelOrder = [];
549 for (var panelName in this.panels)
550 previousToolbarItem = WebInspector.addPanelToolbarIcon(toolbarElement, this.panels[panelName], previousToolbarItem);
553 ResourceNotCompressed: {id: 0, message: WebInspector.UIString("You could save bandwidth by having your web server compress this transfer with gzip or zlib.")}
557 IncorrectMIMEType: {id: 0, message: WebInspector.UIString("Resource interpreted as %s but transferred with MIME type %s.")}
560 this.addMainEventListeners(document);
562 window.addEventListener("resize", this.windowResize.bind(this), true);
564 document.addEventListener("focus", this.focusChanged.bind(this), true);
565 document.addEventListener("keydown", this.documentKeyDown.bind(this), false);
566 document.addEventListener("beforecopy", this.documentCanCopy.bind(this), true);
567 document.addEventListener("copy", this.documentCopy.bind(this), true);
568 document.addEventListener("contextmenu", this.contextMenuEventFired.bind(this), true);
570 var dockToggleButton = document.getElementById("dock-status-bar-item");
571 dockToggleButton.addEventListener("click", this.toggleAttach.bind(this), false);
574 dockToggleButton.title = WebInspector.UIString("Undock into separate window.");
576 dockToggleButton.title = WebInspector.UIString("Dock to main window.");
578 var errorWarningCount = document.getElementById("error-warning-count");
579 errorWarningCount.addEventListener("click", this.showConsole.bind(this), false);
580 this._updateErrorAndWarningCounts();
582 this.styleChanges = 0;
583 // TODO: Uncomment when enabling the Changes Panel
584 // var changesElement = document.getElementById("changes-count");
585 // changesElement.addEventListener("click", this.showChanges.bind(this), false);
586 // this._updateErrorAndWarningCounts();
588 var searchField = document.getElementById("search");
589 searchField.addEventListener("search", this.performSearch.bind(this), false); // when the search is emptied
590 searchField.addEventListener("mousedown", this._searchFieldManualFocus.bind(this), false); // when the search field is manually selected
591 searchField.addEventListener("keydown", this._searchKeyDown.bind(this), true);
593 toolbarElement.addEventListener("mousedown", this.toolbarDragStart, true);
594 document.getElementById("close-button-left").addEventListener("click", this.close, true);
595 document.getElementById("close-button-right").addEventListener("click", this.close, true);
597 this.extensionServer.initExtensions();
599 function populateInspectorState(inspectorState)
601 WebInspector.monitoringXHREnabled = inspectorState.monitoringXHREnabled;
602 if ("pauseOnExceptionsState" in inspectorState)
603 WebInspector.panels.scripts.updatePauseOnExceptionsState(inspectorState.pauseOnExceptionsState);
605 InspectorBackend.getInspectorState(populateInspectorState);
607 function onPopulateScriptObjects()
609 if (!WebInspector.currentPanel)
610 WebInspector.showPanel(WebInspector.settings.lastActivePanel);
612 InspectorBackend.populateScriptObjects(onPopulateScriptObjects);
614 InspectorBackend.setConsoleMessagesEnabled(true);
616 // As a DOMAgent method, this needs to happen after the frontend has loaded and the agent is available.
617 InspectorBackend.getSupportedCSSProperties(WebInspector.CSSCompletions._load);
620 WebInspector.addPanelToolbarIcon = function(toolbarElement, panel, previousToolbarItem)
622 var panelToolbarItem = panel.toolbarItem;
623 this.panelOrder.push(panel);
624 panelToolbarItem.addEventListener("click", this._toolbarItemClicked.bind(this));
625 if (previousToolbarItem)
626 toolbarElement.insertBefore(panelToolbarItem, previousToolbarItem.nextSibling);
628 toolbarElement.insertBefore(panelToolbarItem, toolbarElement.firstChild);
629 return panelToolbarItem;
632 var windowLoaded = function()
634 var localizedStringsURL = InspectorFrontendHost.localizedStringsURL();
635 if (localizedStringsURL) {
636 var localizedStringsScriptElement = document.createElement("script");
637 localizedStringsScriptElement.addEventListener("load", WebInspector.loaded.bind(WebInspector), false);
638 localizedStringsScriptElement.type = "text/javascript";
639 localizedStringsScriptElement.src = localizedStringsURL;
640 document.head.appendChild(localizedStringsScriptElement);
642 WebInspector.loaded();
644 window.removeEventListener("DOMContentLoaded", windowLoaded, false);
648 window.addEventListener("DOMContentLoaded", windowLoaded, false);
650 WebInspector.dispatch = function(message) {
651 // We'd like to enforce asynchronous interaction between the inspector controller and the frontend.
652 // This is important to LayoutTests.
653 function delayDispatch()
655 InspectorBackend.dispatch(message);
656 WebInspector.pendingDispatches--;
658 WebInspector.pendingDispatches++;
659 setTimeout(delayDispatch, 0);
662 WebInspector.dispatchMessageFromBackend = function(messageObject)
664 WebInspector.dispatch(messageObject);
667 WebInspector.windowResize = function(event)
669 if (this.currentPanel)
670 this.currentPanel.resize();
671 this.drawer.resize();
674 WebInspector.windowFocused = function(event)
676 // Fires after blur, so when focusing on either the main inspector
677 // or an <iframe> within the inspector we should always remove the
679 if (event.target.document.nodeType === Node.DOCUMENT_NODE)
680 document.body.removeStyleClass("inactive");
683 WebInspector.windowBlurred = function(event)
685 // Leaving the main inspector or an <iframe> within the inspector.
686 // We can add "inactive" now, and if we are moving the focus to another
687 // part of the inspector then windowFocused will correct this.
688 if (event.target.document.nodeType === Node.DOCUMENT_NODE)
689 document.body.addStyleClass("inactive");
692 WebInspector.focusChanged = function(event)
694 this.currentFocusElement = event.target;
697 WebInspector.setAttachedWindow = function(attached)
699 this.attached = attached;
702 WebInspector.close = function(event)
706 this._isClosing = true;
707 InspectorFrontendHost.closeWindow();
710 WebInspector.disconnectFromBackend = function()
712 InspectorFrontendHost.disconnectFromBackend();
715 WebInspector.documentClick = function(event)
717 var anchor = event.target.enclosingNodeOrSelfWithNodeName("a");
718 if (!anchor || anchor.target === "_blank")
721 // Prevent the link from navigating, since we don't do any navigation by following links normally.
722 event.preventDefault();
723 event.stopPropagation();
725 function followLink()
727 // FIXME: support webkit-html-external-link links here.
728 if (WebInspector.canShowSourceLine(anchor.href, anchor.getAttribute("line_number"), anchor.getAttribute("preferred_panel"))) {
729 if (anchor.hasStyleClass("webkit-html-external-link")) {
730 anchor.removeStyleClass("webkit-html-external-link");
731 anchor.addStyleClass("webkit-html-resource-link");
734 WebInspector.showSourceLine(anchor.href, anchor.getAttribute("line_number"), anchor.getAttribute("preferred_panel"));
738 const profileMatch = WebInspector.ProfileType.URLRegExp.exec(anchor.href);
740 WebInspector.showProfileForURL(anchor.href);
744 var parsedURL = anchor.href.asParsedURL();
745 if (parsedURL && parsedURL.scheme === "webkit-link-action") {
746 if (parsedURL.host === "show-panel") {
747 var panel = parsedURL.path.substring(1);
748 if (WebInspector.panels[panel])
749 WebInspector.showPanel(panel);
754 WebInspector.showPanel("resources");
757 if (WebInspector.followLinkTimeout)
758 clearTimeout(WebInspector.followLinkTimeout);
760 if (anchor.preventFollowOnDoubleClick) {
761 // Start a timeout if this is the first click, if the timeout is canceled
762 // before it fires, then a double clicked happened or another link was clicked.
763 if (event.detail === 1)
764 WebInspector.followLinkTimeout = setTimeout(followLink, 333);
771 WebInspector.openResource = function(resourceURL, inResourcesPanel)
773 var resource = WebInspector.resourceForURL(resourceURL);
774 if (inResourcesPanel && resource) {
775 WebInspector.panels.resources.showResource(resource);
776 WebInspector.showPanel("resources");
778 InspectorBackend.openInInspectedWindow(resource ? resource.url : resourceURL);
781 WebInspector._registerShortcuts = function()
783 var shortcut = WebInspector.KeyboardShortcut;
784 var section = WebInspector.shortcutsHelp.section(WebInspector.UIString("All Panels"));
786 shortcut.shortcutToString("]", shortcut.Modifiers.CtrlOrMeta),
787 shortcut.shortcutToString("[", shortcut.Modifiers.CtrlOrMeta)
789 section.addRelatedKeys(keys, WebInspector.UIString("Next/previous panel"));
790 section.addKey(shortcut.shortcutToString(shortcut.Keys.Esc), WebInspector.UIString("Toggle console"));
791 section.addKey(shortcut.shortcutToString("f", shortcut.Modifiers.CtrlOrMeta), WebInspector.UIString("Search"));
793 shortcut.shortcutToString("g", shortcut.Modifiers.CtrlOrMeta),
794 shortcut.shortcutToString("g", shortcut.Modifiers.CtrlOrMeta | shortcut.Modifiers.Shift)
796 section.addRelatedKeys(keys, WebInspector.UIString("Find next/previous"));
799 WebInspector.documentKeyDown = function(event)
801 var isInputElement = event.target.nodeName === "INPUT";
802 var isInEditMode = event.target.enclosingNodeOrSelfWithClass("text-prompt") || WebInspector.isEditingAnyField();
803 const helpKey = WebInspector.isMac() ? "U+003F" : "U+00BF"; // "?" for both platforms
805 if (event.keyIdentifier === "F1" ||
806 (event.keyIdentifier === helpKey && event.shiftKey && (!isInEditMode && !isInputElement || event.metaKey))) {
807 WebInspector.shortcutsHelp.show();
808 event.stopPropagation();
809 event.preventDefault();
813 if (WebInspector.isEditingAnyField())
816 if (this.currentFocusElement && this.currentFocusElement.handleKeyEvent) {
817 this.currentFocusElement.handleKeyEvent(event);
819 event.preventDefault();
824 if (this.currentPanel && this.currentPanel.handleShortcut) {
825 this.currentPanel.handleShortcut(event);
827 event.preventDefault();
832 var isMac = WebInspector.isMac();
833 switch (event.keyIdentifier) {
835 var isBackKey = !isInEditMode && (isMac ? event.metaKey : event.ctrlKey);
836 if (isBackKey && this._panelHistory.canGoBack()) {
837 this._panelHistory.goBack();
838 event.preventDefault();
843 var isForwardKey = !isInEditMode && (isMac ? event.metaKey : event.ctrlKey);
844 if (isForwardKey && this._panelHistory.canGoForward()) {
845 this._panelHistory.goForward();
846 event.preventDefault();
850 case "U+001B": // Escape key
851 event.preventDefault();
852 if (this.drawer.fullPanel)
855 this.drawer.visible = !this.drawer.visible;
858 case "U+0046": // F key
860 var isFindKey = event.metaKey && !event.ctrlKey && !event.altKey && !event.shiftKey;
862 var isFindKey = event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey;
865 WebInspector.focusSearchField();
866 event.preventDefault();
872 WebInspector.focusSearchField();
873 event.preventDefault();
877 case "U+0047": // G key
879 var isFindAgainKey = event.metaKey && !event.ctrlKey && !event.altKey;
881 var isFindAgainKey = event.ctrlKey && !event.metaKey && !event.altKey;
883 if (isFindAgainKey) {
884 if (event.shiftKey) {
885 if (this.currentPanel.jumpToPreviousSearchResult)
886 this.currentPanel.jumpToPreviousSearchResult();
887 } else if (this.currentPanel.jumpToNextSearchResult)
888 this.currentPanel.jumpToNextSearchResult();
889 event.preventDefault();
894 // Windows and Mac have two different definitions of [, so accept both.
896 case "U+00DB": // [ key
898 var isRotateLeft = event.metaKey && !event.shiftKey && !event.ctrlKey && !event.altKey;
900 var isRotateLeft = event.ctrlKey && !event.shiftKey && !event.metaKey && !event.altKey;
903 var index = this.panelOrder.indexOf(this.currentPanel);
904 index = (index === 0) ? this.panelOrder.length - 1 : index - 1;
905 this.panelOrder[index].toolbarItem.click();
906 event.preventDefault();
911 // Windows and Mac have two different definitions of ], so accept both.
913 case "U+00DD": // ] key
915 var isRotateRight = event.metaKey && !event.shiftKey && !event.ctrlKey && !event.altKey;
917 var isRotateRight = event.ctrlKey && !event.shiftKey && !event.metaKey && !event.altKey;
920 var index = this.panelOrder.indexOf(this.currentPanel);
921 index = (index + 1) % this.panelOrder.length;
922 this.panelOrder[index].toolbarItem.click();
923 event.preventDefault();
928 case "U+0052": // R key
929 if ((event.metaKey && isMac) || (event.ctrlKey && !isMac)) {
930 InspectorBackend.reloadPage();
931 event.preventDefault();
936 InspectorBackend.reloadPage();
941 WebInspector.documentCanCopy = function(event)
943 if (this.currentPanel && this.currentPanel.handleCopyEvent)
944 event.preventDefault();
947 WebInspector.documentCopy = function(event)
949 if (this.currentPanel && this.currentPanel.handleCopyEvent)
950 this.currentPanel.handleCopyEvent(event);
953 WebInspector.contextMenuEventFired = function(event)
955 if (event.handled || event.target.hasStyleClass("popup-glasspane"))
956 event.preventDefault();
959 WebInspector.animateStyle = function(animations, duration, callback)
964 const intervalDuration = (1000 / 30); // 30 frames per second.
965 const animationsLength = animations.length;
966 const propertyUnit = {opacity: ""};
967 const defaultUnit = "px";
969 function cubicInOut(t, b, c, d)
971 if ((t/=d/2) < 1) return c/2*t*t*t + b;
972 return c/2*((t-=2)*t*t + 2) + b;
975 // Pre-process animations.
976 for (var i = 0; i < animationsLength; ++i) {
977 var animation = animations[i];
978 var element = null, start = null, end = null, key = null;
979 for (key in animation) {
980 if (key === "element")
981 element = animation[key];
982 else if (key === "start")
983 start = animation[key];
984 else if (key === "end")
985 end = animation[key];
988 if (!element || !end)
992 var computedStyle = element.ownerDocument.defaultView.getComputedStyle(element);
995 start[key] = parseInt(computedStyle.getPropertyValue(key));
996 animation.start = start;
999 element.style.setProperty(key, start[key] + (key in propertyUnit ? propertyUnit[key] : defaultUnit));
1002 function animateLoop()
1005 complete += intervalDuration;
1006 var next = complete + intervalDuration;
1008 // Make style changes.
1009 for (var i = 0; i < animationsLength; ++i) {
1010 var animation = animations[i];
1011 var element = animation.element;
1012 var start = animation.start;
1013 var end = animation.end;
1014 if (!element || !end)
1017 var style = element.style;
1019 var endValue = end[key];
1020 if (next < duration) {
1021 var startValue = start[key];
1022 var newValue = cubicInOut(complete, startValue, endValue - startValue, duration);
1023 style.setProperty(key, newValue + (key in propertyUnit ? propertyUnit[key] : defaultUnit));
1025 style.setProperty(key, endValue + (key in propertyUnit ? propertyUnit[key] : defaultUnit));
1030 if (complete >= duration) {
1031 clearInterval(interval);
1037 interval = setInterval(animateLoop, intervalDuration);
1041 WebInspector.updateSearchLabel = function()
1043 if (!this.currentPanel)
1046 var newLabel = WebInspector.UIString("Search %s", this.currentPanel.toolbarItemLabel);
1048 document.getElementById("search").setAttribute("placeholder", newLabel);
1050 document.getElementById("search").removeAttribute("placeholder");
1051 document.getElementById("search-toolbar-label").textContent = newLabel;
1055 WebInspector.focusSearchField = function()
1057 var searchField = document.getElementById("search");
1058 searchField.focus();
1059 searchField.select();
1062 WebInspector.toggleAttach = function()
1065 InspectorFrontendHost.requestAttachWindow();
1067 InspectorFrontendHost.requestDetachWindow();
1070 WebInspector.toolbarDragStart = function(event)
1072 if ((!WebInspector.attached && WebInspector.platformFlavor !== WebInspector.PlatformFlavor.MacLeopard && WebInspector.platformFlavor !== WebInspector.PlatformFlavor.MacSnowLeopard) || WebInspector.port == "qt")
1075 var target = event.target;
1076 if (target.hasStyleClass("toolbar-item") && target.hasStyleClass("toggleable"))
1079 var toolbar = document.getElementById("toolbar");
1080 if (target !== toolbar && !target.hasStyleClass("toolbar-item"))
1083 toolbar.lastScreenX = event.screenX;
1084 toolbar.lastScreenY = event.screenY;
1086 WebInspector.elementDragStart(toolbar, WebInspector.toolbarDrag, WebInspector.toolbarDragEnd, event, (WebInspector.attached ? "row-resize" : "default"));
1089 WebInspector.toolbarDragEnd = function(event)
1091 var toolbar = document.getElementById("toolbar");
1093 WebInspector.elementDragEnd(event);
1095 delete toolbar.lastScreenX;
1096 delete toolbar.lastScreenY;
1099 WebInspector.toolbarDrag = function(event)
1101 var toolbar = document.getElementById("toolbar");
1103 if (WebInspector.attached) {
1104 var height = window.innerHeight - (event.screenY - toolbar.lastScreenY);
1106 InspectorFrontendHost.setAttachedWindowHeight(height);
1108 var x = event.screenX - toolbar.lastScreenX;
1109 var y = event.screenY - toolbar.lastScreenY;
1111 // We cannot call window.moveBy here because it restricts the movement
1112 // of the window at the edges.
1113 InspectorFrontendHost.moveWindowBy(x, y);
1116 toolbar.lastScreenX = event.screenX;
1117 toolbar.lastScreenY = event.screenY;
1119 event.preventDefault();
1122 WebInspector.elementDragStart = function(element, dividerDrag, elementDragEnd, event, cursor)
1124 if (this._elementDraggingEventListener || this._elementEndDraggingEventListener)
1125 this.elementDragEnd(event);
1127 this._elementDraggingEventListener = dividerDrag;
1128 this._elementEndDraggingEventListener = elementDragEnd;
1130 document.addEventListener("mousemove", dividerDrag, true);
1131 document.addEventListener("mouseup", elementDragEnd, true);
1133 document.body.style.cursor = cursor;
1135 event.preventDefault();
1138 WebInspector.elementDragEnd = function(event)
1140 document.removeEventListener("mousemove", this._elementDraggingEventListener, true);
1141 document.removeEventListener("mouseup", this._elementEndDraggingEventListener, true);
1143 document.body.style.removeProperty("cursor");
1145 delete this._elementDraggingEventListener;
1146 delete this._elementEndDraggingEventListener;
1148 event.preventDefault();
1151 WebInspector.toggleSearchingForNode = function()
1153 if (this.panels.elements) {
1154 this.showPanel("elements");
1155 this.panels.elements.toggleSearchingForNode();
1159 WebInspector.showConsole = function()
1161 this.drawer.showView(this.console);
1164 WebInspector.showChanges = function()
1166 this.drawer.showView(this.changes);
1169 WebInspector.showPanel = function(panel)
1171 if (!(panel in this.panels))
1173 this.currentPanel = this.panels[panel];
1176 WebInspector.selectDatabase = function(o)
1178 WebInspector.showPanel("resources");
1179 WebInspector.panels.resources.selectDatabase(o);
1182 WebInspector.consoleMessagesCleared = function()
1184 WebInspector.console.clearMessages();
1187 WebInspector.selectDOMStorage = function(o)
1189 WebInspector.showPanel("resources");
1190 WebInspector.panels.resources.selectDOMStorage(o);
1193 WebInspector.domContentEventFired = function(time)
1195 this.panels.audits.mainResourceDOMContentTime = time;
1196 if (this.panels.network)
1197 this.panels.network.mainResourceDOMContentTime = time;
1198 this.extensionServer.notifyPageDOMContentLoaded((time - WebInspector.mainResource.startTime) * 1000);
1199 this.mainResourceDOMContentTime = time;
1202 WebInspector.loadEventFired = function(time)
1204 this.panels.audits.mainResourceLoadTime = time;
1205 if (this.panels.network)
1206 this.panels.network.mainResourceLoadTime = time;
1207 this.extensionServer.notifyPageLoaded((time - WebInspector.mainResource.startTime) * 1000);
1208 this.mainResourceLoadTime = time;
1211 WebInspector.addDatabase = function(payload)
1213 if (!this.panels.resources)
1215 var database = new WebInspector.Database(
1220 this.panels.resources.addDatabase(database);
1223 WebInspector.addDOMStorage = function(payload)
1225 if (!this.panels.resources)
1227 var domStorage = new WebInspector.DOMStorage(
1230 payload.isLocalStorage);
1231 this.panels.resources.addDOMStorage(domStorage);
1234 WebInspector.updateDOMStorage = function(storageId)
1236 this.panels.resources.updateDOMStorage(storageId);
1239 WebInspector.updateApplicationCacheStatus = function(status)
1241 this.panels.resources.updateApplicationCacheStatus(status);
1244 WebInspector.didGetFileSystemPath = function(root, type, origin)
1246 this.panels.resources.updateFileSystemPath(root, type, origin);
1249 WebInspector.didGetFileSystemError = function(type, origin)
1251 this.panels.resources.updateFileSystemError(type, origin);
1254 WebInspector.didGetFileSystemDisabled = function()
1256 this.panels.resources.setFileSystemDisabled();
1259 WebInspector.updateNetworkState = function(isNowOnline)
1261 this.panels.resources.updateNetworkState(isNowOnline);
1264 WebInspector.searchingForNodeWasEnabled = function()
1266 this.panels.elements.searchingForNodeWasEnabled();
1269 WebInspector.searchingForNodeWasDisabled = function()
1271 this.panels.elements.searchingForNodeWasDisabled();
1274 WebInspector.attachDebuggerWhenShown = function()
1276 this.panels.scripts.attachDebuggerWhenShown();
1279 WebInspector.debuggerWasEnabled = function()
1281 this.panels.scripts.debuggerWasEnabled();
1284 WebInspector.debuggerWasDisabled = function()
1286 this.panels.scripts.debuggerWasDisabled();
1289 WebInspector.profilerWasEnabled = function()
1291 this.panels.profiles.profilerWasEnabled();
1294 WebInspector.profilerWasDisabled = function()
1296 this.panels.profiles.profilerWasDisabled();
1299 WebInspector.parsedScriptSource = function(sourceID, sourceURL, source, startingLine, scriptWorldType)
1301 this.panels.scripts.addScript(sourceID, sourceURL, source, startingLine, undefined, undefined, scriptWorldType);
1304 WebInspector.restoredBreakpoint = function(sourceID, sourceURL, line, enabled, condition)
1306 this.debuggerModel.breakpointRestored(sourceID, sourceURL, line, enabled, condition);
1309 WebInspector.failedToParseScriptSource = function(sourceURL, source, startingLine, errorLine, errorMessage)
1311 this.panels.scripts.addScript(null, sourceURL, source, startingLine, errorLine, errorMessage);
1314 WebInspector.pausedScript = function(details)
1316 this.debuggerModel.debuggerPaused(details);
1319 WebInspector.resumedScript = function()
1321 this.debuggerModel.debuggerResumed();
1324 WebInspector.reset = function()
1326 this.debuggerModel.reset();
1327 this.breakpointManager.reset();
1329 for (var panelName in this.panels) {
1330 var panel = this.panels[panelName];
1331 if ("reset" in panel)
1335 this.resources = {};
1336 this.highlightDOMNode(0);
1338 this.console.clearMessages();
1339 this.extensionServer.notifyInspectorReset();
1341 this.breakpointManager.restoreBreakpoints();
1344 WebInspector.resetProfilesPanel = function()
1346 if (WebInspector.panels.profiles)
1347 WebInspector.panels.profiles.resetProfiles();
1350 WebInspector.bringToFront = function()
1352 InspectorFrontendHost.bringToFront();
1355 WebInspector.inspectedURLChanged = function(url)
1357 InspectorFrontendHost.inspectedURLChanged(url);
1358 this.settings.inspectedURLChanged(url);
1359 this.extensionServer.notifyInspectedURLChanged();
1360 if (!this._breakpointsRestored) {
1361 this.breakpointManager.restoreBreakpoints();
1362 this._breakpointsRestored = true;
1366 WebInspector.didCommitLoad = function()
1368 // Cleanup elements panel early on inspected page refresh.
1369 WebInspector.domAgent.setDocument(null);
1372 WebInspector.updateConsoleMessageExpiredCount = function(count)
1374 var message = String.sprintf(WebInspector.UIString("%d console messages are not shown."), count);
1375 WebInspector.console.addMessage(WebInspector.ConsoleMessage.createTextMessage(message, WebInspector.ConsoleMessage.MessageLevel.Warning));
1378 WebInspector.addConsoleMessage = function(payload)
1380 var consoleMessage = new WebInspector.ConsoleMessage(
1386 payload.repeatCount,
1391 this.console.addMessage(consoleMessage);
1394 WebInspector.updateConsoleMessageRepeatCount = function(count)
1396 this.console.updateMessageRepeatCount(count);
1399 WebInspector.log = function(message, messageLevel)
1401 // remember 'this' for setInterval() callback
1404 // return indication if we can actually log a message
1405 function isLogAvailable()
1407 return WebInspector.ConsoleMessage && WebInspector.RemoteObject && self.console;
1410 // flush the queue of pending messages
1411 function flushQueue()
1413 var queued = WebInspector.log.queued;
1417 for (var i = 0; i < queued.length; ++i)
1418 logMessage(queued[i]);
1420 delete WebInspector.log.queued;
1423 // flush the queue if it console is available
1424 // - this function is run on an interval
1425 function flushQueueIfAvailable()
1427 if (!isLogAvailable())
1430 clearInterval(WebInspector.log.interval);
1431 delete WebInspector.log.interval;
1436 // actually log the message
1437 function logMessage(message)
1439 var repeatCount = 1;
1440 if (message == WebInspector.log.lastMessage)
1441 repeatCount = WebInspector.log.repeatCount + 1;
1443 WebInspector.log.lastMessage = message;
1444 WebInspector.log.repeatCount = repeatCount;
1446 // ConsoleMessage expects a proxy object
1447 message = new WebInspector.RemoteObject.fromPrimitiveValue(message);
1450 var msg = new WebInspector.ConsoleMessage(
1451 WebInspector.ConsoleMessage.MessageSource.Other,
1452 WebInspector.ConsoleMessage.MessageType.Log,
1453 messageLevel || WebInspector.ConsoleMessage.MessageLevel.Debug,
1461 self.console.addMessage(msg);
1464 // if we can't log the message, queue it
1465 if (!isLogAvailable()) {
1466 if (!WebInspector.log.queued)
1467 WebInspector.log.queued = [];
1469 WebInspector.log.queued.push(message);
1471 if (!WebInspector.log.interval)
1472 WebInspector.log.interval = setInterval(flushQueueIfAvailable, 1000);
1477 // flush the pending queue if any
1481 logMessage(message);
1484 WebInspector.addProfileHeader = function(profile)
1486 this.panels.profiles.addProfileHeader(profile);
1489 WebInspector.setRecordingProfile = function(isProfiling)
1491 this.panels.profiles.getProfileType(WebInspector.CPUProfileType.TypeId).setRecordingProfile(isProfiling);
1492 if (this.panels.profiles.hasTemporaryProfile(WebInspector.CPUProfileType.TypeId) !== isProfiling) {
1493 if (!this._temporaryRecordingProfile) {
1494 this._temporaryRecordingProfile = {
1495 typeId: WebInspector.CPUProfileType.TypeId,
1496 title: WebInspector.UIString("Recording…"),
1502 this.panels.profiles.addProfileHeader(this._temporaryRecordingProfile);
1504 this.panels.profiles.removeProfileHeader(this._temporaryRecordingProfile);
1506 this.panels.profiles.updateProfileTypeButtons();
1509 WebInspector.addHeapSnapshotChunk = function(uid, chunk)
1511 this.panels.profiles.addHeapSnapshotChunk(uid, chunk);
1514 WebInspector.finishHeapSnapshot = function(uid)
1516 this.panels.profiles.finishHeapSnapshot(uid);
1519 WebInspector.drawLoadingPieChart = function(canvas, percent) {
1520 var g = canvas.getContext("2d");
1521 var darkColor = "rgb(122, 168, 218)";
1522 var lightColor = "rgb(228, 241, 251)";
1528 g.arc(cx, cy, r, 0, Math.PI * 2, false);
1532 g.strokeStyle = darkColor;
1533 g.fillStyle = lightColor;
1537 var startangle = -Math.PI / 2;
1538 var endangle = startangle + (percent * Math.PI * 2);
1542 g.arc(cx, cy, r, startangle, endangle, false);
1545 g.fillStyle = darkColor;
1549 WebInspector.updateFocusedNode = function(nodeId)
1551 this._updateFocusedNode(nodeId);
1552 this.highlightDOMNodeForTwoSeconds(nodeId);
1555 WebInspector.displayNameForURL = function(url)
1560 var resource = this.resourceForURL(url);
1562 return resource.displayName;
1564 if (!WebInspector.mainResource)
1565 return url.trimURL("");
1567 var lastPathComponent = WebInspector.mainResource.lastPathComponent;
1568 var index = WebInspector.mainResource.url.indexOf(lastPathComponent);
1569 if (index !== -1 && index + lastPathComponent.length === WebInspector.mainResource.url.length) {
1570 var baseURL = WebInspector.mainResource.url.substring(0, index);
1571 if (url.indexOf(baseURL) === 0)
1572 return url.substring(index);
1575 return url.trimURL(WebInspector.mainResource.domain);
1578 WebInspector._choosePanelToShowSourceLine = function(url, line, preferredPanel)
1580 preferredPanel = preferredPanel || "resources";
1582 var panel = this.panels[preferredPanel];
1583 if (panel && panel.canShowSourceLine(url, line))
1585 panel = this.panels.resources;
1586 return panel.canShowSourceLine(url, line) ? panel : null;
1589 WebInspector.canShowSourceLine = function(url, line, preferredPanel)
1591 return !!this._choosePanelToShowSourceLine(url, line, preferredPanel);
1594 WebInspector.showSourceLine = function(url, line, preferredPanel)
1596 this.currentPanel = this._choosePanelToShowSourceLine(url, line, preferredPanel);
1597 if (!this.currentPanel)
1599 this.currentPanel.showSourceLine(url, line);
1603 WebInspector.linkifyStringAsFragment = function(string)
1605 var container = document.createDocumentFragment();
1606 var linkStringRegEx = /(?:[a-zA-Z][a-zA-Z0-9+.-]{2,}:\/\/|www\.)[\w$\-_+*'=\|\/\\(){}[\]%@&#~,:;.!?]{2,}[\w$\-_+*=\|\/\\({%@&#~]/;
1607 var lineColumnRegEx = /:(\d+)(:(\d+))?$/;
1610 var linkString = linkStringRegEx.exec(string);
1614 linkString = linkString[0];
1615 var title = linkString;
1616 var linkIndex = string.indexOf(linkString);
1617 var nonLink = string.substring(0, linkIndex);
1618 container.appendChild(document.createTextNode(nonLink));
1620 var profileStringMatches = WebInspector.ProfileType.URLRegExp.exec(title);
1621 if (profileStringMatches)
1622 title = WebInspector.panels.profiles.displayTitleForProfileLink(profileStringMatches[2], profileStringMatches[1]);
1624 var realURL = (linkString.indexOf("www.") === 0 ? "http://" + linkString : linkString);
1625 var lineColumnMatch = lineColumnRegEx.exec(realURL);
1626 if (lineColumnMatch)
1627 realURL = realURL.substring(0, realURL.length - lineColumnMatch[0].length);
1629 var hasResourceWithURL = !!WebInspector.resourceForURL(realURL);
1630 var urlNode = WebInspector.linkifyURLAsNode(realURL, title, null, hasResourceWithURL);
1631 container.appendChild(urlNode);
1632 if (lineColumnMatch) {
1633 urlNode.setAttribute("line_number", lineColumnMatch[1]);
1634 urlNode.setAttribute("preferred_panel", "scripts");
1636 string = string.substring(linkIndex + linkString.length, string.length);
1640 container.appendChild(document.createTextNode(string));
1645 WebInspector.showProfileForURL = function(url)
1647 WebInspector.showPanel("profiles");
1648 WebInspector.panels.profiles.showProfileForURL(url);
1651 WebInspector.linkifyURLAsNode = function(url, linkText, classes, isExternal, tooltipText)
1655 classes = (classes ? classes + " " : "");
1656 classes += isExternal ? "webkit-html-external-link" : "webkit-html-resource-link";
1658 var a = document.createElement("a");
1660 a.className = classes;
1661 if (typeof tooltipText === "undefined")
1663 else if (typeof tooltipText !== "string" || tooltipText.length)
1664 a.title = tooltipText;
1665 a.textContent = linkText;
1670 WebInspector.linkifyURL = function(url, linkText, classes, isExternal, tooltipText)
1672 // Use the DOM version of this function so as to avoid needing to escape attributes.
1673 // FIXME: Get rid of linkifyURL entirely.
1674 return WebInspector.linkifyURLAsNode(url, linkText, classes, isExternal, tooltipText).outerHTML;
1677 WebInspector.linkifyResourceAsNode = function(url, preferredPanel, lineNumber, classes, tooltipText)
1679 var linkText = WebInspector.displayNameForURL(url);
1681 linkText += ":" + lineNumber;
1682 var node = WebInspector.linkifyURLAsNode(url, linkText, classes, false, tooltipText);
1683 node.setAttribute("line_number", lineNumber);
1684 node.setAttribute("preferred_panel", preferredPanel);
1688 WebInspector.resourceURLForRelatedNode = function(node, url)
1690 if (!url || url.indexOf("://") > 0)
1693 for (var frameOwnerCandidate = node; frameOwnerCandidate; frameOwnerCandidate = frameOwnerCandidate.parentNode) {
1694 if (frameOwnerCandidate.documentURL) {
1695 var result = WebInspector.completeURL(frameOwnerCandidate.documentURL, url);
1702 // documentURL not found or has bad value
1703 var resourceURL = url;
1704 function callback(resource)
1706 if (resource.path === url) {
1707 resourceURL = resource.url;
1711 WebInspector.forAllResources(callback);
1715 WebInspector.completeURL = function(baseURL, href)
1717 var parsedURL = baseURL.asParsedURL();
1720 if (path.charAt(0) !== "/") {
1721 var basePath = parsedURL.path;
1722 path = basePath.substring(0, basePath.lastIndexOf("/")) + "/" + path;
1723 } else if (path.length > 1 && path.charAt(1) === "/") {
1724 // href starts with "//" which is a full URL with the protocol dropped (use the baseURL protocol).
1725 return parsedURL.scheme + ":" + path;
1727 return parsedURL.scheme + "://" + parsedURL.host + (parsedURL.port ? (":" + parsedURL.port) : "") + path;
1732 WebInspector.addMainEventListeners = function(doc)
1734 doc.defaultView.addEventListener("focus", this.windowFocused.bind(this), false);
1735 doc.defaultView.addEventListener("blur", this.windowBlurred.bind(this), false);
1736 doc.addEventListener("click", this.documentClick.bind(this), true);
1739 WebInspector._searchFieldManualFocus = function(event)
1741 this.currentFocusElement = event.target;
1742 this._previousFocusElement = event.target;
1745 WebInspector._searchKeyDown = function(event)
1747 // Escape Key will clear the field and clear the search results
1748 if (event.keyCode === WebInspector.KeyboardShortcut.Keys.Esc.code) {
1749 // If focus belongs here and text is empty - nothing to do, return unhandled.
1750 if (event.target.value === "" && this.currentFocusElement === this.previousFocusElement)
1752 event.preventDefault();
1753 event.stopPropagation();
1754 // When search was selected manually and is currently blank, we'd like Esc stay unhandled
1755 // and hit console drawer handler.
1756 event.target.value = "";
1758 this.performSearch(event);
1759 this.currentFocusElement = this.previousFocusElement;
1760 if (this.currentFocusElement === event.target)
1761 this.currentFocusElement.select();
1765 if (!isEnterKey(event))
1768 // Select all of the text so the user can easily type an entirely new query.
1769 event.target.select();
1771 // Only call performSearch if the Enter key was pressed. Otherwise the search
1772 // performance is poor because of searching on every key. The search field has
1773 // the incremental attribute set, so we still get incremental searches.
1774 this.performSearch(event);
1776 // Call preventDefault since this was the Enter key. This prevents a "search" event
1777 // from firing for key down. This stops performSearch from being called twice in a row.
1778 event.preventDefault();
1781 WebInspector.performSearch = function(event)
1783 var forceSearch = event.keyIdentifier === "Enter";
1784 this.doPerformSearch(event.target.value, forceSearch, event.shiftKey, false);
1787 WebInspector.doPerformSearch = function(query, forceSearch, isBackwardSearch, repeatSearch)
1789 var isShortSearch = (query.length < 3);
1791 // Clear a leftover short search flag due to a non-conflicting forced search.
1792 if (isShortSearch && this.shortSearchWasForcedByKeyEvent && this.currentQuery !== query)
1793 delete this.shortSearchWasForcedByKeyEvent;
1795 // Indicate this was a forced search on a short query.
1796 if (isShortSearch && forceSearch)
1797 this.shortSearchWasForcedByKeyEvent = true;
1799 if (!query || !query.length || (!forceSearch && isShortSearch)) {
1800 // Prevent clobbering a short search forced by the user.
1801 if (this.shortSearchWasForcedByKeyEvent) {
1802 delete this.shortSearchWasForcedByKeyEvent;
1806 delete this.currentQuery;
1808 for (var panelName in this.panels) {
1809 var panel = this.panels[panelName];
1810 var hadCurrentQuery = !!panel.currentQuery;
1811 delete panel.currentQuery;
1812 if (hadCurrentQuery && panel.searchCanceled)
1813 panel.searchCanceled();
1816 this.updateSearchMatchesCount();
1821 if (!repeatSearch && query === this.currentPanel.currentQuery && this.currentPanel.currentQuery === this.currentQuery) {
1822 // When this is the same query and a forced search, jump to the next
1823 // search result for a good user experience.
1825 if (!isBackwardSearch && this.currentPanel.jumpToNextSearchResult)
1826 this.currentPanel.jumpToNextSearchResult();
1827 else if (isBackwardSearch && this.currentPanel.jumpToPreviousSearchResult)
1828 this.currentPanel.jumpToPreviousSearchResult();
1833 this.currentQuery = query;
1835 this.updateSearchMatchesCount();
1837 if (!this.currentPanel.performSearch)
1840 this.currentPanel.currentQuery = query;
1841 this.currentPanel.performSearch(query);
1844 WebInspector.addNodesToSearchResult = function(nodeIds)
1846 WebInspector.panels.elements.addNodesToSearchResult(nodeIds);
1849 WebInspector.updateSearchMatchesCount = function(matches, panel)
1852 panel = this.currentPanel;
1854 panel.currentSearchMatches = matches;
1856 if (panel !== this.currentPanel)
1859 if (!this.currentPanel.currentQuery) {
1860 document.getElementById("search-results-matches").addStyleClass("hidden");
1866 var matchesString = WebInspector.UIString("1 match");
1868 var matchesString = WebInspector.UIString("%d matches", matches);
1870 var matchesString = WebInspector.UIString("Not Found");
1872 var matchesToolbarElement = document.getElementById("search-results-matches");
1873 matchesToolbarElement.removeStyleClass("hidden");
1874 matchesToolbarElement.textContent = matchesString;
1877 WebInspector.UIString = function(string)
1879 if (window.localizedStrings && string in window.localizedStrings)
1880 string = window.localizedStrings[string];
1882 if (!(string in WebInspector.missingLocalizedStrings)) {
1883 if (!WebInspector.InspectorBackendStub)
1884 console.error("Localized string \"" + string + "\" not found.");
1885 WebInspector.missingLocalizedStrings[string] = true;
1888 if (Preferences.showMissingLocalizedStrings)
1889 string += " (not localized)";
1892 return String.vsprintf(string, Array.prototype.slice.call(arguments, 1));
1895 WebInspector.formatLocalized = function(format, substitutions, formatters, initialValue, append)
1897 return String.format(WebInspector.UIString(format), substitutions, formatters, initialValue, append);
1900 WebInspector.isMac = function()
1902 if (!("_isMac" in this))
1903 this._isMac = WebInspector.platform === "mac";
1908 WebInspector.isBeingEdited = function(element)
1910 return element.__editing;
1913 WebInspector.isEditingAnyField = function()
1915 return this.__editing;
1918 // Available config fields (all optional):
1919 // context: Object - an arbitrary context object to be passed to the commit and cancel handlers
1920 // commitHandler: Function - handles editing "commit" outcome
1921 // cancelHandler: Function - handles editing "cancel" outcome
1922 // customFinishHandler: Function - custom finish handler for the editing session (invoked on keydown)
1923 // multiline: Boolean - whether the edited element is multiline
1924 WebInspector.startEditing = function(element, config)
1926 if (element.__editing)
1928 element.__editing = true;
1929 WebInspector.__editing = true;
1931 config = config || {};
1932 var committedCallback = config.commitHandler;
1933 var cancelledCallback = config.cancelHandler;
1934 var context = config.context;
1935 var oldText = getContent(element);
1936 var moveDirection = "";
1938 element.addStyleClass("editing");
1940 var oldTabIndex = element.tabIndex;
1941 if (element.tabIndex < 0)
1942 element.tabIndex = 0;
1944 function blurEventListener() {
1945 editingCommitted.call(element);
1948 function getContent(element) {
1949 if (element.tagName === "INPUT" && element.type === "text")
1950 return element.value;
1952 return element.textContent;
1955 function cleanUpAfterEditing() {
1956 delete this.__editing;
1957 delete WebInspector.__editing;
1959 this.removeStyleClass("editing");
1960 this.tabIndex = oldTabIndex;
1962 this.scrollLeft = 0;
1964 element.removeEventListener("blur", blurEventListener, false);
1965 element.removeEventListener("keydown", keyDownEventListener, true);
1967 if (element === WebInspector.currentFocusElement || element.isAncestor(WebInspector.currentFocusElement))
1968 WebInspector.currentFocusElement = WebInspector.previousFocusElement;
1971 function editingCancelled() {
1972 if (this.tagName === "INPUT" && this.type === "text")
1973 this.value = oldText;
1975 this.textContent = oldText;
1977 cleanUpAfterEditing.call(this);
1979 if (cancelledCallback)
1980 cancelledCallback(this, context);
1983 function editingCommitted() {
1984 cleanUpAfterEditing.call(this);
1986 if (committedCallback)
1987 committedCallback(this, getContent(this), oldText, context, moveDirection);
1990 function defaultFinishHandler(event)
1992 var isMetaOrCtrl = WebInspector.isMac() ?
1993 event.metaKey && !event.shiftKey && !event.ctrlKey && !event.altKey :
1994 event.ctrlKey && !event.shiftKey && !event.metaKey && !event.altKey;
1995 if (isEnterKey(event) && (!config.multiline || isMetaOrCtrl))
1997 else if (event.keyCode === WebInspector.KeyboardShortcut.Keys.Esc.code)
1999 else if (event.keyIdentifier === "U+0009") // Tab key
2000 return "move-" + (event.shiftKey ? "backward" : "forward");
2003 function keyDownEventListener(event)
2005 var handler = config.customFinishHandler || defaultFinishHandler;
2006 var result = handler(event);
2007 if (result === "commit") {
2008 editingCommitted.call(element);
2009 event.preventDefault();
2010 event.stopPropagation();
2011 } else if (result === "cancel") {
2012 editingCancelled.call(element);
2013 event.preventDefault();
2014 event.stopPropagation();
2015 } else if (result && result.indexOf("move-") === 0) {
2016 moveDirection = result.substring(5);
2017 if (event.keyIdentifier !== "U+0009")
2018 blurEventListener();
2022 element.addEventListener("blur", blurEventListener, false);
2023 element.addEventListener("keydown", keyDownEventListener, true);
2025 WebInspector.currentFocusElement = element;
2027 cancel: editingCancelled.bind(element),
2028 commit: editingCommitted.bind(element)
2032 WebInspector._toolbarItemClicked = function(event)
2034 var toolbarItem = event.currentTarget;
2035 this.currentPanel = toolbarItem.panel;
2038 // This table maps MIME types to the Resource.Types which are valid for them.
2039 // The following line:
2040 // "text/html": {0: 1},
2041 // means that text/html is a valid MIME type for resources that have type
2042 // WebInspector.Resource.Type.Document (which has a value of 0).
2043 WebInspector.MIMETypes = {
2044 "text/html": {0: true},
2045 "text/xml": {0: true},
2046 "text/plain": {0: true},
2047 "application/xhtml+xml": {0: true},
2048 "text/css": {1: true},
2049 "text/xsl": {1: true},
2050 "image/jpeg": {2: true},
2051 "image/png": {2: true},
2052 "image/gif": {2: true},
2053 "image/bmp": {2: true},
2054 "image/vnd.microsoft.icon": {2: true},
2055 "image/x-icon": {2: true},
2056 "image/x-xbitmap": {2: true},
2057 "font/ttf": {3: true},
2058 "font/opentype": {3: true},
2059 "application/x-font-type1": {3: true},
2060 "application/x-font-ttf": {3: true},
2061 "application/x-truetype-font": {3: true},
2062 "text/javascript": {4: true},
2063 "text/ecmascript": {4: true},
2064 "application/javascript": {4: true},
2065 "application/ecmascript": {4: true},
2066 "application/x-javascript": {4: true},
2067 "text/javascript1.1": {4: true},
2068 "text/javascript1.2": {4: true},
2069 "text/javascript1.3": {4: true},
2070 "text/jscript": {4: true},
2071 "text/livescript": {4: true},
2074 WebInspector.PanelHistory = function()
2077 this._historyIterator = -1;
2080 WebInspector.PanelHistory.prototype = {
2081 canGoBack: function()
2083 return this._historyIterator > 0;
2088 this._inHistory = true;
2089 WebInspector.currentPanel = WebInspector.panels[this._history[--this._historyIterator]];
2090 delete this._inHistory;
2093 canGoForward: function()
2095 return this._historyIterator < this._history.length - 1;
2098 goForward: function()
2100 this._inHistory = true;
2101 WebInspector.currentPanel = WebInspector.panels[this._history[++this._historyIterator]];
2102 delete this._inHistory;
2105 setPanel: function(panelName)
2107 if (this._inHistory)
2110 this._history.splice(this._historyIterator + 1, this._history.length - this._historyIterator - 1);
2111 if (!this._history.length || this._history[this._history.length - 1] !== panelName)
2112 this._history.push(panelName);
2113 this._historyIterator = this._history.length - 1;