Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion .github/workflows/swift.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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 }})
Expand All @@ -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
15 changes: 14 additions & 1 deletion Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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")
],
Expand Down Expand Up @@ -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",
Expand Down
7 changes: 6 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
5 changes: 5 additions & 0 deletions Sources/CFreeType/module.modulemap
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
module CFreeType [system] {
header "shim.h"
link "freetype"
export *
}
3 changes: 3 additions & 0 deletions Sources/CFreeType/shim.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
#include <ft2build.h>
#include FT_FREETYPE_H
#include FT_SIZES_H
93 changes: 93 additions & 0 deletions Sources/GraphiteText/FontFinder.swift
Original file line number Diff line number Diff line change
@@ -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<String> = ["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
137 changes: 137 additions & 0 deletions Sources/GraphiteText/FreeTypeFace.swift
Original file line number Diff line number Diff line change
@@ -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<Void>(())
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
Loading
Loading