From 7b886e53fa16d1fed13574d1bc230c4239b1a348 Mon Sep 17 00:00:00 2001 From: Kyle Date: Sat, 7 Nov 2026 19:46:41 +0800 Subject: [PATCH 01/22] feat(shape): implement built-in inset paths --- .../Shape/InsettableShape.swift | 33 ++++++++++++++----- 1 file changed, 25 insertions(+), 8 deletions(-) diff --git a/Sources/OpenSwiftUICore/Shape/InsettableShape.swift b/Sources/OpenSwiftUICore/Shape/InsettableShape.swift index 204cdd943..55488c521 100644 --- a/Sources/OpenSwiftUICore/Shape/InsettableShape.swift +++ b/Sources/OpenSwiftUICore/Shape/InsettableShape.swift @@ -2,8 +2,8 @@ // InsettableShape.swift // OpenSwiftUICore // -// Audited for 6.0.87 -// Status: WIP +// Audited for 6.5.4 +// Status: Complete public import Foundation @@ -93,7 +93,7 @@ extension Rectangle: InsettableShape { @usableFromInline nonisolated func path(in rect: CGRect) -> Path { - Path(rect.insetBy(dx: amount, dy: amount)) + Rectangle().path(in: rect.insetBy(dx: amount, dy: amount)) } @usableFromInline @@ -140,7 +140,13 @@ extension RoundedRectangle: InsettableShape { @usableFromInline nonisolated func path(in rect: CGRect) -> Path { - _openSwiftUIUnimplementedFailure() + RoundedRectangle( + cornerSize: CGSize( + width: max(base.cornerSize.width - amount, 0), + height: max(base.cornerSize.height - amount, 0) + ), + style: base.style + ).path(in: rect.insetBy(dx: amount, dy: amount)) } @usableFromInline @@ -187,7 +193,15 @@ extension UnevenRoundedRectangle: InsettableShape { @usableFromInline nonisolated func path(in rect: CGRect) -> Path { - _openSwiftUIUnimplementedFailure() + UnevenRoundedRectangle( + cornerRadii: RectangleCornerRadii( + topLeft: max(base.cornerRadii.topLeft - amount, 0), + topRight: max(base.cornerRadii.topRight - amount, 0), + bottomRight: max(base.cornerRadii.bottomRight - amount, 0), + bottomLeft: max(base.cornerRadii.bottomLeft - amount, 0) + ), + style: base.style + ).path(in: rect.insetBy(dx: amount, dy: amount)) } @usableFromInline @@ -226,7 +240,10 @@ extension Capsule: InsettableShape { @usableFromInline nonisolated func path(in rect: CGRect) -> Path { - _openSwiftUIUnimplementedFailure() + let (amount, style) = isLinkedOnOrAfter(.v5) + ? Self._extractInset(amount) + : (amount, RoundedCornerStyle.circular) + return Capsule(style: style).path(in: rect.insetBy(dx: amount, dy: amount)) } @usableFromInline @@ -285,7 +302,7 @@ extension Ellipse: InsettableShape { @usableFromInline nonisolated func path(in rect: CGRect) -> Path { - _openSwiftUIUnimplementedFailure() + Ellipse().path(in: rect.insetBy(dx: amount, dy: amount)) } @usableFromInline @@ -329,7 +346,7 @@ extension Circle: InsettableShape { @usableFromInline nonisolated func path(in rect: CGRect) -> Path { - _openSwiftUIUnimplementedFailure() + Circle().path(in: rect.insetBy(dx: amount, dy: amount)) } @usableFromInline From b6bd8607a5111e456f0925374b3a881cb4ae5d36 Mon Sep 17 00:00:00 2001 From: Kyle Date: Sat, 7 Nov 2026 20:00:13 +0800 Subject: [PATCH 02/22] fix(path): align portable PathData storage --- Sources/OpenSwiftUICore/Shape/PathData.swift | 31 +++----------------- 1 file changed, 4 insertions(+), 27 deletions(-) diff --git a/Sources/OpenSwiftUICore/Shape/PathData.swift b/Sources/OpenSwiftUICore/Shape/PathData.swift index 69d0de6aa..707eae035 100644 --- a/Sources/OpenSwiftUICore/Shape/PathData.swift +++ b/Sources/OpenSwiftUICore/Shape/PathData.swift @@ -20,36 +20,13 @@ package import OpenRenderBoxShims /// uint8_t buffer[0x60]; // 96 bytes /// } PathData; package struct PathData { - // 96 bytes of raw storage (0x60) + // Pointer alignment is required by both the union fields and RenderBox Storage. package typealias Buffer = ( - UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, - UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, - UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, - UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, - UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, - UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, - UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, - UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, - UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, - UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, - UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, - UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8 + UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, + UInt64, UInt64, UInt64, UInt64, UInt64, UInt64 ) - private var storage: Buffer = ( - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, - ) + private var storage: Buffer = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) package init() {} From 8b23a4052a5b88a11e29e5bcc7c8a5913eaff0b1 Mon Sep 17 00:00:00 2001 From: Kyle Date: Sun, 8 Nov 2026 11:52:12 +0800 Subject: [PATCH 03/22] build: preserve Swift symbols in XCFrameworks --- Scripts/build_xcframework.sh | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Scripts/build_xcframework.sh b/Scripts/build_xcframework.sh index 6a997609d..b620ff1f3 100755 --- a/Scripts/build_xcframework.sh +++ b/Scripts/build_xcframework.sh @@ -489,6 +489,8 @@ prebuild_compute_framework() { SKIP_INSTALL=NO BUILD_LIBRARY_FOR_DISTRIBUTION=YES SWIFT_EMIT_MODULE_INTERFACE=YES + # Keep Swift names for binary inspection; otherwise Xcode adds strip -T. + STRIP_SWIFT_SYMBOLS=NO ENABLE_USER_SCRIPT_SANDBOXING=NO ) @@ -540,6 +542,8 @@ build_framework() { SKIP_INSTALL=NO BUILD_LIBRARY_FOR_DISTRIBUTION=YES SWIFT_EMIT_MODULE_INTERFACE=YES + # Keep Swift names for binary inspection; otherwise Xcode adds strip -T. + STRIP_SWIFT_SYMBOLS=NO "SWIFT_ACTIVE_COMPILATION_CONDITIONS=\$(inherited) OPENSWIFTUI_XCFRAMEWORK_BUILD" "GCC_PREPROCESSOR_DEFINITIONS=\$(inherited) OPENSWIFTUI_XCFRAMEWORK_BUILD=1" ENABLE_USER_SCRIPT_SANDBOXING=NO From e883ed0ff978a8e8e01d3b97c88c7c75832ca157 Mon Sep 17 00:00:00 2001 From: Kyle Date: Sun, 8 Nov 2026 12:30:46 +0800 Subject: [PATCH 04/22] build: preserve Swift symbols only for local slices --- Scripts/build_xcframework.sh | 12 ++++++++---- Scripts/build_xcframework_slice.sh | 4 +++- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/Scripts/build_xcframework.sh b/Scripts/build_xcframework.sh index b620ff1f3..3a9622afe 100755 --- a/Scripts/build_xcframework.sh +++ b/Scripts/build_xcframework.sh @@ -26,6 +26,7 @@ XCODEWORKSPACE="$PROJECT_ROOT/Workspace.xcworkspace" # If --archs is omitted for an SDK, all default architectures are built. SDKS=() SDK_ARCHS=() +SWIFT_SYMBOL_SETTINGS=() DEBUG_MODE=false RUN_TUIST_INSTALL=true CLEAN_DERIVED_DATA=true @@ -53,6 +54,7 @@ Options: --compute Build OpenAttributeGraphShims with the Compute source backend. --skip-tuist-install Skip tuist install. --keep-derived-data Reuse DerivedData from a previous build. + --keep-swift-symbols Keep Swift symbol names for local binary inspection. --framework Build one framework. May be passed multiple times. --help Show this help. @@ -102,6 +104,10 @@ while [[ $# -gt 0 ]]; do CLEAN_DERIVED_DATA=false shift ;; + --keep-swift-symbols) + SWIFT_SYMBOL_SETTINGS=(STRIP_SWIFT_SYMBOLS=NO) + shift + ;; --framework) EXPLICIT_FRAMEWORK_NAMES=true FRAMEWORK_NAMES+=("$2") @@ -489,8 +495,7 @@ prebuild_compute_framework() { SKIP_INSTALL=NO BUILD_LIBRARY_FOR_DISTRIBUTION=YES SWIFT_EMIT_MODULE_INTERFACE=YES - # Keep Swift names for binary inspection; otherwise Xcode adds strip -T. - STRIP_SWIFT_SYMBOLS=NO + "${SWIFT_SYMBOL_SETTINGS[@]}" ENABLE_USER_SCRIPT_SANDBOXING=NO ) @@ -542,8 +547,7 @@ build_framework() { SKIP_INSTALL=NO BUILD_LIBRARY_FOR_DISTRIBUTION=YES SWIFT_EMIT_MODULE_INTERFACE=YES - # Keep Swift names for binary inspection; otherwise Xcode adds strip -T. - STRIP_SWIFT_SYMBOLS=NO + "${SWIFT_SYMBOL_SETTINGS[@]}" "SWIFT_ACTIVE_COMPILATION_CONDITIONS=\$(inherited) OPENSWIFTUI_XCFRAMEWORK_BUILD" "GCC_PREPROCESSOR_DEFINITIONS=\$(inherited) OPENSWIFTUI_XCFRAMEWORK_BUILD=1" ENABLE_USER_SCRIPT_SANDBOXING=NO diff --git a/Scripts/build_xcframework_slice.sh b/Scripts/build_xcframework_slice.sh index 728188280..4fc7c4048 100755 --- a/Scripts/build_xcframework_slice.sh +++ b/Scripts/build_xcframework_slice.sh @@ -24,7 +24,7 @@ print_usage() { Usage: Scripts/build_xcframework_slice.sh [options] [osuicore|osui ...] Build a single-architecture Release XCFramework for local binary comparison. -The default target is OpenSwiftUICore. +Keep Swift symbol names for inspection. The default target is OpenSwiftUICore. Typical timing on a recent Apple Silicon Mac (rough planning estimates): OpenSwiftUICore clean ~3-8 min; warm no-change ~10-60 sec @@ -93,6 +93,8 @@ build_args=( --compute --sdk iphonesimulator --archs arm64 + # Disable strip -T for local inspection; distribution builds use the default. + --keep-swift-symbols ) if [ "$KEEP_DERIVED_DATA" = true ]; then From 6b3cca186d1c1d08ed0d89955c97ae9a2660f9d2 Mon Sep 17 00:00:00 2001 From: Kyle Date: Sun, 8 Nov 2026 15:49:47 +0800 Subject: [PATCH 05/22] fix(path): mark PathData.cgPath as nullable --- Sources/OpenSwiftUICore/Shape/PathData.swift | 12 ++++++------ Sources/OpenSwiftUI_SPI/Util/PathData.h | 2 +- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/Sources/OpenSwiftUICore/Shape/PathData.swift b/Sources/OpenSwiftUICore/Shape/PathData.swift index 707eae035..73a81418f 100644 --- a/Sources/OpenSwiftUICore/Shape/PathData.swift +++ b/Sources/OpenSwiftUICore/Shape/PathData.swift @@ -15,9 +15,9 @@ package import OpenRenderBoxShims /// C definition: /// /// typedef union PathData { -/// CGPathRef cgPath; // 8 bytes (pointer) -/// ORBPath rbPath; // 16 bytes (2 pointers) -/// uint8_t buffer[0x60]; // 96 bytes +/// CGPathRef _Nullable cgPath; // 8 bytes (pointer) +/// ORBPath rbPath; // 16 bytes (2 pointers) +/// uint8_t buffer[0x60]; // 96 bytes /// } PathData; package struct PathData { // Pointer alignment is required by both the union fields and RenderBox Storage. @@ -36,15 +36,15 @@ package struct PathData { self.cgPath = cgPath } - package var cgPath: Unmanaged { + package var cgPath: Unmanaged? { get { withUnsafeBytes(of: storage) { buffer in - buffer.load(as: Unmanaged.self) + buffer.load(as: Unmanaged?.self) } } set { withUnsafeMutableBytes(of: &storage) { buffer in - buffer.storeBytes(of: newValue, as: Unmanaged.self) + buffer.storeBytes(of: newValue, as: Unmanaged?.self) } } } diff --git a/Sources/OpenSwiftUI_SPI/Util/PathData.h b/Sources/OpenSwiftUI_SPI/Util/PathData.h index eb088a6f2..127e5b48b 100644 --- a/Sources/OpenSwiftUI_SPI/Util/PathData.h +++ b/Sources/OpenSwiftUI_SPI/Util/PathData.h @@ -21,7 +21,7 @@ OPENSWIFTUI_IMPLICIT_BRIDGING_ENABLED typedef union PathData { #if OPENSWIFTUI_TARGET_OS_DARWIN - CGPathRef cgPath; + CGPathRef _Nullable cgPath; #endif ORBPath rbPath; uint8_t buffer[0x60]; From 7abe75acd565aa95e4901711656cd08dcdd3573e Mon Sep 17 00:00:00 2001 From: Kyle Date: Tue, 17 Nov 2026 01:21:49 +0800 Subject: [PATCH 06/22] fix(spi): refine CGPath string and rounded rect helpers --- .../Overlay/CoreGraphics/CGPath+OpenSwiftUI.h | 31 +- .../Overlay/CoreGraphics/CGPath+OpenSwiftUI.m | 375 +++++++++--------- .../CGPath+OpenSwiftUITests.swift | 61 +-- 3 files changed, 234 insertions(+), 233 deletions(-) diff --git a/Sources/OpenSwiftUI_SPI/Overlay/CoreGraphics/CGPath+OpenSwiftUI.h b/Sources/OpenSwiftUI_SPI/Overlay/CoreGraphics/CGPath+OpenSwiftUI.h index f3c2e9e59..b5dc21c9b 100644 --- a/Sources/OpenSwiftUI_SPI/Overlay/CoreGraphics/CGPath+OpenSwiftUI.h +++ b/Sources/OpenSwiftUI_SPI/Overlay/CoreGraphics/CGPath+OpenSwiftUI.h @@ -1,6 +1,9 @@ // // CGPath+OpenSwiftUI.h // OpenSwiftUI_SPI +// +// Audited for 6.5.4 +// Status: Complete #ifndef CGPath_OpenSwiftUI_h #define CGPath_OpenSwiftUI_h @@ -9,18 +12,11 @@ #if OPENSWIFTUI_TARGET_OS_DARWIN -#include +#include #include OPENSWIFTUI_ASSUME_NONNULL_BEGIN - -/// Defines the shape of a rounded rectangle's corners. -typedef OPENSWIFTUI_ENUM(uint8_t, PathRoundedCornerStyle) { - /// Quarter-circle rounded rect corners. - PathRoundedCornerStyleCircular = 0, - /// Continuous curvature rounded rect corners. - PathRoundedCornerStyleContinuous = 1, -}; +OPENSWIFTUI_IMPLICIT_BRIDGING_ENABLED /// Parses a path string and appends the path elements to a mutable path. /// @@ -44,8 +40,8 @@ typedef OPENSWIFTUI_ENUM(uint8_t, PathRoundedCornerStyle) { /// - Parameters: /// - path: The mutable path to append elements to. /// - utf8CString: The path string to parse. -/// - Returns: `YES` if parsing succeeded, `NO` if the string is malformed. -BOOL _CGPathParseString(CGMutablePathRef path, const char *utf8CString); +/// - Returns: `true` if parsing succeeded, `false` if the string is malformed. +bool _CGPathParseString(CGMutablePathRef path, const char *utf8CString); /// Creates a string description of a path with optional coordinate rounding. /// @@ -54,8 +50,8 @@ BOOL _CGPathParseString(CGMutablePathRef path, const char *utf8CString); /// - step: The rounding step for coordinates. When non-zero, coordinates /// are rounded to the nearest multiple of this value. Pass 0 for no rounding. /// - Returns: A string representation of the path using SVG-like commands -/// (m for move, l for line, h for close). -NSString * _CGPathCopyDescription(CGPathRef path, CGFloat step); +/// (m for move, l for line, q for quad curve, c for cubic curve, h for close). +CFStringRef _CGPathCopyDescription(CGPathRef path, CGFloat step) OPENSWIFTUI_RETURNS_RETAINED; /// Creates a rounded rectangle path with the specified corner radii. /// @@ -67,14 +63,13 @@ NSString * _CGPathCopyDescription(CGPathRef path, CGFloat step); /// - rect: The rectangle to create the path from. /// - cornerWidth: The horizontal radius of the rounded corners. /// - cornerHeight: The vertical radius of the rounded corners. -/// - style: The corner style to use. ``CGPathRoundedCornerStyleCircular`` -/// uses quarter-circle corners. ``CGPathRoundedCornerStyleContinuous`` -/// uses continuous curvature corners. +/// - continuous: Whether to use continuous curvature corners (`true`) or +/// quarter-circle corners (`false`). /// - Returns: A new path representing the rounded rectangle. Returns a plain /// rectangle path if either corner dimension is 0 or if the rect is empty. -OPENSWIFTUI_RETURNS_RETAINED -CGPathRef _CGPathCreateRoundedRect(CGRect rect, CGFloat cornerWidth, CGFloat cornerHeight, PathRoundedCornerStyle style); +CGPathRef _CGPathCreateRoundedRect(CGRect rect, CGFloat cornerWidth, CGFloat cornerHeight, bool continuous) OPENSWIFTUI_RETURNS_RETAINED; +OPENSWIFTUI_IMPLICIT_BRIDGING_DISABLED OPENSWIFTUI_ASSUME_NONNULL_END #endif diff --git a/Sources/OpenSwiftUI_SPI/Overlay/CoreGraphics/CGPath+OpenSwiftUI.m b/Sources/OpenSwiftUI_SPI/Overlay/CoreGraphics/CGPath+OpenSwiftUI.m index 9605461bb..b2267dce4 100644 --- a/Sources/OpenSwiftUI_SPI/Overlay/CoreGraphics/CGPath+OpenSwiftUI.m +++ b/Sources/OpenSwiftUI_SPI/Overlay/CoreGraphics/CGPath+OpenSwiftUI.m @@ -1,144 +1,173 @@ // // CGPath+OpenSwiftUI.m // OpenSwiftUI_SPI +// +// Audited for 6.5.4 +// Status: Complete #import "CGPath+OpenSwiftUI.h" #if OPENSWIFTUI_TARGET_OS_DARWIN -#import -#import -#import - #include +#include +#include +#include +#include -BOOL _CGPathParseString(CGMutablePathRef path, const char *utf8CString) { +bool _CGPathParseString(CGMutablePathRef path, const char *utf8CString) { double numbers[6]; int numCount = 0; CGFloat currentX = 0.0, currentY = 0.0; CGFloat lastControlX = 0.0, lastControlY = 0.0; - const char *ptr = utf8CString; - do { - while (*ptr <= 0x1f) { - switch (*ptr) { - case 0: return true; - case 9: case 10: case 12: case 13: ptr++; break; - default: return false; - } - } - unsigned char c = (unsigned char)*ptr; - BOOL isNumberStart = NO; - switch (c) { - case ' ': break; - case '+': case '-': case '.': case '0' ... '9': - case 'E': case 'P': case 'X': case 'e': case 'p': case 'x': - isNumberStart = YES; - break; - case 'I': - if (ptr[1] == 'n' && ptr[2] == 'f') { isNumberStart = YES; } - break; - case 'm': - if (numCount != 2) return NO; - CGPathMoveToPoint(path, NULL, - numbers[0], numbers[1]); - currentX = lastControlX = numbers[0]; - currentY = lastControlY = numbers[1]; - numCount = 0; - break; - case 'l': - if (numCount != 2) return NO; - CGPathAddLineToPoint(path, NULL, - numbers[0], numbers[1]); - currentX = lastControlX = numbers[0]; - currentY = lastControlY = numbers[1]; - numCount = 0; - break; - case 'c': - if (numCount != 6) return NO; - CGPathAddCurveToPoint(path, NULL, - numbers[0], numbers[1], - numbers[2], numbers[3], - numbers[4], numbers[5]); - lastControlX = numbers[2]; - lastControlY = numbers[3]; - currentX = numbers[4]; - currentY = numbers[5]; - numCount = 0; - break; - case 'q': - if (numCount != 4) return NO; - CGPathAddQuadCurveToPoint(path, NULL, - numbers[0], numbers[1], - numbers[2], numbers[3]); - lastControlX = numbers[0]; - lastControlY = numbers[1]; - currentX = numbers[2]; - currentY = numbers[3]; - numCount = 0; - break; - case 't': - if (numCount != 2) return NO; - CGFloat reflectedX = currentX * 2.0 - lastControlX; - CGFloat reflectedY = currentY * 2.0 - lastControlY; - CGPathAddQuadCurveToPoint(path, NULL, - reflectedX, reflectedY, - numbers[0], numbers[1]); - lastControlX = reflectedX; - lastControlY = reflectedY; - currentX = numbers[0]; - currentY = numbers[1]; - numCount = 0; - break; - case 'v': - if (numCount != 4) return NO; - CGPathAddCurveToPoint(path, NULL, - currentX, currentY, - numbers[0], numbers[1], - numbers[2], numbers[3]); - lastControlX = numbers[0]; - lastControlY = numbers[1]; - currentX = numbers[2]; - currentY = numbers[3]; - numCount = 0; - break; - case 'y': - if (numCount != 4) return NO; - CGPathAddCurveToPoint(path, NULL, - numbers[0], numbers[1], - numbers[2], numbers[3], - numbers[2], numbers[3]); - lastControlX = numbers[2]; - lastControlY = numbers[3]; - numCount = 0; - break; - case 'h': - if (numCount != 0) return NO; - CGPathCloseSubpath(path); - lastControlX = 0.0; - lastControlY = 0.0; - numCount = 0; - break; - case 'r': - if (ptr[1] != 'e') return NO; - if (numCount != 4) return NO; - CGPathAddRect(path, NULL, - CGRectMake(numbers[0], numbers[1], - numbers[2], numbers[3])); - ptr++; - numCount = 0; + while (1) { + unsigned char c; + while ((c = (unsigned char)*utf8CString) <= 0x1f) { + switch (c) { + case 0: + return true; + case 9: + case 10: + case 12: + case 13: + utf8CString++; break; default: return false; + } + } + bool isNumberStart = false; + switch (c) { + case ' ': + break; + case '+': + case '-': + case '.': + case '0' ... '9': + case 'E': + case 'P': + case 'X': + case 'e': + case 'p': + case 'x': + isNumberStart = true; + break; + case 'I': + if (utf8CString[1] == 'n' && utf8CString[2] == 'f') { + isNumberStart = true; + } + break; + case 'm': + if (numCount != 2) return false; + CGPathMoveToPoint(path, NULL, numbers[0], numbers[1]); + currentX = lastControlX = numbers[0]; + currentY = lastControlY = numbers[1]; + numCount = 0; + break; + case 'l': + if (numCount != 2) return false; + CGPathAddLineToPoint(path, NULL, numbers[0], numbers[1]); + currentX = lastControlX = numbers[0]; + currentY = lastControlY = numbers[1]; + numCount = 0; + break; + case 'c': + if (numCount != 6) return false; + CGPathAddCurveToPoint( + path, NULL, + numbers[0], numbers[1], + numbers[2], numbers[3], + numbers[4], numbers[5] + ); + lastControlX = numbers[2]; + lastControlY = numbers[3]; + currentX = numbers[4]; + currentY = numbers[5]; + numCount = 0; + break; + case 'q': + if (numCount != 4) return false; + CGPathAddQuadCurveToPoint( + path, NULL, + numbers[0], numbers[1], + numbers[2], numbers[3] + ); + lastControlX = numbers[0]; + lastControlY = numbers[1]; + currentX = numbers[2]; + currentY = numbers[3]; + numCount = 0; + break; + case 't': { + if (numCount != 2) return false; + CGFloat reflectedX = currentX * 2.0 - lastControlX; + CGFloat reflectedY = currentY * 2.0 - lastControlY; + CGPathAddQuadCurveToPoint( + path, NULL, + reflectedX, reflectedY, + numbers[0], numbers[1] + ); + lastControlX = reflectedX; + lastControlY = reflectedY; + currentX = numbers[0]; + currentY = numbers[1]; + numCount = 0; + break; + } + case 'v': + if (numCount != 4) return false; + CGPathAddCurveToPoint( + path, NULL, + currentX, currentY, + numbers[0], numbers[1], + numbers[2], numbers[3] + ); + lastControlX = numbers[0]; + lastControlY = numbers[1]; + currentX = numbers[2]; + currentY = numbers[3]; + numCount = 0; + break; + case 'y': + if (numCount != 4) return false; + CGPathAddCurveToPoint( + path, NULL, + numbers[0], numbers[1], + numbers[2], numbers[3], + numbers[2], numbers[3] + ); + currentX = numbers[2]; + currentY = numbers[3]; + numCount = 0; + break; + case 'h': + if (numCount != 0) return false; + CGPathCloseSubpath(path); + currentX = 0.0; + currentY = 0.0; + break; + case 'r': + if (utf8CString[1] != 'e') return false; + if (numCount != 4) return false; + CGPathAddRect( + path, NULL, + CGRectMake(numbers[0], numbers[1], numbers[2], numbers[3]) + ); + currentX = numbers[2]; + currentY = numbers[3]; + utf8CString++; + numCount = 0; + break; + default: + return false; } if (isNumberStart) { if (numCount == 6) return false; - char *endPtr; - numbers[numCount++] = strtod_l(ptr, &endPtr, NULL); - ptr = endPtr; + numbers[numCount++] = strtod_l(utf8CString, (char **)&utf8CString, NULL); } else { - ptr++; + utf8CString++; } - } while (1); + } } typedef struct PathInfo { @@ -147,111 +176,87 @@ BOOL _CGPathParseString(CGMutablePathRef path, const char *utf8CString) { CGFloat inverseStep; } PathInfo; -#define APPEND_COORD(coord) do { \ - CGFloat value = (coord); \ - if (path_info->step != 0.0) { \ - value = path_info->step * round(value * path_info->inverseStep); \ - } \ - char buffer[64]; \ - snprintf_l(buffer, 64, NULL, "%g ", value); \ - CFStringAppendCString(path_info->description, buffer, kCFStringEncodingUTF8); \ -} while (0) - -#define APPEND_POINTS(count) do { \ - for (int i = 0; i < (count); i++) { \ - APPEND_COORD(element->points[i].x); \ - APPEND_COORD(element->points[i].y); \ - } \ -} while (0) - -void copy_path_iter(void * __nullable info, const CGPathElement * element) { +static void copy_path_iter(void * _Nullable info, const CGPathElement *element) { PathInfo *path_info = (PathInfo *)info; - if (path_info->description != NULL) { + if (CFStringGetLength(path_info->description) != 0) { CFStringAppend(path_info->description, CFSTR(" ")); } UniChar ch; + int count; switch (element->type) { - case kCGPathElementMoveToPoint: - APPEND_POINTS(1); - ch = 'm'; - break; - case kCGPathElementAddLineToPoint: - APPEND_POINTS(1); - ch = 'l'; - break; - case kCGPathElementAddQuadCurveToPoint: - APPEND_POINTS(2); - ch = 'q'; - break; - case kCGPathElementAddCurveToPoint: - APPEND_POINTS(3); - ch = 'c'; - break; - case kCGPathElementCloseSubpath: - ch = 'h'; - break; - default: - return; + case kCGPathElementMoveToPoint: + ch = 'm'; + count = 2; + break; + case kCGPathElementAddLineToPoint: + ch = 'l'; + count = 2; + break; + case kCGPathElementAddQuadCurveToPoint: + ch = 'q'; + count = 4; + break; + case kCGPathElementAddCurveToPoint: + ch = 'c'; + count = 6; + break; + case kCGPathElementCloseSubpath: + ch = 'h'; + count = 0; + break; + default: + return; + } + #pragma clang loop unroll(disable) + for (int i = 0; i < count; i++) { + CGFloat value = ((const CGFloat *)element->points)[i]; + if (path_info->step != 0.0) { + value = path_info->step * round(value * path_info->inverseStep); + } + char buffer[64]; + snprintf_l(buffer, sizeof(buffer), NULL, "%g ", value); + CFStringAppendCString(path_info->description, buffer, kCFStringEncodingUTF8); } CFStringAppendCharacters(path_info->description, &ch, 1); } -#undef APPEND_COORD -#undef APPEND_POINTS - -NSString * _CGPathCopyDescription(CGPathRef path, CGFloat step) { +CFStringRef _CGPathCopyDescription(CGPathRef path, CGFloat step) { PathInfo info = { - CFStringCreateMutable(kCFAllocatorDefault, 0), + CFStringCreateMutable(NULL, 0), step, 1.0 / step }; - CGPathApply(path, &info, ©_path_iter); - return (__bridge_transfer NSString *)(info.description); + CGPathApply(path, &info, copy_path_iter); + return info.description; } -CGPathRef _CGPathCreateRoundedRect(CGRect rect, CGFloat cornerWidth, CGFloat cornerHeight, PathRoundedCornerStyle style) { - // Clamp corner dimensions to be non-negative +CGPathRef _CGPathCreateRoundedRect(CGRect rect, CGFloat cornerWidth, CGFloat cornerHeight, bool continuous) { if (cornerWidth < 0.0) { cornerWidth = 0.0; } if (cornerHeight < 0.0) { cornerHeight = 0.0; } - - // If either corner dimension is 0, or rect is empty, return a plain rectangle if (cornerWidth == 0.0 || cornerHeight == 0.0 || CGRectIsEmpty(rect)) { return CGPathCreateWithRect(rect, NULL); } - - if (style == PathRoundedCornerStyleContinuous) { + if (continuous) { ORBPath rbPath = ORBPathMakeRoundedRect(rect, cornerWidth, cornerHeight, ORBPathRoundedCornerStyleContinuous, NULL); CGPathRef cgPath = ORBPathCopyCGPath(rbPath); ORBPathRelease(rbPath); return cgPath; } - - // Use CoreGraphics path creation (circular style) CGFloat width = CGRectGetWidth(rect); CGFloat height = CGRectGetHeight(rect); - - // Clamp cornerWidth to at most half the width if (cornerWidth * 2.0 > width) { cornerWidth = nextafter(width * 0.5, 0.0); } - - // Clamp cornerHeight to at most half the height if (cornerHeight * 2.0 > height) { cornerHeight = nextafter(height * 0.5, 0.0); } - - // Final validation - if (cornerWidth < 0.0 || cornerWidth * 2.0 > width) { - return CGPathCreateWithRect(rect, NULL); - } - if (cornerHeight < 0.0 || cornerHeight * 2.0 > height) { + if (cornerWidth < 0.0 || cornerWidth * 2.0 > width || cornerHeight < 0.0 || cornerHeight * 2.0 > height) { return CGPathCreateWithRect(rect, NULL); } - return CGPathCreateWithRoundedRect(rect, cornerWidth, cornerHeight, NULL); } diff --git a/Tests/OpenSwiftUI_SPITests/Overlay/CoreGraphics/CGPath+OpenSwiftUITests.swift b/Tests/OpenSwiftUI_SPITests/Overlay/CoreGraphics/CGPath+OpenSwiftUITests.swift index 8de7b8595..6c79dd9da 100644 --- a/Tests/OpenSwiftUI_SPITests/Overlay/CoreGraphics/CGPath+OpenSwiftUITests.swift +++ b/Tests/OpenSwiftUI_SPITests/Overlay/CoreGraphics/CGPath+OpenSwiftUITests.swift @@ -1,7 +1,9 @@ // // CGPath+OpenSwiftUITests.swift // OpenSwiftUI_SPITests +// +import Foundation import OpenSwiftUI_SPI import Testing @@ -15,25 +17,25 @@ struct CGPath_OpenSwiftUITests { struct ParseString { @Test(arguments: [ // m - move to - ("100 0 m 200 100 l h", true, " 100 0 m 200 100 l h"), + ("100 0 m 200 100 l h", true, "100 0 m 200 100 l h"), // l - line to (multiple) - ("0 0 m 100 0 l 100 100 l 0 100 l h", true, " 0 0 m 100 0 l 100 100 l 0 100 l h"), + ("0 0 m 100 0 l 100 100 l 0 100 l h", true, "0 0 m 100 0 l 100 100 l 0 100 l h"), // q - quad curve - ("0 0 m 50 0 100 100 q", true, " 0 0 m 50 0 100 100 q"), + ("0 0 m 50 0 100 100 q", true, "0 0 m 50 0 100 100 q"), // c - cubic curve - ("0 0 m 25 0 75 100 100 100 c", true, " 0 0 m 25 0 75 100 100 100 c"), + ("0 0 m 25 0 75 100 100 100 c", true, "0 0 m 25 0 75 100 100 100 c"), // v - smooth cubic (cp1 = current point) - ("0 0 m 50 50 100 100 v", true, " 0 0 m 0 0 50 50 100 100 c"), + ("0 0 m 50 50 100 100 v", true, "0 0 m 0 0 50 50 100 100 c"), // y - shorthand cubic (cp2 = endpoint) - ("0 0 m 25 0 100 100 y", true, " 0 0 m 25 0 100 100 100 100 c"), + ("0 0 m 25 0 100 100 y", true, "0 0 m 25 0 100 100 100 100 c"), // re - rectangle - ("10 20 30 40 re", true, " 10 20 m 40 20 l 40 60 l 10 60 l h"), + ("10 20 30 40 re", true, "10 20 m 40 20 l 40 60 l 10 60 l h"), // Negative numbers - ("-10 -20 m 30 40 l", true, " -10 -20 m 30 40 l"), + ("-10 -20 m 30 40 l", true, "-10 -20 m 30 40 l"), // Decimal numbers - ("0.5 1.5 m 2.5 3.5 l", true, " 0.5 1.5 m 2.5 3.5 l"), + ("0.5 1.5 m 2.5 3.5 l", true, "0.5 1.5 m 2.5 3.5 l"), // Whitespace variants (tab, newline) - ("0\t0\nm\n100\t100\tl", true, " 0 0 m 100 100 l"), + ("0\t0\nm\n100\t100\tl", true, "0 0 m 100 100 l"), // Invalid: unknown command ("0 0 z", false, ""), // Invalid: wrong number of parameters @@ -46,7 +48,7 @@ struct CGPath_OpenSwiftUITests { let result = _CGPathParseString(path, input) #expect(result == expectedResult) if expectedResult { - let description = _CGPathCopyDescription(path, 0) + let description = _CGPathCopyDescription(path, 0) as String #expect(description == expectedString) } } @@ -56,11 +58,11 @@ struct CGPath_OpenSwiftUITests { struct CopyDescription { @Test(arguments: [ - (0.0, " 100 0 m 189.5 189.5 l 0 189.5 l h"), - (1.0, " 100 0 m 190 190 l 0 190 l h"), - (2.0, " 100 0 m 190 190 l 0 190 l h"), - (3.0, " 99 0 m 189 189 l 0 189 l h"), - (4.0, " 100 0 m 188 188 l 0 188 l h"), + (0.0, "100 0 m 189.5 189.5 l 0 189.5 l h"), + (1.0, "100 0 m 190 190 l 0 190 l h"), + (2.0, "100 0 m 190 190 l 0 190 l h"), + (3.0, "99 0 m 189 189 l 0 189 l h"), + (4.0, "100 0 m 188 188 l 0 188 l h"), ]) func copyDescription(step: Double, expected: String) { let path = CGMutablePath() @@ -68,7 +70,7 @@ struct CGPath_OpenSwiftUITests { path.addLine(to: CGPoint(x: 189.5, y: 189.5)) path.addLine(to: CGPoint(x: 0, y: 189.5)) path.closeSubpath() - let description = _CGPathCopyDescription(path, step) + let description = _CGPathCopyDescription(path, step) as String #expect(description == expected) } @@ -77,8 +79,8 @@ struct CGPath_OpenSwiftUITests { let path = CGMutablePath() path.move(to: CGPoint(x: 0, y: 0)) path.addQuadCurve(to: CGPoint(x: 100, y: 100), control: CGPoint(x: 50, y: 0)) - let description = _CGPathCopyDescription(path, 1) - #expect(description == " 0 0 m 50 0 100 100 q") + let description = _CGPathCopyDescription(path, 1) as String + #expect(description == "0 0 m 50 0 100 100 q") } @Test @@ -86,8 +88,8 @@ struct CGPath_OpenSwiftUITests { let path = CGMutablePath() path.move(to: CGPoint(x: 0, y: 0)) path.addCurve(to: CGPoint(x: 100, y: 100), control1: CGPoint(x: 25, y: 0), control2: CGPoint(x: 75, y: 100)) - let description = _CGPathCopyDescription(path, 1) - #expect(description == " 0 0 m 25 0 75 100 100 100 c") + let description = _CGPathCopyDescription(path, 1) as String + #expect(description == "0 0 m 25 0 75 100 100 100 c") } } @@ -97,32 +99,31 @@ struct CGPath_OpenSwiftUITests { @Test func zeroCornerWidth() { let rect = CGRect(x: 0, y: 0, width: 100, height: 50) - let path = _CGPathCreateRoundedRect(rect, 0, 10, .circular) - #expect(_CGPathCopyDescription(path, 0) == " 0 0 m 100 0 l 100 50 l 0 50 l h") + let path = _CGPathCreateRoundedRect(rect, 0, 10, false) + #expect((_CGPathCopyDescription(path, 0) as String) == "0 0 m 100 0 l 100 50 l 0 50 l h") } @Test func zeroCornerHeight() { let rect = CGRect(x: 0, y: 0, width: 100, height: 50) - let path = _CGPathCreateRoundedRect(rect, 10, 0, .circular) - #expect(_CGPathCopyDescription(path, 0) == " 0 0 m 100 0 l 100 50 l 0 50 l h") + let path = _CGPathCreateRoundedRect(rect, 10, 0, false) + #expect((_CGPathCopyDescription(path, 0) as String) == "0 0 m 100 0 l 100 50 l 0 50 l h") } @Test func negativeCornerValues() { let rect = CGRect(x: 0, y: 0, width: 100, height: 50) - let path = _CGPathCreateRoundedRect(rect, -5, -5, .circular) - #expect(_CGPathCopyDescription(path, 0) == " 0 0 m 100 0 l 100 50 l 0 50 l h") + let path = _CGPathCreateRoundedRect(rect, -5, -5, false) + #expect((_CGPathCopyDescription(path, 0) as String) == "0 0 m 100 0 l 100 50 l 0 50 l h") } @Test func emptyRect() { let rect = CGRect(x: 0, y: 0, width: 0, height: 50) - let path = _CGPathCreateRoundedRect(rect, 10, 10, .circular) - #expect(_CGPathCopyDescription(path, 0) == " 0 0 m 0 0 l 0 50 l 0 50 l h") + let path = _CGPathCreateRoundedRect(rect, 10, 10, false) + #expect((_CGPathCopyDescription(path, 0) as String) == "0 0 m 0 0 l 0 50 l 0 50 l h") } } } #endif - From ad22b6b85d3a877062b064e614ca74f53a3277c0 Mon Sep 17 00:00:00 2001 From: Kyle Date: Sat, 21 Nov 2026 15:35:49 +0800 Subject: [PATCH 07/22] feat(path): complete Path and PathBox implementation --- Sources/OpenSwiftUICore/Shape/Path.swift | 1360 +++++++++++++---- .../Shape/RoundedCornerStyle.swift | 21 +- .../Util/Extension/CGRect+Extension.swift | 6 +- Sources/OpenSwiftUI_SPI/Util/PathData.h | 8 + .../Shape/Path/FixedRoundedRectTests.swift | 1 + .../Shape/Path/PathTests.swift | 105 +- .../Shape/Path/TrimmedPathTests.swift | 2 +- 7 files changed, 1169 insertions(+), 334 deletions(-) diff --git a/Sources/OpenSwiftUICore/Shape/Path.swift b/Sources/OpenSwiftUICore/Shape/Path.swift index 10862f598..fd1756f13 100644 --- a/Sources/OpenSwiftUICore/Shape/Path.swift +++ b/Sources/OpenSwiftUICore/Shape/Path.swift @@ -3,7 +3,7 @@ // OpenSwiftUICore // // Audited for 6.5.4 -// Status: WIP +// Status: Complete // ID: 31FD92B70C320DDD253E93C7417D779A (SwiftUI) // ID: 3591905F51357E95FA93E39751507471 (SwiftUICore) @@ -12,7 +12,7 @@ package import OpenRenderBoxShims import OpenSwiftUI_SPI public import OpenCoreGraphicsShims -// MARK: - Path [WIP] +// MARK: - Path /// The outline of a 2D shape. @available(OpenSwiftUI_v1_0, *) @@ -24,197 +24,196 @@ public struct Path: Equatable, LosslessStringConvertible, @unchecked Sendable { @usableFromInline final package class PathBox: Equatable { private enum Kind: UInt8 { - #if canImport(CoreGraphics) || !OPENSWIFTUI_CF_CGTYPES case cgPath - #endif case rbPath case buffer } private var kind: Kind - private var data: PathData + private var data: PathData = PathData() + + private func withStorage(_ body: (ORBPath.Storage) -> Result) -> Result { + ManagedBufferPointer<(Kind, PathData), Void>(unsafeBufferObject: self) + .withUnsafeMutablePointerToHeader { + body(ORBPath.Storage($0.pointer(to: \.1)!)) + } + } + + @inline(__always) + init(_ body: (UnsafeMutableRawPointer) -> Void) { + kind = .buffer + withStorage { + $0.initialize(capacity: MemoryLayout.size, source: nil) + body(UnsafeMutableRawPointer($0.rawValue)) + } + } + + @inline(__always) + convenience init() { + self.init { _ in } + } + + @inline(__always) + init(copying box: PathBox) { + kind = box.kind + switch kind { + case .cgPath: + data.cgPath = .passRetained(box.data.cgPath!.takeUnretainedValue()) + case .rbPath: + data.rbPath = box.data.rbPath.retain() + case .buffer: + box.withStorage { source in + withStorage { dest in + dest.initialize(capacity: MemoryLayout.size, source: source) + } + } + } + } - #if canImport(CoreGraphics) || !OPENSWIFTUI_CF_CGTYPES @inline(__always) init(_ path: CGPath) { - var data = PathData() kind = .cgPath data.cgPath = .passRetained(path) - self.data = data } - #endif package init(takingPath path: ORBPath) { - var data = PathData() kind = .rbPath data.rbPath = path - self.data = data } deinit { switch kind { - #if canImport(CoreGraphics) || !OPENSWIFTUI_CF_CGTYPES case .cgPath: - data.cgPath.release() - #endif + data.cgPath!.release() case .rbPath: data.rbPath.release() case .buffer: - withUnsafeMutablePointer(to: &data) { pointer in - let storage = unsafeBitCast(pointer, to: ORBPath.Storage.self) - storage.destroy() - } + withStorage { $0.destroy() } } } private func prepareBuffer() { let path: ORBPath switch kind { - #if canImport(CoreGraphics) || !OPENSWIFTUI_CF_CGTYPES case .cgPath: - path = ORBPath(cgPath: data.cgPath.takeRetainedValue()) - #endif + path = ORBPath(cgPath: data.cgPath!.takeRetainedValue()) case .rbPath: path = data.rbPath case .buffer: return } - withUnsafeMutablePointer(to: &data) { pointer in - let storage = unsafeBitCast(pointer, to: ORBPath.Storage.self) - storage.initialize(capacity: 96, source: nil) - storage.append(path: path) - kind = .buffer - path.release() + withStorage { + $0.initialize(capacity: MemoryLayout.size, source: nil) + _ = $0.append(path: path) + } + kind = .buffer + path.release() + } + + @inline(__always) + func withBuffer(_ body: (UnsafeMutableRawPointer) -> Result) -> Result { + if kind != .buffer { + prepareBuffer() + } + return withStorage { + body(UnsafeMutableRawPointer($0.rawValue)) } } + @inline(__always) + static func fromOpaque(_ pointer: UnsafeRawPointer) -> PathBox { + Unmanaged.fromOpaque(pointer).takeUnretainedValue() + } + private static let bufferCallbacks: UnsafePointer = { let pointer = UnsafeMutablePointer.allocate(capacity: 1) - var callbacks = ORBPath.empty.callbacks.pointee - callbacks.retain = { object in + pointer.initialize(to: .init()) + pointer.pointee.retain = { object in UnsafeRawPointer( Unmanaged.fromOpaque(object) - .retain() - .toOpaque() + .retain() + .toOpaque() ) } - callbacks.release = { object in + pointer.pointee.release = { object in Unmanaged.fromOpaque(object) .release() } - callbacks.apply = { object, info, callback in - let box = object.assumingMemoryBound(to: PathBox.self).pointee - let storage = withUnsafeMutablePointer(to: &box.data) { - unsafeBitCast($0, to: ORBPath.Storage.self) - } - return storage.apply(info: info, callback: callback) + pointer.pointee.apply = { object, info, callback in + fromOpaque(object).withStorage { $0.apply(info: info, callback: callback) } } - callbacks.isEqual = { lhs, rhs in - let lhsBox = lhs.assumingMemoryBound(to: PathBox.self).pointee - let rhsBox = rhs.assumingMemoryBound(to: PathBox.self).pointee - let lhsStorage = withUnsafeMutablePointer(to: &lhsBox.data) { - unsafeBitCast($0, to: ORBPath.Storage.self) + pointer.pointee.isEqual = { lhs, rhs in + fromOpaque(rhs).withStorage { rhsStorage in + fromOpaque(lhs).withStorage { lhsStorage in + lhsStorage.isEqual(to: rhsStorage) + } } - let rhsStorage = withUnsafeMutablePointer(to: &rhsBox.data) { - unsafeBitCast($0, to: ORBPath.Storage.self) - } - return lhsStorage.isEqual(to: rhsStorage) } - callbacks.isEmpty = { object in - let box = object.assumingMemoryBound(to: PathBox.self).pointee - let storage = withUnsafeMutablePointer(to: &box.data) { - unsafeBitCast($0, to: ORBPath.Storage.self) - } - return storage.isEmpty + pointer.pointee.isEmpty = { object in + fromOpaque(object).withStorage { $0.isEmpty } } - callbacks.isSingleElement = { object in - let box = object.assumingMemoryBound(to: PathBox.self).pointee - let storage = withUnsafeMutablePointer(to: &box.data) { - unsafeBitCast($0, to: ORBPath.Storage.self) - } - return storage.isEmpty + pointer.pointee.isSingleElement = { object in + fromOpaque(object).withStorage { $0.isSingleElement } } - callbacks.bezierOrder = { object in - let box = object.assumingMemoryBound(to: PathBox.self).pointee - let storage = withUnsafeMutablePointer(to: &box.data) { - unsafeBitCast($0, to: ORBPath.Storage.self) - } - return storage.bezierOrder + pointer.pointee.bezierOrder = { object in + fromOpaque(object).withStorage { $0.bezierOrder } } - callbacks.boundingRect = { object in - let box = object.assumingMemoryBound(to: PathBox.self).pointee - let storage = withUnsafeMutablePointer(to: &box.data) { - unsafeBitCast($0, to: ORBPath.Storage.self) - } - return storage.boundingRect + pointer.pointee.boundingRect = { object in + fromOpaque(object).withStorage { $0.boundingRect } } - pointer.initialize(to: callbacks) return UnsafePointer(pointer) }() - #if canImport(CoreGraphics) || !OPENSWIFTUI_CF_CGTYPES @inline(__always) - fileprivate var cgPath: CGPath { - let rbPath: ORBPath + func withRBPath(_ body: (ORBPath) -> Result) -> Result { + let path: ORBPath switch kind { case .cgPath: - return data.cgPath.takeUnretainedValue() + path = ORBPath( + storage: ORBPath.Storage(data.cgPath!.toOpaque()), + callbacks: PathData.cgPathCallbacks + ) case .rbPath: - rbPath = data.rbPath + path = data.rbPath case .buffer: - let storage = unsafeBitCast(self, to: ORBPath.Storage.self) - rbPath = ORBPath(storage: storage, callbacks: Self.bufferCallbacks) + path = ORBPath( + storage: ORBPath.Storage(Unmanaged.passUnretained(self).toOpaque()), + callbacks: Self.bufferCallbacks + ) } - return rbPath.cgPath + return body(path) } - #endif @inline(__always) - fileprivate var rbPath: ORBPath { - switch kind { - case .cgPath: - return ORBPath(cgPath: data.cgPath.takeUnretainedValue()) - case .rbPath: - return data.rbPath - case .buffer: - let storage = unsafeBitCast(self, to: ORBPath.Storage.self) - return ORBPath(storage: storage, callbacks: Self.bufferCallbacks) + var cgPath: CGPath { + guard kind != .cgPath else { + return data.cgPath!.takeUnretainedValue() } + return withRBPath { $0.cgPath } } - + @inline(__always) - fileprivate var boundingRect: CGRect { + var boundingRect: CGRect { switch kind { case .cgPath: - #if canImport(CoreGraphics) - return data.cgPath.takeUnretainedValue().boundingBoxOfPath - #else - _openSwiftUIPlatformUnimplementedWarning() - return .zero - #endif + return data.cgPath!.takeUnretainedValue().boundingBoxOfPath case .rbPath: - _openSwiftUIUnimplementedWarning() - // return data.rbPath.boundingBox // FIXME: RB API - return .zero + return data.rbPath.boundingRect case .buffer: - let storage = unsafeBitCast(self, to: ORBPath.Storage.self) - return storage.boundingRect + return withStorage { $0.boundingRect } } } - @inline(__always) - fileprivate func retainRBPath() -> ORBPath { - let rbPath = rbPath - rbPath.retain() - return rbPath - } - @usableFromInline package static func == (lhs: PathBox, rhs: PathBox) -> Bool { - return lhs.rbPath.isEqual(to: rhs.rbPath) + lhs.withRBPath { lhsPath in + rhs.withRBPath { lhsPath.isEqual(to: $0) } + } } } + // MARK: - Path.Storage + @usableFromInline @frozen package enum Storage: Equatable { @@ -244,7 +243,10 @@ public struct Path: Equatable, LosslessStringConvertible, @unchecked Sendable { storage = .empty } - #if canImport(CoreGraphics) || !OPENSWIFTUI_CF_CGTYPES + package init(_ path: ORBPath) { + self.init(box: PathBox(takingPath: path.retain())) + } + /// Creates a path from an immutable shape path. /// /// - Parameter path: The immutable CoreGraphics path to initialize @@ -270,7 +272,6 @@ public struct Path: Equatable, LosslessStringConvertible, @unchecked Sendable { } storage = .path(PathBox(path.mutableCopy()!)) } - #endif /// Creates a path containing a rectangle. /// @@ -357,13 +358,10 @@ public struct Path: Equatable, LosslessStringConvertible, @unchecked Sendable { /// - style: The corner style. Defaults to the `continous` style /// if not specified. /// + @available(OpenSwiftUI_v4_0, *) public init(roundedRect rect: CGRect, cornerRadii: RectangleCornerRadii, style: RoundedCornerStyle = .continuous) { - guard !rect.isNull else { - storage = .empty - return - } - // TODO: addRoundedRect - _openSwiftUIUnimplementedFailure() + storage = .empty + addRoundedRect(in: rect, cornerRadii: cornerRadii, style: style) } /// Creates a path as an ellipse within the given rectangle. @@ -414,11 +412,8 @@ public struct Path: Equatable, LosslessStringConvertible, @unchecked Sendable { public init?(_ string: String) { #if canImport(CoreGraphics) let mutablePath = CGMutablePath() - let nsString = string as NSString - guard let str = nsString.utf8String else { - return nil - } - guard _CGPathParseString(mutablePath, str) else { + guard let utf8 = (string as NSString).utf8String, + _CGPathParseString(mutablePath, utf8) else { return nil } storage = .path(PathBox(mutablePath)) @@ -432,46 +427,44 @@ public struct Path: Equatable, LosslessStringConvertible, @unchecked Sendable { /// via `init?(_:)`. public var description: String { #if canImport(Darwin) - _CGPathCopyDescription(cgPath, 0.0) + _CGPathCopyDescription(cgPath, 0.0) as String #else _openSwiftUIPlatformUnimplementedFailure() #endif } - #if canImport(CoreGraphics) || !OPENSWIFTUI_CF_CGTYPES /// An immutable path representing the elements in the path. public var cgPath: CGPath { - #if canImport(Darwin) + #if canImport(CoreGraphics) switch storage { case .empty: - CGPath(rect: .null, transform: nil) + return CGPath(rect: .null, transform: nil) case let .rect(rect): - CGPath(rect: rect, transform: nil) + return CGPath(rect: rect, transform: nil) case let .ellipse(rect): - CGPath(ellipseIn: rect, transform: nil) + return CGPath(ellipseIn: rect, transform: nil) case let .roundedRect(fixedRoundedRect): - fixedRoundedRect.cgPath + return fixedRoundedRect.cgPath case .stroked, .trimmed: - _openSwiftUIUnreachableCode() + preconditionFailure("obsolete") case let .path(pathBox): - pathBox.cgPath + return pathBox.cgPath } #else _openSwiftUIPlatformUnimplementedFailure() #endif } - #endif package func retainRBPath() -> ORBPath { switch storage { case .empty: - ORBPath.empty + return ORBPath.empty case let .rect(rect): - ORBPath(rect: rect, transform: nil) + return ORBPath(rect: rect, transform: nil) case let .ellipse(rect): - ORBPath(ellipseIn: rect, transform: nil) + return ORBPath(ellipseIn: rect, transform: nil) case let .roundedRect(fixedRoundedRect): - ORBPath( + return ORBPath( roundedRect: fixedRoundedRect.rect, cornerWidth: fixedRoundedRect.cornerSize.width, cornerHeight: fixedRoundedRect.cornerSize.height, @@ -479,31 +472,88 @@ public struct Path: Equatable, LosslessStringConvertible, @unchecked Sendable { transform: nil ) case .stroked, .trimmed: - _openSwiftUIUnreachableCode() + preconditionFailure("obsolete") case let .path(pathBox): - pathBox.retainRBPath() + return pathBox.withRBPath { $0.retain() } } } package mutating func withMutableBuffer(do body: (UnsafeMutableRawPointer) -> Void) { - _openSwiftUIUnimplementedFailure() + let box: PathBox + if case .path(var existing) = storage { + storage = .empty + if !isKnownUniquelyReferenced(&existing) { + existing = PathBox(copying: existing) + } + box = existing + } else { + box = PathBox() + box.withBuffer { append(to: $0) } + } + storage = .path(box) + box.withBuffer(body) + } + + private func append(to buffer: UnsafeMutableRawPointer) { + let storage = ORBPath.Storage(buffer) + switch self.storage { + case .empty: + break + case let .rect(rect): + storage.append( + element: .rect, + points: [ + rect.x, + rect.y, + rect.size.width, + rect.size.height + ], + userInfo: nil + ) + case let .ellipse(rect): + storage.append( + element: .ellipse, + points: [ + rect.x, + rect.y, + rect.size.width, + rect.size.height + ], + userInfo: nil + ) + case let .roundedRect(roundedRect): + storage.append( + element: roundedRect.style == .circular ? .fixedRoundedRectCircular : .fixedRoundedRectContinuous, + points: [ + roundedRect.rect.x, + roundedRect.rect.y, + roundedRect.rect.size.width, + roundedRect.rect.size.height, + roundedRect.cornerSize.width, + roundedRect.cornerSize.height + ], + userInfo: nil + ) + case .stroked, .trimmed: + preconditionFailure("obsolete") + case let .path(box): + box.withRBPath { _ = storage.append(path: $0) } + } } /// A Boolean value indicating whether the path contains zero elements. public var isEmpty: Bool { switch storage { case .empty: - true - case let .rect(rect): - rect.isNull - case let .ellipse(rect): - rect.isNull + return true + case let .rect(rect), let .ellipse(rect): + return rect.isNull case let .roundedRect(fixedRoundedRect): - fixedRoundedRect.rect.isNull + return fixedRoundedRect.rect.isNull case .stroked, .trimmed: - _openSwiftUIUnreachableCode() + preconditionFailure("obsolete") case let .path(pathBox): - pathBox.rbPath.isEmpty + return pathBox.withRBPath { $0.isEmpty } } } @@ -515,17 +565,15 @@ public struct Path: Equatable, LosslessStringConvertible, @unchecked Sendable { public var boundingRect: CGRect { switch storage { case .empty: - .null - case let .rect(rect): - rect - case let .ellipse(rect): - rect + return .null + case let .rect(rect), let .ellipse(rect): + return rect case let .roundedRect(fixedRoundedRect): - fixedRoundedRect.rect + return fixedRoundedRect.rect case .stroked, .trimmed: - _openSwiftUIUnreachableCode() + preconditionFailure("obsolete") case let .path(pathBox): - pathBox.boundingRect + return pathBox.boundingRect } } @@ -542,21 +590,11 @@ public struct Path: Equatable, LosslessStringConvertible, @unchecked Sendable { case let .ellipse(rect): return ellipseContains(in: rect, contains: p) case let .roundedRect(rect): - #if canImport(Darwin) return rect.contains(p) - #else - // FIXME - let path = retainRBPath() - defer { path.release() } - return path.contains(point: p, eoFill: false) - #endif case .stroked, .trimmed: - _openSwiftUIUnreachableCode() + preconditionFailure("obsolete") case let .path(box): - let path = box.retainRBPath() - // TBA - defer { path.release() } - return path.contains(point: p, eoFill: eoFill) + return box.withRBPath { $0.contains(point: p, eoFill: eoFill) } } } @@ -575,11 +613,46 @@ public struct Path: Equatable, LosslessStringConvertible, @unchecked Sendable { eoFill: Bool = false, origin: CGPoint = .zero ) -> BitVector64 { - // FIXME: - // The RenderBox shim currently declares the batched mask result as Bool. - // Use scalar containment to preserve every bit until that ABI is corrected. - points.mapBool { - contains(CGPoint(x: $0.x - origin.x, y: $0.y - origin.y), eoFill: eoFill) + guard !points.isEmpty else { + return BitVector64() + } + switch storage { + case .empty: + return BitVector64() + case let .rect(rect): + return points.mapBool { + rect.contains(CGPoint($0 - origin)) + } + case let .ellipse(rect): + return points.mapBool { + ellipseContains(in: rect, contains: CGPoint($0 - origin)) + } + case let .roundedRect(roundedRect): + var transform = CGAffineTransform(translationX: -origin.x, y: -origin.y) + return roundedRect.withTemporaryPath { rbPath in + BitVector64( + rawValue: rbPath.containsPoints( + count: UInt64(points.count), + points: points.baseAddress!, + eoFill: false, + transform: &transform + ) + ) + } + case .stroked, .trimmed: + preconditionFailure("obsolete") + case let .path(box): + var transform = CGAffineTransform(translationX: -origin.x, y: -origin.y) + return box.withRBPath { rbPath in + BitVector64( + rawValue: rbPath.containsPoints( + count: UInt64(points.count), + points: points.baseAddress!, + eoFill: eoFill, + transform: &transform + ) + ) + } } } @@ -615,34 +688,68 @@ public struct Path: Equatable, LosslessStringConvertible, @unchecked Sendable { /// Calls `body` with each element in the path. public func forEach(_ body: (Path.Element) -> Void) { - #if canImport(CoreGraphics) - // FIXME: Use RB API instead of CG API - cgPath.applyWithBlock { element in - let element = element.pointee - switch element.type { - case .moveToPoint: - body(.move(to: element.points[0])) - case .addLineToPoint: - body(.line(to: element.points[0])) - case .addQuadCurveToPoint: - body(.quadCurve(to: element.points[1], control: element.points[0])) - case .addCurveToPoint: - body(.curve(to: element.points[2], control1: element.points[0], control2: element.points[1])) - case .closeSubpath: - body(.closeSubpath) - @unknown default: - break + withoutActuallyEscaping(body) { escapingBody in + struct Context { + let body: (Path.Element) -> Void + } + let rbPath = retainRBPath() + defer { rbPath.release() } + var context = Context(body: escapingBody) + withUnsafeMutablePointer(to: &context) { contextPtr in + _ = rbPath.applyCGPathElements(transform: nil, info: contextPtr) { info, elementPtr in + let context = info.assumingMemoryBound(to: Context.self) + switch elementPtr.pointee.type { + case .moveToPoint: + context.pointee.body(.move(to: elementPtr.pointee.points[0])) + case .addLineToPoint: + context.pointee.body(.line(to: elementPtr.pointee.points[0])) + case .addQuadCurveToPoint: + context.pointee.body( + .quadCurve( + to: elementPtr.pointee.points[1], + control: elementPtr.pointee.points[0] + ) + ) + case .addCurveToPoint: + context.pointee.body( + .curve( + to: elementPtr.pointee.points[2], + control1: elementPtr.pointee.points[0], + control2: elementPtr.pointee.points[1] + ) + ) + case .closeSubpath: + context.pointee.body(.closeSubpath) + @unknown default: + break + } + return true + } } } - #else - _openSwiftUIPlatformUnimplementedFailure() - #endif } /// Returns a stroked copy of the path using `style` to define how the /// stroked outline is created. public func strokedPath(_ style: StrokeStyle) -> Path { - _openSwiftUIUnimplementedFailure() + guard !isEmpty else { return Path() } + let rbPath = retainRBPath() + defer { rbPath.release() } + return Path(box: PathBox { buffer in + let storage = ORBPath.Storage(buffer) + style.dash.withUnsafeBufferPointer { dash in + let points = [style.lineWidth, style.miterLimit, style.dashPhase] + var metadata = ( + style.lineCap.rawValue, + style.lineJoin.rawValue, + dash.count, + dash.baseAddress + ) + storage.append(element: .stroked, points: points, userInfo: &metadata) + } + append(to: buffer) + storage.append(element: .end, points: nil, userInfo: nil) + }) } /// Returns a partial copy of the path. @@ -660,38 +767,57 @@ public struct Path: Equatable, LosslessStringConvertible, @unchecked Sendable { guard to > from else { return Path() } - // let retainedPath = retainRBPath() - _openSwiftUIUnimplementedWarning() - return self + let rbPath = retainRBPath() + defer { rbPath.release() } + return Path(box: PathBox { buffer in + let storage = ORBPath.Storage(buffer) + storage.append(element: .trimmed, points: [from, to], userInfo: nil) + append(to: buffer) + storage.append(element: .end, points: nil, userInfo: nil) + }) + } + + package func mix(with rhs: Path, by fraction: CGFloat) -> Path? { + let p1 = retainRBPath() + let p2 = rhs.retainRBPath() + defer { + p1.release() + p2.release() + } + let mixed = p1.interpolated(to: p2, fraction: Float(fraction)) + guard !mixed.isNull else { + return nil + } + return Path(box: PathBox(takingPath: mixed)) } package func rect() -> CGRect? { switch storage { case let .rect(rect): - rect + return rect default: - nil + return nil } } package func roundedRect() -> FixedRoundedRect? { switch storage { case let .rect(rect): - FixedRoundedRect(rect) + return FixedRoundedRect(rect) case let .ellipse(rect): - if rect.width == rect.height { - FixedRoundedRect( + if rect.size.width == rect.size.height { + return FixedRoundedRect( rect, - cornerRadius: rect.width / 2, + cornerRadius: rect.size.width / 2, style: .circular ) } else { - nil + return nil } case let .roundedRect(fixedRoundedRect): - fixedRoundedRect + return fixedRoundedRect default: - nil + return nil } } } @@ -704,32 +830,65 @@ extension Path.PathBox: Sendable {} // MARK: - Path + Shape +@available(OpenSwiftUI_v1_0, *) extension Path: Shape { nonisolated public func path(in _: CGRect) -> Path { self } - - public typealias AnimatableData = EmptyAnimatableData - - public typealias Body = _ShapeView } // MARK: - Path + ProtobufMessage extension Path: ProtobufMessage { package func encode(to encoder: inout ProtobufEncoder) throws { - _openSwiftUIUnimplementedFailure() + switch storage { + case .empty: + break + case let .rect(rect): + try encoder.messageField(1, rect) + case let .ellipse(rect): + try encoder.messageField(2, rect) + case let .roundedRect(roundedRect): + try encoder.messageField(3, roundedRect) + case .stroked, .trimmed: + preconditionFailure("obsolete") + case .path: + let rbPath = retainRBPath() + defer { rbPath.release() } + if let data = rbPath.data { + encoder.dataField(4, data as Data) + } + } } package init(from decoder: inout ProtobufDecoder) throws { - _openSwiftUIUnimplementedFailure() + var path = Path() + while let field = try decoder.nextField() { + switch field.tag { + case 1: + path.storage = .rect(try decoder.messageField(field)) + case 2: + path.storage = .ellipse(try decoder.messageField(field)) + case 3: + path.storage = .roundedRect(try decoder.messageField(field)) + case 4: + let data = try decoder.dataField(field) + path.storage = .path(PathBox(takingPath: ORBPath(data: data as CFData))) + default: + try decoder.skipField(field) + } + } + self = path } } // MARK: - StrokedPath +@available(OpenSwiftUI_v1_0, *) @available(*, deprecated, message: "obsolete") @usableFromInline package struct StrokedPath: Equatable { - public init(path: Path, style: StrokeStyle) {} + public init(path: Path, style: StrokeStyle) { + _openSwiftUIEmptyStub() + } @usableFromInline package static func == (a: StrokedPath, b: StrokedPath) -> Bool { @@ -742,6 +901,7 @@ extension StrokedPath: Sendable {} // MARK: - TrimmedPath +@available(OpenSwiftUI_v1_0, *) @available(*, deprecated, message: "obsolete") @usableFromInline package struct TrimmedPath: Equatable { @@ -754,53 +914,217 @@ package struct TrimmedPath: Equatable { @available(*, unavailable) extension TrimmedPath: Sendable {} -// MARK: - Path + Extension [WIP] +// MARK: - Path + Extension @available(OpenSwiftUI_v1_0, *) extension Path { + /// Begins a new subpath at the specified point. + /// + /// The specified point becomes the start point of a new subpath. + /// The current point is set to this start point. + /// + /// - Parameter end: The point, in user space coordinates, at which + /// to start a new subpath. + /// public mutating func move(to end: CGPoint) { - _openSwiftUIUnimplementedFailure() + withMutableBuffer { buffer in + ORBPath.Storage(buffer) + .append( + element: .moveToPoint, + points: [end.x, end.y], + userInfo: nil + ) + } } + /// Appends a straight line segment from the current point to the + /// specified point. + /// + /// After adding the line segment, the current point is set to the + /// endpoint of the line segment. + /// + /// - Parameter end: The location, in user space coordinates, for the + /// end of the new line segment. + /// public mutating func addLine(to end: CGPoint) { - _openSwiftUIUnimplementedFailure() + withMutableBuffer { buffer in + ORBPath.Storage(buffer) + .append( + element: .addLineToPoint, + points: [end.x, end.y], + userInfo: nil + ) + } } + /// Adds a quadratic Bézier curve to the path, with the + /// specified end point and control point. + /// + /// This method constructs a curve starting from the path's current + /// point and ending at the specified end point, with curvature + /// defined by the control point. After this method appends that + /// curve to the current path, the end point of the curve becomes + /// the path's current point. + /// + /// - Parameters: + /// the curve. + /// - control: The control point of the curve, in user space + /// coordinates. + /// public mutating func addQuadCurve( to end: CGPoint, control: CGPoint ) { - _openSwiftUIUnimplementedFailure() + withMutableBuffer { buffer in + ORBPath.Storage(buffer) + .append( + element: .addQuadCurveToPoint, + points: [control.x, control.y, end.x, end.y], + userInfo: nil + ) + } } + /// Adds a cubic Bézier curve to the path, with the + /// specified end point and control points. + /// + /// This method constructs a curve starting from the path's current + /// point and ending at the specified end point, with curvature + /// defined by the two control points. After this method appends + /// that curve to the current path, the end point of the curve + /// becomes the path's current point. + /// + /// - Parameters: + /// the curve. + /// - control1: The first control point of the curve, in user + /// space coordinates. + /// - control2: The second control point of the curve, in user + /// space coordinates. + /// public mutating func addCurve( to end: CGPoint, control1: CGPoint, control2: CGPoint ) { - _openSwiftUIUnimplementedFailure() + withMutableBuffer { buffer in + ORBPath.Storage(buffer) + .append( + element: .addCurveToPoint, + points: [control1.x, control1.y, control2.x, control2.y, end.x, end.y], + userInfo: nil + ) + } } + /// Closes and completes the current subpath. + /// + /// Appends a line from the current point to the starting point of + /// the current subpath and ends the subpath. + /// + /// After closing the subpath, your application can begin a new + /// subpath without first calling `move(to:)`. In this case, a new + /// subpath is implicitly created with a starting and current point + /// equal to the previous subpath's starting point. + /// public mutating func closeSubpath() { - _openSwiftUIUnimplementedFailure() + withMutableBuffer { buffer in + ORBPath.Storage(buffer) + .append( + element: .closeSubpath, + points: nil, + userInfo: nil + ) + } } + /// Adds a rectangular subpath to the path. + /// + /// This is a convenience function that adds a rectangle to a path, + /// starting by moving to the bottom-left corner and then adding + /// lines counter-clockwise to create a rectangle, closing the + /// subpath. + /// + /// - Parameters: + /// - rect: A rectangle, specified in user space coordinates. + /// - transform: An affine transform to apply to the rectangle + /// before adding to the path. Defaults to the identity + /// transform if not specified. + /// public mutating func addRect( _ rect: CGRect, transform: CGAffineTransform = .identity ) { - _openSwiftUIUnimplementedFailure() + guard !rect.isNull else { return } + if case .empty = storage, transform.isRectilinear { + storage = .rect(rect.applying(transform)) + return + } + withMutableBuffer { buffer in + var transform = transform + ORBPath.Storage(buffer).append( + element: .rect, + points: [rect.x, rect.y, rect.size.width, rect.size.height], + userInfo: &transform + ) + } } + /// Adds a rounded rectangle to the path. + /// + /// This is a convenience function that adds a rounded rectangle to + /// a path, starting by moving to the center of the right edge and + /// then adding lines and curves counter-clockwise to create a + /// rounded rectangle, closing the subpath. + /// + /// - Parameters: + /// - rect: A rectangle, specified in user space coordinates. + /// - cornerSize: The size of the corners, specified in user space + /// coordinates. + /// - style: The corner style. Defaults to the `continous` style + /// if not specified. + /// - transform: An affine transform to apply to the rectangle + /// before adding to the path. Defaults to the identity + /// transform if not specified. + /// public mutating func addRoundedRect( in rect: CGRect, cornerSize: CGSize, style: RoundedCornerStyle = .continuous, transform: CGAffineTransform = .identity ) { - _openSwiftUIUnimplementedFailure() + guard !rect.isNull else { return } + if case .empty = storage, transform.isRectilinear { + let roundedRect = FixedRoundedRect(rect, cornerSize: cornerSize, style: style).applying(transform) + storage = .roundedRect(roundedRect) + return + } + withMutableBuffer { buffer in + var transform = transform + ORBPath.Storage(buffer).append( + element: style == .circular ? .fixedRoundedRectCircular : .fixedRoundedRectContinuous, + points: [rect.x, rect.y, rect.size.width, rect.size.height, cornerSize.width, cornerSize.height], + userInfo: &transform + ) + } } + /// Adds a rounded rectangle with uneven corners to the path. + /// + /// This is a convenience function that adds a rounded rectangle to + /// a path, starting by moving to the center of the right edge and + /// then adding lines and curves counter-clockwise to create a + /// rounded rectangle, closing the subpath. + /// + /// - Parameters: + /// - rect: A rectangle, specified in user space coordinates. + /// - cornerRadii: The radius of each corner of the rectangle, + /// specified in user space coordinates. + /// - style: The corner style. Defaults to the `continous` style + /// if not specified. + /// - transform: An affine transform to apply to the rectangle + /// before adding to the path. Defaults to the identity + /// transform if not specified. + /// @available(OpenSwiftUI_v4_0, *) public mutating func addRoundedRect( in rect: CGRect, @@ -808,27 +1132,168 @@ extension Path { style: RoundedCornerStyle = .continuous, transform: CGAffineTransform = .identity ) { - _openSwiftUIUnimplementedFailure() + guard !rect.isNull else { return } + withMutableBuffer { buffer in + var transform = transform + ORBPath.Storage(buffer).append( + element: style == .circular ? .unevenRoundedRectCircular : .unevenRoundedRectContinuous, + points: [ + rect.x, rect.y, rect.size.width, rect.size.height, + cornerRadii.topLeft, cornerRadii.topRight, + cornerRadii.bottomRight, cornerRadii.bottomLeft, + ], + userInfo: &transform + ) + } } + /// Adds an ellipse that fits inside the specified rectangle to the + /// path. + /// + /// The ellipse is approximated by a sequence of Bézier + /// curves. Its center is the midpoint of the rectangle defined by + /// the `rect` parameter. If the rectangle is square, then the + /// ellipse is circular with a radius equal to one-half the width + /// (or height) of the rectangle. If the `rect` parameter specifies + /// a rectangular shape, then the major and minor axes of the + /// ellipse are defined by the width and height of the rectangle. + /// + /// The ellipse forms a complete subpath of the path— + /// that is, the ellipse drawing starts with a move-to operation + /// and ends with a close-subpath operation, with all moves + /// oriented in the clockwise direction. + /// + /// - Parameter: + /// - rect: A rectangle that defines the area for the ellipse to + /// fit in. + /// - transform: An affine transform to apply to the ellipse + /// before adding to the path. Defaults to the identity + /// transform if not specified. + /// public mutating func addEllipse( in rect: CGRect, transform: CGAffineTransform = .identity ) { - _openSwiftUIUnimplementedFailure() + guard !rect.isNull else { return } + if case .empty = storage, transform.isRectilinear { + storage = .ellipse(rect.applying(transform)) + return + } + withMutableBuffer { buffer in + var transform = transform + ORBPath.Storage(buffer).append( + element: .ellipse, + points: [rect.x, rect.y, rect.size.width, rect.size.height], + userInfo: &transform + ) + } } + /// Adds a set of rectangular subpaths to the path. + /// + /// Calling this convenience method is equivalent to repeatedly + /// calling the `addRect(_:transform:)` method for each rectangle + /// in the array. + /// + /// - Parameter: + /// - rects: An array of rectangles, specified in user space + /// coordinates. + /// - transform: An affine transform to apply to the ellipse + /// before adding to the path. Defaults to the identity + /// transform if not specified. + /// public mutating func addRects( _ rects: [CGRect], transform: CGAffineTransform = .identity ) { - _openSwiftUIUnimplementedFailure() + switch rects.count { + case 0: + break + case 1: + addRect(rects[0], transform: transform) + default: + withMutableBuffer { buffer in + let storage = ORBPath.Storage(buffer) + for rect in rects { + var transform = transform + storage.append( + element: .rect, + points: [rect.x, rect.y, rect.size.width, rect.size.height], + userInfo: &transform + ) + } + } + } } + /// Adds a sequence of connected straight-line segments to the path. + /// + /// Calling this convenience method is equivalent to applying the + /// transform to all points in the array, then calling the + /// `move(to:)` method with the first value in the `points` array, + /// then calling the `addLine(to:)` method for each subsequent + /// point until the array is exhausted. After calling this method, + /// the path's current point is the last point in the array. + /// + /// - Parameter: + /// - lines: An array of values that specify the start and end + /// points of the line segments to draw. Each point in the + /// array specifies a position in user space. The first point + /// in the array specifies the initial starting point. + /// - transform: An affine transform to apply to the points + /// before adding to the path. Defaults to the identity + /// transform if not specified. + /// public mutating func addLines(_ lines: [CGPoint]) { - _openSwiftUIUnimplementedFailure() + guard !lines.isEmpty else { return } + withMutableBuffer { buffer in + let storage = ORBPath.Storage(buffer) + let start = lines[0] + storage.append(element: .moveToPoint, points: [start.x, start.y], userInfo: nil) + for i in 1 ..< lines.count { + let point = lines[i] + storage.append(element: .addLineToPoint, points: [point.x, point.y], userInfo: nil) + } + } } + /// Adds an arc of a circle to the path, specified with a radius + /// and a difference in angle. + /// + /// This method calculates starting and ending points using the + /// radius and angles you specify, uses a sequence of cubic + /// Bézier curves to approximate a segment of a circle + /// between those points, and then appends those curves to the + /// path. + /// + /// The `delta` parameter determines both the length of the arc the + /// direction in which the arc is created; the actual direction of + /// the final path is dependent on the `transform` parameter and + /// the current transform of a context where the path is drawn. + /// However, because OpenSwiftUI by default uses a vertically-flipped + /// coordinate system (with the origin in the top-left of the + /// view), specifying a clockwise arc results in a counterclockwise + /// arc after the transformation is applied. + /// + /// If the path ends with an unclosed subpath, this method adds a + /// line connecting the current point to the starting point of the + /// arc. If there is no unclosed subpath, this method creates a new + /// subpath whose starting point is the starting point of the arc. + /// The ending point of the arc becomes the new current point of + /// the path. + /// + /// - Parameters: + /// - center: The center of the arc, in user space coordinates. + /// - radius: The radius of the arc, in user space coordinates. + /// - startAngle: The angle to the starting point of the arc, + /// measured from the positive x-axis. + /// - delta: The difference between the starting angle and ending + /// angle of the arc. A positive value creates a counter- + /// clockwise arc (in user space coordinates), and vice versa. + /// - transform: An affine transform to apply to the arc before + /// adding to the path. Defaults to the identity transform if + /// not specified. + /// public mutating func addRelativeArc( center: CGPoint, radius: CGFloat, @@ -836,9 +1301,54 @@ extension Path { delta: Angle, transform: CGAffineTransform = .identity ) { - _openSwiftUIUnimplementedFailure() + withMutableBuffer { buffer in + var transform = transform + ORBPath.Storage(buffer).append( + element: .relativeArc, + points: [center.x, center.y, radius, CGFloat(startAngle.radians), CGFloat(delta.radians)], + userInfo: &transform + ) + } } + /// Adds an arc of a circle to the path, specified with a radius + /// and angles. + /// + /// This method calculates starting and ending points using the + /// radius and angles you specify, uses a sequence of cubic + /// Bézier curves to approximate a segment of a circle + /// between those points, and then appends those curves to the + /// path. + /// + /// The `clockwise` parameter determines the direction in which the + /// arc is created; the actual direction of the final path is + /// dependent on the `transform` parameter and the current + /// transform of a context where the path is drawn. However, + /// because OpenSwiftUI by default uses a vertically-flipped coordinate + /// system (with the origin in the top-left of the view), + /// specifying a clockwise arc results in a counterclockwise arc + /// after the transformation is applied. + /// + /// If the path ends with an unclosed subpath, this method adds a + /// line connecting the current point to the starting point of the + /// arc. If there is no unclosed subpath, this method creates a new + /// subpath whose starting point is the starting point of the arc. + /// The ending point of the arc becomes the new current point of + /// the path. + /// + /// - Parameters: + /// - center: The center of the arc, in user space coordinates. + /// - radius: The radius of the arc, in user space coordinates. + /// - startAngle: The angle to the starting point of the arc, + /// measured from the positive x-axis. + /// - endAngle: The angle to the end point of the arc, measured + /// from the positive x-axis. + /// - clockwise: true to make a clockwise arc; false to make a + /// counterclockwise arc. + /// - transform: An affine transform to apply to the arc before + /// adding to the path. Defaults to the identity transform if + /// not specified. + /// public mutating func addArc( center: CGPoint, radius: CGFloat, @@ -847,95 +1357,308 @@ extension Path { clockwise: Bool, transform: CGAffineTransform = .identity ) { - _openSwiftUIUnimplementedFailure() + withMutableBuffer { buffer in + var transform = transform + ORBPath.Storage(buffer).append( + element: clockwise ? .arc : .arcCounterclockwise, + points: [center.x, center.y, radius, CGFloat(startAngle.radians), CGFloat(endAngle.radians)], + userInfo: &transform + ) + } } + /// Adds an arc of a circle to the path, specified with a radius + /// and two tangent lines. + /// + /// This method calculates two tangent lines—the first + /// from the current point to the tangent1End point, and the second + /// from the `tangent1End` point to the `tangent2End` + /// point—then calculates the start and end points for a + /// circular arc of the specified radius such that the arc is + /// tangent to both lines. Finally, this method approximates that + /// arc with a sequence of cubic Bézier curves and appends + /// those curves to the path. + /// + /// If the starting point of the arc (that is, the point where a + /// circle of the specified radius must meet the first tangent line + /// in order to also be tangent to the second line) is not the + /// current point, this method appends a straight line segment from + /// the current point to the starting point of the arc. + /// + /// The ending point of the arc (that is, the point where a circle + /// of the specified radius must meet the second tangent line in + /// order to also be tangent to the first line) becomes the new + /// current point of the path. + /// + /// - Parameters: + /// - tangent1End:The end point, in user space coordinates, for + /// the first tangent line to be used in constructing the arc. + /// (The start point for this tangent line is the path's + /// current point.) + /// - tangent2End: The end point, in user space coordinates, for + /// the second tangent line to be used in constructing the arc. + /// (The start point for this tangent line is the tangent1End + /// point.) + /// - radius: The radius of the arc, in user space coordinates. + /// - transform: An affine transform to apply to the arc before + /// adding to the path. Defaults to the identity transform if + /// not specified. + /// public mutating func addArc( tangent1End: CGPoint, tangent2End: CGPoint, radius: CGFloat, transform: CGAffineTransform = .identity ) { - _openSwiftUIUnimplementedFailure() + withMutableBuffer { buffer in + var transform = transform + ORBPath.Storage(buffer).append( + element: .arcTo, + points: [tangent1End.x, tangent1End.y, tangent2End.x, tangent2End.y, radius], + userInfo: &transform + ) + } } + /// Appends another path value to this path. + /// + /// If the `path` parameter is a non-empty empty path, its elements + /// are appended in order to this path. Afterward, the start point + /// and current point of this path are those of the last subpath in + /// the `path` parameter. + /// + /// - Parameters: + /// - path: The path to add. + /// - transform: An affine transform to apply to the path + /// parameter before adding to this path. Defaults to the + /// identity transform if not specified. + /// public mutating func addPath( _ path: Path, transform: CGAffineTransform = .identity ) { - // FIXME: Use RB instead of CG if case .empty = storage { self = path.applying(transform) - } else if !path.isEmpty { - #if canImport(CoreGraphics) - let result = cgPath.mutableCopy()! - result.addPath(path.cgPath, transform: transform) - self = Path(result) - #else - _openSwiftUIPlatformUnimplementedFailure() - #endif + return + } + guard !path.isEmpty else { return } + withMutableBuffer { buffer in + if transform.isIdentity { + path.append(to: buffer) + } else { + let storage = ORBPath.Storage(buffer) + var transform = transform + storage.append(element: .transformed, points: nil, userInfo: &transform) + path.append(to: buffer) + storage.append(element: .end, points: nil, userInfo: nil) + } } } + /// Returns the last point in the path, or nil if the path contains + /// no points. public var currentPoint: CGPoint? { - get { _openSwiftUIUnimplementedFailure() } + switch storage { + case let .rect(rect): + return rect.origin + case .empty: + return nil + default: + let path = cgPath + return path.isEmpty ? nil : path.currentPoint + } } - @available(OpenSwiftUI_v5_0, *) - public func normalized(eoFill: Bool = true) -> Path { - _openSwiftUIUnimplementedFailure() + package func dilatedGlyphPath(with size: CGSize) -> Path { + guard size != .zero else { return self } + return Path(box: PathBox { buffer in + let storage = ORBPath.Storage(buffer) + storage.append(element: .dilateGlyph, points: [size.width, size.height], userInfo: nil) + append(to: buffer) + storage.append(element: .end, points: nil, userInfo: nil) + }) } + /// Returns a new weakly-simple copy of this path. + /// + /// - Parameters: + /// - eoFill: Whether to use the even-odd rule for determining + /// which areas to treat as the interior of the paths (if true), + /// or the non-zero rule (if false). + /// - Returns: A new path. + /// + /// The returned path is a weakly-simple path, has no + /// self-intersections, and has a normalized orientation. The + /// result of filling this path using either even-odd or non-zero + /// fill rules is identical. + @available(OpenSwiftUI_v5_0, *) + public func normalized(eoFill: Bool = true) -> Path { + Path(box: PathBox { buffer in + let storage = ORBPath.Storage(buffer) + var info = (false, eoFill) + storage.append(element: .boolean, points: nil, userInfo: &info) + append(to: buffer) + storage.append(element: .end, points: nil, userInfo: nil) + }) + } + + // FIXME: Add a enum type for op instead of op + @inline(__always) + private func booleanOperation(_ other: Path, eoFill: Bool, op: UInt8) -> Path { + Path(box: PathBox { buffer in + let storage = ORBPath.Storage(buffer) + var info = (op, eoFill) + storage.append(element: .boolean, points: nil, userInfo: &info) + append(to: buffer) + storage.append(element: .booleanSeparator, points: nil, userInfo: nil) + other.append(to: buffer) + storage.append(element: .end, points: nil, userInfo: nil) + }) + } + + /// Returns a new path with filled regions common to both paths. + /// + /// - Parameters: + /// - other: The path to intersect. + /// - eoFill: Whether to use the even-odd rule for determining + /// which areas to treat as the interior of the paths (if true), + /// or the non-zero rule (if false). + /// - Returns: A new path. + /// + /// The filled region of the resulting path is the overlapping area + /// of the filled region of both paths. This can be used to clip + /// the fill of a path to a mask. + /// + /// Any unclosed subpaths in either path are assumed to be closed. + /// The result of filling this path using either even-odd or + /// non-zero fill rules is identical. @available(OpenSwiftUI_v5_0, *) public func intersection( _ other: Path, eoFill: Bool = false ) -> Path { - _openSwiftUIUnimplementedFailure() + booleanOperation(other, eoFill: eoFill, op: 1) } + /// Returns a new path with filled regions in either this path or + /// the given path. + /// + /// - Parameters: + /// - other: The path to union. + /// - eoFill: Whether to use the even-odd rule for determining + /// which areas to treat as the interior of the paths (if true), + /// or the non-zero rule (if false). + /// - Returns: A new path. + /// + /// The filled region of resulting path is the combination of the + /// filled region of both paths added together. + /// + /// Any unclosed subpaths in either path are assumed to be closed. + /// The result of filling this path using either even-odd or + /// non-zero fill rules is identical. @available(OpenSwiftUI_v5_0, *) public func union( _ other: Path, eoFill: Bool = false ) -> Path { - _openSwiftUIUnimplementedFailure() + booleanOperation(other, eoFill: eoFill, op: 2) } + /// Returns a new path with filled regions from this path that are + /// not in the given path. + /// + /// - Parameters: + /// - other: The path to subtract. + /// - eoFill: Whether to use the even-odd rule for determining + /// which areas to treat as the interior of the paths (if true), + /// or the non-zero rule (if false). + /// - Returns: A new path. + /// + /// The filled region of the resulting path is the filled region of + /// this path with the filled region `other` removed from it. + /// + /// Any unclosed subpaths in either path are assumed to be closed. + /// The result of filling this path using either even-odd or + /// non-zero fill rules is identical. @available(OpenSwiftUI_v5_0, *) public func subtracting( _ other: Path, eoFill: Bool = false ) -> Path { - _openSwiftUIUnimplementedFailure() + booleanOperation(other, eoFill: eoFill, op: 3) } + /// Returns a new path with filled regions either from this path or + /// the given path, but not in both. + /// + /// - Parameters: + /// - other: The path to difference. + /// - eoFill: Whether to use the even-odd rule for determining + /// which areas to treat as the interior of the paths (if true), + /// or the non-zero rule (if false). + /// - Returns: A new path. + /// + /// The filled region of the resulting path is the filled region + /// contained in either this path or `other`, but not both. + /// + /// Any unclosed subpaths in either path are assumed to be closed. + /// The result of filling this path using either even-odd or + /// non-zero fill rules is identical. @available(OpenSwiftUI_v5_0, *) public func symmetricDifference( _ other: Path, eoFill: Bool = false ) -> Path { - _openSwiftUIUnimplementedFailure() + booleanOperation(other, eoFill: eoFill, op: 4) } + /// Returns a new path with a line from this path that overlaps the + /// filled regions of the given path. + /// + /// - Parameters: + /// - other: The path to intersect. + /// - eoFill: Whether to use the even-odd rule for determining + /// which areas to treat as the interior of the paths (if true), + /// or the non-zero rule (if false). + /// - Returns: A new path. + /// + /// The line of the resulting path is the line of this path that + /// overlaps the filled region of `other`. + /// + /// Intersected subpaths that are clipped create open subpaths. + /// Closed subpaths that do not intersect `other` remain closed. @available(OpenSwiftUI_v5_0, *) public func lineIntersection( _ other: Path, eoFill: Bool = false ) -> Path { - _openSwiftUIUnimplementedFailure() + booleanOperation(other, eoFill: eoFill, op: 5) } + /// Returns a new path with a line from this path that does not + /// overlap the filled region of the given path. + /// + /// - Parameters: + /// - other: The path to subtract. + /// - eoFill: Whether to use the even-odd rule for determining + /// which areas to treat as the interior of the paths (if true), + /// or the non-zero rule (if false). + /// - Returns: A new path. + /// + /// The line of the resulting path is the line of this path that + /// does not overlap the filled region of `other`. + /// + /// Intersected subpaths that are clipped create open subpaths. + /// Closed subpaths that do not intersect `other` remain closed. @available(OpenSwiftUI_v5_0, *) public func lineSubtraction( _ other: Path, eoFill: Bool = false ) -> Path { - _openSwiftUIUnimplementedFailure() + booleanOperation(other, eoFill: eoFill, op: 6) } package mutating func formTrivialUnion(_ path: Path) { - // TBA guard !path.isEmpty else { return } @@ -951,6 +1674,14 @@ extension Path { addPath(path) } + /// Returns a path constructed by applying the transform to all + /// points of the path. + /// + /// - Parameter transform: An affine transform to apply to the path. + /// + /// - Returns: a new copy of the path with the transform applied to + /// all points. + /// public func applying(_ transform: CGAffineTransform) -> Path { guard !transform.isIdentity else { return self @@ -965,47 +1696,54 @@ extension Path { case let .roundedRect(fixedRoundedRect) where transform.isRectilinear: return Path(storage: .roundedRect(fixedRoundedRect.applying(transform))) case .stroked, .trimmed: - _openSwiftUIUnreachableCode() + preconditionFailure("obsolete") default: - // TBA - #if canImport(CoreGraphics) - var transform = transform - return Path(cgPath.copy(using: &transform)!) - #else - _openSwiftUIPlatformUnimplementedFailure() - #endif + return Path(box: PathBox { buffer in + let storage = ORBPath.Storage(buffer) + var transform = transform + storage.append(element: .transformed, points: nil, userInfo: &transform) + append(to: buffer) + storage.append(element: .end, points: nil, userInfo: nil) + }) } } + /// Returns a path constructed by translating all its points. + /// + /// - Parameters: + /// - dx: The offset to apply in the horizontal axis. + /// - dy: The offset to apply in the vertical axis. + /// + /// - Returns: a new copy of the path with the offset applied to + /// all points. + /// public func offsetBy( dx: CGFloat, dy: CGFloat ) -> Path { - _openSwiftUIUnimplementedFailure() + guard dx != 0 || dy != 0 else { + return self + } + return applying(CGAffineTransform(translationX: dx, y: dy)) } - func mapPoints(_ body: (inout [CGPoint]) -> ()) -> Path { - // TBA + package func mapPoints(_ body: (inout [CGPoint]) -> ()) -> Path { switch storage { case .empty: - return self + return Path() case let .rect(rect): var points = rect.cornerPoints body(&points) if let rect = CGRect(exactCornerPoints: points) { return Path(rect) } - #if canImport(CoreGraphics) - let result = CGMutablePath() - result.move(to: points[0]) - for point in points[1..<4] { - result.addLine(to: point) + var path = Path() + path.move(to: points[0]) + for index in 1 ..< 4 { + path.addLine(to: points[index]) } - result.closeSubpath() - return Path(result) - #else - _openSwiftUIPlatformUnimplementedFailure() - #endif + path.closeSubpath() + return path case let .ellipse(rect): var points = rect.cornerPoints body(&points) @@ -1026,21 +1764,21 @@ extension Path { style: rect.style ))) } - case .stroked, .trimmed: - _openSwiftUIUnreachableCode() - case .path: + default: break } - #if canImport(CoreGraphics) var points: [CGPoint] = [] forEach { element in switch element { case let .move(point), let .line(point): points.append(point) case let .quadCurve(point, control): - points.append(contentsOf: [point, control]) + points.append(point) + points.append(control) case let .curve(point, control1, control2): - points.append(contentsOf: [point, control1, control2]) + points.append(point) + points.append(control1) + points.append(control2) case .closeSubpath: break } @@ -1066,10 +1804,7 @@ extension Path { result.closeSubpath() } } - return Path(result) - #else - _openSwiftUIPlatformUnimplementedFailure() - #endif + return Path(result as CGPath) } } @@ -1088,61 +1823,47 @@ private func ellipseContains(in rect: CGRect, contains point: CGPoint) -> Bool { return dx * dx + dy * dy < radius * radius } -// MARK: - RenderBox +// MARK: - ORB Helper private let temporaryPathCallbacks: UnsafePointer = { let pointer = UnsafeMutablePointer.allocate(capacity: 1) - var callbacks = ORBPath.empty.callbacks.pointee - callbacks.retain = { _ in + pointer.initialize(to: .init()) + pointer.pointee.retain = { _ in _openSwiftUIUnreachableCode() } - callbacks.release = { _ in + pointer.pointee.release = { _ in _openSwiftUIUnreachableCode() } - callbacks.apply = { object, info, callback in - let storage = unsafeBitCast(object, to: ORBPath.Storage.self) - return storage.apply(info: info, callback: callback) + pointer.pointee.apply = { object, info, callback in + ORBPath.Storage(object).apply(info: info, callback: callback) } - callbacks.isEqual = { lhs, rhs in - let lhs = unsafeBitCast(lhs, to: ORBPath.Storage.self) - let rhs = unsafeBitCast(rhs, to: ORBPath.Storage.self) - return lhs.isEqual(to: rhs) + pointer.pointee.isEqual = { lhs, rhs in + ORBPath.Storage(lhs).isEqual(to: ORBPath.Storage(rhs)) } - callbacks.isEmpty = { object in - let storage = unsafeBitCast(object, to: ORBPath.Storage.self) - return storage.isEmpty + pointer.pointee.isEmpty = { object in + ORBPath.Storage(object).isEmpty } - callbacks.isSingleElement = { object in - let storage = unsafeBitCast(object, to: ORBPath.Storage.self) - return storage.isSingleElement + pointer.pointee.isSingleElement = { object in + ORBPath.Storage(object).isSingleElement } - callbacks.boundingRect = { object in - let storage = unsafeBitCast(object, to: ORBPath.Storage.self) - return storage.boundingRect + pointer.pointee.boundingRect = { object in + ORBPath.Storage(object).boundingRect } - callbacks.cgPath = { object in - let storage = unsafeBitCast(object, to: ORBPath.Storage.self) - let cgPath = storage.cgPath - return cgPath.map { .passUnretained($0) } + pointer.pointee.cgPath = { object in + ORBPath.Storage(object).cgPath.map { .passUnretained($0) } } - pointer.initialize(to: callbacks) return UnsafePointer(pointer) }() extension ORBPath { static func withTemporaryPath( do body: (ORBPath) -> R, - builder: (UnsafeMutableRawPointer) -> () + builder: (UnsafeMutableRawPointer) -> Void ) -> R { - return withUnsafeTemporaryAllocation( - of: UInt8.self, - capacity: 128 - ) { bufferPointer in - let pointer = UnsafeMutableRawBufferPointer( - mutating: UnsafeRawBufferPointer(bufferPointer) - ).baseAddress! - let storage: ORBPath.Storage = unsafeBitCast(pointer, to: ORBPath.Storage.self) - storage.initialize(capacity: 128, source: nil) + withUnsafeTemporaryAllocation(of: UInt8.self, capacity: 128) { bufferPointer in + let pointer = UnsafeMutableRawPointer(bufferPointer.baseAddress!) + let storage = ORBPath.Storage(pointer) + storage.initialize(capacity: bufferPointer.count, source: nil) builder(pointer) let path = ORBPath( storage: storage, @@ -1154,3 +1875,10 @@ extension ORBPath { } } } + +extension ORBPath.Storage { + @inline(__always) + init(@_nonEphemeral _ pointer: UnsafeRawPointer) { + self.init(OpaquePointer(pointer)) + } +} diff --git a/Sources/OpenSwiftUICore/Shape/RoundedCornerStyle.swift b/Sources/OpenSwiftUICore/Shape/RoundedCornerStyle.swift index 50f6bab3c..4370594d0 100644 --- a/Sources/OpenSwiftUICore/Shape/RoundedCornerStyle.swift +++ b/Sources/OpenSwiftUICore/Shape/RoundedCornerStyle.swift @@ -73,21 +73,19 @@ package struct FixedRoundedRect: Equatable { min(min(rect.width, rect.height) / 2, cornerSize.width) } - #if canImport(Darwin) package func withTemporaryPath(_ body: (ORBPath) -> R) -> R { ORBPath.withTemporaryPath(do: body) { pointer in - let storage = unsafeBitCast(pointer, to: ORBPath.Storage.self) - var points: [CGFloat] = [ + let points: [CGFloat] = [ rect.x, rect.y, - rect.width, - rect.height, + rect.size.width, + rect.size.height, cornerSize.width, - cornerSize.height + cornerSize.height, ] - storage.append( - element: style == .continuous ? .fixedRoundedRectContinuous : .fixedRoundedRectCircular, - points: &points, + ORBPath.Storage(pointer).append( + element: style == .circular ? .fixedRoundedRectCircular : .fixedRoundedRectContinuous, + points: points, userInfo: nil ) } @@ -98,7 +96,6 @@ package struct FixedRoundedRect: Equatable { path.contains(point: point, eoFill: false) } } - #endif package func applying(_ m: CGAffineTransform) -> FixedRoundedRect { let newRect = rect.applying(m) @@ -177,7 +174,6 @@ package struct FixedRoundedRect: Equatable { ) } - #if canImport(CoreGraphics) || !OPENSWIFTUI_CF_CGTYPES package var cgPath: CGPath { #if canImport(Darwin) let clamped = clampedCornerSize @@ -185,13 +181,12 @@ package struct FixedRoundedRect: Equatable { rect, clamped.width, clamped.height, - needsContinuousCorners ? .continuous : .circular + needsContinuousCorners ) #else _openSwiftUIPlatformUnimplementedFailure() #endif } - #endif @usableFromInline package static func == (a: FixedRoundedRect, b: FixedRoundedRect) -> Bool { diff --git a/Sources/OpenSwiftUICore/Util/Extension/CGRect+Extension.swift b/Sources/OpenSwiftUICore/Util/Extension/CGRect+Extension.swift index d9ae52928..441b2c553 100644 --- a/Sources/OpenSwiftUICore/Util/Extension/CGRect+Extension.swift +++ b/Sources/OpenSwiftUICore/Util/Extension/CGRect+Extension.swift @@ -149,9 +149,9 @@ extension CGRect { package var cornerPoints: [CGPoint] { [ origin, - origin.offsetBy(dx: width), - origin.offsetBy(dx: width, dy: height), - origin.offsetBy(dy: height), + CGPoint(x: origin.x + size.width, y: origin.y), + CGPoint(x: origin.x + size.width, y: origin.y + size.height), + CGPoint(x: origin.x, y: origin.y + size.height), ] } diff --git a/Sources/OpenSwiftUI_SPI/Util/PathData.h b/Sources/OpenSwiftUI_SPI/Util/PathData.h index 127e5b48b..c8bada36e 100644 --- a/Sources/OpenSwiftUI_SPI/Util/PathData.h +++ b/Sources/OpenSwiftUI_SPI/Util/PathData.h @@ -34,6 +34,14 @@ static inline PathData PathDataMakeEmpty(void) { return data; } +#if OPENSWIFTUI_TARGET_OS_DARWIN +static inline const ORBPathCallbacks *PathDataGetCGPathCallbacks(void) OPENSWIFTUI_SWIFT_NAME(getter:PathData.cgPathCallbacks()); + +static inline const ORBPathCallbacks *PathDataGetCGPathCallbacks(void) { + return &ORBPathCGPathCallbacks; +} +#endif + OPENSWIFTUI_ASSUME_NONNULL_END OPENSWIFTUI_IMPLICIT_BRIDGING_DISABLED diff --git a/Tests/OpenSwiftUICoreTests/Shape/Path/FixedRoundedRectTests.swift b/Tests/OpenSwiftUICoreTests/Shape/Path/FixedRoundedRectTests.swift index d6e172095..0849df741 100644 --- a/Tests/OpenSwiftUICoreTests/Shape/Path/FixedRoundedRectTests.swift +++ b/Tests/OpenSwiftUICoreTests/Shape/Path/FixedRoundedRectTests.swift @@ -221,6 +221,7 @@ struct FixedRoundedRectTests { (CGRect(x: 0, y: 0, width: 100, height: 100), 10.0, RoundedCornerStyle.circular), (CGRect(x: 10, y: 20, width: 80, height: 60), 15.0, RoundedCornerStyle.continuous), (CGRect(x: 0, y: 0, width: 50, height: 50), 5.0, RoundedCornerStyle.circular), + (CGRect(x: 10, y: 20, width: -80, height: -60), 15.0, RoundedCornerStyle.circular), ] as [(CGRect, CGFloat, RoundedCornerStyle)]) func withTemporaryPath(rect: CGRect, cornerRadius: CGFloat, style: RoundedCornerStyle) { let roundedRect = FixedRoundedRect(rect, cornerRadius: cornerRadius, style: style) diff --git a/Tests/OpenSwiftUICoreTests/Shape/Path/PathTests.swift b/Tests/OpenSwiftUICoreTests/Shape/Path/PathTests.swift index 79bfb78ce..2d9d1a633 100644 --- a/Tests/OpenSwiftUICoreTests/Shape/Path/PathTests.swift +++ b/Tests/OpenSwiftUICoreTests/Shape/Path/PathTests.swift @@ -47,6 +47,109 @@ struct PathTests { } #if canImport(CoreGraphics) + @Test + func appendingElementsPreservesControlsAndOriginalCopy() { + var path = Path() + path.move(to: CGPoint(x: 1, y: 2)) + path.addLine(to: CGPoint(x: 3, y: 4)) + let original = path + path.addQuadCurve(to: CGPoint(x: 7, y: 8), control: CGPoint(x: 5, y: 6)) + path.addCurve(to: CGPoint(x: 13, y: 14), control1: CGPoint(x: 9, y: 10), control2: CGPoint(x: 11, y: 12)) + path.closeSubpath() + + var elements: [Path.Element] = [] + path.forEach { elements.append($0) } + #expect(elements == [ + .move(to: CGPoint(x: 1, y: 2)), + .line(to: CGPoint(x: 3, y: 4)), + .quadCurve(to: CGPoint(x: 7, y: 8), control: CGPoint(x: 5, y: 6)), + .curve(to: CGPoint(x: 13, y: 14), control1: CGPoint(x: 9, y: 10), control2: CGPoint(x: 11, y: 12)), + .closeSubpath, + ]) + var originalElements: [Path.Element] = [] + original.forEach { originalElements.append($0) } + #expect(originalElements == [ + .move(to: CGPoint(x: 1, y: 2)), + .line(to: CGPoint(x: 3, y: 4)), + ]) + #expect(original.currentPoint == CGPoint(x: 3, y: 4)) + } + + enum BufferedShape: CaseIterable { + case rect, ellipse, roundedRect + } + + @Test(arguments: BufferedShape.allCases) + func bufferedShapesPreserveNegativeRectSizes(shape: BufferedShape) { + let rect = CGRect(x: 10, y: 20, width: -6, height: -8) + let transform = CGAffineTransform(translationX: 100, y: 200) + var path = Path() + // Keep the append operation on the buffer path. + path.move(to: CGPoint(x: 107, y: 216)) + switch shape { + case .rect: + path.addRect(rect, transform: transform) + case .ellipse: + path.addEllipse(in: rect, transform: transform) + case .roundedRect: + path.addRoundedRect(in: rect, cornerSize: CGSize(width: 1, height: 2), style: .circular, transform: transform) + } + + #expect(path.boundingRect == CGRect(x: 104, y: 212, width: 6, height: 8)) + } + + @Test + func transformedRoundedRectPreservesAsymmetricCorners() { + var path = Path() + path.addRoundedRect( + in: CGRect(x: 10, y: 20, width: 100, height: 100), + cornerRadii: RectangleCornerRadii(topLeading: 0, bottomLeading: 20, bottomTrailing: 30, topTrailing: 10), + style: .circular, + transform: CGAffineTransform(translationX: 100, y: 200) + ) + + #expect(path.boundingRect == CGRect(x: 110, y: 220, width: 100, height: 100)) + #expect(path.contains(CGPoint(x: 111, y: 221))) + #expect(!path.contains(CGPoint(x: 209, y: 221))) + #expect(path.contains(CGPoint(x: 205, y: 225))) + #expect(!path.contains(CGPoint(x: 111, y: 319))) + #expect(path.contains(CGPoint(x: 118, y: 312))) + #expect(!path.contains(CGPoint(x: 202, y: 312))) + #expect(path.contains(CGPoint(x: 200, y: 310))) + } + + @Test(arguments: [false, true]) + func transformedArcPreservesEndpoints(relative: Bool) throws { + var path = Path() + let transform = CGAffineTransform(translationX: 5, y: 7) + if relative { + path.addRelativeArc( + center: CGPoint(x: 20, y: 30), + radius: 10, + startAngle: .degrees(0), + delta: .degrees(90), + transform: transform + ) + } else { + path.addArc( + center: CGPoint(x: 20, y: 30), + radius: 10, + startAngle: .degrees(0), + endAngle: .degrees(90), + clockwise: false, + transform: transform + ) + } + + var elements: [Path.Element] = [] + path.forEach { elements.append($0) } + #expect(elements.first == .move(to: CGPoint(x: 35, y: 37))) + let end = try #require(path.currentPoint) + // Storage can encode arc angles as Float. + #expect(abs(end.x - 25) < 1e-6) + #expect(abs(end.y - 47) < 1e-6) + } + @Test(arguments: [false, true]) func fillRule(eoFill: Bool) { let outline = CGMutablePath() @@ -58,7 +161,7 @@ struct PathTests { #expect(path.contains(points[0], eoFill: eoFill)) #expect(path.contains(points[1], eoFill: eoFill) == !eoFill) #expect(!path.contains(points[2], eoFill: eoFill)) - #expect(path.contains(points: points, eoFill: eoFill).rawValue == (eoFill ? 0b001 : 0b011)) + #expect((path.contains(points: points, eoFill: eoFill).rawValue & 0b111) == (eoFill ? 0b001 : 0b011)) } @Test(arguments: [false, true]) diff --git a/Tests/OpenSwiftUICoreTests/Shape/Path/TrimmedPathTests.swift b/Tests/OpenSwiftUICoreTests/Shape/Path/TrimmedPathTests.swift index 34bd174a5..904e18e04 100644 --- a/Tests/OpenSwiftUICoreTests/Shape/Path/TrimmedPathTests.swift +++ b/Tests/OpenSwiftUICoreTests/Shape/Path/TrimmedPathTests.swift @@ -36,7 +36,7 @@ struct TrimmedPathTests { } #if canImport(CoreGraphics) - @Test(.disabled("Trim is not implemented yet")) + @Test func partialRectangle() { let trimmedPath = Path(CGRect(x: 0, y: 0, width: 100, height: 100)) .trimmedPath(from: 0.125, to: 0.375) From 5bc75bed39ea55e897311b236d0c1bba7645573a Mon Sep 17 00:00:00 2001 From: Kyle Date: Wed, 18 Nov 2026 01:31:58 +0800 Subject: [PATCH 08/22] feat(shape): complete ShapeType path classification Classify boxed paths via ORBPath.applyShape into filled rectangles, uniform rounded rectangles, stroked borders, and stroked path fallbacks. --- .../OpenSwiftUICore/Shape/ShapeLayer.swift | 172 ++++++++++++++++-- 1 file changed, 152 insertions(+), 20 deletions(-) diff --git a/Sources/OpenSwiftUICore/Shape/ShapeLayer.swift b/Sources/OpenSwiftUICore/Shape/ShapeLayer.swift index d5f0cb1c9..7a82124c3 100644 --- a/Sources/OpenSwiftUICore/Shape/ShapeLayer.swift +++ b/Sources/OpenSwiftUICore/Shape/ShapeLayer.swift @@ -3,14 +3,14 @@ // OpenSwiftUICore // // Audited for 6.5.4 -// Status: WIP (Path classification and GraphicsContext rendering) +// Status: WIP (GraphicsContext rendering) // ID: E19F490D25D5E0EC8A24903AF958E341 (SwiftUICore) import Foundation import OpenQuartzCoreShims +import OpenRenderBoxShims import OpenSwiftUI_SPI import UIFoundation_Private -// import OpenRenderBoxShims // MARK: - ColorShapeLayer @@ -873,13 +873,13 @@ extension DisplayList.ViewUpdater { } } -// MARK: - ShapeType [WIP] +// MARK: - ShapeType enum ShapeType { + case empty case rect(CGRect, radius: CGFloat, style: RoundedCornerStyle) case rectBorder(CGRect, radius: CGFloat, style: RoundedCornerStyle, lineWidth: CGFloat) case strokedPath(Path, style: StrokeStyle) - case empty case other init(_ path: Path) { @@ -906,24 +906,156 @@ enum ShapeType { ) case .stroked, .trimmed: self = .other - case .path: - // TODO: Classify RenderBox paths with initFromFilled. + case let .path(box): self = .other + struct Context { + var type: UnsafeMutablePointer + } + withUnsafeMutablePointer(to: &self) { type in + var context = Context(type: type) + withUnsafeMutablePointer(to: &context) { ptr in + box.withRBPath { rbPath in + _ = rbPath.applyShape(allowLine: true, info: ptr) { ptr, type, shape in + ptr.assumingMemoryBound(to: Context.self) + .pointee.type.pointee + .initFromFilled(type: type, shape: shape) + } + } + } + } } } -// private func initFromFilled( -// type: ORBPathShapeType, -// shape: UnsafePointer -// ) { -// _openSwiftUIUnimplementedFailure() -// } -// -// private func initFromStroked( -// type: ORBPathShapeType, -// shape: UnsafePointer, -// style: StrokeStyle -// ) { -// _openSwiftUIUnimplementedFailure() -// } + private mutating func initFromFilled( + type: ORBPathShapeType, + shape: UnsafePointer + ) { + switch type { + case .rect: + let rect = shape.pointee.rect + guard rect.transform.isRectilinear else { + return + } + self = .rect( + rect.rect.applying(rect.transform), + radius: 0.0, + style: .circular + ) + case .fixedRoundedRect: + let roundedRect = shape.pointee.fixedRoundedRect + guard roundedRect.transform.isRectilinear else { + return + } + let rect = roundedRect.rect.applying(roundedRect.transform) + let cornerSize = roundedRect.cornerSize.applying(roundedRect.transform) + guard cornerSize.width == cornerSize.height else { + return + } + self = .rect( + rect, + radius: min(min(rect.width, rect.height) / 2, cornerSize.width), + style: roundedRect.style == .continuous ? .continuous : .circular + ) + case .stroked: + let stroked = shape.pointee.stroked + guard !stroked.path.isEmpty else { + self = .empty + return + } + var dash: [CGFloat] = [] + for i in 0 ..< Int(stroked.style.dashCount) { + dash.append(stroked.style.dash![i]) + } + let style = StrokeStyle( + lineWidth: stroked.style.lineWidth, + lineCap: CGLineCap(rawValue: stroked.style.lineCap) ?? .butt, + lineJoin: CGLineJoin(rawValue: stroked.style.lineJoin) ?? .miter, + miterLimit: stroked.style.miterLimit, + dash: dash, + dashPhase: stroked.style.dashPhase + ) + struct Context { + var type: UnsafeMutablePointer + var style: StrokeStyle + } + withUnsafeMutablePointer(to: &self) { type in + var context = Context(type: type, style: style) + withUnsafeMutablePointer(to: &context) { ptr in + _ = stroked.path.applyShape(allowLine: true, info: ptr) { ptr, type, shape in + let context = ptr.assumingMemoryBound(to: Context.self) + context.pointee.type.pointee.initFromStroked( + type: type, + shape: shape, + style: context.pointee.style + ) + } + } + } + guard case .other = self else { + return + } + self = .strokedPath(Path(stroked.path), style: style) + default: + return + } + } + + private mutating func initFromStroked( + type: ORBPathShapeType, + shape: UnsafePointer, + style: StrokeStyle + ) { + guard style.dash.isEmpty else { + return + } + switch type { + case .rect: + let rect = shape.pointee.rect + guard style.lineJoin == .miter, + style.miterLimit > 1.4142, + rect.transform.isIdentity + else { + return + } + self = .rectBorder( + rect.rect.insetBy(dx: -style.lineWidth / 2, dy: -style.lineWidth / 2), + radius: 0, + style: .circular, + lineWidth: style.lineWidth + ) + case .ellipse: + let ellipse = shape.pointee.ellipse + guard ellipse.rect.width == ellipse.rect.height, + ellipse.transform.isIdentity + else { + return + } + let baseRadius = ellipse.rect.width / 2 + self = .rectBorder( + ellipse.rect.insetBy(dx: -style.lineWidth / 2, dy: -style.lineWidth / 2), + radius: baseRadius == 0 ? 0 : baseRadius + style.lineWidth / 2, + style: .circular, + lineWidth: style.lineWidth + ) + case .fixedRoundedRect: + let roundedRect = shape.pointee.fixedRoundedRect + guard roundedRect.cornerSize.width == roundedRect.cornerSize.height, + roundedRect.transform.isIdentity + else { + return + } + let baseRadius = min( + min(roundedRect.rect.width, roundedRect.rect.height) / 2, + roundedRect.cornerSize.width + ) + self = .rectBorder( + roundedRect.rect.insetBy(dx: -style.lineWidth / 2, dy: -style.lineWidth / 2), + radius: baseRadius == 0 ? 0 : baseRadius + style.lineWidth / 2, + style: roundedRect.style == .continuous ? .continuous : .circular, + lineWidth: style.lineWidth + ) + default: + return + } + } } From df19da3d49e4f486f26d77ab05ba33f80cf72c1c Mon Sep 17 00:00:00 2001 From: Kyle Date: Sun, 22 Nov 2026 00:18:55 +0800 Subject: [PATCH 09/22] chore: update dependency --- Example/Tuist/Package.resolved | 2 +- Package.resolved | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/Example/Tuist/Package.resolved b/Example/Tuist/Package.resolved index 2b24e979e..ecf1dd93b 100644 --- a/Example/Tuist/Package.resolved +++ b/Example/Tuist/Package.resolved @@ -25,7 +25,7 @@ "location" : "https://github.com/OpenSwiftUIProject/OpenCoreGraphics", "state" : { "branch" : "main", - "revision" : "3440823f9b2580dcd3795373214521efc37628b8" + "revision" : "9f247e283862ce3e2008d0156702643e72693adb" } }, { diff --git a/Package.resolved b/Package.resolved index de5d0a24f..35aa5554c 100644 --- a/Package.resolved +++ b/Package.resolved @@ -7,7 +7,7 @@ "location" : "https://github.com/OpenSwiftUIProject/DarwinPrivateFrameworks.git", "state" : { "branch" : "main", - "revision" : "5a8c0cb54ae37cccad0e222b51f4d7bee928b709" + "revision" : "600fcdfb9462e985d5fef429daf236e2de3104db" } }, { @@ -25,7 +25,7 @@ "location" : "https://github.com/OpenSwiftUIProject/OpenCoreGraphics", "state" : { "branch" : "main", - "revision" : "3440823f9b2580dcd3795373214521efc37628b8" + "revision" : "9f247e283862ce3e2008d0156702643e72693adb" } }, { @@ -43,7 +43,7 @@ "location" : "https://github.com/OpenSwiftUIProject/OpenRenderBox", "state" : { "branch" : "main", - "revision" : "0bb9980ad7aab62231913c659d1909a95e50c5b4" + "revision" : "49db676067daf36c6b2c6cec9cb7a4595979f4ae" } }, { @@ -67,7 +67,7 @@ { "identity" : "symbollocator", "kind" : "remoteSourceControl", - "location" : "https://github.com/OpenSwiftUIProject/SymbolLocator.git", + "location" : "https://github.com/OpenSwiftUIProject/SymbolLocator", "state" : { "revision" : "546053c03f282df1a8270853da6692e1b078be09", "version" : "0.2.1" From eb4590918eb02e4ae52280ddbdcdf5492fd76c49 Mon Sep 17 00:00:00 2001 From: Kyle Date: Sun, 22 Nov 2026 01:56:18 +0800 Subject: [PATCH 10/22] feat(shape): add StrokeStyle(ORBPathStrokeStyle) initializer Initialize StrokeStyle directly from ORBPathStrokeStyle for stroked shape classification, and update DarwinPrivateFrameworks and OpenRenderBox revisions. --- Package.resolved | 4 +-- .../OpenSwiftUICore/Shape/ShapeLayer.swift | 13 +--------- .../OpenSwiftUICore/Shape/StrokeStyle.swift | 25 +++++++++++++++++++ 3 files changed, 28 insertions(+), 14 deletions(-) diff --git a/Package.resolved b/Package.resolved index 35aa5554c..b1c5e20ea 100644 --- a/Package.resolved +++ b/Package.resolved @@ -7,7 +7,7 @@ "location" : "https://github.com/OpenSwiftUIProject/DarwinPrivateFrameworks.git", "state" : { "branch" : "main", - "revision" : "600fcdfb9462e985d5fef429daf236e2de3104db" + "revision" : "7b1da8b32736a879afd3964a13085c076eaa1221" } }, { @@ -43,7 +43,7 @@ "location" : "https://github.com/OpenSwiftUIProject/OpenRenderBox", "state" : { "branch" : "main", - "revision" : "49db676067daf36c6b2c6cec9cb7a4595979f4ae" + "revision" : "3c97339a194d3e02f31825dd6da934730449611b" } }, { diff --git a/Sources/OpenSwiftUICore/Shape/ShapeLayer.swift b/Sources/OpenSwiftUICore/Shape/ShapeLayer.swift index 7a82124c3..168d35c8d 100644 --- a/Sources/OpenSwiftUICore/Shape/ShapeLayer.swift +++ b/Sources/OpenSwiftUICore/Shape/ShapeLayer.swift @@ -962,18 +962,7 @@ enum ShapeType { self = .empty return } - var dash: [CGFloat] = [] - for i in 0 ..< Int(stroked.style.dashCount) { - dash.append(stroked.style.dash![i]) - } - let style = StrokeStyle( - lineWidth: stroked.style.lineWidth, - lineCap: CGLineCap(rawValue: stroked.style.lineCap) ?? .butt, - lineJoin: CGLineJoin(rawValue: stroked.style.lineJoin) ?? .miter, - miterLimit: stroked.style.miterLimit, - dash: dash, - dashPhase: stroked.style.dashPhase - ) + let style = StrokeStyle(stroked.style) struct Context { var type: UnsafeMutablePointer var style: StrokeStyle diff --git a/Sources/OpenSwiftUICore/Shape/StrokeStyle.swift b/Sources/OpenSwiftUICore/Shape/StrokeStyle.swift index 86da0b12c..e500d69b8 100644 --- a/Sources/OpenSwiftUICore/Shape/StrokeStyle.swift +++ b/Sources/OpenSwiftUICore/Shape/StrokeStyle.swift @@ -7,6 +7,9 @@ public import Foundation public import OpenCoreGraphicsShims +package import OpenRenderBoxShims + +// MARK: - StrokeStyle /// The characteristics of a stroke that traces a path. @available(OpenSwiftUI_v1_0, *) @@ -52,6 +55,8 @@ public struct StrokeStyle: Equatable { } } +// MARK: - StrokeStyle + Animatable + @available(OpenSwiftUI_v1_0, *) extension StrokeStyle: Animatable { public var animatableData: AnimatablePair> { @@ -65,3 +70,23 @@ extension StrokeStyle: Animatable { } } } + +// MARK: - StrokeStyle + ORB + +extension StrokeStyle { + @inline(__always) + package init(_ style: ORBPathStrokeStyle) { + var dash: [CGFloat] = [] + for i in 0 ..< Int(style.dashCount) { + dash.append(style.dash![i]) + } + self.init( + lineWidth: style.lineWidth, + lineCap: style.lineCap, + lineJoin: style.lineJoin, + miterLimit: style.miterLimit, + dash: dash, + dashPhase: style.dashPhase + ) + } +} From e2f109f4b3918f8ce914aa8e69e7bd33474385b9 Mon Sep 17 00:00:00 2001 From: Kyle Date: Sun, 22 Nov 2026 03:18:03 +0800 Subject: [PATCH 11/22] refactor(path): use ORBPath.Callbacks.cgPath directly Remove PathDataGetCGPathCallbacks and use ORBPath.Callbacks.cgPath directly in PathBox.withRBPath, and update DarwinPrivateFrameworks and OpenRenderBox revisions. --- Package.resolved | 4 ++-- Sources/OpenSwiftUICore/Shape/Path.swift | 2 +- Sources/OpenSwiftUI_SPI/Util/PathData.h | 8 -------- 3 files changed, 3 insertions(+), 11 deletions(-) diff --git a/Package.resolved b/Package.resolved index b1c5e20ea..f538b09f7 100644 --- a/Package.resolved +++ b/Package.resolved @@ -7,7 +7,7 @@ "location" : "https://github.com/OpenSwiftUIProject/DarwinPrivateFrameworks.git", "state" : { "branch" : "main", - "revision" : "7b1da8b32736a879afd3964a13085c076eaa1221" + "revision" : "211a9a3d6c2021dd3e8953892131abe06b26bb6f" } }, { @@ -43,7 +43,7 @@ "location" : "https://github.com/OpenSwiftUIProject/OpenRenderBox", "state" : { "branch" : "main", - "revision" : "3c97339a194d3e02f31825dd6da934730449611b" + "revision" : "f0c4861998d95d14a4b159ef7845d1d8e469f3e6" } }, { diff --git a/Sources/OpenSwiftUICore/Shape/Path.swift b/Sources/OpenSwiftUICore/Shape/Path.swift index fd1756f13..92e7ea5b2 100644 --- a/Sources/OpenSwiftUICore/Shape/Path.swift +++ b/Sources/OpenSwiftUICore/Shape/Path.swift @@ -171,7 +171,7 @@ public struct Path: Equatable, LosslessStringConvertible, @unchecked Sendable { case .cgPath: path = ORBPath( storage: ORBPath.Storage(data.cgPath!.toOpaque()), - callbacks: PathData.cgPathCallbacks + callbacks: ORBPath.Callbacks.cgPath ) case .rbPath: path = data.rbPath diff --git a/Sources/OpenSwiftUI_SPI/Util/PathData.h b/Sources/OpenSwiftUI_SPI/Util/PathData.h index c8bada36e..127e5b48b 100644 --- a/Sources/OpenSwiftUI_SPI/Util/PathData.h +++ b/Sources/OpenSwiftUI_SPI/Util/PathData.h @@ -34,14 +34,6 @@ static inline PathData PathDataMakeEmpty(void) { return data; } -#if OPENSWIFTUI_TARGET_OS_DARWIN -static inline const ORBPathCallbacks *PathDataGetCGPathCallbacks(void) OPENSWIFTUI_SWIFT_NAME(getter:PathData.cgPathCallbacks()); - -static inline const ORBPathCallbacks *PathDataGetCGPathCallbacks(void) { - return &ORBPathCGPathCallbacks; -} -#endif - OPENSWIFTUI_ASSUME_NONNULL_END OPENSWIFTUI_IMPLICIT_BRIDGING_DISABLED From a98f16e51118d694de92fe6823a74e9e6123f93f Mon Sep 17 00:00:00 2001 From: Kyle Date: Sun, 22 Nov 2026 14:08:21 +0800 Subject: [PATCH 12/22] fix(core): bridge Data and CFData on non-Darwin platforms --- Sources/OpenSwiftUICore/Shape/Path.swift | 4 +- .../Util/Extension/Data+Extension.swift | 32 ++++++++++++ .../Shape/Path/PathTests.swift | 25 ++++++++++ .../Util/Extension/Data+ExtensionTests.swift | 50 +++++++++++++++++++ 4 files changed, 109 insertions(+), 2 deletions(-) create mode 100644 Sources/OpenSwiftUICore/Util/Extension/Data+Extension.swift create mode 100644 Tests/OpenSwiftUICoreTests/Util/Extension/Data+ExtensionTests.swift diff --git a/Sources/OpenSwiftUICore/Shape/Path.swift b/Sources/OpenSwiftUICore/Shape/Path.swift index 92e7ea5b2..c116b0e94 100644 --- a/Sources/OpenSwiftUICore/Shape/Path.swift +++ b/Sources/OpenSwiftUICore/Shape/Path.swift @@ -854,7 +854,7 @@ extension Path: ProtobufMessage { let rbPath = retainRBPath() defer { rbPath.release() } if let data = rbPath.data { - encoder.dataField(4, data as Data) + encoder.dataField(4, Data(cfData: data)) } } } @@ -871,7 +871,7 @@ extension Path: ProtobufMessage { path.storage = .roundedRect(try decoder.messageField(field)) case 4: let data = try decoder.dataField(field) - path.storage = .path(PathBox(takingPath: ORBPath(data: data as CFData))) + path.storage = .path(PathBox(takingPath: ORBPath(data: data.cfData))) default: try decoder.skipField(field) } diff --git a/Sources/OpenSwiftUICore/Util/Extension/Data+Extension.swift b/Sources/OpenSwiftUICore/Util/Extension/Data+Extension.swift new file mode 100644 index 000000000..a227b4a8e --- /dev/null +++ b/Sources/OpenSwiftUICore/Util/Extension/Data+Extension.swift @@ -0,0 +1,32 @@ +// +// Data+Extension.swift +// OpenSwiftUICore + +package import CoreFoundation +package import Foundation + +/* OpenSwiftUI Addition Begin */ + +// MARK: - Data + CFData + +extension Data { + @inline(__always) + package init(cfData: CFData) { + #if canImport(Darwin) + self = cfData as Data + #else + self = unsafeBitCast(cfData, to: NSData.self) as Data + #endif + } + + @inline(__always) + package var cfData: CFData { + #if canImport(Darwin) + self as CFData + #else + unsafeBitCast(self as NSData, to: CFData.self) + #endif + } +} + +/* OpenSwiftUI Addition End */ diff --git a/Tests/OpenSwiftUICoreTests/Shape/Path/PathTests.swift b/Tests/OpenSwiftUICoreTests/Shape/Path/PathTests.swift index 2d9d1a633..b50d3e174 100644 --- a/Tests/OpenSwiftUICoreTests/Shape/Path/PathTests.swift +++ b/Tests/OpenSwiftUICoreTests/Shape/Path/PathTests.swift @@ -46,6 +46,31 @@ struct PathTests { #expect(path.boundingRect == CGRect(x: 1, y: 2, width: 10, height: 20)) } + @Test + func protobufRoundTrip() throws { + var customPath = Path() + customPath.move(to: CGPoint(x: 1, y: 2)) + customPath.addLine(to: CGPoint(x: 3, y: 4)) + customPath.addQuadCurve(to: CGPoint(x: 7, y: 8), control: CGPoint(x: 5, y: 6)) + customPath.addCurve(to: CGPoint(x: 13, y: 14), control1: CGPoint(x: 9, y: 10), control2: CGPoint(x: 11, y: 12)) + customPath.closeSubpath() + + let cases: [Path] = [ + Path(), + Path(CGRect(x: 1, y: 2, width: 30, height: 40)), + Path(ellipseIn: CGRect(x: 3, y: 4, width: 20, height: 10)), + Path(roundedRect: CGRect(x: 0, y: 0, width: 50, height: 30), cornerSize: CGSize(width: 6, height: 8), style: .continuous), + customPath, + ] + + for original in cases { + let encoded = try ProtobufEncoder.encoding(original) + var decoder = ProtobufDecoder(encoded) + let decoded = try Path(from: &decoder) + #expect(decoded == original) + } + } + #if canImport(CoreGraphics) @Test func appendingElementsPreservesControlsAndOriginalCopy() { diff --git a/Tests/OpenSwiftUICoreTests/Util/Extension/Data+ExtensionTests.swift b/Tests/OpenSwiftUICoreTests/Util/Extension/Data+ExtensionTests.swift new file mode 100644 index 000000000..cd0351125 --- /dev/null +++ b/Tests/OpenSwiftUICoreTests/Util/Extension/Data+ExtensionTests.swift @@ -0,0 +1,50 @@ +// +// Data+ExtensionTests.swift +// OpenSwiftUICoreTests + +import CoreFoundation +import Foundation +@testable import OpenSwiftUICore +import Testing + +struct Data_ExtensionTests { + @Test + func roundTripAcrossRepresentations() { + let full = Data((0..<64).map { UInt8($0 + 10) }) + let cases: [Data] = [ + Data(), + Data([1, 2, 3, 4]), + Data((0..<128).map { UInt8($0) }), + full[7..<39], + ] + + for expected in cases { + let cfData = expected.cfData + #expect(CFGetTypeID(cfData) == CFDataGetTypeID()) + let length = CFDataGetLength(cfData) + #expect(length == expected.count) + + var extracted = [UInt8](repeating: 0, count: length) + if length > 0 { + CFDataGetBytes(cfData, CFRange(location: 0, length: length), &extracted) + } + #expect(extracted == Array(expected)) + #expect(Data(cfData: cfData) == expected) + } + } + + @Test + func initFromCFDataPreservesValueSemantics() throws { + let bytes: [UInt8] = [10, 20, 30, 40] + let immutable = try #require(CFDataCreate(nil, bytes, bytes.count)) + #expect(Array(Data(cfData: immutable)) == bytes) + + let mutable = try #require(CFDataCreateMutable(nil, 0)) + CFDataAppendBytes(mutable, bytes, bytes.count) + let bridged = Data(cfData: mutable) + if let mutablePtr = CFDataGetMutableBytePtr(mutable) { + mutablePtr[0] = 99 + } + #expect(Array(bridged) == bytes) + } +} From 8533f8d98105904fd242251d870ca942b5c9b46b Mon Sep 17 00:00:00 2001 From: Kyle Date: Sun, 22 Nov 2026 14:49:12 +0800 Subject: [PATCH 13/22] feat(path): support Path.cgPath on non-Darwin platforms Provide _CGPathCreateRoundedRect on non-Darwin platforms to enable FixedRoundedRect.cgPath and Path.cgPath unconditionally, expand cross-platform path test coverage, and update OpenCoreGraphics revision. --- Example/Tuist/Package.resolved | 2 +- Package.resolved | 2 +- Sources/OpenSwiftUICore/Shape/Path.swift | 4 -- .../Shape/RoundedCornerStyle.swift | 4 -- .../Shim/CGPathNonDarwinShims.swift | 50 +++++++++++++++++++ .../Shape/Path/FixedRoundedRectTests.swift | 2 +- .../Shape/Path/PathTests.swift | 44 ++++++++++++++-- .../Shape/Path/TrimmedPathTests.swift | 6 +-- 8 files changed, 93 insertions(+), 21 deletions(-) create mode 100644 Sources/OpenSwiftUICore/Shim/CGPathNonDarwinShims.swift diff --git a/Example/Tuist/Package.resolved b/Example/Tuist/Package.resolved index ecf1dd93b..7d3b6828f 100644 --- a/Example/Tuist/Package.resolved +++ b/Example/Tuist/Package.resolved @@ -25,7 +25,7 @@ "location" : "https://github.com/OpenSwiftUIProject/OpenCoreGraphics", "state" : { "branch" : "main", - "revision" : "9f247e283862ce3e2008d0156702643e72693adb" + "revision" : "9089c96c3bd62709ad28c8f4083e99baa32123a0" } }, { diff --git a/Package.resolved b/Package.resolved index f538b09f7..964f20291 100644 --- a/Package.resolved +++ b/Package.resolved @@ -25,7 +25,7 @@ "location" : "https://github.com/OpenSwiftUIProject/OpenCoreGraphics", "state" : { "branch" : "main", - "revision" : "9f247e283862ce3e2008d0156702643e72693adb" + "revision" : "9089c96c3bd62709ad28c8f4083e99baa32123a0" } }, { diff --git a/Sources/OpenSwiftUICore/Shape/Path.swift b/Sources/OpenSwiftUICore/Shape/Path.swift index c116b0e94..7820038c4 100644 --- a/Sources/OpenSwiftUICore/Shape/Path.swift +++ b/Sources/OpenSwiftUICore/Shape/Path.swift @@ -435,7 +435,6 @@ public struct Path: Equatable, LosslessStringConvertible, @unchecked Sendable { /// An immutable path representing the elements in the path. public var cgPath: CGPath { - #if canImport(CoreGraphics) switch storage { case .empty: return CGPath(rect: .null, transform: nil) @@ -450,9 +449,6 @@ public struct Path: Equatable, LosslessStringConvertible, @unchecked Sendable { case let .path(pathBox): return pathBox.cgPath } - #else - _openSwiftUIPlatformUnimplementedFailure() - #endif } package func retainRBPath() -> ORBPath { diff --git a/Sources/OpenSwiftUICore/Shape/RoundedCornerStyle.swift b/Sources/OpenSwiftUICore/Shape/RoundedCornerStyle.swift index 4370594d0..452bb9333 100644 --- a/Sources/OpenSwiftUICore/Shape/RoundedCornerStyle.swift +++ b/Sources/OpenSwiftUICore/Shape/RoundedCornerStyle.swift @@ -175,7 +175,6 @@ package struct FixedRoundedRect: Equatable { } package var cgPath: CGPath { - #if canImport(Darwin) let clamped = clampedCornerSize return _CGPathCreateRoundedRect( rect, @@ -183,9 +182,6 @@ package struct FixedRoundedRect: Equatable { clamped.height, needsContinuousCorners ) - #else - _openSwiftUIPlatformUnimplementedFailure() - #endif } @usableFromInline diff --git a/Sources/OpenSwiftUICore/Shim/CGPathNonDarwinShims.swift b/Sources/OpenSwiftUICore/Shim/CGPathNonDarwinShims.swift new file mode 100644 index 000000000..a7bf3c17b --- /dev/null +++ b/Sources/OpenSwiftUICore/Shim/CGPathNonDarwinShims.swift @@ -0,0 +1,50 @@ +// +// CGPathNonDarwinShims.swift +// OpenSwiftUICore + +#if !canImport(Darwin) +package import Foundation +package import OpenCoreGraphicsShims +import OpenRenderBoxShims + +package func _CGPathCreateRoundedRect( + _ rect: CGRect, + _ cornerWidth: CGFloat, + _ cornerHeight: CGFloat, + _ continuous: Bool +) -> CGPath { + var cornerWidth = max(cornerWidth, 0.0) + var cornerHeight = max(cornerHeight, 0.0) + if cornerWidth == 0.0 || cornerHeight == 0.0 || rect.isEmpty { + return CGPath(rect: rect, transform: nil) + } + if continuous { + let rbPath = ORBPath( + roundedRect: rect, + cornerWidth: cornerWidth, + cornerHeight: cornerHeight, + style: .continuous, + transform: nil + ) + defer { rbPath.release() } + return rbPath.cgPath + } + let width = rect.width + let height = rect.height + if cornerWidth * 2.0 > width { + cornerWidth = (width * 0.5).nextDown + } + if cornerHeight * 2.0 > height { + cornerHeight = (height * 0.5).nextDown + } + if cornerWidth < 0.0 || cornerWidth * 2.0 > width || cornerHeight < 0.0 || cornerHeight * 2.0 > height { + return CGPath(rect: rect, transform: nil) + } + return CGPath( + roundedRect: rect, + cornerWidth: cornerWidth, + cornerHeight: cornerHeight, + transform: nil + ) +} +#endif diff --git a/Tests/OpenSwiftUICoreTests/Shape/Path/FixedRoundedRectTests.swift b/Tests/OpenSwiftUICoreTests/Shape/Path/FixedRoundedRectTests.swift index 0849df741..5506dc2e8 100644 --- a/Tests/OpenSwiftUICoreTests/Shape/Path/FixedRoundedRectTests.swift +++ b/Tests/OpenSwiftUICoreTests/Shape/Path/FixedRoundedRectTests.swift @@ -197,7 +197,6 @@ struct FixedRoundedRectTests { #expect(roundedRect.contains(rect: CGRect(x: 200, y: 200, width: 10, height: 10)) == false) } - #if canImport(Darwin) @Test(arguments: [ (CGPoint(x: 50, y: 50), true), // Center point - inside (CGPoint(x: 200, y: 200), false), // Point clearly outside @@ -217,6 +216,7 @@ struct FixedRoundedRectTests { #expect(roundedRect.contains(point) == expected) } + #if canImport(Darwin) @Test(arguments: [ (CGRect(x: 0, y: 0, width: 100, height: 100), 10.0, RoundedCornerStyle.circular), (CGRect(x: 10, y: 20, width: 80, height: 60), 15.0, RoundedCornerStyle.continuous), diff --git a/Tests/OpenSwiftUICoreTests/Shape/Path/PathTests.swift b/Tests/OpenSwiftUICoreTests/Shape/Path/PathTests.swift index b50d3e174..634f319ce 100644 --- a/Tests/OpenSwiftUICoreTests/Shape/Path/PathTests.swift +++ b/Tests/OpenSwiftUICoreTests/Shape/Path/PathTests.swift @@ -2,10 +2,8 @@ // PathTests.swift // OpenSwiftUICoreTests -#if canImport(CoreGraphics) -import CoreGraphics -#endif import Foundation +import OpenCoreGraphicsShims @_spi(ForOpenSwiftUIOnly) @testable import OpenSwiftUICore import OpenSwiftUITestsSupport import Testing @@ -71,7 +69,44 @@ struct PathTests { } } - #if canImport(CoreGraphics) + @Test + func cgPathAcrossStorages() { + #expect(Path().cgPath.boundingBoxOfPath == .null) + + let rect = CGRect(x: 10, y: 20, width: 80, height: 40) + #expect(Path(rect).cgPath == CGPath(rect: rect, transform: nil)) + let ellipseBounds = Path(ellipseIn: rect).cgPath.boundingBoxOfPath + #expect(abs(ellipseBounds.origin.x - 10) < 1e-6) + #expect(abs(ellipseBounds.origin.y - 20) < 1e-6) + #expect(abs(ellipseBounds.size.width - 80) < 1e-6) + #expect(abs(ellipseBounds.size.height - 40) < 1e-6) + + let circular = Path(roundedRect: rect, cornerSize: CGSize(width: 10, height: 8), style: .circular).cgPath + let circularBounds = circular.boundingBoxOfPath + #expect(abs(circularBounds.origin.x - 10) < 1e-6) + #expect(abs(circularBounds.origin.y - 20) < 1e-6) + #expect(abs(circularBounds.size.width - 80) < 1e-6) + #expect(abs(circularBounds.size.height - 40) < 1e-6) + #expect(abs(circular.currentPoint.x - 90) < 1e-6) + #expect(abs(circular.currentPoint.y - 40) < 1e-6) + + let continuous = Path(roundedRect: rect, cornerSize: CGSize(width: 10, height: 8), style: .continuous).cgPath + let continuousBounds = continuous.boundingBoxOfPath + #expect(abs(continuousBounds.origin.x - 10) < 1e-5) + #expect(abs(continuousBounds.origin.y - 20) < 1e-5) + #expect(abs(continuousBounds.size.width - 80) < 1e-5) + #expect(abs(continuousBounds.size.height - 40) < 1e-5) + + let oversizedCircular = FixedRoundedRect(rect, cornerSize: CGSize(width: 100, height: 100), style: .circular).cgPath + #expect(abs(oversizedCircular.boundingBoxOfPath.size.width - 80) < 1e-6) + #expect(abs(oversizedCircular.boundingBoxOfPath.size.height - 40) < 1e-6) + + var custom = Path() + custom.move(to: CGPoint(x: 2, y: 3)) + custom.addLine(to: CGPoint(x: 12, y: 23)) + #expect(custom.cgPath.boundingBoxOfPath == CGRect(x: 2, y: 3, width: 10, height: 20)) + } + @Test func appendingElementsPreservesControlsAndOriginalCopy() { var path = Path() @@ -230,5 +265,4 @@ struct PathTests { #expect(path.contains(CGPoint(x: 25, y: 5))) #expect(original.boundingRect == CGRect(x: 0, y: 0, width: 10, height: 10)) } - #endif } diff --git a/Tests/OpenSwiftUICoreTests/Shape/Path/TrimmedPathTests.swift b/Tests/OpenSwiftUICoreTests/Shape/Path/TrimmedPathTests.swift index 904e18e04..bdec34cfd 100644 --- a/Tests/OpenSwiftUICoreTests/Shape/Path/TrimmedPathTests.swift +++ b/Tests/OpenSwiftUICoreTests/Shape/Path/TrimmedPathTests.swift @@ -3,11 +3,9 @@ // OpenSwiftUICoreTests import Foundation +import OpenCoreGraphicsShims import OpenSwiftUICore import Testing -#if canImport(CoreGraphics) -import CoreGraphics -#endif struct TrimmedPathTests { @Test @@ -35,7 +33,6 @@ struct TrimmedPathTests { #expect(path.trimmedPath(from: from, to: to).isEmpty) } - #if canImport(CoreGraphics) @Test func partialRectangle() { let trimmedPath = Path(CGRect(x: 0, y: 0, width: 100, height: 100)) @@ -50,5 +47,4 @@ struct TrimmedPathTests { #expect(path.boundingBoxOfPath == expectedBounds) #expect(path.currentPoint == CGPoint(x: 100, y: 50)) } - #endif } From 38750737580433f2cd9ece2ed8e583f60eb75b6a Mon Sep 17 00:00:00 2001 From: Kyle Date: Sun, 22 Nov 2026 15:06:42 +0800 Subject: [PATCH 14/22] feat(path): support Path string parsing and description on non-Darwin platforms Add String/CFString bridging helpers and non-Darwin _CGPathParseString and _CGPathCopyDescription shims, removing the remaining platform conditionals from Path.swift. --- Sources/OpenSwiftUICore/Shape/Path.swift | 14 +- .../Shim/CGPathNonDarwinShims.swift | 219 ++++++++++++++++++ .../View/Text/Util/String+Extension.swift | 27 +++ .../Shape/Path/PathTests.swift | 31 +++ .../Text/Util/String+ExtensionTests.swift | 30 +++ 5 files changed, 309 insertions(+), 12 deletions(-) create mode 100644 Tests/OpenSwiftUICoreTests/View/Text/Util/String+ExtensionTests.swift diff --git a/Sources/OpenSwiftUICore/Shape/Path.swift b/Sources/OpenSwiftUICore/Shape/Path.swift index 7820038c4..c7a00b9c3 100644 --- a/Sources/OpenSwiftUICore/Shape/Path.swift +++ b/Sources/OpenSwiftUICore/Shape/Path.swift @@ -410,27 +410,17 @@ public struct Path: Equatable, LosslessStringConvertible, @unchecked Sendable { /// `Path.stringRepresentation`. Fails if the `string` does not /// describe a valid path. public init?(_ string: String) { - #if canImport(CoreGraphics) let mutablePath = CGMutablePath() - guard let utf8 = (string as NSString).utf8String, - _CGPathParseString(mutablePath, utf8) else { + guard string.withCString({ _CGPathParseString(mutablePath, $0) }) else { return nil } storage = .path(PathBox(mutablePath)) - #else - _openSwiftUIPlatformUnimplementedWarning() - return nil - #endif } /// A description of the path that may be used to recreate the path /// via `init?(_:)`. public var description: String { - #if canImport(Darwin) - _CGPathCopyDescription(cgPath, 0.0) as String - #else - _openSwiftUIPlatformUnimplementedFailure() - #endif + String(cfString: _CGPathCopyDescription(cgPath, 0.0)) } /// An immutable path representing the elements in the path. diff --git a/Sources/OpenSwiftUICore/Shim/CGPathNonDarwinShims.swift b/Sources/OpenSwiftUICore/Shim/CGPathNonDarwinShims.swift index a7bf3c17b..23aceb98c 100644 --- a/Sources/OpenSwiftUICore/Shim/CGPathNonDarwinShims.swift +++ b/Sources/OpenSwiftUICore/Shim/CGPathNonDarwinShims.swift @@ -3,9 +3,228 @@ // OpenSwiftUICore #if !canImport(Darwin) +package import CoreFoundation package import Foundation package import OpenCoreGraphicsShims import OpenRenderBoxShims +#if canImport(Glibc) +import Glibc +#elseif canImport(Musl) +import Musl +#elseif os(WASI) +import WASILibc +#elseif os(Windows) +import ucrt +#endif + +package func _CGPathParseString( + _ path: CGMutablePath, + _ utf8CString: UnsafePointer +) -> Bool { + var ptr = utf8CString + var numbers = (0.0, 0.0, 0.0, 0.0, 0.0, 0.0) + return withUnsafeMutablePointer(to: &numbers) { tuplePtr in + tuplePtr.withMemoryRebound(to: Double.self, capacity: 6) { nums in + var numCount = 0 + var currentX: CGFloat = 0.0 + var currentY: CGFloat = 0.0 + var lastControlX: CGFloat = 0.0 + var lastControlY: CGFloat = 0.0 + while true { + var c = UInt8(bitPattern: ptr.pointee) + while c <= 0x1f { + switch c { + case 0: + return true + case 9, 10, 12, 13: + ptr = ptr.advanced(by: 1) + c = UInt8(bitPattern: ptr.pointee) + default: + return false + } + } + var isNumberStart = false + switch c { + case UInt8(ascii: " "): + break + case UInt8(ascii: "+"), + UInt8(ascii: "-"), + UInt8(ascii: "."), + UInt8(ascii: "0") ... UInt8(ascii: "9"), + UInt8(ascii: "E"), + UInt8(ascii: "P"), + UInt8(ascii: "X"), + UInt8(ascii: "e"), + UInt8(ascii: "p"), + UInt8(ascii: "x"): + isNumberStart = true + case UInt8(ascii: "I"): + if UInt8(bitPattern: ptr[1]) == UInt8(ascii: "n"), + UInt8(bitPattern: ptr[2]) == UInt8(ascii: "f") { + isNumberStart = true + } + case UInt8(ascii: "m"): + guard numCount == 2 else { return false } + let x = CGFloat(nums[0]), y = CGFloat(nums[1]) + path.move(to: CGPoint(x: x, y: y)) + currentX = x; lastControlX = x + currentY = y; lastControlY = y + numCount = 0 + case UInt8(ascii: "l"): + guard numCount == 2 else { return false } + let x = CGFloat(nums[0]), y = CGFloat(nums[1]) + path.addLine(to: CGPoint(x: x, y: y)) + currentX = x; lastControlX = x + currentY = y; lastControlY = y + numCount = 0 + case UInt8(ascii: "c"): + guard numCount == 6 else { return false } + let cp1x = CGFloat(nums[0]), cp1y = CGFloat(nums[1]) + let cp2x = CGFloat(nums[2]), cp2y = CGFloat(nums[3]) + let x = CGFloat(nums[4]), y = CGFloat(nums[5]) + path.addCurve( + to: CGPoint(x: x, y: y), + control1: CGPoint(x: cp1x, y: cp1y), + control2: CGPoint(x: cp2x, y: cp2y) + ) + lastControlX = cp2x + lastControlY = cp2y + currentX = x + currentY = y + numCount = 0 + case UInt8(ascii: "q"): + guard numCount == 4 else { return false } + let cpx = CGFloat(nums[0]), cpy = CGFloat(nums[1]) + let x = CGFloat(nums[2]), y = CGFloat(nums[3]) + path.addQuadCurve( + to: CGPoint(x: x, y: y), + control: CGPoint(x: cpx, y: cpy) + ) + lastControlX = cpx + lastControlY = cpy + currentX = x + currentY = y + numCount = 0 + case UInt8(ascii: "t"): + guard numCount == 2 else { return false } + let reflectedX = currentX * 2.0 - lastControlX + let reflectedY = currentY * 2.0 - lastControlY + let x = CGFloat(nums[0]), y = CGFloat(nums[1]) + path.addQuadCurve( + to: CGPoint(x: x, y: y), + control: CGPoint(x: reflectedX, y: reflectedY) + ) + lastControlX = reflectedX + lastControlY = reflectedY + currentX = x + currentY = y + numCount = 0 + case UInt8(ascii: "v"): + guard numCount == 4 else { return false } + let cp2x = CGFloat(nums[0]), cp2y = CGFloat(nums[1]) + let x = CGFloat(nums[2]), y = CGFloat(nums[3]) + path.addCurve( + to: CGPoint(x: x, y: y), + control1: CGPoint(x: currentX, y: currentY), + control2: CGPoint(x: cp2x, y: cp2y) + ) + lastControlX = cp2x + lastControlY = cp2y + currentX = x + currentY = y + numCount = 0 + case UInt8(ascii: "y"): + guard numCount == 4 else { return false } + let cp1x = CGFloat(nums[0]), cp1y = CGFloat(nums[1]) + let x = CGFloat(nums[2]), y = CGFloat(nums[3]) + let end = CGPoint(x: x, y: y) + path.addCurve( + to: end, + control1: CGPoint(x: cp1x, y: cp1y), + control2: end + ) + currentX = x + currentY = y + numCount = 0 + case UInt8(ascii: "h"): + guard numCount == 0 else { return false } + path.closeSubpath() + currentX = 0.0 + currentY = 0.0 + case UInt8(ascii: "r"): + guard UInt8(bitPattern: ptr[1]) == UInt8(ascii: "e"), + numCount == 4 else { + return false + } + let x = CGFloat(nums[0]), y = CGFloat(nums[1]) + let w = CGFloat(nums[2]), h = CGFloat(nums[3]) + path.addRect(CGRect(x: x, y: y, width: w, height: h)) + currentX = w + currentY = h + ptr = ptr.advanced(by: 1) + numCount = 0 + default: + return false + } + if isNumberStart { + guard numCount < 6 else { return false } + var endPtr: UnsafeMutablePointer? + nums[numCount] = strtod(ptr, &endPtr) + numCount += 1 + if let endPtr { + ptr = UnsafePointer(endPtr) + } + } else { + ptr = ptr.advanced(by: 1) + } + } + } + } +} + +package func _CGPathCopyDescription(_ path: CGPath, _ step: CGFloat) -> CFString { + var description = "" + let inverseStep = 1.0 / step + path.applyWithBlock { elementPtr in + let element = elementPtr.pointee + let command: Character + let pointCount: Int + switch element.type { + case .moveToPoint: + command = "m" + pointCount = 1 + case .addLineToPoint: + command = "l" + pointCount = 1 + case .addQuadCurveToPoint: + command = "q" + pointCount = 2 + case .addCurveToPoint: + command = "c" + pointCount = 3 + case .closeSubpath: + command = "h" + pointCount = 0 + @unknown default: + return + } + if !description.isEmpty { + description.append(" ") + } + for i in 0.. Date: Sun, 22 Nov 2026 15:44:52 +0800 Subject: [PATCH 15/22] refactor(path): remove OPENSWIFTUI_CF_CGTYPES conditional Select the C PathData union on Darwin and the Swift PathData layout on non-Darwin platforms directly, and update OpenRenderBox revision. --- Package.resolved | 4 ++-- Package.swift | 16 ---------------- Sources/OpenSwiftUICore/Shape/PathData.swift | 2 +- Sources/OpenSwiftUI_SPI/Util/PathData.h | 11 +++-------- 4 files changed, 6 insertions(+), 27 deletions(-) diff --git a/Package.resolved b/Package.resolved index 964f20291..954c526f0 100644 --- a/Package.resolved +++ b/Package.resolved @@ -1,5 +1,5 @@ { - "originHash" : "d835df14202f1ad0c0bb332af55103cb7665747f71aa0a62b293817ac1d9e66a", + "originHash" : "459c86ed5ed6171cedbd2fe012f83881dbd0c3cccccdd9d5f335fc1a88e79b0e", "pins" : [ { "identity" : "darwinprivateframeworks", @@ -43,7 +43,7 @@ "location" : "https://github.com/OpenSwiftUIProject/OpenRenderBox", "state" : { "branch" : "main", - "revision" : "f0c4861998d95d14a4b159ef7845d1d8e469f3e6" + "revision" : "f49e3003ad898f72ddcd5c378ecc95692613b83a" } }, { diff --git a/Package.swift b/Package.swift index 631b7505a..68e09c7f2 100644 --- a/Package.swift +++ b/Package.swift @@ -188,13 +188,6 @@ let bridgeFramework = envStringValue("OPENSWIFTUI_BRIDGE_FRAMEWORK", default: "S // Workaround iOS CI build issue (We need to disable this on iOS CI) let supportMultiProducts: Bool = envBoolValue("SUPPORT_MULTI_PRODUCTS", default: true) -/// CGFloat and CGRect def in CFCGTypes.h will conflict with Foundation's CGSize/CGRect def on Linux. -/// macOS: true -> no issue -/// macOS: false -> use Swift implementation with OpenCoreGraphics Swift CGPath -/// Linux: true + No CGPathRef support in ORBPath -> confilict with Foundation def -/// Linux: false -> use Swift implementation with OpenCoreGraphics Swift CGPath -let cfCGTypes = envBoolValue("CF_CGTYPES", default: buildForDarwinPlatform) - // MARK: - Shared Settings var sharedCSettings: [CSetting] = [ @@ -375,15 +368,6 @@ if enableRuntimeConcurrencyCheck { sharedSwiftSettings.append(.define("OPENSWIFTUI_ENABLE_RUNTIME_CONCURRENCY_CHECK")) } -if cfCGTypes { - sharedCSettings.append(.define("OPENSWIFTUI_CF_CGTYPES")) - sharedCxxSettings.append(.define("OPENSWIFTUI_CF_CGTYPES")) - sharedSwiftSettings.append(.define("OPENSWIFTUI_CF_CGTYPES")) - sharedCSettings.append(.define("OPENRENDERBOX_CF_CGTYPES")) - sharedCxxSettings.append(.define("OPENRENDERBOX_CF_CGTYPES")) - sharedSwiftSettings.append(.define("OPENRENDERBOX_CF_CGTYPES")) -} - if computeCondition { sharedCSettings.append(.define("OPENSWIFTUI_COMPUTE")) sharedCxxSettings.append(.define("OPENSWIFTUI_COMPUTE")) diff --git a/Sources/OpenSwiftUICore/Shape/PathData.swift b/Sources/OpenSwiftUICore/Shape/PathData.swift index 73a81418f..621bfe6af 100644 --- a/Sources/OpenSwiftUICore/Shape/PathData.swift +++ b/Sources/OpenSwiftUICore/Shape/PathData.swift @@ -2,7 +2,7 @@ // PathData.swift // OpenSwiftUICore -#if !OPENSWIFTUI_CF_CGTYPES +#if !canImport(Darwin) package import OpenCoreGraphicsShims package import OpenRenderBoxShims diff --git a/Sources/OpenSwiftUI_SPI/Util/PathData.h b/Sources/OpenSwiftUI_SPI/Util/PathData.h index 127e5b48b..03162b55c 100644 --- a/Sources/OpenSwiftUI_SPI/Util/PathData.h +++ b/Sources/OpenSwiftUI_SPI/Util/PathData.h @@ -2,17 +2,14 @@ // PathData.h // OpenSwiftUI_SPI -#if OPENSWIFTUI_CF_CGTYPES - #ifndef PathData_h #define PathData_h #include "OpenSwiftUIBase.h" #if OPENSWIFTUI_TARGET_OS_DARWIN -#include -#endif +#include #include OPENSWIFTUI_ASSUME_NONNULL_BEGIN @@ -20,9 +17,7 @@ OPENSWIFTUI_ASSUME_NONNULL_BEGIN OPENSWIFTUI_IMPLICIT_BRIDGING_ENABLED typedef union PathData { - #if OPENSWIFTUI_TARGET_OS_DARWIN CGPathRef _Nullable cgPath; - #endif ORBPath rbPath; uint8_t buffer[0x60]; } PathData; @@ -38,6 +33,6 @@ OPENSWIFTUI_ASSUME_NONNULL_END OPENSWIFTUI_IMPLICIT_BRIDGING_DISABLED -#endif /* PathData_h */ +#endif /* OPENSWIFTUI_TARGET_OS_DARWIN */ -#endif /* OPENSWIFTUI_CF_CGTYPES */ +#endif /* PathData_h */ From 5c37adc68c2d62a21ff298c1fb93d939647385ea Mon Sep 17 00:00:00 2001 From: Kyle Date: Sun, 22 Nov 2026 16:17:24 +0800 Subject: [PATCH 16/22] chore: update dependency --- Example/Tuist/Package.resolved | 2 +- Package.resolved | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Example/Tuist/Package.resolved b/Example/Tuist/Package.resolved index 7d3b6828f..908f2cd69 100644 --- a/Example/Tuist/Package.resolved +++ b/Example/Tuist/Package.resolved @@ -25,7 +25,7 @@ "location" : "https://github.com/OpenSwiftUIProject/OpenCoreGraphics", "state" : { "branch" : "main", - "revision" : "9089c96c3bd62709ad28c8f4083e99baa32123a0" + "revision" : "89eb70998d076c52c11ada3c5cebefce6d8b1954" } }, { diff --git a/Package.resolved b/Package.resolved index 954c526f0..5b9907302 100644 --- a/Package.resolved +++ b/Package.resolved @@ -25,7 +25,7 @@ "location" : "https://github.com/OpenSwiftUIProject/OpenCoreGraphics", "state" : { "branch" : "main", - "revision" : "9089c96c3bd62709ad28c8f4083e99baa32123a0" + "revision" : "89eb70998d076c52c11ada3c5cebefce6d8b1954" } }, { From 15cf217e931b9866d2995835e33fdf54d2e7c2fe Mon Sep 17 00:00:00 2001 From: Kyle Date: Sun, 22 Nov 2026 16:17:24 +0800 Subject: [PATCH 17/22] test(path): redesign Path, TrimmedPath, and FixedRoundedRect unit tests --- .../Shape/Path/FixedRoundedRectTests.swift | 341 ++++---- .../Shape/Path/PathTests.swift | 805 ++++++++++++------ .../Shape/Path/TrimmedPathTests.swift | 57 +- 3 files changed, 743 insertions(+), 460 deletions(-) diff --git a/Tests/OpenSwiftUICoreTests/Shape/Path/FixedRoundedRectTests.swift b/Tests/OpenSwiftUICoreTests/Shape/Path/FixedRoundedRectTests.swift index 5506dc2e8..c834e5062 100644 --- a/Tests/OpenSwiftUICoreTests/Shape/Path/FixedRoundedRectTests.swift +++ b/Tests/OpenSwiftUICoreTests/Shape/Path/FixedRoundedRectTests.swift @@ -1,237 +1,210 @@ // // FixedRoundedRectTests.swift -// OpenSwiftUITests +// OpenSwiftUICoreTests -@testable import OpenSwiftUICore import Foundation +import OpenCoreGraphicsShims +@testable import OpenSwiftUICore import Testing +@Suite(.tags(.aigc)) struct FixedRoundedRectTests { - // MARK: - Initialization - @Test - func initWithRect() { - let rect = CGRect(x: 10, y: 20, width: 100, height: 50) - let roundedRect = FixedRoundedRect(rect) - #expect(roundedRect.rect == rect) - #expect(roundedRect.cornerSize == .zero) - #expect(roundedRect.style == .circular) - } + // MARK: - Initialization & Properties @Test - func initWithCornerSize() { - let rect = CGRect(x: 0, y: 0, width: 100, height: 50) - let cornerSize = CGSize(width: 10, height: 15) - let roundedRect = FixedRoundedRect(rect, cornerSize: cornerSize, style: .continuous) - #expect(roundedRect.rect == rect) - #expect(roundedRect.cornerSize == cornerSize) - #expect(roundedRect.style == .continuous) - } + func initializersAndEquality() { + let rect = CGRect(x: 10, y: 20, width: 100, height: 50) + let plain = FixedRoundedRect(rect) + #expect(plain.rect == rect) + #expect(plain.cornerSize == .zero) + #expect(plain.style == .circular) - @Test - func initWithCornerRadius() { - let rect = CGRect(x: 0, y: 0, width: 100, height: 50) - let roundedRect = FixedRoundedRect(rect, cornerRadius: 12, style: .circular) - #expect(roundedRect.rect == rect) - #expect(roundedRect.cornerSize == CGSize(width: 12, height: 12)) - #expect(roundedRect.style == .circular) + let uniform = FixedRoundedRect(rect, cornerRadius: 12, style: .circular) + #expect(uniform == FixedRoundedRect(rect, cornerSize: CGSize(width: 12, height: 12), style: .circular)) + #expect(uniform != FixedRoundedRect(rect, cornerRadius: 12, style: .continuous)) + #expect(uniform != FixedRoundedRect(rect, cornerRadius: 15, style: .circular)) } - // MARK: - Properties - - @Test - func isRounded() { - let rect = CGRect(x: 0, y: 0, width: 100, height: 50) - let notRounded = FixedRoundedRect(rect) - #expect(notRounded.isRounded == false) - - let rounded = FixedRoundedRect(rect, cornerRadius: 10, style: .circular) - #expect(rounded.isRounded == true) - - let partiallyRounded = FixedRoundedRect(rect, cornerSize: CGSize(width: 5, height: 0), style: .circular) - #expect(partiallyRounded.isRounded == true) + @Test(arguments: [ + (CGSize.zero, RoundedCornerStyle.circular, false, true, false), + (CGSize(width: 10, height: 10), .circular, true, true, false), + (CGSize(width: 10, height: 10), .continuous, true, true, true), + (CGSize.zero, .continuous, false, true, false), + (CGSize(width: 10, height: 0), .circular, true, false, false), + ]) + func cornerFlags( + cornerSize: CGSize, + style: RoundedCornerStyle, + isRounded: Bool, + isUniform: Bool, + needsContinuousCorners: Bool + ) { + let value = FixedRoundedRect(CGRect(x: 0, y: 0, width: 100, height: 50), cornerSize: cornerSize, style: style) + #expect(value.isRounded == isRounded) + #expect(value.isUniform == isUniform) + #expect(value.needsContinuousCorners == needsContinuousCorners) } - @Test - func isUniform() { - let rect = CGRect(x: 0, y: 0, width: 100, height: 50) - let uniform = FixedRoundedRect(rect, cornerRadius: 10, style: .circular) - #expect(uniform.isUniform == true) - - let nonUniform = FixedRoundedRect(rect, cornerSize: CGSize(width: 10, height: 15), style: .circular) - #expect(nonUniform.isUniform == false) + @Test(arguments: [ + (CGSize(width: 10, height: 15), CGSize(width: 10, height: 15), 10.0), + (CGSize(width: 30, height: 30), CGSize(width: 25, height: 25), 25.0), + (CGSize(width: 40, height: 10), CGSize(width: 25, height: 10), 25.0), + ]) + func clampedCornerDimensions(input: CGSize, expectedSize: CGSize, expectedRadius: CGFloat) { + let value = FixedRoundedRect(CGRect(x: 0, y: 0, width: 100, height: 50), cornerSize: input, style: .circular) + #expect(value.clampedCornerSize == expectedSize) + #expect(value.clampedCornerRadius == expectedRadius) } - @Test - func needsContinuousCorners() { - let rect = CGRect(x: 0, y: 0, width: 100, height: 50) - let circularRounded = FixedRoundedRect(rect, cornerRadius: 10, style: .circular) - #expect(circularRounded.needsContinuousCorners == false) - - let continuousRounded = FixedRoundedRect(rect, cornerRadius: 10, style: .continuous) - #expect(continuousRounded.needsContinuousCorners == true) + // MARK: - Transforms & Insets - let continuousNotRounded = FixedRoundedRect(rect, cornerRadius: 0, style: .continuous) - #expect(continuousNotRounded.needsContinuousCorners == false) - } - - @Test - func clampedCornerSize() { - let rect = CGRect(x: 0, y: 0, width: 100, height: 50) - // Corner size fits within rect - let normal = FixedRoundedRect(rect, cornerSize: CGSize(width: 10, height: 10), style: .circular) - #expect(normal.clampedCornerSize == CGSize(width: 10, height: 10)) - - // Corner size exceeds half of smaller dimension (height=50, so max=25) - let oversized = FixedRoundedRect(rect, cornerSize: CGSize(width: 30, height: 30), style: .circular) - #expect(oversized.clampedCornerSize == CGSize(width: 25, height: 25)) - - // Non-uniform corner size - let nonUniform = FixedRoundedRect(rect, cornerSize: CGSize(width: 40, height: 10), style: .circular) - #expect(nonUniform.clampedCornerSize == CGSize(width: 25, height: 10)) + @Test(arguments: [ + (CGSize.zero, CGRect(x: 0, y: 0, width: 100, height: 50), CGSize(width: 10, height: 10)), + (CGSize(width: 5, height: 12), CGRect(x: 5, y: 12, width: 90, height: 26), CGSize(width: 5, height: 0)), + (CGSize(width: 60, height: 30), nil as CGRect?, nil as CGSize?), + ]) + func insetBy(delta: CGSize, expectedRect: CGRect?, expectedCornerSize: CGSize?) { + let base = FixedRoundedRect(CGRect(x: 0, y: 0, width: 100, height: 50), cornerRadius: 10, style: .circular) + let result = base.insetBy(dx: delta.width, dy: delta.height) + #expect(result?.rect == expectedRect) + #expect(result?.cornerSize == expectedCornerSize) } @Test - func clampedCornerRadius() { - let rect = CGRect(x: 0, y: 0, width: 100, height: 50) - let normal = FixedRoundedRect(rect, cornerRadius: 10, style: .circular) - #expect(normal.clampedCornerRadius == 10) - - let oversized = FixedRoundedRect(rect, cornerRadius: 30, style: .circular) - #expect(oversized.clampedCornerRadius == 25) + func applyingAffineTransformPreservesCornerSigns() { + let base = FixedRoundedRect( + CGRect(x: 10, y: 20, width: 40, height: 30), + cornerSize: CGSize(width: -4, height: 6), + style: .continuous + ) + let scaled = base.applying(CGAffineTransform(scaleX: -2, y: 3)) + #expect(scaled.rect == CGRect(x: -100, y: 60, width: 80, height: 90)) + #expect(scaled.cornerSize == CGSize(width: -8, height: 18)) + #expect(scaled.style == .continuous) } - // MARK: - Equality + // MARK: - Intersection & Containment - @Test - func equality() { - let rect = CGRect(x: 0, y: 0, width: 100, height: 50) - let a = FixedRoundedRect(rect, cornerRadius: 10, style: .circular) - let b = FixedRoundedRect(rect, cornerRadius: 10, style: .circular) - let c = FixedRoundedRect(rect, cornerRadius: 10, style: .continuous) - let d = FixedRoundedRect(rect, cornerRadius: 15, style: .circular) - #expect(a == b) - #expect(a != c) - #expect(a != d) + @Test(arguments: [ + (CGRect(x: 50, y: 25, width: 20, height: 10), true), + (CGRect(x: 90, y: 40, width: 20, height: 20), true), + (CGRect(x: 200, y: 200, width: 20, height: 10), false), + ]) + func hasIntersection(query: CGRect, expected: Bool) { + let base = FixedRoundedRect(CGRect(x: 0, y: 0, width: 100, height: 50), cornerRadius: 10, style: .circular) + #expect(base.hasIntersection(query) == expected) } - // MARK: - Transformations + @Test(arguments: [ + (CGPoint(x: 50, y: 50), true), // Center + (CGPoint(x: 50, y: 1), true), // Near top edge + (CGPoint(x: 5, y: 5), true), // Inside rounded corner + (CGPoint(x: 1, y: 1), false), // Cut off by top-left corner + (CGPoint(x: 99, y: 99), false), // Cut off by bottom-right corner + (CGPoint(x: 200, y: 200), false), + ]) + func containsPoint(point: CGPoint, expected: Bool) { + let rounded = FixedRoundedRect(CGRect(x: 0, y: 0, width: 100, height: 100), cornerRadius: 10, style: .circular) + #expect(rounded.contains(point) == expected) + } + + enum ContainedShapeKind: CaseIterable, Sendable { + case innerRect + case outerRect + case circleEllipse + case nonCircleEllipse + case innerRoundedRect + case customLinePath + } + + @Test(arguments: ContainedShapeKind.allCases) + func containsPathWithOffset(kind: ContainedShapeKind) { + let container = FixedRoundedRect(CGRect(x: 0, y: 0, width: 100, height: 100), cornerRadius: 20, style: .circular) + let offset = CGSize(width: 10, height: 10) + + let (candidate, expected): (Path, Bool) = switch kind { + case .innerRect: + (Path(CGRect(x: 10, y: 10, width: 60, height: 60)), true) + case .outerRect: + (Path(CGRect(x: 0, y: 0, width: 95, height: 95)), false) + case .circleEllipse: + // Circle of diameter 100 at (-10, -10) shifts to (0, 0, 100, 100) with radius 50 >= 20 + (Path(ellipseIn: CGRect(x: -10, y: -10, width: 100, height: 100)), true) + case .nonCircleEllipse: + (Path(ellipseIn: CGRect(x: 10, y: 20, width: 60, height: 40)), true) + case .innerRoundedRect: + (Path(roundedRect: CGRect(x: 10, y: 10, width: 60, height: 60), cornerRadius: 5, style: .circular), true) + case .customLinePath: + (Path { p in p.move(to: CGPoint(x: 10, y: 10)); p.addLine(to: CGPoint(x: 50, y: 50)) }, true) + } - @Test - func insetBy() { - let rect = CGRect(x: 0, y: 0, width: 100, height: 50) - let roundedRect = FixedRoundedRect(rect, cornerRadius: 10, style: .circular) - - let inset = roundedRect.insetBy(dx: 5, dy: 5) - #expect(inset != nil) - #expect(inset?.rect == CGRect(x: 5, y: 5, width: 90, height: 40)) - #expect(inset?.cornerSize == CGSize(width: 5, height: 5)) - - // Zero inset returns self - let noInset = roundedRect.insetBy(dx: 0, dy: 0) - #expect(noInset == roundedRect) - - // Inset that makes rect empty returns nil - let tooMuchInset = roundedRect.insetBy(dx: 60, dy: 30) - #expect(tooMuchInset == nil) + #expect(container.contains(path: candidate, offsetBy: offset) == expected) } @Test - func hasIntersection() { - let rect = CGRect(x: 0, y: 0, width: 100, height: 50) - let roundedRect = FixedRoundedRect(rect, cornerRadius: 10, style: .circular) - - #expect(roundedRect.hasIntersection(CGRect(x: 50, y: 25, width: 20, height: 10)) == true) - #expect(roundedRect.hasIntersection(CGRect(x: 200, y: 200, width: 20, height: 10)) == false) - #expect(roundedRect.hasIntersection(CGRect(x: 90, y: 40, width: 20, height: 20)) == true) + func containsUsesShortestDimensionForClamping() { + let pill = FixedRoundedRect(CGRect(x: 0, y: 0, width: 100, height: 20), cornerSize: CGSize(width: 50, height: 10), style: .circular) + #expect(pill.contains(rect: CGRect(x: 4, y: 4, width: 92, height: 12))) + #expect(!pill.contains(rect: CGRect(x: 1, y: 1, width: 98, height: 18))) } - // MARK: - Contains + // MARK: - CGPath & Protobuf - @Test - func containsFixedRoundedRect() { - let outer = FixedRoundedRect( - CGRect(x: 0, y: 0, width: 100, height: 100), - cornerRadius: 10, - style: .circular - ) - let inner = FixedRoundedRect( - CGRect(x: 10, y: 10, width: 80, height: 80), - cornerRadius: 5, - style: .circular - ) - let outside = FixedRoundedRect( - CGRect(x: 200, y: 200, width: 50, height: 50), - cornerRadius: 5, - style: .circular + @Test(arguments: [RoundedCornerStyle.circular, .continuous]) + func cgPathAndProtobufRoundTrip(style: RoundedCornerStyle) throws { + let original = FixedRoundedRect( + CGRect(x: 5, y: 10, width: 80, height: 40), + cornerSize: CGSize(width: 8, height: 6), + style: style ) - #expect(outer.contains(inner) == true) - #expect(outer.contains(outside) == false) - #expect(inner.contains(outer) == false) - } + let bounds = original.cgPath.boundingBoxOfPath + #expect(abs(bounds.origin.x - 5) < 1e-5) + #expect(abs(bounds.origin.y - 10) < 1e-5) + #expect(abs(bounds.size.width - 80) < 1e-5) + #expect(abs(bounds.size.height - 40) < 1e-5) - @Test - func containsFixedRoundedRectUsesShortestDimension() { - let outer = FixedRoundedRect( - CGRect(x: 0, y: 0, width: 100, height: 20), - cornerSize: CGSize(width: 50, height: 10), - style: .circular - ) - let inner = FixedRoundedRect( - CGRect(x: 4, y: 4, width: 92, height: 12) - ) + let encoded = try ProtobufEncoder.encoding(original) + var decoder = ProtobufDecoder(encoded) + let decoded = try FixedRoundedRect(from: &decoder) + #expect(decoded == original) - #expect(outer.contains(inner)) + #expect(RoundedCornerStyle(protobufValue: style.protobufValue) == style) + #expect(RoundedCornerStyle(protobufValue: 99) == nil) } + // MARK: - RectangleCornerRadii + @Test - func containsRect() { - let roundedRect = FixedRoundedRect( - CGRect(x: 0, y: 0, width: 100, height: 100), - cornerRadius: 10, - style: .circular - ) + func rectangleCornerRadiiAccessorsAndAnimatableData() { + var radii = RectangleCornerRadii(topLeading: 1, bottomLeading: 2, bottomTrailing: 3, topTrailing: 4) + #expect(radii.topLeft == 1) + #expect(radii.bottomLeft == 2) + #expect(radii.bottomRight == 3) + #expect(radii.topRight == 4) - #expect(roundedRect.contains(rect: CGRect(x: 20, y: 20, width: 60, height: 60)) == true) - #expect(roundedRect.contains(rect: CGRect(x: 200, y: 200, width: 10, height: 10)) == false) - } + radii.topLeading = 10 + radii.bottomLeading = 20 + radii.bottomTrailing = 30 + radii.topTrailing = 40 - @Test(arguments: [ - (CGPoint(x: 50, y: 50), true), // Center point - inside - (CGPoint(x: 200, y: 200), false), // Point clearly outside - (CGPoint(x: 50, y: 1), true), // Near top edge - inside - (CGPoint(x: 1, y: 50), true), // Near left edge - inside - (CGPoint(x: 5, y: 5), true), // Corner region - inside rounded corner - (CGPoint(x: 1, y: 1), false), // Corner - outside due to rounding - (CGPoint(x: 99, y: 99), false), // Bottom-right corner - outside due to rounding - (CGPoint(x: 95, y: 95), true), // Bottom-right corner region - inside - ] as [(CGPoint, Bool)]) - func containsPoint(point: CGPoint, expected: Bool) { - let roundedRect = FixedRoundedRect( - CGRect(x: 0, y: 0, width: 100, height: 100), - cornerRadius: 10, - style: .circular - ) - #expect(roundedRect.contains(point) == expected) + var copy = RectangleCornerRadii() + copy.animatableData = radii.animatableData + #expect(copy == radii) } #if canImport(Darwin) @Test(arguments: [ (CGRect(x: 0, y: 0, width: 100, height: 100), 10.0, RoundedCornerStyle.circular), (CGRect(x: 10, y: 20, width: 80, height: 60), 15.0, RoundedCornerStyle.continuous), - (CGRect(x: 0, y: 0, width: 50, height: 50), 5.0, RoundedCornerStyle.circular), (CGRect(x: 10, y: 20, width: -80, height: -60), 15.0, RoundedCornerStyle.circular), - ] as [(CGRect, CGFloat, RoundedCornerStyle)]) - func withTemporaryPath(rect: CGRect, cornerRadius: CGFloat, style: RoundedCornerStyle) { + ]) + func withTemporaryPathPreservesRawRect(rect: CGRect, cornerRadius: CGFloat, style: RoundedCornerStyle) { let roundedRect = FixedRoundedRect(rect, cornerRadius: cornerRadius, style: style) - let boundingRect = roundedRect.withTemporaryPath { path in - path.storage.boundingRect - } - #expect(boundingRect.origin.x == rect.origin.x) - #expect(boundingRect.origin.y == rect.origin.y) - #expect(boundingRect.size.width == rect.size.width) - #expect(boundingRect.size.height == rect.size.height) + let boundingRect = roundedRect.withTemporaryPath { $0.storage.boundingRect } + #expect(boundingRect.origin == rect.origin) + #expect(boundingRect.size == rect.size) } #endif } diff --git a/Tests/OpenSwiftUICoreTests/Shape/Path/PathTests.swift b/Tests/OpenSwiftUICoreTests/Shape/Path/PathTests.swift index 6b757f3d5..512ea3609 100644 --- a/Tests/OpenSwiftUICoreTests/Shape/Path/PathTests.swift +++ b/Tests/OpenSwiftUICoreTests/Shape/Path/PathTests.swift @@ -10,290 +10,593 @@ import Testing @Suite(.tags(.aigc)) struct PathTests { - @Test(arguments: [0, 1, 64, 65]) - func containmentPreservesMaskAndOrigin(count: Int) { - let path = Path(CGRect(x: 0, y: 0, width: 10, height: 10)) - var points = Array(repeating: CGPoint(x: 25, y: 35), count: count) - if count > 0 { - points[0] = CGPoint(x: 35, y: 35) - } - let mask = path.contains(points: points, origin: CGPoint(x: 20, y: 30)) - #expect(mask.rawValue == (count < 2 ? 0 : 0xffff_ffff_ffff_fffe)) - } - - @Test - func ellipseExcludesBoundary() { - let path = Path(ellipseIn: CGRect(x: 10, y: 20, width: 40, height: 20)) - #expect(path.contains(CGPoint(x: 30, y: 30))) - #expect(!path.contains(CGPoint(x: 10, y: 30))) - #expect(!path.contains(CGPoint(x: 50, y: 30))) - #expect(!path.contains(CGPoint(x: 11, y: 21))) - } - @Test - func coordinateConversionUpdatesPath() { - var transform = ViewTransform() - transform.appendCoordinateSpace(name: "path") - transform.appendTranslation(CGSize(width: 3, height: 4)) - var path = Path(CGRect(x: 1, y: 2, width: 10, height: 20)) + // MARK: - Initialization & Introspection + + struct Initialization { + enum DegenerateInput: CaseIterable, Sendable { + case empty + case nullRect + case nullEllipse + case nullRoundedRect + case nullUnevenRoundedRect + case emptyCGPath + case emptyMutableCGPath + } - path.convert(to: .named("path"), transform: transform) - #expect(path.boundingRect == CGRect(x: -2, y: -2, width: 10, height: 20)) + @Test(arguments: DegenerateInput.allCases) + func degenerateInputsNormalizeToEmpty(input: DegenerateInput) { + let path: Path = switch input { + case .empty: + Path() + case .nullRect: + Path(CGRect.null) + case .nullEllipse: + Path(ellipseIn: .null) + case .nullRoundedRect: + Path(roundedRect: .null, cornerRadius: 8) + case .nullUnevenRoundedRect: + Path(roundedRect: .null, cornerRadii: .init(topLeading: 8)) + case .emptyCGPath: + Path(CGMutablePath() as CGPath) + case .emptyMutableCGPath: + Path(CGMutablePath()) + } - path.convert(from: .named("path"), transform: transform) - #expect(path.boundingRect == CGRect(x: 1, y: 2, width: 10, height: 20)) - } + #expect(path.isEmpty) + #expect(path.boundingRect == .null) + #expect(path.currentPoint == nil) + #expect(path.rect() == nil) + #expect(path.roundedRect() == nil) + } - @Test - func protobufRoundTrip() throws { - var customPath = Path() - customPath.move(to: CGPoint(x: 1, y: 2)) - customPath.addLine(to: CGPoint(x: 3, y: 4)) - customPath.addQuadCurve(to: CGPoint(x: 7, y: 8), control: CGPoint(x: 5, y: 6)) - customPath.addCurve(to: CGPoint(x: 13, y: 14), control1: CGPoint(x: 9, y: 10), control2: CGPoint(x: 11, y: 12)) - customPath.closeSubpath() - - let cases: [Path] = [ - Path(), - Path(CGRect(x: 1, y: 2, width: 30, height: 40)), - Path(ellipseIn: CGRect(x: 3, y: 4, width: 20, height: 10)), - Path(roundedRect: CGRect(x: 0, y: 0, width: 50, height: 30), cornerSize: CGSize(width: 6, height: 8), style: .continuous), - customPath, - ] - - for original in cases { - let encoded = try ProtobufEncoder.encoding(original) - var decoder = ProtobufDecoder(encoded) - let decoded = try Path(from: &decoder) - #expect(decoded == original) + enum RectFallbackInput: CaseIterable, Sendable { + case plainRect + case zeroCornerRadius + case zeroCornerSize + case infiniteEllipse + case infiniteRoundedRect } - } - @Test - func cgPathAcrossStorages() { - #expect(Path().cgPath.boundingBoxOfPath == .null) - - let rect = CGRect(x: 10, y: 20, width: 80, height: 40) - #expect(Path(rect).cgPath == CGPath(rect: rect, transform: nil)) - let ellipseBounds = Path(ellipseIn: rect).cgPath.boundingBoxOfPath - #expect(abs(ellipseBounds.origin.x - 10) < 1e-6) - #expect(abs(ellipseBounds.origin.y - 20) < 1e-6) - #expect(abs(ellipseBounds.size.width - 80) < 1e-6) - #expect(abs(ellipseBounds.size.height - 40) < 1e-6) - - let circular = Path(roundedRect: rect, cornerSize: CGSize(width: 10, height: 8), style: .circular).cgPath - let circularBounds = circular.boundingBoxOfPath - #expect(abs(circularBounds.origin.x - 10) < 1e-6) - #expect(abs(circularBounds.origin.y - 20) < 1e-6) - #expect(abs(circularBounds.size.width - 80) < 1e-6) - #expect(abs(circularBounds.size.height - 40) < 1e-6) - #expect(abs(circular.currentPoint.x - 90) < 1e-6) - #expect(abs(circular.currentPoint.y - 40) < 1e-6) - - let continuous = Path(roundedRect: rect, cornerSize: CGSize(width: 10, height: 8), style: .continuous).cgPath - let continuousBounds = continuous.boundingBoxOfPath - #expect(abs(continuousBounds.origin.x - 10) < 1e-5) - #expect(abs(continuousBounds.origin.y - 20) < 1e-5) - #expect(abs(continuousBounds.size.width - 80) < 1e-5) - #expect(abs(continuousBounds.size.height - 40) < 1e-5) - - let oversizedCircular = FixedRoundedRect(rect, cornerSize: CGSize(width: 100, height: 100), style: .circular).cgPath - #expect(abs(oversizedCircular.boundingBoxOfPath.size.width - 80) < 1e-6) - #expect(abs(oversizedCircular.boundingBoxOfPath.size.height - 40) < 1e-6) - - var custom = Path() - custom.move(to: CGPoint(x: 2, y: 3)) - custom.addLine(to: CGPoint(x: 12, y: 23)) - #expect(custom.cgPath.boundingBoxOfPath == CGRect(x: 2, y: 3, width: 10, height: 20)) - } + @Test(arguments: RectFallbackInput.allCases) + func rectAndDegenerateRoundedInitializersStoreRect(input: RectFallbackInput) { + let rect = CGRect(x: 10, y: 20, width: 80, height: 40) + let (path, expectedRect): (Path, CGRect) = switch input { + case .plainRect: + (Path(rect), rect) + case .zeroCornerRadius: + (Path(roundedRect: rect, cornerRadius: 0), rect) + case .zeroCornerSize: + (Path(roundedRect: rect, cornerSize: .zero), rect) + case .infiniteEllipse: + (Path(ellipseIn: .infinite), .infinite) + case .infiniteRoundedRect: + (Path(roundedRect: .infinite, cornerRadius: 10), .infinite) + } - @Test - func stringRepresentationAndParsing() { - #expect(Path().description == "inf inf m inf inf l inf inf l inf inf l h") + #expect(path.rect() == expectedRect) + } - let validCases: [(String, String)] = [ - ("100 0 m 200 100 l h", "100 0 m 200 100 l h"), - ("0 0 m 50 0 100 100 q", "0 0 m 50 0 100 100 q"), - ("0 0 m 25 0 75 100 100 100 c", "0 0 m 25 0 75 100 100 100 c"), - ("0 0 m 50 0 100 100 q 200 0 t", "0 0 m 50 0 100 100 q 150 200 200 0 q"), - ("0 0 m 50 50 100 100 v", "0 0 m 0 0 50 50 100 100 c"), - ("0 0 m 25 0 100 100 y", "0 0 m 25 0 100 100 100 100 c"), - ("10 20 30 40 re", "10 20 m 40 20 l 40 60 l 10 60 l h"), - ("-10 -20 m 0.5 1.5 l", "-10 -20 m 0.5 1.5 l"), - ("0\t0\nm\r\n100\t100\tl", "0 0 m 100 100 l"), - ("100 200m", "100 200 m"), - ("1.5e2 -2.5e1 m", "150 -25 m"), - ] + @Test(arguments: [ + (CGRect(x: 0, y: 0, width: 40, height: 40), true), + (CGRect(x: 0, y: 0, width: 40, height: 20), false), + ]) + func roundedRectIntrospection(ellipseRect: CGRect, isCircle: Bool) { + let ellipse = Path(ellipseIn: ellipseRect) + #expect(ellipse.rect() == nil) + if isCircle { + #expect(ellipse.roundedRect() == FixedRoundedRect(ellipseRect, cornerRadius: 20, style: .circular)) + } else { + #expect(ellipse.roundedRect() == nil) + } - for (input, expected) in validCases { - let parsed = Path(input) - #expect(parsed != nil) - #expect(parsed?.description == expected) + let rounded = Path(roundedRect: ellipseRect, cornerSize: CGSize(width: 6, height: 8), style: .continuous) + #expect(rounded.rect() == nil) + #expect(rounded.roundedRect() == FixedRoundedRect(ellipseRect, cornerSize: CGSize(width: 6, height: 8), style: .continuous)) } - #expect(Path("Inf -inf m") != nil) + @Test + func mutableCGPathAndBuilderClosureCopyIndependently() { + let mutable = CGMutablePath() + mutable.move(to: CGPoint(x: 0, y: 0)) + mutable.addLine(to: CGPoint(x: 10, y: 20)) + let fromMutable = Path(mutable) + mutable.addLine(to: CGPoint(x: 100, y: 200)) + + let fromClosure = Path { path in + path.move(to: CGPoint(x: 0, y: 0)) + path.addLine(to: CGPoint(x: 10, y: 20)) + } - for invalid in ["0 0 z", "0 m", "1 2 3 4 5 6 7 m", "10 20 rx"] { - #expect(Path(invalid) == nil) + #expect(fromMutable == fromClosure) + #expect(fromMutable.boundingRect == CGRect(x: 0, y: 0, width: 10, height: 20)) } } - @Test - func appendingElementsPreservesControlsAndOriginalCopy() { - var path = Path() - path.move(to: CGPoint(x: 1, y: 2)) - path.addLine(to: CGPoint(x: 3, y: 4)) - let original = path - path.addQuadCurve(to: CGPoint(x: 7, y: 8), control: CGPoint(x: 5, y: 6)) - path.addCurve(to: CGPoint(x: 13, y: 14), control1: CGPoint(x: 9, y: 10), control2: CGPoint(x: 11, y: 12)) - path.closeSubpath() - - var elements: [Path.Element] = [] - path.forEach { elements.append($0) } - #expect(elements == [ - .move(to: CGPoint(x: 1, y: 2)), - .line(to: CGPoint(x: 3, y: 4)), - .quadCurve(to: CGPoint(x: 7, y: 8), control: CGPoint(x: 5, y: 6)), - .curve(to: CGPoint(x: 13, y: 14), control1: CGPoint(x: 9, y: 10), control2: CGPoint(x: 11, y: 12)), - .closeSubpath, + // MARK: - Subpaths & Element Construction + + struct ElementsAndSubpaths { + @Test + func curveElementsAndCopyOnWrite() { + var path = Path() + path.move(to: CGPoint(x: 1, y: 2)) + path.addLine(to: CGPoint(x: 3, y: 4)) + let snapshot = path + + path.addQuadCurve(to: CGPoint(x: 7, y: 8), control: CGPoint(x: 5, y: 6)) + path.addCurve(to: CGPoint(x: 13, y: 14), control1: CGPoint(x: 9, y: 10), control2: CGPoint(x: 11, y: 12)) + path.closeSubpath() + + #expect(elements(of: path) == [ + .move(to: CGPoint(x: 1, y: 2)), + .line(to: CGPoint(x: 3, y: 4)), + .quadCurve(to: CGPoint(x: 7, y: 8), control: CGPoint(x: 5, y: 6)), + .curve(to: CGPoint(x: 13, y: 14), control1: CGPoint(x: 9, y: 10), control2: CGPoint(x: 11, y: 12)), + .closeSubpath, + ]) + #expect(elements(of: snapshot) == [ + .move(to: CGPoint(x: 1, y: 2)), + .line(to: CGPoint(x: 3, y: 4)), + ]) + #expect(snapshot.currentPoint == CGPoint(x: 3, y: 4)) + } + + @Test(arguments: [ + ([], true, nil as CGPoint?), + ([CGPoint(x: 1, y: 2), CGPoint(x: 5, y: 6), CGPoint(x: 9, y: 10)], false, CGPoint(x: 9, y: 10)), ]) - var originalElements: [Path.Element] = [] - original.forEach { originalElements.append($0) } - #expect(originalElements == [ - .move(to: CGPoint(x: 1, y: 2)), - .line(to: CGPoint(x: 3, y: 4)), + func addLines(points: [CGPoint], expectsEmpty: Bool, expectedCurrent: CGPoint?) { + var path = Path() + path.addLines(points) + + #expect(path.isEmpty == expectsEmpty) + #expect(path.currentPoint == expectedCurrent) + } + + @Test(arguments: [ + ([] as [CGRect], CGRect.null, nil as CGRect?), + ([CGRect(x: 0, y: 0, width: 10, height: 20)], CGRect(x: 0, y: 0, width: 10, height: 20), CGRect(x: 0, y: 0, width: 10, height: 20)), + ([CGRect(x: 0, y: 0, width: 10, height: 10), CGRect(x: 20, y: 30, width: 10, height: 10)], CGRect(x: 0, y: 0, width: 30, height: 40), nil), ]) - #expect(original.currentPoint == CGPoint(x: 3, y: 4)) - } + func addRects(rects: [CGRect], expectedBounds: CGRect, expectedSingleRect: CGRect?) { + var path = Path() + path.addRects(rects) - enum BufferedShape: CaseIterable { - case rect, ellipse, roundedRect - } + #expect(path.boundingRect == expectedBounds) + #expect(path.rect() == expectedSingleRect) + } - @Test(arguments: BufferedShape.allCases) - func bufferedShapesPreserveNegativeRectSizes(shape: BufferedShape) { - let rect = CGRect(x: 10, y: 20, width: -6, height: -8) - let transform = CGAffineTransform(translationX: 100, y: 200) - var path = Path() - // Keep the append operation on the buffer path. - path.move(to: CGPoint(x: 107, y: 216)) - switch shape { - case .rect: - path.addRect(rect, transform: transform) - case .ellipse: - path.addEllipse(in: rect, transform: transform) - case .roundedRect: - path.addRoundedRect(in: rect, cornerSize: CGSize(width: 1, height: 2), style: .circular, transform: transform) - } - - #expect(path.boundingRect == CGRect(x: 104, y: 212, width: 6, height: 8)) - } + enum BufferedPrimitive: CaseIterable, Sendable { + case rect, ellipse, roundedRect + } + + @Test(arguments: BufferedPrimitive.allCases) + func bufferedPrimitivesPreserveNegativeRectSizes(primitive: BufferedPrimitive) { + let rect = CGRect(x: 10, y: 20, width: -6, height: -8) + let transform = CGAffineTransform(translationX: 100, y: 200) + var path = Path() + path.move(to: CGPoint(x: 107, y: 216)) + + switch primitive { + case .rect: + path.addRect(rect, transform: transform) + case .ellipse: + path.addEllipse(in: rect, transform: transform) + case .roundedRect: + path.addRoundedRect(in: rect, cornerSize: CGSize(width: 1, height: 2), style: .circular, transform: transform) + } + + #expect(path.boundingRect == CGRect(x: 104, y: 212, width: 6, height: 8)) + } + + enum ArcKind: CaseIterable, Sendable { + case startEndAngles + case relativeDelta + case tangentCorner + } + + @Test(arguments: ArcKind.allCases) + func arcsPreserveTransformedEndpoints(kind: ArcKind) throws { + var path = Path() + let transform = CGAffineTransform(translationX: 5, y: 7) + + let expectedStart: CGPoint + let expectedEnd: CGPoint + switch kind { + case .startEndAngles: + path.addArc( + center: CGPoint(x: 20, y: 30), + radius: 10, + startAngle: .degrees(0), + endAngle: .degrees(90), + clockwise: false, + transform: transform + ) + expectedStart = CGPoint(x: 35, y: 37) + expectedEnd = CGPoint(x: 25, y: 47) + case .relativeDelta: + path.addRelativeArc( + center: CGPoint(x: 20, y: 30), + radius: 10, + startAngle: .degrees(0), + delta: .degrees(90), + transform: transform + ) + expectedStart = CGPoint(x: 35, y: 37) + expectedEnd = CGPoint(x: 25, y: 47) + case .tangentCorner: + path.move(to: CGPoint(x: 5, y: 7)) + path.addArc( + tangent1End: CGPoint(x: 10, y: 0), + tangent2End: CGPoint(x: 10, y: 10), + radius: 4, + transform: transform + ) + expectedStart = CGPoint(x: 5, y: 7) + expectedEnd = CGPoint(x: 15, y: 11) + } + + let recorded = elements(of: path) + #expect(recorded.first == .move(to: expectedStart)) + let end = try #require(path.currentPoint) + #expect(abs(end.x - expectedEnd.x) < 1e-5) + #expect(abs(end.y - expectedEnd.y) < 1e-5) + } + + @Test(arguments: [false, true]) + func addPathIntoEmptyAndNonEmptyBase(intoEmpty: Bool) { + let child = Path(CGRect(x: 0, y: 0, width: 10, height: 10)) + let offset = CGAffineTransform(translationX: 20, y: 30) + + var path = intoEmpty ? Path() : Path(CGRect(x: 0, y: 0, width: 5, height: 5)) + path.addPath(child, transform: offset) + path.addPath(Path()) - @Test - func transformedRoundedRectPreservesAsymmetricCorners() { - var path = Path() - path.addRoundedRect( - in: CGRect(x: 10, y: 20, width: 100, height: 100), - cornerRadii: RectangleCornerRadii(topLeading: 0, bottomLeading: 20, bottomTrailing: 30, topTrailing: 10), - style: .circular, - transform: CGAffineTransform(translationX: 100, y: 200) - ) - - #expect(path.boundingRect == CGRect(x: 110, y: 220, width: 100, height: 100)) - #expect(path.contains(CGPoint(x: 111, y: 221))) - #expect(!path.contains(CGPoint(x: 209, y: 221))) - #expect(path.contains(CGPoint(x: 205, y: 225))) - #expect(!path.contains(CGPoint(x: 111, y: 319))) - #expect(path.contains(CGPoint(x: 118, y: 312))) - #expect(!path.contains(CGPoint(x: 202, y: 312))) - #expect(path.contains(CGPoint(x: 200, y: 310))) + if intoEmpty { + #expect(path.rect() == CGRect(x: 20, y: 30, width: 10, height: 10)) + } else { + #expect(path.boundingRect == CGRect(x: 0, y: 0, width: 30, height: 40)) + } + } } - @Test(arguments: [false, true]) - func transformedArcPreservesEndpoints(relative: Bool) throws { - var path = Path() - let transform = CGAffineTransform(translationX: 5, y: 7) - if relative { - path.addRelativeArc( - center: CGPoint(x: 20, y: 30), - radius: 10, - startAngle: .degrees(0), - delta: .degrees(90), - transform: transform - ) - } else { - path.addArc( - center: CGPoint(x: 20, y: 30), - radius: 10, - startAngle: .degrees(0), - endAngle: .degrees(90), - clockwise: false, - transform: transform + // MARK: - Containment + + struct Containment { + @Test(arguments: [ + (CGPoint(x: 30, y: 30), true), // Center + (CGPoint(x: 10, y: 30), false), // Left boundary + (CGPoint(x: 50, y: 30), false), // Right boundary + (CGPoint(x: 11, y: 21), false), // Bounding-box corner outside ellipse + ]) + func ellipseInteriorAndBoundary(point: CGPoint, expected: Bool) { + let ellipse = Path(ellipseIn: CGRect(x: 10, y: 20, width: 40, height: 20)) + #expect(ellipse.contains(point) == expected) + } + + @Test(arguments: [ + (CGPoint(x: 111, y: 221), true), // Top-leading radius 0 (sharp corner) + (CGPoint(x: 209, y: 221), false), // Top-trailing radius 10 (outside arc) + (CGPoint(x: 205, y: 225), true), // Top-trailing radius 10 (inside arc) + (CGPoint(x: 111, y: 319), false), // Bottom-leading radius 20 (outside arc) + (CGPoint(x: 202, y: 312), false), // Bottom-trailing radius 30 (outside arc) + (CGPoint(x: 200, y: 310), true), // Bottom-trailing radius 30 (inside arc) + ]) + func unevenRoundedRectCorners(point: CGPoint, expected: Bool) { + var path = Path() + path.addRoundedRect( + in: CGRect(x: 10, y: 20, width: 100, height: 100), + cornerRadii: RectangleCornerRadii(topLeading: 0, bottomLeading: 20, bottomTrailing: 30, topTrailing: 10), + style: .circular, + transform: CGAffineTransform(translationX: 100, y: 200) ) + #expect(path.contains(point) == expected) } - var elements: [Path.Element] = [] - path.forEach { elements.append($0) } - #expect(elements.first == .move(to: CGPoint(x: 35, y: 37))) - let end = try #require(path.currentPoint) - // Storage can encode arc angles as Float. - #expect(abs(end.x - 25) < 1e-6) - #expect(abs(end.y - 47) < 1e-6) - } + @Test(arguments: [false, true]) + func windingVersusEvenOddFillRule(eoFill: Bool) { + let concentric = CGMutablePath() + concentric.addRect(CGRect(x: 0, y: 0, width: 100, height: 100)) + concentric.addRect(CGRect(x: 25, y: 25, width: 50, height: 50)) + let path = Path(concentric) + let queries = [CGPoint(x: 10, y: 10), CGPoint(x: 50, y: 50), CGPoint(x: 110, y: 50)] + + #expect(path.contains(queries[0], eoFill: eoFill)) + #expect(path.contains(queries[1], eoFill: eoFill) == !eoFill) + #expect(!path.contains(queries[2], eoFill: eoFill)) + #expect((path.contains(points: queries, eoFill: eoFill).rawValue & 0b111) == (eoFill ? 0b001 : 0b011)) + } - @Test(arguments: [false, true]) - func fillRule(eoFill: Bool) { - let outline = CGMutablePath() - outline.addRect(CGRect(x: 0, y: 0, width: 100, height: 100)) - outline.addRect(CGRect(x: 25, y: 25, width: 50, height: 50)) - let path = Path(outline) - let points = [CGPoint(x: 10, y: 10), CGPoint(x: 50, y: 50), CGPoint(x: 110, y: 50)] - - #expect(path.contains(points[0], eoFill: eoFill)) - #expect(path.contains(points[1], eoFill: eoFill) == !eoFill) - #expect(!path.contains(points[2], eoFill: eoFill)) - #expect((path.contains(points: points, eoFill: eoFill).rawValue & 0b111) == (eoFill ? 0b001 : 0b011)) + @Test(arguments: [0, 1, 64, 65]) + func batchContainmentMaskAndOrigin(count: Int) { + let path = Path(CGRect(x: 0, y: 0, width: 10, height: 10)) + var points = Array(repeating: CGPoint(x: 25, y: 35), count: count) + if count > 0 { + points[0] = CGPoint(x: 35, y: 35) + } + let mask = path.contains(points: points, origin: CGPoint(x: 20, y: 30)) + #expect(mask.rawValue == (count < 2 ? 0 : 0xffff_ffff_ffff_fffe)) + } } - @Test(arguments: [false, true]) - func transformedCurvePreservesControlsAndOwnership(useAffineTransform: Bool) { - let path: Path = { - let outline = CGMutablePath() - outline.move(to: CGPoint(x: 0, y: 0)) - outline.addQuadCurve(to: CGPoint(x: 10, y: 20), control: CGPoint(x: 5, y: 30)) - outline.addCurve(to: CGPoint(x: 40, y: 50), control1: CGPoint(x: 20, y: 60), control2: CGPoint(x: 30, y: 70)) - outline.closeSubpath() - return Path(outline) - }() - let mapped: Path - if useAffineTransform { - mapped = path.applying(CGAffineTransform(translationX: 100, y: 200)) - } else { - mapped = path.mapPoints { points in - for index in points.indices { - points[index].x += 100 - points[index].y += 200 + // MARK: - Transforms & Coordinate Spaces + + struct Transforms { + enum TransformMethod: CaseIterable, Sendable { + case applying + case offsetBy + case mapPoints + } + + @Test(arguments: TransformMethod.allCases) + func translationMethodsPreserveGeometry(method: TransformMethod) { + let base = Path { path in + path.move(to: CGPoint(x: 0, y: 0)) + path.addQuadCurve(to: CGPoint(x: 10, y: 20), control: CGPoint(x: 5, y: 30)) + path.addCurve(to: CGPoint(x: 40, y: 50), control1: CGPoint(x: 20, y: 60), control2: CGPoint(x: 30, y: 70)) + path.closeSubpath() + } + + let translated: Path = switch method { + case .applying: + base.applying(CGAffineTransform(translationX: 100, y: 200)) + case .offsetBy: + base.offsetBy(dx: 100, dy: 200) + case .mapPoints: + base.mapPoints { points in + for i in points.indices { + points[i].x += 100 + points[i].y += 200 + } } } + + #expect(elements(of: translated) == [ + .move(to: CGPoint(x: 100, y: 200)), + .quadCurve(to: CGPoint(x: 110, y: 220), control: CGPoint(x: 105, y: 230)), + .curve(to: CGPoint(x: 140, y: 250), control1: CGPoint(x: 120, y: 260), control2: CGPoint(x: 130, y: 270)), + .closeSubpath, + ]) + } + + @Test + func identityOffsetAndShearMapPoints() { + let rectPath = Path(CGRect(x: 0, y: 0, width: 10, height: 20)) + #expect(rectPath.offsetBy(dx: 0, dy: 0) == rectPath) + #expect(rectPath.applying(.identity) == rectPath) + + let sheared = rectPath.mapPoints { points in + for i in points.indices { + points[i].x += points[i].y + } + } + #expect(sheared.rect() == nil) + #expect(sheared.boundingRect == CGRect(x: 0, y: 0, width: 30, height: 20)) + } + + @Test + func coordinateSpaceConversion() { + var transform = ViewTransform() + transform.appendCoordinateSpace(name: "canvas") + transform.appendTranslation(CGSize(width: 3, height: 4)) + var path = Path(CGRect(x: 1, y: 2, width: 10, height: 20)) + + path.convert(to: .named("canvas"), transform: transform) + #expect(path.boundingRect == CGRect(x: -2, y: -2, width: 10, height: 20)) + + path.convert(from: .named("canvas"), transform: transform) + #expect(path.boundingRect == CGRect(x: 1, y: 2, width: 10, height: 20)) + } + } + + // MARK: - Path Operations + + struct Operations { + @Test + func shapeConformanceReturnsSelf() { + let path = Path(CGRect(x: 5, y: 6, width: 20, height: 30)) + #expect(path.path(in: CGRect(x: 0, y: 0, width: 500, height: 500)) == path) + } + + enum TrivialUnionScenario: CaseIterable, Sendable { + case ignoresEmpty + case outerKeepsSelf + case innerAdoptsOuter + case disjointCombinesBoth + } + + @Test(arguments: TrivialUnionScenario.allCases) + func formTrivialUnion(scenario: TrivialUnionScenario) { + let outer = Path(CGRect(x: 0, y: 0, width: 100, height: 100)) + let inner = Path(CGRect(x: 20, y: 20, width: 40, height: 40)) + let disjoint = Path(CGRect(x: 200, y: 0, width: 50, height: 50)) + + switch scenario { + case .ignoresEmpty: + var path = inner + path.formTrivialUnion(Path()) + #expect(path == inner) + case .outerKeepsSelf: + var path = outer + path.formTrivialUnion(inner) + #expect(path == outer) + case .innerAdoptsOuter: + var path = inner + path.formTrivialUnion(outer) + #expect(path == outer) + case .disjointCombinesBoth: + var path = inner + path.formTrivialUnion(disjoint) + #expect(path.contains(CGPoint(x: 30, y: 30))) + #expect(!path.contains(CGPoint(x: 120, y: 30))) + #expect(path.contains(CGPoint(x: 220, y: 20))) + } } - var elements: [Path.Element] = [] - mapped.forEach { elements.append($0) } - #expect(elements == [ - .move(to: CGPoint(x: 100, y: 200)), - .quadCurve(to: CGPoint(x: 110, y: 220), control: CGPoint(x: 105, y: 230)), - .curve(to: CGPoint(x: 140, y: 250), control1: CGPoint(x: 120, y: 260), control2: CGPoint(x: 130, y: 270)), - .closeSubpath, + + @Test(arguments: [ + (0.0, CGRect(x: 0, y: 0, width: 20, height: 20)), + (0.5, CGRect(x: 10, y: 20, width: 30, height: 40)), + (1.0, CGRect(x: 20, y: 40, width: 40, height: 60)), ]) + func mixInterpolatesCompatiblePaths(fraction: CGFloat, expectedBounds: CGRect) throws { + let start = Path(CGRect(x: 0, y: 0, width: 20, height: 20)) + let end = Path(CGRect(x: 20, y: 40, width: 40, height: 60)) + let mixed = try #require(start.mix(with: end, by: fraction)) + #expect(mixed.boundingRect == expectedBounds) + } + + #if canImport(Darwin) + @Test(arguments: [ + (CGLineCap.butt, CGRect(x: 0, y: -5, width: 100, height: 10)), + (CGLineCap.square, CGRect(x: -5, y: -5, width: 110, height: 10)), + ]) + func strokedPathLineWidthAndCap(lineCap: CGLineCap, expectedBounds: CGRect) { + #expect(Path().strokedPath(StrokeStyle(lineWidth: 10)).isEmpty) + + let segment = Path { path in + path.move(to: CGPoint(x: 0, y: 0)) + path.addLine(to: CGPoint(x: 100, y: 0)) + } + let stroked = segment.strokedPath(StrokeStyle(lineWidth: 10, lineCap: lineCap)) + #expect(stroked.boundingRect == expectedBounds) + } + + enum FillBooleanOp: CaseIterable, Sendable { + case union + case intersection + case subtracting + case symmetricDifference + } + + @Test(arguments: FillBooleanOp.allCases) + func booleanRegionOperations(op: FillBooleanOp) { + let lhs = Path(CGRect(x: 0, y: 0, width: 100, height: 100)) + let rhs = Path(CGRect(x: 50, y: 0, width: 100, height: 100)) + + let (result, inLeftOnly, inOverlap, inRightOnly): (Path, Bool, Bool, Bool) = switch op { + case .union: + (lhs.union(rhs), true, true, true) + case .intersection: + (lhs.intersection(rhs), false, true, false) + case .subtracting: + (lhs.subtracting(rhs), true, false, false) + case .symmetricDifference: + (lhs.symmetricDifference(rhs), true, false, true) + } + + #expect(result.contains(CGPoint(x: 25, y: 50)) == inLeftOnly) + #expect(result.contains(CGPoint(x: 75, y: 50)) == inOverlap) + #expect(result.contains(CGPoint(x: 125, y: 50)) == inRightOnly) + } + + @Test + func lineClippingNormalizationAndDilation() { + let line = Path { path in + path.move(to: CGPoint(x: 0, y: 50)) + path.addLine(to: CGPoint(x: 100, y: 50)) + } + let mask = Path(CGRect(x: 25, y: 0, width: 50, height: 100)) + + #expect(line.lineIntersection(mask).boundingRect == CGRect(x: 25, y: 50, width: 50, height: 0)) + #expect(line.lineSubtraction(mask).boundingRect == CGRect(x: 0, y: 50, width: 100, height: 0)) + + let rect = Path(CGRect(x: 10, y: 20, width: 30, height: 40)) + #expect(rect.normalized().contains(CGPoint(x: 25, y: 40))) + #expect(rect.dilatedGlyphPath(with: .zero) == rect) + // Glyph dilation expands horizontally by ±width and vertically from baseline by [0, 2 * height]. + #expect(rect.dilatedGlyphPath(with: CGSize(width: 2, height: 3)).boundingRect == CGRect(x: 8, y: 20, width: 34, height: 46)) + } + #endif } - @Test - func pathUnionKeepsDisjointRegions() { - var path = Path(CGRect(x: 0, y: 0, width: 10, height: 10)) - let original = path - path.formTrivialUnion(Path(CGRect(x: 20, y: 0, width: 10, height: 10))) - #expect(path.contains(CGPoint(x: 5, y: 5))) - #expect(!path.contains(CGPoint(x: 15, y: 5))) - #expect(path.contains(CGPoint(x: 25, y: 5))) - #expect(original.boundingRect == CGRect(x: 0, y: 0, width: 10, height: 10)) + // MARK: - String, CGPath & Protobuf Representations + + struct Representations { + @Test(arguments: [ + ("100 0 m 200 100 l h", "100 0 m 200 100 l h"), + ("0 0 m 50 0 100 100 q", "0 0 m 50 0 100 100 q"), + ("0 0 m 25 0 75 100 100 100 c", "0 0 m 25 0 75 100 100 100 c"), + ("0 0 m 50 0 100 100 q 200 0 t", "0 0 m 50 0 100 100 q 150 200 200 0 q"), + ("0 0 m 50 50 100 100 v", "0 0 m 0 0 50 50 100 100 c"), + ("0 0 m 25 0 100 100 y", "0 0 m 25 0 100 100 100 100 c"), + ("10 20 30 40 re", "10 20 m 40 20 l 40 60 l 10 60 l h"), + ("-10 -20 m 0.5 1.5 l", "-10 -20 m 0.5 1.5 l"), + ("0\t0\nm\r\n100\t100\tl", "0 0 m 100 100 l"), + ("100 200m", "100 200 m"), + ("1.5e2 -2.5e1 m", "150 -25 m"), + ]) + func validStringRoundTrip(input: String, expectedDescription: String) { + #expect(Path(input)?.description == expectedDescription) + } + + @Test(arguments: ["0 0 z", "0 m", "1 2 3 4 5 6 7 m", "10 20 rx"]) + func invalidStringReturnsNil(input: String) { + #expect(Path(input) == nil) + } + + enum StorageSample: CaseIterable, Sendable { + case empty + case rect + case ellipse + case circularRoundedRect + case continuousRoundedRect + case customSubpath + + var path: Path { + let rect = CGRect(x: 10, y: 20, width: 80, height: 40) + return switch self { + case .empty: + Path() + case .rect: + Path(rect) + case .ellipse: + Path(ellipseIn: rect) + case .circularRoundedRect: + Path(roundedRect: rect, cornerSize: CGSize(width: 10, height: 8), style: .circular) + case .continuousRoundedRect: + Path(roundedRect: rect, cornerSize: CGSize(width: 10, height: 8), style: .continuous) + case .customSubpath: + Path { path in + path.move(to: CGPoint(x: 1, y: 2)) + path.addLine(to: CGPoint(x: 3, y: 4)) + path.addQuadCurve(to: CGPoint(x: 7, y: 8), control: CGPoint(x: 5, y: 6)) + path.addCurve(to: CGPoint(x: 13, y: 14), control1: CGPoint(x: 9, y: 10), control2: CGPoint(x: 11, y: 12)) + path.closeSubpath() + } + } + } + } + + @Test(arguments: StorageSample.allCases) + func cgPathMatchesBounds(sample: StorageSample) { + let path = sample.path + let cgBounds = path.cgPath.boundingBoxOfPath + + if sample == .empty { + #expect(cgBounds == .null) + #expect(path.description == "inf inf m inf inf l inf inf l inf inf l h") + } else { + let expected = path.boundingRect + #expect(abs(cgBounds.origin.x - expected.origin.x) < 1e-5) + #expect(abs(cgBounds.origin.y - expected.origin.y) < 1e-5) + #expect(abs(cgBounds.size.width - expected.size.width) < 1e-5) + #expect(abs(cgBounds.size.height - expected.size.height) < 1e-5) + } + } + + @Test(arguments: StorageSample.allCases) + func protobufRoundTrip(sample: StorageSample) throws { + let original = sample.path + let encoded = try ProtobufEncoder.encoding(original) + var decoder = ProtobufDecoder(encoded) + let decoded = try Path(from: &decoder) + #expect(decoded == original) + } } } + +private func elements(of path: Path) -> [Path.Element] { + var result: [Path.Element] = [] + path.forEach { result.append($0) } + return result +} diff --git a/Tests/OpenSwiftUICoreTests/Shape/Path/TrimmedPathTests.swift b/Tests/OpenSwiftUICoreTests/Shape/Path/TrimmedPathTests.swift index bdec34cfd..33641730a 100644 --- a/Tests/OpenSwiftUICoreTests/Shape/Path/TrimmedPathTests.swift +++ b/Tests/OpenSwiftUICoreTests/Shape/Path/TrimmedPathTests.swift @@ -7,44 +7,51 @@ import OpenCoreGraphicsShims import OpenSwiftUICore import Testing +@Suite(.tags(.aigc)) struct TrimmedPathTests { @Test - func emptyPath() { - let path = Path() - - #expect(path.trimmedPath(from: 0.25, to: 0.75).isEmpty) + func emptyPathRemainsEmpty() { + #expect(Path().trimmedPath(from: 0.25, to: 0.75).isEmpty) } - @Test - func fullRangeReturnsOriginalPath() { + @Test(arguments: [ + (0.0, 1.0), + (-0.5, 1.5), + ]) + func fullOrSupersetRangeReturnsOriginalPath(from: CGFloat, to: CGFloat) { let path = Path(CGRect(x: 10, y: 20, width: 30, height: 40)) - - #expect(path.trimmedPath(from: 0, to: 1) == path) - #expect(path.trimmedPath(from: -1, to: 2) == path) + #expect(path.trimmedPath(from: from, to: to) == path) } @Test(arguments: [ (0.5, 0.5), (0.75, 0.25), - ] as [(CGFloat, CGFloat)]) - func nonIncreasingRangeIsEmpty(from: CGFloat, to: CGFloat) { + ]) + func nonIncreasingRangeReturnsEmptyPath(from: CGFloat, to: CGFloat) { let path = Path(CGRect(x: 10, y: 20, width: 30, height: 40)) - #expect(path.trimmedPath(from: from, to: to).isEmpty) } - @Test - func partialRectangle() { - let trimmedPath = Path(CGRect(x: 0, y: 0, width: 100, height: 100)) - .trimmedPath(from: 0.125, to: 0.375) - let expectedBounds = CGRect(x: 50, y: 0, width: 50, height: 50) - - #expect(!trimmedPath.isEmpty) - #expect(trimmedPath.boundingRect == expectedBounds) - - let path = trimmedPath.cgPath - - #expect(path.boundingBoxOfPath == expectedBounds) - #expect(path.currentPoint == CGPoint(x: 100, y: 50)) + @Test(arguments: [ + // Perimeter of 100x100 rect starts at (0, 0) -> (100, 0) -> (100, 100) -> (0, 100) -> (0, 0) + (0.0, 0.25, CGRect(x: 0, y: 0, width: 100, height: 0), CGPoint(x: 100, y: 0)), + (0.125, 0.375, CGRect(x: 50, y: 0, width: 50, height: 50), CGPoint(x: 100, y: 50)), + (0.5, 0.75, CGRect(x: 0, y: 100, width: 100, height: 0), CGPoint(x: 0, y: 100)), + ]) + func partialSquarePerimeterSegments( + from: CGFloat, + to: CGFloat, + expectedBounds: CGRect, + expectedCurrentPoint: CGPoint + ) { + let trimmed = Path(CGRect(x: 0, y: 0, width: 100, height: 100)) + .trimmedPath(from: from, to: to) + + #expect(!trimmed.isEmpty) + #expect(trimmed.boundingRect == expectedBounds) + + let cgPath = trimmed.cgPath + #expect(cgPath.boundingBoxOfPath == expectedBounds) + #expect(cgPath.currentPoint == expectedCurrentPoint) } } From 5a660ff1befe2cd77afdfa04e35fc28d20b32ff1 Mon Sep 17 00:00:00 2001 From: Kyle Date: Sun, 22 Nov 2026 16:38:45 +0800 Subject: [PATCH 18/22] docs(skills): prefer DocC examples in UI tests --- .../skills/openswiftui-test-authoring/references/ui-tests.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.agents/skills/openswiftui-test-authoring/references/ui-tests.md b/.agents/skills/openswiftui-test-authoring/references/ui-tests.md index ced007901..2d363dcae 100644 --- a/.agents/skills/openswiftui-test-authoring/references/ui-tests.md +++ b/.agents/skills/openswiftui-test-authoring/references/ui-tests.md @@ -6,6 +6,9 @@ Follow the nearest test under `Example/Tests/OpenSwiftUIUITests`. - Exercise public API through rendered example content. Add or change shared example content only when the requested UI test needs an entry point. +- Prefer examples from official DocC documentation and SDK doc comments for the + target API when authoring shared examples and UI snapshot cases, adapting + only as needed for deterministic sizing, layout, or supported dependencies. - Use the existing snapshot helpers, suite traits, and platform guards instead of introducing a parallel harness. - Make layout, state, and timing deterministic enough that the snapshot represents From aa8bff94210924e41fd70df9b75baa15d7940ffb Mon Sep 17 00:00:00 2001 From: Kyle Date: Sun, 22 Nov 2026 16:38:46 +0800 Subject: [PATCH 19/22] feat(example): add Path and Shape examples and UI tests --- Example/Shared/Shape/FlowerView.swift | 10 +- Example/Shared/Shape/PathExample.swift | 280 ++++++++++++++++++ Example/Shared/Shape/ShapeExample.swift | 178 +++++++++++ .../Shape/PathUITests.swift | 61 ++++ .../ShapeStyle/BackgroundStyleUITests.swift | 5 +- .../Shape/ShapeUITests.swift | 40 ++- 6 files changed, 564 insertions(+), 10 deletions(-) create mode 100644 Example/Shared/Shape/PathExample.swift create mode 100644 Example/Shared/Shape/ShapeExample.swift create mode 100644 Example/Tests/OpenSwiftUIUITests/Shape/PathUITests.swift diff --git a/Example/Shared/Shape/FlowerView.swift b/Example/Shared/Shape/FlowerView.swift index cd3b44a31..47f6f59b3 100644 --- a/Example/Shared/Shape/FlowerView.swift +++ b/Example/Shared/Shape/FlowerView.swift @@ -2,12 +2,12 @@ // FlowerView.swift // Shared +import Foundation #if OPENSWIFTUI import OpenSwiftUI #else import SwiftUI #endif -import Foundation struct FlowerView: View { var body: some View { @@ -44,3 +44,11 @@ struct FlowerViewAnimation: View { .task { animate = true } } } + +#Preview("Static") { + FlowerView() +} + +#Preview("Animated") { + FlowerViewAnimation() +} diff --git a/Example/Shared/Shape/PathExample.swift b/Example/Shared/Shape/PathExample.swift new file mode 100644 index 000000000..ab1ba9048 --- /dev/null +++ b/Example/Shared/Shape/PathExample.swift @@ -0,0 +1,280 @@ +// +// PathExample.swift +// Shared + +import Foundation +#if OPENSWIFTUI +import OpenSwiftUI +#else +import SwiftUI +#endif + +struct PathTrimExample: View { + enum RangeKind: String, CaseIterable { + case full + case threeQuarters + case leftLobe + + var fractions: (start: CGFloat, end: CGFloat) { + switch self { + case .full: (0.0, 1.0) + case .threeQuarters: (0.25, 1.0) + case .leftLobe: (0.0, 0.5) + } + } + } + + var range: RangeKind = .threeQuarters + + var body: some View { + let fractions = range.fractions + Path { path in + path.addLines([ + .init(x: 2, y: 1), + .init(x: 1, y: 0), + .init(x: 0, y: 1), + .init(x: 1, y: 2), + .init(x: 3, y: 0), + .init(x: 4, y: 1), + .init(x: 3, y: 2), + .init(x: 2, y: 1), + ]) + } + .applying(CGAffineTransform(translationX: 20, y: 60).scaledBy(x: 40, y: 40)) + .trim(from: fractions.start, to: fractions.end) + .stroke(Color.primary, lineWidth: 3) + .frame(width: 200, height: 200) + } +} + +struct PathArcSectorExample: View { + var body: some View { + Path { path in + path.move(to: CGPoint(x: 40, y: 40)) + path.addLine(to: CGPoint(x: 160, y: 40)) + path.addArc( + center: CGPoint(x: 40, y: 40), + radius: 120, + startAngle: .zero, + endAngle: .degrees(90), + clockwise: false + ) + path.closeSubpath() + } + .fill(.orange) + .stroke(.red, lineWidth: 4) + .frame(width: 200, height: 200) + } +} + +struct PathTrapezoidBackgroundExample: View { + enum StyleKind: String, CaseIterable { + case explicitTeal + case defaultBackground + } + + var styleKind: StyleKind = .explicitTeal + + private var trapezoid: Path { + Path { path in + path.move(to: .zero) + path.addLine(to: CGPoint(x: 90, y: 0)) + path.addLine(to: CGPoint(x: 80, y: 50)) + path.addLine(to: CGPoint(x: 10, y: 50)) + path.closeSubpath() + } + } + + private var flagIcon: some View { + Path { path in + path.move(to: CGPoint(x: 2, y: 1)) + path.addLine(to: CGPoint(x: 2, y: 15)) + path.move(to: CGPoint(x: 2, y: 2)) + path.addLine(to: CGPoint(x: 14, y: 5)) + path.addLine(to: CGPoint(x: 2, y: 9)) + path.closeSubpath() + } + .fill(.primary) + .stroke(.primary, lineWidth: 1.5) + .frame(width: 16, height: 16) + } + + var body: some View { + switch styleKind { + case .explicitTeal: + HStack(spacing: 6) { + flagIcon + Text("Flag") + } + .frame(width: 90, height: 50) + .background(.teal, in: trapezoid) + case .defaultBackground: + ZStack { + Color.teal + HStack(spacing: 6) { + flagIcon + Text("Flag") + } + .frame(width: 90, height: 50) + .background(in: trapezoid) + } + .frame(width: 160, height: 100) + } + } +} + +struct PathCurvesAndFillRuleExample: View { + enum Variant: String, CaseIterable { + case bezierBadge + case evenOddRings + case nonZeroRings + case starFromString + } + + var variant: Variant = .bezierBadge + + private var concentricRings: Path { + Path { path in + path.addEllipse(in: CGRect(x: 30, y: 30, width: 140, height: 140)) + path.addEllipse(in: CGRect(x: 65, y: 65, width: 70, height: 70)) + } + } + + var body: some View { + Group { + switch variant { + case .bezierBadge: + Path { path in + path.move(to: CGPoint(x: 30, y: 110)) + path.addQuadCurve( + to: CGPoint(x: 170, y: 110), + control: CGPoint(x: 100, y: 20) + ) + path.addCurve( + to: CGPoint(x: 30, y: 110), + control1: CGPoint(x: 150, y: 185), + control2: CGPoint(x: 50, y: 185) + ) + path.closeSubpath() + } + .fill(.indigo) + .stroke(.cyan, lineWidth: 4) + case .evenOddRings: + concentricRings + .fill(.teal, style: FillStyle(eoFill: true)) + case .nonZeroRings: + concentricRings + .fill(.teal, style: FillStyle(eoFill: false)) + case .starFromString: + (Path("100 25 m 123 165 l 30 78 l 170 78 l 77 165 l h") ?? Path()) + .fill(.purple, style: FillStyle(eoFill: true)) + } + } + .frame(width: 200, height: 200) + } +} + +struct PathBooleanExample: View { + enum Operation: String, CaseIterable { + case union + case intersection + case subtracting + case symmetricDifference + case lineIntersection + case lineSubtraction + } + + var operation: Operation = .symmetricDifference + + private var circlePath: Path { + Path(ellipseIn: CGRect(x: 25, y: 45, width: 110, height: 110)) + } + + private var roundedRectPath: Path { + Path(roundedRect: CGRect(x: 65, y: 45, width: 110, height: 110), cornerRadius: 24) + } + + private var stripeLines: Path { + Path { path in + for y in stride(from: 45.0, through: 155.0, by: 18.0) { + path.move(to: CGPoint(x: 20, y: y)) + path.addLine(to: CGPoint(x: 180, y: y)) + } + } + } + + var body: some View { + Group { + switch operation { + case .union: + circlePath.union(roundedRectPath) + .fill(.blue) + case .intersection: + circlePath.intersection(roundedRectPath) + .fill(.green) + case .subtracting: + circlePath.subtracting(roundedRectPath) + .fill(.orange) + case .symmetricDifference: + circlePath.symmetricDifference(roundedRectPath) + .fill(.pink) + case .lineIntersection: + stripeLines.lineIntersection(circlePath) + .stroke(.teal, style: StrokeStyle(lineWidth: 4, lineCap: .round)) + case .lineSubtraction: + stripeLines.lineSubtraction(circlePath) + .stroke(.indigo, style: StrokeStyle(lineWidth: 4, lineCap: .round)) + } + } + .frame(width: 200, height: 200) + } +} + +#Preview("Trim Infinity") { + VStack { + PathTrimExample(range: .threeQuarters) + PathTrimExample(range: .leftLobe) + } +} + +#Preview("Arc Sector") { + PathArcSectorExample() +} + +#Preview("Trapezoid Background") { + VStack(spacing: 16) { + PathTrapezoidBackgroundExample(styleKind: .explicitTeal) + PathTrapezoidBackgroundExample(styleKind: .defaultBackground) + } + .padding() +} + +#Preview("Curves & Fill Rules") { + VStack { + HStack { + PathCurvesAndFillRuleExample(variant: .bezierBadge) + PathCurvesAndFillRuleExample(variant: .starFromString) + } + HStack { + PathCurvesAndFillRuleExample(variant: .evenOddRings) + PathCurvesAndFillRuleExample(variant: .nonZeroRings) + } + } +} + +#Preview("Boolean Operations") { + VStack { + HStack { + PathBooleanExample(operation: .union) + PathBooleanExample(operation: .intersection) + } + HStack { + PathBooleanExample(operation: .subtracting) + PathBooleanExample(operation: .symmetricDifference) + } + HStack { + PathBooleanExample(operation: .lineIntersection) + PathBooleanExample(operation: .lineSubtraction) + } + } +} diff --git a/Example/Shared/Shape/ShapeExample.swift b/Example/Shared/Shape/ShapeExample.swift new file mode 100644 index 000000000..7cb68dc1c --- /dev/null +++ b/Example/Shared/Shape/ShapeExample.swift @@ -0,0 +1,178 @@ +// +// ShapeExample.swift +// Shared + +import Foundation +#if OPENSWIFTUI +import OpenSwiftUI +#else +import SwiftUI +#endif + +struct BuiltInShapeExample: View { + enum Kind: String, CaseIterable { + case rectangle + case circle + case ellipse + case capsuleCircular + case capsuleContinuous + case roundedRectangleCircular + case roundedRectangleContinuous + case unevenRoundedRectangle + } + + var kind: Kind = .roundedRectangleContinuous + + var body: some View { + Group { + switch kind { + case .rectangle: + Rectangle() + .fill(.teal) + case .circle: + Circle() + .fill(.red) + case .ellipse: + Ellipse() + .fill(.orange) + case .capsuleCircular: + Capsule(style: .circular) + .fill(.green) + case .capsuleContinuous: + Capsule(style: .continuous) + .fill(.mint) + case .roundedRectangleCircular: + RoundedRectangle(cornerRadius: 24, style: .circular) + .fill(.blue) + case .roundedRectangleContinuous: + RoundedRectangle(cornerRadius: 24, style: .continuous) + .fill(.indigo) + case .unevenRoundedRectangle: + UnevenRoundedRectangle( + cornerRadii: RectangleCornerRadii( + topLeading: 30, + bottomLeading: 10, + bottomTrailing: 30, + topTrailing: 10 + ), + style: .continuous + ) + .fill(.purple) + } + } + .frame(width: 150, height: 100) + } +} + +struct ShapeStrokeExample: View { + enum Variant: String, CaseIterable { + case circleLineWidth + case roundedRectMint + case dashedCapsule + case filledAndStrokedCapsule + } + + var variant: Variant = .dashedCapsule + + var body: some View { + Group { + switch variant { + case .circleLineWidth: + Circle() + .stroke(Color.purple, lineWidth: 5) + .frame(width: 120, height: 120) + case .roundedRectMint: + RoundedRectangle(cornerRadius: 10) + .stroke(.mint, lineWidth: 10) + .frame(width: 160, height: 50) + case .dashedCapsule: + Capsule() + .stroke( + Color.purple, + style: StrokeStyle( + lineWidth: 5, + lineCap: .round, + lineJoin: .miter, + miterLimit: 0, + dash: [5, 10], + dashPhase: 0 + ) + ) + .frame(width: 150, height: 80) + case .filledAndStrokedCapsule: + Capsule() + .fill(.yellow) + .stroke(.blue, lineWidth: 8) + .frame(width: 150, height: 80) + } + } + } +} + +struct ShapeStrokeBorderExample: View { + enum Variant: String, CaseIterable { + case roundedRectangle + case insetCircle + case unevenRoundedRectangle + } + + var variant: Variant = .unevenRoundedRectangle + + var body: some View { + Group { + switch variant { + case .roundedRectangle: + RoundedRectangle(cornerRadius: 20, style: .continuous) + .fill(.mint.opacity(0.25)) + .strokeBorder(.mint, lineWidth: 8) + .frame(width: 150, height: 100) + case .insetCircle: + Circle() + .inset(by: 12) + .fill(.orange.opacity(0.2)) + .strokeBorder(.orange, lineWidth: 8) + .frame(width: 140, height: 140) + case .unevenRoundedRectangle: + UnevenRoundedRectangle( + cornerRadii: RectangleCornerRadii( + topLeading: 30, + bottomLeading: 10, + bottomTrailing: 30, + topTrailing: 10 + ), + style: .continuous + ) + .fill(.blue.opacity(0.2)) + .strokeBorder(.blue, lineWidth: 5) + .frame(width: 160, height: 100) + } + } + } +} + +#Preview("Built-in Shapes") { + VStack(spacing: 12) { + ForEach(BuiltInShapeExample.Kind.allCases, id: \.rawValue) { kind in + BuiltInShapeExample(kind: kind) + } + } + .padding() +} + +#Preview("Strokes") { + VStack(spacing: 20) { + ForEach(ShapeStrokeExample.Variant.allCases, id: \.rawValue) { variant in + ShapeStrokeExample(variant: variant) + } + } + .padding() +} + +#Preview("Stroke Borders") { + VStack(spacing: 20) { + ForEach(ShapeStrokeBorderExample.Variant.allCases, id: \.rawValue) { variant in + ShapeStrokeBorderExample(variant: variant) + } + } + .padding() +} diff --git a/Example/Tests/OpenSwiftUIUITests/Shape/PathUITests.swift b/Example/Tests/OpenSwiftUIUITests/Shape/PathUITests.swift new file mode 100644 index 000000000..e3f53a361 --- /dev/null +++ b/Example/Tests/OpenSwiftUIUITests/Shape/PathUITests.swift @@ -0,0 +1,61 @@ +// +// PathUITests.swift +// OpenSwiftUIUITests + +import SnapshotTesting +import Testing +@testable import TestingHost + +@MainActor +@Suite(.snapshots(record: .never, diffTool: diffTool)) +struct PathUITests { + @Test(arguments: PathTrimExample.RangeKind.allCases) + func trimInfinity(range: PathTrimExample.RangeKind) { + openSwiftUIAssertSnapshot( + of: PathTrimExample(range: range), + named: range.rawValue + ) + } + + @Test + func arcSector() { + openSwiftUIAssertSnapshot(of: PathArcSectorExample()) + } + + @Test + func trapezoidBackground() { + openSwiftUIAssertSnapshot( + of: PathTrapezoidBackgroundExample(styleKind: .explicitTeal) + ) + } + + @Test(.disabled { + #if os(macOS) + // FIXME: Update RenderShape DL + true + #else + false + #endif + }) + func trapezoidDefaultBackground() { + openSwiftUIAssertSnapshot( + of: PathTrapezoidBackgroundExample(styleKind: .defaultBackground) + ) + } + + @Test(arguments: PathCurvesAndFillRuleExample.Variant.allCases) + func curvesAndFillRules(variant: PathCurvesAndFillRuleExample.Variant) { + openSwiftUIAssertSnapshot( + of: PathCurvesAndFillRuleExample(variant: variant), + named: variant.rawValue + ) + } + + @Test(arguments: PathBooleanExample.Operation.allCases) + func booleanOperations(operation: PathBooleanExample.Operation) { + openSwiftUIAssertSnapshot( + of: PathBooleanExample(operation: operation), + named: operation.rawValue + ) + } +} diff --git a/Example/Tests/OpenSwiftUIUITests/Shape/ShapeStyle/BackgroundStyleUITests.swift b/Example/Tests/OpenSwiftUIUITests/Shape/ShapeStyle/BackgroundStyleUITests.swift index f904b9a6e..290a88d38 100644 --- a/Example/Tests/OpenSwiftUIUITests/Shape/ShapeStyle/BackgroundStyleUITests.swift +++ b/Example/Tests/OpenSwiftUIUITests/Shape/ShapeStyle/BackgroundStyleUITests.swift @@ -2,8 +2,8 @@ // BackgroundStyleUITests.swift // OpenSwiftUIUITests -import Testing import SnapshotTesting +import Testing @MainActor @Suite(.snapshots(record: .never, diffTool: diffTool)) @@ -95,8 +95,7 @@ struct BackgroundStyleUITests { openSwiftUIAssertSnapshot(of: ContentView()) } - // FIXME - @Test(.disabled("Shape color does not match")) + @Test func backgroundWithContent() { struct ContentView: View { var body: some View { diff --git a/Example/Tests/OpenSwiftUIUITests/Shape/ShapeUITests.swift b/Example/Tests/OpenSwiftUIUITests/Shape/ShapeUITests.swift index 515f70e05..8df00a1d2 100644 --- a/Example/Tests/OpenSwiftUIUITests/Shape/ShapeUITests.swift +++ b/Example/Tests/OpenSwiftUIUITests/Shape/ShapeUITests.swift @@ -2,8 +2,9 @@ // ShapeUITests.swift // OpenSwiftUIUITests -import Testing import SnapshotTesting +import Testing +@testable import TestingHost @MainActor @Suite(.snapshots(record: .never, diffTool: diffTool)) @@ -20,8 +21,7 @@ struct ShapeUITests { openSwiftUIAssertSnapshot(of: ContentView()) } - // FIXME - @Test(.disabled("Shape color does not match")) + @Test func circle() { struct ContentView: View { var body: some View { @@ -33,16 +33,44 @@ struct ShapeUITests { openSwiftUIAssertSnapshot(of: ContentView()) } - // FIXME - @Test(.disabled("Shape color does not match")) + @Test func shadow() { struct ContentView: View { var body: some View { Circle() - .fill(Color.red.shadow(.drop(color: .blue,radius: 5, x: 10, y: 10))) + .fill(Color.red.shadow(.drop(color: .blue, radius: 5, x: 10, y: 10))) .frame(width: 100, height: 100, alignment: .center) } } openSwiftUIAssertSnapshot(of: ContentView()) } + + @Test(arguments: BuiltInShapeExample.Kind.allCases) + func builtInShapes(kind: BuiltInShapeExample.Kind) { + openSwiftUIAssertSnapshot( + of: BuiltInShapeExample(kind: kind), + named: kind.rawValue + ) + } + + @Test(arguments: ShapeStrokeExample.Variant.allCases) + func strokes(variant: ShapeStrokeExample.Variant) { + openSwiftUIAssertSnapshot( + of: ShapeStrokeExample(variant: variant), + named: variant.rawValue + ) + } + + @Test(arguments: ShapeStrokeBorderExample.Variant.allCases) + func strokeBorders(variant: ShapeStrokeBorderExample.Variant) { + openSwiftUIAssertSnapshot( + of: ShapeStrokeBorderExample(variant: variant), + named: variant.rawValue + ) + } + + @Test + func flower() { + openSwiftUIAssertSnapshot(of: FlowerView()) + } } From 1c6e04ef49e608f76cb423c1d2c5855559dc755b Mon Sep 17 00:00:00 2001 From: Kyle Date: Sun, 22 Nov 2026 16:59:29 +0800 Subject: [PATCH 20/22] chore(example): restore path, stroke, and border modifiers in examples --- Example/Shared/Layout/CustomLayout/FlowLayout.swift | 9 ++++----- .../GeometryEffect/MatchedGeometryEffectExample.swift | 6 ++---- Example/Shared/View/ConditionalContentExample.swift | 1 - Example/Shared/View/Image/SunsetSceneExample.swift | 9 ++++----- Example/Shared/View/Text/FontPlayground.swift | 7 ++++--- 5 files changed, 14 insertions(+), 18 deletions(-) diff --git a/Example/Shared/Layout/CustomLayout/FlowLayout.swift b/Example/Shared/Layout/CustomLayout/FlowLayout.swift index a90555f26..2c5dfacf4 100644 --- a/Example/Shared/Layout/CustomLayout/FlowLayout.swift +++ b/Example/Shared/Layout/CustomLayout/FlowLayout.swift @@ -155,7 +155,7 @@ struct FlowLayoutDemo: View { } } .padding() -// .background(.thinMaterial, in: RoundedRectangle(cornerRadius: 16)) + .background(.thinMaterial, in: RoundedRectangle(cornerRadius: 16)) // GroupBox("Fixed width container (320)") { // FlowLayout(spacing: 8, rowSpacing: 8, alignment: .center, maxRowWidth: 320) { @@ -194,9 +194,8 @@ private struct TagChip: View { .padding(.horizontal, 12) .padding(.vertical, 6) .background(Color.accentColor.opacity(0.12), in: Capsule()) - // TODO: strokePath is not supported yet. -// .overlay { -// Capsule().strokeBorder(Color.accentColor.opacity(0.35)) -// } + .overlay { + Capsule().strokeBorder(Color.accentColor.opacity(0.35)) + } } } diff --git a/Example/Shared/Render/GeometryEffect/MatchedGeometryEffectExample.swift b/Example/Shared/Render/GeometryEffect/MatchedGeometryEffectExample.swift index 0d979e8c9..9cf9bc4b4 100644 --- a/Example/Shared/Render/GeometryEffect/MatchedGeometryEffectExample.swift +++ b/Example/Shared/Render/GeometryEffect/MatchedGeometryEffectExample.swift @@ -50,8 +50,7 @@ struct MatchedGeometryEffectModifierExample: View { } } .frame(width: 250).padding(10) - // TODO: strokePath not implemented -// .border(Color.gray, width: 3) + .border(Color.gray, width: 3) } } @@ -93,8 +92,7 @@ struct MatchedGeometryEffectClipShapeModifierExample: View { } } .frame(width: 250).padding(10) - // TODO: strokePath not implemented -// .border(Color.gray, width: 3) + .border(Color.gray, width: 3) } } diff --git a/Example/Shared/View/ConditionalContentExample.swift b/Example/Shared/View/ConditionalContentExample.swift index 5b9a2ebad..b4dd5b789 100644 --- a/Example/Shared/View/ConditionalContentExample.swift +++ b/Example/Shared/View/ConditionalContentExample.swift @@ -9,7 +9,6 @@ import SwiftUI #endif import Foundation -// FIXME struct ConditionalContentExample: View { @State private var first = true diff --git a/Example/Shared/View/Image/SunsetSceneExample.swift b/Example/Shared/View/Image/SunsetSceneExample.swift index 1034682a7..c192fb292 100644 --- a/Example/Shared/View/Image/SunsetSceneExample.swift +++ b/Example/Shared/View/Image/SunsetSceneExample.swift @@ -427,11 +427,10 @@ private struct BadgeView: View { Capsule() .fill(Color.black.opacity(0.3)) } - // TODO: strokePath is not supported yet. -// .overlay { -// Capsule() -// .stroke(Color.white.opacity(0.2), lineWidth: 1) -// } + .overlay { + Capsule() + .stroke(Color.white.opacity(0.2), lineWidth: 1) + } .padding(.bottom, 40) } } diff --git a/Example/Shared/View/Text/FontPlayground.swift b/Example/Shared/View/Text/FontPlayground.swift index dbb0f00b9..519e50e8b 100644 --- a/Example/Shared/View/Text/FontPlayground.swift +++ b/Example/Shared/View/Text/FontPlayground.swift @@ -42,12 +42,9 @@ struct FontPlayground: View { #if canImport(UIKit) Text("BackdropText") .font(.headline) - - #if !OPENSWIFTUI // FIXME: CGPath crash BackdropText() .font(.custom("Avenir", size: 32).italic()) #endif - #endif Text("Inter 4.1: slant × weight") .font(.headline) @@ -457,3 +454,7 @@ private extension UIFont { } } #endif + +#Preview { + FontPlayground() +} From 978c754fb7ad75d3059ad31372ea34a3957b4ea4 Mon Sep 17 00:00:00 2001 From: Kyle Date: Sun, 22 Nov 2026 17:45:37 +0800 Subject: [PATCH 21/22] feat(example): add PathPlayground showcase --- .../Shared/Shape/{ => Path}/PathExample.swift | 0 .../Shared/Shape/Path/PathPlayground.swift | 537 ++++++++++++++++++ 2 files changed, 537 insertions(+) rename Example/Shared/Shape/{ => Path}/PathExample.swift (100%) create mode 100644 Example/Shared/Shape/Path/PathPlayground.swift diff --git a/Example/Shared/Shape/PathExample.swift b/Example/Shared/Shape/Path/PathExample.swift similarity index 100% rename from Example/Shared/Shape/PathExample.swift rename to Example/Shared/Shape/Path/PathExample.swift diff --git a/Example/Shared/Shape/Path/PathPlayground.swift b/Example/Shared/Shape/Path/PathPlayground.swift new file mode 100644 index 000000000..65bcd4988 --- /dev/null +++ b/Example/Shared/Shape/Path/PathPlayground.swift @@ -0,0 +1,537 @@ +// +// PathPlayground.swift +// Shared + +import Foundation +#if OPENSWIFTUI +import OpenSwiftUI +#else +import SwiftUI +#endif + +struct PathPlayground: View { + private var frameworkName: String { + #if OPENSWIFTUI + "OpenSwiftUI" + #else + "SwiftUI" + #endif + } + + var body: some View { + ZStack { + Color(red: 0.06, green: 0.07, blue: 0.12) + .ignoresSafeArea() + + VStack(spacing: 12) { + headerBar + + VStack(spacing: 10) { + HStack(spacing: 10) { + ShowcaseCard(title: "Bezier & forEach", subtitle: "addCurve · quadCurve") { + BezierInspectorArtwork() + } + ShowcaseCard(title: "Boolean CSG", subtitle: "xor · intersect · union") { + BooleanCSGArtwork() + } + } + + HStack(spacing: 10) { + ShowcaseCard(title: "Line Clip & Hit-Test", subtitle: "lineIntersection · contains") { + LineClipAndContainsArtwork() + } + ShowcaseCard(title: "Trim, Arcs & Dashes", subtitle: "trim · StrokeStyle · applying") { + TrimAndDashesArtwork() + } + } + + HStack(spacing: 10) { + ShowcaseCard(title: "String & Winding", subtitle: "Path(String) · eoFill") { + StringAndEvenOddArtwork() + } + ShowcaseCard(title: "Inset & Borders", subtitle: "strokeBorder · background(in:)") { + InsetAndBorderArtwork() + } + } + } + + footerStrip + } + .padding(16) + } + } + + private var headerBar: some View { + HStack(spacing: 10) { + PathBrandEmblem() + .frame(width: 34, height: 34) + + VStack(alignment: .leading, spacing: 2) { + Text("Path & Shape") + .font(.system(size: 17, weight: .bold)) + .foregroundStyle(.white) + Text("Complete API & Rendering Parity") + .font(.system(size: 11, weight: .medium)) + .foregroundStyle(.white.opacity(0.65)) + } + + Spacer() + + Text(frameworkName) + .font(.system(size: 11, weight: .semibold, design: .monospaced)) + .foregroundStyle(.cyan) + .padding(.horizontal, 10) + .padding(.vertical, 5) + .background(.cyan.opacity(0.15), in: Capsule(style: .continuous)) + .overlay { + Capsule(style: .continuous) + .strokeBorder(.cyan.opacity(0.5), lineWidth: 1) + } + } + .frame(width: 350) + } + + private var footerStrip: some View { + Text("Curves · Arcs · Trim · Dashes · CSG · eoFill · String · Cross-Platform") + .font(.system(size: 9.5, weight: .medium, design: .monospaced)) + .foregroundStyle(.white.opacity(0.5)) + .frame(width: 350) + } +} + +// MARK: - Card Container + +private struct ShowcaseCard: View { + let title: String + let subtitle: String + @ViewBuilder let content: () -> Content + + private let cardShape = RoundedRectangle(cornerRadius: 16, style: .continuous) + + var body: some View { + VStack(alignment: .leading, spacing: 4) { + content() + .frame(width: 150, height: 96) + + Text(title) + .font(.system(size: 11.5, weight: .semibold)) + .foregroundStyle(.white) + + Text(subtitle) + .font(.system(size: 9.5, weight: .regular, design: .monospaced)) + .foregroundStyle(.white.opacity(0.55)) + } + .padding(10) + .frame(width: 170, height: 148) + .background(Color(red: 0.11, green: 0.13, blue: 0.20), in: cardShape) + .overlay { + cardShape + .strokeBorder(.white.opacity(0.12), lineWidth: 1) + } + } +} + +// MARK: - Header Emblem + +private struct PathBrandEmblem: View { + private let tile = RoundedRectangle(cornerRadius: 9, style: .continuous) + + private var spline: Path { + Path { p in + p.move(to: CGPoint(x: 8, y: 25)) + p.addCurve( + to: CGPoint(x: 26, y: 9), + control1: CGPoint(x: 8, y: 11), + control2: CGPoint(x: 26, y: 23) + ) + } + } + + private var nodes: Path { + Path { p in + p.addEllipse(in: CGRect(x: 5.5, y: 22.5, width: 5, height: 5)) + p.addEllipse(in: CGRect(x: 23.5, y: 6.5, width: 5, height: 5)) + } + } + + var body: some View { + ZStack { + tile.fill( + LinearGradient( + colors: [.cyan, .blue, .indigo], + startPoint: .topLeading, + endPoint: .bottomTrailing + ) + ) + tile.strokeBorder(.white.opacity(0.35), lineWidth: 1) + spline.stroke(.white, style: StrokeStyle(lineWidth: 2.4, lineCap: .round)) + nodes.fill(.white) + } + } +} + +// MARK: - 1. Bezier & Element Iteration + +private struct BezierInspectorArtwork: View { + private var spline: Path { + Path { p in + p.move(to: CGPoint(x: 16, y: 72)) + p.addCurve( + to: CGPoint(x: 88, y: 38), + control1: CGPoint(x: 32, y: 12), + control2: CGPoint(x: 62, y: 84) + ) + p.addQuadCurve( + to: CGPoint(x: 134, y: 24), + control: CGPoint(x: 112, y: 8) + ) + } + } + + private var ribbonFill: Path { + var p = spline + p.addLine(to: CGPoint(x: 134, y: 84)) + p.addCurve( + to: CGPoint(x: 16, y: 84), + control1: CGPoint(x: 96, y: 68), + control2: CGPoint(x: 52, y: 90) + ) + p.closeSubpath() + return p + } + + private var echoWave: Path { + spline.applying(CGAffineTransform(translationX: 0, y: 10)) + } + + private var inspectionOverlay: (handles: Path, controls: Path, anchors: Path) { + var handles = Path() + var controls = Path() + var anchors = Path() + var current = CGPoint.zero + + func addDot(_ point: CGPoint, radius: CGFloat, into target: inout Path) { + target.addEllipse( + in: CGRect( + x: point.x - radius, + y: point.y - radius, + width: radius * 2, + height: radius * 2 + ) + ) + } + + spline.forEach { element in + switch element { + case let .move(to: end): + current = end + addDot(end, radius: 3.2, into: &anchors) + case let .line(to: end): + current = end + addDot(end, radius: 3.2, into: &anchors) + case let .quadCurve(to: end, control: c): + handles.move(to: current) + handles.addLine(to: c) + handles.addLine(to: end) + addDot(c, radius: 2.8, into: &controls) + addDot(end, radius: 3.2, into: &anchors) + current = end + case let .curve(to: end, control1: c1, control2: c2): + handles.move(to: current) + handles.addLine(to: c1) + handles.move(to: end) + handles.addLine(to: c2) + addDot(c1, radius: 2.8, into: &controls) + addDot(c2, radius: 2.8, into: &controls) + addDot(end, radius: 3.2, into: &anchors) + current = end + case .closeSubpath: + break + } + } + return (handles, controls, anchors) + } + + var body: some View { + let overlay = inspectionOverlay + ZStack { + ribbonFill.fill(.cyan.opacity(0.22)) + echoWave.stroke( + .indigo.opacity(0.75), + style: StrokeStyle(lineWidth: 1.8, lineCap: .round) + ) + overlay.handles.stroke( + .white.opacity(0.45), + style: StrokeStyle(lineWidth: 1, lineCap: .round, dash: [3, 3]) + ) + spline.stroke( + .cyan, + style: StrokeStyle(lineWidth: 3.2, lineCap: .round) + ) + overlay.controls.fill(.orange) + overlay.anchors.fill(.white) + } + } +} + +// MARK: - 2. Boolean CSG + +private struct BooleanCSGArtwork: View { + private var leftCircle: Path { + Path(ellipseIn: CGRect(x: 24, y: 10, width: 64, height: 64)) + } + + private var rightCircle: Path { + Path(ellipseIn: CGRect(x: 62, y: 10, width: 64, height: 64)) + } + + private var lowerRoundedRect: Path { + Path( + roundedRect: CGRect(x: 43, y: 32, width: 64, height: 54), + cornerRadius: 16, + style: .continuous + ) + } + + var body: some View { + let xorFill = leftCircle + .symmetricDifference(rightCircle) + .symmetricDifference(lowerRoundedRect) + let pairwiseLens = leftCircle + .intersection(rightCircle) + .subtracting(lowerRoundedRect) + let tripleCore = leftCircle + .intersection(rightCircle) + .intersection(lowerRoundedRect) + let unionContour = leftCircle + .union(rightCircle) + .union(lowerRoundedRect) + + ZStack { + xorFill.fill(.orange.opacity(0.85)) + pairwiseLens.fill(.pink.opacity(0.65)) + tripleCore.fill(.yellow) + unionContour.stroke(.white.opacity(0.8), lineWidth: 1.4) + } + } +} + +// MARK: - 3. Line Clipping & Point Containment + +private struct LineClipAndContainsArtwork: View { + private var targetRegion: Path { + let outer = Path( + roundedRect: CGRect(x: 26, y: 10, width: 98, height: 76), + cornerRadii: .init(topLeading: 26, bottomLeading: 10, bottomTrailing: 26, topTrailing: 10), + style: .continuous + ) + let hole = Path(ellipseIn: CGRect(x: 56, y: 29, width: 38, height: 38)) + return outer.subtracting(hole) + } + + private var hatchLines: Path { + let raw = Path { p in + for x in stride(from: -36.0, through: 138.0, by: 9.0) { + p.move(to: CGPoint(x: x, y: 88)) + p.addLine(to: CGPoint(x: x + 52, y: 8)) + } + } + let bounds = Path(CGRect(x: 12, y: 8, width: 126, height: 80)) + return raw.lineIntersection(bounds) + } + + private var probePoints: (inside: Path, outside: Path) { + let region = targetRegion + var inside = Path() + var outside = Path() + for x in stride(from: 18.0, through: 132.0, by: 19.0) { + let pt = CGPoint(x: x, y: 48) + let dot = CGRect(x: pt.x - 2.6, y: pt.y - 2.6, width: 5.2, height: 5.2) + if region.contains(pt) { + inside.addEllipse(in: dot) + } else { + outside.addEllipse(in: dot) + } + } + return (inside, outside) + } + + var body: some View { + let region = targetRegion + let hatch = hatchLines + let probes = probePoints + + ZStack { + hatch.lineSubtraction(region) + .stroke(.indigo.opacity(0.45), style: StrokeStyle(lineWidth: 1.4, lineCap: .round)) + + hatch.lineIntersection(region) + .stroke(.mint, style: StrokeStyle(lineWidth: 2.6, lineCap: .round)) + + region.stroke(.cyan.opacity(0.45), lineWidth: 1.1) + probes.outside.fill(.white.opacity(0.35)) + probes.inside.fill(.yellow) + } + } +} + +// MARK: - 4. Trim, Arcs & Dashes + +private struct TrimAndDashesArtwork: View { + private var outerGauge: Path { + Path { p in + p.addArc( + center: CGPoint(x: 75, y: 50), + radius: 38, + startAngle: .degrees(135), + endAngle: .degrees(45), + clockwise: false + ) + } + } + + private var middleOrbit: Path { + Path { p in + p.addArc( + center: CGPoint(x: 75, y: 50), + radius: 27, + startAngle: .degrees(135), + endAngle: .degrees(45), + clockwise: false + ) + } + } + + private var infinityLoop: Path { + Path { p in + p.addLines([ + CGPoint(x: 0, y: 0), + CGPoint(x: -1, y: -0.75), + CGPoint(x: -1.8, y: 0), + CGPoint(x: -1, y: 0.75), + CGPoint(x: 1, y: -0.75), + CGPoint(x: 1.8, y: 0), + CGPoint(x: 1, y: 0.75), + CGPoint(x: 0, y: 0), + ]) + } + .applying(CGAffineTransform(translationX: 75, y: 52).scaledBy(x: 10.5, y: 10.5)) + } + + var body: some View { + ZStack { + outerGauge.stroke( + .white.opacity(0.12), + style: StrokeStyle(lineWidth: 6, lineCap: .round) + ) + outerGauge + .trim(from: 0.0, to: 0.28) + .stroke(.cyan, style: StrokeStyle(lineWidth: 6, lineCap: .round)) + outerGauge + .trim(from: 0.34, to: 0.62) + .stroke(.mint, style: StrokeStyle(lineWidth: 6, lineCap: .round)) + outerGauge + .trim(from: 0.68, to: 0.88) + .stroke(.orange, style: StrokeStyle(lineWidth: 6, lineCap: .round)) + + middleOrbit + .trim(from: 0.06, to: 0.94) + .stroke( + .purple.opacity(0.9), + style: StrokeStyle(lineWidth: 2.4, lineCap: .round, dash: [5, 5]) + ) + + infinityLoop + .trim(from: 0.1, to: 0.92) + .stroke( + .white, + style: StrokeStyle(lineWidth: 2.2, lineCap: .round, lineJoin: .round) + ) + } + } +} + +// MARK: - 5. String Parsing & Even-Odd Winding + +private struct StringAndEvenOddArtwork: View { + private var starPath: Path { + Path("75 11 m 98 81 l 38 38 l 112 38 l 52 81 l h") ?? Path() + } + + private var compoundRosette: Path { + let star = starPath + return Path { p in + p.addEllipse(in: CGRect(x: 35, y: 8, width: 80, height: 80)) + p.addPath(star) + p.addEllipse(in: CGRect(x: 60, y: 33, width: 30, height: 30)) + } + } + + var body: some View { + let rosette = compoundRosette + ZStack { + rosette.fill(.purple.opacity(0.85), style: FillStyle(eoFill: true)) + starPath.stroke(.cyan.opacity(0.85), style: StrokeStyle(lineWidth: 1.3, lineJoin: .round)) + rosette.stroke(.white.opacity(0.35), lineWidth: 1) + } + } +} + +// MARK: - 6. Insettable Shapes & Shape Background + +private struct ChamferedPill: Shape { + func path(in rect: CGRect) -> Path { + let cut = min(rect.height * 0.32, 9) + return Path { p in + p.move(to: CGPoint(x: rect.minX + cut, y: rect.minY)) + p.addLine(to: CGPoint(x: rect.maxX - cut, y: rect.minY)) + p.addLine(to: CGPoint(x: rect.maxX, y: rect.midY)) + p.addLine(to: CGPoint(x: rect.maxX - cut, y: rect.maxY)) + p.addLine(to: CGPoint(x: rect.minX + cut, y: rect.maxY)) + p.addLine(to: CGPoint(x: rect.minX, y: rect.midY)) + p.closeSubpath() + } + } +} + +private struct InsetAndBorderArtwork: View { + private let outerFrame = UnevenRoundedRectangle( + cornerRadii: .init(topLeading: 24, bottomLeading: 8, bottomTrailing: 24, topTrailing: 8), + style: .continuous + ) + + var body: some View { + ZStack { + outerFrame + .fill(.teal.opacity(0.16)) + .frame(width: 126, height: 78) + + outerFrame + .strokeBorder(.teal, lineWidth: 3.5) + .frame(width: 126, height: 78) + + outerFrame + .inset(by: 9) + .strokeBorder( + .mint.opacity(0.75), + style: StrokeStyle(lineWidth: 1.8, lineCap: .round, dash: [5, 4]) + ) + .frame(width: 126, height: 78) + + Text("1:1 PARITY") + .font(.system(size: 10, weight: .bold, design: .monospaced)) + .foregroundStyle(.white) + .padding(.horizontal, 12) + .padding(.vertical, 6) + .background(.teal.opacity(0.45), in: ChamferedPill()) + .overlay { + ChamferedPill() + .stroke(.cyan.opacity(0.8), lineWidth: 1.2) + } + } + } +} + +#Preview { + PathPlayground() +} From 8ff339f8e222ed3be2c0caf36145b8e8cc3a4970 Mon Sep 17 00:00:00 2001 From: Kyle Date: Sun, 22 Nov 2026 18:04:03 +0800 Subject: [PATCH 22/22] fix(displaylist): add space before path description in SExp printer --- .../Render/DisplayList/DisplayListPrinter.swift | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Sources/OpenSwiftUICore/Render/DisplayList/DisplayListPrinter.swift b/Sources/OpenSwiftUICore/Render/DisplayList/DisplayListPrinter.swift index 944f5ce3f..b4ae6ab80 100644 --- a/Sources/OpenSwiftUICore/Render/DisplayList/DisplayListPrinter.swift +++ b/Sources/OpenSwiftUICore/Render/DisplayList/DisplayListPrinter.swift @@ -128,13 +128,13 @@ extension DisplayList.Content.Value { printer.pop() case let .shape(path, paint, style): printer.push("shape") - printer.print("(path\(path.description))") + printer.print("(path \(path.description))") printer.print("(paint \(paint))") printer.print("(style \(style))") printer.pop() case let .shadow(path, shadow): printer.push("shadow") - printer.print("(path\(path.description))") + printer.print("(path \(path.description))") printer.print("(shadow \(shadow))") printer.pop() case .platformView: @@ -254,7 +254,7 @@ extension DisplayList.Effect { printer.print("#:blend-mode \(mode)", newline: false) case let .clip(path, style, options): printer.push("clip") - printer.print("(path\(path.description))") + printer.print("(path \(path.description))") printer.print("(style \(style))") if !options.isEmpty { printer.print("(options \(options))")