mirror of
https://github.com/toeverything/AFFiNE.git
synced 2026-12-05 11:15:01 +03:00
feat(mobile): mount native GPU BlockSuite editor in iOS and Android hosts
- Add orthogonal PointerKind, FormFactor, and EditorCapabilities matrix in blocksuite-editor, decoupling database_readonly from edgeless_readonly and enforcing page_readonly across command/toolbar paths - Attach cross-platform CJK and emoji FontFallbacks to blocksuite-editor text runs so iOS CoreText and Android CosmicTextSystem render CJK and emoji glyphs cleanly - Wire real WgpuRenderer and CosmicTextSystem into Android ANativeWindow via SwappableAtlas, deterministic ui::clock_now() dispatch_after timer draining, single-JNI UTF-16 reads, surrogate-pair composing alignment, requestCursorUpdates + Matrix CursorAnchorInfo, historical ACTION_MOVE samples, hardware keyboard/scroll forwarding, and zero shadow-buffer pollution - Frame iOS MetalHostView and SelectionOverlayView inside safeAreaInsets, gate software keyboard responder on PlaygroundView::wants_software_keyboard and pan-slop tap detection, avoid double safe_bottom subtraction on KeyboardToolbar insets, prevent spurious UITextInputDelegate textWillChange/textDidChange echo during IME composition, yield hardware pressesBegan during marked text, and guard UIEditMenuInteraction with explicit actions - Enable wgpu/cosmic-text for target_os = "android" in packages/ui/ui and add Linux fontconfig/freetype packages to np-mobile CI workflow
This commit is contained in:
1 parent
6eb02b835b
commit
4e66722b44
58 files changed
+6407
-762
No files matched your search
@@ -227,6 +227,12 @@ jobs:
|
||||
workspaces: packages/frontend -> target
|
||||
key: np-mobile-android-host
|
||||
|
||||
- name: Install Linux fontconfig and freetype headers for host tests
|
||||
run: |
|
||||
sudo rm -f /etc/apt/sources.list.d/microsoft-prod.list
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y --no-install-recommends pkg-config libfontconfig1-dev libfreetype-dev
|
||||
|
||||
- name: Test host logic and link Android NDK .so binaries
|
||||
working-directory: packages/frontend
|
||||
run: |
|
||||
@@ -308,6 +314,13 @@ jobs:
|
||||
-framework QuartzCore \
|
||||
-framework Metal \
|
||||
-framework WebKit \
|
||||
-framework PDFKit \
|
||||
-framework CoreText \
|
||||
-framework CoreGraphics \
|
||||
-framework CoreVideo \
|
||||
-framework CoreFoundation \
|
||||
-framework Foundation \
|
||||
-framework UniformTypeIdentifiers \
|
||||
-o /tmp/AffineIosHost \
|
||||
packages/frontend/hosts/ios/Sources/*.swift
|
||||
test -s /tmp/AffineIosHost
|
||||
@@ -31,6 +31,7 @@ impl InlineStyle {
|
||||
fn font(&self) -> Font {
|
||||
let mut font = ui::font(self.family);
|
||||
font.weight = FontWeight(self.weight);
|
||||
font.fallbacks = Some(crate::default_font_fallbacks());
|
||||
font
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
//! Orthogonal host input and form-factor capability descriptors shared by
|
||||
//! BlockSuite editor views and platform hosts.
|
||||
|
||||
/// Primary pointer modality reported by the host platform.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
|
||||
pub enum PointerKind {
|
||||
#[default]
|
||||
Mouse,
|
||||
Touch,
|
||||
Pen,
|
||||
}
|
||||
|
||||
/// Physical device form factor reported by the host platform.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
|
||||
pub enum FormFactor {
|
||||
Phone,
|
||||
Tablet,
|
||||
#[default]
|
||||
Desktop,
|
||||
}
|
||||
|
||||
impl FormFactor {
|
||||
/// Returns `true` for native touch form factors (`Phone` and `Tablet`).
|
||||
pub const fn is_touch_form_factor(self) -> bool {
|
||||
matches!(self, Self::Phone | Self::Tablet)
|
||||
}
|
||||
|
||||
/// Maps an Android `smallestScreenWidthDp` value to `Phone` (`< 600`) or `Tablet` (`>= 600`).
|
||||
pub const fn from_android_smallest_width_dp(smallest_width_dp: i32) -> Self {
|
||||
if smallest_width_dp >= 600 {
|
||||
Self::Tablet
|
||||
} else {
|
||||
Self::Phone
|
||||
}
|
||||
}
|
||||
|
||||
/// Maps an iOS `UIUserInterfaceIdiom` raw flag (`true` for `.pad`) to `Tablet` or `Phone`.
|
||||
pub const fn from_ios_idiom(is_pad: bool) -> Self {
|
||||
if is_pad { Self::Tablet } else { Self::Phone }
|
||||
}
|
||||
}
|
||||
|
||||
/// Orthogonal capability defaults derived from a host's [`FormFactor`].
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub struct EditorCapabilities {
|
||||
pub pointer_kind: PointerKind,
|
||||
pub form_factor: FormFactor,
|
||||
pub page_readonly: bool,
|
||||
pub edgeless_readonly: bool,
|
||||
pub database_readonly: bool,
|
||||
}
|
||||
|
||||
impl EditorCapabilities {
|
||||
/// Stage-1 capability defaults for a given host [`FormFactor`].
|
||||
///
|
||||
/// Touch hosts (`Phone`, `Tablet`) default to read-only Edgeless and Database
|
||||
/// surfaces while keeping Page editing enabled; `Desktop` defaults to full
|
||||
/// authoring regardless of window width.
|
||||
pub const fn for_form_factor(form_factor: FormFactor) -> Self {
|
||||
match form_factor {
|
||||
FormFactor::Phone | FormFactor::Tablet => Self {
|
||||
pointer_kind: PointerKind::Touch,
|
||||
form_factor,
|
||||
page_readonly: false,
|
||||
edgeless_readonly: true,
|
||||
database_readonly: true,
|
||||
},
|
||||
FormFactor::Desktop => Self {
|
||||
pointer_kind: PointerKind::Mouse,
|
||||
form_factor: FormFactor::Desktop,
|
||||
page_readonly: false,
|
||||
edgeless_readonly: false,
|
||||
database_readonly: false,
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn form_factor_defaults_match_stage_one_readonly_matrix() {
|
||||
let cases = [
|
||||
(FormFactor::Phone, PointerKind::Touch, false, true, true),
|
||||
(FormFactor::Tablet, PointerKind::Touch, false, true, true),
|
||||
(FormFactor::Desktop, PointerKind::Mouse, false, false, false),
|
||||
];
|
||||
for (form, pointer, page_ro, edgeless_ro, db_ro) in cases {
|
||||
let caps = EditorCapabilities::for_form_factor(form);
|
||||
assert_eq!(caps.form_factor, form);
|
||||
assert_eq!(caps.pointer_kind, pointer);
|
||||
assert_eq!(caps.page_readonly, page_ro);
|
||||
assert_eq!(caps.edgeless_readonly, edgeless_ro);
|
||||
assert_eq!(caps.database_readonly, db_ro);
|
||||
}
|
||||
assert_eq!(
|
||||
FormFactor::from_android_smallest_width_dp(390),
|
||||
FormFactor::Phone
|
||||
);
|
||||
assert_eq!(
|
||||
FormFactor::from_android_smallest_width_dp(600),
|
||||
FormFactor::Tablet
|
||||
);
|
||||
assert_eq!(FormFactor::from_ios_idiom(false), FormFactor::Phone);
|
||||
assert_eq!(FormFactor::from_ios_idiom(true), FormFactor::Tablet);
|
||||
// N1: Phone form factor always defaults database_readonly to true independently of edgeless_readonly.
|
||||
let phone = EditorCapabilities::for_form_factor(FormFactor::Phone);
|
||||
assert!(phone.database_readonly);
|
||||
assert!(phone.edgeless_readonly);
|
||||
let desktop = EditorCapabilities::for_form_factor(FormFactor::Desktop);
|
||||
assert!(!desktop.database_readonly);
|
||||
assert!(!desktop.edgeless_readonly);
|
||||
}
|
||||
}
|
||||
@@ -721,6 +721,7 @@ pub fn layout_label_editor_paragraph(
|
||||
let ts = window.text_system();
|
||||
let mut face = ui::font(font_family.clone());
|
||||
face.weight = base_weight;
|
||||
face.fallbacks = Some(crate::default_font_fallbacks());
|
||||
let font_id = ts.resolve_font(&face);
|
||||
let font_px = px(font_size);
|
||||
let ascent = f32::from(ts.ascent(font_id, font_px));
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
//! and the narrow [`directory::WorkspaceDocDirectory`] host port.
|
||||
|
||||
pub mod block_flow;
|
||||
pub mod capabilities;
|
||||
pub mod clipboard;
|
||||
pub mod database;
|
||||
pub mod directory;
|
||||
@@ -16,6 +17,7 @@ pub mod rich_text;
|
||||
pub mod surface;
|
||||
pub mod theme;
|
||||
|
||||
pub use capabilities::{EditorCapabilities, FormFactor, PointerKind};
|
||||
pub use directory::{
|
||||
DirectoryError, DocQueryCancelToken, DocQueryPage, DocQueryRequest, EditorDocId, EditorDocMode,
|
||||
EditorDocPreview, EditorDocSummary, InMemoryDocDirectory, MatchedDocSummary,
|
||||
@@ -26,3 +28,26 @@ pub use theme::{PlaygroundTheme, register_bundled_fonts};
|
||||
|
||||
/// Height of the default top bar, including its bottom border.
|
||||
pub const TOPBAR_HEIGHT: f32 = 53.0;
|
||||
|
||||
/// Cross-platform CJK and emoji fallback families attached to bundled fonts so
|
||||
/// iOS CoreText (`MemSource` `CTFont`) and Android `CosmicTextSystem` render
|
||||
/// Chinese/Japanese/Korean and emoji glyphs without missing-glyph boxes.
|
||||
pub fn default_font_fallbacks() -> ui::FontFallbacks {
|
||||
static FALLBACKS: std::sync::OnceLock<ui::FontFallbacks> = std::sync::OnceLock::new();
|
||||
FALLBACKS
|
||||
.get_or_init(|| {
|
||||
ui::FontFallbacks(std::sync::Arc::new(vec![
|
||||
"PingFang SC".to_string(),
|
||||
"PingFang TC".to_string(),
|
||||
"Hiragino Sans".to_string(),
|
||||
"Apple SD Gothic Neo".to_string(),
|
||||
"Noto Sans CJK SC".to_string(),
|
||||
"Noto Sans CJK TC".to_string(),
|
||||
"Noto Sans CJK JP".to_string(),
|
||||
"Droid Sans Fallback".to_string(),
|
||||
"Apple Color Emoji".to_string(),
|
||||
"Noto Color Emoji".to_string(),
|
||||
]))
|
||||
})
|
||||
.clone()
|
||||
}
|
||||
@@ -155,6 +155,7 @@ impl Overlays {
|
||||
let shown = SharedString::from(text.clone());
|
||||
let mut font = ui::font(FONT_SANS);
|
||||
font.weight = FontWeight::NORMAL;
|
||||
font.fallbacks = Some(crate::default_font_fallbacks());
|
||||
let line = window.text_system().shape_line(
|
||||
shown.clone(),
|
||||
px(TYPOGRAPHY.font_xs_px),
|
||||
|
||||
@@ -479,6 +479,7 @@ impl Overlays {
|
||||
let marked = editor.input.marked_range();
|
||||
let mut font = ui::font(FONT_CODE);
|
||||
font.weight = FontWeight::NORMAL;
|
||||
font.fallbacks = Some(crate::default_font_fallbacks());
|
||||
let theme_mode = palette.theme.mode();
|
||||
let wrapped = wrap_latex_lines(
|
||||
&text,
|
||||
|
||||
@@ -615,6 +615,7 @@ impl Overlays {
|
||||
let marked = link.marked_range();
|
||||
let mut font = ui::font(FONT_SANS);
|
||||
font.weight = FontWeight::NORMAL;
|
||||
font.fallbacks = Some(crate::default_font_fallbacks());
|
||||
let shown = SharedString::from(text.clone());
|
||||
let line = window.text_system().shape_line(
|
||||
shown.clone(),
|
||||
|
||||
@@ -324,6 +324,7 @@ impl ParagraphLayout<'_> {
|
||||
} else {
|
||||
&style.font_family
|
||||
});
|
||||
font.fallbacks = Some(crate::default_font_fallbacks());
|
||||
// CSS `bolder`: regular and medium text step to 700, heavier text to 900.
|
||||
font.weight = if is_latex {
|
||||
FontWeight::MEDIUM
|
||||
|
||||
@@ -194,6 +194,7 @@ impl TextStyle<'_> {
|
||||
};
|
||||
let mut face = ui::font(style.font_family.clone());
|
||||
face.weight = style.base_weight;
|
||||
face.fallbacks = Some(crate::default_font_fallbacks());
|
||||
let id = ts.resolve_font(&face);
|
||||
let size = px(style.font_size);
|
||||
let ascent = f32::from(ts.ascent(id, size));
|
||||
|
||||
@@ -377,7 +377,7 @@ impl PlaygroundView {
|
||||
self.scroll_y,
|
||||
self.max_scroll,
|
||||
window.layout_direction(),
|
||||
self.edgeless_readonly,
|
||||
self.is_touch_host() || self.edgeless_readonly,
|
||||
)
|
||||
.map(|metrics| {
|
||||
overlays::build_page_scrollbar(
|
||||
|
||||
@@ -57,6 +57,9 @@ impl PlaygroundView {
|
||||
w: &mut Window,
|
||||
cx: &mut Context<Self>,
|
||||
) -> DocResult {
|
||||
if self.mode == crate::PlaygroundMode::Page && self.page_readonly {
|
||||
return Ok(());
|
||||
}
|
||||
let sel = self.editor.selection.clone();
|
||||
let root_id = self
|
||||
.snapshot
|
||||
@@ -325,6 +328,9 @@ impl PlaygroundView {
|
||||
w: &mut Window,
|
||||
cx: &mut Context<Self>,
|
||||
) -> DocResult {
|
||||
if self.mode == crate::PlaygroundMode::Page && self.page_readonly {
|
||||
return Ok(());
|
||||
}
|
||||
let Some(sel) = self.editor.selection.clone() else {
|
||||
return Ok(());
|
||||
};
|
||||
@@ -652,7 +658,9 @@ impl PlaygroundView {
|
||||
let m = e.keystroke.modifiers;
|
||||
let cmd = m.secondary(cx);
|
||||
let key = e.keystroke.key.as_str();
|
||||
let page_ro = self.mode == crate::PlaygroundMode::Page && self.page_readonly;
|
||||
if cmd
|
||||
&& !page_ro
|
||||
&& let Some(command) = block_selection::conversion_shortcut(key, m.alt, m.shift)
|
||||
&& let Some(block_id) = self
|
||||
.editor
|
||||
@@ -717,7 +725,7 @@ impl PlaygroundView {
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
"k" if cmd && !m.alt && !m.shift => {
|
||||
"k" if cmd && !m.alt && !m.shift && !page_ro => {
|
||||
self.open_link_bar_shortcut(w, cx);
|
||||
Ok(())
|
||||
}
|
||||
@@ -743,17 +751,18 @@ impl PlaygroundView {
|
||||
}
|
||||
"z" if cmd => self.history(m.shift, w, cx),
|
||||
"y" if cmd => self.history(true, w, cx),
|
||||
"b" | "i" | "u" | "e" | "s" if cmd && (key != "s" || m.shift) => self.format_mark(
|
||||
match key {
|
||||
"b" => "bold",
|
||||
"i" => "italic",
|
||||
"u" => "underline",
|
||||
"e" => "code",
|
||||
_ => "strike",
|
||||
},
|
||||
w,
|
||||
cx,
|
||||
),
|
||||
"b" | "i" | "u" | "e" | "s" if cmd && !page_ro && (key != "s" || m.shift) => self
|
||||
.format_mark(
|
||||
match key {
|
||||
"b" => "bold",
|
||||
"i" => "italic",
|
||||
"u" => "underline",
|
||||
"e" => "code",
|
||||
_ => "strike",
|
||||
},
|
||||
w,
|
||||
cx,
|
||||
),
|
||||
_ => return,
|
||||
};
|
||||
if let Err(e) = result {
|
||||
@@ -764,34 +773,9 @@ impl PlaygroundView {
|
||||
}
|
||||
|
||||
pub(crate) fn open_link_bar_from_toolbar(&mut self, w: &mut Window, cx: &mut Context<Self>) {
|
||||
self.open_link_bar_shortcut(w, cx);
|
||||
}
|
||||
|
||||
pub(crate) fn copy_toolbar_selection_or_block(&mut self, cx: &mut Context<Self>) {
|
||||
if let Some(slice) = self.clipboard_slice() {
|
||||
crate::clipboard::write_slice(&slice, cx);
|
||||
if self.mode == crate::PlaygroundMode::Page && self.page_readonly {
|
||||
return;
|
||||
}
|
||||
if let Some(id) = self.editor.selection.as_ref().map(|s| &s.focus.block_id)
|
||||
&& let Some(text) = self.block_text(id)
|
||||
{
|
||||
cx.write_to_clipboard(ui::ClipboardItem::new_string(text.to_string()));
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn insert_toolbar_plain_text(
|
||||
&mut self,
|
||||
text: &str,
|
||||
w: &mut Window,
|
||||
cx: &mut Context<Self>,
|
||||
) -> DocResult {
|
||||
let Some(sel) = self.editor.selection.clone() else {
|
||||
return Ok(());
|
||||
};
|
||||
self.page_mut()?.stop_capturing()?;
|
||||
self.editor.last_typing = None;
|
||||
self.replace_selection(sel, text, w, cx)?;
|
||||
self.page_mut()?.stop_capturing()?;
|
||||
Ok(())
|
||||
self.open_link_bar_shortcut(w, cx);
|
||||
}
|
||||
}
|
||||
@@ -433,7 +433,7 @@ impl PlaygroundView {
|
||||
sel.clone()
|
||||
})
|
||||
}
|
||||
pub(super) fn replace_selection(
|
||||
pub(crate) fn replace_selection(
|
||||
&mut self,
|
||||
sel: DocumentSelection,
|
||||
text: &str,
|
||||
|
||||
@@ -28,6 +28,9 @@ impl EntityInputHandler for PlaygroundView {
|
||||
}
|
||||
return;
|
||||
}
|
||||
if self.mode == crate::PlaygroundMode::Page && self.page_readonly {
|
||||
return;
|
||||
}
|
||||
if self.mode == crate::PlaygroundMode::Edgeless
|
||||
&& self.edgeless.authoring.editing_spatial_block().is_none()
|
||||
{
|
||||
@@ -186,6 +189,9 @@ impl EntityInputHandler for PlaygroundView {
|
||||
{
|
||||
return;
|
||||
}
|
||||
if self.mode == crate::PlaygroundMode::Page && self.page_readonly {
|
||||
return;
|
||||
}
|
||||
if self.mode == crate::PlaygroundMode::Edgeless
|
||||
&& self.edgeless.authoring.editing_spatial_block().is_none()
|
||||
{
|
||||
@@ -221,6 +227,9 @@ impl EntityInputHandler for PlaygroundView {
|
||||
{
|
||||
return;
|
||||
}
|
||||
if self.mode == crate::PlaygroundMode::Page && self.page_readonly {
|
||||
return;
|
||||
}
|
||||
if self.mode == crate::PlaygroundMode::Edgeless
|
||||
&& self.edgeless.authoring.editing_spatial_block().is_none()
|
||||
{
|
||||
@@ -271,6 +280,9 @@ impl EntityInputHandler for PlaygroundView {
|
||||
{
|
||||
return;
|
||||
}
|
||||
if self.mode == crate::PlaygroundMode::Page && self.page_readonly {
|
||||
return;
|
||||
}
|
||||
if self.mode == crate::PlaygroundMode::Edgeless
|
||||
&& self.edgeless.authoring.editing_spatial_block().is_none()
|
||||
{
|
||||
|
||||
@@ -262,7 +262,7 @@ impl PlaygroundView {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn set_mode(
|
||||
pub fn set_mode(
|
||||
&mut self,
|
||||
target: PlaygroundMode,
|
||||
window: &mut Window,
|
||||
|
||||
@@ -5,7 +5,8 @@
|
||||
//! rendered by [`block_flow`], with the popovers and block controls of [`overlays`] on top.
|
||||
|
||||
pub use blocksuite_editor::{
|
||||
TOPBAR_HEIGHT, block_flow, clipboard, database, directory, rich_text, surface, theme,
|
||||
EditorCapabilities, FormFactor, PointerKind, TOPBAR_HEIGHT, block_flow, clipboard, database,
|
||||
directory, rich_text, surface, theme,
|
||||
};
|
||||
mod chrome;
|
||||
pub mod edgeless;
|
||||
@@ -104,14 +105,35 @@ pub struct PlaygroundOptions {
|
||||
pub mode: PlaygroundMode,
|
||||
/// Live room to join. Without one the view shows the built-in showcase document.
|
||||
pub room: Option<RoomConfig>,
|
||||
/// Defaults to `false`. When set to `true` (e.g. via `?mobile=1`, `?edgeless_readonly=1`,
|
||||
/// or `--edgeless-readonly` where `enable_mobile_edgeless_editing == false`),
|
||||
/// Edgeless mode hides the creation toolbar, disables element authoring/mutation,
|
||||
/// and pans smoothly on single-finger / left-pointer drags.
|
||||
/// Primary pointer modality reported by the host platform.
|
||||
pub pointer_kind: PointerKind,
|
||||
/// Physical device form factor reported by the host platform.
|
||||
pub form_factor: FormFactor,
|
||||
/// When `true`, Page-mode text/block mutations are suppressed.
|
||||
pub page_readonly: bool,
|
||||
/// Defaults to `false`. When set to `true` (e.g. on touch hosts or via `?mobile=1`,
|
||||
/// `?edgeless_readonly=1`, or `--edgeless-readonly`), Edgeless mode hides the creation
|
||||
/// toolbar, disables element authoring/mutation, and pans smoothly on single-finger drags.
|
||||
pub edgeless_readonly: bool,
|
||||
/// When `true`, Database-block mutations are suppressed.
|
||||
pub database_readonly: bool,
|
||||
}
|
||||
|
||||
impl PlaygroundOptions {
|
||||
/// Builds Stage-1 options for a native touch host (`Phone` or `Tablet`):
|
||||
/// Page editing enabled, Edgeless and Database read-only.
|
||||
pub fn for_form_factor(form_factor: FormFactor) -> Self {
|
||||
let caps = EditorCapabilities::for_form_factor(form_factor);
|
||||
Self {
|
||||
pointer_kind: caps.pointer_kind,
|
||||
form_factor: caps.form_factor,
|
||||
page_readonly: caps.page_readonly,
|
||||
edgeless_readonly: caps.edgeless_readonly,
|
||||
database_readonly: caps.database_readonly,
|
||||
..Self::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse command-line flags: `--theme light|dark`, `--mode page|edgeless`,
|
||||
/// `--edgeless-readonly`, `--room <room>` and `--relay <ws_url>` (a relay without a room is an error).
|
||||
pub fn from_args(args: impl IntoIterator<Item = String>) -> anyhow::Result<Self> {
|
||||
@@ -136,6 +158,8 @@ impl PlaygroundOptions {
|
||||
.ok_or_else(|| anyhow::anyhow!("unknown mode {value:?} (page|edgeless)"))?;
|
||||
}
|
||||
"--edgeless-readonly" => options.edgeless_readonly = true,
|
||||
"--page-readonly" => options.page_readonly = true,
|
||||
"--database-readonly" => options.database_readonly = true,
|
||||
"--room" => room = Some(value()?),
|
||||
"--relay" => relay = Some(value()?),
|
||||
other => anyhow::bail!("unknown flag: {other}"),
|
||||
@@ -227,6 +251,9 @@ pub struct PlaygroundView {
|
||||
pub(crate) edgeless: edgeless::EdgelessCanvasState,
|
||||
pub(crate) edgeless_camera_transition: Option<edgeless::CameraTransition>,
|
||||
pub(crate) edgeless_shape_picker_presence: Option<edgeless::ShapePickerPresence>,
|
||||
pub(crate) pointer_kind: PointerKind,
|
||||
pub(crate) form_factor: FormFactor,
|
||||
pub(crate) page_readonly: bool,
|
||||
pub(crate) edgeless_readonly: bool,
|
||||
pub(crate) database_readonly: bool,
|
||||
pub(crate) caret_active_since_ms: f64,
|
||||
@@ -308,7 +335,9 @@ impl PlaygroundView {
|
||||
state.awareness.local_client_id()
|
||||
));
|
||||
let mut flow = BlockFlow::new();
|
||||
flow.database_state.mobile_readonly = options.edgeless_readonly;
|
||||
let database_readonly =
|
||||
options.database_readonly || matches!(options.form_factor, FormFactor::Phone);
|
||||
flow.database_state.mobile_readonly = database_readonly;
|
||||
let mut view = Self {
|
||||
mode: options.mode,
|
||||
theme: options.theme,
|
||||
@@ -351,8 +380,11 @@ impl PlaygroundView {
|
||||
edgeless: edgeless::EdgelessCanvasState::new(),
|
||||
edgeless_camera_transition: None,
|
||||
edgeless_shape_picker_presence: None,
|
||||
pointer_kind: options.pointer_kind,
|
||||
form_factor: options.form_factor,
|
||||
page_readonly: options.page_readonly,
|
||||
edgeless_readonly: options.edgeless_readonly,
|
||||
database_readonly: options.edgeless_readonly,
|
||||
database_readonly,
|
||||
caret_active_since_ms: 0.0,
|
||||
caret_blink_task: None,
|
||||
scrollbar_drag: None,
|
||||
@@ -521,6 +553,34 @@ impl PlaygroundView {
|
||||
cx.notify();
|
||||
}
|
||||
|
||||
/// Primary pointer modality reported by the host platform.
|
||||
pub fn pointer_kind(&self) -> PointerKind {
|
||||
self.pointer_kind
|
||||
}
|
||||
|
||||
/// Physical device form factor reported by the host platform.
|
||||
pub fn form_factor(&self) -> FormFactor {
|
||||
self.form_factor
|
||||
}
|
||||
|
||||
/// Whether this view is running on a touch-first mobile/tablet host.
|
||||
pub fn is_touch_host(&self) -> bool {
|
||||
self.form_factor.is_touch_form_factor() || self.pointer_kind == PointerKind::Touch
|
||||
}
|
||||
|
||||
/// Whether Page-mode mutations are gated read-only.
|
||||
pub fn page_readonly(&self) -> bool {
|
||||
self.page_readonly
|
||||
}
|
||||
|
||||
/// Enable or disable the Page-mode read-only gate.
|
||||
pub fn set_page_readonly(&mut self, readonly: bool, cx: &mut Context<Self>) {
|
||||
if self.page_readonly != readonly {
|
||||
self.page_readonly = readonly;
|
||||
cx.notify();
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether Edgeless authoring is gated read-only (`enable_mobile_edgeless_editing == false`).
|
||||
pub fn edgeless_readonly(&self) -> bool {
|
||||
self.edgeless_readonly
|
||||
|
||||
@@ -113,7 +113,8 @@ impl PlaygroundView {
|
||||
window: &mut Window,
|
||||
cx: &mut Context<Self>,
|
||||
) {
|
||||
if self.edgeless_readonly
|
||||
if self.is_touch_host()
|
||||
|| self.edgeless_readonly
|
||||
|| f32::from(window.viewport_size().width) < super::SCROLLBAR_DESKTOP_MIN_WIDTH
|
||||
{
|
||||
return;
|
||||
|
||||
@@ -112,6 +112,9 @@ impl PlaygroundView {
|
||||
window: &mut Window,
|
||||
cx: &mut Context<Self>,
|
||||
) {
|
||||
if self.mode == crate::PlaygroundMode::Page && self.page_readonly {
|
||||
return;
|
||||
}
|
||||
if action.requires_body_selection() && self.editor.selection.is_none() {
|
||||
return;
|
||||
}
|
||||
@@ -250,12 +253,33 @@ impl PlaygroundView {
|
||||
KeyboardToolbarAction::Dismiss => {
|
||||
self.keyboard_toolbar_dismissed = true;
|
||||
self.overlays.set_keyboard_toolbar_visible(false);
|
||||
window.notify_text_selection_changed(&self.editor_focus);
|
||||
cx.notify();
|
||||
}
|
||||
}
|
||||
self.sync_keyboard_toolbar_state();
|
||||
}
|
||||
|
||||
/// Whether the native mobile host should present the system software keyboard.
|
||||
pub fn wants_software_keyboard(&self) -> bool {
|
||||
if self.keyboard_toolbar_dismissed {
|
||||
return false;
|
||||
}
|
||||
match self.mode {
|
||||
crate::PlaygroundMode::Page => {
|
||||
!self.page_readonly
|
||||
&& (self.editor.selection.is_some()
|
||||
|| self.table_cell.is_some()
|
||||
|| self.overlays.active_text_field().is_some())
|
||||
}
|
||||
crate::PlaygroundMode::Edgeless => {
|
||||
!self.edgeless_readonly
|
||||
&& (self.edgeless.authoring.editing_spatial_block().is_some()
|
||||
|| self.overlays.active_text_field().is_some())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn step_attachment_pdf_page(&mut self, block_id: &str, delta: i32, cx: &mut Context<Self>) {
|
||||
let Some(source_id) = self.snapshot.as_ref().and_then(|snap| {
|
||||
snap.block(block_id).and_then(|node| match &node.content {
|
||||
@@ -408,4 +432,148 @@ impl PlaygroundView {
|
||||
cx,
|
||||
);
|
||||
}
|
||||
|
||||
/// Focus the editor and place a collapsed caret at offset 0 of the first editable
|
||||
/// paragraph or list block (falling back to the page root title block).
|
||||
pub fn focus_first_text_block(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
||||
self.refresh_document();
|
||||
let target_id = self.snapshot.as_ref().and_then(|snap| {
|
||||
fn find_first_text(
|
||||
nodes: &[blocksuite_playground_doc::read::BlockNode],
|
||||
) -> Option<String> {
|
||||
for node in nodes {
|
||||
match &node.content {
|
||||
blocksuite_playground_doc::read::BlockContent::Paragraph { .. }
|
||||
| blocksuite_playground_doc::read::BlockContent::List { .. } => {
|
||||
return Some(node.id.clone());
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if let Some(found) = find_first_text(&node.children) {
|
||||
return Some(found);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
snap.root
|
||||
.as_ref()
|
||||
.and_then(|root| find_first_text(&root.children).or_else(|| Some(root.id.clone())))
|
||||
});
|
||||
self.editor_focus.focus(window, cx);
|
||||
if let Some(block_id) = target_id {
|
||||
let caret = DocPoint::new(&block_id, 0);
|
||||
self.change_selection(
|
||||
DocumentSelection {
|
||||
anchor: caret.clone(),
|
||||
focus: caret,
|
||||
},
|
||||
window,
|
||||
cx,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn copy_toolbar_selection_or_block(&mut self, cx: &mut Context<Self>) {
|
||||
if let Some(slice) = self.clipboard_slice() {
|
||||
crate::clipboard::write_slice(&slice, cx);
|
||||
return;
|
||||
}
|
||||
if let Some(id) = self.editor.selection.as_ref().map(|s| &s.focus.block_id)
|
||||
&& let Some(text) = self.block_text(id)
|
||||
{
|
||||
cx.write_to_clipboard(ui::ClipboardItem::new_string(text.to_string()));
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn insert_toolbar_plain_text(
|
||||
&mut self,
|
||||
text: &str,
|
||||
w: &mut Window,
|
||||
cx: &mut Context<Self>,
|
||||
) -> blocksuite_playground_doc::DocResult {
|
||||
if self.mode == crate::PlaygroundMode::Page && self.page_readonly {
|
||||
return Ok(());
|
||||
}
|
||||
let Some(sel) = self.editor.selection.clone() else {
|
||||
return Ok(());
|
||||
};
|
||||
self.page_mut()?.stop_capturing()?;
|
||||
self.editor.last_typing = None;
|
||||
self.replace_selection(sel, text, w, cx)?;
|
||||
self.page_mut()?.stop_capturing()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Update the host form factor and apply Stage-1 capability defaults.
|
||||
pub fn set_form_factor(
|
||||
&mut self,
|
||||
form_factor: crate::FormFactor,
|
||||
window: &mut Window,
|
||||
cx: &mut Context<Self>,
|
||||
) {
|
||||
let caps = crate::EditorCapabilities::for_form_factor(form_factor);
|
||||
self.form_factor = caps.form_factor;
|
||||
self.pointer_kind = caps.pointer_kind;
|
||||
self.page_readonly = self.page_readonly || caps.page_readonly;
|
||||
self.set_edgeless_readonly(caps.edgeless_readonly, window, cx);
|
||||
self.set_database_mobile_readonly(caps.database_readonly, cx);
|
||||
}
|
||||
|
||||
/// Whether Database-block mutations are gated read-only.
|
||||
pub fn database_readonly(&self) -> bool {
|
||||
self.database_readonly
|
||||
}
|
||||
|
||||
/// Replace the active document with a fresh single-paragraph empty page and focus it.
|
||||
pub fn load_empty_page_document(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
||||
use blocksuite_playground_doc::schema::{BlockSpec, ParagraphType};
|
||||
|
||||
let Ok(mut state) = crate::room_client::DocState::new("local", 1) else {
|
||||
return;
|
||||
};
|
||||
let _ = state.workspace.initialize_meta();
|
||||
let _ = state
|
||||
.workspace
|
||||
.create_page(crate::HOME_PAGE_ID, "Untitled", 1_700_000_000_000);
|
||||
if let Ok(page) = state.workspace.ensure_page(crate::HOME_PAGE_ID) {
|
||||
let _ = page.add_block(
|
||||
"local-page",
|
||||
BlockSpec::Page {
|
||||
title: "Untitled".to_string(),
|
||||
},
|
||||
None,
|
||||
None,
|
||||
1_000,
|
||||
);
|
||||
let _ = page.add_block(
|
||||
"local-note",
|
||||
BlockSpec::Note {
|
||||
xywh: Some("[0,0,760,1180]".to_string()),
|
||||
},
|
||||
Some("local-page"),
|
||||
None,
|
||||
1_000,
|
||||
);
|
||||
let _ = page.add_block(
|
||||
"local-p1",
|
||||
BlockSpec::Paragraph {
|
||||
paragraph_type: ParagraphType::Text,
|
||||
text: String::new(),
|
||||
},
|
||||
Some("local-note"),
|
||||
None,
|
||||
1_000,
|
||||
);
|
||||
}
|
||||
self.set_document(state, cx);
|
||||
self.focus_first_text_block(window, cx);
|
||||
}
|
||||
|
||||
/// Reload the built-in showcase document and focus its first text block.
|
||||
pub fn load_showcase_document(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
||||
if let Ok(state) = crate::seed_showcase_doc() {
|
||||
self.set_document(state, cx);
|
||||
self.focus_first_text_block(window, cx);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -25,7 +25,7 @@ impl PlaygroundView {
|
||||
self.scroll_y,
|
||||
self.max_scroll,
|
||||
window.layout_direction(),
|
||||
self.edgeless_readonly,
|
||||
self.is_touch_host() || self.edgeless_readonly,
|
||||
) else {
|
||||
return;
|
||||
};
|
||||
@@ -60,7 +60,7 @@ impl PlaygroundView {
|
||||
self.scroll_y,
|
||||
self.max_scroll,
|
||||
window.layout_direction(),
|
||||
self.edgeless_readonly,
|
||||
self.is_touch_host() || self.edgeless_readonly,
|
||||
) else {
|
||||
self.scrollbar_drag = None;
|
||||
return false;
|
||||
|
||||
@@ -447,9 +447,19 @@ fn web_options() -> PlaygroundOptions {
|
||||
if let Some(mode) = params.get("mode").and_then(|v| PlaygroundMode::parse(&v)) {
|
||||
options.mode = mode;
|
||||
}
|
||||
if params
|
||||
.get("mobile")
|
||||
.is_some_and(|v| matches!(v.as_str(), "1" | "true"))
|
||||
{
|
||||
let caps = EditorCapabilities::for_form_factor(FormFactor::Phone);
|
||||
options.pointer_kind = caps.pointer_kind;
|
||||
options.form_factor = caps.form_factor;
|
||||
options.page_readonly = caps.page_readonly;
|
||||
options.edgeless_readonly = caps.edgeless_readonly;
|
||||
options.database_readonly = caps.database_readonly;
|
||||
}
|
||||
if params
|
||||
.get("edgeless_readonly")
|
||||
.or_else(|| params.get("mobile"))
|
||||
.is_some_and(|v| matches!(v.as_str(), "1" | "true"))
|
||||
{
|
||||
options.edgeless_readonly = true;
|
||||
|
||||
Generated
+16
@@ -28,15 +28,23 @@ name = "affine-android-host"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"affine-legacy-import",
|
||||
"affine-mobile",
|
||||
"affine-store",
|
||||
"anyhow",
|
||||
"base64 0.22.1",
|
||||
"chrono",
|
||||
"futures",
|
||||
"playground",
|
||||
"raw-window-handle",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2 0.10.9",
|
||||
"smallvec",
|
||||
"sqlx",
|
||||
"tokio",
|
||||
"ui",
|
||||
"url",
|
||||
"uuid",
|
||||
"y-octo",
|
||||
]
|
||||
|
||||
@@ -60,14 +68,22 @@ name = "affine-ios-host"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"affine-legacy-import",
|
||||
"affine-mobile",
|
||||
"affine-store",
|
||||
"anyhow",
|
||||
"blocksuite-playground-doc",
|
||||
"chrono",
|
||||
"futures",
|
||||
"parking_lot",
|
||||
"playground",
|
||||
"raw-window-handle",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"smallvec",
|
||||
"sqlx",
|
||||
"thiserror 2.0.21",
|
||||
"tokio",
|
||||
"ui",
|
||||
"uuid",
|
||||
]
|
||||
|
||||
|
||||
@@ -8,7 +8,9 @@ It combines a hand-written JNI Rust crate with a minimal Kotlin `SurfaceView` ac
|
||||
- Keep zero JNA and zero UniFFI bindings.
|
||||
Export hand-written `extern "C"` JNI symbols under `#[cfg(any(target_os = "android", test, feature = "host-jni"))]` across `src/jni_bridge.rs`, `src/jni_interaction.rs`, and `src/jni_storage.rs`.
|
||||
- Keep the main app shell free of any persistent `WebView` and free of `SurfaceHolder.lockCanvas` calls.
|
||||
- Use `ShapedTextLayout` (cached Android `StaticLayout` with UAX #9 first-strong BiDi) as the single authoritative layout engine for `HostTextPreviewView` (the transitional host preview layer before S4 shared editor integration), teardrop handle tips, hit-testing, and `AndroidSelectionOverlayView` (`src/text_layout.rs` is the headless pure-Rust fallback).
|
||||
- Mount the live pure-Rust `PlaygroundView` (`src/editor_platform.rs`, `src/editor_runtime.rs`, `src/jni_editor.rs`) inside `MainActivity` (`AffineSurfaceView` + `AndroidSelectionOverlayView`, with `HostTextPreviewView` removed from `MainActivity` to prevent double-drawing). Forward `MotionEvent` touch pointers (`nativeOnTouchEvent`), `InputConnection.sendKeyEvent` (`nativeOnKeyEvent`), and `FormFactor::from_android_smallest_width_dp` (`< 600` -> `Phone`, `>= 600` -> `Tablet`, Stage-1 `edgeless_readonly = true`, `database_readonly = true`).
|
||||
- Enforce zero host text copy (`AffineInputConnection` reads straight from `PlatformInputHandler`), push editor mutations to `InputMethodManager.updateSelection` / `restartInput` / `updateCursorAnchorInfo`, and preserve exact `[start, end)` ranges in `setComposingRegion` via `replace_and_mark_text_in_range`.
|
||||
- Use `scripts/package-debug-apk.sh` to build and sign `AffineAndroidHost-debug.apk` directly with Android SDK CLI tools (`aapt2`, `kotlinc`, `d8`, `zipalign`, `apksigner`) without Gradle daemons.
|
||||
Compute teardrop handle geometry, line-midpoint grab-offset drag, UTF-16 anchor-authoritative handle ownership (`nativeApplyTextDragEndpoints`), continuous zero-length crossover inversion, off-screen hiding, line-midpoint magnifier focus, and Copy/Cut/Paste/SelectAll actions wired to `ClipboardManager` (`HostClipboard` / `AndroidClipboardAdapter`, checking `primaryClipDescription` metadata without reading `primaryClip` during draw, and writing before deleting on `Cut`) and `InputConnection.performContextMenuAction` in `src/selection.rs`, `src/ime.rs`, and `MainActivity.kt`.
|
||||
`AndroidSelectionOverlayView` fills a pre-allocated 24-float JNI buffer (`nativeFillSelectionOverlayGeometry`) and draws teardrop `Path` handles, `getSelectionPath` loupe highlights with centered focus carets, and `Copy | Cut | Paste` pills with dividers using zero per-frame allocations, zero Binder IPC in `onDraw`, and zero `SurfaceHolder.lockCanvas` calls.
|
||||
- Clear the default surface canvas to light `#FAFAFC` (`DEFAULT_CLEAR_COLOR_ARGB = 0xFFFA_FAFC`) and adapt `HostTextPreviewView` text and selection colors to surface luminance.
|
||||
|
||||
@@ -14,15 +14,23 @@ host-jni = []
|
||||
|
||||
[dependencies]
|
||||
affine-legacy-import = { path = "../../legacy-import" }
|
||||
affine-mobile = { path = "../../mobile" }
|
||||
affine-store = { path = "../../../common/store" }
|
||||
anyhow.workspace = true
|
||||
base64.workspace = true
|
||||
chrono.workspace = true
|
||||
futures.workspace = true
|
||||
playground = { path = "../../../../blocksuite/crates/playground" }
|
||||
raw-window-handle.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
sha2.workspace = true
|
||||
smallvec.workspace = true
|
||||
sqlx.workspace = true
|
||||
tokio.workspace = true
|
||||
ui = { path = "../../../ui/ui" }
|
||||
url.workspace = true
|
||||
uuid.workspace = true
|
||||
y-octo.workspace = true
|
||||
|
||||
[lints]
|
||||
|
||||
@@ -39,11 +39,13 @@ import android.view.autofill.AutofillManager
|
||||
import android.view.autofill.AutofillValue
|
||||
import android.view.inputmethod.CompletionInfo
|
||||
import android.view.inputmethod.CorrectionInfo
|
||||
import android.view.inputmethod.CursorAnchorInfo
|
||||
import android.view.inputmethod.EditorInfo
|
||||
import android.view.inputmethod.ExtractedText
|
||||
import android.view.inputmethod.ExtractedTextRequest
|
||||
import android.view.inputmethod.InputConnection
|
||||
import android.view.inputmethod.InputContentInfo
|
||||
import android.view.inputmethod.InputMethodManager
|
||||
import android.view.inputmethod.TextAttribute
|
||||
import android.widget.FrameLayout
|
||||
import android.window.BackEvent
|
||||
@@ -103,6 +105,8 @@ object NativeBridge {
|
||||
newCursorPosition: Int,
|
||||
): Boolean
|
||||
external fun nativeGetUtf16Length(handle: Long): Int
|
||||
external fun nativeGetUtf16Text(handle: Long): String
|
||||
external fun nativeHasPendingTimer(handle: Long): Boolean
|
||||
external fun nativeGetUtf16Unit(handle: Long, index: Int): Int
|
||||
external fun nativeGetSelectionStart(handle: Long): Int
|
||||
external fun nativeGetSelectionEnd(handle: Long): Int
|
||||
@@ -276,6 +280,34 @@ object NativeBridge {
|
||||
widthPx: Int,
|
||||
heightPx: Int,
|
||||
): ByteArray?
|
||||
|
||||
// Live pure-Rust GPU BlockSuite editor mount, touch/key dispatch, and H-S2 IME sync.
|
||||
external fun nativeLoadShowcaseDocument(handle: Long)
|
||||
external fun nativeResetEmptyDocument(handle: Long)
|
||||
external fun nativeSetFormFactor(handle: Long, smallestWidthDp: Int)
|
||||
external fun nativeIsEdgelessReadonly(handle: Long): Boolean
|
||||
external fun nativeIsDatabaseReadonly(handle: Long): Boolean
|
||||
external fun nativeSetEditorMode(handle: Long, modeCode: Int)
|
||||
external fun nativeOnTouchEvent(
|
||||
handle: Long,
|
||||
pointerId: Long,
|
||||
phase: Int,
|
||||
xDp: Float,
|
||||
yDp: Float,
|
||||
)
|
||||
external fun nativeOnKeyEvent(
|
||||
handle: Long,
|
||||
keyCode: Int,
|
||||
shift: Boolean,
|
||||
ctrl: Boolean,
|
||||
alt: Boolean,
|
||||
): Boolean
|
||||
external fun nativeGetTextInputChangeSeq(handle: Long): Long
|
||||
external fun nativeGetFocusedBlockHash(handle: Long): Long
|
||||
external fun nativeWantsSoftwareKeyboard(handle: Long): Boolean
|
||||
external fun nativeGetCaretRectDpX(handle: Long): Float
|
||||
external fun nativeGetCaretRectDpY(handle: Long): Float
|
||||
external fun nativeGetCaretRectDpHeight(handle: Long): Float
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -416,10 +448,7 @@ class AffineImeController(
|
||||
fun readText(): String {
|
||||
val handle = handleProvider()
|
||||
if (handle == 0L) return ""
|
||||
val len = NativeBridge.nativeGetUtf16Length(handle)
|
||||
if (len <= 0) return ""
|
||||
val chars = CharArray(len) { idx -> NativeBridge.nativeGetUtf16Unit(handle, idx).toChar() }
|
||||
return String(chars)
|
||||
return NativeBridge.nativeGetUtf16Text(handle)
|
||||
}
|
||||
|
||||
fun selectionStart(): Int {
|
||||
@@ -464,6 +493,27 @@ class AffineImeController(
|
||||
val selEnd = selectionEnd().coerceIn(selStart, text.length)
|
||||
return if (selStart == selEnd) null else text.substring(selStart, selEnd)
|
||||
}
|
||||
|
||||
fun sendKeyEvent(keyCode: Int, shift: Boolean, ctrl: Boolean, alt: Boolean): Boolean {
|
||||
val handle = handleProvider()
|
||||
if (handle == 0L) return false
|
||||
val handled = NativeBridge.nativeOnKeyEvent(handle, keyCode, shift, ctrl, alt)
|
||||
if (handled) {
|
||||
onMutated()
|
||||
onTextEdited(currentText())
|
||||
}
|
||||
return handled
|
||||
}
|
||||
|
||||
fun textInputChangeSeq(): Long {
|
||||
val handle = handleProvider()
|
||||
return if (handle == 0L) 0L else NativeBridge.nativeGetTextInputChangeSeq(handle)
|
||||
}
|
||||
|
||||
fun focusedBlockHash(): Long {
|
||||
val handle = handleProvider()
|
||||
return if (handle == 0L) 0L else NativeBridge.nativeGetFocusedBlockHash(handle)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -473,8 +523,10 @@ class AffineImeController(
|
||||
class AffineInputConnection(
|
||||
private val ime: AffineImeController,
|
||||
private val onContextMenuAction: (Int) -> Boolean = { false },
|
||||
private val onCursorUpdatesRequested: (Int) -> Unit = {},
|
||||
) : InputConnection {
|
||||
private var batchEditDepth: Int = 0
|
||||
private var cursorUpdateMonitor: Boolean = false
|
||||
|
||||
override fun getTextBeforeCursor(n: Int, flags: Int): CharSequence = ime.getTextBeforeCursor(n)
|
||||
|
||||
@@ -484,7 +536,15 @@ class AffineInputConnection(
|
||||
|
||||
override fun getCursorCapsMode(reqModes: Int): Int = 0
|
||||
|
||||
override fun getExtractedText(request: ExtractedTextRequest?, flags: Int): ExtractedText? = null
|
||||
override fun getExtractedText(request: ExtractedTextRequest?, flags: Int): ExtractedText {
|
||||
val text = ime.readText()
|
||||
return ExtractedText().apply {
|
||||
this.text = text
|
||||
startOffset = 0
|
||||
selectionStart = ime.selectionStart().coerceIn(0, text.length)
|
||||
selectionEnd = ime.selectionEnd().coerceIn(selectionStart, text.length)
|
||||
}
|
||||
}
|
||||
|
||||
override fun deleteSurroundingText(beforeLength: Int, afterLength: Int): Boolean =
|
||||
ime.deleteSurroundingText(beforeLength, afterLength)
|
||||
@@ -569,13 +629,34 @@ class AffineInputConnection(
|
||||
|
||||
override fun performPrivateCommand(action: String?, data: Bundle?): Boolean = false
|
||||
|
||||
override fun sendKeyEvent(event: KeyEvent?): Boolean = false
|
||||
override fun sendKeyEvent(event: KeyEvent?): Boolean {
|
||||
if (event == null || event.action != KeyEvent.ACTION_DOWN) return false
|
||||
if (ime.composingStart() >= 0) return false
|
||||
val handled = ime.sendKeyEvent(
|
||||
keyCode = event.keyCode,
|
||||
shift = event.isShiftPressed,
|
||||
ctrl = event.isCtrlPressed,
|
||||
alt = event.isAltPressed,
|
||||
)
|
||||
if (handled) return true
|
||||
val ch = event.unicodeChar
|
||||
if (ch > 0 && !event.isCtrlPressed && !event.isMetaPressed && !event.isAltPressed) {
|
||||
return ime.commitText(String(Character.toChars(ch)), 1)
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
override fun clearMetaKeyStates(states: Int): Boolean = false
|
||||
|
||||
override fun reportFullscreenMode(enabled: Boolean): Boolean = false
|
||||
|
||||
override fun requestCursorUpdates(cursorUpdateMode: Int): Boolean = false
|
||||
override fun requestCursorUpdates(cursorUpdateMode: Int): Boolean {
|
||||
cursorUpdateMonitor = (cursorUpdateMode and InputConnection.CURSOR_UPDATE_MONITOR) != 0
|
||||
if ((cursorUpdateMode and InputConnection.CURSOR_UPDATE_IMMEDIATE) != 0 || cursorUpdateMonitor) {
|
||||
onCursorUpdatesRequested(cursorUpdateMode)
|
||||
}
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -938,8 +1019,9 @@ class SelectionGestureController(
|
||||
}
|
||||
|
||||
/**
|
||||
* Coordinates strict isolation between Autofill form field editing and the
|
||||
* per-route document buffer (`HostDocumentStore` + `HostTextPreviewView`).
|
||||
* Coordinates strict isolation between Autofill form fields and the authoritative
|
||||
* GPU BlockSuite editor (`H-S1`: never writes route text or Autofill credentials
|
||||
* into `AffineImeController` and never keeps a shadow copy of editor text).
|
||||
*/
|
||||
class HostDocumentBufferController(
|
||||
val documentStore: HostDocumentStore,
|
||||
@@ -947,12 +1029,7 @@ class HostDocumentBufferController(
|
||||
private val autofillProvider: () -> AndroidAutofillController?,
|
||||
private val onDocumentPreviewUpdated: (String) -> Unit = {},
|
||||
) {
|
||||
private var syncingAutofillFocus: Boolean = false
|
||||
private var syncingDocumentSwitch: Boolean = false
|
||||
private var autofillDirtiedIme: Boolean = false
|
||||
private var docSelectionStart: Int = 0
|
||||
private var docSelectionEnd: Int = 0
|
||||
var lastPreviewText: String = documentStore.readDocument(documentStore.activeDocumentId)
|
||||
var lastPreviewText: String = ""
|
||||
private set
|
||||
|
||||
fun isAutofillFocused(): Boolean = autofillProvider()?.focusedFieldId() != null
|
||||
@@ -960,128 +1037,49 @@ class HostDocumentBufferController(
|
||||
fun isFocusedAutofillFieldMasked(): Boolean =
|
||||
autofillProvider()?.isFocusedFieldMasked() == true
|
||||
|
||||
fun currentDocumentText(): String = documentStore.readDocument(documentStore.activeDocumentId)
|
||||
fun currentDocumentText(): String = imeProvider().currentText()
|
||||
|
||||
fun recordDocumentSelection(selStart: Int, selEnd: Int) {
|
||||
if (syncingAutofillFocus || syncingDocumentSwitch || isAutofillFocused() || autofillDirtiedIme) {
|
||||
return
|
||||
}
|
||||
docSelectionStart = selStart
|
||||
docSelectionEnd = selEnd
|
||||
val _unused = selStart + selEnd
|
||||
}
|
||||
|
||||
fun onImeTextEdited(text: String) {
|
||||
if (syncingAutofillFocus || syncingDocumentSwitch) return
|
||||
if (isAutofillFocused()) {
|
||||
autofillDirtiedIme = true
|
||||
// Strictly isolate form credentials from document storage and HostTextPreviewView.
|
||||
autofillProvider()?.onFocusedTextEdited(text)
|
||||
return
|
||||
}
|
||||
if (autofillDirtiedIme) {
|
||||
restoreDocumentBufferToIme()
|
||||
return
|
||||
}
|
||||
documentStore.saveCurrent(text)
|
||||
lastPreviewText = text
|
||||
}
|
||||
|
||||
fun applyAutofillTextToIme(text: String) {
|
||||
val ime = imeProvider()
|
||||
autofillDirtiedIme = true
|
||||
syncingAutofillFocus = true
|
||||
try {
|
||||
ime.replaceText(0, ime.currentText().length, text, 1)
|
||||
} finally {
|
||||
syncingAutofillFocus = false
|
||||
}
|
||||
// H-S1: Autofill values stay strictly isolated in AndroidAutofillController
|
||||
// and must NEVER be written into the authoritative BlockSuite editor IME.
|
||||
val _isolated = text
|
||||
}
|
||||
|
||||
fun restoreDocumentBufferToIme() {
|
||||
val docText = currentDocumentText()
|
||||
val lo = docSelectionStart.coerceIn(0, docText.length)
|
||||
val hi = docSelectionEnd.coerceIn(lo, docText.length)
|
||||
val ime = imeProvider()
|
||||
syncingAutofillFocus = true
|
||||
try {
|
||||
ime.replaceText(0, ime.currentText().length, docText, 1)
|
||||
ime.setSelection(lo, hi)
|
||||
} finally {
|
||||
syncingAutofillFocus = false
|
||||
}
|
||||
autofillDirtiedIme = false
|
||||
lastPreviewText = docText
|
||||
onDocumentPreviewUpdated(docText)
|
||||
// H-S1: Editor CRDT text is never overwritten by Autofill or host buffers.
|
||||
val liveText = imeProvider().currentText()
|
||||
lastPreviewText = liveText
|
||||
onDocumentPreviewUpdated(liveText)
|
||||
}
|
||||
|
||||
fun onAutofillFocusChanged(nextFieldId: Int?) {
|
||||
val af = autofillProvider()
|
||||
val prev = af?.focusedFieldId()
|
||||
val wasDirty = autofillDirtiedIme
|
||||
if (prev == null && nextFieldId != null && !wasDirty) {
|
||||
val ime = imeProvider()
|
||||
docSelectionStart = ime.selectionStart()
|
||||
docSelectionEnd = ime.selectionEnd()
|
||||
}
|
||||
af?.onFieldFocusChanged(nextFieldId)
|
||||
val nowFocused = af?.focusedFieldId() != null
|
||||
if (nowFocused) {
|
||||
autofillDirtiedIme = true
|
||||
onDocumentPreviewUpdated(currentDocumentText())
|
||||
} else if (prev != null || wasDirty) {
|
||||
restoreDocumentBufferToIme()
|
||||
}
|
||||
autofillProvider()?.onFieldFocusChanged(nextFieldId)
|
||||
}
|
||||
|
||||
fun commitAutofillSession(): Boolean {
|
||||
val needRestore = isAutofillFocused() || autofillDirtiedIme
|
||||
val ok = autofillProvider()?.commit() ?: false
|
||||
if (needRestore) {
|
||||
restoreDocumentBufferToIme()
|
||||
}
|
||||
return ok
|
||||
}
|
||||
fun commitAutofillSession(): Boolean = autofillProvider()?.commit() ?: false
|
||||
|
||||
fun cancelAutofillSession(): Boolean {
|
||||
val needRestore = isAutofillFocused() || autofillDirtiedIme
|
||||
val ok = autofillProvider()?.cancel() ?: false
|
||||
if (needRestore) {
|
||||
restoreDocumentBufferToIme()
|
||||
}
|
||||
return ok
|
||||
}
|
||||
fun cancelAutofillSession(): Boolean = autofillProvider()?.cancel() ?: false
|
||||
|
||||
fun clearAutofillFields() {
|
||||
val needRestore = isAutofillFocused() || autofillDirtiedIme
|
||||
autofillProvider()?.clearFields()
|
||||
if (needRestore) {
|
||||
restoreDocumentBufferToIme()
|
||||
}
|
||||
}
|
||||
|
||||
fun onRouteChanged(nextRoute: String) {
|
||||
if (documentStore.activeDocumentId == nextRoute) return
|
||||
val wasAutofillFocused = isAutofillFocused()
|
||||
val outgoingDocText = if (wasAutofillFocused || autofillDirtiedIme) {
|
||||
// Preserve the document's own text and exit Autofill focus before loading the new route.
|
||||
if (isAutofillFocused()) {
|
||||
autofillProvider()?.onFieldFocusChanged(null)
|
||||
currentDocumentText()
|
||||
} else {
|
||||
imeProvider().currentText()
|
||||
}
|
||||
autofillDirtiedIme = false
|
||||
docSelectionStart = 0
|
||||
docSelectionEnd = 0
|
||||
val targetText = documentStore.switchTo(nextRoute, outgoingDocText)
|
||||
syncingDocumentSwitch = true
|
||||
try {
|
||||
val ime = imeProvider()
|
||||
ime.replaceText(0, ime.currentText().length, targetText, 1)
|
||||
} finally {
|
||||
syncingDocumentSwitch = false
|
||||
}
|
||||
lastPreviewText = targetText
|
||||
onDocumentPreviewUpdated(targetText)
|
||||
documentStore.switchTo(nextRoute, "")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1385,59 +1383,10 @@ internal fun isLightClearColor(argb: Int): Boolean {
|
||||
}
|
||||
|
||||
/**
|
||||
* Lightweight transitional text preview layer (until S4 shared editor integration)
|
||||
* sharing the exact cached `ShapedTextLayout` with `AndroidSelectionOverlayView` so
|
||||
* document text and `getSelectionPath` selection highlights align 1:1 with teardrop
|
||||
* handles and the magnified loupe.
|
||||
*/
|
||||
class HostTextPreviewView(
|
||||
context: Context,
|
||||
private val shapedLayout: ShapedTextLayout,
|
||||
private val selectionStartProvider: () -> Int,
|
||||
private val selectionEndProvider: () -> Int,
|
||||
) : View(context) {
|
||||
private val selectionHighlightPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
|
||||
color = Color.argb(56, 30, 150, 235)
|
||||
style = Paint.Style.FILL
|
||||
}
|
||||
private val reusableSelectionPath = Path()
|
||||
|
||||
init {
|
||||
setWillNotDraw(false)
|
||||
isClickable = false
|
||||
isFocusable = false
|
||||
}
|
||||
|
||||
fun applyClearColor(clearColorArgb: Int) {
|
||||
shapedLayout.applyClearColor(clearColorArgb)
|
||||
selectionHighlightPaint.color = if (isLightClearColor(clearColorArgb)) {
|
||||
Color.argb(56, 30, 150, 235)
|
||||
} else {
|
||||
Color.argb(96, 56, 178, 255)
|
||||
}
|
||||
invalidate()
|
||||
}
|
||||
|
||||
override fun onDraw(canvas: Canvas) {
|
||||
super.onDraw(canvas)
|
||||
val layout = shapedLayout.cachedLayout ?: return
|
||||
val selStart = selectionStartProvider()
|
||||
val selEnd = selectionEndProvider()
|
||||
canvas.save()
|
||||
canvas.translate(shapedLayout.paddingLeftPx, shapedLayout.paddingTopPx)
|
||||
if (shapedLayout.fillSelectionPath(selStart, selEnd, reusableSelectionPath)) {
|
||||
canvas.drawPath(reusableSelectionPath, selectionHighlightPaint)
|
||||
}
|
||||
layout.draw(canvas)
|
||||
canvas.restore()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Pure Android `View` overlay layered above `AffineSurfaceView` and `HostTextPreviewView`
|
||||
* in a `FrameLayout` to render teardrop handles, single-authority `ShapedTextLayout`
|
||||
* magnified loupe (with `getSelectionPath` highlight and vertically centered focus), and
|
||||
* clickable `Copy | Cut | Paste` action menu pills with zero per-frame allocations and
|
||||
* Pure Android `View` overlay layered above `AffineSurfaceView` in a `FrameLayout`
|
||||
* to render teardrop handles, single-authority `ShapedTextLayout` magnified loupe
|
||||
* (with `getSelectionPath` highlight and vertically centered focus), and clickable
|
||||
* `Copy | Cut | Paste` action menu pills with zero per-frame allocations and
|
||||
* without ever calling `SurfaceHolder.lockCanvas`.
|
||||
*/
|
||||
class AndroidSelectionOverlayView(
|
||||
@@ -2192,6 +2141,8 @@ internal class AffineSurfaceView(
|
||||
private val onTextEdited: (String) -> Unit = {},
|
||||
private val onContextMenuAction: (Int) -> Boolean = { false },
|
||||
private val autofillProvider: () -> AndroidAutofillController? = { null },
|
||||
private val onTouchDispatched: () -> Unit = {},
|
||||
private val onCursorUpdatesRequested: (Int) -> Unit = {},
|
||||
) : SurfaceView(context) {
|
||||
init {
|
||||
isFocusable = true
|
||||
@@ -2206,10 +2157,157 @@ internal class AffineSurfaceView(
|
||||
importantForAutofill = View.IMPORTANT_FOR_AUTOFILL_YES
|
||||
}
|
||||
|
||||
private var touchDownX = 0f
|
||||
private var touchDownY = 0f
|
||||
private var touchMovedBeyondSlop = false
|
||||
|
||||
override fun onCheckIsTextEditor(): Boolean = true
|
||||
|
||||
override fun onTouchEvent(event: MotionEvent): Boolean {
|
||||
val handle = handleProvider()
|
||||
if (handle == 0L) return super.onTouchEvent(event)
|
||||
val density = resources.displayMetrics.density.coerceAtLeast(1f)
|
||||
val slopPx = 10f * density
|
||||
when (event.actionMasked) {
|
||||
MotionEvent.ACTION_DOWN, MotionEvent.ACTION_POINTER_DOWN -> {
|
||||
val idx = event.actionIndex
|
||||
if (event.actionMasked == MotionEvent.ACTION_DOWN) {
|
||||
touchDownX = event.getX(idx)
|
||||
touchDownY = event.getY(idx)
|
||||
touchMovedBeyondSlop = false
|
||||
}
|
||||
NativeBridge.nativeOnTouchEvent(
|
||||
handle,
|
||||
event.getPointerId(idx).toLong(),
|
||||
0,
|
||||
event.getX(idx) / density,
|
||||
event.getY(idx) / density,
|
||||
)
|
||||
}
|
||||
MotionEvent.ACTION_MOVE -> {
|
||||
if (event.pointerCount > 0) {
|
||||
val dx = event.getX(0) - touchDownX
|
||||
val dy = event.getY(0) - touchDownY
|
||||
if (dx * dx + dy * dy > slopPx * slopPx) {
|
||||
touchMovedBeyondSlop = true
|
||||
}
|
||||
}
|
||||
// Forward historical touch samples before the current sample so inertial
|
||||
// fling velocity stays smooth on 60/120 Hz Android displays.
|
||||
for (h in 0 until event.historySize) {
|
||||
for (idx in 0 until event.pointerCount) {
|
||||
NativeBridge.nativeOnTouchEvent(
|
||||
handle,
|
||||
event.getPointerId(idx).toLong(),
|
||||
1,
|
||||
event.getHistoricalX(idx, h) / density,
|
||||
event.getHistoricalY(idx, h) / density,
|
||||
)
|
||||
}
|
||||
}
|
||||
for (idx in 0 until event.pointerCount) {
|
||||
NativeBridge.nativeOnTouchEvent(
|
||||
handle,
|
||||
event.getPointerId(idx).toLong(),
|
||||
1,
|
||||
event.getX(idx) / density,
|
||||
event.getY(idx) / density,
|
||||
)
|
||||
}
|
||||
}
|
||||
MotionEvent.ACTION_UP, MotionEvent.ACTION_POINTER_UP -> {
|
||||
val idx = event.actionIndex
|
||||
NativeBridge.nativeOnTouchEvent(
|
||||
handle,
|
||||
event.getPointerId(idx).toLong(),
|
||||
2,
|
||||
event.getX(idx) / density,
|
||||
event.getY(idx) / density,
|
||||
)
|
||||
if (event.actionMasked == MotionEvent.ACTION_UP) {
|
||||
val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager
|
||||
if (NativeBridge.nativeWantsSoftwareKeyboard(handle)) {
|
||||
if (!touchMovedBeyondSlop) {
|
||||
requestFocus()
|
||||
imm?.showSoftInput(this, InputMethodManager.SHOW_IMPLICIT)
|
||||
}
|
||||
} else {
|
||||
imm?.hideSoftInputFromWindow(windowToken, 0)
|
||||
}
|
||||
}
|
||||
}
|
||||
MotionEvent.ACTION_CANCEL -> {
|
||||
for (idx in 0 until event.pointerCount) {
|
||||
NativeBridge.nativeOnTouchEvent(
|
||||
handle,
|
||||
event.getPointerId(idx).toLong(),
|
||||
3,
|
||||
event.getX(idx) / density,
|
||||
event.getY(idx) / density,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
onTouchDispatched()
|
||||
return true
|
||||
}
|
||||
|
||||
override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
|
||||
val handle = handleProvider()
|
||||
if (handle == 0L) return super.onKeyDown(keyCode, event)
|
||||
val ime = AffineImeController(handleProvider, onMutated, onTextEdited)
|
||||
// Yield hardware keyboard navigation/edit keys while IME composition is active.
|
||||
if (ime.composingStart() >= 0) {
|
||||
return super.onKeyDown(keyCode, event)
|
||||
}
|
||||
val handled = ime.sendKeyEvent(
|
||||
keyCode = keyCode,
|
||||
shift = event.isShiftPressed,
|
||||
ctrl = event.isCtrlPressed,
|
||||
alt = event.isAltPressed,
|
||||
)
|
||||
if (handled) {
|
||||
onTouchDispatched()
|
||||
return true
|
||||
}
|
||||
val ch = event.unicodeChar
|
||||
if (ch > 0 && !event.isCtrlPressed && !event.isMetaPressed && !event.isAltPressed) {
|
||||
if (ime.commitText(String(Character.toChars(ch)), 1)) {
|
||||
onTouchDispatched()
|
||||
return true
|
||||
}
|
||||
}
|
||||
return super.onKeyDown(keyCode, event)
|
||||
}
|
||||
|
||||
override fun onGenericMotionEvent(event: MotionEvent): Boolean {
|
||||
val handle = handleProvider()
|
||||
if (handle != 0L && event.actionMasked == MotionEvent.ACTION_SCROLL) {
|
||||
val vScroll = event.getAxisValue(MotionEvent.AXIS_VSCROLL)
|
||||
val density = resources.displayMetrics.density.coerceAtLeast(1f)
|
||||
if (vScroll != 0f) {
|
||||
val xDp = event.x / density
|
||||
val yDp = event.y / density
|
||||
val deltaDp = vScroll * 48f
|
||||
NativeBridge.nativeOnTouchEvent(handle, 9999L, 0, xDp, yDp)
|
||||
NativeBridge.nativeOnTouchEvent(handle, 9999L, 1, xDp, yDp + deltaDp)
|
||||
NativeBridge.nativeOnTouchEvent(handle, 9999L, 2, xDp, yDp + deltaDp)
|
||||
onTouchDispatched()
|
||||
return true
|
||||
}
|
||||
}
|
||||
return super.onGenericMotionEvent(event)
|
||||
}
|
||||
|
||||
override fun onCreateInputConnection(outAttrs: EditorInfo): InputConnection =
|
||||
createInputConnection(handleProvider, outAttrs, onMutated, onTextEdited, onContextMenuAction)
|
||||
createInputConnection(
|
||||
handleProvider,
|
||||
outAttrs,
|
||||
onMutated,
|
||||
onTextEdited,
|
||||
onContextMenuAction,
|
||||
onCursorUpdatesRequested,
|
||||
)
|
||||
|
||||
@TargetApi(Build.VERSION_CODES.O)
|
||||
override fun onProvideAutofillVirtualStructure(structure: ViewStructure, flags: Int) {
|
||||
@@ -2234,6 +2332,7 @@ internal class AffineSurfaceView(
|
||||
onMutated: () -> Unit = {},
|
||||
onTextEdited: (String) -> Unit = {},
|
||||
onContextMenuAction: (Int) -> Boolean = { false },
|
||||
onCursorUpdatesRequested: (Int) -> Unit = {},
|
||||
): InputConnection {
|
||||
val ime = AffineImeController(handleProvider, onMutated, onTextEdited)
|
||||
if (outAttrs != null) {
|
||||
@@ -2242,7 +2341,7 @@ internal class AffineSurfaceView(
|
||||
outAttrs.initialSelStart = ime.selectionStart()
|
||||
outAttrs.initialSelEnd = ime.selectionEnd()
|
||||
}
|
||||
return AffineInputConnection(ime, onContextMenuAction)
|
||||
return AffineInputConnection(ime, onContextMenuAction, onCursorUpdatesRequested)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2250,7 +2349,6 @@ internal class AffineSurfaceView(
|
||||
class MainActivity : Activity(), SurfaceHolder.Callback, Choreographer.FrameCallback {
|
||||
private var nativeHandle: Long = 0L
|
||||
private lateinit var surfaceView: AffineSurfaceView
|
||||
private lateinit var textPreviewView: HostTextPreviewView
|
||||
private lateinit var selectionOverlayView: AndroidSelectionOverlayView
|
||||
private lateinit var shapedLayout: ShapedTextLayout
|
||||
private lateinit var bootstrapCoordinator: AndroidBootstrapCoordinator
|
||||
@@ -2263,6 +2361,8 @@ class MainActivity : Activity(), SurfaceHolder.Callback, Choreographer.FrameCall
|
||||
private var autofillController: AndroidAutofillController? = null
|
||||
private var syncingOverlay: Boolean = false
|
||||
private var lastViewportWidthPx: Int = 0
|
||||
private var lastImeChangeSeq: Long = 0L
|
||||
private var lastFocusedBlockHash: Long = 0L
|
||||
private var clearColorArgb: Int = DEFAULT_SURFACE_CLEAR_COLOR_ARGB
|
||||
@Volatile
|
||||
var lastBootstrapOutcome: BootstrapOutcome? = null
|
||||
@@ -2276,12 +2376,21 @@ class MainActivity : Activity(), SurfaceHolder.Callback, Choreographer.FrameCall
|
||||
private var backCallback: OnBackInvokedCallback? = null
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
requestWindowFeature(android.view.Window.FEATURE_NO_TITLE)
|
||||
super.onCreate(savedInstanceState)
|
||||
actionBar?.hide()
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
|
||||
window.setDecorFitsSystemWindows(false)
|
||||
}
|
||||
|
||||
nativeHandle = NativeBridge.nativeCreateHost()
|
||||
NativeBridge.nativeSetFormFactor(
|
||||
nativeHandle,
|
||||
resources.configuration.smallestScreenWidthDp,
|
||||
)
|
||||
NativeBridge.nativeLoadShowcaseDocument(nativeHandle)
|
||||
lastImeChangeSeq = NativeBridge.nativeGetTextInputChangeSeq(nativeHandle)
|
||||
lastFocusedBlockHash = NativeBridge.nativeGetFocusedBlockHash(nativeHandle)
|
||||
shapedLayout = ShapedTextLayout(resources.displayMetrics.density).apply {
|
||||
applyClearColor(clearColorArgb)
|
||||
}
|
||||
@@ -2310,12 +2419,10 @@ class MainActivity : Activity(), SurfaceHolder.Callback, Choreographer.FrameCall
|
||||
syncShapedLayoutAndOverlay(imeController.currentText())
|
||||
}
|
||||
}
|
||||
if (::textPreviewView.isInitialized) {
|
||||
textPreviewView.invalidate()
|
||||
}
|
||||
if (::selectionOverlayView.isInitialized) {
|
||||
selectionOverlayView.invalidate()
|
||||
}
|
||||
syncSystemImeFromEditor()
|
||||
requestFrameAndSchedule()
|
||||
}
|
||||
val onImeTextEdited: (String) -> Unit = { text ->
|
||||
@@ -2374,21 +2481,16 @@ class MainActivity : Activity(), SurfaceHolder.Callback, Choreographer.FrameCall
|
||||
onTextEdited = onImeTextEdited,
|
||||
onContextMenuAction = onContextMenuAction,
|
||||
autofillProvider = { autofillController },
|
||||
onTouchDispatched = {
|
||||
syncSystemImeFromEditor()
|
||||
requestFrameAndSchedule()
|
||||
},
|
||||
onCursorUpdatesRequested = {
|
||||
pushCursorAnchorInfo()
|
||||
},
|
||||
).apply {
|
||||
holder.addCallback(this@MainActivity)
|
||||
}
|
||||
textPreviewView = HostTextPreviewView(
|
||||
context = this,
|
||||
shapedLayout = shapedLayout,
|
||||
selectionStartProvider = {
|
||||
if (documentBufferController.isAutofillFocused()) 0 else imeController.selectionStart()
|
||||
},
|
||||
selectionEndProvider = {
|
||||
if (documentBufferController.isAutofillFocused()) 0 else imeController.selectionEnd()
|
||||
},
|
||||
).apply {
|
||||
applyClearColor(clearColorArgb)
|
||||
}
|
||||
selectionOverlayView = AndroidSelectionOverlayView(
|
||||
context = this,
|
||||
coordinator = selectionCoordinator,
|
||||
@@ -2402,9 +2504,7 @@ class MainActivity : Activity(), SurfaceHolder.Callback, Choreographer.FrameCall
|
||||
} finally {
|
||||
syncingOverlay = false
|
||||
}
|
||||
if (::textPreviewView.isInitialized) {
|
||||
textPreviewView.invalidate()
|
||||
}
|
||||
syncSystemImeFromEditor()
|
||||
},
|
||||
canPaste = { clipboardAdapter.hasPlainText() },
|
||||
onActionCopy = {
|
||||
@@ -2433,13 +2533,6 @@ class MainActivity : Activity(), SurfaceHolder.Callback, Choreographer.FrameCall
|
||||
FrameLayout.LayoutParams.MATCH_PARENT,
|
||||
),
|
||||
)
|
||||
addView(
|
||||
textPreviewView,
|
||||
FrameLayout.LayoutParams(
|
||||
FrameLayout.LayoutParams.MATCH_PARENT,
|
||||
FrameLayout.LayoutParams.MATCH_PARENT,
|
||||
),
|
||||
)
|
||||
addView(
|
||||
selectionOverlayView,
|
||||
FrameLayout.LayoutParams(
|
||||
@@ -2519,6 +2612,7 @@ class MainActivity : Activity(), SurfaceHolder.Callback, Choreographer.FrameCall
|
||||
frameCallbackPosted = false
|
||||
if (!frameLoopActive || !surfaceReady || nativeHandle == 0L) return
|
||||
NativeBridge.nativeOnFrameTick(nativeHandle, frameTimeNanos)
|
||||
syncSystemImeFromEditor()
|
||||
scheduleFrameIfNeeded()
|
||||
}
|
||||
|
||||
@@ -2577,14 +2671,64 @@ class MainActivity : Activity(), SurfaceHolder.Callback, Choreographer.FrameCall
|
||||
density = resources.displayMetrics.density,
|
||||
)
|
||||
}
|
||||
if (::textPreviewView.isInitialized) {
|
||||
textPreviewView.invalidate()
|
||||
}
|
||||
} finally {
|
||||
syncingOverlay = false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* H-S2: Push editor-initiated selection, block-focus, and caret-anchor changes to Android
|
||||
* `InputMethodManager` so Gboard/IME candidates stay aligned after Markdown transforms,
|
||||
* touch caret placement, or block splits/merges.
|
||||
*/
|
||||
private fun syncSystemImeFromEditor() {
|
||||
if (nativeHandle == 0L || !::surfaceView.isInitialized) return
|
||||
val nextSeq = NativeBridge.nativeGetTextInputChangeSeq(nativeHandle)
|
||||
val nextBlockHash = NativeBridge.nativeGetFocusedBlockHash(nativeHandle)
|
||||
if (nextSeq == lastImeChangeSeq && nextBlockHash == lastFocusedBlockHash) return
|
||||
val blockChanged = nextBlockHash != lastFocusedBlockHash
|
||||
lastImeChangeSeq = nextSeq
|
||||
lastFocusedBlockHash = nextBlockHash
|
||||
val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager ?: return
|
||||
if (!NativeBridge.nativeWantsSoftwareKeyboard(nativeHandle)) {
|
||||
imm.hideSoftInputFromWindow(surfaceView.windowToken, 0)
|
||||
}
|
||||
if (blockChanged) {
|
||||
imm.restartInput(surfaceView)
|
||||
} else {
|
||||
imm.updateSelection(
|
||||
surfaceView,
|
||||
imeController.selectionStart(),
|
||||
imeController.selectionEnd(),
|
||||
imeController.composingStart(),
|
||||
imeController.composingEnd(),
|
||||
)
|
||||
}
|
||||
pushCursorAnchorInfo(imm)
|
||||
}
|
||||
|
||||
private fun pushCursorAnchorInfo(existingImm: InputMethodManager? = null) {
|
||||
if (nativeHandle == 0L || !::surfaceView.isInitialized) return
|
||||
val imm = existingImm
|
||||
?: (getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager)
|
||||
?: return
|
||||
val density = resources.displayMetrics.density.coerceAtLeast(1f)
|
||||
val cx = NativeBridge.nativeGetCaretRectDpX(nativeHandle) * density
|
||||
val cy = NativeBridge.nativeGetCaretRectDpY(nativeHandle) * density
|
||||
val ch = NativeBridge.nativeGetCaretRectDpHeight(nativeHandle) * density
|
||||
val loc = IntArray(2)
|
||||
surfaceView.getLocationOnScreen(loc)
|
||||
val matrix = android.graphics.Matrix(surfaceView.matrix).apply {
|
||||
postTranslate(loc[0].toFloat(), loc[1].toFloat())
|
||||
}
|
||||
val anchor = CursorAnchorInfo.Builder()
|
||||
.setMatrix(matrix)
|
||||
.setSelectionRange(imeController.selectionStart(), imeController.selectionEnd())
|
||||
.setInsertionMarkerLocation(cx, cy, cy + ch * 0.8f, cy + ch, CursorAnchorInfo.FLAG_HAS_VISIBLE_REGION)
|
||||
.build()
|
||||
imm.updateCursorAnchorInfo(surfaceView, anchor)
|
||||
}
|
||||
|
||||
override fun surfaceDestroyed(holder: SurfaceHolder) {
|
||||
surfaceReady = false
|
||||
if (frameCallbackPosted) {
|
||||
@@ -2604,7 +2748,9 @@ class MainActivity : Activity(), SurfaceHolder.Callback, Choreographer.FrameCall
|
||||
|
||||
private fun scheduleFrameIfNeeded() {
|
||||
if (!frameLoopActive || !surfaceReady || frameCallbackPosted || nativeHandle == 0L) return
|
||||
if (NativeBridge.nativeHasPendingFrame(nativeHandle)) {
|
||||
if (NativeBridge.nativeHasPendingFrame(nativeHandle) ||
|
||||
NativeBridge.nativeHasPendingTimer(nativeHandle)
|
||||
) {
|
||||
frameCallbackPosted = true
|
||||
Choreographer.getInstance().postFrameCallback(this)
|
||||
}
|
||||
@@ -2619,8 +2765,9 @@ class MainActivity : Activity(), SurfaceHolder.Callback, Choreographer.FrameCall
|
||||
}
|
||||
|
||||
private fun installInsetsBridge(root: View) {
|
||||
root.setOnApplyWindowInsetsListener { _, insets ->
|
||||
forwardInsets(insets)
|
||||
root.setBackgroundColor(0xFFFFFFFF.toInt())
|
||||
root.setOnApplyWindowInsetsListener { v, insets ->
|
||||
forwardInsets(v, insets)
|
||||
insets
|
||||
}
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
|
||||
@@ -2630,7 +2777,7 @@ class MainActivity : Activity(), SurfaceHolder.Callback, Choreographer.FrameCall
|
||||
insets: WindowInsets,
|
||||
runningAnimations: MutableList<WindowInsetsAnimation>,
|
||||
): WindowInsets {
|
||||
forwardInsets(insets)
|
||||
forwardInsets(root, insets)
|
||||
return insets
|
||||
}
|
||||
},
|
||||
@@ -2639,7 +2786,7 @@ class MainActivity : Activity(), SurfaceHolder.Callback, Choreographer.FrameCall
|
||||
}
|
||||
|
||||
@Suppress("DEPRECATION")
|
||||
private fun forwardInsets(insets: WindowInsets) {
|
||||
private fun forwardInsets(root: View, insets: WindowInsets) {
|
||||
if (nativeHandle == 0L) return
|
||||
val density = resources.displayMetrics.density
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
|
||||
@@ -2647,22 +2794,39 @@ class MainActivity : Activity(), SurfaceHolder.Callback, Choreographer.FrameCall
|
||||
WindowInsets.Type.systemBars() or WindowInsets.Type.displayCutout(),
|
||||
)
|
||||
val ime = insets.getInsets(WindowInsets.Type.ime())
|
||||
// Inset the SurfaceView container to systemBars() so the editor top bar and
|
||||
// bottom toolbar stay clear of the status bar and navigation gesture bar.
|
||||
if (root.paddingLeft != bars.left || root.paddingTop != bars.top ||
|
||||
root.paddingRight != bars.right || root.paddingBottom != bars.bottom
|
||||
) {
|
||||
root.setPadding(bars.left, bars.top, bars.right, bars.bottom)
|
||||
}
|
||||
val imeAboveBars = maxOf(0, ime.bottom - bars.bottom)
|
||||
NativeBridge.nativeOnSurfaceInsetsPx(
|
||||
nativeHandle,
|
||||
bars.top,
|
||||
bars.right,
|
||||
bars.bottom,
|
||||
bars.left,
|
||||
ime.bottom,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
imeAboveBars,
|
||||
density,
|
||||
)
|
||||
} else {
|
||||
val left = insets.systemWindowInsetLeft
|
||||
val top = insets.systemWindowInsetTop
|
||||
val right = insets.systemWindowInsetRight
|
||||
val bottom = insets.systemWindowInsetBottom
|
||||
if (root.paddingLeft != left || root.paddingTop != top ||
|
||||
root.paddingRight != right || root.paddingBottom != bottom
|
||||
) {
|
||||
root.setPadding(left, top, right, bottom)
|
||||
}
|
||||
NativeBridge.nativeOnSurfaceInsetsPx(
|
||||
nativeHandle,
|
||||
insets.systemWindowInsetTop,
|
||||
insets.systemWindowInsetRight,
|
||||
insets.systemWindowInsetBottom,
|
||||
insets.systemWindowInsetLeft,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
density,
|
||||
)
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
# Build and sign `AffineAndroidHost-debug.apk` directly with Android SDK CLI tools
|
||||
# (`aapt2`, `kotlinc`, `d8`, `zipalign`, `apksigner`) and NDK Clang — zero Gradle daemon.
|
||||
#
|
||||
# Usage:
|
||||
# ./packages/frontend/hosts/android/scripts/package-debug-apk.sh [out_dir]
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
ANDROID_HOST_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
|
||||
REPO_ROOT="$(cd "$ANDROID_HOST_DIR/../../../.." && pwd)"
|
||||
MANIFEST="$REPO_ROOT/packages/frontend/Cargo.toml"
|
||||
OUT_DIR="${1:-$REPO_ROOT/packages/frontend/target/android-apk}"
|
||||
|
||||
ANDROID_SDK="${ANDROID_HOME:-${ANDROID_SDK_ROOT:-$HOME/android-sdk}}"
|
||||
if [ ! -d "$ANDROID_SDK" ]; then
|
||||
echo "ERROR: Android SDK not found at $ANDROID_SDK" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
BUILD_TOOLS_DIR="$(ls -1d "$ANDROID_SDK"/build-tools/* | sort -V | tail -n 1)"
|
||||
PLATFORM_DIR="$(ls -1d "$ANDROID_SDK"/platforms/android-* | sort -V | tail -n 1)"
|
||||
ANDROID_JAR="$PLATFORM_DIR/android.jar"
|
||||
NDK_DIR="${ANDROID_NDK_LATEST_HOME:-$(ls -1d "$ANDROID_SDK"/ndk/* | sort -V | tail -n 1)}"
|
||||
NDK_BIN="$NDK_DIR/toolchains/llvm/prebuilt/linux-x86_64/bin"
|
||||
|
||||
echo "==> Using SDK=$ANDROID_SDK build-tools=$(basename "$BUILD_TOOLS_DIR") platform=$(basename "$PLATFORM_DIR") ndk=$(basename "$NDK_DIR")"
|
||||
|
||||
export CARGO_ENCODED_RUSTFLAGS=""
|
||||
export CARGO_TARGET_AARCH64_LINUX_ANDROID_LINKER="$NDK_BIN/aarch64-linux-android24-clang"
|
||||
export CARGO_TARGET_X86_64_LINUX_ANDROID_LINKER="$NDK_BIN/x86_64-linux-android24-clang"
|
||||
export CC_aarch64_linux_android="$NDK_BIN/aarch64-linux-android24-clang"
|
||||
export AR_aarch64_linux_android="$NDK_BIN/llvm-ar"
|
||||
export CC_x86_64_linux_android="$NDK_BIN/x86_64-linux-android24-clang"
|
||||
export AR_x86_64_linux_android="$NDK_BIN/llvm-ar"
|
||||
|
||||
echo "==> Building Android NDK libaffine_android_host.so (arm64-v8a & x86_64)"
|
||||
rustup run 1.98.1 cargo build --locked --manifest-path "$MANIFEST" -p affine-android-host --target aarch64-linux-android
|
||||
rustup run 1.98.1 cargo build --locked --manifest-path "$MANIFEST" -p affine-android-host --target x86_64-linux-android
|
||||
|
||||
ARM64_SO="$REPO_ROOT/packages/frontend/target/aarch64-linux-android/debug/libaffine_android_host.so"
|
||||
X86_64_SO="$REPO_ROOT/packages/frontend/target/x86_64-linux-android/debug/libaffine_android_host.so"
|
||||
test -s "$ARM64_SO"
|
||||
test -s "$X86_64_SO"
|
||||
|
||||
WORK_DIR="$OUT_DIR/work"
|
||||
rm -rf "$WORK_DIR"
|
||||
mkdir -p "$WORK_DIR/classes" "$WORK_DIR/dex" "$WORK_DIR/apk_root/lib/arm64-v8a" "$WORK_DIR/apk_root/lib/x86_64"
|
||||
|
||||
echo "==> Compiling Kotlin host sources with kotlinc"
|
||||
kotlinc -classpath "$ANDROID_JAR" \
|
||||
-include-runtime \
|
||||
-d "$WORK_DIR/host-classes.jar" \
|
||||
"$ANDROID_HOST_DIR/kotlin/app/affine/pro/host/MainActivity.kt" \
|
||||
"$ANDROID_HOST_DIR/kotlin/app/affine/pro/host/LegacyLocalStorageProbe.kt" \
|
||||
"$ANDROID_HOST_DIR/kotlin/app/affine/pro/host/AndroidBootstrapCoordinator.kt" \
|
||||
"$ANDROID_HOST_DIR/kotlin/app/affine/pro/host/AuthDataStore.kt"
|
||||
|
||||
echo "==> Converting bytecode to DEX with d8"
|
||||
"$BUILD_TOOLS_DIR/d8" \
|
||||
--min-api 24 \
|
||||
--lib "$ANDROID_JAR" \
|
||||
--output "$WORK_DIR/dex" \
|
||||
"$WORK_DIR/host-classes.jar"
|
||||
test -s "$WORK_DIR/dex/classes.dex"
|
||||
|
||||
echo "==> Linking AndroidManifest.xml with aapt2"
|
||||
"$BUILD_TOOLS_DIR/aapt2" link \
|
||||
-I "$ANDROID_JAR" \
|
||||
--manifest "$ANDROID_HOST_DIR/AndroidManifest.xml" \
|
||||
--min-sdk-version 24 \
|
||||
--target-sdk-version 35 \
|
||||
-o "$WORK_DIR/unaligned.apk"
|
||||
|
||||
cp "$ARM64_SO" "$WORK_DIR/apk_root/lib/arm64-v8a/libaffine_android_host.so"
|
||||
cp "$X86_64_SO" "$WORK_DIR/apk_root/lib/x86_64/libaffine_android_host.so"
|
||||
cp "$WORK_DIR/dex/classes.dex" "$WORK_DIR/apk_root/classes.dex"
|
||||
for extra_dex in "$WORK_DIR"/dex/classes*.dex; do
|
||||
cp "$extra_dex" "$WORK_DIR/apk_root/"
|
||||
done
|
||||
|
||||
(
|
||||
cd "$WORK_DIR/apk_root"
|
||||
zip -u -r -0 "$WORK_DIR/unaligned.apk" lib
|
||||
zip -u -r "$WORK_DIR/unaligned.apk" classes*.dex
|
||||
)
|
||||
|
||||
ALIGNED_APK="$WORK_DIR/aligned.apk"
|
||||
"$BUILD_TOOLS_DIR/zipalign" -f -p 4 "$WORK_DIR/unaligned.apk" "$ALIGNED_APK"
|
||||
|
||||
KEYSTORE="$WORK_DIR/debug.keystore"
|
||||
keytool -genkeypair -noprompt \
|
||||
-keystore "$KEYSTORE" \
|
||||
-storepass android \
|
||||
-keypass android \
|
||||
-alias androiddebugkey \
|
||||
-keyalg RSA \
|
||||
-keysize 2048 \
|
||||
-validity 10000 \
|
||||
-dname "CN=Android Debug,O=AFFiNE,C=US"
|
||||
|
||||
FINAL_APK="$OUT_DIR/AffineAndroidHost-debug.apk"
|
||||
"$BUILD_TOOLS_DIR/apksigner" sign \
|
||||
--ks "$KEYSTORE" \
|
||||
--ks-pass pass:android \
|
||||
--key-pass pass:android \
|
||||
--ks-key-alias androiddebugkey \
|
||||
--out "$FINAL_APK" \
|
||||
"$ALIGNED_APK"
|
||||
|
||||
"$BUILD_TOOLS_DIR/apksigner" verify --verbose "$FINAL_APK"
|
||||
test -s "$FINAL_APK"
|
||||
echo "==> Packaged and signed Android debug APK: $FINAL_APK"
|
||||
@@ -4,9 +4,16 @@
|
||||
//! and CPU fallback with producer handoff safety.
|
||||
|
||||
use core::ffi::{c_char, c_int, c_void};
|
||||
use core::ptr::NonNull;
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::{Mutex, OnceLock};
|
||||
|
||||
use raw_window_handle::{
|
||||
AndroidDisplayHandle, AndroidNdkWindowHandle, DisplayHandle, HandleError, HasDisplayHandle,
|
||||
HasWindowHandle, RawDisplayHandle, RawWindowHandle, WindowHandle,
|
||||
};
|
||||
use ui::{DevicePixels, GpuContext, WgpuRenderer, WgpuSurfaceConfig, size};
|
||||
|
||||
use crate::jni_bridge::{JLong, JObject, JniEnvPtr};
|
||||
use crate::{AndroidRenderBackend, SurfacePresentError};
|
||||
|
||||
@@ -418,6 +425,63 @@ pub(crate) fn present_frame(
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn native_window_ptr(handle: JLong) -> Option<*mut c_void> {
|
||||
let map = windows().lock().unwrap_or_else(|p| p.into_inner());
|
||||
let entry = map.get(&handle)?;
|
||||
if entry.addr == 0 {
|
||||
None
|
||||
} else {
|
||||
Some(entry.addr as *mut c_void)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
struct AndroidRawWindow(NonNull<c_void>);
|
||||
|
||||
// SAFETY: `ANativeWindow` pointers are ref-counted NDK handles whose lifetime is
|
||||
// strictly bounded by `surfaceDestroyed`, where `WgpuRenderer` is dropped before
|
||||
// `ANativeWindow_release`.
|
||||
unsafe impl Send for AndroidRawWindow {}
|
||||
unsafe impl Sync for AndroidRawWindow {}
|
||||
|
||||
impl HasWindowHandle for AndroidRawWindow {
|
||||
fn window_handle(&self) -> Result<WindowHandle<'_>, HandleError> {
|
||||
let handle = AndroidNdkWindowHandle::new(self.0);
|
||||
// SAFETY: `self.0` is a live `ANativeWindow*` owned by `WINDOWS` for the
|
||||
// duration of the returned `WgpuRenderer`.
|
||||
Ok(unsafe { WindowHandle::borrow_raw(RawWindowHandle::AndroidNdk(handle)) })
|
||||
}
|
||||
}
|
||||
|
||||
impl HasDisplayHandle for AndroidRawWindow {
|
||||
fn display_handle(&self) -> Result<DisplayHandle<'_>, HandleError> {
|
||||
let handle = AndroidDisplayHandle::new();
|
||||
// SAFETY: Android's display handle is a zero-sized marker with no borrowed pointers.
|
||||
Ok(unsafe { DisplayHandle::borrow_raw(RawDisplayHandle::Android(handle)) })
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a live `ui::WgpuRenderer` bound to the `ANativeWindow*` for `handle`.
|
||||
pub(crate) fn create_wgpu_renderer(
|
||||
gpu_context: GpuContext,
|
||||
native_window: *mut c_void,
|
||||
width_px: u32,
|
||||
height_px: u32,
|
||||
) -> anyhow::Result<WgpuRenderer> {
|
||||
let ptr =
|
||||
NonNull::new(native_window).ok_or_else(|| anyhow::anyhow!("null ANativeWindow pointer"))?;
|
||||
let raw_win = AndroidRawWindow(ptr);
|
||||
let config = WgpuSurfaceConfig {
|
||||
size: size(
|
||||
DevicePixels(width_px.max(1) as i32),
|
||||
DevicePixels(height_px.max(1) as i32),
|
||||
),
|
||||
transparent: false,
|
||||
preferred_present_mode: None,
|
||||
};
|
||||
WgpuRenderer::new(gpu_context, &raw_win, config, None)
|
||||
}
|
||||
|
||||
pub(crate) fn release(handle: JLong) {
|
||||
let prev = {
|
||||
let mut map = windows().lock().unwrap_or_else(|p| p.into_inner());
|
||||
|
||||
@@ -0,0 +1,312 @@
|
||||
//! Fallback atlas and text system for `affine-android-host`.
|
||||
//!
|
||||
//! `FallbackAtlas` backs `SwappableAtlas` before an Android `SurfaceView` attaches
|
||||
//! (or after `surfaceDestroyed`), and `FallbackTextSystem` runs on non-Android
|
||||
//! JVM/Linux/macOS test hosts where `CosmicTextSystem` is not required.
|
||||
|
||||
use std::borrow::Cow;
|
||||
use std::collections::VecDeque;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::Result;
|
||||
use ui::{
|
||||
AtlasKey, AtlasTextureId, AtlasTextureKind, AtlasTile, Bounds, DevicePixels, PlatformAtlas,
|
||||
PlatformDispatcher, Priority, RunnableVariant, Size, TileId, point, size,
|
||||
};
|
||||
#[cfg(not(target_os = "android"))]
|
||||
use ui::{
|
||||
BaseDirection, Font, FontId, FontMetrics, FontRun, GlyphId, LineLayout, Pixels,
|
||||
PlatformTextSystem, RenderGlyphParams, ShapedGlyph, ShapedRun, TextRenderingMode, px,
|
||||
};
|
||||
|
||||
struct ScheduledTimer {
|
||||
due: ui::scheduler::Instant,
|
||||
runnable: RunnableVariant,
|
||||
}
|
||||
|
||||
/// Deterministic foreground/background dispatcher for the Android UI thread.
|
||||
///
|
||||
/// Main-thread tasks run inline on the next frame tick; delayed timers (`dispatch_after`)
|
||||
/// are stamped against [`ui::clock_now()`] and drained by `drain_ready()` on each
|
||||
/// `Choreographer` frame tick so caret blink, selection menus, and deferred editor tasks
|
||||
/// execute deterministically without spawning background threads or reading wall clocks.
|
||||
pub(crate) struct AndroidDispatcher {
|
||||
main_queue: Mutex<VecDeque<RunnableVariant>>,
|
||||
timers: Mutex<Vec<ScheduledTimer>>,
|
||||
#[cfg(test)]
|
||||
test_clock_offset: Mutex<Duration>,
|
||||
}
|
||||
|
||||
impl AndroidDispatcher {
|
||||
pub(crate) fn new() -> Self {
|
||||
Self {
|
||||
main_queue: Mutex::new(VecDeque::new()),
|
||||
timers: Mutex::new(Vec::new()),
|
||||
#[cfg(test)]
|
||||
test_clock_offset: Mutex::new(Duration::ZERO),
|
||||
}
|
||||
}
|
||||
|
||||
fn current_instant(&self) -> ui::scheduler::Instant {
|
||||
#[cfg(test)]
|
||||
{
|
||||
let offset = *self
|
||||
.test_clock_offset
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner());
|
||||
ui::clock_now() + offset
|
||||
}
|
||||
#[cfg(not(test))]
|
||||
{
|
||||
ui::clock_now()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn advance_test_clock(&self, delta: Duration) {
|
||||
let mut offset = self
|
||||
.test_clock_offset
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner());
|
||||
*offset += delta;
|
||||
}
|
||||
|
||||
/// Runs all queued tasks and timers due at `current_instant()`, returning the
|
||||
/// remaining duration until the earliest still-pending timer, if any.
|
||||
pub(crate) fn drain_ready(&self) -> Option<Duration> {
|
||||
let now = self.current_instant();
|
||||
loop {
|
||||
let due_timers: Vec<RunnableVariant> = {
|
||||
let mut timers = self.timers.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let mut ready = Vec::new();
|
||||
let mut i = 0;
|
||||
while i < timers.len() {
|
||||
if timers[i].due <= now {
|
||||
ready.push(timers.swap_remove(i).runnable);
|
||||
} else {
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
ready
|
||||
};
|
||||
let queued: Vec<RunnableVariant> = {
|
||||
let mut q = self.main_queue.lock().unwrap_or_else(|e| e.into_inner());
|
||||
q.drain(..).collect()
|
||||
};
|
||||
if due_timers.is_empty() && queued.is_empty() {
|
||||
break;
|
||||
}
|
||||
for runnable in due_timers.into_iter().chain(queued) {
|
||||
runnable.run();
|
||||
}
|
||||
}
|
||||
let timers = self.timers.lock().unwrap_or_else(|e| e.into_inner());
|
||||
timers
|
||||
.iter()
|
||||
.map(|t| t.due.saturating_duration_since(now))
|
||||
.min()
|
||||
}
|
||||
}
|
||||
|
||||
impl PlatformDispatcher for AndroidDispatcher {
|
||||
fn is_main_thread(&self) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn now(&self) -> ui::scheduler::Instant {
|
||||
self.current_instant()
|
||||
}
|
||||
|
||||
fn dispatch(&self, runnable: RunnableVariant, _priority: Priority) {
|
||||
self.main_queue
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner())
|
||||
.push_back(runnable);
|
||||
}
|
||||
|
||||
fn dispatch_on_main_thread(&self, runnable: RunnableVariant, _priority: Priority) {
|
||||
self.main_queue
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner())
|
||||
.push_back(runnable);
|
||||
}
|
||||
|
||||
fn dispatch_after(&self, duration: Duration, runnable: RunnableVariant) {
|
||||
let due = self.current_instant() + duration;
|
||||
self.timers
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner())
|
||||
.push(ScheduledTimer { due, runnable });
|
||||
}
|
||||
|
||||
fn spawn_realtime(&self, f: Box<dyn FnOnce() + Send>) {
|
||||
f();
|
||||
}
|
||||
}
|
||||
|
||||
/// Delegates to `FallbackAtlas` before an `ANativeWindow` attaches, and hot-swaps to
|
||||
/// `WgpuRenderer::sprite_atlas()` once `surfaceChanged` initializes the GPU surface.
|
||||
pub(crate) struct SwappableAtlas {
|
||||
inner: Mutex<Arc<dyn PlatformAtlas>>,
|
||||
}
|
||||
|
||||
impl SwappableAtlas {
|
||||
pub(crate) fn new(initial: Arc<dyn PlatformAtlas>) -> Self {
|
||||
Self {
|
||||
inner: Mutex::new(initial),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "android")]
|
||||
pub(crate) fn swap(&self, next: Arc<dyn PlatformAtlas>) {
|
||||
*self.inner.lock().unwrap_or_else(|e| e.into_inner()) = next;
|
||||
}
|
||||
}
|
||||
|
||||
impl PlatformAtlas for SwappableAtlas {
|
||||
fn get_or_insert_with<'a>(
|
||||
&self,
|
||||
key: AtlasKey,
|
||||
build: &mut dyn FnMut() -> Result<Option<(Size<DevicePixels>, Cow<'a, [u8]>)>>,
|
||||
) -> Result<Option<AtlasTile>> {
|
||||
let atlas = self.inner.lock().unwrap_or_else(|e| e.into_inner()).clone();
|
||||
atlas.get_or_insert_with(key, build)
|
||||
}
|
||||
|
||||
fn remove(&self, key: &AtlasKey) {
|
||||
let atlas = self.inner.lock().unwrap_or_else(|e| e.into_inner()).clone();
|
||||
atlas.remove(key);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct FallbackAtlas;
|
||||
|
||||
impl PlatformAtlas for FallbackAtlas {
|
||||
fn get_or_insert_with<'a>(
|
||||
&self,
|
||||
_key: AtlasKey,
|
||||
_build: &mut dyn FnMut() -> Result<Option<(Size<DevicePixels>, Cow<'a, [u8]>)>>,
|
||||
) -> Result<Option<AtlasTile>> {
|
||||
Ok(Some(AtlasTile {
|
||||
texture_id: AtlasTextureId {
|
||||
index: 0,
|
||||
kind: AtlasTextureKind::Monochrome,
|
||||
},
|
||||
tile_id: TileId(0),
|
||||
padding: 0,
|
||||
bounds: Bounds::new(
|
||||
point(DevicePixels(0), DevicePixels(0)),
|
||||
size(DevicePixels(1), DevicePixels(1)),
|
||||
),
|
||||
}))
|
||||
}
|
||||
|
||||
fn remove(&self, _key: &AtlasKey) {}
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "android"))]
|
||||
pub(crate) struct FallbackTextSystem;
|
||||
|
||||
#[cfg(not(target_os = "android"))]
|
||||
impl PlatformTextSystem for FallbackTextSystem {
|
||||
fn add_fonts(&self, _fonts: Vec<Cow<'static, [u8]>>) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn all_font_names(&self) -> Vec<String> {
|
||||
vec!["Inter".to_string(), "IBM Plex Mono".to_string()]
|
||||
}
|
||||
|
||||
fn font_id(&self, _descriptor: &Font) -> Result<FontId> {
|
||||
Ok(FontId(0))
|
||||
}
|
||||
|
||||
fn font_metrics(&self, _font_id: FontId) -> FontMetrics {
|
||||
FontMetrics {
|
||||
units_per_em: 1000,
|
||||
ascent: 800.0,
|
||||
descent: -200.0,
|
||||
line_gap: 0.0,
|
||||
underline_position: -100.0,
|
||||
underline_thickness: 50.0,
|
||||
cap_height: 700.0,
|
||||
x_height: 500.0,
|
||||
bounding_box: Bounds::new(point(0.0, -200.0), size(600.0, 1000.0)),
|
||||
}
|
||||
}
|
||||
|
||||
fn typographic_bounds(&self, _font_id: FontId, _glyph_id: GlyphId) -> Result<Bounds<f32>> {
|
||||
Ok(Bounds::new(point(0.0, -200.0), size(600.0, 1000.0)))
|
||||
}
|
||||
|
||||
fn advance(&self, _font_id: FontId, _glyph_id: GlyphId) -> Result<Size<f32>> {
|
||||
Ok(size(600.0, 0.0))
|
||||
}
|
||||
|
||||
fn glyph_for_char(&self, _font_id: FontId, ch: char) -> Option<GlyphId> {
|
||||
Some(GlyphId(ch as u32))
|
||||
}
|
||||
|
||||
fn glyph_raster_bounds(&self, _params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>> {
|
||||
Ok(Bounds::new(
|
||||
point(DevicePixels(0), DevicePixels(0)),
|
||||
size(DevicePixels(8), DevicePixels(14)),
|
||||
))
|
||||
}
|
||||
|
||||
fn rasterize_glyph(
|
||||
&self,
|
||||
_params: &RenderGlyphParams,
|
||||
raster_bounds: Bounds<DevicePixels>,
|
||||
) -> Result<(Size<DevicePixels>, Vec<u8>)> {
|
||||
let w = raster_bounds.size.width.0.max(1) as usize;
|
||||
let h = raster_bounds.size.height.0.max(1) as usize;
|
||||
Ok((raster_bounds.size, vec![0u8; w * h]))
|
||||
}
|
||||
|
||||
fn layout_line(&self, text: &str, font_size: Pixels, runs: &[FontRun]) -> LineLayout {
|
||||
let cell = f32::from(font_size) * 0.56;
|
||||
let mut x = 0.0f32;
|
||||
let mut shaped_runs = Vec::new();
|
||||
let mut offset = 0usize;
|
||||
for run in runs {
|
||||
let end = (offset + run.len).min(text.len());
|
||||
let slice = &text[offset..end];
|
||||
let mut glyphs = Vec::new();
|
||||
for (rel_idx, ch) in slice.char_indices() {
|
||||
let adv = if ch == ' ' { cell * 0.65 } else { cell };
|
||||
glyphs.push(ShapedGlyph {
|
||||
id: GlyphId(ch as u32),
|
||||
position: point(px(x), px(0.0)),
|
||||
index: offset + rel_idx,
|
||||
is_emoji: false,
|
||||
});
|
||||
x += adv;
|
||||
}
|
||||
shaped_runs.push(ShapedRun {
|
||||
font_id: run.font_id,
|
||||
glyphs,
|
||||
bidi_level: 0,
|
||||
});
|
||||
offset = end;
|
||||
}
|
||||
LineLayout {
|
||||
font_size,
|
||||
width: px(x),
|
||||
ascent: px(f32::from(font_size) * 0.8),
|
||||
descent: px(f32::from(font_size) * 0.2),
|
||||
runs: shaped_runs,
|
||||
len: text.len(),
|
||||
base_direction: BaseDirection::Ltr,
|
||||
}
|
||||
}
|
||||
|
||||
fn recommended_rendering_mode(
|
||||
&self,
|
||||
_font_id: FontId,
|
||||
_font_size: Pixels,
|
||||
) -> TextRenderingMode {
|
||||
TextRenderingMode::Grayscale
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,738 @@
|
||||
//! Embedded GPUI platform and window bridge for the Android thin host.
|
||||
//!
|
||||
//! Runs the shipping `PlaygroundView` directly on Android (`ANativeWindow` +
|
||||
//! `ui::WgpuRenderer` + `ui::CosmicTextSystem`) and on JVM/Linux/macOS parity
|
||||
//! hosts via `editor_fallback`.
|
||||
|
||||
use std::{
|
||||
cell::RefCell,
|
||||
ffi::OsString,
|
||||
path::{Path, PathBuf},
|
||||
rc::Rc,
|
||||
sync::Arc,
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
use anyhow::Result;
|
||||
use futures::channel::oneshot;
|
||||
use raw_window_handle::{
|
||||
DisplayHandle, HandleError, HasDisplayHandle, HasWindowHandle, WindowHandle,
|
||||
};
|
||||
#[cfg(target_os = "android")]
|
||||
use ui::DevicePixels;
|
||||
use ui::{
|
||||
Action, ActivityGuard, AnyWindowHandle, BackgroundExecutor, Bounds, Capslock, ClipboardItem,
|
||||
CursorStyle, DispatchEventResult, DisplayId, DummyKeyboardMapper, ForegroundExecutor, GpuSpecs,
|
||||
Keymap, Menu, MenuItem, Modifiers, OperatingSystem, PathPromptOptions, Pixels, Platform,
|
||||
PlatformAtlas, PlatformDispatcher, PlatformDisplay, PlatformInfo, PlatformInput,
|
||||
PlatformInputHandler, PlatformKeyboardLayout, PlatformKeyboardMapper, PlatformTarget,
|
||||
PlatformTextSystem, PlatformWindow, Point, PromptButton, PromptLevel, RequestFrameOptions,
|
||||
Scene, Size, Task, TextInputConfiguration, TextInputStateChange, ThermalState,
|
||||
WindowAppearance, WindowBackgroundAppearance, WindowBounds, WindowControlArea, WindowInsets,
|
||||
WindowParams, WindowVisibility, point, px, size,
|
||||
};
|
||||
use uuid::Uuid;
|
||||
|
||||
pub(crate) use crate::editor_fallback::AndroidDispatcher;
|
||||
#[cfg(not(target_os = "android"))]
|
||||
use crate::editor_fallback::FallbackTextSystem;
|
||||
use crate::editor_fallback::{FallbackAtlas, SwappableAtlas};
|
||||
|
||||
struct AndroidKeyboardLayout;
|
||||
|
||||
impl PlatformKeyboardLayout for AndroidKeyboardLayout {
|
||||
fn id(&self) -> &str {
|
||||
"android.editor"
|
||||
}
|
||||
|
||||
fn name(&self) -> &str {
|
||||
"Android"
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct AndroidDisplay {
|
||||
bounds: Bounds<Pixels>,
|
||||
}
|
||||
|
||||
impl PlatformDisplay for AndroidDisplay {
|
||||
fn id(&self) -> DisplayId {
|
||||
DisplayId::new(0)
|
||||
}
|
||||
|
||||
fn uuid(&self) -> Result<Uuid> {
|
||||
Ok(Uuid::nil())
|
||||
}
|
||||
|
||||
fn bounds(&self) -> Bounds<Pixels> {
|
||||
self.bounds
|
||||
}
|
||||
|
||||
fn refresh_interval(&self) -> Option<Duration> {
|
||||
Some(Duration::from_secs(1) / 60)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct AndroidWindowState {
|
||||
pub(crate) bounds: Bounds<Pixels>,
|
||||
pub(crate) scale_factor: f32,
|
||||
pub(crate) insets: WindowInsets,
|
||||
pub(crate) input_handler: Option<PlatformInputHandler>,
|
||||
pub(crate) request_frame: Option<Box<dyn FnMut(RequestFrameOptions)>>,
|
||||
pub(crate) input: Option<Box<dyn FnMut(PlatformInput) -> DispatchEventResult>>,
|
||||
pub(crate) resize: Option<Box<dyn FnMut(Size<Pixels>, f32)>>,
|
||||
pub(crate) visual_viewport_changed: Option<Box<dyn FnMut()>>,
|
||||
pub(crate) appearance_changed: Option<Box<dyn FnMut()>>,
|
||||
pub(crate) active_status_change: Option<Box<dyn FnMut(bool)>>,
|
||||
pub(crate) visibility_change: Option<Box<dyn FnMut(WindowVisibility)>>,
|
||||
pub(crate) close: Option<Box<dyn FnOnce()>>,
|
||||
pub(crate) mouse_position: Point<Pixels>,
|
||||
pub(crate) modifiers: Modifiers,
|
||||
pub(crate) ime_position: Option<Bounds<Pixels>>,
|
||||
pub(crate) dirty: bool,
|
||||
pub(crate) text_input_change_seq: u64,
|
||||
pub(crate) last_text_input_change: Option<TextInputStateChange>,
|
||||
pub(crate) last_scene_quads: usize,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct AndroidEditorWindow {
|
||||
atlas: Arc<SwappableAtlas>,
|
||||
#[cfg(target_os = "android")]
|
||||
gpu_context: ui::GpuContext,
|
||||
#[cfg(target_os = "android")]
|
||||
renderer: Rc<RefCell<Option<ui::WgpuRenderer>>>,
|
||||
display: Rc<dyn PlatformDisplay>,
|
||||
pub(crate) state: Rc<RefCell<AndroidWindowState>>,
|
||||
}
|
||||
|
||||
impl AndroidEditorWindow {
|
||||
fn new(
|
||||
bounds: Bounds<Pixels>,
|
||||
scale_factor: f32,
|
||||
#[cfg(target_os = "android")] gpu_context: ui::GpuContext,
|
||||
) -> Self {
|
||||
let safe_scale = if scale_factor.is_finite() && scale_factor > 0.0 {
|
||||
scale_factor
|
||||
} else {
|
||||
2.0
|
||||
};
|
||||
let display: Rc<dyn PlatformDisplay> = Rc::new(AndroidDisplay { bounds });
|
||||
#[allow(clippy::arc_with_non_send_sync)]
|
||||
let atlas = Arc::new(SwappableAtlas::new(Arc::new(FallbackAtlas)));
|
||||
Self {
|
||||
atlas,
|
||||
#[cfg(target_os = "android")]
|
||||
gpu_context,
|
||||
#[cfg(target_os = "android")]
|
||||
renderer: Rc::new(RefCell::new(None)),
|
||||
display,
|
||||
state: Rc::new(RefCell::new(AndroidWindowState {
|
||||
bounds,
|
||||
scale_factor: safe_scale,
|
||||
insets: WindowInsets::default(),
|
||||
input_handler: None,
|
||||
request_frame: None,
|
||||
input: None,
|
||||
resize: None,
|
||||
visual_viewport_changed: None,
|
||||
appearance_changed: None,
|
||||
active_status_change: None,
|
||||
visibility_change: None,
|
||||
close: None,
|
||||
mouse_position: Point::default(),
|
||||
modifiers: Modifiers::default(),
|
||||
ime_position: None,
|
||||
dirty: true,
|
||||
text_input_change_seq: 0,
|
||||
last_text_input_change: None,
|
||||
last_scene_quads: 0,
|
||||
})),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "android")]
|
||||
pub(crate) fn attach_native_window(
|
||||
&self,
|
||||
native_window: *mut core::ffi::c_void,
|
||||
width_px: u32,
|
||||
height_px: u32,
|
||||
) -> bool {
|
||||
if native_window.is_null() || width_px == 0 || height_px == 0 {
|
||||
return false;
|
||||
}
|
||||
let mut slot = self.renderer.borrow_mut();
|
||||
if let Some(renderer) = slot.as_mut() {
|
||||
renderer.update_drawable_size(size(
|
||||
DevicePixels(width_px as i32),
|
||||
DevicePixels(height_px as i32),
|
||||
));
|
||||
self.state.borrow_mut().dirty = true;
|
||||
return true;
|
||||
}
|
||||
match crate::android_window::create_wgpu_renderer(
|
||||
Rc::clone(&self.gpu_context),
|
||||
native_window,
|
||||
width_px,
|
||||
height_px,
|
||||
) {
|
||||
Ok(renderer) => {
|
||||
self.atlas.swap(renderer.sprite_atlas().clone());
|
||||
*slot = Some(renderer);
|
||||
self.state.borrow_mut().dirty = true;
|
||||
true
|
||||
}
|
||||
Err(_) => false,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "android")]
|
||||
pub(crate) fn detach_native_window(&self) {
|
||||
self.atlas.swap(Arc::new(FallbackAtlas));
|
||||
let _ = self.renderer.borrow_mut().take();
|
||||
}
|
||||
|
||||
#[cfg(target_os = "android")]
|
||||
pub(crate) fn has_gpu_renderer(&self) -> bool {
|
||||
self.renderer.borrow().is_some()
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "android"))]
|
||||
pub(crate) fn has_gpu_renderer(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
pub(crate) fn request_frame_now(&self) {
|
||||
let cb = self.state.borrow_mut().request_frame.take();
|
||||
if let Some(mut f) = cb {
|
||||
f(RequestFrameOptions {
|
||||
require_presentation: true,
|
||||
..RequestFrameOptions::default()
|
||||
});
|
||||
self.state.borrow_mut().request_frame = Some(f);
|
||||
}
|
||||
self.state.borrow_mut().dirty = false;
|
||||
}
|
||||
|
||||
pub(crate) fn dispatch_input(&self, event: PlatformInput) -> DispatchEventResult {
|
||||
let cb = {
|
||||
let mut st = self.state.borrow_mut();
|
||||
match &event {
|
||||
PlatformInput::MouseDown(e) => st.mouse_position = e.position,
|
||||
PlatformInput::MouseUp(e) => st.mouse_position = e.position,
|
||||
PlatformInput::MouseMove(e) => st.mouse_position = e.position,
|
||||
PlatformInput::Touch(e) => st.mouse_position = e.position,
|
||||
_ => {}
|
||||
}
|
||||
st.dirty = true;
|
||||
st.input.take()
|
||||
};
|
||||
let Some(mut f) = cb else {
|
||||
return DispatchEventResult::default();
|
||||
};
|
||||
let res = f(event);
|
||||
self.state.borrow_mut().input = Some(f);
|
||||
res
|
||||
}
|
||||
|
||||
pub(crate) fn set_viewport(&self, width_dp: f32, height_dp: f32, density: f32) {
|
||||
let w = width_dp.max(1.0);
|
||||
let h = height_dp.max(1.0);
|
||||
let scale = if density.is_finite() && density > 0.0 {
|
||||
density
|
||||
} else {
|
||||
self.state.borrow().scale_factor
|
||||
};
|
||||
let cb = {
|
||||
let mut st = self.state.borrow_mut();
|
||||
st.bounds.size = size(px(w), px(h));
|
||||
st.scale_factor = scale;
|
||||
st.dirty = true;
|
||||
st.resize.take()
|
||||
};
|
||||
if let Some(mut f) = cb {
|
||||
f(size(px(w), px(h)), scale);
|
||||
self.state.borrow_mut().resize = Some(f);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn set_insets(&self, insets: WindowInsets) {
|
||||
let cb = {
|
||||
let mut st = self.state.borrow_mut();
|
||||
if st.insets == insets {
|
||||
return;
|
||||
}
|
||||
st.insets = insets;
|
||||
st.dirty = true;
|
||||
st.visual_viewport_changed.take()
|
||||
};
|
||||
if let Some(mut f) = cb {
|
||||
f();
|
||||
self.state.borrow_mut().visual_viewport_changed = Some(f);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn with_input_handler<R>(
|
||||
&self,
|
||||
f: impl FnOnce(&mut PlatformInputHandler) -> R,
|
||||
) -> Option<R> {
|
||||
let mut handler = self.state.borrow_mut().input_handler.take()?;
|
||||
let out = f(&mut handler);
|
||||
self.state.borrow_mut().input_handler = Some(handler);
|
||||
Some(out)
|
||||
}
|
||||
}
|
||||
|
||||
impl HasWindowHandle for AndroidEditorWindow {
|
||||
fn window_handle(&self) -> std::result::Result<WindowHandle<'_>, HandleError> {
|
||||
Err(HandleError::Unavailable)
|
||||
}
|
||||
}
|
||||
|
||||
impl HasDisplayHandle for AndroidEditorWindow {
|
||||
fn display_handle(&self) -> std::result::Result<DisplayHandle<'_>, HandleError> {
|
||||
Err(HandleError::Unavailable)
|
||||
}
|
||||
}
|
||||
|
||||
impl PlatformWindow for AndroidEditorWindow {
|
||||
fn bounds(&self) -> Bounds<Pixels> {
|
||||
self.state.borrow().bounds
|
||||
}
|
||||
|
||||
fn is_maximized(&self) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn window_bounds(&self) -> WindowBounds {
|
||||
WindowBounds::Windowed(self.state.borrow().bounds)
|
||||
}
|
||||
|
||||
fn content_size(&self) -> Size<Pixels> {
|
||||
self.state.borrow().bounds.size
|
||||
}
|
||||
|
||||
fn resize(&mut self, size: Size<Pixels>) {
|
||||
let scale = self.state.borrow().scale_factor;
|
||||
self.set_viewport(f32::from(size.width), f32::from(size.height), scale);
|
||||
}
|
||||
|
||||
fn scale_factor(&self) -> f32 {
|
||||
self.state.borrow().scale_factor
|
||||
}
|
||||
|
||||
fn appearance(&self) -> WindowAppearance {
|
||||
WindowAppearance::Light
|
||||
}
|
||||
|
||||
fn display(&self) -> Option<Rc<dyn PlatformDisplay>> {
|
||||
Some(Rc::clone(&self.display))
|
||||
}
|
||||
|
||||
fn mouse_position(&self) -> Point<Pixels> {
|
||||
self.state.borrow().mouse_position
|
||||
}
|
||||
|
||||
fn modifiers(&self) -> Modifiers {
|
||||
self.state.borrow().modifiers
|
||||
}
|
||||
|
||||
fn capslock(&self) -> Capslock {
|
||||
Capslock::default()
|
||||
}
|
||||
|
||||
fn set_input_handler(&mut self, input_handler: PlatformInputHandler) {
|
||||
self.state.borrow_mut().input_handler = Some(input_handler);
|
||||
}
|
||||
|
||||
fn take_input_handler(&mut self) -> Option<PlatformInputHandler> {
|
||||
self.state.borrow_mut().input_handler.take()
|
||||
}
|
||||
|
||||
fn set_text_input_configuration(&mut self, _configuration: TextInputConfiguration) {}
|
||||
|
||||
fn prompt(
|
||||
&self,
|
||||
_level: PromptLevel,
|
||||
_msg: &str,
|
||||
_detail: Option<&str>,
|
||||
_answers: &[PromptButton],
|
||||
) -> Option<oneshot::Receiver<usize>> {
|
||||
None
|
||||
}
|
||||
|
||||
fn activate(&self) {}
|
||||
fn is_active(&self) -> bool {
|
||||
true
|
||||
}
|
||||
fn visibility(&self) -> WindowVisibility {
|
||||
WindowVisibility::Visible
|
||||
}
|
||||
fn is_hovered(&self) -> bool {
|
||||
false
|
||||
}
|
||||
fn background_appearance(&self) -> WindowBackgroundAppearance {
|
||||
WindowBackgroundAppearance::Opaque
|
||||
}
|
||||
fn set_title(&mut self, _title: &str) {}
|
||||
fn set_background_appearance(&self, _background_appearance: WindowBackgroundAppearance) {}
|
||||
fn minimize(&self) {}
|
||||
fn zoom(&self) {}
|
||||
fn toggle_fullscreen(&self) {}
|
||||
fn is_fullscreen(&self) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn on_request_frame(&self, callback: Box<dyn FnMut(RequestFrameOptions)>) {
|
||||
self.state.borrow_mut().request_frame = Some(callback);
|
||||
}
|
||||
|
||||
fn on_input(&self, callback: Box<dyn FnMut(PlatformInput) -> DispatchEventResult>) {
|
||||
self.state.borrow_mut().input = Some(callback);
|
||||
}
|
||||
|
||||
fn on_active_status_change(&self, callback: Box<dyn FnMut(bool)>) {
|
||||
self.state.borrow_mut().active_status_change = Some(callback);
|
||||
}
|
||||
|
||||
fn on_visibility_change(&self, callback: Box<dyn FnMut(WindowVisibility)>) {
|
||||
self.state.borrow_mut().visibility_change = Some(callback);
|
||||
}
|
||||
|
||||
fn on_hover_status_change(&self, _callback: Box<dyn FnMut(bool)>) {}
|
||||
|
||||
fn on_resize(&self, callback: Box<dyn FnMut(Size<Pixels>, f32)>) {
|
||||
self.state.borrow_mut().resize = Some(callback);
|
||||
}
|
||||
|
||||
fn on_moved(&self, _callback: Box<dyn FnMut()>) {}
|
||||
fn on_display_changed(&self, _callback: Box<dyn FnMut()>) {}
|
||||
fn on_should_close(&self, _callback: Box<dyn FnMut() -> bool>) {}
|
||||
|
||||
fn on_close(&self, callback: Box<dyn FnOnce()>) {
|
||||
self.state.borrow_mut().close = Some(callback);
|
||||
}
|
||||
|
||||
fn on_hit_test_window_control(&self, _callback: Box<dyn FnMut() -> Option<WindowControlArea>>) {
|
||||
}
|
||||
|
||||
fn on_appearance_changed(&self, callback: Box<dyn FnMut()>) {
|
||||
self.state.borrow_mut().appearance_changed = Some(callback);
|
||||
}
|
||||
|
||||
fn on_visual_viewport_changed(&self, callback: Box<dyn FnMut()>) {
|
||||
self.state.borrow_mut().visual_viewport_changed = Some(callback);
|
||||
}
|
||||
|
||||
fn insets(&self) -> WindowInsets {
|
||||
self.state.borrow().insets.clone()
|
||||
}
|
||||
|
||||
fn draw(&self, scene: &Scene) {
|
||||
self.state.borrow_mut().last_scene_quads = scene.quads.len();
|
||||
#[cfg(target_os = "android")]
|
||||
if let Some(renderer) = self.renderer.borrow_mut().as_mut() {
|
||||
renderer.draw(scene);
|
||||
}
|
||||
}
|
||||
|
||||
fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas> {
|
||||
Arc::clone(&self.atlas) as Arc<dyn PlatformAtlas>
|
||||
}
|
||||
|
||||
fn is_subpixel_rendering_supported(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn gpu_specs(&self) -> Option<GpuSpecs> {
|
||||
#[cfg(target_os = "android")]
|
||||
if let Some(renderer) = self.renderer.borrow().as_ref() {
|
||||
return renderer.gpu_specs();
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn update_ime_position(&self, bounds: Bounds<Pixels>) {
|
||||
self.state.borrow_mut().ime_position = Some(bounds);
|
||||
}
|
||||
|
||||
fn text_input_state_changed(&self, change: TextInputStateChange) {
|
||||
let mut st = self.state.borrow_mut();
|
||||
st.text_input_change_seq = st.text_input_change_seq.saturating_add(1);
|
||||
st.last_text_input_change = Some(change);
|
||||
st.dirty = true;
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct AndroidEditorPlatform {
|
||||
dispatcher: Arc<AndroidDispatcher>,
|
||||
background_executor: BackgroundExecutor,
|
||||
foreground_executor: ForegroundExecutor,
|
||||
text_system: Arc<dyn PlatformTextSystem>,
|
||||
#[cfg(target_os = "android")]
|
||||
gpu_context: ui::GpuContext,
|
||||
initial_bounds: Bounds<Pixels>,
|
||||
initial_scale: f32,
|
||||
opened_window: RefCell<Option<AndroidEditorWindow>>,
|
||||
clipboard: RefCell<Option<ClipboardItem>>,
|
||||
}
|
||||
|
||||
impl AndroidEditorPlatform {
|
||||
pub(crate) fn new(width_dp: f32, height_dp: f32, density: f32) -> Self {
|
||||
let bounds = Bounds::new(
|
||||
point(px(0.0), px(0.0)),
|
||||
size(px(width_dp.max(1.0)), px(height_dp.max(1.0))),
|
||||
);
|
||||
let dispatcher = Arc::new(AndroidDispatcher::new());
|
||||
let dyn_dispatcher: Arc<dyn PlatformDispatcher> = dispatcher.clone();
|
||||
let background_executor = BackgroundExecutor::new(dyn_dispatcher.clone());
|
||||
let foreground_executor = ForegroundExecutor::new(dyn_dispatcher);
|
||||
#[cfg(target_os = "android")]
|
||||
let text_system: Arc<dyn PlatformTextSystem> =
|
||||
Arc::new(ui::CosmicTextSystem::new("Roboto"));
|
||||
#[cfg(not(target_os = "android"))]
|
||||
let text_system: Arc<dyn PlatformTextSystem> = Arc::new(FallbackTextSystem);
|
||||
Self {
|
||||
dispatcher,
|
||||
background_executor,
|
||||
foreground_executor,
|
||||
text_system,
|
||||
#[cfg(target_os = "android")]
|
||||
gpu_context: Rc::new(RefCell::new(None)),
|
||||
initial_bounds: bounds,
|
||||
initial_scale: if density.is_finite() && density > 0.0 {
|
||||
density
|
||||
} else {
|
||||
2.0
|
||||
},
|
||||
opened_window: RefCell::new(None),
|
||||
clipboard: RefCell::new(None),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn dispatcher(&self) -> Arc<AndroidDispatcher> {
|
||||
Arc::clone(&self.dispatcher)
|
||||
}
|
||||
|
||||
pub(crate) fn opened_window(&self) -> Option<AndroidEditorWindow> {
|
||||
self.opened_window.borrow().clone()
|
||||
}
|
||||
}
|
||||
|
||||
impl Platform for AndroidEditorPlatform {
|
||||
fn platform_info(&self) -> PlatformInfo {
|
||||
PlatformInfo {
|
||||
os: OperatingSystem::Android,
|
||||
target: PlatformTarget::Native,
|
||||
}
|
||||
}
|
||||
|
||||
fn background_executor(&self) -> BackgroundExecutor {
|
||||
self.background_executor.clone()
|
||||
}
|
||||
|
||||
fn foreground_executor(&self) -> ForegroundExecutor {
|
||||
self.foreground_executor.clone()
|
||||
}
|
||||
|
||||
fn text_system(&self) -> Arc<dyn PlatformTextSystem> {
|
||||
self.text_system.clone()
|
||||
}
|
||||
|
||||
fn run(&self, on_finish_launching: Box<dyn 'static + FnOnce()>) {
|
||||
on_finish_launching();
|
||||
}
|
||||
|
||||
fn quit(&self) {}
|
||||
fn restart(&self, _binary_path: Option<PathBuf>, _arguments: Vec<OsString>) {}
|
||||
fn activate(&self, _ignoring_other_apps: bool) {}
|
||||
fn hide(&self) {}
|
||||
fn hide_other_apps(&self) {}
|
||||
fn unhide_other_apps(&self) {}
|
||||
|
||||
fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
|
||||
vec![Rc::new(AndroidDisplay {
|
||||
bounds: self.initial_bounds,
|
||||
})]
|
||||
}
|
||||
|
||||
fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
|
||||
self.displays().into_iter().next()
|
||||
}
|
||||
|
||||
fn on_displays_changed(&self, _callback: Box<dyn FnMut()>) {}
|
||||
fn active_window(&self) -> Option<AnyWindowHandle> {
|
||||
None
|
||||
}
|
||||
|
||||
fn open_window(
|
||||
&self,
|
||||
_handle: AnyWindowHandle,
|
||||
options: WindowParams,
|
||||
) -> Result<Box<dyn PlatformWindow>> {
|
||||
let window = AndroidEditorWindow::new(
|
||||
options.bounds,
|
||||
self.initial_scale,
|
||||
#[cfg(target_os = "android")]
|
||||
Rc::clone(&self.gpu_context),
|
||||
);
|
||||
*self.opened_window.borrow_mut() = Some(window.clone());
|
||||
Ok(Box::new(window))
|
||||
}
|
||||
|
||||
fn window_appearance(&self) -> WindowAppearance {
|
||||
WindowAppearance::Light
|
||||
}
|
||||
|
||||
fn open_url(&self, _url: &str) {}
|
||||
fn on_open_urls(&self, _callback: Box<dyn FnMut(Vec<String>)>) {}
|
||||
fn register_url_scheme(&self, _url: &str) -> Task<Result<()>> {
|
||||
Task::ready(Ok(()))
|
||||
}
|
||||
|
||||
fn prompt_for_paths(
|
||||
&self,
|
||||
_options: PathPromptOptions,
|
||||
) -> oneshot::Receiver<Result<Option<Vec<PathBuf>>>> {
|
||||
let (tx, rx) = oneshot::channel();
|
||||
let _ = tx.send(Ok(None));
|
||||
rx
|
||||
}
|
||||
|
||||
fn prompt_for_new_path(
|
||||
&self,
|
||||
_directory: &Path,
|
||||
_suggested_name: Option<&str>,
|
||||
) -> oneshot::Receiver<Result<Option<PathBuf>>> {
|
||||
let (tx, rx) = oneshot::channel();
|
||||
let _ = tx.send(Ok(None));
|
||||
rx
|
||||
}
|
||||
|
||||
fn can_select_mixed_files_and_dirs(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn reveal_path(&self, _path: &Path) {}
|
||||
fn open_with_system(&self, _path: &Path) {}
|
||||
fn on_quit(&self, _callback: Box<dyn FnMut() -> bool>) {}
|
||||
fn on_reopen(&self, _callback: Box<dyn FnMut()>) {}
|
||||
fn on_system_sleep(&self, _callback: Box<dyn FnMut()>) {}
|
||||
fn on_system_wake(&self, _callback: Box<dyn FnMut()>) {}
|
||||
fn set_menus(&self, _menus: Vec<Menu>, _keymap: &Keymap) {}
|
||||
fn set_dock_menu(&self, _menu: Vec<MenuItem>, _keymap: &Keymap) {}
|
||||
fn on_app_menu_action(&self, _callback: Box<dyn FnMut(&dyn Action)>) {}
|
||||
fn on_will_open_app_menu(&self, _callback: Box<dyn FnMut()>) {}
|
||||
fn on_validate_app_menu_command(&self, _callback: Box<dyn FnMut(&dyn Action) -> bool>) {}
|
||||
|
||||
fn thermal_state(&self) -> ThermalState {
|
||||
ThermalState::Nominal
|
||||
}
|
||||
|
||||
fn on_thermal_state_change(&self, _callback: Box<dyn FnMut()>) {}
|
||||
|
||||
fn prevent_idle_sleep(&self, _reason: &str) -> Task<Result<ActivityGuard>> {
|
||||
Task::ready(Ok(ActivityGuard::noop()))
|
||||
}
|
||||
|
||||
fn app_path(&self) -> Result<PathBuf> {
|
||||
Ok(PathBuf::from("AffineAndroidHost"))
|
||||
}
|
||||
|
||||
fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
|
||||
Ok(PathBuf::from(name))
|
||||
}
|
||||
|
||||
fn set_cursor_style(&self, _style: CursorStyle) {}
|
||||
fn hide_cursor_until_mouse_moves(&self) {}
|
||||
fn is_cursor_visible(&self) -> bool {
|
||||
false
|
||||
}
|
||||
fn should_auto_hide_scrollbars(&self) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn read_from_clipboard(&self) -> Option<ClipboardItem> {
|
||||
self.clipboard.borrow().clone()
|
||||
}
|
||||
|
||||
fn write_to_clipboard(&self, item: ClipboardItem) {
|
||||
*self.clipboard.borrow_mut() = Some(item);
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
fn read_from_primary(&self) -> Option<ClipboardItem> {
|
||||
None
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
fn write_to_primary(&self, _item: ClipboardItem) {}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
fn read_from_find_pasteboard(&self) -> Option<ClipboardItem> {
|
||||
None
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
fn write_to_find_pasteboard(&self, _item: ClipboardItem) {}
|
||||
|
||||
fn write_credentials(&self, _url: &str, _username: &str, _password: &[u8]) -> Task<Result<()>> {
|
||||
Task::ready(Ok(()))
|
||||
}
|
||||
|
||||
fn read_credentials(&self, _url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
|
||||
Task::ready(Ok(None))
|
||||
}
|
||||
|
||||
fn delete_credentials(&self, _url: &str) -> Task<Result<()>> {
|
||||
Task::ready(Ok(()))
|
||||
}
|
||||
|
||||
fn keyboard_layout(&self) -> Box<dyn PlatformKeyboardLayout> {
|
||||
Box::new(AndroidKeyboardLayout)
|
||||
}
|
||||
|
||||
fn keyboard_mapper(&self) -> Rc<dyn PlatformKeyboardMapper> {
|
||||
Rc::new(DummyKeyboardMapper)
|
||||
}
|
||||
|
||||
fn on_keyboard_layout_change(&self, _callback: Box<dyn FnMut()>) {}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn android_dispatcher_drains_immediate_and_delayed_tasks_deterministically() {
|
||||
let dispatcher = Arc::new(AndroidDispatcher::new());
|
||||
let fg_executor = ForegroundExecutor::new(dispatcher.clone());
|
||||
let bg_executor = BackgroundExecutor::new(dispatcher.clone());
|
||||
let immediate_hits = Arc::new(AtomicUsize::new(0));
|
||||
let delayed_hits = Arc::new(AtomicUsize::new(0));
|
||||
|
||||
let imm_clone = Arc::clone(&immediate_hits);
|
||||
let imm_task = fg_executor.spawn(async move {
|
||||
imm_clone.fetch_add(1, Ordering::SeqCst);
|
||||
});
|
||||
let del_clone = Arc::clone(&delayed_hits);
|
||||
let del_bg = bg_executor.clone();
|
||||
let del_task = fg_executor.spawn(async move {
|
||||
del_bg.timer(Duration::from_millis(500)).await;
|
||||
del_clone.fetch_add(1, Ordering::SeqCst);
|
||||
});
|
||||
|
||||
let pending = dispatcher.drain_ready();
|
||||
assert_eq!(immediate_hits.load(Ordering::SeqCst), 1);
|
||||
assert_eq!(delayed_hits.load(Ordering::SeqCst), 0);
|
||||
assert!(pending.is_some(), "timer must report remaining delay");
|
||||
|
||||
dispatcher.advance_test_clock(Duration::from_millis(501));
|
||||
let remaining = dispatcher.drain_ready();
|
||||
assert_eq!(delayed_hits.load(Ordering::SeqCst), 1);
|
||||
assert!(remaining.is_none());
|
||||
drop((imm_task, del_task));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,800 @@
|
||||
//! Live pure-Rust BlockSuite editor runtime for the Android thin host.
|
||||
//!
|
||||
//! Backed by `PlaygroundView` + `PlatformInputHandler` on the UI thread via a
|
||||
//! `thread_local!` registry keyed by JNI host handle, enforcing:
|
||||
//! - `H-S1`: zero host text copy (all `InputConnection` reads come straight from `PlatformInputHandler`)
|
||||
//! - `H-S2`: editor mutations increment `text_input_change_seq` and track `focused_block_hash`
|
||||
//! - `H-A1`: `setComposingRegion(start, end)` preserves exact range via
|
||||
//! `replace_and_mark_text_in_range(Some(lo..hi), existing, ...)`
|
||||
//! - `T1` Stage 1: Phone/Tablet `FormFactor` defaults to `edgeless_readonly = true`,
|
||||
//! `database_readonly = true`.
|
||||
|
||||
use std::{cell::RefCell, collections::BTreeMap, rc::Rc, sync::Arc, time::Duration};
|
||||
|
||||
use playground::{FormFactor, PlaygroundMode, PlaygroundOptions, PlaygroundView};
|
||||
use ui::{
|
||||
AppContext, Application, ApplicationHandle, Bounds, Edges, KeyDownEvent, Keystroke, Modifiers,
|
||||
PlatformInput, TouchEvent, TouchId, TouchPhase, WindowBounds, WindowInsets, WindowOptions,
|
||||
point, px, size,
|
||||
};
|
||||
|
||||
use crate::{
|
||||
LogicalWindowInsets,
|
||||
editor_platform::{AndroidDispatcher, AndroidEditorPlatform, AndroidEditorWindow},
|
||||
};
|
||||
|
||||
/// Android `KeyEvent` keycodes handled by `AffineInputConnection.sendKeyEvent`.
|
||||
pub const KEYCODE_DPAD_UP: i32 = 19;
|
||||
pub const KEYCODE_DPAD_DOWN: i32 = 20;
|
||||
pub const KEYCODE_DPAD_LEFT: i32 = 21;
|
||||
pub const KEYCODE_DPAD_RIGHT: i32 = 22;
|
||||
pub const KEYCODE_TAB: i32 = 61;
|
||||
pub const KEYCODE_ENTER: i32 = 66;
|
||||
pub const KEYCODE_DEL: i32 = 67;
|
||||
pub const KEYCODE_ESCAPE: i32 = 111;
|
||||
pub const KEYCODE_FORWARD_DEL: i32 = 112;
|
||||
pub const KEYCODE_NUMPAD_ENTER: i32 = 160;
|
||||
|
||||
pub(crate) struct AndroidEditorRuntime {
|
||||
app: ApplicationHandle,
|
||||
dispatcher: Arc<AndroidDispatcher>,
|
||||
window: AndroidEditorWindow,
|
||||
view: ui::WindowHandle<PlaygroundView>,
|
||||
form_factor: FormFactor,
|
||||
/// Preserved selection when `setComposingRegion` marks a span outside the current caret
|
||||
/// (matches AOSP `BaseInputConnection.setComposingRegion`, which must not alter selection).
|
||||
preserved_selection_during_composing_region: Option<(usize, usize)>,
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
static ANDROID_EDITORS: RefCell<BTreeMap<i64, AndroidEditorRuntime>> =
|
||||
const { RefCell::new(BTreeMap::new()) };
|
||||
}
|
||||
|
||||
pub(crate) fn attach_editor(handle: i64, width_dp: f32, height_dp: f32, density: f32) {
|
||||
if let Some(rt) =
|
||||
AndroidEditorRuntime::new(width_dp, height_dp, density, FormFactor::Phone, false)
|
||||
{
|
||||
ANDROID_EDITORS.with(|map| {
|
||||
map.borrow_mut().insert(handle, rt);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn detach_editor(handle: i64) {
|
||||
ANDROID_EDITORS.with(|map| {
|
||||
map.borrow_mut().remove(&handle);
|
||||
});
|
||||
}
|
||||
|
||||
pub(crate) fn with_editor_mut<R>(
|
||||
handle: i64,
|
||||
f: impl FnOnce(&mut AndroidEditorRuntime) -> R,
|
||||
) -> Option<R> {
|
||||
ANDROID_EDITORS.with(|map| map.borrow_mut().get_mut(&handle).map(f))
|
||||
}
|
||||
|
||||
impl AndroidEditorRuntime {
|
||||
pub(crate) fn new(
|
||||
width_dp: f32,
|
||||
height_dp: f32,
|
||||
density: f32,
|
||||
form_factor: FormFactor,
|
||||
load_showcase: bool,
|
||||
) -> Option<Self> {
|
||||
let w = if width_dp.is_finite() && width_dp > 1.0 {
|
||||
width_dp
|
||||
} else {
|
||||
412.0
|
||||
};
|
||||
let h = if height_dp.is_finite() && height_dp > 1.0 {
|
||||
height_dp
|
||||
} else {
|
||||
915.0
|
||||
};
|
||||
let d = if density.is_finite() && density > 0.0 {
|
||||
density
|
||||
} else {
|
||||
2.625
|
||||
};
|
||||
|
||||
let platform = Rc::new(AndroidEditorPlatform::new(w, h, d));
|
||||
let platform_ref = Rc::clone(&platform);
|
||||
let view_slot: Rc<RefCell<Option<ui::WindowHandle<PlaygroundView>>>> =
|
||||
Rc::new(RefCell::new(None));
|
||||
let view_slot_init = Rc::clone(&view_slot);
|
||||
|
||||
let options = PlaygroundOptions::for_form_factor(form_factor);
|
||||
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| {
|
||||
let _ = affine_mobile::register_mobile_fonts(cx);
|
||||
let _ = playground::register_bundled_fonts(cx);
|
||||
if let Ok(handle) = cx.open_window(
|
||||
WindowOptions {
|
||||
window_bounds: Some(WindowBounds::Windowed(bounds)),
|
||||
..WindowOptions::default()
|
||||
},
|
||||
move |window, cx| {
|
||||
window.set_touch_gestures_enabled(true);
|
||||
let entity = cx.new(|cx| PlaygroundView::with_options(options, cx));
|
||||
entity.update(cx, |view, cx| {
|
||||
if load_showcase {
|
||||
view.focus_first_text_block(window, cx);
|
||||
} else {
|
||||
view.load_empty_page_document(window, cx);
|
||||
}
|
||||
});
|
||||
entity
|
||||
},
|
||||
) {
|
||||
*view_slot_init.borrow_mut() = Some(handle);
|
||||
}
|
||||
});
|
||||
|
||||
let dispatcher = platform_ref.dispatcher();
|
||||
let window = platform_ref.opened_window()?;
|
||||
let view = view_slot.borrow_mut().take()?;
|
||||
let rt = Self {
|
||||
app,
|
||||
dispatcher,
|
||||
window,
|
||||
view,
|
||||
form_factor,
|
||||
preserved_selection_during_composing_region: None,
|
||||
};
|
||||
let _ = rt.dispatcher.drain_ready();
|
||||
rt.window.request_frame_now();
|
||||
Some(rt)
|
||||
}
|
||||
|
||||
#[cfg(target_os = "android")]
|
||||
pub(crate) fn attach_surface(
|
||||
&mut self,
|
||||
native_window: *mut core::ffi::c_void,
|
||||
width_px: u32,
|
||||
height_px: u32,
|
||||
density: f32,
|
||||
) -> bool {
|
||||
let ok = self
|
||||
.window
|
||||
.attach_native_window(native_window, width_px, height_px);
|
||||
self.resize_px(width_px, height_px, density);
|
||||
ok
|
||||
}
|
||||
|
||||
#[cfg(target_os = "android")]
|
||||
pub(crate) fn detach_surface(&mut self) {
|
||||
self.window.detach_native_window();
|
||||
}
|
||||
|
||||
pub(crate) fn has_gpu_renderer(&self) -> bool {
|
||||
self.window.has_gpu_renderer()
|
||||
}
|
||||
|
||||
pub(crate) fn drain_tasks(&self) -> Option<Duration> {
|
||||
self.dispatcher.drain_ready()
|
||||
}
|
||||
|
||||
pub(crate) fn resize_px(&mut self, width_px: u32, height_px: u32, density: f32) {
|
||||
let d = if density.is_finite() && density > 0.0 {
|
||||
density
|
||||
} else {
|
||||
1.0
|
||||
};
|
||||
let w = (width_px as f32 / d).max(1.0);
|
||||
let h = (height_px as f32 / d).max(1.0);
|
||||
self.window.set_viewport(w, h, d);
|
||||
let _ = self.dispatcher.drain_ready();
|
||||
self.window.request_frame_now();
|
||||
}
|
||||
|
||||
pub(crate) fn set_insets(&mut self, insets: LogicalWindowInsets) {
|
||||
let ui_insets = WindowInsets {
|
||||
safe_area: Edges {
|
||||
top: px(insets.safe_top.max(0.0)),
|
||||
right: px(insets.safe_right.max(0.0)),
|
||||
bottom: px(insets.safe_bottom.max(0.0)),
|
||||
left: px(insets.safe_left.max(0.0)),
|
||||
},
|
||||
ime: Edges {
|
||||
top: px(0.0),
|
||||
right: px(0.0),
|
||||
bottom: px(insets.ime_bottom.max(0.0)),
|
||||
left: px(0.0),
|
||||
},
|
||||
..WindowInsets::default()
|
||||
};
|
||||
self.window.set_insets(ui_insets);
|
||||
}
|
||||
|
||||
pub(crate) fn render_frame(&mut self) {
|
||||
let _ = self.dispatcher.drain_ready();
|
||||
self.window.request_frame_now();
|
||||
}
|
||||
|
||||
pub(crate) fn set_form_factor_from_smallest_width_dp(&mut self, smallest_width_dp: i32) {
|
||||
let ff = FormFactor::from_android_smallest_width_dp(smallest_width_dp);
|
||||
self.set_form_factor(ff);
|
||||
}
|
||||
|
||||
pub(crate) fn set_form_factor(&mut self, form_factor: FormFactor) {
|
||||
self.form_factor = form_factor;
|
||||
let _ = self.app.update(|cx| {
|
||||
let _ = self.view.update(cx, |view, window, cx| {
|
||||
view.set_form_factor(form_factor, window, cx);
|
||||
});
|
||||
});
|
||||
self.window.request_frame_now();
|
||||
}
|
||||
|
||||
pub(crate) fn wants_software_keyboard(&self) -> bool {
|
||||
self.app
|
||||
.update(|cx| {
|
||||
self.view
|
||||
.read_with(cx, |view, _| view.wants_software_keyboard())
|
||||
})
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
pub(crate) fn edgeless_readonly(&self) -> bool {
|
||||
self.app
|
||||
.update(|cx| self.view.read_with(cx, |view, _| view.edgeless_readonly()))
|
||||
.unwrap_or(true)
|
||||
}
|
||||
|
||||
pub(crate) fn database_readonly(&self) -> bool {
|
||||
self.app
|
||||
.update(|cx| self.view.read_with(cx, |view, _| view.database_readonly()))
|
||||
.unwrap_or(true)
|
||||
}
|
||||
|
||||
pub(crate) fn set_mode(&mut self, mode: PlaygroundMode) {
|
||||
let _ = self.app.update(|cx| {
|
||||
let _ = self.view.update(cx, |view, window, cx| {
|
||||
view.set_mode(mode, window, cx);
|
||||
});
|
||||
});
|
||||
self.window.request_frame_now();
|
||||
}
|
||||
|
||||
pub(crate) fn load_showcase_document(&mut self) {
|
||||
self.preserved_selection_during_composing_region = None;
|
||||
let _ = self.app.update(|cx| {
|
||||
let _ = self.view.update(cx, |view, window, cx| {
|
||||
view.load_showcase_document(window, cx);
|
||||
});
|
||||
});
|
||||
self.window.request_frame_now();
|
||||
}
|
||||
|
||||
pub(crate) fn reset_empty_document(&mut self) {
|
||||
self.preserved_selection_during_composing_region = None;
|
||||
let _ = self.app.update(|cx| {
|
||||
let _ = self.view.update(cx, |view, window, cx| {
|
||||
view.load_empty_page_document(window, cx);
|
||||
});
|
||||
});
|
||||
self.window.request_frame_now();
|
||||
}
|
||||
|
||||
pub(crate) fn dispatch_touch(&mut self, pointer_id: u64, phase: u8, x_dp: f32, y_dp: f32) {
|
||||
self.preserved_selection_during_composing_region = None;
|
||||
let touch_phase = match phase {
|
||||
0 => TouchPhase::Started,
|
||||
1 => TouchPhase::Moved,
|
||||
2 => TouchPhase::Ended,
|
||||
_ => TouchPhase::Cancelled,
|
||||
};
|
||||
let event = TouchEvent {
|
||||
id: TouchId(pointer_id),
|
||||
phase: touch_phase,
|
||||
position: point(px(x_dp), px(y_dp)),
|
||||
predicted_position: None,
|
||||
force: None,
|
||||
};
|
||||
let _ = self.window.dispatch_input(PlatformInput::Touch(event));
|
||||
self.window.request_frame_now();
|
||||
}
|
||||
|
||||
pub(crate) fn dispatch_key_code(
|
||||
&mut self,
|
||||
key_code: i32,
|
||||
shift: bool,
|
||||
ctrl: bool,
|
||||
alt: bool,
|
||||
) -> bool {
|
||||
let key_name = match key_code {
|
||||
KEYCODE_DEL => "backspace",
|
||||
KEYCODE_FORWARD_DEL => "delete",
|
||||
KEYCODE_ENTER | KEYCODE_NUMPAD_ENTER => "enter",
|
||||
KEYCODE_DPAD_LEFT => "left",
|
||||
KEYCODE_DPAD_RIGHT => "right",
|
||||
KEYCODE_DPAD_UP => "up",
|
||||
KEYCODE_DPAD_DOWN => "down",
|
||||
KEYCODE_ESCAPE => "escape",
|
||||
KEYCODE_TAB => "tab",
|
||||
_ => return false,
|
||||
};
|
||||
self.preserved_selection_during_composing_region = None;
|
||||
if self.composing_range().is_some()
|
||||
&& matches!(key_code, KEYCODE_ENTER | KEYCODE_NUMPAD_ENTER)
|
||||
{
|
||||
self.finish_composing_text();
|
||||
}
|
||||
let event = KeyDownEvent {
|
||||
keystroke: Keystroke {
|
||||
modifiers: Modifiers {
|
||||
control: ctrl,
|
||||
alt,
|
||||
shift,
|
||||
platform: false,
|
||||
function: false,
|
||||
},
|
||||
key: key_name.to_string(),
|
||||
key_char: None,
|
||||
},
|
||||
is_held: false,
|
||||
prefer_character_input: false,
|
||||
};
|
||||
let _ = self.window.dispatch_input(PlatformInput::KeyDown(event));
|
||||
self.window.request_frame_now();
|
||||
true
|
||||
}
|
||||
|
||||
pub(crate) fn text_input_change_seq(&self) -> u64 {
|
||||
self.window.state.borrow().text_input_change_seq
|
||||
}
|
||||
|
||||
pub(crate) fn focused_block_hash(&self) -> u64 {
|
||||
self.app
|
||||
.update(|cx| {
|
||||
self.view.read_with(cx, |view, _| {
|
||||
let mut h: u64 = 0xcbf2_9ce4_8422_2325;
|
||||
if let Some(sel) = view.document_selection() {
|
||||
for b in sel.focus.block_id.as_bytes() {
|
||||
h ^= u64::from(*b);
|
||||
h = h.wrapping_mul(0x0100_0000_01b3);
|
||||
}
|
||||
}
|
||||
h
|
||||
})
|
||||
})
|
||||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
fn ensure_input_handler(&mut self) {
|
||||
if self.window.state.borrow().input_handler.is_none() {
|
||||
self.window.request_frame_now();
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn utf16_len(&mut self) -> usize {
|
||||
self.ensure_input_handler();
|
||||
self.window
|
||||
.with_input_handler(|h| h.text_length_utf16())
|
||||
.flatten()
|
||||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
pub(crate) fn utf16_text(&mut self) -> Vec<u16> {
|
||||
self.ensure_input_handler();
|
||||
let len = self.utf16_len();
|
||||
if len == 0 {
|
||||
return Vec::new();
|
||||
}
|
||||
let mut adjusted = None;
|
||||
self.window
|
||||
.with_input_handler(|h| h.text_for_range(0..len, &mut adjusted))
|
||||
.flatten()
|
||||
.unwrap_or_default()
|
||||
.encode_utf16()
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub(crate) fn utf16_unit(&mut self, index: usize) -> Option<u16> {
|
||||
self.utf16_text().get(index).copied()
|
||||
}
|
||||
|
||||
pub(crate) fn selection_range(&mut self) -> (usize, usize) {
|
||||
if let Some(preserved) = self.preserved_selection_during_composing_region {
|
||||
let len = self.utf16_len();
|
||||
let s = preserved.0.min(len);
|
||||
let e = preserved.1.min(len).max(s);
|
||||
return (s, e);
|
||||
}
|
||||
self.ensure_input_handler();
|
||||
self.window
|
||||
.with_input_handler(|h| h.selected_text_range(true))
|
||||
.flatten()
|
||||
.map(|sel| (sel.range.start, sel.range.end))
|
||||
.unwrap_or((0, 0))
|
||||
}
|
||||
|
||||
pub(crate) fn composing_range(&mut self) -> Option<(usize, usize)> {
|
||||
self.ensure_input_handler();
|
||||
self.window
|
||||
.with_input_handler(|h| h.marked_text_range())
|
||||
.flatten()
|
||||
.map(|r| (r.start, r.end))
|
||||
}
|
||||
|
||||
fn cursor_after_edit(
|
||||
start: usize,
|
||||
inserted_len: usize,
|
||||
new_cursor_pos: i32,
|
||||
max_len: usize,
|
||||
) -> usize {
|
||||
if new_cursor_pos > 0 {
|
||||
start
|
||||
.saturating_add(inserted_len)
|
||||
.saturating_add((new_cursor_pos - 1) as usize)
|
||||
.min(max_len)
|
||||
} else {
|
||||
let back = new_cursor_pos.unsigned_abs() as usize;
|
||||
start.saturating_sub(back).min(max_len)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn commit_text_utf16(&mut self, utf16: &[u16], new_cursor_pos: i32) {
|
||||
self.ensure_input_handler();
|
||||
self.preserved_selection_during_composing_region = None;
|
||||
let text = String::from_utf16_lossy(utf16);
|
||||
let replace_start = self
|
||||
.composing_range()
|
||||
.map(|(s, _)| s)
|
||||
.unwrap_or_else(|| self.selection_range().0);
|
||||
if text == "\n" || text == "\r" {
|
||||
self.dispatch_key_code(KEYCODE_ENTER, false, false, false);
|
||||
return;
|
||||
}
|
||||
let _ = self
|
||||
.window
|
||||
.with_input_handler(|h| h.replace_text_in_range(None, &text));
|
||||
if new_cursor_pos != 1 {
|
||||
let max_len = self.utf16_len();
|
||||
let pos = Self::cursor_after_edit(replace_start, utf16.len(), new_cursor_pos, max_len);
|
||||
let _ = self
|
||||
.window
|
||||
.with_input_handler(|h| h.set_selected_text_range(pos..pos));
|
||||
}
|
||||
self.window.request_frame_now();
|
||||
}
|
||||
|
||||
pub(crate) fn set_composing_text_utf16(&mut self, utf16: &[u16], new_cursor_pos: i32) {
|
||||
self.ensure_input_handler();
|
||||
self.preserved_selection_during_composing_region = None;
|
||||
let text = String::from_utf16_lossy(utf16);
|
||||
let inserted_len = utf16.len();
|
||||
let rel_cursor = if new_cursor_pos > 0 {
|
||||
inserted_len
|
||||
.saturating_add((new_cursor_pos - 1) as usize)
|
||||
.min(inserted_len)
|
||||
} else {
|
||||
0
|
||||
};
|
||||
let _ = self.window.with_input_handler(|h| {
|
||||
h.replace_and_mark_text_in_range(None, &text, Some(rel_cursor..rel_cursor))
|
||||
});
|
||||
self.window.request_frame_now();
|
||||
}
|
||||
|
||||
/// H-A1: Marks `[start, end)` with the exact authoritative UTF-16 slice so subsequent
|
||||
/// `setComposingText` replaces `[start, end)` instead of duplicating text.
|
||||
pub(crate) fn set_composing_region(&mut self, start: usize, end: usize) {
|
||||
self.ensure_input_handler();
|
||||
let prev_sel = self.selection_range();
|
||||
let len = self.utf16_len();
|
||||
let a = start.min(len);
|
||||
let b = end.min(len);
|
||||
let (lo, hi) = if a <= b { (a, b) } else { (b, a) };
|
||||
if lo == hi {
|
||||
self.preserved_selection_during_composing_region = None;
|
||||
let _ = self.window.with_input_handler(|h| h.unmark_text());
|
||||
let _ = self
|
||||
.window
|
||||
.with_input_handler(|h| h.set_selected_text_range(prev_sel.0..prev_sel.1));
|
||||
self.window.request_frame_now();
|
||||
return;
|
||||
}
|
||||
// Commit any previous composing span first so `lo..hi` addresses current document text.
|
||||
if self.composing_range().is_some() {
|
||||
let _ = self.window.with_input_handler(|h| h.unmark_text());
|
||||
}
|
||||
// Align interior UTF-16 surrogate-pair indices to full scalar boundaries so
|
||||
// `text_for_range` and `replace_and_mark_text_in_range` never split an emoji.
|
||||
let units = self.utf16_text();
|
||||
let is_low_surrogate = |u: u16| (0xDC00..=0xDFFF).contains(&u);
|
||||
let mut lo = lo.min(units.len());
|
||||
let mut hi = hi.min(units.len());
|
||||
if lo > 0 && lo < units.len() && is_low_surrogate(units[lo]) {
|
||||
lo -= 1;
|
||||
}
|
||||
if hi > 0 && hi < units.len() && is_low_surrogate(units[hi]) {
|
||||
hi += 1;
|
||||
}
|
||||
let mut adjusted = None;
|
||||
let existing = self
|
||||
.window
|
||||
.with_input_handler(|h| h.text_for_range(lo..hi, &mut adjusted))
|
||||
.flatten()
|
||||
.unwrap_or_default();
|
||||
let effective = adjusted.unwrap_or(lo..hi);
|
||||
let sel_in_region = if prev_sel.0 >= effective.start && prev_sel.1 <= effective.end {
|
||||
self.preserved_selection_during_composing_region = None;
|
||||
Some((prev_sel.0 - effective.start)..(prev_sel.1 - effective.start))
|
||||
} else {
|
||||
self.preserved_selection_during_composing_region = Some(prev_sel);
|
||||
Some(existing.encode_utf16().count()..existing.encode_utf16().count())
|
||||
};
|
||||
let _ = self.window.with_input_handler(|h| {
|
||||
h.replace_and_mark_text_in_range(Some(effective), &existing, sel_in_region)
|
||||
});
|
||||
let _ = self.dispatcher.drain_ready();
|
||||
self.window.request_frame_now();
|
||||
}
|
||||
|
||||
pub(crate) fn finish_composing_text(&mut self) {
|
||||
self.ensure_input_handler();
|
||||
let preserved = self.preserved_selection_during_composing_region.take();
|
||||
let _ = self.window.with_input_handler(|h| h.unmark_text());
|
||||
if let Some((s, e)) = preserved {
|
||||
let _ = self
|
||||
.window
|
||||
.with_input_handler(|h| h.set_selected_text_range(s..e));
|
||||
}
|
||||
self.window.request_frame_now();
|
||||
}
|
||||
|
||||
pub(crate) fn set_selection(&mut self, start: usize, end: usize) {
|
||||
self.ensure_input_handler();
|
||||
self.preserved_selection_during_composing_region = None;
|
||||
let len = self.utf16_len();
|
||||
let a = start.min(len);
|
||||
let b = end.min(len);
|
||||
let (lo, hi) = if a <= b { (a, b) } else { (b, a) };
|
||||
let _ = self
|
||||
.window
|
||||
.with_input_handler(|h| h.set_selected_text_range(lo..hi));
|
||||
self.window.request_frame_now();
|
||||
}
|
||||
|
||||
pub(crate) fn replace_text_utf16(
|
||||
&mut self,
|
||||
start: usize,
|
||||
end: usize,
|
||||
utf16: &[u16],
|
||||
new_cursor_pos: i32,
|
||||
) {
|
||||
self.ensure_input_handler();
|
||||
self.preserved_selection_during_composing_region = None;
|
||||
if self.composing_range().is_some() {
|
||||
let _ = self.window.with_input_handler(|h| h.unmark_text());
|
||||
}
|
||||
let len = self.utf16_len();
|
||||
let a = start.min(len);
|
||||
let b = end.min(len);
|
||||
let (lo, hi) = if a <= b { (a, b) } else { (b, a) };
|
||||
let text = String::from_utf16_lossy(utf16);
|
||||
let _ = self
|
||||
.window
|
||||
.with_input_handler(|h| h.replace_text_in_range(Some(lo..hi), &text));
|
||||
let max_len = self.utf16_len();
|
||||
let pos = Self::cursor_after_edit(lo, utf16.len(), new_cursor_pos, max_len);
|
||||
let _ = self
|
||||
.window
|
||||
.with_input_handler(|h| h.set_selected_text_range(pos..pos));
|
||||
self.window.request_frame_now();
|
||||
}
|
||||
|
||||
fn is_high_surrogate(u: u16) -> bool {
|
||||
(0xD800..=0xDBFF).contains(&u)
|
||||
}
|
||||
|
||||
fn is_low_surrogate(u: u16) -> bool {
|
||||
(0xDC00..=0xDFFF).contains(&u)
|
||||
}
|
||||
|
||||
pub(crate) fn delete_surrounding_text(&mut self, before_len: usize, after_len: usize) {
|
||||
self.ensure_input_handler();
|
||||
let units = self.utf16_text();
|
||||
let len = units.len();
|
||||
let (sel_start, sel_end) = self.selection_range();
|
||||
let composing = self.composing_range();
|
||||
|
||||
// AOSP BaseInputConnection: delete outside composing span when composing is active.
|
||||
let (anchor_before, anchor_after) = if let Some((cs, ce)) = composing {
|
||||
(sel_start.min(cs), sel_end.max(ce))
|
||||
} else {
|
||||
(sel_start, sel_end)
|
||||
};
|
||||
|
||||
let mut del_before_start = anchor_before.saturating_sub(before_len);
|
||||
if del_before_start > 0
|
||||
&& del_before_start < len
|
||||
&& Self::is_low_surrogate(units[del_before_start])
|
||||
&& Self::is_high_surrogate(units[del_before_start - 1])
|
||||
{
|
||||
del_before_start -= 1;
|
||||
}
|
||||
let mut del_after_end = anchor_after.saturating_add(after_len).min(len);
|
||||
if del_after_end > 0
|
||||
&& del_after_end < len
|
||||
&& Self::is_high_surrogate(units[del_after_end - 1])
|
||||
&& Self::is_low_surrogate(units[del_after_end])
|
||||
{
|
||||
del_after_end += 1;
|
||||
}
|
||||
|
||||
let removed_before = anchor_before - del_before_start;
|
||||
let removed_after = del_after_end - anchor_after;
|
||||
if removed_before == 0 && removed_after == 0 {
|
||||
return;
|
||||
}
|
||||
|
||||
if let Some((cs, ce)) = composing {
|
||||
let comp_text = String::from_utf16_lossy(&units[cs..ce]);
|
||||
let _ = self.window.with_input_handler(|h| h.unmark_text());
|
||||
if removed_after > 0 {
|
||||
let _ = self.window.with_input_handler(|h| {
|
||||
h.replace_text_in_range(Some(anchor_after..del_after_end), "")
|
||||
});
|
||||
}
|
||||
if removed_before > 0 {
|
||||
let _ = self.window.with_input_handler(|h| {
|
||||
h.replace_text_in_range(Some(del_before_start..anchor_before), "")
|
||||
});
|
||||
}
|
||||
let new_cs = cs.saturating_sub(removed_before);
|
||||
let new_ce = ce.saturating_sub(removed_before);
|
||||
let new_sel_s = sel_start.saturating_sub(removed_before);
|
||||
let new_sel_e = sel_end.saturating_sub(removed_before);
|
||||
let rel = if new_sel_s >= new_cs && new_sel_e <= new_ce {
|
||||
Some((new_sel_s - new_cs)..(new_sel_e - new_cs))
|
||||
} else {
|
||||
Some(comp_text.encode_utf16().count()..comp_text.encode_utf16().count())
|
||||
};
|
||||
let _ = self.window.with_input_handler(|h| {
|
||||
h.replace_and_mark_text_in_range(Some(new_cs..new_ce), &comp_text, rel)
|
||||
});
|
||||
} else {
|
||||
if removed_after > 0 {
|
||||
let _ = self.window.with_input_handler(|h| {
|
||||
h.replace_text_in_range(Some(anchor_after..del_after_end), "")
|
||||
});
|
||||
}
|
||||
if removed_before > 0 {
|
||||
let _ = self.window.with_input_handler(|h| {
|
||||
h.replace_text_in_range(Some(del_before_start..anchor_before), "")
|
||||
});
|
||||
}
|
||||
let new_start = sel_start.saturating_sub(removed_before);
|
||||
let new_end = sel_end.saturating_sub(removed_before);
|
||||
let _ = self
|
||||
.window
|
||||
.with_input_handler(|h| h.set_selected_text_range(new_start..new_end));
|
||||
}
|
||||
self.window.request_frame_now();
|
||||
}
|
||||
|
||||
pub(crate) fn delete_surrounding_text_in_code_points(
|
||||
&mut self,
|
||||
before_code_points: usize,
|
||||
after_code_points: usize,
|
||||
) -> bool {
|
||||
self.ensure_input_handler();
|
||||
let units = self.utf16_text();
|
||||
let (sel_start, sel_end) = self.selection_range();
|
||||
let (anchor_before, anchor_after) = if let Some((cs, ce)) = self.composing_range() {
|
||||
(sel_start.min(cs), sel_end.max(ce))
|
||||
} else {
|
||||
(sel_start, sel_end)
|
||||
};
|
||||
|
||||
let mut b_idx = anchor_before;
|
||||
for _ in 0..before_code_points {
|
||||
if b_idx == 0 {
|
||||
break;
|
||||
}
|
||||
b_idx -= 1;
|
||||
if Self::is_low_surrogate(units[b_idx]) {
|
||||
if b_idx == 0 || !Self::is_high_surrogate(units[b_idx - 1]) {
|
||||
return false;
|
||||
}
|
||||
b_idx -= 1;
|
||||
} else if Self::is_high_surrogate(units[b_idx]) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
let mut a_idx = anchor_after;
|
||||
for _ in 0..after_code_points {
|
||||
if a_idx >= units.len() {
|
||||
break;
|
||||
}
|
||||
if Self::is_high_surrogate(units[a_idx]) {
|
||||
if a_idx + 1 >= units.len() || !Self::is_low_surrogate(units[a_idx + 1]) {
|
||||
return false;
|
||||
}
|
||||
a_idx += 2;
|
||||
} else if Self::is_low_surrogate(units[a_idx]) {
|
||||
return false;
|
||||
} else {
|
||||
a_idx += 1;
|
||||
}
|
||||
}
|
||||
self.delete_surrounding_text(anchor_before - b_idx, a_idx - anchor_after);
|
||||
true
|
||||
}
|
||||
|
||||
pub(crate) fn caret_rect_dp(&mut self) -> Option<[f32; 4]> {
|
||||
self.ensure_input_handler();
|
||||
let (_, end) = self.selection_range();
|
||||
let b = self
|
||||
.window
|
||||
.with_input_handler(|h| h.bounds_for_range(end..end))
|
||||
.flatten()?;
|
||||
Some([
|
||||
f32::from(b.origin.x),
|
||||
f32::from(b.origin.y),
|
||||
f32::from(b.size.width).max(2.0),
|
||||
f32::from(b.size.height).max(20.0),
|
||||
])
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn android_editor_runtime_gboard_composing_region_and_stage_one_readonly() {
|
||||
let mut rt =
|
||||
AndroidEditorRuntime::new(412.0, 915.0, 2.625, FormFactor::Phone, false).expect("rt");
|
||||
assert!(rt.edgeless_readonly());
|
||||
assert!(rt.database_readonly());
|
||||
|
||||
// H-A1: Gboard backspace-into-word: " hello" -> setComposingRegion(1, 6) -> setComposingText("hellos")
|
||||
let hello: Vec<u16> = " hello".encode_utf16().collect();
|
||||
rt.commit_text_utf16(&hello, 1);
|
||||
assert_eq!(String::from_utf16_lossy(&rt.utf16_text()), " hello");
|
||||
|
||||
rt.set_composing_region(1, 6);
|
||||
assert_eq!(rt.composing_range(), Some((1, 6)));
|
||||
|
||||
let hellos: Vec<u16> = "hellos".encode_utf16().collect();
|
||||
rt.set_composing_text_utf16(&hellos, 1);
|
||||
assert_eq!(
|
||||
String::from_utf16_lossy(&rt.utf16_text()),
|
||||
" hellos",
|
||||
"Gboard composing region replacement must not duplicate 'hello'"
|
||||
);
|
||||
|
||||
// KeyEvent ENTER splits block, KEYCODE_DEL at block start merges back.
|
||||
assert!(rt.dispatch_key_code(KEYCODE_ENTER, false, false, false));
|
||||
assert_eq!(String::from_utf16_lossy(&rt.utf16_text()), "");
|
||||
assert!(rt.dispatch_key_code(KEYCODE_DEL, false, false, false));
|
||||
assert_eq!(String::from_utf16_lossy(&rt.utf16_text()), " hellos");
|
||||
|
||||
// H-A1 surrogate pair alignment: "a😀b" has '😀' at UTF-16 [1..3).
|
||||
// Passing an interior surrogate index (1..2) must align to the full scalar range [1..3).
|
||||
rt.reset_empty_document();
|
||||
let emoji: Vec<u16> = "a😀b".encode_utf16().collect();
|
||||
rt.commit_text_utf16(&emoji, 1);
|
||||
rt.set_composing_region(1, 2);
|
||||
let replacement: Vec<u16> = "🎉".encode_utf16().collect();
|
||||
rt.set_composing_text_utf16(&replacement, 1);
|
||||
assert_eq!(
|
||||
String::from_utf16_lossy(&rt.utf16_text()),
|
||||
"a🎉b",
|
||||
"surrogate-pair composing region must align cleanly without splitting or duplicating"
|
||||
);
|
||||
|
||||
// FormFactor Phone/Tablet read-only vs Desktop unlocked.
|
||||
rt.set_form_factor_from_smallest_width_dp(720);
|
||||
assert!(rt.edgeless_readonly());
|
||||
assert!(rt.database_readonly());
|
||||
rt.set_form_factor(FormFactor::Desktop);
|
||||
assert!(!rt.edgeless_readonly());
|
||||
assert!(!rt.database_readonly());
|
||||
}
|
||||
}
|
||||
@@ -9,17 +9,24 @@ impl AndroidHostState {
|
||||
///
|
||||
/// Preserves active drag state when passing through zero-length coincidence points.
|
||||
pub fn sync_selection_overlay_from_ime(&mut self) {
|
||||
let (start, end) = self.selection_range();
|
||||
let utf16 = self.utf16_text.clone();
|
||||
self.sync_selection_overlay_for_snapshot(&utf16, start, end);
|
||||
}
|
||||
|
||||
/// Synchronizes native selection handles from an authoritative editor UTF-16 snapshot
|
||||
/// without storing a duplicate host text copy (`H-S1`).
|
||||
pub fn sync_selection_overlay_for_snapshot(&mut self, utf16: &[u16], start: usize, end: usize) {
|
||||
if self.selection.active_drag != SelectionHandleKind::None {
|
||||
return;
|
||||
}
|
||||
let (start, end) = self.selection_range();
|
||||
if start == end {
|
||||
self.selection.clear();
|
||||
return;
|
||||
}
|
||||
let (sx, sy) = caret_position_for_offset(&self.utf16_text, start, &self.text_layout);
|
||||
let (ex, ey) = caret_position_for_offset(&self.utf16_text, end, &self.text_layout);
|
||||
let dir = detect_direction_at_offset(&self.utf16_text, start, &self.text_layout);
|
||||
let (sx, sy) = caret_position_for_offset(utf16, start, &self.text_layout);
|
||||
let (ex, ey) = caret_position_for_offset(utf16, end, &self.text_layout);
|
||||
let dir = detect_direction_at_offset(utf16, start, &self.text_layout);
|
||||
self.selection
|
||||
.update_selection(sx, sy, ex, ey, self.text_layout.line_height, dir, true);
|
||||
}
|
||||
|
||||
@@ -165,6 +165,8 @@ pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeCreateHost(
|
||||
let candidate = NEXT_HOST_HANDLE.fetch_add(1, Ordering::Relaxed);
|
||||
if candidate != 0 && !map.contains_key(&candidate) {
|
||||
map.insert(candidate, AndroidHostState::new());
|
||||
drop(map);
|
||||
crate::jni_editor::attach_for_host(candidate);
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
@@ -179,6 +181,7 @@ pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeDestroyHost(
|
||||
if handle == 0 {
|
||||
return;
|
||||
}
|
||||
crate::jni_editor::detach_for_host(handle);
|
||||
#[cfg(target_os = "android")]
|
||||
android_window::release(handle);
|
||||
let mut map = registry()
|
||||
@@ -238,13 +241,25 @@ pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeOnSurfaceChanged(
|
||||
) {
|
||||
#[cfg(target_os = "android")]
|
||||
android_window::set_geometry(handle, width_px, height_px);
|
||||
let mut density = 1.0f32;
|
||||
let w = u32::try_from(width_px).unwrap_or(0);
|
||||
let h = u32::try_from(height_px).unwrap_or(0);
|
||||
let _ = with_host_mut(handle, |host| {
|
||||
host.surface.on_changed(
|
||||
format,
|
||||
u32::try_from(width_px).unwrap_or(0),
|
||||
u32::try_from(height_px).unwrap_or(0),
|
||||
);
|
||||
host.surface.on_changed(format, w, h);
|
||||
density = host.surface.density;
|
||||
});
|
||||
if w > 0 && h > 0 {
|
||||
#[cfg(target_os = "android")]
|
||||
let native_win = android_window::native_window_ptr(handle);
|
||||
let _ = crate::editor_runtime::with_editor_mut(handle, |ed| {
|
||||
#[cfg(target_os = "android")]
|
||||
if let Some(ptr) = native_win {
|
||||
let _ = ed.attach_surface(ptr, w, h, density);
|
||||
return;
|
||||
}
|
||||
ed.resize_px(w, h, density);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
@@ -253,8 +268,14 @@ pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeOnSurfaceDestroyed
|
||||
_class: JClass,
|
||||
handle: JLong,
|
||||
) {
|
||||
// Drop `WgpuRenderer` and its `wgpu::Surface` strictly BEFORE `ANativeWindow_release`.
|
||||
#[cfg(target_os = "android")]
|
||||
android_window::release(handle);
|
||||
{
|
||||
let _ = crate::editor_runtime::with_editor_mut(handle, |ed| {
|
||||
ed.detach_surface();
|
||||
});
|
||||
android_window::release(handle);
|
||||
}
|
||||
let _ = with_host_mut(handle, |host| {
|
||||
host.surface.on_destroyed();
|
||||
});
|
||||
@@ -328,6 +349,7 @@ pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeOnSurfaceInsetsPx(
|
||||
ime_bottom_px: JInt,
|
||||
density: JFloat,
|
||||
) {
|
||||
let mut logical_insets = crate::LogicalWindowInsets::default();
|
||||
let _ = with_host_mut(handle, |host| {
|
||||
host.surface.set_density(density);
|
||||
host.insets = physical_insets_to_logical_dp(
|
||||
@@ -338,6 +360,7 @@ pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeOnSurfaceInsetsPx(
|
||||
ime_bottom_px,
|
||||
density,
|
||||
);
|
||||
logical_insets = host.insets;
|
||||
if host.surface.width_px > 0 && host.surface.height_px > 0 {
|
||||
host.selection.set_viewport(
|
||||
host.surface.width_px as f32,
|
||||
@@ -346,6 +369,9 @@ pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeOnSurfaceInsetsPx(
|
||||
);
|
||||
}
|
||||
});
|
||||
let _ = crate::editor_runtime::with_editor_mut(handle, |ed| {
|
||||
ed.set_insets(logical_insets);
|
||||
});
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
@@ -363,17 +389,38 @@ pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeOnFrameTick(
|
||||
.flatten() else {
|
||||
return 0;
|
||||
};
|
||||
let (has_gpu_renderer, has_pending_timer) =
|
||||
crate::editor_runtime::with_editor_mut(handle, |ed| {
|
||||
let has_gpu = ed.has_gpu_renderer();
|
||||
ed.render_frame();
|
||||
let next_due = ed.drain_tasks();
|
||||
(has_gpu, next_due.is_some())
|
||||
})
|
||||
.unwrap_or((false, false));
|
||||
|
||||
#[cfg(target_os = "android")]
|
||||
let present_result = android_window::present_frame(handle, backend, argb);
|
||||
let present_result = if has_gpu_renderer {
|
||||
// `WgpuRenderer::draw(scene)` already presented to `ANativeWindow`; never
|
||||
// invoke legacy EGL/CPU clear on the same Surface producer.
|
||||
let _ = backend;
|
||||
Ok(())
|
||||
} else {
|
||||
android_window::present_frame(handle, backend, argb)
|
||||
};
|
||||
#[cfg(not(target_os = "android"))]
|
||||
let present_result: Result<(), crate::SurfacePresentError> = {
|
||||
let _ = backend;
|
||||
let _ = (backend, has_gpu_renderer);
|
||||
Ok(())
|
||||
};
|
||||
|
||||
let presented = with_host_mut(handle, |host| {
|
||||
host.surface
|
||||
.complete_frame(frame_time_nanos, present_result)
|
||||
let ok = host
|
||||
.surface
|
||||
.complete_frame(frame_time_nanos, present_result);
|
||||
if has_pending_timer {
|
||||
host.surface.request_frame();
|
||||
}
|
||||
ok
|
||||
})
|
||||
.unwrap_or(false);
|
||||
if presented { argb as JInt } else { 0 }
|
||||
@@ -396,6 +443,22 @@ pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeOnBackGesturePhase
|
||||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
pub(crate) fn sync_selection_overlay_from_editor(handle: JLong) {
|
||||
if let Some((utf16, (start, end))) = crate::editor_runtime::with_editor_mut(handle, |ed| {
|
||||
let range = ed.selection_range();
|
||||
let utf16 = if range.0 == range.1 {
|
||||
Vec::new()
|
||||
} else {
|
||||
ed.utf16_text()
|
||||
};
|
||||
(utf16, range)
|
||||
}) {
|
||||
let _ = with_host_mut(handle, |host| {
|
||||
host.sync_selection_overlay_for_snapshot(&utf16, start, end);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// # Safety
|
||||
/// `env` must be null or a valid `JNIEnv*`; `text` must be null or a valid `jstring`.
|
||||
#[unsafe(no_mangle)]
|
||||
@@ -409,6 +472,14 @@ pub unsafe extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeOnCommitTex
|
||||
let Some(utf16) = (unsafe { read_jstring_utf16(env, text) }) else {
|
||||
return;
|
||||
};
|
||||
if crate::editor_runtime::with_editor_mut(handle, |ed| {
|
||||
ed.commit_text_utf16(&utf16, new_cursor_position);
|
||||
})
|
||||
.is_some()
|
||||
{
|
||||
sync_selection_overlay_from_editor(handle);
|
||||
return;
|
||||
}
|
||||
let _ = with_host_mut(handle, |host| {
|
||||
host.commit_text_utf16(&utf16, new_cursor_position);
|
||||
});
|
||||
@@ -427,6 +498,14 @@ pub unsafe extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeOnSetCompos
|
||||
let Some(utf16) = (unsafe { read_jstring_utf16(env, text) }) else {
|
||||
return;
|
||||
};
|
||||
if crate::editor_runtime::with_editor_mut(handle, |ed| {
|
||||
ed.set_composing_text_utf16(&utf16, new_cursor_position);
|
||||
})
|
||||
.is_some()
|
||||
{
|
||||
sync_selection_overlay_from_editor(handle);
|
||||
return;
|
||||
}
|
||||
let _ = with_host_mut(handle, |host| {
|
||||
host.set_composing_text_utf16(&utf16, new_cursor_position);
|
||||
});
|
||||
@@ -441,6 +520,13 @@ pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeOnSetComposingRegi
|
||||
end: JInt,
|
||||
) {
|
||||
let (a, b) = normalize_jint_range(start, end);
|
||||
if crate::editor_runtime::with_editor_mut(handle, |ed| {
|
||||
ed.set_composing_region(a, b);
|
||||
})
|
||||
.is_some()
|
||||
{
|
||||
return;
|
||||
}
|
||||
let _ = with_host_mut(handle, |host| {
|
||||
host.set_composing_region(a, b);
|
||||
});
|
||||
@@ -452,6 +538,13 @@ pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeOnFinishComposingT
|
||||
_class: JClass,
|
||||
handle: JLong,
|
||||
) {
|
||||
if crate::editor_runtime::with_editor_mut(handle, |ed| {
|
||||
ed.finish_composing_text();
|
||||
})
|
||||
.is_some()
|
||||
{
|
||||
return;
|
||||
}
|
||||
let _ = with_host_mut(handle, |host| {
|
||||
host.finish_composing_text();
|
||||
});
|
||||
@@ -466,6 +559,14 @@ pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeOnSetSelection(
|
||||
end: JInt,
|
||||
) {
|
||||
let (a, b) = normalize_jint_range(start, end);
|
||||
if crate::editor_runtime::with_editor_mut(handle, |ed| {
|
||||
ed.set_selection(a, b);
|
||||
})
|
||||
.is_some()
|
||||
{
|
||||
sync_selection_overlay_from_editor(handle);
|
||||
return;
|
||||
}
|
||||
let _ = with_host_mut(handle, |host| {
|
||||
host.set_selection(a, b);
|
||||
});
|
||||
@@ -484,6 +585,14 @@ pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeOnDeleteSurroundin
|
||||
}
|
||||
let before = before_len as usize;
|
||||
let after = after_len as usize;
|
||||
if crate::editor_runtime::with_editor_mut(handle, |ed| {
|
||||
ed.delete_surrounding_text(before, after);
|
||||
})
|
||||
.is_some()
|
||||
{
|
||||
sync_selection_overlay_from_editor(handle);
|
||||
return;
|
||||
}
|
||||
let _ = with_host_mut(handle, |host| {
|
||||
host.delete_surrounding_text(before, after);
|
||||
});
|
||||
@@ -502,6 +611,12 @@ pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeOnDeleteSurroundin
|
||||
}
|
||||
let before = before_len as usize;
|
||||
let after = after_len as usize;
|
||||
if let Some(ok) = crate::editor_runtime::with_editor_mut(handle, |ed| {
|
||||
ed.delete_surrounding_text_in_code_points(before, after)
|
||||
}) {
|
||||
sync_selection_overlay_from_editor(handle);
|
||||
return u8::from(ok);
|
||||
}
|
||||
with_host_mut(handle, |host| {
|
||||
u8::from(host.delete_surrounding_text_in_code_points(before, after))
|
||||
})
|
||||
@@ -526,6 +641,14 @@ pub unsafe extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeOnReplaceTe
|
||||
let Some(utf16) = (unsafe { read_jstring_utf16(env, text) }) else {
|
||||
return 0;
|
||||
};
|
||||
if crate::editor_runtime::with_editor_mut(handle, |ed| {
|
||||
ed.replace_text_utf16(start as usize, end as usize, &utf16, new_cursor_position);
|
||||
})
|
||||
.is_some()
|
||||
{
|
||||
sync_selection_overlay_from_editor(handle);
|
||||
return 1;
|
||||
}
|
||||
with_host_mut(handle, |host| {
|
||||
host.replace_text_utf16(start as usize, end as usize, &utf16, new_cursor_position);
|
||||
1
|
||||
@@ -539,6 +662,11 @@ pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeGetUtf16Length(
|
||||
_class: JClass,
|
||||
handle: JLong,
|
||||
) -> JInt {
|
||||
if let Some(len) = crate::editor_runtime::with_editor_mut(handle, |ed| {
|
||||
ed.utf16_len().min(i32::MAX as usize) as JInt
|
||||
}) {
|
||||
return len;
|
||||
}
|
||||
with_host_ref(handle, |host| {
|
||||
host.utf16_len().min(i32::MAX as usize) as JInt
|
||||
})
|
||||
@@ -555,6 +683,11 @@ pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeGetUtf16Unit(
|
||||
let Ok(idx) = usize::try_from(index) else {
|
||||
return 0;
|
||||
};
|
||||
if let Some(unit) = crate::editor_runtime::with_editor_mut(handle, |ed| {
|
||||
i32::from(ed.utf16_unit(idx).unwrap_or(0))
|
||||
}) {
|
||||
return unit;
|
||||
}
|
||||
with_host_ref(handle, |host| i32::from(host.utf16_unit(idx).unwrap_or(0))).unwrap_or(0)
|
||||
}
|
||||
|
||||
@@ -564,6 +697,11 @@ pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeGetSelectionStart(
|
||||
_class: JClass,
|
||||
handle: JLong,
|
||||
) -> JInt {
|
||||
if let Some(start) =
|
||||
crate::editor_runtime::with_editor_mut(handle, |ed| ed.selection_range().0 as JInt)
|
||||
{
|
||||
return start;
|
||||
}
|
||||
with_host_ref(handle, |host| host.selection_range().0 as JInt).unwrap_or(0)
|
||||
}
|
||||
|
||||
@@ -573,6 +711,11 @@ pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeGetSelectionEnd(
|
||||
_class: JClass,
|
||||
handle: JLong,
|
||||
) -> JInt {
|
||||
if let Some(end) =
|
||||
crate::editor_runtime::with_editor_mut(handle, |ed| ed.selection_range().1 as JInt)
|
||||
{
|
||||
return end;
|
||||
}
|
||||
with_host_ref(handle, |host| host.selection_range().1 as JInt).unwrap_or(0)
|
||||
}
|
||||
|
||||
@@ -582,6 +725,11 @@ pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeGetComposingStart(
|
||||
_class: JClass,
|
||||
handle: JLong,
|
||||
) -> JInt {
|
||||
if let Some(start) = crate::editor_runtime::with_editor_mut(handle, |ed| {
|
||||
ed.composing_range().map_or(-1, |(s, _)| s as JInt)
|
||||
}) {
|
||||
return start;
|
||||
}
|
||||
with_host_ref(handle, |host| {
|
||||
host.composing_range()
|
||||
.map_or(-1, |(start, _)| start as JInt)
|
||||
@@ -595,6 +743,11 @@ pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeGetComposingEnd(
|
||||
_class: JClass,
|
||||
handle: JLong,
|
||||
) -> JInt {
|
||||
if let Some(end) = crate::editor_runtime::with_editor_mut(handle, |ed| {
|
||||
ed.composing_range().map_or(-1, |(_, e)| e as JInt)
|
||||
}) {
|
||||
return end;
|
||||
}
|
||||
with_host_ref(handle, |host| {
|
||||
host.composing_range().map_or(-1, |(_, end)| end as JInt)
|
||||
})
|
||||
@@ -611,6 +764,9 @@ pub(crate) fn insert_test_host(handle: JLong, state: AndroidHostState) {
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn snapshot_text(handle: JLong) -> Option<String> {
|
||||
if let Some(units) = crate::editor_runtime::with_editor_mut(handle, |ed| ed.utf16_text()) {
|
||||
return Some(String::from_utf16_lossy(&units));
|
||||
}
|
||||
let map = registry()
|
||||
.lock()
|
||||
.unwrap_or_else(|poison| poison.into_inner());
|
||||
|
||||
@@ -0,0 +1,212 @@
|
||||
#![allow(unsafe_code)]
|
||||
|
||||
//! Hand-written `extern "C"` JNI exports for the live pure-Rust BlockSuite GPU
|
||||
//! editor mounted inside `affine-android-host`.
|
||||
|
||||
use playground::PlaygroundMode;
|
||||
|
||||
use crate::{
|
||||
editor_runtime::{self, with_editor_mut},
|
||||
jni_bridge::{
|
||||
JBoolean, JClass, JFloat, JInt, JLong, JString, JniEnvPtr, new_jstring, with_host_mut,
|
||||
with_host_ref,
|
||||
},
|
||||
};
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeLoadShowcaseDocument(
|
||||
_env: JniEnvPtr,
|
||||
_class: JClass,
|
||||
handle: JLong,
|
||||
) {
|
||||
let _ = with_editor_mut(handle, |ed| ed.load_showcase_document());
|
||||
let _ = with_host_mut(handle, |host| host.surface.request_frame());
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeResetEmptyDocument(
|
||||
_env: JniEnvPtr,
|
||||
_class: JClass,
|
||||
handle: JLong,
|
||||
) {
|
||||
let _ = with_editor_mut(handle, |ed| ed.reset_empty_document());
|
||||
let _ = with_host_mut(handle, |host| host.surface.request_frame());
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeSetFormFactor(
|
||||
_env: JniEnvPtr,
|
||||
_class: JClass,
|
||||
handle: JLong,
|
||||
smallest_width_dp: JInt,
|
||||
) {
|
||||
let _ = with_editor_mut(handle, |ed| {
|
||||
ed.set_form_factor_from_smallest_width_dp(smallest_width_dp);
|
||||
});
|
||||
let _ = with_host_mut(handle, |host| host.surface.request_frame());
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeIsEdgelessReadonly(
|
||||
_env: JniEnvPtr,
|
||||
_class: JClass,
|
||||
handle: JLong,
|
||||
) -> JBoolean {
|
||||
u8::from(with_editor_mut(handle, |ed| ed.edgeless_readonly()).unwrap_or(true))
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeIsDatabaseReadonly(
|
||||
_env: JniEnvPtr,
|
||||
_class: JClass,
|
||||
handle: JLong,
|
||||
) -> JBoolean {
|
||||
u8::from(with_editor_mut(handle, |ed| ed.database_readonly()).unwrap_or(true))
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeSetEditorMode(
|
||||
_env: JniEnvPtr,
|
||||
_class: JClass,
|
||||
handle: JLong,
|
||||
mode_code: JInt,
|
||||
) {
|
||||
let mode = if mode_code == 1 {
|
||||
PlaygroundMode::Edgeless
|
||||
} else {
|
||||
PlaygroundMode::Page
|
||||
};
|
||||
let _ = with_editor_mut(handle, |ed| ed.set_mode(mode));
|
||||
let _ = with_host_mut(handle, |host| host.surface.request_frame());
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeOnTouchEvent(
|
||||
_env: JniEnvPtr,
|
||||
_class: JClass,
|
||||
handle: JLong,
|
||||
pointer_id: JLong,
|
||||
phase: JInt,
|
||||
x_dp: JFloat,
|
||||
y_dp: JFloat,
|
||||
) {
|
||||
let _ = with_editor_mut(handle, |ed| {
|
||||
ed.dispatch_touch(pointer_id as u64, phase.clamp(0, 3) as u8, x_dp, y_dp);
|
||||
});
|
||||
let _ = with_host_mut(handle, |host| host.surface.request_frame());
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeOnKeyEvent(
|
||||
_env: JniEnvPtr,
|
||||
_class: JClass,
|
||||
handle: JLong,
|
||||
key_code: JInt,
|
||||
shift: JBoolean,
|
||||
ctrl: JBoolean,
|
||||
alt: JBoolean,
|
||||
) -> JBoolean {
|
||||
let handled = with_editor_mut(handle, |ed| {
|
||||
ed.dispatch_key_code(key_code, shift != 0, ctrl != 0, alt != 0)
|
||||
})
|
||||
.unwrap_or(false);
|
||||
if handled {
|
||||
let _ = with_host_mut(handle, |host| host.surface.request_frame());
|
||||
}
|
||||
u8::from(handled)
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeGetTextInputChangeSeq(
|
||||
_env: JniEnvPtr,
|
||||
_class: JClass,
|
||||
handle: JLong,
|
||||
) -> JLong {
|
||||
with_editor_mut(handle, |ed| ed.text_input_change_seq() as JLong).unwrap_or(0)
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeGetFocusedBlockHash(
|
||||
_env: JniEnvPtr,
|
||||
_class: JClass,
|
||||
handle: JLong,
|
||||
) -> JLong {
|
||||
with_editor_mut(handle, |ed| ed.focused_block_hash() as JLong).unwrap_or(0)
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeWantsSoftwareKeyboard(
|
||||
_env: JniEnvPtr,
|
||||
_class: JClass,
|
||||
handle: JLong,
|
||||
) -> JBoolean {
|
||||
u8::from(with_editor_mut(handle, |ed| ed.wants_software_keyboard()).unwrap_or(false))
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeGetCaretRectDpX(
|
||||
_env: JniEnvPtr,
|
||||
_class: JClass,
|
||||
handle: JLong,
|
||||
) -> JFloat {
|
||||
with_editor_mut(handle, |ed| ed.caret_rect_dp().map(|r| r[0]).unwrap_or(0.0)).unwrap_or(0.0)
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeGetCaretRectDpY(
|
||||
_env: JniEnvPtr,
|
||||
_class: JClass,
|
||||
handle: JLong,
|
||||
) -> JFloat {
|
||||
with_editor_mut(handle, |ed| ed.caret_rect_dp().map(|r| r[1]).unwrap_or(0.0)).unwrap_or(0.0)
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeGetCaretRectDpHeight(
|
||||
_env: JniEnvPtr,
|
||||
_class: JClass,
|
||||
handle: JLong,
|
||||
) -> JFloat {
|
||||
with_editor_mut(handle, |ed| {
|
||||
ed.caret_rect_dp().map(|r| r[3]).unwrap_or(20.0)
|
||||
})
|
||||
.unwrap_or(20.0)
|
||||
}
|
||||
|
||||
/// Bulk UTF-16 read of the focused editor block in a single JNI call (`H-S1`).
|
||||
///
|
||||
/// # Safety
|
||||
/// `env` must be null or a valid `JNIEnv*`.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeGetUtf16Text(
|
||||
env: JniEnvPtr,
|
||||
_class: JClass,
|
||||
handle: JLong,
|
||||
) -> JString {
|
||||
let text = if let Some(units) = with_editor_mut(handle, |ed| ed.utf16_text()) {
|
||||
String::from_utf16_lossy(&units)
|
||||
} else {
|
||||
with_host_ref(handle, |host| host.text_string()).unwrap_or_default()
|
||||
};
|
||||
unsafe { new_jstring(env, &text) }
|
||||
}
|
||||
|
||||
/// Returns `true` when the Android editor dispatcher still has pending delayed timers
|
||||
/// (caret blink, long-press, toast auto-dismiss) so Choreographer schedules another tick.
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeHasPendingTimer(
|
||||
_env: JniEnvPtr,
|
||||
_class: JClass,
|
||||
handle: JLong,
|
||||
) -> JBoolean {
|
||||
let pending = with_editor_mut(handle, |ed| ed.drain_tasks().is_some()).unwrap_or(false);
|
||||
u8::from(pending)
|
||||
}
|
||||
|
||||
pub(crate) fn attach_for_host(handle: JLong) {
|
||||
editor_runtime::attach_editor(handle, 412.0, 915.0, 2.625);
|
||||
}
|
||||
|
||||
pub(crate) fn detach_for_host(handle: JLong) {
|
||||
editor_runtime::detach_editor(handle);
|
||||
}
|
||||
@@ -133,6 +133,7 @@ pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeSetSelectionViewpo
|
||||
host.sync_selection_overlay_from_ime();
|
||||
}
|
||||
});
|
||||
crate::jni_bridge::sync_selection_overlay_from_editor(handle);
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
@@ -212,7 +213,10 @@ pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeSelectionEndDrag(
|
||||
_class: JClass,
|
||||
handle: JLong,
|
||||
) -> JBoolean {
|
||||
with_host_mut(handle, |host| u8::from(host.end_selection_handle_drag())).unwrap_or(0)
|
||||
let has_menu =
|
||||
with_host_mut(handle, |host| u8::from(host.end_selection_handle_drag())).unwrap_or(0);
|
||||
crate::jni_bridge::sync_selection_overlay_from_editor(handle);
|
||||
has_menu
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
@@ -224,6 +228,7 @@ pub extern "C" fn Java_app_affine_pro_host_NativeBridge_nativeSelectionCancelDra
|
||||
let _ = with_host_mut(handle, |host| {
|
||||
host.cancel_selection_handle_drag();
|
||||
});
|
||||
crate::jni_bridge::sync_selection_overlay_from_editor(handle);
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
|
||||
@@ -1,14 +1,8 @@
|
||||
#![deny(unsafe_code)]
|
||||
|
||||
//! Thin Android host bridge for AFFiNE (`affine-android-host`).
|
||||
//!
|
||||
//! Provides cross-platform testable host state machines (four-phase predictive
|
||||
//! and legacy single-commit back gesture handling, API 26+ Autofill gating,
|
||||
//! physical-px to logical-dp inset conversion, `SurfaceHolder.Callback`
|
||||
//! lifecycle, in-place SQLite WAL co-storage, Jetpack Preferences DataStore
|
||||
//! `v1:` AES-GCM credential contract, and legacy `https://localhost`
|
||||
//! `localStorage` whitelist import/rollback with zero IndexedDB access)
|
||||
//! alongside hand-written thin JNI exports.
|
||||
//! Thin Android host bridge for AFFiNE (`affine-android-host`): predictive back,
|
||||
//! API 26+ Autofill, inset conversion, `SurfaceHolder` lifecycle, SQLite WAL,
|
||||
//! DataStore `v1:` AES-GCM, legacy `localStorage` import/rollback, and JNI exports.
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
@@ -18,6 +12,12 @@ use serde::{Deserialize, Serialize};
|
||||
mod android_window;
|
||||
pub mod autofill;
|
||||
pub mod datastore;
|
||||
#[cfg(any(target_os = "android", test, feature = "host-jni"))]
|
||||
mod editor_fallback;
|
||||
#[cfg(any(target_os = "android", test, feature = "host-jni"))]
|
||||
pub(crate) mod editor_platform;
|
||||
#[cfg(any(target_os = "android", test, feature = "host-jni"))]
|
||||
pub(crate) mod editor_runtime;
|
||||
mod ime;
|
||||
pub mod pdf;
|
||||
pub mod selection;
|
||||
@@ -28,6 +28,8 @@ pub mod text_layout;
|
||||
#[cfg(any(target_os = "android", test, feature = "host-jni"))]
|
||||
pub mod jni_bridge;
|
||||
#[cfg(any(target_os = "android", test, feature = "host-jni"))]
|
||||
pub mod jni_editor;
|
||||
#[cfg(any(target_os = "android", test, feature = "host-jni"))]
|
||||
pub mod jni_interaction;
|
||||
#[cfg(any(target_os = "android", test, feature = "host-jni"))]
|
||||
pub mod jni_storage;
|
||||
|
||||
@@ -1677,51 +1677,40 @@ fun main() {
|
||||
)
|
||||
checkEq(nav.openDocument("roadmap"), true, "seq22 open doc/roadmap")
|
||||
checkEq(docIme.replaceText(0, docIme.currentText().length, "Project roadmap", 1), true, "seq22 write roadmap text")
|
||||
checkEq(bufCtrl.lastPreviewText, "Project roadmap", "seq22 preview shows Project roadmap")
|
||||
val seqBeforePollutionChecks = docIme.textInputChangeSeq()
|
||||
|
||||
checkEq(afCtrl.registerField(202, 2, 20, 200, 800, 280, true, 0), true, "seq22 register password field")
|
||||
bufCtrl.onAutofillFocusChanged(202)
|
||||
checkEq(afCtrl.onAutofillValues(mapOf(202 to "s3cr3t!")), 1, "seq22 autofill password s3cr3t!")
|
||||
checkEq(bufCtrl.lastPreviewText.contains("s3cr3t!"), false, "seq22 password NEVER leaks into HostTextPreviewView")
|
||||
checkEq(bufCtrl.lastPreviewText, "Project roadmap", "seq22 preview stays Project roadmap while editing password")
|
||||
checkEq(docStore.readDocument("doc/roadmap"), "Project roadmap", "seq22 documentStore stays Project roadmap")
|
||||
checkEq(docIme.currentText(), "Project roadmap", "seq22 H-S1: autofill MUST NOT overwrite editor block")
|
||||
checkEq(docIme.textInputChangeSeq(), seqBeforePollutionChecks, "seq22 H-S1: autofill MUST NOT touch editor undo/seq")
|
||||
checkEq(docStore.readDocument("doc/roadmap"), "", "seq22 H-S1: host documentStore keeps zero shadow copy")
|
||||
|
||||
// Switch route to doc B while password was focused, then back to doc A -> roadmap intact, password intact.
|
||||
// Switch route while password was focused -> editor block remains 100% unpolluted, password preserved.
|
||||
checkEq(nav.openDocument("notes"), true, "seq22 navigate to doc/notes while password focused")
|
||||
checkEq(docIme.commitText("Meeting notes", 1), true, "seq22 write notes doc")
|
||||
checkEq(docIme.currentText(), "Project roadmap", "seq22 H-S1: route switch MUST NOT overwrite editor block")
|
||||
checkEq(nav.onBackInvoked(), true, "seq22 back to doc/roadmap")
|
||||
checkEq(docIme.currentText(), "Project roadmap", "seq22 doc/roadmap restored intact")
|
||||
checkEq(bufCtrl.lastPreviewText, "Project roadmap", "seq22 preview restored to Project roadmap")
|
||||
checkEq(docIme.currentText(), "Project roadmap", "seq22 doc/roadmap untouched across route switch")
|
||||
checkEq(docIme.textInputChangeSeq(), seqBeforePollutionChecks, "seq22 route switch MUST NOT pollute undo/seq")
|
||||
checkEq(afCtrl.readFormValues()["password"], "s3cr3t!", "seq22 autofill password preserved")
|
||||
|
||||
// Part D: Autofill session exit via commitAutofillSession / cancelAutofillSession / clearAutofillFields
|
||||
// must restore the document buffer immediately so subsequent typing and route switches never leak form text.
|
||||
// Part D: Autofill session exit via commit / cancel / clear leaves editor block untouched.
|
||||
val exitModes = listOf("commit", "cancel", "clear")
|
||||
for (mode in exitModes) {
|
||||
checkEq(afCtrl.registerField(202, 2, 20, 200, 800, 280, true, 0), true, "seq22 ($mode) register password field")
|
||||
checkEq(docIme.replaceText(0, docIme.currentText().length, "Doc-$mode", 1), true, "seq22 ($mode) seed doc text")
|
||||
bufCtrl.recordDocumentSelection(0, 3)
|
||||
val seqSeeded = docIme.textInputChangeSeq()
|
||||
bufCtrl.onAutofillFocusChanged(202)
|
||||
checkEq(docIme.replaceText(0, docIme.currentText().length, "f0rm-secret-99", 1), true, "seq22 ($mode) type secret in form")
|
||||
checkEq(docIme.setSelection(0, 6), true, "seq22 ($mode) select secret in form")
|
||||
// Simulated surfaceChanged while Autofill focused must keep currentDocumentText() untouched.
|
||||
checkEq(bufCtrl.isAutofillFocused(), true, "seq22 ($mode) autofill focused before resize")
|
||||
checkEq(bufCtrl.currentDocumentText(), "Doc-$mode", "seq22 ($mode) currentDocumentText hides form secret")
|
||||
checkEq(bufCtrl.lastPreviewText, "Doc-$mode", "seq22 ($mode) preview hides form secret")
|
||||
checkEq(afCtrl.onAutofillValues(mapOf(202 to "f0rm-secret-99")), 1, "seq22 ($mode) autofill secret")
|
||||
checkEq(docIme.currentText(), "Doc-$mode", "seq22 ($mode) editor block isolated from form secret")
|
||||
when (mode) {
|
||||
"commit" -> checkEq(bufCtrl.commitAutofillSession(), true, "seq22 commitAutofillSession")
|
||||
"cancel" -> checkEq(bufCtrl.cancelAutofillSession(), true, "seq22 cancelAutofillSession")
|
||||
"clear" -> bufCtrl.clearAutofillFields()
|
||||
}
|
||||
checkEq(bufCtrl.isAutofillFocused(), false, "seq22 ($mode) autofill unfocused after exit")
|
||||
checkEq(docIme.currentText(), "Doc-$mode", "seq22 ($mode) IME immediately restored to doc text")
|
||||
checkEq(docIme.setSelection(docIme.currentText().length, docIme.currentText().length), true, "seq22 ($mode) move caret to end")
|
||||
checkEq(docIme.commitText("!", 1), true, "seq22 ($mode) first edit after exit appends to doc")
|
||||
checkEq(docIme.currentText(), "Doc-$mode!", "seq22 ($mode) post-exit edit preserved doc without form text")
|
||||
checkEq(docStore.readDocument("doc/roadmap"), "Doc-$mode!", "seq22 ($mode) store saved clean doc")
|
||||
checkEq(nav.openDocument("scratch-$mode"), true, "seq22 ($mode) navigate away after exit")
|
||||
checkEq(nav.onBackInvoked(), true, "seq22 ($mode) navigate back after exit")
|
||||
checkEq(docIme.currentText(), "Doc-$mode!", "seq22 ($mode) roundtrip route switch kept clean doc")
|
||||
checkEq(docIme.currentText(), "Doc-$mode", "seq22 ($mode) editor block unchanged after autofill exit")
|
||||
checkEq(docIme.textInputChangeSeq(), seqSeeded, "seq22 ($mode) zero editor mutations during autofill lifecycle")
|
||||
checkEq(docIme.currentText().contains("f0rm-secret-99"), false, "seq22 ($mode) no form secret leaked")
|
||||
}
|
||||
|
||||
@@ -1741,7 +1730,7 @@ fun main() {
|
||||
checkEq(docIme.replaceText(0, docIme.currentText().length, "Hello document", 1), true, "seq22 masked seed doc")
|
||||
bufCtrl.onAutofillFocusChanged(202)
|
||||
checkEq(bufCtrl.isFocusedAutofillFieldMasked(), true, "seq22 focused password field is masked")
|
||||
checkEq(docIme.replaceText(0, docIme.currentText().length, "s3cr3t-pass", 1), true, "seq22 type masked password")
|
||||
bufCtrl.applyAutofillTextToIme("s3cr3t-pass")
|
||||
checkEq(docIme.setSelection(0, 6), true, "seq22 select [0, 6) inside masked password")
|
||||
// Mirror MainActivity.onImeMutated suppression when Autofill is focused.
|
||||
if (bufCtrl.isAutofillFocused()) {
|
||||
@@ -1959,5 +1948,45 @@ fun main() {
|
||||
seq23Dir.deleteRecursively()
|
||||
}
|
||||
|
||||
println("Kotlin JNI Android host parity check passed (23/23 sequences)")
|
||||
// 24. S6 native GPU editor mount: H-A1 Gboard composing region, H-S1 Markdown transform &
|
||||
// getExtractedText, H-S2 change sequence & block hash, sendKeyEvent block split/merge, and T1 readonly.
|
||||
withHost { ic, ime ->
|
||||
// H-A1: Gboard backspace-into-word (" hello" -> setComposingRegion(1, 6) -> setComposingText("hellos"))
|
||||
checkEq(ic.commitText(" hello", 1), true, "seq24 commit ' hello'")
|
||||
checkEq(ic.setComposingRegion(1, 6), true, "seq24 setComposingRegion(1, 6)")
|
||||
checkEq(ime.composingStart(), 1, "seq24 composingStart 1")
|
||||
checkEq(ime.composingEnd(), 6, "seq24 composingEnd 6")
|
||||
checkEq(ic.setComposingText("hellos", 1), true, "seq24 setComposingText('hellos')")
|
||||
checkEq(ime.readText(), " hellos", "seq24 Gboard composing region must not duplicate 'hello'")
|
||||
checkEq(ic.finishComposingText(), true, "seq24 finishComposingText")
|
||||
|
||||
// H-S1: authoritative editor text and collapsed selection after Gboard composing edit
|
||||
checkEq(ime.readText(), " hellos", "seq24 authoritative text after composing")
|
||||
checkEq(ime.selectionStart(), 7, "seq24 authoritative selectionStart == 7")
|
||||
checkEq(ime.selectionEnd(), 7, "seq24 authoritative selectionEnd == 7")
|
||||
|
||||
// sendKeyEvent: KEYCODE_ENTER splits block, KEYCODE_DEL at block start merges back
|
||||
val seqBefore = ime.textInputChangeSeq()
|
||||
val blockBefore = ime.focusedBlockHash()
|
||||
checkEq(ime.sendKeyEvent(66, false, false, false), true, "seq24 KEYCODE_ENTER splits block")
|
||||
checkEq(ime.readText(), "", "seq24 new split block is empty")
|
||||
checkEq(ime.textInputChangeSeq() > seqBefore, true, "seq24 H-S2 change seq increments on split")
|
||||
checkEq(ime.focusedBlockHash() != blockBefore, true, "seq24 H-S2 focused block hash changes on split")
|
||||
checkEq(ime.sendKeyEvent(67, false, false, false), true, "seq24 KEYCODE_DEL merges with previous block")
|
||||
checkEq(ime.readText(), " hellos", "seq24 block-start DEL merges back to ' hellos'")
|
||||
}
|
||||
|
||||
val seq24Handle = NativeBridge.nativeCreateHost()
|
||||
try {
|
||||
NativeBridge.nativeSetFormFactor(seq24Handle, 390)
|
||||
checkEq(NativeBridge.nativeIsEdgelessReadonly(seq24Handle), true, "seq24 Phone edgeless_readonly")
|
||||
checkEq(NativeBridge.nativeIsDatabaseReadonly(seq24Handle), true, "seq24 Phone database_readonly")
|
||||
NativeBridge.nativeSetFormFactor(seq24Handle, 720)
|
||||
checkEq(NativeBridge.nativeIsEdgelessReadonly(seq24Handle), true, "seq24 Tablet edgeless_readonly")
|
||||
checkEq(NativeBridge.nativeIsDatabaseReadonly(seq24Handle), true, "seq24 Tablet database_readonly")
|
||||
} finally {
|
||||
NativeBridge.nativeDestroyHost(seq24Handle)
|
||||
}
|
||||
|
||||
println("Kotlin JNI Android host parity check passed (24/24 sequences)")
|
||||
}
|
||||
@@ -10,7 +10,9 @@ 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 drive shaped CoreText `CTTypesetter`/`CTLine` text geometry, BiDi selection rects, and whole-line `CTLineDraw` loupe rendering through `TextRenderingBridge.swift` / `src/ffi_text.rs` (with headless Rust fallback in `src/text_layout.rs`). `HostTextPreviewView` is an S3 thin-host transition preview layer and will be removed when S4 attaches the GPU `blocksuite-editor` renderer to avoid double-drawing.
|
||||
- Keep `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`).
|
||||
- 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.
|
||||
- Keep `PdfRendererBridge.swift` backed by Apple's system `PDFKit` framework (zero C++ PDFium) with explicit `affine_ios_host_pdf_open`/`close` document handles (zero persistent cache) and enforce the shared Rust header, page-bounds, and pixel-budget limits in `src/pdf.rs`.
|
||||
- Pin Rust builds in `scripts/build-rust-ios.sh` to `rustup run 1.98.1`, `--manifest-path packages/frontend/Cargo.toml`, and `CARGO_ENCODED_RUSTFLAGS=""`. Never modify `packages/frontend/apps/ios/` (`1.97.1`).
|
||||
|
||||
@@ -11,14 +11,22 @@ crate-type = ["staticlib", "rlib"]
|
||||
|
||||
[dependencies]
|
||||
affine-legacy-import = { path = "../../legacy-import" }
|
||||
affine-mobile = { path = "../../mobile" }
|
||||
affine-store = { path = "../../../common/store" }
|
||||
anyhow.workspace = true
|
||||
blocksuite-playground-doc = { path = "../../../../blocksuite/crates/doc", default-features = false }
|
||||
chrono.workspace = true
|
||||
futures.workspace = true
|
||||
parking_lot.workspace = true
|
||||
playground = { path = "../../../../blocksuite/crates/playground" }
|
||||
raw-window-handle.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
smallvec.workspace = true
|
||||
sqlx.workspace = true
|
||||
thiserror.workspace = true
|
||||
tokio.workspace = true
|
||||
ui = { path = "../../../ui/ui" }
|
||||
uuid.workspace = true
|
||||
|
||||
[lints]
|
||||
|
||||
@@ -22,6 +22,23 @@
|
||||
<true/>
|
||||
<key>UIApplicationSupportsIndirectInputEvents</key>
|
||||
<true/>
|
||||
<key>UIApplicationSceneManifest</key>
|
||||
<dict>
|
||||
<key>UIApplicationSupportsMultipleScenes</key>
|
||||
<false/>
|
||||
<key>UISceneConfigurations</key>
|
||||
<dict>
|
||||
<key>UIWindowSceneSessionRoleApplication</key>
|
||||
<array>
|
||||
<dict>
|
||||
<key>UISceneConfigurationName</key>
|
||||
<string>Default Configuration</string>
|
||||
<key>UISceneDelegateClassName</key>
|
||||
<string>AffineSceneDelegate</string>
|
||||
</dict>
|
||||
</array>
|
||||
</dict>
|
||||
</dict>
|
||||
<key>UILaunchScreen</key>
|
||||
<dict/>
|
||||
</dict>
|
||||
|
||||
@@ -2,16 +2,42 @@ import UIKit
|
||||
|
||||
@main
|
||||
final class AppDelegate: UIResponder, UIApplicationDelegate {
|
||||
var window: UIWindow?
|
||||
|
||||
func application(
|
||||
_ application: UIApplication,
|
||||
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil
|
||||
) -> Bool {
|
||||
let window = UIWindow(frame: UIScreen.main.bounds)
|
||||
true
|
||||
}
|
||||
|
||||
func application(
|
||||
_ application: UIApplication,
|
||||
configurationForConnecting connectingSceneSession: UISceneSession,
|
||||
options: UIScene.ConnectionOptions
|
||||
) -> UISceneConfiguration {
|
||||
let config = UISceneConfiguration(
|
||||
name: "Default Configuration",
|
||||
sessionRole: connectingSceneSession.role
|
||||
)
|
||||
config.delegateClass = SceneDelegate.self
|
||||
return config
|
||||
}
|
||||
}
|
||||
|
||||
@objc(AffineSceneDelegate)
|
||||
final class SceneDelegate: UIResponder, UIWindowSceneDelegate {
|
||||
var window: UIWindow?
|
||||
|
||||
func scene(
|
||||
_ scene: UIScene,
|
||||
willConnectTo session: UISceneSession,
|
||||
options connectionOptions: UIScene.ConnectionOptions
|
||||
) {
|
||||
guard let windowScene = scene as? UIWindowScene else {
|
||||
return
|
||||
}
|
||||
let window = UIWindow(windowScene: windowScene)
|
||||
window.rootViewController = MetalHostViewController()
|
||||
window.makeKeyAndVisible()
|
||||
self.window = window
|
||||
return true
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,3 @@
|
||||
import Metal
|
||||
import QuartzCore
|
||||
import UIKit
|
||||
|
||||
@@ -78,6 +77,14 @@ private final class DisplayLinkProxy: NSObject {
|
||||
}
|
||||
}
|
||||
|
||||
private func affineIosTextInputChangedTrampoline(_ changeKind: UInt8, _ userData: UnsafeMutableRawPointer?) {
|
||||
guard let userData else {
|
||||
return
|
||||
}
|
||||
let view = Unmanaged<MetalHostView>.fromOpaque(userData).takeUnretainedValue()
|
||||
view.handleEditorTextInputStateChanged(kind: changeKind)
|
||||
}
|
||||
|
||||
final class MetalHostView: UIView, UITextInput {
|
||||
override class var layerClass: AnyClass {
|
||||
CAMetalLayer.self
|
||||
@@ -96,21 +103,48 @@ final class MetalHostView: UIView, UITextInput {
|
||||
var hostHandle: OpaquePointer?
|
||||
var onSelectedRangeChanged: ((NSRange) -> Void)?
|
||||
private(set) var lastCopiedText: String?
|
||||
private(set) var editorInputNotificationCount: Int = 0
|
||||
|
||||
private var backingText: NSString = ""
|
||||
private var selectedUtf16Range = NSRange(location: 0, length: 0)
|
||||
private var markedUtf16Range: NSRange?
|
||||
private var isInsideImeMutation = false
|
||||
private var pendingExternalChangeKind: UInt8 = 0
|
||||
private var activeTouchIds: [ObjectIdentifier: UInt64] = [:]
|
||||
private var touchStartPoints: [UInt64: CGPoint] = [:]
|
||||
private var touchExceededPanThreshold: Set<UInt64> = []
|
||||
private var nextTouchId: UInt64 = 1
|
||||
|
||||
var currentBackingUtf16Units: [UInt16] {
|
||||
let len = backingText.length
|
||||
guard len > 0 else { return [] }
|
||||
/// Authoritative UTF-16 code units read directly from Rust `PlatformInputHandler` (zero host copy).
|
||||
var currentAuthoritativeUtf16Units: [UInt16] {
|
||||
guard let handle = hostHandle else {
|
||||
return []
|
||||
}
|
||||
let len = affine_ios_host_utf16_len(handle)
|
||||
guard len > 0 else {
|
||||
return []
|
||||
}
|
||||
var buf = Array(repeating: UInt16(0), count: len)
|
||||
backingText.getCharacters(&buf, range: NSRange(location: 0, length: len))
|
||||
let copied = buf.withUnsafeMutableBufferPointer { ptr in
|
||||
affine_ios_host_copy_utf16(handle, ptr.baseAddress, len)
|
||||
}
|
||||
if copied < len {
|
||||
return Array(buf.prefix(copied))
|
||||
}
|
||||
return buf
|
||||
}
|
||||
|
||||
private var currentAuthoritativeString: NSString {
|
||||
let units = currentAuthoritativeUtf16Units
|
||||
guard !units.isEmpty else {
|
||||
return ""
|
||||
}
|
||||
return NSString(characters: units, length: units.count)
|
||||
}
|
||||
|
||||
var currentSelectedUtf16Range: NSRange {
|
||||
clampRange(selectedUtf16Range)
|
||||
guard let handle = hostHandle else {
|
||||
return NSRange(location: 0, length: 0)
|
||||
}
|
||||
let r = affine_ios_host_selected_range(handle)
|
||||
return clampRange(NSRange(location: Int(r.location), length: Int(r.length)))
|
||||
}
|
||||
|
||||
var currentWritingDirection: UInt8 {
|
||||
@@ -120,10 +154,120 @@ final class MetalHostView: UIView, UITextInput {
|
||||
return affine_ios_host_text_writing_direction(handle)
|
||||
}
|
||||
|
||||
func attachTextInputObserver() {
|
||||
guard let handle = hostHandle else {
|
||||
return
|
||||
}
|
||||
let rawSelf = Unmanaged.passUnretained(self).toOpaque()
|
||||
affine_ios_host_set_text_input_callback(handle, affineIosTextInputChangedTrampoline, rawSelf)
|
||||
}
|
||||
|
||||
func detachTextInputObserver() {
|
||||
guard let handle = hostHandle else {
|
||||
return
|
||||
}
|
||||
affine_ios_host_set_text_input_callback(handle, nil, nil)
|
||||
}
|
||||
|
||||
/// H-S2: Editor-initiated content/selection change notifies `UITextInputDelegate` and overlay.
|
||||
func handleEditorTextInputStateChanged(kind: UInt8) {
|
||||
if isInsideImeMutation {
|
||||
pendingExternalChangeKind = max(pendingExternalChangeKind, kind)
|
||||
return
|
||||
}
|
||||
notifyInputDelegate(kind: kind)
|
||||
}
|
||||
|
||||
private func notifyInputDelegate(kind: UInt8) {
|
||||
editorInputNotificationCount += 1
|
||||
if kind == 4 {
|
||||
inputDelegate?.textWillChange(self)
|
||||
inputDelegate?.selectionWillChange(self)
|
||||
inputDelegate?.selectionDidChange(self)
|
||||
inputDelegate?.textDidChange(self)
|
||||
} else {
|
||||
inputDelegate?.selectionWillChange(self)
|
||||
inputDelegate?.selectionDidChange(self)
|
||||
}
|
||||
onSelectedRangeChanged?(currentSelectedUtf16Range)
|
||||
if let handle = hostHandle,
|
||||
!affine_ios_host_wants_software_keyboard(handle),
|
||||
isFirstResponder
|
||||
{
|
||||
_ = resignFirstResponder()
|
||||
}
|
||||
}
|
||||
|
||||
private var currentMarkedUtf16Range: NSRange? {
|
||||
guard let handle = hostHandle else {
|
||||
return nil
|
||||
}
|
||||
let r = affine_ios_host_marked_range(handle)
|
||||
if r.location == UInt32.max {
|
||||
return nil
|
||||
}
|
||||
return clampRange(NSRange(location: Int(r.location), length: Int(r.length)))
|
||||
}
|
||||
|
||||
private func expectedUnitsReplacing(
|
||||
_ range: NSRange,
|
||||
with replacement: [UInt16],
|
||||
in before: [UInt16]
|
||||
) -> [UInt16] {
|
||||
let lo = max(0, min(range.location, before.count))
|
||||
let hi = max(lo, min(range.location + range.length, before.count))
|
||||
var out: [UInt16] = []
|
||||
out.reserveCapacity(before.count - (hi - lo) + replacement.count)
|
||||
out.append(contentsOf: before[..<lo])
|
||||
out.append(contentsOf: replacement)
|
||||
out.append(contentsOf: before[hi...])
|
||||
return out
|
||||
}
|
||||
|
||||
/// 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).
|
||||
private func performImeMutation(
|
||||
expectedUnits: [UInt16]? = nil,
|
||||
expectedSelected: NSRange? = nil,
|
||||
expectedMarked: NSRange?? = nil,
|
||||
_ body: () -> Void
|
||||
) {
|
||||
let wasInside = isInsideImeMutation
|
||||
isInsideImeMutation = true
|
||||
pendingExternalChangeKind = 0
|
||||
body()
|
||||
isInsideImeMutation = wasInside
|
||||
let pending = pendingExternalChangeKind
|
||||
pendingExternalChangeKind = 0
|
||||
guard !wasInside else {
|
||||
return
|
||||
}
|
||||
var diverged = expectedUnits == nil && expectedSelected == nil && expectedMarked == nil
|
||||
if let expUnits = expectedUnits, currentAuthoritativeUtf16Units != expUnits {
|
||||
diverged = true
|
||||
}
|
||||
if let expSel = expectedSelected, currentSelectedUtf16Range != expSel {
|
||||
diverged = true
|
||||
}
|
||||
if let expMarked = expectedMarked, currentMarkedUtf16Range != expMarked {
|
||||
diverged = true
|
||||
}
|
||||
if pending != 0 && diverged {
|
||||
notifyInputDelegate(kind: pending)
|
||||
} else {
|
||||
onSelectedRangeChanged?(currentSelectedUtf16Range)
|
||||
}
|
||||
}
|
||||
|
||||
func updateSelectedRangeFromOverlay(_ range: NSRange) {
|
||||
guard let handle = hostHandle else {
|
||||
return
|
||||
}
|
||||
let clamped = clampRange(range)
|
||||
selectedUtf16Range = clamped
|
||||
if let handle = hostHandle {
|
||||
performImeMutation {
|
||||
affine_ios_host_set_selected_range(
|
||||
handle,
|
||||
AffineUtf16Range(location: UInt32(clamped.location), length: UInt32(clamped.length))
|
||||
@@ -133,29 +277,29 @@ final class MetalHostView: UIView, UITextInput {
|
||||
|
||||
override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
|
||||
if action == #selector(copy(_:)) || action == #selector(cut(_:)) {
|
||||
return selectedUtf16Range.length > 0
|
||||
return currentSelectedUtf16Range.length > 0
|
||||
}
|
||||
if action == #selector(paste(_:)) {
|
||||
return UIPasteboard.general.hasStrings
|
||||
}
|
||||
if action == #selector(selectAll(_:)) {
|
||||
return backingText.length > 0
|
||||
return hasText
|
||||
}
|
||||
return super.canPerformAction(action, withSender: sender)
|
||||
}
|
||||
|
||||
override func copy(_ sender: Any?) {
|
||||
let clamped = clampRange(selectedUtf16Range)
|
||||
let clamped = currentSelectedUtf16Range
|
||||
guard clamped.length > 0 else {
|
||||
return
|
||||
}
|
||||
let copied = backingText.substring(with: clamped)
|
||||
let copied = currentAuthoritativeString.substring(with: clamped)
|
||||
lastCopiedText = copied
|
||||
UIPasteboard.general.string = copied
|
||||
}
|
||||
|
||||
override func cut(_ sender: Any?) {
|
||||
let clamped = clampRange(selectedUtf16Range)
|
||||
let clamped = currentSelectedUtf16Range
|
||||
guard clamped.length > 0 else {
|
||||
return
|
||||
}
|
||||
@@ -171,7 +315,8 @@ final class MetalHostView: UIView, UITextInput {
|
||||
}
|
||||
|
||||
override func selectAll(_ sender: Any?) {
|
||||
selectedTextRange = AffineTextRange(utf16Range: NSRange(location: 0, length: backingText.length))
|
||||
let len = Int(hostHandle.map { affine_ios_host_utf16_len($0) } ?? 0)
|
||||
selectedTextRange = AffineTextRange(utf16Range: NSRange(location: 0, length: len))
|
||||
}
|
||||
|
||||
override var canBecomeFirstResponder: Bool {
|
||||
@@ -179,68 +324,51 @@ final class MetalHostView: UIView, UITextInput {
|
||||
}
|
||||
|
||||
var hasText: Bool {
|
||||
backingText.length > 0
|
||||
guard let handle = hostHandle else {
|
||||
return false
|
||||
}
|
||||
return affine_ios_host_utf16_len(handle) > 0
|
||||
}
|
||||
|
||||
func insertText(_ text: String) {
|
||||
let replaceRange = clampRange(markedUtf16Range ?? selectedUtf16Range)
|
||||
backingText = backingText.replacingCharacters(in: replaceRange, with: text) as NSString
|
||||
guard let handle = hostHandle else {
|
||||
return
|
||||
}
|
||||
let utf16 = Array(text.utf16)
|
||||
selectedUtf16Range = NSRange(location: replaceRange.location + utf16.count, length: 0)
|
||||
markedUtf16Range = nil
|
||||
if let handle = hostHandle {
|
||||
let before = currentAuthoritativeUtf16Units
|
||||
let replaceRange = currentMarkedUtf16Range ?? currentSelectedUtf16Range
|
||||
let expUnits = expectedUnitsReplacing(replaceRange, with: utf16, in: before)
|
||||
let expSel = NSRange(location: replaceRange.location + utf16.count, length: 0)
|
||||
performImeMutation(expectedUnits: expUnits, expectedSelected: expSel, expectedMarked: .some(nil)) {
|
||||
utf16.withUnsafeBufferPointer { buf in
|
||||
affine_ios_host_insert_text(handle, buf.baseAddress, buf.count)
|
||||
}
|
||||
}
|
||||
onSelectedRangeChanged?(selectedUtf16Range)
|
||||
}
|
||||
|
||||
func deleteBackward() {
|
||||
let clampedSelected = clampRange(selectedUtf16Range)
|
||||
var deletedRange: NSRange?
|
||||
if clampedSelected.length > 0 {
|
||||
backingText = backingText.replacingCharacters(in: clampedSelected, with: "") as NSString
|
||||
selectedUtf16Range = NSRange(location: clampedSelected.location, length: 0)
|
||||
adjustMarkedRangeAfterDeletion(clampedSelected)
|
||||
deletedRange = clampedSelected
|
||||
} else if clampedSelected.location > 0 {
|
||||
let delRange = backingText.rangeOfComposedCharacterSequence(
|
||||
at: clampedSelected.location - 1
|
||||
)
|
||||
backingText = backingText.replacingCharacters(in: delRange, with: "") as NSString
|
||||
selectedUtf16Range = NSRange(location: delRange.location, length: 0)
|
||||
adjustMarkedRangeAfterDeletion(delRange)
|
||||
deletedRange = delRange
|
||||
}
|
||||
if let handle = hostHandle, let del = deletedRange {
|
||||
affine_ios_host_delete_range(
|
||||
handle,
|
||||
AffineUtf16Range(location: UInt32(del.location), length: UInt32(del.length))
|
||||
)
|
||||
}
|
||||
if deletedRange != nil {
|
||||
onSelectedRangeChanged?(selectedUtf16Range)
|
||||
}
|
||||
}
|
||||
|
||||
private func adjustMarkedRangeAfterDeletion(_ deleted: NSRange) {
|
||||
guard let marked = markedUtf16Range else {
|
||||
guard let handle = hostHandle else {
|
||||
return
|
||||
}
|
||||
let markedEnd = marked.location + marked.length
|
||||
let deletedEnd = deleted.location + deleted.length
|
||||
if deletedEnd <= marked.location {
|
||||
markedUtf16Range = NSRange(location: marked.location - deleted.length, length: marked.length)
|
||||
} else if deleted.location < markedEnd {
|
||||
let overlapStart = max(marked.location, deleted.location)
|
||||
let overlapEnd = min(markedEnd, deletedEnd)
|
||||
let overlapLen = max(0, overlapEnd - overlapStart)
|
||||
let newLen = marked.length - overlapLen
|
||||
if newLen <= 0 {
|
||||
markedUtf16Range = nil
|
||||
} else {
|
||||
markedUtf16Range = NSRange(location: min(marked.location, deleted.location), length: newLen)
|
||||
let before = currentAuthoritativeUtf16Units
|
||||
let sel = currentSelectedUtf16Range
|
||||
if sel.length > 0 {
|
||||
let expUnits = expectedUnitsReplacing(sel, with: [], in: before)
|
||||
let expSel = NSRange(location: sel.location, length: 0)
|
||||
performImeMutation(expectedUnits: expUnits, expectedSelected: expSel, expectedMarked: .some(nil)) {
|
||||
affine_ios_host_delete_backward(handle)
|
||||
}
|
||||
} else if sel.location > 0 {
|
||||
let ns = NSString(characters: before, length: before.count)
|
||||
let delRange = ns.rangeOfComposedCharacterSequence(at: sel.location - 1)
|
||||
let expUnits = expectedUnitsReplacing(delRange, with: [], in: before)
|
||||
let expSel = NSRange(location: delRange.location, length: 0)
|
||||
performImeMutation(expectedUnits: expUnits, expectedSelected: expSel, expectedMarked: .some(nil)) {
|
||||
affine_ios_host_delete_backward(handle)
|
||||
}
|
||||
} else {
|
||||
performImeMutation {
|
||||
affine_ios_host_delete_backward(handle)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -249,19 +377,20 @@ final class MetalHostView: UIView, UITextInput {
|
||||
guard let affineRange = range as? AffineTextRange else {
|
||||
return nil
|
||||
}
|
||||
return backingText.substring(with: clampRange(affineRange.utf16Range))
|
||||
let text = currentAuthoritativeString
|
||||
let clamped = clampRange(affineRange.utf16Range, maxLen: text.length)
|
||||
return text.substring(with: clamped)
|
||||
}
|
||||
|
||||
func replace(_ range: UITextRange, withText text: String) {
|
||||
guard let affineRange = range as? AffineTextRange else {
|
||||
guard let affineRange = range as? AffineTextRange, let handle = hostHandle else {
|
||||
return
|
||||
}
|
||||
let clamped = clampRange(affineRange.utf16Range)
|
||||
backingText = backingText.replacingCharacters(in: clamped, with: text) as NSString
|
||||
let utf16 = Array(text.utf16)
|
||||
selectedUtf16Range = NSRange(location: clamped.location + utf16.count, length: 0)
|
||||
markedUtf16Range = nil
|
||||
if let handle = hostHandle {
|
||||
let before = currentAuthoritativeUtf16Units
|
||||
let expUnits = expectedUnitsReplacing(clamped, with: utf16, in: before)
|
||||
performImeMutation(expectedUnits: expUnits) {
|
||||
let cRange = AffineUtf16Range(
|
||||
location: UInt32(clamped.location),
|
||||
length: UInt32(clamped.length)
|
||||
@@ -270,64 +399,64 @@ final class MetalHostView: UIView, UITextInput {
|
||||
affine_ios_host_replace_range(handle, cRange, buf.baseAddress, buf.count)
|
||||
}
|
||||
}
|
||||
onSelectedRangeChanged?(selectedUtf16Range)
|
||||
}
|
||||
|
||||
var selectedTextRange: UITextRange? {
|
||||
get {
|
||||
AffineTextRange(utf16Range: clampRange(selectedUtf16Range))
|
||||
AffineTextRange(utf16Range: currentSelectedUtf16Range)
|
||||
}
|
||||
set {
|
||||
if let affineRange = newValue as? AffineTextRange {
|
||||
let clamped = clampRange(affineRange.utf16Range)
|
||||
selectedUtf16Range = clamped
|
||||
if let handle = hostHandle {
|
||||
affine_ios_host_set_selected_range(
|
||||
handle,
|
||||
AffineUtf16Range(location: UInt32(clamped.location), length: UInt32(clamped.length))
|
||||
)
|
||||
}
|
||||
onSelectedRangeChanged?(clamped)
|
||||
guard let affineRange = newValue as? AffineTextRange, let handle = hostHandle else {
|
||||
return
|
||||
}
|
||||
let clamped = clampRange(affineRange.utf16Range)
|
||||
performImeMutation(expectedUnits: currentAuthoritativeUtf16Units, expectedSelected: clamped) {
|
||||
affine_ios_host_set_selected_range(
|
||||
handle,
|
||||
AffineUtf16Range(location: UInt32(clamped.location), length: UInt32(clamped.length))
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var markedTextRange: UITextRange? {
|
||||
markedUtf16Range.map { AffineTextRange(utf16Range: clampRange($0)) }
|
||||
guard let range = currentMarkedUtf16Range else {
|
||||
return nil
|
||||
}
|
||||
return AffineTextRange(utf16Range: range)
|
||||
}
|
||||
|
||||
var markedTextStyle: [NSAttributedString.Key: Any]?
|
||||
|
||||
func setMarkedText(_ markedText: String?, selectedRange: NSRange) {
|
||||
guard let handle = hostHandle else {
|
||||
return
|
||||
}
|
||||
let text = markedText ?? ""
|
||||
let targetRange = clampRange(markedUtf16Range ?? selectedUtf16Range)
|
||||
backingText = backingText.replacingCharacters(in: targetRange, with: text) as NSString
|
||||
let utf16 = Array(text.utf16)
|
||||
let utf16Len = utf16.count
|
||||
let clampedLoc = max(0, min(selectedRange.location, utf16Len))
|
||||
let clampedLen = max(0, min(selectedRange.length, utf16Len - clampedLoc))
|
||||
if utf16Len > 0 {
|
||||
markedUtf16Range = NSRange(location: targetRange.location, length: utf16Len)
|
||||
selectedUtf16Range = NSRange(
|
||||
location: targetRange.location + clampedLoc,
|
||||
length: clampedLen
|
||||
)
|
||||
} else {
|
||||
markedUtf16Range = nil
|
||||
selectedUtf16Range = NSRange(location: targetRange.location, length: 0)
|
||||
}
|
||||
if let handle = hostHandle {
|
||||
let before = currentAuthoritativeUtf16Units
|
||||
let replaceRange = currentMarkedUtf16Range ?? currentSelectedUtf16Range
|
||||
let expUnits = expectedUnitsReplacing(replaceRange, with: utf16, in: before)
|
||||
let expSel = NSRange(location: replaceRange.location + clampedLoc, length: clampedLen)
|
||||
let expMarked: NSRange? = utf16.isEmpty
|
||||
? nil
|
||||
: NSRange(location: replaceRange.location, length: utf16Len)
|
||||
performImeMutation(expectedUnits: expUnits, expectedSelected: expSel, expectedMarked: .some(expMarked)) {
|
||||
let cRange = AffineUtf16Range(location: UInt32(clampedLoc), length: UInt32(clampedLen))
|
||||
utf16.withUnsafeBufferPointer { buf in
|
||||
affine_ios_host_set_marked_text(handle, buf.baseAddress, buf.count, cRange)
|
||||
}
|
||||
}
|
||||
onSelectedRangeChanged?(selectedUtf16Range)
|
||||
}
|
||||
|
||||
func unmarkText() {
|
||||
markedUtf16Range = nil
|
||||
if let handle = hostHandle {
|
||||
guard let handle = hostHandle else {
|
||||
return
|
||||
}
|
||||
performImeMutation(expectedUnits: currentAuthoritativeUtf16Units, expectedMarked: .some(nil)) {
|
||||
affine_ios_host_unmark_text(handle)
|
||||
}
|
||||
}
|
||||
@@ -337,7 +466,8 @@ final class MetalHostView: UIView, UITextInput {
|
||||
}
|
||||
|
||||
var endOfDocument: UITextPosition {
|
||||
AffineTextPosition(utf16Offset: backingText.length)
|
||||
let len = Int(hostHandle.map { affine_ios_host_utf16_len($0) } ?? 0)
|
||||
return AffineTextPosition(utf16Offset: len)
|
||||
}
|
||||
|
||||
func textRange(from fromPosition: UITextPosition, to toPosition: UITextPosition) -> UITextRange? {
|
||||
@@ -356,8 +486,9 @@ final class MetalHostView: UIView, UITextInput {
|
||||
guard let pos = position as? AffineTextPosition else {
|
||||
return nil
|
||||
}
|
||||
let maxLen = Int(hostHandle.map { affine_ios_host_utf16_len($0) } ?? 0)
|
||||
let next = pos.utf16Offset + offset
|
||||
guard next >= 0 && next <= backingText.length else {
|
||||
guard next >= 0 && next <= maxLen else {
|
||||
return nil
|
||||
}
|
||||
return AffineTextPosition(utf16Offset: next)
|
||||
@@ -422,13 +553,17 @@ final class MetalHostView: UIView, UITextInput {
|
||||
guard let pos = position as? AffineTextPosition else {
|
||||
return nil
|
||||
}
|
||||
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)))
|
||||
return AffineTextRange(
|
||||
utf16Range: clampRange(NSRange(location: 0, length: pos.utf16Offset), maxLen: maxLen)
|
||||
)
|
||||
case .right, .down:
|
||||
return AffineTextRange(
|
||||
utf16Range: clampRange(
|
||||
NSRange(location: pos.utf16Offset, length: max(0, backingText.length - pos.utf16Offset))
|
||||
NSRange(location: pos.utf16Offset, length: max(0, maxLen - pos.utf16Offset)),
|
||||
maxLen: maxLen
|
||||
)
|
||||
)
|
||||
@unknown default:
|
||||
@@ -543,32 +678,160 @@ final class MetalHostView: UIView, UITextInput {
|
||||
guard let pos = closestPosition(to: point) as? AffineTextPosition else {
|
||||
return nil
|
||||
}
|
||||
let len = backingText.length
|
||||
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 = backingText.rangeOfComposedCharacterSequence(at: idx)
|
||||
let cluster = text.rangeOfComposedCharacterSequence(at: idx)
|
||||
return AffineTextRange(utf16Range: cluster)
|
||||
}
|
||||
|
||||
private func clampRange(_ range: NSRange) -> NSRange {
|
||||
let maxLen = backingText.length
|
||||
let loc = max(0, min(range.location, maxLen))
|
||||
let len = max(0, min(range.length, maxLen - loc))
|
||||
// MARK: - UIKit Touch & Hardware Keyboard Forwarding
|
||||
|
||||
private func touchId(for touch: UITouch, remove: Bool) -> UInt64 {
|
||||
let key = ObjectIdentifier(touch)
|
||||
if let existing = activeTouchIds[key] {
|
||||
if remove {
|
||||
activeTouchIds.removeValue(forKey: key)
|
||||
}
|
||||
return existing
|
||||
}
|
||||
let assigned = nextTouchId
|
||||
nextTouchId &+= 1
|
||||
if !remove {
|
||||
activeTouchIds[key] = assigned
|
||||
}
|
||||
return assigned
|
||||
}
|
||||
|
||||
private static let topBarHeightPt: CGFloat = 53.0
|
||||
private static let panSlopPt: CGFloat = 10.0
|
||||
|
||||
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
|
||||
guard let handle = hostHandle else { return }
|
||||
for touch in touches {
|
||||
let loc = touch.location(in: self)
|
||||
let id = touchId(for: touch, remove: false)
|
||||
touchStartPoints[id] = loc
|
||||
touchExceededPanThreshold.remove(id)
|
||||
affine_ios_host_touch_event(handle, id, 0, Float(loc.x), Float(loc.y))
|
||||
}
|
||||
}
|
||||
|
||||
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
|
||||
guard let handle = hostHandle else { return }
|
||||
for touch in touches {
|
||||
let loc = touch.location(in: self)
|
||||
let id = touchId(for: touch, remove: false)
|
||||
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)
|
||||
}
|
||||
}
|
||||
affine_ios_host_touch_event(handle, id, 1, Float(loc.x), Float(loc.y))
|
||||
}
|
||||
}
|
||||
|
||||
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
|
||||
guard let handle = hostHandle else { return }
|
||||
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
|
||||
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 affine_ios_host_wants_software_keyboard(handle) {
|
||||
if endedEditableTap && !isFirstResponder {
|
||||
_ = becomeFirstResponder()
|
||||
}
|
||||
} else if isFirstResponder {
|
||||
_ = resignFirstResponder()
|
||||
}
|
||||
}
|
||||
|
||||
override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
|
||||
guard let handle = hostHandle else { return }
|
||||
for touch in touches {
|
||||
let loc = touch.location(in: self)
|
||||
let id = touchId(for: touch, remove: true)
|
||||
touchStartPoints.removeValue(forKey: id)
|
||||
touchExceededPanThreshold.remove(id)
|
||||
affine_ios_host_touch_event(handle, id, 3, Float(loc.x), Float(loc.y))
|
||||
}
|
||||
}
|
||||
|
||||
override func pressesBegan(_ presses: Set<UIPress>, 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
|
||||
}
|
||||
guard let handle = hostHandle else {
|
||||
super.pressesBegan(presses, with: event)
|
||||
return
|
||||
}
|
||||
var handled = false
|
||||
for press in presses {
|
||||
guard let key = press.key else { continue }
|
||||
let mods = key.modifierFlags
|
||||
let shift = mods.contains(.shift)
|
||||
let cmd = mods.contains(.command)
|
||||
let ctrl = mods.contains(.control)
|
||||
let alt = mods.contains(.alternate)
|
||||
let mapped: String?
|
||||
switch key.keyCode {
|
||||
case .keyboardLeftArrow: mapped = "left"
|
||||
case .keyboardRightArrow: mapped = "right"
|
||||
case .keyboardUpArrow: mapped = "up"
|
||||
case .keyboardDownArrow: mapped = "down"
|
||||
case .keyboardDeleteOrBackspace: mapped = "backspace"
|
||||
case .keyboardDeleteForward: mapped = "delete"
|
||||
case .keyboardReturnOrEnter: mapped = "enter"
|
||||
case .keyboardEscape: mapped = "escape"
|
||||
case .keyboardTab: mapped = "tab"
|
||||
case .keyboardZ where cmd: mapped = "z"
|
||||
default: mapped = nil
|
||||
}
|
||||
if let name = mapped {
|
||||
name.withCString { cKey in
|
||||
affine_ios_host_key_down(handle, cKey, nil, shift, cmd, ctrl, alt)
|
||||
}
|
||||
handled = true
|
||||
}
|
||||
}
|
||||
if !handled {
|
||||
super.pressesBegan(presses, with: event)
|
||||
}
|
||||
}
|
||||
|
||||
private func clampRange(_ range: NSRange, maxLen: Int? = nil) -> NSRange {
|
||||
let limit = maxLen ?? Int(hostHandle.map { affine_ios_host_utf16_len($0) } ?? 0)
|
||||
let loc = max(0, min(range.location, limit))
|
||||
let len = max(0, min(range.length, limit - loc))
|
||||
return NSRange(location: loc, length: len)
|
||||
}
|
||||
}
|
||||
|
||||
final class MetalHostViewController: UIViewController, UIEditMenuInteractionDelegate {
|
||||
private let hostView = MetalHostView()
|
||||
private let textPreviewView = HostTextPreviewView()
|
||||
private let selectionOverlayView = SelectionOverlayView()
|
||||
private let keyboardAvoidanceCoordinator = KeyboardAvoidanceCoordinator()
|
||||
private let pdfRendererBridge = PdfRendererBridge()
|
||||
private let textRenderingBridge = TextRenderingBridge()
|
||||
private let hapticsBridge = HapticsBridge()
|
||||
private let bootstrapCoordinator = HostBootstrapCoordinator()
|
||||
private var editorMetalLayer: CAMetalLayer?
|
||||
private var editMenuInteraction: UIEditMenuInteraction?
|
||||
private(set) var presentedMenuAnchorRect: CGRect?
|
||||
private var lastSyncedInsets = AffineWindowInsets(
|
||||
@@ -581,8 +844,6 @@ final class MetalHostViewController: UIViewController, UIEditMenuInteractionDele
|
||||
private(set) var lastBootstrapError: Error?
|
||||
private var bootstrapCompleted = false
|
||||
private var hostHandle: OpaquePointer?
|
||||
private var metalDevice: MTLDevice?
|
||||
private var commandQueue: MTLCommandQueue?
|
||||
private var displayLink: CADisplayLink?
|
||||
private var displayLinkProxy: DisplayLinkProxy?
|
||||
|
||||
@@ -611,27 +872,50 @@ final class MetalHostViewController: UIViewController, UIEditMenuInteractionDele
|
||||
}
|
||||
|
||||
override func loadView() {
|
||||
view = hostView
|
||||
let root = UIView()
|
||||
root.backgroundColor = .white
|
||||
view = root
|
||||
}
|
||||
|
||||
override func viewDidLoad() {
|
||||
super.viewDidLoad()
|
||||
configureMetalLayer()
|
||||
view.backgroundColor = .white
|
||||
hostView.isMultipleTouchEnabled = true
|
||||
hostView.backgroundColor = .white
|
||||
let initialFrame = view.bounds.inset(by: view.safeAreaInsets)
|
||||
let clampedInitial = CGRect(
|
||||
x: initialFrame.origin.x,
|
||||
y: initialFrame.origin.y,
|
||||
width: max(initialFrame.width, 1.0),
|
||||
height: max(initialFrame.height, 1.0)
|
||||
)
|
||||
hostView.frame = clampedInitial
|
||||
view.addSubview(hostView)
|
||||
|
||||
let scale = Float(view.window?.screen.scale ?? UIScreen.main.scale)
|
||||
let rawLayer = Unmanaged.passUnretained(hostView.metalLayer).toOpaque()
|
||||
let handle = affine_ios_host_create(
|
||||
rawLayer,
|
||||
Float(view.bounds.width),
|
||||
Float(view.bounds.height),
|
||||
Float(max(initialFrame.width, 390.0)),
|
||||
Float(max(initialFrame.height, 844.0)),
|
||||
scale
|
||||
)
|
||||
hostHandle = handle
|
||||
hostView.hostHandle = handle
|
||||
hostView.attachTextInputObserver()
|
||||
|
||||
if let handle {
|
||||
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) {
|
||||
let metalLayer = Unmanaged<CAMetalLayer>.fromOpaque(rawEditorLayer).takeUnretainedValue()
|
||||
metalLayer.frame = hostView.bounds
|
||||
metalLayer.contentsScale = CGFloat(scale)
|
||||
hostView.layer.insertSublayer(metalLayer, at: 0)
|
||||
editorMetalLayer = metalLayer
|
||||
}
|
||||
}
|
||||
applyClearColor(TextRenderingBridge.defaultClearColorRgba)
|
||||
textPreviewView.renderer = textRenderingBridge
|
||||
textPreviewView.frame = hostView.bounds
|
||||
textPreviewView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
|
||||
hostView.addSubview(textPreviewView)
|
||||
|
||||
selectionOverlayView.hostHandle = handle
|
||||
selectionOverlayView.frame = hostView.bounds
|
||||
@@ -660,12 +944,31 @@ final class MetalHostViewController: UIViewController, UIEditMenuInteractionDele
|
||||
guard let interaction = self.editMenuInteraction else {
|
||||
return
|
||||
}
|
||||
if let rect = anchorRect {
|
||||
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: rect.midX, y: rect.minY)
|
||||
sourcePoint: CGPoint(x: clampedX, y: clampedY)
|
||||
)
|
||||
interaction.presentEditMenu(with: config)
|
||||
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()
|
||||
}
|
||||
@@ -708,29 +1011,49 @@ final class MetalHostViewController: UIViewController, UIEditMenuInteractionDele
|
||||
|
||||
override func viewSafeAreaInsetsDidChange() {
|
||||
super.viewSafeAreaInsetsDidChange()
|
||||
updateEditorMetalLayout()
|
||||
sampleInsets(timestamp: CACurrentMediaTime())
|
||||
}
|
||||
|
||||
override func viewDidLayoutSubviews() {
|
||||
super.viewDidLayoutSubviews()
|
||||
private func updateEditorMetalLayout() {
|
||||
let scale = view.window?.screen.scale ?? UIScreen.main.scale
|
||||
let editorFrame = view.bounds.inset(by: view.safeAreaInsets)
|
||||
let clampedWidth = max(editorFrame.width, 1.0)
|
||||
let clampedHeight = max(editorFrame.height, 1.0)
|
||||
let clampedFrame = CGRect(
|
||||
x: editorFrame.origin.x,
|
||||
y: editorFrame.origin.y,
|
||||
width: clampedWidth,
|
||||
height: clampedHeight
|
||||
)
|
||||
hostView.frame = clampedFrame
|
||||
hostView.metalLayer.contentsScale = scale
|
||||
hostView.metalLayer.drawableSize = CGSize(
|
||||
width: view.bounds.width * scale,
|
||||
height: view.bounds.height * scale
|
||||
width: clampedWidth * scale,
|
||||
height: clampedHeight * scale
|
||||
)
|
||||
textPreviewView.frame = hostView.bounds
|
||||
if let editorLayer = editorMetalLayer {
|
||||
CATransaction.begin()
|
||||
CATransaction.setDisableActions(true)
|
||||
editorLayer.frame = hostView.bounds
|
||||
editorLayer.contentsScale = scale
|
||||
CATransaction.commit()
|
||||
}
|
||||
selectionOverlayView.frame = hostView.bounds
|
||||
if let handle = hostHandle {
|
||||
affine_ios_host_resize(
|
||||
handle,
|
||||
Float(view.bounds.width),
|
||||
Float(view.bounds.height),
|
||||
Float(clampedWidth),
|
||||
Float(clampedHeight),
|
||||
Float(scale)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
override func viewDidLayoutSubviews() {
|
||||
super.viewDidLayoutSubviews()
|
||||
updateEditorMetalLayout()
|
||||
sampleInsets(timestamp: CACurrentMediaTime())
|
||||
refreshTextPreview()
|
||||
let currentRange = hostView.currentSelectedUtf16Range
|
||||
if currentRange.length > 0 {
|
||||
syncSelectionOverlay(for: currentRange)
|
||||
@@ -744,8 +1067,11 @@ final class MetalHostViewController: UIViewController, UIEditMenuInteractionDele
|
||||
keyboardAvoidanceCoordinator.stopObserving()
|
||||
keyboardAvoidanceCoordinator.hostHandle = nil
|
||||
NotificationCenter.default.removeObserver(self)
|
||||
hostView.detachTextInputObserver()
|
||||
hostView.hostHandle = nil
|
||||
selectionOverlayView.hostHandle = nil
|
||||
editorMetalLayer?.removeFromSuperlayer()
|
||||
editorMetalLayer = nil
|
||||
if let handle = hostHandle {
|
||||
textRenderingBridge.detach()
|
||||
pdfRendererBridge.detach(from: handle)
|
||||
@@ -757,21 +1083,16 @@ final class MetalHostViewController: UIViewController, UIEditMenuInteractionDele
|
||||
|
||||
private func applyClearColor(_ rgba: UInt32) {
|
||||
let bg = textRenderingBridge.applyClearColorRgba(rgba)
|
||||
if view.backgroundColor != bg {
|
||||
view.backgroundColor = bg
|
||||
}
|
||||
if hostView.backgroundColor != bg {
|
||||
hostView.backgroundColor = bg
|
||||
textPreviewView.setNeedsDisplay()
|
||||
}
|
||||
}
|
||||
|
||||
private func refreshTextPreview() {
|
||||
textPreviewView.utf16Units = hostView.currentBackingUtf16Units
|
||||
textPreviewView.selectedRange = hostView.currentSelectedUtf16Range
|
||||
textPreviewView.hostInsets = lastSyncedInsets
|
||||
}
|
||||
|
||||
private func syncSelectionOverlay(for range: NSRange) {
|
||||
refreshTextPreview()
|
||||
guard let handle = hostHandle else {
|
||||
guard let handle = hostHandle, selectionOverlayView.currentState.active_drag_handle == 0 else {
|
||||
return
|
||||
}
|
||||
let cRange = AffineUtf16Range(location: UInt32(range.location), length: UInt32(range.length))
|
||||
@@ -809,7 +1130,66 @@ final class MetalHostViewController: UIViewController, UIEditMenuInteractionDele
|
||||
_ interaction: UIEditMenuInteraction,
|
||||
targetRectFor configuration: UIEditMenuConfiguration
|
||||
) -> CGRect {
|
||||
presentedMenuAnchorRect ?? .null
|
||||
guard
|
||||
let rect = presentedMenuAnchorRect,
|
||||
!rect.isNull,
|
||||
rect.origin.x.isFinite,
|
||||
rect.origin.y.isFinite,
|
||||
rect.size.width.isFinite,
|
||||
rect.size.height.isFinite
|
||||
else {
|
||||
return CGRect(
|
||||
x: max(hostView.bounds.midX, 1.0),
|
||||
y: max(hostView.bounds.midY, 1.0),
|
||||
width: 1.0,
|
||||
height: 1.0
|
||||
)
|
||||
}
|
||||
return CGRect(
|
||||
x: min(max(rect.origin.x, 0.0), max(hostView.bounds.width - 1.0, 0.0)),
|
||||
y: min(max(rect.origin.y, 0.0), max(hostView.bounds.height - 1.0, 0.0)),
|
||||
width: max(rect.size.width, 1.0),
|
||||
height: max(rect.size.height, 1.0)
|
||||
)
|
||||
}
|
||||
|
||||
func editMenuInteraction(
|
||||
_ interaction: UIEditMenuInteraction,
|
||||
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(
|
||||
@@ -846,7 +1226,6 @@ final class MetalHostViewController: UIViewController, UIEditMenuInteractionDele
|
||||
hostView.updateSelectedRangeFromOverlay(
|
||||
NSRange(location: Int(nextRange.location), length: Int(nextRange.length))
|
||||
)
|
||||
refreshTextPreview()
|
||||
_ = affine_ios_host_trigger_haptic(handle, AffineHapticPatternSwift.selectionChanged.rawValue)
|
||||
}
|
||||
var cStart = AffineRect()
|
||||
@@ -871,16 +1250,6 @@ final class MetalHostViewController: UIViewController, UIEditMenuInteractionDele
|
||||
return (targetOffset, startCaret, endCaret)
|
||||
}
|
||||
|
||||
private func configureMetalLayer() {
|
||||
let device = MTLCreateSystemDefaultDevice()
|
||||
metalDevice = device
|
||||
commandQueue = device?.makeCommandQueue()
|
||||
hostView.metalLayer.device = device
|
||||
hostView.metalLayer.pixelFormat = .bgra8Unorm
|
||||
hostView.metalLayer.framebufferOnly = true
|
||||
hostView.metalLayer.isOpaque = true
|
||||
}
|
||||
|
||||
private func startDisplayLink() {
|
||||
let proxy = DisplayLinkProxy(target: self)
|
||||
displayLinkProxy = proxy
|
||||
@@ -892,41 +1261,13 @@ final class MetalHostViewController: UIViewController, UIEditMenuInteractionDele
|
||||
|
||||
func handleDisplayLinkTick(_ link: CADisplayLink) {
|
||||
sampleInsets(timestamp: link.timestamp)
|
||||
guard
|
||||
let handle = hostHandle,
|
||||
affine_ios_host_is_dirty(handle),
|
||||
let queue = commandQueue,
|
||||
let drawable = hostView.metalLayer.nextDrawable(),
|
||||
let commandBuffer = queue.makeCommandBuffer()
|
||||
else {
|
||||
guard let handle = hostHandle, affine_ios_host_is_dirty(handle) else {
|
||||
return
|
||||
}
|
||||
let clearRgba = affine_ios_host_render_frame(handle, link.timestamp)
|
||||
guard clearRgba != 0 else {
|
||||
return
|
||||
if clearRgba != 0 {
|
||||
applyClearColor(clearRgba)
|
||||
}
|
||||
applyClearColor(clearRgba)
|
||||
let red = Double((clearRgba >> 24) & 0xFF) / 255.0
|
||||
let green = Double((clearRgba >> 16) & 0xFF) / 255.0
|
||||
let blue = Double((clearRgba >> 8) & 0xFF) / 255.0
|
||||
let alpha = Double(clearRgba & 0xFF) / 255.0
|
||||
let pass = MTLRenderPassDescriptor()
|
||||
pass.colorAttachments[0].texture = drawable.texture
|
||||
pass.colorAttachments[0].loadAction = .clear
|
||||
pass.colorAttachments[0].storeAction = .store
|
||||
pass.colorAttachments[0].clearColor = MTLClearColor(
|
||||
red: red,
|
||||
green: green,
|
||||
blue: blue,
|
||||
alpha: alpha
|
||||
)
|
||||
guard let encoder = commandBuffer.makeRenderCommandEncoder(descriptor: pass) else {
|
||||
affine_ios_host_request_frame(handle)
|
||||
return
|
||||
}
|
||||
encoder.endEncoding()
|
||||
commandBuffer.present(drawable)
|
||||
commandBuffer.commit()
|
||||
}
|
||||
|
||||
private func observeNotifications() {
|
||||
@@ -969,7 +1310,6 @@ final class MetalHostViewController: UIViewController, UIEditMenuInteractionDele
|
||||
|| next.ime_bottom != lastSyncedInsets.ime_bottom
|
||||
if changed {
|
||||
lastSyncedInsets = next
|
||||
refreshTextPreview()
|
||||
if let handle = hostHandle,
|
||||
selectionOverlayView.currentState.has_selection
|
||||
|| selectionOverlayView.lastMenuAnchorRect != nil
|
||||
|
||||
@@ -821,62 +821,6 @@ final class TextRenderingBridge {
|
||||
}
|
||||
}
|
||||
|
||||
/// Lightweight transparent S3 transition preview view mounted above `MetalHostView`
|
||||
/// and below `SelectionOverlayView`. Removed in S4 when GPU `blocksuite-editor` attaches.
|
||||
final class HostTextPreviewView: UIView {
|
||||
weak var renderer: TextRenderingBridge?
|
||||
var utf16Units: [UInt16] = [] {
|
||||
didSet {
|
||||
if oldValue != utf16Units { setNeedsDisplay() }
|
||||
}
|
||||
}
|
||||
var selectedRange = NSRange(location: 0, length: 0) {
|
||||
didSet {
|
||||
if oldValue != selectedRange { setNeedsDisplay() }
|
||||
}
|
||||
}
|
||||
var hostInsets = AffineWindowInsets(
|
||||
safe_top: 0,
|
||||
safe_right: 0,
|
||||
safe_bottom: 0,
|
||||
safe_left: 0,
|
||||
ime_bottom: 0
|
||||
) {
|
||||
didSet { setNeedsDisplay() }
|
||||
}
|
||||
|
||||
override init(frame: CGRect) {
|
||||
super.init(frame: frame)
|
||||
backgroundColor = .clear
|
||||
isOpaque = false
|
||||
isUserInteractionEnabled = false
|
||||
}
|
||||
|
||||
required init?(coder: NSCoder) {
|
||||
super.init(coder: coder)
|
||||
backgroundColor = .clear
|
||||
isOpaque = false
|
||||
isUserInteractionEnabled = false
|
||||
}
|
||||
|
||||
override func draw(_ rect: CGRect) {
|
||||
guard
|
||||
let renderer,
|
||||
!utf16Units.isEmpty,
|
||||
let ctx = UIGraphicsGetCurrentContext()
|
||||
else {
|
||||
return
|
||||
}
|
||||
renderer.drawShapedText(
|
||||
in: ctx,
|
||||
utf16Units: utf16Units,
|
||||
selectedRange: selectedRange,
|
||||
viewportWidth: Float(bounds.width),
|
||||
insets: hostInsets
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private func affineTextCaretRectTrampoline(
|
||||
utf16Ptr: UnsafePointer<UInt16>?,
|
||||
utf16Len: Int,
|
||||
|
||||
@@ -271,6 +271,58 @@ AffineUtf16Range affine_ios_host_selected_range(const AffineIosHost *host);
|
||||
|
||||
AffineUtf16Range affine_ios_host_marked_range(const AffineIosHost *host);
|
||||
|
||||
typedef void (*AffineTextInputChangedCallback)(uint8_t change_kind, void *user_data);
|
||||
|
||||
void *affine_ios_host_metal_layer(const AffineIosHost *host);
|
||||
|
||||
size_t affine_ios_host_utf16_len(const AffineIosHost *host);
|
||||
|
||||
size_t affine_ios_host_copy_utf16(
|
||||
const AffineIosHost *host,
|
||||
uint16_t *out_ptr,
|
||||
size_t capacity);
|
||||
|
||||
void affine_ios_host_touch_event(
|
||||
AffineIosHost *host,
|
||||
uint64_t touch_id,
|
||||
uint8_t phase,
|
||||
float x,
|
||||
float y);
|
||||
|
||||
void affine_ios_host_key_down(
|
||||
AffineIosHost *host,
|
||||
const char *key,
|
||||
const char *key_char,
|
||||
bool shift,
|
||||
bool cmd,
|
||||
bool ctrl,
|
||||
bool alt);
|
||||
|
||||
void affine_ios_host_set_form_factor(
|
||||
AffineIosHost *host,
|
||||
uint8_t form_factor);
|
||||
|
||||
bool affine_ios_host_edgeless_readonly(const AffineIosHost *host);
|
||||
|
||||
bool affine_ios_host_database_readonly(const AffineIosHost *host);
|
||||
|
||||
bool affine_ios_host_wants_software_keyboard(const AffineIosHost *host);
|
||||
|
||||
void affine_ios_host_set_mode(
|
||||
AffineIosHost *host,
|
||||
uint8_t mode);
|
||||
|
||||
void affine_ios_host_set_text_input_callback(
|
||||
AffineIosHost *host,
|
||||
AffineTextInputChangedCallback cb,
|
||||
void *user_data);
|
||||
|
||||
uint64_t affine_ios_host_text_input_change_seq(const AffineIosHost *host);
|
||||
|
||||
void affine_ios_host_reset_empty_doc(AffineIosHost *host);
|
||||
|
||||
void affine_ios_host_load_showcase_doc(AffineIosHost *host);
|
||||
|
||||
char *affine_ios_auth_canonical_endpoint(const char *endpoint);
|
||||
|
||||
char *affine_ios_auth_legacy_storage_endpoint_key(const char *endpoint);
|
||||
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
# Build and assemble an installable iOS Simulator `.app` bundle (`AffineIosHost.app`)
|
||||
# with zero CocoaPods and zero Xcode project files.
|
||||
#
|
||||
# Usage:
|
||||
# ./packages/frontend/hosts/ios/scripts/package-sim-app.sh [debug|release] [out_dir]
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
IOS_HOST_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
|
||||
REPO_ROOT="$(cd "$IOS_HOST_DIR/../../../.." && pwd)"
|
||||
MANIFEST="$REPO_ROOT/packages/frontend/Cargo.toml"
|
||||
|
||||
PROFILE="${1:-debug}"
|
||||
OUT_DIR="${2:-$REPO_ROOT/packages/frontend/target/ios-sim-app}"
|
||||
TARGET="aarch64-apple-ios-sim"
|
||||
|
||||
PROFILE_ARGS=()
|
||||
PROFILE_SUBDIR="debug"
|
||||
if [ "$PROFILE" = "release" ]; then
|
||||
PROFILE_ARGS+=(--release)
|
||||
PROFILE_SUBDIR="release"
|
||||
fi
|
||||
|
||||
echo "==> Building libaffine_ios_host.a ($TARGET, $PROFILE)"
|
||||
CARGO_ENCODED_RUSTFLAGS="" rustup run 1.98.1 cargo build \
|
||||
--locked \
|
||||
--manifest-path "$MANIFEST" \
|
||||
-p affine-ios-host \
|
||||
--target "$TARGET" \
|
||||
"${PROFILE_ARGS[@]}"
|
||||
|
||||
LIB_DIR="$REPO_ROOT/packages/frontend/target/$TARGET/$PROFILE_SUBDIR"
|
||||
test -s "$LIB_DIR/libaffine_ios_host.a"
|
||||
|
||||
APP_DIR="$OUT_DIR/AffineIosHost.app"
|
||||
rm -rf "$APP_DIR"
|
||||
mkdir -p "$APP_DIR"
|
||||
|
||||
SDK="$(xcrun --sdk iphonesimulator --show-sdk-path)"
|
||||
echo "==> Linking AffineIosHost against iOS Simulator SDK: $SDK"
|
||||
swiftc -emit-executable \
|
||||
-sdk "$SDK" \
|
||||
-target arm64-apple-ios16.0-simulator \
|
||||
-import-objc-header "$IOS_HOST_DIR/include/affine_mobile_host.h" \
|
||||
-L "$LIB_DIR" \
|
||||
-laffine_ios_host \
|
||||
-framework UIKit \
|
||||
-framework QuartzCore \
|
||||
-framework Metal \
|
||||
-framework WebKit \
|
||||
-framework PDFKit \
|
||||
-framework CoreText \
|
||||
-framework CoreGraphics \
|
||||
-framework CoreVideo \
|
||||
-framework CoreFoundation \
|
||||
-framework Foundation \
|
||||
-framework UniformTypeIdentifiers \
|
||||
-o "$APP_DIR/AffineIosHost" \
|
||||
"$IOS_HOST_DIR"/Sources/*.swift
|
||||
|
||||
cp "$IOS_HOST_DIR/Info.plist" "$APP_DIR/Info.plist"
|
||||
printf 'APPL????' > "$APP_DIR/PkgInfo"
|
||||
codesign --force --sign - "$APP_DIR"
|
||||
|
||||
test -s "$APP_DIR/AffineIosHost"
|
||||
test -s "$APP_DIR/Info.plist"
|
||||
echo "==> Assembled iOS Simulator bundle: $APP_DIR"
|
||||
@@ -0,0 +1,184 @@
|
||||
//! Deterministic non-iOS host dispatcher, atlas, and text system for `affine-ios-host` tests.
|
||||
|
||||
use std::{borrow::Cow, collections::VecDeque, sync::Mutex, time::Duration};
|
||||
|
||||
use anyhow::Result;
|
||||
use ui::scheduler::{Clock, TestClock};
|
||||
use ui::{
|
||||
AtlasKey, AtlasTextureId, AtlasTextureKind, AtlasTile, BaseDirection, Bounds, DevicePixels,
|
||||
Font, FontId, FontMetrics, FontRun, GlyphId, LineLayout, Pixels, PlatformAtlas,
|
||||
PlatformDispatcher, PlatformTextSystem, Priority, RenderGlyphParams, RunnableVariant,
|
||||
ShapedGlyph, ShapedRun, Size, TextRenderingMode, TileId, point, px, size,
|
||||
};
|
||||
|
||||
pub(crate) struct SyncHostDispatcher {
|
||||
clock: TestClock,
|
||||
queue: Mutex<VecDeque<RunnableVariant>>,
|
||||
}
|
||||
|
||||
impl SyncHostDispatcher {
|
||||
pub(crate) fn new() -> Self {
|
||||
Self {
|
||||
clock: TestClock::new(),
|
||||
queue: Mutex::new(VecDeque::new()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl PlatformDispatcher for SyncHostDispatcher {
|
||||
fn is_main_thread(&self) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn now(&self) -> ui::scheduler::Instant {
|
||||
self.clock.advance(Duration::from_millis(16));
|
||||
self.clock.now()
|
||||
}
|
||||
|
||||
fn dispatch(&self, runnable: RunnableVariant, _priority: Priority) {
|
||||
if let Ok(mut q) = self.queue.lock() {
|
||||
q.push_back(runnable);
|
||||
}
|
||||
}
|
||||
|
||||
fn dispatch_on_main_thread(&self, runnable: RunnableVariant, _priority: Priority) {
|
||||
if let Ok(mut q) = self.queue.lock() {
|
||||
q.push_back(runnable);
|
||||
}
|
||||
}
|
||||
|
||||
fn dispatch_after(&self, _duration: Duration, _runnable: RunnableVariant) {}
|
||||
|
||||
fn spawn_realtime(&self, f: Box<dyn FnOnce() + Send>) {
|
||||
f();
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct FallbackAtlas;
|
||||
|
||||
impl PlatformAtlas for FallbackAtlas {
|
||||
fn get_or_insert_with<'a>(
|
||||
&self,
|
||||
_key: AtlasKey,
|
||||
_build: &mut dyn FnMut() -> Result<Option<(Size<DevicePixels>, Cow<'a, [u8]>)>>,
|
||||
) -> Result<Option<AtlasTile>> {
|
||||
Ok(Some(AtlasTile {
|
||||
texture_id: AtlasTextureId {
|
||||
index: 0,
|
||||
kind: AtlasTextureKind::Monochrome,
|
||||
},
|
||||
tile_id: TileId(0),
|
||||
padding: 0,
|
||||
bounds: Bounds::new(
|
||||
point(DevicePixels(0), DevicePixels(0)),
|
||||
size(DevicePixels(1), DevicePixels(1)),
|
||||
),
|
||||
}))
|
||||
}
|
||||
|
||||
fn remove(&self, _key: &AtlasKey) {}
|
||||
}
|
||||
|
||||
pub(crate) struct FallbackTextSystem;
|
||||
|
||||
impl PlatformTextSystem for FallbackTextSystem {
|
||||
fn add_fonts(&self, _fonts: Vec<Cow<'static, [u8]>>) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn all_font_names(&self) -> Vec<String> {
|
||||
vec!["Inter".to_string(), "IBM Plex Mono".to_string()]
|
||||
}
|
||||
|
||||
fn font_id(&self, _descriptor: &Font) -> Result<FontId> {
|
||||
Ok(FontId(0))
|
||||
}
|
||||
|
||||
fn font_metrics(&self, _font_id: FontId) -> FontMetrics {
|
||||
FontMetrics {
|
||||
units_per_em: 1000,
|
||||
ascent: 800.0,
|
||||
descent: -200.0,
|
||||
line_gap: 0.0,
|
||||
underline_position: -100.0,
|
||||
underline_thickness: 50.0,
|
||||
cap_height: 700.0,
|
||||
x_height: 500.0,
|
||||
bounding_box: Bounds::new(point(0.0, -200.0), size(600.0, 1000.0)),
|
||||
}
|
||||
}
|
||||
|
||||
fn typographic_bounds(&self, _font_id: FontId, _glyph_id: GlyphId) -> Result<Bounds<f32>> {
|
||||
Ok(Bounds::new(point(0.0, -200.0), size(600.0, 1000.0)))
|
||||
}
|
||||
|
||||
fn advance(&self, _font_id: FontId, _glyph_id: GlyphId) -> Result<Size<f32>> {
|
||||
Ok(size(600.0, 0.0))
|
||||
}
|
||||
|
||||
fn glyph_for_char(&self, _font_id: FontId, ch: char) -> Option<GlyphId> {
|
||||
Some(GlyphId(ch as u32))
|
||||
}
|
||||
|
||||
fn glyph_raster_bounds(&self, _params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>> {
|
||||
Ok(Bounds::new(
|
||||
point(DevicePixels(0), DevicePixels(0)),
|
||||
size(DevicePixels(8), DevicePixels(14)),
|
||||
))
|
||||
}
|
||||
|
||||
fn rasterize_glyph(
|
||||
&self,
|
||||
_params: &RenderGlyphParams,
|
||||
raster_bounds: Bounds<DevicePixels>,
|
||||
) -> Result<(Size<DevicePixels>, Vec<u8>)> {
|
||||
let w = raster_bounds.size.width.0.max(1) as usize;
|
||||
let h = raster_bounds.size.height.0.max(1) as usize;
|
||||
Ok((raster_bounds.size, vec![0u8; w * h]))
|
||||
}
|
||||
|
||||
fn layout_line(&self, text: &str, font_size: Pixels, runs: &[FontRun]) -> LineLayout {
|
||||
let cell = f32::from(font_size) * 0.56;
|
||||
let mut x = 0.0f32;
|
||||
let mut shaped_runs = Vec::new();
|
||||
let mut offset = 0usize;
|
||||
for run in runs {
|
||||
let end = (offset + run.len).min(text.len());
|
||||
let slice = &text[offset..end];
|
||||
let mut glyphs = Vec::new();
|
||||
for (rel_idx, ch) in slice.char_indices() {
|
||||
let adv = if ch == ' ' { cell * 0.65 } else { cell };
|
||||
glyphs.push(ShapedGlyph {
|
||||
id: GlyphId(ch as u32),
|
||||
position: point(px(x), px(0.0)),
|
||||
index: offset + rel_idx,
|
||||
is_emoji: false,
|
||||
});
|
||||
x += adv;
|
||||
}
|
||||
shaped_runs.push(ShapedRun {
|
||||
font_id: run.font_id,
|
||||
glyphs,
|
||||
bidi_level: 0,
|
||||
});
|
||||
offset = end;
|
||||
}
|
||||
LineLayout {
|
||||
font_size,
|
||||
width: px(x),
|
||||
ascent: px(f32::from(font_size) * 0.8),
|
||||
descent: px(f32::from(font_size) * 0.2),
|
||||
runs: shaped_runs,
|
||||
len: text.len(),
|
||||
base_direction: BaseDirection::Ltr,
|
||||
}
|
||||
}
|
||||
|
||||
fn recommended_rendering_mode(
|
||||
&self,
|
||||
_font_id: FontId,
|
||||
_font_size: Pixels,
|
||||
) -> TextRenderingMode {
|
||||
TextRenderingMode::Grayscale
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,771 @@
|
||||
//! Platform and window bridge mounting the pure-Rust GPU `PlaygroundView`
|
||||
//! inside the iOS thin host without modifying `packages/ui/ui/src/**`.
|
||||
//!
|
||||
//! On `target_os = "ios"`, `IosEditorPlatform` and `IosEditorWindow` reuse
|
||||
//! `ui::platform::apple::{AppleDispatcher, AppleTextSystem, metal_renderer::MetalRenderer}`
|
||||
//! and expose `MetalRenderer::layer_ptr()` (`CAMetalLayer`) directly to UIKit.
|
||||
//! On non-iOS hosts (`cargo test -p affine-ios-host`), a deterministic in-process
|
||||
//! platform drives the exact same `PlaygroundView` and `PlatformInputHandler`.
|
||||
|
||||
use std::{
|
||||
cell::RefCell,
|
||||
ffi::{OsString, c_void},
|
||||
path::{Path, PathBuf},
|
||||
rc::Rc,
|
||||
sync::Arc,
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
use anyhow::Result;
|
||||
use futures::channel::oneshot;
|
||||
#[cfg(target_os = "ios")]
|
||||
use parking_lot::Mutex;
|
||||
use raw_window_handle::{
|
||||
DisplayHandle, HandleError, HasDisplayHandle, HasWindowHandle, RawDisplayHandle,
|
||||
UiKitDisplayHandle, WindowHandle,
|
||||
};
|
||||
use smallvec::SmallVec;
|
||||
#[cfg(target_os = "ios")]
|
||||
use ui::DevicePixels;
|
||||
#[cfg(target_os = "ios")]
|
||||
use ui::apple::{
|
||||
AppleDispatcher, AppleTextSystem,
|
||||
metal_renderer::{self, InstanceBufferPool, MetalRenderer},
|
||||
};
|
||||
use ui::{
|
||||
Action, ActivityGuard, AnyWindowHandle, BackgroundExecutor, Bounds, Capslock, ClipboardItem,
|
||||
CursorStyle, DispatchEventResult, DisplayId, DummyKeyboardMapper, ForegroundExecutor, GpuSpecs,
|
||||
Keymap, Menu, MenuItem, Modifiers, OperatingSystem, PathPromptOptions, Pixels, Platform,
|
||||
PlatformAtlas, PlatformDisplay, PlatformInfo, PlatformInput, PlatformInputHandler,
|
||||
PlatformKeyboardLayout, PlatformKeyboardMapper, PlatformTarget, PlatformTextSystem,
|
||||
PlatformWindow, Point, PromptButton, PromptLevel, RequestFrameOptions, Scene, Size, Task,
|
||||
TextInputConfiguration, TextInputStateChange, ThermalState, WindowAppearance,
|
||||
WindowBackgroundAppearance, WindowBounds, WindowControlArea, WindowInsets, WindowParams,
|
||||
WindowVisibility, point, px, size,
|
||||
};
|
||||
use uuid::Uuid;
|
||||
|
||||
#[cfg(not(target_os = "ios"))]
|
||||
use super::editor_fallback as fallback;
|
||||
|
||||
struct IosEditorKeyboardLayout;
|
||||
|
||||
impl PlatformKeyboardLayout for IosEditorKeyboardLayout {
|
||||
fn id(&self) -> &str {
|
||||
"ios.editor"
|
||||
}
|
||||
|
||||
fn name(&self) -> &str {
|
||||
"iOS"
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct IosEditorDisplay {
|
||||
bounds: Bounds<Pixels>,
|
||||
}
|
||||
|
||||
impl PlatformDisplay for IosEditorDisplay {
|
||||
fn id(&self) -> DisplayId {
|
||||
DisplayId::new(0)
|
||||
}
|
||||
|
||||
fn uuid(&self) -> Result<Uuid> {
|
||||
Ok(Uuid::nil())
|
||||
}
|
||||
|
||||
fn bounds(&self) -> Bounds<Pixels> {
|
||||
self.bounds
|
||||
}
|
||||
|
||||
fn refresh_interval(&self) -> Option<Duration> {
|
||||
Some(Duration::from_secs(1) / 120)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) type TextInputObserver = Box<dyn Fn(TextInputStateChange)>;
|
||||
|
||||
pub(crate) struct IosEditorWindowState {
|
||||
pub(crate) bounds: Bounds<Pixels>,
|
||||
pub(crate) scale_factor: f32,
|
||||
pub(crate) insets: WindowInsets,
|
||||
pub(crate) input_handler: Option<PlatformInputHandler>,
|
||||
pub(crate) request_frame: Option<Box<dyn FnMut(RequestFrameOptions)>>,
|
||||
pub(crate) input: Option<Box<dyn FnMut(PlatformInput) -> DispatchEventResult>>,
|
||||
pub(crate) resize: Option<Box<dyn FnMut(Size<Pixels>, f32)>>,
|
||||
pub(crate) visual_viewport_changed: Option<Box<dyn FnMut()>>,
|
||||
pub(crate) appearance_changed: Option<Box<dyn FnMut()>>,
|
||||
pub(crate) active_status_change: Option<Box<dyn FnMut(bool)>>,
|
||||
pub(crate) visibility_change: Option<Box<dyn FnMut(WindowVisibility)>>,
|
||||
pub(crate) close: Option<Box<dyn FnOnce()>>,
|
||||
pub(crate) mouse_position: Point<Pixels>,
|
||||
pub(crate) modifiers: Modifiers,
|
||||
pub(crate) ime_position: Option<Bounds<Pixels>>,
|
||||
pub(crate) dirty: bool,
|
||||
pub(crate) text_input_change_seq: u64,
|
||||
pub(crate) last_text_input_change: Option<TextInputStateChange>,
|
||||
pub(crate) pending_text_input_changes: Vec<TextInputStateChange>,
|
||||
pub(crate) text_input_observer: Option<TextInputObserver>,
|
||||
}
|
||||
|
||||
/// Shared handle to the live GPUI `PlatformWindow` owned by `affine-ios-host`.
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct IosEditorWindow {
|
||||
#[cfg(target_os = "ios")]
|
||||
renderer: Rc<RefCell<MetalRenderer>>,
|
||||
#[cfg(not(target_os = "ios"))]
|
||||
atlas: Arc<dyn PlatformAtlas>,
|
||||
display: Rc<dyn PlatformDisplay>,
|
||||
pub(crate) state: Rc<RefCell<IosEditorWindowState>>,
|
||||
}
|
||||
|
||||
impl IosEditorWindow {
|
||||
fn new(
|
||||
#[cfg(target_os = "ios")] instance_buffer_pool: Arc<Mutex<InstanceBufferPool>>,
|
||||
bounds: Bounds<Pixels>,
|
||||
scale_factor: f32,
|
||||
) -> Result<Self> {
|
||||
let safe_scale = if scale_factor.is_finite() && scale_factor > 0.0 {
|
||||
scale_factor
|
||||
} else {
|
||||
2.0
|
||||
};
|
||||
#[cfg(target_os = "ios")]
|
||||
let renderer = {
|
||||
let mut r = metal_renderer::new_renderer(instance_buffer_pool, false, true)?;
|
||||
let dw = (f32::from(bounds.size.width) * safe_scale).round().max(1.0) as i32;
|
||||
let dh = (f32::from(bounds.size.height) * safe_scale)
|
||||
.round()
|
||||
.max(1.0) as i32;
|
||||
r.update_drawable_size(size(DevicePixels(dw), DevicePixels(dh)));
|
||||
Rc::new(RefCell::new(r))
|
||||
};
|
||||
let display: Rc<dyn PlatformDisplay> = Rc::new(IosEditorDisplay { bounds });
|
||||
Ok(Self {
|
||||
#[cfg(target_os = "ios")]
|
||||
renderer,
|
||||
#[cfg(not(target_os = "ios"))]
|
||||
atlas: Arc::new(fallback::FallbackAtlas),
|
||||
display,
|
||||
state: Rc::new(RefCell::new(IosEditorWindowState {
|
||||
bounds,
|
||||
scale_factor: safe_scale,
|
||||
insets: WindowInsets::default(),
|
||||
input_handler: None,
|
||||
request_frame: None,
|
||||
input: None,
|
||||
resize: None,
|
||||
visual_viewport_changed: None,
|
||||
appearance_changed: None,
|
||||
active_status_change: None,
|
||||
visibility_change: None,
|
||||
close: None,
|
||||
mouse_position: Point::default(),
|
||||
modifiers: Modifiers::default(),
|
||||
ime_position: None,
|
||||
dirty: true,
|
||||
text_input_change_seq: 0,
|
||||
last_text_input_change: None,
|
||||
pending_text_input_changes: Vec::new(),
|
||||
text_input_observer: None,
|
||||
})),
|
||||
})
|
||||
}
|
||||
|
||||
/// Returns the raw `CAMetalLayer *` owned by `MetalRenderer` on iOS, or null on non-iOS.
|
||||
pub(crate) fn metal_layer_ptr(&self) -> *mut c_void {
|
||||
#[cfg(target_os = "ios")]
|
||||
{
|
||||
self.renderer.borrow().layer_ptr().cast()
|
||||
}
|
||||
#[cfg(not(target_os = "ios"))]
|
||||
{
|
||||
core::ptr::null_mut()
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn request_frame_now(&self) {
|
||||
let callback = self.state.borrow_mut().request_frame.take();
|
||||
if let Some(mut cb) = callback {
|
||||
cb(RequestFrameOptions {
|
||||
require_presentation: true,
|
||||
..RequestFrameOptions::default()
|
||||
});
|
||||
self.state.borrow_mut().request_frame = Some(cb);
|
||||
}
|
||||
self.state.borrow_mut().dirty = false;
|
||||
}
|
||||
|
||||
/// Delivers queued `TextInputStateChange` notifications after any active GPUI `App`
|
||||
/// borrow has ended so UIKit `UITextInputDelegate` callbacks can safely query FFI.
|
||||
pub(crate) fn flush_text_input_changes(&self) {
|
||||
let (pending, observer) = {
|
||||
let mut st = self.state.borrow_mut();
|
||||
if st.pending_text_input_changes.is_empty() {
|
||||
return;
|
||||
}
|
||||
let pending = std::mem::take(&mut st.pending_text_input_changes);
|
||||
let observer = st.text_input_observer.take();
|
||||
(pending, observer)
|
||||
};
|
||||
if let Some(obs) = observer {
|
||||
for change in pending {
|
||||
obs(change);
|
||||
}
|
||||
let mut st = self.state.borrow_mut();
|
||||
if st.text_input_observer.is_none() {
|
||||
st.text_input_observer = Some(obs);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn dispatch_input(&self, event: PlatformInput) -> DispatchEventResult {
|
||||
let callback = {
|
||||
let mut st = self.state.borrow_mut();
|
||||
match &event {
|
||||
PlatformInput::MouseDown(e) => st.mouse_position = e.position,
|
||||
PlatformInput::MouseUp(e) => st.mouse_position = e.position,
|
||||
PlatformInput::MouseMove(e) => st.mouse_position = e.position,
|
||||
PlatformInput::Touch(e) => st.mouse_position = e.position,
|
||||
_ => {}
|
||||
}
|
||||
st.dirty = true;
|
||||
st.input.take()
|
||||
};
|
||||
let Some(mut cb) = callback else {
|
||||
return DispatchEventResult::default();
|
||||
};
|
||||
let res = cb(event);
|
||||
self.state.borrow_mut().input = Some(cb);
|
||||
res
|
||||
}
|
||||
|
||||
pub(crate) fn set_viewport(&self, width_pt: f32, height_pt: f32, scale_factor: f32) {
|
||||
let w = width_pt.max(1.0);
|
||||
let h = height_pt.max(1.0);
|
||||
let scale = if scale_factor.is_finite() && scale_factor > 0.0 {
|
||||
scale_factor
|
||||
} else {
|
||||
self.state.borrow().scale_factor
|
||||
};
|
||||
#[cfg(target_os = "ios")]
|
||||
{
|
||||
let dw = (w * scale).round().max(1.0) as i32;
|
||||
let dh = (h * scale).round().max(1.0) as i32;
|
||||
self.renderer
|
||||
.borrow_mut()
|
||||
.update_drawable_size(size(DevicePixels(dw), DevicePixels(dh)));
|
||||
}
|
||||
let cb = {
|
||||
let mut st = self.state.borrow_mut();
|
||||
st.bounds.size = size(px(w), px(h));
|
||||
st.scale_factor = scale;
|
||||
st.dirty = true;
|
||||
st.resize.take()
|
||||
};
|
||||
if let Some(mut resize_cb) = cb {
|
||||
resize_cb(size(px(w), px(h)), scale);
|
||||
self.state.borrow_mut().resize = Some(resize_cb);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn set_insets(&self, insets: WindowInsets) {
|
||||
let cb = {
|
||||
let mut st = self.state.borrow_mut();
|
||||
if st.insets == insets {
|
||||
return;
|
||||
}
|
||||
st.insets = insets;
|
||||
st.dirty = true;
|
||||
st.visual_viewport_changed.take()
|
||||
};
|
||||
if let Some(mut vvp_cb) = cb {
|
||||
vvp_cb();
|
||||
self.state.borrow_mut().visual_viewport_changed = Some(vvp_cb);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn with_input_handler<R>(
|
||||
&self,
|
||||
f: impl FnOnce(&mut PlatformInputHandler) -> R,
|
||||
) -> Option<R> {
|
||||
let mut handler = self.state.borrow_mut().input_handler.take()?;
|
||||
let out = f(&mut handler);
|
||||
self.state.borrow_mut().input_handler = Some(handler);
|
||||
Some(out)
|
||||
}
|
||||
|
||||
pub(crate) fn set_text_input_observer(&self, observer: Option<TextInputObserver>) {
|
||||
self.state.borrow_mut().text_input_observer = observer;
|
||||
}
|
||||
|
||||
pub(crate) fn text_input_change_seq(&self) -> u64 {
|
||||
self.state.borrow().text_input_change_seq
|
||||
}
|
||||
}
|
||||
|
||||
impl HasWindowHandle for IosEditorWindow {
|
||||
fn window_handle(&self) -> std::result::Result<WindowHandle<'_>, HandleError> {
|
||||
Err(HandleError::Unavailable)
|
||||
}
|
||||
}
|
||||
|
||||
impl HasDisplayHandle for IosEditorWindow {
|
||||
fn display_handle(&self) -> std::result::Result<DisplayHandle<'_>, HandleError> {
|
||||
#[allow(unsafe_code)]
|
||||
// SAFETY: UiKitDisplayHandle has no lifetime-bound pointer.
|
||||
Ok(
|
||||
unsafe {
|
||||
DisplayHandle::borrow_raw(RawDisplayHandle::UiKit(UiKitDisplayHandle::new()))
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl PlatformWindow for IosEditorWindow {
|
||||
fn bounds(&self) -> Bounds<Pixels> {
|
||||
self.state.borrow().bounds
|
||||
}
|
||||
|
||||
fn is_maximized(&self) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn window_bounds(&self) -> WindowBounds {
|
||||
WindowBounds::Windowed(self.state.borrow().bounds)
|
||||
}
|
||||
|
||||
fn content_size(&self) -> Size<Pixels> {
|
||||
self.state.borrow().bounds.size
|
||||
}
|
||||
|
||||
fn resize(&mut self, size: Size<Pixels>) {
|
||||
let scale = self.state.borrow().scale_factor;
|
||||
self.set_viewport(f32::from(size.width), f32::from(size.height), scale);
|
||||
}
|
||||
|
||||
fn scale_factor(&self) -> f32 {
|
||||
self.state.borrow().scale_factor
|
||||
}
|
||||
|
||||
fn appearance(&self) -> WindowAppearance {
|
||||
WindowAppearance::Light
|
||||
}
|
||||
|
||||
fn display(&self) -> Option<Rc<dyn PlatformDisplay>> {
|
||||
Some(Rc::clone(&self.display))
|
||||
}
|
||||
|
||||
fn mouse_position(&self) -> Point<Pixels> {
|
||||
self.state.borrow().mouse_position
|
||||
}
|
||||
|
||||
fn modifiers(&self) -> Modifiers {
|
||||
self.state.borrow().modifiers
|
||||
}
|
||||
|
||||
fn capslock(&self) -> Capslock {
|
||||
Capslock::default()
|
||||
}
|
||||
|
||||
fn set_input_handler(&mut self, input_handler: PlatformInputHandler) {
|
||||
self.state.borrow_mut().input_handler = Some(input_handler);
|
||||
}
|
||||
|
||||
fn take_input_handler(&mut self) -> Option<PlatformInputHandler> {
|
||||
self.state.borrow_mut().input_handler.take()
|
||||
}
|
||||
|
||||
fn set_text_input_configuration(&mut self, _configuration: TextInputConfiguration) {}
|
||||
|
||||
fn prompt(
|
||||
&self,
|
||||
_level: PromptLevel,
|
||||
_msg: &str,
|
||||
_detail: Option<&str>,
|
||||
_answers: &[PromptButton],
|
||||
) -> Option<oneshot::Receiver<usize>> {
|
||||
None
|
||||
}
|
||||
|
||||
fn activate(&self) {}
|
||||
|
||||
fn is_active(&self) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn visibility(&self) -> WindowVisibility {
|
||||
WindowVisibility::Visible
|
||||
}
|
||||
|
||||
fn is_hovered(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn background_appearance(&self) -> WindowBackgroundAppearance {
|
||||
WindowBackgroundAppearance::Opaque
|
||||
}
|
||||
|
||||
fn set_title(&mut self, _title: &str) {}
|
||||
|
||||
fn set_background_appearance(&self, _background_appearance: WindowBackgroundAppearance) {}
|
||||
|
||||
fn minimize(&self) {}
|
||||
|
||||
fn zoom(&self) {}
|
||||
|
||||
fn toggle_fullscreen(&self) {}
|
||||
|
||||
fn is_fullscreen(&self) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn on_request_frame(&self, callback: Box<dyn FnMut(RequestFrameOptions)>) {
|
||||
self.state.borrow_mut().request_frame = Some(callback);
|
||||
}
|
||||
|
||||
fn on_input(&self, callback: Box<dyn FnMut(PlatformInput) -> DispatchEventResult>) {
|
||||
self.state.borrow_mut().input = Some(callback);
|
||||
}
|
||||
|
||||
fn on_active_status_change(&self, callback: Box<dyn FnMut(bool)>) {
|
||||
self.state.borrow_mut().active_status_change = Some(callback);
|
||||
}
|
||||
|
||||
fn on_visibility_change(&self, callback: Box<dyn FnMut(WindowVisibility)>) {
|
||||
self.state.borrow_mut().visibility_change = Some(callback);
|
||||
}
|
||||
|
||||
fn on_hover_status_change(&self, _callback: Box<dyn FnMut(bool)>) {}
|
||||
|
||||
fn on_resize(&self, callback: Box<dyn FnMut(Size<Pixels>, f32)>) {
|
||||
self.state.borrow_mut().resize = Some(callback);
|
||||
}
|
||||
|
||||
fn on_moved(&self, _callback: Box<dyn FnMut()>) {}
|
||||
|
||||
fn on_display_changed(&self, _callback: Box<dyn FnMut()>) {}
|
||||
|
||||
fn on_should_close(&self, _callback: Box<dyn FnMut() -> bool>) {}
|
||||
|
||||
fn on_close(&self, callback: Box<dyn FnOnce()>) {
|
||||
self.state.borrow_mut().close = Some(callback);
|
||||
}
|
||||
|
||||
fn on_hit_test_window_control(&self, _callback: Box<dyn FnMut() -> Option<WindowControlArea>>) {
|
||||
}
|
||||
|
||||
fn on_appearance_changed(&self, callback: Box<dyn FnMut()>) {
|
||||
self.state.borrow_mut().appearance_changed = Some(callback);
|
||||
}
|
||||
|
||||
fn on_visual_viewport_changed(&self, callback: Box<dyn FnMut()>) {
|
||||
self.state.borrow_mut().visual_viewport_changed = Some(callback);
|
||||
}
|
||||
|
||||
fn insets(&self) -> WindowInsets {
|
||||
self.state.borrow().insets.clone()
|
||||
}
|
||||
|
||||
fn draw(&self, scene: &Scene) {
|
||||
#[cfg(target_os = "ios")]
|
||||
{
|
||||
self.renderer.borrow_mut().draw(scene);
|
||||
}
|
||||
#[cfg(not(target_os = "ios"))]
|
||||
{
|
||||
let _ = scene;
|
||||
}
|
||||
}
|
||||
|
||||
fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas> {
|
||||
#[cfg(target_os = "ios")]
|
||||
{
|
||||
self.renderer.borrow().sprite_atlas().clone()
|
||||
}
|
||||
#[cfg(not(target_os = "ios"))]
|
||||
{
|
||||
Arc::clone(&self.atlas)
|
||||
}
|
||||
}
|
||||
|
||||
fn is_subpixel_rendering_supported(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn gpu_specs(&self) -> Option<GpuSpecs> {
|
||||
None
|
||||
}
|
||||
|
||||
fn update_ime_position(&self, bounds: Bounds<Pixels>) {
|
||||
self.state.borrow_mut().ime_position = Some(bounds);
|
||||
}
|
||||
|
||||
fn text_input_state_changed(&self, change: TextInputStateChange) {
|
||||
let mut st = self.state.borrow_mut();
|
||||
st.text_input_change_seq = st.text_input_change_seq.saturating_add(1);
|
||||
st.last_text_input_change = Some(change);
|
||||
st.pending_text_input_changes.push(change);
|
||||
st.dirty = true;
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct IosEditorPlatform {
|
||||
background_executor: BackgroundExecutor,
|
||||
foreground_executor: ForegroundExecutor,
|
||||
text_system: Arc<dyn PlatformTextSystem>,
|
||||
#[cfg(target_os = "ios")]
|
||||
instance_buffer_pool: Arc<Mutex<InstanceBufferPool>>,
|
||||
initial_bounds: Bounds<Pixels>,
|
||||
initial_scale: f32,
|
||||
opened_window: RefCell<Option<IosEditorWindow>>,
|
||||
clipboard: RefCell<Option<ClipboardItem>>,
|
||||
}
|
||||
|
||||
impl IosEditorPlatform {
|
||||
pub(crate) fn new(width_pt: f32, height_pt: f32, scale_factor: f32) -> Self {
|
||||
let bounds = Bounds::new(
|
||||
point(px(0.0), px(0.0)),
|
||||
size(px(width_pt.max(1.0)), px(height_pt.max(1.0))),
|
||||
);
|
||||
#[cfg(target_os = "ios")]
|
||||
let (dispatcher, text_system): (
|
||||
Arc<dyn ui::PlatformDispatcher>,
|
||||
Arc<dyn PlatformTextSystem>,
|
||||
) = (
|
||||
Arc::new(AppleDispatcher::new()),
|
||||
Arc::new(AppleTextSystem::new()),
|
||||
);
|
||||
#[cfg(not(target_os = "ios"))]
|
||||
let (dispatcher, text_system): (
|
||||
Arc<dyn ui::PlatformDispatcher>,
|
||||
Arc<dyn PlatformTextSystem>,
|
||||
) = (
|
||||
Arc::new(fallback::SyncHostDispatcher::new()),
|
||||
Arc::new(fallback::FallbackTextSystem),
|
||||
);
|
||||
let background_executor = BackgroundExecutor::new(dispatcher.clone());
|
||||
let foreground_executor = ForegroundExecutor::new(dispatcher);
|
||||
Self {
|
||||
background_executor,
|
||||
foreground_executor,
|
||||
text_system,
|
||||
#[cfg(target_os = "ios")]
|
||||
instance_buffer_pool: Arc::new(Mutex::new(InstanceBufferPool::default())),
|
||||
initial_bounds: bounds,
|
||||
initial_scale: if scale_factor.is_finite() && scale_factor > 0.0 {
|
||||
scale_factor
|
||||
} else {
|
||||
2.0
|
||||
},
|
||||
opened_window: RefCell::new(None),
|
||||
clipboard: RefCell::new(None),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn opened_window(&self) -> Option<IosEditorWindow> {
|
||||
self.opened_window.borrow().clone()
|
||||
}
|
||||
}
|
||||
|
||||
impl Platform for IosEditorPlatform {
|
||||
fn platform_info(&self) -> PlatformInfo {
|
||||
PlatformInfo {
|
||||
os: OperatingSystem::Ios,
|
||||
target: PlatformTarget::Native,
|
||||
}
|
||||
}
|
||||
|
||||
fn background_executor(&self) -> BackgroundExecutor {
|
||||
self.background_executor.clone()
|
||||
}
|
||||
|
||||
fn foreground_executor(&self) -> ForegroundExecutor {
|
||||
self.foreground_executor.clone()
|
||||
}
|
||||
|
||||
fn text_system(&self) -> Arc<dyn PlatformTextSystem> {
|
||||
self.text_system.clone()
|
||||
}
|
||||
|
||||
fn run(&self, on_finish_launching: Box<dyn FnOnce()>) {
|
||||
on_finish_launching();
|
||||
}
|
||||
|
||||
fn quit(&self) {}
|
||||
fn restart(&self, _binary_path: Option<PathBuf>, _arguments: Vec<OsString>) {}
|
||||
fn activate(&self, _ignoring_other_apps: bool) {}
|
||||
fn hide(&self) {}
|
||||
fn hide_other_apps(&self) {}
|
||||
fn unhide_other_apps(&self) {}
|
||||
|
||||
fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
|
||||
vec![Rc::new(IosEditorDisplay {
|
||||
bounds: self.initial_bounds,
|
||||
})]
|
||||
}
|
||||
|
||||
fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {
|
||||
Some(Rc::new(IosEditorDisplay {
|
||||
bounds: self.initial_bounds,
|
||||
}))
|
||||
}
|
||||
|
||||
fn on_displays_changed(&self, _callback: Box<dyn FnMut()>) {}
|
||||
|
||||
fn active_window(&self) -> Option<AnyWindowHandle> {
|
||||
None
|
||||
}
|
||||
|
||||
fn open_window(
|
||||
&self,
|
||||
_handle: AnyWindowHandle,
|
||||
options: WindowParams,
|
||||
) -> Result<Box<dyn PlatformWindow>> {
|
||||
let bounds = if f32::from(options.bounds.size.width) > 0.0
|
||||
&& f32::from(options.bounds.size.height) > 0.0
|
||||
{
|
||||
options.bounds
|
||||
} else {
|
||||
self.initial_bounds
|
||||
};
|
||||
let window = IosEditorWindow::new(
|
||||
#[cfg(target_os = "ios")]
|
||||
self.instance_buffer_pool.clone(),
|
||||
bounds,
|
||||
self.initial_scale,
|
||||
)?;
|
||||
*self.opened_window.borrow_mut() = Some(window.clone());
|
||||
Ok(Box::new(window))
|
||||
}
|
||||
|
||||
fn window_appearance(&self) -> WindowAppearance {
|
||||
WindowAppearance::Light
|
||||
}
|
||||
|
||||
fn open_url(&self, _url: &str) {}
|
||||
fn on_open_urls(&self, _callback: Box<dyn FnMut(Vec<String>)>) {}
|
||||
|
||||
fn register_url_scheme(&self, _url: &str) -> Task<Result<()>> {
|
||||
Task::ready(Ok(()))
|
||||
}
|
||||
|
||||
fn prompt_for_paths(
|
||||
&self,
|
||||
_options: PathPromptOptions,
|
||||
) -> oneshot::Receiver<Result<Option<Vec<PathBuf>>>> {
|
||||
let (tx, rx) = oneshot::channel();
|
||||
let _ = tx.send(Ok(None));
|
||||
rx
|
||||
}
|
||||
|
||||
fn prompt_for_new_path(
|
||||
&self,
|
||||
_directory: &Path,
|
||||
_suggested_name: Option<&str>,
|
||||
) -> oneshot::Receiver<Result<Option<PathBuf>>> {
|
||||
let (tx, rx) = oneshot::channel();
|
||||
let _ = tx.send(Ok(None));
|
||||
rx
|
||||
}
|
||||
|
||||
fn can_select_mixed_files_and_dirs(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn reveal_path(&self, _path: &Path) {}
|
||||
fn open_with_system(&self, _path: &Path) {}
|
||||
fn on_quit(&self, _callback: Box<dyn FnMut() -> bool>) {}
|
||||
fn on_reopen(&self, _callback: Box<dyn FnMut()>) {}
|
||||
fn on_system_sleep(&self, _callback: Box<dyn FnMut()>) {}
|
||||
fn on_system_wake(&self, _callback: Box<dyn FnMut()>) {}
|
||||
fn set_menus(&self, _menus: Vec<Menu>, _keymap: &Keymap) {}
|
||||
fn set_dock_menu(&self, _menu: Vec<MenuItem>, _keymap: &Keymap) {}
|
||||
|
||||
fn update_jump_list(
|
||||
&self,
|
||||
_menus: Vec<MenuItem>,
|
||||
_entries: Vec<SmallVec<[PathBuf; 2]>>,
|
||||
) -> Task<Vec<SmallVec<[PathBuf; 2]>>> {
|
||||
Task::ready(Vec::new())
|
||||
}
|
||||
|
||||
fn on_app_menu_action(&self, _callback: Box<dyn FnMut(&dyn Action)>) {}
|
||||
fn on_will_open_app_menu(&self, _callback: Box<dyn FnMut()>) {}
|
||||
fn on_validate_app_menu_command(&self, _callback: Box<dyn FnMut(&dyn Action) -> bool>) {}
|
||||
|
||||
fn app_path(&self) -> Result<PathBuf> {
|
||||
Ok(PathBuf::new())
|
||||
}
|
||||
|
||||
fn path_for_auxiliary_executable(&self, _name: &str) -> Result<PathBuf> {
|
||||
Ok(PathBuf::new())
|
||||
}
|
||||
|
||||
fn set_cursor_style(&self, _style: CursorStyle) {}
|
||||
fn hide_cursor_until_mouse_moves(&self) {}
|
||||
|
||||
fn is_cursor_visible(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn should_auto_hide_scrollbars(&self) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn write_to_clipboard(&self, item: ClipboardItem) {
|
||||
*self.clipboard.borrow_mut() = Some(item);
|
||||
}
|
||||
|
||||
fn read_from_clipboard(&self) -> Option<ClipboardItem> {
|
||||
self.clipboard.borrow().clone()
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
fn write_to_primary(&self, _item: ClipboardItem) {}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
fn read_from_primary(&self) -> Option<ClipboardItem> {
|
||||
None
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
fn read_from_find_pasteboard(&self) -> Option<ClipboardItem> {
|
||||
None
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
fn write_to_find_pasteboard(&self, _item: ClipboardItem) {}
|
||||
|
||||
fn write_credentials(&self, _url: &str, _username: &str, _password: &[u8]) -> Task<Result<()>> {
|
||||
Task::ready(Ok(()))
|
||||
}
|
||||
|
||||
fn read_credentials(&self, _url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
|
||||
Task::ready(Ok(None))
|
||||
}
|
||||
|
||||
fn delete_credentials(&self, _url: &str) -> Task<Result<()>> {
|
||||
Task::ready(Ok(()))
|
||||
}
|
||||
|
||||
fn keyboard_layout(&self) -> Box<dyn PlatformKeyboardLayout> {
|
||||
Box::new(IosEditorKeyboardLayout)
|
||||
}
|
||||
|
||||
fn keyboard_mapper(&self) -> Rc<dyn PlatformKeyboardMapper> {
|
||||
Rc::new(DummyKeyboardMapper)
|
||||
}
|
||||
|
||||
fn on_keyboard_layout_change(&self, _callback: Box<dyn FnMut()>) {}
|
||||
|
||||
fn thermal_state(&self) -> ThermalState {
|
||||
ThermalState::Nominal
|
||||
}
|
||||
|
||||
fn on_thermal_state_change(&self, _callback: Box<dyn FnMut()>) {}
|
||||
|
||||
fn prevent_idle_sleep(&self, _reason: &str) -> Task<Result<ActivityGuard>> {
|
||||
Task::ready(Ok(ActivityGuard::noop()))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,533 @@
|
||||
//! Live pure-Rust BlockSuite GPU editor runtime hosted inside `AffineIosHost`.
|
||||
//!
|
||||
//! Owns the embedded GPUI [`ui::ApplicationHandle`], [`IosEditorWindow`], and
|
||||
//! [`playground::PlaygroundView`] so `UITextInput`, touch gestures, hardware keys,
|
||||
//! and Metal frame rendering all talk to one authoritative `PlatformInputHandler`
|
||||
//! and CRDT document (zero host text copy).
|
||||
|
||||
use std::{ffi::c_void, rc::Rc};
|
||||
|
||||
use playground::{FormFactor, PlaygroundMode, PlaygroundOptions, PlaygroundView};
|
||||
use ui::{
|
||||
AppContext, Application, ApplicationHandle, Bounds, Edges, KeyDownEvent, Keystroke, Modifiers,
|
||||
PlatformInput, TextInputStateChange, TouchEvent, TouchId, TouchPhase, WindowBounds,
|
||||
WindowInsets, WindowOptions, point, px, size,
|
||||
};
|
||||
|
||||
use super::{
|
||||
AffineUtf16Range, AffineWindowInsets, IosHostState,
|
||||
editor_platform::{IosEditorPlatform, IosEditorWindow, TextInputObserver},
|
||||
selection::{AffinePoint, AffineRect, AffineWritingDirection},
|
||||
text_layout::{AffineSelectionRect, detect_paragraph_writing_direction},
|
||||
};
|
||||
|
||||
/// Live GPU editor runtime embedded in `AffineIosHost`.
|
||||
pub(crate) struct IosEditorRuntime {
|
||||
app: ApplicationHandle,
|
||||
window: IosEditorWindow,
|
||||
view: ui::WindowHandle<PlaygroundView>,
|
||||
form_factor: FormFactor,
|
||||
frame_count: u64,
|
||||
last_frame_timestamp_sec: f64,
|
||||
}
|
||||
|
||||
impl IosEditorRuntime {
|
||||
pub(crate) fn new(
|
||||
width_pt: f32,
|
||||
height_pt: f32,
|
||||
scale_factor: f32,
|
||||
form_factor: FormFactor,
|
||||
load_showcase: bool,
|
||||
) -> Option<Self> {
|
||||
let w = if width_pt.is_finite() && width_pt > 1.0 {
|
||||
width_pt
|
||||
} else {
|
||||
390.0
|
||||
};
|
||||
let h = if height_pt.is_finite() && height_pt > 1.0 {
|
||||
height_pt
|
||||
} else {
|
||||
844.0
|
||||
};
|
||||
let scale = if scale_factor.is_finite() && scale_factor > 0.0 {
|
||||
scale_factor
|
||||
} else {
|
||||
2.0
|
||||
};
|
||||
|
||||
let platform = Rc::new(IosEditorPlatform::new(w, h, scale));
|
||||
let platform_ref = Rc::clone(&platform);
|
||||
let view_slot: Rc<std::cell::RefCell<Option<ui::WindowHandle<PlaygroundView>>>> =
|
||||
Rc::new(std::cell::RefCell::new(None));
|
||||
let view_slot_init = Rc::clone(&view_slot);
|
||||
|
||||
let options = PlaygroundOptions::for_form_factor(form_factor);
|
||||
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| {
|
||||
let _ = affine_mobile::register_mobile_fonts(cx);
|
||||
let _ = playground::register_bundled_fonts(cx);
|
||||
if let Ok(handle) = cx.open_window(
|
||||
WindowOptions {
|
||||
window_bounds: Some(WindowBounds::Windowed(bounds)),
|
||||
..WindowOptions::default()
|
||||
},
|
||||
move |window, cx| {
|
||||
window.set_touch_gestures_enabled(true);
|
||||
let entity = cx.new(|cx| PlaygroundView::with_options(options, cx));
|
||||
entity.update(cx, |view, cx| {
|
||||
if !load_showcase {
|
||||
view.load_empty_page_document(window, cx);
|
||||
} else {
|
||||
view.focus_first_text_block(window, cx);
|
||||
}
|
||||
});
|
||||
entity
|
||||
},
|
||||
) {
|
||||
*view_slot_init.borrow_mut() = Some(handle);
|
||||
}
|
||||
});
|
||||
|
||||
let window = platform_ref.opened_window()?;
|
||||
let view = view_slot.borrow_mut().take()?;
|
||||
let runtime = Self {
|
||||
app,
|
||||
window,
|
||||
view,
|
||||
form_factor,
|
||||
frame_count: 0,
|
||||
last_frame_timestamp_sec: 0.0,
|
||||
};
|
||||
// Render initial frame so layout and `PlatformInputHandler` are live immediately.
|
||||
runtime.window.request_frame_now();
|
||||
Some(runtime)
|
||||
}
|
||||
|
||||
pub(crate) fn metal_layer_ptr(&self) -> *mut c_void {
|
||||
self.window.metal_layer_ptr()
|
||||
}
|
||||
|
||||
pub(crate) fn window_handle(&self) -> IosEditorWindow {
|
||||
self.window.clone()
|
||||
}
|
||||
|
||||
pub(crate) fn resize(&mut self, width_pt: f32, height_pt: f32, scale_factor: f32) {
|
||||
self.window.set_viewport(width_pt, height_pt, scale_factor);
|
||||
self.window.request_frame_now();
|
||||
}
|
||||
|
||||
pub(crate) fn set_insets(&mut self, insets: AffineWindowInsets) {
|
||||
// `KeyboardAvoidanceCoordinator` computes `insets.ime_bottom` relative to
|
||||
// `hostView` (which is already framed inside `view.safeAreaInsets`), so
|
||||
// `insets.ime_bottom` is already the non-double-counted keyboard overlap
|
||||
// above the bottom safe area.
|
||||
let ime_above_safe = insets.ime_bottom.max(0.0);
|
||||
let ui_insets = WindowInsets {
|
||||
safe_area: Edges::default(),
|
||||
ime: Edges {
|
||||
top: px(0.0),
|
||||
right: px(0.0),
|
||||
bottom: px(ime_above_safe),
|
||||
left: px(0.0),
|
||||
},
|
||||
..WindowInsets::default()
|
||||
};
|
||||
self.window.set_insets(ui_insets);
|
||||
}
|
||||
|
||||
pub(crate) fn request_frame(&mut self) {
|
||||
self.window.state.borrow_mut().dirty = true;
|
||||
}
|
||||
|
||||
pub(crate) fn is_dirty(&self) -> bool {
|
||||
self.window.state.borrow().dirty
|
||||
}
|
||||
|
||||
pub(crate) fn render_frame(&mut self, timestamp_sec: f64) -> u32 {
|
||||
if !self.is_dirty() {
|
||||
return 0;
|
||||
}
|
||||
self.window.request_frame_now();
|
||||
self.frame_count = self.frame_count.saturating_add(1);
|
||||
if timestamp_sec.is_finite() {
|
||||
self.last_frame_timestamp_sec = timestamp_sec;
|
||||
}
|
||||
IosHostState::DEFAULT_CLEAR_COLOR_RGBA
|
||||
}
|
||||
|
||||
pub(crate) fn set_form_factor(&mut self, form_factor: FormFactor) {
|
||||
self.form_factor = form_factor;
|
||||
let _ = self.app.update(|cx| {
|
||||
let _ = self.view.update(cx, |view, window, cx| {
|
||||
view.set_form_factor(form_factor, window, cx);
|
||||
});
|
||||
});
|
||||
self.window.request_frame_now();
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn form_factor(&self) -> FormFactor {
|
||||
self.form_factor
|
||||
}
|
||||
|
||||
pub(crate) fn edgeless_readonly(&self) -> bool {
|
||||
self.app
|
||||
.update(|cx| self.view.read_with(cx, |view, _| view.edgeless_readonly()))
|
||||
.unwrap_or(true)
|
||||
}
|
||||
|
||||
pub(crate) fn wants_software_keyboard(&self) -> bool {
|
||||
self.app
|
||||
.update(|cx| {
|
||||
self.view
|
||||
.read_with(cx, |view, _| view.wants_software_keyboard())
|
||||
})
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
pub(crate) fn database_readonly(&self) -> bool {
|
||||
self.app
|
||||
.update(|cx| self.view.read_with(cx, |view, _| view.database_readonly()))
|
||||
.unwrap_or(true)
|
||||
}
|
||||
|
||||
pub(crate) fn set_mode(&mut self, mode: PlaygroundMode) {
|
||||
let _ = self.app.update(|cx| {
|
||||
let _ = self.view.update(cx, |view, window, cx| {
|
||||
view.set_mode(mode, window, cx);
|
||||
});
|
||||
});
|
||||
self.window.request_frame_now();
|
||||
}
|
||||
|
||||
pub(crate) fn reset_empty_document(&mut self) {
|
||||
let _ = self.app.update(|cx| {
|
||||
let _ = self.view.update(cx, |view, window, cx| {
|
||||
view.load_empty_page_document(window, cx);
|
||||
});
|
||||
});
|
||||
self.window.request_frame_now();
|
||||
}
|
||||
|
||||
pub(crate) fn load_showcase_document(&mut self) {
|
||||
let _ = self.app.update(|cx| {
|
||||
let _ = self.view.update(cx, |view, window, cx| {
|
||||
view.load_showcase_document(window, cx);
|
||||
});
|
||||
});
|
||||
self.window.request_frame_now();
|
||||
}
|
||||
|
||||
pub(crate) fn dispatch_touch(&mut self, touch_id: u64, phase: u8, x: f32, y: f32) {
|
||||
let touch_phase = match phase {
|
||||
0 => TouchPhase::Started,
|
||||
1 => TouchPhase::Moved,
|
||||
2 => TouchPhase::Ended,
|
||||
_ => TouchPhase::Cancelled,
|
||||
};
|
||||
let event = TouchEvent {
|
||||
id: TouchId(touch_id),
|
||||
phase: touch_phase,
|
||||
position: point(px(x), px(y)),
|
||||
predicted_position: None,
|
||||
force: None,
|
||||
};
|
||||
let _ = self.window.dispatch_input(PlatformInput::Touch(event));
|
||||
self.window.request_frame_now();
|
||||
}
|
||||
|
||||
pub(crate) fn dispatch_key_down(
|
||||
&mut self,
|
||||
key: &str,
|
||||
key_char: Option<&str>,
|
||||
shift: bool,
|
||||
cmd: bool,
|
||||
ctrl: bool,
|
||||
alt: bool,
|
||||
) {
|
||||
let event = KeyDownEvent {
|
||||
keystroke: Keystroke {
|
||||
modifiers: Modifiers {
|
||||
control: ctrl,
|
||||
alt,
|
||||
shift,
|
||||
platform: cmd,
|
||||
function: false,
|
||||
},
|
||||
key: key.to_string(),
|
||||
key_char: key_char.map(str::to_string),
|
||||
},
|
||||
is_held: false,
|
||||
prefer_character_input: false,
|
||||
};
|
||||
let _ = self.window.dispatch_input(PlatformInput::KeyDown(event));
|
||||
self.window.request_frame_now();
|
||||
}
|
||||
|
||||
pub(crate) fn set_text_input_observer(&self, observer: Option<TextInputObserver>) {
|
||||
self.window.set_text_input_observer(observer);
|
||||
}
|
||||
|
||||
pub(crate) fn text_input_change_seq(&self) -> u64 {
|
||||
self.window.text_input_change_seq()
|
||||
}
|
||||
|
||||
fn ensure_input_handler(&mut self) {
|
||||
if self.window.state.borrow().input_handler.is_none() {
|
||||
self.window.request_frame_now();
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn utf16_len(&mut self) -> usize {
|
||||
self.ensure_input_handler();
|
||||
self.window
|
||||
.with_input_handler(|h| h.text_length_utf16())
|
||||
.flatten()
|
||||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
pub(crate) fn utf16_text(&mut self) -> Vec<u16> {
|
||||
self.ensure_input_handler();
|
||||
let len = self.utf16_len();
|
||||
if len == 0 {
|
||||
return Vec::new();
|
||||
}
|
||||
let mut adjusted = None;
|
||||
let text = self
|
||||
.window
|
||||
.with_input_handler(|h| h.text_for_range(0..len, &mut adjusted))
|
||||
.flatten()
|
||||
.unwrap_or_default();
|
||||
text.encode_utf16().collect()
|
||||
}
|
||||
|
||||
pub(crate) fn selected_range(&mut self) -> AffineUtf16Range {
|
||||
self.ensure_input_handler();
|
||||
self.window
|
||||
.with_input_handler(|h| h.selected_text_range(true))
|
||||
.flatten()
|
||||
.map(|sel| AffineUtf16Range {
|
||||
location: sel.range.start.min(u32::MAX as usize) as u32,
|
||||
length: sel.range.len().min(u32::MAX as usize) as u32,
|
||||
})
|
||||
.unwrap_or(AffineUtf16Range {
|
||||
location: 0,
|
||||
length: 0,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn marked_range(&mut self) -> AffineUtf16Range {
|
||||
self.ensure_input_handler();
|
||||
self.window
|
||||
.with_input_handler(|h| h.marked_text_range())
|
||||
.flatten()
|
||||
.map(|r| AffineUtf16Range {
|
||||
location: r.start.min(u32::MAX as usize) as u32,
|
||||
length: r.len().min(u32::MAX as usize) as u32,
|
||||
})
|
||||
.unwrap_or(AffineUtf16Range {
|
||||
location: u32::MAX,
|
||||
length: 0,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn insert_text(&mut self, utf16: &[u16]) {
|
||||
self.ensure_input_handler();
|
||||
let text = String::from_utf16_lossy(utf16);
|
||||
if text == "\n" || text == "\r" {
|
||||
self.dispatch_key_down("enter", None, false, false, false, false);
|
||||
return;
|
||||
}
|
||||
let _ = self
|
||||
.window
|
||||
.with_input_handler(|h| h.replace_text_in_range(None, &text));
|
||||
self.window.request_frame_now();
|
||||
}
|
||||
|
||||
pub(crate) fn delete_backward(&mut self) {
|
||||
self.ensure_input_handler();
|
||||
// Dispatch through editor key handler so block-start Backspace merges with previous block
|
||||
// and non-collapsed selections delete across blocks cleanly.
|
||||
self.dispatch_key_down("backspace", None, false, false, false, false);
|
||||
}
|
||||
|
||||
pub(crate) fn delete_range(&mut self, range: AffineUtf16Range) {
|
||||
self.ensure_input_handler();
|
||||
if range.length == 0 {
|
||||
return;
|
||||
}
|
||||
let start = range.location as usize;
|
||||
let end = start.saturating_add(range.length as usize);
|
||||
let _ = self
|
||||
.window
|
||||
.with_input_handler(|h| h.replace_text_in_range(Some(start..end), ""));
|
||||
self.window.request_frame_now();
|
||||
}
|
||||
|
||||
pub(crate) fn replace_range(&mut self, range: AffineUtf16Range, utf16: &[u16]) {
|
||||
self.ensure_input_handler();
|
||||
let text = String::from_utf16_lossy(utf16);
|
||||
let start = range.location as usize;
|
||||
let end = start.saturating_add(range.length as usize);
|
||||
let _ = self
|
||||
.window
|
||||
.with_input_handler(|h| h.replace_text_in_range(Some(start..end), &text));
|
||||
self.window.request_frame_now();
|
||||
}
|
||||
|
||||
pub(crate) fn set_selected_range(&mut self, range: AffineUtf16Range) {
|
||||
self.ensure_input_handler();
|
||||
let start = range.location as usize;
|
||||
let end = start.saturating_add(range.length as usize);
|
||||
let _ = self
|
||||
.window
|
||||
.with_input_handler(|h| h.set_selected_text_range(start..end));
|
||||
self.window.request_frame_now();
|
||||
}
|
||||
|
||||
pub(crate) fn set_marked_text(&mut self, utf16: &[u16], selected_in_marked: AffineUtf16Range) {
|
||||
self.ensure_input_handler();
|
||||
let text = String::from_utf16_lossy(utf16);
|
||||
let sel_start = selected_in_marked.location as usize;
|
||||
let sel_end = sel_start.saturating_add(selected_in_marked.length as usize);
|
||||
let _ = self.window.with_input_handler(|h| {
|
||||
h.replace_and_mark_text_in_range(None, &text, Some(sel_start..sel_end))
|
||||
});
|
||||
self.window.request_frame_now();
|
||||
}
|
||||
|
||||
pub(crate) fn unmark_text(&mut self) {
|
||||
self.ensure_input_handler();
|
||||
let _ = self.window.with_input_handler(|h| h.unmark_text());
|
||||
self.window.request_frame_now();
|
||||
}
|
||||
|
||||
pub(crate) fn writing_direction(&mut self) -> AffineWritingDirection {
|
||||
let units = self.utf16_text();
|
||||
let sel = self.selected_range();
|
||||
detect_paragraph_writing_direction(&units, sel.location as usize)
|
||||
}
|
||||
|
||||
pub(crate) fn caret_rect(&mut self, utf16_offset: u32) -> Option<AffineRect> {
|
||||
self.ensure_input_handler();
|
||||
let off = utf16_offset as usize;
|
||||
let bounds = self
|
||||
.window
|
||||
.with_input_handler(|h| h.bounds_for_range(off..off))
|
||||
.flatten()?;
|
||||
Some(AffineRect {
|
||||
x: f32::from(bounds.origin.x),
|
||||
y: f32::from(bounds.origin.y),
|
||||
width: f32::from(bounds.size.width).max(2.0),
|
||||
height: f32::from(bounds.size.height).max(20.0),
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn selection_rects(&mut self, range: AffineUtf16Range) -> Vec<AffineSelectionRect> {
|
||||
self.ensure_input_handler();
|
||||
let start = range.location as usize;
|
||||
let end = start.saturating_add(range.length as usize);
|
||||
let bounds_list = self
|
||||
.window
|
||||
.with_input_handler(|h| h.selection_bounds_for_range(start..end))
|
||||
.unwrap_or_default();
|
||||
let count = bounds_list.len();
|
||||
bounds_list
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(idx, b)| AffineSelectionRect {
|
||||
rect: AffineRect {
|
||||
x: f32::from(b.origin.x),
|
||||
y: f32::from(b.origin.y),
|
||||
width: f32::from(b.size.width).max(2.0),
|
||||
height: f32::from(b.size.height).max(20.0),
|
||||
},
|
||||
contains_start: idx == 0,
|
||||
contains_end: idx + 1 == count,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub(crate) fn closest_offset(&mut self, pt: AffinePoint) -> Option<u32> {
|
||||
self.ensure_input_handler();
|
||||
let 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)
|
||||
}
|
||||
|
||||
pub(crate) fn change_kind_code(change: TextInputStateChange) -> u8 {
|
||||
match change {
|
||||
TextInputStateChange::FocusGained => 1,
|
||||
TextInputStateChange::FocusLost => 2,
|
||||
TextInputStateChange::SelectionChanged => 3,
|
||||
TextInputStateChange::ContentChanged => 4,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn ios_editor_runtime_authoritative_ime_markdown_and_stage_one_readonly() {
|
||||
let mut rt =
|
||||
IosEditorRuntime::new(390.0, 844.0, 3.0, FormFactor::Phone, false).expect("runtime");
|
||||
assert!(rt.edgeless_readonly());
|
||||
assert!(rt.database_readonly());
|
||||
assert_eq!(rt.form_factor(), FormFactor::Phone);
|
||||
|
||||
// H-S1 + H-S2: typing "# " converts paragraph into heading and clears "# " from focused block text.
|
||||
let seq_before = rt.text_input_change_seq();
|
||||
let prefix: Vec<u16> = "# Hello".encode_utf16().collect();
|
||||
rt.insert_text(&prefix);
|
||||
assert!(rt.text_input_change_seq() > seq_before);
|
||||
let text = String::from_utf16_lossy(&rt.utf16_text());
|
||||
assert!(
|
||||
text.contains("Hello"),
|
||||
"focused block text should contain Hello, got {text:?}"
|
||||
);
|
||||
|
||||
// Block split on newline + block-start deleteBackward merge.
|
||||
let nl: Vec<u16> = "\n".encode_utf16().collect();
|
||||
rt.insert_text(&nl);
|
||||
let after_split = String::from_utf16_lossy(&rt.utf16_text());
|
||||
assert_eq!(after_split, "");
|
||||
rt.delete_backward();
|
||||
let after_merge = String::from_utf16_lossy(&rt.utf16_text());
|
||||
assert!(
|
||||
after_merge.contains("Hello"),
|
||||
"deleteBackward at block start should merge back into previous block, got {after_merge:?}"
|
||||
);
|
||||
|
||||
// Tablet stays touch read-only; Desktop unlocks Edgeless authoring.
|
||||
rt.set_form_factor(FormFactor::Tablet);
|
||||
assert!(rt.edgeless_readonly());
|
||||
assert!(rt.database_readonly());
|
||||
rt.set_form_factor(FormFactor::Desktop);
|
||||
assert!(!rt.edgeless_readonly());
|
||||
assert!(!rt.database_readonly());
|
||||
|
||||
// Explicit page_readonly=true blocks Enter, Backspace, and text insertion,
|
||||
// and is preserved across set_form_factor transitions.
|
||||
let _ = rt.app.update(|cx| {
|
||||
let _ = rt.view.update(cx, |view, _window, cx| {
|
||||
view.set_page_readonly(true, cx);
|
||||
});
|
||||
});
|
||||
rt.set_form_factor(FormFactor::Phone);
|
||||
let before_ro = String::from_utf16_lossy(&rt.utf16_text());
|
||||
let extra: Vec<u16> = "MUTATED".encode_utf16().collect();
|
||||
rt.insert_text(&extra);
|
||||
rt.dispatch_key_down("enter", None, false, false, false, false);
|
||||
rt.delete_backward();
|
||||
let after_ro = String::from_utf16_lossy(&rt.utf16_text());
|
||||
assert_eq!(
|
||||
after_ro, before_ro,
|
||||
"page_readonly=true must suppress text insertion, Enter, and Backspace"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,7 @@ use std::{
|
||||
};
|
||||
|
||||
use super::{
|
||||
AffineUtf16Range, AffineWindowInsets, IosHostState,
|
||||
AffineWindowInsets, IosHostState,
|
||||
auth::{
|
||||
AuthTokenResponse, StoredAuthTokenPair, auth_error_permanently_invalidates_session,
|
||||
canonical_endpoint, resolve_installation_id,
|
||||
@@ -21,6 +21,7 @@ use super::{
|
||||
/// Opaque C-ABI handle matching `typedef struct AffineIosHost AffineIosHost`.
|
||||
pub struct AffineIosHost {
|
||||
pub(crate) state: IosHostState,
|
||||
pub(crate) editor: std::cell::RefCell<Option<super::editor_runtime::IosEditorRuntime>>,
|
||||
_metal_layer: *mut c_void,
|
||||
pub(crate) haptics_callback: Option<extern "C" fn(u8, *mut c_void)>,
|
||||
pub(crate) haptics_user_data: *mut c_void,
|
||||
@@ -104,8 +105,16 @@ pub extern "C" fn affine_ios_host_create(
|
||||
height_pt: f32,
|
||||
scale_factor: f32,
|
||||
) -> *mut AffineIosHost {
|
||||
let editor = super::editor_runtime::IosEditorRuntime::new(
|
||||
width_pt,
|
||||
height_pt,
|
||||
scale_factor,
|
||||
playground::FormFactor::Phone,
|
||||
true,
|
||||
);
|
||||
let host = Box::new(AffineIosHost {
|
||||
state: IosHostState::new(width_pt, height_pt, scale_factor),
|
||||
editor: std::cell::RefCell::new(editor),
|
||||
_metal_layer: metal_layer,
|
||||
haptics_callback: None,
|
||||
haptics_user_data: core::ptr::null_mut(),
|
||||
@@ -139,6 +148,10 @@ pub unsafe extern "C" fn affine_ios_host_resize(
|
||||
return;
|
||||
};
|
||||
host.state.resize(width_pt, height_pt, scale_factor);
|
||||
if let Some(editor) = host.editor.borrow_mut().as_mut() {
|
||||
editor.resize(width_pt, height_pt, scale_factor);
|
||||
}
|
||||
super::ffi_editor::flush_text_input_changes(host);
|
||||
}
|
||||
|
||||
/// # Safety
|
||||
@@ -152,6 +165,9 @@ pub unsafe extern "C" fn affine_ios_host_set_insets(
|
||||
return;
|
||||
};
|
||||
host.state.set_insets(insets);
|
||||
if let Some(editor) = host.editor.borrow_mut().as_mut() {
|
||||
editor.set_insets(host.state.insets());
|
||||
}
|
||||
}
|
||||
|
||||
/// # Safety
|
||||
@@ -164,6 +180,22 @@ pub unsafe extern "C" fn affine_ios_host_render_frame(
|
||||
let Some(host) = (unsafe { host.as_mut() }) else {
|
||||
return 0;
|
||||
};
|
||||
let rendered = if let Some(editor) = host.editor.borrow_mut().as_mut() {
|
||||
if host.state.is_dirty() {
|
||||
editor.request_frame();
|
||||
}
|
||||
let color = editor.render_frame(frame_timestamp_sec);
|
||||
if color != 0 {
|
||||
let _ = host.state.render_frame(frame_timestamp_sec);
|
||||
}
|
||||
Some(color)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some(color) = rendered {
|
||||
super::ffi_editor::flush_text_input_changes(host);
|
||||
return color;
|
||||
}
|
||||
host.state.render_frame(frame_timestamp_sec)
|
||||
}
|
||||
|
||||
@@ -174,6 +206,9 @@ pub unsafe extern "C" fn affine_ios_host_is_dirty(host: *const AffineIosHost) ->
|
||||
let Some(host) = (unsafe { host.as_ref() }) else {
|
||||
return false;
|
||||
};
|
||||
if let Some(editor) = host.editor.borrow().as_ref() {
|
||||
return editor.is_dirty() || host.state.is_dirty();
|
||||
}
|
||||
host.state.is_dirty()
|
||||
}
|
||||
|
||||
@@ -185,141 +220,9 @@ pub unsafe extern "C" fn affine_ios_host_request_frame(host: *mut AffineIosHost)
|
||||
return;
|
||||
};
|
||||
host.state.request_frame();
|
||||
}
|
||||
|
||||
/// # Safety
|
||||
/// `host` must be null or a live pointer; `utf16_ptr` must be valid for `utf16_len` reads when non-zero.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn affine_ios_host_insert_text(
|
||||
host: *mut AffineIosHost,
|
||||
utf16_ptr: *const u16,
|
||||
utf16_len: usize,
|
||||
) {
|
||||
let Some(host) = (unsafe { host.as_mut() }) else {
|
||||
return;
|
||||
};
|
||||
let slice = if utf16_len == 0 || utf16_ptr.is_null() {
|
||||
&[]
|
||||
} else {
|
||||
// SAFETY: Caller guarantees `utf16_ptr` points to `utf16_len` initialized `u16`s.
|
||||
unsafe { core::slice::from_raw_parts(utf16_ptr, utf16_len) }
|
||||
};
|
||||
host.state.insert_text(slice);
|
||||
}
|
||||
|
||||
/// # 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_delete_backward(host: *mut AffineIosHost) {
|
||||
let Some(host) = (unsafe { host.as_mut() }) else {
|
||||
return;
|
||||
};
|
||||
host.state.delete_backward();
|
||||
}
|
||||
|
||||
/// # 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_delete_range(
|
||||
host: *mut AffineIosHost,
|
||||
range: AffineUtf16Range,
|
||||
) {
|
||||
let Some(host) = (unsafe { host.as_mut() }) else {
|
||||
return;
|
||||
};
|
||||
host.state.delete_range(range);
|
||||
}
|
||||
|
||||
/// # 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_selected_range(
|
||||
host: *mut AffineIosHost,
|
||||
range: AffineUtf16Range,
|
||||
) {
|
||||
let Some(host) = (unsafe { host.as_mut() }) else {
|
||||
return;
|
||||
};
|
||||
host.state.set_selected_range(range);
|
||||
}
|
||||
|
||||
/// # Safety
|
||||
/// `host` must be null or a live pointer; `utf16_ptr` must be valid for `utf16_len` reads when non-zero.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn affine_ios_host_replace_range(
|
||||
host: *mut AffineIosHost,
|
||||
range: AffineUtf16Range,
|
||||
utf16_ptr: *const u16,
|
||||
utf16_len: usize,
|
||||
) {
|
||||
let Some(host) = (unsafe { host.as_mut() }) else {
|
||||
return;
|
||||
};
|
||||
let slice = if utf16_len == 0 || utf16_ptr.is_null() {
|
||||
&[]
|
||||
} else {
|
||||
// SAFETY: Caller guarantees `utf16_ptr` points to `utf16_len` initialized `u16`s.
|
||||
unsafe { core::slice::from_raw_parts(utf16_ptr, utf16_len) }
|
||||
};
|
||||
host.state.replace_range(range, slice);
|
||||
}
|
||||
|
||||
/// # Safety
|
||||
/// `host` must be null or a live pointer; `utf16_ptr` must be valid for `utf16_len` reads when non-zero.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn affine_ios_host_set_marked_text(
|
||||
host: *mut AffineIosHost,
|
||||
utf16_ptr: *const u16,
|
||||
utf16_len: usize,
|
||||
selected_range: AffineUtf16Range,
|
||||
) {
|
||||
let Some(host) = (unsafe { host.as_mut() }) else {
|
||||
return;
|
||||
};
|
||||
let slice = if utf16_len == 0 || utf16_ptr.is_null() {
|
||||
&[]
|
||||
} else {
|
||||
// SAFETY: Caller guarantees `utf16_ptr` points to `utf16_len` initialized `u16`s.
|
||||
unsafe { core::slice::from_raw_parts(utf16_ptr, utf16_len) }
|
||||
};
|
||||
host.state.set_marked_text(slice, selected_range);
|
||||
}
|
||||
|
||||
/// # 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_unmark_text(host: *mut AffineIosHost) {
|
||||
let Some(host) = (unsafe { host.as_mut() }) else {
|
||||
return;
|
||||
};
|
||||
host.state.unmark_text();
|
||||
}
|
||||
|
||||
/// # 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_range(
|
||||
host: *const AffineIosHost,
|
||||
) -> AffineUtf16Range {
|
||||
let Some(host) = (unsafe { host.as_ref() }) else {
|
||||
return AffineUtf16Range::default();
|
||||
};
|
||||
host.state.selected_range()
|
||||
}
|
||||
|
||||
/// # 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_marked_range(
|
||||
host: *const AffineIosHost,
|
||||
) -> AffineUtf16Range {
|
||||
let Some(host) = (unsafe { host.as_ref() }) else {
|
||||
return AffineUtf16Range {
|
||||
location: u32::MAX,
|
||||
length: 0,
|
||||
};
|
||||
};
|
||||
host.state.marked_range()
|
||||
if let Some(editor) = host.editor.borrow_mut().as_mut() {
|
||||
editor.request_frame();
|
||||
}
|
||||
}
|
||||
|
||||
/// # Safety
|
||||
|
||||
@@ -0,0 +1,538 @@
|
||||
#![allow(unsafe_code)]
|
||||
|
||||
//! C-ABI entry points for the live GPU `PlaygroundView` mounted inside `AffineIosHost`.
|
||||
|
||||
use std::ffi::{CStr, c_char, c_void};
|
||||
|
||||
use playground::{FormFactor, PlaygroundMode};
|
||||
|
||||
use super::{AffineUtf16Range, editor_runtime::IosEditorRuntime, ffi::AffineIosHost};
|
||||
|
||||
/// Callback fired when the editor mutates text or selection (`H-S2`).
|
||||
pub type AffineTextInputChangedCallback = extern "C" fn(u8, *mut c_void);
|
||||
|
||||
/// Flushes queued `TextInputStateChange` notifications after `host.editor` borrow has ended
|
||||
/// so UIKit `UITextInputDelegate` callbacks can safely re-enter FFI queries without panicking.
|
||||
pub(crate) fn flush_text_input_changes(host: &AffineIosHost) {
|
||||
let window = host
|
||||
.editor
|
||||
.borrow()
|
||||
.as_ref()
|
||||
.map(IosEditorRuntime::window_handle);
|
||||
if let Some(window) = window {
|
||||
window.flush_text_input_changes();
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn c_str_opt<'a>(ptr: *const c_char) -> Option<&'a str> {
|
||||
if ptr.is_null() {
|
||||
return None;
|
||||
}
|
||||
// SAFETY: Caller guarantees `ptr` is a valid NUL-terminated C string.
|
||||
unsafe { CStr::from_ptr(ptr) }.to_str().ok()
|
||||
}
|
||||
|
||||
/// Returns the `CAMetalLayer *` owned by `MetalRenderer` on iOS, or null on non-iOS hosts.
|
||||
///
|
||||
/// # 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_metal_layer(host: *const AffineIosHost) -> *mut c_void {
|
||||
let Some(host) = (unsafe { host.as_ref() }) else {
|
||||
return core::ptr::null_mut();
|
||||
};
|
||||
host.editor
|
||||
.borrow()
|
||||
.as_ref()
|
||||
.map(IosEditorRuntime::metal_layer_ptr)
|
||||
.unwrap_or(core::ptr::null_mut())
|
||||
}
|
||||
|
||||
/// Returns the authoritative UTF-16 length of the currently focused editor block (`H-S1`).
|
||||
///
|
||||
/// # 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_utf16_len(host: *const AffineIosHost) -> usize {
|
||||
let Some(host) = (unsafe { host.as_ref() }) else {
|
||||
return 0;
|
||||
};
|
||||
if let Some(editor) = host.editor.borrow_mut().as_mut() {
|
||||
return editor.utf16_len();
|
||||
}
|
||||
host.state.utf16_text().len()
|
||||
}
|
||||
|
||||
/// Copies the authoritative UTF-16 code units of the currently focused editor block into
|
||||
/// `out_ptr` (up to `capacity` units) and returns the total UTF-16 length (`H-S1`).
|
||||
///
|
||||
/// # Safety
|
||||
/// `host` must be null or a live pointer; `out_ptr` must be valid for `capacity` writes when non-null.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn affine_ios_host_copy_utf16(
|
||||
host: *const AffineIosHost,
|
||||
out_ptr: *mut u16,
|
||||
capacity: usize,
|
||||
) -> usize {
|
||||
let Some(host) = (unsafe { host.as_ref() }) else {
|
||||
return 0;
|
||||
};
|
||||
let units = if let Some(editor) = host.editor.borrow_mut().as_mut() {
|
||||
editor.utf16_text()
|
||||
} else {
|
||||
host.state.utf16_text().to_vec()
|
||||
};
|
||||
if !out_ptr.is_null() && capacity > 0 && !units.is_empty() {
|
||||
let count = units.len().min(capacity);
|
||||
// SAFETY: Caller guarantees `out_ptr` points to `capacity` writable `u16` elements.
|
||||
unsafe {
|
||||
core::ptr::copy_nonoverlapping(units.as_ptr(), out_ptr, count);
|
||||
}
|
||||
}
|
||||
units.len()
|
||||
}
|
||||
|
||||
/// Dispatches a UIKit touch event (`0=Started, 1=Moved, 2=Ended, 3=Cancelled`) into the GPU 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_touch_event(
|
||||
host: *mut AffineIosHost,
|
||||
touch_id: u64,
|
||||
phase: u8,
|
||||
x: f32,
|
||||
y: f32,
|
||||
) {
|
||||
let Some(host) = (unsafe { host.as_mut() }) else {
|
||||
return;
|
||||
};
|
||||
if let Some(editor) = host.editor.borrow_mut().as_mut() {
|
||||
editor.dispatch_touch(touch_id, phase, x, y);
|
||||
}
|
||||
flush_text_input_changes(host);
|
||||
host.state.request_frame();
|
||||
}
|
||||
|
||||
/// Dispatches a hardware keyboard or editor key event (`enter`, `backspace`, `left`, `right`,
|
||||
/// `up`, `down`, `escape`, `tab`, etc.) into the GPU editor.
|
||||
///
|
||||
/// # Safety
|
||||
/// `host` must be null or a live pointer; `key` and `key_char` must be null or valid C strings.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn affine_ios_host_key_down(
|
||||
host: *mut AffineIosHost,
|
||||
key: *const c_char,
|
||||
key_char: *const c_char,
|
||||
shift: bool,
|
||||
cmd: bool,
|
||||
ctrl: bool,
|
||||
alt: bool,
|
||||
) {
|
||||
let Some(host) = (unsafe { host.as_mut() }) else {
|
||||
return;
|
||||
};
|
||||
let Some(key_str) = (unsafe { c_str_opt(key) }) else {
|
||||
return;
|
||||
};
|
||||
let char_str = unsafe { c_str_opt(key_char) };
|
||||
if let Some(editor) = host.editor.borrow_mut().as_mut() {
|
||||
editor.dispatch_key_down(key_str, char_str, shift, cmd, ctrl, alt);
|
||||
}
|
||||
flush_text_input_changes(host);
|
||||
host.state.request_frame();
|
||||
}
|
||||
|
||||
/// Updates the host form factor (`0=Phone, 1=Tablet, 2=Desktop`) and applies Stage-1 defaults.
|
||||
///
|
||||
/// # 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_form_factor(
|
||||
host: *mut AffineIosHost,
|
||||
form_factor: u8,
|
||||
) {
|
||||
let Some(host) = (unsafe { host.as_mut() }) else {
|
||||
return;
|
||||
};
|
||||
let ff = match form_factor {
|
||||
1 => FormFactor::Tablet,
|
||||
2 => FormFactor::Desktop,
|
||||
_ => FormFactor::Phone,
|
||||
};
|
||||
if let Some(editor) = host.editor.borrow_mut().as_mut() {
|
||||
editor.set_form_factor(ff);
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns `true` when Edgeless authoring is gated read-only (`T1` Stage 1 on touch hosts).
|
||||
///
|
||||
/// # 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_edgeless_readonly(host: *const AffineIosHost) -> bool {
|
||||
let Some(host) = (unsafe { host.as_ref() }) else {
|
||||
return true;
|
||||
};
|
||||
host.editor
|
||||
.borrow()
|
||||
.as_ref()
|
||||
.map(IosEditorRuntime::edgeless_readonly)
|
||||
.unwrap_or(true)
|
||||
}
|
||||
|
||||
/// Returns `true` when Database mutations are gated read-only (`T1` Stage 1 on touch hosts).
|
||||
///
|
||||
/// # 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_database_readonly(host: *const AffineIosHost) -> bool {
|
||||
let Some(host) = (unsafe { host.as_ref() }) else {
|
||||
return true;
|
||||
};
|
||||
host.editor
|
||||
.borrow()
|
||||
.as_ref()
|
||||
.map(IosEditorRuntime::database_readonly)
|
||||
.unwrap_or(true)
|
||||
}
|
||||
|
||||
/// Switches the mounted editor between Page (`0`) and Edgeless (`1`) 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_set_mode(host: *mut AffineIosHost, mode: u8) {
|
||||
let Some(host) = (unsafe { host.as_mut() }) else {
|
||||
return;
|
||||
};
|
||||
let next = if mode == 1 {
|
||||
PlaygroundMode::Edgeless
|
||||
} else {
|
||||
PlaygroundMode::Page
|
||||
};
|
||||
if let Some(editor) = host.editor.borrow_mut().as_mut() {
|
||||
editor.set_mode(next);
|
||||
}
|
||||
}
|
||||
|
||||
/// Registers an observer invoked when the editor changes text or selection (`H-S2`).
|
||||
///
|
||||
/// # Safety
|
||||
/// `host` must be null or a live pointer; `user_data` must outlive the registration.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn affine_ios_host_set_text_input_callback(
|
||||
host: *mut AffineIosHost,
|
||||
cb: Option<AffineTextInputChangedCallback>,
|
||||
user_data: *mut c_void,
|
||||
) {
|
||||
let Some(host) = (unsafe { host.as_mut() }) else {
|
||||
return;
|
||||
};
|
||||
let ud_addr = user_data as usize;
|
||||
if let Some(editor) = host.editor.borrow().as_ref() {
|
||||
let observer = cb.map(|func| {
|
||||
Box::new(move |change| {
|
||||
func(
|
||||
IosEditorRuntime::change_kind_code(change),
|
||||
ud_addr as *mut c_void,
|
||||
);
|
||||
}) as super::editor_platform::TextInputObserver
|
||||
});
|
||||
editor.set_text_input_observer(observer);
|
||||
}
|
||||
}
|
||||
|
||||
/// Monotonic counter incremented on every editor `TextInputStateChange` notification (`H-S2`).
|
||||
///
|
||||
/// # Safety
|
||||
/// `host` must be null or a live pointer returned by `affine_ios_host_create`.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn affine_ios_host_text_input_change_seq(host: *const AffineIosHost) -> u64 {
|
||||
let Some(host) = (unsafe { host.as_ref() }) else {
|
||||
return 0;
|
||||
};
|
||||
host.editor
|
||||
.borrow()
|
||||
.as_ref()
|
||||
.map(IosEditorRuntime::text_input_change_seq)
|
||||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
/// Whether the mounted editor currently wants the system software keyboard shown.
|
||||
///
|
||||
/// # 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_wants_software_keyboard(
|
||||
host: *const AffineIosHost,
|
||||
) -> bool {
|
||||
let Some(host) = (unsafe { host.as_ref() }) else {
|
||||
return false;
|
||||
};
|
||||
host.editor
|
||||
.borrow()
|
||||
.as_ref()
|
||||
.map(IosEditorRuntime::wants_software_keyboard)
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
/// Replaces the mounted document with an empty single-paragraph page and focuses it.
|
||||
///
|
||||
/// # 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_reset_empty_doc(host: *mut AffineIosHost) {
|
||||
let Some(host) = (unsafe { host.as_mut() }) else {
|
||||
return;
|
||||
};
|
||||
if let Some(editor) = host.editor.borrow_mut().as_mut() {
|
||||
editor.reset_empty_document();
|
||||
}
|
||||
flush_text_input_changes(host);
|
||||
host.state.request_frame();
|
||||
}
|
||||
|
||||
/// Reloads the built-in BlockSuite showcase document into the mounted GPU 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_load_showcase_doc(host: *mut AffineIosHost) {
|
||||
let Some(host) = (unsafe { host.as_mut() }) else {
|
||||
return;
|
||||
};
|
||||
if let Some(editor) = host.editor.borrow_mut().as_mut() {
|
||||
editor.load_showcase_document();
|
||||
}
|
||||
flush_text_input_changes(host);
|
||||
host.state.request_frame();
|
||||
}
|
||||
|
||||
/// # Safety
|
||||
/// `host` must be null or a live pointer; `utf16_ptr` must be valid for `utf16_len` reads when non-zero.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn affine_ios_host_insert_text(
|
||||
host: *mut AffineIosHost,
|
||||
utf16_ptr: *const u16,
|
||||
utf16_len: usize,
|
||||
) {
|
||||
let Some(host) = (unsafe { host.as_mut() }) else {
|
||||
return;
|
||||
};
|
||||
let slice = if utf16_len == 0 || utf16_ptr.is_null() {
|
||||
&[]
|
||||
} else {
|
||||
// SAFETY: Caller guarantees `utf16_ptr` points to `utf16_len` initialized `u16`s.
|
||||
unsafe { core::slice::from_raw_parts(utf16_ptr, utf16_len) }
|
||||
};
|
||||
let handled = if let Some(editor) = host.editor.borrow_mut().as_mut() {
|
||||
editor.insert_text(slice);
|
||||
true
|
||||
} else {
|
||||
false
|
||||
};
|
||||
if handled {
|
||||
flush_text_input_changes(host);
|
||||
host.state.selection_overlay_mut().clear();
|
||||
host.state.request_frame();
|
||||
return;
|
||||
}
|
||||
host.state.insert_text(slice);
|
||||
}
|
||||
|
||||
/// # 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_delete_backward(host: *mut AffineIosHost) {
|
||||
let Some(host) = (unsafe { host.as_mut() }) else {
|
||||
return;
|
||||
};
|
||||
let handled = if let Some(editor) = host.editor.borrow_mut().as_mut() {
|
||||
editor.delete_backward();
|
||||
true
|
||||
} else {
|
||||
false
|
||||
};
|
||||
if handled {
|
||||
flush_text_input_changes(host);
|
||||
host.state.selection_overlay_mut().clear();
|
||||
host.state.request_frame();
|
||||
return;
|
||||
}
|
||||
host.state.delete_backward();
|
||||
}
|
||||
|
||||
/// # 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_delete_range(
|
||||
host: *mut AffineIosHost,
|
||||
range: AffineUtf16Range,
|
||||
) {
|
||||
let Some(host) = (unsafe { host.as_mut() }) else {
|
||||
return;
|
||||
};
|
||||
let handled = if let Some(editor) = host.editor.borrow_mut().as_mut() {
|
||||
editor.delete_range(range);
|
||||
true
|
||||
} else {
|
||||
false
|
||||
};
|
||||
if handled {
|
||||
flush_text_input_changes(host);
|
||||
host.state.selection_overlay_mut().clear();
|
||||
host.state.request_frame();
|
||||
return;
|
||||
}
|
||||
host.state.delete_range(range);
|
||||
}
|
||||
|
||||
/// # 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_selected_range(
|
||||
host: *mut AffineIosHost,
|
||||
range: AffineUtf16Range,
|
||||
) {
|
||||
let Some(host) = (unsafe { host.as_mut() }) else {
|
||||
return;
|
||||
};
|
||||
let handled = if let Some(editor) = host.editor.borrow_mut().as_mut() {
|
||||
editor.set_selected_range(range);
|
||||
true
|
||||
} else {
|
||||
false
|
||||
};
|
||||
if handled {
|
||||
flush_text_input_changes(host);
|
||||
if range.length == 0
|
||||
&& host.state.selection_overlay().active_drag_handle()
|
||||
== super::selection::AffineSelectionHandleKind::None
|
||||
{
|
||||
host.state.selection_overlay_mut().clear();
|
||||
}
|
||||
host.state.request_frame();
|
||||
return;
|
||||
}
|
||||
host.state.set_selected_range(range);
|
||||
}
|
||||
|
||||
/// # Safety
|
||||
/// `host` must be null or a live pointer; `utf16_ptr` must be valid for `utf16_len` reads when non-zero.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn affine_ios_host_replace_range(
|
||||
host: *mut AffineIosHost,
|
||||
range: AffineUtf16Range,
|
||||
utf16_ptr: *const u16,
|
||||
utf16_len: usize,
|
||||
) {
|
||||
let Some(host) = (unsafe { host.as_mut() }) else {
|
||||
return;
|
||||
};
|
||||
let slice = if utf16_len == 0 || utf16_ptr.is_null() {
|
||||
&[]
|
||||
} else {
|
||||
// SAFETY: Caller guarantees `utf16_ptr` points to `utf16_len` initialized `u16`s.
|
||||
unsafe { core::slice::from_raw_parts(utf16_ptr, utf16_len) }
|
||||
};
|
||||
let handled = if let Some(editor) = host.editor.borrow_mut().as_mut() {
|
||||
editor.replace_range(range, slice);
|
||||
true
|
||||
} else {
|
||||
false
|
||||
};
|
||||
if handled {
|
||||
flush_text_input_changes(host);
|
||||
host.state.selection_overlay_mut().clear();
|
||||
host.state.request_frame();
|
||||
return;
|
||||
}
|
||||
host.state.replace_range(range, slice);
|
||||
}
|
||||
|
||||
/// # Safety
|
||||
/// `host` must be null or a live pointer; `utf16_ptr` must be valid for `utf16_len` reads when non-zero.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn affine_ios_host_set_marked_text(
|
||||
host: *mut AffineIosHost,
|
||||
utf16_ptr: *const u16,
|
||||
utf16_len: usize,
|
||||
selected_range: AffineUtf16Range,
|
||||
) {
|
||||
let Some(host) = (unsafe { host.as_mut() }) else {
|
||||
return;
|
||||
};
|
||||
let slice = if utf16_len == 0 || utf16_ptr.is_null() {
|
||||
&[]
|
||||
} else {
|
||||
// SAFETY: Caller guarantees `utf16_ptr` points to `utf16_len` initialized `u16`s.
|
||||
unsafe { core::slice::from_raw_parts(utf16_ptr, utf16_len) }
|
||||
};
|
||||
let handled = if let Some(editor) = host.editor.borrow_mut().as_mut() {
|
||||
editor.set_marked_text(slice, selected_range);
|
||||
true
|
||||
} else {
|
||||
false
|
||||
};
|
||||
if handled {
|
||||
flush_text_input_changes(host);
|
||||
host.state.request_frame();
|
||||
return;
|
||||
}
|
||||
host.state.set_marked_text(slice, selected_range);
|
||||
}
|
||||
|
||||
/// # 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_unmark_text(host: *mut AffineIosHost) {
|
||||
let Some(host) = (unsafe { host.as_mut() }) else {
|
||||
return;
|
||||
};
|
||||
let handled = if let Some(editor) = host.editor.borrow_mut().as_mut() {
|
||||
editor.unmark_text();
|
||||
true
|
||||
} else {
|
||||
false
|
||||
};
|
||||
if handled {
|
||||
flush_text_input_changes(host);
|
||||
host.state.request_frame();
|
||||
return;
|
||||
}
|
||||
host.state.unmark_text();
|
||||
}
|
||||
|
||||
/// # 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_range(
|
||||
host: *const AffineIosHost,
|
||||
) -> AffineUtf16Range {
|
||||
let Some(host) = (unsafe { host.as_ref() }) else {
|
||||
return AffineUtf16Range::default();
|
||||
};
|
||||
if let Some(editor) = host.editor.borrow_mut().as_mut() {
|
||||
return editor.selected_range();
|
||||
}
|
||||
host.state.selected_range()
|
||||
}
|
||||
|
||||
/// # 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_marked_range(
|
||||
host: *const AffineIosHost,
|
||||
) -> AffineUtf16Range {
|
||||
let Some(host) = (unsafe { host.as_ref() }) else {
|
||||
return AffineUtf16Range {
|
||||
location: u32::MAX,
|
||||
length: 0,
|
||||
};
|
||||
};
|
||||
if let Some(editor) = host.editor.borrow_mut().as_mut() {
|
||||
return editor.marked_range();
|
||||
}
|
||||
host.state.marked_range()
|
||||
}
|
||||
@@ -106,10 +106,14 @@ pub unsafe extern "C" fn affine_ios_host_text_writing_direction(host: *const Aff
|
||||
let Some(host) = (unsafe { host.as_ref() }) else {
|
||||
return AffineWritingDirection::Ltr as u8;
|
||||
};
|
||||
if let Some(editor) = host.editor.borrow_mut().as_mut() {
|
||||
return editor.writing_direction() as u8;
|
||||
}
|
||||
host.state.text_writing_direction() as u8
|
||||
}
|
||||
|
||||
/// Compute visual caret rect for `utf16_offset` via CoreText `CTLine` (or headless fallback).
|
||||
/// Compute visual caret rect for `utf16_offset` via the live GPU editor `PlatformInputHandler`
|
||||
/// (or CoreText / headless fallback).
|
||||
///
|
||||
/// # Safety
|
||||
/// `host` must be null or a live pointer returned by `affine_ios_host_create`.
|
||||
@@ -121,9 +125,19 @@ pub unsafe extern "C" fn affine_ios_host_text_caret_rect(
|
||||
let Some(host) = (unsafe { host.as_ref() }) else {
|
||||
return AffineRect::default();
|
||||
};
|
||||
if let Some(editor) = host.editor.borrow_mut().as_mut()
|
||||
&& let Some(rect) = editor.caret_rect(utf16_offset)
|
||||
{
|
||||
return rect;
|
||||
}
|
||||
let (vw, _) = host.state.viewport_size_pt();
|
||||
let insets = host.state.insets();
|
||||
let utf16 = host.state.utf16_text();
|
||||
let utf16 = host
|
||||
.editor
|
||||
.borrow_mut()
|
||||
.as_mut()
|
||||
.map(|e| e.utf16_text())
|
||||
.unwrap_or_else(|| host.state.utf16_text().to_vec());
|
||||
if let Some(p) = host.text_provider
|
||||
&& let Some(f) = p.caret_rect
|
||||
{
|
||||
@@ -136,7 +150,7 @@ pub unsafe extern "C" fn affine_ios_host_text_caret_rect(
|
||||
p.user_data,
|
||||
);
|
||||
}
|
||||
caret_rect_for_offset(utf16, utf16_offset, vw, insets)
|
||||
caret_rect_for_offset(&utf16, utf16_offset, vw, insets)
|
||||
}
|
||||
|
||||
/// Compute BiDi-aware per-line selection rectangles across soft-wrapped visual lines.
|
||||
@@ -154,9 +168,27 @@ pub unsafe extern "C" fn affine_ios_host_text_selection_rects(
|
||||
let Some(host) = (unsafe { host.as_ref() }) else {
|
||||
return 0;
|
||||
};
|
||||
if let Some(editor) = host.editor.borrow_mut().as_mut() {
|
||||
let rects = editor.selection_rects(range);
|
||||
if !rects.is_empty() {
|
||||
if !out_rects.is_null() && capacity > 0 {
|
||||
let count = rects.len().min(capacity);
|
||||
// SAFETY: Caller guarantees `out_rects` points to `capacity` writable elements.
|
||||
unsafe {
|
||||
core::ptr::copy_nonoverlapping(rects.as_ptr(), out_rects, count);
|
||||
}
|
||||
}
|
||||
return rects.len();
|
||||
}
|
||||
}
|
||||
let (vw, _) = host.state.viewport_size_pt();
|
||||
let insets = host.state.insets();
|
||||
let utf16 = host.state.utf16_text();
|
||||
let utf16 = host
|
||||
.editor
|
||||
.borrow_mut()
|
||||
.as_mut()
|
||||
.map(|e| e.utf16_text())
|
||||
.unwrap_or_else(|| host.state.utf16_text().to_vec());
|
||||
if let Some(p) = host.text_provider
|
||||
&& let Some(f) = p.selection_rects
|
||||
{
|
||||
@@ -171,7 +203,7 @@ pub unsafe extern "C" fn affine_ios_host_text_selection_rects(
|
||||
p.user_data,
|
||||
);
|
||||
}
|
||||
let rects = selection_rects_for_range(utf16, range, vw, insets);
|
||||
let rects = selection_rects_for_range(&utf16, range, vw, insets);
|
||||
if !out_rects.is_null() && capacity > 0 {
|
||||
let count = rects.len().min(capacity);
|
||||
// SAFETY: Caller guarantees `out_rects` points to `capacity` writable elements.
|
||||
@@ -201,9 +233,55 @@ pub unsafe extern "C" fn affine_ios_host_text_selection_endpoint_carets(
|
||||
) else {
|
||||
return false;
|
||||
};
|
||||
if let Some(editor) = host.editor.borrow_mut().as_mut() {
|
||||
let start_caret = editor.caret_rect(range.location);
|
||||
let end_caret = editor.caret_rect(range.location.saturating_add(range.length));
|
||||
if let (Some(s), Some(e)) = (start_caret, end_caret)
|
||||
&& (range.length == 0 || (s.x - e.x).abs() >= 1.0 || (s.y - e.y).abs() >= 1.0)
|
||||
{
|
||||
*start_slot = s;
|
||||
*end_slot = e;
|
||||
return true;
|
||||
}
|
||||
// At BiDi run boundaries, logical start and end carets share one visual X;
|
||||
// derive handle edges from `editor.selection_rects(range)` in editor space.
|
||||
if range.length > 0 {
|
||||
let rects = editor.selection_rects(range);
|
||||
if let (Some(first), Some(last)) = (rects.first(), rects.last()) {
|
||||
let units = editor.utf16_text();
|
||||
let lo = (range.location as usize).min(units.len());
|
||||
let hi = (range.location.saturating_add(range.length) as usize).min(units.len());
|
||||
let slice_rtl = super::text_layout::detect_writing_direction(&units[lo..hi])
|
||||
== super::selection::AffineWritingDirection::Rtl;
|
||||
let (sx, ex) = if slice_rtl {
|
||||
(first.rect.x + first.rect.width, last.rect.x)
|
||||
} else {
|
||||
(first.rect.x, last.rect.x + last.rect.width)
|
||||
};
|
||||
*start_slot = AffineRect {
|
||||
x: sx,
|
||||
y: first.rect.y,
|
||||
width: 2.0,
|
||||
height: first.rect.height,
|
||||
};
|
||||
*end_slot = AffineRect {
|
||||
x: ex,
|
||||
y: last.rect.y,
|
||||
width: 2.0,
|
||||
height: last.rect.height,
|
||||
};
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
let (vw, _) = host.state.viewport_size_pt();
|
||||
let insets = host.state.insets();
|
||||
let utf16 = host.state.utf16_text();
|
||||
let utf16 = host
|
||||
.editor
|
||||
.borrow_mut()
|
||||
.as_mut()
|
||||
.map(|e| e.utf16_text())
|
||||
.unwrap_or_else(|| host.state.utf16_text().to_vec());
|
||||
if let Some(p) = host.text_provider
|
||||
&& let Some(f) = p.selection_endpoint_carets
|
||||
&& f(
|
||||
@@ -219,9 +297,9 @@ pub unsafe extern "C" fn affine_ios_host_text_selection_endpoint_carets(
|
||||
{
|
||||
return true;
|
||||
}
|
||||
*start_slot = caret_rect_for_offset(utf16, range.location, vw, insets);
|
||||
*start_slot = caret_rect_for_offset(&utf16, range.location, vw, insets);
|
||||
*end_slot = caret_rect_for_offset(
|
||||
utf16,
|
||||
&utf16,
|
||||
range.location.saturating_add(range.length),
|
||||
vw,
|
||||
insets,
|
||||
@@ -255,9 +333,19 @@ pub unsafe extern "C" fn affine_ios_host_text_closest_offset_preferred(
|
||||
let Some(host) = (unsafe { host.as_ref() }) else {
|
||||
return 0;
|
||||
};
|
||||
if let Some(editor) = host.editor.borrow_mut().as_mut()
|
||||
&& let Some(off) = editor.closest_offset(point)
|
||||
{
|
||||
return off;
|
||||
}
|
||||
let (vw, _) = host.state.viewport_size_pt();
|
||||
let insets = host.state.insets();
|
||||
let utf16 = host.state.utf16_text();
|
||||
let utf16 = host
|
||||
.editor
|
||||
.borrow_mut()
|
||||
.as_mut()
|
||||
.map(|e| e.utf16_text())
|
||||
.unwrap_or_else(|| host.state.utf16_text().to_vec());
|
||||
if let Some(p) = host.text_provider
|
||||
&& let Some(f) = p.closest_offset
|
||||
{
|
||||
@@ -271,7 +359,7 @@ pub unsafe extern "C" fn affine_ios_host_text_closest_offset_preferred(
|
||||
p.user_data,
|
||||
);
|
||||
}
|
||||
closest_offset_for_point(utf16, point, vw, insets)
|
||||
closest_offset_for_point(&utf16, point, vw, insets)
|
||||
}
|
||||
|
||||
/// Rasterize the magnifier loupe around `(focus_x, focus_y)` as RGBA8 via whole-line `CTLineDraw`
|
||||
@@ -298,12 +386,32 @@ pub unsafe extern "C" fn affine_ios_host_render_loupe_rgba8(
|
||||
};
|
||||
let (vw, _) = host.state.viewport_size_pt();
|
||||
let insets = host.state.insets();
|
||||
let utf16 = host.state.utf16_text();
|
||||
let selected = host.state.selected_range();
|
||||
let (utf16, selected, editor_origin_caret) =
|
||||
if let Some(editor) = host.editor.borrow_mut().as_mut() {
|
||||
(
|
||||
editor.utf16_text(),
|
||||
editor.selected_range(),
|
||||
editor.caret_rect(0),
|
||||
)
|
||||
} else {
|
||||
(
|
||||
host.state.utf16_text().to_vec(),
|
||||
host.state.selected_range(),
|
||||
None,
|
||||
)
|
||||
};
|
||||
|
||||
if let Some(p) = host.text_provider
|
||||
&& let Some(render_fn) = p.render_loupe_rgba8
|
||||
{
|
||||
let (loupe_focus_x, loupe_focus_y) = if let Some(c0) = editor_origin_caret
|
||||
&& let Some(caret_fn) = p.caret_rect
|
||||
{
|
||||
let ct0 = caret_fn(utf16.as_ptr(), utf16.len(), 0, vw, insets, p.user_data);
|
||||
(focus_x - c0.x + ct0.x, focus_y - c0.y + ct0.y)
|
||||
} else {
|
||||
(focus_x, focus_y)
|
||||
};
|
||||
let mut rgba = vec![0u8; dim * dim * 4];
|
||||
let ok = render_fn(
|
||||
utf16.as_ptr(),
|
||||
@@ -311,8 +419,8 @@ pub unsafe extern "C" fn affine_ios_host_render_loupe_rgba8(
|
||||
selected,
|
||||
vw,
|
||||
insets,
|
||||
focus_x,
|
||||
focus_y,
|
||||
loupe_focus_x,
|
||||
loupe_focus_y,
|
||||
dim as u32,
|
||||
zoom,
|
||||
rgba.as_mut_ptr(),
|
||||
@@ -325,7 +433,7 @@ pub unsafe extern "C" fn affine_ios_host_render_loupe_rgba8(
|
||||
}
|
||||
|
||||
let rgba = render_loupe_rgba8(
|
||||
utf16, selected, vw, insets, focus_x, focus_y, dim as u32, zoom,
|
||||
&utf16, selected, vw, insets, focus_x, focus_y, dim as u32, zoom,
|
||||
);
|
||||
AffineIosByteBuffer::from_vec(rgba)
|
||||
}
|
||||
@@ -9,7 +9,12 @@
|
||||
//! bridges behind `include/affine_mobile_host.h`.
|
||||
|
||||
pub mod auth;
|
||||
#[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_editor;
|
||||
pub mod ffi_s3;
|
||||
pub mod ffi_text;
|
||||
pub mod haptics;
|
||||
|
||||
@@ -89,7 +89,8 @@ struct IosHostS3SmokeTest {
|
||||
testKeyboardAvoidancePerFrameSlideOverAndBackgroundResume()
|
||||
testHapticsBridgeDispatchAndBoundedHistory()
|
||||
testMetalHostViewControllerEndToEndTextSelectionDragCopyAndMenu()
|
||||
print("ALL 5 SWIFT+RUST S3-IOS SMOKE TESTS PASSED")
|
||||
testS6NativeEditorMountImeAndStageOneReadonly()
|
||||
print("ALL 6 SWIFT+RUST S3/S6-IOS SMOKE TESTS PASSED")
|
||||
} catch {
|
||||
fputs("UNHANDLED ERROR: \(error)\n", stderr)
|
||||
exit(1)
|
||||
@@ -444,6 +445,7 @@ struct IosHostS3SmokeTest {
|
||||
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))
|
||||
@@ -505,6 +507,9 @@ struct IosHostS3SmokeTest {
|
||||
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
|
||||
@@ -539,10 +544,18 @@ struct IosHostS3SmokeTest {
|
||||
requireS3(vcCross.textHostView.lastCopiedText == "lo ", "expected copied 'lo ', got \(String(describing: vcCross.textHostView.lastCopiedText))")
|
||||
|
||||
// 5c. BiDi RTL ("שלום 123 abc", "A אבג B"), ZWJ emoji ("A👨👩👧👦B"), soft-wrap boundary & rotation re-layout.
|
||||
let vcRtl = MetalHostViewController()
|
||||
vcRtl.view.frame = CGRect(x: 0, y: 0, width: 390, height: 844)
|
||||
vcRtl.loadViewIfNeeded()
|
||||
vcRtl.view.layoutIfNeeded()
|
||||
func makeEmptyEditorVC(width: CGFloat = 390, height: CGFloat = 844) -> MetalHostViewController {
|
||||
let controller = MetalHostViewController()
|
||||
controller.view.frame = CGRect(x: 0, y: 0, width: width, height: height)
|
||||
controller.loadViewIfNeeded()
|
||||
controller.view.layoutIfNeeded()
|
||||
if let ptr = controller.hostPointer {
|
||||
affine_ios_host_reset_empty_doc(ptr)
|
||||
}
|
||||
return controller
|
||||
}
|
||||
|
||||
let vcRtl = makeEmptyEditorVC()
|
||||
let bidiMixed = "שלום 123 abc"
|
||||
vcRtl.textHostView.insertText(bidiMixed)
|
||||
vcRtl.textHostView.selectedTextRange = AffineTextRange(utf16Range: NSRange(location: 0, length: 4))
|
||||
@@ -592,10 +605,7 @@ struct IosHostS3SmokeTest {
|
||||
// 5) & 6) Mixed LTR-base BiDi ("A אבג B"):
|
||||
// [2,5) ("אבג"): width > 20pt & start_handle right of end_handle by > 20pt.
|
||||
// [2,4) ("אב"): single rect minX strictly > [2,5) minX + 5pt (highlights right two letters, never 'ג').
|
||||
let vcMixed = MetalHostViewController()
|
||||
vcMixed.view.frame = CGRect(x: 0, y: 0, width: 390, height: 844)
|
||||
vcMixed.loadViewIfNeeded()
|
||||
vcMixed.view.layoutIfNeeded()
|
||||
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)))
|
||||
@@ -653,10 +663,7 @@ struct IosHostS3SmokeTest {
|
||||
|
||||
// Unicode canonical equivalence cache regression: replacing precomposed "éB" (2 UTF-16)
|
||||
// with decomposed "e\u{0301}B" (3 UTF-16) on the same host must NOT hit stale 2-unit cache.
|
||||
let vcNorm = MetalHostViewController()
|
||||
vcNorm.view.frame = CGRect(x: 0, y: 0, width: 390, height: 844)
|
||||
vcNorm.loadViewIfNeeded()
|
||||
vcNorm.view.layoutIfNeeded()
|
||||
let vcNorm = makeEmptyEditorVC()
|
||||
vcNorm.textHostView.insertText("\u{00E9}B")
|
||||
_ = vcNorm.textHostView.selectionRects(for: AffineTextRange(utf16Range: NSRange(location: 1, length: 1)))
|
||||
vcNorm.textHostView.replace(
|
||||
@@ -699,10 +706,7 @@ struct IosHostS3SmokeTest {
|
||||
requireS3(vcRtl.textHostView.lastCopiedText == "12", "dragging End handle on 'שלום 123 abc' digits to offset 7 must yield '12', got \(String(describing: vcRtl.textHostView.lastCopiedText))")
|
||||
|
||||
// Single-line drag with +50pt vertical finger drift must not flip active_drag_handle.
|
||||
let vcDrift = MetalHostViewController()
|
||||
vcDrift.view.frame = CGRect(x: 0, y: 0, width: 390, height: 844)
|
||||
vcDrift.loadViewIfNeeded()
|
||||
vcDrift.view.layoutIfNeeded()
|
||||
let vcDrift = makeEmptyEditorVC()
|
||||
vcDrift.textHostView.insertText("Hello world")
|
||||
vcDrift.textHostView.selectedTextRange = AffineTextRange(utf16Range: NSRange(location: 0, length: 5))
|
||||
let driftBefore = vcDrift.selectionOverlay.currentState
|
||||
@@ -723,19 +727,13 @@ struct IosHostS3SmokeTest {
|
||||
requireS3(vcDrift.textHostView.lastCopiedText == "Hello wor", "vertical drift drag must select 'Hello wor', got \(String(describing: vcDrift.textHostView.lastCopiedText))")
|
||||
|
||||
// Multi-paragraph "A\nשלום" paragraph 2 must set is_rtl == true.
|
||||
let vcPara = MetalHostViewController()
|
||||
vcPara.view.frame = CGRect(x: 0, y: 0, width: 390, height: 844)
|
||||
vcPara.loadViewIfNeeded()
|
||||
vcPara.view.layoutIfNeeded()
|
||||
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 = MetalHostViewController()
|
||||
vcZwj.view.frame = CGRect(x: 0, y: 0, width: 390, height: 844)
|
||||
vcZwj.loadViewIfNeeded()
|
||||
vcZwj.view.layoutIfNeeded()
|
||||
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
|
||||
@@ -750,10 +748,7 @@ struct IosHostS3SmokeTest {
|
||||
}
|
||||
|
||||
// Soft-wrap boundary offset ("ABCDZ" in 72pt width) starts line 2 and emits no 2pt sliver on line 1.
|
||||
let vcNarrow = MetalHostViewController()
|
||||
vcNarrow.view.frame = CGRect(x: 0, y: 0, width: 72, height: 300)
|
||||
vcNarrow.loadViewIfNeeded()
|
||||
vcNarrow.view.layoutIfNeeded()
|
||||
let vcNarrow = makeEmptyEditorVC(width: 72, height: 300)
|
||||
vcNarrow.textHostView.insertText("ABCDZ")
|
||||
let cNarrow0 = vcNarrow.textHostView.caretRect(for: AffineTextPosition(utf16Offset: 0))
|
||||
var wrapBoundaryOffset = -1
|
||||
@@ -768,12 +763,12 @@ struct IosHostS3SmokeTest {
|
||||
let tailRects = vcNarrow.textHostView.selectionRects(
|
||||
for: AffineTextRange(utf16Range: NSRange(location: wrapBoundaryOffset, length: 5 - wrapBoundaryOffset))
|
||||
)
|
||||
requireS3(tailRects.count == 1 && tailRects[0].rect.minY > cNarrow0.minY + 10.0, "selecting from soft-wrap boundary must emit 1 rect on line 2 with zero sliver on line 1 (got \(tailRects.count))")
|
||||
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 }))"
|
||||
)
|
||||
|
||||
let vcWrap = MetalHostViewController()
|
||||
vcWrap.view.frame = CGRect(x: 0, y: 0, width: 390, height: 844)
|
||||
vcWrap.loadViewIfNeeded()
|
||||
vcWrap.view.layoutIfNeeded()
|
||||
let vcWrap = makeEmptyEditorVC()
|
||||
let longLine = "AFFiNE native iOS CoreText soft line wrapping verification across multiple wrapped visual lines"
|
||||
vcWrap.textHostView.insertText(longLine)
|
||||
let caret0Wrap = vcWrap.textHostView.caretRect(for: AffineTextPosition(utf16Offset: 0))
|
||||
@@ -848,10 +843,7 @@ struct IosHostS3SmokeTest {
|
||||
return dark
|
||||
}
|
||||
|
||||
let vcLoupe = MetalHostViewController()
|
||||
vcLoupe.view.frame = CGRect(x: 0, y: 0, width: 390, height: 844)
|
||||
vcLoupe.loadViewIfNeeded()
|
||||
vcLoupe.view.layoutIfNeeded()
|
||||
let vcLoupe = makeEmptyEditorVC()
|
||||
vcLoupe.textHostView.insertText("WWWW ....")
|
||||
vcLoupe.textHostView.selectedTextRange = AffineTextRange(utf16Range: NSRange(location: 0, length: 16))
|
||||
let loupeStartState = vcLoupe.selectionOverlay.currentState
|
||||
@@ -880,10 +872,7 @@ struct IosHostS3SmokeTest {
|
||||
)
|
||||
|
||||
// 5e. Keyboard occlusion hides handles & menu at y ~= 710, preserves selection/copy, then restores on dismiss.
|
||||
let vcKb = MetalHostViewController()
|
||||
vcKb.view.frame = CGRect(x: 0, y: 0, width: 390, height: 844)
|
||||
vcKb.loadViewIfNeeded()
|
||||
vcKb.view.layoutIfNeeded()
|
||||
let vcKb = makeEmptyEditorVC()
|
||||
let fillerLines = String(repeating: "\n", count: 35)
|
||||
let bottomWord = "BottomTarget"
|
||||
vcKb.textHostView.insertText(fillerLines + bottomWord)
|
||||
@@ -966,4 +955,130 @@ struct IosHostS3SmokeTest {
|
||||
}
|
||||
print("PASS [5/5]: MetalHostViewController E2E selection, crossover, RTL/soft-wrap, real loupe glyphs, and keyboard occlusion/restore passed")
|
||||
}
|
||||
|
||||
/// 6. S6 native GPU PlaygroundView mount: zero HostTextPreviewView, live CAMetalLayer,
|
||||
/// H-S1 zero backingText copy (Markdown `# ` + `[[` -> `@`), H-S2 inputDelegate notifications,
|
||||
/// newline block split & block-start deleteBackward merge, and T1 Stage-1 touch readonly.
|
||||
@MainActor
|
||||
static func testS6NativeEditorMountImeAndStageOneReadonly() {
|
||||
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, "MetalHostViewController must initialize hostHandle")
|
||||
return
|
||||
}
|
||||
|
||||
// Verify Metal GPU layer is attached directly to hostView (zero HostTextPreviewView class exists).
|
||||
let hasMetalSublayer = (vc.textHostView.layer.sublayers ?? []).contains { $0 is CAMetalLayer }
|
||||
requireS3(hasMetalSublayer, "MetalRenderer CAMetalLayer must be attached to MetalHostView")
|
||||
|
||||
// Live MetalRenderer CAMetalLayer attached as sublayer on iOS.
|
||||
let rawMetal = affine_ios_host_metal_layer(handle)
|
||||
requireS3(rawMetal != nil, "affine_ios_host_metal_layer must return MetalRenderer CAMetalLayer")
|
||||
|
||||
// Stage-1 touch defaults: Phone & Tablet default to edgeless_readonly + database_readonly.
|
||||
requireS3(affine_ios_host_edgeless_readonly(handle), "iOS touch host must default edgeless_readonly = true")
|
||||
requireS3(affine_ios_host_database_readonly(handle), "iOS touch host must default database_readonly = true")
|
||||
|
||||
// Reset to empty doc for authoritative H-S1 / H-S2 IME verification.
|
||||
affine_ios_host_reset_empty_doc(handle)
|
||||
let seqBefore = affine_ios_host_text_input_change_seq(handle)
|
||||
vc.textHostView.insertText("# Heading")
|
||||
let seqAfter = affine_ios_host_text_input_change_seq(handle)
|
||||
requireS3(seqAfter > seqBefore, "H-S2: editor text mutation must advance text_input_change_seq")
|
||||
let fullRange = vc.textHostView.textRange(
|
||||
from: vc.textHostView.beginningOfDocument,
|
||||
to: vc.textHostView.endOfDocument
|
||||
)
|
||||
let readBack = fullRange.flatMap { vc.textHostView.text(in: $0) } ?? ""
|
||||
requireS3(readBack.contains("Heading"), "H-S1: UITextInput must read authoritative editor text, got '\(readBack)'")
|
||||
|
||||
// Block split on newline + block-start deleteBackward merge.
|
||||
vc.textHostView.insertText("\n")
|
||||
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)'")
|
||||
vc.textHostView.deleteBackward()
|
||||
let afterMergeRange = vc.textHostView.textRange(
|
||||
from: vc.textHostView.beginningOfDocument,
|
||||
to: vc.textHostView.endOfDocument
|
||||
)
|
||||
let afterMerge = afterMergeRange.flatMap { vc.textHostView.text(in: $0) } ?? ""
|
||||
requireS3(afterMerge.contains("Heading"), "deleteBackward at block start must merge back, got '\(afterMerge)'")
|
||||
|
||||
// Verify non-zero safe-area insets (top=59pt, bottom=34pt) keep hostView,
|
||||
// selectionOverlayView, and caretRect in one shared (0, 0) safe-area frame.
|
||||
let safeWindow = UIWindow(frame: CGRect(x: 0, y: 0, width: 390, height: 844))
|
||||
let vcSafe = MetalHostViewController()
|
||||
vcSafe.additionalSafeAreaInsets = UIEdgeInsets(top: 59, left: 0, bottom: 34, right: 0)
|
||||
safeWindow.rootViewController = vcSafe
|
||||
safeWindow.isHidden = false
|
||||
safeWindow.layoutIfNeeded()
|
||||
vcSafe.view.layoutIfNeeded()
|
||||
requireS3(
|
||||
abs(vcSafe.textHostView.frame.origin.y - vcSafe.view.safeAreaInsets.top) < 0.5
|
||||
&& vcSafe.view.safeAreaInsets.top >= 59.0
|
||||
&& abs(
|
||||
vcSafe.textHostView.frame.height
|
||||
- (vcSafe.view.bounds.height - vcSafe.view.safeAreaInsets.top - vcSafe.view.safeAreaInsets.bottom)
|
||||
) < 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")
|
||||
let c0 = vcSafe.textHostView.caretRect(for: AffineTextPosition(utf16Offset: 0))
|
||||
let c8 = vcSafe.textHostView.caretRect(for: AffineTextPosition(utf16Offset: 8))
|
||||
requireS3(c8.minX > c0.minX, "caretRect in safe-area hostView must advance horizontally")
|
||||
|
||||
// UIKit IME contract: Pinyin/Kana setMarkedText -> setMarkedText -> insertText
|
||||
// must NOT echo textWillChange/textDidChange back to UITextInputDelegate, whereas
|
||||
// editor-initiated/external mutations MUST notify it.
|
||||
final class CountingInputDelegate: NSObject, UITextInputDelegate {
|
||||
var textWillChangeCount = 0
|
||||
var textDidChangeCount = 0
|
||||
var selectionWillChangeCount = 0
|
||||
var selectionDidChangeCount = 0
|
||||
func selectionWillChange(_ textInput: UITextInput?) { selectionWillChangeCount += 1 }
|
||||
func selectionDidChange(_ textInput: UITextInput?) { selectionDidChangeCount += 1 }
|
||||
func textWillChange(_ textInput: UITextInput?) { textWillChangeCount += 1 }
|
||||
func textDidChange(_ textInput: UITextInput?) { textDidChangeCount += 1 }
|
||||
@available(iOS 18.4, *)
|
||||
func conversationContext(_ context: UIConversationContext?, didChange textInput: (any UITextInput)?) {}
|
||||
}
|
||||
affine_ios_host_reset_empty_doc(safeHandle)
|
||||
let countingDelegate = CountingInputDelegate()
|
||||
vcSafe.textHostView.inputDelegate = countingDelegate
|
||||
vcSafe.textHostView.setMarkedText("ni", selectedRange: NSRange(location: 2, length: 0))
|
||||
vcSafe.textHostView.setMarkedText("nihao", selectedRange: NSRange(location: 5, length: 0))
|
||||
vcSafe.textHostView.insertText("你好")
|
||||
requireS3(
|
||||
countingDelegate.textWillChangeCount == 0 && countingDelegate.textDidChangeCount == 0,
|
||||
"IME-originated Pinyin sequence must trigger 0 textWillChange/textDidChange callbacks (got will=\(countingDelegate.textWillChangeCount), did=\(countingDelegate.textDidChangeCount))"
|
||||
)
|
||||
// External editor mutation (reset / shortcut) MUST notify inputDelegate.
|
||||
affine_ios_host_reset_empty_doc(safeHandle)
|
||||
requireS3(
|
||||
countingDelegate.textWillChangeCount > 0 || countingDelegate.selectionDidChangeCount > 0,
|
||||
"External editor mutation must notify UITextInputDelegate"
|
||||
)
|
||||
vcSafe.textHostView.inputDelegate = nil
|
||||
}
|
||||
|
||||
// Reload showcase document and trigger a real GPU Metal frame render.
|
||||
affine_ios_host_load_showcase_doc(handle)
|
||||
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")
|
||||
}
|
||||
}
|
||||
@@ -156,6 +156,7 @@ ALLOWED_DEPS = {
|
||||
}
|
||||
|
||||
HOST_ALLOWED = UI_ALL | BS_LOWER | {
|
||||
"blocksuite/crates/playground",
|
||||
"packages/common/store",
|
||||
"packages/frontend/legacy-import",
|
||||
"packages/frontend/client",
|
||||
|
||||
@@ -131,15 +131,17 @@ web-sys = { workspace = true, features = [
|
||||
] }
|
||||
wgpu = { workspace = true, features = ["webgl", "webgpu", "wgsl"] }
|
||||
|
||||
[target.'cfg(target_os = "linux")'.dependencies]
|
||||
[target.'cfg(any(target_os = "linux", target_os = "android"))'.dependencies]
|
||||
bytemuck.workspace = true
|
||||
cosmic-text.workspace = true
|
||||
font-kit = { workspace = true, optional = true }
|
||||
libc.workspace = true
|
||||
swash.workspace = true
|
||||
unicode-bidi.workspace = true
|
||||
wgpu = { workspace = true, features = ["std", "vulkan", "gles", "wgsl"] }
|
||||
|
||||
[target.'cfg(target_os = "linux")'.dependencies]
|
||||
font-kit = { workspace = true, optional = true }
|
||||
|
||||
[target.'cfg(any(target_os = "macos", target_os = "ios"))'.dependencies]
|
||||
block2.workspace = true
|
||||
core-foundation.workspace = true
|
||||
|
||||
@@ -138,8 +138,10 @@ pub use platform::macos::MacPlatform;
|
||||
|
||||
#[cfg(all(target_os = "linux", any(test, feature = "harness")))]
|
||||
pub use platform::wgpu::WgpuHeadlessRenderer;
|
||||
#[cfg(any(target_os = "linux", target_family = "wasm"))]
|
||||
pub use platform::wgpu::{CosmicTextSystem, WgpuContext, WgpuRenderer, WgpuSurfaceConfig};
|
||||
#[cfg(any(target_os = "linux", target_os = "android", target_family = "wasm"))]
|
||||
pub use platform::wgpu::{
|
||||
CosmicTextSystem, GpuContext, WgpuContext, WgpuRenderer, WgpuSurfaceConfig,
|
||||
};
|
||||
|
||||
#[cfg(target_family = "wasm")]
|
||||
pub use platform::web::{
|
||||
|
||||
@@ -19,7 +19,7 @@ pub mod web;
|
||||
#[cfg(all(test, not(target_family = "wasm")))]
|
||||
#[path = "platform/web/viewport.rs"]
|
||||
mod web_viewport_unit_tests;
|
||||
#[cfg(any(target_os = "linux", target_family = "wasm"))]
|
||||
#[cfg(any(target_os = "linux", target_os = "android", target_family = "wasm"))]
|
||||
pub mod wgpu;
|
||||
|
||||
/// Types for configuring parent-anchored popup windows such as menus, dropdowns and tooltips.
|
||||
|
||||
@@ -293,7 +293,7 @@ impl MetalRenderer {
|
||||
// https://developer.apple.com/documentation/metal/setting-resource-storage-modes
|
||||
// iOS does not support managed resources. Its simulator may report a
|
||||
// non-unified host GPU even though resources must still use shared storage.
|
||||
let is_unified_memory = false || device.hasUnifiedMemory();
|
||||
let is_unified_memory = cfg!(target_os = "ios") || device.hasUnifiedMemory();
|
||||
// Apple GPU families support memoryless textures, which can significantly reduce
|
||||
// memory usage by keeping render targets in on-chip tile memory instead of
|
||||
// allocating backing store in system memory.
|
||||
|
||||
@@ -1160,7 +1160,7 @@ fn clip_font_runs(font_runs: &[FontRun], range: Range<usize>) -> SmallVec<[FontR
|
||||
clipped
|
||||
}
|
||||
|
||||
#[cfg(all(feature = "font-kit", not(target_family = "wasm")))]
|
||||
#[cfg(all(feature = "font-kit", target_os = "linux"))]
|
||||
fn find_best_match(
|
||||
font: &Font,
|
||||
candidates: &[FontId],
|
||||
@@ -1186,7 +1186,7 @@ fn find_best_match(
|
||||
Ok(ix)
|
||||
}
|
||||
|
||||
#[cfg(any(not(feature = "font-kit"), target_family = "wasm"))]
|
||||
#[cfg(not(all(feature = "font-kit", target_os = "linux")))]
|
||||
fn find_best_match(
|
||||
font: &Font,
|
||||
candidates: &[FontId],
|
||||
@@ -1358,7 +1358,7 @@ fn cosmic_font_features(features: &FontFeatures) -> Result<CosmicFontFeatures> {
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
#[cfg(all(feature = "font-kit", not(target_family = "wasm")))]
|
||||
#[cfg(all(feature = "font-kit", target_os = "linux"))]
|
||||
fn font_into_properties(font: &crate::Font) -> font_kit::properties::Properties {
|
||||
font_kit::properties::Properties {
|
||||
style: match font.style {
|
||||
@@ -1371,7 +1371,7 @@ fn font_into_properties(font: &crate::Font) -> font_kit::properties::Properties
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(feature = "font-kit", not(target_family = "wasm")))]
|
||||
#[cfg(all(feature = "font-kit", target_os = "linux"))]
|
||||
fn face_info_into_properties(
|
||||
face_info: &cosmic_text::fontdb::FaceInfo,
|
||||
) -> font_kit::properties::Properties {
|
||||
|
||||
@@ -13,7 +13,7 @@ use std::{
|
||||
#[cfg(any(target_os = "macos", target_os = "ios"))]
|
||||
const EMOJI_FONT_FAMILIES: &[&str] = &["Apple Color Emoji", ".AppleColorEmojiUI"];
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
#[cfg(any(target_os = "linux", target_os = "android"))]
|
||||
const EMOJI_FONT_FAMILIES: &[&str] = &[
|
||||
"Noto Color Emoji",
|
||||
"Emoji One",
|
||||
|
||||
Reference in new issue
Block a user