Project

Profile

Help

Bug #4537 » units.xsl

Norman Tovey-Walsh, 2020-05-01 22:45

 
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:db="http://docbook.org/ns/docbook"
xmlns:f="http://docbook.org/ns/docbook/functions"
xmlns:v="http://docbook.org/ns/docbook/variables"
xmlns:vp="http://docbook.org/ns/docbook/variables/private"
xmlns:m="http://docbook.org/ns/docbook/modes"
xmlns:map="http://www.w3.org/2005/xpath-functions/map"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns="http://www.w3.org/1999/xhtml"
exclude-result-prefixes="db f m map v vp xs"
version="3.0">

<xsl:param name="pixels-per-inch" select="96.0"/>
<xsl:param name="nominal-page-width" select="$pixels-per-inch * 6"/>
<xsl:param name="default-length"
select="floor($pixels-per-inch * $nominal-page-width) * 0.25"/>

<xsl:variable name="v:unit-scale" as="map(*)"
select="map {
'px': 1.0,
'in': $pixels-per-inch,
'm' : $pixels-per-inch div 2.54 * 100.0,
'cm': $pixels-per-inch div 2.54,
'mm': $pixels-per-inch div 25.4,
'pt': $pixels-per-inch div 72.0,
'pc': $pixels-per-inch div 6.0
}"/>

<xsl:variable name="vp:length-regex" select="'^(\d+(\.\d+)?)\s*(\S+)'"/>
<xsl:variable name="vp:percent-regex" select="'^(\d+(\.\d+)?)\s*%'"/>

<xsl:function name="f:parse-length" as="xs:double">
<xsl:param name="length" as="xs:string"/>

<xsl:variable name="length" select="normalize-space($length)"/>

<xsl:choose>
<xsl:when test="matches($length, $vp:percent-regex)">
<xsl:variable name="perc"
select="replace($length, $vp:percent-regex, '$1')"/>
<xsl:sequence
select="$nominal-page-width * xs:double($perc) div 100.0"/>
</xsl:when>
<xsl:when test="matches($length, $vp:length-regex)">
<xsl:variable name="mag"
select="xs:double(replace($length, $vp:length-regex, '$1'))"/>
<xsl:variable name="unit"
select="replace($length, $vp:length-regex, '$3')"/>
<xsl:choose>
<xsl:when test="map:contains($v:unit-scale, $unit)">
<xsl:sequence select="$mag * map:get($v:unit-scale, $unit)"/>
</xsl:when>
<xsl:otherwise>
<xsl:message expand-text="yes"
>Unrecognized unit {$unit}, using $default-length</xsl:message>
<xsl:sequence select="$default-length"/>
</xsl:otherwise>
</xsl:choose>
</xsl:when>
<xsl:otherwise>
<xsl:message expand-text="yes"
>Unparsed length {$length}, using $default-length</xsl:message>
<xsl:sequence select="$default-length"/>
</xsl:otherwise>
</xsl:choose>
</xsl:function>


</xsl:stylesheet>
(2-2/2)