Not reviewed. Added svn:eol-style native to unbreak some build bots.
[WebKit-https.git] / Source / WebCore / inspector / front-end / ElementsPanel.js
1 /*
2  * Copyright (C) 2007, 2008 Apple Inc.  All rights reserved.
3  * Copyright (C) 2008 Matt Lilek <webkit@mattlilek.com>
4  * Copyright (C) 2009 Joseph Pecoraro
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  *
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.
18  *
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.
29  */
30
31 importScript("CSSNamedFlowCollectionsView.js");
32 importScript("EventListenersSidebarPane.js");
33 importScript("MetricsSidebarPane.js");
34 importScript("PropertiesSidebarPane.js");
35 importScript("StylesSidebarPane.js");
36
37 /**
38  * @constructor
39  * @extends {WebInspector.Panel}
40  */
41 WebInspector.ElementsPanel = function()
42 {
43     WebInspector.Panel.call(this, "elements");
44     this.registerRequiredCSS("breadcrumbList.css");
45     this.registerRequiredCSS("elementsPanel.css");
46     this.registerRequiredCSS("textPrompt.css");
47     this.setHideOnDetach();
48
49     const initialSidebarWidth = 325;
50     const minimalContentWidthPercent = 34;
51     this.createSplitView(this.element, WebInspector.SplitView.SidebarPosition.Right, initialSidebarWidth);
52     this.splitView.minimalSidebarWidth = Preferences.minElementsSidebarWidth;
53     this.splitView.minimalMainWidthPercent = minimalContentWidthPercent;
54
55     this.contentElement = this.splitView.mainElement;
56     this.contentElement.id = "elements-content";
57     this.contentElement.addStyleClass("outline-disclosure");
58     this.contentElement.addStyleClass("source-code");
59     if (!WebInspector.settings.domWordWrap.get())
60         this.contentElement.classList.add("nowrap");
61     WebInspector.settings.domWordWrap.addChangeListener(this._domWordWrapSettingChanged.bind(this));
62
63     this.contentElement.addEventListener("contextmenu", this._contextMenuEventFired.bind(this), true);
64
65     this.treeOutline = new WebInspector.ElementsTreeOutline(true, true, false, this._populateContextMenu.bind(this), this._setPseudoClassForNodeId.bind(this));
66     this.treeOutline.wireToDomAgent();
67
68     this.treeOutline.addEventListener(WebInspector.ElementsTreeOutline.Events.SelectedNodeChanged, this._selectedNodeChanged, this);
69
70     this.crumbsElement = document.createElement("div");
71     this.crumbsElement.className = "crumbs";
72     this.crumbsElement.addEventListener("mousemove", this._mouseMovedInCrumbs.bind(this), false);
73     this.crumbsElement.addEventListener("mouseout", this._mouseMovedOutOfCrumbs.bind(this), false);
74
75     this.sidebarPanes = {};
76     this.sidebarPanes.computedStyle = new WebInspector.ComputedStyleSidebarPane();
77     this.sidebarPanes.styles = new WebInspector.StylesSidebarPane(this.sidebarPanes.computedStyle, this._setPseudoClassForNodeId.bind(this));
78     this.sidebarPanes.metrics = new WebInspector.MetricsSidebarPane();
79     this.sidebarPanes.properties = new WebInspector.PropertiesSidebarPane();
80     this.sidebarPanes.domBreakpoints = WebInspector.domBreakpointsSidebarPane;
81     this.sidebarPanes.eventListeners = new WebInspector.EventListenersSidebarPane();
82
83     this.sidebarPanes.styles.onexpand = this.updateStyles.bind(this);
84     this.sidebarPanes.metrics.onexpand = this.updateMetrics.bind(this);
85     this.sidebarPanes.properties.onexpand = this.updateProperties.bind(this);
86     this.sidebarPanes.eventListeners.onexpand = this.updateEventListeners.bind(this);
87
88     this.sidebarPanes.styles.expanded = true;
89
90     this.sidebarPanes.styles.addEventListener("style edited", this._stylesPaneEdited, this);
91     this.sidebarPanes.styles.addEventListener("style property toggled", this._stylesPaneEdited, this);
92     this.sidebarPanes.metrics.addEventListener("metrics edited", this._metricsPaneEdited, this);
93
94     for (var pane in this.sidebarPanes) {
95         this.sidebarElement.appendChild(this.sidebarPanes[pane].element);
96         if (this.sidebarPanes[pane].onattach)
97             this.sidebarPanes[pane].onattach();
98     }
99
100     this._registerShortcuts();
101
102     this._popoverHelper = new WebInspector.PopoverHelper(this.element, this._getPopoverAnchor.bind(this), this._showPopover.bind(this));
103     this._popoverHelper.setTimeout(0);
104
105     WebInspector.domAgent.addEventListener(WebInspector.DOMAgent.Events.NodeRemoved, this._nodeRemoved, this);
106     WebInspector.domAgent.addEventListener(WebInspector.DOMAgent.Events.DocumentUpdated, this._documentUpdatedEvent, this);
107     WebInspector.domAgent.addEventListener(WebInspector.DOMAgent.Events.InspectElementRequested, this._inspectElementRequested, this);
108
109     if (WebInspector.domAgent.existingDocument())
110         this._documentUpdated(WebInspector.domAgent.existingDocument());
111 }
112
113 WebInspector.ElementsPanel.prototype = {
114     get statusBarItems()
115     {
116         return [this.crumbsElement];
117     },
118
119     defaultFocusedElement: function()
120     {
121         return this.treeOutline.element;
122     },
123
124     statusBarResized: function()
125     {
126         this.updateBreadcrumbSizes();
127     },
128
129     wasShown: function()
130     {
131         // Attach heavy component lazily
132         if (this.treeOutline.element.parentElement !== this.contentElement)
133             this.contentElement.appendChild(this.treeOutline.element);
134
135         WebInspector.Panel.prototype.wasShown.call(this);
136
137         this.updateBreadcrumb();
138         this.treeOutline.updateSelection();
139         this.treeOutline.setVisible(true);
140
141         if (!this.treeOutline.rootDOMNode)
142             WebInspector.domAgent.requestDocument();
143
144         this.sidebarElement.insertBefore(this.sidebarPanes.domBreakpoints.element, this.sidebarPanes.eventListeners.element);
145     },
146
147     willHide: function()
148     {
149         WebInspector.domAgent.hideDOMNodeHighlight();
150         this.treeOutline.setVisible(false);
151         this._popoverHelper.hidePopover();
152
153         // Detach heavy component on hide
154         this.contentElement.removeChild(this.treeOutline.element);
155
156         for (var pane in this.sidebarPanes) {
157             if (this.sidebarPanes[pane].willHide)
158                 this.sidebarPanes[pane].willHide();
159         }
160
161         WebInspector.Panel.prototype.willHide.call(this);
162     },
163
164     onResize: function()
165     {
166         this.treeOutline.updateSelection();
167         this.updateBreadcrumbSizes();
168     },
169
170     /**
171      * @param {DOMAgent.NodeId} nodeId
172      * @param {string} pseudoClass
173      * @param {boolean} enable
174      */
175     _setPseudoClassForNodeId: function(nodeId, pseudoClass, enable)
176     {
177         var node = WebInspector.domAgent.nodeForId(nodeId);
178         if (!node)
179             return;
180
181         var pseudoClasses = node.getUserProperty(WebInspector.ElementsTreeOutline.PseudoStateDecorator.PropertyName);
182         if (enable) {
183             pseudoClasses = pseudoClasses || [];
184             if (pseudoClasses.indexOf(pseudoClass) >= 0)
185                 return;
186             pseudoClasses.push(pseudoClass);
187             node.setUserProperty(WebInspector.ElementsTreeOutline.PseudoStateDecorator.PropertyName, pseudoClasses);
188         } else {
189             if (!pseudoClasses || pseudoClasses.indexOf(pseudoClass) < 0)
190                 return;
191             pseudoClasses.remove(pseudoClass);
192             if (!pseudoClasses.length)
193                 node.removeUserProperty(WebInspector.ElementsTreeOutline.PseudoStateDecorator.PropertyName);
194         }
195
196         this.treeOutline.updateOpenCloseTags(node);
197         WebInspector.cssModel.forcePseudoState(node.id, node.getUserProperty(WebInspector.ElementsTreeOutline.PseudoStateDecorator.PropertyName));
198         this._metricsPaneEdited();
199         this._stylesPaneEdited();
200     },
201
202     _selectedNodeChanged: function()
203     {
204         var selectedNode = this.selectedDOMNode();
205         if (!selectedNode && this._lastValidSelectedNode)
206             this._selectedPathOnReset = this._lastValidSelectedNode.path();
207
208         this.updateBreadcrumb(false);
209
210         this._updateSidebars();
211
212         if (selectedNode) {
213             ConsoleAgent.addInspectedNode(selectedNode.id);
214             this._lastValidSelectedNode = selectedNode;
215         }
216         WebInspector.notifications.dispatchEventToListeners(WebInspector.ElementsTreeOutline.Events.SelectedNodeChanged);
217     },
218
219     _updateSidebars: function()
220     {
221         for (var pane in this.sidebarPanes)
222            this.sidebarPanes[pane].needsUpdate = true;
223
224         this.updateStyles(true);
225         this.updateMetrics();
226         this.updateProperties();
227         this.updateEventListeners();
228     },
229
230     _reset: function()
231     {
232         delete this.currentQuery;
233     },
234
235     _documentUpdatedEvent: function(event)
236     {
237         this._documentUpdated(event.data);
238     },
239
240     _documentUpdated: function(inspectedRootDocument)
241     {
242         this._reset();
243         this.searchCanceled();
244
245         this.treeOutline.rootDOMNode = inspectedRootDocument;
246
247         if (!inspectedRootDocument) {
248             if (this.isShowing())
249                 WebInspector.domAgent.requestDocument();
250             return;
251         }
252
253         this.sidebarPanes.domBreakpoints.restoreBreakpoints();
254
255         /**
256          * @this {WebInspector.ElementsPanel}
257          * @param {WebInspector.DOMNode=} candidateFocusNode
258          */
259         function selectNode(candidateFocusNode)
260         {
261             if (!candidateFocusNode)
262                 candidateFocusNode = inspectedRootDocument.body || inspectedRootDocument.documentElement;
263
264             if (!candidateFocusNode)
265                 return;
266
267             this.selectDOMNode(candidateFocusNode);
268             if (this.treeOutline.selectedTreeElement)
269                 this.treeOutline.selectedTreeElement.expand();
270         }
271
272         function selectLastSelectedNode(nodeId)
273         {
274             if (this.selectedDOMNode()) {
275                 // Focused node has been explicitly set while reaching out for the last selected node.
276                 return;
277             }
278             var node = nodeId ? WebInspector.domAgent.nodeForId(nodeId) : null;
279             selectNode.call(this, node);
280         }
281
282         if (this._selectedPathOnReset)
283             WebInspector.domAgent.pushNodeByPathToFrontend(this._selectedPathOnReset, selectLastSelectedNode.bind(this));
284         else
285             selectNode.call(this);
286         delete this._selectedPathOnReset;
287     },
288
289     searchCanceled: function()
290     {
291         delete this._searchQuery;
292         this._hideSearchHighlights();
293
294         WebInspector.searchController.updateSearchMatchesCount(0, this);
295
296         delete this._currentSearchResultIndex;
297         delete this._searchResults;
298         WebInspector.domAgent.cancelSearch();
299     },
300
301     /**
302      * @param {string} query
303      */
304     performSearch: function(query)
305     {
306         // Call searchCanceled since it will reset everything we need before doing a new search.
307         this.searchCanceled();
308
309         const whitespaceTrimmedQuery = query.trim();
310         if (!whitespaceTrimmedQuery.length)
311             return;
312
313         this._searchQuery = query;
314
315         /**
316          * @param {number} resultCount
317          */
318         function resultCountCallback(resultCount)
319         {
320             WebInspector.searchController.updateSearchMatchesCount(resultCount, this);
321             if (!resultCount)
322                 return;
323
324             this._searchResults = new Array(resultCount);
325             this._currentSearchResultIndex = -1;
326             this.jumpToNextSearchResult();
327         }
328         WebInspector.domAgent.performSearch(whitespaceTrimmedQuery, resultCountCallback.bind(this));
329     },
330
331     _contextMenuEventFired: function(event)
332     {
333         function toggleWordWrap()
334         {
335             WebInspector.settings.domWordWrap.set(!WebInspector.settings.domWordWrap.get());
336         }
337
338         var contextMenu = new WebInspector.ContextMenu();
339         var populated = this.treeOutline.populateContextMenu(contextMenu, event);
340
341         if (WebInspector.experimentsSettings.cssRegions.isEnabled()) {
342             contextMenu.appendSeparator();
343             contextMenu.appendItem(WebInspector.UIString("CSS Named Flows..."), this._showNamedFlowCollections.bind(this));
344         }
345
346         contextMenu.appendSeparator();
347         contextMenu.appendCheckboxItem(WebInspector.UIString(WebInspector.useLowerCaseMenuTitles() ? "Word wrap" : "Word Wrap"), toggleWordWrap.bind(this), WebInspector.settings.domWordWrap.get());
348
349         contextMenu.show(event);
350     },
351
352     _showNamedFlowCollections: function()
353     {
354         if (!WebInspector.cssNamedFlowCollectionsView)
355             WebInspector.cssNamedFlowCollectionsView = new WebInspector.CSSNamedFlowCollectionsView();
356         WebInspector.cssNamedFlowCollectionsView.showInDrawer();
357     },
358
359     _domWordWrapSettingChanged: function(event)
360     {
361         if (event.data)
362             this.contentElement.removeStyleClass("nowrap");
363         else
364             this.contentElement.addStyleClass("nowrap");
365
366         var selectedNode = this.selectedDOMNode();
367         if (!selectedNode)
368             return;
369
370         var treeElement = this.treeOutline.findTreeElement(selectedNode);
371         if (treeElement)
372             treeElement.updateSelection(); // Recalculate selection highlight dimensions.
373     },
374
375     switchToAndFocus: function(node)
376     {
377         // Reset search restore.
378         WebInspector.searchController.cancelSearch();
379         WebInspector.inspectorView.setCurrentPanel(this);
380         this.selectDOMNode(node, true);
381     },
382
383     _populateContextMenu: function(contextMenu, node)
384     {
385         // Add debbuging-related actions
386         contextMenu.appendSeparator();
387         var pane = this.sidebarPanes.domBreakpoints;
388         pane.populateNodeContextMenu(node, contextMenu);
389     },
390
391     _getPopoverAnchor: function(element)
392     {
393         var anchor = element.enclosingNodeOrSelfWithClass("webkit-html-resource-link");
394         if (anchor) {
395             if (!anchor.href)
396                 return null;
397
398             var resource = WebInspector.resourceTreeModel.resourceForURL(anchor.href);
399             if (!resource || resource.type !== WebInspector.resourceTypes.Image)
400                 return null;
401
402             anchor.removeAttribute("title");
403         }
404         return anchor;
405     },
406     
407     _loadDimensionsForNode: function(treeElement, callback)
408     {
409         // We get here for CSS properties, too, so bail out early for non-DOM treeElements.
410         if (treeElement.treeOutline !== this.treeOutline) {
411             callback();
412             return;
413         }
414         
415         var node = /** @type {WebInspector.DOMNode} */ treeElement.representedObject;
416
417         if (!node.nodeName() || node.nodeName().toLowerCase() !== "img") {
418             callback();
419             return;
420         }
421
422         WebInspector.RemoteObject.resolveNode(node, "", resolvedNode);
423
424         function resolvedNode(object)
425         {
426             if (!object) {
427                 callback();
428                 return;
429             }
430
431             object.callFunctionJSON(dimensions, undefined, callback);
432             object.release();
433
434             function dimensions()
435             {
436                 return { offsetWidth: this.offsetWidth, offsetHeight: this.offsetHeight, naturalWidth: this.naturalWidth, naturalHeight: this.naturalHeight };
437             }
438         }
439     },
440
441     /**
442      * @param {Element} anchor
443      * @param {WebInspector.Popover} popover
444      */
445     _showPopover: function(anchor, popover)
446     {
447         var listItem = anchor.enclosingNodeOrSelfWithNodeName("li");
448         if (listItem && listItem.treeElement)
449             this._loadDimensionsForNode(listItem.treeElement, WebInspector.DOMPresentationUtils.buildImagePreviewContents.bind(WebInspector.DOMPresentationUtils, anchor.href, true, showPopover));
450         else
451             WebInspector.DOMPresentationUtils.buildImagePreviewContents(anchor.href, true, showPopover);
452
453         /**
454          * @param {Element=} contents
455          */
456         function showPopover(contents)
457         {
458             if (!contents)
459                 return;
460             popover.setCanShrink(false);
461             popover.show(contents, anchor);
462         }
463     },
464
465     jumpToNextSearchResult: function()
466     {
467         if (!this._searchResults)
468             return;
469
470         this._hideSearchHighlights();
471         if (++this._currentSearchResultIndex >= this._searchResults.length)
472             this._currentSearchResultIndex = 0;
473
474         this._highlightCurrentSearchResult();
475     },
476
477     jumpToPreviousSearchResult: function()
478     {
479         if (!this._searchResults)
480             return;
481
482         this._hideSearchHighlights();
483         if (--this._currentSearchResultIndex < 0)
484             this._currentSearchResultIndex = (this._searchResults.length - 1);
485
486         this._highlightCurrentSearchResult();
487         return true;
488     },
489
490     _highlightCurrentSearchResult: function()
491     {
492         var index = this._currentSearchResultIndex;
493         var searchResults = this._searchResults;
494         var searchResult = searchResults[index];
495
496         if (searchResult === null) {
497             WebInspector.searchController.updateCurrentMatchIndex(index, this);
498             return;
499         }
500
501         if (typeof searchResult === "undefined") {
502             // No data for slot, request it.
503             function callback(node)
504             {
505                 searchResults[index] = node || null;
506                 this._highlightCurrentSearchResult();
507             }
508             WebInspector.domAgent.searchResult(index, callback.bind(this));
509             return;
510         }
511
512         WebInspector.searchController.updateCurrentMatchIndex(index, this);
513
514         var treeElement = this.treeOutline.findTreeElement(searchResult);
515         if (treeElement) {
516             treeElement.highlightSearchResults(this._searchQuery);
517             treeElement.reveal();
518         }
519     },
520
521     _hideSearchHighlights: function()
522     {
523         if (!this._searchResults)
524             return;
525         var searchResult = this._searchResults[this._currentSearchResultIndex];
526         if (!searchResult)
527             return;
528         var treeElement = this.treeOutline.findTreeElement(searchResult);
529         if (treeElement)
530             treeElement.hideSearchHighlights();
531     },
532
533     selectedDOMNode: function()
534     {
535         return this.treeOutline.selectedDOMNode();
536     },
537
538     /**
539      * @param {boolean=} focus
540      */
541     selectDOMNode: function(node, focus)
542     {
543         this.treeOutline.selectDOMNode(node, focus);
544     },
545
546     _nodeRemoved: function(event)
547     {
548         if (!this.isShowing())
549             return;
550
551         var crumbs = this.crumbsElement;
552         for (var crumb = crumbs.firstChild; crumb; crumb = crumb.nextSibling) {
553             if (crumb.representedObject === event.data.node) {
554                 this.updateBreadcrumb(true);
555                 return;
556             }
557         }
558     },
559
560     _stylesPaneEdited: function()
561     {
562         // Once styles are edited, the Metrics pane should be updated.
563         this.sidebarPanes.metrics.needsUpdate = true;
564         this.updateMetrics();
565     },
566
567     _metricsPaneEdited: function()
568     {
569         // Once metrics are edited, the Styles pane should be updated.
570         this.sidebarPanes.styles.needsUpdate = true;
571         this.updateStyles(true);
572     },
573
574     _mouseMovedInCrumbs: function(event)
575     {
576         var nodeUnderMouse = document.elementFromPoint(event.pageX, event.pageY);
577         var crumbElement = nodeUnderMouse.enclosingNodeOrSelfWithClass("crumb");
578
579         WebInspector.domAgent.highlightDOMNode(crumbElement ? crumbElement.representedObject.id : 0);
580
581         if ("_mouseOutOfCrumbsTimeout" in this) {
582             clearTimeout(this._mouseOutOfCrumbsTimeout);
583             delete this._mouseOutOfCrumbsTimeout;
584         }
585     },
586
587     _mouseMovedOutOfCrumbs: function(event)
588     {
589         var nodeUnderMouse = document.elementFromPoint(event.pageX, event.pageY);
590         if (nodeUnderMouse && nodeUnderMouse.isDescendant(this.crumbsElement))
591             return;
592
593         WebInspector.domAgent.hideDOMNodeHighlight();
594
595         this._mouseOutOfCrumbsTimeout = setTimeout(this.updateBreadcrumbSizes.bind(this), 1000);
596     },
597
598     /**
599      * @param {boolean=} forceUpdate
600      */
601     updateBreadcrumb: function(forceUpdate)
602     {
603         if (!this.isShowing())
604             return;
605
606         var crumbs = this.crumbsElement;
607
608         var handled = false;
609         var foundRoot = false;
610         var crumb = crumbs.firstChild;
611         while (crumb) {
612             if (crumb.representedObject === this.treeOutline.rootDOMNode)
613                 foundRoot = true;
614
615             if (foundRoot)
616                 crumb.addStyleClass("dimmed");
617             else
618                 crumb.removeStyleClass("dimmed");
619
620             if (crumb.representedObject === this.selectedDOMNode()) {
621                 crumb.addStyleClass("selected");
622                 handled = true;
623             } else {
624                 crumb.removeStyleClass("selected");
625             }
626
627             crumb = crumb.nextSibling;
628         }
629
630         if (handled && !forceUpdate) {
631             // We don't need to rebuild the crumbs, but we need to adjust sizes
632             // to reflect the new focused or root node.
633             this.updateBreadcrumbSizes();
634             return;
635         }
636
637         crumbs.removeChildren();
638
639         var panel = this;
640
641         function selectCrumbFunction(event)
642         {
643             var crumb = event.currentTarget;
644             if (crumb.hasStyleClass("collapsed")) {
645                 // Clicking a collapsed crumb will expose the hidden crumbs.
646                 if (crumb === panel.crumbsElement.firstChild) {
647                     // If the focused crumb is the first child, pick the farthest crumb
648                     // that is still hidden. This allows the user to expose every crumb.
649                     var currentCrumb = crumb;
650                     while (currentCrumb) {
651                         var hidden = currentCrumb.hasStyleClass("hidden");
652                         var collapsed = currentCrumb.hasStyleClass("collapsed");
653                         if (!hidden && !collapsed)
654                             break;
655                         crumb = currentCrumb;
656                         currentCrumb = currentCrumb.nextSibling;
657                     }
658                 }
659
660                 panel.updateBreadcrumbSizes(crumb);
661             } else
662                 panel.selectDOMNode(crumb.representedObject, true);
663
664             event.preventDefault();
665         }
666
667         foundRoot = false;
668         for (var current = this.selectedDOMNode(); current; current = current.parentNode) {
669             if (current.nodeType() === Node.DOCUMENT_NODE)
670                 continue;
671
672             if (current === this.treeOutline.rootDOMNode)
673                 foundRoot = true;
674
675             crumb = document.createElement("span");
676             crumb.className = "crumb";
677             crumb.representedObject = current;
678             crumb.addEventListener("mousedown", selectCrumbFunction, false);
679
680             var crumbTitle;
681             switch (current.nodeType()) {
682                 case Node.ELEMENT_NODE:
683                     WebInspector.DOMPresentationUtils.decorateNodeLabel(current, crumb);
684                     break;
685
686                 case Node.TEXT_NODE:
687                     crumbTitle = WebInspector.UIString("(text)");
688                     break
689
690                 case Node.COMMENT_NODE:
691                     crumbTitle = "<!-->";
692                     break;
693
694                 case Node.DOCUMENT_TYPE_NODE:
695                     crumbTitle = "<!DOCTYPE>";
696                     break;
697
698                 default:
699                     crumbTitle = current.nodeNameInCorrectCase();
700             }
701
702             if (!crumb.childNodes.length) {
703                 var nameElement = document.createElement("span");
704                 nameElement.textContent = crumbTitle;
705                 crumb.appendChild(nameElement);
706                 crumb.title = crumbTitle;
707             }
708
709             if (foundRoot)
710                 crumb.addStyleClass("dimmed");
711             if (current === this.selectedDOMNode())
712                 crumb.addStyleClass("selected");
713             if (!crumbs.childNodes.length)
714                 crumb.addStyleClass("end");
715
716             crumbs.appendChild(crumb);
717         }
718
719         if (crumbs.hasChildNodes())
720             crumbs.lastChild.addStyleClass("start");
721
722         this.updateBreadcrumbSizes();
723     },
724
725     /**
726      * @param {Element=} focusedCrumb
727      */
728     updateBreadcrumbSizes: function(focusedCrumb)
729     {
730         if (!this.isShowing())
731             return;
732
733         if (document.body.offsetWidth <= 0) {
734             // The stylesheet hasn't loaded yet or the window is closed,
735             // so we can't calculate what is need. Return early.
736             return;
737         }
738
739         var crumbs = this.crumbsElement;
740         if (!crumbs.childNodes.length || crumbs.offsetWidth <= 0)
741             return; // No crumbs, do nothing.
742
743         // A Zero index is the right most child crumb in the breadcrumb.
744         var selectedIndex = 0;
745         var focusedIndex = 0;
746         var selectedCrumb;
747
748         var i = 0;
749         var crumb = crumbs.firstChild;
750         while (crumb) {
751             // Find the selected crumb and index.
752             if (!selectedCrumb && crumb.hasStyleClass("selected")) {
753                 selectedCrumb = crumb;
754                 selectedIndex = i;
755             }
756
757             // Find the focused crumb index.
758             if (crumb === focusedCrumb)
759                 focusedIndex = i;
760
761             // Remove any styles that affect size before
762             // deciding to shorten any crumbs.
763             if (crumb !== crumbs.lastChild)
764                 crumb.removeStyleClass("start");
765             if (crumb !== crumbs.firstChild)
766                 crumb.removeStyleClass("end");
767
768             crumb.removeStyleClass("compact");
769             crumb.removeStyleClass("collapsed");
770             crumb.removeStyleClass("hidden");
771
772             crumb = crumb.nextSibling;
773             ++i;
774         }
775
776         // Restore the start and end crumb classes in case they got removed in coalesceCollapsedCrumbs().
777         // The order of the crumbs in the document is opposite of the visual order.
778         crumbs.firstChild.addStyleClass("end");
779         crumbs.lastChild.addStyleClass("start");
780
781         function crumbsAreSmallerThanContainer()
782         {
783             var rightPadding = 20;
784             var errorWarningElement = document.getElementById("error-warning-count");
785             if (!WebInspector.drawer.visible && errorWarningElement)
786                 rightPadding += errorWarningElement.offsetWidth;
787             return ((crumbs.totalOffsetLeft() + crumbs.offsetWidth + rightPadding) < window.innerWidth);
788         }
789
790         if (crumbsAreSmallerThanContainer())
791             return; // No need to compact the crumbs, they all fit at full size.
792
793         var BothSides = 0;
794         var AncestorSide = -1;
795         var ChildSide = 1;
796
797         /**
798          * @param {boolean=} significantCrumb
799          */
800         function makeCrumbsSmaller(shrinkingFunction, direction, significantCrumb)
801         {
802             if (!significantCrumb)
803                 significantCrumb = (focusedCrumb || selectedCrumb);
804
805             if (significantCrumb === selectedCrumb)
806                 var significantIndex = selectedIndex;
807             else if (significantCrumb === focusedCrumb)
808                 var significantIndex = focusedIndex;
809             else {
810                 var significantIndex = 0;
811                 for (var i = 0; i < crumbs.childNodes.length; ++i) {
812                     if (crumbs.childNodes[i] === significantCrumb) {
813                         significantIndex = i;
814                         break;
815                     }
816                 }
817             }
818
819             function shrinkCrumbAtIndex(index)
820             {
821                 var shrinkCrumb = crumbs.childNodes[index];
822                 if (shrinkCrumb && shrinkCrumb !== significantCrumb)
823                     shrinkingFunction(shrinkCrumb);
824                 if (crumbsAreSmallerThanContainer())
825                     return true; // No need to compact the crumbs more.
826                 return false;
827             }
828
829             // Shrink crumbs one at a time by applying the shrinkingFunction until the crumbs
830             // fit in the container or we run out of crumbs to shrink.
831             if (direction) {
832                 // Crumbs are shrunk on only one side (based on direction) of the signifcant crumb.
833                 var index = (direction > 0 ? 0 : crumbs.childNodes.length - 1);
834                 while (index !== significantIndex) {
835                     if (shrinkCrumbAtIndex(index))
836                         return true;
837                     index += (direction > 0 ? 1 : -1);
838                 }
839             } else {
840                 // Crumbs are shrunk in order of descending distance from the signifcant crumb,
841                 // with a tie going to child crumbs.
842                 var startIndex = 0;
843                 var endIndex = crumbs.childNodes.length - 1;
844                 while (startIndex != significantIndex || endIndex != significantIndex) {
845                     var startDistance = significantIndex - startIndex;
846                     var endDistance = endIndex - significantIndex;
847                     if (startDistance >= endDistance)
848                         var index = startIndex++;
849                     else
850                         var index = endIndex--;
851                     if (shrinkCrumbAtIndex(index))
852                         return true;
853                 }
854             }
855
856             // We are not small enough yet, return false so the caller knows.
857             return false;
858         }
859
860         function coalesceCollapsedCrumbs()
861         {
862             var crumb = crumbs.firstChild;
863             var collapsedRun = false;
864             var newStartNeeded = false;
865             var newEndNeeded = false;
866             while (crumb) {
867                 var hidden = crumb.hasStyleClass("hidden");
868                 if (!hidden) {
869                     var collapsed = crumb.hasStyleClass("collapsed");
870                     if (collapsedRun && collapsed) {
871                         crumb.addStyleClass("hidden");
872                         crumb.removeStyleClass("compact");
873                         crumb.removeStyleClass("collapsed");
874
875                         if (crumb.hasStyleClass("start")) {
876                             crumb.removeStyleClass("start");
877                             newStartNeeded = true;
878                         }
879
880                         if (crumb.hasStyleClass("end")) {
881                             crumb.removeStyleClass("end");
882                             newEndNeeded = true;
883                         }
884
885                         continue;
886                     }
887
888                     collapsedRun = collapsed;
889
890                     if (newEndNeeded) {
891                         newEndNeeded = false;
892                         crumb.addStyleClass("end");
893                     }
894                 } else
895                     collapsedRun = true;
896                 crumb = crumb.nextSibling;
897             }
898
899             if (newStartNeeded) {
900                 crumb = crumbs.lastChild;
901                 while (crumb) {
902                     if (!crumb.hasStyleClass("hidden")) {
903                         crumb.addStyleClass("start");
904                         break;
905                     }
906                     crumb = crumb.previousSibling;
907                 }
908             }
909         }
910
911         function compact(crumb)
912         {
913             if (crumb.hasStyleClass("hidden"))
914                 return;
915             crumb.addStyleClass("compact");
916         }
917
918         function collapse(crumb, dontCoalesce)
919         {
920             if (crumb.hasStyleClass("hidden"))
921                 return;
922             crumb.addStyleClass("collapsed");
923             crumb.removeStyleClass("compact");
924             if (!dontCoalesce)
925                 coalesceCollapsedCrumbs();
926         }
927
928         function compactDimmed(crumb)
929         {
930             if (crumb.hasStyleClass("dimmed"))
931                 compact(crumb);
932         }
933
934         function collapseDimmed(crumb)
935         {
936             if (crumb.hasStyleClass("dimmed"))
937                 collapse(crumb, false);
938         }
939
940         if (!focusedCrumb) {
941             // When not focused on a crumb we can be biased and collapse less important
942             // crumbs that the user might not care much about.
943
944             // Compact child crumbs.
945             if (makeCrumbsSmaller(compact, ChildSide))
946                 return;
947
948             // Collapse child crumbs.
949             if (makeCrumbsSmaller(collapse, ChildSide))
950                 return;
951
952             // Compact dimmed ancestor crumbs.
953             if (makeCrumbsSmaller(compactDimmed, AncestorSide))
954                 return;
955
956             // Collapse dimmed ancestor crumbs.
957             if (makeCrumbsSmaller(collapseDimmed, AncestorSide))
958                 return;
959         }
960
961         // Compact ancestor crumbs, or from both sides if focused.
962         if (makeCrumbsSmaller(compact, (focusedCrumb ? BothSides : AncestorSide)))
963             return;
964
965         // Collapse ancestor crumbs, or from both sides if focused.
966         if (makeCrumbsSmaller(collapse, (focusedCrumb ? BothSides : AncestorSide)))
967             return;
968
969         if (!selectedCrumb)
970             return;
971
972         // Compact the selected crumb.
973         compact(selectedCrumb);
974         if (crumbsAreSmallerThanContainer())
975             return;
976
977         // Collapse the selected crumb as a last resort. Pass true to prevent coalescing.
978         collapse(selectedCrumb, true);
979     },
980
981     updateStyles: function(forceUpdate)
982     {
983         var stylesSidebarPane = this.sidebarPanes.styles;
984         var computedStylePane = this.sidebarPanes.computedStyle;
985         if ((!stylesSidebarPane.expanded && !computedStylePane.expanded) || !stylesSidebarPane.needsUpdate)
986             return;
987
988         stylesSidebarPane.update(this.selectedDOMNode(), forceUpdate);
989         stylesSidebarPane.needsUpdate = false;
990     },
991
992     updateMetrics: function()
993     {
994         var metricsSidebarPane = this.sidebarPanes.metrics;
995         if (!metricsSidebarPane.expanded || !metricsSidebarPane.needsUpdate)
996             return;
997
998         metricsSidebarPane.update(this.selectedDOMNode());
999         metricsSidebarPane.needsUpdate = false;
1000     },
1001
1002     updateProperties: function()
1003     {
1004         var propertiesSidebarPane = this.sidebarPanes.properties;
1005         if (!propertiesSidebarPane.expanded || !propertiesSidebarPane.needsUpdate)
1006             return;
1007
1008         propertiesSidebarPane.update(this.selectedDOMNode());
1009         propertiesSidebarPane.needsUpdate = false;
1010     },
1011
1012     updateEventListeners: function()
1013     {
1014         var eventListenersSidebarPane = this.sidebarPanes.eventListeners;
1015         if (!eventListenersSidebarPane.expanded || !eventListenersSidebarPane.needsUpdate)
1016             return;
1017
1018         eventListenersSidebarPane.update(this.selectedDOMNode());
1019         eventListenersSidebarPane.needsUpdate = false;
1020     },
1021
1022     _registerShortcuts: function()
1023     {
1024         var shortcut = WebInspector.KeyboardShortcut;
1025         var section = WebInspector.shortcutsScreen.section(WebInspector.UIString("Elements Panel"));
1026         var keys = [
1027             shortcut.shortcutToString(shortcut.Keys.Up),
1028             shortcut.shortcutToString(shortcut.Keys.Down)
1029         ];
1030         section.addRelatedKeys(keys, WebInspector.UIString("Navigate elements"));
1031
1032         keys = [
1033             shortcut.shortcutToString(shortcut.Keys.Right),
1034             shortcut.shortcutToString(shortcut.Keys.Left)
1035         ];
1036         section.addRelatedKeys(keys, WebInspector.UIString("Expand/collapse"));
1037         section.addKey(shortcut.shortcutToString(shortcut.Keys.Enter), WebInspector.UIString("Edit attribute"));
1038         section.addKey(shortcut.shortcutToString(shortcut.Keys.F2), WebInspector.UIString("Toggle edit as HTML"));
1039
1040         this.sidebarPanes.styles.registerShortcuts();
1041     },
1042
1043     handleShortcut: function(event)
1044     {
1045         if (WebInspector.KeyboardShortcut.eventHasCtrlOrMeta(event) && !event.shiftKey && event.keyIdentifier === "U+005A") { // Z key
1046             WebInspector.domAgent.undo(this._updateSidebars.bind(this));
1047             event.handled = true;
1048             return;
1049         }
1050
1051         var isRedoKey = WebInspector.isMac() ? event.metaKey && event.shiftKey && event.keyIdentifier === "U+005A" : // Z key
1052                                                event.ctrlKey && event.keyIdentifier === "U+0059"; // Y key
1053         if (isRedoKey) {
1054             DOMAgent.redo(this._updateSidebars.bind(this));
1055             event.handled = true;
1056             return;
1057         }
1058
1059         this.treeOutline.handleShortcut(event);
1060     },
1061
1062     handleCopyEvent: function(event)
1063     {
1064         // Don't prevent the normal copy if the user has a selection.
1065         if (!window.getSelection().isCollapsed)
1066             return;
1067         event.clipboardData.clearData();
1068         event.preventDefault();
1069         this.selectedDOMNode().copyNode();
1070     },
1071
1072     sidebarResized: function(event)
1073     {
1074         this.treeOutline.updateSelection();
1075     },
1076
1077     _inspectElementRequested: function(event)
1078     {
1079         var node = event.data;
1080         this.revealAndSelectNode(node.id);
1081     },
1082
1083     revealAndSelectNode: function(nodeId)
1084     {
1085         WebInspector.inspectorView.setCurrentPanel(this);
1086
1087         var node = WebInspector.domAgent.nodeForId(nodeId);
1088         if (!node)
1089             return;
1090
1091         WebInspector.domAgent.highlightDOMNodeForTwoSeconds(nodeId);
1092         this.selectDOMNode(node, true);
1093     },
1094
1095     /** 
1096      * @param {WebInspector.ContextMenu} contextMenu
1097      * @param {Object} target
1098      */
1099     appendApplicableItems: function(contextMenu, target)
1100     {
1101         if (!(target instanceof WebInspector.RemoteObject))
1102             return;
1103         var remoteObject = /** @type {WebInspector.RemoteObject} */ target;
1104         if (remoteObject.subtype !== "node")
1105             return;
1106
1107         function selectNode(nodeId)
1108         {
1109             if (nodeId)
1110                 WebInspector.domAgent.inspectElement(nodeId);
1111         }
1112   
1113         function revealElement()
1114         {
1115             remoteObject.pushNodeToFrontend(selectNode);
1116         }
1117
1118         contextMenu.appendItem(WebInspector.UIString("Reveal in Elements Panel"), revealElement.bind(this));
1119     }
1120 }
1121
1122 WebInspector.ElementsPanel.prototype.__proto__ = WebInspector.Panel.prototype;