diff --git a/.github/workflows/swift.yml b/.github/workflows/swift.yml index 51d684c..ffe1d53 100644 --- a/.github/workflows/swift.yml +++ b/.github/workflows/swift.yml @@ -28,11 +28,11 @@ jobs: WEBKIT_DISABLE_SANDBOX_THIS_IS_DANGEROUS: 1 steps: - uses: actions/checkout@v4 - - name: Install Cairo, FreeType, fontconfig and Wayland for Cacao, Mesa for GL, WPE WebKit, and GStreamer + - name: Install Cairo, FreeType, fontconfig and Wayland for Cacao, HarfBuzz for fonts, Mesa for GL, WPE WebKit, and GStreamer run: | apt-get update apt-get install -y --no-install-recommends cmake ninja-build git libcairo2-dev libfreetype-dev \ - libfontconfig-dev libwayland-dev wayland-protocols fonts-dejavu-core \ + libfontconfig-dev libharfbuzz-dev libwayland-dev wayland-protocols fonts-dejavu-core \ libegl1 libegl-mesa0 libgles-dev libgl1-mesa-dri \ libwpewebkit-2.0-1 libwpebackend-fdo-1.0-1 libwayland-server0 \ libgstreamer1.0-0 libgstreamer-plugins-base1.0-0 gstreamer1.0-plugins-base gstreamer1.0-plugins-good \ diff --git a/Dockerfile b/Dockerfile index 12de5c4..620e90f 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,5 +1,6 @@ # Linux environment for building and testing the host: Swift 6.4.2 on # Debian 13, SDL3, Cairo, FreeType, fontconfig and Wayland for Cacao, a font, +# HarfBuzz for fonts, # Mesa's EGL and GLES 2.0 for GL surfaces (llvmpipe without a GPU), WPE WebKit # and its FreeDesktop.org backend for web views and GStreamer for media, which # the host loads at run time, Python for AppRuntime's scripts, and WABT for its @@ -11,7 +12,7 @@ FROM swift:6.4.2-trixie RUN apt-get update \ && apt-get install -y --no-install-recommends \ - cmake ninja-build git libfontconfig-dev fonts-dejavu-core \ + cmake ninja-build git libfontconfig-dev libharfbuzz-dev fonts-dejavu-core \ libcairo2-dev libfreetype-dev libwayland-dev wayland-protocols \ libegl1 libegl-mesa0 libgles-dev libgl1-mesa-dri \ libwpewebkit-2.0-1 libwpebackend-fdo-1.0-1 libwayland-server0 \ diff --git a/Package.swift b/Package.swift index acd7588..a481926 100644 --- a/Package.swift +++ b/Package.swift @@ -83,6 +83,7 @@ let package = Package( .library(name: "LinuxMotion", targets: ["LinuxMotion"]), .library(name: "LinuxNFC", targets: ["LinuxNFC"]), .library(name: "LinuxMedia", targets: ["LinuxMedia"]), + .library(name: "LinuxFonts", targets: ["LinuxFonts"]), .library(name: "LinuxHostApp", targets: ["LinuxHostApp"]), .executable(name: "linux-app-host", targets: ["LinuxAppHost"]), .executable(name: "linux-app", targets: ["LinuxAppTool"]), @@ -92,8 +93,9 @@ let package = Package( cacao, webKit, // D-Bus, in Swift without libdbus, which Bluetooth talks to BlueZ - // over, and Location to GeoClue; it has no releases. - .package(url: "https://github.com/PureSwift/DBus.git", revision: "d34567d64bb553a35e5b263f344c6963a5170ca3"), + // over, and Location to GeoClue. 0.3.1 is the release Cacao needs, + // with the StatusNotifier service. + .package(url: "https://github.com/PureSwift/DBus.git", from: "0.3.1"), .package(url: "https://github.com/apple/swift-argument-parser.git", from: "1.5.0"), // SHA-256, for bundles' CodeResources. .package(url: "https://github.com/apple/swift-crypto.git", "3.0.0"..<"5.0.0"), @@ -104,6 +106,11 @@ let package = Package( .package(url: "https://github.com/PureSwift/CoreModel-SQLite.git", branch: "master"), .package(url: "https://github.com/PureSwift/CoreModel.git", branch: "master"), .package(url: "https://github.com/PureSwift/SQLite.git", from: "0.2.2"), + // Fonts: faces, images and outlines from FreeType, shaping from + // HarfBuzz, and finding fonts and fallbacks with Fontconfig. + .package(url: "https://github.com/PureSwift/swift-freetype.git", from: "0.1.1"), + .package(url: "https://github.com/PureSwift/swift-harfbuzz.git", from: "0.1.1"), + .package(url: "https://github.com/PureSwift/FontConfig.git", from: "2.0.0"), ], targets: [ @@ -246,6 +253,20 @@ let package = Package( swiftSettings: host ), + // MARK: - Fonts + + // The platform's fonts, for a guest that draws text itself. + .target( + name: "LinuxFonts", + dependencies: [ + "LinuxHost", runtime("DynamicFonts"), runtime("RuntimeFonts"), runtime("DynamicRuntime"), runtime("RuntimeHost"), + .product(name: "FreeTypeSwift", package: "swift-freetype"), + .product(name: "HarfBuzzSwift", package: "swift-harfbuzz"), + .product(name: "FontConfig", package: "FontConfig"), + ], + swiftSettings: host + ), + // MARK: - App // What the runner's process supplies that libc may not @@ -253,7 +274,7 @@ let package = Package( .target(name: "CLinuxHost"), .target( name: "LinuxHostApp", - dependencies: ["LinuxHost", "LinuxUI", "LinuxBluetooth", "LinuxGraphics", "LinuxWebKit", "LinuxCoreModel", "LinuxDevice", "LinuxLocation", "LinuxDocuments", "LinuxMotion", "LinuxNFC", "LinuxMedia", "CLinuxHost", runtime("CRuntime"), runtime("RuntimeFormatting"), runtime("RuntimeNetworking"), + dependencies: ["LinuxHost", "LinuxUI", "LinuxBluetooth", "LinuxGraphics", "LinuxWebKit", "LinuxCoreModel", "LinuxDevice", "LinuxLocation", "LinuxDocuments", "LinuxMotion", "LinuxNFC", "LinuxMedia", "LinuxFonts", "CLinuxHost", runtime("CRuntime"), runtime("RuntimeFormatting"), runtime("RuntimeNetworking"), runtime("DynamicGraphics"), .product(name: "CacaoSDL", package: "Cacao")], swiftSettings: host ), @@ -277,7 +298,7 @@ let package = Package( // doesn't build Cacao. .target( name: "LinuxPackager", - dependencies: ["LinuxHost", "LinuxBluetooth", "LinuxGraphics", "LinuxWebKit", "LinuxCoreModel", "LinuxDevice", "LinuxLocation", "LinuxDocuments", "LinuxMotion", "LinuxNFC", "LinuxMedia", runtime("RuntimeFormatting"), runtime("RuntimeNetworking"), runtime("DynamicUI"), + dependencies: ["LinuxHost", "LinuxBluetooth", "LinuxGraphics", "LinuxWebKit", "LinuxCoreModel", "LinuxDevice", "LinuxLocation", "LinuxDocuments", "LinuxMotion", "LinuxNFC", "LinuxMedia", "LinuxFonts", runtime("RuntimeFormatting"), runtime("RuntimeNetworking"), runtime("DynamicUI"), .product(name: "Crypto", package: "swift-crypto")] ), .executableTarget( @@ -316,6 +337,8 @@ let package = Package( swiftSettings: host), .testTarget(name: "LinuxMediaTests", dependencies: ["LinuxMedia", runtime("DynamicMedia"), runtime("RuntimeMedia"), runtime("RuntimeHost")], swiftSettings: host), + .testTarget(name: "LinuxFontsTests", dependencies: ["LinuxFonts", runtime("DynamicFonts"), runtime("RuntimeFonts"), runtime("DynamicRuntime")], + resources: [.copy("Fixtures")], swiftSettings: host), .testTarget(name: "LinuxMotionTests", dependencies: ["LinuxMotion", runtime("DynamicMotion")], swiftSettings: host), .testTarget(name: "LinuxWebKitTests", dependencies: ["LinuxWebKit", runtime("DynamicWebKit"), .product(name: "WPEWebKit", package: "WebKit")], swiftSettings: host), diff --git a/README.md b/README.md index 392676e..70352c9 100644 --- a/README.md +++ b/README.md @@ -66,19 +66,20 @@ added to its database between launches: | `LinuxMotion` | Motion: the accelerometer, gyroscope, magnetometer and barometer from the kernel's IIO sensors in sysfs, device motion fused from them, and a pedometer and activity recognizer that are unavailable ([plan](Documentation/Plan.md) §13) | | `LinuxNFC` | `NFCReader`, `NFCTag`, `NDEFMessage`, `NDEFRecord`: reading and writing NDEF tags through neard on the system bus; no raw commands or locking ([plan](Documentation/Plan.md) §14) | | `LinuxMedia` | `MediaPlayback`: songs and videos through GStreamer's `playbin`, opened at run time, from files, bytes or URLs; the player's `VideoPlayer` view shows the pictures, with play, pause and a scrubber ([plan](Documentation/Plan.md) §15) | +| `LinuxFonts` | `FontFace`: the system's fonts and the bundle's for a guest that draws text itself (glyphs, shaped lines, glyph images, outlines): FreeType, HarfBuzz and Fontconfig, through AppRuntime's `HostFontFace` | | `LinuxHostApp`, `linux-app-host` | The app's `main`: the host, and Cacao's window and loop. It also registers AppRuntime's `RuntimeFormatting`, dates and numbers over Swift Foundation, and `RuntimeNetworking`, HTTP over `URLSession` and libcurl ([plan](Documentation/Plan.md) §3) | | `LinuxPackager`, `linux-app` | The packager: validation, thinning a bundle to one target, the install tree, PortMaster ports | ## Building Swift 6.4.2 (`.swift-version`) on Debian 13; SDL 3.4, Cairo, FreeType, -fontconfig and Wayland for Cacao; EGL and GLES 2.0, which GL surfaces load +fontconfig and Wayland for Cacao; HarfBuzz for fonts; EGL and GLES 2.0, which GL surfaces load at run time and apps that draw link (Mesa's draw without a GPU); WPE WebKit, which web views load at run time; and GStreamer, with its base and good plugins and libav's decoders, which media players load at run time: ```sh -apt-get install cmake ninja-build git libcairo2-dev libfreetype-dev libfontconfig-dev \ +apt-get install cmake ninja-build git libcairo2-dev libfreetype-dev libfontconfig-dev libharfbuzz-dev \ libwayland-dev wayland-protocols fonts-dejavu-core \ libegl1 libegl-mesa0 libgles-dev libgl1-mesa-dri \ libwpewebkit-2.0-1 libwpebackend-fdo-1.0-1 libwayland-server0 \ diff --git a/Sources/LinuxBluetooth/BlueZBus.swift b/Sources/LinuxBluetooth/BlueZBus.swift index 07c7e82..aad897c 100644 --- a/Sources/LinuxBluetooth/BlueZBus.swift +++ b/Sources/LinuxBluetooth/BlueZBus.swift @@ -71,28 +71,14 @@ enum BlueZInterface { // MARK: - Values /// BlueZ's values; the rest are LinuxDBus's (`text`, `flag`, `entries`, -/// `vardict`). +/// `vardict`) and DBus's (`intValue`, `bytes`, `byteArray`). public extension DBusMessageArgument { - var intValue: Int? { - int64Value.map(Int.init) - } - - /// `ay`. - var bytes: [UInt8]? { - elements?.compactMap { if case .byte(let byte) = $0.contents { byte } else { nil } } - } - /// `as` or `ao`. var strings: [String] { elements?.compactMap(\.text) ?? [] } - /// `ay`. - static func byteArray(_ bytes: [UInt8]) -> DBusMessageArgument { - .list(of: .byte, bytes.map { .byte($0) }) - } - /// `a{sa{sv}}` as interfaces and their properties. func interfaces() -> BlueZInterfaces { var interfaces: BlueZInterfaces = [:] diff --git a/Sources/LinuxFonts/FreeTypeFontEngine.swift b/Sources/LinuxFonts/FreeTypeFontEngine.swift new file mode 100644 index 0000000..7353311 --- /dev/null +++ b/Sources/LinuxFonts/FreeTypeFontEngine.swift @@ -0,0 +1,402 @@ +import CFontConfig +import DynamicFonts +import FreeTypeSwift +import HarfBuzzSwift +import RuntimeFonts + +// FreeType has its own types by these names. +typealias GlyphOutline = DynamicFonts.GlyphOutline +typealias GlyphImage = DynamicFonts.GlyphImage + +/// Fonts over FreeType, HarfBuzz and Fontconfig: the Linux host's engine, +/// and any other host's that has those libraries. +/// +/// ```swift +/// HostFontFace.engine = FreeTypeFontEngine() +/// HostFontsModule.register(in: runtime) +/// ``` +/// +/// Fontconfig finds fonts by name and the fallbacks for characters a face +/// lacks; FreeType gives metrics, images and outlines; HarfBuzz shapes. +/// Main thread only. +/// +/// A line whose first run is right to left is laid out right to left, run +/// by run; a line that mixes directions isn't reordered as a bidi algorithm +/// would. +public final class FreeTypeFontEngine: FontEngine { + + let library: FreeTypeLibrary + + /// The faces in registered files, by normalized PostScript, family and + /// full name. + private var catalog: [String: FontFile] = [:] + + /// Every face made, by file, face index, size and scale, so a fallback + /// is the same object each time shaping uses it. + private var faces: [String: FreeTypeEngineFace] = [:] + + public init?() { + guard let library = try? FreeTypeLibrary(), FcInit() != 0 else { return nil } + self.library = library + } + + // MARK: FontEngine + + public func makeFace(name: String?, size: Float, scale: Float, weight: Typeface.Weight, design: Typeface.Design) + -> (any EngineFace)? { + let file: FontFile + if let name { + guard let found = registered(named: name) ?? installed(named: name) else { return nil } + file = found + } else { + guard let found = system(weight: weight, design: design) else { return nil } + file = found + } + return face(file, size: size, scale: scale) + } + + public func register(fontFiles paths: [String]) -> [String] { + var names: [String] = [] + for path in paths { + guard let descriptions = try? library.faceDescriptions(path: path), !descriptions.isEmpty else { continue } + _ = path.withCString { FcConfigAppFontAddFile(nil, UnsafeRawPointer($0).assumingMemoryBound(to: FcChar8.self)) } + for description in descriptions { + let file = FontFile(path: path, index: description.index) + if let postScriptName = description.postScriptName { + names.append(postScriptName) + catalog[Self.normalized(postScriptName)] = file + } + let full = Self.normalized(description.familyName + description.styleName) + catalog[full] = catalog[full] ?? file + let family = Self.normalized(description.familyName) + if catalog[family] == nil || description.styleName == "Regular" { + catalog[family] = file + } + } + } + return names + } + + // MARK: Faces + + func face(_ file: FontFile, size: Float, scale: Float) -> FreeTypeEngineFace? { + let key = "\(file.path)#\(file.index)@\(size)@\(scale)" + if let known = faces[key] { + return known + } + guard let face = FreeTypeEngineFace(file: file, size: size, scale: scale, engine: self) else { return nil } + faces[key] = face + return face + } + + /// The face Fontconfig picks for a character `base` lacks, at `base`'s + /// size; nil when no font has it. + func fallback(for scalar: Unicode.Scalar, from base: FreeTypeEngineFace) -> FreeTypeEngineFace? { + guard let pattern = FcPatternCreate() else { return nil } + defer { FcPatternDestroy(pattern) } + if let family = base.familyName { + Self.add(family, FC_FAMILY, to: pattern) + } + if let characters = FcCharSetCreate() { + FcCharSetAddChar(characters, scalar.value) + FcPatternAddCharSet(pattern, FC_CHARSET, characters) + FcCharSetDestroy(characters) + } + guard let file = Self.match(pattern)?.file, + file != base.file, + let face = face(file, size: base.size, scale: base.scale), + face.glyphIndex(scalar) != 0 else { return nil } + return face + } + + // MARK: Finding fonts + + struct Match { + var file: FontFile + var names: [String] + } + + func registered(named name: String) -> FontFile? { + catalog[Self.normalized(name)] + } + + /// An installed font whose PostScript, family or full name is `name`: + /// Fontconfig always answers with something, so its answer is checked. + func installed(named name: String) -> FontFile? { + let wanted = Self.normalized(name) + for object in [FC_POSTSCRIPT_NAME, FC_FAMILY, FC_FULLNAME] { + guard let pattern = FcPatternCreate() else { return nil } + defer { FcPatternDestroy(pattern) } + Self.add(name, object, to: pattern) + if let match = Self.match(pattern), match.names.contains(where: { Self.normalized($0) == wanted }) { + return match.file + } + } + return nil + } + + /// The system's font: Fontconfig's sans-serif, serif or monospace at the + /// weight. Fontconfig has no rounded design, so rounded is sans-serif. + func system(weight: Typeface.Weight, design: Typeface.Design) -> FontFile? { + guard let pattern = FcPatternCreate() else { return nil } + defer { FcPatternDestroy(pattern) } + let family = switch design { + case .serif: "serif" + case .monospaced: "monospace" + default: "sans-serif" + } + Self.add(family, FC_FAMILY, to: pattern) + FcPatternAddInteger(pattern, FC_WEIGHT, FcWeightFromOpenType(weight.rawValue)) + return Self.match(pattern)?.file + } + + static func match(_ pattern: OpaquePointer) -> Match? { + FcConfigSubstitute(nil, pattern, FcMatchPattern) + FcDefaultSubstitute(pattern) + var result = FcResultNoMatch + guard let matched = FcFontMatch(nil, pattern, &result) else { return nil } + defer { FcPatternDestroy(matched) } + guard result == FcResultMatch, let path = string(FC_FILE, of: matched) else { return nil } + var index: Int32 = 0 + FcPatternGetInteger(matched, FC_INDEX, 0, &index) + var names: [String] = [] + for object in [FC_POSTSCRIPT_NAME, FC_FAMILY, FC_FULLNAME] { + var n: Int32 = 0 + while let name = string(object, of: matched, at: n) { + names.append(name) + n += 1 + } + } + return Match(file: FontFile(path: path, index: Int(index & 0xFFFF)), names: names) + } + + static func string(_ object: String, of pattern: OpaquePointer, at n: Int32 = 0) -> String? { + var value: UnsafeMutablePointer? + guard FcPatternGetString(pattern, object, n, &value) == FcResultMatch, let value else { return nil } + return String(cString: value) + } + + static func add(_ value: String, _ object: String, to pattern: OpaquePointer) { + _ = value.withCString { + FcPatternAddString(pattern, object, UnsafeRawPointer($0).assumingMemoryBound(to: FcChar8.self)) + } + } + + /// Lower case, without spaces, hyphens or underscores: how a name is + /// compared. + static func normalized(_ name: String) -> String { + String(name.lowercased().filter { $0 != " " && $0 != "-" && $0 != "_" }) + } +} + +/// A face in a font file. +struct FontFile: Hashable { + var path: String + var index: Int +} + +/// One face at a size, for `FreeTypeFontEngine`. +final class FreeTypeEngineFace: EngineFace { + + let file: FontFile + + let size: Float + + let scale: Float + + unowned let engine: FreeTypeFontEngine + + /// Sized at the size times the scale, for images. + var freeType: FreeTypeFace + + /// Sized at the size, so shaping answers in points. + let harfBuzz: HarfBuzzFont + + let familyName: String? + + let unitsPerEm: Float + + let metrics: FontMetrics + + /// The face each character this one lacks fell back to, or nil when + /// none has it. + private var fallbacks: [Unicode.Scalar: FreeTypeEngineFace?] = [:] + + init?(file: FontFile, size: Float, scale: Float, engine: FreeTypeFontEngine) { + guard var freeType = try? engine.library.face(path: file.path, index: file.index), + let harfBuzzFace = try? HarfBuzzFace(path: file.path, index: file.index), + let harfBuzz = try? HarfBuzzFont(face: harfBuzzFace, size: size) else { return nil } + if freeType.isScalable { + guard (try? freeType.setCharSize(pointSize: Double(size * scale))) != nil else { return nil } + } else { + // A bitmap font, as colour emoji often are: the strike nearest + // the size wanted. + let pixels = Double(size * scale) + let strikes = freeType.bitmapStrikes + guard let nearest = strikes.indices.min(by: { + abs(Double(strikes[$0].height) - pixels) < abs(Double(strikes[$1].height) - pixels) + }), (try? freeType.selectBitmapStrike(at: nearest)) != nil else { return nil } + } + let unitsPerEm = Float(max(freeType.unitsPerEM, 1)) + let points = size / unitsPerEm + let ascent = Float(freeType.designAscender) * points + let descent = -Float(freeType.designDescender) * points + let lineHeight = Float(freeType.designLineHeight) * points + func height(of scalar: Unicode.Scalar) -> Float { + guard let glyph = harfBuzz.glyph(for: scalar), let extents = harfBuzz.extents(of: glyph) else { return 0 } + return extents.yBearing + } + self.metrics = FontMetrics(ascent: ascent, descent: descent, lineGap: max(0, lineHeight - ascent - descent), + capHeight: height(of: "H"), xHeight: height(of: "x"), unitsPerEm: unitsPerEm) + self.familyName = freeType.familyName.isEmpty ? nil : freeType.familyName + self.freeType = freeType + self.harfBuzz = harfBuzz + self.unitsPerEm = unitsPerEm + self.file = file + self.size = size + self.scale = scale + self.engine = engine + } + + func glyphIndex(_ scalar: Unicode.Scalar) -> UInt32 { + freeType.glyphIndex(for: scalar) + } + + func glyphs(for characters: String) -> [UInt32] { + characters.unicodeScalars.map(glyphIndex) + } + + // MARK: Shaping + + /// Characters drawn with the one before, whichever face that is: marks, + /// joiners and variation selectors. + static func joinsPrevious(_ scalar: Unicode.Scalar) -> Bool { + switch scalar.properties.generalCategory { + case .nonspacingMark, .spacingMark, .enclosingMark, .format: + return true + default: + return (0xFE00 ... 0xFE0F).contains(scalar.value) || (0xE0100 ... 0xE01EF).contains(scalar.value) + } + } + + func fallback(for scalar: Unicode.Scalar) -> FreeTypeEngineFace? { + if let known = fallbacks[scalar] { + return known + } + let found = engine.fallback(for: scalar, from: self) + fallbacks[scalar] = .some(found) + return found + } + + /// The line split where the face changes: each run's face and its UTF-8 + /// range. + func runs(of line: String) -> [(face: FreeTypeEngineFace, start: Int, end: Int)] { + var runs: [(face: FreeTypeEngineFace, start: Int, end: Int)] = [] + var offset = 0 + for scalar in line.unicodeScalars { + let length = UTF8.width(scalar) + let face: FreeTypeEngineFace + if let last = runs.last, Self.joinsPrevious(scalar) || scalar.properties.isWhitespace { + face = last.face + } else if glyphIndex(scalar) != 0 { + face = self + } else { + face = fallback(for: scalar) ?? self + } + if let last = runs.last, last.face === face { + runs[runs.count - 1].end = offset + length + } else { + runs.append((face, offset, offset + length)) + } + offset += length + } + return runs + } + + func shape(_ line: String, features: [String]) -> [EngineShapedGlyph] { + let features = features.compactMap(Feature.init) + let bytes = Array(line.utf8) + var shapedRuns: [[EngineShapedGlyph]] = [] + var direction: Direction? + for run in runs(of: line) { + let text = String(decoding: bytes[run.start ..< run.end], as: UTF8.self) + let shaped = run.face.harfBuzz.shape(text, features: features) + direction = direction ?? shaped.direction + shapedRuns.append(shaped.glyphs.map { glyph in + EngineShapedGlyph(glyph: glyph.glyph, face: run.face === self ? nil : run.face, + advance: glyph.xAdvance, offsetX: glyph.xOffset, offsetY: glyph.yOffset, + cluster: run.start + glyph.cluster) + }) + } + if direction == .rightToLeft { + shapedRuns.reverse() + } + return shapedRuns.flatMap { $0 } + } + + // MARK: Images and outlines + + func rasterize(_ glyph: UInt32) -> GlyphImage { + guard let loaded = try? freeType.glyph(at: glyph, flags: [.noHinting, .color], render: .normal), + let bitmap = loaded.bitmap, bitmap.width > 0, bitmap.rows > 0, + bitmap.width <= FontRecords.maximumImageSide, bitmap.rows <= FontRecords.maximumImageSide else { + return .empty + } + let width = bitmap.width + var pixels: [UInt8] = [] + var isColor = false + switch bitmap.pixelMode { + case .gray: + pixels.reserveCapacity(width * bitmap.rows) + for row in 0 ..< bitmap.rows { + let start = row * bitmap.bytesPerRow + pixels.append(contentsOf: bitmap.pixels[start ..< start + width]) + } + case .mono: + pixels.reserveCapacity(width * bitmap.rows) + for row in 0 ..< bitmap.rows { + for column in 0 ..< width { + let byte = bitmap.pixels[row * bitmap.bytesPerRow + column / 8] + pixels.append(byte & (0x80 >> UInt8(column % 8)) != 0 ? 255 : 0) + } + } + case .bgra: + // FreeType's colour is premultiplied BGRA; images are + // premultiplied RGBA. + isColor = true + pixels.reserveCapacity(width * bitmap.rows * 4) + for row in 0 ..< bitmap.rows { + for column in 0 ..< width { + let start = row * bitmap.bytesPerRow + column * 4 + pixels.append(bitmap.pixels[start + 2]) + pixels.append(bitmap.pixels[start + 1]) + pixels.append(bitmap.pixels[start]) + pixels.append(bitmap.pixels[start + 3]) + } + } + case .lcd, .lcdVertical: + return .empty + } + return GlyphImage(width: width, height: bitmap.rows, bearingX: bitmap.left, bearingY: bitmap.top, + isColor: isColor, pixels: pixels) + } + + func outline(_ glyph: UInt32) -> GlyphOutline? { + guard let loaded = try? freeType.glyph(at: glyph, flags: [.noScale, .noHinting]), + let outline = loaded.outline, !outline.elements.isEmpty else { return nil } + let points = Double(size / unitsPerEm) + func point(_ p: OutlinePoint) -> GlyphOutline.Point { + GlyphOutline.Point(Float(p.x * points), Float(p.y * points)) + } + return GlyphOutline(outline.elements.map { element in + switch element { + case .moveTo(let p): .move(point(p)) + case .lineTo(let p): .line(point(p)) + case .quadCurveTo(let control, let to): .quad(control: point(control), to: point(to)) + case .curveTo(let control1, let control2, let to): + .cubic(control1: point(control1), control2: point(control2), to: point(to)) + case .close: .close + } + }) + } +} diff --git a/Sources/LinuxFonts/LinuxFonts.swift b/Sources/LinuxFonts/LinuxFonts.swift new file mode 100644 index 0000000..15e5321 --- /dev/null +++ b/Sources/LinuxFonts/LinuxFonts.swift @@ -0,0 +1,25 @@ +import DynamicFonts +import DynamicRuntime +import LinuxHost +import RuntimeFonts +import RuntimeHost + +/// The Fonts contract (`Documentation/Contracts/Fonts.md` in AppRuntime): +/// AppRuntime's `HostFontFace` over `FreeTypeFontEngine`, with the fonts in +/// the app's bundle added to Fontconfig's. Main loop only. +public enum LinuxFonts: HostModule { + + public static var contracts: [ContractDescriptor] { + HostFontsModule.contracts + } + + public static func register(in registrar: some ContractRegistrar) { + if HostFontFace.engine == nil { + HostFontFace.engine = FreeTypeFontEngine() + if HostFontFace.engine == nil { + HostLog.error("fonts: FreeType or Fontconfig didn't start: there are no fonts") + } + } + HostFontsModule.register(in: registrar) + } +} diff --git a/Sources/LinuxHostApp/HostApp.swift b/Sources/LinuxHostApp/HostApp.swift index 2f6c463..3b04c7e 100644 --- a/Sources/LinuxHostApp/HostApp.swift +++ b/Sources/LinuxHostApp/HostApp.swift @@ -8,6 +8,7 @@ import LinuxBluetooth import LinuxCoreModel import LinuxDevice import LinuxDocuments +import LinuxFonts import LinuxGraphics import LinuxLocation import LinuxMedia @@ -40,12 +41,12 @@ public enum HostApp { /// Bluetooth, GL surfaces and web pages, which the player shows, the /// app's files, settings and model stores, AppRuntime's date and number /// formatting and its HTTP client over Swift Foundation, the device, - /// location, the user's documents, motion sensors, NFC tags, and media - /// players, whose pictures the player shows. + /// location, the user's documents, motion sensors, NFC tags, media + /// players, whose pictures the player shows, and fonts. public static let modules: [any HostModule.Type] = [ DarwinUI.self, LinuxBluetooth.self, LinuxGraphics.self, LinuxWebKit.self, LinuxFiles.self, LinuxDefaults.self, LinuxModelStore.self, HostFormattingModule.self, HostNetworkingModule.self, LinuxDeviceModule.self, LinuxLocation.self, - LinuxDocuments.self, LinuxMotion.self, LinuxNFC.self, LinuxMedia.self, + LinuxDocuments.self, LinuxMotion.self, LinuxNFC.self, LinuxMedia.self, LinuxFonts.self, ] /// Points AppRuntime's modules at this host: networking's callbacks, diff --git a/Sources/LinuxNFC/NeardBus.swift b/Sources/LinuxNFC/NeardBus.swift index cb12366..6d7d2cf 100644 --- a/Sources/LinuxNFC/NeardBus.swift +++ b/Sources/LinuxNFC/NeardBus.swift @@ -140,18 +140,3 @@ public final class SystemNeard: NeardBus { return interfaces } } - -// MARK: - Values - -extension DBusMessageArgument { - - /// `ay`. - var bytes: [UInt8]? { - elements?.compactMap { if case .byte(let byte) = $0.contents { byte } else { nil } } - } - - /// `ay`. - static func byteArray(_ bytes: [UInt8]) -> DBusMessageArgument { - .list(of: .byte, bytes.map { .byte($0) }) - } -} diff --git a/Sources/LinuxPackager/Validator.swift b/Sources/LinuxPackager/Validator.swift index 84a5e38..f3b3692 100644 --- a/Sources/LinuxPackager/Validator.swift +++ b/Sources/LinuxPackager/Validator.swift @@ -4,6 +4,7 @@ import LinuxBluetooth import LinuxCoreModel import LinuxDevice import LinuxDocuments +import LinuxFonts import LinuxGraphics import LinuxLocation import LinuxMedia @@ -22,11 +23,11 @@ public enum HostContracts { /// The modules `linux-app-host` registers (`HostApp.modules`): the /// player's contracts, without building the player, Bluetooth, /// graphics, web views, files, settings, model stores, formatting, HTTP, - /// the device, location, documents, motion, NFC and media. + /// the device, location, documents, motion, NFC, media and fonts. nonisolated(unsafe) public static let modules: [any HostModule.Type] = [ PlayerContracts.self, LinuxBluetooth.self, LinuxGraphics.self, LinuxWebKit.self, LinuxFiles.self, LinuxDefaults.self, LinuxModelStore.self, HostFormattingModule.self, HostNetworkingModule.self, LinuxDeviceModule.self, LinuxLocation.self, - LinuxDocuments.self, LinuxMotion.self, LinuxNFC.self, LinuxMedia.self, + LinuxDocuments.self, LinuxMotion.self, LinuxNFC.self, LinuxMedia.self, LinuxFonts.self, ] public static var provided: [String: ContractDescriptor] { diff --git a/Tests/LinuxFontsTests/Fixtures/Inter-OFL.txt b/Tests/LinuxFontsTests/Fixtures/Inter-OFL.txt new file mode 100644 index 0000000..21f6aff --- /dev/null +++ b/Tests/LinuxFontsTests/Fixtures/Inter-OFL.txt @@ -0,0 +1,93 @@ +Copyright 2020 The Inter Project Authors (https://github.com/rsms/inter) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +https://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/Tests/LinuxFontsTests/Fixtures/Inter-Regular-Shaping.ttf b/Tests/LinuxFontsTests/Fixtures/Inter-Regular-Shaping.ttf new file mode 100644 index 0000000..6903b4a Binary files /dev/null and b/Tests/LinuxFontsTests/Fixtures/Inter-Regular-Shaping.ttf differ diff --git a/Tests/LinuxFontsTests/LinuxFontsTests.swift b/Tests/LinuxFontsTests/LinuxFontsTests.swift new file mode 100644 index 0000000..940911d --- /dev/null +++ b/Tests/LinuxFontsTests/LinuxFontsTests.swift @@ -0,0 +1,158 @@ +import DynamicFonts +import DynamicRuntime +import Foundation +import RuntimeFonts +import Testing +@testable import LinuxFonts + +/// `Fixtures/Inter-Regular-Shaping.ttf` is Inter (SIL Open Font License, +/// `Inter-OFL.txt`) at regular weight: printable ASCII with its OpenType +/// layout tables. +@Suite(.serialized) struct LinuxFontsTests { + + static let fixtures = Bundle.module.url(forResource: "Fixtures", withExtension: nil)!.path + + static let shaping = fixtures + "/Inter-Regular-Shaping.ttf" + + /// One engine, with Inter registered, as the bundle's fonts are. + nonisolated(unsafe) static let engine: FreeTypeFontEngine = { + let engine = FreeTypeFontEngine()! + _ = engine.register(fontFiles: [shaping]) + return engine + }() + + func inter(size: Float = 32, scale: Float = 1) throws -> FreeTypeEngineFace { + let face = Self.engine.makeFace(name: "Inter", size: size, scale: scale, weight: .regular, design: .default) + return try #require(face as? FreeTypeEngineFace) + } + + @Test func registersFontsByName() throws { + let names = FreeTypeFontEngine()!.register(fontFiles: [Self.shaping, Self.fixtures + "/Inter-OFL.txt"]) + #expect(names == ["Inter-Regular"]) + for name in ["Inter", "Inter-Regular", "inter regular"] { + #expect(Self.engine.makeFace(name: name, size: 12, scale: 1, weight: .regular, design: .default) != nil) + } + } + + @Test func refusesNamesItDoesNotHave() { + #expect(Self.engine.makeFace(name: "No Such Font 9a7b", size: 12, scale: 1, weight: .regular, design: .default) == nil) + } + + @Test func findsTheSystemFont() throws { + for design in [Typeface.Design.default, .serif, .rounded, .monospaced] { + let face = try #require(Self.engine.makeFace(name: nil, size: 17, scale: 2, weight: .bold, design: design)) + #expect(face.metrics.ascent > 0) + #expect(face.glyphs(for: "A") != [0]) + } + } + + @Test func measuresInPoints() throws { + let metrics = try inter(size: 32).metrics + // Inter: ascent 0.97 em, descent 0.24, cap height 0.727, x height 0.545. + #expect(abs(metrics.ascent - 31) < 1) + #expect(abs(metrics.descent - 7.75) < 1) + #expect(metrics.lineGap >= 0) + #expect(abs(metrics.capHeight - 23.3) < 1) + #expect(abs(metrics.xHeight - 17.4) < 1) + #expect(metrics.unitsPerEm == 2048) + // Doubling the scale changes images, not points. + #expect(try inter(size: 32, scale: 2).metrics == metrics) + } + + @Test func mapsCharactersWithoutShaping() throws { + let glyphs = try inter().glyphs(for: "Ab é") + #expect(glyphs.count == 4) + #expect(glyphs[0] != 0 && glyphs[1] != 0 && glyphs[2] != 0) + // The fixture is ASCII only. + #expect(glyphs[3] == 0) + } + + @Test func shapesWithKerningAndContextualAlternates() throws { + let face = try inter() + let kerned = face.shape("AV", features: []) + let unkerned = face.shape("AV", features: ["-kern"]) + #expect(kerned.count == 2 && unkerned.count == 2) + #expect(kerned[0].advance < unkerned[0].advance) + #expect(kerned.map(\.cluster) == [0, 1]) + #expect(kerned.allSatisfy { $0.face == nil }) + // Inter's "->" becomes one arrow through calt. + #expect(face.shape("->", features: []).count == 1) + #expect(face.shape("->", features: ["-calt"]).count == 2) + } + + @Test func fallsBackForCharactersTheFaceLacks() throws { + let face = try inter() + let shaped = face.shape("Aé", features: []) + #expect(shaped.count >= 2) + #expect(shaped[0].face == nil) + // é is two UTF-8 bytes after A, from another face if one has it. + let last = try #require(shaped.last) + #expect(last.cluster == 1) + if let fallback = last.face { + #expect(last.glyph != 0) + // The same face object each time. + #expect(face.shape("é", features: []).first?.face === fallback) + } + } + + @Test func rasterizesAtTheSizeTimesTheScale() throws { + let glyph = try inter().glyphs(for: "H")[0] + let one = try inter(size: 32, scale: 1).rasterize(glyph) + let two = try inter(size: 32, scale: 2).rasterize(glyph) + #expect(!one.isColor && one.pixels.count == one.width * one.height) + #expect(abs(one.bearingY - 23) <= 1) + #expect(abs(two.height - one.height * 2) <= 2) + #expect(one.pixels.contains(255)) + // A space has no ink. + #expect(try inter().rasterize(inter().glyphs(for: " ")[0]) == .empty) + } + + @Test func outlinesInPoints() throws { + let face = try inter(size: 32) + let outline = try #require(face.outline(face.glyphs(for: "O")[0])) + guard case .move = outline.elements.first else { + Issue.record("an outline starts with a move") + return + } + #expect(outline.elements.contains(.close)) + let ys = outline.elements.compactMap { element -> Float? in + if case .line(let p) = element { return p.y } + if case .quad(_, let p) = element { return p.y } + if case .cubic(_, _, let p) = element { return p.y } + return nil + } + #expect((ys.max() ?? 0) > 20 && (ys.max() ?? 0) < 26) + #expect(face.outline(face.glyphs(for: " ")[0]) == nil) + } + + /// The contract's answers, from `HostFontFace` over this engine. The + /// guest's side, through `Typeface`, is AppRuntime's to test: this + /// package builds it without `GuestExports`. + @Test func servesTheContract() throws { + HostFontFace.engine = Self.engine + let registrar = RecordingRegistrar() + LinuxFonts.register(in: registrar) + #expect(registrar.registered == ["org.pureswift.fonts.Face"]) + #expect(LinuxFonts.contracts.map(\.name) == registrar.registered) + + let face = try #require(HostFontFace.make(name: "Inter", size: 32, scale: 2, weight: 400, design: 0)) + let metrics = try FontRecords.decodeMetrics(face.metrics()) + #expect(abs(metrics.capHeight - 23.3) < 1) + let line = try FontRecords.decodeShaped(face.shape("AV", features: "")) + #expect(line.count == 2 && line.allSatisfy { $0.face == face.identifier() }) + let images = try FontRecords.decodeImages(face.rasterize(FontRecords.encode(line.map(\.glyph)))) + #expect(images.count == 2 && images[0].height > 40) + #expect(!face.outline(Int32(bitPattern: line[0].glyph.index)).isEmpty) + #expect(HostFontFace.make(name: "No Such Font 9a7b", size: 12, scale: 1, weight: 400, design: 0) == nil) + } +} + +/// Records what a module registers. +final class RecordingRegistrar: ContractRegistrar { + + var registered: [String] = [] + + func register(_ descriptor: ContractDescriptor, statics: StaticMethodTable?) { + registered.append(descriptor.name) + } +}