diff --git a/DOM/Sources/DOM.swift b/DOM/Sources/DOM.swift index ae180619..ad7a127b 100644 --- a/DOM/Sources/DOM.swift +++ b/DOM/Sources/DOM.swift @@ -257,9 +257,11 @@ extension DOM { case ideographic case textBeforeEdge = "text-before-edge" case textAfterEdge = "text-after-edge" + /// the parent's value; `alignment-baseline` is not inherited otherwise + case inherit - /// 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. + /// A value, with the aliases SVG 1.1 and CSS Inline 3 give some of them. nil for 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 diff --git a/DOM/Sources/Parser.XML.Element.swift b/DOM/Sources/Parser.XML.Element.swift index 82f7a02f..b7c6f246 100644 --- a/DOM/Sources/Parser.XML.Element.swift +++ b/DOM/Sources/Parser.XML.Element.swift @@ -348,15 +348,25 @@ extension XMLParser { return result } - /// The `marker` shorthand sets `marker-start`, `marker-mid` and `marker-end` (SVG 2 §11.6.4). - /// It is a CSS property only, not a presentation attribute; expanded in place so a later - /// longhand still overrides it, and an earlier one is overridden. + /// The `marker` shorthand sets `marker-start`, `marker-mid` and `marker-end` (SVG 2 §11.6.4), and + /// `font` sets `font-style`, `font-weight`, `font-size` and `font-family` (CSS Fonts 4 §2.8). + /// They are CSS properties only, not presentation attributes (SVG 2 §6.6); expanded in place so a + /// later longhand still overrides them, and an earlier one is overridden. An invalid `font` is dropped. static func expandingShorthands(_ declarations: [CSSDeclaration]) -> [CSSDeclaration] { - guard declarations.contains(where: { $0.name == "marker" }) else { return declarations } + guard declarations.contains(where: { $0.name == "marker" || $0.name == "font" }) else { return declarations } return declarations.flatMap { d -> [CSSDeclaration] in - guard d.name == "marker" else { return [d] } - return ["marker-start", "marker-mid", "marker-end"].map { - CSSDeclaration(name: $0, value: d.value, important: d.important) + switch d.name { + case "marker": + return ["marker-start", "marker-mid", "marker-end"].map { + CSSDeclaration(name: $0, value: d.value, important: d.important) + } + case "font": + let value = XMLParser.Attributes.removingImportant(from: d.value) + return (parseFontShorthand(value) ?? []).map { + CSSDeclaration(name: $0.name, value: $0.value, important: d.important) + } + default: + return [d] } } } diff --git a/DOM/Sources/Parser.XML.FontShorthand.swift b/DOM/Sources/Parser.XML.FontShorthand.swift new file mode 100644 index 00000000..3ff99e78 --- /dev/null +++ b/DOM/Sources/Parser.XML.FontShorthand.swift @@ -0,0 +1,166 @@ +// +// Parser.XML.FontShorthand.swift +// SwiftDraw +// +// Created by Simon Whitty on 18/11/26. +// Copyright 2026 Simon Whitty +// +// Distributed under the permissive zlib license +// Get the latest version from here: +// +// https://github.com/swhitty/SwiftDraw +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// +// 3. This notice may not be removed or altered from any source distribution. +// + +import Foundation + +extension XMLParser { + + /// The longhands of the CSS `font` shorthand (CSS Fonts 4 §2.8): + /// `[ || || || ]? [ / ]? `, + /// or a system font keyword. The parts it leaves out are reset to their initial values. Only the + /// longhands SwiftDraw draws are returned (`font-variant`, `font-stretch` and `line-height` are + /// checked but dropped). nil when the value is invalid, so the declaration is ignored. + static func parseFontShorthand(_ value: String) -> [(name: String, value: String)]? { + let text = value.trimmingCharacters(in: .whitespacesAndNewlines) + let lowercased = text.lowercased() + + // system fonts: the platform's UI font, approximated by 13px sans-serif as macOS draws it + if systemFontKeywords.contains(lowercased) { + return longhands(style: "normal", weight: "normal", size: "13px", family: "sans-serif") + } + + var style: String? + var variant: String? + var weight: String? + var stretch: String? + + var tokens = Tokens(text) + var preambleCount = 0 + while let token = tokens.peek() { + let word = token.lowercased() + let next = tokens.peek(offset: 1) + if word == "normal" { + // `normal` sets whichever of the four is still unset to its initial value + guard preambleCount < 4 else { return nil } + } else if style == nil, word == "italic" || word == "oblique" { + style = word + // `oblique `: drawn as oblique + if word == "oblique", let angle = next, isAngle(angle) { + tokens.advance() + } + } else if variant == nil, word == "small-caps" { + variant = word + } else if weight == nil, isWeight(word), next != nil, DOM.FontWeight(word) != nil { + // a unitless number is a weight when a size still follows it + weight = word + } else if stretch == nil, stretchKeywords.contains(word) { + stretch = word + } else { + break + } + preambleCount += 1 + guard preambleCount <= 4 else { return nil } + tokens.advance() + } + + // [ / ]? + guard let sizeToken = tokens.peek() else { return nil } + tokens.advance() + let sizeParts = sizeToken.split(separator: "/", maxSplits: 1, omittingEmptySubsequences: false).map(String.init) + let size = sizeParts[0] + guard DOM.FontSize(size) != nil else { return nil } + if sizeParts.count == 2 { + // `12px/1.5` or `12px/ 1.5` + if sizeParts[1].isEmpty { + guard tokens.peek() != nil else { return nil } + tokens.advance() + } + } else if let slash = tokens.peek(), slash.hasPrefix("/") { + // `12px /1.5` or `12px / 1.5` + tokens.advance() + if slash == "/" { + guard tokens.peek() != nil else { return nil } + tokens.advance() + } + } + + let family = tokens.remainder.trimmingCharacters(in: .whitespacesAndNewlines) + guard !family.isEmpty else { return nil } + + return longhands(style: style ?? "normal", weight: weight ?? "normal", size: size, family: family) + } + + private static func longhands(style: String, weight: String, size: String, family: String) -> [(name: String, value: String)] { + [("font-style", style), ("font-weight", weight), ("font-size", size), ("font-family", family)] + } + + private static let systemFontKeywords: Set = [ + "caption", "icon", "menu", "message-box", "small-caption", "status-bar" + ] + + private static let stretchKeywords: Set = [ + "ultra-condensed", "extra-condensed", "condensed", "semi-condensed", + "semi-expanded", "expanded", "extra-expanded", "ultra-expanded" + ] + + private static func isWeight(_ word: String) -> Bool { + switch word { + case "bold", "bolder", "lighter": return true + default: return Double(word) != nil + } + } + + private static func isAngle(_ token: String) -> Bool { + let token = token.lowercased() + for unit in ["deg", "grad", "rad", "turn"] where token.hasSuffix(unit) { + return Double(token.dropLast(unit.count)) != nil + } + return false + } + + /// Whitespace-separated words of the value, keeping the unscanned rest (the family list) as written. + private struct Tokens { + private let text: Substring + private var position: Substring.Index + + init(_ text: String) { + self.text = Substring(text) + self.position = self.text.startIndex + } + + /// The words from the current position, the first `offset + 1` of them + private func words(_ count: Int) -> [Substring] { + Array(text[position...].split(whereSeparator: \.isWhitespace).prefix(count)) + } + + func peek(offset: Int = 0) -> String? { + let words = words(offset + 1) + return words.count > offset ? String(words[offset]) : nil + } + + mutating func advance() { + guard let word = words(1).first else { return } + position = word.endIndex + } + + var remainder: Substring { text[position...] } + } +} diff --git a/DOM/Tests/Parser.FontShorthandTests.swift b/DOM/Tests/Parser.FontShorthandTests.swift new file mode 100644 index 00000000..1de378fd --- /dev/null +++ b/DOM/Tests/Parser.FontShorthandTests.swift @@ -0,0 +1,134 @@ +// +// Parser.FontShorthandTests.swift +// SwiftDraw +// +// Distributed under the permissive zlib license +// Get the latest version from here: +// +// https://github.com/swhitty/SwiftDraw +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// +// 3. This notice may not be removed or altered from any source distribution. +// + +@testable import SwiftDrawDOM +@testable import SwiftDrawDOM +import Foundation +import Testing + +/// The CSS `font` shorthand (CSS Fonts 4 §2.8) +struct ParserFontShorthandTests { + + private typealias Longhands = [String] + + private func longhands(_ value: String) -> Longhands? { + XMLParser.parseFontShorthand(value)?.map { "\($0.name): \($0.value)" } + } + + @Test(arguments: [ + // matplotlib's SVG output with svg.fonttype='none' + ("12px 'DejaVu Sans'", ["normal", "normal", "12px", "'DejaVu Sans'"]), + ("italic bold 20px/1.5 Helvetica, sans-serif", ["italic", "bold", "20px", "Helvetica, sans-serif"]), + ("bold italic 20px serif", ["italic", "bold", "20px", "serif"]), + ("small-caps 650 condensed 2em monospace", ["normal", "650", "2em", "monospace"]), + ("oblique 10deg 12px serif", ["oblique", "normal", "12px", "serif"]), + ("normal normal 12px serif", ["normal", "normal", "12px", "serif"]), + ("12px / 2 serif", ["normal", "normal", "12px", "serif"]), + ("12px/ 2 serif", ["normal", "normal", "12px", "serif"]), + ("12px /2 serif", ["normal", "normal", "12px", "serif"]), + ("x-large \"Times New Roman\"", ["normal", "normal", "x-large", "\"Times New Roman\""]), + ("0 serif", ["normal", "normal", "0", "serif"]), + // system fonts + ("menu", ["normal", "normal", "13px", "sans-serif"]), + ("Caption", ["normal", "normal", "13px", "sans-serif"]), + ] as [(String, [String])]) + func expandsToLonghands(value: String, expected: [String]) { + let names = ["font-style", "font-weight", "font-size", "font-family"] + #expect(longhands(value) == zip(names, expected).map { "\($0): \($1)" }) + } + + @Test(arguments: [ + "", "serif", "12px", "bold serif", "-12px serif", "12px/ serif", "big serif", + "italic italic 12px serif", "normal normal normal normal normal 12px serif", "inherit" + ]) + func rejectsInvalidValues(value: String) { + #expect(longhands(value) == nil) + } + + private func element(_ body: String) throws -> DOM.GraphicsElement { + let svg = try DOM.SVG.parse(xml: """ + \(body) + """) + return try #require(svg.childElements.last) + } + + @Test + func styleAttributeSetsTheLonghands() throws { + let text = try element(#"a"#) + #expect(text.style.fontStyle == .italic) + #expect(text.style.fontWeight == .bold) + #expect(text.style.fontSize == .length(12)) + #expect(text.style.fontFamily == [.name("DejaVu Sans")]) + } + + // parts left out are reset to their initial values, overriding inherited and earlier ones + @Test + func resetsTheOmittedParts() throws { + let text = try element(#"a"#) + #expect(text.style.fontWeight == .normal) + #expect(text.style.fontStyle == .normal) + } + + @Test + func laterLonghandOverridesTheShorthand() throws { + let text = try element(#"a"#) + #expect(text.style.fontWeight == .bold) + #expect(text.style.fontSize == .length(12)) + } + + @Test + func invalidShorthandIsIgnored() throws { + let text = try element(#"a"#) + #expect(text.style.fontSize == .length(10)) + #expect(text.style.fontWeight == nil) + } + + @Test + func stylesheetRuleSetsTheLonghands() throws { + let text = try element(#"a"#) + let matched = try #require(text.matchedStyle) + #expect(matched.attributes.fontWeight == .bold) + #expect(matched.attributes.fontSize == .length(30)) + #expect(matched.attributes.fontFamily == [.keyword(.monospace)]) + } + + // SVG 2 §6.6: shorthands are not presentation attributes + @Test + func isNotAPresentationAttribute() throws { + let text = try element(#"a"#) + #expect(text.attributes.fontSize == nil) + #expect(text.attributes.fontWeight == nil) + } + + // em lengths of the element resolve against the shorthand's size + @Test + func sizeSetsTheFontSizeOfEmLengths() throws { + let text = try #require(try element(#"a"#) as? DOM.Text) + #expect(text.x == 40) + } +} diff --git a/Samples.bundle/text-filter.svg b/Samples.bundle/text-filter.svg new file mode 100644 index 00000000..70148f8a --- /dev/null +++ b/Samples.bundle/text-filter.svg @@ -0,0 +1,29 @@ + + + + + + + + + + + Text + Text + Text + Text + + + + grouped + + + grouped + + Shadow + + + + Abg + + diff --git a/Samples.bundle/text-font-shorthand.svg b/Samples.bundle/text-font-shorthand.svg new file mode 100644 index 00000000..270946d1 --- /dev/null +++ b/Samples.bundle/text-font-shorthand.svg @@ -0,0 +1,33 @@ + + + + + font: shorthand + + + + + + + + + 0 + 1 + 2 + 3 + 4 + 0.0 + 0.5 + 1.0 + 1.5 + + time (s) + value + + overridden + invalid font + + diff --git a/SwiftDraw/Sources/LayerTree/LayerTree.Builder.Text.swift b/SwiftDraw/Sources/LayerTree/LayerTree.Builder.Text.swift index e1336130..e11386aa 100644 --- a/SwiftDraw/Sources/LayerTree/LayerTree.Builder.Text.swift +++ b/SwiftDraw/Sources/LayerTree/LayerTree.Builder.Text.swift @@ -699,7 +699,7 @@ extension LayerTree.Builder { let ascent = LayerTree.Float(CTFontGetAscent(font)) let descent = LayerTree.Float(CTFontGetDescent(font)) switch baseline { - case .auto, .alphabetic: + case .auto, .alphabetic, .inherit: return 0 case .textBeforeEdge: return ascent diff --git a/SwiftDraw/Sources/LayerTree/LayerTree.Builder.swift b/SwiftDraw/Sources/LayerTree/LayerTree.Builder.swift index 31478dd4..f23e849f 100644 --- a/SwiftDraw/Sources/LayerTree/LayerTree.Builder.swift +++ b/SwiftDraw/Sources/LayerTree/LayerTree.Builder.swift @@ -230,10 +230,12 @@ extension LayerTree { } func makeLayer(from root: DOM.GraphicsElement, inheriting previousState: State) -> Layer { - var stack: [(DOM.GraphicsElement, State, Layer?)] = [(root, previousState, nil)] + // `isFiltered`: the element or an ancestor has a filter, so text measures its bounding box + // for an objectBoundingBox filter region + var stack: [(DOM.GraphicsElement, State, Layer?, isFiltered: Bool)] = [(root, previousState, nil, false)] var resultLayer: Layer? = nil - while let (currentElement, currentState, parentLayer) = stack.popLast() { + while let (currentElement, currentState, parentLayer, parentIsFiltered) = stack.popLast() { // a is only drawn as the root of a that references it if currentElement is DOM.Symbol, parentLayer != nil { continue @@ -257,12 +259,16 @@ extension LayerTree { continue } + let isFiltered = parentIsFiltered || !layer.filters.isEmpty if let contents = makeContents(from: currentElement, with: newState) { contentLayer.appendContents(contents) + if isFiltered, let text = currentElement as? DOM.Text { + contentLayer.textBounds = makeTextBounds(for: text, with: newState) + } } else if let container = currentElement as? any ContainerElement { // Push children in reverse so they are processed in the original order for child in container.childElements.reversed() { - stack.append((child, newState, contentLayer)) + stack.append((child, newState, contentLayer, isFiltered)) } } @@ -743,27 +749,30 @@ extension LayerTree.Builder { return [] } let candidates = faces.filter { $0.style == bestStyle } - - // lower is better: (tier, distance) where tier orders the search directions of §5.2 step 4 - func rank(_ range: ClosedRange) -> (Int, Int) { - if range.contains(weight) { return (0, 0) } - let below = range.upperBound < weight - let distance = below ? weight - range.upperBound : range.lowerBound - weight - switch weight { - case 400...500: - // heavier up to 500, then lighter, then heavier past 500 - if !below && range.lowerBound <= 500 { return (1, distance) } - return below ? (2, distance) : (3, distance) - case ..<400: - return below ? (1, distance) : (2, distance) - default: - return below ? (2, distance) : (1, distance) - } - } + func rank(_ range: ClosedRange) -> (Int, Int) { fontWeightRank(range, for: weight) } guard let best = candidates.map({ rank($0.weight) }).min(by: { $0 < $1 }) else { return [] } return candidates.filter { rank($0.weight) == best } } + /// How well a face of `weights` matches the desired `weight` in CSS Fonts 4 §5.2 step 4; lower + /// is better: (tier, distance), where the tier orders the directions searched. Between 400 and + /// 500, heavier faces up to 500 come first, then lighter, then heavier; below 400 lighter first; + /// above 500 heavier first. + static func fontWeightRank(_ weights: ClosedRange, for weight: Int) -> (Int, Int) { + if weights.contains(weight) { return (0, 0) } + let below = weights.upperBound < weight + let distance = below ? weight - weights.upperBound : weights.lowerBound - weight + switch weight { + case 400...500: + if !below && weights.lowerBound <= 500 { return (1, distance) } + return below ? (2, distance) : (3, distance) + case ..<400: + return below ? (1, distance) : (2, distance) + default: + return below ? (2, distance) : (1, distance) + } + } + /// The bold and oblique an `@font-face` face needs synthesized, from its declared `font-weight` and /// `font-style` (not the font file's own): bold when 600 or heavier is asked for and the face is /// lighter, oblique when italic or oblique is asked for and the face is normal. @@ -1281,8 +1290,12 @@ extension LayerTree.Builder { state.fontWeight = attributes.fontWeight?.resolved(inheriting: existing.fontWeight) ?? existing.fontWeight 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.textBaseline = attributes.dominantBaseline.flatMap { $0 == .inherit ? nil : $0 } ?? existing.textBaseline + switch attributes.alignmentBaseline { + case .auto?, nil: state.alignmentBaseline = nil + case .inherit?: state.alignmentBaseline = existing.alignmentBaseline + case let baseline?: state.alignmentBaseline = baseline + } 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 diff --git a/SwiftDraw/Sources/LayerTree/LayerTree.CommandGenerator.swift b/SwiftDraw/Sources/LayerTree/LayerTree.CommandGenerator.swift index 89d62dbc..4d1f9a73 100644 --- a/SwiftDraw/Sources/LayerTree/LayerTree.CommandGenerator.swift +++ b/SwiftDraw/Sources/LayerTree/LayerTree.CommandGenerator.swift @@ -1044,11 +1044,22 @@ extension LayerTree.CommandGenerator { } // Geometry bounding box of the layer contents in the layer's user space; stroke excluded. - // nil when the contents include text, which is not measured: the filter is then dropped - // rather than clipping the text away. + // Text counts with the box the builder measured for it (`textBounds`); nil when the contents + // include text that was not measured: the filter is then dropped rather than clipping the text away. func makeBounds(for layer: LayerTree.Layer) -> LayerTree.Rect? { - guard !layer.containsText else { return nil } var points = [LayerTree.Point]() + guard appendBounds(of: layer, to: &points, isTextMeasured: false), !points.isEmpty else { return nil } + return .makeBounds(between: points) + } + + /// Appends the corners of the layer's contents; false when it draws text without a measured box. + /// - Parameter isTextMeasured: an ancestor's `textBounds` already covers the text of this layer + private func appendBounds(of layer: LayerTree.Layer, to points: inout [LayerTree.Point], isTextMeasured: Bool) -> Bool { + var isTextMeasured = isTextMeasured + if let bounds = layer.textBounds { + points.append(contentsOf: bounds.corners) + isTextMeasured = true + } for contents in layer.contents { switch contents { case .shape(let shape, _, _): @@ -1060,16 +1071,15 @@ extension LayerTree.CommandGenerator { points.append(contentsOf: LayerTree.Rect(x: image.origin.x, y: image.origin.y, width: width, height: height).corners) } case .text, .glyphs: - break + guard isTextMeasured else { return false } case .layer(let child): - if let rect = makeBounds(for: child) { - let matrix = child.transform.toMatrix() - points.append(contentsOf: rect.corners.map { matrix.transform(point: $0) }) - } + var childPoints = [LayerTree.Point]() + guard appendBounds(of: child, to: &childPoints, isTextMeasured: isTextMeasured) else { return false } + let matrix = child.transform.toMatrix() + points.append(contentsOf: childPoints.map { matrix.transform(point: $0) }) } } - guard !points.isEmpty else { return nil } - return .makeBounds(between: points) + return true } func logUnsupportedFilters(_ filters: [LayerTree.FilterPrimitive]) { diff --git a/SwiftDraw/Sources/LayerTree/LayerTree.Layer.swift b/SwiftDraw/Sources/LayerTree/LayerTree.Layer.swift index 9a664d15..2c049b66 100644 --- a/SwiftDraw/Sources/LayerTree/LayerTree.Layer.swift +++ b/SwiftDraw/Sources/LayerTree/LayerTree.Layer.swift @@ -52,6 +52,9 @@ extension LayerTree { /// The contents are one shape's fill, stroke and markers in a `paint-order` other than the /// default, with the shape split into a fill-only and a stroke-only `.shape`. var isPaintOrdered = false + /// The bounding box of the text this layer draws, in its user space (SVG 2 §8.10), where a + /// filter needs it for an objectBoundingBox region. nil when not measured. + var textBounds: Rect? enum MaskType: Hashable { case luminance @@ -92,7 +95,8 @@ extension LayerTree { clip == [], mask == nil, filters == [], - filterImages.isEmpty else { return nil } + filterImages.isEmpty, + textBounds == nil else { return nil } return first } @@ -110,6 +114,7 @@ extension LayerTree { filterRegion.hash(into: &hasher) filterImages.hash(into: &hasher) isPaintOrdered.hash(into: &hasher) + textBounds.hash(into: &hasher) } static func ==(lhs: Layer, rhs: Layer) -> Bool { @@ -126,7 +131,8 @@ extension LayerTree { lhs.filters == rhs.filters && lhs.filterRegion == rhs.filterRegion && lhs.filterImages == rhs.filterImages && - lhs.isPaintOrdered == rhs.isPaintOrdered + lhs.isPaintOrdered == rhs.isPaintOrdered && + lhs.textBounds == rhs.textBounds } } diff --git a/SwiftDraw/Sources/Renderer/Renderer.CoreGraphics.swift b/SwiftDraw/Sources/Renderer/Renderer.CoreGraphics.swift index 68a6eaa3..d8c744b1 100644 --- a/SwiftDraw/Sources/Renderer/Renderer.CoreGraphics.swift +++ b/SwiftDraw/Sources/Renderer/Renderer.CoreGraphics.swift @@ -369,10 +369,56 @@ struct CGProvider: RendererTypeProvider { return postScriptName } - /// The face of a system font family closest to a CSS weight and slant, as CoreText matches it - /// (e.g. Helvetica 700 is Helvetica-Bold, 300 is Helvetica-Light, italic is Helvetica-Oblique). - /// Within `fontLookup`. + /// The face of a system font family closest to a CSS weight and slant (e.g. Helvetica 700 is + /// Helvetica-Bold, 300 is Helvetica-Light, italic is Helvetica-Oblique). Faces of normal width are + /// matched as CSS Fonts 4 §5.2 does: slant first, then weight (650 picks a bold face over a + /// semibold one). Within `fontLookup`. private static func createCTFont(family: String, size: CGFloat, weight: Int, isItalic: Bool) -> CTFont? { + if let descriptor = matchFace(family: family, weight: weight, isItalic: isItalic) { + return CTFontCreateWithFontDescriptor(descriptor, size, nil) + } + return createCTFontByTraits(family: family, size: size, weight: weight, isItalic: isItalic) + } + + /// CSS font matching over the installed faces of a family; nil when CoreText lists none. + private static func matchFace(family: String, weight: Int, isItalic: Bool) -> CTFontDescriptor? { + let request = CTFontDescriptorCreateWithAttributes([kCTFontFamilyNameAttribute: family] as CFDictionary) + guard let matches = CTFontDescriptorCreateMatchingFontDescriptors(request, nil) as? [CTFontDescriptor] else { + return nil + } + let faces = matches.compactMap { descriptor -> (descriptor: CTFontDescriptor, weight: Int, isItalic: Bool, width: CGFloat)? in + guard CTFontDescriptorCopyAttribute(descriptor, kCTFontFamilyNameAttribute) as? String == family, + let traits = CTFontDescriptorCopyAttribute(descriptor, kCTFontTraitsAttribute) as? [CFString: Any] else { + return nil + } + let coreTextWeight = (traits[kCTFontWeightTrait] as? NSNumber).map { CGFloat($0.doubleValue) } ?? 0 + let width = (traits[kCTFontWidthTrait] as? NSNumber).map { CGFloat($0.doubleValue) } ?? 0 + let symbolic = (traits[kCTFontSymbolicTrait] as? NSNumber).map { CTFontSymbolicTraits(rawValue: $0.uint32Value) } ?? [] + return (descriptor, cssWeight(for: coreTextWeight), symbolic.contains(.traitItalic), width) + } + // font-stretch: normal, the narrowest distance from the normal width + guard let bestWidth = faces.map({ abs($0.width) }).min() else { return nil } + let normalWidth = faces.filter { abs($0.width) == bestWidth } + // font-style: italic and oblique faces are both italic to CoreText; else the other slant + let slanted = normalWidth.filter { $0.isItalic == isItalic } + let candidates = slanted.isEmpty ? normalWidth : slanted + return candidates.min { + LayerTree.Builder.fontWeightRank($0.weight...$0.weight, for: weight) < + LayerTree.Builder.fontWeightRank($1.weight...$1.weight, for: weight) + }?.descriptor + } + + /// The CSS weight of a CoreText weight trait, the inverse of `coreTextWeight(for:)` + static func cssWeight(for coreTextWeight: CGFloat) -> Int { + let points = coreTextWeightPoints + let w = min(max(coreTextWeight, -1), 1) + guard let upper = points.firstIndex(where: { $0.ct >= w }), upper > 0 else { return Int(points[0].css) } + let (a, b) = (points[upper - 1], points[upper]) + return Int((a.css + (b.css - a.css) * (w - a.ct) / (b.ct - a.ct)).rounded()) + } + + /// The face CoreText matches to the weight and slant traits + private static func createCTFontByTraits(family: String, size: CGFloat, weight: Int, isItalic: Bool) -> CTFont? { var traits: [CFString: Any] = [kCTFontWeightTrait: coreTextWeight(for: weight)] if isItalic { traits[kCTFontSymbolicTrait] = CTFontSymbolicTraits.traitItalic.rawValue @@ -390,16 +436,18 @@ struct CGProvider: RendererTypeProvider { /// CSS weights (1–1000) on CoreText's weight trait (−1…1), at the points of `NSFont.Weight` /// (ultraLight 100 … black 900), interpolated between them. static func coreTextWeight(for weight: Int) -> CGFloat { - let points: [(css: CGFloat, ct: CGFloat)] = [ - (1, -1), (100, -0.8), (200, -0.6), (300, -0.4), (400, 0), - (500, 0.23), (600, 0.3), (700, 0.4), (800, 0.56), (900, 0.62), (1000, 1) - ] + let points = coreTextWeightPoints let w = min(max(CGFloat(weight), 1), 1000) guard let upper = points.firstIndex(where: { $0.css >= w }), upper > 0 else { return points[0].ct } let (a, b) = (points[upper - 1], points[upper]) return a.ct + (b.ct - a.ct) * (w - a.css) / (b.css - a.css) } + private static let coreTextWeightPoints: [(css: CGFloat, ct: CGFloat)] = [ + (1, -1), (100, -0.8), (200, -0.6), (300, -0.4), (400, 0), + (500, 0.23), (600, 0.3), (700, 0.4), (800, 0.56), (900, 0.62), (1000, 1) + ] + static func createCTFont(for attributes: LayerTree.TextAttributes) -> CTFont { createFont(for: attributes).font } diff --git a/SwiftDraw/Tests/LayerTree/LayerTree.FilterTests.swift b/SwiftDraw/Tests/LayerTree/LayerTree.FilterTests.swift index 24f6f212..c7f7a070 100644 --- a/SwiftDraw/Tests/LayerTree/LayerTree.FilterTests.swift +++ b/SwiftDraw/Tests/LayerTree/LayerTree.FilterTests.swift @@ -204,13 +204,15 @@ struct LayerTreeFilterTests { ]) } - // text has no measured bounds: drawn unfiltered, neither warned about nor hidden as unsupported + // SVG 2 §8.10: the objectBoundingBox filter region of text is that of its glyph cells, measured + // with CoreText; without it text has no bounds and is drawn unfiltered, neither warned about nor + // hidden as unsupported @Test - func textWithObjectBoundingBoxBlurIsDrawnUnfiltered() throws { + func textWithObjectBoundingBoxBlurIsFilteredByItsBoundingBox() throws { let svg = try DOM.SVG.parse(xml: #""" - Hi + Hi """#) let root = LayerTree.Builder(svg: svg).makeLayer() @@ -218,24 +220,53 @@ struct LayerTreeFilterTests { let generator = LayerTree.CommandGenerator(provider: LayerTreeProvider(), size: .init(100, 100), options: .hideUnsupportedFilters) #expect(!layer.hasUnsupportedFilters) + #if canImport(CoreText) + let bounds = try #require(layer.textBounds) + #expect(bounds.x == 10) + #expect(bounds.y < 50 && bounds.y + bounds.height > 50) + let filter = try #require(generator.makeFilterLayer(for: layer)) + #expect(filter.region == LayerTree.Rect( + x: bounds.x - 0.1 * bounds.width, y: bounds.y - 0.1 * bounds.height, + width: 1.2 * bounds.width, height: 1.2 * bounds.height + )) + #else #expect(generator.makeFilterLayer(for: layer) == nil) + #endif } - // a group mixing shapes and text has unknown bounds: draw it unfiltered rather than clip the text away + // a group mixing shapes and text: its box includes the text's, so the text is not clipped away @Test - func groupWithTextIsDrawnUnfiltered() throws { + func groupWithTextIsFilteredByTheUnionOfItsContents() throws { let commands = try makeCommands(#""" - - + + - Hello + Hello """#, options: .hideUnsupportedFilters) + #if canImport(CoreText) + let region = try #require(commands.filterLayers.first?.region) + #expect(region.x == 10 && region.y == 10) + #expect(region.width > 10 && region.y + region.height > 80) + #else #expect(commands.filterLayers.isEmpty) #expect(commands.names.prefix(2) == ["setFillColor", "fillPath"]) + #endif + } + + // the text's own box is not measured where no filter needs it + @Test + func textIsOnlyMeasuredUnderAFilter() throws { + let svg = try DOM.SVG.parse(xml: #""" + + Hi + + """#) + let root = LayerTree.Builder(svg: svg).makeLayer() + #expect(root.allLayers.allSatisfy { $0.textBounds == nil }) } @Test diff --git a/SwiftDraw/Tests/LayerTree/LayerTree.FontWeightTests.swift b/SwiftDraw/Tests/LayerTree/LayerTree.FontWeightTests.swift index a8911329..02a6d27f 100644 --- a/SwiftDraw/Tests/LayerTree/LayerTree.FontWeightTests.swift +++ b/SwiftDraw/Tests/LayerTree/LayerTree.FontWeightTests.swift @@ -152,6 +152,32 @@ struct CGProviderFontWeightTests { #expect(postScriptName("NoSuchFamily", weight: 700) == "Times-Bold") } + // CSS Fonts 4 §5.2 over the installed faces, not CoreText's nearest weight trait + @Test(arguments: [ + (450, "HelveticaNeue-Medium"), // 400–500: heavier up to 500 first + (550, "HelveticaNeue-Bold"), // above 500: heavier first, not the nearer Medium + (650, "HelveticaNeue-Bold"), + (350, "HelveticaNeue-Light"), // below 400: lighter first + (900, "HelveticaNeue-Bold"), // nothing heavier of normal width: lighter, not CondensedBlack + ] as [(Int, String)]) + func systemFamilyFaceIsMatchedLikeCSS(weight: Int, expected: String) { + #expect(postScriptName("Helvetica Neue", weight: weight) == expected) + } + + @Test + func systemFamilyFaceKeepsSlantBeforeWeight() { + #expect(postScriptName("Helvetica Neue", weight: 550, italic: true) == "HelveticaNeue-BoldItalic") + // Times has no light face: 300 has nothing lighter, so the regular + #expect(postScriptName("Times", weight: 300) == "Times-Roman") + } + + @Test + func cssWeightInvertsCoreTextWeight() { + for weight in [1, 100, 300, 400, 450, 500, 650, 700, 900, 1000] { + #expect(CGProvider.cssWeight(for: CGProvider.coreTextWeight(for: weight)) == weight) + } + } + @Test func coreTextWeightScale() { #expect(CGProvider.coreTextWeight(for: 400) == 0) diff --git a/SwiftDraw/Tests/LayerTree/LayerTree.TextBaselineTests.swift b/SwiftDraw/Tests/LayerTree/LayerTree.TextBaselineTests.swift index a9a24b0c..eca09d47 100644 --- a/SwiftDraw/Tests/LayerTree/LayerTree.TextBaselineTests.swift +++ b/SwiftDraw/Tests/LayerTree/LayerTree.TextBaselineTests.swift @@ -84,11 +84,32 @@ struct LayerTreeTextBaselineTests { #expect(DOM.TextBaseline(css: value) == expected) } - @Test(arguments: ["inherit", "no-change", "reset-size", "top", ""]) + @Test(arguments: ["no-change", "reset-size", "top", ""]) func baselinesThatKeepTheParentsAreNotParsed(value: String) { #expect(DOM.TextBaseline(css: value) == nil) } + @Test + func inheritIsParsed() { + #expect(DOM.TextBaseline(css: " INHERIT ") == .inherit) + } + + // alignment-baseline is not inherited, but `inherit` takes the parent's + @Test + func alignmentBaselineInheritTakesTheParents() throws { + let states = try runStates(#"A"#) + #expect(states.map(\.alignmentBaseline) == [.hanging]) + let plain = try runStates(#"A"#) + #expect(plain.map(\.alignmentBaseline) == [nil]) + } + + // dominant-baseline is inherited anyway: `inherit` keeps the parent's + @Test + func dominantBaselineInheritKeepsTheParents() throws { + let states = try runStates(#"A"#) + #expect(states.map(\.textBaseline) == [.central]) + } + @Test(arguments: [ ("baseline", DOM.BaselineShift.baseline), ("sub", .sub), ("super", .super), ("inherit", .inherit), ("10", .length(.absolute(10))), ("-2mm", .length(.absolute(-2 * 96 / 25.4))),