diff --git a/packages/frontend/hosts/ios/AGENTS.md b/packages/frontend/hosts/ios/AGENTS.md index 8e5736fb22..016c4c4ddf 100644 --- a/packages/frontend/hosts/ios/AGENTS.md +++ b/packages/frontend/hosts/ios/AGENTS.md @@ -1,7 +1,7 @@ # Working in `packages/frontend/hosts/ios/` (for agents) This directory holds the zero-CocoaPods iOS thin host for AFFiNE. -It bridges `UIKit`, `CAMetalLayer`, ProMotion `CADisplayLink`, and `UITextInput` to the Rust client workspace through a C ABI. +It bridges `UIKit`, `CAMetalLayer`, ProMotion `CADisplayLink`, `UITextInput`, native teardrop selection handles and magnifier loupe (`SelectionOverlayView`), per-frame keyboard avoidance (`KeyboardAvoidanceCoordinator`), system `PDFKit` page rasterization (`PdfRendererBridge`), and UIKit haptics (`HapticsBridge`) to the Rust client workspace through a C ABI. ## Hard boundaries @@ -10,6 +10,9 @@ It bridges `UIKit`, `CAMetalLayer`, ProMotion `CADisplayLink`, and `UITextInput` - Use `LegacyLocalStorageProbe.swift` only as a one-shot sentinel and rollback writer under `capacitor://localhost` for whitelisted `localStorage` keys. Keep the `window.indexedDB` runtime trap active so IndexedDB access stays strictly zero. - Share `/workspaces///.db` in place through `affine-store` and mount local workspaces strictly from the `affine-local-workspace` allowlist without scanning disk for `*.db` files. - Keep `LegacyAuthBridge.swift` and `src/auth.rs` aligned with Keychain service `app.affine.pro.auth-token` (2001 reference epoch `f64` timestamps) and `UserDefaults` key `app.affine.pro.auth-installation-id`. +- Keep `SelectionOverlayView.swift` pure `UIView`/`CALayer` (zero `WKWebView`), drive all handle/loupe geometry from Rust `src/selection.rs`, and drive shaped CoreText `CTTypesetter`/`CTLine` text geometry, BiDi selection rects, and whole-line `CTLineDraw` loupe rendering through `TextRenderingBridge.swift` / `src/ffi_text.rs` (with headless Rust fallback in `src/text_layout.rs`). `HostTextPreviewView` is an S3 thin-host transition preview layer and will be removed when S4 attaches the GPU `blocksuite-editor` renderer to avoid double-drawing. +- Keep `KeyboardAvoidanceCoordinator.swift` aligned with `ui::WindowInsets::effective()` (`ime_bottom` is the absolute docked keyboard overlap from the window bottom edge, `effective_bottom = max(safe_bottom, ime_bottom)`, and `affine_ios_host_ime_above_safe_bottom` exposes `max(0, ime_bottom - safe_bottom)` to avoid double-deducting safe area), returning `0` for floating, split, and external hardware keyboards. +- Keep `PdfRendererBridge.swift` backed by Apple's system `PDFKit` framework (zero C++ PDFium) with explicit `affine_ios_host_pdf_open`/`close` document handles (zero persistent cache) and enforce the shared Rust header, page-bounds, and pixel-budget limits in `src/pdf.rs`. - Pin Rust builds in `scripts/build-rust-ios.sh` to `rustup run 1.98.1`, `--manifest-path packages/frontend/Cargo.toml`, and `CARGO_ENCODED_RUSTFLAGS=""`. Never modify `packages/frontend/apps/ios/` (`1.97.1`). ## Verification diff --git a/packages/frontend/hosts/ios/Sources/HapticsBridge.swift b/packages/frontend/hosts/ios/Sources/HapticsBridge.swift new file mode 100644 index 0000000000..4dd8d2a0d6 --- /dev/null +++ b/packages/frontend/hosts/ios/Sources/HapticsBridge.swift @@ -0,0 +1,134 @@ +import Foundation +import UIKit + +enum AffineHapticPatternSwift: UInt8, CaseIterable, Equatable { + case lightImpact = 0 + case mediumImpact = 1 + case heavyImpact = 2 + case selectionChanged = 3 + case success = 4 + case warning = 5 + case error = 6 +} + +/// Bridges Rust haptic pattern triggers to UIKit feedback generators with pre-warming +/// and main-thread-safe dispatch. +final class HapticsBridge { + static let maxRecordedPatterns = 64 + + private let lock = NSLock() + private var recordedPatterns: [AffineHapticPatternSwift] = [] + + private var lightGenerator: UIImpactFeedbackGenerator? + private var mediumGenerator: UIImpactFeedbackGenerator? + private var heavyGenerator: UIImpactFeedbackGenerator? + private var selectionGenerator: UISelectionFeedbackGenerator? + private var notificationGenerator: UINotificationFeedbackGenerator? + + var dispatchedPatterns: [AffineHapticPatternSwift] { + lock.lock() + defer { lock.unlock() } + return recordedPatterns + } + + func resetDispatchedPatterns() { + lock.lock() + recordedPatterns.removeAll() + lock.unlock() + } + + func prepareAll() { + dispatchOnMain { + self.ensureGeneratorsOnMain() + self.lightGenerator?.prepare() + self.mediumGenerator?.prepare() + self.heavyGenerator?.prepare() + self.selectionGenerator?.prepare() + self.notificationGenerator?.prepare() + } + } + + func trigger(_ pattern: AffineHapticPatternSwift) { + lock.lock() + if recordedPatterns.count >= Self.maxRecordedPatterns { + recordedPatterns.removeFirst(recordedPatterns.count - Self.maxRecordedPatterns + 1) + } + recordedPatterns.append(pattern) + lock.unlock() + + dispatchOnMain { + self.ensureGeneratorsOnMain() + switch pattern { + case .lightImpact: + self.lightGenerator?.impactOccurred() + self.lightGenerator?.prepare() + case .mediumImpact: + self.mediumGenerator?.impactOccurred() + self.mediumGenerator?.prepare() + case .heavyImpact: + self.heavyGenerator?.impactOccurred() + self.heavyGenerator?.prepare() + case .selectionChanged: + self.selectionGenerator?.selectionChanged() + self.selectionGenerator?.prepare() + case .success: + self.notificationGenerator?.notificationOccurred(.success) + self.notificationGenerator?.prepare() + case .warning: + self.notificationGenerator?.notificationOccurred(.warning) + self.notificationGenerator?.prepare() + case .error: + self.notificationGenerator?.notificationOccurred(.error) + self.notificationGenerator?.prepare() + } + } + } + + func attach(to host: OpaquePointer) { + let userData = Unmanaged.passUnretained(self).toOpaque() + affine_ios_host_set_haptics_callback( + host, + { rawPattern, ctx in + guard + let ctx, + let pattern = AffineHapticPatternSwift(rawValue: rawPattern) + else { + return + } + let bridge = Unmanaged.fromOpaque(ctx).takeUnretainedValue() + bridge.trigger(pattern) + }, + userData + ) + } + + func detach(from host: OpaquePointer) { + affine_ios_host_set_haptics_callback(host, nil, nil) + } + + private func dispatchOnMain(_ work: @escaping () -> Void) { + if Thread.isMainThread { + work() + } else { + DispatchQueue.main.async(execute: work) + } + } + + private func ensureGeneratorsOnMain() { + if lightGenerator == nil { + lightGenerator = UIImpactFeedbackGenerator(style: .light) + } + if mediumGenerator == nil { + mediumGenerator = UIImpactFeedbackGenerator(style: .medium) + } + if heavyGenerator == nil { + heavyGenerator = UIImpactFeedbackGenerator(style: .heavy) + } + if selectionGenerator == nil { + selectionGenerator = UISelectionFeedbackGenerator() + } + if notificationGenerator == nil { + notificationGenerator = UINotificationFeedbackGenerator() + } + } +} diff --git a/packages/frontend/hosts/ios/Sources/KeyboardAvoidanceCoordinator.swift b/packages/frontend/hosts/ios/Sources/KeyboardAvoidanceCoordinator.swift new file mode 100644 index 0000000000..6b4a0aaee3 --- /dev/null +++ b/packages/frontend/hosts/ios/Sources/KeyboardAvoidanceCoordinator.swift @@ -0,0 +1,161 @@ +import QuartzCore +import UIKit + +/// Observes UIKit keyboard frame notifications and samples non-double-counted keyboard +/// avoidance insets on every `CADisplayLink` tick through the Rust C ABI. +final class KeyboardAvoidanceCoordinator { + weak var hostView: UIView? + var hostHandle: OpaquePointer? + var currentTimeProvider: () -> Double = { CACurrentMediaTime() } + + private(set) var lastMetrics = AffineKeyboardAvoidanceMetrics() + private(set) var lastInsets = AffineWindowInsets( + safe_top: 0, + safe_right: 0, + safe_bottom: 0, + safe_left: 0, + ime_bottom: 0 + ) + private var lastDisplayTimestamp: Double = 0 + private var observing = false + + func startObserving() { + guard !observing else { + return + } + observing = true + let center = NotificationCenter.default + center.addObserver( + self, + selector: #selector(handleKeyboardWillChangeFrame(_:)), + name: UIResponder.keyboardWillChangeFrameNotification, + object: nil + ) + center.addObserver( + self, + selector: #selector(handleKeyboardWillHide(_:)), + name: UIResponder.keyboardWillHideNotification, + object: nil + ) + } + + func stopObserving() { + guard observing else { + return + } + observing = false + NotificationCenter.default.removeObserver(self) + } + + deinit { + stopObserving() + } + + /// Sample the current eased keyboard avoidance height on each `CADisplayLink` tick. + @discardableResult + func sampleDisplayLinkFrame( + timestamp: Double, + safeAreaInsets: UIEdgeInsets + ) -> AffineWindowInsets { + lastDisplayTimestamp = timestamp + guard let handle = hostHandle else { + return lastInsets + } + let next = affine_ios_host_sample_keyboard_frame( + handle, + Float(safeAreaInsets.top), + Float(safeAreaInsets.right), + Float(safeAreaInsets.bottom), + Float(safeAreaInsets.left), + timestamp + ) + lastInsets = next + return next + } + + /// Deterministic entry point for evaluating a keyboard frame change against window bounds. + @discardableResult + func applyKeyboardFrame( + windowBounds: CGRect, + keyboardFrameInView: CGRect, + safeAreaInsets: UIEdgeInsets, + isHidden: Bool, + durationSec: Double, + timestampSec: Double + ) -> AffineKeyboardAvoidanceMetrics { + lastDisplayTimestamp = timestampSec + let cWindow = AffineRect( + x: Float(windowBounds.origin.x), + y: Float(windowBounds.origin.y), + width: Float(windowBounds.size.width), + height: Float(windowBounds.size.height) + ) + let cKeyboard = AffineRect( + x: Float(keyboardFrameInView.origin.x), + y: Float(keyboardFrameInView.origin.y), + width: Float(keyboardFrameInView.size.width), + height: Float(keyboardFrameInView.size.height) + ) + let metrics = affine_ios_keyboard_compute_avoidance( + cWindow, + cKeyboard, + Float(safeAreaInsets.bottom), + isHidden + ) + lastMetrics = metrics + + if let handle = hostHandle { + affine_ios_host_begin_keyboard_transition( + handle, + metrics.ime_bottom_pt, + timestampSec, + durationSec + ) + lastInsets = affine_ios_host_sample_keyboard_frame( + handle, + Float(safeAreaInsets.top), + Float(safeAreaInsets.right), + Float(safeAreaInsets.bottom), + Float(safeAreaInsets.left), + timestampSec + ) + } + return metrics + } + + @objc private func handleKeyboardWillChangeFrame(_ notification: Notification) { + handleKeyboardNotification(notification, isHidden: false) + } + + @objc private func handleKeyboardWillHide(_ notification: Notification) { + handleKeyboardNotification(notification, isHidden: true) + } + + private func handleKeyboardNotification(_ notification: Notification, isHidden: Bool) { + guard + let view = hostView, + let userInfo = notification.userInfo, + let endFrame = userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect + else { + return + } + let duration = (userInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as? Double) ?? 0.25 + let converted: CGRect + if let window = view.window { + converted = view.convert(endFrame, from: window.screen.coordinateSpace) + } else { + converted = view.convert(endFrame, from: nil) + } + // Always sample fresh monotonic media time so resuming after background suspension + // never reuses a stale pre-background `CADisplayLink` timestamp and skips animation frames. + let nowTs = currentTimeProvider() + _ = applyKeyboardFrame( + windowBounds: view.bounds, + keyboardFrameInView: converted, + safeAreaInsets: view.safeAreaInsets, + isHidden: isHidden, + durationSec: duration, + timestampSec: nowTs + ) + } +} diff --git a/packages/frontend/hosts/ios/Sources/MetalHostViewController.swift b/packages/frontend/hosts/ios/Sources/MetalHostViewController.swift index 45f10774f9..47a01c4ddc 100644 --- a/packages/frontend/hosts/ios/Sources/MetalHostViewController.swift +++ b/packages/frontend/hosts/ios/Sources/MetalHostViewController.swift @@ -32,6 +32,39 @@ final class AffineTextRange: UITextRange { } } +final class AffineTextSelectionRect: UITextSelectionRect { + private let selectionRect: CGRect + private let isStart: Bool + private let isEnd: Bool + + init(rect: CGRect, containsStart: Bool, containsEnd: Bool) { + self.selectionRect = rect + self.isStart = containsStart + self.isEnd = containsEnd + super.init() + } + + override var rect: CGRect { + selectionRect + } + + override var writingDirection: NSWritingDirection { + .natural + } + + override var containsStart: Bool { + isStart + } + + override var containsEnd: Bool { + isEnd + } + + override var isVertical: Bool { + false + } +} + private final class DisplayLinkProxy: NSObject { weak var target: MetalHostViewController? @@ -61,11 +94,86 @@ final class MetalHostView: UIView, UITextInput { lazy var tokenizer: UITextInputTokenizer = UITextInputStringTokenizer(textInput: self) var hostHandle: OpaquePointer? + var onSelectedRangeChanged: ((NSRange) -> Void)? + private(set) var lastCopiedText: String? private var backingText: NSString = "" private var selectedUtf16Range = NSRange(location: 0, length: 0) private var markedUtf16Range: NSRange? + var currentBackingUtf16Units: [UInt16] { + let len = backingText.length + guard len > 0 else { return [] } + var buf = Array(repeating: UInt16(0), count: len) + backingText.getCharacters(&buf, range: NSRange(location: 0, length: len)) + return buf + } + + var currentSelectedUtf16Range: NSRange { + clampRange(selectedUtf16Range) + } + + var currentWritingDirection: UInt8 { + guard let handle = hostHandle else { + return 0 + } + return affine_ios_host_text_writing_direction(handle) + } + + func updateSelectedRangeFromOverlay(_ range: NSRange) { + let clamped = clampRange(range) + selectedUtf16Range = clamped + if let handle = hostHandle { + affine_ios_host_set_selected_range( + handle, + AffineUtf16Range(location: UInt32(clamped.location), length: UInt32(clamped.length)) + ) + } + } + + override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool { + if action == #selector(copy(_:)) || action == #selector(cut(_:)) { + return selectedUtf16Range.length > 0 + } + if action == #selector(paste(_:)) { + return UIPasteboard.general.hasStrings + } + if action == #selector(selectAll(_:)) { + return backingText.length > 0 + } + return super.canPerformAction(action, withSender: sender) + } + + override func copy(_ sender: Any?) { + let clamped = clampRange(selectedUtf16Range) + guard clamped.length > 0 else { + return + } + let copied = backingText.substring(with: clamped) + lastCopiedText = copied + UIPasteboard.general.string = copied + } + + override func cut(_ sender: Any?) { + let clamped = clampRange(selectedUtf16Range) + guard clamped.length > 0 else { + return + } + copy(sender) + deleteBackward() + } + + override func paste(_ sender: Any?) { + guard let text = UIPasteboard.general.string, !text.isEmpty else { + return + } + insertText(text) + } + + override func selectAll(_ sender: Any?) { + selectedTextRange = AffineTextRange(utf16Range: NSRange(location: 0, length: backingText.length)) + } + override var canBecomeFirstResponder: Bool { true } @@ -85,6 +193,7 @@ final class MetalHostView: UIView, UITextInput { affine_ios_host_insert_text(handle, buf.baseAddress, buf.count) } } + onSelectedRangeChanged?(selectedUtf16Range) } func deleteBackward() { @@ -110,6 +219,9 @@ final class MetalHostView: UIView, UITextInput { AffineUtf16Range(location: UInt32(del.location), length: UInt32(del.length)) ) } + if deletedRange != nil { + onSelectedRangeChanged?(selectedUtf16Range) + } } private func adjustMarkedRangeAfterDeletion(_ deleted: NSRange) { @@ -158,6 +270,7 @@ final class MetalHostView: UIView, UITextInput { affine_ios_host_replace_range(handle, cRange, buf.baseAddress, buf.count) } } + onSelectedRangeChanged?(selectedUtf16Range) } var selectedTextRange: UITextRange? { @@ -174,6 +287,7 @@ final class MetalHostView: UIView, UITextInput { AffineUtf16Range(location: UInt32(clamped.location), length: UInt32(clamped.length)) ) } + onSelectedRangeChanged?(clamped) } } } @@ -208,6 +322,7 @@ final class MetalHostView: UIView, UITextInput { affine_ios_host_set_marked_text(handle, buf.baseAddress, buf.count, cRange) } } + onSelectedRangeChanged?(selectedUtf16Range) } func unmarkText() { @@ -325,33 +440,116 @@ final class MetalHostView: UIView, UITextInput { for position: UITextPosition, in direction: UITextStorageDirection ) -> NSWritingDirection { - .natural + currentWritingDirection == 1 ? .rightToLeft : .leftToRight } func setBaseWritingDirection(_ writingDirection: NSWritingDirection, for range: UITextRange) {} func firstRect(for range: UITextRange) -> CGRect { - .zero + guard let affineRange = range as? AffineTextRange else { + return .zero + } + let clamped = clampRange(affineRange.utf16Range) + let startRect = caretRect(for: AffineTextPosition(utf16Offset: clamped.location)) + if clamped.length == 0 { + return startRect + } + let endRect = caretRect(for: AffineTextPosition(utf16Offset: clamped.location + clamped.length)) + if abs(startRect.minY - endRect.minY) < 1.0 { + return CGRect( + x: min(startRect.minX, endRect.minX), + y: startRect.minY, + width: max(2.0, abs(endRect.maxX - startRect.minX)), + height: startRect.height + ) + } + return startRect } func caretRect(for position: UITextPosition) -> CGRect { - .zero + guard + let pos = position as? AffineTextPosition, + let handle = hostHandle + else { + return .zero + } + let cRect = affine_ios_host_text_caret_rect(handle, UInt32(max(0, pos.utf16Offset))) + return CGRect( + x: CGFloat(cRect.x), + y: CGFloat(cRect.y), + width: CGFloat(cRect.width), + height: CGFloat(cRect.height) + ) } func selectionRects(for range: UITextRange) -> [UITextSelectionRect] { - [] + guard + let affineRange = range as? AffineTextRange, + let handle = hostHandle + else { + return [] + } + let clamped = clampRange(affineRange.utf16Range) + guard clamped.length > 0 else { + return [] + } + let cRange = AffineUtf16Range(location: UInt32(clamped.location), length: UInt32(clamped.length)) + let count = affine_ios_host_text_selection_rects(handle, cRange, nil, 0) + guard count > 0 else { + return [] + } + var rawRects = Array(repeating: AffineSelectionRect(), count: count) + _ = rawRects.withUnsafeMutableBufferPointer { buf in + affine_ios_host_text_selection_rects(handle, cRange, buf.baseAddress, count) + } + return rawRects.map { item in + AffineTextSelectionRect( + rect: CGRect( + x: CGFloat(item.rect.x), + y: CGFloat(item.rect.y), + width: CGFloat(item.rect.width), + height: CGFloat(item.rect.height) + ), + containsStart: item.contains_start, + containsEnd: item.contains_end + ) + } } func closestPosition(to point: CGPoint) -> UITextPosition? { - endOfDocument + guard let handle = hostHandle else { + return AffineTextPosition(utf16Offset: 0) + } + let offset = affine_ios_host_text_closest_offset( + handle, + AffinePoint(x: Float(point.x), y: Float(point.y)) + ) + return AffineTextPosition(utf16Offset: Int(offset)) } func closestPosition(to point: CGPoint, within range: UITextRange) -> UITextPosition? { - range.end + guard let affineRange = range as? AffineTextRange else { + return closestPosition(to: point) + } + let clamped = clampRange(affineRange.utf16Range) + guard let pos = closestPosition(to: point) as? AffineTextPosition else { + return affineRange.end + } + let bounded = max(clamped.location, min(pos.utf16Offset, clamped.location + clamped.length)) + return AffineTextPosition(utf16Offset: bounded) } func characterRange(at point: CGPoint) -> UITextRange? { - nil + guard let pos = closestPosition(to: point) as? AffineTextPosition else { + return nil + } + let len = backingText.length + guard len > 0 else { + return AffineTextRange(utf16Range: NSRange(location: 0, length: 0)) + } + let idx = min(pos.utf16Offset, len - 1) + let cluster = backingText.rangeOfComposedCharacterSequence(at: idx) + return AffineTextRange(utf16Range: cluster) } private func clampRange(_ range: NSRange) -> NSRange { @@ -362,9 +560,24 @@ final class MetalHostView: UIView, UITextInput { } } -final class MetalHostViewController: UIViewController { +final class MetalHostViewController: UIViewController, UIEditMenuInteractionDelegate { private let hostView = MetalHostView() + private let textPreviewView = HostTextPreviewView() + private let selectionOverlayView = SelectionOverlayView() + private let keyboardAvoidanceCoordinator = KeyboardAvoidanceCoordinator() + private let pdfRendererBridge = PdfRendererBridge() + private let textRenderingBridge = TextRenderingBridge() + private let hapticsBridge = HapticsBridge() private let bootstrapCoordinator = HostBootstrapCoordinator() + private var editMenuInteraction: UIEditMenuInteraction? + private(set) var presentedMenuAnchorRect: CGRect? + private var lastSyncedInsets = AffineWindowInsets( + safe_top: 0, + safe_right: 0, + safe_bottom: 0, + safe_left: 0, + ime_bottom: 0 + ) private(set) var lastBootstrapError: Error? private var bootstrapCompleted = false private var hostHandle: OpaquePointer? @@ -372,14 +585,30 @@ final class MetalHostViewController: UIViewController { private var commandQueue: MTLCommandQueue? private var displayLink: CADisplayLink? private var displayLinkProxy: DisplayLinkProxy? - private var keyboardOverlapHeight: CGFloat = 0 - private var lastInsets = AffineWindowInsets( - safe_top: 0, - safe_right: 0, - safe_bottom: 0, - safe_left: 0, - ime_bottom: 0 - ) + + var textHostView: MetalHostView { + hostView + } + + var selectionOverlay: SelectionOverlayView { + selectionOverlayView + } + + var keyboardCoordinator: KeyboardAvoidanceCoordinator { + keyboardAvoidanceCoordinator + } + + var haptics: HapticsBridge { + hapticsBridge + } + + var textRenderer: TextRenderingBridge { + textRenderingBridge + } + + var hostPointer: OpaquePointer? { + hostHandle + } override func loadView() { view = hostView @@ -398,6 +627,60 @@ final class MetalHostViewController: UIViewController { ) hostHandle = handle hostView.hostHandle = handle + applyClearColor(TextRenderingBridge.defaultClearColorRgba) + textPreviewView.renderer = textRenderingBridge + textPreviewView.frame = hostView.bounds + textPreviewView.autoresizingMask = [.flexibleWidth, .flexibleHeight] + hostView.addSubview(textPreviewView) + + selectionOverlayView.hostHandle = handle + selectionOverlayView.frame = hostView.bounds + selectionOverlayView.autoresizingMask = [.flexibleWidth, .flexibleHeight] + hostView.addSubview(selectionOverlayView) + + let menuInteraction = UIEditMenuInteraction(delegate: self) + hostView.addInteraction(menuInteraction) + editMenuInteraction = menuInteraction + + hostView.onSelectedRangeChanged = { [weak self] range in + self?.syncSelectionOverlay(for: range) + } + selectionOverlayView.onSelectionDragResolved = { [weak self] probePoint in + guard let self else { + let fallback = CGRect(x: probePoint.x, y: probePoint.y, width: 2, height: 22) + return (0, fallback, fallback) + } + return self.resolveSelectionDrag(at: probePoint) + } + selectionOverlayView.onMenuAnchorChanged = { [weak self] anchorRect in + guard let self else { + return + } + self.presentedMenuAnchorRect = anchorRect + guard let interaction = self.editMenuInteraction else { + return + } + if let rect = anchorRect { + let config = UIEditMenuConfiguration( + identifier: nil, + sourcePoint: CGPoint(x: rect.midX, y: rect.minY) + ) + interaction.presentEditMenu(with: config) + } else { + interaction.dismissMenu() + } + } + + keyboardAvoidanceCoordinator.hostView = hostView + keyboardAvoidanceCoordinator.hostHandle = handle + keyboardAvoidanceCoordinator.startObserving() + + if let handle { + textRenderingBridge.attach(to: handle) + pdfRendererBridge.attach(to: handle) + hapticsBridge.attach(to: handle) + hapticsBridge.prepareAll() + } observeNotifications() startDisplayLink() retryBootstrapIfNeeded() @@ -425,7 +708,7 @@ final class MetalHostViewController: UIViewController { override func viewSafeAreaInsetsDidChange() { super.viewSafeAreaInsetsDidChange() - publishInsetsIfChanged() + sampleInsets(timestamp: CACurrentMediaTime()) } override func viewDidLayoutSubviews() { @@ -436,6 +719,8 @@ final class MetalHostViewController: UIViewController { width: view.bounds.width * scale, height: view.bounds.height * scale ) + textPreviewView.frame = hostView.bounds + selectionOverlayView.frame = hostView.bounds if let handle = hostHandle { affine_ios_host_resize( handle, @@ -444,19 +729,148 @@ final class MetalHostViewController: UIViewController { Float(scale) ) } - publishInsetsIfChanged() + sampleInsets(timestamp: CACurrentMediaTime()) + refreshTextPreview() + let currentRange = hostView.currentSelectedUtf16Range + if currentRange.length > 0 { + syncSelectionOverlay(for: currentRange) + } else { + selectionOverlayView.refreshFromHost() + } } deinit { displayLink?.invalidate() + keyboardAvoidanceCoordinator.stopObserving() + keyboardAvoidanceCoordinator.hostHandle = nil NotificationCenter.default.removeObserver(self) hostView.hostHandle = nil + selectionOverlayView.hostHandle = nil if let handle = hostHandle { + textRenderingBridge.detach() + pdfRendererBridge.detach(from: handle) + hapticsBridge.detach(from: handle) affine_ios_host_destroy(handle) hostHandle = nil } } + private func applyClearColor(_ rgba: UInt32) { + let bg = textRenderingBridge.applyClearColorRgba(rgba) + if hostView.backgroundColor != bg { + hostView.backgroundColor = bg + textPreviewView.setNeedsDisplay() + } + } + + private func refreshTextPreview() { + textPreviewView.utf16Units = hostView.currentBackingUtf16Units + textPreviewView.selectedRange = hostView.currentSelectedUtf16Range + textPreviewView.hostInsets = lastSyncedInsets + } + + private func syncSelectionOverlay(for range: NSRange) { + refreshTextPreview() + guard let handle = hostHandle else { + return + } + let cRange = AffineUtf16Range(location: UInt32(range.location), length: UInt32(range.length)) + var cStart = AffineRect() + var cEnd = AffineRect() + if !affine_ios_host_text_selection_endpoint_carets(handle, cRange, &cStart, &cEnd) { + let startRect = hostView.caretRect(for: AffineTextPosition(utf16Offset: range.location)) + let endRect = hostView.caretRect( + for: AffineTextPosition(utf16Offset: range.location + range.length) + ) + cStart = AffineRect( + x: Float(startRect.origin.x), + y: Float(startRect.origin.y), + width: Float(max(startRect.size.width, 2.0)), + height: Float(max(startRect.size.height, 22.0)) + ) + cEnd = AffineRect( + x: Float(endRect.origin.x), + y: Float(endRect.origin.y), + width: Float(max(endRect.size.width, 2.0)), + height: Float(max(endRect.size.height, 22.0)) + ) + } + let state = affine_ios_host_selection_set( + handle, + cStart, + cEnd, + cRange, + hostView.currentWritingDirection + ) + selectionOverlayView.applyOverlayState(state) + } + + func editMenuInteraction( + _ interaction: UIEditMenuInteraction, + targetRectFor configuration: UIEditMenuConfiguration + ) -> CGRect { + presentedMenuAnchorRect ?? .null + } + + private func resolveSelectionDrag( + at probePoint: CGPoint + ) -> (targetOffset: UInt32, startCaret: CGRect, endCaret: CGRect) { + let fallback = CGRect(x: probePoint.x - 1.0, y: probePoint.y - 11.0, width: 2.0, height: 22.0) + guard let handle = hostHandle else { + return (0, fallback, fallback) + } + let previousRange = selectionOverlayView.currentState.range + let rawAnchor = affine_ios_host_selection_drag_anchor(handle) + let anchor: UInt32 + if rawAnchor != UInt32.max { + anchor = rawAnchor + } else if selectionOverlayView.currentState.active_drag_handle == 1 { + anchor = previousRange.location + previousRange.length + } else { + anchor = previousRange.location + } + + let activeCurrentOffset: UInt32 = + selectionOverlayView.currentState.active_drag_handle == 1 + ? previousRange.location + : (previousRange.location + previousRange.length) + let targetOffset = affine_ios_host_text_closest_offset_preferred( + handle, + AffinePoint(x: Float(probePoint.x), y: Float(probePoint.y)), + activeCurrentOffset + ) + let newStart = min(anchor, targetOffset) + let newEnd = max(anchor, targetOffset) + let nextRange = AffineUtf16Range(location: newStart, length: newEnd - newStart) + if nextRange.location != previousRange.location || nextRange.length != previousRange.length { + hostView.updateSelectedRangeFromOverlay( + NSRange(location: Int(nextRange.location), length: Int(nextRange.length)) + ) + refreshTextPreview() + _ = affine_ios_host_trigger_haptic(handle, AffineHapticPatternSwift.selectionChanged.rawValue) + } + var cStart = AffineRect() + var cEnd = AffineRect() + if affine_ios_host_text_selection_endpoint_carets(handle, nextRange, &cStart, &cEnd) { + let startCaret = CGRect( + x: CGFloat(cStart.x), + y: CGFloat(cStart.y), + width: CGFloat(cStart.width), + height: CGFloat(cStart.height) + ) + let endCaret = CGRect( + x: CGFloat(cEnd.x), + y: CGFloat(cEnd.y), + width: CGFloat(cEnd.width), + height: CGFloat(cEnd.height) + ) + return (targetOffset, startCaret, endCaret) + } + let startCaret = hostView.caretRect(for: AffineTextPosition(utf16Offset: Int(newStart))) + let endCaret = hostView.caretRect(for: AffineTextPosition(utf16Offset: Int(newEnd))) + return (targetOffset, startCaret, endCaret) + } + private func configureMetalLayer() { let device = MTLCreateSystemDefaultDevice() metalDevice = device @@ -477,7 +891,7 @@ final class MetalHostViewController: UIViewController { } func handleDisplayLinkTick(_ link: CADisplayLink) { - publishInsetsIfChanged() + sampleInsets(timestamp: link.timestamp) guard let handle = hostHandle, affine_ios_host_is_dirty(handle), @@ -491,6 +905,7 @@ final class MetalHostViewController: UIViewController { guard clearRgba != 0 else { return } + applyClearColor(clearRgba) let red = Double((clearRgba >> 24) & 0xFF) / 255.0 let green = Double((clearRgba >> 16) & 0xFF) / 255.0 let blue = Double((clearRgba >> 8) & 0xFF) / 255.0 @@ -516,12 +931,6 @@ final class MetalHostViewController: UIViewController { private func observeNotifications() { let center = NotificationCenter.default - center.addObserver( - self, - selector: #selector(handleKeyboardFrameChange(_:)), - name: UIResponder.keyboardWillChangeFrameNotification, - object: nil - ) center.addObserver( self, selector: #selector(handleDidEnterBackground), @@ -548,43 +957,24 @@ final class MetalHostViewController: UIViewController { displayLink?.isPaused = false } - @objc private func handleKeyboardFrameChange(_ notification: Notification) { - guard - let userInfo = notification.userInfo, - let endFrame = userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect - else { - return - } - let converted: CGRect - if let window = view.window { - converted = view.convert(endFrame, from: window.screen.coordinateSpace) - } else { - converted = view.convert(endFrame, from: nil) - } - let intersection = view.bounds.intersection(converted) - keyboardOverlapHeight = intersection.isNull ? 0 : max(0, intersection.height) - publishInsetsIfChanged() - } - - private func publishInsetsIfChanged() { - let safe = view.safeAreaInsets - let absoluteImeBottom = max(0, keyboardOverlapHeight) - let next = AffineWindowInsets( - safe_top: Float(safe.top), - safe_right: Float(safe.right), - safe_bottom: Float(safe.bottom), - safe_left: Float(safe.left), - ime_bottom: Float(absoluteImeBottom) + func sampleInsets(timestamp: Double) { + let next = keyboardAvoidanceCoordinator.sampleDisplayLinkFrame( + timestamp: timestamp, + safeAreaInsets: view.safeAreaInsets ) - if next.safe_top != lastInsets.safe_top - || next.safe_right != lastInsets.safe_right - || next.safe_bottom != lastInsets.safe_bottom - || next.safe_left != lastInsets.safe_left - || next.ime_bottom != lastInsets.ime_bottom - { - lastInsets = next - if let handle = hostHandle { - affine_ios_host_set_insets(handle, next) + let changed = next.safe_top != lastSyncedInsets.safe_top + || next.safe_right != lastSyncedInsets.safe_right + || next.safe_bottom != lastSyncedInsets.safe_bottom + || next.safe_left != lastSyncedInsets.safe_left + || next.ime_bottom != lastSyncedInsets.ime_bottom + if changed { + lastSyncedInsets = next + refreshTextPreview() + if let handle = hostHandle, + selectionOverlayView.currentState.has_selection + || selectionOverlayView.lastMenuAnchorRect != nil + { + selectionOverlayView.applyOverlayState(affine_ios_host_selection_state(handle)) } } } diff --git a/packages/frontend/hosts/ios/Sources/PdfRendererBridge.swift b/packages/frontend/hosts/ios/Sources/PdfRendererBridge.swift new file mode 100644 index 0000000000..b2e0aa1d04 --- /dev/null +++ b/packages/frontend/hosts/ios/Sources/PdfRendererBridge.swift @@ -0,0 +1,327 @@ +import CoreGraphics +import Foundation +import PDFKit + +enum PdfRendererError: Error, Equatable { + case invalidArgument + case emptyDocument + case documentTooLarge + case invalidOrEncryptedPdf + case pathOutsideAllowedDirectory + case pageOutOfRange + case invalidDimensions + case pixelLimitExceeded + case renderFailed +} + +struct PdfDocumentHandle { + let document: PDFDocument + + var pageCount: Int { + document.pageCount + } +} + +struct PdfRenderedPage: Equatable { + let widthPx: Int + let heightPx: Int + let rgba8: Data +} + +/// Native iOS `PDFKit` page renderer bridge (zero C++ PDFium dependency). +/// Shares header, page-bounds, and OOM pixel-budget invariants with Rust `src/pdf.rs` +/// and manages explicit open/close document handles with zero persistent cache. +final class PdfRendererBridge { + static let maxDocumentBytes = 128 * 1024 * 1024 + + private let handleLock = NSLock() + private var nextDocId: UInt64 = 1 + private var openDocuments: [UInt64: PdfDocumentHandle] = [:] + + var openDocumentCount: Int { + handleLock.lock() + defer { handleLock.unlock() } + return openDocuments.count + } + + func open(data: Data) throws -> PdfDocumentHandle { + let validationCode = data.withUnsafeBytes { rawBuf -> UInt32 in + let ptr = rawBuf.bindMemory(to: UInt8.self).baseAddress + return affine_ios_pdf_validate_bytes(ptr, data.count) + } + if validationCode != 0 { + throw mapErrorCode(validationCode) + } + // Check `!doc.isLocked` (not `!doc.isEncrypted`) so PDFs with only an owner + // permission password and no user reading password still open cleanly. + guard let doc = PDFDocument(data: data), !doc.isLocked, doc.pageCount > 0 else { + throw PdfRendererError.invalidOrEncryptedPdf + } + return PdfDocumentHandle(document: doc) + } + + /// Open a PDF from a controlled local file path strictly contained inside `allowedDirectory`. + func open(fileURL: URL, allowedDirectory: URL) throws -> PdfDocumentHandle { + guard fileURL.isFileURL, allowedDirectory.isFileURL else { + throw PdfRendererError.invalidArgument + } + let canonicalRoot = allowedDirectory.standardizedFileURL.resolvingSymlinksInPath() + let canonicalFile = fileURL.standardizedFileURL.resolvingSymlinksInPath() + let rootPrefix = canonicalRoot.path.hasSuffix("/") ? canonicalRoot.path : canonicalRoot.path + "/" + guard canonicalFile.path.hasPrefix(rootPrefix) else { + throw PdfRendererError.pathOutsideAllowedDirectory + } + let attrs = try FileManager.default.attributesOfItem(atPath: canonicalFile.path) + if let fileSize = attrs[.size] as? NSNumber, fileSize.intValue > Self.maxDocumentBytes { + throw PdfRendererError.documentTooLarge + } + let data = try Data(contentsOf: canonicalFile, options: [.mappedIfSafe]) + return try open(data: data) + } + + /// Return the displayed `.cropBox` size in PDF points after applying `/Rotate`. + func pageSizePoints(of handle: PdfDocumentHandle, pageIndex: Int) throws -> CGSize { + guard pageIndex >= 0, pageIndex < handle.pageCount, let page = handle.document.page(at: pageIndex) else { + throw PdfRendererError.pageOutOfRange + } + let shownSize = displayedPageSize(page) + guard shownSize.width > 0, shownSize.height > 0 else { + throw PdfRendererError.invalidDimensions + } + return shownSize + } + + /// Rasterize a single PDF page onto a white anti-aliased RGBA8 canvas. + func renderPageRgba8( + of handle: PdfDocumentHandle, + pageIndex: Int, + targetWidthPx: Int, + targetHeightPx: Int + ) throws -> PdfRenderedPage { + guard pageIndex >= 0, let pageIdx32 = UInt32(exactly: pageIndex) else { + throw PdfRendererError.pageOutOfRange + } + guard targetWidthPx >= 0, targetHeightPx >= 0 else { + throw PdfRendererError.invalidDimensions + } + guard + let width32 = UInt32(exactly: targetWidthPx), + let height32 = UInt32(exactly: targetHeightPx) + else { + throw PdfRendererError.pixelLimitExceeded + } + let plan = affine_ios_pdf_plan_render( + pageIdx32, + UInt32(handle.pageCount), + width32, + height32 + ) + if plan.error != 0 { + throw mapErrorCode(plan.error) + } + guard let page = handle.document.page(at: pageIndex) else { + throw PdfRendererError.pageOutOfRange + } + var rgba = Data(count: plan.byte_len) + let ok = rgba.withUnsafeMutableBytes { rawBuf -> Bool in + guard let base = rawBuf.baseAddress else { + return false + } + return rasterizePage( + page, + widthPx: Int(plan.target_width_px), + heightPx: Int(plan.target_height_px), + into: base, + byteLen: plan.byte_len + ) + } + guard ok else { + throw PdfRendererError.renderFailed + } + return PdfRenderedPage( + widthPx: Int(plan.target_width_px), + heightPx: Int(plan.target_height_px), + rgba8: rgba + ) + } + + /// Register this bridge as the explicit-handle C-ABI `AffinePdfProvider` on `host`. + func attach(to host: OpaquePointer) { + let provider = AffinePdfProvider( + open_doc: { pdfPtr, pdfLen, userData in + guard let pdfPtr, pdfLen > 0, let userData else { + return 0 + } + let bridge = Unmanaged.fromOpaque(userData).takeUnretainedValue() + // Copy into owned Data once on open; freed immediately on `close_doc`. + let owned = Data(bytes: pdfPtr, count: pdfLen) + guard let handle = try? bridge.open(data: owned) else { + return 0 + } + return bridge.insertDocument(handle) + }, + close_doc: { docId, userData in + guard docId != 0, let userData else { + return + } + let bridge = Unmanaged.fromOpaque(userData).takeUnretainedValue() + bridge.removeDocument(id: docId) + }, + doc_page_count: { docId, userData in + guard docId != 0, let userData else { + return 0 + } + let bridge = Unmanaged.fromOpaque(userData).takeUnretainedValue() + guard let handle = bridge.lookupDocument(id: docId) else { + return 0 + } + return UInt32(handle.pageCount) + }, + doc_page_size: { docId, pageIndex, outSize, userData in + guard docId != 0, let outSize, let userData else { + return false + } + let bridge = Unmanaged.fromOpaque(userData).takeUnretainedValue() + guard + let handle = bridge.lookupDocument(id: docId), + let size = try? bridge.pageSizePoints(of: handle, pageIndex: Int(pageIndex)) + else { + return false + } + outSize.pointee = AffinePdfPageSize( + width_pt: Float(size.width), + height_pt: Float(size.height) + ) + return true + }, + doc_render_rgba8: { docId, pageIndex, widthPx, heightPx, outRgbaPtr, outRgbaLen, userData in + guard docId != 0, let outRgbaPtr, outRgbaLen > 0, let userData else { + return false + } + let bridge = Unmanaged.fromOpaque(userData).takeUnretainedValue() + guard + let handle = bridge.lookupDocument(id: docId), + let page = handle.document.page(at: Int(pageIndex)) + else { + return false + } + return bridge.rasterizePage( + page, + widthPx: Int(widthPx), + heightPx: Int(heightPx), + into: outRgbaPtr, + byteLen: outRgbaLen + ) + }, + user_data: Unmanaged.passUnretained(self).toOpaque() + ) + affine_ios_host_set_pdf_provider(host, provider) + } + + func detach(from host: OpaquePointer) { + let empty = AffinePdfProvider( + open_doc: nil, + close_doc: nil, + doc_page_count: nil, + doc_page_size: nil, + doc_render_rgba8: nil, + user_data: nil + ) + affine_ios_host_set_pdf_provider(host, empty) + handleLock.lock() + openDocuments.removeAll() + handleLock.unlock() + } + + private func insertDocument(_ handle: PdfDocumentHandle) -> UInt64 { + handleLock.lock() + defer { handleLock.unlock() } + let id = nextDocId + nextDocId &+= 1 + if nextDocId == 0 { + nextDocId = 1 + } + openDocuments[id] = handle + return id + } + + private func lookupDocument(id: UInt64) -> PdfDocumentHandle? { + handleLock.lock() + defer { handleLock.unlock() } + return openDocuments[id] + } + + private func removeDocument(id: UInt64) { + handleLock.lock() + openDocuments.removeValue(forKey: id) + handleLock.unlock() + } + + private func displayedPageSize(_ page: PDFPage) -> CGSize { + let box = page.bounds(for: .cropBox) + let rot = ((page.rotation % 360) + 360) % 360 + return (rot == 90 || rot == 270) + ? CGSize(width: box.height, height: box.width) + : box.size + } + + private func rasterizePage( + _ page: PDFPage, + widthPx: Int, + heightPx: Int, + into buffer: UnsafeMutableRawPointer, + byteLen: Int + ) -> Bool { + let expectedBytes = widthPx * heightPx * 4 + guard widthPx > 0, heightPx > 0, byteLen == expectedBytes else { + return false + } + let shownSize = displayedPageSize(page) + guard shownSize.width > 0, shownSize.height > 0 else { + return false + } + let colorSpace = CGColorSpaceCreateDeviceRGB() + let bitmapInfo = + CGImageAlphaInfo.premultipliedLast.rawValue | CGBitmapInfo.byteOrder32Big.rawValue + guard let ctx = CGContext( + data: buffer, + width: widthPx, + height: heightPx, + bitsPerComponent: 8, + bytesPerRow: widthPx * 4, + space: colorSpace, + bitmapInfo: bitmapInfo + ) else { + return false + } + ctx.setFillColor(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0) + ctx.fill(CGRect(x: 0, y: 0, width: widthPx, height: heightPx)) + ctx.setAllowsAntialiasing(true) + ctx.setShouldAntialias(true) + ctx.interpolationQuality = .high + + // `PDFPage.draw(with: .cropBox, to:)` already applies `-cropBox.origin` translation + // and `/Rotate` transforms; apply only the target pixel scale factor here. + ctx.saveGState() + ctx.scaleBy( + x: CGFloat(widthPx) / shownSize.width, + y: CGFloat(heightPx) / shownSize.height + ) + page.draw(with: .cropBox, to: ctx) + ctx.restoreGState() + return true + } + + private func mapErrorCode(_ code: UInt32) -> PdfRendererError { + switch code { + case 1: return .invalidArgument + case 2: return .emptyDocument + case 3: return .documentTooLarge + case 4: return .invalidOrEncryptedPdf + case 5: return .pageOutOfRange + case 6: return .invalidDimensions + case 7: return .pixelLimitExceeded + default: return .renderFailed + } + } +} diff --git a/packages/frontend/hosts/ios/Sources/SelectionOverlayView.swift b/packages/frontend/hosts/ios/Sources/SelectionOverlayView.swift new file mode 100644 index 0000000000..2fc3f132be --- /dev/null +++ b/packages/frontend/hosts/ios/Sources/SelectionOverlayView.swift @@ -0,0 +1,306 @@ +import QuartzCore +import UIKit + +/// Pure UIKit/CALayer selection overlay rendering native teardrop handles and a circular +/// magnifier loupe driven deterministically by Rust `AffineSelectionOverlayState`. +final class SelectionOverlayView: UIView { + var hostHandle: OpaquePointer? + var onSelectionDragResolved: ((CGPoint) -> (targetOffset: UInt32, startCaret: CGRect, endCaret: CGRect))? + var onMenuAnchorChanged: ((CGRect?) -> Void)? + + private let accentColor = UIColor(red: 0.118, green: 0.588, blue: 0.922, alpha: 1.0) + private let startHandleLayer = CAShapeLayer() + private let endHandleLayer = CAShapeLayer() + private let loupeContainer = UIView() + private let loupeImageView = UIImageView() + private let loupeBorderLayer = CAShapeLayer() + private let panRecognizer = UIPanGestureRecognizer() + + private(set) var currentState = AffineSelectionOverlayState() + private(set) var lastMenuAnchorRect: CGRect? + private(set) var lastResolvedProbePoint: CGPoint? + + var loupeSnapshotImage: UIImage? { + loupeImageView.image + } + + override init(frame: CGRect) { + super.init(frame: frame) + configureLayers() + } + + required init?(coder: NSCoder) { + super.init(coder: coder) + configureLayers() + } + + private func configureLayers() { + backgroundColor = .clear + isOpaque = false + + for shape in [startHandleLayer, endHandleLayer] { + shape.fillColor = accentColor.cgColor + shape.strokeColor = accentColor.cgColor + shape.lineWidth = 0 + shape.shadowColor = UIColor.black.cgColor + shape.shadowOpacity = 0.18 + shape.shadowRadius = 2.0 + shape.shadowOffset = CGSize(width: 0, height: 1) + shape.isHidden = true + layer.addSublayer(shape) + } + + loupeContainer.backgroundColor = UIColor(white: 1.0, alpha: 0.96) + loupeContainer.layer.shadowColor = UIColor.black.cgColor + loupeContainer.layer.shadowOpacity = 0.22 + loupeContainer.layer.shadowRadius = 8.0 + loupeContainer.layer.shadowOffset = CGSize(width: 0, height: 4) + loupeContainer.isUserInteractionEnabled = false + loupeContainer.isHidden = true + + loupeImageView.contentMode = .scaleToFill + loupeImageView.clipsToBounds = true + loupeImageView.isUserInteractionEnabled = false + loupeContainer.addSubview(loupeImageView) + + loupeBorderLayer.strokeColor = accentColor.withAlphaComponent(0.85).cgColor + loupeBorderLayer.fillColor = UIColor.clear.cgColor + loupeBorderLayer.lineWidth = 2.0 + loupeContainer.layer.addSublayer(loupeBorderLayer) + addSubview(loupeContainer) + + panRecognizer.addTarget(self, action: #selector(handlePanGesture(_:))) + panRecognizer.maximumNumberOfTouches = 1 + addGestureRecognizer(panRecognizer) + } + + override func point(inside point: CGPoint, with event: UIEvent?) -> Bool { + guard let handle = hostHandle else { + return false + } + let hit = affine_ios_host_selection_hit_test( + handle, + AffinePoint(x: Float(point.x), y: Float(point.y)), + 22.0 + ) + return hit != 0 || currentState.active_drag_handle != 0 + } + + /// Sync UIKit layers from the latest Rust `AffineSelectionOverlayState`. + func refreshFromHost() { + guard let handle = hostHandle else { + return + } + applyOverlayState(affine_ios_host_selection_state(handle)) + } + + /// Apply a computed Rust overlay state snapshot to the teardrop and loupe layers. + func applyOverlayState(_ state: AffineSelectionOverlayState) { + currentState = state + updateHandleLayer(startHandleLayer, layout: state.start_handle) + updateHandleLayer(endHandleLayer, layout: state.end_handle) + updateLoupe(layout: state.loupe) + + let nextAnchor: CGRect? = state.show_floating_menu + ? CGRect( + x: CGFloat(state.menu_anchor_rect.x), + y: CGFloat(state.menu_anchor_rect.y), + width: CGFloat(state.menu_anchor_rect.width), + height: CGFloat(state.menu_anchor_rect.height) + ) + : nil + if nextAnchor != lastMenuAnchorRect { + lastMenuAnchorRect = nextAnchor + onMenuAnchorChanged?(nextAnchor) + } + } + + /// Deterministic drag step entry point used by both `UIPanGestureRecognizer` and smoke tests. + @discardableResult + func processDragStep( + phase: UIGestureRecognizer.State, + point: CGPoint + ) -> AffineSelectionOverlayState? { + guard let handle = hostHandle else { + return nil + } + let cPoint = AffinePoint(x: Float(point.x), y: Float(point.y)) + switch phase { + case .began: + let hit = affine_ios_host_selection_hit_test(handle, cPoint, 22.0) + guard hit != 0 else { + return nil + } + _ = affine_ios_host_selection_begin_drag(handle, hit, cPoint) + let state = affine_ios_host_selection_state(handle) + lastResolvedProbePoint = CGPoint( + x: CGFloat(state.drag_probe_point.x), + y: CGFloat(state.drag_probe_point.y) + ) + applyOverlayState(state) + return state + + case .changed: + // Apply Rust's recorded `grab_offset` so holding the teardrop center with 0pt + // movement probes the exact caret midpoint without jumping to the adjacent line. + let cProbe = affine_ios_host_selection_drag_probe(handle, cPoint) + let probePoint = CGPoint(x: CGFloat(cProbe.x), y: CGFloat(cProbe.y)) + lastResolvedProbePoint = probePoint + let state: AffineSelectionOverlayState + if let resolver = onSelectionDragResolved { + let resolved = resolver(probePoint) + let cStart = AffineRect( + x: Float(resolved.startCaret.origin.x), + y: Float(resolved.startCaret.origin.y), + width: Float(resolved.startCaret.size.width), + height: Float(resolved.startCaret.size.height) + ) + let cEnd = AffineRect( + x: Float(resolved.endCaret.origin.x), + y: Float(resolved.endCaret.origin.y), + width: Float(resolved.endCaret.size.width), + height: Float(resolved.endCaret.size.height) + ) + state = affine_ios_host_selection_apply_drag_endpoints( + handle, + cPoint, + resolved.targetOffset, + cStart, + cEnd + ) + } else { + let activeHeight = max( + 1.0, + CGFloat( + currentState.active_drag_handle == 1 + ? (currentState.start_handle.stem_bottom_y - currentState.start_handle.stem_top_y) + : (currentState.end_handle.stem_bottom_y - currentState.end_handle.stem_top_y) + ) + ) + let cCaret = AffineRect( + x: Float(probePoint.x - 1.0), + y: Float(probePoint.y - activeHeight * 0.5), + width: 2.0, + height: Float(activeHeight) + ) + state = affine_ios_host_selection_update_drag(handle, cPoint, cCaret, currentState.range) + } + applyOverlayState(state) + return state + + case .ended, .cancelled, .failed: + let state = affine_ios_host_selection_end_drag(handle) + lastResolvedProbePoint = nil + applyOverlayState(state) + return state + + default: + return nil + } + } + + @objc private func handlePanGesture(_ recognizer: UIPanGestureRecognizer) { + let location = recognizer.location(in: self) + _ = processDragStep(phase: recognizer.state, point: location) + } + + private func updateHandleLayer(_ shape: CAShapeLayer, layout: AffineTeardropHandleLayout) { + guard layout.visible else { + shape.isHidden = true + shape.path = nil + return + } + shape.isHidden = false + let path = CGMutablePath() + let stemW = CGFloat(max(layout.stem_width, 1.0)) + let stemX = CGFloat(layout.stem_x) + let stemTopY = CGFloat(layout.stem_top_y) + let stemBottomY = CGFloat(layout.stem_bottom_y) + let stemRect = CGRect( + x: stemX - stemW * 0.5, + y: stemTopY, + width: stemW, + height: max(1.0, stemBottomY - stemTopY) + ) + path.addRoundedRect(in: stemRect, cornerWidth: stemW * 0.5, cornerHeight: stemW * 0.5) + + // Native iOS handle bulb aligned cleanly on `stem_x` and fused to the stem tip. + let r = CGFloat(max(layout.drop_radius, 1.0)) + let dropCenterY = layout.drop_above ? (stemTopY - r + 1.0) : (stemBottomY + r - 1.0) + let dropRect = CGRect( + x: stemX - r, + y: dropCenterY - r, + width: r * 2.0, + height: r * 2.0 + ) + path.addEllipse(in: dropRect) + shape.path = path + } + + private func updateLoupe(layout: AffineLoupeLayout) { + guard layout.visible else { + loupeContainer.isHidden = true + loupeImageView.image = nil + return + } + let diameter = CGFloat(max(layout.diameter, 1.0)) + let radius = diameter * 0.5 + let zoom = max(layout.zoom_scale, 1.0) + loupeContainer.isHidden = false + loupeContainer.frame = CGRect( + x: CGFloat(layout.center_x) - radius, + y: CGFloat(layout.center_y) - radius, + width: diameter, + height: diameter + ) + loupeContainer.layer.cornerRadius = radius + let inset: CGFloat = 2.0 + loupeImageView.frame = CGRect( + x: inset, + y: inset, + width: max(1.0, diameter - inset * 2.0), + height: max(1.0, diameter - inset * 2.0) + ) + loupeImageView.layer.cornerRadius = max(0.0, radius - inset) + loupeBorderLayer.path = UIBezierPath( + ovalIn: CGRect(x: 1.0, y: 1.0, width: max(1.0, diameter - 2.0), height: max(1.0, diameter - 2.0)) + ).cgPath + + // Render Retina-resolution anti-aliased loupe via Rust C-ABI + native CoreText provider. + if let handle = hostHandle { + let scale = max(window?.screen.scale ?? UIScreen.main.scale, 2.0) + let dimPx = max(32, min(512, UInt32((diameter * scale).rounded()))) + let effectiveZoom = zoom * Float(scale) + let buf = affine_ios_host_render_loupe_rgba8( + handle, + layout.focus_x, + layout.focus_y, + dimPx, + effectiveZoom + ) + defer { affine_ios_bytes_free(buf) } + if let ptr = buf.ptr, buf.len == Int(dimPx * dimPx * 4) { + let data = Data(bytes: ptr, count: buf.len) + if let provider = CGDataProvider(data: data as CFData), + let cgImage = CGImage( + width: Int(dimPx), + height: Int(dimPx), + bitsPerComponent: 8, + bitsPerPixel: 32, + bytesPerRow: Int(dimPx) * 4, + space: CGColorSpaceCreateDeviceRGB(), + bitmapInfo: CGBitmapInfo( + rawValue: CGImageAlphaInfo.premultipliedLast.rawValue | CGBitmapInfo.byteOrder32Big.rawValue + ), + provider: provider, + decode: nil, + shouldInterpolate: true, + intent: .defaultIntent + ) + { + loupeImageView.image = UIImage(cgImage: cgImage, scale: scale, orientation: .up) + } + } + } + } +} diff --git a/packages/frontend/hosts/ios/Sources/TextRenderingBridge.swift b/packages/frontend/hosts/ios/Sources/TextRenderingBridge.swift new file mode 100644 index 0000000000..48d83801ed --- /dev/null +++ b/packages/frontend/hosts/ios/Sources/TextRenderingBridge.swift @@ -0,0 +1,995 @@ +import CoreGraphics +import CoreText +import UIKit + +/// Native CoreText `CTTypesetter`/`CTLine`/`CTRun` text geometry, BiDi glyph-slot +/// selection rects, affinity-aware endpoint carets, whole-line `CTLineDraw` preview, +/// and Retina anti-aliased loupe rasterizer. +final class TextRenderingBridge { + static let contentInsetPt: CGFloat = 16.0 + static let lineHeightPt: CGFloat = 22.0 + static let defaultClearColorRgba: UInt32 = 0xFAFA_FCFF + + let font = UIFont.systemFont(ofSize: 17, weight: .regular) + private var isDarkCanvas = false + private var canvasBackgroundColor = UIColor( + red: 250.0 / 255.0, + green: 250.0 / 255.0, + blue: 252.0 / 255.0, + alpha: 1.0 + ) + private var textColor = UIColor(white: 0.1, alpha: 1.0) + private var selectionColor = UIColor(red: 0.808, green: 0.910, blue: 1.0, alpha: 1.0) + private let caretColor = UIColor(red: 0.118, green: 0.588, blue: 0.922, alpha: 1.0) + + private struct LayoutKey: Equatable { + let utf16Units: [UInt16] + let viewportWidthBits: UInt32 + let safeLeftBits: UInt32 + let safeTopBits: UInt32 + let safeRightBits: UInt32 + let isDarkCanvas: Bool + } + + struct ShapedVisualLine { + let ctLine: CTLine + let paragraphStart: Int + let start: Int + let end: Int + let isSoftWrapped: Bool + let writingDirection: NSWritingDirection + let originX: CGFloat + let topY: CGFloat + let width: CGFloat + let height: CGFloat + let ascent: CGFloat + let descent: CGFloat + } + + private struct GlyphSlot { + let docStart: Int + let docEnd: Int + let xLeft: CGFloat + let xRight: CGFloat + let isRtl: Bool + let topY: CGFloat + let height: CGFloat + } + + private struct CachedLayout { + let key: LayoutKey + let nsText: NSString + let originX: CGFloat + let originY: CGFloat + let maxWidth: CGFloat + let lines: [ShapedVisualLine] + } + + private var cachedLayout: CachedLayout? + private var attachedHost: OpaquePointer? + + /// Adapt text & selection colors to the host's current clear color and return its `UIColor`. + @discardableResult + func applyClearColorRgba(_ rgba: UInt32) -> UIColor { + let r = CGFloat((rgba >> 24) & 0xFF) / 255.0 + let g = CGFloat((rgba >> 16) & 0xFF) / 255.0 + let b = CGFloat((rgba >> 8) & 0xFF) / 255.0 + let a = CGFloat(rgba & 0xFF) / 255.0 + let bg = UIColor(red: r, green: g, blue: b, alpha: a) + canvasBackgroundColor = bg + let luma = 0.2126 * r + 0.7152 * g + 0.0722 * b + let dark = luma < 0.35 + if dark != isDarkCanvas { + isDarkCanvas = dark + if dark { + textColor = UIColor(red: 242.0 / 255.0, green: 242.0 / 255.0, blue: 245.0 / 255.0, alpha: 1.0) + selectionColor = UIColor(red: 0.118, green: 0.588, blue: 0.922, alpha: 0.35) + } else { + textColor = UIColor(white: 0.1, alpha: 1.0) + selectionColor = UIColor(red: 0.808, green: 0.910, blue: 1.0, alpha: 1.0) + } + cachedLayout = nil + } + return bg + } + + func attach(to host: OpaquePointer) { + detach() + attachedHost = host + let provider = AffineTextProvider( + caret_rect: affineTextCaretRectTrampoline, + closest_offset: affineTextClosestOffsetTrampoline, + selection_rects: affineTextSelectionRectsTrampoline, + selection_endpoint_carets: affineTextSelectionEndpointCaretsTrampoline, + render_loupe_rgba8: affineTextRenderLoupeRgba8Trampoline, + user_data: Unmanaged.passUnretained(self).toOpaque() + ) + affine_ios_host_set_text_provider(host, provider) + } + + func detach() { + guard let host = attachedHost else { + return + } + let empty = AffineTextProvider( + caret_rect: nil, + closest_offset: nil, + selection_rects: nil, + selection_endpoint_carets: nil, + render_loupe_rgba8: nil, + user_data: nil + ) + affine_ios_host_set_text_provider(host, empty) + attachedHost = nil + cachedLayout = nil + } + + deinit { + detach() + } + + private func utf16ArrayFrom(_ ptr: UnsafePointer?, _ len: Int) -> [UInt16] { + guard let ptr, len > 0 else { return [] } + return Array(UnsafeBufferPointer(start: ptr, count: len)) + } + + private func layoutFor( + utf16Units: [UInt16], + viewportWidth: Float, + insets: AffineWindowInsets + ) -> CachedLayout { + let key = LayoutKey( + utf16Units: utf16Units, + viewportWidthBits: viewportWidth.bitPattern, + safeLeftBits: insets.safe_left.bitPattern, + safeTopBits: insets.safe_top.bitPattern, + safeRightBits: insets.safe_right.bitPattern, + isDarkCanvas: isDarkCanvas + ) + if let existing = cachedLayout, existing.key == key { + return existing + } + + let safeLeft = CGFloat(max(0.0, insets.safe_left.isFinite ? insets.safe_left : 0.0)) + let safeTop = CGFloat(max(0.0, insets.safe_top.isFinite ? insets.safe_top : 0.0)) + let safeRight = CGFloat(max(0.0, insets.safe_right.isFinite ? insets.safe_right : 0.0)) + let vw = CGFloat(max(0.0, viewportWidth.isFinite ? viewportWidth : 0.0)) + let originX = safeLeft + Self.contentInsetPt + let originY = safeTop + Self.contentInsetPt + let maxWidth = max(40.0, vw - originX - (safeRight + Self.contentInsetPt)) + + let nsText: NSString = utf16Units.isEmpty + ? "" + : NSString(characters: utf16Units, length: utf16Units.count) + let totalLen = nsText.length + var lines: [ShapedVisualLine] = [] + var lineIndex = 0 + + func emitEmptyLine(at docOffset: Int, dir: NSWritingDirection) { + let emptyAttr = NSAttributedString(string: "", attributes: [.font: font]) + let ctLine = CTLineCreateWithAttributedString(emptyAttr) + let x = dir == .rightToLeft ? (originX + maxWidth) : originX + lines.append( + ShapedVisualLine( + ctLine: ctLine, + paragraphStart: docOffset, + start: docOffset, + end: docOffset, + isSoftWrapped: false, + writingDirection: dir, + originX: x, + topY: originY + CGFloat(lineIndex) * Self.lineHeightPt, + width: 0.0, + height: Self.lineHeightPt, + ascent: font.ascender, + descent: abs(font.descender) + ) + ) + lineIndex += 1 + } + + var paraStart = 0 + while paraStart <= totalLen { + var paraEnd = paraStart + while paraEnd < totalLen && nsText.character(at: paraEnd) != 0x000A { + paraEnd += 1 + } + let paraLen = paraEnd - paraStart + let paraRange = NSRange(location: paraStart, length: paraLen) + let paraStr = paraLen > 0 ? nsText.substring(with: paraRange) : "" + let dir = detectBaseWritingDirection(paraStr) + + if paraLen == 0 { + emitEmptyLine(at: paraStart, dir: dir) + } else { + let paraStyle = NSMutableParagraphStyle() + paraStyle.baseWritingDirection = dir + paraStyle.alignment = (dir == .rightToLeft) ? .right : .left + let attrStr = NSAttributedString( + string: paraStr, + attributes: [ + .font: font, + .foregroundColor: textColor, + .paragraphStyle: paraStyle, + ] + ) + let typesetter = CTTypesetterCreateWithAttributedString(attrStr) + var localStart = 0 + while localStart < paraLen { + var count = CTTypesetterSuggestLineBreak(typesetter, localStart, Double(maxWidth)) + if count <= 0 { + let seq = (paraStr as NSString).rangeOfComposedCharacterSequence(at: localStart) + count = max(1, seq.length) + } + let localEnd = min(paraLen, localStart + count) + let ctLine = CTTypesetterCreateLine( + typesetter, + CFRange(location: localStart, length: localEnd - localStart) + ) + var ascent: CGFloat = 0 + var descent: CGFloat = 0 + var leading: CGFloat = 0 + let lineW = CGFloat(CTLineGetTypographicBounds(ctLine, &ascent, &descent, &leading)) + let flush: CGFloat = (dir == .rightToLeft) ? 1.0 : 0.0 + let penOffset = CGFloat(CTLineGetPenOffsetForFlush(ctLine, flush, Double(maxWidth))) + let lineOriginX = originX + max(0.0, penOffset) + lines.append( + ShapedVisualLine( + ctLine: ctLine, + paragraphStart: paraStart, + start: paraStart + localStart, + end: paraStart + localEnd, + isSoftWrapped: localEnd < paraLen, + writingDirection: dir, + originX: lineOriginX, + topY: originY + CGFloat(lineIndex) * Self.lineHeightPt, + width: lineW, + height: Self.lineHeightPt, + ascent: ascent > 0 ? ascent : font.ascender, + descent: descent > 0 ? descent : abs(font.descender) + ) + ) + lineIndex += 1 + localStart = localEnd + } + } + + if paraEnd < totalLen && nsText.character(at: paraEnd) == 0x000A { + paraStart = paraEnd + 1 + } else { + break + } + } + + if lines.isEmpty { + emitEmptyLine(at: 0, dir: .leftToRight) + } + + let built = CachedLayout( + key: key, + nsText: nsText, + originX: originX, + originY: originY, + maxWidth: maxWidth, + lines: lines + ) + cachedLayout = built + return built + } + + private func snapToGraphemeBoundary(_ nsText: NSString, offset: Int) -> Int { + let clamped = max(0, min(offset, nsText.length)) + guard clamped > 0 && clamped < nsText.length else { + return clamped + } + let seq = nsText.rangeOfComposedCharacterSequence(at: clamped) + if clamped > seq.location && clamped < seq.location + seq.length { + let distStart = clamped - seq.location + let distEnd = (seq.location + seq.length) - clamped + return distStart <= distEnd ? seq.location : (seq.location + seq.length) + } + return clamped + } + + /// Extract exact visual glyph slots (`[docStart, docEnd)` -> `[xLeft, xRight]`) from `CTRun`s + /// so BiDi direction boundaries never collapse or jump to the outer run's primary caret edge. + private func glyphSlots(in line: ShapedVisualLine) -> [GlyphSlot] { + let runs = CTLineGetGlyphRuns(line.ctLine) as? [CTRun] ?? [] + var slots: [GlyphSlot] = [] + for run in runs { + let count = CTRunGetGlyphCount(run) + guard count > 0 else { continue } + let runRange = CTRunGetStringRange(run) + let runEnd = runRange.location + runRange.length + let isRtl = CTRunGetStatus(run).contains(.rightToLeft) + + var indices = Array(repeating: CFIndex(0), count: count) + var positions = Array(repeating: CGPoint.zero, count: count) + var advances = Array(repeating: CGSize.zero, count: count) + CTRunGetStringIndices(run, CFRange(location: 0, length: count), &indices) + CTRunGetPositions(run, CFRange(location: 0, length: count), &positions) + CTRunGetAdvances(run, CFRange(location: 0, length: count), &advances) + + var uniqueSorted = Array(Set(indices)).sorted() + if uniqueSorted.last != runEnd { + uniqueSorted.append(runEnd) + } + var nextBoundaryByIndex: [CFIndex: CFIndex] = [:] + for i in 0..<(uniqueSorted.count - 1) { + nextBoundaryByIndex[uniqueSorted[i]] = uniqueSorted[i + 1] + } + + for g in 0.. (minX: CGFloat, maxX: CGFloat) { + let totalUnits = max(1, slot.docEnd - slot.docStart) + if ovStart <= slot.docStart && ovEnd >= slot.docEnd { + return (slot.xLeft, slot.xRight) + } + let fracStart = CGFloat(max(0, ovStart - slot.docStart)) / CGFloat(totalUnits) + let fracEnd = CGFloat(min(totalUnits, ovEnd - slot.docStart)) / CGFloat(totalUnits) + let span = slot.xRight - slot.xLeft + if slot.isRtl { + return (slot.xRight - fracEnd * span, slot.xRight - fracStart * span) + } + return (slot.xLeft + fracStart * span, slot.xLeft + fracEnd * span) + } + + private func caretRectInLayout(_ layout: CachedLayout, utf16Offset: UInt32) -> AffineRect { + let offset = snapToGraphemeBoundary(layout.nsText, offset: Int(utf16Offset)) + let targetLine = layout.lines.first { line in + if line.isSoftWrapped { + return offset >= line.start && offset < line.end + } + return offset >= line.start && offset <= line.end + } ?? layout.lines.last! + let localIdx = max(0, offset - targetLine.paragraphStart) + let xOff = CTLineGetOffsetForStringIndex(targetLine.ctLine, localIdx, nil) + return AffineRect( + x: Float(targetLine.originX + xOff), + y: Float(targetLine.topY), + width: 2.0, + height: Float(targetLine.height) + ) + } + + private func selectionEndpointCaretsInLayout( + _ layout: CachedLayout, + range: AffineUtf16Range + ) -> (start: AffineRect, end: AffineRect) { + let selStart = snapToGraphemeBoundary(layout.nsText, offset: Int(range.location)) + let selEnd = snapToGraphemeBoundary( + layout.nsText, + offset: Int(range.location) + Int(range.length) + ) + if selEnd <= selStart || layout.nsText.length == 0 { + let c = caretRectInLayout(layout, utf16Offset: UInt32(max(0, selStart))) + return (c, c) + } + + var startRect: AffineRect? + var endRect: AffineRect? + let lastUnit = selEnd - 1 + + for line in layout.lines { + if selEnd < line.start || selStart > line.end { + continue + } + let slots = glyphSlots(in: line) + if startRect == nil && selStart >= line.start && selStart < line.end { + if let slot = slots.first(where: { selStart >= $0.docStart && selStart < $0.docEnd }) { + let bounds = slicedBounds( + for: slot, + ovStart: selStart, + ovEnd: min(slot.docEnd, selEnd) + ) + let edgeX = slot.isRtl ? bounds.maxX : bounds.minX + startRect = AffineRect( + x: Float(edgeX), + y: Float(slot.topY), + width: 2.0, + height: Float(slot.height) + ) + } + } + if endRect == nil && lastUnit >= line.start && lastUnit < line.end { + if let slot = slots.last(where: { lastUnit >= $0.docStart && lastUnit < $0.docEnd }) { + let bounds = slicedBounds( + for: slot, + ovStart: max(slot.docStart, selStart), + ovEnd: selEnd + ) + let edgeX = slot.isRtl ? bounds.minX : bounds.maxX + endRect = AffineRect( + x: Float(edgeX), + y: Float(slot.topY), + width: 2.0, + height: Float(slot.height) + ) + } + } + if startRect != nil && endRect != nil { + break + } + } + + let resolvedStart = startRect ?? caretRectInLayout(layout, utf16Offset: UInt32(selStart)) + let resolvedEnd = endRect ?? caretRectInLayout(layout, utf16Offset: UInt32(selEnd)) + return (resolvedStart, resolvedEnd) + } + + func caretRect( + utf16Ptr: UnsafePointer?, + utf16Len: Int, + utf16Offset: UInt32, + viewportWidth: Float, + insets: AffineWindowInsets + ) -> AffineRect { + let units = utf16ArrayFrom(utf16Ptr, utf16Len) + let layout = layoutFor(utf16Units: units, viewportWidth: viewportWidth, insets: insets) + return caretRectInLayout(layout, utf16Offset: utf16Offset) + } + + func selectionEndpointCarets( + utf16Ptr: UnsafePointer?, + utf16Len: Int, + range: AffineUtf16Range, + viewportWidth: Float, + insets: AffineWindowInsets, + outStart: UnsafeMutablePointer?, + outEnd: UnsafeMutablePointer? + ) -> Bool { + guard let outStart, let outEnd else { return false } + let units = utf16ArrayFrom(utf16Ptr, utf16Len) + let layout = layoutFor(utf16Units: units, viewportWidth: viewportWidth, insets: insets) + let pair = selectionEndpointCaretsInLayout(layout, range: range) + outStart.pointee = pair.start + outEnd.pointee = pair.end + return true + } + + func closestOffset( + utf16Ptr: UnsafePointer?, + utf16Len: Int, + point: AffinePoint, + preferredOffset: UInt32, + viewportWidth: Float, + insets: AffineWindowInsets + ) -> UInt32 { + let units = utf16ArrayFrom(utf16Ptr, utf16Len) + guard !units.isEmpty else { return 0 } + let layout = layoutFor(utf16Units: units, viewportWidth: viewportWidth, insets: insets) + let px = CGFloat(point.x.isFinite ? point.x : 0.0) + let py = CGFloat(point.y.isFinite ? point.y : 0.0) + + var targetLine = layout.lines[0] + var bestDy = CGFloat.greatestFiniteMagnitude + for line in layout.lines { + let dy = abs(py - (line.topY + line.height * 0.5)) + if dy < bestDy { + bestDy = dy + targetLine = line + } + } + + // At BiDi direction-change boundaries, one visual x maps to two logical UTF-16 offsets. + // When the drag probe sits within 2.0pt of a glyph boundary matching `preferredOffset`, + // keep `preferredOffset` so in-place or micro-jitter drags never collapse the selection. + if preferredOffset != UInt32.max { + let pref = snapToGraphemeBoundary(layout.nsText, offset: Int(preferredOffset)) + let slots = glyphSlots(in: targetLine) + let boundaryTolerance: CGFloat = 2.0 + for slot in slots { + let leadX = slot.isRtl ? slot.xRight : slot.xLeft + let trailX = slot.isRtl ? slot.xLeft : slot.xRight + if slot.docStart == pref && abs(px - leadX) <= boundaryTolerance { + return UInt32(max(0, pref)) + } + if slot.docEnd == pref && abs(px - trailX) <= boundaryTolerance { + return UInt32(max(0, pref)) + } + } + } + + let localPos = CGPoint(x: px - targetLine.originX, y: targetLine.height * 0.5) + let rawLocalIdx = CTLineGetStringIndexForPosition(targetLine.ctLine, localPos) + if rawLocalIdx == kCFNotFound { + return UInt32(max(0, targetLine.start)) + } + let docOffset = max(targetLine.start, min(targetLine.paragraphStart + rawLocalIdx, targetLine.end)) + let snapped = snapToGraphemeBoundary(layout.nsText, offset: docOffset) + return UInt32(max(0, snapped)) + } + + private func computeSelectionRects( + layout: CachedLayout, + range: AffineUtf16Range + ) -> [AffineSelectionRect] { + guard range.length > 0 && layout.nsText.length > 0 else { + return [] + } + let selStart = snapToGraphemeBoundary(layout.nsText, offset: Int(range.location)) + let selEnd = snapToGraphemeBoundary( + layout.nsText, + offset: Int(range.location) + Int(range.length) + ) + guard selEnd > selStart else { + return [] + } + + var result: [AffineSelectionRect] = [] + for line in layout.lines { + if selEnd < line.start || selStart > line.end { + continue + } + let segStart = max(line.start, selStart) + let segEnd = min(line.end, selEnd) + let emptyHardInside = + line.start == line.end && !line.isSoftWrapped && selStart < line.start && selEnd > line.end + if segEnd <= segStart && !emptyHardInside { + continue + } + + if emptyHardInside { + result.append( + AffineSelectionRect( + rect: AffineRect( + x: Float(line.originX), + y: Float(line.topY), + width: 2.0, + height: Float(line.height) + ), + contains_start: false, + contains_end: false + ) + ) + continue + } + + let slots = glyphSlots(in: line) + var intervals: [(minX: CGFloat, maxX: CGFloat, hasStart: Bool, hasEnd: Bool)] = [] + let lastUnit = selEnd - 1 + + for slot in slots { + let ovStart = max(slot.docStart, segStart) + let ovEnd = min(slot.docEnd, segEnd) + guard ovEnd > ovStart else { continue } + let bounds = slicedBounds(for: slot, ovStart: ovStart, ovEnd: ovEnd) + let hasStart = selStart >= ovStart && selStart < ovEnd + let hasEnd = lastUnit >= ovStart && lastUnit < ovEnd + intervals.append((bounds.minX, bounds.maxX, hasStart, hasEnd)) + } + + if intervals.isEmpty { + let localStart = segStart - line.paragraphStart + let localEnd = segEnd - line.paragraphStart + let x0 = line.originX + CTLineGetOffsetForStringIndex(line.ctLine, localStart, nil) + let x1 = line.originX + CTLineGetOffsetForStringIndex(line.ctLine, localEnd, nil) + intervals.append((min(x0, x1), max(x0, x1), selStart == segStart, selEnd == segEnd)) + } + + intervals.sort { $0.minX < $1.minX } + var merged: [(minX: CGFloat, maxX: CGFloat, hasStart: Bool, hasEnd: Bool)] = [] + for item in intervals { + if let last = merged.last, item.minX <= last.maxX + 0.75 { + merged[merged.count - 1] = ( + min(last.minX, item.minX), + max(last.maxX, item.maxX), + last.hasStart || item.hasStart, + last.hasEnd || item.hasEnd + ) + } else { + merged.append(item) + } + } + + for seg in merged { + result.append( + AffineSelectionRect( + rect: AffineRect( + x: Float(seg.minX), + y: Float(line.topY), + width: Float(max(2.0, seg.maxX - seg.minX)), + height: Float(line.height) + ), + contains_start: seg.hasStart, + contains_end: seg.hasEnd + ) + ) + } + } + return result + } + + func selectionRects( + utf16Ptr: UnsafePointer?, + utf16Len: Int, + range: AffineUtf16Range, + viewportWidth: Float, + insets: AffineWindowInsets, + outRects: UnsafeMutablePointer?, + capacity: Int + ) -> Int { + let units = utf16ArrayFrom(utf16Ptr, utf16Len) + let layout = layoutFor(utf16Units: units, viewportWidth: viewportWidth, insets: insets) + let rects = computeSelectionRects(layout: layout, range: range) + if let outRects, capacity > 0 { + let count = min(rects.count, capacity) + for i in 0.. 0 { + let rects = computeSelectionRects(layout: layout, range: selectedRange) + ctx.setFillColor(selectionColor.cgColor) + for item in rects { + ctx.fill( + CGRect( + x: CGFloat(item.rect.x), + y: CGFloat(item.rect.y), + width: CGFloat(item.rect.width), + height: CGFloat(item.rect.height) + ) + ) + } + } + + for line in layout.lines { + let contentH = line.ascent + line.descent + let baselineY = line.topY + max(0.0, (line.height - contentH) * 0.5) + line.ascent + ctx.saveGState() + ctx.translateBy(x: line.originX, y: baselineY) + ctx.scaleBy(x: 1.0, y: -1.0) + ctx.textMatrix = .identity + ctx.textPosition = .zero + CTLineDraw(line.ctLine, ctx) + ctx.restoreGState() + } + } + + func renderLoupeRgba8( + utf16Ptr: UnsafePointer?, + utf16Len: Int, + selectedRange: AffineUtf16Range, + viewportWidth: Float, + insets: AffineWindowInsets, + focusX: Float, + focusY: Float, + diameterPx: UInt32, + zoomScale: Float, + outPtr: UnsafeMutablePointer?, + outLen: Int + ) -> Bool { + let dim = Int(diameterPx) + guard dim >= 16, let outPtr, outLen >= dim * dim * 4 else { + return false + } + let colorSpace = CGColorSpaceCreateDeviceRGB() + let bitmapInfo = + CGImageAlphaInfo.premultipliedLast.rawValue | CGBitmapInfo.byteOrder32Big.rawValue + guard + let ctx = CGContext( + data: outPtr, + width: dim, + height: dim, + bitsPerComponent: 8, + bytesPerRow: dim * 4, + space: colorSpace, + bitmapInfo: bitmapInfo + ) + else { + return false + } + + ctx.setAllowsAntialiasing(true) + ctx.setShouldAntialias(true) + ctx.setAllowsFontSmoothing(true) + ctx.setShouldSmoothFonts(true) + ctx.interpolationQuality = .high + + ctx.setFillColor(canvasBackgroundColor.cgColor) + ctx.fill(CGRect(x: 0, y: 0, width: dim, height: dim)) + + ctx.saveGState() + ctx.translateBy(x: 0, y: CGFloat(dim)) + ctx.scaleBy(x: 1.0, y: -1.0) + let half = CGFloat(dim) * 0.5 + let zoom = CGFloat(zoomScale) + ctx.translateBy(x: half, y: half) + ctx.scaleBy(x: zoom, y: zoom) + ctx.translateBy(x: -CGFloat(focusX), y: -CGFloat(focusY)) + + let units = utf16ArrayFrom(utf16Ptr, utf16Len) + let layout = layoutFor(utf16Units: units, viewportWidth: viewportWidth, insets: insets) + drawShapedLayout(in: ctx, layout: layout, selectedRange: selectedRange) + + // Snap the loupe caret bar to the nearest affinity-aware selection endpoint edge. + let endpoints = selectionEndpointCaretsInLayout(layout, range: selectedRange) + let startDist = hypot( + CGFloat(endpoints.start.x) - CGFloat(focusX), + CGFloat(endpoints.start.y + endpoints.start.height * 0.5) - CGFloat(focusY) + ) + let endDist = hypot( + CGFloat(endpoints.end.x) - CGFloat(focusX), + CGFloat(endpoints.end.y + endpoints.end.height * 0.5) - CGFloat(focusY) + ) + let snappedCaret = startDist <= endDist ? endpoints.start : endpoints.end + ctx.setFillColor(caretColor.cgColor) + ctx.fill( + CGRect( + x: CGFloat(snappedCaret.x) - 0.85, + y: CGFloat(snappedCaret.y), + width: 1.7, + height: CGFloat(snappedCaret.height) + ) + ) + ctx.restoreGState() + return true + } + + private func detectBaseWritingDirection(_ text: String) -> NSWritingDirection { + for scalar in text.unicodeScalars { + let v = scalar.value + if (0x0590...0x08FF).contains(v) + || (0xFB1D...0xFDFF).contains(v) + || (0xFE70...0xFEFC).contains(v) + { + return .rightToLeft + } + if (0x0041...0x005A).contains(v) + || (0x0061...0x007A).contains(v) + || (0x00C0...0x024F).contains(v) + || (0x0370...0x052F).contains(v) + || (0x4E00...0x9FFF).contains(v) + { + return .leftToRight + } + } + return .leftToRight + } +} + +/// Lightweight transparent S3 transition preview view mounted above `MetalHostView` +/// and below `SelectionOverlayView`. Removed in S4 when GPU `blocksuite-editor` attaches. +final class HostTextPreviewView: UIView { + weak var renderer: TextRenderingBridge? + var utf16Units: [UInt16] = [] { + didSet { + if oldValue != utf16Units { setNeedsDisplay() } + } + } + var selectedRange = NSRange(location: 0, length: 0) { + didSet { + if oldValue != selectedRange { setNeedsDisplay() } + } + } + var hostInsets = AffineWindowInsets( + safe_top: 0, + safe_right: 0, + safe_bottom: 0, + safe_left: 0, + ime_bottom: 0 + ) { + didSet { setNeedsDisplay() } + } + + override init(frame: CGRect) { + super.init(frame: frame) + backgroundColor = .clear + isOpaque = false + isUserInteractionEnabled = false + } + + required init?(coder: NSCoder) { + super.init(coder: coder) + backgroundColor = .clear + isOpaque = false + isUserInteractionEnabled = false + } + + override func draw(_ rect: CGRect) { + guard + let renderer, + !utf16Units.isEmpty, + let ctx = UIGraphicsGetCurrentContext() + else { + return + } + renderer.drawShapedText( + in: ctx, + utf16Units: utf16Units, + selectedRange: selectedRange, + viewportWidth: Float(bounds.width), + insets: hostInsets + ) + } +} + +private func affineTextCaretRectTrampoline( + utf16Ptr: UnsafePointer?, + utf16Len: Int, + utf16Offset: UInt32, + viewportWidth: Float, + insets: AffineWindowInsets, + userData: UnsafeMutableRawPointer? +) -> AffineRect { + guard let userData else { return AffineRect() } + let bridge = Unmanaged.fromOpaque(userData).takeUnretainedValue() + return bridge.caretRect( + utf16Ptr: utf16Ptr, + utf16Len: utf16Len, + utf16Offset: utf16Offset, + viewportWidth: viewportWidth, + insets: insets + ) +} + +private func affineTextClosestOffsetTrampoline( + utf16Ptr: UnsafePointer?, + utf16Len: Int, + point: AffinePoint, + preferredOffset: UInt32, + viewportWidth: Float, + insets: AffineWindowInsets, + userData: UnsafeMutableRawPointer? +) -> UInt32 { + guard let userData else { return 0 } + let bridge = Unmanaged.fromOpaque(userData).takeUnretainedValue() + return bridge.closestOffset( + utf16Ptr: utf16Ptr, + utf16Len: utf16Len, + point: point, + preferredOffset: preferredOffset, + viewportWidth: viewportWidth, + insets: insets + ) +} + +private func affineTextSelectionRectsTrampoline( + utf16Ptr: UnsafePointer?, + utf16Len: Int, + range: AffineUtf16Range, + viewportWidth: Float, + insets: AffineWindowInsets, + outRects: UnsafeMutablePointer?, + capacity: Int, + userData: UnsafeMutableRawPointer? +) -> Int { + guard let userData else { return 0 } + let bridge = Unmanaged.fromOpaque(userData).takeUnretainedValue() + return bridge.selectionRects( + utf16Ptr: utf16Ptr, + utf16Len: utf16Len, + range: range, + viewportWidth: viewportWidth, + insets: insets, + outRects: outRects, + capacity: capacity + ) +} + +private func affineTextSelectionEndpointCaretsTrampoline( + utf16Ptr: UnsafePointer?, + utf16Len: Int, + range: AffineUtf16Range, + viewportWidth: Float, + insets: AffineWindowInsets, + outStart: UnsafeMutablePointer?, + outEnd: UnsafeMutablePointer?, + userData: UnsafeMutableRawPointer? +) -> Bool { + guard let userData else { return false } + let bridge = Unmanaged.fromOpaque(userData).takeUnretainedValue() + return bridge.selectionEndpointCarets( + utf16Ptr: utf16Ptr, + utf16Len: utf16Len, + range: range, + viewportWidth: viewportWidth, + insets: insets, + outStart: outStart, + outEnd: outEnd + ) +} + +private func affineTextRenderLoupeRgba8Trampoline( + utf16Ptr: UnsafePointer?, + utf16Len: Int, + selectedRange: AffineUtf16Range, + viewportWidth: Float, + insets: AffineWindowInsets, + focusX: Float, + focusY: Float, + diameterPx: UInt32, + zoomScale: Float, + outPtr: UnsafeMutablePointer?, + outLen: Int, + userData: UnsafeMutableRawPointer? +) -> Bool { + guard let userData else { return false } + let bridge = Unmanaged.fromOpaque(userData).takeUnretainedValue() + return bridge.renderLoupeRgba8( + utf16Ptr: utf16Ptr, + utf16Len: utf16Len, + selectedRange: selectedRange, + viewportWidth: viewportWidth, + insets: insets, + focusX: focusX, + focusY: focusY, + diameterPx: diameterPx, + zoomScale: zoomScale, + outPtr: outPtr, + outLen: outLen + ) +} diff --git a/packages/frontend/hosts/ios/include/affine_mobile_host.h b/packages/frontend/hosts/ios/include/affine_mobile_host.h index e9f053ff4f..7873372dbc 100644 --- a/packages/frontend/hosts/ios/include/affine_mobile_host.h +++ b/packages/frontend/hosts/ios/include/affine_mobile_host.h @@ -22,9 +22,9 @@ typedef struct AffineWindowInsets { float safe_right; float safe_bottom; float safe_left; - /* Absolute keyboard overlap height from the window bottom edge in logical points. - * Do not subtract safe_bottom; Rust ui::WindowInsets::effective() computes - * safe_area.bottom.max(ime.bottom). */ + /* Absolute docked keyboard overlap height from the window bottom edge in logical points + * (0 for floating, split, hardware, or hidden keyboards). Do not subtract safe_bottom; + * Rust ui::WindowInsets::effective() computes safe_area.bottom.max(ime.bottom). */ float ime_bottom; } AffineWindowInsets; @@ -33,6 +33,181 @@ typedef struct AffineUtf16Range { uint32_t length; } AffineUtf16Range; +typedef struct AffinePoint { + float x; + float y; +} AffinePoint; + +typedef struct AffineRect { + float x; + float y; + float width; + float height; +} AffineRect; + +typedef struct AffineTeardropHandleLayout { + bool visible; + bool drop_above; + float stem_x; + float stem_top_y; + float stem_bottom_y; + float stem_width; + float drop_center_x; + float drop_center_y; + float drop_radius; + float drop_offset_x; +} AffineTeardropHandleLayout; + +typedef struct AffineLoupeLayout { + bool visible; + float center_x; + float center_y; + float focus_x; + float focus_y; + float diameter; + float zoom_scale; +} AffineLoupeLayout; + +typedef struct AffineSelectionOverlayState { + bool has_selection; + bool is_collapsed; + bool is_rtl; + uint8_t active_drag_handle; + bool show_floating_menu; + AffineUtf16Range range; + AffinePoint drag_probe_point; + AffineTeardropHandleLayout start_handle; + AffineTeardropHandleLayout end_handle; + AffineLoupeLayout loupe; + AffineRect menu_anchor_rect; +} AffineSelectionOverlayState; + +typedef struct AffineKeyboardAvoidanceMetrics { + float raw_overlap_pt; + float ime_bottom_pt; + float ime_above_safe_bottom_pt; + float effective_bottom_pt; + bool is_floating_or_split; + bool is_hardware_or_hidden; +} AffineKeyboardAvoidanceMetrics; + +typedef struct AffinePdfPageSize { + float width_pt; + float height_pt; +} AffinePdfPageSize; + +typedef struct AffinePdfRenderPlan { + uint32_t target_width_px; + uint32_t target_height_px; + size_t byte_len; + uint32_t error; +} AffinePdfRenderPlan; + +typedef void (*AffineHapticsCallback)(uint8_t pattern, void *user_data); + +typedef uint64_t (*AffinePdfOpenDocFn)( + const uint8_t *pdf_ptr, + size_t pdf_len, + void *user_data); + +typedef void (*AffinePdfCloseDocFn)( + uint64_t doc_id, + void *user_data); + +typedef uint32_t (*AffinePdfDocPageCountFn)( + uint64_t doc_id, + void *user_data); + +typedef bool (*AffinePdfDocPageSizeFn)( + uint64_t doc_id, + uint32_t page_index, + AffinePdfPageSize *out_size, + void *user_data); + +typedef bool (*AffinePdfDocRenderRgba8Fn)( + uint64_t doc_id, + uint32_t page_index, + uint32_t target_width_px, + uint32_t target_height_px, + uint8_t *out_rgba_ptr, + size_t out_rgba_len, + void *user_data); + +typedef struct AffinePdfProvider { + AffinePdfOpenDocFn open_doc; + AffinePdfCloseDocFn close_doc; + AffinePdfDocPageCountFn doc_page_count; + AffinePdfDocPageSizeFn doc_page_size; + AffinePdfDocRenderRgba8Fn doc_render_rgba8; + void *user_data; +} AffinePdfProvider; + +typedef struct AffineSelectionRect { + AffineRect rect; + bool contains_start; + bool contains_end; +} AffineSelectionRect; + +typedef AffineRect (*AffineTextCaretRectFn)( + const uint16_t *utf16_ptr, + size_t utf16_len, + uint32_t utf16_offset, + float viewport_w, + AffineWindowInsets insets, + void *user_data); + +typedef uint32_t (*AffineTextClosestOffsetFn)( + const uint16_t *utf16_ptr, + size_t utf16_len, + AffinePoint point, + uint32_t preferred_offset, + float viewport_w, + AffineWindowInsets insets, + void *user_data); + +typedef size_t (*AffineTextSelectionRectsFn)( + const uint16_t *utf16_ptr, + size_t utf16_len, + AffineUtf16Range range, + float viewport_w, + AffineWindowInsets insets, + AffineSelectionRect *out_rects, + size_t capacity, + void *user_data); + +typedef bool (*AffineTextSelectionEndpointCaretsFn)( + const uint16_t *utf16_ptr, + size_t utf16_len, + AffineUtf16Range range, + float viewport_w, + AffineWindowInsets insets, + AffineRect *out_start, + AffineRect *out_end, + void *user_data); + +typedef bool (*AffineTextRenderLoupeRgba8Fn)( + const uint16_t *utf16_ptr, + size_t utf16_len, + AffineUtf16Range selected_range, + float viewport_w, + AffineWindowInsets insets, + float focus_x, + float focus_y, + uint32_t diameter_px, + float zoom_scale, + uint8_t *out_rgba_ptr, + size_t out_rgba_len, + void *user_data); + +typedef struct AffineTextProvider { + AffineTextCaretRectFn caret_rect; + AffineTextClosestOffsetFn closest_offset; + AffineTextSelectionRectsFn selection_rects; + AffineTextSelectionEndpointCaretsFn selection_endpoint_carets; + AffineTextRenderLoupeRgba8Fn render_loupe_rgba8; + void *user_data; +} AffineTextProvider; + void affine_ios_string_free(char *ptr); void affine_ios_bytes_free(AffineIosByteBuffer buf); @@ -178,6 +353,190 @@ bool affine_ios_workspace_checkpoint_passive(const AffineIosWorkspace *ws); bool affine_ios_workspace_checkpoint(const AffineIosWorkspace *ws); +AffineWindowInsets affine_ios_host_insets(const AffineIosHost *host); + +float affine_ios_host_ime_above_safe_bottom(const AffineIosHost *host); + +AffineKeyboardAvoidanceMetrics affine_ios_keyboard_compute_avoidance( + AffineRect window_bounds, + AffineRect keyboard_frame_in_window, + float safe_bottom, + bool is_hidden); + +void affine_ios_host_begin_keyboard_transition( + AffineIosHost *host, + float target_ime_bottom_pt, + double start_timestamp_sec, + double duration_sec); + +AffineWindowInsets affine_ios_host_sample_keyboard_frame( + AffineIosHost *host, + float safe_top, + float safe_right, + float safe_bottom, + float safe_left, + double frame_timestamp_sec); + +AffineSelectionOverlayState affine_ios_host_selection_set( + AffineIosHost *host, + AffineRect start_caret, + AffineRect end_caret, + AffineUtf16Range range, + uint8_t writing_direction); + +void affine_ios_host_selection_clear(AffineIosHost *host); + +AffineSelectionOverlayState affine_ios_host_selection_state( + const AffineIosHost *host); + +uint8_t affine_ios_host_selection_hit_test( + const AffineIosHost *host, + AffinePoint point, + float hit_radius_pt); + +bool affine_ios_host_selection_begin_drag( + AffineIosHost *host, + uint8_t handle_kind, + AffinePoint touch_point); + +AffinePoint affine_ios_host_selection_drag_probe( + const AffineIosHost *host, + AffinePoint touch_point); + +AffineSelectionOverlayState affine_ios_host_selection_update_drag( + AffineIosHost *host, + AffinePoint touch_point, + AffineRect updated_caret, + AffineUtf16Range updated_range); + +uint32_t affine_ios_host_selection_drag_anchor( + const AffineIosHost *host); + +AffineSelectionOverlayState affine_ios_host_selection_apply_drag_endpoints( + AffineIosHost *host, + AffinePoint touch_point, + uint32_t target_offset, + AffineRect start_caret, + AffineRect end_caret); + +AffineSelectionOverlayState affine_ios_host_selection_end_drag( + AffineIosHost *host); + +void affine_ios_host_set_text_provider( + AffineIosHost *host, + AffineTextProvider provider); + +uint8_t affine_ios_host_text_writing_direction( + const AffineIosHost *host); + +AffineRect affine_ios_host_text_caret_rect( + const AffineIosHost *host, + uint32_t utf16_offset); + +size_t affine_ios_host_text_selection_rects( + const AffineIosHost *host, + AffineUtf16Range range, + AffineSelectionRect *out_rects, + size_t capacity); + +bool affine_ios_host_text_selection_endpoint_carets( + const AffineIosHost *host, + AffineUtf16Range range, + AffineRect *out_start, + AffineRect *out_end); + +uint32_t affine_ios_host_text_closest_offset( + const AffineIosHost *host, + AffinePoint point); + +uint32_t affine_ios_host_text_closest_offset_preferred( + const AffineIosHost *host, + AffinePoint point, + uint32_t preferred_offset); + +AffineIosByteBuffer affine_ios_host_render_loupe_rgba8( + const AffineIosHost *host, + float focus_x, + float focus_y, + uint32_t diameter_px, + float zoom_scale); + +uint32_t affine_ios_pdf_validate_bytes( + const uint8_t *pdf_ptr, + size_t pdf_len); + +AffinePdfRenderPlan affine_ios_pdf_plan_render( + uint32_t page_index, + uint32_t page_count, + uint32_t target_width_px, + uint32_t target_height_px); + +void affine_ios_host_set_pdf_provider( + AffineIosHost *host, + AffinePdfProvider provider); + +uint64_t affine_ios_host_pdf_open( + const AffineIosHost *host, + const uint8_t *pdf_ptr, + size_t pdf_len, + uint32_t *out_error); + +void affine_ios_host_pdf_close( + const AffineIosHost *host, + uint64_t doc_id); + +uint32_t affine_ios_host_pdf_doc_page_count( + const AffineIosHost *host, + uint64_t doc_id, + uint32_t *out_error); + +bool affine_ios_host_pdf_doc_page_size( + const AffineIosHost *host, + uint64_t doc_id, + uint32_t page_index, + AffinePdfPageSize *out_size, + uint32_t *out_error); + +AffineIosByteBuffer affine_ios_host_pdf_doc_render_page_rgba8( + const AffineIosHost *host, + uint64_t doc_id, + uint32_t page_index, + uint32_t target_width_px, + uint32_t target_height_px, + uint32_t *out_error); + +/* Stateless convenience wrappers; production callers should prefer affine_ios_host_pdf_open/close handles. */ +uint32_t affine_ios_host_pdf_page_count( + const AffineIosHost *host, + const uint8_t *pdf_ptr, + size_t pdf_len, + uint32_t *out_error); + +AffineIosByteBuffer affine_ios_host_pdf_render_page_rgba8( + const AffineIosHost *host, + const uint8_t *pdf_ptr, + size_t pdf_len, + uint32_t page_index, + uint32_t target_width_px, + uint32_t target_height_px, + uint32_t *out_error); + +void affine_ios_host_set_haptics_callback( + AffineIosHost *host, + AffineHapticsCallback callback, + void *user_data); + +bool affine_ios_host_trigger_haptic( + AffineIosHost *host, + uint8_t pattern); + +uint64_t affine_ios_host_haptic_count( + const AffineIosHost *host, + uint8_t pattern); + +uint64_t affine_ios_host_haptic_total_count( + const AffineIosHost *host); + #ifdef __cplusplus } #endif diff --git a/packages/frontend/hosts/ios/src/ffi.rs b/packages/frontend/hosts/ios/src/ffi.rs index f89b6e3264..48a9578a2f 100644 --- a/packages/frontend/hosts/ios/src/ffi.rs +++ b/packages/frontend/hosts/ios/src/ffi.rs @@ -20,8 +20,12 @@ use super::{ /// Opaque C-ABI handle matching `typedef struct AffineIosHost AffineIosHost`. pub struct AffineIosHost { - state: IosHostState, + pub(crate) state: IosHostState, _metal_layer: *mut c_void, + pub(crate) haptics_callback: Option, + pub(crate) haptics_user_data: *mut c_void, + pub(crate) pdf_provider: Option, + pub(crate) text_provider: Option, } /// Opaque C-ABI handle matching `typedef struct AffineIosWorkspace AffineIosWorkspace`. @@ -38,14 +42,14 @@ pub struct AffineIosByteBuffer { } impl AffineIosByteBuffer { - fn empty() -> Self { + pub(crate) fn empty() -> Self { Self { ptr: core::ptr::null_mut(), len: 0, } } - fn from_vec(bytes: Vec) -> Self { + pub(crate) fn from_vec(bytes: Vec) -> Self { if bytes.is_empty() { return Self::empty(); } @@ -103,6 +107,10 @@ pub extern "C" fn affine_ios_host_create( let host = Box::new(AffineIosHost { state: IosHostState::new(width_pt, height_pt, scale_factor), _metal_layer: metal_layer, + haptics_callback: None, + haptics_user_data: core::ptr::null_mut(), + pdf_provider: None, + text_provider: None, }); Box::into_raw(host) } diff --git a/packages/frontend/hosts/ios/src/ffi_s3.rs b/packages/frontend/hosts/ios/src/ffi_s3.rs new file mode 100644 index 0000000000..7f951c5bd0 --- /dev/null +++ b/packages/frontend/hosts/ios/src/ffi_s3.rs @@ -0,0 +1,907 @@ +#![allow(unsafe_code)] + +use std::ffi::c_void; + +use super::{ + AffineUtf16Range, AffineWindowInsets, + ffi::{AffineIosByteBuffer, AffineIosHost}, + haptics::AffineHapticPattern, + keyboard_insets::{AffineKeyboardAvoidanceMetrics, compute_keyboard_avoidance}, + pdf::{ + AffinePdfErrorCode, AffinePdfPageSize, AffinePdfRenderPlan, plan_pdf_page_render, + validate_pdf_bytes, + }, + selection::{ + AffinePoint, AffineRect, AffineSelectionHandleKind, AffineSelectionOverlayState, + AffineWritingDirection, + }, +}; + +/// C-ABI callback invoked by Rust when a haptic pattern is triggered. +pub type AffineHapticsCallback = extern "C" fn(u8, *mut c_void); + +/// C-ABI callback opening an in-memory PDF into an explicit native document handle (`0` on error). +pub type AffinePdfOpenDocFn = extern "C" fn(*const u8, usize, *mut c_void) -> u64; + +/// C-ABI callback closing an explicit native PDF document handle. +pub type AffinePdfCloseDocFn = extern "C" fn(u64, *mut c_void); + +/// C-ABI callback querying total page count of an open native PDF document handle. +pub type AffinePdfDocPageCountFn = extern "C" fn(u64, *mut c_void) -> u32; + +/// C-ABI callback querying displayed point size of one page on an open PDF handle. +pub type AffinePdfDocPageSizeFn = + extern "C" fn(u64, u32, *mut AffinePdfPageSize, *mut c_void) -> bool; + +/// C-ABI callback rasterizing one page on an open PDF handle into a caller RGBA8 buffer. +pub type AffinePdfDocRenderRgba8Fn = + extern "C" fn(u64, u32, u32, u32, *mut u8, usize, *mut c_void) -> bool; + +/// Native PDFKit provider table registered by Swift `PdfRendererBridge`. +#[repr(C)] +#[derive(Clone, Copy)] +pub struct AffinePdfProvider { + pub open_doc: Option, + pub close_doc: Option, + pub doc_page_count: Option, + pub doc_page_size: Option, + pub doc_render_rgba8: Option, + pub user_data: *mut c_void, +} + +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_insets(host: *const AffineIosHost) -> AffineWindowInsets { + let Some(host) = (unsafe { host.as_ref() }) else { + return AffineWindowInsets::default(); + }; + host.state.insets() +} + +/// Query keyboard height strictly above `safe_bottom` (`max(0, ime_bottom - safe_bottom)`). +/// +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_ime_above_safe_bottom(host: *const AffineIosHost) -> f32 { + let Some(host) = (unsafe { host.as_ref() }) else { + return 0.0; + }; + host.state.ime_above_safe_bottom() +} + +/// Compute keyboard avoidance metrics from window bounds and keyboard frame. +#[unsafe(no_mangle)] +pub extern "C" fn affine_ios_keyboard_compute_avoidance( + window_bounds: AffineRect, + keyboard_frame_in_window: AffineRect, + safe_bottom: f32, + is_hidden: bool, +) -> AffineKeyboardAvoidanceMetrics { + compute_keyboard_avoidance( + window_bounds, + keyboard_frame_in_window, + safe_bottom, + is_hidden, + ) +} + +/// Begin a per-frame eased keyboard avoidance transition on `host`. +/// +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_begin_keyboard_transition( + host: *mut AffineIosHost, + target_ime_bottom_pt: f32, + start_timestamp_sec: f64, + duration_sec: f64, +) { + let Some(host) = (unsafe { host.as_mut() }) else { + return; + }; + host.state + .begin_keyboard_transition(target_ime_bottom_pt, start_timestamp_sec, duration_sec); +} + +/// Sample the active keyboard transition at `frame_timestamp_sec` and sync `AffineWindowInsets`. +/// +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_sample_keyboard_frame( + host: *mut AffineIosHost, + safe_top: f32, + safe_right: f32, + safe_bottom: f32, + safe_left: f32, + frame_timestamp_sec: f64, +) -> AffineWindowInsets { + let Some(host) = (unsafe { host.as_mut() }) else { + return AffineWindowInsets::default(); + }; + host.state.sample_keyboard_frame( + safe_top, + safe_right, + safe_bottom, + safe_left, + frame_timestamp_sec, + ) +} + +/// Update selection caret geometry, UTF-16 range, and writing direction on `host`. +/// +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_selection_set( + host: *mut AffineIosHost, + start_caret: AffineRect, + end_caret: AffineRect, + range: AffineUtf16Range, + writing_direction: u8, +) -> AffineSelectionOverlayState { + let Some(host) = (unsafe { host.as_mut() }) else { + return AffineSelectionOverlayState::default(); + }; + host.state.selection_overlay_mut().set_selection( + start_caret, + end_caret, + range, + AffineWritingDirection::from_u8(writing_direction), + ); + host.state.selection_overlay_state() +} + +/// Clear active selection overlay state on `host`. +/// +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_selection_clear(host: *mut AffineIosHost) { + let Some(host) = (unsafe { host.as_mut() }) else { + return; + }; + host.state.selection_overlay_mut().clear(); +} + +/// Query the current computed selection overlay state (teardrop handles, loupe, menu anchor). +/// +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_selection_state( + host: *const AffineIosHost, +) -> AffineSelectionOverlayState { + let Some(host) = (unsafe { host.as_ref() }) else { + return AffineSelectionOverlayState::default(); + }; + host.state.selection_overlay_state() +} + +/// Hit-test teardrop selection handles at `point` (`0 = none, 1 = start, 2 = end`). +/// +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_selection_hit_test( + host: *const AffineIosHost, + point: AffinePoint, + hit_radius_pt: f32, +) -> u8 { + let Some(host) = (unsafe { host.as_ref() }) else { + return AffineSelectionHandleKind::None as u8; + }; + let (vw, vh) = host.state.viewport_size_pt(); + let insets = host.state.insets(); + host.state + .selection_overlay() + .hit_test_handle(point, hit_radius_pt, vw, vh, insets) as u8 +} + +/// Begin dragging a teardrop selection handle and activate the magnifier loupe. +/// +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_selection_begin_drag( + host: *mut AffineIosHost, + handle_kind: u8, + touch_point: AffinePoint, +) -> bool { + let Some(host) = (unsafe { host.as_mut() }) else { + return false; + }; + host.state + .selection_overlay_mut() + .begin_drag(AffineSelectionHandleKind::from_u8(handle_kind), touch_point) +} + +/// Compute the caret-aligned probe point (`touch + grab_offset`) for an active drag. +/// +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_selection_drag_probe( + host: *const AffineIosHost, + touch_point: AffinePoint, +) -> AffinePoint { + let Some(host) = (unsafe { host.as_ref() }) else { + return touch_point; + }; + host.state + .selection_overlay() + .drag_probe_point_for(touch_point) +} + +/// Update an in-progress teardrop handle drag and return the refreshed overlay state. +/// +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_selection_update_drag( + host: *mut AffineIosHost, + touch_point: AffinePoint, + updated_caret: AffineRect, + updated_range: AffineUtf16Range, +) -> AffineSelectionOverlayState { + let Some(host) = (unsafe { host.as_mut() }) else { + return AffineSelectionOverlayState::default(); + }; + let _ = + host.state + .selection_overlay_mut() + .update_drag(touch_point, updated_caret, updated_range); + host.state.selection_overlay_state() +} + +/// Query the fixed UTF-16 anchor offset of an active handle drag (`u32::MAX` when idle). +/// +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_selection_drag_anchor(host: *const AffineIosHost) -> u32 { + let Some(host) = (unsafe { host.as_ref() }) else { + return u32::MAX; + }; + host.state + .selection_overlay() + .drag_anchor_utf16() + .unwrap_or(u32::MAX) +} + +/// Update an in-progress drag from authoritative UTF-16 target offset and shaped start/end carets. +/// +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_selection_apply_drag_endpoints( + host: *mut AffineIosHost, + touch_point: AffinePoint, + target_offset: u32, + start_caret: AffineRect, + end_caret: AffineRect, +) -> AffineSelectionOverlayState { + let Some(host) = (unsafe { host.as_mut() }) else { + return AffineSelectionOverlayState::default(); + }; + let _ = host + .state + .selection_overlay_mut() + .apply_text_drag_endpoints(touch_point, target_offset, start_caret, end_caret); + host.state.selection_overlay_state() +} + +/// Finish an active handle drag, hiding the loupe and exposing `menu_anchor_rect`. +/// +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_selection_end_drag( + host: *mut AffineIosHost, +) -> AffineSelectionOverlayState { + let Some(host) = (unsafe { host.as_mut() }) else { + return AffineSelectionOverlayState::default(); + }; + let _ = host.state.selection_overlay_mut().end_drag(); + host.state.selection_overlay_state() +} + +/// Validate raw PDF bytes (`0 = ok`, otherwise `AffinePdfErrorCode`). +/// +/// # Safety +/// `pdf_ptr` must be valid for `pdf_len` reads when `pdf_len > 0`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_pdf_validate_bytes(pdf_ptr: *const u8, pdf_len: usize) -> u32 { + let slice = if pdf_len == 0 || pdf_ptr.is_null() { + &[] + } else { + // SAFETY: Caller guarantees `pdf_ptr` points to `pdf_len` initialized bytes. + unsafe { core::slice::from_raw_parts(pdf_ptr, pdf_len) } + }; + match validate_pdf_bytes(slice) { + Ok(()) => AffinePdfErrorCode::Ok as u32, + Err(code) => code as u32, + } +} + +/// Validate page index and target pixel dimensions and compute the RGBA8 byte budget. +#[unsafe(no_mangle)] +pub extern "C" fn affine_ios_pdf_plan_render( + page_index: u32, + page_count: u32, + target_width_px: u32, + target_height_px: u32, +) -> AffinePdfRenderPlan { + plan_pdf_page_render(page_index, page_count, target_width_px, target_height_px) +} + +/// Register the Swift `PDFKit` provider callback table on `host`. +/// +/// # Safety +/// `host` must be null or a live pointer; callbacks and `user_data` must outlive registration. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_set_pdf_provider( + host: *mut AffineIosHost, + provider: AffinePdfProvider, +) { + let Some(host) = (unsafe { host.as_mut() }) else { + return; + }; + if provider.open_doc.is_none() + && provider.close_doc.is_none() + && provider.doc_page_count.is_none() + && provider.doc_page_size.is_none() + && provider.doc_render_rgba8.is_none() + { + host.pdf_provider = None; + } else { + host.pdf_provider = Some(provider); + } +} + +fn write_pdf_err(out_error: *mut u32, code: AffinePdfErrorCode) { + if let Some(slot) = unsafe { out_error.as_mut() } { + *slot = code as u32; + } +} + +/// Open an in-memory PDF into an explicit native document handle (`0` on error). +/// +/// # Safety +/// `host` must be a live pointer; `pdf_ptr` must be valid for `pdf_len` reads when non-zero. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_pdf_open( + host: *const AffineIosHost, + pdf_ptr: *const u8, + pdf_len: usize, + out_error: *mut u32, +) -> u64 { + let Some(host) = (unsafe { host.as_ref() }) else { + write_pdf_err(out_error, AffinePdfErrorCode::InvalidArgument); + return 0; + }; + let slice = if pdf_len == 0 || pdf_ptr.is_null() { + &[] + } else { + // SAFETY: Caller guarantees `pdf_ptr` points to `pdf_len` bytes. + unsafe { core::slice::from_raw_parts(pdf_ptr, pdf_len) } + }; + if let Err(code) = validate_pdf_bytes(slice) { + write_pdf_err(out_error, code); + return 0; + } + let Some(provider) = host.pdf_provider else { + write_pdf_err(out_error, AffinePdfErrorCode::RenderFailed); + return 0; + }; + let Some(open_fn) = provider.open_doc else { + write_pdf_err(out_error, AffinePdfErrorCode::RenderFailed); + return 0; + }; + let doc_id = open_fn(slice.as_ptr(), slice.len(), provider.user_data); + if doc_id == 0 { + write_pdf_err(out_error, AffinePdfErrorCode::InvalidOrEncryptedPdf); + } else { + write_pdf_err(out_error, AffinePdfErrorCode::Ok); + } + doc_id +} + +/// Close an explicit native PDF document handle, releasing its `PDFDocument` immediately. +/// +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_pdf_close(host: *const AffineIosHost, doc_id: u64) { + if doc_id == 0 { + return; + } + let Some(host) = (unsafe { host.as_ref() }) else { + return; + }; + if let Some(provider) = host.pdf_provider + && let Some(close_fn) = provider.close_doc + { + close_fn(doc_id, provider.user_data); + } +} + +/// Query page count on an open PDF handle (`O(1)` lookup, zero hashing). +/// +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_pdf_doc_page_count( + host: *const AffineIosHost, + doc_id: u64, + out_error: *mut u32, +) -> u32 { + let Some(host) = (unsafe { host.as_ref() }) else { + write_pdf_err(out_error, AffinePdfErrorCode::InvalidArgument); + return 0; + }; + if doc_id == 0 { + write_pdf_err(out_error, AffinePdfErrorCode::InvalidArgument); + return 0; + } + let Some(provider) = host.pdf_provider else { + write_pdf_err(out_error, AffinePdfErrorCode::RenderFailed); + return 0; + }; + let Some(count_fn) = provider.doc_page_count else { + write_pdf_err(out_error, AffinePdfErrorCode::RenderFailed); + return 0; + }; + let count = count_fn(doc_id, provider.user_data); + if count == 0 { + write_pdf_err(out_error, AffinePdfErrorCode::InvalidArgument); + } else { + write_pdf_err(out_error, AffinePdfErrorCode::Ok); + } + count +} + +/// Query displayed page point size on an open PDF handle. +/// +/// # Safety +/// `host` must be null or a live pointer; `out_size` must be writable when non-null. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_pdf_doc_page_size( + host: *const AffineIosHost, + doc_id: u64, + page_index: u32, + out_size: *mut AffinePdfPageSize, + out_error: *mut u32, +) -> bool { + let Some(host_ref) = (unsafe { host.as_ref() }) else { + write_pdf_err(out_error, AffinePdfErrorCode::InvalidArgument); + return false; + }; + if doc_id == 0 || out_size.is_null() { + write_pdf_err(out_error, AffinePdfErrorCode::InvalidArgument); + return false; + } + let mut count_err = AffinePdfErrorCode::Ok as u32; + let count = unsafe { affine_ios_host_pdf_doc_page_count(host, doc_id, &mut count_err) }; + if count_err != AffinePdfErrorCode::Ok as u32 { + if let Some(slot) = unsafe { out_error.as_mut() } { + *slot = count_err; + } + return false; + } + if page_index >= count { + write_pdf_err(out_error, AffinePdfErrorCode::PageOutOfRange); + return false; + } + let Some(provider) = host_ref.pdf_provider else { + write_pdf_err(out_error, AffinePdfErrorCode::RenderFailed); + return false; + }; + let Some(size_fn) = provider.doc_page_size else { + write_pdf_err(out_error, AffinePdfErrorCode::RenderFailed); + return false; + }; + let ok = size_fn(doc_id, page_index, out_size, provider.user_data); + write_pdf_err( + out_error, + if ok { + AffinePdfErrorCode::Ok + } else { + AffinePdfErrorCode::RenderFailed + }, + ); + ok +} + +/// Rasterize one page on an open PDF handle to RGBA8 with bounds/OOM checks. +/// +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_pdf_doc_render_page_rgba8( + host: *const AffineIosHost, + doc_id: u64, + page_index: u32, + target_width_px: u32, + target_height_px: u32, + out_error: *mut u32, +) -> AffineIosByteBuffer { + let Some(host_ref) = (unsafe { host.as_ref() }) else { + write_pdf_err(out_error, AffinePdfErrorCode::InvalidArgument); + return AffineIosByteBuffer::empty(); + }; + let mut count_err = AffinePdfErrorCode::Ok as u32; + let page_count = unsafe { affine_ios_host_pdf_doc_page_count(host, doc_id, &mut count_err) }; + if count_err != AffinePdfErrorCode::Ok as u32 { + if let Some(slot) = unsafe { out_error.as_mut() } { + *slot = count_err; + } + return AffineIosByteBuffer::empty(); + } + let plan = plan_pdf_page_render(page_index, page_count, target_width_px, target_height_px); + if plan.error != AffinePdfErrorCode::Ok as u32 { + if let Some(slot) = unsafe { out_error.as_mut() } { + *slot = plan.error; + } + return AffineIosByteBuffer::empty(); + } + let Some(provider) = host_ref.pdf_provider else { + write_pdf_err(out_error, AffinePdfErrorCode::RenderFailed); + return AffineIosByteBuffer::empty(); + }; + let Some(render_fn) = provider.doc_render_rgba8 else { + write_pdf_err(out_error, AffinePdfErrorCode::RenderFailed); + return AffineIosByteBuffer::empty(); + }; + let mut rgba = vec![0u8; plan.byte_len]; + let ok = render_fn( + doc_id, + page_index, + plan.target_width_px, + plan.target_height_px, + rgba.as_mut_ptr(), + rgba.len(), + provider.user_data, + ); + if !ok { + write_pdf_err(out_error, AffinePdfErrorCode::RenderFailed); + return AffineIosByteBuffer::empty(); + } + write_pdf_err(out_error, AffinePdfErrorCode::Ok); + AffineIosByteBuffer::from_vec(rgba) +} + +/// Stateless convenience wrapper: opens, queries page count, and immediately closes the PDF handle. +/// +/// # Safety +/// `host` must be a live pointer; `pdf_ptr` must be valid for `pdf_len` reads when non-zero. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_pdf_page_count( + host: *const AffineIosHost, + pdf_ptr: *const u8, + pdf_len: usize, + out_error: *mut u32, +) -> u32 { + let mut open_err = AffinePdfErrorCode::Ok as u32; + let doc_id = unsafe { affine_ios_host_pdf_open(host, pdf_ptr, pdf_len, &mut open_err) }; + if doc_id == 0 { + if let Some(slot) = unsafe { out_error.as_mut() } { + *slot = open_err; + } + return 0; + } + let count = unsafe { affine_ios_host_pdf_doc_page_count(host, doc_id, out_error) }; + unsafe { affine_ios_host_pdf_close(host, doc_id) }; + count +} + +/// Stateless convenience wrapper: opens, rasterizes one page, and immediately closes the PDF handle. +/// +/// # Safety +/// `host` must be a live pointer; `pdf_ptr` must be valid for `pdf_len` reads when non-zero. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_pdf_render_page_rgba8( + host: *const AffineIosHost, + pdf_ptr: *const u8, + pdf_len: usize, + page_index: u32, + target_width_px: u32, + target_height_px: u32, + out_error: *mut u32, +) -> AffineIosByteBuffer { + let mut open_err = AffinePdfErrorCode::Ok as u32; + let doc_id = unsafe { affine_ios_host_pdf_open(host, pdf_ptr, pdf_len, &mut open_err) }; + if doc_id == 0 { + if let Some(slot) = unsafe { out_error.as_mut() } { + *slot = open_err; + } + return AffineIosByteBuffer::empty(); + } + let buf = unsafe { + affine_ios_host_pdf_doc_render_page_rgba8( + host, + doc_id, + page_index, + target_width_px, + target_height_px, + out_error, + ) + }; + unsafe { affine_ios_host_pdf_close(host, doc_id) }; + buf +} + +/// Register the Swift `HapticsBridge` callback on `host`. +/// +/// # Safety +/// `host` must be null or a live pointer; `user_data` must outlive the registration. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_set_haptics_callback( + host: *mut AffineIosHost, + callback: Option, + user_data: *mut c_void, +) { + let Some(host) = (unsafe { host.as_mut() }) else { + return; + }; + host.haptics_callback = callback; + host.haptics_user_data = user_data; +} + +/// Trigger one haptic pattern (`0..=6`), increment counters, and invoke any registered callback. +/// +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_trigger_haptic( + host: *mut AffineIosHost, + pattern: u8, +) -> bool { + let Some(host) = (unsafe { host.as_mut() }) else { + return false; + }; + let Some(parsed) = AffineHapticPattern::from_u8(pattern) else { + return false; + }; + host.state.record_haptic(parsed); + if let Some(cb) = host.haptics_callback { + cb(pattern, host.haptics_user_data); + } + true +} + +/// Query dispatch count for a single haptic pattern (`0..=6`). +/// +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_haptic_count( + host: *const AffineIosHost, + pattern: u8, +) -> u64 { + let Some(host) = (unsafe { host.as_ref() }) else { + return 0; + }; + let Some(parsed) = AffineHapticPattern::from_u8(pattern) else { + return 0; + }; + host.state.haptics().count_for(parsed) +} + +/// Query total haptic dispatch count across all patterns. +/// +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_haptic_total_count(host: *const AffineIosHost) -> u64 { + let Some(host) = (unsafe { host.as_ref() }) else { + return 0; + }; + host.state.haptics().total_count() +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::ffi::{affine_ios_bytes_free, affine_ios_host_create, affine_ios_host_destroy}; + + extern "C" fn test_haptic_cb(pattern: u8, user_data: *mut c_void) { + let log = unsafe { &mut *(user_data as *mut Vec) }; + log.push(pattern); + } + + extern "C" fn test_pdf_open(_ptr: *const u8, _len: usize, _ud: *mut c_void) -> u64 { + 42 + } + + extern "C" fn test_pdf_close(_doc_id: u64, _ud: *mut c_void) {} + + extern "C" fn test_pdf_doc_count(doc_id: u64, _ud: *mut c_void) -> u32 { + if doc_id == 42 { 2 } else { 0 } + } + + extern "C" fn test_pdf_doc_size( + doc_id: u64, + _page_index: u32, + out_size: *mut AffinePdfPageSize, + _ud: *mut c_void, + ) -> bool { + if doc_id != 42 || out_size.is_null() { + return false; + } + unsafe { + *out_size = AffinePdfPageSize { + width_pt: 200.0, + height_pt: 300.0, + }; + } + true + } + + extern "C" fn test_pdf_doc_render( + doc_id: u64, + page_index: u32, + w: u32, + h: u32, + out_ptr: *mut u8, + out_len: usize, + _ud: *mut c_void, + ) -> bool { + let expected = (w as usize) * (h as usize) * 4; + if doc_id != 42 || out_ptr.is_null() || out_len != expected { + return false; + } + let buf = unsafe { core::slice::from_raw_parts_mut(out_ptr, out_len) }; + buf.fill(if page_index == 0 { 0x22 } else { 0x88 }); + true + } + + #[test] + fn c_abi_s3_selection_keyboard_pdf_and_haptics_roundtrip() { + let host = affine_ios_host_create(core::ptr::null_mut(), 390.0, 844.0, 3.0); + assert!(!host.is_null()); + + // Keyboard avoidance + per-frame transition. + let metrics = affine_ios_keyboard_compute_avoidance( + AffineRect { + x: 0.0, + y: 0.0, + width: 390.0, + height: 844.0, + }, + AffineRect { + x: 0.0, + y: 542.0, + width: 390.0, + height: 302.0, + }, + 34.0, + false, + ); + assert_eq!(metrics.ime_bottom_pt, 302.0); + assert_eq!(metrics.ime_above_safe_bottom_pt, 268.0); + assert_eq!(metrics.effective_bottom_pt, 302.0); + + unsafe { + affine_ios_host_begin_keyboard_transition(host, metrics.ime_bottom_pt, 1.0, 0.25); + let mid = affine_ios_host_sample_keyboard_frame(host, 59.0, 0.0, 34.0, 0.0, 1.125); + assert!(mid.ime_bottom > 150.0 && mid.ime_bottom < 302.0); + let end = affine_ios_host_sample_keyboard_frame(host, 59.0, 0.0, 34.0, 0.0, 1.25); + assert_eq!(end.ime_bottom, 302.0); + assert_eq!(affine_ios_host_insets(host), end); + assert_eq!(affine_ios_host_ime_above_safe_bottom(host), 268.0); + } + + // Selection teardrop + loupe drag lifecycle. + let sel = unsafe { + affine_ios_host_selection_set( + host, + AffineRect { + x: 60.0, + y: 160.0, + width: 2.0, + height: 20.0, + }, + AffineRect { + x: 180.0, + y: 160.0, + width: 2.0, + height: 20.0, + }, + AffineUtf16Range { + location: 0, + length: 8, + }, + 0, + ) + }; + assert!(sel.start_handle.visible && sel.end_handle.visible && sel.show_floating_menu); + let hit = unsafe { + affine_ios_host_selection_hit_test(host, AffinePoint { x: 183.0, y: 186.0 }, 22.0) + }; + assert_eq!(hit, AffineSelectionHandleKind::End as u8); + assert!(unsafe { + affine_ios_host_selection_begin_drag(host, hit, AffinePoint { x: 183.0, y: 186.0 }) + }); + let dragged = unsafe { + affine_ios_host_selection_update_drag( + host, + AffinePoint { x: 220.0, y: 186.0 }, + AffineRect { + x: 220.0, + y: 160.0, + width: 2.0, + height: 20.0, + }, + AffineUtf16Range { + location: 0, + length: 12, + }, + ) + }; + assert!(dragged.loupe.visible && !dragged.show_floating_menu); + let ended = unsafe { affine_ios_host_selection_end_drag(host) }; + assert!(!ended.loupe.visible && ended.show_floating_menu); + + // Explicit PDF handle lifecycle + stateless convenience wrapper. + unsafe { + affine_ios_host_set_pdf_provider( + host, + AffinePdfProvider { + open_doc: Some(test_pdf_open), + close_doc: Some(test_pdf_close), + doc_page_count: Some(test_pdf_doc_count), + doc_page_size: Some(test_pdf_doc_size), + doc_render_rgba8: Some(test_pdf_doc_render), + user_data: core::ptr::null_mut(), + }, + ); + let sample_pdf = b"%PDF-1.4\n%%EOF\n"; + let mut err = 99u32; + let doc_id = + affine_ios_host_pdf_open(host, sample_pdf.as_ptr(), sample_pdf.len(), &mut err); + assert_eq!(err, AffinePdfErrorCode::Ok as u32); + assert_eq!(doc_id, 42); + + let mut size = AffinePdfPageSize::default(); + assert!(affine_ios_host_pdf_doc_page_size( + host, doc_id, 0, &mut size, &mut err + )); + assert_eq!(size.width_pt, 200.0); + assert_eq!(size.height_pt, 300.0); + + let buf = affine_ios_host_pdf_doc_render_page_rgba8(host, doc_id, 0, 4, 4, &mut err); + assert_eq!(err, AffinePdfErrorCode::Ok as u32); + assert_eq!(buf.len, 64); + let bytes = core::slice::from_raw_parts(buf.ptr, buf.len); + assert_eq!(bytes[0], 0x22); + affine_ios_bytes_free(buf); + + // Out-of-range page rejected before calling provider. + let bad = affine_ios_host_pdf_doc_render_page_rgba8(host, doc_id, 2, 4, 4, &mut err); + assert_eq!(err, AffinePdfErrorCode::PageOutOfRange as u32); + assert_eq!(bad.len, 0); + affine_ios_host_pdf_close(host, doc_id); + } + + // Haptics callback + counters. + let mut received = Vec::::new(); + unsafe { + affine_ios_host_set_haptics_callback( + host, + Some(test_haptic_cb), + (&mut received as *mut Vec).cast(), + ); + assert!(affine_ios_host_trigger_haptic(host, 0)); + assert!(affine_ios_host_trigger_haptic(host, 4)); + assert!(!affine_ios_host_trigger_haptic(host, 99)); + assert_eq!(affine_ios_host_haptic_count(host, 0), 1); + assert_eq!(affine_ios_host_haptic_count(host, 4), 1); + assert_eq!(affine_ios_host_haptic_total_count(host), 2); + affine_ios_host_destroy(host); + } + assert_eq!(received, vec![0, 4]); + } +} diff --git a/packages/frontend/hosts/ios/src/ffi_text.rs b/packages/frontend/hosts/ios/src/ffi_text.rs new file mode 100644 index 0000000000..0ad6409926 --- /dev/null +++ b/packages/frontend/hosts/ios/src/ffi_text.rs @@ -0,0 +1,331 @@ +#![allow(unsafe_code)] + +use std::ffi::c_void; + +use super::{ + AffineUtf16Range, AffineWindowInsets, + ffi::{AffineIosByteBuffer, AffineIosHost}, + selection::{AffinePoint, AffineRect, AffineWritingDirection}, + text_layout::{ + AffineSelectionRect, caret_rect_for_offset, closest_offset_for_point, render_loupe_rgba8, + selection_rects_for_range, + }, +}; + +/// C-ABI callback computing the shaped visual caret rect via native CoreText `CTLine`. +pub type AffineTextCaretRectFn = + extern "C" fn(*const u16, usize, u32, f32, AffineWindowInsets, *mut c_void) -> AffineRect; + +/// C-ABI callback hit-testing the closest grapheme-aligned UTF-16 offset via native CoreText, +/// disambiguating BiDi direction boundaries using `preferred_offset` (`u32::MAX` = none). +pub type AffineTextClosestOffsetFn = + extern "C" fn(*const u16, usize, AffinePoint, u32, f32, AffineWindowInsets, *mut c_void) -> u32; + +/// C-ABI callback computing BiDi-aware per-line selection rects via native CoreText `CTLine`. +pub type AffineTextSelectionRectsFn = extern "C" fn( + *const u16, + usize, + AffineUtf16Range, + f32, + AffineWindowInsets, + *mut AffineSelectionRect, + usize, + *mut c_void, +) -> usize; + +/// C-ABI callback computing affinity-aware start/end caret rects for a selection range. +pub type AffineTextSelectionEndpointCaretsFn = extern "C" fn( + *const u16, + usize, + AffineUtf16Range, + f32, + AffineWindowInsets, + *mut AffineRect, + *mut AffineRect, + *mut c_void, +) -> bool; + +/// C-ABI callback rasterizing the magnifier loupe via whole-line CoreText `CTLineDraw`. +pub type AffineTextRenderLoupeRgba8Fn = extern "C" fn( + *const u16, + usize, + AffineUtf16Range, + f32, + AffineWindowInsets, + f32, + f32, + u32, + f32, + *mut u8, + usize, + *mut c_void, +) -> bool; + +/// Native CoreText `CTTypesetter`/`CTLine` text geometry and vector loupe provider. +#[repr(C)] +#[derive(Clone, Copy)] +pub struct AffineTextProvider { + pub caret_rect: Option, + pub closest_offset: Option, + pub selection_rects: Option, + pub selection_endpoint_carets: Option, + pub render_loupe_rgba8: Option, + pub user_data: *mut c_void, +} + +/// Register the native CoreText `CTTypesetter`/`CTLine` provider on `host`. +/// +/// # Safety +/// `host` must be null or a live pointer; callbacks and `user_data` must outlive registration. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_set_text_provider( + host: *mut AffineIosHost, + provider: AffineTextProvider, +) { + let Some(host) = (unsafe { host.as_mut() }) else { + return; + }; + if provider.caret_rect.is_none() + && provider.closest_offset.is_none() + && provider.selection_rects.is_none() + && provider.selection_endpoint_carets.is_none() + && provider.render_loupe_rgba8.is_none() + { + host.text_provider = None; + } else { + host.text_provider = Some(provider); + } +} + +/// Query detected base writing direction of the host text buffer (`0 = LTR, 1 = RTL`). +/// +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_text_writing_direction(host: *const AffineIosHost) -> u8 { + let Some(host) = (unsafe { host.as_ref() }) else { + return AffineWritingDirection::Ltr as u8; + }; + host.state.text_writing_direction() as u8 +} + +/// Compute visual caret rect for `utf16_offset` via CoreText `CTLine` (or headless fallback). +/// +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_text_caret_rect( + host: *const AffineIosHost, + utf16_offset: u32, +) -> AffineRect { + let Some(host) = (unsafe { host.as_ref() }) else { + return AffineRect::default(); + }; + let (vw, _) = host.state.viewport_size_pt(); + let insets = host.state.insets(); + let utf16 = host.state.utf16_text(); + if let Some(p) = host.text_provider + && let Some(f) = p.caret_rect + { + return f( + utf16.as_ptr(), + utf16.len(), + utf16_offset, + vw, + insets, + p.user_data, + ); + } + caret_rect_for_offset(utf16, utf16_offset, vw, insets) +} + +/// Compute BiDi-aware per-line selection rectangles across soft-wrapped visual lines. +/// Returns total rectangle count; writes up to `capacity` items into `out_rects` when non-null. +/// +/// # Safety +/// `host` must be null or a live pointer; `out_rects` must be valid for `capacity` writes when non-null. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_text_selection_rects( + host: *const AffineIosHost, + range: AffineUtf16Range, + out_rects: *mut AffineSelectionRect, + capacity: usize, +) -> usize { + let Some(host) = (unsafe { host.as_ref() }) else { + return 0; + }; + let (vw, _) = host.state.viewport_size_pt(); + let insets = host.state.insets(); + let utf16 = host.state.utf16_text(); + if let Some(p) = host.text_provider + && let Some(f) = p.selection_rects + { + return f( + utf16.as_ptr(), + utf16.len(), + range, + vw, + insets, + out_rects, + capacity, + p.user_data, + ); + } + let rects = selection_rects_for_range(utf16, range, vw, insets); + if !out_rects.is_null() && capacity > 0 { + let count = rects.len().min(capacity); + // SAFETY: Caller guarantees `out_rects` points to `capacity` writable elements. + unsafe { + core::ptr::copy_nonoverlapping(rects.as_ptr(), out_rects, count); + } + } + rects.len() +} + +/// Compute affinity-aware start and end caret rects for `range` so handles align with +/// the visual leading/trailing edges of the first/last selected glyphs across BiDi boundaries. +/// +/// # Safety +/// `host`, `out_start`, and `out_end` must be valid pointers (or null for safe no-op). +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_text_selection_endpoint_carets( + host: *const AffineIosHost, + range: AffineUtf16Range, + out_start: *mut AffineRect, + out_end: *mut AffineRect, +) -> bool { + let (Some(host), Some(start_slot), Some(end_slot)) = ( + unsafe { host.as_ref() }, + unsafe { out_start.as_mut() }, + unsafe { out_end.as_mut() }, + ) else { + return false; + }; + let (vw, _) = host.state.viewport_size_pt(); + let insets = host.state.insets(); + let utf16 = host.state.utf16_text(); + if let Some(p) = host.text_provider + && let Some(f) = p.selection_endpoint_carets + && f( + utf16.as_ptr(), + utf16.len(), + range, + vw, + insets, + start_slot, + end_slot, + p.user_data, + ) + { + return true; + } + *start_slot = caret_rect_for_offset(utf16, range.location, vw, insets); + *end_slot = caret_rect_for_offset( + utf16, + range.location.saturating_add(range.length), + vw, + insets, + ); + true +} + +/// Hit-test closest grapheme-safe UTF-16 offset for `point` in host coordinates. +/// +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_text_closest_offset( + host: *const AffineIosHost, + point: AffinePoint, +) -> u32 { + unsafe { affine_ios_host_text_closest_offset_preferred(host, point, u32::MAX) } +} + +/// Hit-test closest grapheme-safe UTF-16 offset for `point`, preferring `preferred_offset` +/// (`u32::MAX` = none) when `point` sits on a BiDi direction boundary shared by two offsets. +/// +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_text_closest_offset_preferred( + host: *const AffineIosHost, + point: AffinePoint, + preferred_offset: u32, +) -> u32 { + let Some(host) = (unsafe { host.as_ref() }) else { + return 0; + }; + let (vw, _) = host.state.viewport_size_pt(); + let insets = host.state.insets(); + let utf16 = host.state.utf16_text(); + if let Some(p) = host.text_provider + && let Some(f) = p.closest_offset + { + return f( + utf16.as_ptr(), + utf16.len(), + point, + preferred_offset, + vw, + insets, + p.user_data, + ); + } + closest_offset_for_point(utf16, point, vw, insets) +} + +/// Rasterize the magnifier loupe around `(focus_x, focus_y)` as RGBA8 via whole-line `CTLineDraw` +/// (or software fallback in headless environments). Free with `affine_ios_bytes_free`. +/// +/// # Safety +/// `host` must be null or a live pointer returned by `affine_ios_host_create`. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_render_loupe_rgba8( + host: *const AffineIosHost, + focus_x: f32, + focus_y: f32, + diameter_px: u32, + zoom_scale: f32, +) -> AffineIosByteBuffer { + let Some(host) = (unsafe { host.as_ref() }) else { + return AffineIosByteBuffer::empty(); + }; + let dim = diameter_px.clamp(16, 512) as usize; + let zoom = if zoom_scale.is_finite() && zoom_scale > 0.25 { + zoom_scale.min(12.0) + } else { + 1.75 + }; + let (vw, _) = host.state.viewport_size_pt(); + let insets = host.state.insets(); + let utf16 = host.state.utf16_text(); + let selected = host.state.selected_range(); + + if let Some(p) = host.text_provider + && let Some(render_fn) = p.render_loupe_rgba8 + { + let mut rgba = vec![0u8; dim * dim * 4]; + let ok = render_fn( + utf16.as_ptr(), + utf16.len(), + selected, + vw, + insets, + focus_x, + focus_y, + dim as u32, + zoom, + rgba.as_mut_ptr(), + rgba.len(), + p.user_data, + ); + if ok { + return AffineIosByteBuffer::from_vec(rgba); + } + } + + let rgba = render_loupe_rgba8( + utf16, selected, vw, insets, focus_x, focus_y, dim as u32, zoom, + ); + AffineIosByteBuffer::from_vec(rgba) +} diff --git a/packages/frontend/hosts/ios/src/haptics.rs b/packages/frontend/hosts/ios/src/haptics.rs new file mode 100644 index 0000000000..471627c21b --- /dev/null +++ b/packages/frontend/hosts/ios/src/haptics.rs @@ -0,0 +1,90 @@ +//! Native iOS Haptics pattern definitions and deterministic dispatch accounting. + +/// Number of valid `AffineHapticPattern` variants. +pub const HAPTIC_PATTERN_COUNT: usize = 7; + +/// C-ABI haptic pattern enum matching `include/affine_mobile_host.h`. +#[repr(u8)] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum AffineHapticPattern { + LightImpact = 0, + MediumImpact = 1, + HeavyImpact = 2, + SelectionChanged = 3, + Success = 4, + Warning = 5, + Error = 6, +} + +impl AffineHapticPattern { + pub fn from_u8(raw: u8) -> Option { + match raw { + 0 => Some(Self::LightImpact), + 1 => Some(Self::MediumImpact), + 2 => Some(Self::HeavyImpact), + 3 => Some(Self::SelectionChanged), + 4 => Some(Self::Success), + 5 => Some(Self::Warning), + 6 => Some(Self::Error), + _ => None, + } + } +} + +/// Deterministic counter state for triggered haptic events. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct HapticsState { + counts: [u64; HAPTIC_PATTERN_COUNT], + total: u64, + last_pattern: Option, +} + +impl HapticsState { + pub fn record(&mut self, pattern: AffineHapticPattern) { + let idx = pattern as usize; + self.counts[idx] = self.counts[idx].saturating_add(1); + self.total = self.total.saturating_add(1); + self.last_pattern = Some(pattern); + } + + pub fn count_for(&self, pattern: AffineHapticPattern) -> u64 { + self.counts[pattern as usize] + } + + pub fn total_count(&self) -> u64 { + self.total + } + + pub fn last_pattern(&self) -> Option { + self.last_pattern + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn haptics_pattern_mapping_and_counters_cover_all_seven_variants() { + let all = [ + (0, AffineHapticPattern::LightImpact), + (1, AffineHapticPattern::MediumImpact), + (2, AffineHapticPattern::HeavyImpact), + (3, AffineHapticPattern::SelectionChanged), + (4, AffineHapticPattern::Success), + (5, AffineHapticPattern::Warning), + (6, AffineHapticPattern::Error), + ]; + + let mut state = HapticsState::default(); + for (raw, expected) in all { + assert_eq!(AffineHapticPattern::from_u8(raw), Some(expected)); + state.record(expected); + assert_eq!(state.count_for(expected), 1); + assert_eq!(state.last_pattern(), Some(expected)); + } + assert_eq!(state.total_count(), 7); + assert_eq!(AffineHapticPattern::from_u8(7), None); + assert_eq!(AffineHapticPattern::from_u8(255), None); + } +} diff --git a/packages/frontend/hosts/ios/src/keyboard_insets.rs b/packages/frontend/hosts/ios/src/keyboard_insets.rs new file mode 100644 index 0000000000..4814226588 --- /dev/null +++ b/packages/frontend/hosts/ios/src/keyboard_insets.rs @@ -0,0 +1,374 @@ +use crate::{AffineWindowInsets, selection::AffineRect}; + +/// Deterministic result of evaluating a keyboard frame against window bounds and safe area. +#[repr(C)] +#[derive(Debug, Clone, Copy, Default, PartialEq)] +pub struct AffineKeyboardAvoidanceMetrics { + /// Raw vertical intersection between the docked software keyboard and window bounds. + pub raw_overlap_pt: f32, + /// Absolute docked keyboard overlap height from the window bottom edge in logical points + /// (`0.0` for floating, split, hardware, or hidden keyboards). Matches `ui::WindowInsets.ime.bottom`. + pub ime_bottom_pt: f32, + /// Additional keyboard height above `safe_bottom` (`max(0, ime_bottom_pt - safe_bottom)`). + /// Provided for local containers that already deduct `safeAreaInsets.bottom`. + pub ime_above_safe_bottom_pt: f32, + /// Effective total bottom avoidance inset (`max(safe_bottom, ime_bottom_pt)`), + /// matching `ui::WindowInsets::effective().bottom` and `safe_bottom + ime_above_safe_bottom_pt`. + pub effective_bottom_pt: f32, + /// True when the keyboard is floating or split (iPad) and does not dock to the bottom edge. + pub is_floating_or_split: bool, + /// True when no docked software keyboard overlaps the window (hidden or hardware keyboard). + pub is_hardware_or_hidden: bool, +} + +/// Active keyboard height animation tracked deterministically by `CADisplayLink` timestamps. +#[derive(Debug, Clone, Copy, Default, PartialEq)] +pub struct KeyboardFrameTransition { + pub active: bool, + pub start_ime_bottom_pt: f32, + pub target_ime_bottom_pt: f32, + pub start_timestamp_sec: f64, + pub duration_sec: f64, +} + +impl KeyboardFrameTransition { + /// Begin a smooth transition toward `target_ime_bottom_pt` starting at `start_timestamp_sec`. + pub fn begin( + current_ime_bottom_pt: f32, + target_ime_bottom_pt: f32, + start_timestamp_sec: f64, + duration_sec: f64, + ) -> Self { + let cur = sanitize_non_neg(current_ime_bottom_pt); + let tgt = sanitize_non_neg(target_ime_bottom_pt); + let dur = if duration_sec.is_finite() && duration_sec > 0.0 { + duration_sec + } else { + 0.0 + }; + let ts = if start_timestamp_sec.is_finite() { + start_timestamp_sec + } else { + 0.0 + }; + Self { + active: dur > 0.0 && (cur - tgt).abs() > 0.01, + start_ime_bottom_pt: cur, + target_ime_bottom_pt: tgt, + start_timestamp_sec: ts, + duration_sec: dur, + } + } + + /// Sample the eased keyboard inset at `timestamp_sec` (monotonic `CADisplayLink.timestamp`). + /// Uses a cubic ease-out curve approximating UIKit's keyboard animation curve (`options: 7`). + pub fn sample(&mut self, timestamp_sec: f64) -> f32 { + if !self.active || self.duration_sec <= 0.0 { + self.active = false; + return self.target_ime_bottom_pt; + } + let now = if timestamp_sec.is_finite() { + timestamp_sec + } else { + self.start_timestamp_sec + self.duration_sec + }; + let elapsed = (now - self.start_timestamp_sec).max(0.0); + let t = (elapsed / self.duration_sec).clamp(0.0, 1.0); + if t >= 1.0 { + self.active = false; + return self.target_ime_bottom_pt; + } + let inv = 1.0 - t; + let eased = 1.0 - inv * inv * inv; + let value = f64::from(self.start_ime_bottom_pt) + + (f64::from(self.target_ime_bottom_pt) - f64::from(self.start_ime_bottom_pt)) * eased; + sanitize_non_neg(value as f32) + } +} + +/// Compute keyboard avoidance metrics from a keyboard frame in window coordinates, +/// isomorphic with `ui::WindowInsets::effective()` (`safe_area.bottom.max(ime.bottom)`). +/// +/// - Floating or split iPad keyboards (narrower than the window or detached from the bottom edge) +/// produce `ime_bottom_pt = 0.0`, `ime_above_safe_bottom_pt = 0.0`, and `is_floating_or_split = true`. +/// - External hardware keyboards or hidden keyboards produce `ime_bottom_pt = 0.0`, +/// `ime_above_safe_bottom_pt = 0.0`, and `is_hardware_or_hidden = true`. +/// - Docked software keyboards report `ime_bottom_pt = overlap_h` (from window bottom edge), +/// `ime_above_safe_bottom_pt = (overlap_h - safe_bottom).max(0.0)`, and +/// `effective_bottom_pt = safe_bottom.max(ime_bottom_pt)` with zero double deduction. +pub fn compute_keyboard_avoidance( + window_bounds: AffineRect, + keyboard_frame_in_window: AffineRect, + safe_bottom: f32, + is_hidden: bool, +) -> AffineKeyboardAvoidanceMetrics { + let wb = window_bounds.sanitized(); + let kb = keyboard_frame_in_window.sanitized(); + let safe_b = sanitize_non_neg(safe_bottom); + + if is_hidden || wb.width <= 0.0 || wb.height <= 0.0 || kb.width <= 0.0 || kb.height <= 0.0 { + return AffineKeyboardAvoidanceMetrics { + raw_overlap_pt: 0.0, + ime_bottom_pt: 0.0, + ime_above_safe_bottom_pt: 0.0, + effective_bottom_pt: safe_b, + is_floating_or_split: false, + is_hardware_or_hidden: true, + }; + } + + let inter_top = wb.y.max(kb.y); + let inter_bottom = wb.bottom().min(kb.bottom()); + let inter_left = wb.x.max(kb.x); + let inter_right = wb.right().min(kb.right()); + let overlap_h = (inter_bottom - inter_top).max(0.0); + let overlap_w = (inter_right - inter_left).max(0.0); + + if overlap_h <= 0.5 || overlap_w <= 0.5 { + return AffineKeyboardAvoidanceMetrics { + raw_overlap_pt: 0.0, + ime_bottom_pt: 0.0, + ime_above_safe_bottom_pt: 0.0, + effective_bottom_pt: safe_b, + is_floating_or_split: false, + is_hardware_or_hidden: true, + }; + } + + // Floating or split/slide-over keyboards either overlap less than the full window width + // or hover above the bottom edge of the window. + let edge_tolerance = 1.5; + let touches_bottom = kb.bottom() >= wb.bottom() - edge_tolerance; + let spans_full_width = overlap_w >= wb.width - edge_tolerance; + if !touches_bottom || !spans_full_width { + return AffineKeyboardAvoidanceMetrics { + raw_overlap_pt: 0.0, + ime_bottom_pt: 0.0, + ime_above_safe_bottom_pt: 0.0, + effective_bottom_pt: safe_b, + is_floating_or_split: true, + is_hardware_or_hidden: false, + }; + } + + let ime_above_safe_bottom_pt = (overlap_h - safe_b).max(0.0); + AffineKeyboardAvoidanceMetrics { + raw_overlap_pt: overlap_h, + ime_bottom_pt: overlap_h, + ime_above_safe_bottom_pt, + effective_bottom_pt: safe_b.max(overlap_h), + is_floating_or_split: false, + is_hardware_or_hidden: false, + } +} + +/// Build an `AffineWindowInsets` snapshot from safe areas and non-double-counted `ime_bottom_pt`. +pub fn build_window_insets( + safe_top: f32, + safe_right: f32, + safe_bottom: f32, + safe_left: f32, + ime_bottom_pt: f32, +) -> AffineWindowInsets { + AffineWindowInsets { + safe_top: sanitize_non_neg(safe_top), + safe_right: sanitize_non_neg(safe_right), + safe_bottom: sanitize_non_neg(safe_bottom), + safe_left: sanitize_non_neg(safe_left), + ime_bottom: sanitize_non_neg(ime_bottom_pt), + } +} + +fn sanitize_non_neg(v: f32) -> f32 { + if v.is_finite() { v.max(0.0) } else { 0.0 } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn keyboard_avoidance_table_covers_docked_safe_area_floating_split_and_hardware() { + struct Case { + name: &'static str, + window: AffineRect, + keyboard: AffineRect, + safe_bottom: f32, + is_hidden: bool, + expect_ime_bottom: f32, + expect_ime_above_safe: f32, + expect_effective: f32, + expect_floating: bool, + expect_hidden_or_hw: bool, + } + + let iphone_window = AffineRect { + x: 0.0, + y: 0.0, + width: 390.0, + height: 844.0, + }; + let ipad_window = AffineRect { + x: 0.0, + y: 0.0, + width: 1024.0, + height: 768.0, + }; + + let cases = [ + Case { + name: "iphone_docked_matches_ui_window_insets_and_exposes_above_safe", + window: iphone_window, + keyboard: AffineRect { + x: 0.0, + y: 542.0, + width: 390.0, + height: 302.0, + }, + safe_bottom: 34.0, + is_hidden: false, + expect_ime_bottom: 302.0, + expect_ime_above_safe: 268.0, + expect_effective: 302.0, + expect_floating: false, + expect_hidden_or_hw: false, + }, + Case { + name: "overlap_smaller_than_safe_bottom_keeps_effective_at_safe_bottom", + window: iphone_window, + keyboard: AffineRect { + x: 0.0, + y: 820.0, + width: 390.0, + height: 24.0, + }, + safe_bottom: 34.0, + is_hidden: false, + expect_ime_bottom: 24.0, + expect_ime_above_safe: 0.0, + expect_effective: 34.0, + expect_floating: false, + expect_hidden_or_hw: false, + }, + Case { + name: "hardware_keyboard_offscreen_frame_yields_zero_ime", + window: iphone_window, + keyboard: AffineRect { + x: 0.0, + y: 844.0, + width: 390.0, + height: 302.0, + }, + safe_bottom: 34.0, + is_hidden: false, + expect_ime_bottom: 0.0, + expect_ime_above_safe: 0.0, + expect_effective: 34.0, + expect_floating: false, + expect_hidden_or_hw: true, + }, + Case { + name: "explicit_hide_notification_yields_zero_ime", + window: iphone_window, + keyboard: AffineRect { + x: 0.0, + y: 542.0, + width: 390.0, + height: 302.0, + }, + safe_bottom: 34.0, + is_hidden: true, + expect_ime_bottom: 0.0, + expect_ime_above_safe: 0.0, + expect_effective: 34.0, + expect_floating: false, + expect_hidden_or_hw: true, + }, + Case { + name: "ipad_floating_keyboard_narrower_than_window_yields_zero_ime", + window: ipad_window, + keyboard: AffineRect { + x: 640.0, + y: 420.0, + width: 320.0, + height: 280.0, + }, + safe_bottom: 20.0, + is_hidden: false, + expect_ime_bottom: 0.0, + expect_ime_above_safe: 0.0, + expect_effective: 20.0, + expect_floating: true, + expect_hidden_or_hw: false, + }, + Case { + name: "ipad_split_undocked_keyboard_above_bottom_yields_zero_ime", + window: ipad_window, + keyboard: AffineRect { + x: 0.0, + y: 380.0, + width: 1024.0, + height: 260.0, + }, + safe_bottom: 20.0, + is_hidden: false, + expect_ime_bottom: 0.0, + expect_ime_above_safe: 0.0, + expect_effective: 20.0, + expect_floating: true, + expect_hidden_or_hw: false, + }, + Case { + name: "slide_over_full_width_keyboard_partial_horizontal_overlap_yields_zero_ime", + window: iphone_window, + keyboard: AffineRect { + x: 380.0, + y: 544.0, + width: 390.0, + height: 300.0, + }, + safe_bottom: 34.0, + is_hidden: false, + expect_ime_bottom: 0.0, + expect_ime_above_safe: 0.0, + expect_effective: 34.0, + expect_floating: true, + expect_hidden_or_hw: false, + }, + ]; + + for c in cases { + let m = compute_keyboard_avoidance(c.window, c.keyboard, c.safe_bottom, c.is_hidden); + assert_eq!(m.ime_bottom_pt, c.expect_ime_bottom, "{}", c.name); + assert_eq!( + m.ime_above_safe_bottom_pt, c.expect_ime_above_safe, + "{}", + c.name + ); + assert_eq!(m.effective_bottom_pt, c.expect_effective, "{}", c.name); + assert_eq!( + m.effective_bottom_pt, + c.safe_bottom + m.ime_above_safe_bottom_pt, + "{}", + c.name + ); + assert_eq!(m.is_floating_or_split, c.expect_floating, "{}", c.name); + assert_eq!(m.is_hardware_or_hidden, c.expect_hidden_or_hw, "{}", c.name); + } + } + + #[test] + fn per_frame_keyboard_transition_interpolates_monotonically_to_target() { + let mut tr = KeyboardFrameTransition::begin(0.0, 302.0, 10.0, 0.25); + assert!(tr.active); + let f0 = tr.sample(10.0); + let f1 = tr.sample(10.05); + let f2 = tr.sample(10.125); + let f3 = tr.sample(10.25); + assert_eq!(f0, 0.0); + assert!(f1 > f0 && f1 < f2); + assert!(f2 > 151.0 && f2 < 302.0); + assert_eq!(f3, 302.0); + assert!(!tr.active); + } +} diff --git a/packages/frontend/hosts/ios/src/lib.rs b/packages/frontend/hosts/ios/src/lib.rs index dd828725b8..677cbdd9ee 100644 --- a/packages/frontend/hosts/ios/src/lib.rs +++ b/packages/frontend/hosts/ios/src/lib.rs @@ -10,7 +10,14 @@ pub mod auth; pub mod ffi; +pub mod ffi_s3; +pub mod ffi_text; +pub mod haptics; +pub mod keyboard_insets; pub mod legacy_storage; +pub mod pdf; +pub mod selection; +pub mod text_layout; pub mod workspace_store; /// C-ABI window insets matching `AffineWindowInsets` in `include/affine_mobile_host.h`. @@ -47,6 +54,9 @@ pub struct IosHostState { utf16_text: Vec, selected_range: AffineUtf16Range, marked_range: Option, + selection_overlay: selection::SelectionOverlayController, + keyboard_transition: keyboard_insets::KeyboardFrameTransition, + haptics: haptics::HapticsState, } impl IosHostState { @@ -91,7 +101,122 @@ impl IosHostState { self.insets } - pub const DEFAULT_CLEAR_COLOR_RGBA: u32 = 0x1414_14FF; + /// Additional keyboard height above `safe_bottom` (`(ime_bottom - safe_bottom).max(0.0)`), + /// for containers that already apply `safe_bottom` separately. + pub fn ime_above_safe_bottom(&self) -> f32 { + (self.insets.ime_bottom - self.insets.safe_bottom).max(0.0) + } + + pub fn viewport_size_pt(&self) -> (f32, f32) { + (self.width_pt, self.height_pt) + } + + pub fn selection_overlay(&self) -> &selection::SelectionOverlayController { + &self.selection_overlay + } + + pub fn selection_overlay_mut(&mut self) -> &mut selection::SelectionOverlayController { + self.dirty = true; + &mut self.selection_overlay + } + + pub fn selection_overlay_state(&self) -> selection::AffineSelectionOverlayState { + self.selection_overlay + .layout(self.width_pt, self.height_pt, self.insets) + } + + pub fn text_writing_direction(&self) -> selection::AffineWritingDirection { + text_layout::detect_paragraph_writing_direction( + &self.utf16_text, + self.selected_range().location as usize, + ) + } + + pub fn text_caret_rect(&self, utf16_offset: u32) -> selection::AffineRect { + text_layout::caret_rect_for_offset( + &self.utf16_text, + utf16_offset, + self.width_pt, + self.insets, + ) + } + + pub fn text_closest_offset(&self, point: selection::AffinePoint) -> u32 { + text_layout::closest_offset_for_point(&self.utf16_text, point, self.width_pt, self.insets) + } + + pub fn render_loupe_rgba8( + &self, + focus_x: f32, + focus_y: f32, + diameter_px: u32, + zoom_scale: f32, + ) -> Vec { + text_layout::render_loupe_rgba8( + &self.utf16_text, + self.selected_range(), + self.width_pt, + self.insets, + focus_x, + focus_y, + diameter_px, + zoom_scale, + ) + } + + pub fn begin_keyboard_transition( + &mut self, + target_ime_bottom_pt: f32, + start_timestamp_sec: f64, + duration_sec: f64, + ) { + self.keyboard_transition = keyboard_insets::KeyboardFrameTransition::begin( + self.insets.ime_bottom, + target_ime_bottom_pt, + start_timestamp_sec, + duration_sec, + ); + if !self.keyboard_transition.active { + let mut next = self.insets; + next.ime_bottom = self.keyboard_transition.target_ime_bottom_pt; + self.set_insets(next); + } + } + + pub fn sample_keyboard_frame( + &mut self, + safe_top: f32, + safe_right: f32, + safe_bottom: f32, + safe_left: f32, + frame_timestamp_sec: f64, + ) -> AffineWindowInsets { + let sampled_ime = if self.keyboard_transition.active { + self.keyboard_transition.sample(frame_timestamp_sec) + } else { + self.insets.ime_bottom + }; + let next = keyboard_insets::build_window_insets( + safe_top, + safe_right, + safe_bottom, + safe_left, + sampled_ime, + ); + self.set_insets(next); + self.insets + } + + pub fn haptics(&self) -> &haptics::HapticsState { + &self.haptics + } + + pub fn record_haptic(&mut self, pattern: haptics::AffineHapticPattern) { + self.haptics.record(pattern); + } + + /// AFFiNE light canvas clear color (`#FAFAFC`, contrast > 16:1 against `#1A1A1A` text). + pub const DEFAULT_CLEAR_COLOR_RGBA: u32 = 0xFAFA_FCFF; /// Mark the host surface dirty so the next `render_frame` tick draws. pub fn request_frame(&mut self) { @@ -146,6 +271,7 @@ impl IosHostState { length: 0, }; self.marked_range = None; + self.selection_overlay.clear(); self.dirty = true; } @@ -162,6 +288,7 @@ impl IosHostState { length: 0, }; self.shrink_marked_range(start, end); + self.selection_overlay.clear(); self.dirty = true; return; } @@ -183,6 +310,7 @@ impl IosHostState { length: 0, }; self.shrink_marked_range(start, end); + self.selection_overlay.clear(); self.dirty = true; } @@ -202,12 +330,19 @@ impl IosHostState { length: 0, }; self.shrink_marked_range(start, end); + self.selection_overlay.clear(); self.dirty = true; } /// Updates the active UTF-16 selection range (clamped to current buffer bounds). pub fn set_selected_range(&mut self, range: AffineUtf16Range) { let next = self.clamp_range(range); + if next.length == 0 + && self.selection_overlay.active_drag_handle() + == selection::AffineSelectionHandleKind::None + { + self.selection_overlay.clear(); + } if next != self.selected_range { self.selected_range = next; self.dirty = true; @@ -227,6 +362,7 @@ impl IosHostState { length: 0, }; self.marked_range = None; + self.selection_overlay.clear(); self.dirty = true; } diff --git a/packages/frontend/hosts/ios/src/pdf.rs b/packages/frontend/hosts/ios/src/pdf.rs new file mode 100644 index 0000000000..a6e6865b0f --- /dev/null +++ b/packages/frontend/hosts/ios/src/pdf.rs @@ -0,0 +1,221 @@ +//! Pure-Rust PDFKit bridge validation, render-budget planning, and C-ABI data types. +//! +//! Enforces strict document size, header, page-index, and pixel-budget limits before +//! delegating page rasterization to Apple's system `PDFKit` framework in Swift. + +/// Maximum accepted PDF payload size in bytes (128 MiB). +pub const MAX_PDF_DOCUMENT_BYTES: usize = 128 * 1024 * 1024; +/// Maximum single rasterized page edge length in pixels (4096 px). +pub const MAX_PDF_PAGE_DIMENSION_PX: u32 = 4096; +/// Maximum total pixels per rasterized page (4096 * 4096 = 16M pixels = 64 MiB RGBA8). +pub const MAX_PDF_PAGE_PIXELS: u64 = 16_777_216; +/// Number of leading bytes scanned for the `%PDF-` signature per ISO 32000-1. +const PDF_HEADER_SCAN_LIMIT: usize = 1024; + +/// C-ABI error codes shared between Rust validation and Swift `PdfRendererBridge`. +#[repr(u32)] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub enum AffinePdfErrorCode { + #[default] + Ok = 0, + InvalidArgument = 1, + EmptyDocument = 2, + DocumentTooLarge = 3, + InvalidOrEncryptedPdf = 4, + PageOutOfRange = 5, + InvalidDimensions = 6, + PixelLimitExceeded = 7, + RenderFailed = 8, +} + +/// Original page box size in PDF points (`72 pt = 1 inch`). +#[repr(C)] +#[derive(Debug, Clone, Copy, Default, PartialEq)] +pub struct AffinePdfPageSize { + pub width_pt: f32, + pub height_pt: f32, +} + +/// Validated RGBA8 rasterization plan returned to Swift `PdfRendererBridge`. +#[repr(C)] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct AffinePdfRenderPlan { + pub target_width_px: u32, + pub target_height_px: u32, + pub byte_len: usize, + pub error: u32, +} + +/// Validate a raw PDF payload before passing it to `PDFKit`. +pub fn validate_pdf_bytes(bytes: &[u8]) -> Result<(), AffinePdfErrorCode> { + if bytes.is_empty() { + return Err(AffinePdfErrorCode::EmptyDocument); + } + if bytes.len() > MAX_PDF_DOCUMENT_BYTES { + return Err(AffinePdfErrorCode::DocumentTooLarge); + } + let scan_end = bytes.len().min(PDF_HEADER_SCAN_LIMIT); + let prefix = &bytes[..scan_end]; + if !prefix.windows(5).any(|w| w == b"%PDF-") { + return Err(AffinePdfErrorCode::InvalidOrEncryptedPdf); + } + Ok(()) +} + +/// Validate page bounds and pixel dimensions and compute the exact RGBA8 buffer length. +pub fn plan_pdf_page_render( + page_index: u32, + page_count: u32, + target_width_px: u32, + target_height_px: u32, +) -> AffinePdfRenderPlan { + if page_count == 0 || page_index >= page_count { + return AffinePdfRenderPlan { + target_width_px: 0, + target_height_px: 0, + byte_len: 0, + error: AffinePdfErrorCode::PageOutOfRange as u32, + }; + } + if target_width_px == 0 || target_height_px == 0 { + return AffinePdfRenderPlan { + target_width_px: 0, + target_height_px: 0, + byte_len: 0, + error: AffinePdfErrorCode::InvalidDimensions as u32, + }; + } + if target_width_px > MAX_PDF_PAGE_DIMENSION_PX || target_height_px > MAX_PDF_PAGE_DIMENSION_PX { + return AffinePdfRenderPlan { + target_width_px: 0, + target_height_px: 0, + byte_len: 0, + error: AffinePdfErrorCode::PixelLimitExceeded as u32, + }; + } + let pixels = u64::from(target_width_px) * u64::from(target_height_px); + if pixels > MAX_PDF_PAGE_PIXELS { + return AffinePdfRenderPlan { + target_width_px: 0, + target_height_px: 0, + byte_len: 0, + error: AffinePdfErrorCode::PixelLimitExceeded as u32, + }; + } + let Some(byte_len) = (pixels as usize).checked_mul(4) else { + return AffinePdfRenderPlan { + target_width_px: 0, + target_height_px: 0, + byte_len: 0, + error: AffinePdfErrorCode::PixelLimitExceeded as u32, + }; + }; + AffinePdfRenderPlan { + target_width_px, + target_height_px, + byte_len, + error: AffinePdfErrorCode::Ok as u32, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn pdf_header_validation_table() { + let cases: [(&str, &[u8], Result<(), AffinePdfErrorCode>); 4] = [ + ("empty", b"", Err(AffinePdfErrorCode::EmptyDocument)), + ( + "not_pdf", + b"not a pdf", + Err(AffinePdfErrorCode::InvalidOrEncryptedPdf), + ), + ("valid_pdf_1_4", b"%PDF-1.4\n%%EOF\n", Ok(())), + ( + "valid_pdf_with_leading_junk", + b" \n%PDF-1.7\n%%EOF\n", + Ok(()), + ), + ]; + for (name, bytes, expected) in cases { + assert_eq!(validate_pdf_bytes(bytes), expected, "{name}"); + } + } + + #[test] + fn pdf_render_plan_table_enforces_page_bounds_and_oom_limits() { + struct Case { + name: &'static str, + page: u32, + count: u32, + w: u32, + h: u32, + expect_err: AffinePdfErrorCode, + expect_bytes: usize, + } + + let cases = [ + Case { + name: "valid_page_0", + page: 0, + count: 2, + w: 300, + h: 400, + expect_err: AffinePdfErrorCode::Ok, + expect_bytes: 300 * 400 * 4, + }, + Case { + name: "valid_max_4096_square", + page: 1, + count: 2, + w: 4096, + h: 4096, + expect_err: AffinePdfErrorCode::Ok, + expect_bytes: 4096 * 4096 * 4, + }, + Case { + name: "out_of_range_page", + page: 2, + count: 2, + w: 200, + h: 200, + expect_err: AffinePdfErrorCode::PageOutOfRange, + expect_bytes: 0, + }, + Case { + name: "zero_page_count", + page: 0, + count: 0, + w: 200, + h: 200, + expect_err: AffinePdfErrorCode::PageOutOfRange, + expect_bytes: 0, + }, + Case { + name: "zero_dimension", + page: 0, + count: 1, + w: 0, + h: 200, + expect_err: AffinePdfErrorCode::InvalidDimensions, + expect_bytes: 0, + }, + Case { + name: "exceeds_edge_cap", + page: 0, + count: 1, + w: 4097, + h: 100, + expect_err: AffinePdfErrorCode::PixelLimitExceeded, + expect_bytes: 0, + }, + ]; + + for c in cases { + let plan = plan_pdf_page_render(c.page, c.count, c.w, c.h); + assert_eq!(plan.error, c.expect_err as u32, "{}", c.name); + assert_eq!(plan.byte_len, c.expect_bytes, "{}", c.name); + } + } +} diff --git a/packages/frontend/hosts/ios/src/selection.rs b/packages/frontend/hosts/ios/src/selection.rs new file mode 100644 index 0000000000..3aedb9c0c0 --- /dev/null +++ b/packages/frontend/hosts/ios/src/selection.rs @@ -0,0 +1,1279 @@ +use crate::{AffineUtf16Range, AffineWindowInsets}; + +/// C-ABI 2D point in logical points matching `AffinePoint` in `include/affine_mobile_host.h`. +#[repr(C)] +#[derive(Debug, Clone, Copy, Default, PartialEq)] +pub struct AffinePoint { + pub x: f32, + pub y: f32, +} + +/// C-ABI rectangle in logical points matching `AffineRect` in `include/affine_mobile_host.h`. +#[repr(C)] +#[derive(Debug, Clone, Copy, Default, PartialEq)] +pub struct AffineRect { + pub x: f32, + pub y: f32, + pub width: f32, + pub height: f32, +} + +impl AffineRect { + pub fn sanitized(self) -> Self { + Self { + x: sanitize_f32(self.x), + y: sanitize_f32(self.y), + width: sanitize_f32(self.width).max(0.0), + height: sanitize_f32(self.height).max(0.0), + } + } + + pub fn right(self) -> f32 { + self.x + self.width + } + + pub fn bottom(self) -> f32 { + self.y + self.height + } +} + +/// Which teardrop handle is active or hit-tested (`0 = none, 1 = start, 2 = end`). +#[repr(u8)] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub enum AffineSelectionHandleKind { + #[default] + None = 0, + Start = 1, + End = 2, +} + +impl AffineSelectionHandleKind { + pub fn from_u8(raw: u8) -> Self { + match raw { + 1 => Self::Start, + 2 => Self::End, + _ => Self::None, + } + } +} + +/// Writing direction for teardrop handle horizontal bias (`0 = LTR, 1 = RTL`). +#[repr(u8)] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub enum AffineWritingDirection { + #[default] + Ltr = 0, + Rtl = 1, +} + +impl AffineWritingDirection { + pub fn from_u8(raw: u8) -> Self { + match raw { + 1 => Self::Rtl, + _ => Self::Ltr, + } + } +} + +/// Computed layout for one teardrop selection handle. +#[repr(C)] +#[derive(Debug, Clone, Copy, Default, PartialEq)] +pub struct AffineTeardropHandleLayout { + pub visible: bool, + pub drop_above: bool, + pub stem_x: f32, + pub stem_top_y: f32, + pub stem_bottom_y: f32, + pub stem_width: f32, + pub drop_center_x: f32, + pub drop_center_y: f32, + pub drop_radius: f32, + pub drop_offset_x: f32, +} + +/// Computed layout for the circular magnifier loupe shown during handle drags. +#[repr(C)] +#[derive(Debug, Clone, Copy, Default, PartialEq)] +pub struct AffineLoupeLayout { + pub visible: bool, + pub center_x: f32, + pub center_y: f32, + pub focus_x: f32, + pub focus_y: f32, + pub diameter: f32, + pub zoom_scale: f32, +} + +/// Full deterministic selection overlay snapshot consumed by Swift `SelectionOverlayView`. +#[repr(C)] +#[derive(Debug, Clone, Copy, Default, PartialEq)] +pub struct AffineSelectionOverlayState { + pub has_selection: bool, + pub is_collapsed: bool, + pub is_rtl: bool, + pub active_drag_handle: u8, + pub show_floating_menu: bool, + pub range: AffineUtf16Range, + pub drag_probe_point: AffinePoint, + pub start_handle: AffineTeardropHandleLayout, + pub end_handle: AffineTeardropHandleLayout, + pub loupe: AffineLoupeLayout, + pub menu_anchor_rect: AffineRect, +} + +/// Deterministic selection handle geometry and drag state machine. +#[derive(Debug, Clone, Default)] +pub struct SelectionOverlayController { + has_selection: bool, + range: AffineUtf16Range, + writing_direction: AffineWritingDirection, + start_caret: AffineRect, + end_caret: AffineRect, + active_drag: AffineSelectionHandleKind, + drag_anchor_utf16: Option, + drag_touch_point: AffinePoint, + grab_offset: AffinePoint, +} + +impl SelectionOverlayController { + pub const STEM_WIDTH_PT: f32 = 2.0; + pub const DROP_RADIUS_PT: f32 = 6.0; + pub const DROP_BIAS_PT: f32 = 3.0; + pub const LOUPE_DIAMETER_PT: f32 = 88.0; + pub const LOUPE_ZOOM_SCALE: f32 = 1.5; + pub const LOUPE_VERTICAL_OFFSET_PT: f32 = 68.0; + pub const MIN_TOUCH_HIT_RADIUS_PT: f32 = 22.0; + pub const VIEWPORT_MARGIN_PT: f32 = 4.0; + + pub fn set_selection( + &mut self, + start_caret: AffineRect, + end_caret: AffineRect, + range: AffineUtf16Range, + writing_direction: AffineWritingDirection, + ) { + self.has_selection = true; + self.range = range; + self.writing_direction = writing_direction; + self.start_caret = start_caret.sanitized(); + self.end_caret = end_caret.sanitized(); + if range.length == 0 { + self.active_drag = AffineSelectionHandleKind::None; + } + } + + pub fn clear(&mut self) { + self.has_selection = false; + self.range = AffineUtf16Range::default(); + self.start_caret = AffineRect::default(); + self.end_caret = AffineRect::default(); + self.active_drag = AffineSelectionHandleKind::None; + self.drag_anchor_utf16 = None; + self.drag_touch_point = AffinePoint::default(); + self.grab_offset = AffinePoint::default(); + } + + pub fn active_drag_handle(&self) -> AffineSelectionHandleKind { + self.active_drag + } + + pub fn drag_anchor_utf16(&self) -> Option { + self.drag_anchor_utf16 + } + + pub fn hit_test_handle( + &self, + point: AffinePoint, + hit_radius_pt: f32, + viewport_w: f32, + viewport_h: f32, + insets: AffineWindowInsets, + ) -> AffineSelectionHandleKind { + let state = self.layout(viewport_w, viewport_h, insets); + if !state.has_selection || state.is_collapsed { + return AffineSelectionHandleKind::None; + } + let radius = sanitize_f32(hit_radius_pt).max(Self::MIN_TOUCH_HIT_RADIUS_PT); + let px = sanitize_f32(point.x); + let py = sanitize_f32(point.y); + let d_start = distance_to_handle(px, py, state.start_handle); + let d_end = distance_to_handle(px, py, state.end_handle); + + match (d_start <= radius, d_end <= radius) { + (true, true) => { + if d_start <= d_end { + AffineSelectionHandleKind::Start + } else { + AffineSelectionHandleKind::End + } + } + (true, false) => AffineSelectionHandleKind::Start, + (false, true) => AffineSelectionHandleKind::End, + (false, false) => AffineSelectionHandleKind::None, + } + } + + pub fn begin_drag( + &mut self, + handle: AffineSelectionHandleKind, + touch_point: AffinePoint, + ) -> bool { + if !self.has_selection || self.range.length == 0 { + return false; + } + let active_caret = match handle { + AffineSelectionHandleKind::Start => self.start_caret, + AffineSelectionHandleKind::End => self.end_caret, + AffineSelectionHandleKind::None => return false, + }; + let tx = sanitize_f32(touch_point.x); + let ty = sanitize_f32(touch_point.y); + let caret_ref_x = active_caret.x + active_caret.width * 0.5; + let caret_ref_y = active_caret.y + active_caret.height * 0.5; + self.active_drag = handle; + self.drag_anchor_utf16 = Some(match handle { + AffineSelectionHandleKind::Start => { + self.range.location.saturating_add(self.range.length) + } + AffineSelectionHandleKind::End => self.range.location, + AffineSelectionHandleKind::None => return false, + }); + self.drag_touch_point = AffinePoint { x: tx, y: ty }; + self.grab_offset = AffinePoint { + x: caret_ref_x - tx, + y: caret_ref_y - ty, + }; + true + } + + /// Compute the caret-aligned probe point (`touch + grab_offset`) for an active drag, + /// ensuring a 0pt move on the teardrop center causes zero vertical or horizontal line jump. + pub fn drag_probe_point_for(&self, touch_point: AffinePoint) -> AffinePoint { + let tx = sanitize_f32(touch_point.x); + let ty = sanitize_f32(touch_point.y); + if self.active_drag == AffineSelectionHandleKind::None { + return AffinePoint { x: tx, y: ty }; + } + AffinePoint { + x: sanitize_f32(tx + self.grab_offset.x), + y: sanitize_f32(ty + self.grab_offset.y), + } + } + + pub fn update_drag( + &mut self, + touch_point: AffinePoint, + updated_caret: AffineRect, + updated_range: AffineUtf16Range, + ) -> bool { + if self.active_drag == AffineSelectionHandleKind::None { + return false; + } + self.drag_touch_point = AffinePoint { + x: sanitize_f32(touch_point.x), + y: sanitize_f32(touch_point.y), + }; + let sanitized = updated_caret.sanitized(); + match self.active_drag { + AffineSelectionHandleKind::Start => { + self.start_caret = sanitized; + if is_caret_after(self.start_caret, self.end_caret, self.writing_direction) { + core::mem::swap(&mut self.start_caret, &mut self.end_caret); + self.active_drag = AffineSelectionHandleKind::End; + } + } + AffineSelectionHandleKind::End => { + self.end_caret = sanitized; + if is_caret_after(self.start_caret, self.end_caret, self.writing_direction) { + core::mem::swap(&mut self.start_caret, &mut self.end_caret); + self.active_drag = AffineSelectionHandleKind::Start; + } + } + AffineSelectionHandleKind::None => return false, + } + self.range = updated_range; + true + } + + /// Update an in-progress drag from authoritative UTF-16 anchor/target offsets and + /// caller-supplied shaped start/end caret rects, without guessing crossover from + /// 2D caret coordinates (safe for mixed BiDi runs and vertical finger drift). + pub fn apply_text_drag_endpoints( + &mut self, + touch_point: AffinePoint, + target_offset: u32, + start_caret: AffineRect, + end_caret: AffineRect, + ) -> bool { + if self.active_drag == AffineSelectionHandleKind::None { + return false; + } + let anchor = self + .drag_anchor_utf16 + .unwrap_or_else(|| match self.active_drag { + AffineSelectionHandleKind::Start => { + self.range.location.saturating_add(self.range.length) + } + AffineSelectionHandleKind::End => self.range.location, + AffineSelectionHandleKind::None => 0, + }); + self.drag_touch_point = AffinePoint { + x: sanitize_f32(touch_point.x), + y: sanitize_f32(touch_point.y), + }; + let new_start = anchor.min(target_offset); + let new_end = anchor.max(target_offset); + self.range = AffineUtf16Range { + location: new_start, + length: new_end.saturating_sub(new_start), + }; + self.start_caret = start_caret.sanitized(); + self.end_caret = end_caret.sanitized(); + if target_offset < anchor { + self.active_drag = AffineSelectionHandleKind::Start; + } else if target_offset > anchor { + self.active_drag = AffineSelectionHandleKind::End; + } + true + } + + pub fn end_drag(&mut self) -> bool { + if self.active_drag == AffineSelectionHandleKind::None { + return false; + } + self.active_drag = AffineSelectionHandleKind::None; + self.drag_anchor_utf16 = None; + self.grab_offset = AffinePoint::default(); + if self.range.length == 0 { + self.clear(); + } + true + } + + pub fn layout( + &self, + viewport_w: f32, + viewport_h: f32, + insets: AffineWindowInsets, + ) -> AffineSelectionOverlayState { + let vw = sanitize_f32(viewport_w).max(0.0); + let vh = sanitize_f32(viewport_h).max(0.0); + let safe_left = sanitize_f32(insets.safe_left).max(0.0).min(vw); + let safe_right = sanitize_f32(insets.safe_right).max(0.0).min(vw); + let safe_top = sanitize_f32(insets.safe_top).max(0.0).min(vh); + let bottom_inset = sanitize_f32(insets.safe_bottom) + .max(0.0) + .max(sanitize_f32(insets.ime_bottom).max(0.0)) + .min(vh); + + let min_x = safe_left; + let max_x = (vw - safe_right).max(min_x); + let min_y = safe_top; + let max_y = (vh - bottom_inset).max(min_y); + + let is_collapsed = !self.has_selection || self.range.length == 0; + let is_rtl = self.writing_direction == AffineWritingDirection::Rtl; + let drag_probe_point = if self.active_drag != AffineSelectionHandleKind::None { + self.drag_probe_point_for(self.drag_touch_point) + } else { + AffinePoint::default() + }; + let loupe = if self.active_drag != AffineSelectionHandleKind::None { + build_loupe(drag_probe_point, min_x, max_x, min_y, max_y) + } else { + AffineLoupeLayout::default() + }; + + if !self.has_selection || is_collapsed { + let start_handle = if self.has_selection + && self.active_drag == AffineSelectionHandleKind::Start + { + build_teardrop_handle(self.start_caret, true, is_rtl, min_x, max_x, min_y, max_y) + } else { + AffineTeardropHandleLayout::default() + }; + let end_handle = + if self.has_selection && self.active_drag == AffineSelectionHandleKind::End { + build_teardrop_handle(self.end_caret, false, is_rtl, min_x, max_x, min_y, max_y) + } else { + AffineTeardropHandleLayout::default() + }; + return AffineSelectionOverlayState { + has_selection: self.has_selection, + is_collapsed: true, + is_rtl, + active_drag_handle: self.active_drag as u8, + show_floating_menu: false, + range: self.range, + drag_probe_point, + start_handle, + end_handle, + loupe, + menu_anchor_rect: AffineRect::default(), + }; + } + + let start_handle = + build_teardrop_handle(self.start_caret, true, is_rtl, min_x, max_x, min_y, max_y); + let end_handle = + build_teardrop_handle(self.end_caret, false, is_rtl, min_x, max_x, min_y, max_y); + + let sel_top = self.start_caret.y.min(self.end_caret.y); + let sel_bottom = self + .start_caret + .bottom() + .max(self.end_caret.bottom()) + .max(sel_top + 1.0); + let selection_visible = sel_bottom > min_y && sel_top < max_y; + let show_floating_menu = self.active_drag == AffineSelectionHandleKind::None + && (start_handle.visible || end_handle.visible || selection_visible); + let menu_anchor_rect = if show_floating_menu { + build_menu_anchor_rect(self.start_caret, self.end_caret, min_x, max_x, min_y, max_y) + } else { + AffineRect::default() + }; + + AffineSelectionOverlayState { + has_selection: true, + is_collapsed: false, + is_rtl, + active_drag_handle: self.active_drag as u8, + show_floating_menu, + range: self.range, + drag_probe_point, + start_handle, + end_handle, + loupe, + menu_anchor_rect, + } + } +} + +fn build_teardrop_handle( + caret: AffineRect, + is_start: bool, + is_rtl: bool, + min_x: f32, + max_x: f32, + min_y: f32, + max_y: f32, +) -> AffineTeardropHandleLayout { + let caret_bottom = caret.bottom().max(caret.y + 1.0); + let in_x = caret.x >= min_x && caret.x <= max_x; + let in_y = caret_bottom >= min_y && caret.y <= max_y; + if !in_x || !in_y { + return AffineTeardropHandleLayout::default(); + } + + let r = SelectionOverlayController::DROP_RADIUS_PT; + let bias = SelectionOverlayController::DROP_BIAS_PT; + let stem_x = clamp_safe(caret.x, min_x, max_x); + let stem_top_y = clamp_safe(caret.y, min_y, max_y); + let stem_bottom_y = clamp_safe(caret_bottom, stem_top_y, max_y); + + // Start handle: teardrop above stem, biased left in LTR and right in RTL. + // End handle: teardrop below stem, biased right in LTR and left in RTL. + let drop_offset_x = match (is_start, is_rtl) { + (true, false) | (false, true) => -bias, + (true, true) | (false, false) => bias, + }; + + let drop_x_min = min_x + r; + let drop_x_max = max_x - r; + let drop_center_x = if drop_x_min <= drop_x_max { + clamp_safe(stem_x + drop_offset_x, drop_x_min, drop_x_max) + } else { + (min_x + max_x) * 0.5 + }; + + let raw_drop_y = if is_start { + stem_top_y - r + } else { + stem_bottom_y + r + }; + let drop_y_min = min_y + r; + let drop_y_max = max_y - r; + let drop_center_y = if drop_y_min <= drop_y_max { + clamp_safe(raw_drop_y, drop_y_min, drop_y_max) + } else { + (min_y + max_y) * 0.5 + }; + + AffineTeardropHandleLayout { + visible: true, + drop_above: is_start, + stem_x, + stem_top_y, + stem_bottom_y, + stem_width: SelectionOverlayController::STEM_WIDTH_PT, + drop_center_x, + drop_center_y, + drop_radius: r, + drop_offset_x, + } +} + +fn build_loupe( + touch: AffinePoint, + min_x: f32, + max_x: f32, + min_y: f32, + max_y: f32, +) -> AffineLoupeLayout { + let diameter = SelectionOverlayController::LOUPE_DIAMETER_PT; + let radius = diameter * 0.5; + let margin = SelectionOverlayController::VIEWPORT_MARGIN_PT; + let focus_x = clamp_safe(touch.x, min_x, max_x); + let focus_y = clamp_safe(touch.y, min_y, max_y); + + let cx_min = min_x + radius + margin; + let cx_max = max_x - radius - margin; + let center_x = if cx_min <= cx_max { + clamp_safe(focus_x, cx_min, cx_max) + } else { + (min_x + max_x) * 0.5 + }; + + let cy_min = min_y + radius + margin; + let cy_max = max_y - radius - margin; + let preferred_y = focus_y - SelectionOverlayController::LOUPE_VERTICAL_OFFSET_PT; + let center_y = if cy_min <= cy_max { + clamp_safe(preferred_y, cy_min, cy_max) + } else { + (min_y + max_y) * 0.5 + }; + + AffineLoupeLayout { + visible: true, + center_x, + center_y, + focus_x, + focus_y, + diameter, + zoom_scale: SelectionOverlayController::LOUPE_ZOOM_SCALE, + } +} + +fn build_menu_anchor_rect( + start_caret: AffineRect, + end_caret: AffineRect, + min_x: f32, + max_x: f32, + min_y: f32, + max_y: f32, +) -> AffineRect { + let left = clamp_safe(start_caret.x.min(end_caret.x), min_x, max_x); + let right = clamp_safe(start_caret.right().max(end_caret.right()), left, max_x); + let top = clamp_safe(start_caret.y.min(end_caret.y), min_y, max_y); + let bottom = clamp_safe(start_caret.bottom().max(end_caret.bottom()), top, max_y); + AffineRect { + x: left, + y: top, + width: (right - left).max(1.0), + height: (bottom - top).max(1.0), + } +} + +fn distance_to_handle(px: f32, py: f32, handle: AffineTeardropHandleLayout) -> f32 { + if !handle.visible { + return f32::INFINITY; + } + let d_drop = hypot(px - handle.drop_center_x, py - handle.drop_center_y); + let clamped_y = clamp_safe(py, handle.stem_top_y, handle.stem_bottom_y); + let d_stem = hypot(px - handle.stem_x, py - clamped_y); + d_drop.min(d_stem) +} + +fn is_caret_after(a: AffineRect, b: AffineRect, direction: AffineWritingDirection) -> bool { + let line_tolerance = a.height.max(b.height).max(1.0) * 0.5; + if (a.y - b.y).abs() > line_tolerance { + return a.y > b.y; + } + match direction { + AffineWritingDirection::Ltr => a.x > b.x, + AffineWritingDirection::Rtl => a.x < b.x, + } +} + +fn hypot(dx: f32, dy: f32) -> f32 { + (dx * dx + dy * dy).sqrt() +} + +fn clamp_safe(value: f32, min: f32, max: f32) -> f32 { + let v = sanitize_f32(value); + if min <= max { v.clamp(min, max) } else { min } +} + +fn sanitize_f32(v: f32) -> f32 { + if v.is_finite() { v } else { 0.0 } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn standard_insets() -> AffineWindowInsets { + AffineWindowInsets { + safe_top: 59.0, + safe_right: 0.0, + safe_bottom: 34.0, + safe_left: 0.0, + ime_bottom: 0.0, + } + } + + #[test] + fn teardrop_geometry_table_covers_ltr_rtl_collapsed_multiline_and_narrow_clamp() { + struct Case { + name: &'static str, + start: AffineRect, + end: AffineRect, + range: AffineUtf16Range, + dir: AffineWritingDirection, + vw: f32, + vh: f32, + expect_visible: bool, + expect_start_offset_sign: f32, + expect_end_offset_sign: f32, + } + + let cases = [ + Case { + name: "ltr_single_line", + start: AffineRect { + x: 80.0, + y: 200.0, + width: 2.0, + height: 20.0, + }, + end: AffineRect { + x: 240.0, + y: 200.0, + width: 2.0, + height: 20.0, + }, + range: AffineUtf16Range { + location: 0, + length: 10, + }, + dir: AffineWritingDirection::Ltr, + vw: 390.0, + vh: 844.0, + expect_visible: true, + expect_start_offset_sign: -1.0, + expect_end_offset_sign: 1.0, + }, + Case { + name: "rtl_flips_teardrop_bias", + start: AffineRect { + x: 280.0, + y: 200.0, + width: 2.0, + height: 20.0, + }, + end: AffineRect { + x: 110.0, + y: 200.0, + width: 2.0, + height: 20.0, + }, + range: AffineUtf16Range { + location: 2, + length: 8, + }, + dir: AffineWritingDirection::Rtl, + vw: 390.0, + vh: 844.0, + expect_visible: true, + expect_start_offset_sign: 1.0, + expect_end_offset_sign: -1.0, + }, + Case { + name: "collapsed_caret_hides_handles", + start: AffineRect { + x: 120.0, + y: 200.0, + width: 2.0, + height: 20.0, + }, + end: AffineRect { + x: 120.0, + y: 200.0, + width: 2.0, + height: 20.0, + }, + range: AffineUtf16Range { + location: 4, + length: 0, + }, + dir: AffineWritingDirection::Ltr, + vw: 390.0, + vh: 844.0, + expect_visible: false, + expect_start_offset_sign: 0.0, + expect_end_offset_sign: 0.0, + }, + Case { + name: "multiline_and_narrow_viewport_clamps_handles_inside_bounds", + start: AffineRect { + x: 1.0, + y: 60.0, + width: 2.0, + height: 22.0, + }, + end: AffineRect { + x: 319.0, + y: 420.0, + width: 2.0, + height: 22.0, + }, + range: AffineUtf16Range { + location: 0, + length: 64, + }, + dir: AffineWritingDirection::Ltr, + vw: 320.0, + vh: 568.0, + expect_visible: true, + expect_start_offset_sign: -1.0, + expect_end_offset_sign: 1.0, + }, + ]; + + for c in cases { + let mut ctrl = SelectionOverlayController::default(); + ctrl.set_selection(c.start, c.end, c.range, c.dir); + let layout = ctrl.layout(c.vw, c.vh, standard_insets()); + assert_eq!(layout.start_handle.visible, c.expect_visible, "{}", c.name); + assert_eq!(layout.end_handle.visible, c.expect_visible, "{}", c.name); + assert_eq!(layout.show_floating_menu, c.expect_visible, "{}", c.name); + if c.expect_visible { + assert!(layout.start_handle.drop_above, "{}", c.name); + assert!(!layout.end_handle.drop_above, "{}", c.name); + assert_eq!( + layout.start_handle.drop_offset_x.signum(), + c.expect_start_offset_sign, + "{}", + c.name + ); + assert_eq!( + layout.end_handle.drop_offset_x.signum(), + c.expect_end_offset_sign, + "{}", + c.name + ); + assert!( + layout.start_handle.drop_center_x >= SelectionOverlayController::DROP_RADIUS_PT, + "{}", + c.name + ); + assert!( + layout.end_handle.drop_center_x + <= c.vw - SelectionOverlayController::DROP_RADIUS_PT, + "{}", + c.name + ); + assert!( + layout.start_handle.drop_center_y + >= 59.0 + SelectionOverlayController::DROP_RADIUS_PT, + "{}", + c.name + ); + assert!(layout.menu_anchor_rect.width >= 1.0, "{}", c.name); + assert!(layout.menu_anchor_rect.height >= 20.0, "{}", c.name); + } + } + } + + #[test] + fn drag_lifecycle_activates_clamped_loupe_swaps_crossed_handles_and_restores_menu() { + let mut ctrl = SelectionOverlayController::default(); + let insets = standard_insets(); + ctrl.set_selection( + AffineRect { + x: 80.0, + y: 120.0, + width: 2.0, + height: 20.0, + }, + AffineRect { + x: 200.0, + y: 120.0, + width: 2.0, + height: 20.0, + }, + AffineUtf16Range { + location: 0, + length: 12, + }, + AffineWritingDirection::Ltr, + ); + + let hit = ctrl.hit_test_handle( + AffinePoint { x: 77.0, y: 114.0 }, + 22.0, + 390.0, + 844.0, + insets, + ); + assert_eq!(hit, AffineSelectionHandleKind::Start); + assert!(ctrl.begin_drag(hit, AffinePoint { x: 10.0, y: 70.0 })); + + let dragging = ctrl.layout(390.0, 844.0, insets); + assert!(dragging.loupe.visible); + assert!(!dragging.show_floating_menu); + assert_eq!( + dragging.loupe.zoom_scale, + SelectionOverlayController::LOUPE_ZOOM_SCALE + ); + // Loupe must clamp away from left and top safe edges. + let min_cx = SelectionOverlayController::LOUPE_DIAMETER_PT * 0.5 + + SelectionOverlayController::VIEWPORT_MARGIN_PT; + let min_cy = 59.0 + + SelectionOverlayController::LOUPE_DIAMETER_PT * 0.5 + + SelectionOverlayController::VIEWPORT_MARGIN_PT; + assert!(dragging.loupe.center_x >= min_cx); + assert!(dragging.loupe.center_y >= min_cy); + + // Drag start handle past end handle: handles normalize and active drag flips to End. + assert!(ctrl.update_drag( + AffinePoint { x: 260.0, y: 125.0 }, + AffineRect { + x: 260.0, + y: 120.0, + width: 2.0, + height: 20.0, + }, + AffineUtf16Range { + location: 12, + length: 6, + }, + )); + assert_eq!(ctrl.active_drag_handle(), AffineSelectionHandleKind::End); + + // Release handle: loupe closes and floating menu anchor appears. + assert!(ctrl.end_drag()); + let settled = ctrl.layout(390.0, 844.0, insets); + assert!(!settled.loupe.visible); + assert!(settled.show_floating_menu); + assert_eq!(settled.menu_anchor_rect.x, 200.0); + assert_eq!(settled.menu_anchor_rect.width, 62.0); + } + + #[test] + fn grab_offset_prevents_zero_pt_drag_line_jump_and_offscreen_handles_hide() { + let mut ctrl = SelectionOverlayController::default(); + let insets = standard_insets(); + ctrl.set_selection( + AffineRect { + x: 80.0, + y: 200.0, + width: 2.0, + height: 20.0, + }, + AffineRect { + x: 200.0, + y: 200.0, + width: 2.0, + height: 20.0, + }, + AffineUtf16Range { + location: 0, + length: 12, + }, + AffineWritingDirection::Ltr, + ); + let initial = ctrl.layout(390.0, 844.0, insets); + let drop_center = AffinePoint { + x: initial.end_handle.drop_center_x, + y: initial.end_handle.drop_center_y, + }; + assert!(ctrl.begin_drag(AffineSelectionHandleKind::End, drop_center)); + // 0pt move on teardrop center must probe exact caret midpoint (201.0, 210.0), not drop_center_y (226.0). + let probe = ctrl.drag_probe_point_for(drop_center); + assert_eq!(probe.x, 201.0); + assert_eq!(probe.y, 210.0); + let state = ctrl.layout(390.0, 844.0, insets); + assert_eq!(state.drag_probe_point, probe); + + // Offscreen carets (above safe_top or below keyboard) must hide their handles. + let kb_insets = AffineWindowInsets { + safe_top: 59.0, + safe_right: 0.0, + safe_bottom: 34.0, + safe_left: 0.0, + ime_bottom: 302.0, + }; + ctrl.set_selection( + AffineRect { + x: 80.0, + y: 10.0, + width: 2.0, + height: 20.0, + }, + AffineRect { + x: 200.0, + y: 620.0, + width: 2.0, + height: 20.0, + }, + AffineUtf16Range { + location: 0, + length: 20, + }, + AffineWritingDirection::Ltr, + ); + let offscreen = ctrl.layout(390.0, 844.0, kb_insets); + assert!(!offscreen.start_handle.visible); + assert!(!offscreen.end_handle.visible); + } + + #[test] + fn crossover_table_swaps_active_drag_and_preserves_anchor_for_ltr_rtl_and_multiline() { + struct Case { + name: &'static str, + dir: AffineWritingDirection, + start: AffineRect, + end: AffineRect, + drag: AffineSelectionHandleKind, + target: AffineRect, + expect_active_after: AffineSelectionHandleKind, + expect_start_x: f32, + expect_start_y: f32, + expect_end_x: f32, + expect_end_y: f32, + } + + let cases = [ + Case { + name: "ltr_same_line_start_crosses_end", + dir: AffineWritingDirection::Ltr, + start: AffineRect { + x: 80.0, + y: 200.0, + width: 2.0, + height: 20.0, + }, + end: AffineRect { + x: 180.0, + y: 200.0, + width: 2.0, + height: 20.0, + }, + drag: AffineSelectionHandleKind::Start, + target: AffineRect { + x: 240.0, + y: 200.0, + width: 2.0, + height: 20.0, + }, + expect_active_after: AffineSelectionHandleKind::End, + expect_start_x: 180.0, + expect_start_y: 200.0, + expect_end_x: 240.0, + expect_end_y: 200.0, + }, + Case { + name: "ltr_same_line_end_crosses_before_start", + dir: AffineWritingDirection::Ltr, + start: AffineRect { + x: 120.0, + y: 200.0, + width: 2.0, + height: 20.0, + }, + end: AffineRect { + x: 220.0, + y: 200.0, + width: 2.0, + height: 20.0, + }, + drag: AffineSelectionHandleKind::End, + target: AffineRect { + x: 60.0, + y: 200.0, + width: 2.0, + height: 20.0, + }, + expect_active_after: AffineSelectionHandleKind::Start, + expect_start_x: 60.0, + expect_start_y: 200.0, + expect_end_x: 120.0, + expect_end_y: 200.0, + }, + Case { + name: "rtl_same_line_end_crosses_before_start", + dir: AffineWritingDirection::Rtl, + start: AffineRect { + x: 240.0, + y: 200.0, + width: 2.0, + height: 20.0, + }, + end: AffineRect { + x: 120.0, + y: 200.0, + width: 2.0, + height: 20.0, + }, + drag: AffineSelectionHandleKind::End, + target: AffineRect { + x: 300.0, + y: 200.0, + width: 2.0, + height: 20.0, + }, + expect_active_after: AffineSelectionHandleKind::Start, + expect_start_x: 300.0, + expect_start_y: 200.0, + expect_end_x: 240.0, + expect_end_y: 200.0, + }, + Case { + name: "multiline_end_crosses_above_start", + dir: AffineWritingDirection::Ltr, + start: AffineRect { + x: 100.0, + y: 240.0, + width: 2.0, + height: 20.0, + }, + end: AffineRect { + x: 200.0, + y: 280.0, + width: 2.0, + height: 20.0, + }, + drag: AffineSelectionHandleKind::End, + target: AffineRect { + x: 150.0, + y: 180.0, + width: 2.0, + height: 20.0, + }, + expect_active_after: AffineSelectionHandleKind::Start, + expect_start_x: 150.0, + expect_start_y: 180.0, + expect_end_x: 100.0, + expect_end_y: 240.0, + }, + ]; + + let insets = standard_insets(); + for c in cases { + let mut ctrl = SelectionOverlayController::default(); + ctrl.set_selection( + c.start, + c.end, + AffineUtf16Range { + location: 2, + length: 8, + }, + c.dir, + ); + assert!( + ctrl.begin_drag(c.drag, AffinePoint { x: 100.0, y: 200.0 }), + "{}", + c.name + ); + assert!( + ctrl.update_drag( + AffinePoint { + x: c.target.x, + y: c.target.y, + }, + c.target, + AffineUtf16Range { + location: 1, + length: 6, + }, + ), + "{}", + c.name + ); + assert_eq!( + ctrl.active_drag_handle(), + c.expect_active_after, + "{}", + c.name + ); + let layout = ctrl.layout(390.0, 844.0, insets); + assert_eq!(layout.start_handle.stem_x, c.expect_start_x, "{}", c.name); + assert_eq!( + layout.start_handle.stem_top_y, c.expect_start_y, + "{}", + c.name + ); + assert_eq!(layout.end_handle.stem_x, c.expect_end_x, "{}", c.name); + assert_eq!(layout.end_handle.stem_top_y, c.expect_end_y, "{}", c.name); + } + } + + #[test] + fn keyboard_occlusion_hides_handles_and_menu_then_restores_on_dismiss() { + let mut ctrl = SelectionOverlayController::default(); + ctrl.set_selection( + AffineRect { + x: 40.0, + y: 710.0, + width: 2.0, + height: 20.0, + }, + AffineRect { + x: 180.0, + y: 710.0, + width: 2.0, + height: 20.0, + }, + AffineUtf16Range { + location: 10, + length: 8, + }, + AffineWritingDirection::Ltr, + ); + + let no_kb = standard_insets(); + let before = ctrl.layout(390.0, 844.0, no_kb); + assert!(before.start_handle.visible && before.end_handle.visible); + assert!(before.show_floating_menu); + + let with_kb = AffineWindowInsets { + ime_bottom: 302.0, + ..no_kb + }; + let occluded = ctrl.layout(390.0, 844.0, with_kb); + assert!(!occluded.start_handle.visible && !occluded.end_handle.visible); + assert!(!occluded.show_floating_menu); + assert!(occluded.has_selection); + assert_eq!(occluded.range.location, 10); + assert_eq!(occluded.range.length, 8); + + let restored = ctrl.layout(390.0, 844.0, no_kb); + assert!(restored.start_handle.visible && restored.end_handle.visible); + assert!(restored.show_floating_menu); + } + + #[test] + fn apply_text_drag_endpoints_handles_bidi_crossover_zero_length_and_vertical_drift() { + let mut ctrl = SelectionOverlayController::default(); + let start_c = AffineRect { + x: 180.0, + y: 120.0, + width: 2.0, + height: 22.0, + }; + let end_c = AffineRect { + x: 120.0, + y: 120.0, + width: 2.0, + height: 22.0, + }; + // Mixed BiDi: LTR doc with RTL substring where start_caret.x > end_caret.x. + ctrl.set_selection( + start_c, + end_c, + AffineUtf16Range { + location: 6, + length: 5, + }, + AffineWritingDirection::Ltr, + ); + assert!(ctrl.begin_drag( + AffineSelectionHandleKind::End, + AffinePoint { x: 120.0, y: 148.0 } + )); + assert_eq!(ctrl.drag_anchor_utf16(), Some(6)); + + // 1. Mixed BiDi coordinates (start.x > end.x under LTR) + +50pt vertical finger drift + // must NOT flip active_drag or swap start/end carets. + assert!(ctrl.apply_text_drag_endpoints( + AffinePoint { x: 140.0, y: 198.0 }, + 9, + start_c, + AffineRect { + x: 140.0, + y: 120.0, + width: 2.0, + height: 22.0, + }, + )); + assert_eq!(ctrl.active_drag_handle(), AffineSelectionHandleKind::End); + let st = ctrl.layout(390.0, 844.0, standard_insets()); + assert_eq!( + st.range, + AffineUtf16Range { + location: 6, + length: 3 + } + ); + + // 2. Crossing through length == 0 (target == anchor == 6) keeps dragged handle visible, + // then crossing to 3 flips active_drag to Start, and dragging back to 8 flips back to End. + let at_anchor = AffineRect { + x: 180.0, + y: 120.0, + width: 2.0, + height: 22.0, + }; + assert!(ctrl.apply_text_drag_endpoints( + AffinePoint { x: 180.0, y: 148.0 }, + 6, + at_anchor, + at_anchor, + )); + let st_zero = ctrl.layout(390.0, 844.0, standard_insets()); + assert_eq!( + st_zero.active_drag_handle, + AffineSelectionHandleKind::End as u8 + ); + assert!( + st_zero.end_handle.visible, + "dragged handle stays visible at length == 0" + ); + + assert!(ctrl.apply_text_drag_endpoints( + AffinePoint { x: 210.0, y: 148.0 }, + 3, + AffineRect { + x: 210.0, + y: 120.0, + width: 2.0, + height: 22.0, + }, + at_anchor, + )); + assert_eq!(ctrl.active_drag_handle(), AffineSelectionHandleKind::Start); + let st_cross = ctrl.layout(390.0, 844.0, standard_insets()); + assert_eq!( + st_cross.range, + AffineUtf16Range { + location: 3, + length: 3 + } + ); + + assert!(ctrl.apply_text_drag_endpoints( + AffinePoint { x: 150.0, y: 148.0 }, + 8, + at_anchor, + AffineRect { + x: 150.0, + y: 120.0, + width: 2.0, + height: 22.0, + }, + )); + assert_eq!(ctrl.active_drag_handle(), AffineSelectionHandleKind::End); + let st_back = ctrl.layout(390.0, 844.0, standard_insets()); + assert_eq!( + st_back.range, + AffineUtf16Range { + location: 6, + length: 2 + } + ); + + assert!(ctrl.end_drag()); + assert_eq!(ctrl.drag_anchor_utf16(), None); + } +} diff --git a/packages/frontend/hosts/ios/src/text_layout.rs b/packages/frontend/hosts/ios/src/text_layout.rs new file mode 100644 index 0000000000..e1a495a459 --- /dev/null +++ b/packages/frontend/hosts/ios/src/text_layout.rs @@ -0,0 +1,587 @@ +//! Deterministic pure-Rust fallback text layout (soft line-wrapping, +//! surrogate-safe caret/hit-testing, per-line selection rects, and software +//! loupe rasterization) used when no native CoreText `AffineTextProvider` is +//! attached (for example, headless Linux `cargo test`). + +use crate::{ + AffineUtf16Range, AffineWindowInsets, + selection::{AffinePoint, AffineRect, AffineWritingDirection}, +}; + +pub const CONTENT_INSET_PT: f32 = 16.0; +pub const LINE_HEIGHT_PT: f32 = 22.0; +const GLYPH_ADVANCE_ASCII_PT: f32 = 9.0; +const GLYPH_ADVANCE_SPACE_PT: f32 = 5.0; +const GLYPH_ADVANCE_WIDE_PT: f32 = 11.0; +const GLYPH_ADVANCE_NARROW_PT: f32 = 4.5; + +#[derive(Debug, Clone, Copy)] +struct VisualLine { + start: usize, + end: usize, + is_soft_wrapped: bool, + y: f32, +} + +/// One per-line selection rectangle matching `UITextSelectionRect`. +#[repr(C)] +#[derive(Debug, Clone, Copy, Default, PartialEq)] +pub struct AffineSelectionRect { + pub rect: AffineRect, + pub contains_start: bool, + pub contains_end: bool, +} + +/// Detect document base writing direction from the first strong directional UTF-16 unit. +pub fn detect_writing_direction(utf16: &[u16]) -> AffineWritingDirection { + for &unit in utf16 { + if (0x0590..=0x08FF).contains(&unit) + || (0xFB1D..=0xFDFF).contains(&unit) + || (0xFE70..=0xFEFC).contains(&unit) + { + return AffineWritingDirection::Rtl; + } + if (0x0041..=0x005A).contains(&unit) + || (0x0061..=0x007A).contains(&unit) + || (0x00C0..=0x024F).contains(&unit) + || (0x0370..=0x052F).contains(&unit) + || (0x4E00..=0x9FFF).contains(&unit) + { + return AffineWritingDirection::Ltr; + } + } + AffineWritingDirection::Ltr +} + +/// Detect paragraph base writing direction for the `\n`-delimited paragraph containing `utf16_offset`. +pub fn detect_paragraph_writing_direction( + utf16: &[u16], + utf16_offset: usize, +) -> AffineWritingDirection { + if utf16.is_empty() { + return AffineWritingDirection::Ltr; + } + let idx = utf16_offset.min(utf16.len()); + let mut para_start = idx; + while para_start > 0 && utf16[para_start - 1] != 0x000A { + para_start -= 1; + } + let mut para_end = idx; + while para_end < utf16.len() && utf16[para_end] != 0x000A { + para_end += 1; + } + detect_writing_direction(&utf16[para_start..para_end]) +} + +/// Snap a UTF-16 offset so it never splits a surrogate pair. +pub fn snap_utf16_boundary(utf16: &[u16], offset: usize) -> usize { + let clamped = offset.min(utf16.len()); + if clamped > 0 && clamped < utf16.len() { + let cur = utf16[clamped]; + let prev = utf16[clamped - 1]; + if (0xDC00..=0xDFFF).contains(&cur) && (0xD800..=0xDBFF).contains(&prev) { + return clamped - 1; + } + } + clamped +} + +fn next_cluster_end(utf16: &[u16], idx: usize) -> usize { + if idx >= utf16.len() { + return utf16.len(); + } + let cur = utf16[idx]; + if (0xD800..=0xDBFF).contains(&cur) + && idx + 1 < utf16.len() + && (0xDC00..=0xDFFF).contains(&utf16[idx + 1]) + { + return idx + 2; + } + idx + 1 +} + +fn default_cluster_advance_pt(cluster: &[u16]) -> f32 { + let Some(&u) = cluster.first() else { + return 0.0; + }; + if let Ok(ascii) = u8::try_from(u) { + return match ascii { + b'\n' | b'\r' => 0.0, + b' ' => GLYPH_ADVANCE_SPACE_PT, + b'.' | b',' | b'i' | b'l' | b'!' | b'|' => GLYPH_ADVANCE_NARROW_PT, + b'W' | b'M' => GLYPH_ADVANCE_WIDE_PT, + _ => GLYPH_ADVANCE_ASCII_PT, + }; + } + match u { + 0x0590..=0x08FF => GLYPH_ADVANCE_ASCII_PT, + 0xD800..=0xDBFF => 14.0, + _ => GLYPH_ADVANCE_ASCII_PT, + } +} + +fn content_box(viewport_w: f32, insets: AffineWindowInsets) -> (f32, f32, f32) { + let origin_x = insets.safe_left.max(0.0) + CONTENT_INSET_PT; + let origin_y = insets.safe_top.max(0.0) + CONTENT_INSET_PT; + let right_margin = insets.safe_right.max(0.0) + CONTENT_INSET_PT; + let width = (viewport_w.max(0.0) - origin_x - right_margin).max(40.0); + (origin_x, origin_y, width) +} + +fn layout_visual_lines( + utf16: &[u16], + viewport_w: f32, + insets: AffineWindowInsets, +) -> Vec { + let (_origin_x, origin_y, max_w) = content_box(viewport_w, insets); + let mut lines = Vec::new(); + let mut line_start = 0usize; + let mut cursor = 0usize; + let mut line_w = 0.0f32; + let mut last_space_end: Option = None; + let mut line_idx = 0usize; + + while cursor < utf16.len() { + if utf16[cursor] == 0x000A { + lines.push(VisualLine { + start: line_start, + end: cursor, + is_soft_wrapped: false, + y: origin_y + (line_idx as f32) * LINE_HEIGHT_PT, + }); + line_idx += 1; + cursor += 1; + line_start = cursor; + line_w = 0.0; + last_space_end = None; + continue; + } + let next = next_cluster_end(utf16, cursor); + let adv = default_cluster_advance_pt(&utf16[cursor..next]); + if line_w + adv > max_w && cursor > line_start { + let wrap_end = match last_space_end { + Some(sp) if sp > line_start => sp, + _ => cursor, + }; + lines.push(VisualLine { + start: line_start, + end: wrap_end, + is_soft_wrapped: true, + y: origin_y + (line_idx as f32) * LINE_HEIGHT_PT, + }); + line_idx += 1; + line_start = wrap_end; + cursor = wrap_end; + line_w = 0.0; + last_space_end = None; + continue; + } + line_w += adv; + if utf16[cursor] == 0x0020 { + last_space_end = Some(next); + } + cursor = next; + } + + lines.push(VisualLine { + start: line_start, + end: utf16.len(), + is_soft_wrapped: false, + y: origin_y + (line_idx as f32) * LINE_HEIGHT_PT, + }); + lines +} + +fn measure_range_width(utf16: &[u16], start: usize, end: usize) -> f32 { + let mut w = 0.0f32; + let mut i = start.min(utf16.len()); + let limit = end.min(utf16.len()); + while i < limit { + let next = next_cluster_end(utf16, i); + w += default_cluster_advance_pt(&utf16[i..next]); + i = next; + } + w +} + +/// Compute the fallback visual caret rect for `utf16_offset`. +/// Soft-wrap boundary offsets belong to the start of the wrapped next line; +/// hard `\n` boundary offsets stay at the end of the preceding line. +pub fn caret_rect_for_offset( + utf16: &[u16], + utf16_offset: u32, + viewport_w: f32, + insets: AffineWindowInsets, +) -> AffineRect { + let (origin_x, _origin_y, max_w) = content_box(viewport_w, insets); + let dir = detect_writing_direction(utf16); + let offset = snap_utf16_boundary(utf16, utf16_offset as usize); + let lines = layout_visual_lines(utf16, viewport_w, insets); + + let line = lines + .iter() + .find(|l| { + if l.is_soft_wrapped { + offset >= l.start && offset < l.end + } else { + offset >= l.start && offset <= l.end + } + }) + .or_else(|| lines.last()) + .expect("layout_visual_lines always emits at least one line"); + + let prefix_w = measure_range_width(utf16, line.start, offset); + let x = match dir { + AffineWritingDirection::Ltr => origin_x + prefix_w, + AffineWritingDirection::Rtl => origin_x + max_w - prefix_w, + }; + + AffineRect { + x, + y: line.y, + width: 2.0, + height: LINE_HEIGHT_PT, + } +} + +/// Compute fallback per-line selection rectangles across soft-wrapped visual lines. +pub fn selection_rects_for_range( + utf16: &[u16], + range: AffineUtf16Range, + viewport_w: f32, + insets: AffineWindowInsets, +) -> Vec { + if range.length == 0 || utf16.is_empty() { + return Vec::new(); + } + let sel_start = snap_utf16_boundary(utf16, range.location as usize); + let sel_end = snap_utf16_boundary( + utf16, + (range.location as usize).saturating_add(range.length as usize), + ); + if sel_end <= sel_start { + return Vec::new(); + } + let (origin_x, _origin_y, max_w) = content_box(viewport_w, insets); + let dir = detect_writing_direction(utf16); + let lines = layout_visual_lines(utf16, viewport_w, insets); + let mut rects = Vec::new(); + + for line in &lines { + if sel_end < line.start || sel_start > line.end { + continue; + } + let seg_start = line.start.max(sel_start); + let seg_end = line.end.min(sel_end); + let empty_hard_line_inside = line.start == line.end + && !line.is_soft_wrapped + && sel_start < line.start + && sel_end > line.end; + if seg_end <= seg_start && !empty_hard_line_inside { + continue; + } + + let contains_start = if line.is_soft_wrapped { + sel_start >= line.start && sel_start < line.end + } else { + sel_start >= line.start && sel_start <= line.end + }; + let contains_end = sel_end > line.start && sel_end <= line.end; + + let prefix_start = measure_range_width(utf16, line.start, seg_start); + let prefix_end = measure_range_width(utf16, line.start, seg_end); + let (x0, x1) = match dir { + AffineWritingDirection::Ltr => (origin_x + prefix_start, origin_x + prefix_end), + AffineWritingDirection::Rtl => ( + origin_x + max_w - prefix_end, + origin_x + max_w - prefix_start, + ), + }; + rects.push(AffineSelectionRect { + rect: AffineRect { + x: x0.min(x1), + y: line.y, + width: (x1 - x0).abs().max(2.0), + height: LINE_HEIGHT_PT, + }, + contains_start, + contains_end, + }); + } + rects +} + +/// Hit-test the closest surrogate-safe UTF-16 offset for a point in host view coordinates. +pub fn closest_offset_for_point( + utf16: &[u16], + point: AffinePoint, + viewport_w: f32, + insets: AffineWindowInsets, +) -> u32 { + if utf16.is_empty() { + return 0; + } + let (origin_x, _origin_y, max_w) = content_box(viewport_w, insets); + let dir = detect_writing_direction(utf16); + let lines = layout_visual_lines(utf16, viewport_w, insets); + let px = if point.x.is_finite() { point.x } else { 0.0 }; + let py = if point.y.is_finite() { point.y } else { 0.0 }; + + let mut target_line = &lines[0]; + let mut best_dy = f32::INFINITY; + for line in &lines { + let mid_y = line.y + LINE_HEIGHT_PT * 0.5; + let dy = (py - mid_y).abs(); + if dy < best_dy { + best_dy = dy; + target_line = line; + } + } + + let boundary_x = |prefix_w: f32| match dir { + AffineWritingDirection::Ltr => origin_x + prefix_w, + AffineWritingDirection::Rtl => origin_x + max_w - prefix_w, + }; + + let mut best_offset = target_line.start; + let mut best_dx = (px - boundary_x(0.0)).abs(); + let mut acc_w = 0.0f32; + let mut idx = target_line.start; + while idx < target_line.end { + let next = next_cluster_end(utf16, idx); + acc_w += default_cluster_advance_pt(&utf16[idx..next]); + let dx = (px - boundary_x(acc_w)).abs(); + if dx < best_dx { + best_dx = dx; + best_offset = next; + } + idx = next; + } + + snap_utf16_boundary(utf16, best_offset).min(u32::MAX as usize) as u32 +} + +/// Software fallback RGBA8 loupe rasterizer used only when no native CoreText provider +/// is registered (e.g. headless Linux `cargo test`). +#[allow(clippy::too_many_arguments)] +pub fn render_loupe_rgba8( + utf16: &[u16], + selected_range: AffineUtf16Range, + viewport_w: f32, + insets: AffineWindowInsets, + focus_x: f32, + focus_y: f32, + diameter_px: u32, + zoom_scale: f32, +) -> Vec { + let dim = diameter_px.clamp(16, 512) as usize; + let zoom = if zoom_scale.is_finite() && zoom_scale > 0.25 { + zoom_scale.min(12.0) + } else { + 1.75 + }; + let mut rgba = vec![255u8; dim * dim * 4]; + let (origin_x, _origin_y, max_w) = content_box(viewport_w, insets); + let dir = detect_writing_direction(utf16); + let lines = layout_visual_lines(utf16, viewport_w, insets); + + let sel_start = selected_range.location as usize; + let sel_end = sel_start.saturating_add(selected_range.length as usize); + let half_dim = (dim as f32) * 0.5; + + let to_px = |wx: f32, wy: f32| -> (f32, f32) { + ( + (wx - focus_x) * zoom + half_dim, + (wy - focus_y) * zoom + half_dim, + ) + }; + + for line in &lines { + let mut acc_w = 0.0f32; + let mut idx = line.start; + while idx < line.end { + let next = next_cluster_end(utf16, idx); + let adv = default_cluster_advance_pt(&utf16[idx..next]); + let glyph_x = match dir { + AffineWritingDirection::Ltr => origin_x + acc_w, + AffineWritingDirection::Rtl => origin_x + max_w - acc_w - adv, + }; + + if idx >= sel_start && idx < sel_end { + let (px0, py0) = to_px(glyph_x, line.y); + let (px1, py1) = to_px(glyph_x + adv, line.y + LINE_HEIGHT_PT); + fill_rect(&mut rgba, dim, px0, py0, px1, py1, [206, 232, 255, 255]); + } + + if !matches!(utf16[idx], 0x0020 | 0x000A | 0x000D) { + let (gx0, gy0) = to_px(glyph_x + 1.0, line.y + 4.0); + let (gx1, gy1) = to_px( + glyph_x + (adv - 1.0).max(2.0), + line.y + LINE_HEIGHT_PT - 4.0, + ); + fill_rect(&mut rgba, dim, gx0, gy0, gx1, gy1, [24, 24, 28, 255]); + } + + acc_w += adv; + idx = next; + } + } + + let cx = half_dim; + fill_rect( + &mut rgba, + dim, + cx - 1.0, + half_dim - (LINE_HEIGHT_PT * 0.5) * zoom, + cx + 1.0, + half_dim + (LINE_HEIGHT_PT * 0.5) * zoom, + [30, 150, 235, 255], + ); + + rgba +} + +fn fill_rect(rgba: &mut [u8], dim: usize, x0: f32, y0: f32, x1: f32, y1: f32, color: [u8; 4]) { + let ix0 = (x0.floor() as isize).clamp(0, dim as isize) as usize; + let iy0 = (y0.floor() as isize).clamp(0, dim as isize) as usize; + let ix1 = (x1.ceil() as isize).clamp(0, dim as isize) as usize; + let iy1 = (y1.ceil() as isize).clamp(0, dim as isize) as usize; + for y in iy0..iy1 { + for x in ix0..ix1 { + let base = (y * dim + x) * 4; + rgba[base..base + 4].copy_from_slice(&color); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn fallback_text_layout_handles_soft_wrap_boundary_selection_rects_and_surrogate() { + let insets = AffineWindowInsets::default(); + + // 1. Soft-wrap boundary offset belongs to the start of the wrapped next line, + // and selecting from that offset emits no trailing 2pt sliver on the prior line. + let narrow: Vec = "ABCDZ".encode_utf16().collect(); + let c0 = caret_rect_for_offset(&narrow, 0, 72.0, insets); + let c4 = caret_rect_for_offset(&narrow, 4, 72.0, insets); + assert!( + c4.y > c0.y + 10.0 && (c4.x - c0.x).abs() < 0.01, + "soft-wrap boundary offset 4 must start line 2 (c0={c0:?}, c4={c4:?})" + ); + let wrapped_tail = selection_rects_for_range( + &narrow, + AffineUtf16Range { + location: 4, + length: 1, + }, + 72.0, + insets, + ); + assert_eq!(wrapped_tail.len(), 1, "no 2pt sliver on line 1"); + assert!(wrapped_tail[0].rect.y > c0.y + 10.0); + assert!(wrapped_tail[0].contains_start && wrapped_tail[0].contains_end); + + // Hard newline boundary offset stays on line 1; offset after `\n` starts line 2. + let hard: Vec = "AB\nCD".encode_utf16().collect(); + let ch2 = caret_rect_for_offset(&hard, 2, 390.0, insets); + let ch3 = caret_rect_for_offset(&hard, 3, 390.0, insets); + assert!((ch2.y - c0.y).abs() < 0.01); + assert!(ch3.y > ch2.y + 10.0); + + // 2. Multi-line soft-wrap selection emits per-line rects with start/end flags. + let long: Vec = + "AFFiNE native iOS soft line wrapping verification across multiple visual lines" + .encode_utf16() + .collect(); + let cl0 = caret_rect_for_offset(&long, 0, 390.0, insets); + let cl60 = caret_rect_for_offset(&long, 60, 390.0, insets); + assert!(cl60.y > cl0.y + 10.0); + assert_eq!( + closest_offset_for_point( + &long, + AffinePoint { + x: cl60.x, + y: cl60.y + 10.0, + }, + 390.0, + insets, + ), + 60 + ); + let rects = selection_rects_for_range( + &long, + AffineUtf16Range { + location: 5, + length: 60, + }, + 390.0, + insets, + ); + assert!(rects.len() >= 2); + assert!(rects.first().unwrap().contains_start); + assert!(!rects.first().unwrap().contains_end); + assert!(!rects.last().unwrap().contains_start); + assert!(rects.last().unwrap().contains_end); + + // 3. Base & per-paragraph direction detection and surrogate pair boundary snap. + let hebrew: Vec = "שלום".encode_utf16().collect(); + assert_eq!( + detect_writing_direction(&hebrew), + AffineWritingDirection::Rtl + ); + let multi_para: Vec = "A\nשלום".encode_utf16().collect(); + assert_eq!( + detect_paragraph_writing_direction(&multi_para, 0), + AffineWritingDirection::Ltr + ); + assert_eq!( + detect_paragraph_writing_direction(&multi_para, 2), + AffineWritingDirection::Rtl + ); + let emoji: Vec = "A😀B".encode_utf16().collect(); + assert_eq!(snap_utf16_boundary(&emoji, 2), 1); + + // 4. Fallback loupe RGBA8 produces strictly more dark pixels over 'W' than spaces. + let sample: Vec = "WWWW ....".encode_utf16().collect(); + let cw = caret_rect_for_offset(&sample, 2, 390.0, insets); + let cs = caret_rect_for_offset(&sample, 9, 390.0, insets); + let count_dark = |buf: &[u8]| -> usize { + buf.chunks_exact(4) + .filter(|px| px[3] == 255 && px[0] < 80 && px[1] < 80 && px[2] < 80) + .count() + }; + let dark_w = count_dark(&render_loupe_rgba8( + &sample, + AffineUtf16Range { + location: 0, + length: 16, + }, + 390.0, + insets, + cw.x, + cw.y + 11.0, + 88, + 1.75, + )); + let dark_s = count_dark(&render_loupe_rgba8( + &sample, + AffineUtf16Range { + location: 0, + length: 16, + }, + 390.0, + insets, + cs.x, + cs.y + 11.0, + 88, + 1.75, + )); + assert!( + dark_w > 0 && dark_w > dark_s, + "dark_w={dark_w} dark_s={dark_s}" + ); + } +} diff --git a/packages/frontend/hosts/ios/tests/IosHostS3SmokeTest.swift b/packages/frontend/hosts/ios/tests/IosHostS3SmokeTest.swift new file mode 100644 index 0000000000..c486b30f41 --- /dev/null +++ b/packages/frontend/hosts/ios/tests/IosHostS3SmokeTest.swift @@ -0,0 +1,969 @@ +import CoreGraphics +import Foundation +import PDFKit +import UIKit + +func requireS3(_ condition: Bool, _ message: String) { + if !condition { + fputs("FAIL: \(message)\n", stderr) + exit(1) + } +} + +/// Build a valid 4-page PDF 1.4 document with exact quadrant colors: +/// - Page 0: Normal 200x300 MediaBox [0 0 200 300] +/// - Page 1: /Rotate 90 on 200x300 (displayed size 300x200) +/// - Page 2: Non-zero MediaBox origin [100 100 300 400] (size 200x300) +/// - Page 3: CropBox top-right quarter [100 150 200 300] (size 100x150, pure yellow) +func buildFourPageGeometryTestPdf() -> Data { + func quadrantStream(originX: Int, originY: Int) -> String { + let x0 = originX + let x1 = originX + 100 + let y0 = originY + let y1 = originY + 150 + // Bottom-left: Red, Bottom-right: Green, Top-left: Blue, Top-right: Yellow + return """ + 1 0 0 rg \(x0) \(y0) 100 150 re f + 0 1 0 rg \(x1) \(y0) 100 150 re f + 0 0 1 rg \(x0) \(y1) 100 150 re f + 1 1 0 rg \(x1) \(y1) 100 150 re f + """ + } + + let s0 = quadrantStream(originX: 0, originY: 0) + let s1 = quadrantStream(originX: 0, originY: 0) + let s2 = quadrantStream(originX: 100, originY: 100) + let s3 = quadrantStream(originX: 0, originY: 0) + + let objects: [String] = [ + "1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n", + "2 0 obj\n<< /Type /Pages /Kids [3 0 R 5 0 R 7 0 R 9 0 R] /Count 4 >>\nendobj\n", + "3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 300] /Contents 4 0 R >>\nendobj\n", + "4 0 obj\n<< /Length \(s0.utf8.count) >>\nstream\n\(s0)\nendstream\nendobj\n", + "5 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 300] /Rotate 90 /Contents 6 0 R >>\nendobj\n", + "6 0 obj\n<< /Length \(s1.utf8.count) >>\nstream\n\(s1)\nendstream\nendobj\n", + "7 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [100 100 300 400] /Contents 8 0 R >>\nendobj\n", + "8 0 obj\n<< /Length \(s2.utf8.count) >>\nstream\n\(s2)\nendstream\nendobj\n", + "9 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 300] /CropBox [100 150 200 300] /Contents 10 0 R >>\nendobj\n", + "10 0 obj\n<< /Length \(s3.utf8.count) >>\nstream\n\(s3)\nendstream\nendobj\n", + ] + + var pdf = "%PDF-1.4\n" + var offsets: [Int] = [0] + for obj in objects { + offsets.append(pdf.utf8.count) + pdf += obj + } + let xrefStart = pdf.utf8.count + pdf += "xref\n0 \(objects.count + 1)\n" + pdf += "0000000000 65535 f \n" + for off in offsets.dropFirst() { + pdf += String(format: "%010d 00000 n \n", off) + } + pdf += "trailer\n<< /Size \(objects.count + 1) /Root 1 0 R >>\nstartxref\n\(xrefStart)\n%%EOF\n" + return Data(pdf.utf8) +} + +func pixelAt(_ rgba: Data, width: Int, x: Int, y: Int) -> (UInt8, UInt8, UInt8, UInt8) { + let base = (y * width + x) * 4 + return rgba.withUnsafeBytes { raw in + let bytes = raw.bindMemory(to: UInt8.self) + return (bytes[base], bytes[base + 1], bytes[base + 2], bytes[base + 3]) + } +} + +func assertColor(_ px: (UInt8, UInt8, UInt8, UInt8), r: Bool, g: Bool, b: Bool, _ label: String) { + let okR = r ? px.0 > 200 : px.0 < 55 + let okG = g ? px.1 > 200 : px.1 < 55 + let okB = b ? px.2 > 200 : px.2 < 55 + requireS3(okR && okG && okB && px.3 == 255, "\(label): unexpected RGBA \(px)") +} + +@main +struct IosHostS3SmokeTest { + @MainActor + static func main() { + do { + try testPdfKitFourPageGeometryAndGuards() + testSelectionOverlayGrabOffsetOffscreenAndRealLoupe() + testKeyboardAvoidancePerFrameSlideOverAndBackgroundResume() + testHapticsBridgeDispatchAndBoundedHistory() + testMetalHostViewControllerEndToEndTextSelectionDragCopyAndMenu() + print("ALL 5 SWIFT+RUST S3-IOS SMOKE TESTS PASSED") + } catch { + fputs("UNHANDLED ERROR: \(error)\n", stderr) + exit(1) + } + } + + /// 1. Real PDFKit 4-page geometry (Normal, /Rotate 90, non-zero MediaBox, CropBox), + /// URL scheme guard, 64-bit overflow guard, and zero-copy C-ABI provider. + static func testPdfKitFourPageGeometryAndGuards() throws { + let pdfBytes = buildFourPageGeometryTestPdf() + let bridge = PdfRendererBridge() + + let handle = try bridge.open(data: pdfBytes) + requireS3(handle.pageCount == 4, "expected pageCount == 4, got \(handle.pageCount)") + + // Page 0: Normal 200x300 (top-left Blue, top-right Yellow, bottom-left Red, bottom-right Green). + let size0 = try bridge.pageSizePoints(of: handle, pageIndex: 0) + requireS3(abs(size0.width - 200) < 0.5 && abs(size0.height - 300) < 0.5, "page 0 size \(size0)") + let p0 = try bridge.renderPageRgba8(of: handle, pageIndex: 0, targetWidthPx: 100, targetHeightPx: 150) + assertColor(pixelAt(p0.rgba8, width: 100, x: 25, y: 37), r: false, g: false, b: true, "page0 top-left blue") + assertColor(pixelAt(p0.rgba8, width: 100, x: 75, y: 37), r: true, g: true, b: false, "page0 top-right yellow") + assertColor(pixelAt(p0.rgba8, width: 100, x: 25, y: 112), r: true, g: false, b: false, "page0 bottom-left red") + assertColor(pixelAt(p0.rgba8, width: 100, x: 75, y: 112), r: false, g: true, b: false, "page0 bottom-right green") + + // Page 1: /Rotate 90 -> displayed size 300x200; 90 deg CW: + // top-left=Red, top-right=Blue, bottom-left=Green, bottom-right=Yellow. + let size1 = try bridge.pageSizePoints(of: handle, pageIndex: 1) + requireS3(abs(size1.width - 300) < 0.5 && abs(size1.height - 200) < 0.5, "page 1 rotated size \(size1)") + let p1 = try bridge.renderPageRgba8(of: handle, pageIndex: 1, targetWidthPx: 150, targetHeightPx: 100) + assertColor(pixelAt(p1.rgba8, width: 150, x: 37, y: 25), r: true, g: false, b: false, "page1 rotated top-left red") + assertColor(pixelAt(p1.rgba8, width: 150, x: 112, y: 25), r: false, g: false, b: true, "page1 rotated top-right blue") + assertColor(pixelAt(p1.rgba8, width: 150, x: 37, y: 75), r: false, g: true, b: false, "page1 rotated bottom-left green") + assertColor(pixelAt(p1.rgba8, width: 150, x: 112, y: 75), r: true, g: true, b: false, "page1 rotated bottom-right yellow") + + // Page 2: Non-zero MediaBox origin (100, 100) -> all 4 quadrants must match Page 0 (not all-white!). + let size2 = try bridge.pageSizePoints(of: handle, pageIndex: 2) + requireS3(abs(size2.width - 200) < 0.5 && abs(size2.height - 300) < 0.5, "page 2 size \(size2)") + let p2 = try bridge.renderPageRgba8(of: handle, pageIndex: 2, targetWidthPx: 100, targetHeightPx: 150) + assertColor(pixelAt(p2.rgba8, width: 100, x: 25, y: 37), r: false, g: false, b: true, "page2 origin top-left blue") + assertColor(pixelAt(p2.rgba8, width: 100, x: 75, y: 37), r: true, g: true, b: false, "page2 origin top-right yellow") + assertColor(pixelAt(p2.rgba8, width: 100, x: 25, y: 112), r: true, g: false, b: false, "page2 origin bottom-left red") + assertColor(pixelAt(p2.rgba8, width: 100, x: 75, y: 112), r: false, g: true, b: false, "page2 origin bottom-right green") + + // Page 3: CropBox [100 150 200 300] -> size 100x150, entire page is yellow. + let size3 = try bridge.pageSizePoints(of: handle, pageIndex: 3) + requireS3(abs(size3.width - 100) < 0.5 && abs(size3.height - 150) < 0.5, "page 3 cropBox size \(size3)") + let p3 = try bridge.renderPageRgba8(of: handle, pageIndex: 3, targetWidthPx: 60, targetHeightPx: 90) + assertColor(pixelAt(p3.rgba8, width: 60, x: 15, y: 20), r: true, g: true, b: false, "page3 cropBox top-left yellow") + assertColor(pixelAt(p3.rgba8, width: 60, x: 45, y: 70), r: true, g: true, b: false, "page3 cropBox bottom-right yellow") + + // Controlled local file open + non-file URL scheme guard + path traversal guard. + let tmpDir = FileManager.default.temporaryDirectory.appendingPathComponent("s3-ios-pdf-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: tmpDir, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: tmpDir) } + let fileURL = tmpDir.appendingPathComponent("sample.pdf") + try pdfBytes.write(to: fileURL) + let fileHandle = try bridge.open(fileURL: fileURL, allowedDirectory: tmpDir) + requireS3(fileHandle.pageCount == 4, "file-opened PDF must have pageCount == 4") + + do { + _ = try bridge.open(fileURL: URL(string: "https://example.com/a.pdf")!, allowedDirectory: tmpDir) + requireS3(false, "non-file URL must be rejected") + } catch PdfRendererError.invalidArgument {} + + do { + _ = try bridge.open(fileURL: tmpDir.appendingPathComponent("../escape.pdf"), allowedDirectory: tmpDir) + requireS3(false, "path outside allowed directory must be rejected") + } catch PdfRendererError.pathOutsideAllowedDirectory {} + + // Error guards: negative page index -> pageOutOfRange, >UInt32.max dimension -> pixelLimitExceeded. + do { + _ = try bridge.renderPageRgba8(of: handle, pageIndex: -1, targetWidthPx: 64, targetHeightPx: 64) + requireS3(false, "negative pageIndex must throw pageOutOfRange") + } catch PdfRendererError.pageOutOfRange {} + + do { + _ = try bridge.renderPageRgba8(of: handle, pageIndex: 0, targetWidthPx: Int(UInt32.max) + 10, targetHeightPx: 64) + requireS3(false, "64-bit overflow width must throw pixelLimitExceeded without trapping") + } catch PdfRendererError.pixelLimitExceeded {} + + do { + _ = try bridge.open(data: Data()) + requireS3(false, "empty PDF must fail") + } catch PdfRendererError.emptyDocument {} + + // Zero-copy C-ABI roundtrip via registered AffinePdfProvider. + let host = affine_ios_host_create(nil, 390.0, 844.0, 3.0) + requireS3(host != nil, "host create failed") + defer { + bridge.detach(from: host!) + affine_ios_host_destroy(host) + } + bridge.attach(to: host!) + var errCode: UInt32 = 99 + let cCount = pdfBytes.withUnsafeBytes { raw in + affine_ios_host_pdf_page_count(host, raw.bindMemory(to: UInt8.self).baseAddress, pdfBytes.count, &errCode) + } + requireS3(errCode == 0 && cCount == 4, "C-ABI pdf_page_count expected 4, got \(cCount) (err \(errCode))") + + let cBuf = pdfBytes.withUnsafeBytes { raw in + affine_ios_host_pdf_render_page_rgba8( + host, + raw.bindMemory(to: UInt8.self).baseAddress, + pdfBytes.count, + 1, + 150, + 100, + &errCode + ) + } + defer { affine_ios_bytes_free(cBuf) } + requireS3(errCode == 0 && cBuf.len == 150 * 100 * 4 && cBuf.ptr != nil, "C-ABI rotated render failed") + let cRgba = Data(bytes: cBuf.ptr!, count: cBuf.len) + assertColor(pixelAt(cRgba, width: 150, x: 37, y: 25), r: true, g: false, b: false, "C-ABI page1 rotated top-left red") + + // ABA / same-length, identical-header-and-tail, different-middle-stream cache isolation test. + func makeSingleColorPdf(colorOp: String) -> Data { + let padding = String(repeating: " ", count: 80) + let stream = "\(padding)\n\(colorOp) 0 0 100 100 re f\n\(padding)" + let objs = [ + "1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n", + "2 0 obj\n<< /Type /Pages /Kids [3 0 R] /Count 1 >>\nendobj\n", + "3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 100 100] /Contents 4 0 R >>\nendobj\n", + "4 0 obj\n<< /Length \(stream.utf8.count) >>\nstream\n\(stream)\nendstream\nendobj\n", + ] + var out = "%PDF-1.4\n" + var offs = [0] + for o in objs { + offs.append(out.utf8.count) + out += o + } + let xrefPos = out.utf8.count + out += "xref\n0 5\n0000000000 65535 f \n" + for off in offs.dropFirst() { + out += String(format: "%010d 00000 n \n", off) + } + out += "trailer\n<< /Size 5 /Root 1 0 R >>\nstartxref\n\(xrefPos)\n%%EOF\n" + return Data(out.utf8) + } + + let pdfRed = makeSingleColorPdf(colorOp: "1 0 0 rg") + let pdfBlue = makeSingleColorPdf(colorOp: "0 0 1 rg") + requireS3(pdfRed.count == pdfBlue.count, "ABA test PDFs must have identical byte length") + requireS3(pdfRed.prefix(64) == pdfBlue.prefix(64) && pdfRed.suffix(64) == pdfBlue.suffix(64), "ABA test PDFs must share identical first & last 64 bytes") + + // Explicit PDF handle lifecycle (open -> doc_page_count -> doc_page_size -> doc_render_page_rgba8 -> close). + let docId = pdfBytes.withUnsafeBytes { raw in + affine_ios_host_pdf_open(host, raw.bindMemory(to: UInt8.self).baseAddress, pdfBytes.count, &errCode) + } + requireS3(errCode == 0 && docId != 0 && bridge.openDocumentCount == 1, "explicit pdf_open failed") + let docCount = affine_ios_host_pdf_doc_page_count(host, docId, &errCode) + requireS3(errCode == 0 && docCount == 4, "explicit doc_page_count expected 4, got \(docCount)") + var docPageSize = AffinePdfPageSize() + let gotSize = affine_ios_host_pdf_doc_page_size(host, docId, 1, &docPageSize, &errCode) + requireS3(gotSize && errCode == 0 && abs(docPageSize.width_pt - 300) < 0.5 && abs(docPageSize.height_pt - 200) < 0.5, "explicit doc_page_size rotated mismatch") + let docBuf = affine_ios_host_pdf_doc_render_page_rgba8(host, docId, 1, 150, 100, &errCode) + defer { affine_ios_bytes_free(docBuf) } + requireS3(errCode == 0 && docBuf.len == 150 * 100 * 4 && docBuf.ptr != nil, "explicit doc_render failed") + assertColor(pixelAt(Data(bytes: docBuf.ptr!, count: docBuf.len), width: 150, x: 37, y: 25), r: true, g: false, b: false, "explicit doc page1 rotated top-left red") + affine_ios_host_pdf_close(host, docId) + requireS3(bridge.openDocumentCount == 0, "pdf_close must release PDFDocument immediately") + + // Reuse the exact same mutable buffer address across both stateless C-ABI calls to prove zero UAF / ABA collision. + var sharedBuf = Array(pdfRed) + let bufRed = sharedBuf.withUnsafeBufferPointer { ptr in + affine_ios_host_pdf_render_page_rgba8(host, ptr.baseAddress, ptr.count, 0, 20, 20, &errCode) + } + defer { affine_ios_bytes_free(bufRed) } + requireS3(errCode == 0 && bufRed.len == 20 * 20 * 4 && bufRed.ptr != nil, "ABA red render failed") + assertColor(pixelAt(Data(bytes: bufRed.ptr!, count: bufRed.len), width: 20, x: 10, y: 10), r: true, g: false, b: false, "ABA PDF A red") + + sharedBuf.replaceSubrange(0.. 10.0 && firstFrameAfterResume.ime_bottom < 280.0, + "first frame after background resume must ease smoothly, got \(firstFrameAfterResume.ime_bottom)" + ) + print("PASS [3/5]: KeyboardAvoidanceCoordinator WindowInsets contract, slide-over overlap_w guard, and background resume timestamp passed") + } + + /// 4. HapticsBridge: all 7 patterns dispatch + bounded recordedPatterns ring buffer. + @MainActor + static func testHapticsBridgeDispatchAndBoundedHistory() { + let host = affine_ios_host_create(nil, 390.0, 844.0, 3.0) + requireS3(host != nil, "host create failed") + defer { affine_ios_host_destroy(host) } + + let bridge = HapticsBridge() + bridge.prepareAll() + bridge.attach(to: host!) + defer { bridge.detach(from: host!) } + + for pattern in AffineHapticPatternSwift.allCases { + requireS3(affine_ios_host_trigger_haptic(host, pattern.rawValue), "trigger \(pattern) failed") + requireS3(affine_ios_host_haptic_count(host, pattern.rawValue) == 1, "count mismatch for \(pattern)") + } + requireS3(!affine_ios_host_trigger_haptic(host, 99), "invalid pattern 99 must return false") + requireS3(affine_ios_host_haptic_total_count(host) == 7, "expected total == 7") + requireS3(bridge.dispatchedPatterns == AffineHapticPatternSwift.allCases, "recorded patterns mismatch") + + // Verify bounded history cap (never grows beyond maxRecordedPatterns = 64). + for _ in 0..<80 { + _ = affine_ios_host_trigger_haptic(host, AffineHapticPatternSwift.selectionChanged.rawValue) + } + requireS3( + bridge.dispatchedPatterns.count == HapticsBridge.maxRecordedPatterns, + "dispatchedPatterns must stay bounded at \(HapticsBridge.maxRecordedPatterns), got \(bridge.dispatchedPatterns.count)" + ) + print("PASS [4/5]: HapticsBridge dispatched all 7 patterns and enforced bounded history cap (64)") + } + + /// 5. End-to-end MetalHostViewController: insertText -> selectedTextRange -> real glyph handles -> + /// drag end handle +2 chars -> copy() -> SelectionChanged haptic -> presentedMenuAnchorRect. + @MainActor + static func testMetalHostViewControllerEndToEndTextSelectionDragCopyAndMenu() { + let vc = MetalHostViewController() + vc.view.frame = CGRect(x: 0, y: 0, width: 390, height: 844) + vc.loadViewIfNeeded() + vc.view.layoutIfNeeded() + + let hostView = vc.textHostView + let overlay = vc.selectionOverlay + guard let hostPtr = vc.hostPointer else { + requireS3(false, "MetalHostViewController hostPointer must be initialized") + return + } + + hostView.insertText("Hello world") + hostView.selectedTextRange = AffineTextRange(utf16Range: NSRange(location: 0, length: 5)) + + let stateBefore = overlay.currentState + requireS3(stateBefore.start_handle.visible && stateBefore.end_handle.visible, "both teardrop handles must be visible for [0, 5]") + requireS3( + stateBefore.start_handle.stem_x > 0 && stateBefore.end_handle.stem_x > stateBefore.start_handle.stem_x + 20.0, + "handles must reflect real glyph advance (start=\(stateBefore.start_handle.stem_x), end=\(stateBefore.end_handle.stem_x))" + ) + requireS3(vc.presentedMenuAnchorRect != nil, "menu anchor rect must be published on range selection") + + // Measure exact target caret x for offset 7 ("Hello w") and drag the end teardrop handle there. + let targetCaret7 = hostView.caretRect(for: AffineTextPosition(utf16Offset: 7)) + let endDrop = CGPoint( + x: CGFloat(stateBefore.end_handle.drop_center_x), + y: CGFloat(stateBefore.end_handle.drop_center_y) + ) + let deltaX = targetCaret7.midX - CGFloat(stateBefore.end_handle.stem_x + 1.0) + let draggedPoint = CGPoint(x: endDrop.x + deltaX, y: endDrop.y) + + let hapticBefore = affine_ios_host_haptic_count(hostPtr, AffineHapticPatternSwift.selectionChanged.rawValue) + _ = overlay.processDragStep(phase: .began, point: endDrop) + _ = overlay.processDragStep(phase: .changed, point: draggedPoint) + let stateAfter = overlay.processDragStep(phase: .ended, point: draggedPoint) + requireS3(stateAfter != nil && !stateAfter!.loupe.visible, "loupe must hide after drag end") + + let finalRange = (hostView.selectedTextRange as? AffineTextRange)?.utf16Range + requireS3( + finalRange == NSRange(location: 0, length: 7), + "expected selectedTextRange [0, 7] ('Hello w'), got \(String(describing: finalRange))" + ) + requireS3(hostView.canPerformAction(#selector(UIResponderStandardEditActions.copy(_:)), withSender: nil), "copy action must be enabled") + hostView.copy(nil) + requireS3(hostView.lastCopiedText == "Hello w", "expected copied text 'Hello w', got \(String(describing: hostView.lastCopiedText))") + + let hapticAfter = affine_ios_host_haptic_count(hostPtr, AffineHapticPatternSwift.selectionChanged.rawValue) + requireS3(hapticAfter > hapticBefore, "SelectionChanged haptic count must increase on drag selection change") + requireS3(vc.presentedMenuAnchorRect != nil, "presentedMenuAnchorRect must be non-nil after drag end") + requireS3( + vc.presentedMenuAnchorRect!.minY <= CGFloat(stateAfter!.end_handle.stem_top_y) + 1.0, + "presentedMenuAnchorRect must anchor at/above the selection top" + ) + + // Cut active selection [0, 7] ("Hello w"): remaining text is "orld", handles hide, menu dismisses. + hostView.cut(nil) + let remainingText = hostView.text(in: AffineTextRange(utf16Range: NSRange(location: 0, length: 4))) + requireS3(remainingText == "orld", "expected remaining text 'orld' after cut, got \(String(describing: remainingText))") + requireS3( + !vc.selectionOverlay.currentState.start_handle.visible + && !vc.selectionOverlay.currentState.end_handle.visible + && vc.presentedMenuAnchorRect == nil, + "cut() must hide selection handles and dismiss presentedMenuAnchorRect" + ) + + // 5b. Cross-anchor handle drag sequence on "Hello world": select [6, 11) ("world"), grab End handle, + // drag step-by-step 10 -> 8 -> 6 (length == 0!) -> 5 -> 3 => [3, 6) ("lo "), active_drag_handle == 1. + let vcCross = MetalHostViewController() + vcCross.view.frame = CGRect(x: 0, y: 0, width: 390, height: 844) + vcCross.loadViewIfNeeded() + vcCross.view.layoutIfNeeded() + vcCross.textHostView.insertText("Hello world") + vcCross.textHostView.selectedTextRange = AffineTextRange(utf16Range: NSRange(location: 6, length: 5)) + let crossStart = vcCross.selectionOverlay.currentState + let crossDrop = CGPoint( + x: CGFloat(crossStart.end_handle.drop_center_x), + y: CGFloat(crossStart.end_handle.drop_center_y) + ) + let caret11 = vcCross.textHostView.caretRect(for: AffineTextPosition(utf16Offset: 11)) + _ = vcCross.selectionOverlay.processDragStep(phase: .began, point: crossDrop) + var lastCrossState: AffineSelectionOverlayState? + for stepOffset in [10, 8, 6, 5, 3] { + let cStep = vcCross.textHostView.caretRect(for: AffineTextPosition(utf16Offset: stepOffset)) + let pt = CGPoint(x: crossDrop.x + (cStep.midX - caret11.midX), y: crossDrop.y) + lastCrossState = vcCross.selectionOverlay.processDragStep(phase: .changed, point: pt) + requireS3( + lastCrossState != nil && lastCrossState!.active_drag_handle != 0, + "drag must stay alive across stepOffset=\(stepOffset)" + ) + } + requireS3( + lastCrossState?.active_drag_handle == 1, + "active_drag_handle must flip to Start (1) after crossing anchor 6 -> 3, got \(String(describing: lastCrossState?.active_drag_handle))" + ) + let c3 = vcCross.textHostView.caretRect(for: AffineTextPosition(utf16Offset: 3)) + _ = vcCross.selectionOverlay.processDragStep( + phase: .ended, + point: CGPoint(x: crossDrop.x + (c3.midX - caret11.midX), y: crossDrop.y) + ) + let crossRange = (vcCross.textHostView.selectedTextRange as? AffineTextRange)?.utf16Range + requireS3(crossRange == NSRange(location: 3, length: 3), "expected crossed range [3, 6), got \(String(describing: crossRange))") + vcCross.textHostView.copy(nil) + requireS3(vcCross.textHostView.lastCopiedText == "lo ", "expected copied 'lo ', got \(String(describing: vcCross.textHostView.lastCopiedText))") + + // 5c. BiDi RTL ("שלום 123 abc", "A אבג B"), ZWJ emoji ("A👨👩👧👦B"), soft-wrap boundary & rotation re-layout. + let vcRtl = MetalHostViewController() + vcRtl.view.frame = CGRect(x: 0, y: 0, width: 390, height: 844) + vcRtl.loadViewIfNeeded() + vcRtl.view.layoutIfNeeded() + let bidiMixed = "שלום 123 abc" + vcRtl.textHostView.insertText(bidiMixed) + vcRtl.textHostView.selectedTextRange = AffineTextRange(utf16Range: NSRange(location: 0, length: 4)) + requireS3(vcRtl.selectionOverlay.currentState.is_rtl, "Hebrew text must set is_rtl == true") + var prevHebX = CGFloat.greatestFiniteMagnitude + for offset in 0...3 { + let c = vcRtl.textHostView.caretRect(for: AffineTextPosition(utf16Offset: offset)) + requireS3(c.minX < prevHebX, "Hebrew caret x must decrease RTL at offset \(offset) (prev=\(prevHebX), cur=\(c.minX))") + prevHebX = c.minX + } + // Embedded digits "123" (offsets 5,6,7) and Latin "abc" (offsets 9,10,11) must advance LTR (never mirrored to "cba 321"). + let cDigit1 = vcRtl.textHostView.caretRect(for: AffineTextPosition(utf16Offset: 5)).minX + let cDigit2 = vcRtl.textHostView.caretRect(for: AffineTextPosition(utf16Offset: 6)).minX + let cDigit3 = vcRtl.textHostView.caretRect(for: AffineTextPosition(utf16Offset: 7)).minX + requireS3(cDigit1 < cDigit2 && cDigit2 < cDigit3, "embedded digits '123' must increase LTR (\(cDigit1), \(cDigit2), \(cDigit3))") + let cLatA = vcRtl.textHostView.caretRect(for: AffineTextPosition(utf16Offset: 9)).minX + let cLatB = vcRtl.textHostView.caretRect(for: AffineTextPosition(utf16Offset: 10)).minX + let cLatC = vcRtl.textHostView.caretRect(for: AffineTextPosition(utf16Offset: 11)).minX + requireS3(cLatA < cLatB && cLatB < cLatC, "embedded Latin 'abc' must increase LTR (\(cLatA), \(cLatB), \(cLatC))") + + // Verify 6 BiDi direction-boundary selection rect and handle-edge cases. + // 1) "שלום 123 abc" [5,8) ("123"): rect.width > 20pt & handles separated > 20pt. + vcRtl.textHostView.selectedTextRange = AffineTextRange(utf16Range: NSRange(location: 5, length: 3)) + let r123 = vcRtl.textHostView.selectionRects(for: AffineTextRange(utf16Range: NSRange(location: 5, length: 3))) + let st123 = vcRtl.selectionOverlay.currentState + requireS3(r123.count == 1 && r123[0].rect.width > 20.0, "'123' rect must be >20pt wide, got \(r123.map { $0.rect.width })") + requireS3(abs(st123.end_handle.stem_x - st123.start_handle.stem_x) > 20.0, "'123' handles must be >20pt apart (start=\(st123.start_handle.stem_x), end=\(st123.end_handle.stem_x))") + + // 2) "שלום 123 abc" [9,12) ("abc"): rect.width > 20pt & handles separated > 20pt. + vcRtl.textHostView.selectedTextRange = AffineTextRange(utf16Range: NSRange(location: 9, length: 3)) + let rAbc = vcRtl.textHostView.selectionRects(for: AffineTextRange(utf16Range: NSRange(location: 9, length: 3))) + let stAbc = vcRtl.selectionOverlay.currentState + requireS3(rAbc.count == 1 && rAbc[0].rect.width > 20.0, "'abc' rect must be >20pt wide, got \(rAbc.map { $0.rect.width })") + requireS3(abs(stAbc.end_handle.stem_x - stAbc.start_handle.stem_x) > 20.0, "'abc' handles must not overlap (start=\(stAbc.start_handle.stem_x), end=\(stAbc.end_handle.stem_x))") + + // 3) "שלום 123 abc" [5,7) ("12"): rect.width > 12pt and strictly narrower than "123". + let r12 = vcRtl.textHostView.selectionRects(for: AffineTextRange(utf16Range: NSRange(location: 5, length: 2))) + requireS3(r12.count == 1 && r12[0].rect.width > 12.0 && r12[0].rect.width < r123[0].rect.width, "'12' rect width must be >12pt and < '123' (w12=\(r12.first?.rect.width ?? 0), w123=\(r123[0].rect.width))") + + // 4) "שלום 123 abc" [0,4) ("שלום"): rect.width > 25pt & start_handle right of end_handle by >25pt. + vcRtl.textHostView.selectedTextRange = AffineTextRange(utf16Range: NSRange(location: 0, length: 4)) + let rHeb = vcRtl.textHostView.selectionRects(for: AffineTextRange(utf16Range: NSRange(location: 0, length: 4))) + let stHeb = vcRtl.selectionOverlay.currentState + requireS3(rHeb.count == 1 && rHeb[0].rect.width > 25.0, "'שלום' rect must be >25pt wide, got \(rHeb.map { $0.rect.width })") + requireS3(stHeb.start_handle.stem_x > stHeb.end_handle.stem_x + 25.0, "'שלום' start_handle must be right of end_handle by >25pt (start=\(stHeb.start_handle.stem_x), end=\(stHeb.end_handle.stem_x))") + + // 5) & 6) Mixed LTR-base BiDi ("A אבג B"): + // [2,5) ("אבג"): width > 20pt & start_handle right of end_handle by > 20pt. + // [2,4) ("אב"): single rect minX strictly > [2,5) minX + 5pt (highlights right two letters, never 'ג'). + let vcMixed = MetalHostViewController() + vcMixed.view.frame = CGRect(x: 0, y: 0, width: 390, height: 844) + vcMixed.loadViewIfNeeded() + vcMixed.view.layoutIfNeeded() + vcMixed.textHostView.insertText("A אבג B") + vcMixed.textHostView.selectedTextRange = AffineTextRange(utf16Range: NSRange(location: 2, length: 3)) + let mixedRects = vcMixed.textHostView.selectionRects(for: AffineTextRange(utf16Range: NSRange(location: 2, length: 3))) + let stMix3 = vcMixed.selectionOverlay.currentState + requireS3(mixedRects.count == 1 && mixedRects[0].rect.width > 20.0 && mixedRects[0].containsStart && mixedRects[0].containsEnd, "mixed BiDi 'אבג' must emit 1 rect >20pt wide") + requireS3(stMix3.start_handle.stem_x > stMix3.end_handle.stem_x + 20.0, "'אבג' RTL start_handle must be right of end_handle by >20pt (start=\(stMix3.start_handle.stem_x), end=\(stMix3.end_handle.stem_x))") + let mixedRects2 = vcMixed.textHostView.selectionRects(for: AffineTextRange(utf16Range: NSRange(location: 2, length: 2))) + requireS3(mixedRects2.count == 1 && mixedRects2[0].rect.minX > mixedRects[0].rect.minX + 5.0, "'אב' [2,4) minX must lie strictly right of 'ג' (minX2=\(mixedRects2.first?.rect.minX ?? 0), minX3=\(mixedRects[0].rect.minX))") + vcMixed.textHostView.copy(nil) + requireS3(vcMixed.textHostView.lastCopiedText == "אבג", "mixed BiDi copy must yield exact 'אבג'") + // In-place 0pt drag on Start handle at BiDi boundary ("A אבג B" [2, 5)) must preserve [2, 5) "אבג". + let mixedStartDrop = CGPoint( + x: CGFloat(stMix3.start_handle.drop_center_x), + y: CGFloat(stMix3.start_handle.drop_center_y) + ) + _ = vcMixed.selectionOverlay.processDragStep(phase: .began, point: mixedStartDrop) + _ = vcMixed.selectionOverlay.processDragStep(phase: .changed, point: mixedStartDrop) + _ = vcMixed.selectionOverlay.processDragStep(phase: .ended, point: mixedStartDrop) + let mixedAfterZeroStart = (vcMixed.textHostView.selectedTextRange as? AffineTextRange)?.utf16Range + requireS3(mixedAfterZeroStart == NSRange(location: 2, length: 3), "0pt Start drag on 'A אבג B' [2,5) must preserve [2,5), got \(String(describing: mixedAfterZeroStart))") + vcMixed.textHostView.copy(nil) + requireS3(vcMixed.textHostView.lastCopiedText == "אבג", "0pt Start drag must keep copied 'אבג'") + // Moving Start handle inward by 1 Hebrew letter shrinks [2,5) -> [3,5) "בג". + let cMix3 = vcMixed.textHostView.caretRect(for: AffineTextPosition(utf16Offset: 3)) + let mixStartInwardDx = cMix3.midX - CGFloat(stMix3.start_handle.stem_x) + _ = vcMixed.selectionOverlay.processDragStep(phase: .began, point: mixedStartDrop) + _ = vcMixed.selectionOverlay.processDragStep( + phase: .changed, + point: CGPoint(x: mixedStartDrop.x + mixStartInwardDx, y: mixedStartDrop.y) + ) + _ = vcMixed.selectionOverlay.processDragStep( + phase: .ended, + point: CGPoint(x: mixedStartDrop.x + mixStartInwardDx, y: mixedStartDrop.y) + ) + vcMixed.textHostView.copy(nil) + requireS3(vcMixed.textHostView.lastCopiedText == "בג", "inward Start drag on 'A אבג B' must yield 'בג', got \(String(describing: vcMixed.textHostView.lastCopiedText))") + vcMixed.textHostView.selectedTextRange = AffineTextRange(utf16Range: NSRange(location: 2, length: 3)) + // Drag End handle from offset 5 -> offset 4 inside RTL run of LTR doc: must NOT spuriously flip active_drag_handle! + let mixedBefore = vcMixed.selectionOverlay.currentState + let mixedEndDrop = CGPoint(x: CGFloat(mixedBefore.end_handle.drop_center_x), y: CGFloat(mixedBefore.end_handle.drop_center_y)) + let cMix4 = vcMixed.textHostView.caretRect(for: AffineTextPosition(utf16Offset: 4)) + let mixDx = cMix4.midX - CGFloat(mixedBefore.end_handle.stem_x) + _ = vcMixed.selectionOverlay.processDragStep(phase: .began, point: mixedEndDrop) + let mixedChanged = vcMixed.selectionOverlay.processDragStep( + phase: .changed, + point: CGPoint(x: mixedEndDrop.x + mixDx, y: mixedEndDrop.y) + ) + requireS3(mixedChanged?.active_drag_handle == 2, "dragging End handle inside RTL run of LTR doc must keep active_drag_handle == 2 (got \(String(describing: mixedChanged?.active_drag_handle)))") + _ = vcMixed.selectionOverlay.processDragStep( + phase: .ended, + point: CGPoint(x: mixedEndDrop.x + mixDx, y: mixedEndDrop.y) + ) + vcMixed.textHostView.copy(nil) + requireS3(vcMixed.textHostView.lastCopiedText == "אב", "dragging End handle on 'A אבג B' to offset 4 must yield 'אב', got \(String(describing: vcMixed.textHostView.lastCopiedText))") + + // Unicode canonical equivalence cache regression: replacing precomposed "éB" (2 UTF-16) + // with decomposed "e\u{0301}B" (3 UTF-16) on the same host must NOT hit stale 2-unit cache. + let vcNorm = MetalHostViewController() + vcNorm.view.frame = CGRect(x: 0, y: 0, width: 390, height: 844) + vcNorm.loadViewIfNeeded() + vcNorm.view.layoutIfNeeded() + vcNorm.textHostView.insertText("\u{00E9}B") + _ = vcNorm.textHostView.selectionRects(for: AffineTextRange(utf16Range: NSRange(location: 1, length: 1))) + vcNorm.textHostView.replace( + AffineTextRange(utf16Range: NSRange(location: 0, length: 2)), + withText: "e\u{0301}B" + ) + let decomposedBRects = vcNorm.textHostView.selectionRects( + for: AffineTextRange(utf16Range: NSRange(location: 2, length: 1)) + ) + requireS3( + decomposedBRects.count == 1 && decomposedBRects[0].rect.width > 6.0, + "replacing 'éB' with decomposed 'e\\u{0301}B' must return 1 rect >6pt for [2,3), got \(decomposedBRects.map { $0.rect.width })" + ) + + // In-place 0pt drag on End handle of embedded LTR digits "123" inside RTL doc "שלום 123 abc" must preserve [5, 8) "123". + vcRtl.textHostView.selectedTextRange = AffineTextRange(utf16Range: NSRange(location: 5, length: 3)) + let rtlNumBefore = vcRtl.selectionOverlay.currentState + let rtlNumDrop = CGPoint(x: CGFloat(rtlNumBefore.end_handle.drop_center_x), y: CGFloat(rtlNumBefore.end_handle.drop_center_y)) + _ = vcRtl.selectionOverlay.processDragStep(phase: .began, point: rtlNumDrop) + _ = vcRtl.selectionOverlay.processDragStep(phase: .changed, point: rtlNumDrop) + _ = vcRtl.selectionOverlay.processDragStep(phase: .ended, point: rtlNumDrop) + let rtlNumAfterZero = (vcRtl.textHostView.selectedTextRange as? AffineTextRange)?.utf16Range + requireS3(rtlNumAfterZero == NSRange(location: 5, length: 3), "0pt End drag on 'שלום 123 abc' [5,8) must preserve [5,8), got \(String(describing: rtlNumAfterZero))") + vcRtl.textHostView.copy(nil) + requireS3(vcRtl.textHostView.lastCopiedText == "123", "0pt End drag on 'שלום 123 abc' [5,8) must keep '123'") + // Drag End handle on embedded LTR digits "123" inside RTL doc "שלום 123 abc" -> "12" without spurious flip. + let cNum7 = vcRtl.textHostView.caretRect(for: AffineTextPosition(utf16Offset: 7)) + let numDx = cNum7.midX - CGFloat(rtlNumBefore.end_handle.stem_x) + _ = vcRtl.selectionOverlay.processDragStep(phase: .began, point: rtlNumDrop) + let rtlNumChanged = vcRtl.selectionOverlay.processDragStep( + phase: .changed, + point: CGPoint(x: rtlNumDrop.x + numDx, y: rtlNumDrop.y) + ) + requireS3(rtlNumChanged?.active_drag_handle == 2, "dragging End handle inside LTR digits of RTL doc must keep active_drag_handle == 2 (got \(String(describing: rtlNumChanged?.active_drag_handle)))") + _ = vcRtl.selectionOverlay.processDragStep( + phase: .ended, + point: CGPoint(x: rtlNumDrop.x + numDx, y: rtlNumDrop.y) + ) + vcRtl.textHostView.copy(nil) + requireS3(vcRtl.textHostView.lastCopiedText == "12", "dragging End handle on 'שלום 123 abc' digits to offset 7 must yield '12', got \(String(describing: vcRtl.textHostView.lastCopiedText))") + + // Single-line drag with +50pt vertical finger drift must not flip active_drag_handle. + let vcDrift = MetalHostViewController() + vcDrift.view.frame = CGRect(x: 0, y: 0, width: 390, height: 844) + vcDrift.loadViewIfNeeded() + vcDrift.view.layoutIfNeeded() + vcDrift.textHostView.insertText("Hello world") + vcDrift.textHostView.selectedTextRange = AffineTextRange(utf16Range: NSRange(location: 0, length: 5)) + let driftBefore = vcDrift.selectionOverlay.currentState + let driftDrop = CGPoint(x: CGFloat(driftBefore.end_handle.drop_center_x), y: CGFloat(driftBefore.end_handle.drop_center_y)) + let cDr5 = vcDrift.textHostView.caretRect(for: AffineTextPosition(utf16Offset: 5)) + let cDr9 = vcDrift.textHostView.caretRect(for: AffineTextPosition(utf16Offset: 9)) + _ = vcDrift.selectionOverlay.processDragStep(phase: .began, point: driftDrop) + let driftChanged = vcDrift.selectionOverlay.processDragStep( + phase: .changed, + point: CGPoint(x: driftDrop.x + (cDr9.midX - cDr5.midX), y: driftDrop.y + 50.0) + ) + requireS3(driftChanged?.active_drag_handle == 2, "vertical +50pt finger drift on single line must keep active_drag_handle == 2") + _ = vcDrift.selectionOverlay.processDragStep( + phase: .ended, + point: CGPoint(x: driftDrop.x + (cDr9.midX - cDr5.midX), y: driftDrop.y + 50.0) + ) + vcDrift.textHostView.copy(nil) + requireS3(vcDrift.textHostView.lastCopiedText == "Hello wor", "vertical drift drag must select 'Hello wor', got \(String(describing: vcDrift.textHostView.lastCopiedText))") + + // Multi-paragraph "A\nשלום" paragraph 2 must set is_rtl == true. + let vcPara = MetalHostViewController() + vcPara.view.frame = CGRect(x: 0, y: 0, width: 390, height: 844) + vcPara.loadViewIfNeeded() + vcPara.view.layoutIfNeeded() + vcPara.textHostView.insertText("A\nשלום") + vcPara.textHostView.selectedTextRange = AffineTextRange(utf16Range: NSRange(location: 2, length: 4)) + requireS3(vcPara.selectionOverlay.currentState.is_rtl, "selecting Hebrew paragraph 2 in 'A\\nשלום' must set is_rtl == true") + + // ZWJ family emoji ("A👨👩👧👦B") hit-testing never lands inside the 11-unit composed sequence. + let vcZwj = MetalHostViewController() + vcZwj.view.frame = CGRect(x: 0, y: 0, width: 390, height: 844) + vcZwj.loadViewIfNeeded() + vcZwj.view.layoutIfNeeded() + let zwjStr = "A\u{1F468}\u{200D}\u{1F469}\u{200D}\u{1F467}\u{200D}\u{1F466}B" + vcZwj.textHostView.insertText(zwjStr) + let emojiStart = 1 + let emojiEnd = (zwjStr as NSString).length - 1 + let cEmoji0 = vcZwj.textHostView.caretRect(for: AffineTextPosition(utf16Offset: emojiStart)) + let cEmoji1 = vcZwj.textHostView.caretRect(for: AffineTextPosition(utf16Offset: emojiEnd)) + for step in 0...6 { + let frac = CGFloat(step) / 6.0 + let probe = CGPoint(x: cEmoji0.minX + (cEmoji1.minX - cEmoji0.minX) * frac, y: cEmoji0.midY) + let hit = (vcZwj.textHostView.closestPosition(to: probe) as? AffineTextPosition)?.utf16Offset ?? -1 + requireS3(hit <= emojiStart || hit >= emojiEnd, "ZWJ emoji hit-test must never land inside composed sequence (got \(hit), bounds \(emojiStart)..\(emojiEnd))") + } + + // Soft-wrap boundary offset ("ABCDZ" in 72pt width) starts line 2 and emits no 2pt sliver on line 1. + let vcNarrow = MetalHostViewController() + vcNarrow.view.frame = CGRect(x: 0, y: 0, width: 72, height: 300) + vcNarrow.loadViewIfNeeded() + vcNarrow.view.layoutIfNeeded() + vcNarrow.textHostView.insertText("ABCDZ") + let cNarrow0 = vcNarrow.textHostView.caretRect(for: AffineTextPosition(utf16Offset: 0)) + var wrapBoundaryOffset = -1 + for off in 1..<5 { + let cOff = vcNarrow.textHostView.caretRect(for: AffineTextPosition(utf16Offset: off)) + if cOff.minY > cNarrow0.minY + 10.0 { + wrapBoundaryOffset = off + break + } + } + requireS3(wrapBoundaryOffset > 0, "narrow 72pt viewport must soft-wrap 'ABCDZ'") + let tailRects = vcNarrow.textHostView.selectionRects( + for: AffineTextRange(utf16Range: NSRange(location: wrapBoundaryOffset, length: 5 - wrapBoundaryOffset)) + ) + requireS3(tailRects.count == 1 && tailRects[0].rect.minY > cNarrow0.minY + 10.0, "selecting from soft-wrap boundary must emit 1 rect on line 2 with zero sliver on line 1 (got \(tailRects.count))") + + let vcWrap = MetalHostViewController() + vcWrap.view.frame = CGRect(x: 0, y: 0, width: 390, height: 844) + vcWrap.loadViewIfNeeded() + vcWrap.view.layoutIfNeeded() + let longLine = "AFFiNE native iOS CoreText soft line wrapping verification across multiple wrapped visual lines" + vcWrap.textHostView.insertText(longLine) + let caret0Wrap = vcWrap.textHostView.caretRect(for: AffineTextPosition(utf16Offset: 0)) + let caretWrapLine2 = vcWrap.textHostView.caretRect(for: AffineTextPosition(utf16Offset: 65)) + requireS3( + caretWrapLine2.minY > caret0Wrap.minY + 10.0, + "long English line must soft-wrap onto line 2 (y0=\(caret0Wrap.minY), y65=\(caretWrapLine2.minY))" + ) + vcWrap.textHostView.selectedTextRange = AffineTextRange(utf16Range: NSRange(location: 10, length: 5)) + let wrapState = vcWrap.selectionOverlay.currentState + let wrapEndDrop = CGPoint( + x: CGFloat(wrapState.end_handle.drop_center_x), + y: CGFloat(wrapState.end_handle.drop_center_y) + ) + let caret15Wrap = vcWrap.textHostView.caretRect(for: AffineTextPosition(utf16Offset: 15)) + _ = vcWrap.selectionOverlay.processDragStep(phase: .began, point: wrapEndDrop) + _ = vcWrap.selectionOverlay.processDragStep( + phase: .changed, + point: CGPoint( + x: wrapEndDrop.x + (caretWrapLine2.midX - caret15Wrap.midX), + y: wrapEndDrop.y + (caretWrapLine2.midY - caret15Wrap.midY) + ) + ) + _ = vcWrap.selectionOverlay.processDragStep( + phase: .ended, + point: CGPoint( + x: wrapEndDrop.x + (caretWrapLine2.midX - caret15Wrap.midX), + y: wrapEndDrop.y + (caretWrapLine2.midY - caret15Wrap.midY) + ) + ) + vcWrap.textHostView.copy(nil) + let wrapRange = (vcWrap.textHostView.selectedTextRange as? AffineTextRange)?.utf16Range + requireS3(wrapRange != nil && wrapRange!.length >= 50, "soft-wrap drag must span into line 2, got \(String(describing: wrapRange))") + let wrapSelRects = vcWrap.textHostView.selectionRects(for: AffineTextRange(utf16Range: wrapRange!)) + requireS3( + wrapSelRects.count >= 2 && wrapSelRects.first!.containsStart && wrapSelRects.last!.containsEnd, + "multi-line soft-wrap selectionRects must return >=2 per-line rects with start/end flags (got \(wrapSelRects.count))" + ) + let expectedWrapSub = (longLine as NSString).substring(with: wrapRange!) + requireS3(vcWrap.textHostView.lastCopiedText == expectedWrapSub, "soft-wrap copy must match exact substring") + + // Rotation / viewport resize (390x844 -> 844x390) must recompute handle endpoints to match unwrapped line geometry. + let endYPortrait = vcWrap.selectionOverlay.currentState.end_handle.stem_top_y + vcWrap.view.frame = CGRect(x: 0, y: 0, width: 844, height: 390) + vcWrap.view.setNeedsLayout() + vcWrap.view.layoutIfNeeded() + let endYLandscape = vcWrap.selectionOverlay.currentState.end_handle.stem_top_y + requireS3( + endYLandscape < endYPortrait - 10.0, + "widening viewport 390->844 must move wrapped end handle up to match unwrapped line (portrait=\(endYPortrait), landscape=\(endYLandscape))" + ) + + // 5d. Production host loupe captures real rendered glyph strokes ("WWWW ...."). + func countDarkPixels(in image: UIImage) -> Int { + guard let cg = image.cgImage else { return 0 } + let w = cg.width + let h = cg.height + var buf = [UInt8](repeating: 0, count: w * h * 4) + let cs = CGColorSpaceCreateDeviceRGB() + let info = CGImageAlphaInfo.premultipliedLast.rawValue | CGBitmapInfo.byteOrder32Big.rawValue + guard let ctx = CGContext(data: &buf, width: w, height: h, bitsPerComponent: 8, bytesPerRow: w * 4, space: cs, bitmapInfo: info) else { + return 0 + } + ctx.draw(cg, in: CGRect(x: 0, y: 0, width: w, height: h)) + var dark = 0 + for i in 0..<(w * h) { + let base = i * 4 + if buf[base + 3] > 200 && buf[base] < 128 && buf[base + 1] < 128 && buf[base + 2] < 128 { + dark += 1 + } + } + return dark + } + + let vcLoupe = MetalHostViewController() + vcLoupe.view.frame = CGRect(x: 0, y: 0, width: 390, height: 844) + vcLoupe.loadViewIfNeeded() + vcLoupe.view.layoutIfNeeded() + vcLoupe.textHostView.insertText("WWWW ....") + vcLoupe.textHostView.selectedTextRange = AffineTextRange(utf16Range: NSRange(location: 0, length: 16)) + let loupeStartState = vcLoupe.selectionOverlay.currentState + let loupeDrop = CGPoint( + x: CGFloat(loupeStartState.end_handle.drop_center_x), + y: CGFloat(loupeStartState.end_handle.drop_center_y) + ) + let caret16L = vcLoupe.textHostView.caretRect(for: AffineTextPosition(utf16Offset: 16)) + let caret2W = vcLoupe.textHostView.caretRect(for: AffineTextPosition(utf16Offset: 2)) + let caret10Space = vcLoupe.textHostView.caretRect(for: AffineTextPosition(utf16Offset: 10)) + _ = vcLoupe.selectionOverlay.processDragStep(phase: .began, point: loupeDrop) + _ = vcLoupe.selectionOverlay.processDragStep( + phase: .changed, + point: CGPoint(x: loupeDrop.x + (caret2W.midX - caret16L.midX), y: loupeDrop.y) + ) + let darkAtW = vcLoupe.selectionOverlay.loupeSnapshotImage.map(countDarkPixels(in:)) ?? 0 + _ = vcLoupe.selectionOverlay.processDragStep( + phase: .changed, + point: CGPoint(x: loupeDrop.x + (caret10Space.midX - caret16L.midX), y: loupeDrop.y) + ) + let darkAtSpace = vcLoupe.selectionOverlay.loupeSnapshotImage.map(countDarkPixels(in:)) ?? 0 + _ = vcLoupe.selectionOverlay.processDragStep(phase: .ended, point: loupeDrop) + requireS3( + darkAtW > 0 && darkAtW > darkAtSpace, + "loupe must capture real rendered glyph strokes (darkAtW=\(darkAtW), darkAtSpace=\(darkAtSpace))" + ) + + // 5e. Keyboard occlusion hides handles & menu at y ~= 710, preserves selection/copy, then restores on dismiss. + let vcKb = MetalHostViewController() + vcKb.view.frame = CGRect(x: 0, y: 0, width: 390, height: 844) + vcKb.loadViewIfNeeded() + vcKb.view.layoutIfNeeded() + let fillerLines = String(repeating: "\n", count: 35) + let bottomWord = "BottomTarget" + vcKb.textHostView.insertText(fillerLines + bottomWord) + vcKb.textHostView.selectedTextRange = AffineTextRange( + utf16Range: NSRange(location: fillerLines.utf16.count, length: bottomWord.utf16.count) + ) + let kbBefore = vcKb.selectionOverlay.currentState + requireS3(kbBefore.start_handle.stem_top_y > 650.0, "bottom selection must sit below y=650 (got \(kbBefore.start_handle.stem_top_y))") + requireS3(kbBefore.start_handle.visible && kbBefore.end_handle.visible && vcKb.presentedMenuAnchorRect != nil, "handles and menu visible before keyboard") + + _ = vcKb.keyboardCoordinator.applyKeyboardFrame( + windowBounds: CGRect(x: 0, y: 0, width: 390, height: 844), + keyboardFrameInView: CGRect(x: 0, y: 542, width: 390, height: 302), + safeAreaInsets: .zero, + isHidden: false, + durationSec: 0.0, + timestampSec: 1.0 + ) + vcKb.sampleInsets(timestamp: 1.0) + let kbOccluded = vcKb.selectionOverlay.currentState + requireS3( + !kbOccluded.start_handle.visible && !kbOccluded.end_handle.visible && vcKb.presentedMenuAnchorRect == nil, + "keyboard covering selection must hide handles and presentedMenuAnchorRect" + ) + vcKb.textHostView.copy(nil) + requireS3(vcKb.textHostView.lastCopiedText == bottomWord, "selection and copy must stay intact while keyboard occludes") + + _ = vcKb.keyboardCoordinator.applyKeyboardFrame( + windowBounds: CGRect(x: 0, y: 0, width: 390, height: 844), + keyboardFrameInView: CGRect(x: 0, y: 844, width: 390, height: 302), + safeAreaInsets: .zero, + isHidden: true, + durationSec: 0.0, + timestampSec: 2.0 + ) + vcKb.sampleInsets(timestamp: 2.0) + let kbRestored = vcKb.selectionOverlay.currentState + requireS3( + kbRestored.start_handle.visible && kbRestored.end_handle.visible && vcKb.presentedMenuAnchorRect != nil, + "dismissing keyboard must restore handles and presentedMenuAnchorRect" + ) + + // 5f. Optional offscreen visual evidence capture directly from real production host views + // (using the production `#FAFAFC` clear color with zero test background overrides). + if let outPath = ProcessInfo.processInfo.environment["AFFINE_IOS_EVIDENCE_PNG"], !outPath.isEmpty { + let evVcTop = MetalHostViewController() + evVcTop.view.frame = CGRect(x: 0, y: 0, width: 390, height: 300) + evVcTop.loadViewIfNeeded() + evVcTop.view.layoutIfNeeded() + let topText = "AFFiNE Native iOS — CoreText & Loupe\n\n\n\n\n\nHello world\n\nשלום 123 abc\nسلام 123 abc" + evVcTop.textHostView.insertText(topText) + let selStart = ("AFFiNE Native iOS — CoreText & Loupe\n\n\n\n\n\n" as NSString).length + evVcTop.textHostView.selectedTextRange = AffineTextRange(utf16Range: NSRange(location: selStart, length: 11)) + let evState = evVcTop.selectionOverlay.currentState + let evDrop = CGPoint(x: CGFloat(evState.end_handle.drop_center_x), y: CGFloat(evState.end_handle.drop_center_y)) + _ = evVcTop.selectionOverlay.processDragStep(phase: .began, point: evDrop) + _ = evVcTop.selectionOverlay.processDragStep(phase: .changed, point: evDrop) + + let evVcBidi = MetalHostViewController() + evVcBidi.view.frame = CGRect(x: 0, y: 0, width: 390, height: 80) + evVcBidi.loadViewIfNeeded() + evVcBidi.view.layoutIfNeeded() + evVcBidi.textHostView.insertText("A אבג B") + evVcBidi.textHostView.selectedTextRange = AffineTextRange(utf16Range: NSRange(location: 2, length: 3)) + + let fmt = UIGraphicsImageRendererFormat() + fmt.scale = 2.0 + fmt.opaque = true + let renderer = UIGraphicsImageRenderer(size: CGSize(width: 390, height: 380), format: fmt) + let shot = renderer.image { ctx in + evVcTop.view.layer.render(in: ctx.cgContext) + ctx.cgContext.saveGState() + ctx.cgContext.translateBy(x: 0, y: 300) + evVcBidi.view.layer.render(in: ctx.cgContext) + ctx.cgContext.restoreGState() + } + if let png = shot.pngData() { + try? png.write(to: URL(fileURLWithPath: outPath)) + } + } + print("PASS [5/5]: MetalHostViewController E2E selection, crossover, RTL/soft-wrap, real loupe glyphs, and keyboard occlusion/restore passed") + } +}