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
2 changes: 1 addition & 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. |
| `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. |
| `Graphite` | Re-exports the modules above. |

Everything depends only on the Swift standard library, the C library
Expand Down
14 changes: 11 additions & 3 deletions Sources/GraphiteQuickDraw/Picture.swift
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,12 @@ public enum PictureVerb: Int, Hashable, Sendable {
case frame, paint, erase, invert, fill
}

/// Draws a picture's text: the host's text engine, which draws MacRoman
/// bytes at the port's pen in the port's text settings.
public protocol PictureTextDrawer {
func drawText(macRoman bytes: [UInt8], in port: Port)
}

public struct Picture {

public enum Operation {
Expand Down Expand Up @@ -107,7 +113,7 @@ public struct Picture {

/// DrawPicture: the picture scaled from its frame to a rectangle in the
/// port's coordinates, in the port's state, which is restored after.
public func draw(in port: Port, destination: Rect, decoder: (any PictureImageDecoder)? = nil) {
public func draw(in port: Port, destination: Rect, decoder: (any PictureImageDecoder)? = nil, text: (any PictureTextDrawer)? = nil) {
let saved = (port.pen, port.foreColor, port.backColor, port.backPattern, port.fillPattern, port.clipRegion, port.text)
defer { (port.pen, port.foreColor, port.backColor, port.backPattern, port.fillPattern, port.clipRegion, port.text) = saved }
let map = Mapping(frame: frame, destination: destination)
Expand All @@ -134,8 +140,10 @@ public struct Picture {
case .textFace(let face): port.text.face = face
case .textSize(let size): port.text.size = size
case .textMode(let mode): port.text.mode = mode
case .fontName, .text, .comment:
// Text is drawn by the text engine, which isn't here yet.
case .text(let string, let location):
port.move(to: map.point(location))
text?.drawText(macRoman: string.bytes, in: port)
case .fontName, .comment:
break
case .line(let from, let to):
port.move(to: map.point(from))
Expand Down
198 changes: 198 additions & 0 deletions Sources/GraphiteText/TextLayout.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,198 @@
// ATSUI's layouts: text with styles over ranges of its characters, broken
// into lines at a width, measured, hit-tested and drawn. Each run is drawn
// as QuickDraw draws text in its font, size and face, so the styles a face
// hasn't look the same in both.

import GraphiteBase
import GraphiteQuickDraw

/// A style over a range of a layout's characters (ATSUSetRunStyle).
public struct TextRun: Hashable, Sendable {

/// Character offsets into the layout's text.
public var range: Range<Int>
public var family: Int16
public var size: Int
public var style: TextStyle
public var color: RGBColor

public init(range: Range<Int>, family: Int16 = 0, size: Int = 12, style: TextStyle = [], color: RGBColor = .black) {
self.range = range
self.family = family
self.size = size
self.style = style
self.color = color
}
}

public struct TextLayout {

/// A character placed on a line.
public struct Character: Hashable, Sendable {
/// Its offset in the text.
public var offset: Int
/// Left edge from the layout's left, and its advance.
public var x: Double
public var advance: Double
}

public struct Line {
/// Offsets of the line's characters, a line break's included.
public var range: Range<Int>
public var characters: [Character]
public var width: Double
public var ascent: Int
public var descent: Int
/// The line's baseline from the layout's top.
public var baseline: Int
fileprivate var segments: [(run: TextRun, range: Range<Int>, x: Double)]
}

public let scalars: [Unicode.Scalar]
public let runs: [TextRun]
public private(set) var lines: [Line] = []
public let fonts: FontRegistry

/// A layout of `text` in runs (the text outside every run is drawn in
/// the first), broken at `width` pixels at the last space that fits, and
/// at every return or newline; nil breaks only at those.
public init(text: String, runs: [TextRun], fonts: FontRegistry, width limit: Double? = nil) {
scalars = Array(text.unicodeScalars)
self.fonts = fonts
let fallback = runs.first ?? TextRun(range: 0 ..< scalars.count)
var covered = [TextRun?](repeating: nil, count: scalars.count)
for run in runs {
for index in run.range where index >= 0 && index < scalars.count { covered[index] = run }
}
self.runs = runs
var start = 0
while start < scalars.count || (start == 0 && scalars.isEmpty) {
lines.append(breakLine(from: start, covered: covered.map { $0 ?? fallback }, limit: limit, fallback: fallback))
start = lines.last!.range.upperBound
if scalars.isEmpty { break }
}
var top = 0
for index in lines.indices {
top += lines[index].ascent
lines[index].baseline = top
top += lines[index].descent
}
}

private func port(for run: TextRun) -> Port {
let port = Port(portRect: .zero)
port.text.font = run.family
port.text.size = Int16(clamping: run.size)
port.text.face = run.style.rawValue
return port
}

private func breakLine(from start: Int, covered: [TextRun], limit: Double?, fallback: TextRun) -> Line {
var end = start
var x = 0.0
var lastSpace: Int?
var characters: [Character] = []
var ascent = 0, descent = 0
var segments: [(run: TextRun, range: Range<Int>, x: Double)] = []
scan: while end < scalars.count {
let run = covered[end]
let scratch = port(for: run)
let metrics = scratch.fontInfo(fonts: fonts)
let isBreak = scalars[end] == "\n" || scalars[end] == "\r"
let advance = isBreak ? 0 : Double(scratch.textWidth([scalars[end]], fonts: fonts))
if let limit, !isBreak, x + advance > limit, end > start {
if let space = lastSpace {
characters.removeAll { $0.offset > space }
end = space + 1
segments = segments.compactMap { segment in
segment.range.lowerBound >= end ? nil : (segment.run, segment.range.lowerBound ..< min(segment.range.upperBound, end), segment.x)
}
}
break scan
}
characters.append(Character(offset: end, x: x, advance: advance))
if let last = segments.last, last.run == run {
segments[segments.count - 1].range = last.range.lowerBound ..< end + 1
} else {
segments.append((run, end ..< end + 1, x))
}
ascent = max(ascent, Int(metrics.ascent) + Int(metrics.leading))
descent = max(descent, Int(metrics.descent))
x += advance
end += 1
if scalars[end - 1] == " " { lastSpace = end - 1 }
if isBreak { break scan }
}
if characters.isEmpty {
let metrics = port(for: fallback).fontInfo(fonts: fonts)
ascent = Int(metrics.ascent)
descent = Int(metrics.descent)
}
let width = characters.last.map { $0.x + $0.advance } ?? 0
let finalEnd = max(end, start)
return Line(range: start ..< finalEnd, characters: characters, width: width, ascent: ascent, descent: descent, baseline: 0, segments: segments)
}

// MARK: Measuring

/// The widest line.
public var width: Double { lines.map(\.width).max() ?? 0 }

/// All the lines' height.
public var height: Int { lines.reduce(0) { $0 + $1.ascent + $1.descent } }

/// The line a character offset is on; the last for an offset past the end.
public func lineIndex(containing offset: Int) -> Int {
lines.firstIndex { $0.range.contains(offset) } ?? max(0, lines.count - 1)
}

/// ATSUOffsetToPosition: where a character offset's left edge is, its
/// line's baseline below the top.
public func position(ofOffset offset: Int) -> (x: Double, baseline: Int) {
let line = lines[lineIndex(containing: offset)]
if let character = line.characters.first(where: { $0.offset == offset }) { return (character.x, line.baseline) }
return (line.width, line.baseline)
}

/// ATSUPositionToOffset: the offset of the character whose box holds the
/// point, or of the nearer edge past a line's ends.
public func offset(atX x: Double, y: Int) -> Int {
var line = lines.last!
for candidate in lines where y < candidate.baseline + candidate.descent {
line = candidate
break
}
for character in line.characters where x < character.x + character.advance {
return x < character.x + character.advance / 2 ? character.offset : character.offset + 1
}
return line.range.upperBound
}

// MARK: Drawing

/// ATSUDrawText: the layout with its top left at a point of the port,
/// in the port's own state afterwards.
public func draw(in port: Port, at origin: Point) {
let saved = (port.text, port.foreColor, port.pen.location)
defer { (port.text, port.foreColor, port.pen.location) = saved }
for line in lines {
for segment in line.segments {
port.text.font = segment.run.family
port.text.size = Int16(clamping: segment.run.size)
port.text.face = segment.run.style.rawValue
port.foreColor = segment.run.color
port.move(to: Point(v: origin.v &+ Int16(clamping: line.baseline), h: origin.h &+ Int16(clamping: Int(segment.x.rounded()))))
let characters = scalars[segment.range].filter { $0 != "\n" && $0 != "\r" }
port.drawText(characters, fonts: fonts)
}
}
}
}

extension FontRegistry: PictureTextDrawer {

/// A picture's text, at the port's pen in the port's text settings.
public func drawText(macRoman bytes: [UInt8], in port: Port) {
port.drawText(macRoman: bytes, fonts: self)
}
}
87 changes: 87 additions & 0 deletions Tests/GraphiteTextTests/LayoutTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
import Testing
import GraphiteBase
import GraphiteQuickDraw
import GraphiteText

@Suite struct LayoutTests {

let fonts = FontRegistry()
let red = RGBColor(red8: 0xFF, green8: 0, blue8: 0)

private func layout(_ text: String, width: Double? = nil, runs: [TextRun]? = nil) -> TextLayout {
TextLayout(text: text, runs: runs ?? [TextRun(range: 0 ..< text.unicodeScalars.count)], fonts: fonts, width: width)
}

@Test func measuresAsQuickDrawDoes() {
let layout = layout("Hi!")
let port = Port(portRect: .zero)
#expect(layout.width == Double(port.textWidth("Hi!".unicodeScalars, fonts: fonts)))
#expect(layout.lines.count == 1)
#expect(layout.height == 14)
#expect(layout.lines[0].baseline == 12)
}

@Test func linesBreakAtSpacesAndReturns() {
let wrapped = layout("ab cd ef", width: 30)
#expect(wrapped.lines.map(\.range) == [0 ..< 3, 3 ..< 6, 6 ..< 8])
#expect(wrapped.lines[1].baseline == 12 + 2 + 12)
let returns = layout("a\rb\nc")
#expect(returns.lines.count == 3)
#expect(returns.lines.map(\.range) == [0 ..< 2, 2 ..< 4, 4 ..< 5])
#expect(layout("").lines.count == 1)
}

@Test func positionsAndHitTesting() {
let layout = layout("Hi")
// H is 8 pixels with its spacing, i is 4.
#expect(layout.position(ofOffset: 0).x == 0)
#expect(layout.position(ofOffset: 1).x == 8)
#expect(layout.position(ofOffset: 2).x == 12)
#expect(layout.offset(atX: 1, y: 5) == 0)
#expect(layout.offset(atX: 6, y: 5) == 1)
#expect(layout.offset(atX: 9, y: 5) == 1)
#expect(layout.offset(atX: 100, y: 5) == 2)
let two = self.layout("ab\ncd")
#expect(two.offset(atX: 0, y: 20) == 3)
#expect(two.position(ofOffset: 4).baseline == two.lines[1].baseline)
}

@Test func runsHaveTheirOwnSizesAndColors() {
let runs = [TextRun(range: 0 ..< 1), TextRun(range: 1 ..< 2, size: 24, color: red)]
let styled = layout("HH", runs: runs)
#expect(styled.lines[0].characters[1].advance == 2 * styled.lines[0].characters[0].advance)
#expect(styled.lines[0].ascent == 24)
let port = Port(pixels: PixelBuffer(bounds: Rect(top: 0, left: 0, bottom: 40, right: 60), format: .argb32))
port.perform(.erase, rect: port.portRect)
styled.draw(in: port, at: Point(v: 2, h: 2))
// The first H small and black, the second large and red.
#expect(port.pixels?.color(at: Point(v: 2 + 24 - 5, h: 2 + 1)) == .black)
#expect(port.pixels?.color(at: Point(v: 2 + 24 - 5, h: 2 + 8 + 2)) == red)
// The port's own settings are back.
#expect(port.foreColor == .black)
#expect(port.text.size == 0)
}

@Test func pictureText() throws {
var writer = BigEndianWriter()
writer.write(UInt16(0))
for value: Int16 in [0, 0, 16, 40] { writer.write(UInt16(bitPattern: value)) }
writer.write(bytes: [0x00, 0x11, 0x02, 0xFF, 0x0C, 0x00])
writer.writeZeros(24)
writer.write(UInt16(0x0028)) // LongText
writer.write(UInt16(12))
writer.write(UInt16(1))
writer.write(bytes: ("Hi" as PascalString).lengthPrefixed)
writer.write(bytes: [0x00])
writer.write(UInt16(0x00FF))
let picture = try Picture(bytes: writer.bytes)
let port = Port(pixels: PixelBuffer(bounds: Rect(top: 0, left: 0, bottom: 16, right: 40), format: .indexed(depth: 1)))
port.perform(.erase, rect: port.portRect)
picture.draw(in: port, destination: port.portRect, text: fonts)
#expect(port.pixels?.color(at: Point(v: 5, h: 1)) == .black)
let plain = Port(pixels: PixelBuffer(bounds: Rect(top: 0, left: 0, bottom: 16, right: 40), format: .indexed(depth: 1)))
plain.perform(.erase, rect: plain.portRect)
picture.draw(in: plain, destination: plain.portRect)
#expect(plain.pixels?.color(at: Point(v: 5, h: 1)) == .white)
}
}
Loading