From 3b7f6b09c84176ef3aac479a241f336d0ff6fd90 Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Thu, 26 Nov 2026 02:17:33 -0500 Subject: [PATCH 1/8] Added FreeType as a system library --- Sources/CFreeType/module.modulemap | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Sources/CFreeType/module.modulemap diff --git a/Sources/CFreeType/module.modulemap b/Sources/CFreeType/module.modulemap new file mode 100644 index 0000000..73e1cf0 --- /dev/null +++ b/Sources/CFreeType/module.modulemap @@ -0,0 +1,5 @@ +module CFreeType [system] { + header "shim.h" + link "freetype" + export * +} From 01a5d2635002340a7423c6a57ecd09f3591b8158 Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Thu, 26 Nov 2026 02:17:33 -0500 Subject: [PATCH 2/8] Added FreeType's header --- Sources/CFreeType/shim.h | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 Sources/CFreeType/shim.h diff --git a/Sources/CFreeType/shim.h b/Sources/CFreeType/shim.h new file mode 100644 index 0000000..d1721e7 --- /dev/null +++ b/Sources/CFreeType/shim.h @@ -0,0 +1,3 @@ +#include +#include FT_FREETYPE_H +#include FT_SIZES_H From 07934cf59068ad5cadbaa9abbb551acbc132dd6d Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Thu, 26 Nov 2026 02:17:33 -0500 Subject: [PATCH 3/8] Added faces from outline fonts through FreeType --- Sources/GraphiteText/FreeTypeFace.swift | 137 ++++++++++++++++++++++++ 1 file changed, 137 insertions(+) create mode 100644 Sources/GraphiteText/FreeTypeFace.swift diff --git a/Sources/GraphiteText/FreeTypeFace.swift b/Sources/GraphiteText/FreeTypeFace.swift new file mode 100644 index 0000000..ccf6b7a --- /dev/null +++ b/Sources/GraphiteText/FreeTypeFace.swift @@ -0,0 +1,137 @@ +// Faces from outline fonts (TrueType, OpenType, Type 1 and the rest FreeType +// reads), rendered to 8-bit coverage. Built with the FreeType trait, which +// is on by default; without it there is only the built-in font. + +#if FreeType +import CFreeType +import Synchronization +import GraphiteBase + +/// A font file loaded through FreeType. FreeType's faces aren't thread-safe, +/// so every call goes through one lock. +public final class FreeTypeFace: FontFace, @unchecked Sendable { + + public enum LoadError: Error, Equatable { + case libraryUnavailable + case unreadable + } + + nonisolated(unsafe) private static let library: FT_Library? = { + var library: FT_Library? + return FT_Init_FreeType(&library) == 0 ? library : nil + }() + + private let lock = Mutex(()) + private let face: FT_Face + /// The font's bytes, which FreeType reads from for as long as the face + /// lives. + private let data: UnsafeMutableRawBufferPointer? + + public let familyName: String + + /// The style name the font says ("Regular", "Bold Italic"). + public let styleName: String + + /// The styles the font itself is: its bold and italic bits. + public let styles: TextStyle + + /// A font in memory: nil `index` is the file's first face (a .ttc has + /// several). + public init(data bytes: [UInt8], index: Int = 0) throws { + guard let library = Self.library else { throw LoadError.libraryUnavailable } + let copy = UnsafeMutableRawBufferPointer.allocate(byteCount: max(1, bytes.count), alignment: 16) + bytes.withUnsafeBytes { if !bytes.isEmpty { copy.baseAddress!.copyMemory(from: $0.baseAddress!, byteCount: bytes.count) } } + var face: FT_Face? + guard FT_New_Memory_Face(library, copy.baseAddress!.assumingMemoryBound(to: FT_Byte.self), FT_Long(bytes.count), FT_Long(index), &face) == 0, + let face else { + copy.deallocate() + throw LoadError.unreadable + } + self.face = face + data = copy + (familyName, styleName, styles) = Self.names(of: face) + } + + /// A font file by its path. + public init(path: String, index: Int = 0) throws { + guard let library = Self.library else { throw LoadError.libraryUnavailable } + var face: FT_Face? + guard FT_New_Face(library, path, FT_Long(index), &face) == 0, let face else { throw LoadError.unreadable } + self.face = face + data = nil + (familyName, styleName, styles) = Self.names(of: face) + } + + deinit { + FT_Done_Face(face) + data?.deallocate() + } + + private static func names(of face: FT_Face) -> (String, String, TextStyle) { + let family = face.pointee.family_name.map { String(cString: $0) } ?? "Unknown" + let style = face.pointee.style_name.map { String(cString: $0) } ?? "" + var styles: TextStyle = [] + if face.pointee.style_flags & FT_Long(FT_STYLE_FLAG_BOLD) != 0 { styles.insert(.bold) } + if face.pointee.style_flags & FT_Long(FT_STYLE_FLAG_ITALIC) != 0 { styles.insert(.italic) } + return (family, style, styles) + } + + /// The font is its own plain face: bold and italic ones say so, and the + /// rest are drawn from its glyphs. + public func hasStyle(_ style: TextStyle) -> Bool { + style == styles || style.isEmpty + } + + /// Characters the font has a glyph for. + public func contains(_ character: Unicode.Scalar) -> Bool { + lock.withLock { _ in FT_Get_Char_Index(face, FT_ULong(character.value)) != 0 } + } + + public func metrics(size: Int) -> FontMetrics { + lock.withLock { _ in + setSize(size) + guard let metrics = face.pointee.size?.pointee.metrics else { return FontMetrics(ascent: 0, descent: 0, widMax: 0, leading: 0) } + let ascent = Int((metrics.ascender + 63) >> 6) + let descent = Int((-metrics.descender + 63) >> 6) + let height = Int((metrics.height + 63) >> 6) + return FontMetrics(ascent: Int16(clamping: ascent), descent: Int16(clamping: descent), + widMax: Int16(clamping: Int((metrics.max_advance + 63) >> 6)), + leading: Int16(clamping: max(0, height - ascent - descent))) + } + } + + public func glyph(for character: Unicode.Scalar, size: Int) -> GlyphImage? { + lock.withLock { _ in + setSize(size) + let index = FT_Get_Char_Index(face, FT_ULong(character.value)) + guard index != 0, FT_Load_Glyph(face, index, FT_Int32(FT_LOAD_RENDER)) == 0, + let slot = face.pointee.glyph else { return nil } + let bitmap = slot.pointee.bitmap + let advance = Int((slot.pointee.advance.x + 32) >> 6) + let width = Int(bitmap.width), height = Int(bitmap.rows) + guard width > 0, height > 0, let buffer = bitmap.buffer else { return .blank(advance: advance) } + var coverage = [UInt8](repeating: 0, count: width * height) + let pitch = Int(bitmap.pitch) + for row in 0 ..< height { + let line = buffer + row * pitch + for column in 0 ..< width { + switch Int32(bitmap.pixel_mode) { + case Int32(FT_PIXEL_MODE_MONO.rawValue): + coverage[row * width + column] = line[column / 8] & (0x80 >> UInt8(column % 8)) != 0 ? 255 : 0 + default: + coverage[row * width + column] = line[column] + } + } + } + return GlyphImage(width: width, height: height, left: Int(slot.pointee.bitmap_left), top: Int(slot.pointee.bitmap_top), + coverage: coverage, advance: advance) + } + } + + /// Sets the pixel size, 12 where none is asked for as QuickDraw's + /// default is. Called with the lock held. + private func setSize(_ size: Int) { + _ = FT_Set_Pixel_Sizes(face, 0, FT_UInt(size <= 0 ? 12 : size)) + } +} +#endif From d0cb4a44657e5f749c67a5dbc53f88a6a21312a6 Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Thu, 26 Nov 2026 02:17:33 -0500 Subject: [PATCH 4/8] Added finding installed fonts by family --- Sources/GraphiteText/FontFinder.swift | 93 +++++++++++++++++++++++++++ 1 file changed, 93 insertions(+) create mode 100644 Sources/GraphiteText/FontFinder.swift diff --git a/Sources/GraphiteText/FontFinder.swift b/Sources/GraphiteText/FontFinder.swift new file mode 100644 index 0000000..e240ef5 --- /dev/null +++ b/Sources/GraphiteText/FontFinder.swift @@ -0,0 +1,93 @@ +// Finding installed fonts by family name: the folders fonts are kept in, on +// macOS and on Linux (XDG's too), read once with FreeType for each file's +// family. Give `lookUp` to a FontRegistry. + +#if FreeType +#if canImport(Glibc) +import Glibc +#elseif canImport(Musl) +import Musl +#elseif canImport(Darwin) +import Darwin +#endif +import Synchronization + +public final class FontFinder: Sendable { + + /// A font file and the face in it. + public struct Entry: Hashable, Sendable { + public var path: String + public var index: Int + public var family: String + public var style: String + } + + private let folders: [String] + private let entries = Mutex<[Entry]?>(nil) + + /// Looks in the standard folders, and `extra` ones first. + public init(extraFolders: [String] = []) { + let home = getenv("HOME").map { String(cString: $0) } ?? "/" + var data = getenv("XDG_DATA_HOME").map { String(cString: $0) } ?? home + "/.local/share" + if data.isEmpty { data = home + "/.local/share" } + folders = extraFolders + [ + data + "/fonts", home + "/.fonts", home + "/Library/Fonts", + "/Library/Fonts", "/System/Library/Fonts", "/System/Library/Fonts/Supplemental", + "/usr/local/share/fonts", "/usr/share/fonts", + ] + } + + /// Every face found, scanned on first use. + public var fonts: [Entry] { + entries.withLock { cached in + if let cached { return cached } + var found: [Entry] = [] + for folder in folders { Self.scan(folder, depth: 0, into: &found) } + cached = found + return found + } + } + + /// A face of a family, in any case: its regular style where there is + /// one. + public func face(family: String) -> FreeTypeFace? { + let wanted = family.lowercased() + let matches = fonts.filter { $0.family.lowercased() == wanted } + guard let entry = matches.first(where: { ["regular", "roman", "book", "medium"].contains($0.style.lowercased()) }) ?? matches.first else { return nil } + return try? FreeTypeFace(path: entry.path, index: entry.index) + } + + /// For FontRegistry's `lookUp`. + public var lookUp: @Sendable (String) -> (any FontFace)? { + { [self] name in face(family: name) } + } + + private static let extensions: Set = ["ttf", "otf", "ttc", "otc", "pfb", "dfont"] + + private static func scan(_ folder: String, depth: Int, into found: inout [Entry]) { + guard depth < 4, let directory = opendir(folder) else { return } + defer { closedir(directory) } + var names: [(String, Bool)] = [] + while let entry = readdir(directory) { + let name = withUnsafeBytes(of: entry.pointee.d_name) { String(decoding: $0.prefix { $0 != 0 }, as: UTF8.self) } + guard !name.hasPrefix(".") else { continue } + names.append((name, entry.pointee.d_type == UInt8(DT_DIR))) + } + for (name, isDirectory) in names.sorted(by: { $0.0 < $1.0 }) { + let path = folder + "/" + name + if isDirectory { + scan(path, depth: depth + 1, into: &found) + } else if let dot = name.lastIndex(of: "."), extensions.contains(name[name.index(after: dot)...].lowercased()) { + guard let first = try? FreeTypeFace(path: path) else { continue } + found.append(Entry(path: path, index: 0, family: first.familyName, style: first.styleName)) + // A collection's other faces. + var index = 1 + while index < 32, let next = try? FreeTypeFace(path: path, index: index) { + found.append(Entry(path: path, index: index, family: next.familyName, style: next.styleName)) + index += 1 + } + } + } + } +} +#endif From 4c922aa3e4abce441d00e3799d02566468c334ce Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Thu, 26 Nov 2026 02:17:33 -0500 Subject: [PATCH 5/8] Added the FreeType trait, on by default --- Package.swift | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/Package.swift b/Package.swift index 0d673aa..f9325aa 100644 --- a/Package.swift +++ b/Package.swift @@ -64,6 +64,11 @@ let package = Package( targets: ["GraphiteText"] ) ], + // FreeType reads outline fonts; builds without it keep the bitmap font. + traits: [ + .trait(name: "FreeType", description: "Outline fonts through FreeType"), + .default(enabledTraits: ["FreeType"]), + ], dependencies: [ .package(url: "https://github.com/apple/swift-system.git", from: "1.9.0") ], @@ -100,9 +105,17 @@ let package = Package( name: "GraphiteQuickDraw", dependencies: ["GraphiteBase"] ), + .systemLibrary( + name: "CFreeType", + pkgConfig: "freetype2", + providers: [.apt(["libfreetype-dev"]), .brew(["freetype"])] + ), .target( name: "GraphiteText", - dependencies: ["GraphiteBase", "GraphiteQuickDraw"] + dependencies: [ + "GraphiteBase", "GraphiteQuickDraw", + .target(name: "CFreeType", condition: .when(traits: ["FreeType"])), + ] ), .target( name: "Graphite", From 86b4062e10b4f22980c73876d319748493781bf3 Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Thu, 26 Nov 2026 02:17:33 -0500 Subject: [PATCH 6/8] Tested FreeType faces and the font finder --- Tests/GraphiteTextTests/FreeTypeTests.swift | 78 +++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 Tests/GraphiteTextTests/FreeTypeTests.swift diff --git a/Tests/GraphiteTextTests/FreeTypeTests.swift b/Tests/GraphiteTextTests/FreeTypeTests.swift new file mode 100644 index 0000000..8733440 --- /dev/null +++ b/Tests/GraphiteTextTests/FreeTypeTests.swift @@ -0,0 +1,78 @@ +#if FreeType +#if canImport(Glibc) +import Glibc +#elseif canImport(Darwin) +import Darwin +#endif +import Testing +import GraphiteBase +import GraphiteQuickDraw +import GraphiteText + +/// Needs a font on the machine: the system's, which nothing here checks in. +@Suite struct FreeTypeTests { + + static let finder = FontFinder() + static let entry = finder.fonts.first { $0.index == 0 && $0.path.lowercased().hasSuffix(".ttf") } ?? finder.fonts.first + static let hasFont = entry != nil + + private func face() throws -> FreeTypeFace { + let entry = try #require(Self.entry) + return try FreeTypeFace(path: entry.path, index: entry.index) + } + + @Test(.enabled(if: Self.hasFont)) func glyphsAndMetrics() throws { + let face = try face() + let metrics = face.metrics(size: 24) + #expect(metrics.ascent > 10 && metrics.descent > 0) + #expect(face.metrics(size: 48).ascent > metrics.ascent) + let glyph = try #require(face.glyph(for: "H", size: 24)) + #expect(glyph.width > 0 && glyph.height > 0 && glyph.advance > 0) + #expect(glyph.coverage.count == glyph.width * glyph.height) + #expect(glyph.coverage.contains { $0 > 200 }) + #expect(face.contains("H")) + let space = try #require(face.glyph(for: " ", size: 24)) + #expect(space.width == 0 && space.advance > 0) + #expect(face.glyph(for: "\u{10FFFF}", size: 24) == nil) + } + + @Test(.enabled(if: Self.hasFont)) func loadsFromMemoryToo() throws { + let entry = try #require(Self.entry) + let file = try #require(fopen(entry.path, "rb")) + defer { fclose(file) } + var bytes: [UInt8] = [] + var chunk = [UInt8](repeating: 0, count: 65536) + while case let count = fread(&chunk, 1, chunk.count, file), count > 0 { bytes += chunk[0 ..< count] } + let face = try FreeTypeFace(data: bytes, index: entry.index) + #expect(face.familyName == entry.family) + #expect(face.glyph(for: "H", size: 16) != nil) + #expect(throws: FreeTypeFace.LoadError.unreadable) { try FreeTypeFace(data: [1, 2, 3]) } + #expect(throws: FreeTypeFace.LoadError.unreadable) { try FreeTypeFace(path: "/nonexistent.ttf") } + } + + @Test(.enabled(if: Self.hasFont)) func theFinderFindsFamiliesInAnyCase() throws { + let entry = try #require(Self.entry) + let found = try #require(Self.finder.face(family: entry.family.uppercased())) + #expect(found.familyName == entry.family) + #expect(Self.finder.face(family: "No Such Family") == nil) + } + + @Test(.enabled(if: Self.hasFont)) func drawsThroughTheRegistry() throws { + let entry = try #require(Self.entry) + let fonts = FontRegistry(lookUp: Self.finder.lookUp) + let number = fonts.register(try face()) + let port = Port(pixels: PixelBuffer(bounds: Rect(top: 0, left: 0, bottom: 40, right: 80), format: .argb32)) + port.perform(.erase, rect: port.portRect) + port.text.font = number + port.text.size = 24 + port.move(to: Point(v: 30, h: 4)) + port.drawText("Hi".unicodeScalars, fonts: fonts) + var dark = 0 + for v in Int16(0) ..< 40 { for h in Int16(0) ..< 80 where port.pixels?.color(at: Point(v: v, h: h)) != .white { dark += 1 } } + #expect(dark > 40) + #expect(port.pen.location.h > 4 + 10) + // A name the registry hasn't is found by the host's lookup. + #expect(fonts.face(named: entry.family) is FreeTypeFace) + } +} +#endif From dccafa2906a066647242a963c95828f4582cb193 Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Thu, 26 Nov 2026 02:17:33 -0500 Subject: [PATCH 7/8] Installed FreeType in CI and built without it too --- .github/workflows/swift.yml | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/.github/workflows/swift.yml b/.github/workflows/swift.yml index 99e5b6c..da2956e 100644 --- a/.github/workflows/swift.yml +++ b/.github/workflows/swift.yml @@ -19,12 +19,16 @@ jobs: - uses: SwiftyLab/setup-swift@latest with: swift-version: "6.4.2" + - name: Install FreeType + run: brew install freetype pkg-config - name: Swift version run: swift --version - name: Build run: swift build - name: Test run: swift test + - name: Build and test without FreeType + run: swift test --disable-default-traits --scratch-path .build-notrait linux: name: Linux (${{ matrix.arch }}) @@ -44,10 +48,12 @@ jobs: # The date tests read time zones from the system's database. run: | apt-get update - DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends tzdata + DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends tzdata libfreetype-dev fonts-dejavu-core pkg-config - name: Swift version run: swift --version - name: Build run: swift build - name: Test run: swift test + - name: Build and test without FreeType + run: swift test --disable-default-traits --scratch-path .build-notrait From 84ea90f60366ecfc2363f77e27e31a2f180677c9 Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Thu, 26 Nov 2026 02:17:33 -0500 Subject: [PATCH 8/8] Described the FreeType trait in the README --- README.md | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 76b7b33..5fdfd00 100644 --- a/README.md +++ b/README.md @@ -40,7 +40,7 @@ Any UI it shows will be drawn with [Cacao](https://github.com/PureSwift/Cacao). | `GraphiteResources` | The Resource Manager: resource maps read with every offset checked and written back, resource files changed in memory and updated, the chain of open files with `Get` and `Get1` searches, and `STR#`, `STR ` and `vers` resources. | | `GraphiteAppleEvents` | The Apple Event Manager: descriptors, lists, records and Apple events as values; coercions between text, numbers, booleans, codes, lists, records and file types (`furl`, `fss `, `alis`, and the host's), with installed handlers; the application's handlers by class and ID with wildcards; events sent to itself, and the required events. | | `GraphiteQuickDraw` | QuickDraw's pixels (1 to 8 bits indexed, 16 and 32 bits direct, big-endian on every CPU, in memory of its own or a program's), colors and the system's color tables, regions as real regions with QuickDraw's region records, patterns, transfer modes, ports, devices and offscreen worlds; drawing rectangles, ovals, round rectangles, arcs, polygons, regions and lines with the pen, and CopyBits, CopyMask and ScrollRect between any depths; PICT pictures, version 1 and 2, with PackBits and QuickTime-compressed images through a decoder the host gives. | -| `GraphiteText` | Fonts: faces and their metrics, the Font Manager's family numbers and names with the classic fonts' and their substitutes, a built-in bitmap system font (from Pomme), and QuickDraw's text in a port's font, face, size and mode, with the styles a face hasn't drawn from its plain glyphs; ATSUI-style layouts with styled runs, line breaking, measuring, hit testing and drawing, and the text in PICT pictures. | +| `GraphiteText` | Fonts: faces and their metrics, the Font Manager's family numbers and names with the classic fonts' and their substitutes, a built-in bitmap system font (from Pomme), and QuickDraw's text in a port's font, face, size and mode, with the styles a face hasn't drawn from its plain glyphs; ATSUI-style layouts with styled runs, line breaking, measuring, hit testing and drawing, and the text in PICT pictures; and, with the `FreeType` trait (on by default), faces from TrueType, OpenType and other outline fonts, found by family name in the system's font folders. | | `Graphite` | Re-exports the modules above. | Everything depends only on the Swift standard library, the C library @@ -76,6 +76,11 @@ let ended = try queue.wait(timeout: .milliseconds(1000)) ## Building +Outline fonts need [FreeType](https://freetype.org) (`libfreetype-dev` on +Debian, `brew install freetype` on macOS). Without it, build with +`swift build --disable-default-traits`: text then uses the built-in bitmap +font alone. + ```bash swift build swift test