initial import
[vuplus_webkit] / Source / WebCore / inspector / front-end / MetricsSidebarPane.js
1 /*
2  * Copyright (C) 2007 Apple Inc.  All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *
8  * 1.  Redistributions of source code must retain the above copyright
9  *     notice, this list of conditions and the following disclaimer.
10  * 2.  Redistributions in binary form must reproduce the above copyright
11  *     notice, this list of conditions and the following disclaimer in the
12  *     documentation and/or other materials provided with the distribution.
13  * 3.  Neither the name of Apple Computer, Inc. ("Apple") nor the names of
14  *     its contributors may be used to endorse or promote products derived
15  *     from this software without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
18  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
19  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
20  * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
21  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
22  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
23  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
24  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27  */
28
29 WebInspector.MetricsSidebarPane = function()
30 {
31     WebInspector.SidebarPane.call(this, WebInspector.UIString("Metrics"));
32
33     WebInspector.cssModel.addEventListener(WebInspector.CSSStyleModel.Events.StyleSheetChanged, this._styleSheetChanged, this);
34     WebInspector.domAgent.addEventListener(WebInspector.DOMAgent.Events.AttrModified, this._attributesUpdated, this);
35 }
36
37 WebInspector.MetricsSidebarPane.prototype = {
38     update: function(node)
39     {
40         if (node)
41             this.node = node;
42         this._innerUpdate();
43     },
44
45     _innerUpdate: function()
46     {
47         // FIXME: avoid updates of a collapsed pane.
48         var node = this.node;
49
50         if (!node || node.nodeType() !== Node.ELEMENT_NODE) {
51             this.bodyElement.removeChildren();
52             return;
53         }
54
55         function callback(style)
56         {
57             if (!style || this.node !== node)
58                 return;
59             this._updateMetrics(style);
60         }
61         WebInspector.cssModel.getComputedStyleAsync(node.id, callback.bind(this));
62
63         function inlineStyleCallback(style)
64         {
65             if (!style || this.node !== node)
66                 return;
67             this.inlineStyle = style;
68         }
69         WebInspector.cssModel.getInlineStyleAsync(node.id, inlineStyleCallback.bind(this));
70     },
71
72     _styleSheetChanged: function()
73     {
74         this._innerUpdate();
75     },
76
77     _attributesUpdated: function(event)
78     {
79         if (this.node !== event.data)
80             return;
81
82         // "style" attribute might have changed. Update metrics unless they are being edited.
83         if (!this._isEditingMetrics)
84             this._innerUpdate();
85     },
86
87     _getPropertyValueAsPx: function(style, propertyName)
88     {
89         return Number(style.getPropertyValue(propertyName).replace(/px$/, "") || 0);
90     },
91
92     _getBox: function(computedStyle, componentName)
93     {
94         var suffix = componentName === "border" ? "-width" : "";
95         var left = this._getPropertyValueAsPx(computedStyle, componentName + "-left" + suffix);
96         var top = this._getPropertyValueAsPx(computedStyle, componentName + "-top" + suffix);
97         var right = this._getPropertyValueAsPx(computedStyle, componentName + "-right" + suffix);
98         var bottom = this._getPropertyValueAsPx(computedStyle, componentName + "-bottom" + suffix);
99         return { left: left, top: top, right: right, bottom: bottom };
100     },
101
102     _highlightDOMNode: function(showHighlight, mode, event)
103     {
104         function enclosingOrSelfWithClassInArray(element, classNames)
105         {
106             for (var node = element; node && node !== element.ownerDocument; node = node.parentNode) {
107                 if (node.nodeType === Node.ELEMENT_NODE) {
108                     for (var i = 0; i < classNames.length; ++i) {
109                         if (node.hasStyleClass(classNames[i]))
110                             return node;
111                     }
112                 }
113             }
114             return null;
115         }
116
117         function getBoxRectangleElement(element)
118         {
119             if (!element)
120                 return null;
121             return enclosingOrSelfWithClassInArray(element, ["metrics", "margin", "border", "padding", "content"]);
122         }
123
124         event.stopPropagation();
125         var fromElement = getBoxRectangleElement(event.fromElement);
126         var toElement = getBoxRectangleElement(event.toElement);
127
128         if (fromElement === toElement)
129             return;
130
131         function handleMouseOver(element)
132         {
133             element.addStyleClass("hovered");
134
135             var bgColor;
136             if (element.hasStyleClass("margin"))
137                 bgColor = WebInspector.Color.PageHighlight.Margin.toString("original");
138             else if (element.hasStyleClass("border"))
139                 bgColor = WebInspector.Color.PageHighlight.Border.toString("original");
140             else if (element.hasStyleClass("padding"))
141                 bgColor = WebInspector.Color.PageHighlight.Padding.toString("original");
142             else if (element.hasStyleClass("content"))
143                 bgColor = WebInspector.Color.PageHighlight.Content.toString("original");
144             if (bgColor)
145                 element.style.backgroundColor = bgColor;
146         }
147
148         function handleMouseOut(element)
149         {
150             element.style.backgroundColor = "";
151             element.removeStyleClass("hovered");
152         }
153
154         if (showHighlight) {
155             // Into element.
156             if (this.node && toElement)
157                 handleMouseOver(toElement);
158             var nodeId = this.node ? this.node.id : 0;
159         } else {
160             // Out of element.
161             if (fromElement)
162                 handleMouseOut(fromElement);
163             var nodeId = 0;
164         }
165         if (nodeId) {
166             if (this._highlightMode === mode)
167                 return;
168             this._highlightMode = mode;
169         } else
170             delete this._highlightMode;
171         WebInspector.highlightDOMNode(nodeId, mode);
172     },
173
174     _updateMetrics: function(style)
175     {
176         // Updating with computed style.
177         var metricsElement = document.createElement("div");
178         metricsElement.className = "metrics";
179         var self = this;
180
181         function createBoxPartElement(style, name, side, suffix)
182         {
183             var propertyName = (name !== "position" ? name + "-" : "") + side + suffix;
184             var value = style.getPropertyValue(propertyName);
185             if (value === "" || (name !== "position" && value === "0px"))
186                 value = "\u2012";
187             else if (name === "position" && value === "auto")
188                 value = "\u2012";
189             value = value.replace(/px$/, "");
190
191             var element = document.createElement("div");
192             element.className = side;
193             element.textContent = value;
194             element.addEventListener("dblclick", this.startEditing.bind(this, element, name, propertyName, style), false);
195             return element;
196         }
197
198         function getContentAreaWidthPx(style)
199         {
200             var width = style.getPropertyValue("width").replace(/px$/, "");
201             if (style.getPropertyValue("box-sizing") === "border-box") {
202                 var borderBox = self._getBox(style, "border");
203                 var paddingBox = self._getBox(style, "padding");
204
205                 width = width - borderBox.left - borderBox.right - paddingBox.left - paddingBox.right;
206             }
207
208             return width;
209         }
210
211         function getContentAreaHeightPx(style)
212         {
213             var height = style.getPropertyValue("height").replace(/px$/, "");
214             if (style.getPropertyValue("box-sizing") === "border-box") {
215                 var borderBox = self._getBox(style, "border");
216                 var paddingBox = self._getBox(style, "padding");
217
218                 height = height - borderBox.top - borderBox.bottom - paddingBox.top - paddingBox.bottom;
219             }
220
221             return height;
222         }
223
224         // Display types for which margin is ignored.
225         var noMarginDisplayType = {
226             "table-cell": true,
227             "table-column": true,
228             "table-column-group": true,
229             "table-footer-group": true,
230             "table-header-group": true,
231             "table-row": true,
232             "table-row-group": true
233         };
234
235         // Display types for which padding is ignored.
236         var noPaddingDisplayType = {
237             "table-column": true,
238             "table-column-group": true,
239             "table-footer-group": true,
240             "table-header-group": true,
241             "table-row": true,
242             "table-row-group": true
243         };
244
245         // Position types for which top, left, bottom and right are ignored.
246         var noPositionType = {
247             "static": true
248         };
249
250         var boxes = ["content", "padding", "border", "margin", "position"];
251         var boxLabels = [WebInspector.UIString("content"), WebInspector.UIString("padding"), WebInspector.UIString("border"), WebInspector.UIString("margin"), WebInspector.UIString("position")];
252         var previousBox;
253         for (var i = 0; i < boxes.length; ++i) {
254             var name = boxes[i];
255
256             if (name === "margin" && noMarginDisplayType[style.getPropertyValue("display")])
257                 continue;
258             if (name === "padding" && noPaddingDisplayType[style.getPropertyValue("display")])
259                 continue;
260             if (name === "position" && noPositionType[style.getPropertyValue("position")])
261                 continue;
262
263             var boxElement = document.createElement("div");
264             boxElement.className = name;
265             boxElement.addEventListener("mouseover", this._highlightDOMNode.bind(this, true, name === "position" ? "all" : name), false);
266             boxElement.addEventListener("mouseout", this._highlightDOMNode.bind(this, false, ""), false);
267
268             if (name === "content") {
269                 var widthElement = document.createElement("span");
270                 widthElement.textContent = getContentAreaWidthPx(style);
271                 widthElement.addEventListener("dblclick", this.startEditing.bind(this, widthElement, "width", "width", style), false);
272
273                 var heightElement = document.createElement("span");
274                 heightElement.textContent = getContentAreaHeightPx(style);
275                 heightElement.addEventListener("dblclick", this.startEditing.bind(this, heightElement, "height", "height", style), false);
276
277                 boxElement.appendChild(widthElement);
278                 boxElement.appendChild(document.createTextNode(" \u00D7 "));
279                 boxElement.appendChild(heightElement);
280             } else {
281                 var suffix = (name === "border" ? "-width" : "");
282
283                 var labelElement = document.createElement("div");
284                 labelElement.className = "label";
285                 labelElement.textContent = boxLabels[i];
286                 boxElement.appendChild(labelElement);
287
288                 boxElement.appendChild(createBoxPartElement.call(this, style, name, "top", suffix));
289                 boxElement.appendChild(document.createElement("br"));
290                 boxElement.appendChild(createBoxPartElement.call(this, style, name, "left", suffix));
291
292                 if (previousBox)
293                     boxElement.appendChild(previousBox);
294
295                 boxElement.appendChild(createBoxPartElement.call(this, style, name, "right", suffix));
296                 boxElement.appendChild(document.createElement("br"));
297                 boxElement.appendChild(createBoxPartElement.call(this, style, name, "bottom", suffix));
298             }
299
300             previousBox = boxElement;
301         }
302
303         metricsElement.appendChild(previousBox);
304         metricsElement.addEventListener("mouseover", this._highlightDOMNode.bind(this, true, ""), false);
305         metricsElement.addEventListener("mouseout", this._highlightDOMNode.bind(this, false, ""), false);
306         this.bodyElement.removeChildren();
307         this.bodyElement.appendChild(metricsElement);
308     },
309
310     startEditing: function(targetElement, box, styleProperty, computedStyle)
311     {
312         if (WebInspector.isBeingEdited(targetElement))
313             return;
314
315         var context = { box: box, styleProperty: styleProperty, computedStyle: computedStyle };
316         var boundKeyDown = this._handleKeyDown.bind(this, context, styleProperty);
317         context.keyDownHandler = boundKeyDown;
318         targetElement.addEventListener("keydown", boundKeyDown, false);
319
320         this._isEditingMetrics = true;
321         WebInspector.startEditing(targetElement, {
322             context: context,
323             commitHandler: this.editingCommitted.bind(this),
324             cancelHandler: this.editingCancelled.bind(this)
325         });
326         window.getSelection().setBaseAndExtent(targetElement, 0, targetElement, 1);
327     },
328
329     _handleKeyDown: function(context, styleProperty, event)
330     {
331         if (!/^(?:Page)?(?:Up|Down)$/.test(event.keyIdentifier))
332             return;
333         var element = event.currentTarget;
334
335         var selection = window.getSelection();
336         if (!selection.rangeCount)
337             return;
338
339         var selectionRange = selection.getRangeAt(0);
340         if (selectionRange.commonAncestorContainer !== element && !selectionRange.commonAncestorContainer.isDescendant(element))
341             return;
342
343         var originalValue = element.textContent;
344         var wordRange = selectionRange.startContainer.rangeOfWord(selectionRange.startOffset, WebInspector.StylesSidebarPane.StyleValueDelimiters, element);
345         var wordString = wordRange.toString();
346
347         var matches = /(.*?)(-?(?:\d+(?:\.\d+)?|\.\d+))(.*)/.exec(wordString);
348         var replacementString;
349         if (matches && matches.length) {
350             prefix = matches[1];
351             suffix = matches[3];
352             number = WebInspector.StylesSidebarPane.alteredFloatNumber(parseFloat(matches[2]), event);
353             if (number === null) {
354                 // Need to check for null explicitly.
355                 return;
356             }
357
358             if (styleProperty !== "margin" && number < 0)
359                 number = 0;
360
361             replacementString = prefix + number + suffix;
362         }
363         if (!replacementString)
364             return;
365
366         var replacementTextNode = document.createTextNode(replacementString);
367
368         wordRange.deleteContents();
369         wordRange.insertNode(replacementTextNode);
370
371         var finalSelectionRange = document.createRange();
372         finalSelectionRange.setStart(replacementTextNode, 0);
373         finalSelectionRange.setEnd(replacementTextNode, replacementString.length);
374
375         selection.removeAllRanges();
376         selection.addRange(finalSelectionRange);
377
378         event.handled = true;
379         event.preventDefault();
380         this._applyUserInput(element, replacementString, originalValue, context, false);
381     },
382
383     editingEnded: function(element, context)
384     {
385         delete this.originalPropertyData;
386         delete this.previousPropertyDataCandidate;
387         element.removeEventListener("keydown", context.keyDownHandler, false);
388         delete this._isEditingMetrics;
389     },
390
391     editingCancelled: function(element, context)
392     {
393         if ("originalPropertyData" in this && this.inlineStyle) {
394             if (!this.originalPropertyData) {
395                 // An added property, remove the last property in the style.
396                 var pastLastSourcePropertyIndex = this.inlineStyle.pastLastSourcePropertyIndex();
397                 if (pastLastSourcePropertyIndex)
398                     this.inlineStyle.allProperties[pastLastSourcePropertyIndex - 1].setText("", false);
399             } else
400                 this.inlineStyle.allProperties[this.originalPropertyData.index].setText(this.originalPropertyData.propertyText, false);
401         }
402         this.editingEnded(element, context);
403         this.update();
404     },
405
406     _applyUserInput: function(element, userInput, previousContent, context, commitEditor)
407     {
408         if (!this.inlineStyle) {
409             // Element has no renderer.
410             delete this.originalPropertyValue;
411             return this.editingCancelled(element, context); // nothing changed, so cancel
412         }
413
414         if (commitEditor && userInput === previousContent)
415             return this.editingCancelled(element, context); // nothing changed, so cancel
416
417         if (context.box !== "position" && (!userInput || userInput === "\u2012"))
418             userInput = "0px";
419         else if (context.box === "position" && (!userInput || userInput === "\u2012"))
420             userInput = "auto";
421
422         userInput = userInput.toLowerCase();
423         // Append a "px" unit if the user input was just a number.
424         if (/^\d+$/.test(userInput))
425             userInput += "px";
426
427         var styleProperty = context.styleProperty;
428         var computedStyle = context.computedStyle;
429
430         if (computedStyle.getPropertyValue("box-sizing") === "border-box" && (styleProperty === "width" || styleProperty === "height")) {
431             if (!userInput.match(/px$/)) {
432                 WebInspector.log("For elements with box-sizing: border-box, only absolute content area dimensions can be applied", WebInspector.ConsoleMessage.MessageLevel.Error);
433                 WebInspector.showConsole();
434                 return;
435             }
436
437             var borderBox = this._getBox(computedStyle, "border");
438             var paddingBox = this._getBox(computedStyle, "padding");
439             var userValuePx = Number(userInput.replace(/px$/, ""));
440             if (isNaN(userValuePx))
441                 return;
442             if (styleProperty === "width")
443                 userValuePx += borderBox.left + borderBox.right + paddingBox.left + paddingBox.right;
444             else
445                 userValuePx += borderBox.top + borderBox.bottom + paddingBox.top + paddingBox.bottom;
446
447             userInput = userValuePx + "px";
448         }
449
450         this.previousPropertyDataCandidate = null;
451         var self = this;
452         var callback = function(style) {
453             if (!style)
454                 return;
455             self.inlineStyle = style;
456             if (!("originalPropertyData" in self))
457                 self.originalPropertyData = self.previousPropertyDataCandidate;
458             if ("_highlightMode" in self) {
459                 WebInspector.highlightDOMNode(0, "");
460                 WebInspector.highlightDOMNode(self.node.id, self._highlightMode);
461             }
462             if (commitEditor) {
463                 self.dispatchEventToListeners("metrics edited");
464                 self.update();
465             }
466         };
467
468         var allProperties = this.inlineStyle.allProperties;
469         for (var i = 0; i < allProperties.length; ++i) {
470             var property = allProperties[i];
471             if (property.name !== context.styleProperty || property.inactive)
472                 continue;
473
474             this.previousPropertyDataCandidate = property;
475             property.setValue(userInput, commitEditor, callback);
476             return;
477         }
478
479         this.inlineStyle.appendProperty(context.styleProperty, userInput, callback);
480     },
481
482     editingCommitted: function(element, userInput, previousContent, context)
483     {
484         this.editingEnded(element, context);
485         this._applyUserInput(element, userInput, previousContent, context, true);
486     }
487 }
488
489 WebInspector.MetricsSidebarPane.prototype.__proto__ = WebInspector.SidebarPane.prototype;