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