mirror of
https://github.com/toeverything/AFFiNE.git
synced 2026-12-05 11:15:01 +03:00
The shell padded the bottom edge by the keyboard height, and the embedded page editor lifted its keyboard toolbar by the same height again. In Page mode the editor now owns the bottom edge. The shell gives the editor its resolved keyboard height, so the toolbar sits directly on the keyboard. - Hide the TabBar while the software keyboard is up, as 0.27.5 AppTabs does. The accessibility tree follows the same rule. - Move the focus from the editor to the shell when an overlay sheet opens over a page, so the keyboard goes down. The drawer keeps its own focus. - Add NativeSelectionUi to MobileShellView. The iOS shell lets UITextInteraction draw the handles, caret, and selection. The Android shell draws the handles natively and keeps the GPU caret. - Scroll a long Search query or drawer filter only as far as necessary to keep the caret or the end of the composition in view. The renderer, the scroll, and the IME rects and touch offsets read one shaped layout of the line, and place it in the field with one transform. A line that fits sits at the start edge of the locale, and its glyphs always run left to right in text order, also in RTL locales. - Retry the Android bootstrap from onResume and onNewIntent while the allowlist is empty or the shell has not mounted the workspace that bootstrap opened. Stop after three automatic retries. - Send accessibility events only while an accessibility service runs. The system clears the focus after the last service stops, and the event send threw at that time.
9.5 KiB
9.5 KiB
Working in packages/frontend/hosts/android/ (for agents)
This directory holds the thin Android host for AFFiNE (affine-android-host).
It combines a hand-written JNI Rust crate with a minimal Kotlin SurfaceView activity.
Hard boundaries
- Keep zero JNA and zero UniFFI bindings.
Export hand-written
extern "C"JNI symbols under#[cfg(any(target_os = "android", test, feature = "host-jni"))]acrosssrc/jni_bridge.rs,src/jni_editor.rs,src/jni_interaction.rs,src/jni_shell.rs, andsrc/jni_storage.rs. MainActivitycreates its host withnativeCreateShellHost, which mounts theaffine-mobileMobileShellView;nativeCreateHostkeeps one barePlaygroundViewfor editor-only parity sequences.src/runtime_root.rsresolves the editor that owns theInputConnectionand selection handles: the root editor, or the shell's embeddedpage_editor()while thePageroute shows with no sheet or drawer above it. The shell's focusedEntityInputHandlertakesInputConnectiontext on the Search route with no sheet above it and in the drawer once its filter holdssearch_focus; while any other sheet, or the drawer without a focused filter, covers the shell, the runtime drops text and composition edits.nativeHandleBacklets the page editor close its overlay first, then runsMobileBackCoordinator, and returnsfalseat the root route. Every bootstrap result (first start, retried start, andretryFailedWorkspaces) goes throughMainActivity.applyBootstrapOutcome, which mounts the first allowlisted workspace that bootstrap opened (AndroidBootstrapCoordinator.shellWorkspaceId) withnativeShellMountWorkspace(src/shell_workspace.rs): the mount loads only the root document anddb$*tables, each page loads when the shell opens it (a failed load retries the next time the page shows), a scheduler task commits edits every second (zero SQLite access without pending changes), andnativeShellFlushWorkspacecommits them inonStop.onConfigurationChangedandonResumepass the system dark mode tonativeShellSetSystemDark.AffineSurfaceViewpublishes the shell'sAccessibilityTree(nativeShellAccessibilityJson, parsed byShellAccessibilityNode) as virtual views throughAccessibilityNodeProviderwith stable virtual view IDs per node ID and accessibility focus (ShellAccessibilityViews), and an accessibility click sends a tap at the node center.ShellAccessibilityViewssends accessibility events only whileAccessibilityManager.isEnabledis true, so the system can clear the focus after the last service stops. A retried bootstrap reads the allowlist again while no shell workspace is mounted (AndroidBootstrapCoordinator.retryPlan).ShellBootstrapStatekeeps the bootstrap state of the activity:onResumeandonNewIntentretry asretryPlanplans while no shell workspace is mounted (an incomplete outcome, an allowlist without a workspace yet, or a failed mount), at most three times in a row, and drain shares otherwise.- Keep the main app shell free of any persistent
WebViewand free ofSurfaceHolder.lockCanvascalls. - Mount the live pure-Rust
PlaygroundView(src/editor_platform.rs,src/editor_runtime/mod.rs,src/editor_selection.rs,src/jni_editor.rs, withnative_selection_ui = true) insideMainActivity(AffineSurfaceView+DocumentSelectionHandleView, withHostTextPreviewViewand the customCopy | Cutcapsule removed fromMainActivity). Drive GPU document-level teardrop handles, systemandroid.widget.Magnifier(API 28+), systemActionMode.TYPE_FLOATING(ActionMode.Callback2.onGetContentRect+onPrepareActionModegated by Rustaction_mask), and multi-MIMEClipboardManager(ClipData.newHtmlTextcarrying embeddeddata-blocksuite-snapshot+ plain text) from RustPlaygroundView, hiding handles/Magnifier/ActionMode wheneverdocumentBufferController.isAutofillFocused()is true. ForwardMotionEventtouch pointers (nativeOnTouchEvent),InputConnection.sendKeyEvent(nativeOnKeyEvent), andFormFactor::from_android_smallest_width_dp(< 600->Phone,>= 600->Tablet, Stage-1edgeless_readonly = true,database_readonly = true). - Enforce zero host text copy (
AffineInputConnectionreads straight fromPlatformInputHandler), push editor mutations toInputMethodManager.updateSelection/restartInput/updateCursorAnchorInfo, and preserve exact[start, end)ranges insetComposingRegionviareplace_and_mark_text_in_range. - Use
scripts/package-debug-apk.shto build and signAffineAndroidHost-debug.apkdirectly 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 toClipboardManager(HostClipboard/AndroidClipboardAdapter, checkingprimaryClipDescriptionmetadata without readingprimaryClipduring draw, and writing before deleting onCut) andInputConnection.performContextMenuActioninsrc/selection.rs,src/ime.rs, andMainActivity.kt.AndroidSelectionOverlayViewfills a pre-allocated 24-float JNI buffer (nativeFillSelectionOverlayGeometry) and draws teardropPathhandles,getSelectionPathloupe highlights with centered focus carets, andCopy | Cut | Pastepills with dividers using zero per-frame allocations, zero Binder IPC inonDraw, and zeroSurfaceHolder.lockCanvascalls. - Clear the default surface canvas to light
#FAFAFC(DEFAULT_CLEAR_COLOR_ARGB = 0xFFFA_FAFC) and adaptHostTextPreviewViewtext and selection colors to surface luminance. Preserve viewport size, display density, scroll offset, IME state, and texture generation acrosssurfaceDestroyed -> surfaceCreated -> surfaceChangedrecreation while gatingis_ready()on per-generationsurfaceChangedconfiguration (configured_for_generation).SurfaceLifecycleStatemodelsVulkan -> Gles3 -> CpuFallbackdowngrade on device loss; the currentandroid_windowruntime probe returns(false, true)and starts on EGL/GLES3 with CPU fallback. - Gate
AutofillManagervirtual view structure and per-field isolated value write-back at API 26 (should_expose_autofill(sdk_int)returnssdk_int >= 26,IMPORTANT_FOR_AUTOFILL_YESonAffineSurfaceView, implemented insrc/autofill.rsandAndroidAutofillController). Never emit synthetic placeholder asterisks or spaces inViewStructure, update IME only whenautofillId == focusedFieldId, sync manualInputConnectionedits back to the focused Autofill field viaonFocusedTextEdited, isolate form credentials fromHostDocumentStoreandHostTextPreviewViewviaHostDocumentBufferController, redact sensitive values inDebug, and zero cached plaintext oncommit,cancel, andclear_fields. - Dispatch four-phase predictive back (
Start,Progress,Cancel,Commit) on API 34+ (OnBackAnimationCallback, including standalone button/keyonBackInvokedcalls) and single-step atomic commit on API 24-33 (OnBackInvokedCallback/onBackPressed) against a real destination route stack (BackNavigationState) andHostDocumentStoredriven byMainActivity.navigateToandMainActivity.openDocument, blocking re-entrant commits and returningfalseat the root route. - Render PDF pages in place through
android.graphics.pdf.PdfRenderer(AndroidPdfPageRenderer) with pre-validated Rust bounds, OOM cap (4096x4096), clampeddpi_bucket >= 72cache keys, and zero-Rust-heap chunked streamingARGB_8888 -> RGBA8conversion with per-call JNIExceptionCheckinsrc/pdf.rsandsrc/jni_interaction.rs. - Open in-place SQLite WAL databases only from the ordered
affine-local-workspaceallowlist. Never scan disk*.dbfiles to discover local workspaces. - Store auth sessions in
<filesDir>/datastore/auth-sessions.preferences_pbusingv1:<base64_iv>:<base64_ct_tag>AES-GCM envelopes, 1970 Unix millisecondi64timestamps, and the persistedauth-installation-idkey. - Parse legacy
https://localhostlocalStorageprobe and rollback write-back payloads throughparse_legacy_local_storage_probeusing an explicit key allowlist only. Blockwindow.indexedDB.openandwindow.indexedDB.deleteDatabasein every probe script. - Keep every
.rsfile at or below 800 non-test lines, free of non-testsuper::super::, and free of wall-clock calls.
Verification
Always clear inherited root rustflags:
CARGO_ENCODED_RUSTFLAGS="" cargo test --locked -p affine-android-host --all-features
CARGO_ENCODED_RUSTFLAGS="" cargo build --locked -p affine-android-host --features host-jni
CARGO_ENCODED_RUSTFLAGS="" cargo check --locked -p affine-android-host --target aarch64-linux-android
To run the 33-sequence Kotlin-to-JNI parity harness on a host with kotlinc and ANDROID_HOME:
kotlinc -classpath "$ANDROID_JAR" -d /tmp/affine-android-kotlin \
hosts/android/kotlin/app/affine/pro/host/MainActivity.kt \
hosts/android/kotlin/app/affine/pro/host/LegacyLocalStorageProbe.kt \
hosts/android/kotlin/app/affine/pro/host/AndroidBootstrapCoordinator.kt \
hosts/android/kotlin/app/affine/pro/host/AuthDataStore.kt \
hosts/android/kotlin/app/affine/pro/host/ShareIntentBridge.kt \
hosts/android/kotlin/app/affine/pro/host/ShareReceiverActivity.kt \
hosts/android/tests/ImeHostParityCheck.kt
kotlin -J-Djava.library.path="$PWD/target/debug" -cp "/tmp/affine-android-kotlin:$ANDROID_JAR" ImeHostParityCheckKt