diff --git a/packages/frontend/hosts/ios/AGENTS.md b/packages/frontend/hosts/ios/AGENTS.md index 89100c9fc7..0407086e85 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`, `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. +It bridges `UIKit`, `CAMetalLayer`, ProMotion `CADisplayLink`, `UITextInput`, system `UITextInteraction` (`.editable` / `.nonEditable`) + `UIEditMenuInteraction`, 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,7 +10,7 @@ It bridges `UIKit`, `CAMetalLayer`, ProMotion `CADisplayLink`, `UITextInput`, na - 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 render the live pure-Rust GPU `PlaygroundView` directly through `IosEditorPlatform` + `MetalRenderer`'s `CAMetalLayer` (`affine_ios_host_metal_layer`) with zero `HostTextPreviewView` subview mounted in `MetalHostViewController` and zero host-side `backingText` copy (`UITextInput` reads directly from `PlatformInputHandler` via `affine_ios_host_utf16_len`/`copy_utf16` and receives editor mutations through `affine_ios_host_set_text_input_callback`). +- Drive iOS text selection, handles, loupe, and edit menus through system `UITextInteraction` (`.editable` / `.nonEditable`) + `UIEditMenuInteraction` over full-document `AffineTextPosition` / `AffineTextRange` value semantics (`isEqual:`/`hash`, `affine_ios_host_doc_document_bounds`, zero synchronous `inputDelegate` echo in `setSelectedTextRange:`) with zero `SelectionOverlayView`, rendering the live pure-Rust GPU `PlaygroundView` directly through `IosEditorPlatform` + `MetalRenderer`'s `CAMetalLayer` (`affine_ios_host_metal_layer`) with zero `HostTextPreviewView` subview mounted in `MetalHostViewController` and zero host-side `backingText` copy (`UITextInput` reads directly from `PlatformInputHandler` via `affine_ios_host_utf16_len`/`copy_utf16` and receives editor mutations through `affine_ios_host_set_text_input_callback`). - Stage-1 touch defaults apply via `FormFactor::from_ios_idiom` (`UIDevice.current.userInterfaceIdiom == .pad` -> `Tablet`, otherwise `Phone`): `edgeless_readonly = true`, `database_readonly = true`, `page_readonly = false`. - Use `scripts/package-sim-app.sh` to assemble an installable `AffineIosHost.app` bundle for the iOS Simulator. - 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. diff --git a/packages/frontend/hosts/ios/Sources/MetalHostViewController.swift b/packages/frontend/hosts/ios/Sources/MetalHostViewController.swift index 9c728649c2..3221039f3c 100644 --- a/packages/frontend/hosts/ios/Sources/MetalHostViewController.swift +++ b/packages/frontend/hosts/ios/Sources/MetalHostViewController.swift @@ -1,33 +1,331 @@ import QuartzCore import UIKit +import UniformTypeIdentifiers + +private let affineBlocksuiteSnapshotUti = "pro.affine.blocksuite-snapshot" +private let affineMarkdownUti = "net.daringfireball.markdown" +private let affineHasSystemPasteboardRunLoop: Bool = (Bundle.main.bundleIdentifier != nil) +private var affineHeadlessPasteboard: [String: String] = [:] + +private func affineIosHasPasteboardContent() -> Bool { + guard affineHasSystemPasteboardRunLoop else { + return !affineHeadlessPasteboard.isEmpty + } + let pb = UIPasteboard.general + if pb.hasStrings { + return true + } + return pb.contains(pasteboardTypes: [ + affineBlocksuiteSnapshotUti, + UTType.html.identifier, + affineMarkdownUti, + UTType.utf8PlainText.identifier, + UTType.plainText.identifier, + ]) +} + +private func affineIosWriteSystemPasteboard(_ dict: [String: String]) { + var item: [String: Any] = [:] + if let plain = dict["text/plain"] { + item[UTType.utf8PlainText.identifier] = plain + item[UTType.plainText.identifier] = plain + } + if let html = dict["text/html"], let htmlData = html.data(using: .utf8) { + item[UTType.html.identifier] = htmlData + } + if let md = dict["text/markdown"], let mdData = md.data(using: .utf8) { + item[affineMarkdownUti] = mdData + } + if let snap = dict["application/x-blocksuite-snapshot"], let snapData = snap.data(using: .utf8) { + item[affineBlocksuiteSnapshotUti] = snapData + } + if !item.isEmpty { + UIPasteboard.general.setItems([item], options: [:]) + } +} + +private func affineIosClipboardWriteTrampoline( + _ utf8Ptr: UnsafePointer?, + _ utf8Len: Int, + _ userData: UnsafeMutableRawPointer? +) { + guard let utf8Ptr, utf8Len > 0 else { return } + let data = Data(bytes: utf8Ptr, count: utf8Len) + guard + let obj = try? JSONSerialization.jsonObject(with: data, options: []), + let dict = obj as? [String: String] + else { + return + } + let changeCount: Int + if affineHasSystemPasteboardRunLoop { + affineIosWriteSystemPasteboard(dict) + changeCount = UIPasteboard.general.changeCount + } else { + affineHeadlessPasteboard = dict + changeCount = 1 + } + if let userData { + let controller = Unmanaged.fromOpaque(userData).takeUnretainedValue() + controller.recordLastWrittenClipboard(dict, changeCount: changeCount) + } +} + +private func affineIosClipboardReadTrampoline( + _ sink: AffineClipboardReadSinkFn?, + _ ctx: UnsafeMutableRawPointer?, + _ userData: UnsafeMutableRawPointer? +) { + guard let sink else { return } + var dict: [String: String] = [:] + if affineHasSystemPasteboardRunLoop { + let pb = UIPasteboard.general + if let plain = pb.string, !plain.isEmpty { + dict["text/plain"] = plain + } + if let htmlData = pb.data(forPasteboardType: UTType.html.identifier), + let html = String(data: htmlData, encoding: .utf8), + !html.isEmpty + { + dict["text/html"] = html + } + if let mdData = pb.data(forPasteboardType: affineMarkdownUti), + let md = String(data: mdData, encoding: .utf8), + !md.isEmpty + { + dict["text/markdown"] = md + } + if let snapData = pb.data(forPasteboardType: affineBlocksuiteSnapshotUti), + let snap = String(data: snapData, encoding: .utf8), + !snap.isEmpty + { + dict["application/x-blocksuite-snapshot"] = snap + } + if dict.isEmpty, let userData { + let controller = Unmanaged.fromOpaque(userData).takeUnretainedValue() + if pb.changeCount == controller.lastWrittenPasteboardChangeCount { + dict = controller.lastWrittenClipboard + } + } + } else { + dict = affineHeadlessPasteboard + } + guard + !dict.isEmpty, + let encoded = try? JSONSerialization.data(withJSONObject: dict, options: []) + else { + return + } + encoded.withUnsafeBytes { raw in + if let base = raw.bindMemory(to: UInt8.self).baseAddress { + sink(base, encoded.count, ctx) + } + } +} final class AffineTextPosition: UITextPosition { let utf16Offset: Int + let blockOrder: Int32 + let endpointToken: UInt64 - init(utf16Offset: Int) { + init( + utf16Offset: Int, + blockOrder: Int32 = -1, + endpointToken: UInt64 = 0 + ) { self.utf16Offset = max(0, utf16Offset) + self.blockOrder = blockOrder + self.endpointToken = endpointToken super.init() } + + static func from(_ raw: AffineDocPosition) -> AffineTextPosition { + AffineTextPosition( + utf16Offset: Int(raw.utf16_offset), + blockOrder: raw.block_order, + endpointToken: raw.endpoint_token + ) + } + + override func isEqual(_ object: Any?) -> Bool { + guard let other = object as? AffineTextPosition else { + return false + } + if self === other { + return true + } + if endpointToken != 0 || other.endpointToken != 0 { + return endpointToken == other.endpointToken + } + return blockOrder == other.blockOrder && utf16Offset == other.utf16Offset + } + + override var hash: Int { + var hasher = Hasher() + if endpointToken != 0 { + hasher.combine(1) + hasher.combine(endpointToken) + } else { + hasher.combine(0) + hasher.combine(blockOrder) + hasher.combine(utf16Offset) + } + return hasher.finalize() + } } final class AffineTextRange: UITextRange { - let utf16Range: NSRange + let startPos: AffineTextPosition + let endPos: AffineTextPosition - init(utf16Range: NSRange) { - self.utf16Range = utf16Range + var utf16Range: NSRange { + if startPos.blockOrder == endPos.blockOrder + || startPos.blockOrder == -1 + || endPos.blockOrder == -1 + { + let lo = min(startPos.utf16Offset, endPos.utf16Offset) + let hi = max(startPos.utf16Offset, endPos.utf16Offset) + return NSRange(location: lo, length: hi - lo) + } + return NSRange(location: max(0, startPos.utf16Offset), length: 1) + } + + convenience init(utf16Range: NSRange, blockOrder: Int32 = -1) { + self.init( + startPos: AffineTextPosition(utf16Offset: utf16Range.location, blockOrder: blockOrder), + endPos: AffineTextPosition( + utf16Offset: utf16Range.location + utf16Range.length, + blockOrder: blockOrder + ) + ) + } + + init(startPos: AffineTextPosition, endPos: AffineTextPosition) { + self.startPos = startPos + self.endPos = endPos super.init() } override var start: UITextPosition { - AffineTextPosition(utf16Offset: utf16Range.location) + startPos } override var end: UITextPosition { - AffineTextPosition(utf16Offset: utf16Range.location + utf16Range.length) + endPos } override var isEmpty: Bool { - utf16Range.length == 0 + startPos.isEqual(endPos) + } + + override func isEqual(_ object: Any?) -> Bool { + guard let other = object as? AffineTextRange else { + return false + } + if self === other { + return true + } + return startPos.isEqual(other.startPos) && endPos.isEqual(other.endPos) + } + + override var hash: Int { + var hasher = Hasher() + hasher.combine(startPos.hash) + hasher.combine(endPos.hash) + return hasher.finalize() + } +} + +private final class AffineDocTextTokenizer: UITextInputStringTokenizer { + private weak var hostView: MetalHostView? + + init(hostView: MetalHostView) { + self.hostView = hostView + super.init(textInput: hostView) + } + + private func enclosingTokenRange( + for pos: AffineTextPosition, + granularity: UITextGranularity, + view: MetalHostView + ) -> AffineTextRange? { + guard pos.endpointToken != 0 else { + return nil + } + switch granularity { + case .word: + return view.wordRange(at: pos) + case .character: + return view.characterUnitRange(at: pos) + case .line: + return view.visualLineRange(at: pos) + case .paragraph, .sentence: + return view.blockParagraphRange(at: pos) + default: + return nil + } + } + + override func rangeEnclosingPosition( + _ position: UITextPosition, + with granularity: UITextGranularity, + inDirection direction: UITextDirection + ) -> UITextRange? { + if let pos = position as? AffineTextPosition, + let view = hostView, + let range = enclosingTokenRange(for: pos, granularity: granularity, view: view) + { + return range + } + return super.rangeEnclosingPosition(position, with: granularity, inDirection: direction) + } + + override func isPosition( + _ position: UITextPosition, + atBoundary granularity: UITextGranularity, + inDirection direction: UITextDirection + ) -> Bool { + if let pos = position as? AffineTextPosition, + let view = hostView, + let range = enclosingTokenRange(for: pos, granularity: granularity, view: view) + { + let backward = direction.rawValue == UITextStorageDirection.backward.rawValue + || direction.rawValue == UITextLayoutDirection.left.rawValue + return backward + ? view.compare(pos, to: range.start) == .orderedSame + : view.compare(pos, to: range.end) == .orderedSame + } + return super.isPosition(position, atBoundary: granularity, inDirection: direction) + } + + override func isPosition( + _ position: UITextPosition, + withinTextUnit granularity: UITextGranularity, + inDirection direction: UITextDirection + ) -> Bool { + if let pos = position as? AffineTextPosition, + let view = hostView, + enclosingTokenRange(for: pos, granularity: granularity, view: view) != nil + { + return true + } + return super.isPosition(position, withinTextUnit: granularity, inDirection: direction) + } + + override func position( + from position: UITextPosition, + toBoundary granularity: UITextGranularity, + inDirection direction: UITextDirection + ) -> UITextPosition? { + if let pos = position as? AffineTextPosition, + let view = hostView, + let range = enclosingTokenRange(for: pos, granularity: granularity, view: view) + { + let backward = direction.rawValue == UITextStorageDirection.backward.rawValue + || direction.rawValue == UITextLayoutDirection.left.rawValue + return backward ? range.startPos : range.endPos + } + return super.position(from: position, toBoundary: granularity, inDirection: direction) } } @@ -35,11 +333,18 @@ final class AffineTextSelectionRect: UITextSelectionRect { private let selectionRect: CGRect private let isStart: Bool private let isEnd: Bool + private let dir: NSWritingDirection - init(rect: CGRect, containsStart: Bool, containsEnd: Bool) { + init( + rect: CGRect, + containsStart: Bool, + containsEnd: Bool, + writingDirection: NSWritingDirection = .leftToRight + ) { self.selectionRect = rect self.isStart = containsStart self.isEnd = containsEnd + self.dir = writingDirection super.init() } @@ -48,7 +353,7 @@ final class AffineTextSelectionRect: UITextSelectionRect { } override var writingDirection: NSWritingDirection { - .natural + dir } override var containsStart: Bool { @@ -127,13 +432,35 @@ final class MetalHostView: UIView, UITextInput { } weak var inputDelegate: UITextInputDelegate? - lazy var tokenizer: UITextInputTokenizer = UITextInputStringTokenizer(textInput: self) + lazy var tokenizer: UITextInputTokenizer = AffineDocTextTokenizer(hostView: self) var hostHandle: OpaquePointer? var onSelectedRangeChanged: ((NSRange) -> Void)? + var onSystemSelectionApplied: (() -> Void)? var onInteractionWake: (() -> Void)? + var onDismissEditMenu: (() -> Void)? + var onFallbackCopiedText: (() -> String?)? + var onQuerySystemGestureActive: (() -> Bool)? + var onQueryShouldLetTextInteractionOwnTouch: ((CGPoint) -> Bool)? + var onDidMoveToWindow: (() -> Void)? private(set) var lastCopiedText: String? - private var lastWantsCodeInput: Bool = false + private(set) var editorInputNotificationCount: Int = 0 + + private let emptyInputView = UIView(frame: .zero) + private var lastWantsSoftwareKeyboard = true + private var lastWantsCodeInput = false + private(set) var isInsideImeMutation = false + private(set) var isApplyingSystemSelection = false + private var pendingExternalChangeKind: UInt8 = 0 + private var activeTouchIds: [ObjectIdentifier: UInt64] = [:] + private var touchStartPoints: [UInt64: CGPoint] = [:] + private var touchStartTimes: [UInt64: Double] = [:] + private var touchExceededPanThreshold: Set = [] + private var touchForwardedToRust: Set = [] + private var nextTouchId: UInt64 = 1 + private(set) var lastTouchDownTimestamp: Double = 0 + private(set) var lastTouchUpTimestamp: Double = 0 + private(set) var lastTouchTapCount: Int = 1 private var wantsCodeInput: Bool { guard let handle = hostHandle else { @@ -172,15 +499,6 @@ final class MetalHostView: UIView, UITextInput { } } - private(set) var editorInputNotificationCount: Int = 0 - - private var isInsideImeMutation = false - private var pendingExternalChangeKind: UInt8 = 0 - private var activeTouchIds: [ObjectIdentifier: UInt64] = [:] - private var touchStartPoints: [UInt64: CGPoint] = [:] - private var touchExceededPanThreshold: Set = [] - private var nextTouchId: UInt64 = 1 - /// Authoritative UTF-16 code units read directly from Rust `PlatformInputHandler` (zero host copy). var currentAuthoritativeUtf16Units: [UInt16] { guard let handle = hostHandle else { @@ -240,8 +558,12 @@ final class MetalHostView: UIView, UITextInput { affine_ios_host_set_open_url_callback(handle, nil, nil) } - /// H-S2: Editor-initiated content/selection change notifies `UITextInputDelegate` and overlay. + /// H-S2: Editor-initiated content/selection change notifies `UITextInputDelegate`. + /// Suppressed during UIKit-initiated `setSelectedTextRange:` (Single-Writer invariant). func handleEditorTextInputStateChanged(kind: UInt8) { + if isApplyingSystemSelection { + return + } if isInsideImeMutation { pendingExternalChangeKind = max(pendingExternalChangeKind, kind) return @@ -250,6 +572,9 @@ final class MetalHostView: UIView, UITextInput { } private func notifyInputDelegate(kind: UInt8) { + guard !isApplyingSystemSelection else { + return + } editorInputNotificationCount += 1 if kind == 4 { inputDelegate?.textWillChange(self) @@ -262,8 +587,10 @@ final class MetalHostView: UIView, UITextInput { } onSelectedRangeChanged?(currentSelectedUtf16Range) syncCodeInputTraitsIfNeeded() + syncKeyboardInputViewIfNeeded() if let handle = hostHandle, !affine_ios_host_wants_software_keyboard(handle), + !affine_ios_host_document_selection_snapshot(handle).has_selection, isFirstResponder { _ = resignFirstResponder() @@ -297,10 +624,9 @@ final class MetalHostView: UIView, UITextInput { } /// UIKit forbids calling `inputDelegate.textWillChange/textDidChange` in response to - /// mutations initiated by the text input system itself (otherwise Pinyin/Kana IME - /// resets composition on every keystroke). Only notify `inputDelegate` when the editor - /// performed an unexpected extra transform (e.g. Markdown `# ` heading conversion or - /// block split/merge). + /// mutations initiated by the text input system itself. Only notify `inputDelegate` when + /// the editor performed an unexpected extra transform (e.g. Markdown `# ` heading conversion + /// or block split/merge). private func performImeMutation( expectedUnits: [UInt16]? = nil, expectedSelected: NSRange? = nil, @@ -336,71 +662,140 @@ final class MetalHostView: UIView, UITextInput { onInteractionWake?() } - func updateSelectedRangeFromOverlay(_ range: NSRange) { - guard let handle = hostHandle else { - return - } - let clamped = clampRange(range) - performImeMutation { - 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 currentSelectedUtf16Range.length > 0 + guard let handle = hostHandle else { + return super.canPerformAction(action, withSender: sender) + } + let mask = affine_ios_host_document_selection_snapshot(handle).action_mask + if action == #selector(copy(_:)) { + return (mask & 1) != 0 + } + if action == #selector(cut(_:)) { + return (mask & 2) != 0 } if action == #selector(paste(_:)) { - return UIPasteboard.general.hasStrings + return (mask & 4) != 0 && affineIosHasPasteboardContent() } if action == #selector(selectAll(_:)) { - return hasText + return (mask & 8) != 0 + } + if action == #selector(select(_:)) { + let snap = affine_ios_host_document_selection_snapshot(handle) + return snap.has_selection && snap.is_collapsed && affine_ios_host_utf16_len(handle) > 0 } return super.canPerformAction(action, withSender: sender) } override func copy(_ sender: Any?) { - let clamped = currentSelectedUtf16Range - guard clamped.length > 0 else { + guard let handle = hostHandle else { return } - let copied = currentAuthoritativeString.substring(with: clamped) - lastCopiedText = copied - UIPasteboard.general.string = copied + affine_ios_host_selection_action_copy(handle) + lastCopiedText = onFallbackCopiedText?() + onDismissEditMenu?() + onInteractionWake?() } override func cut(_ sender: Any?) { - let clamped = currentSelectedUtf16Range - guard clamped.length > 0 else { + guard let handle = hostHandle else { return } - copy(sender) - deleteBackward() + affine_ios_host_selection_action_cut(handle) + lastCopiedText = onFallbackCopiedText?() + onDismissEditMenu?() + onInteractionWake?() } override func paste(_ sender: Any?) { - guard let text = UIPasteboard.general.string, !text.isEmpty else { + guard let handle = hostHandle else { return } - insertText(text) + affine_ios_host_selection_action_paste(handle) + onDismissEditMenu?() + onInteractionWake?() } override func selectAll(_ sender: Any?) { - let len = Int(hostHandle.map { affine_ios_host_utf16_len($0) } ?? 0) - selectedTextRange = AffineTextRange(utf16Range: NSRange(location: 0, length: len)) + guard let handle = hostHandle else { + return + } + affine_ios_host_selection_action_select_all(handle) + onInteractionWake?() + } + + override func select(_ sender: Any?) { + guard let handle = hostHandle else { + return + } + let snap = affine_ios_host_document_selection_snapshot(handle) + if snap.has_selection { + _ = affine_ios_host_select_word_at_point( + handle, + snap.start_caret.x, + snap.start_caret.y + max(snap.start_caret.height * 0.5, 4.0) + ) + onInteractionWake?() + } } override var canBecomeFirstResponder: Bool { true } + override func becomeFirstResponder() -> Bool { + if let handle = hostHandle, !affine_ios_host_is_surface_readonly(handle) { + affine_ios_host_restore_software_keyboard(handle) + lastWantsSoftwareKeyboard = true + } + return super.becomeFirstResponder() + } + + override var inputView: UIView? { + guard let handle = hostHandle else { + return nil + } + if affine_ios_host_is_surface_readonly(handle) { + return emptyInputView + } + return affine_ios_host_wants_software_keyboard(handle) ? nil : emptyInputView + } + + func syncKeyboardInputViewIfNeeded() { + guard let handle = hostHandle else { + return + } + let wants = !affine_ios_host_is_surface_readonly(handle) + && affine_ios_host_wants_software_keyboard(handle) + if wants != lastWantsSoftwareKeyboard { + lastWantsSoftwareKeyboard = wants + if isFirstResponder { + reloadInputViews() + } + } + } + + func notifySystemSelectionUpdated() { + guard !isInsideImeMutation && !isApplyingSystemSelection else { + return + } + inputDelegate?.selectionWillChange(self) + inputDelegate?.selectionDidChange(self) + } + var hasText: Bool { guard let handle = hostHandle else { return false } + var sRaw = AffineDocPosition() + var eRaw = AffineDocPosition() + if affine_ios_host_doc_document_bounds(handle, &sRaw, &eRaw), + sRaw.valid, + eRaw.valid, + sRaw.endpoint_token != 0, + eRaw.endpoint_token != 0 + { + return sRaw.endpoint_token != eRaw.endpoint_token + } return affine_ios_host_utf16_len(handle) > 0 } @@ -447,10 +842,232 @@ final class MetalHostView: UIView, UITextInput { } } + private var hasCrossBlockSelectionOnEmptyFocus: Bool { + guard let handle = hostHandle, affine_ios_host_utf16_len(handle) == 0 else { + return false + } + let snap = affine_ios_host_document_selection_snapshot(handle) + return snap.has_selection && !snap.is_collapsed + } + + private var effectiveDocumentUtf16Length: Int { + guard let handle = hostHandle else { + return 0 + } + let raw = Int(affine_ios_host_utf16_len(handle)) + if raw == 0 && hasCrossBlockSelectionOnEmptyFocus { + return 1 + } + return raw + } + + /// Single-Writer system selection apply: commits UIKit's `selectedTextRange` into Rust and + /// updates host signature/menu state WITHOUT synchronously echoing back into `inputDelegate`. + private func applySystemSelectionMutation(_ body: () -> Void) { + let wasApplying = isApplyingSystemSelection + let wasInside = isInsideImeMutation + isApplyingSystemSelection = true + isInsideImeMutation = true + pendingExternalChangeKind = 0 + body() + if !wasApplying { + onSystemSelectionApplied?() + syncCodeInputTraitsIfNeeded() + } + isApplyingSystemSelection = wasApplying + isInsideImeMutation = wasInside + pendingExternalChangeKind = 0 + } + + private var currentFocusedBlockOrder: Int32 { + guard let handle = hostHandle else { + return 0 + } + return affine_ios_host_focused_block_order(handle) + } + + private func resolvedBlockOrder(for pos: AffineTextPosition) -> Int32 { + pos.blockOrder >= 0 ? pos.blockOrder : currentFocusedBlockOrder + } + + private func resolvedEndpointToken(for pos: AffineTextPosition) -> UInt64 { + if pos.endpointToken != 0 { + return pos.endpointToken + } + guard let handle = hostHandle else { + return 0 + } + var sRaw = AffineDocPosition() + var eRaw = AffineDocPosition() + if affine_ios_host_doc_selection_positions(handle, &sRaw, &eRaw), + sRaw.valid, + sRaw.block_order == resolvedBlockOrder(for: pos) + { + let delta = pos.utf16Offset - Int(sRaw.utf16_offset) + if delta == 0 { + return sRaw.endpoint_token + } + let stepped = affine_ios_host_doc_step_position(handle, sRaw.endpoint_token, delta) + if stepped.valid { + return stepped.endpoint_token + } + } + var docStart = AffineDocPosition() + var docEnd = AffineDocPosition() + if affine_ios_host_doc_document_bounds(handle, &docStart, &docEnd), + docStart.valid, + pos.blockOrder <= 0 + { + if pos.utf16Offset == 0 { + return docStart.endpoint_token + } + let stepped = affine_ios_host_doc_step_position(handle, docStart.endpoint_token, pos.utf16Offset) + if stepped.valid { + return stepped.endpoint_token + } + } + return 0 + } + + func wordRange(at pos: AffineTextPosition) -> AffineTextRange? { + guard let handle = hostHandle else { + return nil + } + let tok = resolvedEndpointToken(for: pos) + guard tok != 0 else { + return nil + } + var sRaw = AffineDocPosition() + var eRaw = AffineDocPosition() + guard affine_ios_host_doc_word_range(handle, tok, &sRaw, &eRaw), + sRaw.valid, + eRaw.valid + else { + return nil + } + return AffineTextRange(startPos: .from(sRaw), endPos: .from(eRaw)) + } + + func characterUnitRange(at pos: AffineTextPosition) -> AffineTextRange? { + let tok = resolvedEndpointToken(for: pos) + guard tok != 0 else { + return nil + } + let anchoredPos = pos.endpointToken != 0 + ? pos + : AffineTextPosition(utf16Offset: pos.utf16Offset, blockOrder: pos.blockOrder, endpointToken: tok) + if let para = blockParagraphRange(at: anchoredPos), + let paraText = text(in: para) + { + let nsText = paraText as NSString + if nsText.length == 0 { + return AffineTextRange(startPos: anchoredPos, endPos: anchoredPos) + } + let localOffset = max(0, min(anchoredPos.utf16Offset, nsText.length)) + let probeIndex = localOffset < nsText.length ? localOffset : nsText.length - 1 + let composed = nsText.rangeOfComposedCharacterSequence(at: probeIndex) + if let startPos = position(from: para.startPos, offset: composed.location) as? AffineTextPosition, + let endPos = position(from: para.startPos, offset: composed.location + composed.length) as? AffineTextPosition + { + return AffineTextRange(startPos: startPos, endPos: endPos) + } + } + if let next1 = position(from: anchoredPos, offset: 1) as? AffineTextPosition { + return AffineTextRange(startPos: anchoredPos, endPos: next1) + } + if let prev1 = position(from: anchoredPos, offset: -1) as? AffineTextPosition { + return AffineTextRange(startPos: prev1, endPos: anchoredPos) + } + return AffineTextRange(startPos: anchoredPos, endPos: anchoredPos) + } + + func blockParagraphRange(at pos: AffineTextPosition) -> AffineTextRange? { + let tok = resolvedEndpointToken(for: pos) + guard tok != 0 else { + return nil + } + let anchoredPos = pos.endpointToken != 0 + ? pos + : AffineTextPosition(utf16Offset: pos.utf16Offset, blockOrder: pos.blockOrder, endpointToken: tok) + let startPos = (position(from: anchoredPos, offset: -anchoredPos.utf16Offset) as? AffineTextPosition) ?? anchoredPos + var endPos = anchoredPos + for step in [256, 64, 16, 4, 1] { + while let next = position(from: endPos, offset: step) as? AffineTextPosition, + next.blockOrder == anchoredPos.blockOrder + { + endPos = next + } + } + return AffineTextRange(startPos: startPos, endPos: endPos) + } + + func visualLineRange(at pos: AffineTextPosition) -> AffineTextRange? { + guard let para = blockParagraphRange(at: pos) else { + return nil + } + let baseRect = caretRect(for: pos) + let tol = max(baseRect.height * 0.45, 6.0) + let curOff = pos.utf16Offset + let maxOff = para.endPos.utf16Offset + var lo = 0 + var hi = curOff + var lineStart = pos + while lo <= hi { + let mid = (lo + hi) / 2 + if let cand = position(from: para.startPos, offset: mid) as? AffineTextPosition, + abs(caretRect(for: cand).midY - baseRect.midY) <= tol + { + lineStart = cand + if mid == 0 { break } + hi = mid - 1 + } else { + lo = mid + 1 + } + } + lo = curOff + hi = maxOff + var lineEnd = pos + while lo <= hi { + let mid = (lo + hi) / 2 + if let cand = position(from: para.startPos, offset: mid) as? AffineTextPosition, + abs(caretRect(for: cand).midY - baseRect.midY) <= tol + { + lineEnd = cand + lo = mid + 1 + } else { + if mid == 0 { break } + hi = mid - 1 + } + } + return AffineTextRange(startPos: lineStart, endPos: lineEnd) + } + func text(in range: UITextRange) -> String? { guard let affineRange = range as? AffineTextRange else { return nil } + let sTok = resolvedEndpointToken(for: affineRange.startPos) + let eTok = resolvedEndpointToken(for: affineRange.endPos) + if let handle = hostHandle, sTok != 0, eTok != 0 { + if sTok == eTok { + return "" + } + if let rawPtr = affine_ios_host_doc_text_between_tokens(handle, sTok, eTok) { + defer { affine_ios_string_free(rawPtr) } + return String(cString: rawPtr) + } + return "" + } + if let handle = hostHandle, currentSelectedUtf16Range.length == 0 { + let snap = affine_ios_host_document_selection_snapshot(handle) + if snap.has_selection && !snap.is_collapsed && !affineRange.isEmpty { + if let rawPtr = affine_ios_host_selected_plain_text(handle) { + defer { affine_ios_string_free(rawPtr) } + return String(cString: rawPtr) + } + return "\n" + } + } let text = currentAuthoritativeString let clamped = clampRange(affineRange.utf16Range, maxLen: text.length) return text.substring(with: clamped) @@ -460,6 +1077,23 @@ final class MetalHostView: UIView, UITextInput { guard let affineRange = range as? AffineTextRange, let handle = hostHandle else { return } + let sTok = resolvedEndpointToken(for: affineRange.startPos) + let eTok = resolvedEndpointToken(for: affineRange.endPos) + let focusedOrder = currentFocusedBlockOrder + if sTok != 0, + eTok != 0, + resolvedBlockOrder(for: affineRange.startPos) != focusedOrder + || resolvedBlockOrder(for: affineRange.endPos) != focusedOrder + { + performImeMutation { + _ = affine_ios_host_doc_selection_select_between_endpoint_tokens(handle, sTok, eTok) + let utf16 = Array(text.utf16) + utf16.withUnsafeBufferPointer { buf in + affine_ios_host_insert_text(handle, buf.baseAddress, buf.count) + } + } + return + } let clamped = clampRange(affineRange.utf16Range) let utf16 = Array(text.utf16) let before = currentAuthoritativeUtf16Units @@ -477,18 +1111,58 @@ final class MetalHostView: UIView, UITextInput { var selectedTextRange: UITextRange? { get { - AffineTextRange(utf16Range: currentSelectedUtf16Range) + if let handle = hostHandle { + var sRaw = AffineDocPosition() + var eRaw = AffineDocPosition() + if affine_ios_host_doc_selection_positions(handle, &sRaw, &eRaw), + sRaw.valid, + eRaw.valid + { + return AffineTextRange(startPos: .from(sRaw), endPos: .from(eRaw)) + } + } + return AffineTextRange( + utf16Range: currentSelectedUtf16Range, + blockOrder: currentFocusedBlockOrder + ) } set { guard let affineRange = newValue as? AffineTextRange, let handle = hostHandle else { return } + let bumpMenuIfNonCollapsed = { [weak self] in + let snap = affine_ios_host_document_selection_snapshot(handle) + if snap.has_selection && !snap.is_collapsed { + affine_ios_host_bump_selection_menu_request_seq(handle) + DispatchQueue.main.asyncAfter(deadline: .now() + 0.05) { + self?.onInteractionWake?() + } + } + } + let sTok = resolvedEndpointToken(for: affineRange.startPos) + let eTok = resolvedEndpointToken(for: affineRange.endPos) + if sTok != 0 && eTok != 0 { + applySystemSelectionMutation { + var curStart: UInt64 = 0 + var curEnd: UInt64 = 0 + affine_ios_host_doc_selection_endpoint_tokens(handle, &curStart, &curEnd) + let changed = !(curStart == sTok && curEnd == eTok) + _ = affine_ios_host_doc_selection_select_between_endpoint_tokens(handle, sTok, eTok) + if changed && sTok != eTok { + bumpMenuIfNonCollapsed() + } + } + return + } let clamped = clampRange(affineRange.utf16Range) - performImeMutation(expectedUnits: currentAuthoritativeUtf16Units, expectedSelected: clamped) { + applySystemSelectionMutation { affine_ios_host_set_selected_range( handle, AffineUtf16Range(location: UInt32(clamped.location), length: UInt32(clamped.length)) ) + if clamped.length > 0 { + bumpMenuIfNonCollapsed() + } } } } @@ -497,7 +1171,7 @@ final class MetalHostView: UIView, UITextInput { guard let range = currentMarkedUtf16Range else { return nil } - return AffineTextRange(utf16Range: range) + return AffineTextRange(utf16Range: range, blockOrder: currentFocusedBlockOrder) } var markedTextStyle: [NSAttributedString.Key: Any]? @@ -536,12 +1210,28 @@ final class MetalHostView: UIView, UITextInput { } var beginningOfDocument: UITextPosition { - AffineTextPosition(utf16Offset: 0) + if let handle = hostHandle { + var sRaw = AffineDocPosition() + var eRaw = AffineDocPosition() + if affine_ios_host_doc_document_bounds(handle, &sRaw, &eRaw), sRaw.valid { + return AffineTextPosition.from(sRaw) + } + } + return AffineTextPosition(utf16Offset: 0, blockOrder: 0) } var endOfDocument: UITextPosition { - let len = Int(hostHandle.map { affine_ios_host_utf16_len($0) } ?? 0) - return AffineTextPosition(utf16Offset: len) + if let handle = hostHandle { + var sRaw = AffineDocPosition() + var eRaw = AffineDocPosition() + if affine_ios_host_doc_document_bounds(handle, &sRaw, &eRaw), eRaw.valid { + return AffineTextPosition.from(eRaw) + } + } + return AffineTextPosition( + utf16Offset: effectiveDocumentUtf16Length, + blockOrder: currentFocusedBlockOrder + ) } func textRange(from fromPosition: UITextPosition, to toPosition: UITextPosition) -> UITextRange? { @@ -551,21 +1241,32 @@ final class MetalHostView: UIView, UITextInput { else { return nil } - let start = min(from.utf16Offset, to.utf16Offset) - let end = max(from.utf16Offset, to.utf16Offset) - return AffineTextRange(utf16Range: clampRange(NSRange(location: start, length: end - start))) + if compare(from, to: to) != .orderedDescending { + return AffineTextRange(startPos: from, endPos: to) + } + return AffineTextRange(startPos: to, endPos: from) } func position(from position: UITextPosition, offset: Int) -> UITextPosition? { guard let pos = position as? AffineTextPosition else { return nil } - let maxLen = Int(hostHandle.map { affine_ios_host_utf16_len($0) } ?? 0) + if offset == 0 { + return pos + } + if let handle = hostHandle { + let tok = resolvedEndpointToken(for: pos) + if tok != 0 { + let stepped = affine_ios_host_doc_step_position(handle, tok, offset) + return stepped.valid ? AffineTextPosition.from(stepped) : nil + } + } + let maxLen = effectiveDocumentUtf16Length let next = pos.utf16Offset + offset guard next >= 0 && next <= maxLen else { return nil } - return AffineTextPosition(utf16Offset: next) + return AffineTextPosition(utf16Offset: next, blockOrder: resolvedBlockOrder(for: pos)) } func position( @@ -573,8 +1274,25 @@ final class MetalHostView: UIView, UITextInput { in direction: UITextLayoutDirection, offset: Int ) -> UITextPosition? { - let signedOffset = (direction == .left || direction == .up) ? -offset : offset - return self.position(from: position, offset: signedOffset) + guard let pos = position as? AffineTextPosition else { + return nil + } + if offset == 0 { + return pos + } + switch direction { + case .left: + return self.position(from: pos, offset: -offset) + case .right: + return self.position(from: pos, offset: offset) + case .up, .down: + let cr = caretRect(for: pos) + let lineStep = max(cr.height, 22.0) * CGFloat(offset) + let dy = direction == .up ? -lineStep : lineStep + return closestPosition(to: CGPoint(x: cr.midX, y: cr.midY + dy)) + @unknown default: + return self.position(from: pos, offset: offset) + } } func compare(_ position: UITextPosition, to other: UITextPosition) -> ComparisonResult { @@ -584,6 +1302,11 @@ final class MetalHostView: UIView, UITextInput { else { return .orderedSame } + let lo = resolvedBlockOrder(for: lhs) + let ro = resolvedBlockOrder(for: rhs) + if lo != ro { + return lo < ro ? .orderedAscending : .orderedDescending + } if lhs.utf16Offset < rhs.utf16Offset { return .orderedAscending } @@ -600,7 +1323,19 @@ final class MetalHostView: UIView, UITextInput { else { return 0 } - return end.utf16Offset - start.utf16Offset + let so = resolvedBlockOrder(for: start) + let eo = resolvedBlockOrder(for: end) + if so == eo { + return end.utf16Offset - start.utf16Offset + } + if let handle = hostHandle { + let sTok = resolvedEndpointToken(for: start) + let eTok = resolvedEndpointToken(for: end) + if sTok != 0 && eTok != 0 { + return Int(affine_ios_host_doc_offset_between_tokens(handle, sTok, eTok)) + } + } + return Int(eo - so) * 1024 + (end.utf16Offset - start.utf16Offset) } func position( @@ -612,11 +1347,11 @@ final class MetalHostView: UIView, UITextInput { } switch direction { case .left, .up: - return affineRange.start + return affineRange.startPos case .right, .down: - return affineRange.end + return affineRange.endPos @unknown default: - return affineRange.start + return affineRange.startPos } } @@ -627,18 +1362,34 @@ final class MetalHostView: UIView, UITextInput { guard let pos = position as? AffineTextPosition else { return nil } + if pos.endpointToken != 0 { + switch direction { + case .left, .up: + if let start = self.position(from: pos, offset: -pos.utf16Offset) as? AffineTextPosition { + return AffineTextRange(startPos: start, endPos: pos) + } + case .right, .down: + if let para = blockParagraphRange(at: pos) { + return AffineTextRange(startPos: pos, endPos: para.endPos) + } + @unknown default: + break + } + } let maxLen = Int(hostHandle.map { affine_ios_host_utf16_len($0) } ?? 0) switch direction { case .left, .up: return AffineTextRange( - utf16Range: clampRange(NSRange(location: 0, length: pos.utf16Offset), maxLen: maxLen) + utf16Range: clampRange(NSRange(location: 0, length: pos.utf16Offset), maxLen: maxLen), + blockOrder: resolvedBlockOrder(for: pos) ) case .right, .down: return AffineTextRange( utf16Range: clampRange( NSRange(location: pos.utf16Offset, length: max(0, maxLen - pos.utf16Offset)), maxLen: maxLen - ) + ), + blockOrder: resolvedBlockOrder(for: pos) ) @unknown default: return nil @@ -658,21 +1409,13 @@ final class MetalHostView: UIView, UITextInput { 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 + if affineRange.isEmpty { + return caretRect(for: affineRange.startPos) } - 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 - ) + if let first = selectionRects(for: affineRange).first { + return first.rect } - return startRect + return caretRect(for: affineRange.startPos) } func caretRect(for position: UITextPosition) -> CGRect { @@ -682,6 +1425,34 @@ final class MetalHostView: UIView, UITextInput { else { return .zero } + let tok = resolvedEndpointToken(for: pos) + if tok != 0 { + var tokenRect = AffineRect() + if affine_ios_host_doc_caret_rect_for_token(handle, tok, &tokenRect) { + return CGRect( + x: CGFloat(tokenRect.x), + y: CGFloat(tokenRect.y), + width: CGFloat(max(tokenRect.width, 2.0)), + height: CGFloat(max(tokenRect.height, 18.0)) + ) + } + } + let snap = affine_ios_host_document_selection_snapshot(handle) + if snap.has_selection && snap.is_collapsed { + if pos.utf16Offset == currentSelectedUtf16Range.location + && resolvedBlockOrder(for: pos) == currentFocusedBlockOrder + { + if !snap.start_visible { + return CGRect(x: -1000.0, y: -1000.0, width: 0.0, height: 0.0) + } + return CGRect( + x: CGFloat(snap.start_caret.x), + y: CGFloat(snap.start_caret.y), + width: CGFloat(max(snap.start_caret.width, 2.0)), + height: CGFloat(max(snap.start_caret.height, 18.0)) + ) + } + } let cRect = affine_ios_host_text_caret_rect(handle, UInt32(max(0, pos.utf16Offset))) return CGRect( x: CGFloat(cRect.x), @@ -698,6 +1469,68 @@ final class MetalHostView: UIView, UITextInput { else { return [] } + let sTok = resolvedEndpointToken(for: affineRange.startPos) + let eTok = resolvedEndpointToken(for: affineRange.endPos) + if sTok != 0 && eTok != 0 { + if sTok == eTok { + return [] + } + let count = affine_ios_host_doc_selection_rects_between_tokens(handle, sTok, eTok, nil, 0) + if count > 0 { + var rects = Array(repeating: AffineDocumentSelectionRect(), count: count) + _ = rects.withUnsafeMutableBufferPointer { buf in + affine_ios_host_doc_selection_rects_between_tokens( + handle, + sTok, + eTok, + buf.baseAddress, + count + ) + } + return rects.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, + writingDirection: item.is_rtl ? .rightToLeft : .leftToRight + ) + } + } + return [] + } + let snap = affine_ios_host_document_selection_snapshot(handle) + let cur = currentSelectedUtf16Range + let matchesActiveSelection = snap.has_selection + && !snap.is_collapsed + && snap.rect_count > 0 + && affineRange.utf16Range == cur + if matchesActiveSelection { + let count = affine_ios_host_document_selection_rects(handle, nil, 0) + if count > 0 { + var docRects = Array(repeating: AffineDocumentSelectionRect(), count: count) + _ = docRects.withUnsafeMutableBufferPointer { buf in + affine_ios_host_document_selection_rects(handle, buf.baseAddress, count) + } + return docRects.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, + writingDirection: item.is_rtl ? .rightToLeft : .leftToRight + ) + } + } + } let clamped = clampRange(affineRange.utf16Range) guard clamped.length > 0 else { return [] @@ -711,6 +1544,7 @@ final class MetalHostView: UIView, UITextInput { _ = rawRects.withUnsafeMutableBufferPointer { buf in affine_ios_host_text_selection_rects(handle, cRange, buf.baseAddress, count) } + let dir: NSWritingDirection = currentWritingDirection == 1 ? .rightToLeft : .leftToRight return rawRects.map { item in AffineTextSelectionRect( rect: CGRect( @@ -720,46 +1554,48 @@ final class MetalHostView: UIView, UITextInput { height: CGFloat(item.rect.height) ), containsStart: item.contains_start, - containsEnd: item.contains_end + containsEnd: item.contains_end, + writingDirection: dir ) } } func closestPosition(to point: CGPoint) -> UITextPosition? { guard let handle = hostHandle else { - return AffineTextPosition(utf16Offset: 0) + return AffineTextPosition(utf16Offset: 0, blockOrder: 0) + } + let hit = affine_ios_host_doc_hit_position(handle, Float(point.x), Float(point.y)) + if hit.valid { + return AffineTextPosition.from(hit) } let offset = affine_ios_host_text_closest_offset( handle, AffinePoint(x: Float(point.x), y: Float(point.y)) ) - return AffineTextPosition(utf16Offset: Int(offset)) + return AffineTextPosition(utf16Offset: Int(offset), blockOrder: currentFocusedBlockOrder) } func closestPosition(to point: CGPoint, within range: UITextRange) -> UITextPosition? { 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 + return affineRange.endPos } - let bounded = max(clamped.location, min(pos.utf16Offset, clamped.location + clamped.length)) - return AffineTextPosition(utf16Offset: bounded) + if compare(pos, to: affineRange.startPos) == .orderedAscending { + return affineRange.startPos + } + if compare(pos, to: affineRange.endPos) == .orderedDescending { + return affineRange.endPos + } + return pos } func characterRange(at point: CGPoint) -> UITextRange? { guard let pos = closestPosition(to: point) as? AffineTextPosition else { return nil } - let text = currentAuthoritativeString - let len = text.length - guard len > 0 else { - return AffineTextRange(utf16Range: NSRange(location: 0, length: 0)) - } - let idx = min(pos.utf16Offset, len - 1) - let cluster = text.rangeOfComposedCharacterSequence(at: idx) - return AffineTextRange(utf16Range: cluster) + return characterUnitRange(at: pos) } // MARK: - UIKit Touch & Hardware Keyboard Forwarding @@ -780,60 +1616,96 @@ final class MetalHostView: UIView, UITextInput { return assigned } - private static let topBarHeightPt: CGFloat = 53.0 private static let panSlopPt: CGFloat = 10.0 + private static let topBarHeightPt: CGFloat = 53.0 + + func handleForwardedTouchCompletion(endedEditableTap: Bool) { + guard let handle = hostHandle else { return } + syncCodeInputTraitsIfNeeded() + syncKeyboardInputViewIfNeeded() + if affine_ios_host_wants_software_keyboard(handle), + !affine_ios_host_is_surface_readonly(handle) + { + if endedEditableTap && !isFirstResponder && window != nil { + _ = becomeFirstResponder() + } + } else if !affine_ios_host_document_selection_snapshot(handle).has_selection, + isFirstResponder + { + _ = resignFirstResponder() + } + } + + override func didMoveToWindow() { + super.didMoveToWindow() + onDidMoveToWindow?() + } override func touchesBegan(_ touches: Set, with event: UIEvent?) { guard let handle = hostHandle else { return } + let now = CACurrentMediaTime() + lastTouchDownTimestamp = now for touch in touches { + lastTouchTapCount = max(1, touch.tapCount) let loc = touch.location(in: self) let id = touchId(for: touch, remove: false) touchStartPoints[id] = loc + touchStartTimes[id] = now touchExceededPanThreshold.remove(id) - affine_ios_host_touch_event(handle, id, 0, Float(loc.x), Float(loc.y)) + touchForwardedToRust.remove(id) + if !(onQueryShouldLetTextInteractionOwnTouch?(loc) ?? true) { + touchForwardedToRust.insert(id) + affine_ios_host_touch_event(handle, id, 0, Float(loc.x), Float(loc.y)) + } } onInteractionWake?() } override func touchesMoved(_ touches: Set, with event: UIEvent?) { guard let handle = hostHandle else { return } + let systemGestureActive = onQuerySystemGestureActive?() ?? false for touch in touches { let loc = touch.location(in: self) let id = touchId(for: touch, remove: false) + if touchForwardedToRust.contains(id) { + affine_ios_host_touch_event(handle, id, 1, Float(loc.x), Float(loc.y)) + continue + } if let start = touchStartPoints[id] { let dx = loc.x - start.x let dy = loc.y - start.y if hypot(dx, dy) > Self.panSlopPt { touchExceededPanThreshold.insert(id) + if !systemGestureActive { + touchForwardedToRust.insert(id) + affine_ios_host_touch_event(handle, id, 0, Float(start.x), Float(start.y)) + affine_ios_host_touch_event(handle, id, 1, Float(loc.x), Float(loc.y)) + } } } - affine_ios_host_touch_event(handle, id, 1, Float(loc.x), Float(loc.y)) } onInteractionWake?() } override func touchesEnded(_ touches: Set, with event: UIEvent?) { guard let handle = hostHandle else { return } + lastTouchUpTimestamp = CACurrentMediaTime() var endedEditableTap = false for touch in touches { let loc = touch.location(in: self) let id = touchId(for: touch, remove: true) let start = touchStartPoints.removeValue(forKey: id) ?? loc + touchStartTimes.removeValue(forKey: id) let wasPan = touchExceededPanThreshold.remove(id) != nil || hypot(loc.x - start.x, loc.y - start.y) > Self.panSlopPt - affine_ios_host_touch_event(handle, id, 2, Float(loc.x), Float(loc.y)) - if !wasPan && start.y >= Self.topBarHeightPt && loc.y >= Self.topBarHeightPt { - endedEditableTap = true + if touchForwardedToRust.remove(id) != nil { + affine_ios_host_touch_event(handle, id, 2, Float(loc.x), Float(loc.y)) + if !wasPan && start.y >= Self.topBarHeightPt && loc.y >= Self.topBarHeightPt { + endedEditableTap = true + } } } - syncCodeInputTraitsIfNeeded() - if affine_ios_host_wants_software_keyboard(handle) { - if endedEditableTap && !isFirstResponder { - _ = becomeFirstResponder() - } - } else if isFirstResponder { - _ = resignFirstResponder() - } + handleForwardedTouchCompletion(endedEditableTap: endedEditableTap) onInteractionWake?() } @@ -843,15 +1715,16 @@ final class MetalHostView: UIView, UITextInput { let loc = touch.location(in: self) let id = touchId(for: touch, remove: true) touchStartPoints.removeValue(forKey: id) + touchStartTimes.removeValue(forKey: id) touchExceededPanThreshold.remove(id) - affine_ios_host_touch_event(handle, id, 3, Float(loc.x), Float(loc.y)) + if touchForwardedToRust.remove(id) != nil { + affine_ios_host_touch_event(handle, id, 3, Float(loc.x), Float(loc.y)) + } } onInteractionWake?() } override func pressesBegan(_ presses: Set, with event: UIPressesEvent?) { - // Yield hardware keyboard navigation/edit keys to the active IME composition - // so Pinyin/Kana candidate selection and commit are never intercepted. if markedTextRange != nil { super.pressesBegan(presses, with: event) return @@ -904,17 +1777,63 @@ final class MetalHostView: UIView, UITextInput { } } -final class MetalHostViewController: UIViewController, UIEditMenuInteractionDelegate { +private struct SelectionSyncSignature: Equatable { + let hasSelection: Bool + let isCollapsed: Bool + let isReversed: Bool + let startVisible: Bool + let endVisible: Bool + let startX: Int + let startY: Int + let startH: Int + let endX: Int + let endY: Int + let endH: Int + let rectCount: Int +} + +final class MetalHostViewController: + UIViewController, + UITextInteractionDelegate, + UIEditMenuInteractionDelegate +{ private let hostView = MetalHostView() - 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 editorMetalLayer: CAMetalLayer? + private var textInteraction: UITextInteraction? + private var textInteractionIsReadonly = false private var editMenuInteraction: UIEditMenuInteraction? + private var systemGestureStartPoint: [ObjectIdentifier: CGPoint] = [:] + private var observedSystemGestures: Set = [] + private var lastSelectionSyncSignature: SelectionSyncSignature? + private var lastPresentedMenuWasCollapsed = false + private var lastCollapsedMenuCaretKey: (Int, Int) = (-1, -1) private(set) var presentedMenuAnchorRect: CGRect? + private var lastPresentedMenuSeq: UInt64 = 0 + private var menuSuppressedByMotion = false + private(set) var lastWrittenClipboard: [String: String] = [:] + private(set) var lastWrittenPasteboardChangeCount: Int = -1 + + func recordLastWrittenClipboard( + _ dict: [String: String], + changeCount: Int = affineHasSystemPasteboardRunLoop ? UIPasteboard.general.changeCount : 1 + ) { + lastWrittenClipboard = dict + lastWrittenPasteboardChangeCount = changeCount + } + + static func seedExternalPasteboard(_ dict: [String: String]) { + if affineHasSystemPasteboardRunLoop { + affineIosWriteSystemPasteboard(dict) + } else { + affineHeadlessPasteboard = dict + } + } + private var lastSyncedInsets = AffineWindowInsets( safe_top: 0, safe_right: 0, @@ -929,29 +1848,11 @@ final class MetalHostViewController: UIViewController, UIEditMenuInteractionDele private var displayLinkProxy: DisplayLinkProxy? private var timerWakeWorkItem: DispatchWorkItem? - var textHostView: MetalHostView { - hostView - } - - var selectionOverlay: SelectionOverlayView { - selectionOverlayView - } - - var keyboardCoordinator: KeyboardAvoidanceCoordinator { - keyboardAvoidanceCoordinator - } - - var haptics: HapticsBridge { - hapticsBridge - } - - var textRenderer: TextRenderingBridge { - textRenderingBridge - } - - var hostPointer: OpaquePointer? { - hostHandle - } + var textHostView: MetalHostView { hostView } + var keyboardCoordinator: KeyboardAvoidanceCoordinator { keyboardAvoidanceCoordinator } + var haptics: HapticsBridge { hapticsBridge } + var textRenderer: TextRenderingBridge { textRenderingBridge } + var hostPointer: OpaquePointer? { hostHandle } override func loadView() { let root = UIView() @@ -989,6 +1890,14 @@ final class MetalHostViewController: UIViewController, UIEditMenuInteractionDele if let handle { let rawSelf = Unmanaged.passUnretained(self).toOpaque() affine_ios_host_set_frame_wake_callback(handle, affineIosFrameWakeTrampoline, rawSelf) + affine_ios_host_set_clipboard_provider( + handle, + AffineClipboardProvider( + write_json: affineIosClipboardWriteTrampoline, + read_json: affineIosClipboardReadTrampoline, + user_data: rawSelf + ) + ) let isPad = UIDevice.current.userInterfaceIdiom == .pad affine_ios_host_set_form_factor(handle, isPad ? 1 : 0) if let rawEditorLayer = affine_ios_host_metal_layer(handle) { @@ -1001,64 +1910,38 @@ final class MetalHostViewController: UIViewController, UIEditMenuInteractionDele } applyClearColor(TextRenderingBridge.defaultClearColorRgba) - selectionOverlayView.hostHandle = handle - selectionOverlayView.frame = hostView.bounds - selectionOverlayView.autoresizingMask = [.flexibleWidth, .flexibleHeight] - hostView.addSubview(selectionOverlayView) - + installTextInteraction(readonly: false) let menuInteraction = UIEditMenuInteraction(delegate: self) hostView.addInteraction(menuInteraction) editMenuInteraction = menuInteraction - hostView.onSelectedRangeChanged = { [weak self] range in - self?.syncSelectionOverlay(for: range) + hostView.onDidMoveToWindow = { [weak self] in + self?.attachSystemGestureObservers() + } + hostView.onQuerySystemGestureActive = { [weak self] in + self?.isSystemSelectionGestureActive ?? false + } + hostView.onQueryShouldLetTextInteractionOwnTouch = { [weak self] point in + self?.shouldLetTextInteractionOwnTouch(at: point) ?? false + } + hostView.onSelectedRangeChanged = { [weak self] _ in + self?.syncDocumentSelectionFromEditor(suppressInputDelegateNotification: false) + } + hostView.onSystemSelectionApplied = { [weak self] in + self?.wakeDisplayLink() + self?.syncDocumentSelectionFromEditor(suppressInputDelegateNotification: true) } hostView.onInteractionWake = { [weak self] in self?.wakeDisplayLink() + self?.syncDocumentSelectionFromEditor(suppressInputDelegateNotification: false) } - 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) + hostView.onDismissEditMenu = { [weak self] in + self?.menuSuppressedByMotion = false + self?.editMenuInteraction?.dismissMenu() + self?.presentedMenuAnchorRect = nil } - 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, - !rect.isNull, - rect.origin.x.isFinite, - rect.origin.y.isFinite, - rect.size.width.isFinite, - rect.size.height.isFinite, - self.hostView.window != nil - { - let clampedX = min(max(rect.midX, 1.0), max(self.hostView.bounds.width - 1.0, 1.0)) - let clampedY = min(max(rect.minY, 1.0), max(self.hostView.bounds.height - 1.0, 1.0)) - let config = UIEditMenuConfiguration( - identifier: nil, - sourcePoint: CGPoint(x: clampedX, y: clampedY) - ) - DispatchQueue.main.async { [weak self, weak interaction] in - guard - let self, - let interaction, - self.hostView.window != nil, - self.presentedMenuAnchorRect == rect - else { - return - } - interaction.presentEditMenu(with: config) - } - } else { - interaction.dismissMenu() - } + hostView.onFallbackCopiedText = { [weak self] in + self?.lastWrittenClipboard["text/plain"] } keyboardAvoidanceCoordinator.hostView = hostView @@ -1076,7 +1959,29 @@ final class MetalHostViewController: UIViewController, UIEditMenuInteractionDele retryBootstrapIfNeeded() } - /// Run or retry legacy `capacitor://localhost` bootstrap, retaining any error for recovery UI. + private func installTextInteraction(readonly: Bool) { + if let existing = textInteraction { + hostView.removeInteraction(existing) + textInteraction = nil + } + observedSystemGestures.removeAll() + systemGestureStartPoint.removeAll() + textInteractionIsReadonly = readonly + let interaction = UITextInteraction(for: readonly ? .nonEditable : .editable) + interaction.delegate = self + interaction.textInput = hostView + hostView.addInteraction(interaction) + textInteraction = interaction + attachSystemGestureObservers() + } + + private func syncTextInteractionModeIfNeeded(handle: OpaquePointer) { + let readonly = affine_ios_host_is_surface_readonly(handle) + if readonly != textInteractionIsReadonly { + installTextInteraction(readonly: readonly) + } + } + @MainActor func retryBootstrapIfNeeded() { guard !bootstrapCompleted else { @@ -1127,7 +2032,6 @@ final class MetalHostViewController: UIViewController, UIEditMenuInteractionDele editorLayer.contentsScale = scale CATransaction.commit() } - selectionOverlayView.frame = hostView.bounds if let handle = hostHandle { affine_ios_host_resize( handle, @@ -1140,14 +2044,25 @@ final class MetalHostViewController: UIViewController, UIEditMenuInteractionDele override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() + attachSystemGestureObservers() updateEditorMetalLayout() sampleInsets(timestamp: CACurrentMediaTime()) wakeDisplayLink() - let currentRange = hostView.currentSelectedUtf16Range - if currentRange.length > 0 { - syncSelectionOverlay(for: currentRange) - } else { - selectionOverlayView.refreshFromHost() + syncDocumentSelectionFromEditor(suppressInputDelegateNotification: false) + } + + private func attachSystemGestureObservers() { + let allGestures = (textInteraction?.gesturesForFailureRequirements ?? []) + + (hostView.gestureRecognizers ?? []) + for gesture in allGestures { + let className = NSStringFromClass(type(of: gesture)) + guard className.localizedCaseInsensitiveContains("loupe") else { + continue + } + let id = ObjectIdentifier(gesture) + if observedSystemGestures.insert(id).inserted { + gesture.addTarget(self, action: #selector(handleSystemTextGestureState(_:))) + } } } @@ -1160,11 +2075,14 @@ final class MetalHostViewController: UIViewController, UIEditMenuInteractionDele NotificationCenter.default.removeObserver(self) hostView.detachTextInputObserver() hostView.hostHandle = nil - selectionOverlayView.hostHandle = nil editorMetalLayer?.removeFromSuperlayer() editorMetalLayer = nil if let handle = hostHandle { affine_ios_host_set_frame_wake_callback(handle, nil, nil) + affine_ios_host_set_clipboard_provider( + handle, + AffineClipboardProvider(write_json: nil, read_json: nil, user_data: nil) + ) textRenderingBridge.detach() pdfRendererBridge.detach(from: handle) hapticsBridge.detach(from: handle) @@ -1183,39 +2101,236 @@ final class MetalHostViewController: UIViewController, UIEditMenuInteractionDele } } - private func syncSelectionOverlay(for range: NSRange) { - guard let handle = hostHandle, selectionOverlayView.currentState.active_drag_handle == 0 else { + private var isSystemSelectionGestureActive: Bool { + let gestures = textInteraction?.gesturesForFailureRequirements ?? [] + return gestures.contains { $0.state == .began || $0.state == .changed } + } + + func shouldLetTextInteractionOwnTouch(at point: CGPoint) -> Bool { + guard let handle = hostHandle else { + return false + } + syncTextInteractionModeIfNeeded(handle: handle) + let snap = affine_ios_host_document_selection_snapshot(handle) + if snap.has_selection && !snap.is_collapsed { + if snap.start_visible { + let startDot = CGPoint( + x: CGFloat(snap.start_caret.x), + y: CGFloat(snap.start_caret.y) - 6.0 + ) + let startStem = CGPoint( + x: CGFloat(snap.start_caret.x), + y: CGFloat(snap.start_caret.y + snap.start_caret.height * 0.5) + ) + if hypot(point.x - startDot.x, point.y - startDot.y) <= 24.0 + || hypot(point.x - startStem.x, point.y - startStem.y) <= 20.0 + { + return true + } + } + if snap.end_visible { + let endDot = CGPoint( + x: CGFloat(snap.end_caret.x), + y: CGFloat(snap.end_caret.y + snap.end_caret.height) + 6.0 + ) + let endStem = CGPoint( + x: CGFloat(snap.end_caret.x), + y: CGFloat(snap.end_caret.y + snap.end_caret.height * 0.5) + ) + if hypot(point.x - endDot.x, point.y - endDot.y) <= 24.0 + || hypot(point.x - endStem.x, point.y - endStem.y) <= 20.0 + { + return true + } + } + } + return !affine_ios_host_should_forward_touch_immediately( + handle, + Float(point.x), + Float(point.y) + ) + } + + func interactionShouldBegin(_ interaction: UITextInteraction, at point: CGPoint) -> Bool { + shouldLetTextInteractionOwnTouch(at: point) + } + + @objc private func handleSystemTextGestureState(_ gesture: UIGestureRecognizer) { + let key = ObjectIdentifier(gesture) + let loc = gesture.location(in: hostView) + switch gesture.state { + case .began: + systemGestureStartPoint[key] = loc + editMenuInteraction?.dismissMenu() + case .ended: + let start = systemGestureStartPoint.removeValue(forKey: key) ?? loc + let moved = hypot(loc.x - start.x, loc.y - start.y) + if moved <= 12.0 { + let holdLoc = loc + DispatchQueue.main.async { [weak self] in + guard let self, let h = self.hostHandle else { return } + let postSnap = affine_ios_host_document_selection_snapshot(h) + let isReadonly = affine_ios_host_is_surface_readonly(h) + if isReadonly { + if postSnap.is_collapsed || !postSnap.has_selection { + _ = affine_ios_host_select_word_at_point(h, Float(holdLoc.x), Float(holdLoc.y)) + self.hostView.notifySystemSelectionUpdated() + } else { + affine_ios_host_bump_selection_menu_request_seq(h) + } + } else if postSnap.has_selection { + affine_ios_host_bump_selection_menu_request_seq(h) + } + self.wakeDisplayLink() + self.syncDocumentSelectionFromEditor(suppressInputDelegateNotification: false) + } + } + case .cancelled, .failed: + systemGestureStartPoint.removeValue(forKey: key) + default: + break + } + } + + func syncDocumentSelectionFromEditor(suppressInputDelegateNotification: Bool = false) { + 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)) - ) + syncTextInteractionModeIfNeeded(handle: handle) + hostView.syncKeyboardInputViewIfNeeded() + let snap = affine_ios_host_document_selection_snapshot(handle) + let hideReadonlyCaret = snap.has_selection + && snap.is_collapsed + && affine_ios_host_is_surface_readonly(handle) + && !isSystemSelectionGestureActive + let desiredTint: UIColor = hideReadonlyCaret ? .clear : .systemBlue + if hostView.tintColor != desiredTint { + hostView.tintColor = desiredTint } - let state = affine_ios_host_selection_set( - handle, - cStart, - cEnd, - cRange, - hostView.currentWritingDirection + let hasVisibleRange = snap.has_selection + && !snap.is_collapsed + && (snap.start_visible || snap.end_visible) + if hasVisibleRange && !hostView.isFirstResponder && hostView.window != nil { + _ = hostView.becomeFirstResponder() + } + let nextSig = SelectionSyncSignature( + hasSelection: snap.has_selection, + isCollapsed: snap.is_collapsed, + isReversed: snap.is_reversed, + startVisible: snap.start_visible, + endVisible: snap.end_visible, + startX: Int((snap.start_caret.x * 4.0).rounded()), + startY: Int((snap.start_caret.y * 4.0).rounded()), + startH: Int((snap.start_caret.height * 4.0).rounded()), + endX: Int((snap.end_caret.x * 4.0).rounded()), + endY: Int((snap.end_caret.y * 4.0).rounded()), + endH: Int((snap.end_caret.height * 4.0).rounded()), + rectCount: snap.rect_count ) - selectionOverlayView.applyOverlayState(state) + if nextSig != lastSelectionSyncSignature { + lastSelectionSyncSignature = nextSig + if !suppressInputDelegateNotification + && !hostView.isInsideImeMutation + && !hostView.isApplyingSystemSelection + && !isSystemSelectionGestureActive + && snap.has_selection + { + hostView.notifySystemSelectionUpdated() + } + } + if !snap.has_selection || snap.action_mask == 0 { + menuSuppressedByMotion = false + if presentedMenuAnchorRect != nil { + presentedMenuAnchorRect = nil + editMenuInteraction?.dismissMenu() + } + return + } + if !snap.menu_anchor_visible || snap.menu_suppressed_for_motion { + if !snap.is_collapsed + && (presentedMenuAnchorRect != nil + || menuSuppressedByMotion + || (lastPresentedMenuSeq > 0 && snap.menu_request_seq == lastPresentedMenuSeq)) + { + menuSuppressedByMotion = true + } else if snap.is_collapsed { + menuSuppressedByMotion = false + } + if presentedMenuAnchorRect != nil { + presentedMenuAnchorRect = nil + editMenuInteraction?.dismissMenu() + } + return + } + let seqAdvanced = snap.menu_request_seq != lastPresentedMenuSeq && snap.menu_request_seq > 0 + let restoreAfterMotion = menuSuppressedByMotion && !snap.is_collapsed && lastPresentedMenuSeq > 0 + let caretKey = (Int(affine_ios_host_selected_range(handle).location), Int(affine_ios_host_utf16_len(handle))) + if !seqAdvanced && snap.is_collapsed && (!lastPresentedMenuWasCollapsed || caretKey != lastCollapsedMenuCaretKey) { + menuSuppressedByMotion = false + if presentedMenuAnchorRect != nil { + presentedMenuAnchorRect = nil + editMenuInteraction?.dismissMenu() + } + return + } + let rect = CGRect( + x: CGFloat(snap.menu_anchor_rect.x), + y: CGFloat(snap.menu_anchor_rect.y), + width: CGFloat(max(snap.menu_anchor_rect.width, 2.0)), + height: CGFloat(max(snap.menu_anchor_rect.height, 2.0)) + ) + guard + !rect.isNull, + rect.origin.x.isFinite, + rect.origin.y.isFinite, + rect.size.width.isFinite, + rect.size.height.isFinite + else { + presentedMenuAnchorRect = nil + editMenuInteraction?.dismissMenu() + return + } + let anchorMoved = presentedMenuAnchorRect.map { + abs($0.minX - rect.minX) > 1.0 || abs($0.minY - rect.minY) > 1.0 + } ?? false + presentedMenuAnchorRect = rect + if seqAdvanced || restoreAfterMotion { + if isSystemSelectionGestureActive { + return + } + menuSuppressedByMotion = false + lastPresentedMenuWasCollapsed = snap.is_collapsed + lastCollapsedMenuCaretKey = caretKey + guard let interaction = editMenuInteraction, hostView.window != nil else { + return + } + if seqAdvanced { + lastPresentedMenuSeq = snap.menu_request_seq + } + if !hostView.isFirstResponder { + _ = hostView.becomeFirstResponder() + } + let clampedX = min(max(rect.midX, 1.0), max(hostView.bounds.width - 1.0, 1.0)) + let clampedY = min(max(rect.minY, 1.0), max(hostView.bounds.height - 1.0, 1.0)) + let config = UIEditMenuConfiguration( + identifier: nil, + sourcePoint: CGPoint(x: clampedX, y: clampedY) + ) + DispatchQueue.main.async { [weak self, weak interaction] in + guard + let self, + let interaction, + self.hostView.window != nil, + self.presentedMenuAnchorRect != nil + else { + return + } + interaction.dismissMenu() + interaction.presentEditMenu(with: config) + } + } else if anchorMoved { + editMenuInteraction?.updateVisibleMenuPosition(animated: false) + } } func editMenuInteraction( @@ -1250,96 +2365,7 @@ final class MetalHostViewController: UIViewController, UIEditMenuInteractionDele menuFor configuration: UIEditMenuConfiguration, suggestedActions: [UIMenuElement] ) -> UIMenu? { - var actions: [UIAction] = [] - let hasSelection = hostView.currentSelectedUtf16Range.length > 0 - if hasSelection { - actions.append( - UIAction(title: "Cut") { [weak self] _ in - self?.hostView.cut(nil) - } - ) - actions.append( - UIAction(title: "Copy") { [weak self] _ in - self?.hostView.copy(nil) - } - ) - } - if UIPasteboard.general.hasStrings { - actions.append( - UIAction(title: "Paste") { [weak self] _ in - self?.hostView.paste(nil) - } - ) - } - if hostView.hasText { - actions.append( - UIAction(title: "Select All") { [weak self] _ in - self?.hostView.selectAll(nil) - } - ) - } - guard !actions.isEmpty else { - return nil - } - return UIMenu(children: actions) - } - - 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)) - ) - _ = 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) + nil } private func startDisplayLink() { @@ -1393,6 +2419,7 @@ final class MetalHostViewController: UIViewController, UIEditMenuInteractionDele if clearRgba != 0 { applyClearColor(clearRgba) } + syncDocumentSelectionFromEditor(suppressInputDelegateNotification: false) } if !affine_ios_host_is_dirty(handle) { pauseDisplayLinkUntilNextTimer(handle: handle) @@ -1459,15 +2486,7 @@ final class MetalHostViewController: UIViewController, UIEditMenuInteractionDele if changed { lastSyncedInsets = next wakeDisplayLink() - let currentRange = hostView.currentSelectedUtf16Range - if currentRange.length > 0 { - syncSelectionOverlay(for: currentRange) - } else if let handle = hostHandle, - selectionOverlayView.currentState.has_selection - || selectionOverlayView.lastMenuAnchorRect != nil - { - selectionOverlayView.applyOverlayState(affine_ios_host_selection_state(handle)) - } + syncDocumentSelectionFromEditor(suppressInputDelegateNotification: false) } } } diff --git a/packages/frontend/hosts/ios/Sources/SelectionOverlayView.swift b/packages/frontend/hosts/ios/Sources/SelectionOverlayView.swift deleted file mode 100644 index 9b83a96f8d..0000000000 --- a/packages/frontend/hosts/ios/Sources/SelectionOverlayView.swift +++ /dev/null @@ -1,290 +0,0 @@ -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 - guard let resolver = onSelectionDragResolved else { - return currentState - } - 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) - ) - let state = affine_ios_host_selection_apply_drag_endpoints( - handle, - cPoint, - resolved.targetOffset, - cStart, - cEnd - ) - 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/include/affine_mobile_host.h b/packages/frontend/hosts/ios/include/affine_mobile_host.h index 76df883794..4ae517a530 100644 --- a/packages/frontend/hosts/ios/include/affine_mobile_host.h +++ b/packages/frontend/hosts/ios/include/affine_mobile_host.h @@ -604,6 +604,203 @@ uint64_t affine_ios_host_haptic_count( uint64_t affine_ios_host_haptic_total_count( const AffineIosHost *host); +/* Document-level selection, multi-MIME clipboard, and full-document UITextPosition C ABI. */ + +typedef void (*AffineClipboardWriteFn)( + const uint8_t *utf8_ptr, + size_t utf8_len, + void *user_data); + +typedef void (*AffineClipboardReadSinkFn)( + const uint8_t *utf8_ptr, + size_t utf8_len, + void *ctx); + +typedef void (*AffineClipboardReadFn)( + AffineClipboardReadSinkFn sink, + void *ctx, + void *user_data); + +typedef struct AffineClipboardProvider { + AffineClipboardWriteFn write_json; + AffineClipboardReadFn read_json; + void *user_data; +} AffineClipboardProvider; + +typedef struct AffineDocumentSelectionSnapshot { + bool has_selection; + bool is_collapsed; + bool is_reversed; + bool start_is_rtl; + bool end_is_rtl; + bool start_visible; + bool end_visible; + bool menu_anchor_visible; + bool menu_suppressed_for_motion; + AffineRect start_caret; + AffineRect end_caret; + AffineRect menu_anchor_rect; + uint32_t action_mask; + uint64_t menu_request_seq; + size_t rect_count; +} AffineDocumentSelectionSnapshot; + +typedef struct AffineDocumentSelectionRect { + AffineRect rect; + bool is_rtl; + bool contains_start; + bool contains_end; +} AffineDocumentSelectionRect; + +typedef struct AffineDocPosition { + bool valid; + int32_t block_order; + uint32_t utf16_offset; + uint64_t endpoint_token; +} AffineDocPosition; + +void affine_ios_host_set_clipboard_provider( + AffineIosHost *host, + AffineClipboardProvider provider); + +void affine_ios_host_set_page_readonly( + AffineIosHost *host, + bool readonly); + +bool affine_ios_host_is_surface_readonly( + const AffineIosHost *host); + +void affine_ios_host_restore_software_keyboard( + AffineIosHost *host); + +AffineDocumentSelectionSnapshot affine_ios_host_document_selection_snapshot( + const AffineIosHost *host); + +void affine_ios_host_doc_selection_endpoint_tokens( + const AffineIosHost *host, + uint64_t *out_start, + uint64_t *out_end); + +size_t affine_ios_host_document_selection_rects( + const AffineIosHost *host, + AffineDocumentSelectionRect *out_rects, + size_t capacity); + +size_t affine_ios_host_doc_selection_preview_rects( + const AffineIosHost *host, + uint64_t fixed_endpoint_token, + float fx, + float fy, + AffineDocumentSelectionRect *out_rects, + size_t capacity); + +bool affine_ios_host_doc_caret_rect_at_point( + const AffineIosHost *host, + float x, + float y, + AffineRect *out_rect); + +char *affine_ios_host_selected_plain_text( + const AffineIosHost *host); + +bool affine_ios_host_should_forward_touch_immediately( + const AffineIosHost *host, + float x, + float y); + +bool affine_ios_host_select_word_at_point( + AffineIosHost *host, + float x, + float y); + +void affine_ios_host_bump_selection_menu_request_seq( + AffineIosHost *host); + +bool affine_ios_host_doc_selection_begin_drag( + AffineIosHost *host, + uint8_t handle); + +bool affine_ios_host_doc_selection_update_drag( + AffineIosHost *host, + float x, + float y); + +void affine_ios_host_doc_selection_end_drag( + AffineIosHost *host); + +bool affine_ios_host_doc_selection_select_from_endpoint_token( + AffineIosHost *host, + uint64_t fixed_endpoint_token, + float fx, + float fy); + +bool affine_ios_host_doc_selection_select_between_points( + AffineIosHost *host, + float ax, + float ay, + float fx, + float fy); + +bool affine_ios_host_doc_selection_select_between_endpoint_tokens( + AffineIosHost *host, + uint64_t start_endpoint_token, + uint64_t end_endpoint_token); + +void affine_ios_host_selection_action_copy(AffineIosHost *host); +void affine_ios_host_selection_action_cut(AffineIosHost *host); +void affine_ios_host_selection_action_paste(AffineIosHost *host); +void affine_ios_host_selection_action_select_all(AffineIosHost *host); + +int32_t affine_ios_host_focused_block_order(const AffineIosHost *host); + +bool affine_ios_host_doc_document_bounds( + const AffineIosHost *host, + AffineDocPosition *out_start, + AffineDocPosition *out_end); + +bool affine_ios_host_doc_selection_positions( + const AffineIosHost *host, + AffineDocPosition *out_start, + AffineDocPosition *out_end); + +AffineDocPosition affine_ios_host_doc_hit_position( + const AffineIosHost *host, + float x, + float y); + +bool affine_ios_host_doc_caret_rect_for_token( + const AffineIosHost *host, + uint64_t endpoint_token, + AffineRect *out_rect); + +size_t affine_ios_host_doc_selection_rects_between_tokens( + const AffineIosHost *host, + uint64_t start_endpoint_token, + uint64_t end_endpoint_token, + AffineDocumentSelectionRect *out_rects, + size_t capacity); + +AffineDocPosition affine_ios_host_doc_step_position( + const AffineIosHost *host, + uint64_t endpoint_token, + ptrdiff_t delta); + +bool affine_ios_host_doc_word_range( + const AffineIosHost *host, + uint64_t endpoint_token, + AffineDocPosition *out_start, + AffineDocPosition *out_end); + +int32_t affine_ios_host_doc_offset_between_tokens( + const AffineIosHost *host, + uint64_t from_token, + uint64_t to_token); + +char *affine_ios_host_doc_text_between_tokens( + const AffineIosHost *host, + uint64_t start_endpoint_token, + uint64_t end_endpoint_token); + #ifdef __cplusplus } #endif diff --git a/packages/frontend/hosts/ios/src/clipboard.rs b/packages/frontend/hosts/ios/src/clipboard.rs new file mode 100644 index 0000000000..315eb1f2f8 --- /dev/null +++ b/packages/frontend/hosts/ios/src/clipboard.rs @@ -0,0 +1,182 @@ +//! Multi-MIME `UIPasteboard.general` bridge for `IosEditorPlatform`. + +use std::{cell::RefCell, ffi::c_void}; + +use ui::ClipboardItem; + +/// Combined in-process fallback and `UIPasteboard.general` provider store for `IosEditorPlatform`. +#[derive(Default)] +pub(crate) struct IosClipboardStore { + item: RefCell>, + provider: RefCell>, +} + +impl IosClipboardStore { + pub(crate) fn set_provider(&self, provider: Option) { + *self.provider.borrow_mut() = provider; + } + + pub(crate) fn write(&self, item: ClipboardItem) { + write_via_provider(*self.provider.borrow(), &item); + *self.item.borrow_mut() = Some(item); + } + + pub(crate) fn read(&self) -> Option { + let provider = *self.provider.borrow(); + if provider.is_some() { + read_via_provider(provider) + } else { + self.item.borrow().clone() + } + } +} + +/// Callback invoked by Rust to write a multi-MIME clipboard JSON payload to `UIPasteboard.general`. +pub type IosClipboardWriteFn = extern "C" fn(*const u8, usize, *mut c_void); + +/// Sink passed into `IosClipboardReadFn` so Swift can synchronously hand back UTF-8 JSON bytes +/// without requiring cross-FFI heap allocation. +pub type IosClipboardReadSinkFn = extern "C" fn(*const u8, usize, *mut c_void); + +/// Callback invoked by Rust to read a multi-MIME clipboard JSON payload from `UIPasteboard.general`. +pub type IosClipboardReadFn = extern "C" fn(IosClipboardReadSinkFn, *mut c_void, *mut c_void); + +/// C-ABI clipboard provider table registered by Swift `MetalHostViewController`. +#[repr(C)] +#[derive(Clone, Copy)] +pub struct AffineClipboardProvider { + pub write_json: Option, + pub read_json: Option, + pub user_data: *mut c_void, +} + +pub(crate) fn clipboard_item_to_json(item: &ClipboardItem) -> String { + let mut map = serde_json::Map::new(); + if let Some(text) = item.text() { + map.insert("text/plain".to_string(), serde_json::Value::String(text)); + } + if let Some(meta_str) = item.metadata() + && let Ok(serde_json::Value::Object(meta)) = + serde_json::from_str::(meta_str) + { + for (k, v) in meta { + if k == "application/x-blocksuite-snapshot" { + let serialized = match v { + serde_json::Value::String(s) => s, + other => other.to_string(), + }; + map.insert(k, serde_json::Value::String(serialized)); + } else if let serde_json::Value::String(s) = v { + map.insert(k, serde_json::Value::String(s)); + } + } + } + serde_json::Value::Object(map).to_string() +} + +pub(crate) fn clipboard_item_from_json(raw: &str) -> Option { + let serde_json::Value::Object(map) = serde_json::from_str::(raw).ok()? + else { + return None; + }; + let plain = map + .get("text/plain") + .and_then(serde_json::Value::as_str) + .unwrap_or("") + .to_string(); + let mut meta = serde_json::Map::new(); + for key in [ + "application/x-blocksuite-snapshot", + "text/html", + "text/markdown", + ] { + if let Some(val) = map.get(key) + && !val.is_null() + { + if let Some(s) = val.as_str() { + if !s.is_empty() { + meta.insert(key.to_string(), serde_json::Value::String(s.to_string())); + } + } else { + meta.insert(key.to_string(), val.clone()); + } + } + } + if !meta.is_empty() { + Some(ClipboardItem::new_string_with_json_metadata( + plain, + serde_json::Value::Object(meta), + )) + } else if !plain.is_empty() { + Some(ClipboardItem::new_string(plain)) + } else { + None + } +} + +pub(crate) fn write_via_provider(provider: Option, item: &ClipboardItem) { + if let Some(p) = provider + && let Some(write_fn) = p.write_json + { + let json = clipboard_item_to_json(item); + write_fn(json.as_ptr(), json.len(), p.user_data); + } +} + +pub(crate) fn read_via_provider( + provider: Option, +) -> Option { + let p = provider?; + let read_fn = p.read_json?; + #[allow(unsafe_code)] + extern "C" fn capture_sink(ptr: *const u8, len: usize, ctx: *mut c_void) { + if ptr.is_null() || len == 0 || ctx.is_null() { + return; + } + // SAFETY: `ctx` points to our local `String`, and `ptr..ptr+len` is valid for this call. + let out = unsafe { &mut *(ctx as *mut String) }; + let bytes = unsafe { core::slice::from_raw_parts(ptr, len) }; + if let Ok(s) = core::str::from_utf8(bytes) { + out.clear(); + out.push_str(s); + } + } + let mut captured = String::new(); + read_fn( + capture_sink, + (&mut captured as *mut String).cast::(), + p.user_data, + ); + (!captured.is_empty()) + .then(|| clipboard_item_from_json(&captured)) + .flatten() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn cleared_system_provider_does_not_resurrect_stale_in_process_item() { + extern "C" fn empty_read( + _sink: IosClipboardReadSinkFn, + _ctx: *mut c_void, + _ud: *mut c_void, + ) { + } + + let store = IosClipboardStore::default(); + store.write(ClipboardItem::new_string("PREVIOUS".to_string())); + assert_eq!(store.read().and_then(|c| c.text()), Some("PREVIOUS".into())); + + store.set_provider(Some(AffineClipboardProvider { + write_json: None, + read_json: Some(empty_read), + user_data: core::ptr::null_mut(), + })); + assert!( + store.read().is_none(), + "registered system provider returning empty must never resurrect stale PREVIOUS text" + ); + } +} diff --git a/packages/frontend/hosts/ios/src/editor_doc_positions.rs b/packages/frontend/hosts/ios/src/editor_doc_positions.rs new file mode 100644 index 0000000000..87e8206bac --- /dev/null +++ b/packages/frontend/hosts/ios/src/editor_doc_positions.rs @@ -0,0 +1,598 @@ +//! Read-only full-document position, document-bounds, and cross-block stepping helpers +//! on [`IosEditorRuntime`]. +//! +//! Bridges `PlaygroundView`'s multi-block `SelectionEndpointAnchor` queries to Swift +//! `UITextPosition` / `UITextRange` across the entire addressable document without +//! mutating editor selection on hit-tests or coordinate queries. + +use playground::{SelectionEndpointAnchor, editor_session::DocPoint}; + +use super::{editor_runtime::IosEditorRuntime, selection::AffineRect}; + +/// C-ABI document-level text position (`block_order`, `utf16_offset`, `endpoint_token`). +#[repr(C)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct AffineDocPosition { + pub valid: bool, + pub block_order: i32, + pub utf16_offset: u32, + pub endpoint_token: u64, +} + +impl IosEditorRuntime { + pub(crate) fn focused_block_order(&mut self) -> i32 { + let view = self.view; + self.app + .update(|cx| view.read_with(cx, |v, _| v.focused_selection_block_order())) + .unwrap_or(0) + } + + /// Full-document addressable bounds `(beginningOfDocument, endOfDocument)` spanning all + /// editable blocks in layout order (never truncated to the currently focused block). + pub(crate) fn doc_document_bounds(&mut self) -> Option<(AffineDocPosition, AffineDocPosition)> { + let view = self.view; + let bounds = self + .app + .update(|cx| { + view.read_with(cx, |v, _| { + let layout = v.flow_layout()?; + let mut first: Option<(i32, SelectionEndpointAnchor, u32)> = None; + let mut last: Option<(i32, SelectionEndpointAnchor, u32)> = None; + for (idx, block) in layout.blocks.iter().enumerate() { + if !block.editable() { + continue; + } + if first.is_none() { + first = Some(( + idx as i32, + SelectionEndpointAnchor::Doc(DocPoint::new(&block.block_id, 0)), + 0, + )); + } + let u16_len = block.body.plain.encode_utf16().count() as u32; + last = Some(( + idx as i32, + SelectionEndpointAnchor::Doc(DocPoint::new( + &block.block_id, + u64::from(u16_len), + )), + u16_len, + )); + } + Some((first?, last?)) + }) + }) + .ok() + .flatten()?; + let ((s_ord, s_ep, s_off), (e_ord, e_ep, e_off)) = bounds; + let s_tok = self.intern_endpoint_token(s_ep); + let e_tok = self.intern_endpoint_token(e_ep); + Some(( + AffineDocPosition { + valid: true, + block_order: s_ord, + utf16_offset: s_off, + endpoint_token: s_tok, + }, + AffineDocPosition { + valid: true, + block_order: e_ord, + utf16_offset: e_off, + endpoint_token: e_tok, + }, + )) + } + + pub(crate) fn current_selection_doc_positions( + &mut self, + ) -> Option<(AffineDocPosition, AffineDocPosition)> { + let view = self.view; + let pair = self + .app + .update(|cx| view.read_with(cx, |v, _| v.current_selection_doc_endpoints())) + .ok() + .flatten()?; + let ((s_ep, s_ord, s_off), (e_ep, e_ord, e_off)) = pair; + let s_tok = self.intern_endpoint_token(s_ep); + let e_tok = self.intern_endpoint_token(e_ep); + Some(( + AffineDocPosition { + valid: true, + block_order: s_ord, + utf16_offset: s_off, + endpoint_token: s_tok, + }, + AffineDocPosition { + valid: true, + block_order: e_ord, + utf16_offset: e_off, + endpoint_token: e_tok, + }, + )) + } + + /// Pure read-only viewport hit-test: resolves `(block_order, utf16_offset, endpoint_token)` + /// without changing `editor.selection` or focused block state. + pub(crate) fn doc_hit_position(&mut self, x: f32, y: f32) -> Option { + let view = self.view; + let (ep, ord, off) = self + .app + .update(|cx| view.update(cx, |v, w, _| v.hit_test_doc_position(x, y, w))) + .ok() + .flatten()?; + let tok = self.intern_endpoint_token(ep); + Some(AffineDocPosition { + valid: true, + block_order: ord, + utf16_offset: off, + endpoint_token: tok, + }) + } + + pub(crate) fn doc_caret_rect_for_token(&mut self, token: u64) -> Option { + let anchor = self.lookup_endpoint_token(token)?; + let view = self.view; + let geom = self + .app + .update(|cx| view.update(cx, |v, w, _| v.caret_rect_for_anchor(&anchor, w))) + .ok() + .flatten()?; + Some(AffineRect { + x: geom.x, + y: geom.y, + width: geom.width.max(2.0), + height: geom.height.max(18.0), + }) + } + + pub(crate) fn doc_selection_rects_between_tokens( + &mut self, + start_token: u64, + end_token: u64, + ) -> Vec { + let (Some(a), Some(b)) = ( + self.lookup_endpoint_token(start_token), + self.lookup_endpoint_token(end_token), + ) else { + return Vec::new(); + }; + let view = self.view; + self.app + .update(|cx| view.update(cx, |v, w, _| v.selection_rects_between_anchors(a, b, w))) + .unwrap_or_default() + } + + /// Step `delta` UTF-16 units from `token`, seamlessly crossing editable block boundaries + /// (`+1` per newline separator, matching `offset_between_anchors`). + pub(crate) fn doc_step_position( + &mut self, + token: u64, + delta: isize, + ) -> Option { + let anchor = self.lookup_endpoint_token(token)?; + let view = self.view; + if let Some((next_ep, ord, off)) = self + .app + .update(|cx| view.read_with(cx, |v, _| v.step_anchor_utf16(&anchor, delta))) + .ok() + .flatten() + { + let next_tok = self.intern_endpoint_token(next_ep); + return Some(AffineDocPosition { + valid: true, + block_order: ord, + utf16_offset: off, + endpoint_token: next_tok, + }); + } + // Cross-block step for `SelectionEndpointAnchor::Doc`: resolve cumulative UTF-16 offset + // across editable blocks (`+1` newline separator between editable blocks). + let SelectionEndpointAnchor::Doc(pt) = anchor else { + return None; + }; + let cross = self + .app + .update(|cx| { + view.read_with(cx, |v, _| { + let layout = v.flow_layout()?; + let mut editable_spans: Vec<(i32, &str, isize, isize)> = Vec::new(); + let mut acc: isize = 0; + let mut current_cum: Option = None; + for (idx, block) in layout.blocks.iter().enumerate() { + if !block.editable() { + continue; + } + let len = block.body.plain.encode_utf16().count() as isize; + if block.block_id == pt.block_id { + let local = (pt.offset() as isize).clamp(0, len); + current_cum = Some(acc + local); + } + editable_spans.push((idx as i32, block.block_id.as_str(), acc, len)); + acc += len + 1; + } + let total_max = acc.saturating_sub(1).max(0); + let target = current_cum?.checked_add(delta)?; + if target < 0 || target > total_max { + return None; + } + for (i, &(ord, block_id, start, len)) in editable_spans.iter().enumerate() { + let end = start + len; + if target <= end { + let local = (target - start).clamp(0, len) as u32; + return Some(( + SelectionEndpointAnchor::Doc(DocPoint::new( + block_id, + u64::from(local), + )), + ord, + local, + )); + } + // Target landed on the virtual `\n` separator between block `i` and `i+1`. + if target == end + 1 && i + 1 < editable_spans.len() { + let (next_ord, next_id, _, _) = editable_spans[i + 1]; + return Some(( + SelectionEndpointAnchor::Doc(DocPoint::new(next_id, 0)), + next_ord, + 0, + )); + } + } + None + }) + }) + .ok() + .flatten()?; + let (next_ep, ord, off) = cross; + let next_tok = self.intern_endpoint_token(next_ep); + Some(AffineDocPosition { + valid: true, + block_order: ord, + utf16_offset: off, + endpoint_token: next_tok, + }) + } + + pub(crate) fn doc_word_range( + &mut self, + token: u64, + ) -> Option<(AffineDocPosition, AffineDocPosition)> { + let anchor = self.lookup_endpoint_token(token)?; + let view = self.view; + let ((s_ep, s_ord, s_off), (e_ep, e_ord, e_off)) = self + .app + .update(|cx| view.read_with(cx, |v, _| v.word_anchors_at(&anchor))) + .ok() + .flatten()?; + let s_tok = self.intern_endpoint_token(s_ep); + let e_tok = self.intern_endpoint_token(e_ep); + Some(( + AffineDocPosition { + valid: true, + block_order: s_ord, + utf16_offset: s_off, + endpoint_token: s_tok, + }, + AffineDocPosition { + valid: true, + block_order: e_ord, + utf16_offset: e_off, + endpoint_token: e_tok, + }, + )) + } + + pub(crate) fn doc_offset_between_tokens(&mut self, from_token: u64, to_token: u64) -> i32 { + let (Some(a), Some(b)) = ( + self.lookup_endpoint_token(from_token), + self.lookup_endpoint_token(to_token), + ) else { + return 0; + }; + let view = self.view; + self.app + .update(|cx| view.read_with(cx, |v, _| v.offset_between_anchors(&a, &b))) + .unwrap_or(0) + } + + pub(crate) fn doc_text_between_tokens(&mut self, start_token: u64, end_token: u64) -> String { + let (Some(a), Some(b)) = ( + self.lookup_endpoint_token(start_token), + self.lookup_endpoint_token(end_token), + ) else { + return String::new(); + }; + let view = self.view; + self.app + .update(|cx| view.read_with(cx, |v, _| v.plain_text_between_anchors(&a, &b))) + .unwrap_or_default() + } + + pub(crate) fn document_selection_geometry(&mut self) -> playground::DocumentSelectionGeometry { + self.app + .update(|cx| { + self.view.update(cx, |view, window, _| { + view.document_selection_geometry(window) + }) + }) + .unwrap_or_default() + } + + pub(crate) fn begin_document_selection_drag(&mut self, handle: u8) -> bool { + self.app + .update(|cx| { + self.view.update(cx, |view, window, _| { + view.begin_document_selection_drag(handle, window) + }) + }) + .unwrap_or(false) + } + + pub(crate) fn update_document_selection_drag(&mut self, x: f32, y: f32) -> bool { + let ok = self + .app + .update(|cx| { + self.view.update(cx, |view, window, cx| { + view.update_document_selection_drag(x, y, window, cx) + }) + }) + .unwrap_or(false); + if ok { + self.window.request_frame_now(); + } + ok + } + + pub(crate) fn end_document_selection_drag(&mut self) { + let _ = self.app.update(|cx| { + let _ = self.view.update(cx, |view, window, cx| { + view.end_document_selection_drag(window, cx) + }); + }); + self.window.request_frame_now(); + } + + pub(crate) fn intern_endpoint_token( + &mut self, + endpoint: playground::SelectionEndpointAnchor, + ) -> u64 { + if let Some((tok, _)) = self + .endpoint_tokens + .iter() + .find(|(_, existing)| *existing == endpoint) + { + return *tok; + } + let tok = self.next_endpoint_token; + self.next_endpoint_token = self.next_endpoint_token.wrapping_add(1).max(1); + if self.endpoint_tokens.len() >= 4096 { + let active = self + .app + .update(|cx| { + self.view + .read_with(cx, |v, _| v.ordered_selection_endpoints()) + }) + .ok() + .flatten(); + if let Some(evict_idx) = self + .endpoint_tokens + .iter() + .position(|(_, ep)| active.as_ref().is_none_or(|(s, e)| ep != s && ep != e)) + { + self.endpoint_tokens.remove(evict_idx); + } else { + self.endpoint_tokens.remove(0); + } + } + self.endpoint_tokens.push((tok, endpoint)); + tok + } + + pub(crate) fn current_selection_endpoint_tokens(&mut self) -> (u64, u64) { + let pair = self + .app + .update(|cx| { + self.view + .read_with(cx, |view, _| view.ordered_selection_endpoints()) + }) + .ok() + .flatten(); + let Some((start_ep, end_ep)) = pair else { + return (0, 0); + }; + let s = self.intern_endpoint_token(start_ep); + let e = self.intern_endpoint_token(end_ep); + (s, e) + } + + pub(crate) fn lookup_endpoint_token( + &self, + token: u64, + ) -> Option { + self.endpoint_tokens + .iter() + .find(|(t, _)| *t == token) + .map(|(_, ep)| ep.clone()) + } + + pub(crate) fn select_from_endpoint_token( + &mut self, + fixed_token: u64, + fx: f32, + fy: f32, + ) -> bool { + let Some(fixed) = self.lookup_endpoint_token(fixed_token) else { + return false; + }; + let ok = self + .app + .update(|cx| { + self.view.update(cx, |view, window, cx| { + view.select_from_anchor_to_viewport_point(fixed, fx, fy, window, cx) + }) + }) + .unwrap_or(false); + if ok { + self.window.request_frame_now(); + } + ok + } + + pub(crate) fn select_between_viewport_points( + &mut self, + ax: f32, + ay: f32, + fx: f32, + fy: f32, + ) -> bool { + let ok = self + .app + .update(|cx| { + self.view.update(cx, |view, window, cx| { + view.select_between_viewport_points(ax, ay, fx, fy, window, cx) + }) + }) + .unwrap_or(false); + if ok { + self.window.request_frame_now(); + } + ok + } + + pub(crate) fn select_between_endpoint_tokens( + &mut self, + start_token: u64, + end_token: u64, + ) -> bool { + let (Some(start), Some(end)) = ( + self.lookup_endpoint_token(start_token), + self.lookup_endpoint_token(end_token), + ) else { + return false; + }; + let ok = self + .app + .update(|cx| { + self.view.update(cx, |view, window, cx| { + view.select_between_anchors(start, end, window, cx) + }) + }) + .unwrap_or(false); + if ok { + self.window.request_frame_now(); + } + ok + } + + pub(crate) fn selection_copy(&mut self) { + let _ = self.app.update(|cx| { + let _ = self + .view + .update(cx, |view, window, cx| view.selection_copy(window, cx)); + }); + self.window.request_frame_now(); + } + + pub(crate) fn selection_cut(&mut self) { + let _ = self.app.update(|cx| { + let _ = self + .view + .update(cx, |view, window, cx| view.selection_cut(window, cx)); + }); + self.window.request_frame_now(); + } + + pub(crate) fn selection_paste(&mut self) { + let _ = self.app.update(|cx| { + let _ = self + .view + .update(cx, |view, window, cx| view.selection_paste(window, cx)); + }); + self.window.request_frame_now(); + } + + pub(crate) fn selection_select_all(&mut self) { + let _ = self.app.update(|cx| { + let _ = self + .view + .update(cx, |view, window, cx| view.selection_select_all(window, cx)); + }); + self.window.request_frame_now(); + } +} + +#[cfg(test)] +mod tests { + use playground::FormFactor; + + use crate::{ + AffineUtf16Range, AffineWindowInsets, editor_runtime::IosEditorRuntime, + selection::AffinePoint, + }; + + #[test] + fn full_document_bounds_cross_block_step_and_transient_kb_inset_do_not_lock() { + let mut rt = + IosEditorRuntime::new(390.0, 844.0, 3.0, FormFactor::Phone, false).expect("runtime"); + let p1: Vec = "甲乙丙丁🚀".encode_utf16().collect(); + rt.insert_text(&p1); + let nl: Vec = "\n".encode_utf16().collect(); + let p2: Vec = "Second paragraph".encode_utf16().collect(); + rt.insert_text(&nl); + rt.insert_text(&p2); + let _ = rt.render_frame(1.0); + + // Full-document bounds must span from block 0 offset 0 to last editable block's end, + // even when a different block is focused. + let (doc_start, doc_end) = rt.doc_document_bounds().expect("doc bounds"); + assert!(doc_start.valid && doc_end.valid); + assert!( + doc_end.block_order > doc_start.block_order, + "endOfDocument must reach the last editable block, not just focused block" + ); + let total_len = + rt.doc_offset_between_tokens(doc_start.endpoint_token, doc_end.endpoint_token); + assert!(total_len >= (p1.len() + 1 + p2.len()) as i32); + + // Stepping from doc_start across the first block boundary lands cleanly in the next block. + let stepped = rt + .doc_step_position(doc_start.endpoint_token, (total_len - 1).max(1) as isize) + .expect("cross-block step"); + assert!(stepped.block_order > doc_start.block_order); + + // Transient keyboard inset 300 -> 0 must not self-lock wants_software_keyboard(). + assert!(rt.wants_software_keyboard()); + rt.set_insets(AffineWindowInsets { + safe_top: 59.0, + safe_right: 0.0, + safe_bottom: 34.0, + safe_left: 0.0, + ime_bottom: 300.0, + }); + assert!(rt.wants_software_keyboard()); + rt.set_insets(AffineWindowInsets { + safe_top: 59.0, + safe_right: 0.0, + safe_bottom: 34.0, + safe_left: 0.0, + ime_bottom: 0.0, + }); + assert!( + rt.wants_software_keyboard(), + "transient ime_bottom -> 0 must never self-lock software keyboard" + ); + + // Read-only hit-test in an unfocused block must never mutate focused block. + let focused_before = rt.focused_block_order(); + let c0 = rt.caret_rect(0).expect("caret"); + let _ = rt.closest_offset(AffinePoint { + x: c0.x, + y: c0.y + c0.height * 0.5, + }); + assert_eq!(rt.focused_block_order(), focused_before); + let _ = AffineUtf16Range { + location: 0, + length: 0, + }; + } +} diff --git a/packages/frontend/hosts/ios/src/editor_platform.rs b/packages/frontend/hosts/ios/src/editor_platform.rs index 7d37d7f573..1d91f2ec67 100644 --- a/packages/frontend/hosts/ios/src/editor_platform.rs +++ b/packages/frontend/hosts/ios/src/editor_platform.rs @@ -509,7 +509,7 @@ pub(crate) struct IosEditorPlatform { initial_bounds: Bounds, initial_scale: f32, opened_window: RefCell>, - clipboard: RefCell>, + pub(crate) clipboard: super::clipboard::IosClipboardStore, open_url_observer: RefCell>, } @@ -554,7 +554,7 @@ impl IosEditorPlatform { 2.0 }, opened_window: RefCell::new(None), - clipboard: RefCell::new(None), + clipboard: super::clipboard::IosClipboardStore::default(), open_url_observer: RefCell::new(None), } } @@ -727,11 +727,11 @@ impl Platform for IosEditorPlatform { } fn write_to_clipboard(&self, item: ClipboardItem) { - *self.clipboard.borrow_mut() = Some(item); + self.clipboard.write(item); } fn read_from_clipboard(&self) -> Option { - self.clipboard.borrow().clone() + self.clipboard.read() } #[cfg(target_os = "linux")] diff --git a/packages/frontend/hosts/ios/src/editor_runtime.rs b/packages/frontend/hosts/ios/src/editor_runtime.rs index 50d148ecb0..7666ad1c9d 100644 --- a/packages/frontend/hosts/ios/src/editor_runtime.rs +++ b/packages/frontend/hosts/ios/src/editor_runtime.rs @@ -67,6 +67,8 @@ pub(crate) struct IosEditorRuntime { form_factor: FormFactor, frame_count: u64, last_frame_timestamp_sec: f64, + pub(crate) endpoint_tokens: Vec<(u64, playground::SelectionEndpointAnchor)>, + pub(crate) next_endpoint_token: u64, } impl IosEditorRuntime { @@ -99,7 +101,9 @@ impl IosEditorRuntime { Rc::new(std::cell::RefCell::new(None)); let view_slot_init = Rc::clone(&view_slot); - let options = PlaygroundOptions::for_form_factor(form_factor); + let mut options = PlaygroundOptions::for_form_factor(form_factor); + options.native_selection_ui = true; + options.native_suppresses_gpu_caret_and_selection = true; let bounds = Bounds::new(point(px(0.0), px(0.0)), size(px(w), px(h))); let app = Application::with_platform(platform).run_embedded(move |cx| { @@ -141,6 +145,8 @@ impl IosEditorRuntime { form_factor, frame_count: 0, last_frame_timestamp_sec: 0.0, + endpoint_tokens: Vec::with_capacity(256), + next_endpoint_token: 1, }; // Render initial frame so layout and `PlatformInputHandler` are live immediately. runtime.window.request_frame_now(); @@ -178,8 +184,16 @@ impl IosEditorRuntime { }; let prev = self.window.state.borrow().insets.clone(); if prev != ui_insets { + let was_wants_keyboard = self.wants_software_keyboard(); self.window.set_insets(ui_insets); self.window.request_frame_now(); + // Prevent transient `ime_bottom == 0` samples during `becomeFirstResponder` or + // keyboard frame transitions from flipping `keyboard_toolbar_dismissed = true` + // in `PlaygroundView::render`. Explicit toolbar dismiss already cleared + // `wants_software_keyboard()` before this inset update arrived. + if ime_above_safe == 0.0 && was_wants_keyboard && !self.wants_software_keyboard() { + self.restore_software_keyboard(); + } } } @@ -467,6 +481,7 @@ impl IosEditorRuntime { pub(crate) fn set_selected_range(&mut self, range: AffineUtf16Range) { self.ensure_input_handler(); + self.restore_software_keyboard(); let start = range.location as usize; let end = start.saturating_add(range.length as usize); let _ = self @@ -540,11 +555,14 @@ impl IosEditorRuntime { pub(crate) fn closest_offset(&mut self, pt: AffinePoint) -> Option { self.ensure_input_handler(); - let off = self + if let Some(off) = self .window .with_input_handler(|h| h.character_index_for_point(point(px(pt.x), px(pt.y)))) - .flatten()?; - Some(off.min(u32::MAX as usize) as u32) + .flatten() + { + return Some(off.min(u32::MAX as usize) as u32); + } + self.doc_hit_position(pt.x, pt.y).map(|p| p.utf16_offset) } pub(crate) fn change_kind_code(change: TextInputStateChange) -> u8 { @@ -555,6 +573,40 @@ impl IosEditorRuntime { TextInputStateChange::ContentChanged => 4, } } + + pub(crate) fn set_clipboard_provider( + &self, + provider: Option, + ) { + self.platform.clipboard.set_provider(provider); + } + + pub(crate) fn set_page_readonly(&mut self, readonly: bool) { + let _ = self.app.update(|cx| { + let _ = self + .view + .update(cx, |view, _, cx| view.set_page_readonly(readonly, cx)); + }); + self.window.request_frame_now(); + } + + pub(crate) fn is_surface_readonly(&self) -> bool { + self.app + .update(|cx| { + self.view.read_with(cx, |view, _| match view.mode() { + PlaygroundMode::Page => view.page_readonly(), + PlaygroundMode::Edgeless => view.edgeless_readonly(), + }) + }) + .unwrap_or(true) + } + + pub(crate) fn restore_software_keyboard(&mut self) { + let view = self.view; + let _ = self.app.update(|cx| { + let _ = view.update(cx, |v, _, _| v.restore_software_keyboard_on_focus()); + }); + } } #[cfg(test)] diff --git a/packages/frontend/hosts/ios/src/ffi_doc_positions.rs b/packages/frontend/hosts/ios/src/ffi_doc_positions.rs new file mode 100644 index 0000000000..dc7f2c383c --- /dev/null +++ b/packages/frontend/hosts/ios/src/ffi_doc_positions.rs @@ -0,0 +1,278 @@ +#![allow(unsafe_code)] + +//! C-ABI exports for pure read-only full-document `UITextPosition` queries, +//! document bounds, cross-block stepping, word boundaries, caret rects, and selection rects. + +use std::ffi::CString; + +use super::{ + editor_doc_positions::AffineDocPosition, ffi::AffineIosHost, + ffi_selection::AffineDocumentSelectionRect, selection::AffineRect, +}; + +fn to_affine_rect(r: playground::SelectionRectGeometry) -> AffineRect { + AffineRect { + x: r.x, + y: r.y, + width: r.width, + height: r.height, + } +} + +/// Layout index (`0..`) of the currently focused block. +/// +/// # 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_focused_block_order(host: *const AffineIosHost) -> i32 { + let Some(host) = (unsafe { host.as_ref() }) else { + return 0; + }; + host.editor + .borrow_mut() + .as_mut() + .map_or(0, |e| e.focused_block_order()) +} + +/// Query full-document addressable bounds `(beginningOfDocument, endOfDocument)` across all +/// editable blocks in layout order. +/// +/// # Safety +/// `host` must be null or a live pointer; `out_start` and `out_end` may be null or writable pointers. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_doc_document_bounds( + host: *const AffineIosHost, + out_start: *mut AffineDocPosition, + out_end: *mut AffineDocPosition, +) -> bool { + let Some(host) = (unsafe { host.as_ref() }) else { + return false; + }; + let Some((s, e)) = host + .editor + .borrow_mut() + .as_mut() + .and_then(|ed| ed.doc_document_bounds()) + else { + return false; + }; + if !out_start.is_null() { + unsafe { *out_start = s }; + } + if !out_end.is_null() { + unsafe { *out_end = e }; + } + true +} + +/// Query ordered `(start, end)` `AffineDocPosition`s for the active selection (collapsed or range). +/// +/// # Safety +/// `host` must be null or a live pointer; `out_start` and `out_end` may be null or writable pointers. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_doc_selection_positions( + host: *const AffineIosHost, + out_start: *mut AffineDocPosition, + out_end: *mut AffineDocPosition, +) -> bool { + let Some(host) = (unsafe { host.as_ref() }) else { + return false; + }; + let Some((s, e)) = host + .editor + .borrow_mut() + .as_mut() + .and_then(|ed| ed.current_selection_doc_positions()) + else { + return false; + }; + if !out_start.is_null() { + unsafe { *out_start = s }; + } + if !out_end.is_null() { + unsafe { *out_end = e }; + } + true +} + +/// Pure read-only viewport hit-test returning `AffineDocPosition` (`valid = false` when no text hit). +/// Never mutates `editor.selection` or focused block 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_doc_hit_position( + host: *const AffineIosHost, + x: f32, + y: f32, +) -> AffineDocPosition { + let Some(host) = (unsafe { host.as_ref() }) else { + return AffineDocPosition::default(); + }; + host.editor + .borrow_mut() + .as_mut() + .and_then(|ed| ed.doc_hit_position(x, y)) + .unwrap_or_default() +} + +/// Pure read-only viewport caret rectangle for an interned `endpoint_token`. +/// +/// # Safety +/// `host` must be null or a live pointer; `out_rect` may be null or a writable pointer. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_doc_caret_rect_for_token( + host: *const AffineIosHost, + endpoint_token: u64, + out_rect: *mut AffineRect, +) -> bool { + let Some(host) = (unsafe { host.as_ref() }) else { + return false; + }; + let Some(rect) = host + .editor + .borrow_mut() + .as_mut() + .and_then(|ed| ed.doc_caret_rect_for_token(endpoint_token)) + else { + return false; + }; + if !out_rect.is_null() { + unsafe { *out_rect = rect }; + } + true +} + +/// Pure read-only selection rectangles between two interned endpoint tokens. +/// +/// # 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_doc_selection_rects_between_tokens( + host: *const AffineIosHost, + start_endpoint_token: u64, + end_endpoint_token: u64, + out_rects: *mut AffineDocumentSelectionRect, + capacity: usize, +) -> usize { + let Some(host) = (unsafe { host.as_ref() }) else { + return 0; + }; + let raw = host + .editor + .borrow_mut() + .as_mut() + .map(|ed| ed.doc_selection_rects_between_tokens(start_endpoint_token, end_endpoint_token)) + .unwrap_or_default(); + let mapped: Vec = raw + .into_iter() + .map(|r| AffineDocumentSelectionRect { + rect: to_affine_rect(r), + is_rtl: r.is_rtl, + contains_start: r.contains_start, + contains_end: r.contains_end, + }) + .collect(); + if !out_rects.is_null() && capacity > 0 && !mapped.is_empty() { + let count = mapped.len().min(capacity); + unsafe { + core::ptr::copy_nonoverlapping(mapped.as_ptr(), out_rects, count); + } + } + mapped.len() +} + +/// Step `delta` UTF-16 code units from `endpoint_token` across addressable document blocks. +/// +/// # 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_doc_step_position( + host: *const AffineIosHost, + endpoint_token: u64, + delta: isize, +) -> AffineDocPosition { + let Some(host) = (unsafe { host.as_ref() }) else { + return AffineDocPosition::default(); + }; + host.editor + .borrow_mut() + .as_mut() + .and_then(|ed| ed.doc_step_position(endpoint_token, delta)) + .unwrap_or_default() +} + +/// Resolve authoritative ICU word boundaries `(out_start, out_end)` around `endpoint_token`. +/// +/// # Safety +/// `host` must be null or a live pointer; `out_start` and `out_end` may be null or writable pointers. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_doc_word_range( + host: *const AffineIosHost, + endpoint_token: u64, + out_start: *mut AffineDocPosition, + out_end: *mut AffineDocPosition, +) -> bool { + let Some(host) = (unsafe { host.as_ref() }) else { + return false; + }; + let Some((s, e)) = host + .editor + .borrow_mut() + .as_mut() + .and_then(|ed| ed.doc_word_range(endpoint_token)) + else { + return false; + }; + if !out_start.is_null() { + unsafe { *out_start = s }; + } + if !out_end.is_null() { + unsafe { *out_end = e }; + } + true +} + +/// Signed UTF-16 offset distance from `from_token` to `to_token` across document blocks. +/// +/// # 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_doc_offset_between_tokens( + host: *const AffineIosHost, + from_token: u64, + to_token: u64, +) -> i32 { + let Some(host) = (unsafe { host.as_ref() }) else { + return 0; + }; + host.editor + .borrow_mut() + .as_mut() + .map_or(0, |ed| ed.doc_offset_between_tokens(from_token, to_token)) +} + +/// Newly allocated UTF-8 C string of plain text between two interned endpoint tokens +/// (caller frees via `affine_ios_string_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_doc_text_between_tokens( + host: *const AffineIosHost, + start_endpoint_token: u64, + end_endpoint_token: u64, +) -> *mut core::ffi::c_char { + let Some(host) = (unsafe { host.as_ref() }) else { + return core::ptr::null_mut(); + }; + let s = host + .editor + .borrow_mut() + .as_mut() + .map(|ed| ed.doc_text_between_tokens(start_endpoint_token, end_endpoint_token)) + .unwrap_or_default(); + CString::new(s) + .map(CString::into_raw) + .unwrap_or(core::ptr::null_mut()) +} diff --git a/packages/frontend/hosts/ios/src/ffi_selection.rs b/packages/frontend/hosts/ios/src/ffi_selection.rs new file mode 100644 index 0000000000..2573f5626e --- /dev/null +++ b/packages/frontend/hosts/ios/src/ffi_selection.rs @@ -0,0 +1,614 @@ +#![allow(unsafe_code)] + +//! C-ABI exports for document-level selection geometry, cross-block handle drag, +//! live drag preview, authoritative selection actions, keyboard-focus restoration, +//! and multi-MIME `UIPasteboard` bridging. + +use std::ffi::CString; + +use super::{ + clipboard::AffineClipboardProvider, editor_runtime::IosEditorRuntime, ffi::AffineIosHost, + ffi_editor::flush_text_input_changes, selection::AffineRect, +}; + +/// C-ABI document-level selection geometry and capabilities snapshot. +#[repr(C)] +#[derive(Clone, Copy, Debug, Default)] +pub struct AffineDocumentSelectionSnapshot { + pub has_selection: bool, + pub is_collapsed: bool, + pub is_reversed: bool, + pub start_is_rtl: bool, + pub end_is_rtl: bool, + pub start_visible: bool, + pub end_visible: bool, + pub menu_anchor_visible: bool, + pub menu_suppressed_for_motion: bool, + pub start_caret: AffineRect, + pub end_caret: AffineRect, + pub menu_anchor_rect: AffineRect, + pub action_mask: u32, + pub menu_request_seq: u64, + pub rect_count: usize, +} + +/// C-ABI per-line/per-block document selection rect with writing direction. +#[repr(C)] +#[derive(Clone, Copy, Debug, Default)] +pub struct AffineDocumentSelectionRect { + pub rect: AffineRect, + pub is_rtl: bool, + pub contains_start: bool, + pub contains_end: bool, +} + +fn to_affine_rect(r: playground::SelectionRectGeometry) -> AffineRect { + AffineRect { + x: r.x, + y: r.y, + width: r.width, + height: r.height, + } +} + +/// Register the Swift `UIPasteboard.general` multi-MIME clipboard 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_clipboard_provider( + host: *mut AffineIosHost, + provider: AffineClipboardProvider, +) { + let Some(host) = (unsafe { host.as_ref() }) else { + return; + }; + let opt = if provider.write_json.is_none() && provider.read_json.is_none() { + None + } else { + Some(provider) + }; + if let Some(editor) = host.editor.borrow().as_ref() { + editor.set_clipboard_provider(opt); + } +} + +/// Toggle Page-mode read-only gating on the mounted editor. +/// +/// # 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_set_page_readonly( + host: *mut AffineIosHost, + readonly: bool, +) { + let Some(host) = (unsafe { host.as_mut() }) else { + return; + }; + if let Some(editor) = host.editor.borrow_mut().as_mut() { + editor.set_page_readonly(readonly); + } +} + +/// Returns `true` when the active editor surface is read-only (Page readonly or Edgeless readonly). +/// +/// # 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_is_surface_readonly(host: *const AffineIosHost) -> bool { + let Some(host) = (unsafe { host.as_ref() }) else { + return true; + }; + host.editor + .borrow() + .as_ref() + .map_or(true, IosEditorRuntime::is_surface_readonly) +} + +/// Re-enable software keyboard requests before `becomeFirstResponder` on an editable focus. +/// +/// # 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_restore_software_keyboard(host: *mut AffineIosHost) { + let Some(host) = (unsafe { host.as_mut() }) else { + return; + }; + if let Some(editor) = host.editor.borrow_mut().as_mut() { + editor.restore_software_keyboard(); + } +} + +/// Query document-level selection geometry, visibility, action mask, and menu request seq. +/// +/// # 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_document_selection_snapshot( + host: *const AffineIosHost, +) -> AffineDocumentSelectionSnapshot { + let Some(host) = (unsafe { host.as_ref() }) else { + return AffineDocumentSelectionSnapshot::default(); + }; + let Some(geom) = host + .editor + .borrow_mut() + .as_mut() + .map(IosEditorRuntime::document_selection_geometry) + else { + return AffineDocumentSelectionSnapshot::default(); + }; + AffineDocumentSelectionSnapshot { + has_selection: geom.has_selection, + is_collapsed: geom.is_collapsed, + is_reversed: geom.is_reversed, + start_is_rtl: geom.start_caret.is_rtl, + end_is_rtl: geom.end_caret.is_rtl, + start_visible: geom.start_visible, + end_visible: geom.end_visible, + menu_anchor_visible: geom.menu_anchor_visible, + menu_suppressed_for_motion: geom.menu_suppressed_for_motion, + start_caret: to_affine_rect(geom.start_caret), + end_caret: to_affine_rect(geom.end_caret), + menu_anchor_rect: to_affine_rect(geom.menu_anchor_rect), + action_mask: geom.action_mask, + menu_request_seq: geom.menu_request_seq, + rect_count: geom.selection_rects.len(), + } +} + +/// Intern and return `(start_token, end_token)` for the current ordered non-collapsed selection. +/// +/// # Safety +/// `host` must be null or a live pointer; `out_start` and `out_end` may be null or writable pointers. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn affine_ios_host_doc_selection_endpoint_tokens( + host: *const AffineIosHost, + out_start: *mut u64, + out_end: *mut u64, +) { + let (mut s, mut e) = (0u64, 0u64); + if let Some(host) = unsafe { host.as_ref() } + && let Some(editor) = host.editor.borrow_mut().as_mut() + { + (s, e) = editor.current_selection_endpoint_tokens(); + } + if !out_start.is_null() { + unsafe { *out_start = s }; + } + if !out_end.is_null() { + unsafe { *out_end = e }; + } +} + +/// Copy per-line/per-block document selection rects into `out_rects` (up to `capacity`). +/// +/// # 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_document_selection_rects( + host: *const AffineIosHost, + out_rects: *mut AffineDocumentSelectionRect, + capacity: usize, +) -> usize { + let Some(host) = (unsafe { host.as_ref() }) else { + return 0; + }; + let Some(geom) = host + .editor + .borrow_mut() + .as_mut() + .map(IosEditorRuntime::document_selection_geometry) + else { + return 0; + }; + let mapped: Vec = geom + .selection_rects + .into_iter() + .map(|r| AffineDocumentSelectionRect { + rect: to_affine_rect(r), + is_rtl: r.is_rtl, + contains_start: r.contains_start, + contains_end: r.contains_end, + }) + .collect(); + if !out_rects.is_null() && capacity > 0 && !mapped.is_empty() { + let count = mapped.len().min(capacity); + unsafe { + core::ptr::copy_nonoverlapping(mapped.as_ptr(), out_rects, count); + } + } + mapped.len() +} + +/// Preview document selection rects from `fixed_endpoint_token` to viewport `(fx, fy)` without mutating selection. +/// +/// # 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_doc_selection_preview_rects( + host: *const AffineIosHost, + fixed_endpoint_token: u64, + fx: f32, + fy: f32, + out_rects: *mut AffineDocumentSelectionRect, + capacity: usize, +) -> usize { + let Some(host) = (unsafe { host.as_ref() }) else { + return 0; + }; + let mut editor_ref = host.editor.borrow_mut(); + let Some(editor) = editor_ref.as_mut() else { + return 0; + }; + let Some(fixed) = editor.lookup_endpoint_token(fixed_endpoint_token) else { + return 0; + }; + let view = editor.view; + let raw = editor + .app + .update(|cx| { + view.update(cx, |v, w, _| { + v.preview_selection_rects_for_drag(fixed, fx, fy, w) + }) + }) + .unwrap_or_default(); + let mapped: Vec = raw + .into_iter() + .map(|r| AffineDocumentSelectionRect { + rect: to_affine_rect(r), + is_rtl: r.is_rtl, + contains_start: r.contains_start, + contains_end: r.contains_end, + }) + .collect(); + if !out_rects.is_null() && capacity > 0 && !mapped.is_empty() { + let count = mapped.len().min(capacity); + unsafe { + core::ptr::copy_nonoverlapping(mapped.as_ptr(), out_rects, count); + } + } + mapped.len() +} + +/// Query document-level caret rect at viewport point `(x, y)`. +/// +/// # 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_doc_caret_rect_at_point( + host: *const AffineIosHost, + x: f32, + y: f32, + out_rect: *mut AffineRect, +) -> bool { + let Some(host) = (unsafe { host.as_ref() }) else { + return false; + }; + let mut editor_ref = host.editor.borrow_mut(); + let Some(editor) = editor_ref.as_mut() else { + return false; + }; + let view = editor.view; + let Some(r) = editor + .app + .update(|cx| view.update(cx, |v, w, _| v.caret_rect_at_viewport_point(x, y, w))) + .ok() + .flatten() + else { + return false; + }; + if !out_rect.is_null() { + unsafe { *out_rect = to_affine_rect(r) }; + } + true +} + +/// Return newly allocated UTF-8 C string of the active single-block or cross-block selected text +/// (caller frees via `affine_ios_string_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_selected_plain_text( + host: *const AffineIosHost, +) -> *mut core::ffi::c_char { + let Some(host) = (unsafe { host.as_ref() }) else { + return core::ptr::null_mut(); + }; + let mut editor_ref = host.editor.borrow_mut(); + let Some(editor) = editor_ref.as_mut() else { + return core::ptr::null_mut(); + }; + let view = editor.view; + let s = editor + .app + .update(|cx| view.read_with(cx, |v, _| v.selected_plain_text())) + .unwrap_or_default(); + CString::new(s) + .map(CString::into_raw) + .unwrap_or(core::ptr::null_mut()) +} + +/// Returns `true` when an iOS touch starting at `(x, y)` hits chrome, overlays, Edgeless, or +/// non-text interactive widgets and should bypass `UITextInteraction` tap buffering. +/// +/// # 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_should_forward_touch_immediately( + host: *const AffineIosHost, + x: f32, + y: f32, +) -> bool { + let Some(host) = (unsafe { host.as_ref() }) else { + return false; + }; + let mut editor_ref = host.editor.borrow_mut(); + let Some(editor) = editor_ref.as_mut() else { + return false; + }; + let view = editor.view; + editor + .app + .update(|cx| { + view.update(cx, |v, w, _| { + v.should_forward_ios_touch_immediately(x, y, w) + }) + }) + .unwrap_or(false) +} + +/// Select the word at `(x, y)` and bump `menu_request_seq` (used on read-only stationary long-press). +/// +/// # 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_select_word_at_point( + host: *mut AffineIosHost, + x: f32, + y: f32, +) -> bool { + let Some(host) = (unsafe { host.as_mut() }) else { + return false; + }; + let ok = if let Some(editor) = host.editor.borrow_mut().as_mut() { + let view = editor.view; + let selected = editor + .app + .update(|cx| view.update(cx, |v, w, cx| v.select_word_at_viewport_point(x, y, w, cx))) + .unwrap_or(false); + if selected { + editor.window.request_frame_now(); + } + selected + } else { + false + }; + if ok { + flush_text_input_changes(host); + host.state.request_frame(); + } + ok +} + +/// Increment `selection_menu_request_seq` when UIKit finishes a selection gesture. +/// +/// # 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_bump_selection_menu_request_seq(host: *mut AffineIosHost) { + let Some(host) = (unsafe { host.as_mut() }) else { + return; + }; + if let Some(editor) = host.editor.borrow_mut().as_mut() { + let view = editor.view; + let _ = editor.app.update(|cx| { + let _ = view.update(cx, |v, w, _| { + if v.document_selection_geometry(w).action_mask != 0 { + v.bump_selection_menu_request_seq(); + } + }); + }); + } + host.state.request_frame(); +} + +/// Begin dragging a document-level selection handle (`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_doc_selection_begin_drag( + host: *mut AffineIosHost, + handle: u8, +) -> bool { + let Some(host) = (unsafe { host.as_mut() }) else { + return false; + }; + host.editor + .borrow_mut() + .as_mut() + .is_some_and(|e| e.begin_document_selection_drag(handle)) +} + +/// Update an active document-level selection handle drag to viewport point `(x, y)`. +/// +/// # 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_doc_selection_update_drag( + host: *mut AffineIosHost, + x: f32, + y: f32, +) -> bool { + let Some(host) = (unsafe { host.as_mut() }) else { + return false; + }; + let ok = host + .editor + .borrow_mut() + .as_mut() + .is_some_and(|e| e.update_document_selection_drag(x, y)); + if ok { + flush_text_input_changes(host); + host.state.request_frame(); + } + ok +} + +/// Finish an active document-level selection handle 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_doc_selection_end_drag(host: *mut AffineIosHost) { + let Some(host) = (unsafe { host.as_mut() }) else { + return; + }; + if let Some(editor) = host.editor.borrow_mut().as_mut() { + editor.end_document_selection_drag(); + } + flush_text_input_changes(host); + host.state.request_frame(); +} + +/// Update document-level selection from an interned endpoint token to viewport point `(fx, fy)`. +/// +/// # 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_doc_selection_select_from_endpoint_token( + host: *mut AffineIosHost, + fixed_endpoint_token: u64, + fx: f32, + fy: f32, +) -> bool { + let Some(host) = (unsafe { host.as_mut() }) else { + return false; + }; + let ok = host + .editor + .borrow_mut() + .as_mut() + .is_some_and(|e| e.select_from_endpoint_token(fixed_endpoint_token, fx, fy)); + if ok { + flush_text_input_changes(host); + host.state.request_frame(); + } + ok +} + +/// Update document-level selection directly between two viewport points `(ax, ay)` and `(fx, fy)`. +/// +/// # 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_doc_selection_select_between_points( + host: *mut AffineIosHost, + ax: f32, + ay: f32, + fx: f32, + fy: f32, +) -> bool { + let Some(host) = (unsafe { host.as_mut() }) else { + return false; + }; + let ok = host + .editor + .borrow_mut() + .as_mut() + .is_some_and(|e| e.select_between_viewport_points(ax, ay, fx, fy)); + if ok { + flush_text_input_changes(host); + host.state.request_frame(); + } + ok +} + +/// Update document-level selection directly between two interned endpoint tokens. +/// +/// # 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_doc_selection_select_between_endpoint_tokens( + host: *mut AffineIosHost, + start_endpoint_token: u64, + end_endpoint_token: u64, +) -> bool { + let Some(host) = (unsafe { host.as_mut() }) else { + return false; + }; + let ok = host.editor.borrow_mut().as_mut().is_some_and(|e| { + e.select_between_endpoint_tokens(start_endpoint_token, end_endpoint_token) + }); + if ok { + flush_text_input_changes(host); + host.state.request_frame(); + } + ok +} + +/// Execute editor-authoritative `Copy` (writes rich multi-MIME slice to `UIPasteboard`). +/// +/// # 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_action_copy(host: *mut AffineIosHost) { + let Some(host) = (unsafe { host.as_mut() }) else { + return; + }; + if let Some(editor) = host.editor.borrow_mut().as_mut() { + editor.selection_copy(); + } + flush_text_input_changes(host); + host.state.request_frame(); +} + +/// Execute editor-authoritative `Cut` (blocked in read-only modes). +/// +/// # 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_action_cut(host: *mut AffineIosHost) { + let Some(host) = (unsafe { host.as_mut() }) else { + return; + }; + if let Some(editor) = host.editor.borrow_mut().as_mut() { + editor.selection_cut(); + } + flush_text_input_changes(host); + host.state.request_frame(); +} + +/// Execute editor-authoritative `Paste` (reads multi-MIME `UIPasteboard`, blocked in read-only modes). +/// +/// # 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_action_paste(host: *mut AffineIosHost) { + let Some(host) = (unsafe { host.as_mut() }) else { + return; + }; + if let Some(editor) = host.editor.borrow_mut().as_mut() { + editor.selection_paste(); + } + flush_text_input_changes(host); + host.state.request_frame(); +} + +/// Execute editor-authoritative `Select All`. +/// +/// # 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_action_select_all(host: *mut AffineIosHost) { + let Some(host) = (unsafe { host.as_mut() }) else { + return; + }; + if let Some(editor) = host.editor.borrow_mut().as_mut() { + editor.selection_select_all(); + } + flush_text_input_changes(host); + host.state.request_frame(); +} diff --git a/packages/frontend/hosts/ios/src/lib.rs b/packages/frontend/hosts/ios/src/lib.rs index 4a98827cae..c7d15b505a 100644 --- a/packages/frontend/hosts/ios/src/lib.rs +++ b/packages/frontend/hosts/ios/src/lib.rs @@ -9,13 +9,17 @@ //! bridges behind `include/affine_mobile_host.h`. pub mod auth; +pub mod clipboard; +pub(crate) mod editor_doc_positions; #[cfg(not(target_os = "ios"))] pub(crate) mod editor_fallback; pub(crate) mod editor_platform; pub(crate) mod editor_runtime; pub mod ffi; +pub mod ffi_doc_positions; pub mod ffi_editor; pub mod ffi_s3; +pub mod ffi_selection; pub mod ffi_text; pub mod haptics; pub mod keyboard_insets; diff --git a/packages/frontend/hosts/ios/tests/IosHostS3SmokeTest.swift b/packages/frontend/hosts/ios/tests/IosHostS3SmokeTest.swift index 3677f42117..9b98a7e6d3 100644 --- a/packages/frontend/hosts/ios/tests/IosHostS3SmokeTest.swift +++ b/packages/frontend/hosts/ios/tests/IosHostS3SmokeTest.swift @@ -85,7 +85,7 @@ struct IosHostS3SmokeTest { static func main() { do { try testPdfKitFourPageGeometryAndGuards() - testSelectionOverlayGrabOffsetOffscreenAndRealLoupe() + testTouchOwnershipPartitionAndReadonlyDocPositions() testKeyboardAvoidancePerFrameSlideOverAndBackgroundResume() testHapticsBridgeDispatchAndBoundedHistory() testMetalHostViewControllerEndToEndTextSelectionDragCopyAndMenu() @@ -273,68 +273,56 @@ struct IosHostS3SmokeTest { print("PASS [1/5]: PDFKit 4-page geometry, URL/overflow guards, explicit handle lifecycle, and ABA isolation passed") } - /// 2. SelectionOverlayView: 0pt grab_offset zero-jump, offscreen hiding, real magnified loupe snapshot, and RTL. + /// 2. Single-owner `UITextInteractionDelegate` touch partition & side-effect-free document `UITextPosition` model. @MainActor - static func testSelectionOverlayGrabOffsetOffscreenAndRealLoupe() { - 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) } + static func testTouchOwnershipPartitionAndReadonlyDocPositions() { + let vc = MetalHostViewController() + vc.view.frame = CGRect(x: 0, y: 0, width: 390, height: 844) + vc.loadViewIfNeeded() + vc.view.layoutIfNeeded() + guard let handle = vc.hostPointer else { + requireS3(false, "hostPointer must be initialized") + return + } + _ = affine_ios_host_render_frame(handle, 1.0) + let textInteraction = vc.textHostView.interactions.compactMap { $0 as? UITextInteraction }.first + requireS3(textInteraction != nil && textInteraction?.delegate === vc, "UITextInteraction must bind delegate to MetalHostViewController") - let container = UIView(frame: CGRect(x: 0, y: 0, width: 390, height: 844)) - container.backgroundColor = .white - let marker = UIView(frame: CGRect(x: 195, y: 195, width: 30, height: 30)) - marker.backgroundColor = .systemBlue - container.addSubview(marker) - - let overlay = SelectionOverlayView(frame: container.bounds) - overlay.hostHandle = host - container.addSubview(overlay) - - var lastAnchor: CGRect? - overlay.onMenuAnchorChanged = { lastAnchor = $0 } - - let initial = affine_ios_host_selection_set( - host, - AffineRect(x: 70, y: 200, width: 2, height: 22), - AffineRect(x: 210, y: 200, width: 2, height: 22), - AffineUtf16Range(location: 0, length: 14), - 0 - ) - overlay.applyOverlayState(initial) - requireS3(initial.start_handle.visible && initial.end_handle.visible, "handles must be visible") - requireS3(lastAnchor != nil, "floating menu anchor must be published") - - // Press exact end teardrop center (213, 228) and move 0pt: probe must stay at caret midpoint (211, 211)! - let dropCenter = CGPoint( - x: CGFloat(initial.end_handle.drop_center_x), - y: CGFloat(initial.end_handle.drop_center_y) - ) - let began = overlay.processDragStep(phase: .began, point: dropCenter) - requireS3(began != nil && began!.loupe.visible, "loupe must open on drag begin") - requireS3(overlay.loupeSnapshotImage != nil, "loupe must capture a real magnified snapshot from superview") - - let zeroMove = overlay.processDragStep(phase: .changed, point: dropCenter) - requireS3(zeroMove != nil && zeroMove!.loupe.visible, "loupe must stay visible on 0pt drag") + // Topbar buttons (`Page` / `Edgeless` / `Theme` at y = 26) must bypass UITextInteraction (`interactionShouldBegin == false`). requireS3( - abs(zeroMove!.end_handle.stem_top_y - 200.0) < 0.01 - && abs(zeroMove!.end_handle.stem_bottom_y - 222.0) < 0.01 - && abs(zeroMove!.end_handle.stem_x - 210.0) < 0.01, - "0pt drag on teardrop center must not jump lines (got stem x=\(zeroMove!.end_handle.stem_x) y=\(zeroMove!.end_handle.stem_top_y)..\(zeroMove!.end_handle.stem_bottom_y))" + !vc.shouldLetTextInteractionOwnTouch(at: CGPoint(x: 252, y: 26)) + && !vc.shouldLetTextInteractionOwnTouch(at: CGPoint(x: 380, y: 26)), + "Topbar controls must not be claimed by UITextInteraction" + ) + // Editable prose in body paragraph (`y = 330`) must be owned by UITextInteraction (`interactionShouldBegin == true`). + requireS3( + vc.shouldLetTextInteractionOwnTouch(at: CGPoint(x: 200, y: 330)), + "Editable prose must be owned by UITextInteraction" ) - let ended = overlay.processDragStep(phase: .ended, point: dropCenter) - requireS3(ended != nil && !ended!.loupe.visible && ended!.show_floating_menu, "loupe closes and menu returns on end") - - // Offscreen carets must hide handles. - let offscreen = affine_ios_host_selection_set( - host, - AffineRect(x: -40, y: 200, width: 2, height: 22), - AffineRect(x: 210, y: 900, width: 2, height: 22), - AffineUtf16Range(location: 0, length: 14), - 0 + // Side-effect-free `closestPosition(to:)`: probing `(0, 0)` or another block must NEVER mutate focused block or selection! + affine_ios_host_reset_empty_doc(handle) + vc.textHostView.insertText("First block\nSecond block") + _ = affine_ios_host_render_frame(handle, 1.1) + let focusedBefore = affine_ios_host_focused_block_order(handle) + let selBefore = vc.textHostView.currentSelectedUtf16Range + let probeZero = vc.textHostView.closestPosition(to: .zero) as? AffineTextPosition + requireS3( + probeZero != nil + && affine_ios_host_focused_block_order(handle) == focusedBefore + && vc.textHostView.currentSelectedUtf16Range == selBefore, + "closestPosition(to: .zero) must never mutate focused block or selection" ) - requireS3(!offscreen.start_handle.visible && !offscreen.end_handle.visible, "offscreen handles must be hidden") - print("PASS [2/5]: SelectionOverlayView 0pt grab_offset zero-jump, offscreen hiding, and real loupe snapshot passed") + + // Cross-block monotonic comparison: earlier block < later block regardless of block-local utf16Offset. + let earlierPos = AffineTextPosition(utf16Offset: 10, blockOrder: 1, endpointToken: 0) + let laterPos = AffineTextPosition(utf16Offset: 2, blockOrder: 2, endpointToken: 0) + requireS3( + vc.textHostView.compare(earlierPos, to: laterPos) == .orderedAscending + && vc.textHostView.compare(laterPos, to: earlierPos) == .orderedDescending, + "AffineTextPosition.compare must order cross-block positions monotonically" + ) + print("PASS [2/6]: UITextInteractionDelegate touch partition & side-effect-free document UITextPosition model passed") } /// 3. KeyboardAvoidanceCoordinator: ui::WindowInsets contract, slide-over overlap_w guard, and background resume timestamp. @@ -430,120 +418,11 @@ struct IosHostS3SmokeTest { 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. + /// 5. End-to-end MetalHostViewController: system UITextInteraction mounted (zero SelectionOverlayView + /// subview), document-level GPU selection snapshot, cross-block drag, multi-MIME UIPasteboard + /// copy/cut/paste, readonly action_mask gating, BiDi RTL/mixed selectionRects, soft-wrap, and keyboard scroll. @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 - } - affine_ios_host_reset_empty_doc(hostPtr) - - 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() - if let crossPtr = vcCross.hostPointer { - affine_ios_host_reset_empty_doc(crossPtr) - } - 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. func makeEmptyEditorVC(width: CGFloat = 390, height: CGFloat = 844) -> MetalHostViewController { let controller = MetalHostViewController() controller.view.frame = CGRect(x: 0, y: 0, width: width, height: height) @@ -555,334 +434,229 @@ struct IosHostS3SmokeTest { return controller } + let vc = makeEmptyEditorVC() + let hostView = vc.textHostView + guard let hostPtr = vc.hostPointer else { + requireS3(false, "MetalHostViewController hostPointer must be initialized") + return + } + + // Verify system UITextInteraction is mounted and zero legacy subviews exist on MetalHostView. + let hasTextInteraction = hostView.interactions.contains { $0 is UITextInteraction } + requireS3(hasTextInteraction, "MetalHostView must mount system UITextInteraction") + requireS3(hostView.subviews.isEmpty, "MetalHostView must mount zero custom overlay subviews") + + hostView.insertText("Hello world") + hostView.selectedTextRange = AffineTextRange(utf16Range: NSRange(location: 0, length: 5)) + + let snapBefore = affine_ios_host_document_selection_snapshot(hostPtr) + requireS3(snapBefore.has_selection && !snapBefore.is_collapsed, "document snapshot must report active range selection") + requireS3(snapBefore.start_visible && snapBefore.end_visible, "start and end carets must be visible") + requireS3( + snapBefore.start_caret.x > 0 && snapBefore.end_caret.x > snapBefore.start_caret.x + 20.0, + "document carets must reflect real glyph advance (start=\(snapBefore.start_caret.x), end=\(snapBefore.end_caret.x))" + ) + requireS3(vc.presentedMenuAnchorRect != nil, "menu anchor rect must be published on range selection") + + // Drag end handle to offset 7 ("Hello w") via document-level drag API. + let targetCaret7 = hostView.caretRect(for: AffineTextPosition(utf16Offset: 7)) + requireS3(affine_ios_host_doc_selection_begin_drag(hostPtr, 2), "begin end-handle drag must succeed") + requireS3( + affine_ios_host_doc_selection_update_drag(hostPtr, Float(targetCaret7.midX), Float(targetCaret7.midY)), + "update end-handle drag must succeed" + ) + let snapDuring = affine_ios_host_document_selection_snapshot(hostPtr) + requireS3(snapDuring.menu_suppressed_for_motion && !snapDuring.menu_anchor_visible, "menu must hide during drag") + affine_ios_host_doc_selection_end_drag(hostPtr) + + 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))") + + // Cut active selection [0, 7] ("Hello w"): remaining text is "orld", copy/cut disabled on collapsed caret. + 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(!hostView.canPerformAction(#selector(UIResponderStandardEditActions.copy(_:)), withSender: nil), "copy must be disabled on collapsed caret") + requireS3(!hostView.canPerformAction(#selector(UIResponderStandardEditActions.cut(_:)), withSender: nil), "cut must be disabled on collapsed caret") + + // External paste from system/host pasteboard inserts into editor. + MetalHostViewController.seedExternalPasteboard(["text/plain": "EXT"]) + requireS3(hostView.canPerformAction(#selector(UIResponderStandardEditActions.paste(_:)), withSender: nil), "paste must be enabled when pasteboard has text") + hostView.paste(nil) + let afterPaste = hostView.text(in: AffineTextRange(utf16Range: NSRange(location: 0, length: 7))) + requireS3(afterPaste == "EXTorld", "expected 'EXTorld' after external paste, got \(String(describing: afterPaste))") + + // Clearing system/host pasteboard must immediately disable Paste and never resurrect stale text. + MetalHostViewController.seedExternalPasteboard([:]) + requireS3( + !hostView.canPerformAction(#selector(UIResponderStandardEditActions.paste(_:)), withSender: nil), + "paste must be disabled when system pasteboard is cleared" + ) + hostView.paste(nil) + let afterEmptyPaste = hostView.text(in: AffineTextRange(utf16Range: NSRange(location: 0, length: 7))) + requireS3( + afterEmptyPaste == "EXTorld", + "paste() on cleared pasteboard must be a no-op (got \(String(describing: afterEmptyPaste)))" + ) + MetalHostViewController.seedExternalPasteboard(["text/plain": "EXT"]) + + // Read-only gating: COPY + SELECT_ALL allowed, CUT + PASTE strictly forbidden, + // and inputView suppresses the software keyboard while keeping firstResponder active. + hostView.selectedTextRange = AffineTextRange(utf16Range: NSRange(location: 0, length: 3)) + affine_ios_host_set_page_readonly(hostPtr, true) + requireS3(hostView.inputView != nil, "readonly mode must return zero-size empty inputView to suppress software keyboard") + requireS3(hostView.canPerformAction(#selector(UIResponderStandardEditActions.copy(_:)), withSender: nil), "readonly must allow copy") + requireS3(!hostView.canPerformAction(#selector(UIResponderStandardEditActions.cut(_:)), withSender: nil), "readonly must forbid cut") + requireS3(!hostView.canPerformAction(#selector(UIResponderStandardEditActions.paste(_:)), withSender: nil), "readonly must forbid paste") + affine_ios_host_set_page_readonly(hostPtr, false) + requireS3(hostView.inputView == nil, "editable mode must restore default system keyboard (inputView == nil)") + + // 5b. BiDi RTL ("שלום 123 abc", "A אבג B") multi-line selectionRects and per-endpoint RTL. let vcRtl = makeEmptyEditorVC() 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))") + let snapRtl = affine_ios_host_document_selection_snapshot(vcRtl.hostPointer!) + requireS3(snapRtl.start_is_rtl && snapRtl.end_is_rtl, "Hebrew text must report start_is_rtl & end_is_rtl") + let rHeb = vcRtl.textHostView.selectionRects(for: AffineTextRange(utf16Range: NSRange(location: 0, length: 4))) + requireS3(rHeb.count == 1 && rHeb[0].rect.width > 20.0 && rHeb[0].writingDirection == .rightToLeft, "'שלום' rect must be >20pt wide and RTL") - // 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))") + requireS3(r123.count == 1 && r123[0].rect.width > 12.0, "'123' rect must be >12pt wide, got \(r123.map { $0.rect.width })") - // 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))") + requireS3(rAbc.count == 1 && rAbc[0].rect.width > 12.0, "'abc' rect must be >12pt wide, got \(rAbc.map { $0.rect.width })") - // 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 = makeEmptyEditorVC() 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))") + requireS3(mixedRects.count == 1 && mixedRects[0].rect.width > 15.0 && mixedRects[0].containsStart && mixedRects[0].containsEnd, "mixed BiDi 'אבג' must emit 1 rect >15pt wide") 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. + // Monotonic BiDi caretRect (RTL Hebrew decreasing, embedded digits & Latin increasing) + NFD equivalence. + 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)") + prevHebX = c.minX + } + let d1 = vcRtl.textHostView.caretRect(for: AffineTextPosition(utf16Offset: 5)).minX + let d2 = vcRtl.textHostView.caretRect(for: AffineTextPosition(utf16Offset: 6)).minX + let d3 = vcRtl.textHostView.caretRect(for: AffineTextPosition(utf16Offset: 7)).minX + requireS3(d1 < d2 && d2 < d3, "embedded digits '123' must increase LTR (\(d1), \(d2), \(d3))") + let vcNorm = makeEmptyEditorVC() 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 })" - ) + vcNorm.textHostView.replace(AffineTextRange(utf16Range: NSRange(location: 0, length: 2)), withText: "e\u{0301}B") + let decompRects = vcNorm.textHostView.selectionRects(for: AffineTextRange(utf16Range: NSRange(location: 2, length: 1))) + requireS3(decompRects.count == 1 && decompRects[0].rect.width > 5.0, "NFD 'e\\u{0301}B' [2,3) must yield valid rect") - // 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 = makeEmptyEditorVC() - 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 = makeEmptyEditorVC() - 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 = makeEmptyEditorVC() - 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 = makeEmptyEditorVC(width: 72, height: 300) - 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 + // UIKit single-handle cross-block drag (`textRange(from: selectedTextRange.start, to: closestPosition(to:))`) + // AND cross-block selection ending on an empty paragraph (`end <= endOfDocument`). + let vcCross = makeEmptyEditorVC() + vcCross.textHostView.insertText("First block\nSecond block\n") + if let crossPtr = vcCross.hostPointer { + _ = affine_ios_host_render_frame(crossPtr, 1.0) + let snapP3 = affine_ios_host_document_selection_snapshot(crossPtr) + let baseX = CGFloat(snapP3.start_caret.x) + let p3MidY = CGFloat(snapP3.start_caret.y + snapP3.start_caret.height * 0.5) + // Select "First" from offset 0 of paragraph 1 via two-point viewport selection, then drag ONLY the End handle into paragraph 2! + let p1Pt = CGPoint(x: baseX, y: p3MidY - 68.0) + let p1EndPt = CGPoint(x: baseX + 46.0, y: p3MidY - 68.0) + let p2Pt = CGPoint(x: baseX + 70.0, y: p3MidY - 34.0) + let p3EmptyPt = CGPoint(x: baseX + 4.0, y: p3MidY) + let initRange = vcCross.textHostView.textRange( + from: vcCross.textHostView.closestPosition(to: p1Pt)!, + to: vcCross.textHostView.closestPosition(to: p1EndPt)! + )! + vcCross.textHostView.selectedTextRange = initRange + let fixedStart = vcCross.textHostView.selectedTextRange!.start + let draggedToP2 = vcCross.textHostView.textRange( + from: fixedStart, + to: vcCross.textHostView.closestPosition(to: p2Pt)! + )! + vcCross.textHostView.selectedTextRange = draggedToP2 + vcCross.textHostView.copy(nil) + let crossCopied = vcCross.textHostView.lastCopiedText ?? "" + requireS3( + crossCopied.contains("First block") && crossCopied.contains("Second"), + "UIKit single-handle cross-block drag must preserve paragraph 1 start and extend into paragraph 2 (got '\(crossCopied)')" + ) + // Drag into empty paragraph 3 (`maxLen == 0`): `selectedTextRange.end` must NOT exceed `endOfDocument`. + let draggedToEmptyP3 = vcCross.textHostView.textRange( + from: fixedStart, + to: vcCross.textHostView.closestPosition(to: p3EmptyPt)! + )! + vcCross.textHostView.selectedTextRange = draggedToEmptyP3 + if let activeEmptySel = vcCross.textHostView.selectedTextRange { + let cmp = vcCross.textHostView.compare(activeEmptySel.end, to: vcCross.textHostView.endOfDocument) + requireS3( + cmp != .orderedDescending, + "cross-block selection ending on empty block must never exceed endOfDocument (cmp=\(cmp.rawValue))" + ) } } - requireS3(wrapBoundaryOffset > 0, "narrow 72pt viewport must soft-wrap 'ABCDZ'") - let tailRects = vcNarrow.textHostView.selectionRects( - for: AffineTextRange(utf16Range: NSRange(location: wrapBoundaryOffset, length: 5 - wrapBoundaryOffset)) - ) + + // Cross-anchor single-handle reversal on "Hello world": [6, 11) ("world") -> drag End handle to offset 3 -> "lo ". + let vcRev = makeEmptyEditorVC() + vcRev.textHostView.insertText("Hello world") + vcRev.textHostView.selectedTextRange = AffineTextRange(utf16Range: NSRange(location: 6, length: 5)) + let c3 = vcRev.textHostView.caretRect(for: AffineTextPosition(utf16Offset: 3)) + let fixedAnchor6 = vcRev.textHostView.selectedTextRange!.start + let reversedRange = vcRev.textHostView.textRange( + from: fixedAnchor6, + to: vcRev.textHostView.closestPosition(to: CGPoint(x: c3.midX, y: c3.midY))! + )! + vcRev.textHostView.selectedTextRange = reversedRange + vcRev.textHostView.copy(nil) requireS3( - !tailRects.isEmpty && tailRects.allSatisfy { $0.rect.minY > cNarrow0.minY + 10.0 }, - "selecting from soft-wrap boundary must emit rects starting on line 2 with zero sliver on line 1 (got \(tailRects.map { $0.rect.minY }))" + vcRev.textHostView.lastCopiedText == "lo ", + "single-handle cross-anchor reversal [6,11)->3 must select 'lo ', got '\(vcRev.textHostView.lastCopiedText ?? "")'" ) + // 5c. Soft-wrap multi-line selectionRects and rotation/resize recomputation. let vcWrap = makeEmptyEditorVC() - let longLine = "AFFiNE native iOS CoreText soft line wrapping verification across multiple wrapped visual lines" + let longLine = "AFFiNE native iOS GPU 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!)) + vcWrap.textHostView.selectedTextRange = AffineTextRange(utf16Range: NSRange(location: 10, length: 60)) + let wrapSelRects = vcWrap.textHostView.selectionRects(for: AffineTextRange(utf16Range: NSRange(location: 10, length: 60))) 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 + let endYPortrait = affine_ios_host_document_selection_snapshot(vcWrap.hostPointer!).end_caret.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 + let endYLandscape = affine_ios_host_document_selection_snapshot(vcWrap.hostPointer!).end_caret.y requireS3( endYLandscape < endYPortrait - 10.0, - "widening viewport 390->844 must move wrapped end handle up to match unwrapped line (portrait=\(endYPortrait), landscape=\(endYLandscape))" + "widening viewport 390->844 must move wrapped end caret up (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 = makeEmptyEditorVC() - 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. + // 5d. Keyboard auto-scroll keeps bottom selection visible and copyable. let vcKb = makeEmptyEditorVC() let fillerLines = String(repeating: "\n", count: 35) let bottomWord = "BottomTarget" vcKb.textHostView.insertText(fillerLines + bottomWord) + let kbLen = vcKb.textHostView.currentAuthoritativeUtf16Units.count + let kbStart = max(0, kbLen - bottomWord.utf16.count) vcKb.textHostView.selectedTextRange = AffineTextRange( - utf16Range: NSRange(location: fillerLines.utf16.count, length: bottomWord.utf16.count) + utf16Range: NSRange(location: kbStart, 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") - + let kbBefore = affine_ios_host_document_selection_snapshot(vcKb.hostPointer!) + requireS3(kbBefore.start_caret.y > 650.0, "bottom selection must sit below y=650 (got \(kbBefore.start_caret.y))") _ = vcKb.keyboardCoordinator.applyKeyboardFrame( windowBounds: CGRect(x: 0, y: 0, width: 390, height: 844), keyboardFrameInView: CGRect(x: 0, y: 542, width: 390, height: 302), @@ -892,73 +666,54 @@ struct IosHostS3SmokeTest { timestampSec: 1.0 ) vcKb.sampleInsets(timestamp: 1.0) - let kbRevealed = vcKb.selectionOverlay.currentState + let kbRevealed = affine_ios_host_document_selection_snapshot(vcKb.hostPointer!) requireS3( - kbRevealed.start_handle.visible && kbRevealed.end_handle.visible, - "auto-scrolling above keyboard must keep selection handles visible" - ) - requireS3( - kbRevealed.start_handle.stem_top_y < kbBefore.start_handle.stem_top_y - && kbRevealed.end_handle.stem_bottom_y <= 542.0 - 52.0, - "page must auto-scroll caret/selection above keyboard + toolbar (before=\(kbBefore.start_handle.stem_top_y), after_top=\(kbRevealed.start_handle.stem_top_y), after_bottom=\(kbRevealed.end_handle.stem_bottom_y))" + kbRevealed.start_visible && kbRevealed.end_visible && kbRevealed.start_caret.y < kbBefore.start_caret.y, + "page must auto-scroll selection above keyboard (before=\(kbBefore.start_caret.y), after=\(kbRevealed.start_caret.y))" ) vcKb.textHostView.copy(nil) requireS3(vcKb.textHostView.lastCopiedText == bottomWord, "selection and copy must stay intact while keyboard is open") - _ = 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 keep handles and presentedMenuAnchorRect visible" - ) - - // 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)) - } + // 5e. Unfocused CJK/Emoji `closestPosition` + dual `endpointToken` `selectedTextRange` read-write roundtrip + ordinary-scroll menu restore. + let vcCjk = makeEmptyEditorVC() + vcCjk.textHostView.insertText("甲乙丙丁🚀") + vcCjk.textHostView.insertText("\n") + vcCjk.textHostView.insertText("Second") + if let cjkPtr = vcCjk.hostPointer { + _ = affine_ios_host_render_frame(cjkPtr, 1.0) + let snapP2 = affine_ios_host_document_selection_snapshot(cjkPtr) + let baseX = CGFloat(snapP2.start_caret.x) + let p1Y = CGFloat(snapP2.start_caret.y + snapP2.start_caret.height * 0.5) - 34.0 + let p2Y = CGFloat(snapP2.start_caret.y + snapP2.start_caret.height * 0.5) + // Focus starts in paragraph 2 ("Second"); hit-testing unfocused CJK paragraph 1 must return identical UTF-16 offset on 1st and 2nd call. + let probeCjkPt = CGPoint(x: baseX + 48.0, y: p1Y) + let posFirst = vcCjk.textHostView.closestPosition(to: probeCjkPt) as? AffineTextPosition + let posSecond = vcCjk.textHostView.closestPosition(to: probeCjkPt) as? AffineTextPosition + requireS3( + posFirst != nil && posFirst?.utf16Offset == posSecond?.utf16Offset && (posFirst?.utf16Offset ?? 0) >= 2, + "unfocused CJK closestPosition must match focused UTF-16 offset on first query (first=\(String(describing: posFirst?.utf16Offset)), second=\(String(describing: posSecond?.utf16Offset)))" + ) + // Select cross-block "甲乙丙丁🚀\nSec", read `selectedTextRange` (two `.endpointToken`s), write it straight back, and verify text is preserved! + let crossStart = vcCjk.textHostView.position(from: posFirst!, offset: -(posFirst?.utf16Offset ?? 0))! + let crossEnd = vcCjk.textHostView.closestPosition(to: CGPoint(x: baseX, y: p2Y))! + vcCjk.textHostView.selectedTextRange = vcCjk.textHostView.textRange(from: crossStart, to: crossEnd) + vcCjk.textHostView.copy(nil) + let expectedCross = vcCjk.textHostView.lastCopiedText ?? "" + requireS3( + expectedCross.hasPrefix("甲乙丙丁🚀\nS"), + "cross-block CJK selection setup must span both paragraphs (got '\(expectedCross)')" + ) + let readBackRange = vcCjk.textHostView.selectedTextRange! + vcCjk.textHostView.selectedTextRange = readBackRange + vcCjk.textHostView.copy(nil) + let afterRoundtrip = vcCjk.textHostView.lastCopiedText ?? "" + requireS3( + afterRoundtrip == expectedCross, + "writing back dual-endpointToken selectedTextRange must preserve cross-block selection '\(expectedCross)', got '\(afterRoundtrip)'" + ) } - print("PASS [5/5]: MetalHostViewController E2E selection, crossover, RTL/soft-wrap, real loupe glyphs, and keyboard occlusion/restore passed") + + print("PASS [5/5]: MetalHostViewController E2E UITextInteraction, document drag, multi-MIME clipboard, readonly mask, BiDi, soft-wrap, and keyboard scroll passed") } /// 6. S6 native GPU PlaygroundView mount: zero HostTextPreviewView, live CAMetalLayer, @@ -1002,12 +757,68 @@ struct IosHostS3SmokeTest { // Block split on newline + block-start deleteBackward merge. vc.textHostView.insertText("\n") + requireS3( + vc.textHostView.currentAuthoritativeUtf16Units.isEmpty, + "insertText(\"\\n\") must split into an empty focused next block" + ) let afterSplitRange = vc.textHostView.textRange( from: vc.textHostView.beginningOfDocument, to: vc.textHostView.endOfDocument ) let afterSplit = afterSplitRange.flatMap { vc.textHostView.text(in: $0) } ?? "" - requireS3(afterSplit.isEmpty, "insertText(\"\\n\") must split into an empty next block, got '\(afterSplit)'") + requireS3( + afterSplit.contains("Heading"), + "full-document beginningOfDocument..endOfDocument must span all blocks after split, got '\(afterSplit)'" + ) + // Value equality & hashing on AffineTextPosition / AffineTextRange (NSObject equivalence contract). + let pA = AffineTextPosition(utf16Offset: 3, blockOrder: 1, endpointToken: 42) + let pB = AffineTextPosition(utf16Offset: 3, blockOrder: 1, endpointToken: 42) + let pSameTokMovedBlock = AffineTextPosition(utf16Offset: 3, blockOrder: 2, endpointToken: 42) + let pDiffTokSameCoords = AffineTextPosition(utf16Offset: 3, blockOrder: 1, endpointToken: 99) + let pZeroTok = AffineTextPosition(utf16Offset: 3, blockOrder: 1, endpointToken: 0) + let pC = AffineTextPosition(utf16Offset: 4, blockOrder: 1, endpointToken: 43) + requireS3(pA.isEqual(pB) && pA.hash == pB.hash && !pA.isEqual(pC), "AffineTextPosition must implement value isEqual/hash") + requireS3( + pA.isEqual(pSameTokMovedBlock) && pA.hash == pSameTokMovedBlock.hash, + "AffineTextPosition with identical non-zero endpointToken must stay equal with equal hash across blockOrder changes" + ) + requireS3( + !pA.isEqual(pDiffTokSameCoords) && !pA.isEqual(pZeroTok), + "AffineTextPosition with distinct endpointTokens must never compare equal even at same coordinates" + ) + let rA = AffineTextRange(startPos: pA, endPos: pC) + let rB = AffineTextRange(startPos: pB, endPos: pC) + requireS3(rA.isEqual(rB) && rA.hash == rB.hash, "AffineTextRange must implement value isEqual/hash") + + // Surrogate pair / grapheme cluster characterUnitRange & characterRange(at:) must not split 🚀. + affine_ios_host_reset_empty_doc(handle) + vc.textHostView.insertText("甲🚀乙") + _ = affine_ios_host_render_frame(handle, 1.0) + if let caretEnd = vc.textHostView.selectedTextRange?.start, + let emojiPos = vc.textHostView.position(from: caretEnd, offset: -3) as? AffineTextPosition, + let unitRange = vc.textHostView.characterUnitRange(at: emojiPos) + { + let unitText = vc.textHostView.text(in: unitRange) ?? "" + requireS3( + unitText == "🚀" && unitRange.utf16Range.length == 2, + "characterUnitRange at 🚀 must return full 2-UTF16 surrogate pair, got '\(unitText)' len=\(unitRange.utf16Range.length)" + ) + } else { + requireS3(false, "characterUnitRange must resolve 🚀 surrogate pair position") + } + + // Code block focus must switch autocorrectionType to .no (wantsCodeInput regression guard). + affine_ios_host_reset_empty_doc(handle) + requireS3(vc.textHostView.autocorrectionType == .default, "Prose block must default autocorrectionType to .default") + vc.textHostView.insertText("``` ") + requireS3( + vc.textHostView.autocorrectionType == .no && vc.textHostView.autocapitalizationType == .none, + "Code block focus must set autocorrectionType == .no and autocapitalizationType == .none" + ) + affine_ios_host_reset_empty_doc(handle) + vc.textHostView.insertText("# Heading") + vc.textHostView.insertText("\n") + vc.textHostView.deleteBackward() let afterMergeRange = vc.textHostView.textRange( from: vc.textHostView.beginningOfDocument, @@ -1034,10 +845,6 @@ struct IosHostS3SmokeTest { ) < 0.5, "hostView must be framed inside safeAreaInsets (insets=\(vcSafe.view.safeAreaInsets), got \(vcSafe.textHostView.frame))" ) - requireS3( - vcSafe.selectionOverlay.frame == vcSafe.textHostView.bounds, - "selectionOverlay must share hostView safe-area-local bounds" - ) if let safeHandle = vcSafe.hostPointer { affine_ios_host_reset_empty_doc(safeHandle) vcSafe.textHostView.insertText("SafeArea") @@ -1070,6 +877,16 @@ struct IosHostS3SmokeTest { countingDelegate.textWillChangeCount == 0 && countingDelegate.textDidChangeCount == 0, "IME-originated Pinyin sequence must trigger 0 textWillChange/textDidChange callbacks (got will=\(countingDelegate.textWillChangeCount), did=\(countingDelegate.textDidChangeCount))" ) + // Single-Writer contract: UIKit calling setSelectedTextRange must NOT synchronously echo + // selectionWillChange/selectionDidChange back into inputDelegate. + let selWillBefore = countingDelegate.selectionWillChangeCount + let selDidBefore = countingDelegate.selectionDidChangeCount + vcSafe.textHostView.selectedTextRange = AffineTextRange(utf16Range: NSRange(location: 0, length: 2)) + requireS3( + countingDelegate.selectionWillChangeCount == selWillBefore + && countingDelegate.selectionDidChangeCount == selDidBefore, + "setSelectedTextRange must not synchronously echo selectionWillChange/selectionDidChange" + ) // External editor mutation (reset / shortcut) MUST notify inputDelegate. affine_ios_host_reset_empty_doc(safeHandle) requireS3( @@ -1095,6 +912,42 @@ struct IosHostS3SmokeTest { && vcSafe.textHostView.smartDashesType == .no, "code block must disable autocorrection, autocapitalization, smart quotes, and smart dashes" ) + + // Forwarded empty-tail tap regression guard (5 consecutive rounds): + // tapping below the last block must route to Rust (shouldLetTextInteractionOwnTouch == false), + // append/focus the trailing paragraph, and raise software keyboard (isFirstResponder == true). + safeWindow.makeKeyAndVisible() + for round in 1...5 { + affine_ios_host_reset_empty_doc(safeHandle) + vcSafe.textHostView.insertText("First paragraph \(round)") + _ = affine_ios_host_render_frame(safeHandle, Double(round)) + _ = vcSafe.textHostView.resignFirstResponder() + requireS3(!vcSafe.textHostView.isFirstResponder, "round \(round): must resign before empty-tail tap") + let tailPoint = CGPoint(x: 195.0, y: 620.0) + requireS3( + !vcSafe.shouldLetTextInteractionOwnTouch(at: tailPoint), + "round \(round): empty page tail tap must forward immediately to Rust" + ) + affine_ios_host_touch_event(safeHandle, UInt64(900 + round), 0, Float(tailPoint.x), Float(tailPoint.y)) + affine_ios_host_touch_event(safeHandle, UInt64(900 + round), 2, Float(tailPoint.x), Float(tailPoint.y)) + vcSafe.textHostView.handleForwardedTouchCompletion(endedEditableTap: true) + requireS3( + affine_ios_host_wants_software_keyboard(safeHandle) + && vcSafe.textHostView.isFirstResponder + && vcSafe.textHostView.inputView == nil, + "round \(round): empty-tail tap must raise software keyboard (wantsKb=\(affine_ios_host_wants_software_keyboard(safeHandle)), isFR=\(vcSafe.textHostView.isFirstResponder))" + ) + vcSafe.textHostView.insertText("Tail line \(round)") + let docRange = vcSafe.textHostView.textRange( + from: vcSafe.textHostView.beginningOfDocument, + to: vcSafe.textHostView.endOfDocument + ) + let fullText = docRange.flatMap { vcSafe.textHostView.text(in: $0) } ?? "" + requireS3( + fullText.contains("Tail line \(round)"), + "round \(round): typing after empty-tail tap must write into newly focused paragraph, got '\(fullText)'" + ) + } } // Reload showcase document and trigger a real GPU Metal frame render. @@ -1102,6 +955,6 @@ struct IosHostS3SmokeTest { let renderedColor = affine_ios_host_render_frame(handle, 1.0) requireS3(renderedColor != 0, "GPU editor frame render must succeed on showcase doc") - print("PASS [6/6]: S6 iOS native GPU editor mount, safe-area alignment, H-S1/H-S2 IME, block split/merge, and T1 readonly passed") + print("PASS [6/6]: S6 iOS native GPU editor mount, safe-area alignment, H-S1/H-S2 IME, block split/merge, UITextInteraction selection, empty-tail tap keyboard raise, and T1 readonly passed") } }