Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions Source/HtmlRenderer/Core/Dom/CssBox.cs
Original file line number Diff line number Diff line change
Expand Up @@ -354,6 +354,11 @@ public HtmlTag HtmlTag
get { return _htmltag; }
}

protected override bool IsRootElement
{
get { return _htmltag != null && _htmltag.Name.Equals("html", StringComparison.OrdinalIgnoreCase); }
}

/// <summary>
/// Gets if this box represents an image
/// </summary>
Expand Down
49 changes: 47 additions & 2 deletions Source/HtmlRenderer/Core/Dom/CssBoxProperties.cs
Original file line number Diff line number Diff line change
Expand Up @@ -913,6 +913,10 @@ public string FontSize
{
computedValue = len.ConvertEmToPoints(GetParent().ActualFont.Size).ToString();
}
else if (len.Unit == CssUnit.Rems)
{
computedValue = string.Format(NumberFormatInfo.InvariantInfo, "{0}pt", len.Number * GetRootFontSize());
}
else
{
computedValue = len.ToString();
Expand Down Expand Up @@ -1762,7 +1766,7 @@ public RFont ActualFont
fsize = parentSize + 2;
break;
default:
fsize = CssValueParser.ParseLength(FontSize, parentSize, parentSize, null, true, true);
fsize = CssValueParser.ParseLength(FontSize, parentSize, parentSize, GetRootFontSize(), null, true, true);
break;
}

Expand Down Expand Up @@ -1883,7 +1887,7 @@ public double ActualBorderSpacingVertical
/// Gets the size of 1em in CSS pixels, per spec: an element's own computed font-size, not
/// the font's line-spacing metric (ascent+descent+leading), which is typically 15-30%+
/// larger and would inflate every em-based margin/padding/line-height. <see cref="ActualFont"/>
/// is created from a font-size already converted to points (<see cref="Parse.CssValueParser.ParseLength(string, double, double, string, bool, bool)"/>'s
/// is created from a font-size already converted to points (<see cref="Parse.CssValueParser.ParseLength(string, double, double, double, string, bool, bool)"/>'s
/// fontAdjust factor, 72/96, applied when the declared value is in CSS px), so its own
/// <see cref="Adapters.RFont.Size"/> is in points too - convert back to CSS px (the unit
/// every other length in this engine resolves to) with the inverse, 96/72.
Expand All @@ -1894,6 +1898,47 @@ public double GetEmHeight()
return ActualFont.Size * 96d / 72d;
}

/// <summary>
/// Gets the size of 1rem in CSS pixels, the root element's font size (css-values-4 §6.1.1).
/// </summary>
public double GetRemHeight()
{
return GetRootElement().GetEmHeight();
}

/// <summary>
/// Whether this box is the document's root element.
/// </summary>
protected virtual bool IsRootElement
{
get { return false; }
}

/// <summary>
/// Gets the root element, or the topmost box for a fragment without an html element.
/// </summary>
private CssBoxProperties GetRootElement()
{
var root = this;
for (var box = this; box != null; box = box.GetParent())
{
root = box;
if (box.IsRootElement)
break;
}
return root;
}

/// <summary>
/// Gets the font size in points that rem refers to in this box's font-size.
/// </summary>
private double GetRootFontSize()
{
// css-values-4 §6.1.1: rem in the root element's own font-size refers to the initial value
var root = GetRootElement();
return root == this ? CssConstants.FontSize : root.ActualFont.Size;
}

/// <summary>
/// Ensures that the specified length is converted to pixels if necessary
/// </summary>
Expand Down
11 changes: 9 additions & 2 deletions Source/HtmlRenderer/Core/Dom/CssLength.cs
Original file line number Diff line number Diff line change
Expand Up @@ -57,14 +57,18 @@ public CssLength(string length)
}

//Get units of the length
string u = length.Substring(length.Length - 2, 2);
string u = length.EndsWith(CssConstants.Rem) ? CssConstants.Rem : length.Substring(length.Length - 2, 2);

//Number of the length
string number = length.Substring(0, length.Length - 2);
string number = length.Substring(0, length.Length - u.Length);

//TODO: Units behave different in paper and in screen!
switch (u)
{
case CssConstants.Rem:
_unit = CssUnit.Rems;
_isRelative = true;
break;
case CssConstants.Em:
_unit = CssUnit.Ems;
_isRelative = true;
Expand Down Expand Up @@ -218,6 +222,9 @@ public override string ToString()
case CssUnit.Ems:
u = "em";
break;
case CssUnit.Rems:
u = "rem";
break;
case CssUnit.Pixels:
u = "px";
break;
Expand Down
3 changes: 2 additions & 1 deletion Source/HtmlRenderer/Core/Dom/CssUnit.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ internal enum CssUnit
Centimeters,
Milimeters,
Points,
Picas
Picas,
Rems
}
}
23 changes: 16 additions & 7 deletions Source/HtmlRenderer/Core/Parse/CssValueParser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,10 @@ public static bool IsValidLength(string value)
{
number = value.Substring(0, value.Length - 1);
}
else if (value.EndsWith(CssConstants.Rem))
{
number = value.Substring(0, value.Length - 3);
}
else if (value.Length > 2)
{
number = value.Substring(0, value.Length - 2);
Expand Down Expand Up @@ -216,7 +220,7 @@ private static void AppendFontFaceCandidate(List<CssFontFace> result, List<Token
/// Recognizes a length string that is a single calc-family (calc/min/max/clamp) function call.
/// Real grammar/type validation happens in the vendored CSS-OM's CalcValueConverter at parse
/// time (for any value that didn't arrive via var() substitution); this is a syntactic
/// recognizer only, used to gate the evaluation branch in <see cref="ParseLength(string, double, double, string, bool, bool)"/>.
/// recognizer only, used to gate the evaluation branch in <see cref="ParseLength(string, double, double, double, string, bool, bool)"/>.
/// </summary>
public static bool IsCalcFunction(string value)
{
Expand Down Expand Up @@ -284,7 +288,7 @@ public static double ParseNumber(string number, double hundredPercent)
/// <returns>the parsed length value with adjustments</returns>
public static double ParseLength(string length, double hundredPercent, CssBoxProperties box, bool fontAdjust = false)
{
return ParseLength(length, hundredPercent, box.GetEmHeight(), null, fontAdjust, false);
return ParseLength(length, hundredPercent, box.GetEmHeight(), box.GetRemHeight(), null, fontAdjust, false);
}

/// <summary>
Expand All @@ -297,7 +301,7 @@ public static double ParseLength(string length, double hundredPercent, CssBoxPro
/// <returns>the parsed length value with adjustments</returns>
public static double ParseLength(string length, double hundredPercent, CssBoxProperties box, string defaultUnit)
{
return ParseLength(length, hundredPercent, box.GetEmHeight(), defaultUnit, false, false);
return ParseLength(length, hundredPercent, box.GetEmHeight(), box.GetRemHeight(), defaultUnit, false, false);
}

/// <summary>
Expand All @@ -306,11 +310,12 @@ public static double ParseLength(string length, double hundredPercent, CssBoxPro
/// <param name="length">Specified length</param>
/// <param name="hundredPercent">Equivalent to 100 percent when length is percentage</param>
/// <param name="emFactor"></param>
/// <param name="remFactor">the root element's font size, in the same unit as <paramref name="emFactor"/></param>
/// <param name="defaultUnit"></param>
/// <param name="fontAdjust">if the length is in pixels and the length is font related it needs to use 72/96 factor</param>
/// <param name="returnPoints">Allows the return double to be in points. If false, result will be pixels</param>
/// <returns>the parsed length value with adjustments</returns>
public static double ParseLength(string length, double hundredPercent, double emFactor, string defaultUnit, bool fontAdjust, bool returnPoints)
public static double ParseLength(string length, double hundredPercent, double emFactor, double remFactor, string defaultUnit, bool fontAdjust, bool returnPoints)
{
//Return zero if no length specified, zero specified
if (string.IsNullOrEmpty(length) || length == "0")
Expand All @@ -327,7 +332,7 @@ public static double ParseLength(string length, double hundredPercent, double em
if (TryGetCalcFunction(length, out calcFunction))
{
var node = CalcParser.Parse(calcFunction);
var context = new CalcContext(hundredPercent, emFactor, emFactor, fontAdjust, returnPoints);
var context = new CalcContext(hundredPercent, emFactor, remFactor, fontAdjust, returnPoints);
var pixels = node != null ? CalcEvaluator.Evaluate(node, context) : null;
return pixels ?? 0d;
}
Expand All @@ -340,14 +345,17 @@ public static double ParseLength(string length, double hundredPercent, double em
double factor;

//Number of the length
string number = hasUnit ? length.Substring(0, length.Length - 2) : length;
string number = hasUnit ? length.Substring(0, length.Length - unit.Length) : length;

//TODO: Units behave different in paper and in screen!
switch (unit)
{
case CssConstants.Em:
factor = emFactor;
break;
case CssConstants.Rem:
factor = remFactor;
break;
case CssConstants.Ex:
factor = emFactor / 2;
break;
Expand Down Expand Up @@ -388,9 +396,10 @@ public static double ParseLength(string length, double hundredPercent, double em
/// </summary>
private static string GetUnit(string length, string defaultUnit, out bool hasUnit)
{
var unit = length.Length >= 3 ? length.Substring(length.Length - 2, 2) : string.Empty;
var unit = length.EndsWith(CssConstants.Rem) ? CssConstants.Rem : length.Length >= 3 ? length.Substring(length.Length - 2, 2) : string.Empty;
switch (unit)
{
case CssConstants.Rem:
case CssConstants.Em:
case CssConstants.Ex:
case CssConstants.Px:
Expand Down
2 changes: 1 addition & 1 deletion Source/HtmlRenderer/Core/Parse/RegexParserUtils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ internal static class RegexParserUtils
/// <summary>
/// Extracts CSS lengths; e.g. 9px 3pt .89em
/// </summary>
public const string CssLength = @"([0-9]+|[0-9]*\.[0-9]+)(em|ex|px|in|cm|mm|pt|pc)";
public const string CssLength = @"([0-9]+|[0-9]*\.[0-9]+)(rem|em|ex|px|in|cm|mm|pt|pc)";

/// <summary>
/// Extracts line-height values (normal, numbers, lengths, percentages)
Expand Down
5 changes: 5 additions & 0 deletions Source/HtmlRenderer/Core/Utils/CssConstants.cs
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,11 @@ internal static class CssConstants
/// </summary>
public const string Em = "em";

/// <summary>
/// Rem - The font size of the root element
/// </summary>
public const string Rem = "rem";

/// <summary>
/// The 'x-height' of the relevan font
/// </summary>
Expand Down
50 changes: 45 additions & 5 deletions Source/Test/HtmlRenderer.Test/Css/LengthTests.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using HtmlRenderer.Test.TestSupport;
using TheArtOfDev.HtmlRenderer.Core.Dom;

namespace HtmlRenderer.Test.Css;
Expand All @@ -14,9 +15,9 @@ namespace HtmlRenderer.Test.Css;
/// <c>IFormattable</c>, and predefined constants (Zero/Half/Full/Thin/Medium/Thick).
///
/// HTML-Renderer's internal <see cref="CssLength"/> is much smaller: it has only a single
/// string-parsing constructor (<c>new CssLength("10px")</c>), a 9-member <see cref="CssUnit"/> enum
/// (None, Ems, Pixels, Ex, Inches, Centimeters, Milimeters, Points, Picas - i.e. only em/ex/px/mm/cm/
/// in/pt/pc, no rem/%/ch/viewport/container-query units at all; percentage is tracked separately via
/// string-parsing constructor (<c>new CssLength("10px")</c>), a 10-member <see cref="CssUnit"/> enum
/// (None, Ems, Pixels, Ex, Inches, Centimeters, Milimeters, Points, Picas, Rems - i.e. only em/ex/px/mm/cm/
/// in/pt/pc/rem, no %/ch/viewport/container-query units at all; percentage is tracked separately via
/// <c>IsPercentage</c>/<c>Number</c> rather than being a <see cref="CssUnit"/> value), <c>Number</c>,
/// <c>HasError</c>, <c>IsPercentage</c>, <c>IsRelative</c> (no <c>IsAbsolute</c>), <c>Length</c> (the
/// original string), <c>ConvertEmToPoints(emSize)</c>/<c>ConvertEmToPixels(pixelFactor)</c> (Ems-only,
Expand All @@ -28,15 +29,15 @@ namespace HtmlRenderer.Test.Css;
/// Tests below that exercise only the 8 units/members this fork actually supports are ported as plain
/// passing tests against the real constructor/members (a few reusing <c>ConvertEmToPoints</c>/
/// <c>ConvertEmToPixels</c> as the closest real analog to PeachPDF's richer pixel-conversion API).
/// Tests that need an unsupported unit (rem, %-as-a-unit, ch, any viewport or container-query variant)
/// Tests that need an unsupported unit (%-as-a-unit, ch, any viewport or container-query variant)
/// or an API member this fork's <see cref="CssLength"/> doesn't have (TryParse, To, ToPixel(s),
/// comparison/equality operators, IFormattable, predefined constants, IsAbsolute, UnitString, GetUnit)
/// are ported under <c>[Ignore]</c>, adapted as closely as possible to compile against the real API
/// surface and documenting the intended/target behavior for when such members might be added.
/// The container-query-unit theory (ToPixels_ContainerRelativeUnit_*, 4 methods), the viewport-unit
/// theories (ToPixels_ViewportUnit_*, 2 methods), ToPixels_Rem_UsesRemFactor, and
/// ToPixels_Ch_ApproximatesHalfEm were dropped entirely: their units (cqw/cqh/cqi/cqb/cqmin/cqmax, vw/
/// vh/vmin/vmax and the sv*/lv*/dv* variants, rem, ch) have no representation whatsoever in
/// vh/vmin/vmax and the sv*/lv*/dv* variants, ch) have no representation whatsoever in
/// <see cref="CssUnit"/>, so there is no plausible compileable adaptation - constructing a
/// <see cref="CssLength"/> with any of those suffixes just falls into the "unrecognized unit"
/// <c>HasError</c> branch and asserts nothing meaningful.
Expand Down Expand Up @@ -66,6 +67,7 @@ public void Constructor_SetsValueAndType()
[DataRow("in", "Inches")]
[DataRow("pt", "Points")]
[DataRow("pc", "Picas")]
[DataRow("rem", "Rems")]
[DataRow("bogus", "None")]
public void Constructor_ParsesKnownUnitSuffixes(string suffix, string expectedUnitName)
{
Expand Down Expand Up @@ -414,6 +416,44 @@ public void PredefinedConstants_HaveExpectedValues()
Assert.AreEqual(5d, thick.Number);
}

[TestMethod]
public void Rem_ResolvesAgainstTheRootFontSize()
{
var x = LayoutRem("html{font-size:10px} #x{font-size:20px;margin-left:2rem;padding-left:calc(1rem);text-indent:3rem;height:4rem;border-left:0.5rem solid}");

Assert.AreEqual(20, x.ActualMarginLeft, 0.01);
Assert.AreEqual(10, x.ActualPaddingLeft, 0.01);
Assert.AreEqual(30, x.ActualTextIndent, 0.01);
Assert.AreEqual(40, x.Size.Height, 0.01);
Assert.AreEqual(5, x.ActualBorderLeftWidth, 0.01);
}

[TestMethod]
public void Rem_InFontSize_ResolvesAgainstTheRootFontSize()
{
var x = LayoutRem("html{font-size:10px} body{font-size:30px} #x{font-size:1.5rem}");

Assert.AreEqual(15, x.GetEmHeight(), 0.01);
}

[TestMethod]
public void Rem_InTheRootFontSize_IsTheInitialFontSize()
{
var x = LayoutRem("html{font-size:2rem} #x{margin-left:1rem}");
var initial = 11d * 96d / 72d;

Assert.AreEqual(2 * initial, x.GetEmHeight(), 0.01);
Assert.AreEqual(2 * initial, x.ActualMarginLeft, 0.01);
}

private static CssBox LayoutRem(string css)
{
var (root, _) = LayoutHarness.Layout($"<html><head><style>{css}</style></head><body><div id=x>a</div></body></html>");
var x = LayoutHarness.FindById(root, "x");
Assert.IsNotNull(x);
return x!;
}

private static string ExpectedUnitString(string unitName) => unitName switch
{
"None" => "",
Expand Down
Loading