Skip to content

👾 Open Computer Use – Open-Source Alternative to Codex Computer Use

Add standalone cursor app from reconstructed model

ifuryst33a76faa6d3e
diff --git a/Package.swift b/Package.swift
index af25dc2..12cc295 100644
--- a/Package.swift
+++ b/Package.swift
@@ -28,6 +28,10 @@ let package = Package(
name: "StandaloneCursorLab",
targets: ["StandaloneCursorLab"]
),
+ .executable(
+ name: "StandaloneCursor",
+ targets: ["StandaloneCursor"]
+ ),
],
targets: [
.target(
@@ -56,10 +60,24 @@ let package = Package(
.process("Resources"),
]
),
+ .target(
+ name: "StandaloneCursorSupport",
+ path: "experiments/StandaloneCursor/Sources/StandaloneCursorSupport"
+ ),
+ .executableTarget(
+ name: "StandaloneCursor",
+ dependencies: ["StandaloneCursorSupport"],
+ path: "experiments/StandaloneCursor/Sources/StandaloneCursor"
+ ),
.testTarget(
name: "OpenComputerUseKitTests",
dependencies: ["OpenComputerUseKit"],
path: "packages/OpenComputerUseKit/Tests/OpenComputerUseKitTests"
),
+ .testTarget(
+ name: "StandaloneCursorSupportTests",
+ dependencies: ["StandaloneCursorSupport"],
+ path: "experiments/StandaloneCursor/Tests/StandaloneCursorSupportTests"
+ ),
]
)
diff --git a/README.md b/README.md
index 0d8f5f5..02e6a3a 100644
--- a/README.md
+++ b/README.md
@@ -56,15 +56,17 @@ open-computer-use doctor
open-computer-use -h
```
-## Cursor Lab
+## Cursor Demos
-This repo also includes an experimental standalone cursor-motion demo for iterating on the Codex-style software cursor without coupling every experiment to the MCP server:
+This repo now includes two standalone cursor-motion demos so the reconstructed model and the more speculative lab work can evolve separately:
```bash
+swift run StandaloneCursor
swift run StandaloneCursorLab
```
-The lab lives in [`experiments/StandaloneCursorLab`](./experiments/StandaloneCursorLab) and currently exposes tunable `START HANDLE`, `END HANDLE`, `ARC SIZE`, `ARC FLOW`, and `SPRING` controls.
+- [`experiments/StandaloneCursor`](./experiments/StandaloneCursor) is the cleaner binary-guided viewer built directly from `scripts/cursor-motion-re/official_cursor_motion.py`. It focuses on the recovered 20-candidate pool, score model, and raw spring timeline.
+- [`experiments/StandaloneCursorLab`](./experiments/StandaloneCursorLab) remains the more experimental lab for UI-heavy tuning, candidate overlays, and visual-dynamics exploration.
## License
diff --git a/README.zh-CN.md b/README.zh-CN.md
index 4b28ce3..0c38069 100644
--- a/README.zh-CN.md
+++ b/README.zh-CN.md
@@ -61,15 +61,17 @@ open-computer-use doctor
open-computer-use -h
```
-## Cursor Lab
+## Cursor Demos
-仓库里现在还带了一个独立的 cursor motion 实验 demo,用来脱离 MCP 主链路单独调软件鼠标的轨迹和手感:
+仓库里现在有两条独立的 cursor motion demo 线路,把“基于重建脚本的直接实现”和“更自由的实验室版本”拆开维护:
```bash
+swift run StandaloneCursor
swift run StandaloneCursorLab
```
-这个实验目录在 [`experiments/StandaloneCursorLab`](./experiments/StandaloneCursorLab),当前已经提供 `START HANDLE`、`END HANDLE`、`ARC SIZE`、`ARC FLOW`、`SPRING` 这组可调参数。
+- [`experiments/StandaloneCursor`](./experiments/StandaloneCursor) 是一条更干净的 binary-guided viewer,直接对应 `scripts/cursor-motion-re/official_cursor_motion.py` 里的候选路径池、score 和 raw spring timeline。
+- [`experiments/StandaloneCursorLab`](./experiments/StandaloneCursorLab) 继续保留为更偏实验的 lab,用来做 UI、candidate overlay 和 visual dynamics 调参。
## License
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index af04fd5..f8fbe2d 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -20,6 +20,8 @@
- fixture test bridge
- `experiments/StandaloneCursorLab`
独立的 Swift cursor motion lab,用于试验 `Bezier + arc + spring` 参数模型、调参 UI 和独立渲染,不直接耦合主 MCP runtime。
+- `experiments/StandaloneCursor`
+ 新的独立 Swift cursor viewer,直接复用 `scripts/cursor-motion-re/official_cursor_motion.py` 里收敛出来的候选路径、score 与 raw spring timeline,用来观察更贴近 binary lift 的表现。
- `scripts/`
仓库级自动化命令,包括 smoke test、`.app` 打包入口、npm 分发脚本,以及 `scripts/computer-use-cli/` 这个用于探测官方 bundled `computer-use` 的 Go helper。
- `docs/`
@@ -75,6 +77,9 @@
### 5. Cursor Lab
+- `StandaloneCursor` 是一个新的独立 SwiftUI/AppKit demo target,可通过 `swift run StandaloneCursor` 本地启动。
+- 这条线优先验证 Python 重建脚本已经收敛出来的核心:`20` 条候选路径、`measure + score`、`prefer in-bounds then lowest-score` 选路,以及 `response=1.4` / `dampingFraction=0.9` / `dt=1/240` 的 raw spring timeline。
+- 当前它刻意不引入 speculative 的 wall-clock duration 映射,也不复用 `StandaloneCursorLab` 里更偏视觉手感试验的 pose dynamics。
- `StandaloneCursorLab` 是一个单独的 SwiftUI demo target,可通过 `swift run StandaloneCursorLab` 本地启动。
- 这条线优先验证 motion model 本身:参数层、路径层、spring/timing 模拟和 debug UI。
- 当前它不接真实 tool call,也不回写主 `SoftwareCursorOverlay`,目的是把实验噪音与产品行为边界隔离开。
@@ -90,6 +95,7 @@
## 主要验证路径
- 单元测试:`swift test`
+- standalone cursor 构建:`swift build --product StandaloneCursor`
- cursor lab 构建:`swift build --product StandaloneCursorLab`
- 端到端 smoke:`./scripts/run-tool-smoke-tests.sh`
- app 打包:`./scripts/build-open-computer-use-app.sh debug`
diff --git a/docs/exec-plans/completed/20260419-standalone-cursor-from-python-reconstruction.md b/docs/exec-plans/completed/20260419-standalone-cursor-from-python-reconstruction.md
new file mode 100644
index 0000000..94de81e
--- /dev/null
+++ b/docs/exec-plans/completed/20260419-standalone-cursor-from-python-reconstruction.md
@@ -0,0 +1,70 @@
+# 基于 Python 重建脚本实现新的 StandaloneCursor
+
+## 目标
+
+新增一条不依赖现有 `StandaloneCursorLab` 的独立 Swift demo 线路,把 `scripts/cursor-motion-re/official_cursor_motion.py` 已经收敛出来的候选路径、score、selection policy 和 raw spring timeline 直接搬进一个可运行的 `swift run StandaloneCursor` app。
+
+## 范围
+
+- 包含:
+ - 新增 `StandaloneCursor` executable target。
+ - 新增独立 support module,承载 Python 脚本对应的 Swift 数据模型、候选生成、评分与 timeline。
+ - 新增最小可交互 app UI,用于拖动起终点、选 candidate、重放路径。
+ - 补充 README、架构文档和 history。
+- 不包含:
+ - 不修改现有 `StandaloneCursorLab` 的代码和 UI 逻辑。
+ - 不把这条 demo 直接接回主 `SoftwareCursorOverlay`。
+ - 不宣称已经恢复官方 wall-clock duration 映射。
+
+## 背景
+
+- 相关文档:
+ - `docs/ARCHITECTURE.md`
+ - `docs/REPO_COLLAB_GUIDE.md`
+ - `scripts/cursor-motion-re/README.md`
+- 相关代码路径:
+ - `scripts/cursor-motion-re/official_cursor_motion.py`
+ - `experiments/StandaloneCursor/`
+ - `Package.swift`
+- 已知约束:
+ - 当前 worktree 里 `StandaloneCursorLab` 相关文件已经处于脏状态,应避免继续踩那条线。
+ - 这次目标是“更贴 Python 脚本的独立 viewer”,不是再堆一版可调参数实验室。
+
+## 风险
+
+- 风险:把 Python 脚本里“已确认的核心”和“仍未恢复的 duration 映射”混在一起。
+- 缓解方式:UI 和文档里显式写明只复用 raw spring timeline,不假装已经恢复 wall-clock duration。
+
+- 风险:与当前 `StandaloneCursorLab` 的本地改动发生冲突。
+- 缓解方式:新建完全独立的 target、源码目录和测试目录。
+
+## 里程碑
+
+1. 新 target 和 support model 边界收敛。
+2. Swift app 与交互视图实现。
+3. 验证、文档与 history 收尾。
+
+## 验证方式
+
+- 命令:
+ - `swift build --product StandaloneCursor`
+ - `swift test --filter StandaloneCursorSupportTests`
+ - `swift run StandaloneCursor`
+- 手工检查:
+ - 拖动 `START` / `END`,确认候选路径和选中 candidate 会更新。
+ - 点击右侧 candidate,确认能切到手动锁定并重放。
+- 观测检查:
+ - UI 中能看到 endpoint lock / close-enough 时间以及 raw progress。
+ - 文档明确区分 `StandaloneCursor` 与 `StandaloneCursorLab` 的职责。
+
+## 进度记录
+
+- [x] 里程碑 1
+- [x] 里程碑 2
+- [x] 里程碑 3
+
+## 决策记录
+
+- 2026-04-19:不继续改当前 `StandaloneCursorLab`,改为新增 `StandaloneCursor` target,避免与现有脏 worktree 冲突。
+- 2026-04-19:support model 直接按 Python 脚本命名和结构翻译,优先保证候选路径、评分和 timeline 的可对照性。
+- 2026-04-19:新 app 刻意不做 speculative 的视觉 pose dynamics,只展示 binary-guided path pool 与 raw spring playback。
diff --git a/docs/histories/2026-04/20260419-2300-add-standalone-cursor-from-python-reconstruction.md b/docs/histories/2026-04/20260419-2300-add-standalone-cursor-from-python-reconstruction.md
new file mode 100644
index 0000000..26a3b92
--- /dev/null
+++ b/docs/histories/2026-04/20260419-2300-add-standalone-cursor-from-python-reconstruction.md
@@ -0,0 +1,33 @@
+## [2026-04-19 23:00] | Task: 新增基于 Python 重建脚本的 StandaloneCursor
+
+### 🤖 Execution Context
+* **Agent ID**: `codex`
+* **Base Model**: `GPT-5`
+* **Runtime**: `Codex CLI`
+
+### 📥 User Query
+> 现在有一个 `swift run StandaloneCursorLab` 的版本,但是感觉做得很不理想。基于单独的 `scripts/cursor-motion-re/reconstruct_cursor_motion.py` 去实现一个新的 `StandaloneCursor` 版本出来看看。
+
+### 🛠 Changes Overview
+**Scope:** `Package.swift`、`experiments/StandaloneCursor/`、`README*`、`docs/`
+
+**Key Actions:**
+- **[新增独立 target]**: 在 `Package.swift` 里增加 `StandaloneCursor` executable target、`StandaloneCursorSupport` support module 和对应测试 target,避免继续改当前脏着的 `StandaloneCursorLab` 线路。
+- **[Swift 版重建模型]**: 在 `experiments/StandaloneCursor/Sources/StandaloneCursorSupport/StandaloneCursorModel.swift` 里按 Python 脚本重建 `20` 条 candidate、`measure + score`、selection policy,以及 `response=1.4` / `dampingFraction=0.9` / `dt=1/240` 的 raw spring timeline。
+- **[新独立 viewer]**: 新增 `StandaloneCursor` app,支持拖动起终点、切换 candidate、重放路径,并把 endpoint lock / close-enough 时间直接展示在 UI 上。
+- **[验证与文档]**: 新增 `StandaloneCursorSupportTests`,并补齐 `experiments/StandaloneCursor/README.md`、顶层 README、`docs/ARCHITECTURE.md` 和执行计划。
+
+### 🧠 Design Intent (Why)
+现有 `StandaloneCursorLab` 更偏视觉和交互实验,不适合继续承载“基于 Python 脚本直接对照 binary lift”的诉求。这次把新 viewer 做成独立 target,一方面能保留旧 lab 的实验自由度,另一方面也能给后续对照脚本、继续往主运行时收敛时提供一个更干净的中间层。
+
+### 📁 Files Modified
+- `Package.swift`
+- `experiments/StandaloneCursor/README.md`
+- `experiments/StandaloneCursor/Sources/StandaloneCursor/StandaloneCursorApp.swift`
+- `experiments/StandaloneCursor/Sources/StandaloneCursor/StandaloneCursorRootView.swift`
+- `experiments/StandaloneCursor/Sources/StandaloneCursorSupport/StandaloneCursorModel.swift`
+- `experiments/StandaloneCursor/Tests/StandaloneCursorSupportTests/StandaloneCursorSupportTests.swift`
+- `README.md`
+- `README.zh-CN.md`
+- `docs/ARCHITECTURE.md`
+- `docs/exec-plans/completed/20260419-standalone-cursor-from-python-reconstruction.md`
diff --git a/experiments/StandaloneCursor/README.md b/experiments/StandaloneCursor/README.md
new file mode 100644
index 0000000..c9099dc
--- /dev/null
+++ b/experiments/StandaloneCursor/README.md
@@ -0,0 +1,32 @@
+# Standalone Cursor
+
+这个目录承载一条新的独立 cursor demo 线路,目标不是继续堆调参 UI,而是直接把 `scripts/cursor-motion-re/official_cursor_motion.py` 里已经收敛出来的重建结果搬成一个可运行的 Swift app。
+
+## 目标边界
+
+- 直接复用 Python 脚本里已经确认的几何和 timing 核心:
+ - `2` 条 base candidate + `3 x 3 x 2` arched candidate
+ - `sample(progress)` 与 `measure(...)`
+ - `prefer in-bounds, then lowest score`
+ - `response=1.4`、`dampingFraction=0.9`、`dt=1/240` 的 raw spring timeline
+- 刻意不引入当前还没恢复出来的 wall-clock duration 映射。
+- 刻意不复用 `StandaloneCursorLab` 那套更偏实验性的 visual dynamics / knob 调参结构。
+
+## 运行方式
+
+```bash
+swift run StandaloneCursor
+```
+
+## 当前交互
+
+- 拖动 `START` / `END` handle,实时重算 `20` 条候选路径。
+- 右侧面板会列出全部 candidates、score、length、turn 和 in-bounds 状态。
+- 默认按 Python 脚本同一套策略自动选路,也可以手动锁定某一条 candidate。
+- `Replay` 会按 raw spring timeline 重放当前选中路径。
+
+## 适用场景
+
+- 想看 Python 重建逻辑换成 Swift 之后的实际轨迹和时序表现。
+- 想快速核对候选路径池、score 和 endpoint lock / close-enough 时间,而不是继续调视觉手感。
+- 想和 `StandaloneCursorLab` 做对照,区分“脚本级 binary lift”与“更自由的实验 demo”。
diff --git a/experiments/StandaloneCursor/Sources/StandaloneCursor/StandaloneCursorApp.swift b/experiments/StandaloneCursor/Sources/StandaloneCursor/StandaloneCursorApp.swift
new file mode 100644
index 0000000..65ef28e
--- /dev/null
+++ b/experiments/StandaloneCursor/Sources/StandaloneCursor/StandaloneCursorApp.swift
@@ -0,0 +1,57 @@
+import AppKit
+import SwiftUI
+
+@main
+enum StandaloneCursorMain {
+ static func main() {
+ let application = NSApplication.shared
+ application.setActivationPolicy(.regular)
+
+ let delegate = StandaloneCursorAppDelegate()
+ application.delegate = delegate
+ application.run()
+ }
+}
+
+@MainActor
+final class StandaloneCursorAppDelegate: NSObject, NSApplicationDelegate {
+ private var window: NSWindow?
+
+ func applicationDidFinishLaunching(_ notification: Notification) {
+ installMenu()
+
+ let window = NSWindow(
+ contentRect: NSRect(x: 0, y: 0, width: 1360, height: 860),
+ styleMask: [.titled, .closable, .miniaturizable, .resizable],
+ backing: .buffered,
+ defer: false
+ )
+ window.title = "Standalone Cursor"
+ window.center()
+ window.isReleasedWhenClosed = false
+ window.minSize = NSSize(width: 1180, height: 760)
+ window.contentView = NSHostingView(rootView: StandaloneCursorRootView())
+
+ self.window = window
+ window.orderFrontRegardless()
+ window.makeKeyAndOrderFront(nil)
+ NSRunningApplication.current.activate(options: [.activateAllWindows])
+ NSApp.activate(ignoringOtherApps: true)
+ }
+
+ func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
+ true
+ }
+
+ private func installMenu() {
+ let mainMenu = NSMenu()
+ let appMenuItem = NSMenuItem()
+ mainMenu.addItem(appMenuItem)
+
+ let appMenu = NSMenu()
+ appMenu.addItem(withTitle: "Quit Standalone Cursor", action: #selector(NSApplication.terminate(_:)), keyEquivalent: "q")
+ appMenuItem.submenu = appMenu
+
+ NSApp.mainMenu = mainMenu
+ }
+}
diff --git a/experiments/StandaloneCursor/Sources/StandaloneCursor/StandaloneCursorRootView.swift b/experiments/StandaloneCursor/Sources/StandaloneCursor/StandaloneCursorRootView.swift
new file mode 100644
index 0000000..28e0abf
--- /dev/null
+++ b/experiments/StandaloneCursor/Sources/StandaloneCursor/StandaloneCursorRootView.swift
@@ -0,0 +1,856 @@
+import AppKit
+import QuartzCore
+import SwiftUI
+import StandaloneCursorSupport
+
+struct StandaloneCursorRootView: View {
+ @StateObject private var model = StandaloneCursorViewModel()
+
+ var body: some View {
+ HStack(spacing: 0) {
+ GeometryReader { proxy in
+ let bounds = StandaloneCursorViewModel.canvasBounds(for: proxy.size)
+
+ ZStack(alignment: .topLeading) {
+ canvasBackground
+
+ RoundedRectangle(cornerRadius: 34, style: .continuous)
+ .fill(
+ LinearGradient(
+ colors: [
+ Color(red: 0.07, green: 0.11, blue: 0.16),
+ Color(red: 0.04, green: 0.07, blue: 0.11),
+ ],
+ startPoint: .topLeading,
+ endPoint: .bottomTrailing
+ )
+ )
+ .overlay(
+ RoundedRectangle(cornerRadius: 34, style: .continuous)
+ .stroke(Color.white.opacity(0.08), lineWidth: 1)
+ )
+ .padding(20)
+
+ BoundsBackdrop(bounds: bounds)
+
+ if model.showAllCandidates {
+ ForEach(model.orderedCandidates) { candidate in
+ MotionCurveShape(motionPath: candidate.path)
+ .stroke(
+ candidate.id == model.selectedCandidate?.id
+ ? Color(red: 1.0, green: 0.72, blue: 0.28).opacity(0.42)
+ : candidate.measurement.staysInBounds
+ ? Color(red: 0.53, green: 0.78, blue: 0.90).opacity(0.20)
+ : Color.white.opacity(0.08),
+ lineWidth: candidate.id == model.selectedCandidate?.id ? 3.5 : 1.1
+ )
+ }
+ }
+
+ if let selected = model.selectedCandidate {
+ MotionCurveShape(motionPath: selected.path)
+ .stroke(
+ LinearGradient(
+ colors: [
+ Color(red: 0.98, green: 0.81, blue: 0.33),
+ Color(red: 0.95, green: 0.50, blue: 0.20),
+ ],
+ startPoint: .leading,
+ endPoint: .trailing
+ ),
+ style: StrokeStyle(lineWidth: 4.5, lineCap: .round, lineJoin: .round)
+ )
+
+ MotionTrailShape(motionPath: selected.path, progress: model.displayProgress)
+ .stroke(
+ LinearGradient(
+ colors: [
+ Color(red: 0.73, green: 0.94, blue: 0.98),
+ Color(red: 0.36, green: 0.73, blue: 0.89),
+ ],
+ startPoint: .leading,
+ endPoint: .trailing
+ ),
+ style: StrokeStyle(lineWidth: 7, lineCap: .round, lineJoin: .round)
+ )
+ .shadow(color: Color(red: 0.36, green: 0.73, blue: 0.89).opacity(0.26), radius: 16)
+
+ if model.showControlPolygon {
+ ControlPolygonLayer(candidate: selected)
+ }
+ }
+
+ HandleView(label: "START", tint: Color(red: 0.35, green: 0.86, blue: 0.80))
+ .offset(x: model.start.x - 18, y: model.start.y - 18)
+ .gesture(
+ DragGesture(minimumDistance: 0)
+ .onChanged { value in
+ model.setStart(to: value.location, livePreview: true)
+ }
+ .onEnded { value in
+ model.setStart(to: value.location, livePreview: false)
+ }
+ )
+
+ HandleView(label: "END", tint: Color(red: 1.0, green: 0.65, blue: 0.26))
+ .offset(x: model.end.x - 18, y: model.end.y - 18)
+ .gesture(
+ DragGesture(minimumDistance: 0)
+ .onChanged { value in
+ model.setEnd(to: value.location, livePreview: true)
+ }
+ .onEnded { value in
+ model.setEnd(to: value.location, livePreview: false)
+ }
+ )
+
+ CursorGlyphView(heading: model.headingAngle)
+ .offset(x: model.currentPoint.x, y: model.currentPoint.y)
+
+ statusCard
+ .padding(28)
+ }
+ .onAppear {
+ model.updateCanvasBounds(bounds)
+ }
+ .onChange(of: proxy.size) { _, newSize in
+ model.updateCanvasBounds(StandaloneCursorViewModel.canvasBounds(for: newSize))
+ }
+ }
+
+ sidebar
+ .frame(width: 336)
+ .background(
+ LinearGradient(
+ colors: [
+ Color(red: 0.10, green: 0.08, blue: 0.06),
+ Color(red: 0.06, green: 0.06, blue: 0.08),
+ ],
+ startPoint: .top,
+ endPoint: .bottom
+ )
+ )
+ }
+ }
+
+ private var canvasBackground: some View {
+ LinearGradient(
+ colors: [
+ Color(red: 0.12, green: 0.16, blue: 0.21),
+ Color(red: 0.08, green: 0.11, blue: 0.16),
+ Color(red: 0.04, green: 0.05, blue: 0.07),
+ ],
+ startPoint: .topLeading,
+ endPoint: .bottomTrailing
+ )
+ .overlay(alignment: .topLeading) {
+ Circle()
+ .fill(Color(red: 1.0, green: 0.58, blue: 0.18).opacity(0.13))
+ .frame(width: 360, height: 360)
+ .blur(radius: 60)
+ .offset(x: -110, y: -80)
+ }
+ .overlay(alignment: .bottomTrailing) {
+ Circle()
+ .fill(Color(red: 0.28, green: 0.72, blue: 0.92).opacity(0.16))
+ .frame(width: 320, height: 320)
+ .blur(radius: 52)
+ .offset(x: 80, y: 100)
+ }
+ }
+
+ private var statusCard: some View {
+ VStack(alignment: .leading, spacing: 10) {
+ Text("BINARY-GUIDED STANDALONE CURSOR")
+ .font(.system(size: 12, weight: .black, design: .rounded))
+ .tracking(0.9)
+ .foregroundStyle(Color.white.opacity(0.92))
+
+ Text(model.selectionModeLabel)
+ .font(.system(size: 11, weight: .semibold, design: .rounded))
+ .tracking(0.4)
+ .foregroundStyle(Color(red: 0.98, green: 0.79, blue: 0.35))
+
+ Text(model.selectedCandidateSummary)
+ .font(.system(size: 13, weight: .medium, design: .rounded))
+ .foregroundStyle(Color.white.opacity(0.78))
+
+ Text(model.timingSummary)
+ .font(.system(size: 11, weight: .medium, design: .rounded))
+ .foregroundStyle(Color.white.opacity(0.56))
+
+ Text("Ground truth here is the reconstructed path pool, measurement, score formula, and the raw 1.4 / 0.9 spring chain from the Python script. Duration mapping is still intentionally not claimed as recovered.")
+ .font(.system(size: 11, weight: .regular, design: .rounded))
+ .foregroundStyle(Color.white.opacity(0.48))
+ .fixedSize(horizontal: false, vertical: true)
+ .frame(maxWidth: 360, alignment: .leading)
+ }
+ .padding(18)
+ .background(
+ RoundedRectangle(cornerRadius: 22, style: .continuous)
+ .fill(Color.black.opacity(0.26))
+ .overlay(
+ RoundedRectangle(cornerRadius: 22, style: .continuous)
+ .stroke(Color.white.opacity(0.08), lineWidth: 1)
+ )
+ )
+ }
+
+ private var sidebar: some View {
+ ScrollView {
+ VStack(alignment: .leading, spacing: 16) {
+ VStack(alignment: .leading, spacing: 8) {
+ Text("StandaloneCursor")
+ .font(.system(size: 24, weight: .black, design: .rounded))
+ .foregroundStyle(Color.white.opacity(0.96))
+ Text("A new standalone viewer built from `scripts/cursor-motion-re/official_cursor_motion.py`, with the visual surface stripped back to the binary-lifted path pool, score model, and spring timeline.")
+ .font(.system(size: 12, weight: .medium, design: .rounded))
+ .foregroundStyle(Color.white.opacity(0.62))
+ .fixedSize(horizontal: false, vertical: true)
+ }
+
+ VStack(alignment: .leading, spacing: 10) {
+ HStack(spacing: 10) {
+ ActionButton(title: "Replay", accent: .warm) {
+ model.replay()
+ }
+ ActionButton(title: "Auto", accent: .cool) {
+ model.useAutomaticSelection()
+ }
+ }
+
+ Toggle("Show all candidates", isOn: $model.showAllCandidates)
+ Toggle("Show control polygon", isOn: $model.showControlPolygon)
+ }
+ .toggleStyle(StandaloneCursorToggleStyle())
+ .padding(16)
+ .background(cardBackground)
+
+ VStack(alignment: .leading, spacing: 8) {
+ MetricRow(label: "Selection policy", value: model.selectionPolicy)
+ MetricRow(label: "Selected", value: model.selectedCandidate?.id ?? "none")
+ MetricRow(label: "In bounds", value: model.selectedCandidate?.measurement.staysInBounds == true ? "true" : "false")
+ MetricRow(label: "Raw progress", value: model.formatted(model.rawProgress))
+ MetricRow(label: "Display progress", value: model.formatted(model.displayProgress))
+ MetricRow(label: "Elapsed", value: "\(model.formatted(model.playbackTime)) s")
+ }
+ .padding(16)
+ .background(cardBackground)
+
+ VStack(alignment: .leading, spacing: 8) {
+ Text("Timing")
+ .font(.system(size: 14, weight: .bold, design: .rounded))
+ .foregroundStyle(Color.white.opacity(0.88))
+ MetricRow(label: "Endpoint lock", value: model.timelineMetricString(model.timeline?.firstEndpointLockTime))
+ MetricRow(label: "Close enough", value: model.timelineMetricString(model.timeline?.closeEnoughFirstTime))
+ MetricRow(label: "Reported hz", value: model.timeline.map { "\((Int(round(1 / ($0.springConfiguration.dt * CGFloat($0.reportEverySteps))))))" } ?? "-")
+ Text("The app replays raw spring time directly. There is no speculative distance-based duration layer here.")
+ .font(.system(size: 11, weight: .medium, design: .rounded))
+ .foregroundStyle(Color.white.opacity(0.52))
+ .fixedSize(horizontal: false, vertical: true)
+ }
+ .padding(16)
+ .background(cardBackground)
+
+ VStack(alignment: .leading, spacing: 10) {
+ Text("Candidates")
+ .font(.system(size: 14, weight: .bold, design: .rounded))
+ .foregroundStyle(Color.white.opacity(0.88))
+
+ ForEach(model.orderedCandidates) { candidate in
+ Button {
+ model.selectCandidate(candidate.id)
+ } label: {
+ CandidateRow(candidate: candidate, isSelected: candidate.id == model.selectedCandidate?.id)
+ }
+ .buttonStyle(.plain)
+ }
+ }
+ .padding(16)
+ .background(cardBackground)
+ }
+ .padding(20)
+ }
+ }
+
+ private var cardBackground: some View {
+ RoundedRectangle(cornerRadius: 24, style: .continuous)
+ .fill(Color.white.opacity(0.05))
+ .overlay(
+ RoundedRectangle(cornerRadius: 24, style: .continuous)
+ .stroke(Color.white.opacity(0.08), lineWidth: 1)
+ )
+ }
+}
+
+@MainActor
+final class StandaloneCursorViewModel: ObservableObject {
+ @Published private(set) var canvasBounds = CGRect(x: 72, y: 72, width: 840, height: 580)
+ @Published private(set) var start = CGPoint(x: 180, y: 480)
+ @Published private(set) var end = CGPoint(x: 760, y: 220)
+ @Published private(set) var orderedCandidates: [StandaloneCursorCandidate] = []
+ @Published private(set) var selectedCandidate: StandaloneCursorCandidate?
+ @Published private(set) var selectionPolicy = "prefer_in_bounds_then_lowest_score"
+ @Published private(set) var timeline: StandaloneCursorTimeline?
+ @Published private(set) var currentPoint = CGPoint(x: 180, y: 480)
+ @Published private(set) var headingAngle: CGFloat = 0
+ @Published private(set) var rawProgress: CGFloat = 0
+ @Published private(set) var displayProgress: CGFloat = 0
+ @Published private(set) var playbackTime: CGFloat = 0
+ @Published var showAllCandidates = true
+ @Published var showControlPolygon = true
+
+ private var selectionMode: SelectionMode = .automatic
+ private var springState = StandaloneCursorSpringState()
+ private var displayLink: CVDisplayLink?
+ private var lastTimestamp: CFTimeInterval?
+ private var isAnimating = false
+
+ enum SelectionMode {
+ case automatic
+ case manual(String)
+ }
+
+ init() {
+ rebuildSelection(replay: false)
+ ensureDisplayLink()
+ }
+
+ static func canvasBounds(for size: CGSize) -> CGRect {
+ let insetX: CGFloat = 72
+ let insetY: CGFloat = 78
+ let width = max(size.width - (insetX * 2), 240)
+ let height = max(size.height - (insetY * 2), 240)
+ return CGRect(x: insetX, y: insetY, width: width, height: height)
+ }
+
+ var selectionModeLabel: String {
+ switch selectionMode {
+ case .automatic:
+ return "AUTO SELECT • \(selectionPolicy.uppercased())"
+ case let .manual(id):
+ return "MANUAL LOCK • \(id.uppercased())"
+ }
+ }
+
+ var selectedCandidateSummary: String {
+ guard let selectedCandidate else {
+ return "20 candidates are generated from the recovered 2 base + 18 arched pool."
+ }
+
+ return String(
+ format: "%@ • score %.2f • length %.1f • total turn %.2f",
+ selectedCandidate.id,
+ Double(selectedCandidate.score),
+ Double(selectedCandidate.measurement.length),
+ Double(selectedCandidate.measurement.totalTurn)
+ )
+ }
+
+ var timingSummary: String {
+ guard let timeline else {
+ return "raw spring timeline unavailable"
+ }
+
+ return "endpoint lock \(timelineMetricString(timeline.firstEndpointLockTime)) • close enough \(timelineMetricString(timeline.closeEnoughFirstTime))"
+ }
+
+ func updateCanvasBounds(_ bounds: CGRect) {
+ guard canvasBounds != bounds else {
+ return
+ }
+
+ canvasBounds = bounds
+ start = clamp(start)
+ end = clamp(end)
+ rebuildSelection(replay: false)
+ }
+
+ func setStart(to location: CGPoint, livePreview: Bool) {
+ start = clamp(location)
+ rebuildSelection(replay: !livePreview)
+ }
+
+ func setEnd(to location: CGPoint, livePreview: Bool) {
+ end = clamp(location)
+ rebuildSelection(replay: !livePreview)
+ }
+
+ func selectCandidate(_ id: String) {
+ selectionMode = .manual(id)
+ rebuildSelection(replay: true)
+ }
+
+ func useAutomaticSelection() {
+ selectionMode = .automatic
+ rebuildSelection(replay: true)
+ }
+
+ func replay() {
+ startPlayback()
+ }
+
+ func formatted(_ value: CGFloat) -> String {
+ String(format: "%.3f", Double(value))
+ }
+
+ func timelineMetricString(_ value: CGFloat?) -> String {
+ guard let value else {
+ return "-"
+ }
+ return "\(formatted(value)) s"
+ }
+
+ private func rebuildSelection(replay: Bool) {
+ let candidates = StandaloneCursorBinaryGuidedModel.makeCandidates(start: start, end: end, bounds: canvasBounds)
+ let decision = StandaloneCursorBinaryGuidedModel.chooseCandidate(from: candidates)
+ selectionPolicy = decision.selectionPolicy
+ orderedCandidates = StandaloneCursorBinaryGuidedModel.orderedCandidates(from: candidates)
+
+ switch selectionMode {
+ case .automatic:
+ selectedCandidate = orderedCandidates.first(where: { $0.id == decision.selectedCandidateID }) ?? orderedCandidates.first
+ case let .manual(id):
+ selectedCandidate = orderedCandidates.first(where: { $0.id == id }) ?? orderedCandidates.first
+ if let selectedCandidate {
+ selectionMode = .manual(selectedCandidate.id)
+ } else {
+ selectionMode = .automatic
+ }
+ }
+
+ timeline = selectedCandidate.map {
+ StandaloneCursorBinaryGuidedModel.buildTimeline(path: $0.path)
+ }
+
+ if replay {
+ startPlayback()
+ } else {
+ snapToStart()
+ }
+ }
+
+ private func snapToStart() {
+ lastTimestamp = nil
+ isAnimating = false
+ playbackTime = 0
+ rawProgress = 0
+ displayProgress = 0
+ springState = StandaloneCursorSpringState()
+
+ if let sample = selectedCandidate?.path.sample(at: 0) {
+ currentPoint = sample.point
+ headingAngle = atan2(sample.tangent.dy, sample.tangent.dx)
+ } else {
+ currentPoint = start
+ headingAngle = 0
+ }
+ }
+
+ private func startPlayback() {
+ guard selectedCandidate != nil else {
+ return
+ }
+
+ snapToStart()
+ isAnimating = true
+ }
+
+ private func ensureDisplayLink() {
+ guard displayLink == nil else {
+ return
+ }
+
+ var link: CVDisplayLink?
+ CVDisplayLinkCreateWithActiveCGDisplays(&link)
+ guard let link else {
+ return
+ }
+
+ let callback: CVDisplayLinkOutputCallback = { _, _, _, _, _, userInfo in
+ guard let userInfo else {
+ return kCVReturnSuccess
+ }
+
+ let viewModel = Unmanaged<StandaloneCursorViewModel>.fromOpaque(userInfo).takeUnretainedValue()
+ Task { @MainActor in
+ viewModel.tick()
+ }
+ return kCVReturnSuccess
+ }
+
+ CVDisplayLinkSetOutputCallback(link, callback, Unmanaged.passUnretained(self).toOpaque())
+ displayLink = link
+ CVDisplayLinkStart(link)
+ }
+
+ private func tick() {
+ guard isAnimating, let selectedCandidate else {
+ lastTimestamp = nil
+ return
+ }
+
+ let now = CACurrentMediaTime()
+ let dt = CGFloat(lastTimestamp.map { now - $0 } ?? (1.0 / 60.0))
+ lastTimestamp = now
+
+ playbackTime += max(1.0 / 240.0, min(dt, 1.0 / 24.0))
+ (rawProgress, springState) = StandaloneCursorBinaryGuidedModel.advanceProgress(
+ current: rawProgress,
+ state: springState,
+ to: playbackTime
+ )
+
+ let sample = selectedCandidate.path.sample(at: rawProgress)
+ currentPoint = sample.point
+ headingAngle = atan2(sample.tangent.dy, sample.tangent.dx)
+ displayProgress = min(max(rawProgress, 0), 1)
+
+ if let closeEnoughTime = timeline?.closeEnoughFirstTime, playbackTime >= closeEnoughTime {
+ isAnimating = false
+ }
+ }
+
+ private func clamp(_ point: CGPoint) -> CGPoint {
+ CGPoint(
+ x: min(max(point.x, canvasBounds.minX), canvasBounds.maxX),
+ y: min(max(point.y, canvasBounds.minY), canvasBounds.maxY)
+ )
+ }
+}
+
+private struct BoundsBackdrop: View {
+ let bounds: CGRect
+
+ var body: some View {
+ ZStack(alignment: .topLeading) {
+ RoundedRectangle(cornerRadius: 30, style: .continuous)
+ .stroke(Color.white.opacity(0.08), style: StrokeStyle(lineWidth: 1, dash: [12, 10]))
+ .frame(width: bounds.width, height: bounds.height)
+ .offset(x: bounds.minX, y: bounds.minY)
+
+ RoundedRectangle(cornerRadius: 30, style: .continuous)
+ .fill(Color.white.opacity(0.02))
+ .frame(width: bounds.width, height: bounds.height)
+ .offset(x: bounds.minX, y: bounds.minY)
+ }
+ }
+}
+
+private struct MotionCurveShape: Shape {
+ let motionPath: StandaloneCursorMotionPath
+
+ func path(in rect: CGRect) -> Path {
+ var path = Path()
+ path.move(to: motionPath.start)
+
+ for segment in motionPath.segments {
+ path.addCurve(to: segment.end, control1: segment.control1, control2: segment.control2)
+ }
+
+ return path
+ }
+}
+
+private struct MotionTrailShape: Shape {
+ let motionPath: StandaloneCursorMotionPath
+ let progress: CGFloat
+
+ func path(in rect: CGRect) -> Path {
+ let sampleCount = max(Int(progress * 96), 2)
+ var path = Path()
+ path.move(to: motionPath.start)
+
+ for index in 1...sampleCount {
+ let fraction = CGFloat(index) / CGFloat(sampleCount)
+ let point = motionPath.sample(at: progress * fraction).point
+ path.addLine(to: point)
+ }
+
+ return path
+ }
+}
+
+private struct ControlPolygonLayer: View {
+ let candidate: StandaloneCursorCandidate
+
+ var body: some View {
+ ZStack(alignment: .topLeading) {
+ if let startControl = candidate.path.startControl {
+ Path { path in
+ path.move(to: candidate.path.start)
+ path.addLine(to: startControl)
+ }
+ .stroke(Color.white.opacity(0.18), style: StrokeStyle(lineWidth: 1, dash: [5, 5]))
+
+ ControlNode(point: startControl, tint: Color.white.opacity(0.7))
+ }
+
+ if let arc = candidate.path.arc {
+ if let arcIn = candidate.path.arcIn {
+ Path { path in
+ path.move(to: arc)
+ path.addLine(to: arcIn)
+ }
+ .stroke(Color.white.opacity(0.16), style: StrokeStyle(lineWidth: 1, dash: [4, 6]))
+
+ ControlNode(point: arcIn, tint: Color(red: 0.36, green: 0.73, blue: 0.89))
+ }
+
+ if let arcOut = candidate.path.arcOut {
+ Path { path in
+ path.move(to: arc)
+ path.addLine(to: arcOut)
+ }
+ .stroke(Color.white.opacity(0.16), style: StrokeStyle(lineWidth: 1, dash: [4, 6]))
+
+ ControlNode(point: arcOut, tint: Color(red: 0.36, green: 0.73, blue: 0.89))
+ }
+
+ ArcAnchorNode(point: arc)
+ }
+
+ if let endControl = candidate.path.endControl {
+ Path { path in
+ path.move(to: endControl)
+ path.addLine(to: candidate.path.end)
+ }
+ .stroke(Color.white.opacity(0.18), style: StrokeStyle(lineWidth: 1, dash: [5, 5]))
+
+ ControlNode(point: endControl, tint: Color.white.opacity(0.7))
+ }
+ }
+ }
+}
+
+private struct ControlNode: View {
+ let point: CGPoint
+ let tint: Color
+
+ var body: some View {
+ Circle()
+ .fill(tint)
+ .frame(width: 9, height: 9)
+ .overlay(Circle().stroke(Color.black.opacity(0.45), lineWidth: 1))
+ .offset(x: point.x - 4.5, y: point.y - 4.5)
+ }
+}
+
+private struct ArcAnchorNode: View {
+ let point: CGPoint
+
+ var body: some View {
+ DiamondShape()
+ .fill(Color(red: 0.98, green: 0.79, blue: 0.35))
+ .frame(width: 12, height: 12)
+ .overlay(DiamondShape().stroke(Color.black.opacity(0.45), lineWidth: 1))
+ .offset(x: point.x - 6, y: point.y - 6)
+ }
+}
+
+private struct HandleView: View {
+ let label: String
+ let tint: Color
+
+ var body: some View {
+ ZStack(alignment: .topLeading) {
+ Circle()
+ .fill(tint.opacity(0.18))
+ .frame(width: 36, height: 36)
+ .overlay(
+ Circle()
+ .stroke(tint, lineWidth: 2)
+ )
+ .shadow(color: tint.opacity(0.28), radius: 12)
+
+ Text(label)
+ .font(.system(size: 10, weight: .black, design: .rounded))
+ .tracking(0.8)
+ .foregroundStyle(tint)
+ .padding(.horizontal, 8)
+ .padding(.vertical, 4)
+ .background(
+ Capsule(style: .continuous)
+ .fill(Color.black.opacity(0.32))
+ .overlay(Capsule(style: .continuous).stroke(Color.white.opacity(0.08), lineWidth: 1))
+ )
+ .offset(x: 22, y: -10)
+ }
+ .frame(width: 110, height: 44, alignment: .topLeading)
+ }
+}
+
+private struct CursorGlyphView: View {
+ let heading: CGFloat
+
+ var body: some View {
+ ZStack(alignment: .topLeading) {
+ CursorGlyphShape()
+ .fill(
+ LinearGradient(
+ colors: [
+ Color.white,
+ Color(red: 0.89, green: 0.90, blue: 0.95),
+ ],
+ startPoint: .topLeading,
+ endPoint: .bottomTrailing
+ )
+ )
+ .overlay(
+ CursorGlyphShape()
+ .stroke(Color.black.opacity(0.55), lineWidth: 1.1)
+ )
+ .shadow(color: Color.black.opacity(0.28), radius: 18, x: 0, y: 8)
+ }
+ .frame(width: 30, height: 40, alignment: .topLeading)
+ .rotationEffect(.radians(heading), anchor: .topLeading)
+ }
+}
+
+private struct CursorGlyphShape: Shape {
+ func path(in rect: CGRect) -> Path {
+ let width = rect.width
+ let height = rect.height
+
+ var path = Path()
+ path.move(to: CGPoint(x: 0, y: 0))
+ path.addLine(to: CGPoint(x: width * 0.58, y: height * 0.60))
+ path.addLine(to: CGPoint(x: width * 0.38, y: height * 0.62))
+ path.addLine(to: CGPoint(x: width * 0.50, y: height))
+ path.addLine(to: CGPoint(x: width * 0.30, y: height))
+ path.addLine(to: CGPoint(x: width * 0.18, y: height * 0.66))
+ path.addLine(to: CGPoint(x: 0, y: height * 0.80))
+ path.closeSubpath()
+ return path
+ }
+}
+
+private struct DiamondShape: Shape {
+ func path(in rect: CGRect) -> Path {
+ var path = Path()
+ path.move(to: CGPoint(x: rect.midX, y: rect.minY))
+ path.addLine(to: CGPoint(x: rect.maxX, y: rect.midY))
+ path.addLine(to: CGPoint(x: rect.midX, y: rect.maxY))
+ path.addLine(to: CGPoint(x: rect.minX, y: rect.midY))
+ path.closeSubpath()
+ return path
+ }
+}
+
+private struct MetricRow: View {
+ let label: String
+ let value: String
+
+ var body: some View {
+ HStack(alignment: .firstTextBaseline) {
+ Text(label.uppercased())
+ .font(.system(size: 10, weight: .black, design: .rounded))
+ .tracking(0.8)
+ .foregroundStyle(Color.white.opacity(0.45))
+
+ Spacer(minLength: 12)
+
+ Text(value)
+ .font(.system(size: 12, weight: .semibold, design: .rounded))
+ .foregroundStyle(Color.white.opacity(0.82))
+ }
+ }
+}
+
+private struct CandidateRow: View {
+ let candidate: StandaloneCursorCandidate
+ let isSelected: Bool
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 6) {
+ HStack {
+ Text(candidate.id.uppercased())
+ .font(.system(size: 11, weight: .black, design: .rounded))
+ .tracking(0.6)
+ Spacer()
+ Text(candidate.measurement.staysInBounds ? "IN" : "OUT")
+ .font(.system(size: 10, weight: .black, design: .rounded))
+ .tracking(0.8)
+ }
+
+ Text(String(format: "score %.2f • len %.1f • turn %.2f", Double(candidate.score), Double(candidate.measurement.length), Double(candidate.measurement.totalTurn)))
+ .font(.system(size: 11, weight: .medium, design: .rounded))
+ .foregroundStyle(Color.white.opacity(0.72))
+ }
+ .foregroundStyle(isSelected ? Color.black.opacity(0.82) : Color.white.opacity(0.92))
+ .padding(12)
+ .background(
+ RoundedRectangle(cornerRadius: 18, style: .continuous)
+ .fill(
+ isSelected
+ ? Color(red: 0.98, green: 0.79, blue: 0.35)
+ : Color.white.opacity(0.05)
+ )
+ .overlay(
+ RoundedRectangle(cornerRadius: 18, style: .continuous)
+ .stroke(Color.white.opacity(isSelected ? 0 : 0.08), lineWidth: 1)
+ )
+ )
+ }
+}
+
+private struct ActionButton: View {
+ enum Accent {
+ case warm
+ case cool
+ }
+
+ let title: String
+ let accent: Accent
+ let action: () -> Void
+
+ var body: some View {
+ Button(action: action) {
+ Text(title.uppercased())
+ .font(.system(size: 11, weight: .black, design: .rounded))
+ .tracking(0.8)
+ .frame(maxWidth: .infinity)
+ .padding(.vertical, 11)
+ }
+ .buttonStyle(.plain)
+ .background(background)
+ .foregroundStyle(Color.black.opacity(0.82))
+ .clipShape(RoundedRectangle(cornerRadius: 16, style: .continuous))
+ }
+
+ private var background: some View {
+ let colors: [Color] = switch accent {
+ case .warm:
+ [Color(red: 0.98, green: 0.79, blue: 0.35), Color(red: 0.96, green: 0.57, blue: 0.19)]
+ case .cool:
+ [Color(red: 0.66, green: 0.92, blue: 0.93), Color(red: 0.35, green: 0.72, blue: 0.89)]
+ }
+
+ return LinearGradient(colors: colors, startPoint: .leading, endPoint: .trailing)
+ }
+}
+
+private struct StandaloneCursorToggleStyle: ToggleStyle {
+ func makeBody(configuration: Configuration) -> some View {
+ Button {
+ configuration.isOn.toggle()
+ } label: {
+ HStack {
+ configuration.label
+ .font(.system(size: 12, weight: .semibold, design: .rounded))
+ Spacer()
+ RoundedRectangle(cornerRadius: 999, style: .continuous)
+ .fill(configuration.isOn ? Color(red: 0.36, green: 0.73, blue: 0.89) : Color.white.opacity(0.12))
+ .frame(width: 42, height: 24)
+ .overlay(alignment: configuration.isOn ? .trailing : .leading) {
+ Circle()
+ .fill(Color.white)
+ .frame(width: 18, height: 18)
+ .padding(3)
+ }
+ }
+ .foregroundStyle(Color.white.opacity(0.82))
+ }
+ .buttonStyle(.plain)
+ }
+}
diff --git a/experiments/StandaloneCursor/Sources/StandaloneCursorSupport/StandaloneCursorModel.swift b/experiments/StandaloneCursor/Sources/StandaloneCursorSupport/StandaloneCursorModel.swift
new file mode 100644
index 0000000..bd9dc84
--- /dev/null
+++ b/experiments/StandaloneCursor/Sources/StandaloneCursorSupport/StandaloneCursorModel.swift
@@ -0,0 +1,942 @@
+import CoreGraphics
+import Foundation
+
+public struct StandaloneCursorMotionSegment: Equatable, Sendable {
+ public let end: CGPoint
+ public let control1: CGPoint
+ public let control2: CGPoint
+
+ public init(end: CGPoint, control1: CGPoint, control2: CGPoint) {
+ self.end = end
+ self.control1 = control1
+ self.control2 = control2
+ }
+}
+
+public struct StandaloneCursorPathSample: Equatable, Sendable {
+ public let progress: CGFloat
+ public let point: CGPoint
+ public let tangent: CGVector
+ public let speedUnitsPerProgress: CGFloat
+
+ public init(progress: CGFloat, point: CGPoint, tangent: CGVector, speedUnitsPerProgress: CGFloat) {
+ self.progress = progress
+ self.point = point
+ self.tangent = tangent
+ self.speedUnitsPerProgress = speedUnitsPerProgress
+ }
+}
+
+public struct StandaloneCursorMotionMeasurement: Equatable, Sendable {
+ public let length: CGFloat
+ public let angleChangeEnergy: CGFloat
+ public let maxAngleChange: CGFloat
+ public let totalTurn: CGFloat
+ public let staysInBounds: Bool
+
+ public init(
+ length: CGFloat,
+ angleChangeEnergy: CGFloat,
+ maxAngleChange: CGFloat,
+ totalTurn: CGFloat,
+ staysInBounds: Bool
+ ) {
+ self.length = length
+ self.angleChangeEnergy = angleChangeEnergy
+ self.maxAngleChange = maxAngleChange
+ self.totalTurn = totalTurn
+ self.staysInBounds = staysInBounds
+ }
+}
+
+public struct StandaloneCursorCandidateScoreComponents: Equatable, Sendable {
+ public let excessLengthRatio: CGFloat
+ public let excessLengthCost: CGFloat
+ public let angleEnergyCost: CGFloat
+ public let maxAngleCost: CGFloat
+ public let totalTurnCost: CGFloat
+ public let outOfBoundsCost: CGFloat
+ public let totalScore: CGFloat
+
+ public init(
+ excessLengthRatio: CGFloat,
+ excessLengthCost: CGFloat,
+ angleEnergyCost: CGFloat,
+ maxAngleCost: CGFloat,
+ totalTurnCost: CGFloat,
+ outOfBoundsCost: CGFloat,
+ totalScore: CGFloat
+ ) {
+ self.excessLengthRatio = excessLengthRatio
+ self.excessLengthCost = excessLengthCost
+ self.angleEnergyCost = angleEnergyCost
+ self.maxAngleCost = maxAngleCost
+ self.totalTurnCost = totalTurnCost
+ self.outOfBoundsCost = outOfBoundsCost
+ self.totalScore = totalScore
+ }
+}
+
+public struct StandaloneCursorMotionPath: Equatable, Sendable {
+ public let start: CGPoint
+ public let end: CGPoint
+ public let startControl: CGPoint?
+ public let arc: CGPoint?
+ public let arcIn: CGPoint?
+ public let arcOut: CGPoint?
+ public let endControl: CGPoint?
+ public let segments: [StandaloneCursorMotionSegment]
+
+ public init(
+ start: CGPoint,
+ end: CGPoint,
+ startControl: CGPoint? = nil,
+ arc: CGPoint? = nil,
+ arcIn: CGPoint? = nil,
+ arcOut: CGPoint? = nil,
+ endControl: CGPoint? = nil,
+ segments: [StandaloneCursorMotionSegment]
+ ) {
+ self.start = start
+ self.end = end
+ self.startControl = startControl
+ self.arc = arc
+ self.arcIn = arcIn
+ self.arcOut = arcOut
+ self.endControl = endControl
+ self.segments = segments
+ }
+
+ public func sample(at progress: CGFloat) -> (point: CGPoint, tangent: CGVector) {
+ guard !segments.isEmpty else {
+ return (start, CGVector(dx: 1, dy: 0))
+ }
+
+ let clamped = progress.clamped(to: 0...1)
+ let segmentCount = segments.count
+ let segmentIndex: Int
+ let localT: CGFloat
+
+ if clamped >= 1 {
+ segmentIndex = segmentCount - 1
+ localT = 1
+ } else {
+ let scaled = clamped * CGFloat(segmentCount)
+ segmentIndex = min(Int(scaled), segmentCount - 1)
+ localT = scaled - CGFloat(segmentIndex)
+ }
+
+ let segment = segments[segmentIndex]
+ let segmentStart = segmentIndex == 0 ? start : segments[segmentIndex - 1].end
+ let point = sampleCubic(
+ start: segmentStart,
+ control1: segment.control1,
+ control2: segment.control2,
+ end: segment.end,
+ t: localT
+ )
+ let tangent = sampleCubicTangent(
+ start: segmentStart,
+ control1: segment.control1,
+ control2: segment.control2,
+ end: segment.end,
+ t: localT
+ ).normalized
+ return (point, tangent)
+ }
+
+ public func samplePoints(count: Int) -> [StandaloneCursorPathSample] {
+ let resolvedCount = max(count, 2)
+ var samples: [StandaloneCursorPathSample] = []
+ samples.reserveCapacity(resolvedCount)
+ var previousPoint: CGPoint?
+
+ for index in 0..<resolvedCount {
+ let progress = CGFloat(index) / CGFloat(max(resolvedCount - 1, 1))
+ let sample = sample(at: progress)
+ let speed = previousPoint.map { (sample.point - $0).length } ?? 0
+ samples.append(
+ StandaloneCursorPathSample(
+ progress: progress,
+ point: sample.point,
+ tangent: sample.tangent,
+ speedUnitsPerProgress: speed
+ )
+ )
+ previousPoint = sample.point
+ }
+
+ return samples
+ }
+
+ public func measure(
+ bounds: CGRect?,
+ minStepDistance: CGFloat = 0.01,
+ samplesPerSegment: Int = 24
+ ) -> StandaloneCursorMotionMeasurement {
+ var totalLength: CGFloat = 0
+ var angleChangeEnergy: CGFloat = 0
+ var maxAngleChange: CGFloat = 0
+ var totalTurn: CGFloat = 0
+ var staysInBounds = bounds?.contains(start, padding: 20) ?? true
+ var previousPoint = start
+ var previousAngle: CGFloat?
+
+ let totalSteps = max(segments.count * max(samplesPerSegment, 1), 1)
+ for step in 1...totalSteps {
+ let progress = CGFloat(step) / CGFloat(totalSteps)
+ let point = sample(at: progress).point
+ let delta = point - previousPoint
+ let stepLength = delta.length
+
+ if let bounds, staysInBounds {
+ staysInBounds = bounds.contains(point, padding: 20)
+ }
+
+ if stepLength > minStepDistance {
+ let angle = atan2(delta.dy, delta.dx)
+ totalLength += stepLength
+
+ if let previousAngle {
+ let angleDelta = unwrapAngleDelta(angle - previousAngle)
+ angleChangeEnergy += angleDelta * angleDelta
+ let absoluteDelta = abs(angleDelta)
+ maxAngleChange = max(maxAngleChange, absoluteDelta)
+ totalTurn += absoluteDelta
+ }
+
+ previousAngle = angle
+ previousPoint = point
+ }
+ }
+
+ return StandaloneCursorMotionMeasurement(
+ length: totalLength,
+ angleChangeEnergy: angleChangeEnergy,
+ maxAngleChange: maxAngleChange,
+ totalTurn: totalTurn,
+ staysInBounds: staysInBounds
+ )
+ }
+}
+
+public enum StandaloneCursorCandidateKind: String, Equatable, Sendable {
+ case base
+ case arched
+}
+
+public struct StandaloneCursorCandidate: Identifiable, Equatable, Sendable {
+ public let id: String
+ public let kind: StandaloneCursorCandidateKind
+ public let side: Int
+ public let tableAScale: CGFloat?
+ public let tableBScale: CGFloat?
+ public let score: CGFloat
+ public let scoreComponents: StandaloneCursorCandidateScoreComponents
+ public let measurement: StandaloneCursorMotionMeasurement
+ public let path: StandaloneCursorMotionPath
+
+ public init(
+ id: String,
+ kind: StandaloneCursorCandidateKind,
+ side: Int,
+ tableAScale: CGFloat?,
+ tableBScale: CGFloat?,
+ score: CGFloat,
+ scoreComponents: StandaloneCursorCandidateScoreComponents,
+ measurement: StandaloneCursorMotionMeasurement,
+ path: StandaloneCursorMotionPath
+ ) {
+ self.id = id
+ self.kind = kind
+ self.side = side
+ self.tableAScale = tableAScale
+ self.tableBScale = tableBScale
+ self.score = score
+ self.scoreComponents = scoreComponents
+ self.measurement = measurement
+ self.path = path
+ }
+}
+
+public struct StandaloneCursorSelectionDecision: Equatable, Sendable {
+ public let selectedCandidateID: String?
+ public let selectionPolicy: String
+
+ public init(selectedCandidateID: String?, selectionPolicy: String) {
+ self.selectedCandidateID = selectedCandidateID
+ self.selectionPolicy = selectionPolicy
+ }
+}
+
+public struct StandaloneCursorSpringConfiguration: Equatable, Sendable {
+ public let response: CGFloat
+ public let dampingFraction: CGFloat
+ public let stiffness: CGFloat
+ public let drag: CGFloat
+ public let dt: CGFloat
+ public let closeEnoughProgressThreshold: CGFloat
+ public let closeEnoughDistanceThreshold: CGFloat
+ public let idleVelocityThreshold: CGFloat
+
+ public init(
+ response: CGFloat,
+ dampingFraction: CGFloat,
+ stiffness: CGFloat,
+ drag: CGFloat,
+ dt: CGFloat,
+ closeEnoughProgressThreshold: CGFloat,
+ closeEnoughDistanceThreshold: CGFloat,
+ idleVelocityThreshold: CGFloat
+ ) {
+ self.response = response
+ self.dampingFraction = dampingFraction
+ self.stiffness = stiffness
+ self.drag = drag
+ self.dt = dt
+ self.closeEnoughProgressThreshold = closeEnoughProgressThreshold
+ self.closeEnoughDistanceThreshold = closeEnoughDistanceThreshold
+ self.idleVelocityThreshold = idleVelocityThreshold
+ }
+
+ public static let official: StandaloneCursorSpringConfiguration = {
+ let response: CGFloat = 1.4
+ let dampingFraction: CGFloat = 0.9
+ let dt: CGFloat = 1.0 / 240.0
+ let idleVelocityThreshold: CGFloat = 28_800
+ let rawStiffness = response > 0 ? pow((2 * .pi) / response, 2) : .infinity
+ let stiffness = min(rawStiffness, idleVelocityThreshold)
+ let drag = 2 * dampingFraction * sqrt(stiffness)
+
+ return StandaloneCursorSpringConfiguration(
+ response: response,
+ dampingFraction: dampingFraction,
+ stiffness: stiffness,
+ drag: drag,
+ dt: dt,
+ closeEnoughProgressThreshold: 1,
+ closeEnoughDistanceThreshold: 0.01,
+ idleVelocityThreshold: idleVelocityThreshold
+ )
+ }()
+}
+
+public struct StandaloneCursorSpringState: Equatable, Sendable {
+ public var time: CGFloat
+ public var velocity: CGFloat
+ public var force: CGFloat
+
+ public init(time: CGFloat = 0, velocity: CGFloat = 0, force: CGFloat = 0) {
+ self.time = time
+ self.velocity = velocity
+ self.force = force
+ }
+}
+
+public struct StandaloneCursorTimelineSample: Equatable, Identifiable, Sendable {
+ public var id: Int { step }
+
+ public let step: Int
+ public let time: CGFloat
+ public let progress: CGFloat
+ public let point: CGPoint
+ public let springVelocity: CGFloat
+ public let springForce: CGFloat
+ public let geometricSpeedUnitsPerSecond: CGFloat
+
+ public init(
+ step: Int,
+ time: CGFloat,
+ progress: CGFloat,
+ point: CGPoint,
+ springVelocity: CGFloat,
+ springForce: CGFloat,
+ geometricSpeedUnitsPerSecond: CGFloat
+ ) {
+ self.step = step
+ self.time = time
+ self.progress = progress
+ self.point = point
+ self.springVelocity = springVelocity
+ self.springForce = springForce
+ self.geometricSpeedUnitsPerSecond = geometricSpeedUnitsPerSecond
+ }
+}
+
+public struct StandaloneCursorTimeline: Equatable, Sendable {
+ public let springConfiguration: StandaloneCursorSpringConfiguration
+ public let samples: [StandaloneCursorTimelineSample]
+ public let rawProgressFirstGeTargetTime: CGFloat?
+ public let firstEndpointLockTime: CGFloat?
+ public let closeEnoughFirstTime: CGFloat?
+ public let rawProgressFirstGeTargetStep: Int?
+ public let firstEndpointLockStep: Int?
+ public let closeEnoughFirstStep: Int?
+ public let reportEverySteps: Int
+
+ public init(
+ springConfiguration: StandaloneCursorSpringConfiguration,
+ samples: [StandaloneCursorTimelineSample],
+ rawProgressFirstGeTargetTime: CGFloat?,
+ firstEndpointLockTime: CGFloat?,
+ closeEnoughFirstTime: CGFloat?,
+ rawProgressFirstGeTargetStep: Int?,
+ firstEndpointLockStep: Int?,
+ closeEnoughFirstStep: Int?,
+ reportEverySteps: Int
+ ) {
+ self.springConfiguration = springConfiguration
+ self.samples = samples
+ self.rawProgressFirstGeTargetTime = rawProgressFirstGeTargetTime
+ self.firstEndpointLockTime = firstEndpointLockTime
+ self.closeEnoughFirstTime = closeEnoughFirstTime
+ self.rawProgressFirstGeTargetStep = rawProgressFirstGeTargetStep
+ self.firstEndpointLockStep = firstEndpointLockStep
+ self.closeEnoughFirstStep = closeEnoughFirstStep
+ self.reportEverySteps = reportEverySteps
+ }
+}
+
+public enum StandaloneCursorBinaryGuidedModel {
+ public static let guideVectorInLocalBasis = CGVector(dx: -0.6946583704589973, dy: 0.7193398003386512)
+ public static let tableA: [CGFloat] = [0.55, 0.8, 1.05]
+ public static let tableB: [CGFloat] = [0.65, 1.0, 1.35]
+
+ private static let normalizationEpsilon: CGFloat = 0.001
+ private static let sideBiasScale: CGFloat = 0.65
+ private static let primaryDistanceScale: CGFloat = 0.41960295031576633
+ private static let directSpanScale: CGFloat = 0.9
+ private static let secondaryDistanceScale: CGFloat = 0.2765523188064277
+ private static let arcDistanceScale: CGFloat = 0.5783555327868779
+ private static let candidateArcMin: CGFloat = 38
+ private static let candidateArcMax: CGFloat = 440
+ private static let scoreExcessLengthWeight: CGFloat = 320
+ private static let scoreAngleEnergyWeight: CGFloat = 140
+ private static let scoreMaxAngleWeight: CGFloat = 180
+ private static let scoreTotalTurnWeight: CGFloat = 18
+ private static let scoreOutOfBoundsPenalty: CGFloat = 45
+ private static let minimumStepDistance: CGFloat = 0.01
+
+ public static func makeCandidates(start: CGPoint, end: CGPoint, bounds: CGRect?) -> [StandaloneCursorCandidate] {
+ let delta = end - start
+ let distance = max(delta.length, normalizationEpsilon)
+ let direction = delta.normalized
+ let localNormal = direction.perpendicular
+ let guide = direction.scaled(by: guideVectorInLocalBasis.dx)
+ + localNormal.scaled(by: guideVectorInLocalBasis.dy)
+ let reverseGuide = guide.scaled(by: -1)
+
+ let (startExtentPre, endExtentPre) = binaryPiecewisePrimaryExtents(distance: distance)
+ let startExtent = min(startExtentPre, clipPositiveRay(origin: start, direction: guide, bounds: bounds))
+ let endExtent = min(endExtentPre, clipPositiveRay(origin: end, direction: reverseGuide, bounds: bounds))
+
+ let startExtentScaled = min(
+ max(startExtent * sideBiasScale, 0),
+ clipPositiveRay(origin: start, direction: guide, bounds: bounds)
+ )
+ let endExtentScaled = min(
+ max(endExtent * sideBiasScale, 0),
+ clipPositiveRay(origin: end, direction: reverseGuide, bounds: bounds)
+ )
+
+ let fullStartControl = start + guide.scaled(by: startExtent)
+ let fullEndControl = end - guide.scaled(by: endExtent)
+ let scaledStartControl = start + guide.scaled(by: startExtentScaled)
+ let scaledEndControl = end - guide.scaled(by: endExtentScaled)
+
+ let rawHandleExtent = binaryPiecewiseHandleExtent(distance: distance)
+ let rawArcExtent = (distance * arcDistanceScale).clamped(to: candidateArcMin...candidateArcMax)
+
+ let midpoint = CGPoint(x: (start.x + end.x) * 0.5, y: (start.y + end.y) * 0.5)
+ var signedNormal = localNormal
+ let cross = (guide.dy * direction.dx) - (guide.dx * direction.dy)
+ if cross < 0 {
+ signedNormal = signedNormal.scaled(by: -1)
+ }
+ let arcAnchorBias = guide.scaled(by: startExtent * sideBiasScale)
+ let forwardUnit = normalizedOrDefault(
+ direction.scaled(by: distance) + signedNormal.scaled(by: rawArcExtent),
+ minimumLength: rawHandleExtent
+ )
+
+ var candidates: [StandaloneCursorCandidate] = []
+ candidates.append(
+ makeCandidate(
+ id: "base-full-guide",
+ kind: .base,
+ side: 0,
+ tableAScale: nil,
+ tableBScale: nil,
+ path: StandaloneCursorMotionPath(
+ start: start,
+ end: end,
+ startControl: fullStartControl,
+ endControl: fullEndControl,
+ segments: [
+ StandaloneCursorMotionSegment(
+ end: end,
+ control1: fullStartControl,
+ control2: fullEndControl
+ ),
+ ]
+ ),
+ distance: distance,
+ bounds: bounds
+ )
+ )
+ candidates.append(
+ makeCandidate(
+ id: "base-scaled-guide",
+ kind: .base,
+ side: 0,
+ tableAScale: nil,
+ tableBScale: nil,
+ path: StandaloneCursorMotionPath(
+ start: start,
+ end: end,
+ startControl: scaledStartControl,
+ endControl: scaledEndControl,
+ segments: [
+ StandaloneCursorMotionSegment(
+ end: end,
+ control1: scaledStartControl,
+ control2: scaledEndControl
+ ),
+ ]
+ ),
+ distance: distance,
+ bounds: bounds
+ )
+ )
+
+ for outerScale in tableA {
+ let anchorOffset = signedNormal.scaled(by: rawHandleExtent * outerScale)
+ for innerScale in tableB {
+ let tangentSpan = forwardUnit.scaled(by: rawArcExtent * innerScale)
+
+ for side in [1, -1] {
+ let anchor = midpoint + arcAnchorBias + anchorOffset.scaled(by: CGFloat(side))
+ let arcIn = anchor - tangentSpan
+ let arcOut = anchor + tangentSpan
+ let path = StandaloneCursorMotionPath(
+ start: start,
+ end: end,
+ startControl: fullStartControl,
+ arc: anchor,
+ arcIn: arcIn,
+ arcOut: arcOut,
+ endControl: fullEndControl,
+ segments: [
+ StandaloneCursorMotionSegment(end: anchor, control1: fullStartControl, control2: arcIn),
+ StandaloneCursorMotionSegment(end: end, control1: arcOut, control2: fullEndControl),
+ ]
+ )
+
+ candidates.append(
+ makeCandidate(
+ id: "a\(outerScale.cursorIdentifier)-b\(innerScale.cursorIdentifier)-\(side > 0 ? "positive" : "negative")",
+ kind: .arched,
+ side: side,
+ tableAScale: outerScale,
+ tableBScale: innerScale,
+ path: path,
+ distance: distance,
+ bounds: bounds
+ )
+ )
+ }
+ }
+ }
+
+ return candidates
+ }
+
+ public static func chooseCandidate(from candidates: [StandaloneCursorCandidate]) -> StandaloneCursorSelectionDecision {
+ guard !candidates.isEmpty else {
+ return StandaloneCursorSelectionDecision(selectedCandidateID: nil, selectionPolicy: "empty")
+ }
+
+ let inBoundsCandidates = candidates.filter(\.measurement.staysInBounds)
+ let pool = inBoundsCandidates.isEmpty ? candidates : inBoundsCandidates
+ let selected = pool.min { lhs, rhs in
+ if lhs.score == rhs.score {
+ return lhs.id < rhs.id
+ }
+ return lhs.score < rhs.score
+ }
+
+ return StandaloneCursorSelectionDecision(
+ selectedCandidateID: selected?.id,
+ selectionPolicy: inBoundsCandidates.isEmpty ? "lowest_score" : "prefer_in_bounds_then_lowest_score"
+ )
+ }
+
+ public static func orderedCandidates(from candidates: [StandaloneCursorCandidate]) -> [StandaloneCursorCandidate] {
+ candidates.sorted { lhs, rhs in
+ if lhs.measurement.staysInBounds != rhs.measurement.staysInBounds {
+ return lhs.measurement.staysInBounds && !rhs.measurement.staysInBounds
+ }
+ if lhs.score == rhs.score {
+ return lhs.id < rhs.id
+ }
+ return lhs.score < rhs.score
+ }
+ }
+
+ public static func buildTimeline(
+ path: StandaloneCursorMotionPath,
+ reportEverySteps: Int = 4,
+ maxDurationSeconds: CGFloat = 2.0
+ ) -> StandaloneCursorTimeline {
+ let configuration = StandaloneCursorSpringConfiguration.official
+ let stepCount = Int(maxDurationSeconds / configuration.dt)
+ var current: CGFloat = 0
+ let target: CGFloat = 1
+ var state = StandaloneCursorSpringState()
+ var samples: [StandaloneCursorTimelineSample] = []
+ var previousPoint: CGPoint?
+ var rawProgressFirstGeTargetTime: CGFloat?
+ var rawProgressFirstGeTargetStep: Int?
+ var firstEndpointLockTime: CGFloat?
+ var firstEndpointLockStep: Int?
+ var closeEnoughFirstTime: CGFloat?
+ var closeEnoughFirstStep: Int?
+
+ let startPoint = path.sample(at: current).point
+ samples.append(
+ StandaloneCursorTimelineSample(
+ step: 0,
+ time: 0,
+ progress: current,
+ point: startPoint,
+ springVelocity: state.velocity,
+ springForce: state.force,
+ geometricSpeedUnitsPerSecond: 0
+ )
+ )
+ previousPoint = startPoint
+
+ for step in 1...stepCount {
+ let targetTime = CGFloat(step) * configuration.dt
+ (current, state) = advanceProgress(
+ current: current,
+ target: target,
+ state: state,
+ configuration: configuration,
+ to: targetTime
+ )
+
+ let point = path.sample(at: current).point
+ let geometricSpeed = previousPoint.map { (point - $0).length / configuration.dt } ?? 0
+ previousPoint = point
+
+ if rawProgressFirstGeTargetTime == nil, current >= target {
+ rawProgressFirstGeTargetTime = state.time
+ rawProgressFirstGeTargetStep = step
+ }
+
+ if firstEndpointLockTime == nil, current >= target, point == path.end {
+ firstEndpointLockTime = state.time
+ firstEndpointLockStep = step
+ }
+
+ if closeEnoughFirstTime == nil,
+ current >= configuration.closeEnoughProgressThreshold,
+ abs(target - current) <= configuration.closeEnoughDistanceThreshold {
+ closeEnoughFirstTime = state.time
+ closeEnoughFirstStep = step
+ }
+
+ if (step % reportEverySteps) == 0 || step == stepCount {
+ samples.append(
+ StandaloneCursorTimelineSample(
+ step: step,
+ time: state.time,
+ progress: current,
+ point: point,
+ springVelocity: state.velocity,
+ springForce: state.force,
+ geometricSpeedUnitsPerSecond: geometricSpeed
+ )
+ )
+ }
+ }
+
+ return StandaloneCursorTimeline(
+ springConfiguration: configuration,
+ samples: samples,
+ rawProgressFirstGeTargetTime: rawProgressFirstGeTargetTime,
+ firstEndpointLockTime: firstEndpointLockTime,
+ closeEnoughFirstTime: closeEnoughFirstTime,
+ rawProgressFirstGeTargetStep: rawProgressFirstGeTargetStep,
+ firstEndpointLockStep: firstEndpointLockStep,
+ closeEnoughFirstStep: closeEnoughFirstStep,
+ reportEverySteps: reportEverySteps
+ )
+ }
+
+ public static func advanceProgress(
+ current: CGFloat,
+ target: CGFloat = 1,
+ state: StandaloneCursorSpringState,
+ configuration: StandaloneCursorSpringConfiguration = .official
+ ) -> (current: CGFloat, state: StandaloneCursorSpringState) {
+ let halfDT = configuration.dt * 0.5
+ let velocityHalf = state.velocity + (state.force * halfDT)
+ let nextCurrent = current + (velocityHalf * configuration.dt)
+ let force = (configuration.stiffness * (target - nextCurrent)) + ((-configuration.drag) * velocityHalf)
+ let velocity = velocityHalf + (force * halfDT)
+
+ return (
+ nextCurrent,
+ StandaloneCursorSpringState(
+ time: state.time + configuration.dt,
+ velocity: velocity,
+ force: force
+ )
+ )
+ }
+
+ public static func advanceProgress(
+ current: CGFloat,
+ target: CGFloat = 1,
+ state: StandaloneCursorSpringState,
+ configuration: StandaloneCursorSpringConfiguration = .official,
+ to targetTime: CGFloat
+ ) -> (current: CGFloat, state: StandaloneCursorSpringState) {
+ var adjustedState = state
+ var adjustedCurrent = current
+
+ if (targetTime - adjustedState.time) > 1 {
+ adjustedState.time = targetTime - (1.0 / 60.0)
+ }
+
+ while adjustedState.time < targetTime {
+ (adjustedCurrent, adjustedState) = advanceProgress(
+ current: adjustedCurrent,
+ target: target,
+ state: adjustedState,
+ configuration: configuration
+ )
+ }
+
+ return (adjustedCurrent, adjustedState)
+ }
+
+ private static func makeCandidate(
+ id: String,
+ kind: StandaloneCursorCandidateKind,
+ side: Int,
+ tableAScale: CGFloat?,
+ tableBScale: CGFloat?,
+ path: StandaloneCursorMotionPath,
+ distance: CGFloat,
+ bounds: CGRect?
+ ) -> StandaloneCursorCandidate {
+ let measurement = path.measure(bounds: bounds, minStepDistance: minimumStepDistance)
+ let scoreComponents = scoreCandidate(distance: distance, measurement: measurement)
+ return StandaloneCursorCandidate(
+ id: id,
+ kind: kind,
+ side: side,
+ tableAScale: tableAScale,
+ tableBScale: tableBScale,
+ score: scoreComponents.totalScore,
+ scoreComponents: scoreComponents,
+ measurement: measurement,
+ path: path
+ )
+ }
+
+ private static func scoreCandidate(
+ distance: CGFloat,
+ measurement: StandaloneCursorMotionMeasurement
+ ) -> StandaloneCursorCandidateScoreComponents {
+ let excessLengthRatio = max((measurement.length / max(distance, 1)) - 1, 0)
+ let excessLengthCost = excessLengthRatio * scoreExcessLengthWeight
+ let angleEnergyCost = measurement.angleChangeEnergy * scoreAngleEnergyWeight
+ let maxAngleCost = measurement.maxAngleChange * scoreMaxAngleWeight
+ let totalTurnCost = measurement.totalTurn * scoreTotalTurnWeight
+ let outOfBoundsCost = measurement.staysInBounds ? 0 : scoreOutOfBoundsPenalty
+ let totalScore = excessLengthCost + angleEnergyCost + maxAngleCost + totalTurnCost + outOfBoundsCost
+ return StandaloneCursorCandidateScoreComponents(
+ excessLengthRatio: excessLengthRatio,
+ excessLengthCost: excessLengthCost,
+ angleEnergyCost: angleEnergyCost,
+ maxAngleCost: maxAngleCost,
+ totalTurnCost: totalTurnCost,
+ outOfBoundsCost: outOfBoundsCost,
+ totalScore: totalScore
+ )
+ }
+
+ private static func binaryPiecewisePrimaryExtents(distance: CGFloat) -> (startExtent: CGFloat, endExtent: CGFloat) {
+ let primary = distance * primaryDistanceScale
+ let direct = distance * directSpanScale
+ let secondary = distance * 0.15
+ let lowCutoff: CGFloat = 48
+ let highCutoff: CGFloat = 640
+
+ if primary < lowCutoff {
+ return (lowCutoff, lowCutoff)
+ }
+ if primary < highCutoff {
+ return (primary, direct)
+ }
+ if secondary < highCutoff {
+ return (highCutoff, lowCutoff)
+ }
+ return (highCutoff, highCutoff)
+ }
+
+ private static func binaryPiecewiseHandleExtent(distance: CGFloat) -> CGFloat {
+ let raw = distance * secondaryDistanceScale
+ if raw < 50 {
+ return 50
+ }
+ if raw < 640 {
+ return raw
+ }
+ return 520
+ }
+
+ private static func clipPositiveRay(origin: CGPoint, direction: CGVector, bounds: CGRect?) -> CGFloat {
+ guard let bounds else {
+ return .infinity
+ }
+
+ var limit = CGFloat.infinity
+ if direction.dx > 0 {
+ limit = min(limit, (bounds.maxX - origin.x) / direction.dx)
+ } else if direction.dx < 0 {
+ limit = min(limit, (bounds.minX - origin.x) / direction.dx)
+ }
+
+ if direction.dy > 0 {
+ limit = min(limit, (bounds.maxY - origin.y) / direction.dy)
+ } else if direction.dy < 0 {
+ limit = min(limit, (bounds.minY - origin.y) / direction.dy)
+ }
+
+ return max(limit, 0)
+ }
+
+ private static func normalizedOrDefault(_ vector: CGVector, minimumLength: CGFloat) -> CGVector {
+ let length = vector.length
+ if length < minimumLength || length < normalizationEpsilon {
+ return CGVector(dx: 1, dy: 0)
+ }
+ return vector.scaled(by: 1 / length)
+ }
+}
+
+private func sampleCubic(
+ start: CGPoint,
+ control1: CGPoint,
+ control2: CGPoint,
+ end: CGPoint,
+ t: CGFloat
+) -> CGPoint {
+ let omt = 1 - t
+ let omt2 = omt * omt
+ let t2 = t * t
+ return CGPoint(
+ x: (omt2 * omt * start.x)
+ + (3 * omt2 * t * control1.x)
+ + (3 * omt * t2 * control2.x)
+ + (t2 * t * end.x),
+ y: (omt2 * omt * start.y)
+ + (3 * omt2 * t * control1.y)
+ + (3 * omt * t2 * control2.y)
+ + (t2 * t * end.y)
+ )
+}
+
+private func sampleCubicTangent(
+ start: CGPoint,
+ control1: CGPoint,
+ control2: CGPoint,
+ end: CGPoint,
+ t: CGFloat
+) -> CGVector {
+ let omt = 1 - t
+ return CGVector(
+ dx: (3 * omt * omt * (control1.x - start.x))
+ + (6 * omt * t * (control2.x - control1.x))
+ + (3 * t * t * (end.x - control2.x)),
+ dy: (3 * omt * omt * (control1.y - start.y))
+ + (6 * omt * t * (control2.y - control1.y))
+ + (3 * t * t * (end.y - control2.y))
+ )
+}
+
+private func unwrapAngleDelta(_ value: CGFloat) -> CGFloat {
+ var wrapped = value
+ while wrapped > .pi {
+ wrapped -= (.pi * 2)
+ }
+ while wrapped < -.pi {
+ wrapped += (.pi * 2)
+ }
+ return wrapped
+}
+
+private extension CGRect {
+ func contains(_ point: CGPoint, padding: CGFloat) -> Bool {
+ point.x >= minX - padding
+ && point.x <= maxX + padding
+ && point.y >= minY - padding
+ && point.y <= maxY + padding
+ }
+}
+
+private extension CGPoint {
+ static func + (lhs: CGPoint, rhs: CGVector) -> CGPoint {
+ CGPoint(x: lhs.x + rhs.dx, y: lhs.y + rhs.dy)
+ }
+
+ static func - (lhs: CGPoint, rhs: CGVector) -> CGPoint {
+ CGPoint(x: lhs.x - rhs.dx, y: lhs.y - rhs.dy)
+ }
+
+ static func - (lhs: CGPoint, rhs: CGPoint) -> CGVector {
+ CGVector(dx: lhs.x - rhs.x, dy: lhs.y - rhs.y)
+ }
+}
+
+private extension CGVector {
+ static func + (lhs: CGVector, rhs: CGVector) -> CGVector {
+ CGVector(dx: lhs.dx + rhs.dx, dy: lhs.dy + rhs.dy)
+ }
+
+ static func - (lhs: CGVector, rhs: CGVector) -> CGVector {
+ CGVector(dx: lhs.dx - rhs.dx, dy: lhs.dy - rhs.dy)
+ }
+
+ var length: CGFloat {
+ sqrt((dx * dx) + (dy * dy))
+ }
+
+ var normalized: CGVector {
+ let resolvedLength = max(length, 0.000_001)
+ return CGVector(dx: dx / resolvedLength, dy: dy / resolvedLength)
+ }
+
+ var perpendicular: CGVector {
+ CGVector(dx: -dy, dy: dx)
+ }
+
+ func scaled(by factor: CGFloat) -> CGVector {
+ CGVector(dx: dx * factor, dy: dy * factor)
+ }
+}
+
+private extension CGFloat {
+ func clamped(to range: ClosedRange<CGFloat>) -> CGFloat {
+ Swift.min(Swift.max(self, range.lowerBound), range.upperBound)
+ }
+
+ var cursorIdentifier: String {
+ String(format: "%.2f", Double(self)).replacingOccurrences(of: ".", with: "")
+ }
+}
diff --git a/experiments/StandaloneCursor/Tests/StandaloneCursorSupportTests/StandaloneCursorSupportTests.swift b/experiments/StandaloneCursor/Tests/StandaloneCursorSupportTests/StandaloneCursorSupportTests.swift
new file mode 100644
index 0000000..fb7d625
--- /dev/null
+++ b/experiments/StandaloneCursor/Tests/StandaloneCursorSupportTests/StandaloneCursorSupportTests.swift
@@ -0,0 +1,54 @@
+import CoreGraphics
+import XCTest
+@testable import StandaloneCursorSupport
+
+final class StandaloneCursorSupportTests: XCTestCase {
+ func testRecoveredCandidatePoolShape() {
+ let candidates = StandaloneCursorBinaryGuidedModel.makeCandidates(
+ start: CGPoint(x: 120, y: 180),
+ end: CGPoint(x: 760, y: 320),
+ bounds: CGRect(x: 0, y: 0, width: 960, height: 640)
+ )
+
+ XCTAssertEqual(candidates.count, 20)
+ XCTAssertEqual(candidates.filter { $0.kind == .base }.count, 2)
+ XCTAssertEqual(candidates.filter { $0.kind == .arched }.count, 18)
+ }
+
+ func testSelectionPrefersInBoundsCandidatesWhenAvailable() {
+ let candidates = StandaloneCursorBinaryGuidedModel.makeCandidates(
+ start: CGPoint(x: 120, y: 120),
+ end: CGPoint(x: 760, y: 340),
+ bounds: CGRect(x: 0, y: 0, width: 840, height: 420)
+ )
+ let decision = StandaloneCursorBinaryGuidedModel.chooseCandidate(from: candidates)
+ let selected = candidates.first { $0.id == decision.selectedCandidateID }
+
+ XCTAssertNotNil(selected)
+
+ let inBounds = candidates.filter(\.measurement.staysInBounds)
+ if inBounds.isEmpty == false {
+ XCTAssertEqual(decision.selectionPolicy, "prefer_in_bounds_then_lowest_score")
+ XCTAssertEqual(selected?.measurement.staysInBounds, true)
+ }
+ }
+
+ func testRecoveredSpringTimelineLocksEndpointBeforeCloseEnough() throws {
+ let candidates = StandaloneCursorBinaryGuidedModel.makeCandidates(
+ start: CGPoint(x: 100, y: 120),
+ end: CGPoint(x: 720, y: 380),
+ bounds: CGRect(x: 0, y: 0, width: 1280, height: 800)
+ )
+ let selectedID = StandaloneCursorBinaryGuidedModel.chooseCandidate(from: candidates).selectedCandidateID
+ let candidate = candidates.first { $0.id == selectedID }
+
+ XCTAssertNotNil(candidate)
+
+ let timeline = StandaloneCursorBinaryGuidedModel.buildTimeline(path: try XCTUnwrap(candidate?.path))
+ XCTAssertNotNil(timeline.firstEndpointLockTime)
+ XCTAssertNotNil(timeline.closeEnoughFirstTime)
+ XCTAssertLessThanOrEqual(try XCTUnwrap(timeline.firstEndpointLockTime), try XCTUnwrap(timeline.closeEnoughFirstTime))
+ XCTAssertGreaterThan(try XCTUnwrap(timeline.closeEnoughFirstTime), 1.3)
+ XCTAssertLessThan(try XCTUnwrap(timeline.closeEnoughFirstTime), 1.5)
+ }
+}