Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
package com.foxdebug.acode.cursor

import android.os.Build
import android.view.HapticFeedbackConstants
import androidx.annotation.Keep
import com.foxdebug.acode.runtime.Callback
import com.foxdebug.acode.runtime.Service
import org.json.JSONArray

/**
* Plays the Quick Tools cursor controller's haptics through the platform's
* own feedback constants, so they feel like the rest of the system and follow
* the user's touch feedback setting.
*/
@Keep
class CursorController : Service() {
override fun execute(action: String, args: JSONArray, callback: Callback): Boolean {
if (action != ACTION_FEEDBACK) return false
val view = webView
val constant = feedbackConstant(args.optString(0))
if (view != null && constant != null) {
view.post { view.performHapticFeedback(constant) }
}
callback.success()
return true
}

private fun feedbackConstant(kind: String): Int? = when (kind) {
"tick" -> tick()
"edge" -> reject()
"select" -> HapticFeedbackConstants.LONG_PRESS
"start" -> HapticFeedbackConstants.VIRTUAL_KEY
"end" -> sinceOMr1(HapticFeedbackConstants.VIRTUAL_KEY_RELEASE)
"confirm" -> confirm()
else -> null
}

// TEXT_HANDLE_MOVE and CLOCK_TICK are silent on many devices, so caret
// steps use the slider tick, falling back to the context-click tick.
private fun tick(): Int =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
HapticFeedbackConstants.SEGMENT_TICK
} else {
HapticFeedbackConstants.CONTEXT_CLICK
}

private fun reject(): Int =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
HapticFeedbackConstants.REJECT
} else {
HapticFeedbackConstants.LONG_PRESS
}

private fun confirm(): Int =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
HapticFeedbackConstants.CONFIRM
} else {
HapticFeedbackConstants.VIRTUAL_KEY
}

private fun sinceOMr1(constant: Int): Int? =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) constant else null

private companion object {
const val ACTION_FEEDBACK = "feedback"
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ enum class ServiceName(val key: String) {
NATIVE_HTTP("NativeHttpPlugin"),
BUILD_INFO("BuildInfo"),
CRASH_HANDLER("CrashHandler"),
CURSOR_CONTROLLER("CursorController"),
CUSTOM_TABS("CustomTabs"),
DEVICE("Device"),
FILE("File"),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import com.foxdebug.acode.auth.Authenticator
import com.foxdebug.acode.browser.Plugin
import com.foxdebug.acode.buildinfo.BuildInfo
import com.foxdebug.acode.crashhandler.CrashHandler
import com.foxdebug.acode.cursor.CursorController
import com.foxdebug.acode.customtabs.CustomTabsPlugin
import com.foxdebug.acode.device.Device
import com.foxdebug.acode.file.FileUtils
Expand All @@ -28,6 +29,7 @@ object ServiceRegistry {
ServiceDefinition(ServiceName.NATIVE_HTTP) { NativeHttpPlugin() },
ServiceDefinition(ServiceName.BUILD_INFO) { BuildInfo() },
ServiceDefinition(ServiceName.CRASH_HANDLER, loadOnStart = true) { CrashHandler() },
ServiceDefinition(ServiceName.CURSOR_CONTROLLER) { CursorController() },
ServiceDefinition(ServiceName.CUSTOM_TABS) { CustomTabsPlugin() },
ServiceDefinition(ServiceName.DEVICE) { Device() },
ServiceDefinition(ServiceName.FILE, loadOnStart = true) { FileUtils() },
Expand Down
138 changes: 138 additions & 0 deletions src/cm/cursorController/caretDrag.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
import {
EditorSelection,
type EditorState,
type SelectionRange,
type TransactionSpec,
} from "@codemirror/state";

interface Coords {
left: number;
right: number;
top: number;
bottom: number;
}

export interface CaretDragView {
state: EditorState;
scrollDOM: { scrollLeft: number };
defaultLineHeight: number;
dispatch(spec: TransactionSpec): void;
moveVertically(start: SelectionRange, forward: boolean): SelectionRange;
coordsAtPos(pos: number, side?: -1 | 1): Coords | null;
posAtCoords(coords: { x: number; y: number }, precise: false): number | null;
}

export interface CaretDragResult {
moved: boolean;
blocked: boolean;
changedRow: boolean;
}

/**
* The caret follows the finger 1:1, with no speed curve. A position at a
* soft-wrap break belongs to two visual rows, so ranges keep their `assoc`
* to stay on the row the finger is on.
*/
export default class CaretDrag {
#view: CaretDragView;
#anchor: number | null = null;
#startX: number | null = null;
#startScrollLeft = 0;
#originY = 0;
#lineOffset = 0;

constructor(view: CaretDragView) {
this.#view = view;
this.#captureStart(0);
}

set extend(value: boolean) {
this.#anchor = value ? this.#view.state.selection.main.anchor : null;
}

update(offsetX: number, offsetY: number): CaretDragResult {
const view = this.#view;
if (this.#startX == null) this.#captureStart(offsetX);
const { main } = view.state.selection;
const lineHeight = view.defaultLineHeight || 1;
const targetLines = Math.round((offsetY - this.#originY) / lineHeight);
let range = EditorSelection.cursor(main.head, main.assoc);
let blocked = false;
let changedRow = false;

while (this.#lineOffset !== targetLines) {
const forward = targetLines > this.#lineOffset;
const next = view.moveVertically(range, forward);
if (this.#sameRow(range, next)) {
blocked = true;
this.#originY = offsetY - this.#lineOffset * lineHeight;
break;
}
range = next;
changedRow = true;
this.#lineOffset += forward ? 1 : -1;
}

const target = this.#cursorAtX(range, offsetX) ?? range;
const { head, assoc } = target;
const anchor = Math.min(this.#anchor ?? head, view.state.doc.length);
const sameSide = anchor !== head || assoc < 0 === main.assoc < 0;
if (anchor === main.anchor && head === main.head && sameSide) {
return { moved: false, blocked, changedRow };
}
view.dispatch({
selection: EditorSelection.create([
EditorSelection.range(anchor, head, undefined, undefined, assoc),
]),
scrollIntoView: true,
userEvent: "select",
});
return { moved: true, blocked, changedRow };
}

#captureStart(offsetX: number): void {
const view = this.#view;
const { main } = view.state.selection;
const coords = this.#coords(main.head, main.assoc);
if (!coords) return;
this.#startX = coords.left - offsetX;
this.#startScrollLeft = view.scrollDOM.scrollLeft;
}

#sameRow(from: SelectionRange, to: SelectionRange): boolean {
if (from.head === to.head && from.assoc < 0 === to.assoc < 0) return true;
const before = this.#coords(from.head, from.assoc);
const after = this.#coords(to.head, to.assoc);
if (!before || !after) {
const { doc } = this.#view.state;
return doc.lineAt(from.head).number === doc.lineAt(to.head).number;
}
return this.#sameTop(before, after);
}

#cursorAtX(range: SelectionRange, offsetX: number): SelectionRange | null {
const view = this.#view;
const row = this.#coords(range.head, range.assoc);
if (!row || this.#startX == null) return null;
const scrolled = view.scrollDOM.scrollLeft - this.#startScrollLeft;
const pos = view.posAtCoords(
{
x: this.#startX + offsetX - scrolled,
y: (row.top + row.bottom) / 2,
},
false,
);
if (pos == null) return null;
const after = view.coordsAtPos(pos, 1);
const endOfRow = !!after && !this.#sameTop(after, row);
return EditorSelection.cursor(pos, endOfRow ? -1 : 0);
}

#coords(pos: number, assoc: number): Coords | null {
return this.#view.coordsAtPos(pos, assoc < 0 ? -1 : 1);
}

#sameTop(a: Coords, b: Coords): boolean {
return Math.abs(a.top - b.top) < (this.#view.defaultLineHeight || 1) / 2;
}
}
45 changes: 45 additions & 0 deletions src/cm/cursorController/feedback.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import config from "lib/config";
import appSettings from "lib/settings";
import exec from "native/exec";
import haptic from "utils/haptic";

export type CursorFeedback =
| "tick"
| "edge"
| "select"
| "start"
| "end"
| "confirm";

const TICK_INTERVAL_MS = 35;
const STRONG_FEEDBACK: CursorFeedback[] = ["edge", "select", "confirm"];

let lastTickTime = 0;

/**
* Android plays the matching system haptic constant natively. Elsewhere the
* app's generic haptic stands in, with ticks throttled so quick drags don't buzz.
*/
export default function cursorFeedback(kind: CursorFeedback): void {
const { vibrateOnTap, cursorControllerHaptics } = appSettings.value;
if (!vibrateOnTap || !cursorControllerHaptics) return;

const platformId = window.Bridge?.platformId;
if (platformId === "android") {
try {
exec(null, null, "CursorController", "feedback", [kind]);
} catch (error) {
console.error("Cursor controller feedback failed", error);
}
return;
}

if (kind === "start" || kind === "end") return;
if (platformId !== "ios" && !STRONG_FEEDBACK.includes(kind)) return;
if (kind === "tick") {
const now = performance.now();
if (now - lastTickTime < TICK_INTERVAL_MS) return;
lastTickTime = now;
}
haptic(config.VIBRATION_TIME);
}
19 changes: 18 additions & 1 deletion src/cm/touchSelectionMenu.js
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,7 @@ class TouchSelectionMenuController {
#stateSyncRaf = 0;
#isScrolling = false;
#isPointerInteracting = false;
#isMenuHeld = false;
#pointerSelectionSession = null;
#readOnlyTapSession = null;
#pendingPointerSelectionClick = null;
Expand Down Expand Up @@ -311,6 +312,7 @@ class TouchSelectionMenuController {
this.#menuRequested = false;
this.#isPointerInteracting = false;
this.#isScrolling = false;
this.#isMenuHeld = false;
this.#clearMenuShowTimer();
cancelAnimationFrame(this.#stateSyncRaf);
this.#stateSyncRaf = 0;
Expand Down Expand Up @@ -365,6 +367,18 @@ class TouchSelectionMenuController {
this.#hideMenu();
}

holdMenu(held) {
if (!this.#enabled || this.#canvas) return;
this.#isMenuHeld = !!held;
if (held) {
this.#clearMenuShowTimer();
this.#cancelReadOnlyTap();
this.#hideMenu();
return;
}
if (this.#shouldShowMenu()) this.#scheduleMenuShow(MENU_SHOW_DELAY);
}

onScrollEnd() {
if (!this.#enabled || this.#canvas || !this.#isScrolling) return;
this.#isScrolling = false;
Expand Down Expand Up @@ -405,6 +419,7 @@ class TouchSelectionMenuController {
this.#menuRequested = false;
this.#isPointerInteracting = false;
this.#isScrolling = false;
this.#isMenuHeld = false;
this.#clearMenuShowTimer();
this.#hideMenu(true);
if (this.#canvas) this.#view.touchSelection?.hideMenu();
Expand Down Expand Up @@ -689,7 +704,9 @@ class TouchSelectionMenuController {
}

#shouldShowMenu() {
if (this.#isScrolling || this.#isPointerInteracting) return false;
if (this.#isScrolling || this.#isPointerInteracting || this.#isMenuHeld) {
return false;
}
if (!this.#view.hasFocus && !this.#isReadOnly()) return false;
if (
!this.#menuRequested &&
Expand Down
Loading
Loading