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