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.breakpointManager.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) { WebInspector_syncDispatch(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 this.resourceCategories = {
524 documents: new WebInspector.ResourceCategory("documents", WebInspector.UIString("Documents"), "rgb(47,102,236)"),
525 stylesheets: new WebInspector.ResourceCategory("stylesheets", WebInspector.UIString("Stylesheets"), "rgb(157,231,119)"),
526 images: new WebInspector.ResourceCategory("images", WebInspector.UIString("Images"), "rgb(164,60,255)"),
527 scripts: new WebInspector.ResourceCategory("scripts", WebInspector.UIString("Scripts"), "rgb(255,121,0)"),
528 xhr: new WebInspector.ResourceCategory("xhr", WebInspector.UIString("XHR"), "rgb(231,231,10)"),
529 fonts: new WebInspector.ResourceCategory("fonts", WebInspector.UIString("Fonts"), "rgb(255,82,62)"),
530 websockets: new WebInspector.ResourceCategory("websockets", WebInspector.UIString("WebSocket"), "rgb(186,186,186)"), // FIXME: Decide the color.
531 other: new WebInspector.ResourceCategory("other", WebInspector.UIString("Other"), "rgb(186,186,186)")
534 this.breakpointManager = new WebInspector.BreakpointManager();
535 this.cssModel = new WebInspector.CSSStyleModel();
538 this._createPanels();
539 this._panelHistory = new WebInspector.PanelHistory();
541 var toolbarElement = document.getElementById("toolbar");
542 var previousToolbarItem = toolbarElement.children[0];
544 this.panelOrder = [];
545 for (var panelName in this.panels)
546 previousToolbarItem = WebInspector.addPanelToolbarIcon(toolbarElement, this.panels[panelName], previousToolbarItem);
549 ResourceNotCompressed: {id: 0, message: WebInspector.UIString("You could save bandwidth by having your web server compress this transfer with gzip or zlib.")}
553 IncorrectMIMEType: {id: 0, message: WebInspector.UIString("Resource interpreted as %s but transferred with MIME type %s.")}
556 this.addMainEventListeners(document);
558 window.addEventListener("resize", this.windowResize.bind(this), true);
560 document.addEventListener("focus", this.focusChanged.bind(this), true);
561 document.addEventListener("keydown", this.documentKeyDown.bind(this), false);
562 document.addEventListener("beforecopy", this.documentCanCopy.bind(this), true);
563 document.addEventListener("copy", this.documentCopy.bind(this), true);
564 document.addEventListener("contextmenu", this.contextMenuEventFired.bind(this), true);
566 var dockToggleButton = document.getElementById("dock-status-bar-item");
567 dockToggleButton.addEventListener("click", this.toggleAttach.bind(this), false);
570 dockToggleButton.title = WebInspector.UIString("Undock into separate window.");
572 dockToggleButton.title = WebInspector.UIString("Dock to main window.");
574 var errorWarningCount = document.getElementById("error-warning-count");
575 errorWarningCount.addEventListener("click", this.showConsole.bind(this), false);
576 this._updateErrorAndWarningCounts();
578 this.styleChanges = 0;
579 // TODO: Uncomment when enabling the Changes Panel
580 // var changesElement = document.getElementById("changes-count");
581 // changesElement.addEventListener("click", this.showChanges.bind(this), false);
582 // this._updateErrorAndWarningCounts();
584 var searchField = document.getElementById("search");
585 searchField.addEventListener("search", this.performSearch.bind(this), false); // when the search is emptied
586 searchField.addEventListener("mousedown", this._searchFieldManualFocus.bind(this), false); // when the search field is manually selected
587 searchField.addEventListener("keydown", this._searchKeyDown.bind(this), true);
589 toolbarElement.addEventListener("mousedown", this.toolbarDragStart, true);
590 document.getElementById("close-button-left").addEventListener("click", this.close, true);
591 document.getElementById("close-button-right").addEventListener("click", this.close, true);
593 this.extensionServer.initExtensions();
595 function populateInspectorState(inspectorState)
597 WebInspector.monitoringXHREnabled = inspectorState.monitoringXHREnabled;
598 if ("pauseOnExceptionsState" in inspectorState)
599 WebInspector.panels.scripts.updatePauseOnExceptionsState(inspectorState.pauseOnExceptionsState);
601 InspectorBackend.getInspectorState(populateInspectorState);
603 function onPopulateScriptObjects()
605 if (!WebInspector.currentPanel)
606 WebInspector.showPanel(WebInspector.settings.lastActivePanel);
608 InspectorBackend.populateScriptObjects(onPopulateScriptObjects);
610 InspectorBackend.setConsoleMessagesEnabled(true);
612 // As a DOMAgent method, this needs to happen after the frontend has loaded and the agent is available.
613 InspectorBackend.getSupportedCSSProperties(WebInspector.CSSCompletions._load);
616 WebInspector.addPanelToolbarIcon = function(toolbarElement, panel, previousToolbarItem)
618 var panelToolbarItem = panel.toolbarItem;
619 this.panelOrder.push(panel);
620 panelToolbarItem.addEventListener("click", this._toolbarItemClicked.bind(this));
621 if (previousToolbarItem)
622 toolbarElement.insertBefore(panelToolbarItem, previousToolbarItem.nextSibling);
624 toolbarElement.insertBefore(panelToolbarItem, toolbarElement.firstChild);
625 return panelToolbarItem;
628 var windowLoaded = function()
630 var localizedStringsURL = InspectorFrontendHost.localizedStringsURL();
631 if (localizedStringsURL) {
632 var localizedStringsScriptElement = document.createElement("script");
633 localizedStringsScriptElement.addEventListener("load", WebInspector.loaded.bind(WebInspector), false);
634 localizedStringsScriptElement.type = "text/javascript";
635 localizedStringsScriptElement.src = localizedStringsURL;
636 document.head.appendChild(localizedStringsScriptElement);
638 WebInspector.loaded();
640 window.removeEventListener("DOMContentLoaded", windowLoaded, false);
644 window.addEventListener("DOMContentLoaded", windowLoaded, false);
646 WebInspector.dispatch = function(message) {
647 // We'd like to enforce asynchronous interaction between the inspector controller and the frontend.
648 // This is important to LayoutTests.
649 function delayDispatch()
651 WebInspector_syncDispatch(message);
652 WebInspector.pendingDispatches--;
654 WebInspector.pendingDispatches++;
655 setTimeout(delayDispatch, 0);
658 // This function is purposely put into the global scope for easy access.
659 WebInspector_syncDispatch = function(message)
661 if (window.dumpInspectorProtocolMessages)
662 console.log("backend: " + ((typeof message === "string") ? message : JSON.stringify(message)));
664 var messageObject = (typeof message === "string") ? JSON.parse(message) : message;
667 if (messageObject.data)
668 for (var key in messageObject.data)
669 arguments.push(messageObject.data[key]);
671 if ("seq" in messageObject) { // just a response for some request
672 if (messageObject.success)
673 WebInspector.processResponse(messageObject.seq, arguments);
675 WebInspector.removeResponseCallbackEntry(messageObject.seq)
676 WebInspector.reportProtocolError(messageObject);
681 if (messageObject.type === "event") {
682 if (!(messageObject.event in WebInspector)) {
683 console.error("Protocol Error: Attempted to dispatch an unimplemented WebInspector method '%s'", messageObject.event);
686 WebInspector[messageObject.event].apply(WebInspector, arguments);
690 WebInspector.dispatchMessageFromBackend = function(messageObject)
692 WebInspector.dispatch(messageObject);
695 WebInspector.reportProtocolError = function(messageObject)
697 console.error("Protocol Error: InspectorBackend request with seq = %d failed.", messageObject.seq);
698 for (var i = 0; i < messageObject.errors.length; ++i)
699 console.error(" " + messageObject.errors[i]);
700 WebInspector.removeResponseCallbackEntry(messageObject.seq);
703 WebInspector.windowResize = function(event)
705 if (this.currentPanel)
706 this.currentPanel.resize();
707 this.drawer.resize();
710 WebInspector.windowFocused = function(event)
712 // Fires after blur, so when focusing on either the main inspector
713 // or an <iframe> within the inspector we should always remove the
715 if (event.target.document.nodeType === Node.DOCUMENT_NODE)
716 document.body.removeStyleClass("inactive");
719 WebInspector.windowBlurred = function(event)
721 // Leaving the main inspector or an <iframe> within the inspector.
722 // We can add "inactive" now, and if we are moving the focus to another
723 // part of the inspector then windowFocused will correct this.
724 if (event.target.document.nodeType === Node.DOCUMENT_NODE)
725 document.body.addStyleClass("inactive");
728 WebInspector.focusChanged = function(event)
730 this.currentFocusElement = event.target;
733 WebInspector.setAttachedWindow = function(attached)
735 this.attached = attached;
738 WebInspector.close = function(event)
742 this._isClosing = true;
743 InspectorFrontendHost.closeWindow();
746 WebInspector.disconnectFromBackend = function()
748 InspectorFrontendHost.disconnectFromBackend();
751 WebInspector.documentClick = function(event)
753 var anchor = event.target.enclosingNodeOrSelfWithNodeName("a");
754 if (!anchor || anchor.target === "_blank")
757 // Prevent the link from navigating, since we don't do any navigation by following links normally.
758 event.preventDefault();
759 event.stopPropagation();
761 function followLink()
763 // FIXME: support webkit-html-external-link links here.
764 if (WebInspector.canShowSourceLine(anchor.href, anchor.getAttribute("line_number"), anchor.getAttribute("preferred_panel"))) {
765 if (anchor.hasStyleClass("webkit-html-external-link")) {
766 anchor.removeStyleClass("webkit-html-external-link");
767 anchor.addStyleClass("webkit-html-resource-link");
770 WebInspector.showSourceLine(anchor.href, anchor.getAttribute("line_number"), anchor.getAttribute("preferred_panel"));
774 const profileMatch = WebInspector.ProfileType.URLRegExp.exec(anchor.href);
776 WebInspector.showProfileForURL(anchor.href);
780 var parsedURL = anchor.href.asParsedURL();
781 if (parsedURL && parsedURL.scheme === "webkit-link-action") {
782 if (parsedURL.host === "show-panel") {
783 var panel = parsedURL.path.substring(1);
784 if (WebInspector.panels[panel])
785 WebInspector.showPanel(panel);
790 WebInspector.showPanel("resources");
793 if (WebInspector.followLinkTimeout)
794 clearTimeout(WebInspector.followLinkTimeout);
796 if (anchor.preventFollowOnDoubleClick) {
797 // Start a timeout if this is the first click, if the timeout is canceled
798 // before it fires, then a double clicked happened or another link was clicked.
799 if (event.detail === 1)
800 WebInspector.followLinkTimeout = setTimeout(followLink, 333);
807 WebInspector.openResource = function(resourceURL, inResourcesPanel)
809 var resource = WebInspector.resourceForURL(resourceURL);
810 if (inResourcesPanel && resource) {
811 WebInspector.panels.resources.showResource(resource);
812 WebInspector.showPanel("resources");
814 InspectorBackend.openInInspectedWindow(resource ? resource.url : resourceURL);
817 WebInspector._registerShortcuts = function()
819 var shortcut = WebInspector.KeyboardShortcut;
820 var section = WebInspector.shortcutsHelp.section(WebInspector.UIString("All Panels"));
822 shortcut.shortcutToString("]", shortcut.Modifiers.CtrlOrMeta),
823 shortcut.shortcutToString("[", shortcut.Modifiers.CtrlOrMeta)
825 section.addRelatedKeys(keys, WebInspector.UIString("Next/previous panel"));
826 section.addKey(shortcut.shortcutToString(shortcut.Keys.Esc), WebInspector.UIString("Toggle console"));
827 section.addKey(shortcut.shortcutToString("f", shortcut.Modifiers.CtrlOrMeta), WebInspector.UIString("Search"));
829 shortcut.shortcutToString("g", shortcut.Modifiers.CtrlOrMeta),
830 shortcut.shortcutToString("g", shortcut.Modifiers.CtrlOrMeta | shortcut.Modifiers.Shift)
832 section.addRelatedKeys(keys, WebInspector.UIString("Find next/previous"));
835 WebInspector.documentKeyDown = function(event)
837 var isInputElement = event.target.nodeName === "INPUT";
838 var isInEditMode = event.target.enclosingNodeOrSelfWithClass("text-prompt") || WebInspector.isEditingAnyField();
839 const helpKey = WebInspector.isMac() ? "U+003F" : "U+00BF"; // "?" for both platforms
841 if (event.keyIdentifier === "F1" ||
842 (event.keyIdentifier === helpKey && event.shiftKey && (!isInEditMode && !isInputElement || event.metaKey))) {
843 WebInspector.shortcutsHelp.show();
844 event.stopPropagation();
845 event.preventDefault();
849 if (WebInspector.isEditingAnyField())
852 if (this.currentFocusElement && this.currentFocusElement.handleKeyEvent) {
853 this.currentFocusElement.handleKeyEvent(event);
855 event.preventDefault();
860 if (this.currentPanel && this.currentPanel.handleShortcut) {
861 this.currentPanel.handleShortcut(event);
863 event.preventDefault();
868 var isMac = WebInspector.isMac();
869 switch (event.keyIdentifier) {
871 var isBackKey = !isInEditMode && (isMac ? event.metaKey : event.ctrlKey);
872 if (isBackKey && this._panelHistory.canGoBack()) {
873 this._panelHistory.goBack();
874 event.preventDefault();
879 var isForwardKey = !isInEditMode && (isMac ? event.metaKey : event.ctrlKey);
880 if (isForwardKey && this._panelHistory.canGoForward()) {
881 this._panelHistory.goForward();
882 event.preventDefault();
886 case "U+001B": // Escape key
887 event.preventDefault();
888 if (this.drawer.fullPanel)
891 this.drawer.visible = !this.drawer.visible;
894 case "U+0046": // F key
896 var isFindKey = event.metaKey && !event.ctrlKey && !event.altKey && !event.shiftKey;
898 var isFindKey = event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey;
901 WebInspector.focusSearchField();
902 event.preventDefault();
908 WebInspector.focusSearchField();
909 event.preventDefault();
913 case "U+0047": // G key
915 var isFindAgainKey = event.metaKey && !event.ctrlKey && !event.altKey;
917 var isFindAgainKey = event.ctrlKey && !event.metaKey && !event.altKey;
919 if (isFindAgainKey) {
920 if (event.shiftKey) {
921 if (this.currentPanel.jumpToPreviousSearchResult)
922 this.currentPanel.jumpToPreviousSearchResult();
923 } else if (this.currentPanel.jumpToNextSearchResult)
924 this.currentPanel.jumpToNextSearchResult();
925 event.preventDefault();
930 // Windows and Mac have two different definitions of [, so accept both.
932 case "U+00DB": // [ key
934 var isRotateLeft = event.metaKey && !event.shiftKey && !event.ctrlKey && !event.altKey;
936 var isRotateLeft = event.ctrlKey && !event.shiftKey && !event.metaKey && !event.altKey;
939 var index = this.panelOrder.indexOf(this.currentPanel);
940 index = (index === 0) ? this.panelOrder.length - 1 : index - 1;
941 this.panelOrder[index].toolbarItem.click();
942 event.preventDefault();
947 // Windows and Mac have two different definitions of ], so accept both.
949 case "U+00DD": // ] key
951 var isRotateRight = event.metaKey && !event.shiftKey && !event.ctrlKey && !event.altKey;
953 var isRotateRight = event.ctrlKey && !event.shiftKey && !event.metaKey && !event.altKey;
956 var index = this.panelOrder.indexOf(this.currentPanel);
957 index = (index + 1) % this.panelOrder.length;
958 this.panelOrder[index].toolbarItem.click();
959 event.preventDefault();
964 case "U+0052": // R key
965 if ((event.metaKey && isMac) || (event.ctrlKey && !isMac)) {
966 InspectorBackend.reloadPage();
967 event.preventDefault();
972 InspectorBackend.reloadPage();
977 WebInspector.documentCanCopy = function(event)
979 if (this.currentPanel && this.currentPanel.handleCopyEvent)
980 event.preventDefault();
983 WebInspector.documentCopy = function(event)
985 if (this.currentPanel && this.currentPanel.handleCopyEvent)
986 this.currentPanel.handleCopyEvent(event);
989 WebInspector.contextMenuEventFired = function(event)
991 if (event.handled || event.target.hasStyleClass("popup-glasspane"))
992 event.preventDefault();
995 WebInspector.animateStyle = function(animations, duration, callback)
1000 const intervalDuration = (1000 / 30); // 30 frames per second.
1001 const animationsLength = animations.length;
1002 const propertyUnit = {opacity: ""};
1003 const defaultUnit = "px";
1005 function cubicInOut(t, b, c, d)
1007 if ((t/=d/2) < 1) return c/2*t*t*t + b;
1008 return c/2*((t-=2)*t*t + 2) + b;
1011 // Pre-process animations.
1012 for (var i = 0; i < animationsLength; ++i) {
1013 var animation = animations[i];
1014 var element = null, start = null, end = null, key = null;
1015 for (key in animation) {
1016 if (key === "element")
1017 element = animation[key];
1018 else if (key === "start")
1019 start = animation[key];
1020 else if (key === "end")
1021 end = animation[key];
1024 if (!element || !end)
1028 var computedStyle = element.ownerDocument.defaultView.getComputedStyle(element);
1031 start[key] = parseInt(computedStyle.getPropertyValue(key));
1032 animation.start = start;
1035 element.style.setProperty(key, start[key] + (key in propertyUnit ? propertyUnit[key] : defaultUnit));
1038 function animateLoop()
1041 complete += intervalDuration;
1042 var next = complete + intervalDuration;
1044 // Make style changes.
1045 for (var i = 0; i < animationsLength; ++i) {
1046 var animation = animations[i];
1047 var element = animation.element;
1048 var start = animation.start;
1049 var end = animation.end;
1050 if (!element || !end)
1053 var style = element.style;
1055 var endValue = end[key];
1056 if (next < duration) {
1057 var startValue = start[key];
1058 var newValue = cubicInOut(complete, startValue, endValue - startValue, duration);
1059 style.setProperty(key, newValue + (key in propertyUnit ? propertyUnit[key] : defaultUnit));
1061 style.setProperty(key, endValue + (key in propertyUnit ? propertyUnit[key] : defaultUnit));
1066 if (complete >= duration) {
1067 clearInterval(interval);
1073 interval = setInterval(animateLoop, intervalDuration);
1077 WebInspector.updateSearchLabel = function()
1079 if (!this.currentPanel)
1082 var newLabel = WebInspector.UIString("Search %s", this.currentPanel.toolbarItemLabel);
1084 document.getElementById("search").setAttribute("placeholder", newLabel);
1086 document.getElementById("search").removeAttribute("placeholder");
1087 document.getElementById("search-toolbar-label").textContent = newLabel;
1091 WebInspector.focusSearchField = function()
1093 var searchField = document.getElementById("search");
1094 searchField.focus();
1095 searchField.select();
1098 WebInspector.toggleAttach = function()
1101 InspectorFrontendHost.requestAttachWindow();
1103 InspectorFrontendHost.requestDetachWindow();
1106 WebInspector.toolbarDragStart = function(event)
1108 if ((!WebInspector.attached && WebInspector.platformFlavor !== WebInspector.PlatformFlavor.MacLeopard && WebInspector.platformFlavor !== WebInspector.PlatformFlavor.MacSnowLeopard) || WebInspector.port == "qt")
1111 var target = event.target;
1112 if (target.hasStyleClass("toolbar-item") && target.hasStyleClass("toggleable"))
1115 var toolbar = document.getElementById("toolbar");
1116 if (target !== toolbar && !target.hasStyleClass("toolbar-item"))
1119 toolbar.lastScreenX = event.screenX;
1120 toolbar.lastScreenY = event.screenY;
1122 WebInspector.elementDragStart(toolbar, WebInspector.toolbarDrag, WebInspector.toolbarDragEnd, event, (WebInspector.attached ? "row-resize" : "default"));
1125 WebInspector.toolbarDragEnd = function(event)
1127 var toolbar = document.getElementById("toolbar");
1129 WebInspector.elementDragEnd(event);
1131 delete toolbar.lastScreenX;
1132 delete toolbar.lastScreenY;
1135 WebInspector.toolbarDrag = function(event)
1137 var toolbar = document.getElementById("toolbar");
1139 if (WebInspector.attached) {
1140 var height = window.innerHeight - (event.screenY - toolbar.lastScreenY);
1142 InspectorFrontendHost.setAttachedWindowHeight(height);
1144 var x = event.screenX - toolbar.lastScreenX;
1145 var y = event.screenY - toolbar.lastScreenY;
1147 // We cannot call window.moveBy here because it restricts the movement
1148 // of the window at the edges.
1149 InspectorFrontendHost.moveWindowBy(x, y);
1152 toolbar.lastScreenX = event.screenX;
1153 toolbar.lastScreenY = event.screenY;
1155 event.preventDefault();
1158 WebInspector.elementDragStart = function(element, dividerDrag, elementDragEnd, event, cursor)
1160 if (this._elementDraggingEventListener || this._elementEndDraggingEventListener)
1161 this.elementDragEnd(event);
1163 this._elementDraggingEventListener = dividerDrag;
1164 this._elementEndDraggingEventListener = elementDragEnd;
1166 document.addEventListener("mousemove", dividerDrag, true);
1167 document.addEventListener("mouseup", elementDragEnd, true);
1169 document.body.style.cursor = cursor;
1171 event.preventDefault();
1174 WebInspector.elementDragEnd = function(event)
1176 document.removeEventListener("mousemove", this._elementDraggingEventListener, true);
1177 document.removeEventListener("mouseup", this._elementEndDraggingEventListener, true);
1179 document.body.style.removeProperty("cursor");
1181 delete this._elementDraggingEventListener;
1182 delete this._elementEndDraggingEventListener;
1184 event.preventDefault();
1187 WebInspector.toggleSearchingForNode = function()
1189 if (this.panels.elements) {
1190 this.showPanel("elements");
1191 this.panels.elements.toggleSearchingForNode();
1195 WebInspector.showConsole = function()
1197 this.drawer.showView(this.console);
1200 WebInspector.showChanges = function()
1202 this.drawer.showView(this.changes);
1205 WebInspector.showPanel = function(panel)
1207 if (!(panel in this.panels))
1209 this.currentPanel = this.panels[panel];
1212 WebInspector.selectDatabase = function(o)
1214 WebInspector.showPanel("resources");
1215 WebInspector.panels.resources.selectDatabase(o);
1218 WebInspector.consoleMessagesCleared = function()
1220 WebInspector.console.clearMessages();
1223 WebInspector.selectDOMStorage = function(o)
1225 WebInspector.showPanel("resources");
1226 WebInspector.panels.resources.selectDOMStorage(o);
1229 WebInspector.domContentEventFired = function(time)
1231 this.panels.audits.mainResourceDOMContentTime = time;
1232 if (this.panels.network)
1233 this.panels.network.mainResourceDOMContentTime = time;
1234 this.extensionServer.notifyPageDOMContentLoaded((time - WebInspector.mainResource.startTime) * 1000);
1235 this.mainResourceDOMContentTime = time;
1238 WebInspector.loadEventFired = function(time)
1240 this.panels.audits.mainResourceLoadTime = time;
1241 if (this.panels.network)
1242 this.panels.network.mainResourceLoadTime = time;
1243 this.extensionServer.notifyPageLoaded((time - WebInspector.mainResource.startTime) * 1000);
1244 this.mainResourceLoadTime = time;
1247 WebInspector.addDatabase = function(payload)
1249 if (!this.panels.resources)
1251 var database = new WebInspector.Database(
1256 this.panels.resources.addDatabase(database);
1259 WebInspector.addDOMStorage = function(payload)
1261 if (!this.panels.resources)
1263 var domStorage = new WebInspector.DOMStorage(
1266 payload.isLocalStorage);
1267 this.panels.resources.addDOMStorage(domStorage);
1270 WebInspector.updateDOMStorage = function(storageId)
1272 this.panels.resources.updateDOMStorage(storageId);
1275 WebInspector.updateApplicationCacheStatus = function(status)
1277 this.panels.resources.updateApplicationCacheStatus(status);
1280 WebInspector.didGetFileSystemPath = function(root, type, origin)
1282 this.panels.resources.updateFileSystemPath(root, type, origin);
1285 WebInspector.didGetFileSystemError = function(type, origin)
1287 this.panels.resources.updateFileSystemError(type, origin);
1290 WebInspector.didGetFileSystemDisabled = function()
1292 this.panels.resources.setFileSystemDisabled();
1295 WebInspector.updateNetworkState = function(isNowOnline)
1297 this.panels.resources.updateNetworkState(isNowOnline);
1300 WebInspector.searchingForNodeWasEnabled = function()
1302 this.panels.elements.searchingForNodeWasEnabled();
1305 WebInspector.searchingForNodeWasDisabled = function()
1307 this.panels.elements.searchingForNodeWasDisabled();
1310 WebInspector.attachDebuggerWhenShown = function()
1312 this.panels.scripts.attachDebuggerWhenShown();
1315 WebInspector.debuggerWasEnabled = function()
1317 this.panels.scripts.debuggerWasEnabled();
1320 WebInspector.debuggerWasDisabled = function()
1322 this.panels.scripts.debuggerWasDisabled();
1325 WebInspector.profilerWasEnabled = function()
1327 this.panels.profiles.profilerWasEnabled();
1330 WebInspector.profilerWasDisabled = function()
1332 this.panels.profiles.profilerWasDisabled();
1335 WebInspector.parsedScriptSource = function(sourceID, sourceURL, source, startingLine, scriptWorldType)
1337 this.panels.scripts.addScript(sourceID, sourceURL, source, startingLine, undefined, undefined, scriptWorldType);
1340 WebInspector.restoredBreakpoint = function(sourceID, sourceURL, line, enabled, condition)
1342 this.breakpointManager.restoredBreakpoint(sourceID, sourceURL, line, enabled, condition);
1345 WebInspector.failedToParseScriptSource = function(sourceURL, source, startingLine, errorLine, errorMessage)
1347 this.panels.scripts.addScript(null, sourceURL, source, startingLine, errorLine, errorMessage);
1350 WebInspector.pausedScript = function(details)
1352 this.panels.scripts.debuggerPaused(details.callFrames);
1353 this.breakpointManager.debuggerPaused(details);
1354 InspectorFrontendHost.bringToFront();
1357 WebInspector.resumedScript = function()
1359 this.breakpointManager.debuggerResumed();
1360 this.panels.scripts.debuggerResumed();
1363 WebInspector.reset = function()
1365 this.breakpointManager.reset();
1367 for (var panelName in this.panels) {
1368 var panel = this.panels[panelName];
1369 if ("reset" in panel)
1373 this.resources = {};
1374 this.highlightDOMNode(0);
1376 this.console.clearMessages();
1377 this.extensionServer.notifyInspectorReset();
1379 this.breakpointManager.restoreBreakpoints();
1382 WebInspector.resetProfilesPanel = function()
1384 if (WebInspector.panels.profiles)
1385 WebInspector.panels.profiles.resetProfiles();
1388 WebInspector.bringToFront = function()
1390 InspectorFrontendHost.bringToFront();
1393 WebInspector.inspectedURLChanged = function(url)
1395 InspectorFrontendHost.inspectedURLChanged(url);
1396 this.settings.inspectedURLChanged(url);
1397 this.extensionServer.notifyInspectedURLChanged();
1398 if (!this._breakpointsRestored) {
1399 this.breakpointManager.restoreBreakpoints();
1400 this._breakpointsRestored = true;
1404 WebInspector.didCommitLoad = function()
1406 // Cleanup elements panel early on inspected page refresh.
1407 WebInspector.setDocument(null);
1410 WebInspector.updateConsoleMessageExpiredCount = function(count)
1412 var message = String.sprintf(WebInspector.UIString("%d console messages are not shown."), count);
1413 WebInspector.console.addMessage(WebInspector.ConsoleMessage.createTextMessage(message, WebInspector.ConsoleMessage.MessageLevel.Warning));
1416 WebInspector.addConsoleMessage = function(payload)
1418 var consoleMessage = new WebInspector.ConsoleMessage(
1425 payload.repeatCount,
1428 payload.stackTrace);
1429 this.console.addMessage(consoleMessage);
1432 WebInspector.updateConsoleMessageRepeatCount = function(count)
1434 this.console.updateMessageRepeatCount(count);
1437 WebInspector.log = function(message, messageLevel)
1439 // remember 'this' for setInterval() callback
1442 // return indication if we can actually log a message
1443 function isLogAvailable()
1445 return WebInspector.ConsoleMessage && WebInspector.RemoteObject && self.console;
1448 // flush the queue of pending messages
1449 function flushQueue()
1451 var queued = WebInspector.log.queued;
1455 for (var i = 0; i < queued.length; ++i)
1456 logMessage(queued[i]);
1458 delete WebInspector.log.queued;
1461 // flush the queue if it console is available
1462 // - this function is run on an interval
1463 function flushQueueIfAvailable()
1465 if (!isLogAvailable())
1468 clearInterval(WebInspector.log.interval);
1469 delete WebInspector.log.interval;
1474 // actually log the message
1475 function logMessage(message)
1477 var repeatCount = 1;
1478 if (message == WebInspector.log.lastMessage)
1479 repeatCount = WebInspector.log.repeatCount + 1;
1481 WebInspector.log.lastMessage = message;
1482 WebInspector.log.repeatCount = repeatCount;
1484 // ConsoleMessage expects a proxy object
1485 message = new WebInspector.RemoteObject.fromPrimitiveValue(message);
1488 var msg = new WebInspector.ConsoleMessage(
1489 WebInspector.ConsoleMessage.MessageSource.Other,
1490 WebInspector.ConsoleMessage.MessageType.Log,
1491 messageLevel || WebInspector.ConsoleMessage.MessageLevel.Debug,
1500 self.console.addMessage(msg);
1503 // if we can't log the message, queue it
1504 if (!isLogAvailable()) {
1505 if (!WebInspector.log.queued)
1506 WebInspector.log.queued = [];
1508 WebInspector.log.queued.push(message);
1510 if (!WebInspector.log.interval)
1511 WebInspector.log.interval = setInterval(flushQueueIfAvailable, 1000);
1516 // flush the pending queue if any
1520 logMessage(message);
1523 WebInspector.addProfileHeader = function(profile)
1525 this.panels.profiles.addProfileHeader(profile);
1528 WebInspector.setRecordingProfile = function(isProfiling)
1530 this.panels.profiles.getProfileType(WebInspector.CPUProfileType.TypeId).setRecordingProfile(isProfiling);
1531 if (this.panels.profiles.hasTemporaryProfile(WebInspector.CPUProfileType.TypeId) !== isProfiling) {
1532 if (!this._temporaryRecordingProfile) {
1533 this._temporaryRecordingProfile = {
1534 typeId: WebInspector.CPUProfileType.TypeId,
1535 title: WebInspector.UIString("Recording…"),
1541 this.panels.profiles.addProfileHeader(this._temporaryRecordingProfile);
1543 this.panels.profiles.removeProfileHeader(this._temporaryRecordingProfile);
1545 this.panels.profiles.updateProfileTypeButtons();
1548 WebInspector.addHeapSnapshotChunk = function(uid, chunk)
1550 this.panels.profiles.addHeapSnapshotChunk(uid, chunk);
1553 WebInspector.finishHeapSnapshot = function(uid)
1555 this.panels.profiles.finishHeapSnapshot(uid);
1558 WebInspector.drawLoadingPieChart = function(canvas, percent) {
1559 var g = canvas.getContext("2d");
1560 var darkColor = "rgb(122, 168, 218)";
1561 var lightColor = "rgb(228, 241, 251)";
1567 g.arc(cx, cy, r, 0, Math.PI * 2, false);
1571 g.strokeStyle = darkColor;
1572 g.fillStyle = lightColor;
1576 var startangle = -Math.PI / 2;
1577 var endangle = startangle + (percent * Math.PI * 2);
1581 g.arc(cx, cy, r, startangle, endangle, false);
1584 g.fillStyle = darkColor;
1588 WebInspector.updateFocusedNode = function(nodeId)
1590 this._updateFocusedNode(nodeId);
1591 this.highlightDOMNodeForTwoSeconds(nodeId);
1594 WebInspector.displayNameForURL = function(url)
1599 var resource = this.resourceForURL(url);
1601 return resource.displayName;
1603 if (!WebInspector.mainResource)
1604 return url.trimURL("");
1606 var lastPathComponent = WebInspector.mainResource.lastPathComponent;
1607 var index = WebInspector.mainResource.url.indexOf(lastPathComponent);
1608 if (index !== -1 && index + lastPathComponent.length === WebInspector.mainResource.url.length) {
1609 var baseURL = WebInspector.mainResource.url.substring(0, index);
1610 if (url.indexOf(baseURL) === 0)
1611 return url.substring(index);
1614 return url.trimURL(WebInspector.mainResource.domain);
1617 WebInspector._choosePanelToShowSourceLine = function(url, line, preferredPanel)
1619 preferredPanel = preferredPanel || "resources";
1621 var panel = this.panels[preferredPanel];
1622 if (panel && panel.canShowSourceLine(url, line))
1624 panel = this.panels.resources;
1625 return panel.canShowSourceLine(url, line) ? panel : null;
1628 WebInspector.canShowSourceLine = function(url, line, preferredPanel)
1630 return !!this._choosePanelToShowSourceLine(url, line, preferredPanel);
1633 WebInspector.showSourceLine = function(url, line, preferredPanel)
1635 this.currentPanel = this._choosePanelToShowSourceLine(url, line, preferredPanel);
1636 if (!this.currentPanel)
1638 this.currentPanel.showSourceLine(url, line);
1642 WebInspector.linkifyStringAsFragment = function(string)
1644 var container = document.createDocumentFragment();
1645 var linkStringRegEx = /(?:[a-zA-Z][a-zA-Z0-9+.-]{2,}:\/\/|www\.)[\w$\-_+*'=\|\/\\(){}[\]%@&#~,:;.!?]{2,}[\w$\-_+*=\|\/\\({%@&#~]/;
1646 var lineColumnRegEx = /:(\d+)(:(\d+))?$/;
1649 var linkString = linkStringRegEx.exec(string);
1653 linkString = linkString[0];
1654 var title = linkString;
1655 var linkIndex = string.indexOf(linkString);
1656 var nonLink = string.substring(0, linkIndex);
1657 container.appendChild(document.createTextNode(nonLink));
1659 var profileStringMatches = WebInspector.ProfileType.URLRegExp.exec(title);
1660 if (profileStringMatches)
1661 title = WebInspector.panels.profiles.displayTitleForProfileLink(profileStringMatches[2], profileStringMatches[1]);
1663 var realURL = (linkString.indexOf("www.") === 0 ? "http://" + linkString : linkString);
1664 var lineColumnMatch = lineColumnRegEx.exec(realURL);
1665 if (lineColumnMatch)
1666 realURL = realURL.substring(0, realURL.length - lineColumnMatch[0].length);
1668 var hasResourceWithURL = !!WebInspector.resourceForURL(realURL);
1669 var urlNode = WebInspector.linkifyURLAsNode(realURL, title, null, hasResourceWithURL);
1670 container.appendChild(urlNode);
1671 if (lineColumnMatch) {
1672 urlNode.setAttribute("line_number", lineColumnMatch[1]);
1673 urlNode.setAttribute("preferred_panel", "scripts");
1675 string = string.substring(linkIndex + linkString.length, string.length);
1679 container.appendChild(document.createTextNode(string));
1684 WebInspector.showProfileForURL = function(url)
1686 WebInspector.showPanel("profiles");
1687 WebInspector.panels.profiles.showProfileForURL(url);
1690 WebInspector.linkifyURLAsNode = function(url, linkText, classes, isExternal, tooltipText)
1694 classes = (classes ? classes + " " : "");
1695 classes += isExternal ? "webkit-html-external-link" : "webkit-html-resource-link";
1697 var a = document.createElement("a");
1699 a.className = classes;
1700 if (typeof tooltipText === "undefined")
1702 else if (typeof tooltipText !== "string" || tooltipText.length)
1703 a.title = tooltipText;
1704 a.textContent = linkText;
1709 WebInspector.linkifyURL = function(url, linkText, classes, isExternal, tooltipText)
1711 // Use the DOM version of this function so as to avoid needing to escape attributes.
1712 // FIXME: Get rid of linkifyURL entirely.
1713 return WebInspector.linkifyURLAsNode(url, linkText, classes, isExternal, tooltipText).outerHTML;
1716 WebInspector.linkifyResourceAsNode = function(url, preferredPanel, lineNumber, classes, tooltipText)
1718 var linkText = WebInspector.displayNameForURL(url);
1720 linkText += ":" + lineNumber;
1721 var node = WebInspector.linkifyURLAsNode(url, linkText, classes, false, tooltipText);
1722 node.setAttribute("line_number", lineNumber);
1723 node.setAttribute("preferred_panel", preferredPanel);
1727 WebInspector.resourceURLForRelatedNode = function(node, url)
1729 if (!url || url.indexOf("://") > 0)
1732 for (var frameOwnerCandidate = node; frameOwnerCandidate; frameOwnerCandidate = frameOwnerCandidate.parentNode) {
1733 if (frameOwnerCandidate.documentURL) {
1734 var result = WebInspector.completeURL(frameOwnerCandidate.documentURL, url);
1741 // documentURL not found or has bad value
1742 var resourceURL = url;
1743 function callback(resource)
1745 if (resource.path === url) {
1746 resourceURL = resource.url;
1750 WebInspector.forAllResources(callback);
1754 WebInspector.completeURL = function(baseURL, href)
1756 var parsedURL = baseURL.asParsedURL();
1759 if (path.charAt(0) !== "/") {
1760 var basePath = parsedURL.path;
1761 path = basePath.substring(0, basePath.lastIndexOf("/")) + "/" + path;
1762 } else if (path.length > 1 && path.charAt(1) === "/") {
1763 // href starts with "//" which is a full URL with the protocol dropped (use the baseURL protocol).
1764 return parsedURL.scheme + ":" + path;
1766 return parsedURL.scheme + "://" + parsedURL.host + (parsedURL.port ? (":" + parsedURL.port) : "") + path;
1771 WebInspector.addMainEventListeners = function(doc)
1773 doc.defaultView.addEventListener("focus", this.windowFocused.bind(this), false);
1774 doc.defaultView.addEventListener("blur", this.windowBlurred.bind(this), false);
1775 doc.addEventListener("click", this.documentClick.bind(this), true);
1778 WebInspector._searchFieldManualFocus = function(event)
1780 this.currentFocusElement = event.target;
1781 this._previousFocusElement = event.target;
1784 WebInspector._searchKeyDown = function(event)
1786 // Escape Key will clear the field and clear the search results
1787 if (event.keyCode === WebInspector.KeyboardShortcut.Keys.Esc.code) {
1788 // If focus belongs here and text is empty - nothing to do, return unhandled.
1789 if (event.target.value === "" && this.currentFocusElement === this.previousFocusElement)
1791 event.preventDefault();
1792 event.stopPropagation();
1793 // When search was selected manually and is currently blank, we'd like Esc stay unhandled
1794 // and hit console drawer handler.
1795 event.target.value = "";
1797 this.performSearch(event);
1798 this.currentFocusElement = this.previousFocusElement;
1799 if (this.currentFocusElement === event.target)
1800 this.currentFocusElement.select();
1804 if (!isEnterKey(event))
1807 // Select all of the text so the user can easily type an entirely new query.
1808 event.target.select();
1810 // Only call performSearch if the Enter key was pressed. Otherwise the search
1811 // performance is poor because of searching on every key. The search field has
1812 // the incremental attribute set, so we still get incremental searches.
1813 this.performSearch(event);
1815 // Call preventDefault since this was the Enter key. This prevents a "search" event
1816 // from firing for key down. This stops performSearch from being called twice in a row.
1817 event.preventDefault();
1820 WebInspector.performSearch = function(event)
1822 var forceSearch = event.keyIdentifier === "Enter";
1823 this.doPerformSearch(event.target.value, forceSearch, event.shiftKey, false);
1826 WebInspector.doPerformSearch = function(query, forceSearch, isBackwardSearch, repeatSearch)
1828 var isShortSearch = (query.length < 3);
1830 // Clear a leftover short search flag due to a non-conflicting forced search.
1831 if (isShortSearch && this.shortSearchWasForcedByKeyEvent && this.currentQuery !== query)
1832 delete this.shortSearchWasForcedByKeyEvent;
1834 // Indicate this was a forced search on a short query.
1835 if (isShortSearch && forceSearch)
1836 this.shortSearchWasForcedByKeyEvent = true;
1838 if (!query || !query.length || (!forceSearch && isShortSearch)) {
1839 // Prevent clobbering a short search forced by the user.
1840 if (this.shortSearchWasForcedByKeyEvent) {
1841 delete this.shortSearchWasForcedByKeyEvent;
1845 delete this.currentQuery;
1847 for (var panelName in this.panels) {
1848 var panel = this.panels[panelName];
1849 var hadCurrentQuery = !!panel.currentQuery;
1850 delete panel.currentQuery;
1851 if (hadCurrentQuery && panel.searchCanceled)
1852 panel.searchCanceled();
1855 this.updateSearchMatchesCount();
1860 if (!repeatSearch && query === this.currentPanel.currentQuery && this.currentPanel.currentQuery === this.currentQuery) {
1861 // When this is the same query and a forced search, jump to the next
1862 // search result for a good user experience.
1864 if (!isBackwardSearch && this.currentPanel.jumpToNextSearchResult)
1865 this.currentPanel.jumpToNextSearchResult();
1866 else if (isBackwardSearch && this.currentPanel.jumpToPreviousSearchResult)
1867 this.currentPanel.jumpToPreviousSearchResult();
1872 this.currentQuery = query;
1874 this.updateSearchMatchesCount();
1876 if (!this.currentPanel.performSearch)
1879 this.currentPanel.currentQuery = query;
1880 this.currentPanel.performSearch(query);
1883 WebInspector.addNodesToSearchResult = function(nodeIds)
1885 WebInspector.panels.elements.addNodesToSearchResult(nodeIds);
1888 WebInspector.updateSearchMatchesCount = function(matches, panel)
1891 panel = this.currentPanel;
1893 panel.currentSearchMatches = matches;
1895 if (panel !== this.currentPanel)
1898 if (!this.currentPanel.currentQuery) {
1899 document.getElementById("search-results-matches").addStyleClass("hidden");
1905 var matchesString = WebInspector.UIString("1 match");
1907 var matchesString = WebInspector.UIString("%d matches", matches);
1909 var matchesString = WebInspector.UIString("Not Found");
1911 var matchesToolbarElement = document.getElementById("search-results-matches");
1912 matchesToolbarElement.removeStyleClass("hidden");
1913 matchesToolbarElement.textContent = matchesString;
1916 WebInspector.UIString = function(string)
1918 if (window.localizedStrings && string in window.localizedStrings)
1919 string = window.localizedStrings[string];
1921 if (!(string in WebInspector.missingLocalizedStrings)) {
1922 if (!WebInspector.InspectorBackendStub)
1923 console.error("Localized string \"" + string + "\" not found.");
1924 WebInspector.missingLocalizedStrings[string] = true;
1927 if (Preferences.showMissingLocalizedStrings)
1928 string += " (not localized)";
1931 return String.vsprintf(string, Array.prototype.slice.call(arguments, 1));
1934 WebInspector.formatLocalized = function(format, substitutions, formatters, initialValue, append)
1936 return String.format(WebInspector.UIString(format), substitutions, formatters, initialValue, append);
1939 WebInspector.isMac = function()
1941 if (!("_isMac" in this))
1942 this._isMac = WebInspector.platform === "mac";
1947 WebInspector.isBeingEdited = function(element)
1949 return element.__editing;
1952 WebInspector.isEditingAnyField = function()
1954 return this.__editing;
1957 WebInspector.startEditing = function(element, committedCallback, cancelledCallback, context, multiline)
1959 if (element.__editing)
1961 element.__editing = true;
1962 WebInspector.__editing = true;
1964 var oldText = getContent(element);
1965 var moveDirection = "";
1967 element.addStyleClass("editing");
1969 var oldTabIndex = element.tabIndex;
1970 if (element.tabIndex < 0)
1971 element.tabIndex = 0;
1973 function blurEventListener() {
1974 editingCommitted.call(element);
1977 function getContent(element) {
1978 if (element.tagName === "INPUT" && element.type === "text")
1979 return element.value;
1981 return element.textContent;
1984 function cleanUpAfterEditing() {
1985 delete this.__editing;
1986 delete WebInspector.__editing;
1988 this.removeStyleClass("editing");
1989 this.tabIndex = oldTabIndex;
1991 this.scrollLeft = 0;
1993 element.removeEventListener("blur", blurEventListener, false);
1994 element.removeEventListener("keydown", keyDownEventListener, true);
1996 if (element === WebInspector.currentFocusElement || element.isAncestor(WebInspector.currentFocusElement))
1997 WebInspector.currentFocusElement = WebInspector.previousFocusElement;
2000 function editingCancelled() {
2001 if (this.tagName === "INPUT" && this.type === "text")
2002 this.value = oldText;
2004 this.textContent = oldText;
2006 cleanUpAfterEditing.call(this);
2008 if (cancelledCallback)
2009 cancelledCallback(this, context);
2012 function editingCommitted() {
2013 cleanUpAfterEditing.call(this);
2015 if (committedCallback)
2016 committedCallback(this, getContent(this), oldText, context, moveDirection);
2019 function keyDownEventListener(event) {
2020 var isMetaOrCtrl = WebInspector.isMac() ?
2021 event.metaKey && !event.shiftKey && !event.ctrlKey && !event.altKey :
2022 event.ctrlKey && !event.shiftKey && !event.metaKey && !event.altKey;
2023 if (isEnterKey(event) && (!multiline || isMetaOrCtrl)) {
2024 editingCommitted.call(element);
2025 event.preventDefault();
2026 event.stopPropagation();
2027 } else if (event.keyCode === WebInspector.KeyboardShortcut.Keys.Esc.code) {
2028 editingCancelled.call(element);
2029 event.preventDefault();
2030 event.stopPropagation();
2031 } else if (event.keyIdentifier === "U+0009") // Tab key
2032 moveDirection = (event.shiftKey ? "backward" : "forward");
2035 element.addEventListener("blur", blurEventListener, false);
2036 element.addEventListener("keydown", keyDownEventListener, true);
2038 WebInspector.currentFocusElement = element;
2040 cancel: editingCancelled.bind(element),
2041 commit: editingCommitted.bind(element)
2045 WebInspector._toolbarItemClicked = function(event)
2047 var toolbarItem = event.currentTarget;
2048 this.currentPanel = toolbarItem.panel;
2051 // This table maps MIME types to the Resource.Types which are valid for them.
2052 // The following line:
2053 // "text/html": {0: 1},
2054 // means that text/html is a valid MIME type for resources that have type
2055 // WebInspector.Resource.Type.Document (which has a value of 0).
2056 WebInspector.MIMETypes = {
2057 "text/html": {0: true},
2058 "text/xml": {0: true},
2059 "text/plain": {0: true},
2060 "application/xhtml+xml": {0: true},
2061 "text/css": {1: true},
2062 "text/xsl": {1: true},
2063 "image/jpeg": {2: true},
2064 "image/png": {2: true},
2065 "image/gif": {2: true},
2066 "image/bmp": {2: true},
2067 "image/vnd.microsoft.icon": {2: true},
2068 "image/x-icon": {2: true},
2069 "image/x-xbitmap": {2: true},
2070 "font/ttf": {3: true},
2071 "font/opentype": {3: true},
2072 "application/x-font-type1": {3: true},
2073 "application/x-font-ttf": {3: true},
2074 "application/x-truetype-font": {3: true},
2075 "text/javascript": {4: true},
2076 "text/ecmascript": {4: true},
2077 "application/javascript": {4: true},
2078 "application/ecmascript": {4: true},
2079 "application/x-javascript": {4: true},
2080 "text/javascript1.1": {4: true},
2081 "text/javascript1.2": {4: true},
2082 "text/javascript1.3": {4: true},
2083 "text/jscript": {4: true},
2084 "text/livescript": {4: true},
2087 WebInspector.PanelHistory = function()
2090 this._historyIterator = -1;
2093 WebInspector.PanelHistory.prototype = {
2094 canGoBack: function()
2096 return this._historyIterator > 0;
2101 this._inHistory = true;
2102 WebInspector.currentPanel = WebInspector.panels[this._history[--this._historyIterator]];
2103 delete this._inHistory;
2106 canGoForward: function()
2108 return this._historyIterator < this._history.length - 1;
2111 goForward: function()
2113 this._inHistory = true;
2114 WebInspector.currentPanel = WebInspector.panels[this._history[++this._historyIterator]];
2115 delete this._inHistory;
2118 setPanel: function(panelName)
2120 if (this._inHistory)
2123 this._history.splice(this._historyIterator + 1, this._history.length - this._historyIterator - 1);
2124 if (!this._history.length || this._history[this._history.length - 1] !== panelName)
2125 this._history.push(panelName);
2126 this._historyIterator = this._history.length - 1;