From 8cf24e72faa19240a185eb4649dad6e9961fe829 Mon Sep 17 00:00:00 2001 From: Kyle Date: Tue, 17 Nov 2026 02:51:02 +0800 Subject: [PATCH 1/5] fix(path): mark ORBPathStorageAppendElement points as nullable --- Sources/OpenRenderBox/Path/ORBPath.swift | 6 ++++-- Sources/OpenRenderBox/Path/ORBPathStorage.swift | 2 +- Sources/OpenRenderBoxCxx/Path/ORBPathStorage.h | 2 +- 3 files changed, 6 insertions(+), 4 deletions(-) diff --git a/Sources/OpenRenderBox/Path/ORBPath.swift b/Sources/OpenRenderBox/Path/ORBPath.swift index 713cd26..c3ad90a 100644 --- a/Sources/OpenRenderBox/Path/ORBPath.swift +++ b/Sources/OpenRenderBox/Path/ORBPath.swift @@ -284,13 +284,15 @@ struct _ORBPathRecord: Equatable { self.transform = transform?.isIdentity == false ? transform : nil } - init?(element: ORBPath.Element, points: UnsafePointer, userInfo: UnsafeRawPointer?) { + init?(element: ORBPath.Element, points: UnsafePointer?, userInfo: UnsafeRawPointer?) { let counts = [2, 2, 4, 6, 0, 4, 4, 4, 6, 6, 8, 8, 5, 5, 5, 5, 0, 0, 2, 3, 0, 0, 2, 1, 1] let index = Int(element.rawValue) guard counts.indices.contains(index) else { return nil } + let count = counts[index] + guard count == 0 || points != nil else { return nil } self.init( element: element, - values: Array(UnsafeBufferPointer(start: points, count: counts[index])), + values: count == 0 ? [] : Array(UnsafeBufferPointer(start: points, count: count)), transform: ((0...15).contains(index) && index != 4) || index == 17 || index == 21 ? userInfo?.load(as: CGAffineTransform.self) : nil ) if element == .stroked { diff --git a/Sources/OpenRenderBox/Path/ORBPathStorage.swift b/Sources/OpenRenderBox/Path/ORBPathStorage.swift index a3ab93d..74116b3 100644 --- a/Sources/OpenRenderBox/Path/ORBPathStorage.swift +++ b/Sources/OpenRenderBox/Path/ORBPathStorage.swift @@ -32,7 +32,7 @@ extension ORBPath.Storage { _records.records.removeAll(keepingCapacity: true) } - public func append(element: ORBPath.Element, points: UnsafePointer, userInfo: UnsafeRawPointer?) { + public func append(element: ORBPath.Element, points: UnsafePointer?, userInfo: UnsafeRawPointer?) { guard let record = _ORBPathRecord(element: element, points: points, userInfo: userInfo) else { return } _records.records.append(record) } diff --git a/Sources/OpenRenderBoxCxx/Path/ORBPathStorage.h b/Sources/OpenRenderBoxCxx/Path/ORBPathStorage.h index ba91927..c0fbcc5 100644 --- a/Sources/OpenRenderBoxCxx/Path/ORBPathStorage.h +++ b/Sources/OpenRenderBoxCxx/Path/ORBPathStorage.h @@ -30,7 +30,7 @@ ORB_EXPORT void ORBPathStorageClear(ORBPathStorageRef storage) ORB_SWIFT_NAME(ORBPathStorageRef.clear(self:)); ORB_EXPORT -void ORBPathStorageAppendElement(ORBPathStorageRef storage, ORBPathElement element, CGFloat const * points, const void * _Nullable userInfo) ORB_SWIFT_NAME(ORBPathStorageRef.append(self:element:points:userInfo:)); +void ORBPathStorageAppendElement(ORBPathStorageRef storage, ORBPathElement element, CGFloat const * _Nullable points, const void * _Nullable userInfo) ORB_SWIFT_NAME(ORBPathStorageRef.append(self:element:points:userInfo:)); ORB_EXPORT bool ORBPathStorageAppendPath(ORBPathStorageRef, ORBPath) ORB_SWIFT_NAME(ORBPathStorageRef.append(self:path:)); From 9a5636fbcf5837ebbc59dcaf176f2d52ce360740 Mon Sep 17 00:00:00 2001 From: Kyle Date: Sat, 21 Nov 2026 22:52:27 +0800 Subject: [PATCH 2/5] fix(path): mark ORBPathCopyData return type as nullable --- Sources/OpenRenderBoxCxx/Path/ORBPath.h | 2 +- Sources/OpenRenderBoxCxx/Path/PathData.cpp | 2 +- .../PathOperationsTests.swift | 7 ++++--- 3 files changed, 6 insertions(+), 5 deletions(-) diff --git a/Sources/OpenRenderBoxCxx/Path/ORBPath.h b/Sources/OpenRenderBoxCxx/Path/ORBPath.h index 30d96f3..75709c0 100644 --- a/Sources/OpenRenderBoxCxx/Path/ORBPath.h +++ b/Sources/OpenRenderBoxCxx/Path/ORBPath.h @@ -256,7 +256,7 @@ ORB_EXPORT ORBPath ORBPathCopyInterpolatedPath(ORBPath path, ORBPath other, float fraction) ORB_SWIFT_NAME(ORBPath.interpolated(self:to:fraction:)); ORB_EXPORT -CFDataRef ORBPathCopyData(ORBPath path) ORB_SWIFT_NAME(getter:ORBPath.data(self:)); +CFDataRef _Nullable ORBPathCopyData(ORBPath path) ORB_SWIFT_NAME(getter:ORBPath.data(self:)); ORB_EXPORT ORBPath ORBPathMakeWithData(CFDataRef data) ORB_SWIFT_NAME(ORBPath.init(data:)); diff --git a/Sources/OpenRenderBoxCxx/Path/PathData.cpp b/Sources/OpenRenderBoxCxx/Path/PathData.cpp index e23bbf9..6f7726d 100644 --- a/Sources/OpenRenderBoxCxx/Path/PathData.cpp +++ b/Sources/OpenRenderBoxCxx/Path/PathData.cpp @@ -281,7 +281,7 @@ Encoder encode_metadata(unsigned element, const void *info) { } // namespace -CFDataRef ORBPathCopyData(ORBPath path) { +CFDataRef _Nullable ORBPathCopyData(ORBPath path) { struct Encoding { Encoder output, elements, floats, doubles; } encoding; diff --git a/Tests/OpenRenderBoxCompatibilityTests/PathOperationsTests.swift b/Tests/OpenRenderBoxCompatibilityTests/PathOperationsTests.swift index 43b2b85..eeeb8ff 100644 --- a/Tests/OpenRenderBoxCompatibilityTests/PathOperationsTests.swift +++ b/Tests/OpenRenderBoxCompatibilityTests/PathOperationsTests.swift @@ -200,17 +200,18 @@ struct PathOperationsTests { } @Test - func serializedRectUsesCompatibleWireFormat() { + func serializedRectUsesCompatibleWireFormat() throws { let path = ORBPath(rect: CGRect(x: 1, y: 2, width: 10, height: 20), transform: nil) defer { path.release() } - let data = path.data as Data + let data = try #require(path.data) as Data #expect(data == Data([0x1a, 1, 5, 0x12, 0x10, 0, 0, 0x80, 0x3f, 0, 0, 0, 0x40, 0, 0, 0x20, 0x41, 0, 0, 0xa0, 0x41])) let copy = ORBPath(data: data as CFData) defer { copy.release() } #expect(copy.isEqual(to: path)) #expect(path.debugDescription as String == "RBPath:\n rect 1 2 10 20\n") let fractional = ORBPath(rect: CGRect(x: 0.1, y: 0.2, width: 10.3, height: 20.4), transform: nil) - let decoded = ORBPath(data: fractional.data) + let fractionalData = try #require(fractional.data) + let decoded = ORBPath(data: fractionalData) fractional.release() defer { decoded.release() } #expect(pathElements(decoded) == [PathElementRecord(element: 5, points: [CGFloat(Float(0.1)), CGFloat(Float(0.2)), CGFloat(Float(10.3)), CGFloat(Float(20.4))])]) From 70e909e351ff35fa4a9cf53cbb111c57a73daf5e Mon Sep 17 00:00:00 2001 From: Kyle Date: Sat, 21 Nov 2026 23:14:58 +0800 Subject: [PATCH 3/5] fix(path): mark ORBPathMakeWithData data parameter as nullable --- Sources/OpenRenderBoxCxx/Path/ORBPath.h | 2 +- Sources/OpenRenderBoxCxx/Path/PathData.cpp | 2 +- Tests/OpenRenderBoxTests/Path/PathTests.swift | 9 +++++++++ 3 files changed, 11 insertions(+), 2 deletions(-) diff --git a/Sources/OpenRenderBoxCxx/Path/ORBPath.h b/Sources/OpenRenderBoxCxx/Path/ORBPath.h index 75709c0..3b55e1d 100644 --- a/Sources/OpenRenderBoxCxx/Path/ORBPath.h +++ b/Sources/OpenRenderBoxCxx/Path/ORBPath.h @@ -259,7 +259,7 @@ ORB_EXPORT CFDataRef _Nullable ORBPathCopyData(ORBPath path) ORB_SWIFT_NAME(getter:ORBPath.data(self:)); ORB_EXPORT -ORBPath ORBPathMakeWithData(CFDataRef data) ORB_SWIFT_NAME(ORBPath.init(data:)); +ORBPath ORBPathMakeWithData(CFDataRef _Nullable data) ORB_SWIFT_NAME(ORBPath.init(data:)); ORB_EXPORT CFStringRef ORBPathCopyDebugDescription(ORBPath path) ORB_SWIFT_NAME(getter:ORBPath.debugDescription(self:)); diff --git a/Sources/OpenRenderBoxCxx/Path/PathData.cpp b/Sources/OpenRenderBoxCxx/Path/PathData.cpp index 6f7726d..64cb55c 100644 --- a/Sources/OpenRenderBoxCxx/Path/PathData.cpp +++ b/Sources/OpenRenderBoxCxx/Path/PathData.cpp @@ -309,7 +309,7 @@ CFDataRef _Nullable ORBPathCopyData(ORBPath path) { return CFDataCreate(nullptr, encoding.output.bytes.data(), CFIndex(encoding.output.bytes.size())); } -ORBPath ORBPathMakeWithData(CFDataRef data) { +ORBPath ORBPathMakeWithData(CFDataRef _Nullable data) { if (!data) return ORBPathNull; Decoder decoder{CFDataGetBytePtr(data), size_t(CFDataGetLength(data))}; Bytes elements; diff --git a/Tests/OpenRenderBoxTests/Path/PathTests.swift b/Tests/OpenRenderBoxTests/Path/PathTests.swift index 4f3cb29..2a21c5b 100644 --- a/Tests/OpenRenderBoxTests/Path/PathTests.swift +++ b/Tests/OpenRenderBoxTests/Path/PathTests.swift @@ -224,5 +224,14 @@ struct PathTests { #expect(abs(actual.width - expected.width) < 0.0001) #expect(abs(actual.height - expected.height) < 0.0001) } + + @Test + func nilDataProducesNullPath() { + let path = ORBPath(data: nil) + defer { path.release() } + + #expect(path.isNull) + #expect(path.isEmpty) + } } #endif From e2f854f06151a37d1bff60962039b30321c72b38 Mon Sep 17 00:00:00 2001 From: Kyle Date: Sat, 21 Nov 2026 22:52:28 +0800 Subject: [PATCH 4/5] feat(path): add portable CGPath element applier, interpolation, and data serialization --- Sources/OpenRenderBox/Path/ORBPath.swift | 306 +++++++++++ .../OpenRenderBox/Path/ORBPathCFData.swift | 35 ++ Sources/OpenRenderBox/Path/ORBPathData.swift | 500 ++++++++++++++++++ .../OpenRenderBox/Path/ORBPathGeometry.swift | 5 + Sources/OpenRenderBoxShims/ORBShims.swift | 2 +- .../Path/PortableCFDataTestSupport.swift | 27 + .../Path/PortablePathTests.swift | 219 ++++++++ 7 files changed, 1093 insertions(+), 1 deletion(-) create mode 100644 Sources/OpenRenderBox/Path/ORBPathCFData.swift create mode 100644 Sources/OpenRenderBox/Path/ORBPathData.swift create mode 100644 Tests/OpenRenderBoxTests/Path/PortableCFDataTestSupport.swift diff --git a/Sources/OpenRenderBox/Path/ORBPath.swift b/Sources/OpenRenderBox/Path/ORBPath.swift index c3ad90a..e7161f1 100644 --- a/Sources/OpenRenderBox/Path/ORBPath.swift +++ b/Sources/OpenRenderBox/Path/ORBPath.swift @@ -6,6 +6,7 @@ public import OpenCoreGraphicsShims public typealias ORBPathApplyCallback = (UnsafeMutableRawPointer, ORBPath.Element, UnsafePointer, UnsafeRawPointer?) -> Bool +public typealias ORBPathApplierCallback = (UnsafeMutableRawPointer, UnsafePointer) -> Bool public typealias ORBPathApplyShapeCallback = (UnsafeMutableRawPointer, ORBPathShapeType, UnsafePointer) -> Void public enum ORBPathShapeType: Int32, @unchecked Sendable { @@ -575,6 +576,58 @@ extension ORBPath { return callbacks.pointee.apply?(_object, info, callback) ?? true } + public func applyCGPathElements( + transform: UnsafePointer?, + info: UnsafeMutableRawPointer, + callback: ORBPathApplierCallback + ) -> Bool { + guard let records = _records() else { + preconditionFailure("path enumeration stopped during conversion") + } + let expanded = _orbExpandedRecords(records) + let transform = transform?.pointee + var pointStorage = (CGPoint.zero, CGPoint.zero, CGPoint.zero) + return withUnsafeMutablePointer(to: &pointStorage) { tuplePtr in + tuplePtr.withMemoryRebound(to: CGPoint.self, capacity: 3) { pointsPtr in + for record in expanded { + let type: CGPathElementType + let count: Int + switch record.element { + case .moveToPoint: + type = .moveToPoint + count = 1 + case .addLineToPoint: + type = .addLineToPoint + count = 1 + case .addQuadCurveToPoint: + type = .addQuadCurveToPoint + count = 2 + case .addCurveToPoint: + type = .addCurveToPoint + count = 3 + case .closeSubpath: + type = .closeSubpath + count = 0 + default: + preconditionFailure("Unsupported path element") + } + for index in 0.. Bool { if callbacks != rhs.callbacks { if callbacks == _orbEmptyCallbacks { return storage == Self.null.storage ? false : rhs.isEmpty } @@ -757,6 +810,259 @@ extension ORBPath { record.stroke = .init(lineCap: lineCap, lineJoin: lineJoin, dash: dash.map { Array(UnsafeBufferPointer(start: $0, count: max(0, dashCount))) } ?? []) return _wrapped(record) } + + public func canInterpolate(to other: ORBPath) -> Bool { + if isEqual(to: other) { return true } + guard let lhsRecords = _records() else { return false } + struct ComparisonState { + let records: [_ORBPathRecord] + var position = 0 + var trimmed: [Bool] = [false] + } + var state = ComparisonState(records: lhsRecords) + let result = withUnsafeMutablePointer(to: &state) { statePtr in + other.apply(info: UnsafeMutableRawPointer(statePtr)) { info, type, values, userInfo in + let state = info.assumingMemoryBound(to: ComparisonState.self) + if _orbIsNestingElement(type) { + state.pointee.trimmed.append((state.pointee.trimmed.last ?? false) || type == .trimmed) + } else if type == .end, state.pointee.trimmed.count > 1 { + state.pointee.trimmed.removeLast() + } + guard state.pointee.position < state.pointee.records.count else { return false } + let record = state.pointee.records[state.pointee.position] + state.pointee.position += 1 + guard _orbCompatibleTypes( + from: record.element.rawValue, + to: type.rawValue, + trimmed: state.pointee.trimmed.last ?? false + ) else { + return false + } + if type == .boolean { + let rhsBoolean = userInfo.map { Array(UnsafeRawBufferPointer(start: $0, count: 2)) } ?? [0, 0] + return (record.boolean ?? [0, 0]) == rhsBoolean + } + if type == .clipStroke { + let rhsPayload = userInfo?.load(as: _ORBPathClipPayload.self) + var a = record.clipStroke?.flags ?? 0 + var b = rhsPayload?.flags ?? 0 + let rhsCap = rhsPayload?.cap ?? 1 + if ((a ^ b) & 1) != 0, + let lhsValue = record.values.first, + (lhsValue < 0.0001 || lhsValue > 0.9999), + abs(lhsValue + (values[0] - 1)) < 0.0001 { + a &= ~1 + b &= ~1 + } + return a == b && (record.clipStroke?.cap ?? 1) == rhsCap + } + return true + } + } + return result && state.position == lhsRecords.count + } + + public func interpolated(to other: ORBPath, fraction: Float) -> ORBPath { + if fraction == 0 || (storage == other.storage && callbacks == other.callbacks) { + return retain() + } + if fraction == 1 { + return other.retain() + } + guard let lhsRecords = _records() else { return .null } + struct MixingState { + let records: [_ORBPathRecord] + let fraction: Float + var position = 0 + var output: [_ORBPathRecord] = [] + } + var state = MixingState(records: lhsRecords, fraction: fraction) + let result = withUnsafeMutablePointer(to: &state) { statePtr in + other.apply(info: UnsafeMutableRawPointer(statePtr)) { info, type, values, userInfo in + let state = info.assumingMemoryBound(to: MixingState.self) + guard state.pointee.position < state.pointee.records.count, + let rhsRecord = _ORBPathRecord(element: type, points: values, userInfo: userInfo) else { + return false + } + let record = state.pointee.records[state.pointee.position] + state.pointee.position += 1 + + var outputElement = record.element + var left = record.values + var right = rhsRecord.values + if record.element != type { + let fromRaw = record.element.rawValue + let toRaw = type.rawValue + let fromRect = fromRaw == 5 || fromRaw == 6 + let toRect = toRaw == 5 || toRaw == 6 + let fromRounded = (8...11).contains(fromRaw) + let toRounded = (8...11).contains(toRaw) + if fromRect && toRounded { + outputElement = type + left.append(contentsOf: repeatElement(0, count: right.count - left.count)) + } else if fromRounded && toRect { + right.append(contentsOf: repeatElement(0, count: left.count - right.count)) + } else if !(fromRect && toRect) { + return false + } + } + + let amount = Double(state.pointee.fraction) + let outputValues = zip(left, right).map { _orbInterpolateScalar($0, $1, amount) } + + var outputTransform: CGAffineTransform? = nil + if _orbHasAffineInfo(type) { + let lhsTransform = record.transform ?? .identity + let rhsTransform = rhsRecord.transform ?? .identity + if record.transform != nil || rhsRecord.transform != nil { + let mixed = _orbInterpolateTransform(lhsTransform, rhsTransform, state.pointee.fraction) + outputTransform = mixed.isIdentity ? nil : mixed + } + } + + var outputRecord = _ORBPathRecord(element: outputElement, values: outputValues, transform: outputTransform) + outputRecord.stroke = rhsRecord.stroke + outputRecord.boolean = rhsRecord.boolean + outputRecord.clipStroke = rhsRecord.clipStroke + state.pointee.output.append(outputRecord) + return true + } + } + return result ? Self._fromRecords(state.output) : .null + } +} + +private func _orbHasAffineInfo(_ element: ORBPath.Element) -> Bool { + guard element.rawValue >= 0 else { return false } + let type = UInt32(element.rawValue) + return type <= 24 && ((1 << type) & 0x1dd0010) == 0 +} + +private func _orbIsNestingElement(_ element: ORBPath.Element) -> Bool { + switch element { + case .transformed, .trimmed, .stroked, .boolean, .dilateGlyph, .offset, .clipStroke: + return true + default: + return false + } +} + +private func _orbCompatibleTypes(from: Int32, to: Int32, trimmed: Bool) -> Bool { + if from == to { return true } + let fromRect = from == 6 || (from == 5 && !trimmed) + let toRect = to == 6 || (to == 5 && !trimmed) + let fromRounded = (8...11).contains(from) + let toRounded = (8...11).contains(to) + return (fromRect && (toRect || toRounded)) || (fromRounded && toRect) +} + +private func _orbInterpolateScalar(_ from: CGFloat, _ to: CGFloat, _ amount: Double) -> CGFloat { + let result = Double(from).addingProduct(Double(to) - Double(from), amount) + return result.isNaN ? from : CGFloat(result) +} + +private struct _ORBAffineComponents { + var scaleWidth: Double + var scaleHeight: Double + var horizontalShear: Double + var rotation: Double + var translationDX: Double + var translationDY: Double +} + +private func _orbDecomposeTransform(_ m: CGAffineTransform) -> _ORBAffineComponents { + let a = Double(m.a), b = Double(m.b), c = Double(m.c), d = Double(m.d) + let tx = Double(m.tx), ty = Double(m.ty) + let det = a * d - b * c + var sx = _orbHypot(a, b) + if sx == 0 { + if d == 0 { + return _ORBAffineComponents(scaleWidth: 0, scaleHeight: 0, horizontalShear: 0, rotation: 0, translationDX: tx, translationDY: ty) + } + return _ORBAffineComponents( + scaleWidth: d < 0 ? -0.0 : 0.0, + scaleHeight: abs(d), + horizontalShear: c / d, + rotation: d < 0 ? -.pi : 0.0, + translationDX: tx, + translationDY: ty + ) + } + if det < 0 { + sx = -sx + } + let co = a / sx + let si = b / sx + let rot = _orbAtan2(si, co) + let sy = d * co - c * si + let sh = sy == 0 ? 0 : (c * co + d * si) / sy + return _ORBAffineComponents( + scaleWidth: sx, + scaleHeight: sy, + horizontalShear: sh, + rotation: rot, + translationDX: tx, + translationDY: ty + ) +} + +private func _orbMakeTransform(_ k: _ORBAffineComponents) -> CGAffineTransform { + let co = _orbCos(k.rotation) + let si = _orbSin(k.rotation) + return CGAffineTransform( + a: CGFloat(k.scaleWidth * co), + b: CGFloat(k.scaleWidth * si), + c: CGFloat(k.scaleHeight * (k.horizontalShear * co - si)), + d: CGFloat(k.scaleHeight * (k.horizontalShear * si + co)), + tx: CGFloat(k.translationDX), + ty: CGFloat(k.translationDY) + ) +} + +private func _orbInterpolateTransform(_ from: CGAffineTransform, _ to: CGAffineTransform, _ fraction: Float) -> CGAffineTransform { + let amount = Double(fraction) + func mix(_ a: Double, _ b: Double) -> Double { + a.addingProduct(b - a, amount) + } + if from.a == to.a && from.b == to.b && from.c == to.c && from.d == to.d { + return CGAffineTransform( + a: from.a, b: from.b, c: from.c, d: from.d, + tx: CGFloat(mix(Double(from.tx), Double(to.tx))), + ty: CGFloat(mix(Double(from.ty), Double(to.ty))) + ) + } + if (from.b == 0 && from.c == 0 && to.b == 0 && to.c == 0) || + (from.a == 0 && from.d == 0 && to.a == 0 && to.d == 0) { + return CGAffineTransform( + a: CGFloat(mix(Double(from.a), Double(to.a))), + b: CGFloat(mix(Double(from.b), Double(to.b))), + c: CGFloat(mix(Double(from.c), Double(to.c))), + d: CGFloat(mix(Double(from.d), Double(to.d))), + tx: CGFloat(mix(Double(from.tx), Double(to.tx))), + ty: CGFloat(mix(Double(from.ty), Double(to.ty))) + ) + } + var a = _orbDecomposeTransform(from) + var b = _orbDecomposeTransform(to) + if (a.scaleWidth < 0 && b.scaleHeight < 0) || (a.scaleHeight < 0 && b.scaleWidth < 0) { + a.scaleWidth = -a.scaleWidth + a.scaleHeight = -a.scaleHeight + a.rotation += a.rotation < 0 ? .pi : -.pi + } + if a.rotation == 0 { a.rotation = 2 * .pi } + if b.rotation == 0 { b.rotation = 2 * .pi } + if abs(a.rotation - b.rotation) > .pi { + if a.rotation > b.rotation { a.rotation -= 2 * .pi } + else { b.rotation -= 2 * .pi } + } + return _orbMakeTransform(_ORBAffineComponents( + scaleWidth: mix(a.scaleWidth, b.scaleWidth), + scaleHeight: mix(a.scaleHeight, b.scaleHeight), + horizontalShear: mix(a.horizontalShear, b.horizontalShear), + rotation: mix(a.rotation, b.rotation), + translationDX: mix(a.translationDX, b.translationDX), + translationDY: mix(a.translationDY, b.translationDY) + )) } diff --git a/Sources/OpenRenderBox/Path/ORBPathCFData.swift b/Sources/OpenRenderBox/Path/ORBPathCFData.swift new file mode 100644 index 0000000..b935e3b --- /dev/null +++ b/Sources/OpenRenderBox/Path/ORBPathCFData.swift @@ -0,0 +1,35 @@ +// +// ORBPathCFData.swift +// OpenRenderBox + +#if !OPENRENDERBOX_CF_CGTYPES +public import CoreFoundation + +extension ORBPath { + public var data: CFData? { + let bytes = _encodeWireBytes() + return bytes.withUnsafeBufferPointer { buffer in + CFDataCreate(nil, buffer.baseAddress, buffer.count) + } + } + + public init(data: CFData?) { + guard let data else { + self = .null + return + } + let length = CFDataGetLength(data) + if length <= 0 { + self.init(_wireBytes: []) + } else if let ptr = CFDataGetBytePtr(data) { + self.init(_wireBytes: Array(UnsafeBufferPointer(start: ptr, count: length))) + } else { + let bytes = [UInt8](unsafeUninitializedCapacity: length) { buffer, initializedCount in + CFDataGetBytes(data, CFRange(location: 0, length: length), buffer.baseAddress) + initializedCount = length + } + self.init(_wireBytes: bytes) + } + } +} +#endif diff --git a/Sources/OpenRenderBox/Path/ORBPathData.swift b/Sources/OpenRenderBox/Path/ORBPathData.swift new file mode 100644 index 0000000..186b300 --- /dev/null +++ b/Sources/OpenRenderBox/Path/ORBPathData.swift @@ -0,0 +1,500 @@ +// +// ORBPathData.swift +// OpenRenderBox + +#if !OPENRENDERBOX_CF_CGTYPES +import OpenCoreGraphicsShims + +private typealias _ORBCGFloat = CGFloat +private typealias _ORBCGAffineTransform = CGAffineTransform + +private let _orbElementArgumentCounts = [2, 2, 4, 6, 0, 4, 4, 4, 6, 6, 8, 8, 5, 5, 5, 5, 0, 0, 2, 3, 0, 0, 2, 1, 1] + +private func _orbArgumentCount(_ element: ORBPath.Element) -> Int { + let index = Int(element.rawValue) + return _orbElementArgumentCounts.indices.contains(index) ? _orbElementArgumentCounts[index] : 0 +} + +private func _orbMetadataKind(_ element: UInt32) -> UInt32 { + switch element { + case 4, 16, 18, 22, 23: return 0 + case 19: return 2 + case 20: return 3 + case 24: return 4 + default: return 1 + } +} + +private struct _ORBWireEncoder { + var bytes: [UInt8] = [] + + mutating func appendVarint(_ value: UInt64) { + var current = value + repeat { + let byte = UInt8(current & 0x7f) + current >>= 7 + bytes.append(byte | (current != 0 ? 0x80 : 0)) + } while current != 0 + } + + mutating func appendInteger(_ field: UInt32, _ value: UInt64) { + guard value != 0 else { return } + appendVarint(UInt64(field) << 3) + appendVarint(value) + } + + mutating func appendFloatScalar(_ value: Float) { + var bits = value.bitPattern.littleEndian + withUnsafeBytes(of: &bits) { bytes.append(contentsOf: $0) } + } + + mutating func appendDoubleScalar(_ value: Double) { + var bits = value.bitPattern.littleEndian + withUnsafeBytes(of: &bits) { bytes.append(contentsOf: $0) } + } + + mutating func appendReal(_ field: UInt32, _ value: Float, defaultValue: Float = 0) { + guard value != defaultValue else { return } + appendVarint((UInt64(field) << 3) | 5) + appendFloatScalar(value) + } + + mutating func appendData(_ field: UInt32, _ value: [UInt8]) { + appendVarint((UInt64(field) << 3) | 2) + appendVarint(UInt64(value.count)) + bytes.append(contentsOf: value) + } +} + +private struct _ORBWireField { + var number: UInt32 = 0 + var wire: UInt32 = 0 + var integer: UInt64 = 0 + var slice: ArraySlice = [] +} + +private struct _ORBWireDecoder { + let bytes: [UInt8] + var offset: Int = 0 + var valid: Bool = true + + init(_ bytes: [UInt8]) { + self.bytes = bytes + } + + mutating func readVarint(_ result: inout UInt64) -> Bool { + result = 0 + var shift: UInt64 = 0 + while shift < 70 { + guard offset < bytes.count else { + valid = false + return false + } + let byte = bytes[offset] + offset += 1 + if shift == 63 && byte > 1 { + valid = false + return false + } + result |= UInt64(byte & 0x7f) << shift + if (byte & 0x80) == 0 { + return true + } + shift += 7 + } + valid = false + return false + } + + mutating func next(_ field: inout _ORBWireField) -> Bool { + guard valid, offset < bytes.count else { return false } + var key: UInt64 = 0 + guard readVarint(&key), (key >> 3) != 0, (key >> 3) <= 0x1fff_ffff else { + valid = false + return false + } + field = _ORBWireField(number: UInt32(key >> 3), wire: UInt32(key & 7)) + if field.wire == 0 { + return readVarint(&field.integer) + } + let count: UInt64 + switch field.wire { + case 1: + count = 8 + case 5: + count = 4 + case 2: + var length: UInt64 = 0 + guard readVarint(&length) else { return false } + count = length + default: + valid = false + return false + } + guard count <= UInt64(bytes.count - offset) else { + valid = false + return false + } + let length = Int(count) + field.slice = bytes[offset..<(offset + length)] + offset += length + return true + } +} + +private func _orbReadFloats(_ field: _ORBWireField, _ append: (Float) -> Void) -> Bool { + guard field.wire == 2 || field.wire == 5, field.slice.count % 4 == 0 else { return false } + var index = field.slice.startIndex + while index < field.slice.endIndex { + let b0 = UInt32(field.slice[index]) + let b1 = UInt32(field.slice[index + 1]) << 8 + let b2 = UInt32(field.slice[index + 2]) << 16 + let b3 = UInt32(field.slice[index + 3]) << 24 + append(Float(bitPattern: b0 | b1 | b2 | b3)) + index += 4 + } + return true +} + +private func _orbReadDoubles(_ field: _ORBWireField, _ append: (Double) -> Void) -> Bool { + guard field.wire == 2 || field.wire == 1, field.slice.count % 8 == 0 else { return false } + var index = field.slice.startIndex + while index < field.slice.endIndex { + var bits: UInt64 = 0 + for shift in 0..<8 { + bits |= UInt64(field.slice[index + shift]) << (UInt64(shift) * 8) + } + append(Double(bitPattern: bits)) + index += 8 + } + return true +} + +private struct _ORBDecodedMetadata { + var kind: UInt32 = 0 + var affine: _ORBCGAffineTransform = .identity + var stroke = _ORBPathStrokeInfo(lineCap: 0, lineJoin: 0, dash: []) + var boolean: [UInt8] = [0, 0] + var clip = _ORBPathClipInfo(flags: 0, cap: 1, records: []) +} + +private func _orbDecodeClipKey(_ message: _ORBWireField, _ key: inout _ORBPathClipRecord) -> Bool { + guard message.wire == 2 else { return false } + var decoder = _ORBWireDecoder(Array(message.slice)) + var field = _ORBWireField() + while decoder.next(&field) { + switch field.number { + case 1: + guard _orbReadFloats(field, { key.x = $0 }) else { return false } + case 2: + guard _orbReadFloats(field, { key.y = $0 }) else { return false } + case 3: + guard _orbReadFloats(field, { key.z = $0 }) else { return false } + case 4, 5: + guard field.wire == 0 else { return false } + if field.integer != 0 { + key.type |= field.number == 4 ? 1 : 2 + } + default: + break + } + } + return decoder.valid +} + +private func _orbDecodeMetadata(_ message: _ORBWireField, _ metadata: inout _ORBDecodedMetadata) -> Bool { + guard message.wire == 2 else { return false } + var outer = _ORBWireDecoder(Array(message.slice)) + var variant = _ORBWireField() + while outer.next(&variant) { + if variant.number > 4 || metadata.kind != 0 { continue } + guard variant.wire == 2 else { return false } + metadata.kind = variant.number + var decoder = _ORBWireDecoder(Array(variant.slice)) + var field = _ORBWireField() + while decoder.next(&field) { + switch metadata.kind { + case 1: + switch field.number { + case 1: guard _orbReadFloats(field, { metadata.affine.a = _ORBCGFloat($0) }) else { return false } + case 2: guard _orbReadFloats(field, { metadata.affine.b = _ORBCGFloat($0) }) else { return false } + case 3: guard _orbReadFloats(field, { metadata.affine.c = _ORBCGFloat($0) }) else { return false } + case 4: guard _orbReadFloats(field, { metadata.affine.d = _ORBCGFloat($0) }) else { return false } + case 5: guard _orbReadFloats(field, { metadata.affine.tx = _ORBCGFloat($0) }) else { return false } + case 6: guard _orbReadFloats(field, { metadata.affine.ty = _ORBCGFloat($0) }) else { return false } + default: break + } + case 2: + if field.number <= 2 { + guard field.wire == 0 else { return false } + if field.number == 1 && field.integer <= 6 { metadata.stroke.lineCap = Int32(field.integer) } + if field.number == 2 && field.integer <= 2 { metadata.stroke.lineJoin = Int32(field.integer) } + } else if field.number == 3 { + guard _orbReadFloats(field, { metadata.stroke.dash.append(_ORBCGFloat($0)) }) else { return false } + } + case 3: + if field.number <= 2 { + guard field.wire == 0 else { return false } + if field.number == 1 && field.integer <= 6 { metadata.boolean[0] = UInt8(field.integer) } + if field.number == 2 { metadata.boolean[1] = field.integer != 0 ? 1 : 0 } + } + default: + if field.number == 5 { + var key = _ORBPathClipRecord(type: 0, x: 0, y: 0, z: 0) + guard _orbDecodeClipKey(field, &key) else { return false } + metadata.clip.records.append(key) + } else if field.number <= 6 { + guard field.wire == 0 else { return false } + if field.number == 1 { + if field.integer <= 6 { metadata.clip.cap = Int32(field.integer) } + } else if field.integer != 0 { + let flags: [Int32] = [0, 0, 4, 1, 2, 0, 8] + metadata.clip.flags |= flags[Int(field.number)] + } + } + } + } + guard decoder.valid else { return false } + } + return outer.valid +} + +private func _orbEncodeMetadata(_ element: UInt32, _ info: UnsafeRawPointer?) -> [UInt8] { + guard let info, element != 4, element != 16, element != 18, element != 22, element != 23 else { + return [] + } + var result = _ORBWireEncoder() + var value = _ORBWireEncoder() + switch element { + case 19: + let stroke = info.load(as: _ORBPathStrokePayload.self) + if stroke.lineCap == 0 && stroke.lineJoin == 0 && stroke.dashCount == 0 { return [] } + value.appendInteger(1, UInt64(bitPattern: Int64(stroke.lineCap))) + value.appendInteger(2, UInt64(bitPattern: Int64(stroke.lineJoin))) + if stroke.dashCount > 0, let dashPtr = stroke.dash { + var dash = _ORBWireEncoder() + for i in 0.. 0, let keys = clip.records { + for i in 0.. [UInt8] { + struct EncodingState { + var output = _ORBWireEncoder() + var elements: [UInt8] = [] + var floats = _ORBWireEncoder() + var doubles = _ORBWireEncoder() + } + var state = EncodingState() + _ = withUnsafeMutablePointer(to: &state) { statePtr in + apply(info: UnsafeMutableRawPointer(statePtr)) { info, element, points, userInfo in + guard element.rawValue >= 0 else { return false } + let state = info.assumingMemoryBound(to: EncodingState.self) + let type = UInt32(element.rawValue) + let metadata = _orbEncodeMetadata(type, userInfo) + var code = UInt8(type) + if !metadata.isEmpty { + code |= 0x80 + state.pointee.output.appendData(4, metadata) + } + let count = _orbArgumentCount(element) + for i in 0.. 0 else { + self = .null + return + } + depth -= 1 + } + } + guard depth == 0 else { + self = .null + return + } + + floatIndex = 0 + doubleIndex = 0 + metadataIndex = 0 + var records: [_ORBPathRecord] = [] + records.reserveCapacity(elements.count) + for code in elements { + let rawType = Int32(code & 0x3f) + guard let element = Element(rawValue: rawType) else { + self = .null + return + } + let count = _orbElementArgumentCounts[Int(rawType)] + let values: [_ORBCGFloat] + if (code & 0x40) != 0 { + values = Array(doubles[doubleIndex..<(doubleIndex + count)]) + doubleIndex += count + } else { + values = Array(floats[floatIndex..<(floatIndex + count)]) + floatIndex += count + } + var record = _ORBPathRecord(element: element, values: values) + if (code & 0x80) != 0 { + let meta = metadataList[metadataIndex] + metadataIndex += 1 + switch meta.kind { + case 1: + record.transform = meta.affine.isIdentity ? nil : meta.affine + case 2: + record.stroke = meta.stroke + case 3: + record.boolean = meta.boolean + case 4: + record.clipStroke = meta.clip + default: + break + } + } + records.append(record) + } + self = Self._fromRecords(records) + } +} +#endif diff --git a/Sources/OpenRenderBox/Path/ORBPathGeometry.swift b/Sources/OpenRenderBox/Path/ORBPathGeometry.swift index bb149dc..95cdc80 100644 --- a/Sources/OpenRenderBox/Path/ORBPathGeometry.swift +++ b/Sources/OpenRenderBox/Path/ORBPathGeometry.swift @@ -10,6 +10,11 @@ func _orbRectValues(_ rect: CGRect) -> [CGFloat] { [rect.origin.x, rect.origin.y, rect.size.width, rect.size.height] } +func _orbHypot(_ x: Double, _ y: Double) -> Double { hypot(x, y) } +func _orbAtan2(_ y: Double, _ x: Double) -> Double { atan2(y, x) } +func _orbCos(_ x: Double) -> Double { cos(x) } +func _orbSin(_ x: Double) -> Double { sin(x) } + func _orbRect(_ values: [CGFloat]) -> CGRect { CGRect(x: values[0], y: values[1], width: values[2], height: values[3]) } diff --git a/Sources/OpenRenderBoxShims/ORBShims.swift b/Sources/OpenRenderBoxShims/ORBShims.swift index a9c9dfb..4417671 100644 --- a/Sources/OpenRenderBoxShims/ORBShims.swift +++ b/Sources/OpenRenderBoxShims/ORBShims.swift @@ -74,7 +74,7 @@ public typealias ORBSymbolStyle = RBSymbolStyle public let renderBoxVendor = RenderBoxVendor.rb #else -@_exported import OpenRenderBox +@_exported public import OpenRenderBox public let renderBoxVendor = RenderBoxVendor.orb #endif diff --git a/Tests/OpenRenderBoxTests/Path/PortableCFDataTestSupport.swift b/Tests/OpenRenderBoxTests/Path/PortableCFDataTestSupport.swift new file mode 100644 index 0000000..844552a --- /dev/null +++ b/Tests/OpenRenderBoxTests/Path/PortableCFDataTestSupport.swift @@ -0,0 +1,27 @@ +// +// PortableCFDataTestSupport.swift +// OpenRenderBoxTests + +#if !OPENRENDERBOX_CF_CGTYPES +import CoreFoundation + +func makeTestCFData(_ bytes: [UInt8]) -> CFData { + bytes.withUnsafeBufferPointer { buffer in + CFDataCreate(nil, buffer.baseAddress, buffer.count)! + } +} + +func testCFDataBytes(_ data: CFData) -> [UInt8] { + let length = CFDataGetLength(data) + guard length > 0 else { + return [] + } + if let ptr = CFDataGetBytePtr(data) { + return Array(UnsafeBufferPointer(start: ptr, count: length)) + } + return [UInt8](unsafeUninitializedCapacity: length) { buffer, initializedCount in + CFDataGetBytes(data, CFRange(location: 0, length: length), buffer.baseAddress) + initializedCount = length + } +} +#endif diff --git a/Tests/OpenRenderBoxTests/Path/PortablePathTests.swift b/Tests/OpenRenderBoxTests/Path/PortablePathTests.swift index 9339939..aa17b15 100644 --- a/Tests/OpenRenderBoxTests/Path/PortablePathTests.swift +++ b/Tests/OpenRenderBoxTests/Path/PortablePathTests.swift @@ -248,5 +248,224 @@ struct PortablePathTests { defer { nested.release() } #expect(nested.boundingRect == CGRect(x: 1, y: 2, width: 10, height: 20)) } + + @Test + func applyCGPathElementsTransformsAndStopsOnCancellation() { + let cgPath = CGMutablePath() + cgPath.move(to: CGPoint(x: 1, y: 2)) + cgPath.addQuadCurve(to: CGPoint(x: 7, y: 8), control: CGPoint(x: 5, y: 6)) + cgPath.addCurve(to: CGPoint(x: 13, y: 14), control1: CGPoint(x: 9, y: 10), control2: CGPoint(x: 11, y: 12)) + cgPath.closeSubpath() + let path = ORBPath(cgPath: cgPath) + defer { path.release() } + + var transform = CGAffineTransform(a: 2, b: 0, c: 0, d: 3, tx: 10, ty: 20) + var recorded: [(Int32, [CGFloat])] = [] + let completed = withUnsafeMutablePointer(to: &recorded) { recordedPtr in + path.applyCGPathElements(transform: &transform, info: recordedPtr) { info, elementPtr in + let element = elementPtr.pointee + let count: Int + switch element.type { + case .moveToPoint, .addLineToPoint: count = 1 + case .addQuadCurveToPoint: count = 2 + case .addCurveToPoint: count = 3 + case .closeSubpath: count = 0 + @unknown default: count = 0 + } + let scalars = (0.. ORBPath { + let source = ORBPath(rect: rect, transform: nil) + defer { source.release() } + return dash.withUnsafeBufferPointer { + source.stroked(lineWidth: width, lineCap: cap, lineJoin: 1, miterLimit: 10, dashPhase: 0, dash: $0.baseAddress, dashCount: $0.count) + } + } + let lhs = makeStroke(rect: CGRect(x: 1, y: 2, width: 10, height: 20), width: 1, cap: 0, dash: [2, 4]) + let rhs = makeStroke(rect: CGRect(x: 3, y: 4, width: 30, height: 40), width: 3, cap: 2, dash: [3, 5, 7]) + #expect(lhs.canInterpolate(to: rhs)) + let mixedStroke = lhs.interpolated(to: rhs, fraction: 0.25) + lhs.release() + rhs.release() + struct StrokeResult { var width: CGFloat = 0; var cap: Int32 = -1; var dash: [CGFloat] = []; var child = ORBPath.empty } + var result = StrokeResult() + let strokeRecognized = withUnsafeMutablePointer(to: &result) { resultPtr in + mixedStroke.applyShape(allowLine: true, info: resultPtr) { info, type, shape in + if type == .stroked { + let stroke = shape.pointee.stroked + let out = info.assumingMemoryBound(to: StrokeResult.self) + out.pointee.width = stroke.style.lineWidth + out.pointee.cap = stroke.style.lineCap + out.pointee.dash = Array(UnsafeBufferPointer(start: stroke.style.dash, count: Int(stroke.style.dashCount))) + out.pointee.child = stroke.path.retain() + } + } + } + #expect(strokeRecognized) + mixedStroke.release() + defer { result.child.release() } + #expect(result.width == 1.5) + #expect(result.cap == 2) + #expect(result.dash == [3, 5, 7]) + #expect(result.child.boundingRect == CGRect(x: 1.5, y: 2.5, width: 15, height: 25)) + + var t1 = CGAffineTransform(rotationAngle: 0).translatedBy(x: 0, y: 10) + var t2 = CGAffineTransform(rotationAngle: .pi / 2).translatedBy(x: 20, y: 30) + let r1 = ORBPath(rect: CGRect(x: 0, y: 0, width: 10, height: 20), transform: &t1) + let r2 = ORBPath(rect: CGRect(x: 0, y: 0, width: 10, height: 20), transform: &t2) + defer { + r1.release() + r2.release() + } + let mid = r1.interpolated(to: r2, fraction: 0.5) + defer { mid.release() } + #expect(!mid.isNull) + var capturedTransform = CGAffineTransform.identity + let rectRecognized = withUnsafeMutablePointer(to: &capturedTransform) { ptr in + mid.applyShape(allowLine: true, info: ptr) { info, type, shape in + if type == .rect { + info.assumingMemoryBound(to: CGAffineTransform.self).pointee = shape.pointee.rect.transform + } + } + } + #expect(rectRecognized) + let invSqrt2 = CGFloat(0.5).squareRoot() + #expect(abs(capturedTransform.a - invSqrt2) < 1e-10) + #expect(abs(capturedTransform.b - invSqrt2) < 1e-10) + #expect(abs(capturedTransform.c - (-invSqrt2)) < 1e-10) + #expect(abs(capturedTransform.d - invSqrt2) < 1e-10) + + let trimmedRect = r1.trimmed(from: 0, to: 0.5) + let rounded = ORBPath(roundedRect: CGRect(x: 0, y: 0, width: 10, height: 20), cornerWidth: 4, cornerHeight: 4, style: .circular, transform: nil) + let trimmedRounded = rounded.trimmed(from: 0, to: 0.5) + rounded.release() + defer { + trimmedRect.release() + trimmedRounded.release() + } + #expect(!trimmedRect.canInterpolate(to: trimmedRounded)) + } + + @Test + func serializedDataWireFormatAndInvalidInputs() throws { + let path = ORBPath(rect: CGRect(x: 1, y: 2, width: 10, height: 20), transform: nil) + defer { path.release() } + let data = try #require(path.data) + #expect(testCFDataBytes(data) == [0x1a, 1, 5, 0x12, 0x10, 0, 0, 0x80, 0x3f, 0, 0, 0, 0x40, 0, 0, 0x20, 0x41, 0, 0, 0xa0, 0x41]) + let decoded = ORBPath(data: data) + defer { decoded.release() } + #expect(decoded.isEqual(to: path)) + + let emptyData = try #require(ORBPath.empty.data) + #expect(testCFDataBytes(emptyData).isEmpty) + let decodedEmpty = ORBPath(data: emptyData) + defer { decodedEmpty.release() } + #expect(decodedEmpty.isEmpty) + #expect(!decodedEmpty.isNull) + + let nilPath = ORBPath(data: nil) + defer { nilPath.release() } + #expect(nilPath.isEmpty) + #expect(nilPath.isNull) + + for (bytes, expectedNull) in [ + ([UInt8](), false), + ([0x80], false), + ([0x0f], false), + ([0x1a, 1, 0], true), + ([0x1a, 1, 0x10], true), + ([0x1a, 1, 0x91], true), + ] { + let candidate = ORBPath(data: makeTestCFData(bytes)) + defer { candidate.release() } + #expect(candidate.isEmpty) + #expect(candidate.isNull == expectedNull) + } + } } #endif From 81164672439c6c2acac3b1ae47685f1ec19d165e Mon Sep 17 00:00:00 2001 From: Kyle Date: Sat, 21 Nov 2026 23:44:04 +0800 Subject: [PATCH 5/5] chore: update dependencies --- Package.resolved | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Package.resolved b/Package.resolved index 9d71347..9e6bfad 100644 --- a/Package.resolved +++ b/Package.resolved @@ -7,7 +7,7 @@ "location" : "https://github.com/OpenSwiftUIProject/DarwinPrivateFrameworks.git", "state" : { "branch" : "main", - "revision" : "511cc728141f57dc325753f23898568ccd49c339" + "revision" : "600fcdfb9462e985d5fef429daf236e2de3104db" } }, { @@ -16,7 +16,7 @@ "location" : "https://github.com/OpenSwiftUIProject/OpenCoreGraphics", "state" : { "branch" : "main", - "revision" : "de4866d03ab727b5204633a2c29cb1412dd90ee6" + "revision" : "9f247e283862ce3e2008d0156702643e72693adb" } }, {