View Javadoc
1   /*
2    * Copyright (c) 2002-2026 Gargoyle Software Inc.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    * https://www.apache.org/licenses/LICENSE-2.0
8    *
9    * Unless required by applicable law or agreed to in writing, software
10   * distributed under the License is distributed on an "AS IS" BASIS,
11   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12   * See the License for the specific language governing permissions and
13   * limitations under the License.
14   */
15  package org.htmlunit.css;
16  
17  import static org.htmlunit.BrowserVersionFeatures.JS_CLIENTHEIGHT_INPUT_17;
18  import static org.htmlunit.BrowserVersionFeatures.JS_CLIENTHEIGHT_INPUT_18;
19  import static org.htmlunit.BrowserVersionFeatures.JS_CLIENTHEIGHT_RADIO_CHECKBOX_14;
20  import static org.htmlunit.BrowserVersionFeatures.JS_CLIENTHEIGHT_RB_17;
21  import static org.htmlunit.BrowserVersionFeatures.JS_CLIENTHEIGHT_RT_9;
22  import static org.htmlunit.BrowserVersionFeatures.JS_CLIENTHEIGHT_RUBY_17;
23  import static org.htmlunit.BrowserVersionFeatures.JS_CLIENTWIDTH_INPUT_TEXT_169;
24  import static org.htmlunit.BrowserVersionFeatures.JS_CLIENTWIDTH_RADIO_CHECKBOX_14;
25  import static org.htmlunit.css.CssStyleSheet.ABSOLUTE;
26  import static org.htmlunit.css.CssStyleSheet.AUTO;
27  import static org.htmlunit.css.CssStyleSheet.BLOCK;
28  import static org.htmlunit.css.CssStyleSheet.FIXED;
29  import static org.htmlunit.css.CssStyleSheet.INHERIT;
30  import static org.htmlunit.css.CssStyleSheet.INLINE;
31  import static org.htmlunit.css.CssStyleSheet.NONE;
32  import static org.htmlunit.css.CssStyleSheet.RELATIVE;
33  import static org.htmlunit.css.CssStyleSheet.SCROLL;
34  import static org.htmlunit.css.CssStyleSheet.STATIC;
35  
36  import java.util.EnumSet;
37  import java.util.HashSet;
38  import java.util.Map;
39  import java.util.Set;
40  import java.util.SortedMap;
41  import java.util.TreeMap;
42  
43  import org.htmlunit.BrowserVersion;
44  import org.htmlunit.BrowserVersionFeatures;
45  import org.htmlunit.Page;
46  import org.htmlunit.SgmlPage;
47  import org.htmlunit.WebWindow;
48  import org.htmlunit.css.StyleAttributes.Definition;
49  import org.htmlunit.cssparser.dom.AbstractCSSRuleImpl;
50  import org.htmlunit.cssparser.dom.CSSStyleDeclarationImpl;
51  import org.htmlunit.cssparser.dom.Property;
52  import org.htmlunit.cssparser.parser.selector.Selector;
53  import org.htmlunit.cssparser.parser.selector.SelectorSpecificity;
54  import org.htmlunit.html.BaseFrameElement;
55  import org.htmlunit.html.DomElement;
56  import org.htmlunit.html.DomNode;
57  import org.htmlunit.html.DomText;
58  import org.htmlunit.html.HtmlAbbreviated;
59  import org.htmlunit.html.HtmlAcronym;
60  import org.htmlunit.html.HtmlAddress;
61  import org.htmlunit.html.HtmlArticle;
62  import org.htmlunit.html.HtmlAside;
63  import org.htmlunit.html.HtmlBaseFont;
64  import org.htmlunit.html.HtmlBidirectionalIsolation;
65  import org.htmlunit.html.HtmlBidirectionalOverride;
66  import org.htmlunit.html.HtmlBig;
67  import org.htmlunit.html.HtmlBody;
68  import org.htmlunit.html.HtmlBold;
69  import org.htmlunit.html.HtmlButton;
70  import org.htmlunit.html.HtmlButtonInput;
71  import org.htmlunit.html.HtmlCanvas;
72  import org.htmlunit.html.HtmlCenter;
73  import org.htmlunit.html.HtmlCheckBoxInput;
74  import org.htmlunit.html.HtmlCitation;
75  import org.htmlunit.html.HtmlCode;
76  import org.htmlunit.html.HtmlData;
77  import org.htmlunit.html.HtmlDefinition;
78  import org.htmlunit.html.HtmlDefinitionDescription;
79  import org.htmlunit.html.HtmlDefinitionTerm;
80  import org.htmlunit.html.HtmlDialog;
81  import org.htmlunit.html.HtmlDivision;
82  import org.htmlunit.html.HtmlElement;
83  import org.htmlunit.html.HtmlElement.DisplayStyle;
84  import org.htmlunit.html.HtmlEmphasis;
85  import org.htmlunit.html.HtmlFigure;
86  import org.htmlunit.html.HtmlFigureCaption;
87  import org.htmlunit.html.HtmlFileInput;
88  import org.htmlunit.html.HtmlFooter;
89  import org.htmlunit.html.HtmlFrame;
90  import org.htmlunit.html.HtmlHeader;
91  import org.htmlunit.html.HtmlHeading1;
92  import org.htmlunit.html.HtmlHeading2;
93  import org.htmlunit.html.HtmlHeading3;
94  import org.htmlunit.html.HtmlHeading4;
95  import org.htmlunit.html.HtmlHeading5;
96  import org.htmlunit.html.HtmlHeading6;
97  import org.htmlunit.html.HtmlHiddenInput;
98  import org.htmlunit.html.HtmlImage;
99  import org.htmlunit.html.HtmlInlineFrame;
100 import org.htmlunit.html.HtmlInput;
101 import org.htmlunit.html.HtmlItalic;
102 import org.htmlunit.html.HtmlKeyboard;
103 import org.htmlunit.html.HtmlLayer;
104 import org.htmlunit.html.HtmlLegend;
105 import org.htmlunit.html.HtmlMain;
106 import org.htmlunit.html.HtmlMark;
107 import org.htmlunit.html.HtmlNav;
108 import org.htmlunit.html.HtmlNoBreak;
109 import org.htmlunit.html.HtmlNoEmbed;
110 import org.htmlunit.html.HtmlNoFrames;
111 import org.htmlunit.html.HtmlNoLayer;
112 import org.htmlunit.html.HtmlNoScript;
113 import org.htmlunit.html.HtmlOutput;
114 import org.htmlunit.html.HtmlPage;
115 import org.htmlunit.html.HtmlPasswordInput;
116 import org.htmlunit.html.HtmlPlainText;
117 import org.htmlunit.html.HtmlRadioButtonInput;
118 import org.htmlunit.html.HtmlRb;
119 import org.htmlunit.html.HtmlResetInput;
120 import org.htmlunit.html.HtmlRp;
121 import org.htmlunit.html.HtmlRt;
122 import org.htmlunit.html.HtmlRtc;
123 import org.htmlunit.html.HtmlRuby;
124 import org.htmlunit.html.HtmlS;
125 import org.htmlunit.html.HtmlSample;
126 import org.htmlunit.html.HtmlSection;
127 import org.htmlunit.html.HtmlSelect;
128 import org.htmlunit.html.HtmlSlot;
129 import org.htmlunit.html.HtmlSmall;
130 import org.htmlunit.html.HtmlSpan;
131 import org.htmlunit.html.HtmlStrike;
132 import org.htmlunit.html.HtmlStrong;
133 import org.htmlunit.html.HtmlSubmitInput;
134 import org.htmlunit.html.HtmlSubscript;
135 import org.htmlunit.html.HtmlSummary;
136 import org.htmlunit.html.HtmlSuperscript;
137 import org.htmlunit.html.HtmlTableCell;
138 import org.htmlunit.html.HtmlTableRow;
139 import org.htmlunit.html.HtmlTeletype;
140 import org.htmlunit.html.HtmlTextArea;
141 import org.htmlunit.html.HtmlTextInput;
142 import org.htmlunit.html.HtmlTime;
143 import org.htmlunit.html.HtmlUnderlined;
144 import org.htmlunit.html.HtmlUnknownElement;
145 import org.htmlunit.html.HtmlVariable;
146 import org.htmlunit.html.HtmlWordBreak;
147 import org.htmlunit.html.serializer.HtmlSerializerVisibleText;
148 import org.htmlunit.platform.Platform;
149 import org.htmlunit.util.StringUtils;
150 
151 /**
152  * An object for a CSSStyleDeclaration, which is computed.
153  *
154  * @see org.htmlunit.javascript.host.Window#getComputedStyle(Object, String)
155  *
156  * @author Ahmed Ashour
157  * @author Marc Guillemot
158  * @author Ronald Brill
159  * @author Frank Danek
160  * @author Alex Gorbatovsky
161  * @author cd alexndr
162  */
163 @SuppressWarnings("PMD.AvoidDuplicateLiterals")
164 public class ComputedCssStyleDeclaration extends AbstractCssStyleDeclaration {
165 
166     /** The set of 'inheritable' definitions. */
167     private static final Set<Definition> INHERITABLE_DEFINITIONS = EnumSet.of(
168         Definition.BORDER_COLLAPSE,
169         Definition.BORDER_SPACING,
170         Definition.CAPTION_SIDE,
171         Definition.COLOR,
172         Definition.CURSOR,
173         Definition.DIRECTION,
174         Definition.EMPTY_CELLS,
175         Definition.FONT_FAMILY,
176         Definition.FONT_SIZE,
177         Definition.FONT_STYLE,
178         Definition.FONT_VARIANT,
179         Definition.FONT_WEIGHT,
180         Definition.FONT,
181         Definition.LETTER_SPACING,
182         Definition.LINE_HEIGHT,
183         Definition.LIST_STYLE_IMAGE,
184         Definition.LIST_STYLE_POSITION,
185         Definition.LIST_STYLE_TYPE,
186         Definition.LIST_STYLE,
187         Definition.ORPHANS,
188         Definition.QUOTES,
189         Definition.SPEAK,
190         Definition.TEXT_ALIGN,
191         Definition.TEXT_INDENT,
192         Definition.TEXT_TRANSFORM,
193         Definition.VISIBILITY,
194         Definition.WHITE_SPACE,
195         Definition.WIDOWS,
196         Definition.WORD_SPACING);
197 
198     /** Default font sizes for heading elements, used when no explicit font-size is set. */
199     private static final Map<Class<? extends HtmlElement>, String> HEADING_DEFAULT_FONT_SIZES = Map.of(
200         HtmlHeading1.class, "32px",
201         HtmlHeading2.class, "24px",
202         HtmlHeading3.class, "19px",
203         HtmlHeading4.class, "16px",
204         HtmlHeading5.class, "13px",
205         HtmlHeading6.class, "11px");
206 
207     private static final Set<Class<? extends HtmlElement>> ZERO_HEIGHT_ELEMENT_CLASSES = Set.of(
208             HtmlAbbreviated.class,
209             HtmlAcronym.class,
210             HtmlAddress.class,
211             HtmlArticle.class,
212             HtmlAside.class,
213             HtmlBaseFont.class,
214             HtmlBidirectionalIsolation.class,
215             HtmlBidirectionalOverride.class,
216             HtmlBig.class,
217             HtmlBold.class,
218             HtmlCenter.class,
219             HtmlCitation.class,
220             HtmlCode.class,
221             HtmlData.class,
222             HtmlDefinition.class,
223             HtmlDefinitionDescription.class,
224             HtmlDefinitionTerm.class,
225             HtmlDivision.class,
226             HtmlEmphasis.class,
227             HtmlFigure.class,
228             HtmlFigureCaption.class,
229             HtmlFooter.class,
230             HtmlHeader.class,
231             HtmlItalic.class,
232             HtmlKeyboard.class,
233             HtmlLayer.class,
234             HtmlLegend.class,
235             HtmlMain.class,
236             HtmlMark.class,
237             HtmlNav.class,
238             HtmlNoBreak.class,
239             HtmlNoEmbed.class,
240             HtmlNoFrames.class,
241             HtmlNoLayer.class,
242             HtmlNoScript.class,
243             HtmlOutput.class,
244             HtmlPlainText.class,
245             HtmlRp.class,
246             HtmlRtc.class,
247             HtmlS.class,
248             HtmlSample.class,
249             HtmlSection.class,
250             HtmlSlot.class,
251             HtmlSmall.class,
252             HtmlStrike.class,
253             HtmlStrong.class,
254             HtmlSubscript.class,
255             HtmlSummary.class,
256             HtmlSuperscript.class,
257             HtmlTeletype.class,
258             HtmlTime.class,
259             HtmlUnderlined.class,
260             HtmlUnknownElement.class,
261             HtmlVariable.class,
262             HtmlWordBreak.class
263         );
264 
265     /** Denotes a value which should be returned as is. */
266     public static final String EMPTY_FINAL = new String("");
267 
268     /** The computed, cached width of the element to which this computed style belongs (no padding, borders, etc.). */
269     private int cachedWidth_ = Integer.MIN_VALUE;
270 
271     /** The computed, cached content width (sum/max of children's widths) of the element. */
272     private int cachedContentWidth_ = Integer.MIN_VALUE;
273 
274     /**
275      * The computed, cached height of the element to which this computed style belongs (no padding, borders, etc.),
276      * taking child elements into account.
277      */
278     private int cachedHeight_ = Integer.MIN_VALUE;
279 
280     /**
281      * The computed, cached height of the element to which this computed style belongs (no padding, borders, etc.),
282      * <b>not</b> taking child elements into account.
283      */
284     private int cachedEmptyHeight_ = Integer.MIN_VALUE;
285 
286     /** The computed, cached top of the element to which this computed style belongs. */
287     private int cachedTop_ = Integer.MIN_VALUE;
288 
289     /** The computed, cached horizontal padding (left + right) of the element to which this computed style belongs. */
290     private int cachedPaddingHorizontal_ = Integer.MIN_VALUE;
291 
292     /** The computed, cached vertical padding (top + bottom) of the element to which this computed style belongs. */
293     private int cachedPaddingVertical_ = Integer.MIN_VALUE;
294 
295     /** The computed, cached horizontal border (left + right) of the element to which this computed style belongs. */
296     private int cachedBorderHorizontal_ = Integer.MIN_VALUE;
297 
298     /** The computed, cached vertical border (top + bottom) of the element to which this computed style belongs. */
299     private int cachedBorderVertical_ = Integer.MIN_VALUE;
300 
301     /**
302      * Local modifications maintained here rather than in the element. We use a sorted
303      * map so that results are deterministic and thus easily testable.
304      */
305     private final SortedMap<String, StyleElement> localModifications_ = new TreeMap<>();
306 
307     /** The wrapped CSSStyleDeclaration. */
308     private final ElementCssStyleDeclaration elementStyleDeclaration_;
309 
310     /**
311      * Ctor.
312      * @param styleDeclaration the {@link ElementCssStyleDeclaration} this is based on
313      */
314     public ComputedCssStyleDeclaration(final ElementCssStyleDeclaration styleDeclaration) {
315         super();
316         elementStyleDeclaration_ = styleDeclaration;
317         elementStyleDeclaration_.getDomElement().setDefaults(this);
318     }
319 
320     /**
321      * {@inheritDoc}
322      */
323     @Override
324     public String getStylePriority(final String name) {
325         return elementStyleDeclaration_.getStylePriority(name);
326     }
327 
328     /**
329      * {@inheritDoc}
330      */
331     @Override
332     public String getCssText() {
333         return elementStyleDeclaration_.getCssText();
334     }
335 
336     /**
337      * {@inheritDoc}
338      */
339     @Override
340     public String getStyleAttribute(final String name) {
341         final StyleElement element = getStyleElement(name);
342         if (element != null && element.getValue() != null) {
343             final String value = element.getValue();
344             if (!"content".equals(name)
345                     && !value.contains("url")) {
346                 return StringUtils.toRootLowerCase(value);
347             }
348             return value;
349         }
350         return "";
351     }
352 
353     /**
354      * {@inheritDoc}
355      */
356     @Override
357     public String getStyleAttribute(final Definition definition, final boolean getDefaultValueIfEmpty) {
358         final BrowserVersion browserVersion = getDomElement().getPage().getWebClient().getBrowserVersion();
359         final boolean isDefInheritable = INHERITABLE_DEFINITIONS.contains(definition);
360 
361         // to make the fuzzer happy the recursion was removed
362         final ComputedCssStyleDeclaration[] queue = {this};
363         String value = null;
364         while (queue[0] != null) {
365             value = getStyleAttributeWorker(definition, getDefaultValueIfEmpty,
366                                             browserVersion, isDefInheritable, queue);
367         }
368 
369         return value;
370     }
371 
372     /**
373      * Internal worker to resolve inherited or default style attributes recursively without stack recursion.
374      *
375      * @param definition the CSS style attribute definition
376      * @param getDefaultValueIfEmpty whether to fall back to the default computed value if unassigned
377      * @param browserVersion the current target browser version
378      * @param isDefInheritable true if the style definition is an inheritable property
379      * @param queue single-element array used as a pointer queue for loop-based parent traversal
380      * @return the resolved computed style attribute string
381      */
382     private static String getStyleAttributeWorker(final Definition definition,
383                 final boolean getDefaultValueIfEmpty, final BrowserVersion browserVersion,
384                 final boolean isDefInheritable, final ComputedCssStyleDeclaration[] queue) {
385         final ComputedCssStyleDeclaration decl = queue[0];
386         queue[0] = null;
387 
388         final DomElement domElem = decl.getDomElement();
389         if (!domElem.isAttachedToPage()) {
390             return EMPTY_FINAL;
391         }
392 
393         String value = decl.getStyleAttribute(definition.getAttributeName());
394         if (value.isEmpty()) {
395             final DomNode parent = domElem.getParentNode();
396             if (isDefInheritable && parent instanceof DomElement element) {
397                 final WebWindow window = domElem.getPage().getEnclosingWindow();
398 
399                 queue[0] = window.getComputedStyle(element, null);
400             }
401             else if (getDefaultValueIfEmpty) {
402                 value = definition.getDefaultComputedValue(browserVersion);
403             }
404         }
405 
406         return value;
407     }
408 
409     /**
410      * Return the string, or {@code toReturnIfEmptyOrDefault}.
411      *
412      * @param toReturnIfEmptyOrDefault the value to return if empty or equals the {@code defaultValue}
413      * @param defaultValue the default value of the string
414      * @return the string, or {@code toReturnIfEmptyOrDefault}
415      */
416     private String getStyleAttribute(final Definition definition, final String toReturnIfEmptyOrDefault,
417             final String defaultValue) {
418         final DomElement domElement = getDomElement();
419 
420         if (!domElement.isAttachedToPage()) {
421             return EMPTY_FINAL;
422         }
423 
424         final boolean isDefInheritable = INHERITABLE_DEFINITIONS.contains(definition);
425 
426         // to make the fuzzer happy the recursion was removed
427         final BrowserVersion browserVersion = domElement.getPage().getWebClient().getBrowserVersion();
428         final ComputedCssStyleDeclaration[] queue = {this};
429         String value = null;
430         while (queue[0] != null) {
431             value = getStyleAttributeWorker(definition, false, browserVersion, isDefInheritable, queue);
432         }
433 
434         if (value == null || value.isEmpty() || value.equals(defaultValue)) {
435             return toReturnIfEmptyOrDefault;
436         }
437 
438         return value;
439     }
440 
441     /**
442      * {@inheritDoc}
443      */
444     @Override
445     public void setCssText(final String value) {
446         // read only
447     }
448 
449     /**
450      * {@inheritDoc}
451      */
452     @Override
453     public void setStyleAttribute(final String name, final String newValue, final String important) {
454         // read only
455     }
456 
457     /**
458      * {@inheritDoc}
459      */
460     @Override
461     public String removeStyleAttribute(final String name) {
462         // read only
463         return null;
464     }
465 
466     /**
467      * {@inheritDoc}
468      */
469     @Override
470     public int getLength() {
471         return elementStyleDeclaration_.getLength();
472     }
473 
474     /**
475      * Returns the width.
476      *
477      * @return the width
478      */
479     @Override
480     public String getWidth() {
481         if (NONE.equals(getDisplay())) {
482             return AUTO;
483         }
484 
485         final DomElement domElem = getDomElement();
486         if (!domElem.isAttachedToPage()) {
487             return "";
488         }
489 
490         final int windowWidth = domElem.getPage().getEnclosingWindow().getInnerWidth();
491         final String width = CssPixelValueConverter.pixelString(domElem,
492                 style -> {
493                     final String value = style.getStyleAttribute(Definition.WIDTH, true);
494                     if (StringUtils.isEmptyOrNull(value)) {
495                         final String position = getStyleAttribute(Definition.POSITION, true);
496                         if (ABSOLUTE.equals(position) || FIXED.equals(position)) {
497                             final String content = getLayoutText(domElem);
498                             // do this only for small content
499                             // at least for empty div's this is more correct
500                             if (null != content && content.length() < 13) {
501                                 return (content.length() * 7) + "px";
502                             }
503                         }
504 
505                         int windowDefaultValue = windowWidth;
506                         if (domElem instanceof HtmlBody) {
507                             windowDefaultValue -= 16;
508                         }
509                         return windowDefaultValue + "px";
510                     }
511                     else if (AUTO.equals(value)) {
512                         int windowDefaultValue = windowWidth;
513                         if (domElem instanceof HtmlBody) {
514                             windowDefaultValue -= 16;
515                         }
516                         return windowDefaultValue + "px";
517                     }
518 
519                     return value;
520                 },
521                 () -> 0,
522                 () -> windowWidth);
523         // e.g. calc() may result in a negative value; the width is never negative
524         return width.startsWith("-") ? "0px" : width;
525     }
526 
527     /**
528      * {@inheritDoc}
529      */
530     @Override
531     public String item(final int index) {
532         return elementStyleDeclaration_.item(index);
533     }
534 
535     /**
536      * {@inheritDoc}
537      */
538     @Override
539     public AbstractCSSRuleImpl getParentRule() {
540         return elementStyleDeclaration_.getParentRule();
541     }
542 
543     /**
544      * {@inheritDoc}
545      */
546     @Override
547     public StyleElement getStyleElement(final String name) {
548         final StyleElement existent = elementStyleDeclaration_.getStyleElement(name);
549 
550         final StyleElement localStyleMod = localModifications_.get(name);
551         if (localStyleMod == null) {
552             return existent;
553         }
554 
555         if (existent == null) {
556             // Local modifications represent either default style elements or style elements
557             // defined in stylesheets; either way, they shouldn't overwrite any style
558             // elements derived directly from the HTML element's "style" attribute.
559             return localStyleMod;
560         }
561 
562         // replace if !IMPORTANT
563         if (StyleElement.PRIORITY_IMPORTANT.equals(localStyleMod.getPriority())) {
564             if (existent.isImportant()) {
565                 if (existent.getSpecificity().compareTo(localStyleMod.getSpecificity()) < 0) {
566                     return localStyleMod;
567                 }
568             }
569             else {
570                 return localStyleMod;
571             }
572         }
573         return existent;
574     }
575 
576     /**
577      * {@inheritDoc}
578      */
579     @Override
580     public StyleElement getStyleElementCaseInSensitive(final String name) {
581         return elementStyleDeclaration_.getStyleElementCaseInSensitive(name);
582     }
583 
584     /**
585      * {@inheritDoc}
586      */
587     @Override
588     public Map<String, StyleElement> getStyleMap() {
589         return elementStyleDeclaration_.getStyleMap();
590     }
591 
592     /**
593      * Returns the {@link DomElement} the backing {@link ElementCssStyleDeclaration}
594      * is associated with.
595      *
596      * @return the {@link DomElement} the backing {@link ElementCssStyleDeclaration}
597      *         is associated with
598      */
599     public DomElement getDomElement() {
600         return elementStyleDeclaration_.getDomElement();
601     }
602 
603     /**
604      * {@inheritDoc}
605      */
606     @Override
607     public String getBackgroundAttachment() {
608         return defaultIfEmpty(super.getBackgroundAttachment(), Definition.BACKGROUND_ATTACHMENT);
609     }
610 
611     /**
612      * {@inheritDoc}
613      */
614     @Override
615     public String getBackgroundColor() {
616         if (!getDomElement().isAttachedToPage()) {
617             return EMPTY_FINAL;
618         }
619 
620         final String value = super.getBackgroundColor();
621         if (StringUtils.isEmptyOrNull(value)) {
622             return Definition.BACKGROUND_COLOR.getDefaultComputedValue(getBrowserVersion());
623         }
624         return CssColors.toRGBColor(value);
625     }
626 
627     /**
628      * {@inheritDoc}
629      */
630     @Override
631     public String getBackgroundImage() {
632         return defaultIfEmpty(super.getBackgroundImage(), Definition.BACKGROUND_IMAGE);
633     }
634 
635     /**
636      * Gets the {@code backgroundPosition} style attribute.
637      * @return the style attribute
638      */
639     @Override
640     public String getBackgroundPosition() {
641         return defaultIfEmpty(super.getBackgroundPosition(), Definition.BACKGROUND_POSITION);
642     }
643 
644     /**
645      * {@inheritDoc}
646      */
647     @Override
648     public String getBackgroundRepeat() {
649         return defaultIfEmpty(super.getBackgroundRepeat(), Definition.BACKGROUND_REPEAT);
650     }
651 
652     /**
653      * {@inheritDoc}
654      */
655     @Override
656     public String getBlockSize() {
657         if (NONE.equals(getDisplay())) {
658             return defaultIfEmpty(super.getBlockSize(), Definition.BLOCK_SIZE);
659         }
660 
661         final DomElement domElem = getDomElement();
662         if (!domElem.isAttachedToPage()) {
663             return defaultIfEmpty(super.getBlockSize(), Definition.BLOCK_SIZE);
664         }
665 
666         return CssPixelValueConverter.pixelString(domElem,
667                 style -> {
668                     final String value = style.getStyleAttribute(Definition.HEIGHT, true);
669                     if (StringUtils.isEmptyOrNull(value)) {
670                         final String content = getLayoutText(domElem);
671                         // do this only for small content
672                         // at least for empty div's this is more correct
673                         if (content == null) {
674                             return "0px";
675                         }
676                         return calculateIntrinsicHeight(domElem) + "px";
677                     }
678                     return value;
679                 },
680                 () -> 0,
681                 () -> 0);
682     }
683 
684     /**
685      * {@inheritDoc}
686      */
687     @Override
688     public String getBorderBottomColor() {
689         return defaultIfEmpty(super.getBorderBottomColor(), Definition.BORDER_BOTTOM_COLOR);
690     }
691 
692     /**
693      * {@inheritDoc}
694      */
695     @Override
696     public String getBorderBottomStyle() {
697         return defaultIfEmpty(super.getBorderBottomStyle(), Definition.BORDER_BOTTOM_STYLE);
698     }
699 
700     /**
701      * {@inheritDoc}
702      */
703     @Override
704     public String getBorderBottomWidth() {
705         return pixelString(defaultIfEmpty(super.getBorderBottomWidth(), Definition.BORDER_BOTTOM_WIDTH));
706     }
707 
708     /**
709      * {@inheritDoc}
710      */
711     @Override
712     public String getBorderLeftColor() {
713         return defaultIfEmpty(super.getBorderLeftColor(), Definition.BORDER_LEFT_COLOR);
714     }
715 
716     /**
717      * {@inheritDoc}
718      */
719     @Override
720     public String getBorderLeftStyle() {
721         return defaultIfEmpty(super.getBorderLeftStyle(), Definition.BORDER_LEFT_STYLE);
722     }
723 
724     /**
725      * {@inheritDoc}
726      */
727     @Override
728     public String getBorderLeftWidth() {
729         return pixelString(defaultIfEmpty(super.getBorderLeftWidth(), "0px", null));
730     }
731 
732     /**
733      * {@inheritDoc}
734      */
735     @Override
736     public String getBorderRightColor() {
737         return defaultIfEmpty(super.getBorderRightColor(), "rgb(0, 0, 0)", null);
738     }
739 
740     /**
741      * {@inheritDoc}
742      */
743     @Override
744     public String getBorderRightStyle() {
745         return defaultIfEmpty(super.getBorderRightStyle(), NONE, null);
746     }
747 
748     /**
749      * {@inheritDoc}
750      */
751     @Override
752     public String getBorderRightWidth() {
753         return pixelString(defaultIfEmpty(super.getBorderRightWidth(), "0px", null));
754     }
755 
756     /**
757      * {@inheritDoc}
758      */
759     @Override
760     public String getBorderTopColor() {
761         return defaultIfEmpty(super.getBorderTopColor(), "rgb(0, 0, 0)", null);
762     }
763 
764     /**
765      * {@inheritDoc}
766      */
767     @Override
768     public String getBorderTopStyle() {
769         return defaultIfEmpty(super.getBorderTopStyle(), NONE, null);
770     }
771 
772     /**
773      * {@inheritDoc}
774      */
775     @Override
776     public String getBorderTopWidth() {
777         return pixelString(defaultIfEmpty(super.getBorderTopWidth(), "0px", null));
778     }
779 
780     /**
781      * {@inheritDoc}
782      */
783     @Override
784     public String getBottom() {
785         return getStyleAttribute(Definition.BOTTOM, AUTO, null);
786     }
787 
788     /**
789      * {@inheritDoc}
790      */
791     @Override
792     public String getColor() {
793         final String value = getStyleAttribute(Definition.COLOR, "rgb(0, 0, 0)", null);
794         return CssColors.toRGBColor(value);
795     }
796 
797     /**
798      * {@inheritDoc}
799      */
800     @Override
801     public String getCssFloat() {
802         return defaultIfEmpty(super.getCssFloat(), Definition.CSS_FLOAT);
803     }
804 
805     /**
806      * {@inheritDoc}
807      */
808     @Override
809     public String getDisplay() {
810         final DomElement domElem = getDomElement();
811         if (!domElem.isAttachedToPage()) {
812             return "";
813         }
814 
815         final HtmlElement htmlElem = (domElem instanceof HtmlElement e) ? e : null;
816 
817         // don't use defaultIfEmpty for performance
818         // (no need to calculate the default if not empty)
819         final String value = getStyleAttribute(Definition.DISPLAY.getAttributeName());
820         if (StringUtils.isEmptyOrNull(value)) {
821             if (htmlElem == null) {
822                 return "";
823             }
824             // the hidden attribute is like a default style 'display: none';
825             // an explicit display style wins
826             if (htmlElem.isHidden()) {
827                 return DisplayStyle.NONE.value();
828             }
829             // like the default style 'dialog:not([open]) { display: none; }'
830             if (htmlElem instanceof HtmlDialog dialog) {
831                 return dialog.isOpen() ? DisplayStyle.BLOCK.value() : DisplayStyle.NONE.value();
832             }
833             return htmlElem.getDefaultStyleDisplay().value();
834         }
835 
836         return value;
837     }
838 
839     /**
840      * {@inheritDoc}
841      */
842     @Override
843     public String getFont() {
844         final DomElement domElem = getDomElement();
845         if (domElem.isAttachedToPage()) {
846             return getStyleAttribute(Definition.FONT, true);
847         }
848         return "";
849     }
850 
851     /**
852      * {@inheritDoc}
853      */
854     @Override
855     public String getFontFamily() {
856         return getStyleAttribute(Definition.FONT_FAMILY, true);
857     }
858 
859     /**
860      * {@inheritDoc}
861      */
862     @Override
863     public String getFontSize() {
864         return getStyleAttribute(Definition.FONT_SIZE, true);
865     }
866 
867     /**
868      * {@inheritDoc}
869      */
870     @Override
871     public String getLineHeight() {
872         return defaultIfEmpty(super.getLineHeight(), Definition.LINE_HEIGHT);
873     }
874 
875     /**
876      * {@inheritDoc}
877      */
878     @Override
879     public String getHeight() {
880         if (NONE.equals(getDisplay())) {
881             return AUTO;
882         }
883 
884         final DomElement elem = getDomElement();
885         if (!elem.isAttachedToPage()) {
886             return "";
887         }
888 
889         final ComputedCssStyleDeclaration style = elem.getPage().getEnclosingWindow().getComputedStyle(elem, null);
890         final String styleValue = style.getStyleAttribute(Definition.HEIGHT, true);
891 
892         if (styleValue == null || styleValue.isEmpty() || AUTO.equals(styleValue) || styleValue.endsWith("%")
893                 || CssMathFunctionEvaluator.isMathFunction(styleValue)) {
894             return style.getCalculatedHeight(false, false) + "px";
895         }
896 
897         if (styleValue.endsWith("px")) {
898             return styleValue;
899         }
900 
901         return CssPixelValueConverter.pixelValue(styleValue) + "px";
902     }
903 
904     /**
905      * {@inheritDoc}
906      */
907     @Override
908     public String getLeft() {
909         if (NONE.equals(getDisplay())) {
910             return AUTO;
911         }
912 
913         final DomElement elem = getDomElement();
914         if (!elem.isAttachedToPage()) {
915             return "";
916         }
917 
918         final String superLeft = super.getLeft();
919         if (!superLeft.endsWith("%")) {
920             return defaultIfEmpty(superLeft, AUTO, null);
921         }
922 
923         return CssPixelValueConverter.pixelString(elem,
924                 style -> {
925                     if (style.getDomElement() == elem) {
926                         return style.getStyleAttribute(Definition.LEFT, true);
927                     }
928                     return style.getStyleAttribute(Definition.WIDTH, true);
929                 },
930                 () -> 0,
931                 () -> 0);
932     }
933 
934     /**
935      * {@inheritDoc}
936      */
937     @Override
938     public String getLetterSpacing() {
939         return defaultIfEmpty(super.getLetterSpacing(), "normal", null);
940     }
941 
942     /**
943      * {@inheritDoc}
944      */
945     @Override
946     public String getMargin() {
947         return defaultIfEmpty(super.getMargin(), Definition.MARGIN, true);
948     }
949 
950     /**
951      * {@inheritDoc}
952      */
953     @Override
954     public String getMarginBottom() {
955         return pixelString(defaultIfEmpty(super.getMarginBottom(), "0px", null));
956     }
957 
958     /**
959      * {@inheritDoc}
960      */
961     @Override
962     public String getMarginLeft() {
963         return getMarginX(super.getMarginLeft(), Definition.MARGIN_LEFT);
964     }
965 
966     /**
967      * {@inheritDoc}
968      */
969     @Override
970     public String getMarginRight() {
971         return getMarginX(super.getMarginRight(), Definition.MARGIN_RIGHT);
972     }
973 
974     private String getMarginX(final String superMarginX, final Definition definition) {
975         if (!superMarginX.endsWith("%")) {
976             return pixelString(defaultIfEmpty(superMarginX, "0px", null));
977         }
978         final DomElement element = getDomElement();
979         if (!element.isAttachedToPage()) {
980             return "";
981         }
982 
983         final int windowWidth = element.getPage().getEnclosingWindow().getInnerWidth();
984         return CssPixelValueConverter.pixelString(element,
985                 style -> {
986                     if (style.getDomElement() == element) {
987                         return style.getStyleAttribute(definition, true);
988                     }
989                     return style.getStyleAttribute(Definition.WIDTH, true);
990                 },
991                 () -> 0,
992                 () -> windowWidth);
993     }
994 
995     /**
996      * {@inheritDoc}
997      */
998     @Override
999     public String getMarginTop() {
1000         return pixelString(defaultIfEmpty(super.getMarginTop(), "0px", null));
1001     }
1002 
1003     /**
1004      * {@inheritDoc}
1005      */
1006     @Override
1007     public String getMaxHeight() {
1008         return defaultIfEmpty(super.getMaxHeight(), NONE, null);
1009     }
1010 
1011     /**
1012      * {@inheritDoc}
1013      */
1014     @Override
1015     public String getMaxWidth() {
1016         return defaultIfEmpty(super.getMaxWidth(), NONE, null);
1017     }
1018 
1019     /**
1020      * {@inheritDoc}
1021      */
1022     @Override
1023     public String getMinHeight() {
1024         return defaultIfEmpty(super.getMinHeight(), "0px", null);
1025     }
1026 
1027     /**
1028      * {@inheritDoc}
1029      */
1030     @Override
1031     public String getMinWidth() {
1032         return defaultIfEmpty(super.getMinWidth(), "0px", null);
1033     }
1034 
1035     /**
1036      * {@inheritDoc}
1037      */
1038     @Override
1039     public String getOpacity() {
1040         return defaultIfEmpty(super.getOpacity(), "1", null);
1041     }
1042 
1043     /**
1044      * {@inheritDoc}
1045      */
1046     @Override
1047     public String getOrphans() {
1048         return defaultIfEmpty(super.getOrphans(), Definition.ORPHANS);
1049     }
1050 
1051     /**
1052      * {@inheritDoc}
1053      */
1054     @Override
1055     public String getOutlineWidth() {
1056         return defaultIfEmpty(super.getOutlineWidth(), "0px", null);
1057     }
1058 
1059     /**
1060      * {@inheritDoc}
1061      */
1062     @Override
1063     public String getPadding() {
1064         return defaultIfEmpty(super.getPadding(), Definition.PADDING, true);
1065     }
1066 
1067     /**
1068      * {@inheritDoc}
1069      */
1070     @Override
1071     public String getPaddingBottom() {
1072         return pixelString(defaultIfEmpty(super.getPaddingBottom(), "0px", null));
1073     }
1074 
1075     /**
1076      * {@inheritDoc}
1077      */
1078     @Override
1079     public String getPaddingLeft() {
1080         return pixelString(defaultIfEmpty(super.getPaddingLeft(), "0px", null));
1081     }
1082 
1083     /**
1084      * {@inheritDoc}
1085      */
1086     @Override
1087     public String getPaddingRight() {
1088         return pixelString(defaultIfEmpty(super.getPaddingRight(), "0px", null));
1089     }
1090 
1091     /**
1092      * {@inheritDoc}
1093      */
1094     @Override
1095     public String getPaddingTop() {
1096         return pixelString(defaultIfEmpty(super.getPaddingTop(), "0px", null));
1097     }
1098 
1099     /**
1100      * {@inheritDoc}
1101      */
1102     @Override
1103     public String getRight() {
1104         return defaultIfEmpty(super.getRight(), AUTO, null);
1105     }
1106 
1107     /**
1108      * {@inheritDoc}
1109      */
1110     @Override
1111     public String getTextIndent() {
1112         return defaultIfEmpty(super.getTextIndent(), "0px", null);
1113     }
1114 
1115     /**
1116      * {@inheritDoc}
1117      */
1118     @Override
1119     public String getTop() {
1120         if (NONE.equals(getDisplay())) {
1121             return AUTO;
1122         }
1123 
1124         final DomElement elem = getDomElement();
1125         if (!elem.isAttachedToPage()) {
1126             return "";
1127         }
1128 
1129         final String superTop = super.getTop();
1130         if (!superTop.endsWith("%")) {
1131             return defaultIfEmpty(superTop, Definition.TOP);
1132         }
1133 
1134         return CssPixelValueConverter.pixelString(elem,
1135                 style -> {
1136                     if (style.getDomElement() == elem) {
1137                         return style.getStyleAttribute(Definition.TOP, true);
1138                     }
1139                     return style.getStyleAttribute(Definition.HEIGHT, true);
1140                 },
1141                 () -> 0,
1142                 () -> 0);
1143     }
1144 
1145     /**
1146      * Returns the computed top (Y coordinate), relative to the node's parent's top edge.
1147      * @param includeMargin whether or not to take the margin into account in the calculation
1148      * @param includeBorder whether or not to take the border into account in the calculation
1149      * @param includePadding whether or not to take the padding into account in the calculation
1150      * @return the computed top (Y coordinate), relative to the node's parent's top edge
1151      */
1152     public int getTop(final boolean includeMargin, final boolean includeBorder, final boolean includePadding) {
1153         final Integer cachedTop = getCachedTop();
1154 
1155         int top = 0;
1156         if (cachedTop == Integer.MIN_VALUE) {
1157             final String position = getPositionWithInheritance();
1158             if (ABSOLUTE.equals(position) || FIXED.equals(position)) {
1159                 top = getTopForAbsolutePositionWithInheritance();
1160             }
1161             else if (getDomElement() instanceof HtmlTableCell) {
1162                 top = 0;
1163             }
1164             else {
1165                 // Calculate the vertical displacement caused by *previous* siblings.
1166                 DomNode prev = getDomElement().getPreviousSibling();
1167                 boolean prevHadComputedTop = false;
1168                 while (prev != null && !prevHadComputedTop) {
1169                     if (prev instanceof HtmlElement) {
1170                         final ComputedCssStyleDeclaration style =
1171                                 prev.getPage().getEnclosingWindow().getComputedStyle((DomElement) prev, null);
1172 
1173                         // only previous block elements are counting
1174                         final String display = style.getDisplay();
1175                         if (isBlock(display)) {
1176                             int prevTop = 0;
1177                             final Integer eCachedTop = style.getCachedTop();
1178                             if (eCachedTop == Integer.MIN_VALUE) {
1179                                 final String prevPosition = style.getPositionWithInheritance();
1180                                 if (ABSOLUTE.equals(prevPosition) || FIXED.equals(prevPosition)) {
1181                                     prevTop += style.getTopForAbsolutePositionWithInheritance();
1182                                 }
1183                                 else {
1184                                     if (RELATIVE.equals(prevPosition)) {
1185                                         final String t = style.getTopWithInheritance();
1186                                         prevTop += CssPixelValueConverter.pixelValue(t);
1187                                     }
1188                                 }
1189                             }
1190                             else {
1191                                 prevHadComputedTop = true;
1192                                 prevTop += eCachedTop.intValue();
1193                             }
1194                             prevTop += style.getCalculatedHeight(true, true);
1195                             final int margin = CssPixelValueConverter.pixelValue(style.getMarginTop());
1196                             prevTop += margin;
1197                             top += prevTop;
1198                         }
1199                     }
1200                     prev = prev.getPreviousSibling();
1201                 }
1202                 // If the position is relative, we also need to add the specified "top" displacement.
1203                 if (RELATIVE.equals(position)) {
1204                     final String t = getTopWithInheritance();
1205                     top += CssPixelValueConverter.pixelValue(t);
1206                 }
1207             }
1208             setCachedTop(top);
1209         }
1210         else {
1211             top = cachedTop;
1212         }
1213 
1214         if (includeMargin) {
1215             final int margin = CssPixelValueConverter.pixelValue(getMarginTop());
1216             top += margin;
1217         }
1218 
1219         if (includeBorder) {
1220             final int border = CssPixelValueConverter.pixelValue(getBorderTopWidth());
1221             top += border;
1222         }
1223 
1224         if (includePadding) {
1225             final int padding = getPaddingTopValue();
1226             top += padding;
1227         }
1228 
1229         return top;
1230     }
1231 
1232     private static boolean isBlock(final String display) {
1233         return display != null
1234                 && !INLINE.equals(display)
1235                 && !NONE.equals(display);
1236     }
1237 
1238     /**
1239      * Returns the CSS {@code top} attribute, replacing inherited values with the actual parent values.
1240      * @return the CSS {@code top} attribute, replacing inherited values with the actual parent values
1241      */
1242     public String getTopWithInheritance() {
1243         String top = getTop();
1244         if (INHERIT.equals(top)) {
1245             final HtmlElement parent = (HtmlElement) getDomElement().getParentNode();
1246             if (parent == null) {
1247                 top = AUTO;
1248             }
1249             else {
1250                 final ComputedCssStyleDeclaration style =
1251                         parent.getPage().getEnclosingWindow().getComputedStyle(parent, null);
1252                 top = style.getTopWithInheritance();
1253             }
1254         }
1255         return top;
1256     }
1257 
1258     /**
1259      * Returns the CSS {@code bottom} attribute, replacing inherited values with the actual parent values.
1260      * @return the CSS {@code bottom} attribute, replacing inherited values with the actual parent values
1261      */
1262     public String getBottomWithInheritance() {
1263         String bottom = getBottom();
1264         if (INHERIT.equals(bottom)) {
1265             final DomNode parent = getDomElement().getParentNode();
1266             if (parent == null) {
1267                 bottom = AUTO;
1268             }
1269             else {
1270                 final ComputedCssStyleDeclaration style =
1271                         parent.getPage().getEnclosingWindow().getComputedStyle((DomElement) parent, null);
1272                 bottom = style.getBottomWithInheritance();
1273             }
1274         }
1275         return bottom;
1276     }
1277 
1278     /**
1279      * {@inheritDoc}
1280      */
1281     @Override
1282     public String getVerticalAlign() {
1283         return defaultIfEmpty(super.getVerticalAlign(), "baseline", null);
1284     }
1285 
1286     /**
1287      * {@inheritDoc}
1288      */
1289     @Override
1290     public String getWidows() {
1291         return defaultIfEmpty(super.getWidows(), Definition.WIDOWS);
1292     }
1293 
1294     /**
1295      * {@inheritDoc}
1296      */
1297     @Override
1298     public String getWordSpacing() {
1299         return defaultIfEmpty(super.getWordSpacing(), Definition.WORD_SPACING);
1300     }
1301 
1302     /**
1303      * {@inheritDoc}
1304      */
1305     @Override
1306     public String getZIndex() {
1307         if (!getDomElement().isAttachedToPage()) {
1308             return EMPTY_FINAL;
1309         }
1310 
1311         final String response = super.getZIndex();
1312         if (response.isEmpty()) {
1313             return AUTO;
1314         }
1315         return response;
1316     }
1317 
1318     /**
1319      * Gets the left margin of the element.
1320      * @return the value in pixels
1321      */
1322     public int getMarginLeftValue() {
1323         return CssPixelValueConverter.pixelValue(getMarginLeft());
1324     }
1325 
1326     /**
1327      * Gets the right margin of the element.
1328      * @return the value in pixels
1329      */
1330     public int getMarginRightValue() {
1331         return CssPixelValueConverter.pixelValue(getMarginRight());
1332     }
1333 
1334     /**
1335      * Gets the top margin of the element.
1336      * @return the value in pixels
1337      */
1338     public int getMarginTopValue() {
1339         return CssPixelValueConverter.pixelValue(getMarginTop());
1340     }
1341 
1342     /**
1343      * Gets the bottom margin of the element.
1344      * @return the value in pixels
1345      */
1346     public int getMarginBottomValue() {
1347         return CssPixelValueConverter.pixelValue(getMarginBottom());
1348     }
1349 
1350     /**
1351      * Returns the computed left (X coordinate), relative to the node's parent's left edge.
1352      * @param includeMargin whether or not to take the margin into account in the calculation
1353      * @param includeBorder whether or not to take the border into account in the calculation
1354      * @param includePadding whether or not to take the padding into account in the calculation
1355      * @return the computed left (X coordinate), relative to the node's parent's left edge
1356      */
1357     public int getLeft(final boolean includeMargin, final boolean includeBorder, final boolean includePadding) {
1358         final String p = getPositionWithInheritance();
1359         final String l = getLeftWithInheritance();
1360         final String r = getRightWithInheritance();
1361 
1362         int left;
1363         if ((ABSOLUTE.equals(p) || FIXED.equals(p)) && !AUTO.equals(l)) {
1364             // No need to calculate displacement caused by sibling nodes.
1365             left = CssPixelValueConverter.pixelValue(l);
1366         }
1367         else if ((ABSOLUTE.equals(p) || FIXED.equals(p)) && !AUTO.equals(r)) {
1368             // Need to calculate the horizontal displacement caused by *all* siblings.
1369             final DomNode parent = getDomElement().getParentNode();
1370             final int parentWidth;
1371             if (parent == null) {
1372                 parentWidth = getDomElement().getPage().getEnclosingWindow().getInnerWidth();
1373             }
1374             else if (parent instanceof Page page) {
1375                 parentWidth = page.getEnclosingWindow().getInnerWidth();
1376             }
1377             else {
1378                 final ComputedCssStyleDeclaration parentStyle =
1379                         parent.getPage().getEnclosingWindow().getComputedStyle((DomElement) parent, null);
1380                 parentWidth = parentStyle.getCalculatedWidth(false, false);
1381             }
1382             left = parentWidth - CssPixelValueConverter.pixelValue(r);
1383         }
1384         else if (FIXED.equals(p) && !AUTO.equals(r)) {
1385             final DomElement e = getDomElement();
1386             final WebWindow win = e.getPage().getEnclosingWindow();
1387             final ComputedCssStyleDeclaration style = win.getComputedStyle(e, null);
1388 
1389             final DomNode parent = e.getParentNode();
1390             final int parentWidth;
1391             if (parent == null) {
1392                 parentWidth = win.getInnerWidth();
1393             }
1394             else {
1395                 final ComputedCssStyleDeclaration parentStyle = win.getComputedStyle((DomElement) parent, null);
1396                 parentWidth = CssPixelValueConverter.pixelValue(parentStyle.getWidth())
1397                                 - CssPixelValueConverter.pixelValue(style.getWidth());
1398             }
1399             left = parentWidth - CssPixelValueConverter.pixelValue(r);
1400         }
1401         else if (FIXED.equals(p) && AUTO.equals(l)) {
1402             // Fixed to the location at which the browser puts it via normal element flowing.
1403             final DomNode parent = getDomElement().getParentNode();
1404             if (parent == null || parent instanceof Page) {
1405                 left = 0;
1406             }
1407             else {
1408                 final ComputedCssStyleDeclaration style =
1409                         parent.getPage().getEnclosingWindow().getComputedStyle((DomElement) parent, null);
1410                 left = CssPixelValueConverter.pixelValue(style.getLeftWithInheritance());
1411             }
1412         }
1413         else if (STATIC.equals(p)) {
1414             // We need to calculate the horizontal displacement caused by *previous* siblings.
1415             left = 0;
1416             DomNode prev = getDomElement().getPreviousSibling();
1417             while (prev != null) {
1418                 if (prev instanceof HtmlElement) {
1419                     final ComputedCssStyleDeclaration style =
1420                             prev.getPage().getEnclosingWindow().getComputedStyle((DomElement) prev, null);
1421                     final String d = style.getDisplay();
1422                     if (isBlock(d)) {
1423                         break;
1424                     }
1425                     else if (!NONE.equals(d)) {
1426                         left += style.getCalculatedWidth(true, true);
1427                     }
1428                 }
1429                 else if (prev instanceof DomText) {
1430                     final String content = getLayoutText(prev);
1431                     if (content != null) {
1432                         // the text is rendered with the font of the parent
1433                         String fontSize = null;
1434                         if (prev.getParentNode() instanceof DomElement parent) {
1435                             fontSize = parent.getPage().getEnclosingWindow().getComputedStyle(parent, null)
1436                                     .getStyleAttribute(Definition.FONT_SIZE, true);
1437                         }
1438                         left += (int) Math.round(getDomElement().getPage().getWebClient().getBrowserVersion()
1439                                 .getTextWidth(content.trim(), fontSize));
1440                     }
1441                 }
1442                 prev = prev.getPreviousSibling();
1443             }
1444         }
1445         else {
1446             // Just use the CSS specified value.
1447             left = CssPixelValueConverter.pixelValue(l);
1448         }
1449 
1450         if (includeMargin) {
1451             final int margin = getMarginLeftValue();
1452             left += margin;
1453         }
1454 
1455         if (includeBorder) {
1456             final int border = CssPixelValueConverter.pixelValue(getBorderLeftWidth());
1457             left += border;
1458         }
1459 
1460         if (includePadding) {
1461             final int padding = getPaddingLeftValue();
1462             left += padding;
1463         }
1464 
1465         return left;
1466     }
1467 
1468     /**
1469      * {@inheritDoc}
1470      */
1471     @Override
1472     public String getPosition() {
1473         return defaultIfEmpty(super.getPosition(), Definition.POSITION);
1474     }
1475 
1476     /**
1477      * Returns the CSS {@code position} attribute, replacing inherited values with the actual parent values.
1478      * @return the CSS {@code position} attribute, replacing inherited values with the actual parent values
1479      */
1480     public String getPositionWithInheritance() {
1481         String p = getStyleAttribute(Definition.POSITION, true);
1482         if (INHERIT.equals(p)) {
1483             final DomNode parent = getDomElement().getParentNode();
1484             if (parent == null) {
1485                 p = STATIC;
1486             }
1487             else {
1488                 final ComputedCssStyleDeclaration style =
1489                         parent.getPage().getEnclosingWindow().getComputedStyle((DomElement) parent, null);
1490                 p = style.getPositionWithInheritance();
1491             }
1492         }
1493         return p;
1494     }
1495 
1496     /**
1497      * Returns the CSS {@code left} attribute, replacing inherited values with the actual parent values.
1498      * @return the CSS {@code left} attribute, replacing inherited values with the actual parent values
1499      */
1500     public String getLeftWithInheritance() {
1501         String left = getLeft();
1502         if (INHERIT.equals(left)) {
1503             final DomNode parent = getDomElement().getParentNode();
1504             if (parent == null) {
1505                 left = AUTO;
1506             }
1507             else {
1508                 final ComputedCssStyleDeclaration style =
1509                         parent.getPage().getEnclosingWindow().getComputedStyle((DomElement) parent, null);
1510                 left = style.getLeftWithInheritance();
1511             }
1512         }
1513         return left;
1514     }
1515 
1516     /**
1517      * Returns the CSS {@code right} attribute, replacing inherited values with the actual parent values.
1518      * @return the CSS {@code right} attribute, replacing inherited values with the actual parent values
1519      */
1520     public String getRightWithInheritance() {
1521         String right = getRight();
1522         if (INHERIT.equals(right)) {
1523             final DomNode parent = getDomElement().getParentNode();
1524             if (parent == null) {
1525                 right = AUTO;
1526             }
1527             else {
1528                 final ComputedCssStyleDeclaration style =
1529                         parent.getPage().getEnclosingWindow().getComputedStyle((DomElement) parent, null);
1530                 right = style.getRightWithInheritance();
1531             }
1532         }
1533         return right;
1534     }
1535 
1536     private int getTopForAbsolutePositionWithInheritance() {
1537         final String t = getTopWithInheritance();
1538 
1539         if (!AUTO.equals(t)) {
1540             // No need to calculate displacement caused by sibling nodes.
1541             return CssPixelValueConverter.pixelValue(t);
1542         }
1543 
1544         final String b = getBottomWithInheritance();
1545         if (!AUTO.equals(b)) {
1546             // Estimate the vertical displacement caused by *all* siblings.
1547             // This is very rough, and doesn't even take position or display types into account.
1548             // It also doesn't take into account the fact that the parent's height may be hardcoded in CSS.
1549             int top = 0;
1550             DomNode child = getDomElement().getParentNode().getFirstChild();
1551             while (child != null) {
1552                 if (child instanceof HtmlElement && child.mayBeDisplayed()) {
1553                     top += 20;
1554                 }
1555                 child = child.getNextSibling();
1556             }
1557             top -= CssPixelValueConverter.pixelValue(b);
1558             return top;
1559         }
1560 
1561         return 0;
1562     }
1563 
1564     /**
1565      * Returns the text of the given node used for the layout (size estimations).
1566      * <p>This is the visible text without the WebDriver specific visibility checks
1567      * (opacity, content-visibility, offscreen); the browsers do the layout also for
1568      * elements that are transparent or positioned outside of the page
1569      * (e.g. the qunit-fixture used by many test suites is positioned offscreen).</p>
1570      *
1571      * @param node the node
1572      * @return the text used for the layout
1573      */
1574     private static String getLayoutText(final DomNode node) {
1575         return new HtmlSerializerVisibleText(false).asText(node);
1576     }
1577 
1578     /**
1579      * Returns the element's height, possibly including its padding and border.
1580      * @param includeBorder whether or not to include the border height in the returned value
1581      * @param includePadding whether or not to include the padding height in the returned value
1582      * @return the element's height, possibly including its padding and border
1583      */
1584     public int getCalculatedHeight(final boolean includeBorder, final boolean includePadding) {
1585         final DomElement element = getDomElement();
1586 
1587         if (!element.isAttachedToPage()) {
1588             return 0;
1589         }
1590         int height = getCalculatedHeight(element);
1591         if (!"border-box".equals(getStyleAttribute(Definition.BOX_SIZING, true))) {
1592             if (includeBorder) {
1593                 height += getBorderVertical();
1594             }
1595             else if (isScrollable(element, true, true) && !(element instanceof HtmlBody)) {
1596                 height -= 17;
1597             }
1598 
1599             if (includePadding) {
1600                 height += getPaddingVertical();
1601             }
1602         }
1603         return height;
1604     }
1605 
1606     /**
1607      * Returns the element's calculated height, taking both relevant CSS and the element's children into account.
1608      * @return the element's calculated height, taking both relevant CSS and the element's children into account
1609      */
1610     private int getCalculatedHeight(final DomElement element) {
1611         final int cachedHeight = getCachedHeight();
1612         if (cachedHeight != Integer.MIN_VALUE) {
1613             return cachedHeight;
1614         }
1615 
1616         if (element instanceof HtmlImage image) {
1617             return updateCachedHeight(image.getHeightOrDefault());
1618         }
1619 
1620         final boolean isInline = INLINE.equals(getDisplay()) && !(element instanceof HtmlInlineFrame);
1621         final String styleHeight = super.getHeight();
1622 
1623         // an EXPLICIT, non-auto height wins outright -- mirrors what
1624         // getBlockSize() already does for the same underlying style value,
1625         // and what getCalculatedWidth() does for an explicit width
1626         if (!isInline
1627                 && !StringUtils.isEmptyOrNull(styleHeight)
1628                 && !AUTO.equals(styleHeight)) {
1629             // e.g. calc() may result in a negative value; the height is never negative
1630             return updateCachedHeight(Math.max(0,
1631                     CssPixelValueConverter.pixelValue(element,
1632                             style -> style.getStyleAttribute(Definition.HEIGHT, true),
1633                             () -> 0,
1634                             () -> element.getPage().getEnclosingWindow().getInnerHeight())));
1635         }
1636 
1637         // height is ignored for inline elements, and AUTO/unset falls back to
1638         // content-based sizing
1639         if (isInline || StringUtils.isEmptyOrNull(styleHeight) || AUTO.equals(styleHeight)) {
1640             final int contentHeight = getContentHeight();
1641             if (contentHeight > 0) {
1642                 return updateCachedHeight(contentHeight);
1643             }
1644         }
1645 
1646         return updateCachedHeight(calculateIntrinsicHeight(element));
1647     }
1648 
1649     /**
1650      * Returns the element's width in pixels, possibly including its padding and border.
1651      *
1652      * @param includeBorder whether or not to include the border width in the returned value
1653      * @param includePadding whether or not to include the padding width in the returned value
1654      * @return the element's width in pixels, possibly including its padding and border
1655      */
1656     public int getCalculatedWidth(final boolean includeBorder, final boolean includePadding) {
1657         final DomElement element = getDomElement();
1658 
1659         if (!element.isAttachedToPage()) {
1660             return 0;
1661         }
1662 
1663         int width = getCalculatedWidth(element);
1664         if (!"border-box".equals(getStyleAttribute(Definition.BOX_SIZING, true))) {
1665             if (includeBorder) {
1666                 width += getBorderHorizontal();
1667             }
1668             else if (isScrollable(element, false, true) && !(element instanceof HtmlBody)) {
1669                 width -= 17;
1670             }
1671 
1672             if (includePadding) {
1673                 width += getPaddingHorizontal();
1674             }
1675         }
1676         return width;
1677     }
1678 
1679     /**
1680      * Computes and caches the "used" (rendered) width of this element in pixels,
1681      * following (a simplified approximation of) the CSS width-resolution
1682      * algorithm: explicit style widths win outright; otherwise the width falls
1683      * back through several special cases (fixed-size tags, floated/positioned
1684      * elements, block-level fill-parent, form-control defaults) before finally
1685      * shrink-wrapping to content as a last resort.
1686      *
1687      * @param element the element to compute the width for
1688      * @return the calculated width, in pixels
1689      */
1690     private int getCalculatedWidth(final DomElement element) {
1691         final int cached = getCachedWidth();
1692         if (cached != Integer.MIN_VALUE) {
1693             return cached;
1694         }
1695 
1696         // an element that isn't rendered at all has no box, and therefore no width
1697         if (!element.mayBeDisplayed()) {
1698             return updateCachedWidth(0);
1699         }
1700 
1701         final String display = getDisplay();
1702         if (NONE.equals(getDisplay())) {
1703             return updateCachedWidth(0);
1704         }
1705 
1706         final String styleWidth = getStyleAttribute(Definition.WIDTH, true);
1707         final DomNode parent = element.getParentNode();
1708 
1709         // "width" has no effect on inline elements, and the two shrink-to-fit
1710         // keywords are handled as part of the "not explicitly set" path below
1711         // rather than as an explicit pixel width
1712         final boolean widthNotExplicitlySet = INLINE.equals(display)
1713                 || StringUtils.isEmptyOrNull(styleWidth)
1714                 || AUTO.equals(styleWidth)
1715                 || isShrinkToFitKeyword(styleWidth);
1716         if (widthNotExplicitlySet && parent instanceof HtmlElement) {
1717             return updateCachedWidth(computeWidthWhenNotExplicitlySet(element, display, styleWidth, parent));
1718         }
1719 
1720         if (AUTO.equals(styleWidth)) {
1721             // no parent to size against (or width wasn't handled above) --
1722             // fall back to the window's own width
1723             return updateCachedWidth(element.getPage().getEnclosingWindow().getInnerWidth());
1724         }
1725 
1726         // width was explicitly set in the style attribute to a real value (e.g.
1727         // "200px", "50%") -- resolve it via the normal CSS pixel-value converter,
1728         // which knows how to handle relative units against the window as a
1729         // percentage base
1730         // e.g. calc() may result in a negative value; the width is never negative
1731         return updateCachedWidth(Math.max(0, CssPixelValueConverter.pixelValue(element,
1732                 style -> style.getStyleAttribute(Definition.WIDTH, true),
1733                 () -> 0,
1734                 () -> element.getPage().getEnclosingWindow().getInnerWidth())));
1735     }
1736 
1737     /**
1738      * Returns whether {@code styleWidth} is one of the CSS sizing keywords that
1739      * mean "shrink-wrap to content" rather than a concrete length -- these are
1740      * treated the same as "no explicit width" for the purposes of this class'
1741      * (simplified) width algorithm.
1742      *
1743      * @param styleWidth the raw {@code width} style value to check
1744      * @return {@code true} if {@code styleWidth} is {@code max-content} or
1745      *     {@code min-content}
1746      */
1747     private static boolean isShrinkToFitKeyword(final String styleWidth) {
1748         return "max-content".equals(styleWidth) || "min-content".equals(styleWidth);
1749     }
1750 
1751     /**
1752      * Computes the width for an element whose style doesn't pin down an explicit
1753      * pixel width -- either nothing was specified, the element is inline (where
1754      * width is ignored), or a shrink-to-fit keyword was used. Tries, in order:
1755      * a fixed default for certain special tags (canvas, iframe, frame); shrink-
1756      * wrapping for floated/absolutely-or-fixed-positioned elements; filling the
1757      * containing block for an ordinary block element; a hardcoded default for
1758      * specific form-control tags; and finally shrink-wrapping to content as the
1759      * general fallback.
1760      *
1761      * @param element the element being sized
1762      * @param display the element's resolved {@code display} value
1763      * @param styleWidth the element's raw {@code width} style value
1764      * @param parent the element's parent node (known to be an {@link HtmlElement}
1765      *     by the caller)
1766      * @return the computed width, in pixels
1767      */
1768     private int computeWidthWhenNotExplicitlySet(final DomElement element, final String display,
1769             final String styleWidth, final DomNode parent) {
1770 
1771         // hack: TODO find a way to specify default values for different tags
1772         final Integer fixedDefault = getFixedDefaultWidth(element);
1773         if (fixedDefault != null) {
1774             return fixedDefault;
1775         }
1776 
1777         // an absolutely/fixed-positioned or floated element shrink-wraps to its
1778         // children regardless of display type (block, inline, etc.) -- it's
1779         // taken out of normal flow, so it never "fills" a containing block
1780         if (isFloatedOrOutOfNormalFlow()) {
1781             return shrinkToFitWidth(element);
1782         }
1783 
1784         // an ordinary block-level element (not using a shrink-to-fit keyword)
1785         // fills the full width of its containing block, per normal CSS flow
1786         if (BLOCK.equals(display) && !isShrinkToFitKeyword(styleWidth)) {
1787             return fillsParentWidth(element, parent);
1788         }
1789 
1790         final Integer formControlDefault = getDefaultWidthForFormControl(element);
1791         if (formControlDefault != null) {
1792             return formControlDefault;
1793         }
1794 
1795         // last resort: inline elements, and block elements using a shrink-to-fit
1796         // width keyword, take up however much space is required by their content
1797         return shrinkToFitWidth(element);
1798     }
1799 
1800     /**
1801      * Returns whether this element is floated or taken out of normal document
1802      * flow (absolute/fixed positioning) -- such elements always shrink-wrap to
1803      * their content, never fill their containing block, regardless of their
1804      * {@code display} value.
1805      *
1806      * @return {@code true} if this element is floated left/right, or absolutely
1807      *     or fixed positioned
1808      */
1809     private boolean isFloatedOrOutOfNormalFlow() {
1810         final String position = getStyleAttribute(Definition.POSITION, true);
1811         if (ABSOLUTE.equals(position) || FIXED.equals(position)) {
1812             return true;
1813         }
1814         final String cssFloat = getCssFloat();
1815         return "right".equals(cssFloat) || "left".equals(cssFloat);
1816     }
1817 
1818     /**
1819      * Shrink-wraps to the rendered width of the element's children, falling back
1820      * to a text-length approximation when there is no rendered child content --
1821      * for example, an element containing only a text node, which contributes no
1822      * child element box for {@link #getContentWidth()} to measure.
1823      * <p>
1824      * This fallback previously existed only in the floated/out-of-flow code
1825      * path; a block element sized via a shrink-to-fit width keyword (e.g.
1826      * {@code max-content}) reached an equivalent "shrink to content"
1827      * computation through a separate call site that lacked the fallback,
1828      * incorrectly resolving to {@code 0} for text-only content. Both call sites
1829      * now share this one implementation.
1830      * </p>
1831      *
1832      * @param element the element to shrink-wrap
1833      * @return the shrink-to-fit width, in pixels
1834      */
1835     private int shrinkToFitWidth(final DomElement element) {
1836         final int contentWidth = getContentWidth();
1837         if (contentWidth > 0) {
1838             return contentWidth;
1839         }
1840 
1841         // no rendered child content -- approximate from the element's own
1842         // visible text instead
1843         final BrowserVersion browserVersion = getDomElement().getPage().getWebClient().getBrowserVersion();
1844         return getLayoutText(element).length() * browserVersion.getPixelsPerChar();
1845     }
1846 
1847     /**
1848      * Computes the width of an ordinary block-level element that fills its
1849      * containing block: the window's inner width minus a fixed margin allowance
1850      * for {@code <body>}, or the parent's own calculated width (minus this
1851      * element's own border/padding) for anything else.
1852      *
1853      * @param element the block-level element being sized
1854      * @param parent the element's parent node
1855      * @return the fill-parent width, in pixels
1856      */
1857     private int fillsParentWidth(final DomElement element, final DomNode parent) {
1858         final int windowWidth = element.getPage().getEnclosingWindow().getInnerWidth();
1859         if (element instanceof HtmlBody) {
1860             // approximate default body margin
1861             return windowWidth - 16;
1862         }
1863 
1864         final ComputedCssStyleDeclaration parentStyle =
1865                 parent.getPage().getEnclosingWindow().getComputedStyle((DomElement) parent, null);
1866         return parentStyle.getCalculatedWidth(false, false) - (getBorderHorizontal() + getPaddingHorizontal());
1867     }
1868 
1869     /**
1870      * Returns a fixed, hardcoded default width for element types that real
1871      * browsers give an intrinsic size to regardless of content -- currently
1872      * {@code <canvas>}, {@code <iframe>} and {@code <frame>}.
1873      *
1874      * @param element the element to check
1875      * @return the fixed default width in pixels, or {@code null} if
1876      *     {@code element} isn't one of the special-cased tag types
1877      */
1878     private static Integer getFixedDefaultWidth(final DomElement element) {
1879         if (element instanceof HtmlCanvas) {
1880             return 300;
1881         }
1882 
1883         // iframes have a default width of 300px, like canvas -- unless an
1884         // explicit 'width' HTML attribute (not CSS style) says otherwise
1885         if (element instanceof HtmlInlineFrame iframe) {
1886             final String widthAttribute = iframe.getAttributeDirect("width");
1887             if (DomElement.ATTRIBUTE_NOT_DEFINED != widthAttribute) {
1888                 return CssPixelValueConverter.pixelValue(widthAttribute);
1889             }
1890             return 300;
1891         }
1892 
1893         if (element instanceof HtmlFrame) {
1894             // a <frame> (inside a <frameset>) takes the full width of its
1895             // enclosing window
1896             return element.getPage().getEnclosingWindow().getInnerWidth();
1897         }
1898 
1899         return null;
1900     }
1901 
1902     /**
1903      * Returns a hardcoded default width for specific form-control tags that
1904      * real browsers size intrinsically based on their native widget rendering
1905      * rather than pure CSS content flow -- buttons (sized from their label
1906      * text), text/password inputs, checkboxes/radio buttons, textareas and
1907      * images.
1908      *
1909      * @param element the element to check
1910      * @return the default width in pixels, or {@code null} if {@code element}
1911      *     isn't one of the special-cased form-control types
1912      */
1913     private Integer getDefaultWidthForFormControl(final DomElement element) {
1914         final BrowserVersion browserVersion = getDomElement().getPage().getWebClient().getBrowserVersion();
1915 
1916         if (element instanceof HtmlSubmitInput
1917                 || element instanceof HtmlResetInput
1918                 || element instanceof HtmlButtonInput
1919                 || element instanceof HtmlButton
1920                 || element instanceof HtmlFileInput) {
1921             // use asNormalizedText() here because getVisibleText() returns an
1922             // empty string for submit and reset buttons; default font for
1923             // buttons is a bit smaller than the body font size, hence the 0.9
1924             // scale factor
1925             final String text = element.asNormalizedText();
1926             return 10 + (int) (text.length() * browserVersion.getPixelsPerChar() * 0.9);
1927         }
1928 
1929         if (element instanceof HtmlTextInput || element instanceof HtmlPasswordInput) {
1930             // native text-input widget width varies by rendering engine/version
1931             if (browserVersion.hasFeature(JS_CLIENTWIDTH_INPUT_TEXT_169)) {
1932                 return 169;
1933             }
1934             return 157; // FF
1935         }
1936 
1937         if (element instanceof HtmlRadioButtonInput || element instanceof HtmlCheckBoxInput) {
1938             return browserVersion.hasFeature(JS_CLIENTWIDTH_RADIO_CHECKBOX_14) ? 14 : 13;
1939         }
1940 
1941         if (element instanceof HtmlTextArea) {
1942             return 100; // wild guess
1943         }
1944 
1945         if (element instanceof HtmlImage image) {
1946             return image.getWidthOrDefault();
1947         }
1948 
1949         return null;
1950     }
1951 
1952     /**
1953      * Returns the total width of the element's children.
1954      * @return the total width of the element's children
1955      */
1956     public int getContentWidth() {
1957         final int cachedContentWidth = getCachedContentWidth();
1958         if (cachedContentWidth != Integer.MIN_VALUE) {
1959             return cachedContentWidth;
1960         }
1961 
1962         int inlineWidth = 0;
1963         int maxBlockWidth = 0;
1964         final DomElement element = getDomElement();
1965         Iterable<DomNode> children = element.getChildren();
1966         if (element instanceof BaseFrameElement frameElement) {
1967             final Page enclosedPage = frameElement.getEnclosedPage();
1968             if (enclosedPage != null && enclosedPage.isHtmlPage()) {
1969                 children = ((DomNode) enclosedPage).getChildren();
1970             }
1971         }
1972         final WebWindow webWindow = element.getPage().getEnclosingWindow();
1973         for (final DomNode child : children) {
1974             if (child instanceof HtmlElement e) {
1975                 final ComputedCssStyleDeclaration style = webWindow.getComputedStyle(e, null);
1976                 final String childDisplay = style.getDisplay();
1977                 final int w;
1978                 if (BLOCK.equals(childDisplay)) {
1979                     // For block children, only use their full calculated width if they have
1980                     // an explicit width set. Otherwise recurse into their own content width
1981                     // so that shrink-wrap containers propagate the leaf width all the way up.
1982                     final String childStyleWidth = style.getStyleAttribute(Definition.WIDTH, true);
1983                     if (StringUtils.isEmptyOrNull(childStyleWidth) || AUTO.equals(childStyleWidth)) {
1984                         // No explicit width: the child's contribution is whatever its own
1985                         // content needs (recurse), plus its own border/padding.
1986                         w = style.getContentWidth()
1987                                 + style.getBorderHorizontal()
1988                                 + style.getPaddingHorizontal();
1989                     }
1990                     else {
1991                         w = style.getCalculatedWidth(true, true);
1992                     }
1993                     if (w > maxBlockWidth) {
1994                         maxBlockWidth = w;
1995                     }
1996                 }
1997                 else {
1998                     // Inline / inline-block children sit side-by-side; sum their widths.
1999                     w = style.getCalculatedWidth(true, true);
2000                     inlineWidth += w;
2001                 }
2002             }
2003             else if (child instanceof DomText) {
2004                 final BrowserVersion browserVersion = getDomElement().getPage().getWebClient().getBrowserVersion();
2005                 final DomNode parent = child.getParentNode();
2006                 if (parent instanceof HtmlElement) {
2007                     final ComputedCssStyleDeclaration style = webWindow.getComputedStyle((DomElement) parent, null);
2008                     inlineWidth += (int) Math.round(browserVersion.getTextWidth(getLayoutText(child),
2009                                         style.getStyleAttribute(Definition.FONT_SIZE, true)));
2010                 }
2011                 else {
2012                     inlineWidth += getLayoutText(child).length() * browserVersion.getPixelsPerChar();
2013                 }
2014             }
2015         }
2016 
2017         return updateCachedContentWidth(Math.max(maxBlockWidth, inlineWidth));
2018     }
2019 
2020     /**
2021      * Calculates the intrinsic or base text-line height of an element
2022      * without performing full child-element flow layout.
2023      *
2024      * @return the element's calculated height
2025      */
2026     private int calculateIntrinsicHeight(final DomElement element) {
2027         final int cachedEmptyHeight = getCachedEmptyHeight();
2028         if (cachedEmptyHeight != Integer.MIN_VALUE) {
2029             return cachedEmptyHeight;
2030         }
2031 
2032         if (!element.mayBeDisplayed()) {
2033             return updateCachedEmptyHeight(0);
2034         }
2035 
2036         final String display = getDisplay();
2037         if (NONE.equals(display)) {
2038             return updateCachedEmptyHeight(0);
2039         }
2040 
2041         final SgmlPage page = element.getPage();
2042         final WebWindow webWindow = page.getEnclosingWindow();
2043         final int windowHeight = webWindow.getInnerHeight();
2044 
2045         if (element instanceof HtmlBody) {
2046             if (page instanceof HtmlPage htmlPage && htmlPage.isQuirksMode()) {
2047                 return updateCachedEmptyHeight(windowHeight);
2048             }
2049 
2050             return updateCachedEmptyHeight(0);
2051         }
2052 
2053         int defaultHeight;
2054         if (ZERO_HEIGHT_ELEMENT_CLASSES.contains(element.getClass()) && StringUtils.isBlank(element.getTextContent())) {
2055             defaultHeight = 0;
2056         }
2057         else if (element.getFirstChild() == null) {
2058             if (element instanceof HtmlRadioButtonInput || element instanceof HtmlCheckBoxInput) {
2059                 final BrowserVersion browser = webWindow.getWebClient().getBrowserVersion();
2060                 if (browser.hasFeature(JS_CLIENTHEIGHT_RADIO_CHECKBOX_14)) {
2061                     defaultHeight = 14;
2062                 }
2063                 else {
2064                     defaultHeight = 13;
2065                 }
2066             }
2067             else if (element instanceof HtmlButton) {
2068                 defaultHeight = 20;
2069             }
2070             else if (element instanceof HtmlInput && !(element instanceof HtmlHiddenInput)) {
2071                 final BrowserVersion browser = webWindow.getWebClient().getBrowserVersion();
2072                 if (browser.hasFeature(JS_CLIENTHEIGHT_INPUT_17)) {
2073                     defaultHeight = 17;
2074                 }
2075                 else if (browser.hasFeature(JS_CLIENTHEIGHT_INPUT_18)) {
2076                     defaultHeight = 18;
2077                 }
2078                 else {
2079                     defaultHeight = 20;
2080                 }
2081             }
2082             else if (element instanceof HtmlSelect) {
2083                 defaultHeight = 20;
2084             }
2085             else if (element instanceof HtmlTextArea) {
2086                 defaultHeight = 49;
2087             }
2088             else {
2089                 defaultHeight = 0;
2090             }
2091         }
2092         else if (element instanceof HtmlRb) {
2093             final BrowserVersion browser = webWindow.getWebClient().getBrowserVersion();
2094             if (browser.hasFeature(JS_CLIENTHEIGHT_RB_17)) {
2095                 defaultHeight = 17;
2096             }
2097             else {
2098                 defaultHeight = 0;
2099             }
2100         }
2101         else if (element instanceof HtmlRt) {
2102             final BrowserVersion browser = webWindow.getWebClient().getBrowserVersion();
2103             if (browser.hasFeature(JS_CLIENTHEIGHT_RT_9)) {
2104                 defaultHeight = 9;
2105             }
2106             else {
2107                 defaultHeight = 0;
2108             }
2109         }
2110         else if (element instanceof HtmlRuby) {
2111             final BrowserVersion browser = webWindow.getWebClient().getBrowserVersion();
2112             if (browser.hasFeature(JS_CLIENTHEIGHT_RUBY_17)) {
2113                 defaultHeight = 17;
2114             }
2115             else {
2116                 defaultHeight = 0;
2117             }
2118         }
2119         else {
2120             final String headingDefault = HEADING_DEFAULT_FONT_SIZES.get(element.getClass());
2121             final boolean isHeading = headingDefault != null;
2122 
2123             final String fontSize;
2124             if (isHeading) {
2125                 final String value = getStyleAttribute(Definition.FONT_SIZE, false);
2126                 fontSize = value.isEmpty() ? headingDefault : getStyleAttribute(Definition.FONT_SIZE, true);
2127             }
2128             else {
2129                 fontSize = getStyleAttribute(Definition.FONT_SIZE, true);
2130             }
2131 
2132             defaultHeight = webWindow.getWebClient().getBrowserVersion().getFontHeight(fontSize);
2133 
2134             if (isHeading
2135                     || element instanceof HtmlDivision
2136                     || element instanceof HtmlSpan) {
2137                 String width = getStyleAttribute(Definition.WIDTH, false);
2138 
2139                 // maybe we are enclosed something that forces a width
2140                 DomNode parent = getDomElement().getParentNode();
2141                 final WebWindow win = parent.getPage().getEnclosingWindow();
2142                 while (width.isEmpty() && parent != null) {
2143                     if (parent instanceof DomElement domElement) {
2144                         final ComputedCssStyleDeclaration computedCss = win.getComputedStyle(domElement, null);
2145                         width = computedCss.getStyleAttribute(Definition.WIDTH, false);
2146                     }
2147                     parent = parent.getParentNode();
2148                     if (parent instanceof Page) {
2149                         break;
2150                     }
2151                 }
2152                 final int pixelWidth = CssPixelValueConverter.pixelValue(width);
2153                 final String content = getLayoutText(element);
2154 
2155                 if (pixelWidth > 0
2156                         && !width.isEmpty()
2157                         && StringUtils.isNotBlank(content)) {
2158                     final int fontSizeInt = CssPixelValueConverter.pixelValue(fontSize);
2159                     final int lineCount = Platform.getFontUtil().countLines(content, pixelWidth, fontSizeInt);
2160                     defaultHeight *= lineCount;
2161                 }
2162                 else {
2163                     if (element instanceof HtmlSpan && StringUtils.isEmptyOrNull(content)) {
2164                         defaultHeight = 0;
2165                     }
2166                     else {
2167                         defaultHeight *= org.apache.commons.lang3.StringUtils.countMatches(content, '\n') + 1;
2168                     }
2169                 }
2170 
2171                 final String styleHeight = getStyleAttribute(Definition.HEIGHT, true);
2172                 if (styleHeight.endsWith("%")) {
2173                     if (page instanceof HtmlPage htmlPage && !htmlPage.isQuirksMode()) {
2174                         return updateCachedEmptyHeight(defaultHeight);
2175                     }
2176                 }
2177             }
2178         }
2179 
2180         if (element instanceof HtmlInlineFrame iframe) {
2181             final String heightAttribute = iframe.getAttributeDirect("height");
2182             if (DomElement.ATTRIBUTE_NOT_DEFINED != heightAttribute) {
2183                 final int height = CssPixelValueConverter.pixelValue(heightAttribute);
2184                 return updateCachedEmptyHeight(height);
2185             }
2186 
2187             defaultHeight = 154;
2188         }
2189 
2190         final boolean isInline = INLINE.equals(display) && !(element instanceof HtmlInlineFrame);
2191 
2192         final int defaultHght = defaultHeight;
2193         final int defaultWindowHeight = element instanceof HtmlCanvas ? 150 : windowHeight;
2194 
2195         int height = CssPixelValueConverter.pixelValue(element,
2196                 style -> {
2197                     final DomElement elem = style.getDomElement();
2198                     if (elem instanceof HtmlBody) {
2199                         return String.valueOf(elem.getPage().getEnclosingWindow().getInnerHeight());
2200                     }
2201                     // height is ignored for inline elements
2202                     if (isInline) {
2203                         return "";
2204                     }
2205                     return style.getStyleAttribute(Definition.HEIGHT, true);
2206                 },
2207                 () -> defaultHght,
2208                 () -> defaultWindowHeight);
2209         // e.g. calc() may result in a negative value; the height is never negative
2210         height = Math.max(0, height);
2211 
2212         if (height == 0 && (isInline || super.getHeight().isEmpty())) {
2213             height = defaultHeight;
2214         }
2215 
2216         return updateCachedEmptyHeight(height);
2217     }
2218 
2219     /**
2220      * Returns the total height of the element's children taking positioning into account.
2221      *
2222      * @return the total height of the element's children in pixels
2223      */
2224     public int getContentHeight() {
2225         // There are two different kinds of elements that might determine the content height:
2226         //  - elements with position:static or position:relative (elements that flow and build on each other)
2227         //  - elements with position:absolute (independent elements)
2228 
2229         final DomNode node = getDomElement();
2230         if (!node.mayBeDisplayed()) {
2231             return 0;
2232         }
2233 
2234         // Pre-size set to reduce reallocation overhead during tree scanning
2235         final Set<ComputedCssStyleDeclaration> styles = new HashSet<>(8);
2236 
2237         if (node instanceof HtmlTableRow row) {
2238             for (final HtmlTableCell cell : row.getCellIterator()) {
2239                 if (cell.mayBeDisplayed()) {
2240                     final ComputedCssStyleDeclaration style =
2241                             cell.getPage().getEnclosingWindow().getComputedStyle(cell, null);
2242                     styles.add(style);
2243                 }
2244             }
2245         }
2246         else {
2247             ComputedCssStyleDeclaration lastFlowing = null;
2248             for (final DomNode child : node.getChildren()) {
2249                 if (child.mayBeDisplayed() && child instanceof HtmlElement e) {
2250                     final ComputedCssStyleDeclaration style =
2251                             e.getPage().getEnclosingWindow().getComputedStyle(e, null);
2252                     final String position = style.getPositionWithInheritance();
2253                     if (STATIC.equals(position) || RELATIVE.equals(position)) {
2254                         lastFlowing = style;
2255                     }
2256                     else if (ABSOLUTE.equals(position) || FIXED.equals(position)) {
2257                         styles.add(style);
2258                     }
2259                 }
2260             }
2261 
2262             if (lastFlowing != null) {
2263                 styles.add(lastFlowing);
2264             }
2265         }
2266 
2267         int max = 0;
2268         for (final ComputedCssStyleDeclaration style : styles) {
2269             final int h = style.getTop(true, false, false) + style.getCalculatedHeight(true, true);
2270             if (h > max) {
2271                 max = h;
2272             }
2273         }
2274         return max;
2275     }
2276 
2277     /**
2278      * Returns {@code true} if the element is scrollable along the specified axis.
2279      * @param horizontal if {@code true}, the caller is interested in scrollability along the x-axis;
2280      *        if {@code false}, the caller is interested in scrollability along the y-axis
2281      * @return {@code true} if the element is scrollable along the specified axis
2282      */
2283     public boolean isScrollable(final boolean horizontal) {
2284         return isScrollable(getDomElement(), horizontal, false);
2285     }
2286 
2287     /**
2288      * Returns true if this element shows a scrollbar.
2289      *
2290      * @param ignoreSize whether to consider the content/calculated width/height
2291      * @return true if this element shows a scrollbar
2292      */
2293     private boolean isScrollable(final DomElement element, final boolean horizontal, final boolean ignoreSize) {
2294         final boolean scrollable;
2295 
2296         String overflow;
2297         if (horizontal) {
2298             overflow = getStyleAttribute(Definition.OVERFLOW_X_, false);
2299             if (StringUtils.isEmptyOrNull(overflow)) {
2300                 overflow = getStyleAttribute(Definition.OVERFLOW_X, false);
2301             }
2302             // fall back to default
2303             if (StringUtils.isEmptyOrNull(overflow)) {
2304                 overflow = getStyleAttribute(Definition.OVERFLOW, true);
2305             }
2306             scrollable = (element instanceof HtmlBody || SCROLL.equals(overflow) || AUTO.equals(overflow))
2307                 && (ignoreSize || getContentWidth() > getCalculatedWidth(element));
2308         }
2309         else {
2310             overflow = getStyleAttribute(Definition.OVERFLOW_Y_, false);
2311             if (StringUtils.isEmptyOrNull(overflow)) {
2312                 overflow = getStyleAttribute(Definition.OVERFLOW_Y, false);
2313             }
2314             // fall back to default
2315             if (StringUtils.isEmptyOrNull(overflow)) {
2316                 overflow = getStyleAttribute(Definition.OVERFLOW, true);
2317             }
2318 
2319             scrollable = (element instanceof HtmlBody || SCROLL.equals(overflow) || AUTO.equals(overflow))
2320                 && (ignoreSize || getContentHeight() > calculateIntrinsicHeight(element));
2321         }
2322         return scrollable;
2323     }
2324 
2325     private int getBorderHorizontal() {
2326         final int borderHorizontal = getCachedBorderHorizontal();
2327         if (borderHorizontal != Integer.MIN_VALUE) {
2328             return borderHorizontal;
2329         }
2330 
2331         final int border = NONE.equals(getDisplay()) ? 0 : getBorderLeftValue() + getBorderRightValue();
2332         return updateCachedBorderHorizontal(border);
2333     }
2334 
2335     private int getBorderVertical() {
2336         final int borderVertical = getCachedBorderVertical();
2337         if (borderVertical != Integer.MIN_VALUE) {
2338             return borderVertical;
2339         }
2340 
2341         final int border = NONE.equals(getDisplay()) ? 0 : getBorderTopValue() + getBorderBottomValue();
2342         return updateCachedBorderVertical(border);
2343     }
2344 
2345     /**
2346      * Gets the size of the left border of the element.
2347      * @return the value in pixels
2348      */
2349     public int getBorderLeftValue() {
2350         return CssPixelValueConverter.pixelValue(getBorderLeftWidth());
2351     }
2352 
2353     /**
2354      * Gets the size of the right border of the element.
2355      * @return the value in pixels
2356      */
2357     public int getBorderRightValue() {
2358         return CssPixelValueConverter.pixelValue(getBorderRightWidth());
2359     }
2360 
2361     /**
2362      * Gets the size of the top border of the element.
2363      * @return the value in pixels
2364      */
2365     public int getBorderTopValue() {
2366         return CssPixelValueConverter.pixelValue(getBorderTopWidth());
2367     }
2368 
2369     /**
2370      * Gets the size of the bottom border of the element.
2371      * @return the value in pixels
2372      */
2373     public int getBorderBottomValue() {
2374         return CssPixelValueConverter.pixelValue(getBorderBottomWidth());
2375     }
2376 
2377     private int getPaddingHorizontal() {
2378         final int paddingHorizontal = getCachedPaddingHorizontal();
2379         if (paddingHorizontal != Integer.MIN_VALUE) {
2380             return paddingHorizontal;
2381         }
2382 
2383         final int padding = NONE.equals(getDisplay()) ? 0 : getPaddingLeftValue() + getPaddingRightValue();
2384         return updateCachedPaddingHorizontal(padding);
2385     }
2386 
2387     private int getPaddingVertical() {
2388         final int paddingVertical = getCachedPaddingVertical();
2389         if (paddingVertical != Integer.MIN_VALUE) {
2390             return paddingVertical;
2391         }
2392 
2393         final int padding = NONE.equals(getDisplay()) ? 0 : getPaddingTopValue() + getPaddingBottomValue();
2394         return updateCachedPaddingVertical(padding);
2395     }
2396 
2397     /**
2398      * Gets the left padding of the element.
2399      * @return the value in pixels
2400      */
2401     public int getPaddingLeftValue() {
2402         return CssPixelValueConverter.pixelValue(getPaddingLeft());
2403     }
2404 
2405     /**
2406      * Gets the right padding of the element.
2407      * @return the value in pixels
2408      */
2409     public int getPaddingRightValue() {
2410         return CssPixelValueConverter.pixelValue(getPaddingRight());
2411     }
2412 
2413     /**
2414      * Gets the top padding of the element.
2415      * @return the value in pixels
2416      */
2417     public int getPaddingTopValue() {
2418         return CssPixelValueConverter.pixelValue(getPaddingTop());
2419     }
2420 
2421     /**
2422      * Gets the bottom padding of the element.
2423      * @return the value in pixels
2424      */
2425     public int getPaddingBottomValue() {
2426         return CssPixelValueConverter.pixelValue(getPaddingBottom());
2427     }
2428 
2429     /**
2430      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span>
2431      * @return the cached width
2432      */
2433     public int getCachedWidth() {
2434         return cachedWidth_;
2435     }
2436 
2437     /**
2438      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span>
2439      * @param width the new value
2440      * @return the param width
2441      */
2442     public int updateCachedWidth(final int width) {
2443         cachedWidth_ = width;
2444         return cachedWidth_;
2445     }
2446 
2447     /**
2448      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span>
2449      * @return the cached content width
2450      */
2451     public int getCachedContentWidth() {
2452         return cachedContentWidth_;
2453     }
2454 
2455     /**
2456      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span>
2457      * @param contentWidth the new value
2458      * @return the contentWidth
2459      */
2460     public int updateCachedContentWidth(final int contentWidth) {
2461         cachedContentWidth_ = contentWidth;
2462         return cachedContentWidth_;
2463     }
2464 
2465     /**
2466      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span>
2467      * @return the cached height
2468      */
2469     public int getCachedHeight() {
2470         return cachedHeight_;
2471     }
2472 
2473     /**
2474      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span>
2475      * @param height the new value
2476      * @return the param height
2477      */
2478     public int updateCachedHeight(final int height) {
2479         cachedHeight_ = height;
2480         return cachedHeight_;
2481     }
2482 
2483     /**
2484      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span>
2485      * @return the cached emptyHeight
2486      */
2487     public int getCachedEmptyHeight() {
2488         return cachedEmptyHeight_;
2489     }
2490 
2491     /**
2492      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span>
2493      * @param emptyHeight the new value
2494      * @return the param emptyHeight
2495      */
2496     public int updateCachedEmptyHeight(final int emptyHeight) {
2497         cachedEmptyHeight_ = emptyHeight;
2498         return cachedEmptyHeight_;
2499     }
2500 
2501     /**
2502      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span>
2503      * @return the cached top
2504      */
2505     public int getCachedTop() {
2506         return cachedTop_;
2507     }
2508 
2509     /**
2510      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span>
2511      * @param top the new value
2512      */
2513     public void setCachedTop(final int top) {
2514         cachedTop_ = top;
2515     }
2516 
2517     /**
2518      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span>
2519      * @return the cached padding horizontal
2520      */
2521     public int getCachedPaddingHorizontal() {
2522         return cachedPaddingHorizontal_;
2523     }
2524 
2525     /**
2526      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span>
2527      * @param paddingHorizontal the new value
2528      * @return the param paddingHorizontal
2529      */
2530     public int updateCachedPaddingHorizontal(final int paddingHorizontal) {
2531         cachedPaddingHorizontal_ = paddingHorizontal;
2532         return cachedPaddingHorizontal_;
2533     }
2534 
2535     /**
2536      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span>
2537      * @return the cached padding vertical
2538      */
2539     public int getCachedPaddingVertical() {
2540         return cachedPaddingVertical_;
2541     }
2542 
2543     /**
2544      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span>
2545      * @param paddingVertical the new value
2546      * @return the param paddingVertical
2547      */
2548     public int updateCachedPaddingVertical(final int paddingVertical) {
2549         cachedPaddingVertical_ = paddingVertical;
2550         return cachedPaddingVertical_;
2551     }
2552 
2553     /**
2554      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span>
2555      * @return the cached border horizontal
2556      */
2557     public int getCachedBorderHorizontal() {
2558         return cachedBorderHorizontal_;
2559     }
2560 
2561     /**
2562      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span>
2563      * @param borderHorizontal the new value
2564      * @return the borderHorizontal
2565      */
2566     public int updateCachedBorderHorizontal(final int borderHorizontal) {
2567         cachedBorderHorizontal_ = borderHorizontal;
2568         return cachedBorderHorizontal_;
2569     }
2570 
2571     /**
2572      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span>
2573      * @return the cached border vertical
2574      */
2575     public int getCachedBorderVertical() {
2576         return cachedBorderVertical_;
2577     }
2578 
2579     /**
2580      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span>
2581      * @param borderVertical the new value
2582      * @return the param borderVertical
2583      */
2584     public int updateCachedBorderVertical(final int borderVertical) {
2585         cachedBorderVertical_ = borderVertical;
2586         return cachedBorderVertical_;
2587     }
2588 
2589     /**
2590      * Makes a local, "computed", modification to this CSS style.
2591      *
2592      * @param declaration the style declaration
2593      * @param selector the selector determining that the style applies to this element
2594      */
2595     public void applyStyleFromSelector(final CSSStyleDeclarationImpl declaration, final Selector selector) {
2596         final SelectorSpecificity specificity = selector.getSelectorSpecificity();
2597         for (final Property prop : declaration.getProperties()) {
2598             final String name = prop.getName();
2599             final String value = declaration.getPropertyValue(name);
2600             final String priority = declaration.getPropertyPriority(name);
2601             applyLocalStyleAttribute(name, value, priority, specificity);
2602         }
2603     }
2604 
2605     private void applyLocalStyleAttribute(final String name, final String newValue, final String priority,
2606             final SelectorSpecificity specificity) {
2607         if (!StyleElement.PRIORITY_IMPORTANT.equals(priority)) {
2608             final StyleElement existingElement = localModifications_.get(name);
2609             if (existingElement != null) {
2610                 if (existingElement.isImportant()) {
2611                     return; // can't override a !important rule by a normal rule. Ignore it!
2612                 }
2613                 else if (specificity.compareTo(existingElement.getSpecificity()) < 0) {
2614                     return; // can't override a rule with a rule having higher specificity
2615                 }
2616             }
2617         }
2618         final StyleElement element = new StyleElement(name, newValue, priority, specificity);
2619         localModifications_.put(name, element);
2620     }
2621 
2622     /**
2623      * Makes a local, "computed", modification to this CSS style that won't override other
2624      * style attributes of the same name. This method should be used to set default values
2625      * for style attributes.
2626      *
2627      * @param name the name of the style attribute to set
2628      * @param newValue the value of the style attribute to set
2629      */
2630     public void setDefaultLocalStyleAttribute(final String name, final String newValue) {
2631         final StyleElement element = new StyleElement(name, newValue, "", SelectorSpecificity.DEFAULT_STYLE_ATTRIBUTE);
2632         localModifications_.put(name, element);
2633     }
2634 
2635     /**
2636      * {@inheritDoc}
2637      */
2638     @Override
2639     public boolean hasFeature(final BrowserVersionFeatures property) {
2640         return getDomElement().hasFeature(property);
2641     }
2642 
2643     /**
2644      * {@inheritDoc}
2645      */
2646     @Override
2647     public BrowserVersion getBrowserVersion() {
2648         return getDomElement().getPage().getWebClient().getBrowserVersion();
2649     }
2650 
2651     /**
2652      * {@inheritDoc}
2653      */
2654     @Override
2655     public boolean isComputed() {
2656         return true;
2657     }
2658 
2659     /**
2660      * {@inheritDoc}
2661      */
2662     @Override
2663     public String toString() {
2664         return "ComputedCssStyleDeclaration for '" + getDomElement() + "'";
2665     }
2666 
2667     private String defaultIfEmpty(final String str, final StyleAttributes.Definition definition) {
2668         return defaultIfEmpty(str, definition, false);
2669     }
2670 
2671     private String defaultIfEmpty(final String str, final StyleAttributes.Definition definition,
2672             final boolean isPixel) {
2673         if (!getDomElement().isAttachedToPage()) {
2674             return EMPTY_FINAL;
2675         }
2676         if (str == null || str.isEmpty()) {
2677             return definition.getDefaultComputedValue(getBrowserVersion());
2678         }
2679         if (isPixel) {
2680             return pixelString(str);
2681         }
2682         return str;
2683     }
2684 
2685     /**
2686      * Returns the string, or {@code toReturnIfEmptyOrDefault}.
2687      *
2688      * @param toReturnIfEmptyOrDefault the value to return if empty or equals the {@code defaultValue}
2689      * @param defaultValue the default value of the string
2690      * @return the string, or {@code toReturnIfEmptyOrDefault}
2691      */
2692     private String defaultIfEmpty(final String str, final String toReturnIfEmptyOrDefault, final String defaultValue) {
2693         if (!getDomElement().isAttachedToPage()) {
2694             return EMPTY_FINAL;
2695         }
2696         if (str == null || str.isEmpty() || str.equals(defaultValue)) {
2697             return toReturnIfEmptyOrDefault;
2698         }
2699         return str;
2700     }
2701 
2702     /**
2703      * Returns the specified length value as a pixel length value.
2704      * This method does <b>NOT</b> handle percentages correctly;
2705      * use {@link CssPixelValueConverter#pixelValue(DomElement, CssValue)} if you need percentage support.
2706      * @param value the length value to convert to a pixel length value
2707      * @return the specified length value as a pixel length value
2708      * @see CssPixelValueConverter#pixelString(DomElement, CssValue)
2709      */
2710     private static String pixelString(final String value) {
2711         if (EMPTY_FINAL == value || value.endsWith("px")) {
2712             return value;
2713         }
2714         return CssPixelValueConverter.pixelValue(value) + "px";
2715     }
2716 }