feat(ios-host): switch text selection to single-writer UITextInteraction and guard offline client IDs

This commit is contained in:
DarkSky committed 2026-11-29 03:42:18 +09:00
1 parent 00ece8f2e0
commit bc927e6ed8
12 files changed
+3654 -1147

No files matched your search

+2 -2
View File
@@ -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 `<Documents>/workspaces/<spaceType>/<sanitizedPeer>/<spaceId>.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.
File diff suppressed because it is too large. Load diff
@@ -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)
}
}
}
}
}
@@ -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
@@ -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<Option<ClipboardItem>>,
provider: RefCell<Option<AffineClipboardProvider>>,
}
impl IosClipboardStore {
pub(crate) fn set_provider(&self, provider: Option<AffineClipboardProvider>) {
*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<ClipboardItem> {
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<IosClipboardWriteFn>,
pub read_json: Option<IosClipboardReadFn>,
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::<serde_json::Value>(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<ClipboardItem> {
let serde_json::Value::Object(map) = serde_json::from_str::<serde_json::Value>(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<AffineClipboardProvider>, 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<AffineClipboardProvider>,
) -> Option<ClipboardItem> {
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::<c_void>(),
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"
);
}
}
@@ -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<AffineDocPosition> {
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<AffineRect> {
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<playground::SelectionRectGeometry> {
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<AffineDocPosition> {
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<isize> = 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<playground::SelectionEndpointAnchor> {
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<u16> = "甲乙丙丁🚀".encode_utf16().collect();
rt.insert_text(&p1);
let nl: Vec<u16> = "\n".encode_utf16().collect();
let p2: Vec<u16> = "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,
};
}
}
@@ -509,7 +509,7 @@ pub(crate) struct IosEditorPlatform {
initial_bounds: Bounds<Pixels>,
initial_scale: f32,
opened_window: RefCell<Option<IosEditorWindow>>,
clipboard: RefCell<Option<ClipboardItem>>,
pub(crate) clipboard: super::clipboard::IosClipboardStore,
open_url_observer: RefCell<Option<OpenUrlObserver>>,
}
@@ -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<ClipboardItem> {
self.clipboard.borrow().clone()
self.clipboard.read()
}
#[cfg(target_os = "linux")]
@@ -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<u32> {
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<super::clipboard::AffineClipboardProvider>,
) {
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)]
@@ -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<AffineDocumentSelectionRect> = 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())
}
@@ -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<AffineDocumentSelectionRect> = 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<AffineDocumentSelectionRect> = 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();
}
+4
View File
@@ -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;
File diff suppressed because it is too large. Load diff