diff --git a/Package.swift b/Package.swift index f9325aa..1482379 100644 --- a/Package.swift +++ b/Package.swift @@ -70,7 +70,8 @@ let package = Package( .default(enabledTraits: ["FreeType"]), ], dependencies: [ - .package(url: "https://github.com/apple/swift-system.git", from: "1.9.0") + .package(url: "https://github.com/apple/swift-system.git", from: "1.9.0"), + .package(url: "https://github.com/PureSwift/swift-freetype.git", branch: "master"), ], targets: [ .target( @@ -103,18 +104,13 @@ let package = Package( ), .target( name: "GraphiteQuickDraw", - dependencies: ["GraphiteBase"] - ), - .systemLibrary( - name: "CFreeType", - pkgConfig: "freetype2", - providers: [.apt(["libfreetype-dev"]), .brew(["freetype"])] + dependencies: ["GraphiteBase", "GraphiteFiles", "GraphiteResources"] ), .target( name: "GraphiteText", dependencies: [ "GraphiteBase", "GraphiteQuickDraw", - .target(name: "CFreeType", condition: .when(traits: ["FreeType"])), + .product(name: "FreeTypeSwift", package: "swift-freetype", condition: .when(traits: ["FreeType"])), ] ), .target( @@ -143,7 +139,7 @@ let package = Package( ), .testTarget( name: "GraphiteQuickDrawTests", - dependencies: ["GraphiteQuickDraw"] + dependencies: ["GraphiteQuickDraw", "GraphiteFiles", "GraphiteResources"] ), .testTarget( name: "GraphiteTextTests", diff --git a/Sources/CFreeType/module.modulemap b/Sources/CFreeType/module.modulemap deleted file mode 100644 index 73e1cf0..0000000 --- a/Sources/CFreeType/module.modulemap +++ /dev/null @@ -1,5 +0,0 @@ -module CFreeType [system] { - header "shim.h" - link "freetype" - export * -} diff --git a/Sources/CFreeType/shim.h b/Sources/CFreeType/shim.h deleted file mode 100644 index d1721e7..0000000 --- a/Sources/CFreeType/shim.h +++ /dev/null @@ -1,3 +0,0 @@ -#include -#include FT_FREETYPE_H -#include FT_SIZES_H diff --git a/Sources/GraphiteBase/BigEndianReader.swift b/Sources/GraphiteBase/BigEndianReader.swift index d1f55e1..b760176 100644 --- a/Sources/GraphiteBase/BigEndianReader.swift +++ b/Sources/GraphiteBase/BigEndianReader.swift @@ -2,6 +2,8 @@ // AppleDouble files from bytes. Every read checks its bounds and throws // past the end; none traps, whatever the bytes say. +import struct Foundation.Data + /// A read that went past the bytes there are. public struct BigEndianReadError: Error, Hashable, Sendable { @@ -24,26 +26,33 @@ public struct BigEndianReadError: Error, Hashable, Sendable { /// Reads typed fields one after another from bytes. public struct BigEndianReader: Sendable { - public let bytes: [UInt8] + /// The bytes as given, which may be a slice that doesn't start at 0; + /// offsets are from its start. + private let storage: Data /// Where the next read starts. public var offset: Int - public init(_ bytes: [UInt8], offset: Int = 0) { - self.bytes = bytes + /// Reads the bytes where they are, without copying them: a file mapped + /// into memory is read as its pages are used. + public init(_ bytes: Data, offset: Int = 0) { + storage = bytes self.offset = offset } - public var count: Int { bytes.count } + /// All the bytes, from index 0 (a copy, if the reader is of a slice). + public var bytes: Data { storage.startIndex == 0 ? storage : Data(storage) } + + public var count: Int { storage.count } - public var remaining: Int { max(0, bytes.count - offset) } + public var remaining: Int { max(0, storage.count - offset) } - public var isAtEnd: Bool { offset >= bytes.count } + public var isAtEnd: Bool { offset >= storage.count } /// The range of `count` bytes at `offset`, if they're all there. private func range(at offset: Int, count: Int) throws(BigEndianReadError) -> Range { - guard offset >= 0, count >= 0, offset <= bytes.count, count <= bytes.count - offset else { - throw BigEndianReadError(offset: offset, count: count, available: bytes.count) + guard offset >= 0, count >= 0, offset <= storage.count, count <= storage.count - offset else { + throw BigEndianReadError(offset: offset, count: count, available: storage.count) } return offset ..< offset + count } @@ -53,7 +62,7 @@ public struct BigEndianReader: Sendable { let range = try range(at: offset, count: MemoryLayout.size) var value: T = 0 for index in range { - value = value << 8 | T(truncatingIfNeeded: bytes[index]) + value = value << 8 | T(truncatingIfNeeded: storage[storage.startIndex + index]) } return value } @@ -64,10 +73,13 @@ public struct BigEndianReader: Sendable { return value } - public mutating func readBytes(_ count: Int) throws(BigEndianReadError) -> ArraySlice { + /// The next `count` bytes, as a slice of the reader's: its indices are + /// the reader's, not from 0, so take them with `Array(_:)` or by + /// iterating. + public mutating func readBytes(_ count: Int) throws(BigEndianReadError) -> Data { let range = try range(at: offset, count: count) offset = range.upperBound - return bytes[range] + return storage[storage.startIndex + range.lowerBound ..< storage.startIndex + range.upperBound] } public mutating func skip(_ count: Int) throws(BigEndianReadError) { @@ -85,17 +97,18 @@ public struct BigEndianReader: Sendable { public mutating func align(to alignment: Int) { guard alignment > 1 else { return } let padding = (alignment - offset % alignment) % alignment - offset = min(offset + padding, max(offset, bytes.count)) + offset = min(offset + padding, max(offset, storage.count)) } /// A reader of the next `count` bytes, which this one moves past. public mutating func subreader(_ count: Int) throws(BigEndianReadError) -> BigEndianReader { - BigEndianReader(Array(try readBytes(count))) + BigEndianReader(try readBytes(count)) } /// A reader of `count` bytes at `offset`, without moving. public func subreader(at offset: Int, count: Int) throws(BigEndianReadError) -> BigEndianReader { - BigEndianReader(Array(bytes[try range(at: offset, count: count)])) + let range = try range(at: offset, count: count) + return BigEndianReader(storage[storage.startIndex + range.lowerBound ..< storage.startIndex + range.upperBound]) } } diff --git a/Sources/GraphiteBase/ContiguousBytes.swift b/Sources/GraphiteBase/ContiguousBytes.swift new file mode 100644 index 0000000..52befd9 --- /dev/null +++ b/Sources/GraphiteBase/ContiguousBytes.swift @@ -0,0 +1,44 @@ +// Bytes from anywhere: an array, a Data (which may be a file mapped into +// memory), a raw buffer or a slice of one. Parsers take `some +// ContiguousBytes` so a caller keeps what it has, and copy out only what +// they keep. + +import protocol Foundation.ContiguousBytes +import struct Foundation.Data + +public extension Array where Element == UInt8 { + + /// The bytes of anything contiguous, copied. An array is returned as it + /// is, and shares its storage until one of them changes. Copying a + /// mapped Data reads all of it. + init(copying bytes: some ContiguousBytes) { + if let array = bytes as? [UInt8] { + self = array + } else { + self = bytes.withUnsafeBytes { Array($0) } + } + } +} + +public extension Data { + + /// The bytes of anything contiguous as a Data whose indices start at 0. + /// A Data that already does is itself, mapped or not; a slice of one, + /// and any other bytes, are copied. + init(zeroBased bytes: some ContiguousBytes) { + if let data = bytes as? Data, data.startIndex == 0 { + self = data + } else { + self = bytes.withUnsafeBytes { Data($0) } + } + } +} + +public extension BigEndianReader { + + /// A reader of the bytes of anything contiguous, from `offset`. A Data + /// is read where it is; anything else is copied into one. + init(_ bytes: some ContiguousBytes, offset: Int = 0) { + self.init(bytes as? Data ?? bytes.withUnsafeBytes { Data($0) }, offset: offset) + } +} diff --git a/Sources/GraphiteFiles/AppleDouble.swift b/Sources/GraphiteFiles/AppleDouble.swift index aac2c02..81690c9 100644 --- a/Sources/GraphiteFiles/AppleDouble.swift +++ b/Sources/GraphiteFiles/AppleDouble.swift @@ -9,6 +9,7 @@ // Files/HostVolume.cpp (ADFJumpToResourceFork): // Copyright (c) 2020 Iliyas Jorio. MIT License. +import protocol Foundation.ContiguousBytes import GraphiteBase /// An AppleDouble or AppleSingle file's entries. @@ -52,13 +53,13 @@ public struct AppleDouble: Hashable, Sendable { } /// Whether bytes start as an AppleDouble or AppleSingle file does. - public static func isAppleDouble(_ bytes: [UInt8]) -> Bool { + public static func isAppleDouble(_ bytes: some ContiguousBytes) -> Bool { guard let magic = try? BigEndianReader(bytes).peek(UInt32.self, at: 0) else { return false } return magic == appleDoubleMagic || magic == appleSingleMagic } /// Throws for bytes that aren't one, or an entry past their end. - public init(bytes: [UInt8]) throws(MacError) { + public init(bytes: some ContiguousBytes) throws(MacError) { do { var reader = BigEndianReader(bytes) let magic = try reader.read(UInt32.self) @@ -72,7 +73,7 @@ public struct AppleDouble: Hashable, Sendable { let offset = Int(try reader.read(UInt32.self)) let length = Int(try reader.read(UInt32.self)) let entry = try reader.subreader(at: offset, count: length) - entries.append(Entry(id: EntryID(rawValue: id), bytes: entry.bytes)) + entries.append(Entry(id: EntryID(rawValue: id), bytes: Array(entry.bytes))) } } catch let error as MacError { throw error diff --git a/Sources/GraphiteQuickDraw/ColorTable.swift b/Sources/GraphiteQuickDraw/ColorTable.swift index d0dd72c..8945863 100644 --- a/Sources/GraphiteQuickDraw/ColorTable.swift +++ b/Sources/GraphiteQuickDraw/ColorTable.swift @@ -2,6 +2,7 @@ // the tables indexed pixels look their colors up in, with the system's // standard ones for each depth. +import protocol Foundation.ContiguousBytes import GraphiteBase /// QuickDraw's RGBColor: 16 bits a component. @@ -140,7 +141,7 @@ public struct ColorTable: Hashable, Sendable { /// A 'clut' resource: ctSeed, ctFlags, ctSize (the count less one), /// then each entry's value and red, green and blue. A device table's /// entries are in order whatever their values say. - public init(clut bytes: [UInt8]) throws(MacError) { + public init(clut bytes: some ContiguousBytes) throws(MacError) { var reader = BigEndianReader(bytes) do { seed = Int32(bitPattern: try reader.read(UInt32.self)) diff --git a/Sources/GraphiteQuickDraw/Cursor.swift b/Sources/GraphiteQuickDraw/Cursor.swift index ecd030a..358f9f3 100644 --- a/Sources/GraphiteQuickDraw/Cursor.swift +++ b/Sources/GraphiteQuickDraw/Cursor.swift @@ -3,6 +3,8 @@ // Where data and mask are both set the pixel is black; mask alone, white; // data alone, the screen inverted; neither, the screen as it is. +import protocol Foundation.ContiguousBytes +import struct Foundation.Data import GraphiteBase public struct Cursor: Hashable, Sendable { @@ -32,7 +34,7 @@ public struct Cursor: Hashable, Sendable { /// A 'CURS' resource or a Cursor record: data, mask, hot spot (68 /// bytes). - public init(curs bytes: [UInt8]) throws(MacError) { + public init(curs bytes: some ContiguousBytes) throws(MacError) { do { var reader = BigEndianReader(bytes) let data = try (0 ..< 16).map { _ throws(BigEndianReadError) in try reader.read(UInt16.self) } @@ -57,9 +59,10 @@ public struct Cursor: Hashable, Sendable { /// A 'crsr' resource: its CCrsr record (crsrType, offsets of its pixel /// map and pixels, its 1-bit data, mask and hot spot), then the pixel /// map, which points to its color table by offset too. - public init(crsr bytes: [UInt8]) throws(MacError) { + public init(crsr bytes: some ContiguousBytes) throws(MacError) { + let source = Data(zeroBased: bytes) do { - var reader = BigEndianReader(bytes) + var reader = BigEndianReader(source) try reader.skip(2) // crsrType let mapOffset = Int(try reader.read(UInt32.self)) let dataOffset = Int(try reader.read(UInt32.self)) @@ -67,7 +70,7 @@ public struct Cursor: Hashable, Sendable { let data = try (0 ..< 16).map { _ throws(BigEndianReadError) in try reader.read(UInt16.self) } let mask = try (0 ..< 16).map { _ throws(BigEndianReadError) in try reader.read(UInt16.self) } let v = Int16(bitPattern: try reader.read(UInt16.self)), h = Int16(bitPattern: try reader.read(UInt16.self)) - var map = try BigEndianReader(bytes).subreader(at: mapOffset, count: 50) + var map = try BigEndianReader(source).subreader(at: mapOffset, count: 50) try map.skip(4) let rowBytes = Int(try map.read(UInt16.self) & 0x3FFF) let top = Int(Int16(bitPattern: try map.read(UInt16.self))), left = Int(Int16(bitPattern: try map.read(UInt16.self))) @@ -78,11 +81,11 @@ public struct Cursor: Hashable, Sendable { let tableOffset = Int(try map.read(UInt32.self)) let width = right - left, height = bottom - top guard width > 0, height > 0, width <= 64, height <= 64, [1, 2, 4, 8].contains(depth) else { throw MacError.parameter } - var tableReader = try BigEndianReader(bytes).subreader(at: tableOffset, count: 8) + var tableReader = try BigEndianReader(source).subreader(at: tableOffset, count: 8) try tableReader.skip(6) let entries = Int(try tableReader.read(UInt16.self)) + 1 - let table = try ColorTable(clut: try BigEndianReader(bytes).subreader(at: tableOffset, count: 8 + entries * 8).bytes) - let pixels = try BigEndianReader(bytes).subreader(at: dataOffset, count: rowBytes * height).bytes + let table = try ColorTable(clut: try BigEndianReader(source).subreader(at: tableOffset, count: 8 + entries * 8).bytes) + let pixels = try BigEndianReader(source).subreader(at: dataOffset, count: rowBytes * height).bytes var image: [UInt32] = [] for row in 0 ..< height { for column in 0 ..< width { diff --git a/Sources/GraphiteQuickDraw/CursorState.swift b/Sources/GraphiteQuickDraw/CursorState.swift new file mode 100644 index 0000000..f4e0e30 --- /dev/null +++ b/Sources/GraphiteQuickDraw/CursorState.swift @@ -0,0 +1,67 @@ +// The cursor a program has set: InitCursor, SetCursor, HideCursor and +// ShowCursor, and the cursors it made of its own pixels and set by name. +// A host reads `current` and `isVisible` to show the cursor. + +import GraphiteBase + +public struct CursorState: Hashable, Sendable { + + /// The cursor to show: the arrow until a program sets another. + public private(set) var current = Cursor.arrow + + /// HideCursor calls not yet matched by ShowCursor. + public private(set) var hideCount = 0 + + private var named: [String: Cursor] = [:] + + public init() {} + + public var isVisible: Bool { hideCount == 0 } + + /// InitCursor: the arrow, shown. + public mutating func initialize() { + current = .arrow + hideCount = 0 + } + + /// SetCursor. + public mutating func set(_ cursor: Cursor) { + current = cursor + } + + /// HideCursor. Calls nest. + public mutating func hide() { + hideCount += 1 + } + + /// ShowCursor. More calls than HideCursor's change nothing. + public mutating func show() { + if hideCount > 0 { hideCount -= 1 } + } + + /// QDRegisterNamedPixMapCursor: a cursor of 32-bit ARGB pixels, kept + /// under a name; a name used before is replaced. The pixels are copied, + /// as the program goes on to free its world. + public mutating func register(pixels: PixelBuffer, hotSpot: Point, name: String) throws(MacError) { + guard !name.isEmpty, pixels.format == .argb32, pixels.width > 0, pixels.height > 0 else { throw .parameter } + var image: [UInt32] = [] + image.reserveCapacity(pixels.width * pixels.height) + for row in 0 ..< pixels.height { + for column in 0 ..< pixels.width { + image.append(pixels.value(column: column, row: row)) + } + } + named[name] = Cursor(data: [], mask: [], hotSpot: hotSpot, colorImage: image, colorWidth: pixels.width) + } + + /// QDSetNamedPixMapCursor. + public mutating func setNamed(_ name: String) throws(MacError) { + guard let cursor = named[name] else { throw .parameter } + current = cursor + } + + /// QDUnregisterNamedPixMapCursor. The cursor on show stays until another is set. + public mutating func unregister(_ name: String) throws(MacError) { + guard named.removeValue(forKey: name) != nil else { throw .parameter } + } +} diff --git a/Sources/GraphiteQuickDraw/DeviceColors.swift b/Sources/GraphiteQuickDraw/DeviceColors.swift new file mode 100644 index 0000000..737aea4 --- /dev/null +++ b/Sources/GraphiteQuickDraw/DeviceColors.swift @@ -0,0 +1,43 @@ +// The color table a device's indexed pixels look up: Index2Color, +// SetEntries and RestoreDeviceClut, and CTabChanged for any table. + +import GraphiteBase + +extension ColorTable { + + /// CTabChanged: a program changed the colors, so anything cached from + /// them is stale. + public mutating func changed() { + seed &+= 1 + } +} + +extension GraphicsDevice { + + /// Index2Color: the color of a pixel value on this device. Nil on a + /// direct device, whose pixels hold colors, not indexes. + public func color(forIndex index: Int) -> RGBColor? { + guard pixels.format.isIndexed, index >= 0, index < pixels.colorTable.colors.count else { return nil } + return pixels.colorTable.colors[index] + } + + /// SetEntries: colors written into the device's table from `start`, + /// as many as the table has room for. Does nothing on a direct device. + public func setEntries(from start: Int, colors: [RGBColor]) throws(MacError) { + guard pixels.format.isIndexed else { return } + guard start >= 0, start < pixels.colorTable.colors.count else { throw .parameter } + for (offset, color) in colors.enumerated() where start + offset < pixels.colorTable.colors.count { + pixels.colorTable.colors[start + offset] = color + } + pixels.colorTable.changed() + } + + /// RestoreDeviceClut: the system's standard table for the device's + /// depth again. Does nothing on a direct device. + public func restoreColorTable() { + guard pixels.format.isIndexed, var standard = ColorTable.standard(depth: depth) else { return } + standard.seed = pixels.colorTable.seed + standard.changed() + pixels.colorTable = standard + } +} diff --git a/Sources/GraphiteQuickDraw/FileIcon.swift b/Sources/GraphiteQuickDraw/FileIcon.swift new file mode 100644 index 0000000..0b95fe0 --- /dev/null +++ b/Sources/GraphiteQuickDraw/FileIcon.swift @@ -0,0 +1,72 @@ +// The icon a file, folder or bundle has of its own, as Icon Services finds +// it for GetIconRefFromFile: a custom icon kept in the item's resource +// fork, a bundle's CFBundleIconFile, or the .icns file itself. Icons from +// a file's type and creator, and the system's generic ones, are not here. + +import GraphiteBase +import GraphiteFiles +import GraphiteResources + +extension IconFamily { + + /// kCustomIconResource: where the Finder keeps an item's custom icon. + public static var customIconResourceID: Int16 { -16455 } + + /// The icon of the item at a path, or nil if it has none (or isn't + /// there). In the order the Finder looks: + /// + /// 1. an .icns file is its own icon; + /// 2. a custom icon in the item's resource fork: an 'icns' resource, or + /// 'ICN#', 'icl8' and the rest, all of ID -16455; + /// 3. a bundle's icon: the file CFBundleIconFile names in its + /// Contents/Info.plist, in Contents/Resources; + /// 4. a folder's custom icon, in the resource fork of its "Icon\r" file. + /// + /// The custom icon's Finder flag is not checked: a resource of the ID is + /// enough. + public init?(ofItemAt path: String) { + if path.lowercased().hasSuffix(".icns") { + guard let family = Self.family(icnsFileAt: path) else { return nil } + self = family + return + } + if let family = Self.customIcon(inResourceForkOf: path) + ?? Self.bundleIcon(at: path) + ?? Self.customIcon(inResourceForkOf: path + "/Icon\r") { + self = family + return + } + return nil + } + + private static func family(icnsFileAt path: String) -> IconFamily? { + guard let fork = try? Fork(path: path, kind: .data, permission: .read), + let bytes = try? fork.contents() else { return nil } + return try? IconFamily(icns: bytes) + } + + private static let customIconTypes: [FourCharCode] = ["ICN#", "ics#", "icl4", "icl8", "ics4", "ics8"] + + private static func customIcon(inResourceForkOf path: String) -> IconFamily? { + guard let fork = try? Fork(path: path, kind: .resource, permission: .read), + let resources = try? ResourceFile(fork: fork) else { return nil } + let id = customIconResourceID + if let bytes = try? resources.bytes(type: "icns", id: id), let family = try? IconFamily(icns: bytes) { + return family + } + var members: [FourCharCode: [UInt8]] = [:] + for type in customIconTypes { + if let bytes = try? resources.bytes(type: type, id: id) { members[type] = bytes } + } + return members.isEmpty ? nil : IconFamily(members: members) + } + + private static func bundleIcon(at path: String) -> IconFamily? { + guard let fork = try? Fork(path: path + "/Contents/Info.plist", kind: .data, permission: .read), + let bytes = try? fork.contents(), + let plist = try? InfoPlist(bytes: bytes), + let name = plist["CFBundleIconFile"], !name.isEmpty, !name.contains("/") else { return nil } + let file = name.lowercased().hasSuffix(".icns") ? name : name + ".icns" + return family(icnsFileAt: path + "/Contents/Resources/" + file) + } +} diff --git a/Sources/GraphiteQuickDraw/GraphicsDevice.swift b/Sources/GraphiteQuickDraw/GraphicsDevice.swift index 5ffaea4..12fae81 100644 --- a/Sources/GraphiteQuickDraw/GraphicsDevice.swift +++ b/Sources/GraphiteQuickDraw/GraphicsDevice.swift @@ -131,6 +131,9 @@ public final class QuickDraw { /// The random seed QuickDraw's Random advances. public var random = QuickDrawRandom() + /// The cursor, as InitCursor, SetCursor, HideCursor and ShowCursor leave it. + public var cursor = CursorState() + public init(screens: [GraphicsDevice]) { self.screens = screens currentDevice = screens.first diff --git a/Sources/GraphiteQuickDraw/IconFamily.swift b/Sources/GraphiteQuickDraw/IconFamily.swift index 48cf7f8..5b4cd1b 100644 --- a/Sources/GraphiteQuickDraw/IconFamily.swift +++ b/Sources/GraphiteQuickDraw/IconFamily.swift @@ -3,6 +3,8 @@ // X's icon families ('icns'), each made an ARGB image with its mask as // alpha. Indexed icons use the system's 4- and 8-bit tables. +import protocol Foundation.ContiguousBytes +import struct Foundation.Data import GraphiteBase /// An icon family's members by their types, and the best image of each @@ -17,11 +19,11 @@ public struct IconFamily: Sendable { } /// An 'icns' file or resource: its members after its header. - public init(icns bytes: [UInt8]) throws(MacError) { + public init(icns bytes: some ContiguousBytes) throws(MacError) { var reader = BigEndianReader(bytes) do { guard try reader.read(UInt32.self) == FourCharCode("icns").rawValue else { throw MacError.parameter } - let length = min(Int(try reader.read(UInt32.self)), bytes.count) + let length = min(Int(try reader.read(UInt32.self)), reader.count) members = [:] while reader.offset + 8 <= length { let type = FourCharCode(try reader.read(UInt32.self)) @@ -141,9 +143,10 @@ public struct ColorIcon: Sendable { /// The 'cicn' resource's IconPMap (50 bytes), maskBMap and iconBMap /// (14 each), iconData (4), then the mask's rows, the 1-bit image's, /// the pixel map's color table and its rows. - public init(cicn bytes: [UInt8]) throws(MacError) { + public init(cicn bytes: some ContiguousBytes) throws(MacError) { + let source = Data(zeroBased: bytes) do { - var reader = BigEndianReader(bytes) + var reader = BigEndianReader(source) try reader.skip(4) // baseAddr let rowBytes = Int(try reader.read(UInt16.self) & 0x3FFF) let bounds = try Self.rect(&reader) @@ -163,7 +166,7 @@ public struct ColorIcon: Sendable { let tableStart = reader.offset try reader.skip(6) let entries = Int(try reader.read(UInt16.self)) + 1 - let table = try ColorTable(clut: Array(try BigEndianReader(bytes).subreader(at: tableStart, count: 8 + entries * 8).bytes)) + let table = try ColorTable(clut: try BigEndianReader(source).subreader(at: tableStart, count: 8 + entries * 8).bytes) try reader.seek(to: tableStart + 8 + entries * 8) let pixels = Array(try reader.readBytes(rowBytes * height)) self.bounds = bounds diff --git a/Sources/GraphiteQuickDraw/PackBits.swift b/Sources/GraphiteQuickDraw/PackBits.swift index 1a81f7f..b3bf9f6 100644 --- a/Sources/GraphiteQuickDraw/PackBits.swift +++ b/Sources/GraphiteQuickDraw/PackBits.swift @@ -4,6 +4,7 @@ // -1 to -127; -128 is skipped. Pictures' 16-bit pixels repeat two bytes at a // time. +import protocol Foundation.ContiguousBytes import GraphiteBase public enum PackBits { @@ -26,7 +27,7 @@ public enum PackBits { } /// Unpacks all of `data`. - public static func unpack(_ data: [UInt8], count: Int, unit: Int = 1) throws(MacError) -> [UInt8] { + public static func unpack(_ data: some ContiguousBytes, count: Int, unit: Int = 1) throws(MacError) -> [UInt8] { var reader = BigEndianReader(data) do { return try unpack(&reader, count: count, unit: unit) @@ -37,7 +38,8 @@ public enum PackBits { /// Packs bytes as PackBits does: runs of three or more the same as a /// repeat, the rest as literals of at most 128. - public static func pack(_ bytes: [UInt8]) -> [UInt8] { + public static func pack(_ input: some ContiguousBytes) -> [UInt8] { + let bytes = Array(copying: input) var packed: [UInt8] = [] var index = 0 var literal: [UInt8] = [] diff --git a/Sources/GraphiteQuickDraw/Palette.swift b/Sources/GraphiteQuickDraw/Palette.swift new file mode 100644 index 0000000..3a23cff --- /dev/null +++ b/Sources/GraphiteQuickDraw/Palette.swift @@ -0,0 +1,98 @@ +// The Palette Manager's palettes: the colors a window asks for, each with +// the way it wants to be given them. A palette is a handle in Carbon, so +// it is a class here; two references to it see the same changes. + +import GraphiteBase + +/// The usage an entry asks for (pmCourteous, pmDithered, pmTolerant, +/// pmAnimated, pmExplicit and the rest). Courteous, the default, is the +/// empty set. +public struct PaletteUsage: OptionSet, Hashable, Sendable { + + public var rawValue: Int16 + + public init(rawValue: Int16) { + self.rawValue = rawValue + } + + public static var dithered: PaletteUsage { PaletteUsage(rawValue: 0x0001) } + public static var tolerant: PaletteUsage { PaletteUsage(rawValue: 0x0002) } + public static var animated: PaletteUsage { PaletteUsage(rawValue: 0x0004) } + public static var explicit: PaletteUsage { PaletteUsage(rawValue: 0x0008) } + public static var white: PaletteUsage { PaletteUsage(rawValue: 0x0010) } + public static var black: PaletteUsage { PaletteUsage(rawValue: 0x0020) } +} + +/// One color of a palette: the color, how it is asked for, and how far a +/// tolerant request may be from it (a color's component units). +public struct PaletteEntry: Hashable, Sendable { + + public var color: RGBColor + public var usage: PaletteUsage + public var tolerance: Int16 + + public init(color: RGBColor = .black, usage: PaletteUsage = [], tolerance: Int16 = 0) { + self.color = color + self.usage = usage + self.tolerance = tolerance + } +} + +public final class Palette { + + public private(set) var entries: [PaletteEntry] + + /// NewPalette: `count` entries, their colors from a table's where it has + /// them (CTab2Palette) and black where it hasn't, all with one usage and + /// tolerance. + public init(count: Int, colors: ColorTable? = nil, usage: PaletteUsage = [], tolerance: Int16 = 0) { + entries = (0 ..< max(0, min(count, Int(Int16.max)))).map { index in + PaletteEntry(color: colors?.colors.indices.contains(index) == true ? colors![index] : .black, + usage: usage, tolerance: tolerance) + } + } + + public var count: Int { entries.count } + + /// Palette2CTab: the palette's colors as a table. + public var colorTable: ColorTable { + ColorTable(colors: entries.map(\.color)) + } + + /// GetEntryColor. + public func color(at index: Int) throws(MacError) -> RGBColor { + guard entries.indices.contains(index) else { throw .parameter } + return entries[index].color + } + + /// SetEntryColor. + public func setColor(_ color: RGBColor, at index: Int) throws(MacError) { + guard entries.indices.contains(index) else { throw .parameter } + entries[index].color = color + } + + /// GetEntryUsage. + public func usage(at index: Int) throws(MacError) -> (usage: PaletteUsage, tolerance: Int16) { + guard entries.indices.contains(index) else { throw .parameter } + return (entries[index].usage, entries[index].tolerance) + } + + /// SetEntryUsage. + public func setUsage(_ usage: PaletteUsage, tolerance: Int16, at index: Int) throws(MacError) { + guard entries.indices.contains(index) else { throw .parameter } + entries[index].usage = usage + entries[index].tolerance = tolerance + } + + /// CopyPalette: entries of another palette copied over this one's from + /// `destinationEntry`, as many as `length` and both palettes have. + public func copy(from source: Palette, sourceEntry: Int, destinationEntry: Int, length: Int) throws(MacError) { + guard source.entries.indices.contains(sourceEntry), entries.indices.contains(destinationEntry), length >= 0 else { + throw .parameter + } + let amount = min(length, source.count - sourceEntry, count - destinationEntry) + // Taken first, as a palette may be copied over itself. + let moved = Array(source.entries[sourceEntry ..< sourceEntry + amount]) + entries.replaceSubrange(destinationEntry ..< destinationEntry + amount, with: moved) + } +} diff --git a/Sources/GraphiteQuickDraw/Picture.swift b/Sources/GraphiteQuickDraw/Picture.swift index 7f036de..8996730 100644 --- a/Sources/GraphiteQuickDraw/Picture.swift +++ b/Sources/GraphiteQuickDraw/Picture.swift @@ -5,6 +5,8 @@ // picture with them still draws the rest. Drawing scales the frame to the // destination rectangle. +import protocol Foundation.ContiguousBytes +import struct Foundation.Data import GraphiteBase /// Decodes a QuickTime-compressed image in a picture: JPEG, PNG and the @@ -79,7 +81,7 @@ public struct Picture { /// A picture's bytes, from picSize. Throws for a picture that ends /// before its end opcode, or whose data is malformed. - public init(bytes: [UInt8]) throws(MacError) { + public init(bytes: some ContiguousBytes) throws(MacError) { var reader = BigEndianReader(bytes) do { try reader.skip(2) // picSize: its low 16 bits alone @@ -104,9 +106,10 @@ public struct Picture { } /// A PICT file's picture: after its 512-byte header. - public init(file bytes: [UInt8]) throws(MacError) { - guard bytes.count > 512 else { throw .parameter } - try self.init(bytes: Array(bytes[512...])) + public init(file bytes: some ContiguousBytes) throws(MacError) { + let file = Data(zeroBased: bytes) + guard file.count > 512 else { throw .parameter } + try self.init(bytes: file[512...]) } // MARK: Drawing diff --git a/Sources/GraphiteQuickDraw/Region.swift b/Sources/GraphiteQuickDraw/Region.swift index 9f948f4..3f72442 100644 --- a/Sources/GraphiteQuickDraw/Region.swift +++ b/Sources/GraphiteQuickDraw/Region.swift @@ -5,6 +5,7 @@ // 0x7FFF) is read and written for programs that keep regions in their // memory. +import protocol Foundation.ContiguousBytes import GraphiteBase public struct Region: Hashable, Sendable { @@ -232,7 +233,7 @@ public struct Region: Hashable, Sendable { /// A region record. A record of 10 bytes is its rectangle; past those, /// its scanlines. Throws for one that ends early or whose points don't /// pair up. - public init(record bytes: [UInt8]) throws(MacError) { + public init(record bytes: some ContiguousBytes) throws(MacError) { do { var reader = BigEndianReader(bytes) let size = Int(try reader.read(UInt16.self)) diff --git a/Sources/GraphiteQuickDraw/Shapes.swift b/Sources/GraphiteQuickDraw/Shapes.swift index 75498fa..9c6ca16 100644 --- a/Sources/GraphiteQuickDraw/Shapes.swift +++ b/Sources/GraphiteQuickDraw/Shapes.swift @@ -4,6 +4,7 @@ // the pen's rectangle, hanging below and to the right of each point the // line passes through. +import protocol Foundation.ContiguousBytes import GraphiteBase /// A polygon: its points in order, closed or not. @@ -42,7 +43,7 @@ public struct Polygon: Hashable, Sendable { } /// A polygon record: as many points as polySize says. - public init(record bytes: [UInt8]) throws(MacError) { + public init(record bytes: some ContiguousBytes) throws(MacError) { do { var reader = BigEndianReader(bytes) let size = Int(try reader.read(UInt16.self)) diff --git a/Sources/GraphiteResources/ForkContents.swift b/Sources/GraphiteResources/ForkContents.swift new file mode 100644 index 0000000..bb91fbe --- /dev/null +++ b/Sources/GraphiteResources/ForkContents.swift @@ -0,0 +1,31 @@ +// A fork read whole, for the files programs keep in one piece. + +import Foundation +import GraphiteBase +import GraphiteFiles + +public extension Fork { + + /// The fork's bytes, from its start to its end; the mark moves to the + /// end. A data fork opened for reading only is mapped into memory, not + /// read, so it costs pages as they are used. The map is a view of the + /// file, not a snapshot: truncating the file while it is held can crash + /// the process that reads past the new end. Any other fork is read into + /// memory. memFullErr for one past 2 GB. + func contents() throws(MacError) -> Data { + let count = size + guard count <= Int64(Int32.max) else { throw .memoryFull } + if kind == .data, !canWrite, count > 0, + let mapped = try? Data(contentsOf: URL(fileURLWithPath: path), options: .alwaysMapped), + mapped.count == Int(count) { + return mapped + } + var data = Data(count: Int(count)) + var result = Result.success(0) + data.withUnsafeMutableBytes { buffer in + result = Result { () throws(MacError) -> Int in try read(into: buffer, from: .start(0)) } + } + data.removeLast(Int(count) - (try result.get())) + return data + } +} diff --git a/Sources/GraphiteResources/InfoPlist.swift b/Sources/GraphiteResources/InfoPlist.swift new file mode 100644 index 0000000..61e61af --- /dev/null +++ b/Sources/GraphiteResources/InfoPlist.swift @@ -0,0 +1,32 @@ +// A bundle's Info.plist, read as far as Carbon's callers need: the strings +// at the top of its property list (CFBundleIconFile, CFBundleName, +// CFBundleIdentifier). XML and binary lists are both read; nested values and +// numbers are not kept. + +import Foundation +import GraphiteBase + +public struct InfoPlist: Hashable, Sendable { + + /// The string values of the plist's top-level dictionary, by key. + public private(set) var strings: [String: String] = [:] + + /// Reads a property list from any bytes, a mapped file's among them. A + /// parameter error if the bytes are not one; a list whose top level is + /// not a dictionary reads as empty. + public init(bytes: some ContiguousBytes) throws(MacError) { + let data = bytes as? Data ?? bytes.withUnsafeBytes { Data($0) } + let list: Any + do { + list = try PropertyListSerialization.propertyList(from: data, options: [], format: nil) + } catch { + throw .parameter + } + guard let dictionary = list as? [String: Any] else { return } + for (key, value) in dictionary { + if let string = value as? String { strings[key] = string } + } + } + + public subscript(key: String) -> String? { strings[key] } +} diff --git a/Sources/GraphiteResources/ResourceChain.swift b/Sources/GraphiteResources/ResourceChain.swift index fafb734..b5f165f 100644 --- a/Sources/GraphiteResources/ResourceChain.swift +++ b/Sources/GraphiteResources/ResourceChain.swift @@ -4,6 +4,7 @@ // number is its fork's, from the File Manager, as the Toolbox's were. import GraphiteBase +import protocol Foundation.ContiguousBytes import GraphiteFiles public final class ResourceChain { @@ -59,7 +60,7 @@ public final class ResourceChain { /// A file of resources from bytes, which can't be written back. @discardableResult - public func open(bytes: [UInt8]) throws(MacError) -> Int16 { + public func open(bytes: some ContiguousBytes) throws(MacError) -> Int16 { let file = try ResourceFile(bytes: bytes) let reference = nextBytesReference nextBytesReference -= 1 diff --git a/Sources/GraphiteResources/ResourceFile.swift b/Sources/GraphiteResources/ResourceFile.swift index de6f022..1ae1ee9 100644 --- a/Sources/GraphiteResources/ResourceFile.swift +++ b/Sources/GraphiteResources/ResourceFile.swift @@ -2,6 +2,8 @@ // asked for, changed, added and removed in memory, and written back to the // fork when it is updated or closed, as UpdateResFile and CloseResFile do. +import protocol Foundation.ContiguousBytes +import struct Foundation.Data import GraphiteBase import GraphiteFiles @@ -11,8 +13,9 @@ public final class ResourceFile { /// made from bytes alone. public let fork: Fork? - /// The bytes the map was read from. - private var source: [UInt8] + /// The bytes the map was read from, from index 0: a file mapped into + /// memory stays mapped, and resources are copied out as they are asked for. + private var source: Data private var map: ResourceMap @@ -33,9 +36,10 @@ public final class ResourceFile { } /// The resources of a fork's bytes: mapReadErr for a damaged map. - public init(bytes: [UInt8]) throws(MacError) { - source = bytes - map = try ResourceMap(parsing: bytes) + public init(bytes: some ContiguousBytes) throws(MacError) { + let data = Data(zeroBased: bytes) + source = data + map = try ResourceMap(parsing: data) fork = nil } @@ -45,10 +49,10 @@ public final class ResourceFile { let size = fork.size guard size > 0 else { throw .endOfFile } guard size <= Int64(Int32.max) else { throw .mapRead } - let bytes = try fork.readAll(count: Int(size)) - guard bytes.count == Int(size) else { throw .endOfFile } - source = bytes - map = try ResourceMap(parsing: bytes) + let data = try fork.contents() + guard data.count == Int(size) else { throw .endOfFile } + source = data + map = try ResourceMap(parsing: data) self.fork = fork if !fork.canWrite { map.attributes.insert(.readOnly) } } @@ -195,7 +199,7 @@ public final class ResourceFile { let bytes = try write() try fork.replaceContents(with: bytes) // The file as it now is on disk. - source = bytes + source = Data(bytes) map = try ResourceMap(parsing: bytes) changedBytes = [:] } @@ -203,17 +207,6 @@ public final class ResourceFile { extension Fork { - /// Up to `count` bytes from the fork's start. - func readAll(count: Int) throws(MacError) -> [UInt8] { - var bytes = [UInt8](repeating: 0, count: count) - var result = Result.success(0) - bytes.withUnsafeMutableBytes { buffer in - result = Result { () throws(MacError) -> Int in try read(into: buffer, from: .start(0)) } - } - bytes.removeLast(count - (try result.get())) - return bytes - } - /// The fork's bytes are these, written out. func replaceContents(with bytes: [UInt8]) throws(MacError) { try setSize(0) diff --git a/Sources/GraphiteResources/ResourceMap.swift b/Sources/GraphiteResources/ResourceMap.swift index ef37f12..c8363b8 100644 --- a/Sources/GraphiteResources/ResourceMap.swift +++ b/Sources/GraphiteResources/ResourceMap.swift @@ -16,6 +16,8 @@ // Every offset is checked: a map that points outside its fork throws // mapReadErr, whatever its bytes say. +import protocol Foundation.ContiguousBytes +import struct Foundation.Data import GraphiteBase /// A resource's attributes. @@ -112,7 +114,8 @@ public struct ResourceMap: Hashable, Sendable { /// The map of a fork's bytes: mapReadErr if any offset in it is outside /// them, eofErr if there are too few for a header. - public init(parsing bytes: [UInt8]) throws(MacError) { + public init(parsing contents: some ContiguousBytes) throws(MacError) { + let bytes = Data(zeroBased: contents) guard bytes.count >= 16 else { throw .endOfFile } do { var header = BigEndianReader(bytes) diff --git a/Sources/GraphiteResources/StringList.swift b/Sources/GraphiteResources/StringList.swift index d692c0d..393e270 100644 --- a/Sources/GraphiteResources/StringList.swift +++ b/Sources/GraphiteResources/StringList.swift @@ -2,6 +2,7 @@ // that many Pascal strings, and a single Pascal string. GetIndString reads // the first. +import protocol Foundation.ContiguousBytes import GraphiteBase /// A 'STR#' resource. @@ -16,7 +17,7 @@ public struct StringList: Hashable, Sendable { } /// mapReadErr if the bytes end before the strings their count says. - public init(bytes: [UInt8]) throws(MacError) { + public init(bytes: some ContiguousBytes) throws(MacError) { var reader = BigEndianReader(bytes) do { let count = Int(try reader.read(UInt16.self)) @@ -57,8 +58,8 @@ public struct StringResource: Hashable, Sendable { /// A length longer than the bytes takes what there is, as GetString's /// callers found. - public init(bytes: [UInt8]) { - string = PascalString(lengthPrefixed: bytes) + public init(bytes: some ContiguousBytes) { + string = PascalString(lengthPrefixed: Array(copying: bytes)) } public var bytes: [UInt8] { string.lengthPrefixed } diff --git a/Sources/GraphiteResources/VersionResource.swift b/Sources/GraphiteResources/VersionResource.swift index 93da352..930b02a 100644 --- a/Sources/GraphiteResources/VersionResource.swift +++ b/Sources/GraphiteResources/VersionResource.swift @@ -2,6 +2,7 @@ // NumVersion, a region code, and short and long version strings. ID 1 is the // file's version, 2 the package's it belongs to. +import protocol Foundation.ContiguousBytes import GraphiteBase public struct VersionResource: Hashable, Sendable { @@ -51,7 +52,7 @@ public struct VersionResource: Hashable, Sendable { } /// mapReadErr if the bytes end early. - public init(bytes: [UInt8]) throws(MacError) { + public init(bytes: some ContiguousBytes) throws(MacError) { var reader = BigEndianReader(bytes) do { major = try reader.read(UInt8.self) diff --git a/Sources/GraphiteText/FontFace.swift b/Sources/GraphiteText/FontFace.swift index f784793..e267a54 100644 --- a/Sources/GraphiteText/FontFace.swift +++ b/Sources/GraphiteText/FontFace.swift @@ -87,8 +87,19 @@ public protocol FontFace: AnyObject, Sendable { /// A character's image; nil for one the face hasn't. func glyph(for character: Unicode.Scalar, size: Int) -> GlyphImage? + + /// An sfnt table's bytes by its tag ('head', 'name', 'OS/2'), as + /// ATSFontGetTable reads them; nil where the face has no such table, + /// as a bitmap font has none. + func table(_ tag: FourCharCode) -> [UInt8]? + + /// The font's metrics in ems, as ATSFontGetHorizontalMetrics gives them; + /// nil for a face that isn't an outline font. + var horizontalMetrics: HorizontalFontMetrics? { get } } public extension FontFace { func hasStyle(_ style: TextStyle) -> Bool { style.isEmpty } + func table(_ tag: FourCharCode) -> [UInt8]? { nil } + var horizontalMetrics: HorizontalFontMetrics? { nil } } diff --git a/Sources/GraphiteText/FreeTypeFace.swift b/Sources/GraphiteText/FreeTypeFace.swift index ccf6b7a..d43ef05 100644 --- a/Sources/GraphiteText/FreeTypeFace.swift +++ b/Sources/GraphiteText/FreeTypeFace.swift @@ -3,29 +3,30 @@ // is on by default; without it there is only the built-in font. #if FreeType -import CFreeType +import FreeTypeSwift +import protocol Foundation.ContiguousBytes +import struct Foundation.Data +import struct Foundation.URL 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 { +/// A font file loaded through swift-freetype. FreeType's faces aren't +/// thread-safe, so every call goes through one lock. The font's bytes are +/// kept as well, for its tables: a file loaded by path is mapped into +/// memory, not read. +public final class FreeTypeFace: FontFace, 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 static let library: FreeTypeLibrary? = try? FreeTypeLibrary() - 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? + private let face: Mutex + + /// The font's sfnt tables; nil for a font that isn't one (Type 1, BDF). + private let tables: SfntTables? public let familyName: String @@ -35,44 +36,46 @@ public final class FreeTypeFace: FontFace, @unchecked Sendable { /// 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 + /// A font in memory: `index` picks the face of a collection (a .ttc has /// several). - public init(data bytes: [UInt8], index: Int = 0) throws { + public init(data bytes: some ContiguousBytes, 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() + let font = Data(zeroBased: bytes) + let face: FreeTypeSwift.FreeTypeFace + do { + face = try library.face(data: font, index: index) + } catch { throw LoadError.unreadable } - self.face = face - data = copy - (familyName, styleName, styles) = Self.names(of: face) + tables = try? SfntTables(font: font, index: index) + (familyName, styleName, styles) = Self.names(of: face, tables: tables) + self.face = Mutex(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() + let face: FreeTypeSwift.FreeTypeFace + do { + face = try library.face(path: path, index: index) + } catch { + throw LoadError.unreadable + } + tables = (try? Data(contentsOf: URL(fileURLWithPath: path), options: .alwaysMapped)) + .flatMap { try? SfntTables(font: $0, index: index) } + (familyName, styleName, styles) = Self.names(of: face, tables: tables) + self.face = Mutex(face) } - 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) } ?? "" + private static func names(of face: borrowing FreeTypeSwift.FreeTypeFace, tables: SfntTables?) -> (String, String, TextStyle) { + let family = face.familyName.isEmpty ? "Unknown" : face.familyName + let style = face.styleName + if let tables { return (family, style, tables.styles) } + // A font with no tables says its style in its name. 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) } + let lowered = style.lowercased() + if lowered.contains("bold") { styles.insert(.bold) } + if lowered.contains("italic") || lowered.contains("oblique") { styles.insert(.italic) } return (family, style, styles) } @@ -84,54 +87,99 @@ public final class FreeTypeFace: FontFace, @unchecked Sendable { /// 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 } + face.withLock { $0.glyphIndex(for: character) != 0 } + } + + /// A table of an sfnt font by its tag; nil for a table it hasn't and for + /// a font that isn't an sfnt (Type 1, say). + public func table(_ tag: FourCharCode) -> [UInt8]? { + tables?.table(tag) + } + + /// Ascent, descent and the rest in ems, from the face's own numbers + /// and its 'hhea', 'head', 'OS/2' and 'post' tables where it has them. + /// Without an 'OS/2' table the average advance is half the maximum and + /// the cap and x heights are the ascent and half of it, as with an + /// 'OS/2' older than version 2. + public var horizontalMetrics: HorizontalFontMetrics? { + face.withLock { face in + let em = face.unitsPerEM == 0 ? 1000.0 : Double(face.unitsPerEM) + let ascent = Double(face.designAscender) / em + var metrics = HorizontalFontMetrics( + ascent: ascent, + descent: Double(face.designDescender) / em, + leading: max(0, Double(face.designLineHeight - face.designAscender + face.designDescender) / em)) + if let advance = tables?.maximumAdvance { + metrics.maximumAdvance = Double(advance) / em + } else if (try? face.setPixelSize(width: 0, height: UInt32(em))) != nil { + // At a size of one em in pixels, a pixel is a font unit. + metrics.maximumAdvance = face.maxAdvance / em + } + metrics.minimumLeftSideBearing = Double(tables?.minimumLeftSideBearing ?? 0) / em + if let underline = tables?.underline { + metrics.underlinePosition = Double(underline.position) / em + metrics.underlineThickness = Double(underline.thickness) / em + } + metrics.averageAdvance = tables?.averageAdvance.map { Double($0) / em } ?? metrics.maximumAdvance / 2 + metrics.capHeight = tables?.capHeight.map { Double($0) / em } ?? ascent + metrics.xHeight = tables?.xHeight.map { Double($0) / em } ?? ascent / 2 + metrics.italicAngle = tables?.italicAngle ?? 0 + return metrics + } } 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) + face.withLock { face in + guard (try? face.setPixelSize(width: 0, height: Self.pixelSize(size))) != nil else { + return FontMetrics(ascent: 0, descent: 0, widMax: 0, leading: 0) + } + // FreeType's scaled metrics are whole numbers of 26.6 units, so + // they're exact here; rounded up to whole pixels. + let ascent = Int(face.ascender.rounded(.up)) + let descent = Int((-face.descender).rounded(.up)) + let height = Int(face.lineHeight.rounded(.up)) return FontMetrics(ascent: Int16(clamping: ascent), descent: Int16(clamping: descent), - widMax: Int16(clamping: Int((metrics.max_advance + 63) >> 6)), + widMax: Int16(clamping: Int(face.maxAdvance.rounded(.up))), leading: Int16(clamping: max(0, height - ascent - descent))) } } + /// A character's image, rendered as coverage. Nil for a character the + /// face hasn't, and for one whose bitmap is in a mode that isn't + /// coverage (a color emoji's). 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) } + face.withLock { face in + guard (try? face.setPixelSize(width: 0, height: Self.pixelSize(size))) != nil else { return nil } + let index = face.glyphIndex(for: character) + guard index != 0, let glyph = try? face.glyph(at: index, flags: .render) else { return nil } + let advance = Int(glyph.advanceX.rounded()) + guard let bitmap = glyph.bitmap, bitmap.width > 0, bitmap.rows > 0 else { return .blank(advance: advance) } + let width = bitmap.width, height = bitmap.rows 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] + switch bitmap.pixelMode { + case .mono: + for row in 0 ..< height { + for column in 0 ..< width { + let byte = bitmap.pixels[row * bitmap.bytesPerRow + column / 8] + coverage[row * width + column] = byte & (0x80 >> UInt8(column % 8)) != 0 ? 255 : 0 } } + case .gray: + for row in 0 ..< height { + let start = row * bitmap.bytesPerRow + coverage.replaceSubrange(row * width ..< (row + 1) * width, with: bitmap.pixels[start ..< start + width]) + } + default: + return nil } - return GlyphImage(width: width, height: height, left: Int(slot.pointee.bitmap_left), top: Int(slot.pointee.bitmap_top), - coverage: coverage, advance: advance) + return GlyphImage(width: width, height: height, left: bitmap.left, top: 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)) + /// The pixel size to ask FreeType for: 12 where none is asked for, as + /// QuickDraw's default is. + private static func pixelSize(_ size: Int) -> UInt32 { + UInt32(clamping: size <= 0 ? 12 : size) } } #endif diff --git a/Sources/GraphiteText/HorizontalFontMetrics.swift b/Sources/GraphiteText/HorizontalFontMetrics.swift new file mode 100644 index 0000000..c053763 --- /dev/null +++ b/Sources/GraphiteText/HorizontalFontMetrics.swift @@ -0,0 +1,40 @@ +// A font's horizontal metrics as ATS gives them (ATSFontGetHorizontalMetrics): +// fractions of the em, so they hold at any size. + +/// Distances in ems: ascent is above the baseline, descent below it and +/// negative, and the underline position is below it and negative too. +public struct HorizontalFontMetrics: Hashable, Sendable { + + public var ascent: Double + public var descent: Double + public var leading: Double + public var averageAdvance: Double + public var maximumAdvance: Double + public var minimumLeftSideBearing: Double + public var minimumRightSideBearing: Double + public var capHeight: Double + public var xHeight: Double + + /// Degrees; negative leans right. + public var italicAngle: Double + public var underlinePosition: Double + public var underlineThickness: Double + + public init(ascent: Double, descent: Double, leading: Double = 0, averageAdvance: Double = 0, + maximumAdvance: Double = 0, minimumLeftSideBearing: Double = 0, minimumRightSideBearing: Double = 0, + capHeight: Double = 0, xHeight: Double = 0, italicAngle: Double = 0, + underlinePosition: Double = 0, underlineThickness: Double = 0) { + self.ascent = ascent + self.descent = descent + self.leading = leading + self.averageAdvance = averageAdvance + self.maximumAdvance = maximumAdvance + self.minimumLeftSideBearing = minimumLeftSideBearing + self.minimumRightSideBearing = minimumRightSideBearing + self.capHeight = capHeight + self.xHeight = xHeight + self.italicAngle = italicAngle + self.underlinePosition = underlinePosition + self.underlineThickness = underlineThickness + } +} diff --git a/Sources/GraphiteText/SfntTables.swift b/Sources/GraphiteText/SfntTables.swift new file mode 100644 index 0000000..f81c7e4 --- /dev/null +++ b/Sources/GraphiteText/SfntTables.swift @@ -0,0 +1,112 @@ +// The tables of an sfnt font file (TrueType, OpenType, a .ttc collection's +// faces): the directory read from the font's bytes, and the few fields of +// 'head', 'hhea', 'OS/2' and 'post' that ATS gives programs. Read in place, +// so a font file mapped into memory costs pages as they are used. + +import protocol Foundation.ContiguousBytes +import struct Foundation.Data +import GraphiteBase + +public struct SfntTables: Sendable { + + private let font: Data + + /// Where each table is in the font's bytes. + private var directory: [FourCharCode: Range] = [:] + + /// The tables of a font's bytes: parameter error for bytes that aren't + /// an sfnt, or a collection without that face. `index` picks the face + /// of a collection. + public init(font bytes: some ContiguousBytes, index: Int = 0) throws(MacError) { + font = Data(zeroBased: bytes) + var reader = BigEndianReader(font) + do { + var tag = try reader.read(UInt32.self) + if tag == FourCharCode("ttcf").rawValue { + try reader.skip(4) // version + let count = Int(try reader.read(UInt32.self)) + guard index >= 0, index < count else { throw MacError.parameter } + try reader.seek(to: Int(try reader.peek(UInt32.self, at: 12 + 4 * index))) + tag = try reader.read(UInt32.self) + } + guard tag == 0x0001_0000 || [FourCharCode("true"), "OTTO", "typ1"].contains(FourCharCode(tag)) else { + throw MacError.parameter + } + let count = Int(try reader.read(UInt16.self)) + try reader.skip(6) // searchRange, entrySelector, rangeShift + for _ in 0 ..< count { + let name = FourCharCode(try reader.read(UInt32.self)) + try reader.skip(4) // checksum + let offset = Int(try reader.read(UInt32.self)) + let length = Int(try reader.read(UInt32.self)) + // A table past the end of the file is not there; the first of a tag wins. + guard offset <= font.count, length <= font.count - offset, directory[name] == nil else { continue } + directory[name] = offset ..< offset + length + } + } catch let error as MacError { + throw error + } catch { + throw .parameter + } + } + + /// The tables' tags, sorted. + public var tags: [FourCharCode] { directory.keys.sorted() } + + /// A table's bytes, copied; nil if the font has none of the tag. + public func table(_ tag: FourCharCode) -> [UInt8]? { + directory[tag].map { Array(font[font.startIndex + $0.lowerBound ..< font.startIndex + $0.upperBound]) } + } + + /// A field of a table at an offset, as many bytes as `T` is; nil if the + /// table or the field isn't there. + private func field(_ tag: FourCharCode, at offset: Int, as type: T.Type = T.self) -> T? { + guard let range = directory[tag], offset + MemoryLayout.size <= range.count else { return nil } + let reader = BigEndianReader(font) + return try? reader.peek(T.self, at: range.lowerBound + offset) + } + + /// Font units to the em ('head'). + public var unitsPerEm: Int? { field("head", at: 18, as: UInt16.self).map(Int.init) } + + /// The bold and italic the font says it is: 'head''s macStyle, and + /// 'OS/2''s fsSelection (italic, bold, oblique). + public var styles: TextStyle { + var styles: TextStyle = [] + let macStyle = field("head", at: 44, as: UInt16.self) ?? 0 + let selection = field("OS/2", at: 62, as: UInt16.self) ?? 0 + if macStyle & 1 != 0 || selection & 0x20 != 0 { styles.insert(.bold) } + if macStyle & 2 != 0 || selection & 0x01 != 0 || selection & 0x200 != 0 { styles.insert(.italic) } + return styles + } + + /// The widest advance in font units ('hhea'). + public var maximumAdvance: Int? { field("hhea", at: 10, as: UInt16.self).map(Int.init) } + + /// The left edge of the font's bounding box in font units ('head'). + public var minimumLeftSideBearing: Int? { field("head", at: 36, as: Int16.self).map(Int.init) } + + /// The underline's position (below the baseline, negative) and + /// thickness in font units ('post'). + public var underline: (position: Int, thickness: Int)? { + guard let position = field("post", at: 8, as: Int16.self), let thickness = field("post", at: 10, as: Int16.self) else { return nil } + return (Int(position), Int(thickness)) + } + + /// The italic angle in degrees ('post'); negative leans right. + public var italicAngle: Double? { field("post", at: 4, as: Int32.self).map { Double($0) / 65536 } } + + /// The average character width in font units ('OS/2'). + public var averageAdvance: Int? { field("OS/2", at: 2, as: Int16.self).map(Int.init) } + + /// The height of capitals in font units; nil unless the 'OS/2' table is + /// version 2 or later. + public var capHeight: Int? { field("OS/2", at: 0, as: UInt16.self).flatMap { $0 >= 2 ? field("OS/2", at: 88, as: Int16.self).map(Int.init) : nil } } + + /// The height of the lowercase x in font units; nil unless the 'OS/2' + /// table is version 2 or later. + public var xHeight: Int? { field("OS/2", at: 0, as: UInt16.self).flatMap { $0 >= 2 ? field("OS/2", at: 86, as: Int16.self).map(Int.init) : nil } } + + /// Whether the font has an 'OS/2' table. + public var hasOS2: Bool { directory["OS/2"] != nil } +} diff --git a/Tests/GraphiteBaseTests/BigEndianTests.swift b/Tests/GraphiteBaseTests/BigEndianTests.swift index 462bc6b..5f59297 100644 --- a/Tests/GraphiteBaseTests/BigEndianTests.swift +++ b/Tests/GraphiteBaseTests/BigEndianTests.swift @@ -1,3 +1,4 @@ +import struct Foundation.Data import Testing import GraphiteBase @@ -103,7 +104,28 @@ import GraphiteBase reader.align(to: 16) #expect(reader.offset == 8) let other = try reader.subreader(at: 1, count: 3) - #expect(other.bytes == [1, 2, 3]) + #expect(Array(other.bytes) == [1, 2, 3]) + } + + @Test func slicesAreReadFromTheirOwnStart() throws { + let whole = Data([0xAA, 0xBB, 0, 1, 2, 3, 4, 5, 0xCC]) + var reader = BigEndianReader(whole[2 ..< 8]) + #expect(reader.count == 6) + #expect(try reader.peek(UInt16.self, at: 0) == 0x0001) + #expect(try reader.read(UInt32.self) == 0x0001_0203) + #expect(reader.remaining == 2) + #expect(Array(try reader.readBytes(2)) == [4, 5]) + #expect(reader.isAtEnd) + #expect(throws: BigEndianReadError.self) { try reader.read(UInt8.self) } + // The bytes are all of the slice, from index 0. + #expect(reader.bytes.startIndex == 0) + #expect(Array(reader.bytes) == [0, 1, 2, 3, 4, 5]) + // A reader of a part of a slice, and of a part of that. + var sub = try reader.subreader(at: 1, count: 4) + #expect(Array(sub.bytes) == [1, 2, 3, 4]) + var inner = try sub.subreader(at: 1, count: 2) + #expect(try inner.read(UInt16.self) == 0x0203) + #expect(throws: BigEndianReadError.self) { try sub.subreader(at: 3, count: 2) } } @Test func randomBytesNeverTrap() { diff --git a/Tests/GraphiteBaseTests/ContiguousBytesTests.swift b/Tests/GraphiteBaseTests/ContiguousBytesTests.swift new file mode 100644 index 0000000..3ca6786 --- /dev/null +++ b/Tests/GraphiteBaseTests/ContiguousBytesTests.swift @@ -0,0 +1,46 @@ +import Foundation +import Testing +import GraphiteBase + +@Suite struct ContiguousBytesTests { + + private let bytes: [UInt8] = [0x00, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06] + + @Test func arraysAndDataAndBuffersGiveTheSameBytes() { + #expect(Array(copying: bytes) == bytes) + #expect(Array(copying: Data(bytes)) == bytes) + #expect(bytes.withUnsafeBytes { Array(copying: $0) } == bytes) + #expect(Array(copying: ContiguousArray(bytes)) == bytes) + } + + @Test func aSliceOfDataIsCopiedFromItsOwnStart() { + // A slice keeps its parent's indices; its bytes are what count. + let slice = Data(bytes)[2 ..< 6] + #expect(slice.startIndex == 2) + #expect(Array(copying: slice) == [0x01, 0x02, 0x03, 0x04]) + #expect(Array(copying: bytes[2 ..< 6]) == [0x01, 0x02, 0x03, 0x04]) + } + + @Test func emptyBytes() { + #expect(Array(copying: Data()).isEmpty) + #expect(Array(copying: [UInt8]()).isEmpty) + } + + @Test func aMappedFileReadsLikeAnArray() throws { + let path = "/tmp/graphite-contiguous-\(getpid())" + try Data(bytes).write(to: URL(fileURLWithPath: path)) + defer { unlink(path) } + let mapped = try Data(contentsOf: URL(fileURLWithPath: path), options: .alwaysMapped) + #expect(Array(copying: mapped) == bytes) + } + + @Test func readersTakeAnyBytes() throws { + var fromData = BigEndianReader(Data(bytes), offset: 2) + #expect(try fromData.read(UInt16.self) == 0x0102) + var fromSlice = BigEndianReader(Data(bytes)[4 ..< 8]) + #expect(try fromSlice.read(UInt32.self) == 0x0304_0506) + var fromArray = BigEndianReader(bytes) + #expect(try fromArray.read(UInt32.self) == 0x0000_0102) + #expect(throws: BigEndianReadError.self) { _ = try fromSlice.read(UInt8.self) } + } +} diff --git a/Tests/GraphiteFilesTests/AppleDoubleBytesTests.swift b/Tests/GraphiteFilesTests/AppleDoubleBytesTests.swift new file mode 100644 index 0000000..78d24ee --- /dev/null +++ b/Tests/GraphiteFilesTests/AppleDoubleBytesTests.swift @@ -0,0 +1,37 @@ +import struct Foundation.Data +import Testing +import GraphiteBase +import GraphiteFiles + +@Suite struct AppleDoubleBytesTests { + + private func file() -> [UInt8] { + var double = AppleDouble() + double.resourceFork = [1, 2, 3, 4] + double.finderInfo = FinderInfo(type: "TEXT", creator: "ttxt", flags: 0x0400) + return double.bytes + } + + @Test func readsFromAnyBytes() throws { + let bytes = file() + let fromArray = try AppleDouble(bytes: bytes) + #expect(fromArray.resourceFork == [1, 2, 3, 4]) + #expect(try AppleDouble(bytes: Data(bytes)) == fromArray) + #expect(try AppleDouble(bytes: Data([7, 7, 7] + bytes)[3...]) == fromArray) + #expect(try bytes.withUnsafeBytes { try AppleDouble(bytes: $0) } == fromArray) + } + + @Test func recognisesAnyBytes() { + let bytes = file() + #expect(AppleDouble.isAppleDouble(bytes)) + #expect(AppleDouble.isAppleDouble(Data(bytes))) + #expect(AppleDouble.isAppleDouble(Data([7, 7] + bytes)[2...])) + #expect(!AppleDouble.isAppleDouble(Data([1, 2, 3, 4, 5]))) + #expect(!AppleDouble.isAppleDouble(Data())) + } + + @Test func badBytesAreAParameterError() { + #expect(throws: MacError.parameter) { try AppleDouble(bytes: Data([1, 2, 3, 4, 5, 6, 7, 8])) } + #expect(throws: MacError.parameter) { try AppleDouble(bytes: Data(file().prefix(30))) } + } +} diff --git a/Tests/GraphiteQuickDrawTests/CursorStateTests.swift b/Tests/GraphiteQuickDrawTests/CursorStateTests.swift new file mode 100644 index 0000000..65b5ad9 --- /dev/null +++ b/Tests/GraphiteQuickDrawTests/CursorStateTests.swift @@ -0,0 +1,96 @@ +import Testing +import GraphiteBase +import GraphiteQuickDraw + +@Suite struct CursorStateTests { + + @Test func startsAsTheShownArrow() { + let state = CursorState() + #expect(state.current == .arrow) + #expect(state.isVisible) + } + + @Test func hidingNests() { + var state = CursorState() + state.hide() + state.hide() + state.show() + #expect(!state.isVisible) + state.show() + #expect(state.isVisible) + } + + @Test func showingMoreThanHidingChangesNothing() { + var state = CursorState() + state.show() + state.hide() + #expect(!state.isVisible) + state.show() + #expect(state.isVisible) + } + + @Test func initializingRestoresTheArrowAndShows() { + var state = CursorState() + state.set(Cursor(data: [0xFFFF], mask: [0xFFFF], hotSpot: Point(v: 8, h: 8))) + state.hide() + state.hide() + state.initialize() + #expect(state.current == .arrow) + #expect(state.isVisible) + } + + private func pixels(width: Int, height: Int, value: UInt32) -> PixelBuffer { + let buffer = PixelBuffer(bounds: Rect(top: 0, left: 0, bottom: Int16(height), right: Int16(width)), format: .argb32) + buffer.fill(buffer.bounds, with: value) + return buffer + } + + @Test func namedCursorsAreSetByName() throws { + var state = CursorState() + let buffer = pixels(width: 24, height: 20, value: 0xFF12_3456) + try state.register(pixels: buffer, hotSpot: Point(v: 3, h: 4), name: "target") + try state.setNamed("target") + #expect(state.current.hotSpot == Point(v: 3, h: 4)) + #expect(state.current.colorWidth == 24) + #expect(state.current.colorImage?.count == 24 * 20) + #expect(state.current.colorImage?.first == 0xFF12_3456) + } + + @Test func registeringCopiesThePixels() throws { + var state = CursorState() + let buffer = pixels(width: 16, height: 16, value: 0xFF00_00FF) + try state.register(pixels: buffer, hotSpot: .zero, name: "blue") + buffer.fill(buffer.bounds, with: 0xFFFF_0000) + try state.setNamed("blue") + #expect(state.current.colorImage?.first == 0xFF00_00FF) + } + + @Test func registeringAgainReplaces() throws { + var state = CursorState() + try state.register(pixels: pixels(width: 16, height: 16, value: 0xFF00_0001), hotSpot: .zero, name: "x") + try state.register(pixels: pixels(width: 16, height: 16, value: 0xFF00_0002), hotSpot: .zero, name: "x") + try state.setNamed("x") + #expect(state.current.colorImage?.first == 0xFF00_0002) + } + + @Test func unregisteredAndBadNamesAreParameterErrors() throws { + var state = CursorState() + #expect(throws: MacError.parameter) { try state.setNamed("missing") } + #expect(throws: MacError.parameter) { try state.unregister("missing") } + #expect(throws: MacError.parameter) { + try state.register(pixels: pixels(width: 16, height: 16, value: 0), hotSpot: .zero, name: "") + } + let indexed = PixelBuffer(bounds: Rect(top: 0, left: 0, bottom: 16, right: 16), format: .indexed(depth: 8)) + #expect(throws: MacError.parameter) { try state.register(pixels: indexed, hotSpot: .zero, name: "indexed") } + + try state.register(pixels: pixels(width: 16, height: 16, value: 0), hotSpot: .zero, name: "gone") + try state.unregister("gone") + #expect(throws: MacError.parameter) { try state.setNamed("gone") } + } + + @Test func quickDrawKeepsTheState() { + let quickDraw = QuickDraw(screens: []) + quickDraw.cursor.hide() + #expect(!quickDraw.cursor.isVisible) + } +} diff --git a/Tests/GraphiteQuickDrawTests/DeviceColorsTests.swift b/Tests/GraphiteQuickDrawTests/DeviceColorsTests.swift new file mode 100644 index 0000000..b2e69a4 --- /dev/null +++ b/Tests/GraphiteQuickDrawTests/DeviceColorsTests.swift @@ -0,0 +1,68 @@ +import Testing +import GraphiteBase +import GraphiteQuickDraw + +@Suite struct DeviceColorsTests { + + private func indexedDevice() -> GraphicsDevice { + let bounds = Rect(top: 0, left: 0, bottom: 4, right: 4) + let pixels = PixelBuffer(bounds: bounds, format: .indexed(depth: 8), colorTable: ColorTable.standard(depth: 8)) + return GraphicsDevice(bounds: bounds, pixels: pixels, isScreen: true) + } + + private let orange = RGBColor(red: 0xFFFF, green: 0x8000, blue: 0) + + @Test func changedMovesTheSeed() { + var table = ColorTable(seed: 5, colors: [.black]) + table.changed() + #expect(table.seed == 6) + var last = ColorTable(seed: .max, colors: []) + last.changed() + #expect(last.seed == .min) + } + + @Test func index2ColorReadsTheDevicesTable() { + let device = indexedDevice() + #expect(device.color(forIndex: 0) == .white) + #expect(device.color(forIndex: 255) == .black) + #expect(device.color(forIndex: 256) == nil) + #expect(device.color(forIndex: -1) == nil) + } + + @Test func index2ColorOnADirectDeviceIsNil() { + #expect(GraphicsDevice.screen(width: 4, height: 4, depth: 32).color(forIndex: 0) == nil) + } + + @Test func setEntriesWritesAndBumpsTheSeed() throws { + let device = indexedDevice() + let seed = device.pixels.colorTable.seed + try device.setEntries(from: 10, colors: [orange, .black]) + #expect(device.color(forIndex: 10) == orange) + #expect(device.color(forIndex: 11) == .black) + #expect(device.pixels.colorTable.seed != seed) + } + + @Test func setEntriesStopsAtTheTablesEnd() throws { + let device = indexedDevice() + try device.setEntries(from: 255, colors: [orange, orange, orange]) + #expect(device.color(forIndex: 255) == orange) + #expect(device.pixels.colorTable.colors.count == 256) + #expect(throws: MacError.parameter) { try device.setEntries(from: 256, colors: [orange]) } + #expect(throws: MacError.parameter) { try device.setEntries(from: -1, colors: [orange]) } + } + + @Test func setEntriesOnADirectDeviceDoesNothing() throws { + let device = GraphicsDevice.screen(width: 4, height: 4, depth: 32) + try device.setEntries(from: 0, colors: [orange]) + } + + @Test func restoringBringsBackTheStandardColors() throws { + let device = indexedDevice() + try device.setEntries(from: 0, colors: [orange]) + let seed = device.pixels.colorTable.seed + device.restoreColorTable() + #expect(device.color(forIndex: 0) == .white) + #expect(device.pixels.colorTable.colors == ColorTable.standard(depth: 8)?.colors) + #expect(device.pixels.colorTable.seed != seed) + } +} diff --git a/Tests/GraphiteQuickDrawTests/FileIconTests.swift b/Tests/GraphiteQuickDrawTests/FileIconTests.swift new file mode 100644 index 0000000..59d9b37 --- /dev/null +++ b/Tests/GraphiteQuickDrawTests/FileIconTests.swift @@ -0,0 +1,151 @@ +import struct Foundation.Data +import class Foundation.PropertyListSerialization +import Testing +import GraphiteBase +import GraphiteFiles +import GraphiteResources +import GraphiteQuickDraw + +@Suite struct FileIconTests { + + /// An 'ICN#' member with every pixel black and shown: 32 by 32. + private let largeIcon = [UInt8](repeating: 0xFF, count: 256) + /// An 'ics#' member the same: 16 by 16. + private let smallIcon = [UInt8](repeating: 0xFF, count: 64) + + /// An 'icns' file's bytes. + private func icns(_ members: [(FourCharCode, [UInt8])]) -> [UInt8] { + var body: [UInt8] = [] + for (type, bytes) in members { + body += be(type.rawValue) + be(UInt32(8 + bytes.count)) + bytes + } + return be(FourCharCode("icns").rawValue) + be(UInt32(8 + body.count)) + body + } + + private func be(_ value: UInt32) -> [UInt8] { + [UInt8(value >> 24), UInt8(truncatingIfNeeded: value >> 16), UInt8(truncatingIfNeeded: value >> 8), UInt8(truncatingIfNeeded: value)] + } + + /// A file whose resource fork is in "._name", as macOS copies it. + private func makeFile(_ folder: TemporaryFolder, _ directory: String, _ name: String, _ resources: [(Resource, [UInt8])]) throws { + let prefix = directory.isEmpty ? "" : directory + "/" + folder.write(prefix + name, []) + var double = AppleDouble() + double.resourceFork = try ResourceMap.write(resources.map { (resource: $0.0, bytes: $0.1) }) + folder.write(prefix + "._" + name, double.bytes) + } + + private func customID(_ type: FourCharCode) -> Resource { + Resource(type: type, id: IconFamily.customIconResourceID) + } + + @Test func anIcnsFileIsItsOwnIcon() throws { + let folder = TemporaryFolder() + folder.write("Large.icns", icns([("ICN#", largeIcon)])) + folder.write("Upper.ICNS", icns([("ics#", smallIcon)])) + #expect(IconFamily(ofItemAt: folder.path("Large.icns"))?.sizes == [32]) + #expect(IconFamily(ofItemAt: folder.path("Upper.ICNS"))?.sizes == [16]) + } + + @Test func badIcnsFilesHaveNoIcon() { + let folder = TemporaryFolder() + folder.write("Bad.icns", [1, 2, 3, 4, 5, 6, 7, 8, 9]) + folder.write("Empty.icns", []) + #expect(IconFamily(ofItemAt: folder.path("Bad.icns")) == nil) + #expect(IconFamily(ofItemAt: folder.path("Empty.icns")) == nil) + #expect(IconFamily(ofItemAt: folder.path("Missing.icns")) == nil) + #expect(IconFamily(ofItemAt: folder.path("Missing")) == nil) + } + + @Test func aFileWithNothingHasNoIcon() { + let folder = TemporaryFolder() + folder.write("Plain", [1, 2, 3]) + folder.makeFolder("Folder") + #expect(IconFamily(ofItemAt: folder.path("Plain")) == nil) + #expect(IconFamily(ofItemAt: folder.path("Folder")) == nil) + } + + @Test func customIconInTheResourceFork() throws { + let folder = TemporaryFolder() + try makeFile(folder, "", "Document", [(customID("ICN#"), largeIcon), (customID("ics#"), smallIcon)]) + let family = try #require(IconFamily(ofItemAt: folder.path("Document"))) + #expect(family.sizes == [16, 32]) + #expect(family.image(size: 32)?.value(column: 0, row: 0) == 0xFF00_0000) + } + + @Test func customIcnsResource() throws { + let folder = TemporaryFolder() + try makeFile(folder, "", "Document", [(customID("icns"), icns([("ics#", smallIcon)]))]) + #expect(IconFamily(ofItemAt: folder.path("Document"))?.sizes == [16]) + } + + @Test func iconsOfOtherIDsAreNotCustomIcons() throws { + let folder = TemporaryFolder() + try makeFile(folder, "", "Application", [(Resource(type: "ICN#", id: 128), largeIcon)]) + #expect(IconFamily(ofItemAt: folder.path("Application")) == nil) + } + + @Test func aBundlesIconFile() throws { + let folder = TemporaryFolder() + folder.makeFolder("App.app") + folder.makeFolder("App.app/Contents") + folder.makeFolder("App.app/Contents/Resources") + folder.write("App.app/Contents/Info.plist", Array(""" + CFBundleIconFileAppIcon + """.utf8)) + folder.write("App.app/Contents/Resources/AppIcon.icns", icns([("ICN#", largeIcon)])) + #expect(IconFamily(ofItemAt: folder.path("App.app"))?.sizes == [32]) + } + + @Test func aBundlesIconFileWithItsExtension() throws { + let folder = TemporaryFolder() + folder.makeFolder("App.app") + folder.makeFolder("App.app/Contents") + folder.makeFolder("App.app/Contents/Resources") + folder.write("App.app/Contents/Info.plist", Array(""" + CFBundleIconFileIcon.icns + """.utf8)) + folder.write("App.app/Contents/Resources/Icon.icns", icns([("ics#", smallIcon)])) + #expect(IconFamily(ofItemAt: folder.path("App.app"))?.sizes == [16]) + } + + @Test func aBundleWithABinaryInfoPlist() throws { + let folder = TemporaryFolder() + folder.makeFolder("App.app") + folder.makeFolder("App.app/Contents") + folder.makeFolder("App.app/Contents/Resources") + let plist = try PropertyListSerialization.data(fromPropertyList: ["CFBundleIconFile": "AppIcon"], format: .binary, options: 0) + folder.write("App.app/Contents/Info.plist", Array(plist)) + folder.write("App.app/Contents/Resources/AppIcon.icns", icns([("ics#", smallIcon)])) + #expect(IconFamily(ofItemAt: folder.path("App.app"))?.sizes == [16]) + } + + @Test func bundlesWithoutAnIconFileHaveNone() { + let folder = TemporaryFolder() + folder.makeFolder("App.app") + folder.makeFolder("App.app/Contents") + folder.write("App.app/Contents/Info.plist", Array("CFBundleNameApp".utf8)) + #expect(IconFamily(ofItemAt: folder.path("App.app")) == nil) + folder.makeFolder("Other.app") + #expect(IconFamily(ofItemAt: folder.path("Other.app")) == nil) + } + + @Test func iconFileNamesCannotLeaveTheResourcesFolder() { + let folder = TemporaryFolder() + folder.makeFolder("App.app") + folder.makeFolder("App.app/Contents") + folder.makeFolder("App.app/Contents/Resources") + folder.write("Outside.icns", icns([("ICN#", largeIcon)])) + folder.write("App.app/Contents/Info.plist", Array(""" + CFBundleIconFile../../../Outside + """.utf8)) + #expect(IconFamily(ofItemAt: folder.path("App.app")) == nil) + } + + @Test func aFoldersCustomIcon() throws { + let folder = TemporaryFolder() + folder.makeFolder("Pictures") + try makeFile(folder, "Pictures", "Icon\r", [(customID("ICN#"), largeIcon)]) + #expect(IconFamily(ofItemAt: folder.path("Pictures"))?.sizes == [32]) + } +} diff --git a/Tests/GraphiteQuickDrawTests/IconBytesTests.swift b/Tests/GraphiteQuickDrawTests/IconBytesTests.swift new file mode 100644 index 0000000..d31603f --- /dev/null +++ b/Tests/GraphiteQuickDrawTests/IconBytesTests.swift @@ -0,0 +1,35 @@ +import struct Foundation.Data +import Testing +import GraphiteBase +import GraphiteQuickDraw + +@Suite struct IconBytesTests { + + /// An 'icns' file with one 'ICN#' member, every pixel black and shown. + private let file: [UInt8] = { + func be(_ value: UInt32) -> [UInt8] { + [UInt8(value >> 24), UInt8(truncatingIfNeeded: value >> 16), UInt8(truncatingIfNeeded: value >> 8), UInt8(truncatingIfNeeded: value)] + } + let member = [UInt8](repeating: 0xFF, count: 256) + return be(FourCharCode("icns").rawValue) + be(UInt32(16 + member.count)) + be(FourCharCode("ICN#").rawValue) + + be(UInt32(8 + member.count)) + member + }() + + @Test func familiesReadFromAnyBytes() throws { + #expect(try IconFamily(icns: file).sizes == [32]) + #expect(try IconFamily(icns: Data(file)).sizes == [32]) + #expect(try file.withUnsafeBytes { try IconFamily(icns: $0) }.sizes == [32]) + } + + @Test func aSliceOfDataIsReadFromItsOwnStart() throws { + let padded = Data([9, 9, 9, 9] + file) + let family = try IconFamily(icns: padded[4...]) + #expect(family.sizes == [32]) + #expect(family.image(size: 32)?.value(column: 0, row: 0) == 0xFF00_0000) + } + + @Test func badBytesAreAParameterError() { + #expect(throws: MacError.parameter) { try IconFamily(icns: Data([0, 1, 2, 3])) } + #expect(throws: MacError.parameter) { try IconFamily(icns: Data()) } + } +} diff --git a/Tests/GraphiteQuickDrawTests/PaletteTests.swift b/Tests/GraphiteQuickDrawTests/PaletteTests.swift new file mode 100644 index 0000000..323c1b0 --- /dev/null +++ b/Tests/GraphiteQuickDrawTests/PaletteTests.swift @@ -0,0 +1,70 @@ +import Testing +import GraphiteBase +import GraphiteQuickDraw + +@Suite struct PaletteTests { + + private let red = RGBColor(red: 0xFFFF, green: 0, blue: 0) + private let green = RGBColor(red: 0, green: 0xFFFF, blue: 0) + private let blue = RGBColor(red: 0, green: 0, blue: 0xFFFF) + + @Test func entriesComeFromTheTableAndAreBlackPastIt() throws { + let palette = Palette(count: 4, colors: ColorTable(colors: [red, green]), usage: .animated, tolerance: 7) + #expect(palette.count == 4) + #expect(try palette.color(at: 0) == red) + #expect(try palette.color(at: 1) == green) + #expect(try palette.color(at: 3) == .black) + let usage = try palette.usage(at: 2) + #expect(usage.usage == .animated && usage.tolerance == 7) + } + + @Test func noTableMakesBlackCourteousEntries() throws { + let palette = Palette(count: 2) + #expect(try palette.color(at: 1) == .black) + #expect(try palette.usage(at: 1).usage == []) + } + + @Test func negativeCountIsEmpty() { + #expect(Palette(count: -3).count == 0) + } + + @Test func settingColorsAndUsage() throws { + let palette = Palette(count: 3) + try palette.setColor(blue, at: 2) + try palette.setUsage([.explicit, .tolerant], tolerance: 40, at: 2) + #expect(try palette.color(at: 2) == blue) + #expect(try palette.usage(at: 2).usage == [.explicit, .tolerant]) + #expect(try palette.usage(at: 2).tolerance == 40) + #expect(throws: MacError.parameter) { try palette.setColor(red, at: 3) } + #expect(throws: MacError.parameter) { _ = try palette.color(at: -1) } + #expect(throws: MacError.parameter) { try palette.setUsage([], tolerance: 0, at: 9) } + } + + @Test func aPaletteIsAHandle() throws { + let palette = Palette(count: 1) + let alias = palette + try alias.setColor(green, at: 0) + #expect(try palette.color(at: 0) == green) + } + + @Test func colorTableRoundTrip() { + let palette = Palette(count: 3, colors: ColorTable(colors: [red, green, blue])) + #expect(palette.colorTable.colors == [red, green, blue]) + } + + @Test func copyingEntries() throws { + let source = Palette(count: 3, colors: ColorTable(colors: [red, green, blue])) + let destination = Palette(count: 4) + try destination.copy(from: source, sourceEntry: 1, destinationEntry: 2, length: 5) + // Two fit in the destination from entry 2; the source has two from 1. + #expect(destination.colorTable.colors == [.black, .black, green, blue]) + #expect(throws: MacError.parameter) { try destination.copy(from: source, sourceEntry: 3, destinationEntry: 0, length: 1) } + #expect(throws: MacError.parameter) { try destination.copy(from: source, sourceEntry: 0, destinationEntry: 4, length: 1) } + } + + @Test func copyingOverItself() throws { + let palette = Palette(count: 4, colors: ColorTable(colors: [red, green, blue, .white])) + try palette.copy(from: palette, sourceEntry: 0, destinationEntry: 1, length: 3) + #expect(palette.colorTable.colors == [red, red, green, blue]) + } +} diff --git a/Tests/GraphiteQuickDrawTests/ParserBytesTests.swift b/Tests/GraphiteQuickDrawTests/ParserBytesTests.swift new file mode 100644 index 0000000..cbdd3bd --- /dev/null +++ b/Tests/GraphiteQuickDrawTests/ParserBytesTests.swift @@ -0,0 +1,68 @@ +import struct Foundation.Data +import Testing +import GraphiteBase +import GraphiteQuickDraw + +@Suite struct ParserBytesTests { + + /// A version 2 picture with nothing in it but its end. + private func emptyPicture(frame: Rect) -> [UInt8] { + var writer = BigEndianWriter() + writer.write(UInt16(0)) + for value in [frame.top, frame.left, frame.bottom, frame.right] { writer.write(UInt16(bitPattern: value)) } + writer.write(UInt16(0x0011)) + writer.write(UInt16(0x02FF)) + writer.write(UInt16(0x0C00)) + writer.writeZeros(24) + writer.write(UInt16(0x00FF)) + return writer.bytes + } + + private let frame = Rect(top: 0, left: 0, bottom: 20, right: 30) + + @Test func picturesFromAnyBytes() throws { + let bytes = emptyPicture(frame: frame) + #expect(try Picture(bytes: bytes).frame == frame) + #expect(try Picture(bytes: Data(bytes)).frame == frame) + #expect(try Picture(bytes: Data([5, 5, 5] + bytes)[3...]).frame == frame) + #expect(try bytes.withUnsafeBytes { try Picture(bytes: $0) }.version == 2) + } + + @Test func pictureFilesSkipTheirHeader() throws { + let file = [UInt8](repeating: 0, count: 512) + emptyPicture(frame: frame) + #expect(try Picture(file: file).frame == frame) + #expect(try Picture(file: Data(file)).frame == frame) + // A slice of a bigger Data, which doesn't start at 0. + #expect(try Picture(file: Data([1, 2, 3] + file + [4])[3 ..< 3 + file.count]).frame == frame) + #expect(throws: MacError.parameter) { try Picture(file: Data(count: 512)) } + #expect(throws: MacError.parameter) { try Picture(file: Data()) } + } + + @Test func packBitsFromAnyBytes() throws { + let original: [UInt8] = [1, 1, 1, 1, 2, 3, 4, 4, 4, 4, 4, 5] + let packed = PackBits.pack(original) + #expect(PackBits.pack(Data(original)) == packed) + #expect(try PackBits.unpack(packed, count: original.count) == original) + #expect(try PackBits.unpack(Data(packed), count: original.count) == original) + #expect(try PackBits.unpack(Data([9, 9] + packed)[2...], count: original.count) == original) + #expect(throws: MacError.parameter) { try PackBits.unpack(Data(packed.prefix(2)), count: original.count) } + } + + @Test func regionAndPolygonRecords() throws { + let region = Region(rect: Rect(top: 1, left: 2, bottom: 30, right: 40)).subtracting(Region(rect: Rect(top: 5, left: 6, bottom: 10, right: 12))) + #expect(try Region(record: Data(region.record)) == region) + #expect(try Region(record: Data([3, 3] + region.record)[2...]) == region) + let polygon = Polygon(points: [Point(v: 0, h: 0), Point(v: 10, h: 0), Point(v: 10, h: 10)]) + #expect(try Polygon(record: Data(polygon.record)) == polygon) + #expect(try Polygon(record: Data([3, 3] + polygon.record)[2...]) == polygon) + #expect(throws: MacError.parameter) { try Polygon(record: Data([0, 2])) } + } + + @Test func cursorsFromAnyBytes() throws { + let cursor = Cursor.arrow + #expect(try Cursor(curs: Data(cursor.curs)) == cursor) + #expect(try Cursor(curs: Data([8, 8, 8] + cursor.curs)[3...]) == cursor) + #expect(try cursor.curs.withUnsafeBytes { try Cursor(curs: $0) } == cursor) + #expect(throws: MacError.parameter) { try Cursor(curs: Data(cursor.curs.prefix(60))) } + } +} diff --git a/Tests/GraphiteQuickDrawTests/TemporaryFolder.swift b/Tests/GraphiteQuickDrawTests/TemporaryFolder.swift new file mode 100644 index 0000000..941bcc8 --- /dev/null +++ b/Tests/GraphiteQuickDrawTests/TemporaryFolder.swift @@ -0,0 +1,78 @@ +#if canImport(Glibc) +import Glibc +#elseif canImport(Musl) +import Musl +#elseif canImport(Darwin) +import Darwin +#endif + +/// A folder of its own for a test, deleted with what's in it at the end. +final class TemporaryFolder { + + let path: String + + init() { + var template = Array("/tmp/graphite-XXXXXX".utf8CString) + let made = template.withUnsafeMutableBufferPointer { mkdtemp($0.baseAddress!) } + // The real path: /tmp is a link on macOS. + let resolved = realpath(made!, nil)! + path = String(cString: resolved) + free(resolved) + } + + deinit { + remove(path) + } + + private func remove(_ path: String) { + var info = stat() + guard lstat(path, &info) == 0 else { return } + if info.st_mode & S_IFMT == S_IFDIR, let directory = opendir(path) { + var names: [String] = [] + while let entry = readdir(directory) { + let name = withUnsafeBytes(of: entry.pointee.d_name) { String(decoding: $0.prefix { $0 != 0 }, as: UTF8.self) } + if name != "." && name != ".." { names.append(name) } + } + closedir(directory) + for name in names { remove(path + "/" + name) } + rmdir(path) + } else { + unlink(path) + } + } + + func path(_ name: String) -> String { path + "/" + name } + + func write(_ name: String, _ bytes: [UInt8]) { + let descriptor = open(path(name), O_WRONLY | O_CREAT | O_TRUNC, 0o644) + precondition(descriptor >= 0) + _ = bytes.withUnsafeBytes { systemWrite(descriptor, $0.baseAddress, $0.count) } + close(descriptor) + } + + func read(_ name: String) -> [UInt8]? { + let descriptor = open(path(name), O_RDONLY) + guard descriptor >= 0 else { return nil } + defer { close(descriptor) } + var bytes: [UInt8] = [] + var chunk = [UInt8](repeating: 0, count: 4096) + while true { + let count = chunk.withUnsafeMutableBytes { systemRead(descriptor, $0.baseAddress, $0.count) } + if count <= 0 { return bytes } + bytes += chunk[0 ..< count] + } + } + + func makeFolder(_ name: String) { + mkdir(path(name), 0o755) + } + + func exists(_ name: String) -> Bool { + var info = stat() + return stat(path(name), &info) == 0 + } +} + +private func systemWrite(_ descriptor: Int32, _ bytes: UnsafeRawPointer?, _ count: Int) -> Int { write(descriptor, bytes, count) } + +private func systemRead(_ descriptor: Int32, _ bytes: UnsafeMutableRawPointer?, _ count: Int) -> Int { read(descriptor, bytes, count) } diff --git a/Tests/GraphiteResourcesTests/ForkContentsTests.swift b/Tests/GraphiteResourcesTests/ForkContentsTests.swift new file mode 100644 index 0000000..b9a75d6 --- /dev/null +++ b/Tests/GraphiteResourcesTests/ForkContentsTests.swift @@ -0,0 +1,56 @@ +import Foundation +import Testing +import GraphiteBase +import GraphiteFiles +import GraphiteResources + +@Suite struct ForkContentsTests { + + private let bytes = (0 ..< 5000).map { UInt8(truncatingIfNeeded: $0 &* 7) } + + @Test func readsTheWholeDataFork() throws { + let folder = TemporaryFolder() + folder.write("data", bytes) + let fork = try Fork(path: folder.path("data"), kind: .data, permission: .read) + #expect(Array(try fork.contents()) == bytes) + // Whatever the mark was. + _ = try fork.seek(.start(100)) + #expect(Array(try fork.contents()) == bytes) + } + + @Test func aForkOpenForWritingIsReadIntoMemory() throws { + let folder = TemporaryFolder() + folder.write("data", bytes) + let fork = try Fork(path: folder.path("data"), kind: .data, permission: .readWrite) + let contents = try fork.contents() + #expect(Array(contents) == bytes) + // A copy: the file changing afterwards doesn't show in it. + folder.write("data", [UInt8](repeating: 0, count: bytes.count)) + #expect(Array(contents) == bytes) + } + + @Test func aResourceForkIsReadIntoMemory() throws { + let folder = TemporaryFolder() + folder.write("file", []) + var double = AppleDouble() + double.resourceFork = bytes + folder.write("._file", double.bytes) + let fork = try Fork(path: folder.path("file"), kind: .resource, permission: .read) + #expect(Array(try fork.contents()) == bytes) + } + + @Test func contentsStartAtZeroWhateverTheStorage() throws { + let folder = TemporaryFolder() + folder.write("data", bytes) + let contents = try Fork(path: folder.path("data"), kind: .data, permission: .read).contents() + #expect(contents.startIndex == 0) + #expect(contents.count == bytes.count) + } + + @Test func anEmptyForkIsEmpty() throws { + let folder = TemporaryFolder() + folder.write("empty", []) + let fork = try Fork(path: folder.path("empty"), kind: .data, permission: .read) + #expect(try fork.contents().isEmpty) + } +} diff --git a/Tests/GraphiteResourcesTests/InfoPlistTests.swift b/Tests/GraphiteResourcesTests/InfoPlistTests.swift new file mode 100644 index 0000000..4c62fff --- /dev/null +++ b/Tests/GraphiteResourcesTests/InfoPlistTests.swift @@ -0,0 +1,128 @@ +import Foundation +import Testing +import GraphiteBase +import GraphiteResources + +@Suite struct InfoPlistTests { + + private func plist(_ body: String) -> [UInt8] { + Array(""" + + + + + \(body) + + + """.utf8) + } + + @Test func readsTopLevelStrings() throws { + let info = try InfoPlist(bytes: plist(""" + CFBundleIconFile + App + CFBundleName + My App + """)) + #expect(info["CFBundleIconFile"] == "App") + #expect(info["CFBundleName"] == "My App") + #expect(info["CFBundleVersion"] == nil) + } + + @Test func skipsOtherValuesAndKeepsTheKeysStraight() throws { + let info = try InfoPlist(bytes: plist(""" + LSUIElement + + CFBundleVersion + 3 + CFBundleIconFile + Icon.icns + """)) + #expect(info["CFBundleIconFile"] == "Icon.icns") + #expect(info["LSUIElement"] == nil) + #expect(info["CFBundleVersion"] == nil) + } + + @Test func ignoresNestedValues() throws { + let info = try InfoPlist(bytes: plist(""" + CFBundleDocumentTypes + + + CFBundleIconFile + Wrong + Names + x + + + CFBundleIconFile + Right + Empty + + Name + After + """)) + #expect(info["CFBundleIconFile"] == "Right") + #expect(info["Name"] == "After") + #expect(info["Names"] == nil) + } + + @Test func decodesEntities() throws { + let info = try InfoPlist(bytes: plist(""" + ATom & Jerry <3 AB "q" + """)) + #expect(info["A"] == "Tom & Jerry <3 AB \"q\"") + } + + @Test func emptyStringsAndComments() throws { + let info = try InfoPlist(bytes: plist(""" + + E + F + """)) + #expect(info["E"] == "") + #expect(info["F"] == "") + } + + @Test func nonASCIIText() throws { + let info = try InfoPlist(bytes: plist("NCafé")) + #expect(info["N"] == "Café") + } + + @Test func readsBinaryLists() throws { + let data = try PropertyListSerialization.data( + fromPropertyList: ["CFBundleIconFile": "App", "Count": 3, "Nested": ["CFBundleIconFile": "Wrong"]] as [String: Any], + format: .binary, options: 0) + #expect(data.starts(with: Array("bplist".utf8))) + let info = try InfoPlist(bytes: Array(data)) + #expect(info["CFBundleIconFile"] == "App") + #expect(info["Count"] == nil) + #expect(info.strings.count == 1) + } + + @Test func readsFromAnyBytes() throws { + let bytes = plist("CFBundleIconFileApp") + #expect(try InfoPlist(bytes: bytes)["CFBundleIconFile"] == "App") + #expect(try InfoPlist(bytes: Data(bytes))["CFBundleIconFile"] == "App") + #expect(try bytes.withUnsafeBytes { try InfoPlist(bytes: $0) }["CFBundleIconFile"] == "App") + // A slice keeps its parent's indices; the list is what it holds. + let padded = Data([1, 2, 3] + bytes) + #expect(try InfoPlist(bytes: padded[3...])["CFBundleIconFile"] == "App") + } + + @Test func bytesThatAreNotAListAreAParameterError() { + #expect(throws: MacError.parameter) { try InfoPlist(bytes: []) } + #expect(throws: MacError.parameter) { try InfoPlist(bytes: Array("not a plist".utf8)) } + #expect(throws: MacError.parameter) { try InfoPlist(bytes: Array("bplist00".utf8) + [0, 1, 2]) } + } + + @Test func aListThatIsNotADictionaryReadsAsEmpty() throws { + #expect(try InfoPlist(bytes: Array("x".utf8)).strings.isEmpty) + } + + @Test func truncatedInputDoesNotTrap() { + let whole = plist("Ab") + for length in 0 ... whole.count { + _ = try? InfoPlist(bytes: Array(whole.prefix(length))) + } + } +} diff --git a/Tests/GraphiteResourcesTests/ResourceBytesTests.swift b/Tests/GraphiteResourcesTests/ResourceBytesTests.swift new file mode 100644 index 0000000..9eb5ac5 --- /dev/null +++ b/Tests/GraphiteResourcesTests/ResourceBytesTests.swift @@ -0,0 +1,81 @@ +import struct Foundation.Data +import Testing +import GraphiteBase +import GraphiteFiles +import GraphiteResources + +@Suite struct ResourceBytesTests { + + private let resources: [(resource: Resource, bytes: [UInt8])] = [ + (Resource(type: "TEXT", id: 128, name: "First"), Array("hello".utf8)), + (Resource(type: "TEXT", id: 129), [1, 2, 3]), + (Resource(type: "ICN#", id: -16455), [UInt8](repeating: 0xFF, count: 256)), + ] + + private func fork() throws -> [UInt8] { + try ResourceMap.write(resources) + } + + @Test func mapsReadFromAnyBytes() throws { + let bytes = try fork() + let fromArray = try ResourceMap(parsing: bytes) + #expect(fromArray.entries.count == 3) + #expect(try ResourceMap(parsing: Data(bytes)) == fromArray) + #expect(try bytes.withUnsafeBytes { try ResourceMap(parsing: $0) } == fromArray) + } + + @Test func aSliceOfDataIsAFork() throws { + let bytes = try fork() + let padded = Data([7, 7, 7, 7, 7] + bytes + [9, 9, 9]) + let slice = padded[5 ..< 5 + bytes.count] + #expect(slice.startIndex == 5) + #expect(try ResourceMap(parsing: slice) == ResourceMap(parsing: bytes)) + let file = try ResourceFile(bytes: slice) + #expect(try file.bytes(type: "TEXT", id: 128) == Array("hello".utf8)) + #expect(try file.bytes(type: "TEXT", id: 129) == [1, 2, 3]) + #expect(try file.bytes(type: "ICN#", id: -16455).count == 256) + } + + @Test func filesReadFromAnyBytes() throws { + let bytes = try fork() + for file in [try ResourceFile(bytes: bytes), try ResourceFile(bytes: Data(bytes))] { + #expect(file.types == ["TEXT", "ICN#"]) + #expect(try file.bytes(type: "TEXT", id: 129) == [1, 2, 3]) + } + } + + @Test func truncatedSlicesNeverTrap() throws { + let bytes = try fork() + let padded = Data([1, 2, 3] + bytes) + for length in 0 ... bytes.count { + _ = try? ResourceMap(parsing: padded[3 ..< 3 + length]) + _ = try? ResourceFile(bytes: padded[3 ..< 3 + length]) + } + } + + @Test func aResourceFileInADataForkIsReadFromTheFork() throws { + let folder = TemporaryFolder() + folder.write("Data.rsrc", try fork()) + let file = try ResourceFile(fork: Fork(path: folder.path("Data.rsrc"), kind: .data, permission: .read)) + #expect(file.attributes.contains(.readOnly)) + #expect(file.resources.count == 3) + #expect(try file.bytes(type: "TEXT", id: 128) == Array("hello".utf8)) + #expect(try file.size(type: "ICN#", id: -16455) == 256) + } + + @Test func updatingWritesBackAndReadsAgain() throws { + let folder = TemporaryFolder() + folder.write("Data.rsrc", try fork()) + let file = try ResourceFile(fork: Fork(path: folder.path("Data.rsrc"), kind: .data, permission: .readWrite)) + try file.setBytes([9, 9], type: "TEXT", id: 129) + try file.add(Resource(type: "STR ", id: 128), bytes: [3, 0x61, 0x62, 0x63]) + try file.update() + #expect(try file.bytes(type: "TEXT", id: 129) == [9, 9]) + #expect(try file.bytes(type: "STR ", id: 128) == [3, 0x61, 0x62, 0x63]) + #expect(try file.bytes(type: "TEXT", id: 128) == Array("hello".utf8)) + // What is on disk reads the same. + let again = try ResourceFile(bytes: try #require(folder.read("Data.rsrc"))) + #expect(try again.bytes(type: "TEXT", id: 129) == [9, 9]) + #expect(again.resources.count == 4) + } +} diff --git a/Tests/GraphiteResourcesTests/TypedResourceBytesTests.swift b/Tests/GraphiteResourcesTests/TypedResourceBytesTests.swift new file mode 100644 index 0000000..1e08b1f --- /dev/null +++ b/Tests/GraphiteResourcesTests/TypedResourceBytesTests.swift @@ -0,0 +1,47 @@ +import struct Foundation.Data +import Testing +import GraphiteBase +import GraphiteFiles +import GraphiteResources + +@Suite struct TypedResourceBytesTests { + + @Test func stringLists() throws { + let bytes: [UInt8] = [0, 2, 3, 0x61, 0x62, 0x63, 1, 0x78] + let expected = StringList(strings: [PascalString(bytes: [0x61, 0x62, 0x63]), PascalString(bytes: [0x78])]) + #expect(try StringList(bytes: bytes) == expected) + #expect(try StringList(bytes: Data(bytes)) == expected) + #expect(try StringList(bytes: Data([1, 1] + bytes)[2...]) == expected) + #expect(try bytes.withUnsafeBytes { try StringList(bytes: $0) } == expected) + #expect(throws: MacError.mapRead) { try StringList(bytes: Data([0, 3, 1, 0x61])) } + } + + @Test func stringResources() { + let bytes: [UInt8] = [3, 0x61, 0x62, 0x63] + let expected = StringResource(string: PascalString(bytes: [0x61, 0x62, 0x63])) + #expect(StringResource(bytes: bytes) == expected) + #expect(StringResource(bytes: Data(bytes)) == expected) + #expect(StringResource(bytes: Data([7] + bytes)[1...]) == expected) + } + + @Test func versions() throws { + let bytes: [UInt8] = [1, 0x23, 0x80, 0, 0, 0, 3, 0x31, 0x2E, 0x30, 2, 0x4F, 0x4B] + let fromArray = try VersionResource(bytes: bytes) + #expect(fromArray.major == 1) + #expect(fromArray.shortVersion == PascalString(bytes: Array("1.0".utf8))) + #expect(fromArray.longVersion == PascalString(bytes: Array("OK".utf8))) + #expect(try VersionResource(bytes: Data(bytes)) == fromArray) + #expect(try VersionResource(bytes: Data([5, 5] + bytes)[2...]) == fromArray) + #expect(throws: MacError.mapRead) { try VersionResource(bytes: Data(bytes.prefix(8))) } + } + + @Test func openingAChainFileFromData() throws { + let fork = try ResourceMap.write([(Resource(type: "TEXT", id: 128), [1, 2, 3])]) + let folder = TemporaryFolder() + let chain = ResourceChain(fileSystem: FileSystem(defaultFolder: folder.path)) + let fromData = try chain.open(bytes: Data(fork)) + let fromSlice = try chain.open(bytes: Data([4, 4, 4] + fork)[3...]) + #expect(fromData != fromSlice) + #expect(try chain.get(type: "TEXT", id: 128).bytes == [1, 2, 3]) + } +} diff --git a/Tests/GraphiteTextTests/FontTableTests.swift b/Tests/GraphiteTextTests/FontTableTests.swift new file mode 100644 index 0000000..71cd505 --- /dev/null +++ b/Tests/GraphiteTextTests/FontTableTests.swift @@ -0,0 +1,73 @@ +#if FreeType +import Testing +import GraphiteBase +import GraphiteText + +/// Needs a font on the machine: the system's, which nothing here checks in. +@Suite struct FontTableTests { + + static let finder = FontFinder() + static let entry = finder.fonts.first { $0.index == 0 && $0.path.lowercased().hasSuffix(".ttf") } + 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) + } + + private func int16(_ bytes: [UInt8], at offset: Int) -> Int { + Int(Int16(bitPattern: UInt16(bytes[offset]) << 8 | UInt16(bytes[offset + 1]))) + } + + @Test(.enabled(if: Self.hasFont)) func theHeadTableIsTheFontHeader() throws { + let head = try #require(try face().table("head")) + #expect(head.count == 54) + // The magic number, then the units per em. + #expect(Array(head[12 ..< 16]) == [0x5F, 0x0F, 0x3C, 0xF5]) + #expect(int16(head, at: 18) > 0) + } + + @Test(.enabled(if: Self.hasFont)) func missingTablesAreNil() throws { + #expect(try face().table("zzzz") == nil) + } + + @Test(.enabled(if: Self.hasFont)) func tablesAreTheSameAcrossLoads() throws { + let entry = try #require(Self.entry) + let fromFile = try face() + let bytes = try #require(fromFile.table("head")) + let name = try #require(fromFile.table("name")) + #expect(name.count > 6) + #expect(bytes.count == 54) + #expect(try FreeTypeFace(path: entry.path, index: entry.index).table("head") == bytes) + } + + @Test(.enabled(if: Self.hasFont)) func horizontalMetricsAreInEms() throws { + let face = try face() + let metrics = try #require(face.horizontalMetrics) + #expect(metrics.ascent > 0 && metrics.ascent < 2) + #expect(metrics.descent < 0 && metrics.descent > -1) + #expect(metrics.leading >= 0) + #expect(metrics.maximumAdvance > 0) + #expect(metrics.averageAdvance > 0 && metrics.averageAdvance <= metrics.maximumAdvance) + #expect(metrics.capHeight > 0 && metrics.xHeight > 0 && metrics.xHeight < metrics.capHeight) + #expect(metrics.underlinePosition < 0 && metrics.underlineThickness > 0) + + // The same ascent and descent as the 'hhea' table gives over the em. + let head = try #require(face.table("head")) + let hhea = try #require(face.table("hhea")) + let em = Double(int16(head, at: 18)) + let hheaAscent = Double(int16(hhea, at: 4)) / em + let hheaDescent = Double(int16(hhea, at: 6)) / em + if hheaAscent > 0 { + #expect(abs(metrics.ascent - hheaAscent) < 0.01) + #expect(abs(metrics.descent - hheaDescent) < 0.01) + } + } + + @Test(.enabled(if: Self.hasFont)) func theBuiltInFontHasNoTables() { + let system = SystemFont.shared + #expect(system.table("head") == nil) + #expect(system.horizontalMetrics == nil) + } +} +#endif diff --git a/Tests/GraphiteTextTests/SfntTablesTests.swift b/Tests/GraphiteTextTests/SfntTablesTests.swift new file mode 100644 index 0000000..af712c4 --- /dev/null +++ b/Tests/GraphiteTextTests/SfntTablesTests.swift @@ -0,0 +1,161 @@ +import struct Foundation.Data +import Testing +import GraphiteBase +import GraphiteText + +@Suite struct SfntTablesTests { + + /// A table of `size` zero bytes with fields written at offsets. + private func table(_ size: Int, _ fields: [(Int, UInt32, Int)] = []) -> [UInt8] { + var bytes = [UInt8](repeating: 0, count: size) + for (offset, value, width) in fields { + for index in 0 ..< width { bytes[offset + index] = UInt8(truncatingIfNeeded: value >> UInt32(8 * (width - 1 - index))) } + } + return bytes + } + + private func head(unitsPerEm: UInt32 = 2048, xMin: Int16 = -100, macStyle: UInt32 = 0) -> [UInt8] { + table(54, [(18, unitsPerEm, 2), (36, UInt32(UInt16(bitPattern: xMin)), 2), (44, macStyle, 2)]) + } + + private let hhea = [UInt8](repeating: 0, count: 10) + [0x09, 0xC4] + [UInt8](repeating: 0, count: 24) // advanceWidthMax 2500 + + private func os2(version: UInt32 = 2, selection: UInt32 = 0) -> [UInt8] { + table(96, [(0, version, 2), (2, 1100, 2), (62, selection, 2), (86, 1000, 2), (88, 1400, 2)]) + } + + private func post() -> [UInt8] { + table(32, [(4, UInt32(bitPattern: Int32(-12 * 65536)), 4), (8, UInt32(UInt16(bitPattern: -150)), 2), (10, 90, 2)]) + } + + /// An sfnt file: its directory, then the tables one after another. `base` + /// is where the directory starts, for a face of a collection. + private func sfnt(_ tables: [(FourCharCode, [UInt8])], base: Int = 0) -> [UInt8] { + var writer = BigEndianWriter() + writer.write(UInt32(0x0001_0000)) + writer.write(UInt16(tables.count)) + writer.writeZeros(6) + var offset = base + 12 + 16 * tables.count + for (tag, bytes) in tables { + writer.write(tag.rawValue) + writer.write(UInt32(0)) + writer.write(UInt32(offset)) + writer.write(UInt32(bytes.count)) + offset += bytes.count + } + for (_, bytes) in tables { writer.write(bytes: bytes) } + return writer.bytes + } + + private var font: [UInt8] { + sfnt([("head", head(macStyle: 0)), ("hhea", hhea), ("OS/2", os2()), ("post", post())]) + } + + @Test func readsTheDirectoryAndTables() throws { + let tables = try SfntTables(font: font) + #expect(tables.tags == ["OS/2", "head", "hhea", "post"]) + #expect(tables.table("head") == head()) + #expect(tables.table("post") == post()) + #expect(tables.table("cmap") == nil) + #expect(tables.hasOS2) + } + + @Test func readsTheFields() throws { + let tables = try SfntTables(font: font) + #expect(tables.unitsPerEm == 2048) + #expect(tables.maximumAdvance == 2500) + #expect(tables.minimumLeftSideBearing == -100) + #expect(tables.underline?.position == -150) + #expect(tables.underline?.thickness == 90) + #expect(tables.italicAngle == -12) + #expect(tables.averageAdvance == 1100) + #expect(tables.capHeight == 1400) + #expect(tables.xHeight == 1000) + } + + @Test func missingTablesGiveNoFields() throws { + let tables = try SfntTables(font: sfnt([("head", head())])) + #expect(tables.unitsPerEm == 2048) + #expect(tables.maximumAdvance == nil) + #expect(tables.underline == nil) + #expect(tables.italicAngle == nil) + #expect(tables.averageAdvance == nil) + #expect(tables.capHeight == nil) + #expect(!tables.hasOS2) + #expect(try SfntTables(font: sfnt([])).unitsPerEm == nil) + } + + @Test func oldOS2TablesHaveNoCapOrXHeight() throws { + let tables = try SfntTables(font: sfnt([("OS/2", os2(version: 1))])) + #expect(tables.averageAdvance == 1100) + #expect(tables.capHeight == nil) + #expect(tables.xHeight == nil) + } + + @Test func stylesFromMacStyleAndSelection() throws { + func styles(macStyle: UInt32, selection: UInt32?) throws -> TextStyle { + var tables: [(FourCharCode, [UInt8])] = [("head", head(macStyle: macStyle))] + if let selection { tables.append(("OS/2", os2(selection: selection))) } + return try SfntTables(font: sfnt(tables)).styles + } + #expect(try styles(macStyle: 0, selection: nil) == []) + #expect(try styles(macStyle: 1, selection: nil) == .bold) + #expect(try styles(macStyle: 2, selection: nil) == .italic) + #expect(try styles(macStyle: 3, selection: nil) == [.bold, .italic]) + #expect(try styles(macStyle: 0, selection: 0x20) == .bold) + #expect(try styles(macStyle: 0, selection: 0x01) == .italic) + #expect(try styles(macStyle: 0, selection: 0x200) == .italic) + #expect(try styles(macStyle: 0, selection: 0x40) == []) + } + + @Test func tablesPastTheEndAreNotThere() throws { + var bytes = font + // Cut the file in the middle of the last table. + bytes.removeLast(10) + let tables = try SfntTables(font: bytes) + #expect(tables.table("head") == head()) + #expect(tables.table("post") == nil) + } + + @Test func aCollectionsFacesAreEachTheirOwn() throws { + // A 'ttcf' header of two faces, then each face's directory and tables. + let plain = sfnt([("head", head(macStyle: 0))], base: 20) + var writer = BigEndianWriter() + writer.write(FourCharCode("ttcf").rawValue) + writer.write(UInt32(0x0001_0000)) + writer.write(UInt32(2)) + let firstBase = 20 + let secondBase = firstBase + plain.count + writer.write(UInt32(firstBase)) + writer.write(UInt32(secondBase)) + let bold = sfnt([("head", head(macStyle: 1))], base: secondBase) + let bytes = writer.bytes + plain + bold + #expect(try SfntTables(font: bytes, index: 0).styles == []) + #expect(try SfntTables(font: bytes, index: 1).styles == .bold) + #expect(throws: MacError.parameter) { try SfntTables(font: bytes, index: 2) } + #expect(throws: MacError.parameter) { try SfntTables(font: bytes, index: -1) } + } + + @Test func fontsFromAnyBytes() throws { + let bytes = font + let expected = try SfntTables(font: bytes).tags + #expect(try SfntTables(font: Data(bytes)).tags == expected) + #expect(try SfntTables(font: Data([1, 2, 3] + bytes)[3...]).tags == expected) + #expect(try bytes.withUnsafeBytes { try SfntTables(font: $0) }.tags == expected) + } + + @Test func otherBytesAreAParameterError() { + #expect(throws: MacError.parameter) { try SfntTables(font: [UInt8]()) } + #expect(throws: MacError.parameter) { try SfntTables(font: Array("not a font at all".utf8)) } + #expect(throws: MacError.parameter) { try SfntTables(font: [0, 1, 0]) } + } + + @Test func truncatedFontsNeverTrap() { + let bytes = font + for length in 0 ... bytes.count { + if let tables = try? SfntTables(font: bytes.prefix(length)) { + _ = (tables.tags, tables.styles, tables.unitsPerEm, tables.capHeight, tables.underline) + } + } + } +}