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 DOM/Sources/DOM.PresentationAttributes.swift
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,9 @@ package extension DOM {
package var fontStyle: FontStyle?
package var textAnchor: TextAnchor?
package var dominantBaseline: TextBaseline?
/// not inherited: the baseline of a `<tspan>` itself, when not its `dominant-baseline`
package var alignmentBaseline: TextBaseline?
package var baselineShift: BaselineShift?
/// CSS `letter-spacing` and `word-spacing`; `normal` is a length of 0
package var letterSpacing: DashLength?
package var wordSpacing: DashLength?
Expand Down Expand Up @@ -203,6 +206,8 @@ extension DOM.PresentationAttributes {
merged.fontStyle = att.fontStyle ?? fontStyle
merged.textAnchor = att.textAnchor ?? textAnchor
merged.dominantBaseline = att.dominantBaseline ?? dominantBaseline
merged.alignmentBaseline = att.alignmentBaseline ?? alignmentBaseline
merged.baselineShift = att.baselineShift ?? baselineShift
merged.letterSpacing = att.letterSpacing ?? letterSpacing
merged.wordSpacing = att.wordSpacing ?? wordSpacing

Expand Down
45 changes: 44 additions & 1 deletion DOM/Sources/DOM.swift
Original file line number Diff line number Diff line change
Expand Up @@ -245,12 +245,55 @@ extension DOM {
}
}

/// `dominant-baseline` and `alignment-baseline` (CSS Inline 3, SVG 1.1): the baseline of the
/// font that sits on the text's `y`
package enum TextBaseline: String {
case auto
case alphabetic
case middle
case central
case hanging
case alphabetic
case mathematical
case ideographic
case textBeforeEdge = "text-before-edge"
case textAfterEdge = "text-after-edge"

/// A value, with the aliases SVG 1.1 and CSS Inline 3 give some of them. nil for `inherit`
/// and unknown values, which leave the inherited baseline.
package init?(css value: String) {
switch value.trimmingCharacters(in: .whitespaces).lowercased() {
case "auto", "baseline", "use-script": self = .auto
// SVG 1.1: keep the parent's baseline, as `inherit`
case "no-change", "reset-size": return nil
case "text-top", "before-edge": self = .textBeforeEdge
case "text-bottom", "after-edge": self = .textAfterEdge
case let other: self.init(rawValue: other)
}
}
}

/// `baseline-shift`: how far a `<tspan>` (and the text within it) is raised from the baseline of
/// its parent. Shifts of nested elements add up.
package enum BaselineShift: Equatable {
case baseline
case sub
case `super`
/// positive raises; a percentage is of the font-size (the line-height)
case length(DashLength)
/// the value of the parent element: `baseline-shift` is not inherited otherwise
case inherit

package init?(css value: String) {
switch value.trimmingCharacters(in: .whitespaces).lowercased() {
case "baseline": self = .baseline
case "sub": self = .sub
case "super": self = .super
case "inherit": self = .inherit
default:
guard let length = XMLParser.parseDashLength(value) else { return nil }
self = .length(length)
}
}
}

package enum Transform: Equatable {
Expand Down
7 changes: 6 additions & 1 deletion DOM/Sources/Parser.XML.Element.swift
Original file line number Diff line number Diff line change
Expand Up @@ -456,7 +456,12 @@ extension XMLParser {
el.fontWeight = lenient { try att.parseString("font-weight") as String? }.flatMap(DOM.FontWeight.init)
el.fontStyle = lenient { try att.parseString("font-style") as String? }.flatMap(DOM.FontStyle.init)
el.textAnchor = lenient { try att.parseRaw("text-anchor") }
el.dominantBaseline = lenient { try att.parseRaw("dominant-baseline") }
el.dominantBaseline = lenient { try att.parseString("dominant-baseline") as String? }
.flatMap { DOM.TextBaseline(css: XMLParser.Attributes.removingImportant(from: $0)) }
el.alignmentBaseline = lenient { try att.parseString("alignment-baseline") as String? }
.flatMap { DOM.TextBaseline(css: XMLParser.Attributes.removingImportant(from: $0)) }
el.baselineShift = lenient { try att.parseString("baseline-shift") as String? }
.flatMap { DOM.BaselineShift(css: XMLParser.Attributes.removingImportant(from: $0)) }
// a percentage is of the viewport width, as for other horizontal lengths (as resvg; CSS Text 4
// makes it a percentage of the font-size)
let viewportWidth = lengthContext.viewports.last?.width
Expand Down
2 changes: 1 addition & 1 deletion DOM/Tests/Parser.TolerantTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ struct TolerantParsingTests {
<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10">
<rect id="a" width="5" height="5" fill="" stroke="inherit" opacity="abc"
stroke-width="wide" display="inline-block" stroke-linecap="none"
dominant-baseline="text-top" clip-path="none" mask="none" filter="none"
dominant-baseline="text-middle" clip-path="none" mask="none" filter="none"
transform="none"/>
</svg>
""")
Expand Down
21 changes: 21 additions & 0 deletions Samples.bundle/text-baselines.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,14 @@ extension LayerTree.Builder {
/// The state of an element before invalid references are dropped.
func createReferencedState(for element: DOM.GraphicsElement, inheriting existing: State) -> State {
let attributes = DOM.presentationAttributes(for: element, styles: svg.styles)
return Self.createState(for: attributes, inheriting: existing, viewportDiagonal: viewportDiagonal)
var state = Self.createState(for: attributes, inheriting: existing, viewportDiagonal: viewportDiagonal)
// `baseline-shift` applies to the text content elements within <text> (as resvg, not to the
// <text> itself), and those nested add up
if element is DOM.TextSpan || element is DOM.TextPath,
let shift = state.baselineShift {
state.baselineShifts.append(BaselineShiftEntry(shift: shift, fontSize: state.fontSize))
}
return state
}

func makeInvalidReferences() -> Set<Reference> {
Expand Down
88 changes: 72 additions & 16 deletions SwiftDraw/Sources/LayerTree/LayerTree.Builder.Text.swift
Original file line number Diff line number Diff line change
Expand Up @@ -500,7 +500,7 @@ extension LayerTree.Builder {
let ascent = LayerTree.Float(CTFontGetAscent(font))
let descent = LayerTree.Float(CTFontGetDescent(font))
let origin = LayerTree.Point(run.origin.x + shift, run.origin.y)
let baseline = origin.y + makeBaselineOffset(with: attributes)
let baseline = origin.y + makeBaselineOffset(with: attributes, shifts: run.state.baselineShifts)
let extent = run.horizontalExtent
var cell = LayerTree.Rect(x: extent.lowerBound + shift, y: baseline - ascent,
width: extent.upperBound - extent.lowerBound, height: ascent + descent)
Expand Down Expand Up @@ -528,7 +528,7 @@ extension LayerTree.Builder {
bounds: () -> LayerTree.Rect? = { nil }) -> LayerTree.Layer.Contents? {
// state already holds the cascaded font-family, font-size, font-weight, font-style and text-anchor
let att = makeTextAttributes(with: state)
let baseline = Self.makeBaselineOffset(with: att)
let baseline = Self.makeBaselineOffset(with: att, shifts: state.baselineShifts)
var point = point
point.y += baseline
let rotation = rotate == 0 ? [] : Self.makeRotation(rotate, about: point)
Expand Down Expand Up @@ -621,16 +621,64 @@ extension LayerTree.Builder {
return LayerTree.Float(text.toWidth(font: font.font, synthesis: font.synthesis(for:)))
}

static func makeBaselineOffset(with attributes: LayerTree.TextAttributes) -> LayerTree.Float {
makeYOffset(font: CGProvider.createFont(for: attributes).font, baseline: attributes.baseline)
static func makeBaselineOffset(with attributes: LayerTree.TextAttributes,
shifts: [BaselineShiftEntry] = []) -> LayerTree.Float {
let font = CGProvider.createFont(for: attributes).font
var offset = makeYOffset(font: font, baseline: attributes.baseline)
for entry in shifts {
offset -= makeBaselineShift(entry.shift, font: font, fontSize: entry.fontSize)
}
return offset
}

/// How far `baseline-shift` raises the text (CSS Inline 3 §4.3, SVG 1.1 §10.9.2): `sub` and
/// `super` by the font's own subscript and superscript offsets (its OS/2 table), percentages of
/// the font-size it was declared at.
static func makeBaselineShift(_ shift: DOM.BaselineShift, font: CTFont, fontSize: LayerTree.Float) -> LayerTree.Float {
switch shift {
case .baseline, .inherit:
return 0
case .sub:
return -(makeScriptOffsets(font: font, fontSize: fontSize)?.sub ?? fontSize * 0.2)
case .super:
return makeScriptOffsets(font: font, fontSize: fontSize)?.super ?? fontSize / 3
case .length(.absolute(let value)):
return value
case .length(.em(let value)):
return value * fontSize
case .length(.percentage(let value)):
return value / 100 * fontSize
}
}

/// `ySubscriptYOffset` and `ySuperscriptYOffset` of the font's OS/2 table, at `fontSize`
static func makeScriptOffsets(font: CTFont, fontSize: LayerTree.Float) -> (sub: LayerTree.Float, super: LayerTree.Float)? {
guard let table = CTFontCopyTable(font, CTFontTableTag(kCTFontTableOS2), []) as Data?,
table.count >= 26 else { return nil }
func int16(_ offset: Int) -> LayerTree.Float {
let index = table.startIndex + offset
return LayerTree.Float(Int16(bitPattern: UInt16(table[index]) << 8 | UInt16(table[index + 1])))
}
let unitsPerEm = LayerTree.Float(CTFontGetUnitsPerEm(font))
guard unitsPerEm > 0 else { return nil }
return (int16(16) / unitsPerEm * fontSize, int16(24) / unitsPerEm * fontSize)
}
#else
static func makeAdvance(for text: String, with attributes: LayerTree.TextAttributes) -> LayerTree.Float {
0
}

static func makeBaselineOffset(with attributes: LayerTree.TextAttributes) -> LayerTree.Float {
0
static func makeBaselineOffset(with attributes: LayerTree.TextAttributes,
shifts: [BaselineShiftEntry] = []) -> LayerTree.Float {
// no font metrics: only the shifts that are lengths
shifts.reduce(0) { offset, entry in
switch entry.shift {
case .length(.absolute(let value)): offset - value
case .length(.em(let value)): offset - value * entry.fontSize
case .length(.percentage(let value)): offset - value / 100 * entry.fontSize
case .baseline, .inherit, .sub, .super: offset
}
}
}
#endif

Expand All @@ -644,20 +692,28 @@ extension LayerTree.Builder {
)
}

/// How far down the glyphs move so that `baseline` of the font sits on the text's `y`, from the
/// font's ascent, descent and x-height, as resvg and browsers derive the baselines a font does
/// not list (CSS Inline 3 §4.2).
static func makeYOffset(font: CTFont, baseline: DOM.TextBaseline) -> LayerTree.Float {
let ascent = LayerTree.Float(CTFontGetAscent(font))
let descent = LayerTree.Float(CTFontGetDescent(font))
switch baseline {
case .central:
let capHeight = CTFontGetCapHeight(font)
return LayerTree.Float(capHeight / 2)
case .alphabetic, .auto:
case .auto, .alphabetic:
return 0
case .hanging:
let leading = CTFontGetLeading(font)
let ascent = CTFontGetAscent(font) - leading
return LayerTree.Float(-ascent)
case .textBeforeEdge:
return ascent
case .textAfterEdge, .ideographic:
return -descent
case .central:
// the middle of the em box
return (ascent - descent) / 2
case .middle:
let xHeight = CTFontGetXHeight(font)
return LayerTree.Float(xHeight / 2)
return LayerTree.Float(CTFontGetXHeight(font)) / 2
case .hanging:
return ascent * 0.8
case .mathematical:
return ascent * 0.5
}
}
#else
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ extension LayerTree.Builder {
runs.append(Run(state: state,
glyphs: glyphs,
x: width,
dy: Self.makeYOffset(font: font.font, baseline: attributes.baseline)))
dy: Self.makeBaselineOffset(with: attributes, shifts: state.baselineShifts)))
width += glyphs.reduce(0) { $0 + $1.advance }
case .span(let span):
// a <tspan> with display="none" is not drawn and takes no space
Expand Down
18 changes: 17 additions & 1 deletion SwiftDraw/Sources/LayerTree/LayerTree.Builder.swift
Original file line number Diff line number Diff line change
Expand Up @@ -692,7 +692,7 @@ extension LayerTree.Builder {
weight: state.fontWeight,
isItalic: state.fontStyle != .normal,
anchor: state.textAnchor,
baseline: state.textBaseline
baseline: state.alignmentBaseline ?? state.textBaseline
)
}

Expand Down Expand Up @@ -1173,7 +1173,15 @@ extension LayerTree.Builder {
var fontWeight: Int
var fontStyle: DOM.FontStyle
var textAnchor: DOM.TextAnchor
/// `dominant-baseline`, inherited
var textBaseline: DOM.TextBaseline
/// `alignment-baseline` of the element itself (not inherited); nil uses `textBaseline`
var alignmentBaseline: DOM.TextBaseline?
/// `baseline-shift` of the element itself, for a child's `inherit`
var baselineShift: DOM.BaselineShift?
/// the `baseline-shift` of the text content element and each of its text content ancestors,
/// outermost first, with the font-size each was declared at: they add up
var baselineShifts: [BaselineShiftEntry] = []
/// CSS `letter-spacing` and `word-spacing`, computed: inherited as absolute lengths
var letterSpacing: DOM.Float
var wordSpacing: DOM.Float
Expand Down Expand Up @@ -1215,6 +1223,11 @@ extension LayerTree.Builder {
}
}

struct BaselineShiftEntry {
var shift: DOM.BaselineShift
var fontSize: DOM.Float
}

func createState(for element: DOM.GraphicsElement, inheriting existing: State) -> State {
var state = createReferencedState(for: element, inheriting: existing)
// recursive references to patterns and markers are dropped (see makeInvalidReferences)
Expand Down Expand Up @@ -1269,6 +1282,9 @@ extension LayerTree.Builder {
state.fontStyle = attributes.fontStyle ?? existing.fontStyle
state.textAnchor = attributes.textAnchor ?? existing.textAnchor
state.textBaseline = attributes.dominantBaseline ?? existing.textBaseline
state.alignmentBaseline = attributes.alignmentBaseline == .auto ? nil : attributes.alignmentBaseline
state.baselineShift = attributes.baselineShift == .inherit ? existing.baselineShift : attributes.baselineShift
state.baselineShifts = existing.baselineShifts
// `em` is of the element's computed font-size; the parser resolves percentages of the viewport
func spacing(_ length: DOM.DashLength) -> DOM.Float {
switch length {
Expand Down
Loading
Loading