diff --git a/.env.example b/.env.example
new file mode 100644
index 0000000..36147c8
--- /dev/null
+++ b/.env.example
@@ -0,0 +1,40 @@
+# ============================================================
+# InkProof backend environment (backend/.env or deployment env)
+# NEVER commit real credentials. The Android app contains NO secrets;
+# all keys live only on the backend.
+# ============================================================
+
+# Port the backend listens on.
+PORT=8787
+
+# Force mock mode (no AI calls, deterministic results).
+# Mock mode also activates automatically when no AI key is configured.
+MOCK_MODE=true
+
+# --- AI provider (first configured key wins, top to bottom) ---
+# PRIMARY: Google Gemini — free API key at https://aistudio.google.com/apikey
+GEMINI_API_KEY=
+# Optional: pin a specific model. Default is the rolling alias
+# "gemini-flash-latest" (always the current stable Flash model). If a pinned
+# name ever 404s, the backend auto-discovers a current Flash model instead.
+GEMINI_MODEL=gemini-flash-latest
+# Alternatives (used only if GEMINI_API_KEY is empty):
+# Anthropic
+ANTHROPIC_API_KEY=
+ANTHROPIC_MODEL=claude-sonnet-4-20250514
+# OpenAI
+OPENAI_API_KEY=
+OPENAI_MODEL=gpt-4o
+
+# --- Symbolic math verification (optional but recommended) ---
+# Wolfram|Alpha App ID: https://developer.wolframalpha.com/
+WOLFRAM_APP_ID=
+
+# --- Abuse protection ---
+RATE_LIMIT_PER_MINUTE=20
+
+# ============================================================
+# Android build (optional): point the app at your deployed backend.
+# Pass via Gradle property instead of editing source:
+# ./gradlew assembleDebug -PinkproofBackendUrl=https://your-backend.example.com
+# ============================================================
diff --git a/.github/workflows/android.yml b/.github/workflows/android.yml
new file mode 100644
index 0000000..5b6f105
--- /dev/null
+++ b/.github/workflows/android.yml
@@ -0,0 +1,121 @@
+name: Build & Test
+
+on:
+ push:
+ branches: ["main", "arena/**"]
+ pull_request:
+ workflow_dispatch:
+
+jobs:
+ backend-tests:
+ name: Backend tests (Node)
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-node@v4
+ with:
+ node-version: 20
+ - name: Run backend tests
+ working-directory: backend
+ run: npm test
+
+ android:
+ name: Android unit tests + debug APK
+ runs-on: ubuntu-latest
+ permissions:
+ contents: write
+ issues: write
+ steps:
+ - uses: actions/checkout@v4
+
+ - name: Set up JDK 17
+ uses: actions/setup-java@v4
+ with:
+ distribution: temurin
+ java-version: 17
+
+ - name: Set up Gradle
+ uses: gradle/actions/setup-gradle@v4
+
+ - name: Unit tests
+ run: |
+ set -o pipefail
+ ./gradlew :app:testDebugUnitTest --stacktrace --console=plain 2>&1 | tee /tmp/tests.log
+
+ - name: Build debug APK
+ run: |
+ set -o pipefail
+ ./gradlew :app:assembleDebug --stacktrace --console=plain 2>&1 | tee /tmp/build.log
+
+ - name: Publish failure details (step summary + CI issue)
+ if: failure()
+ env:
+ GH_TOKEN: ${{ github.token }}
+ run: |
+ {
+ echo "## CI failure details (run ${GITHUB_RUN_ID})"
+ echo '```'
+ for f in /tmp/tests.log /tmp/build.log; do
+ [ -f "$f" ] && grep -E "^e: |error:|FAILED|Caused by|What went wrong|Execution failed|Unresolved|Test .* FAILED" -A 3 "$f" | head -c 40000
+ done
+ echo
+ echo '--- test case failures ---'
+ find app/build/test-results -name '*.xml' 2>/dev/null | while read -r x; do
+ if grep -q ' /tmp/summary.md
+ cat /tmp/summary.md >> "$GITHUB_STEP_SUMMARY"
+ EXISTING=$(gh issue list --repo "$GITHUB_REPOSITORY" --state open --search "CI failure log in:title" --json number --jq '.[0].number' || true)
+ if [ -n "$EXISTING" ] && [ "$EXISTING" != "null" ]; then
+ gh issue comment "$EXISTING" --repo "$GITHUB_REPOSITORY" --body-file /tmp/summary.md
+ else
+ gh issue create --repo "$GITHUB_REPOSITORY" --title "CI failure log" --body-file /tmp/summary.md
+ fi
+
+ - name: Upload test reports
+ if: always()
+ uses: actions/upload-artifact@v4
+ with:
+ name: unit-test-report
+ path: app/build/reports/tests/
+ if-no-files-found: ignore
+
+ - name: Upload debug APK
+ uses: actions/upload-artifact@v4
+ with:
+ name: inkproof-debug-apk
+ path: app/build/outputs/apk/debug/app-debug.apk
+
+ # Easy download: keep the newest debug APK on a rolling pre-release,
+ # so it can be grabbed without digging into Actions artifacts.
+ - name: Publish debug APK to the debug-latest release
+ if: success() && github.event_name == 'push'
+ env:
+ GH_TOKEN: ${{ github.token }}
+ run: |
+ cp app/build/outputs/apk/debug/app-debug.apk inkproof-debug.apk
+ if gh release view debug-latest --repo "$GITHUB_REPOSITORY" > /dev/null 2>&1; then
+ gh release upload debug-latest inkproof-debug.apk --clobber --repo "$GITHUB_REPOSITORY"
+ gh release edit debug-latest --repo "$GITHUB_REPOSITORY" \
+ --notes "Auto-published by CI from commit $GITHUB_SHA ($(date -u +'%Y-%m-%d %H:%M UTC'))."
+ else
+ gh release create debug-latest inkproof-debug.apk \
+ --repo "$GITHUB_REPOSITORY" \
+ --target "$GITHUB_SHA" \
+ --prerelease \
+ --title "InkProof debug APK (latest)" \
+ --notes "Auto-published by CI from commit $GITHUB_SHA ($(date -u +'%Y-%m-%d %H:%M UTC'))."
+ fi
+
+ - name: Close CI failure issue on success
+ if: success()
+ env:
+ GH_TOKEN: ${{ github.token }}
+ run: |
+ for n in $(gh issue list --repo "$GITHUB_REPOSITORY" --state open --search "CI failure log in:title" --json number --jq '.[].number'); do
+ gh issue close "$n" --repo "$GITHUB_REPOSITORY" --comment "CI is green at $GITHUB_SHA (tests pass, APK built)."
+ done
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..b28ff54
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,23 @@
+# Gradle
+.gradle/
+build/
+app/build/
+local.properties
+
+# IDE
+.idea/
+*.iml
+.DS_Store
+captures/
+.externalNativeBuild/
+.cxx/
+
+# Secrets — never commit real credentials
+.env
+backend/.env
+*.keystore
+*.jks
+
+# Node
+node_modules/
+npm-debug.log
diff --git a/README.md b/README.md
index aaed51e..8036f8f 100644
--- a/README.md
+++ b/README.md
@@ -1 +1,401 @@
-# inkproof
+# InkProof
+
+**Prove your work.**
+
+*You solve it. InkProof checks it.*
+
+InkProof is a premium handwritten mathematics notebook for Android tablets.
+You write mathematics by hand with an active stylus; InkProof checks *your*
+work — finds the first mistake, explains it, and coaches you with progressive
+hints. It is deliberately **not** an AI homework-answer app: the student does
+the solving, InkProof does the verifying.
+
+Primary hardware target: **OnePlus Pad + OnePlus Stylo 2**.
+
+---
+
+## Features
+
+- **Low-latency handwriting** — ink appears under the stylus as you write.
+ Pressure-tapered strokes, hover cursor, stylus-button eraser, palm rejection
+ based on real Android tool types (not timing hacks).
+- **Real vector stroke model** — every stroke has a persistent ID, points with
+ pressure + timestamps, color, width and tool. Fully editable: undo, redo,
+ erase, lasso, move, copy/paste, recolor. Sharp at any zoom, never flattened
+ to a bitmap.
+- **Notebook library** — folders, notebooks, pages, favorites, search, rename,
+ duplicate, delete; cards show real page thumbnails.
+- **Templates** — blank, ruled, grid, dot grid, engineering grid, math
+ worksheet. Switching templates never touches your ink.
+- **Hold-to-shape** — draw a rough shape, keep the pen down ~400 ms (tunable in
+ Settings) and it snaps to a clean line / arrow / circle / ellipse /
+ rectangle / square / triangle. Deliberately conservative: small glyphs,
+ letters, parentheses and math symbols can never snap — uncertain geometry
+ always stays exactly as you drew it.
+- **Contextual toolbar** — selecting pen / highlighter / eraser / shapes shows
+ a compact horizontal options strip (colors, widths, sizes, shape kinds)
+ under the toolbar; it scrolls sideways when narrow. No tall menus ever
+ cover the notebook.
+- **Stylus button double-press** — toggles eraser ↔ previous tool (Settings →
+ Writing; default on). Uses real `BUTTON_STYLUS_PRIMARY/SECONDARY` events —
+ never faked from screen taps.
+- **Text boxes** — tap with the Text tool to place typed text anywhere on the
+ page; tap an existing box to edit or delete it.
+- **Import image** — pick a photo from the gallery and it becomes a page you
+ can annotate (great for textbook problems).
+- **Question sources** — + Question offers Write by hand / Type / Paste /
+ Import image / Import PDF; an imported image or PDF page becomes the
+ question statement with a normal handwriting solution band below it.
+- **Math question pages** — a **Question is a first-class object** with its own
+ content (typed, handwritten, pasted, imported), its own solution region,
+ version counters and check history. Multiple questions per page are fully
+ isolated.
+- **CHECK MY WORK** — compact side panel (your handwriting stays visible):
+ per-step verdicts (✓ / ✗ first mistake / ↳ depends on earlier error),
+ progressive hints, optional full solution. **SOLVE** is a separate, visually
+ distinct action.
+- **Honest states** — correct, incorrect, incomplete, unclear, unsupported,
+ error. If handwriting can't be read confidently, InkProof says so.
+ **It never guesses.**
+- **Lasso + check selection** — on freeform pages, lasso any work and check
+ just that selection. Selections inside a question route through the Question
+ object (its typed statement is the source of truth).
+- **PDF** — import a PDF (each page becomes an annotatable page), write on it,
+ export the annotated notebook back to PDF.
+- **Local-first** — notebooks, pages, handwriting, lasso, shapes and storage
+ all work offline. Only CHECK/SOLVE needs the network.
+- **Pen stabilization** — Off / Low / Medium / High adaptive jitter smoothing
+ that preserves corners and adds zero latency (position-only filtering).
+- **Continuous scrolling** — finger-scroll naturally from page to page;
+ neighbor pages render in place and the switch is a seamless camera handoff.
+ Pages stay fully independent objects underneath.
+- **Paper colors** — per-page paper from white to black (warm white, grey,
+ slate, dark grey, near black); independent of both template and app theme;
+ template lines adapt to dark paper; ink is never auto-inverted.
+- **Recognize math** — lasso a region → Recognize math → Accept / Edit;
+ on-device recognition first (with per-line writing-area + pre-context and
+ math normalization: `x2` → `x^2`, unicode symbols → ASCII), and ONLY if
+ that is uncertain, one cloud attempt through your backend
+ (`POST /api/recognize`, Gemini multimodal on a render of the selected
+ strokes). Never automatic, never replaces handwriting, never guesses.
+- **Dark mode** — System / Light / Dark in Settings → Appearance; one theme
+ system drives every screen, dialog and panel. Pages keep their own paper
+ color — a dark app never forces dark pages.
+- **Universal import** — one "Import file…" picker: PDF (multi-page,
+ annotatable), images (PNG/JPG/WEBP/BMP), and text formats (TXT/MD/HTML/CSV →
+ editable text pages). Unsupported formats (DOCX/XLSX/PPTX/SVG…) are rejected
+ gracefully with a clear reason, never a crash.
+- **Mock mode** — the full UX works with zero credentials; deterministic mock
+ results (`mock:correct`, `mock:incorrect`, `mock:incomplete`, `mock:unclear`
+ keywords force scenarios). Mock data can never leak into real checks: the
+ provider is chosen per call and only ever processes the submitted request.
+
+---
+
+## Architecture
+
+```
+android/ (this repo, :app)
+├── ink/ Custom handwriting engine (no Compose in the hot path)
+│ ├── InkCanvasView low-latency input + rendering
+│ ├── StrokeRenderer pressure-tapered vector ink
+│ ├── ShapeDetector pure-geometry hold-to-shape
+│ ├── CanvasCamera page-space ↔ screen-space transform
+│ └── UndoRedoStack bounded command history
+├── model/ Stroke / Question / CheckResponse (strict JSON schema)
+├── data/
+│ ├── db/ Room: folders, notebooks, pages, questions, strokes,
+│ │ text/image objects, cached check results
+│ └── repo/ Library / Page / Check repositories
+├── check/ CheckWorkEngine + replaceable abstractions:
+│ ├── HandwritingRecognizer (LocalDigitalInkRecognizer | MockRecognizer)
+│ ├── CheckProvider (BackendCheckProvider | MockCheckProvider)
+│ └── MathVerificationProvider (backend-side Wolfram)
+├── pdf/ PdfImporter / PdfExporter
+└── ui/ Jetpack Compose: library, editor, check panel, settings
+
+backend/ (zero-dependency Node 18+)
+└── /api/check, /api/solve, /api/health
+ rate limiting · request validation · AI call · Wolfram cross-check ·
+ strict response sanitization · response cache
+```
+
+### Handwriting latency architecture
+
+The previous prototype rendered ink only after state updates. InkProof fixes
+this at the architecture level:
+
+```
+Stylus MotionEvent (+ batched historical samples, unbuffered dispatch)
+ → InkCanvasView input layer (page-space points, pressure, timestamps)
+ → active stroke drawn IMMEDIATELY in onDraw
+ → committed strokes live in a Picture display list,
+ rebuilt only when the stroke set changes — never per point
+ → on pen-up, the stroke is persisted to Room asynchronously
+```
+
+Nothing on the stylus path waits for Compose state, the database, JSON,
+recognition or the network.
+
+### Input policy (OnePlus Stylo 2 first)
+
+- `TOOL_TYPE_STYLUS` writes; `TOOL_TYPE_ERASER` and the primary stylus button
+ erase; hover shows a tool cursor.
+- Fingers navigate: one-finger pan, two-finger pan, pinch-zoom.
+- Palm rejection: finger touches are ignored while the stylus is in contact or
+ hovered recently; extra pointers during a stroke are discarded. Optional
+ "finger writing" setting for tablets without a stylus.
+
+### Question model
+
+```
+Page (NOTE | MATH_QUESTION | PDF)
+└── Question (first-class object)
+ ├── content: typed | handwritten | image | pdf | pasted
+ │ typed text is NEVER OCR'd — it is already the truth
+ ├── question region (y-band) → ink here = question content
+ ├── solution region (y-band) → ink here = the student's solution,
+ │ tagged with the question ID at write time
+ ├── contentVersion / solutionVersion → cache invalidation
+ └── check history (CheckResult rows)
+```
+
+The question **object** is the source of truth; the on-page divider is only
+its visual representation. Checking Q2 can structurally never see Q1/Q3 — the
+engine loads strokes by `questionId`, not by scanning the page.
+
+### CHECK MY WORK pipeline
+
+```
+Question object + ONLY that question's solution strokes
+ → HandwritingRecognizer (stroke data: order, coordinates, timestamps —
+ never screenshots; low confidence ⇒ UNCLEAR, never a guess)
+ → structured CheckRequest JSON
+ → backend: validate → AI step analysis → Wolfram cross-check →
+ sanitize to strict schema
+ → CheckResponse JSON → compact side panel
+ → cached by (question, contentVersion, solutionVersion, action);
+ editing the solution automatically invalidates the cache
+```
+
+"What did the student write?", "Is it mathematically correct?" and "How should
+we explain it?" are three separate, replaceable layers.
+
+---
+
+## Setup
+
+### Requirements
+
+- Android Studio (Koala or newer) with Android SDK 34
+- JDK 17
+- Node 18+ for the backend
+
+### Android app
+
+```bash
+git clone
+# open in Android Studio, or:
+./gradlew :app:assembleDebug
+# APK: app/build/outputs/apk/debug/app-debug.apk
+adb install app/build/outputs/apk/debug/app-debug.apk
+```
+
+Debug builds default to **mock mode** — the entire app, including CHECK MY
+WORK, works with no backend and no credentials.
+
+To point the app at a real backend, either set it **at runtime** in
+Settings → AI → Backend URL (e.g. `http://192.168.1.50:8787` while the
+backend runs on a computer on the same Wi-Fi — debug builds allow plain
+HTTP for this), or bake a default into the build:
+
+```bash
+./gradlew :app:assembleDebug -PinkproofBackendUrl=https://your-backend.example.com
+```
+
+then turn off "Mock mode" in Settings → AI.
+
+### Backend
+
+```bash
+cd backend
+cp ../.env.example .env # fill in keys; see .env.example
+npm start # zero dependencies, plain Node
+npm test
+```
+
+Endpoints: `GET /api/health`, `POST /api/check`, `POST /api/solve`, and
+`POST /api/recognize` (hybrid handwriting-recognition fallback — the app
+only calls it when on-device recognition is uncertain).
+
+**Google Gemini is the primary AI provider** — set `GEMINI_API_KEY`
+(free key from https://aistudio.google.com/apikey). The default model is the
+rolling alias `gemini-flash-latest`, so the backend never pins an obsolete
+model name; override with `GEMINI_MODEL`, and if a pinned name ever
+disappears the backend auto-discovers a current Flash model via the
+ListModels API. Anthropic and OpenAI keys work as drop-in alternatives
+behind the same provider interface.
+
+No keys configured ⇒ the backend runs in mock mode automatically. Secrets are
+read only from the environment; the Android client never contains them.
+
+## Getting CHECK MY WORK Working
+
+The real CHECK/SOLVE flow needs a Gemini API key on the **backend** (never in
+the Android app). Follow these steps end-to-end:
+
+1. **Open Google AI Studio** → https://aistudio.google.com/apikey
+ (sign in with any Google account).
+2. **Create an API key** ("Get API key" → "Create API key"). Free-tier keys
+ work; Gemini Flash models have a free quota (subject to Google's current
+ limits — not unlimited).
+3. **Configure the backend**: copy the template and edit it.
+ ```bash
+ cd backend
+ cp ../.env.example .env
+ ```
+4. **Set `GEMINI_API_KEY`** in `backend/.env`:
+ ```
+ GEMINI_API_KEY=AIza...your-key...
+ ```
+5. **(Optional) set `GEMINI_MODEL`**. The default `gemini-flash-latest` is a
+ rolling alias that always points at the current stable Flash model, so you
+ normally don't need this. To pin a version, check the current model list at
+ https://ai.google.dev/gemini-api/docs/models and set e.g.
+ `GEMINI_MODEL=`. If a pinned name ever 404s, the
+ backend auto-discovers a current Flash model and retries.
+6. **Start the backend**:
+ ```bash
+ node --env-file=.env server.js # needs Node 18+ (22+ recommended)
+ ```
+ You should see `InkProof backend listening on :8787 (mock_mode=false)`.
+ `mock_mode=false` confirms the key was picked up.
+7. **Start the Android app** on the tablet (install the debug APK below).
+8. **Check AI status**: Settings → AI → **Test AI connection**. You should see
+ `AI CONNECTED — provider: gemini`. If you see `BACKEND UNAVAILABLE`, set
+ Settings → AI → Backend URL to `http://:8787` (both
+ devices on the same Wi-Fi; debug builds allow plain HTTP).
+9. **Run a test request** from the computer:
+ ```bash
+ curl http://localhost:8787/api/health
+ curl -X POST http://localhost:8787/api/check -H "content-type: application/json" \
+ -d '{"request_id":"t1","action":"check","question_id":"q1","question_text":"Solve 2x + 6 = 14","question_source":"typed","question_confidence":1,"solution_lines":[{"line_index":0,"text":"2x = 8","confidence":0.95},{"line_index":1,"text":"x = 4","confidence":0.95}],"content_version":1,"solution_version":1}'
+ ```
+ A JSON result with `"status":"correct"` means Gemini is answering.
+10. **Test CHECK MY WORK**: turn OFF Settings → AI → Mock mode, open a
+ question, write a solution, tap **Check my work**.
+11. **Test SOLVE**: same question → **Solve** (uses only the question text).
+12. **Common API errors**
+ | Symptom | Cause / fix |
+ |---|---|
+ | `gemini 400` | Malformed key — re-copy it without spaces |
+ | `gemini 403` | Key disabled/restricted — create a fresh key in AI Studio |
+ | `gemini 404` | Model name gone — backend auto-falls back; or fix `GEMINI_MODEL` |
+ | `gemini 429` | Free-tier quota hit — wait a minute, or lower usage |
+ | `BACKEND UNAVAILABLE` | Backend not running / wrong IP / firewall blocks :8787 |
+ | Result is always mock | Mock mode still ON in app settings, or `MOCK_MODE=true` in `.env` |
+
+**Where secrets live**: only in `backend/.env` (gitignored) or your host's
+environment variables. The Android client and this repo contain **no keys**.
+**Restart/redeploy**: edit `.env`, Ctrl-C the Node process, start it again —
+provider/model changes take effect immediately (the app also re-reads the
+backend URL per request, no reinstall needed).
+
+### Windows setup
+
+Everything works on Windows with Node 18+ and Android Studio:
+
+```powershell
+# Backend (PowerShell)
+cd backend
+Copy-Item ..\.env.example .env
+notepad .env # paste GEMINI_API_KEY
+node --env-file=.env server.js # http://localhost:8787
+
+# Test (PowerShell)
+Invoke-RestMethod http://localhost:8787/api/health
+
+# Android: open the repo in Android Studio and Run, or build an APK:
+.\gradlew.bat :app:assembleDebug # output: app\build\outputs\apk\debug\app-debug.apk
+.\gradlew.bat :app:testDebugUnitTest
+```
+
+Alternative to a local `.env`: set a user environment variable
+(`setx GEMINI_API_KEY "AIza..."`, then restart the terminal) and run
+`node server.js`. Find your PC's IP for the tablet with `ipconfig`
+(IPv4 address), and allow Node through Windows Defender Firewall when
+prompted. Never commit a real key.
+
+### Tests
+
+```bash
+./gradlew :app:testDebugUnitTest # Android unit + Robolectric tests
+cd backend && npm test # backend tests
+```
+
+Covered: stroke codec roundtrips, shape detection (line/arrow/circle/ellipse/
+rectangle/square/triangle, squiggle rejection), eraser hit-testing (segment
+distance, radius sizes, pass-through misses), shape factory geometry + scaling,
+clipboard paste independence (new IDs, no shared references), undo/redo, line
+segmentation, strict JSON parsing (including malformed AI output), mock
+scenarios, recognition-confidence thresholding (UNCLEAR, provider never
+called), SOLVE isolation (student ink never recognized, provider gets the
+question only — linear/quadratic/derivative/integral/limit), import
+classification (PDF/image/text/HTML/CSV routed; DOCX/XLSX/PPTX/SVG rejected
+with reasons), text import (HTML stripping, CSV layout, line wrapping),
+folders, text-object persistence, notebook/page persistence, page reordering,
+page independence, question isolation (page A vs page B, Q1/Q2/Q3), cache
+invalidation on solution edits, empty-input error states, backend schema
+validation, provider priority (Gemini first), rate limiting and dedup cache,
+stroke stabilization (jitter reduction, corner preservation, endpoint
+fidelity, OFF pass-through), paper-color persistence + page independence +
+dark-paper detection + adaptive template lines + ink never recolored,
+hold-to-shape conservatism (letter-o loop, parenthesis, √ stroke, sine curve
+and lumpy quads all stay handwriting), math normalization (implicit powers,
+unicode symbols, word-safety for sin/log), hybrid recognition (cloud never
+contacted when local is confident; honest uncertain results), stylus
+double-press detection (timing windows, consumed pairs, OFF reset) and
+eraser↔previous-tool restoration, and the backend /api/recognize contract
+(mock shape, missing-image and bad-mime rejection).
+
+CI (GitHub Actions) runs both suites and uploads a debug APK artifact on every
+push.
+
+---
+
+## OnePlus Pad testing
+
+The architecture targets the OnePlus Pad + Stylo 2 (tool-type routing,
+pressure, hover, unbuffered dispatch, stylus-button eraser). **Physical
+validation on the device has NOT been performed from this environment** — the
+following must be verified on hardware: live ink latency, palm rejection feel,
+pressure curve, hover cursor, hold-to-shape timing, long-session performance
+with thousands of strokes, pinch-zoom smoothness.
+
+## Known limitations
+
+- On-device ML Kit digital ink uses the `en-US` text model (Google ships no
+ public math model). InkProof compensates with recognition context +
+ math normalization, and a hybrid cloud fallback (`/api/recognize`) for
+ low-confidence ink. When even that is uncertain, InkProof reports UNCLEAR
+ instead of guessing.
+- The OnePlus Stylo "double-tap the barrel" air gesture is handled by OnePlus
+ firmware and is not exposed to third-party apps as a public event. InkProof
+ listens for real stylus *button* events; if the OEM maps the gesture to a
+ button event it works automatically.
+- Image objects as movable canvas elements are modelled in the database but
+ not yet editable in the UI — "Import image" brings a picture in as a page
+ you can write on instead.
+- Typed text boxes are placed/edited/deleted via tap dialogs; drag-to-move and
+ resize for text boxes are future refinements.
+- Physical validation on a OnePlus Pad + Stylo 2 has not been performed from
+ this environment and remains required.
+- PDF export flattens ink into the PDF (annotations are not embedded as PDF
+ ink objects).
+- Question regions are vertical bands; free-positioned question frames are a
+ future refinement.
+- No accounts, sync, collaboration or subscriptions — by design (v1 scope).
+
+## License
+
+Personal/portfolio project.
diff --git a/app/build.gradle.kts b/app/build.gradle.kts
new file mode 100644
index 0000000..54ee709
--- /dev/null
+++ b/app/build.gradle.kts
@@ -0,0 +1,102 @@
+plugins {
+ alias(libs.plugins.android.application)
+ alias(libs.plugins.kotlin.android)
+ alias(libs.plugins.kotlin.compose)
+ alias(libs.plugins.kotlin.serialization)
+ alias(libs.plugins.ksp)
+}
+
+android {
+ namespace = "com.inkproof.app"
+ compileSdk = 34
+
+ defaultConfig {
+ applicationId = "com.inkproof.app"
+ minSdk = 26
+ targetSdk = 34
+ versionCode = 1
+ versionName = "1.0.0"
+
+ testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
+
+ // Backend base URL. Debug builds default to mock mode; override in
+ // local.properties or via -PinkproofBackendUrl=... Never put API keys here.
+ val backendUrl = (project.findProperty("inkproofBackendUrl") as String?)
+ ?: "https://inkproof-backend.example.com"
+ buildConfigField("String", "BACKEND_BASE_URL", "\"$backendUrl\"")
+ }
+
+ buildTypes {
+ debug {
+ buildConfigField("boolean", "DEFAULT_MOCK_MODE", "true")
+ }
+ release {
+ isMinifyEnabled = true
+ isShrinkResources = true
+ buildConfigField("boolean", "DEFAULT_MOCK_MODE", "false")
+ proguardFiles(
+ getDefaultProguardFile("proguard-android-optimize.txt"),
+ "proguard-rules.pro"
+ )
+ }
+ }
+
+ compileOptions {
+ sourceCompatibility = JavaVersion.VERSION_17
+ targetCompatibility = JavaVersion.VERSION_17
+ }
+ kotlinOptions {
+ jvmTarget = "17"
+ }
+ buildFeatures {
+ compose = true
+ buildConfig = true
+ }
+ packaging {
+ resources {
+ excludes += "/META-INF/{AL2.0,LGPL2.1}"
+ }
+ }
+ testOptions {
+ unitTests {
+ isIncludeAndroidResources = true
+ isReturnDefaultValues = true
+ }
+ }
+}
+
+dependencies {
+ implementation(libs.androidx.core.ktx)
+ implementation(libs.androidx.lifecycle.runtime.ktx)
+ implementation(libs.androidx.lifecycle.viewmodel.compose)
+ implementation(libs.androidx.lifecycle.runtime.compose)
+ implementation(libs.androidx.activity.compose)
+ implementation(platform(libs.androidx.compose.bom))
+ implementation(libs.androidx.compose.ui)
+ implementation(libs.androidx.compose.ui.graphics)
+ implementation(libs.androidx.compose.ui.tooling.preview)
+ implementation(libs.androidx.compose.material3)
+ implementation(libs.androidx.compose.material.icons)
+ implementation(libs.androidx.navigation.compose)
+
+ implementation(libs.androidx.room.runtime)
+ implementation(libs.androidx.room.ktx)
+ ksp(libs.androidx.room.compiler)
+
+ implementation(libs.androidx.datastore.preferences)
+ implementation(libs.kotlinx.serialization.json)
+ implementation(libs.kotlinx.coroutines.android)
+ implementation(libs.okhttp)
+ implementation(libs.mlkit.digital.ink)
+
+ testImplementation(libs.junit)
+ testImplementation(libs.robolectric)
+ testImplementation(libs.androidx.test.core)
+ testImplementation(libs.kotlinx.coroutines.test)
+ testImplementation(libs.okhttp.mockwebserver)
+
+ androidTestImplementation(libs.androidx.junit)
+ androidTestImplementation(libs.androidx.espresso.core)
+
+ debugImplementation(libs.androidx.compose.ui.tooling)
+}
diff --git a/app/proguard-rules.pro b/app/proguard-rules.pro
new file mode 100644
index 0000000..c75bddb
--- /dev/null
+++ b/app/proguard-rules.pro
@@ -0,0 +1,14 @@
+# InkProof proguard rules.
+
+# kotlinx.serialization
+-keepattributes *Annotation*, InnerClasses
+-dontnote kotlinx.serialization.AnnotationsKt
+-keepclassmembers class kotlinx.serialization.json.** { *** Companion; }
+-keepclasseswithmembers class kotlinx.serialization.json.** { kotlinx.serialization.KSerializer serializer(...); }
+-keep,includedescriptorclasses class com.inkproof.app.**$$serializer { *; }
+-keepclassmembers class com.inkproof.app.** { *** Companion; }
+-keepclasseswithmembers class com.inkproof.app.** { kotlinx.serialization.KSerializer serializer(...); }
+
+# ML Kit digital ink
+-keep class com.google.mlkit.** { *; }
+-dontwarn com.google.mlkit.**
diff --git a/app/src/debug/AndroidManifest.xml b/app/src/debug/AndroidManifest.xml
new file mode 100644
index 0000000..b14a010
--- /dev/null
+++ b/app/src/debug/AndroidManifest.xml
@@ -0,0 +1,9 @@
+
+
+
+
+
diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml
new file mode 100644
index 0000000..a0e708f
--- /dev/null
+++ b/app/src/main/AndroidManifest.xml
@@ -0,0 +1,37 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/app/src/main/java/com/inkproof/app/InkProofApp.kt b/app/src/main/java/com/inkproof/app/InkProofApp.kt
new file mode 100644
index 0000000..b6ed54f
--- /dev/null
+++ b/app/src/main/java/com/inkproof/app/InkProofApp.kt
@@ -0,0 +1,96 @@
+package com.inkproof.app
+
+import android.app.Application
+import com.inkproof.app.check.BackendCheckProvider
+import com.inkproof.app.check.BackendInkRecognizer
+import com.inkproof.app.check.CheckProvider
+import com.inkproof.app.check.CheckWorkEngine
+import com.inkproof.app.check.HandwritingRecognizer
+import com.inkproof.app.check.HybridRecognizer
+import com.inkproof.app.check.LocalDigitalInkRecognizer
+import com.inkproof.app.check.MockCheckProvider
+import com.inkproof.app.check.MockRecognizer
+import com.inkproof.app.data.db.InkProofDatabase
+import com.inkproof.app.data.repo.CheckRepository
+import com.inkproof.app.data.repo.LibraryRepository
+import com.inkproof.app.data.repo.PageRepository
+import com.inkproof.app.data.settings.SettingsStore
+import com.inkproof.app.pdf.ImageImporter
+import com.inkproof.app.pdf.PdfExporter
+import com.inkproof.app.pdf.PdfImporter
+import com.inkproof.app.pdf.TextImporter
+
+/**
+ * Manual dependency wiring — small, explicit and easy to test.
+ *
+ * Mock isolation: the mock providers are selected ONLY through
+ * [checkEngine]'s mockMode flag; they can never leak into a real check,
+ * because the provider is chosen per-call from current settings.
+ */
+class InkProofApp : Application() {
+
+ val database: InkProofDatabase by lazy { InkProofDatabase.get(this) }
+ val libraryRepository: LibraryRepository by lazy { LibraryRepository(database) }
+ val pageRepository: PageRepository by lazy { PageRepository(database) }
+ val checkRepository: CheckRepository by lazy { CheckRepository(database) }
+ val settingsStore: SettingsStore by lazy { SettingsStore(this) }
+ val pdfImporter: PdfImporter by lazy { PdfImporter(this, libraryRepository) }
+ val pdfExporter: PdfExporter by lazy { PdfExporter(this, libraryRepository, pageRepository) }
+ val imageImporter: ImageImporter by lazy { ImageImporter(this, libraryRepository) }
+ val textImporter: TextImporter by lazy {
+ TextImporter(this, libraryRepository, pageRepository)
+ }
+
+ private val mockProvider: CheckProvider by lazy { MockCheckProvider() }
+ private val mockRecognizer: HandwritingRecognizer by lazy { MockRecognizer() }
+ private val localRecognizer: HandwritingRecognizer by lazy { LocalDigitalInkRecognizer() }
+
+ /**
+ * The recognizer matching the current mode — for on-demand recognition.
+ * Real mode is a hybrid: on-device ML Kit first; if (and only if) that
+ * is uncertain, one cloud attempt through the configured backend.
+ */
+ fun recognizer(mockMode: Boolean, backendUrl: String = ""): HandwritingRecognizer {
+ if (mockMode) return mockRecognizer
+ val effectiveUrl = backendUrl.ifBlank { BuildConfig.BACKEND_BASE_URL }
+ return HybridRecognizer(localRecognizer, cloudRecognizer(effectiveUrl))
+ }
+
+ @Volatile private var cachedCloudRecognizer: Pair? = null
+
+ private fun cloudRecognizer(url: String): BackendInkRecognizer? {
+ if (url.isBlank()) return null
+ cachedCloudRecognizer?.let { (cachedUrl, r) -> if (cachedUrl == url) return r }
+ val r = BackendInkRecognizer(url)
+ cachedCloudRecognizer = url to r
+ return r
+ }
+
+ // Backend provider is cached per effective URL so a Settings change
+ // takes effect on the very next check — no app restart needed.
+ @Volatile private var cachedBackend: Pair? = null
+
+ private fun backendProvider(url: String): CheckProvider {
+ cachedBackend?.let { (cachedUrl, provider) ->
+ if (cachedUrl == url) return provider
+ }
+ val provider = BackendCheckProvider(url)
+ cachedBackend = url to provider
+ return provider
+ }
+
+ fun checkEngine(
+ mockMode: Boolean,
+ confidenceThreshold: Float = 0.4f,
+ backendUrl: String = ""
+ ): CheckWorkEngine {
+ val effectiveUrl = backendUrl.ifBlank { BuildConfig.BACKEND_BASE_URL }
+ return CheckWorkEngine(
+ pageRepository = pageRepository,
+ checkRepository = checkRepository,
+ recognizer = recognizer(mockMode, backendUrl),
+ provider = if (mockMode) mockProvider else backendProvider(effectiveUrl),
+ confidenceThreshold = confidenceThreshold
+ )
+ }
+}
diff --git a/app/src/main/java/com/inkproof/app/check/BackendCheckProvider.kt b/app/src/main/java/com/inkproof/app/check/BackendCheckProvider.kt
new file mode 100644
index 0000000..4bbca30
--- /dev/null
+++ b/app/src/main/java/com/inkproof/app/check/BackendCheckProvider.kt
@@ -0,0 +1,84 @@
+package com.inkproof.app.check
+
+import com.inkproof.app.model.CheckRequest
+import com.inkproof.app.model.CheckResponse
+import com.inkproof.app.model.CheckStatus
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.withContext
+import kotlinx.serialization.json.Json
+import okhttp3.MediaType.Companion.toMediaType
+import okhttp3.OkHttpClient
+import okhttp3.Request
+import okhttp3.RequestBody.Companion.toRequestBody
+import java.io.IOException
+import java.util.concurrent.TimeUnit
+
+/**
+ * Talks to the InkProof backend. The backend owns all API secrets; the
+ * Android app never carries production credentials.
+ *
+ * All failures are converted into structured ERROR responses — the UI never
+ * sees raw exceptions or malformed AI prose.
+ */
+class BackendCheckProvider(
+ private val baseUrl: String,
+ client: OkHttpClient? = null
+) : CheckProvider {
+
+ override val name: String = "backend"
+
+ private val json = Json { ignoreUnknownKeys = true; coerceInputValues = true }
+
+ private val http: OkHttpClient = client ?: OkHttpClient.Builder()
+ .connectTimeout(15, TimeUnit.SECONDS)
+ .readTimeout(90, TimeUnit.SECONDS)
+ .build()
+
+ override suspend fun check(request: CheckRequest): CheckResponse =
+ post("/api/check", request)
+
+ override suspend fun solve(request: CheckRequest): CheckResponse =
+ post("/api/solve", request)
+
+ private suspend fun post(path: String, request: CheckRequest): CheckResponse =
+ withContext(Dispatchers.IO) {
+ val body = json.encodeToString(CheckRequest.serializer(), request)
+ .toRequestBody("application/json; charset=utf-8".toMediaType())
+ val httpRequest = Request.Builder()
+ .url(baseUrl.trimEnd('/') + path)
+ .post(body)
+ .build()
+ try {
+ http.newCall(httpRequest).execute().use { response ->
+ val text = response.body?.string().orEmpty()
+ when {
+ response.code == 429 -> CheckResponse(
+ status = CheckStatus.ERROR,
+ message = "Too many checks in a short time. Please wait a moment and try again."
+ )
+ !response.isSuccessful -> CheckResponse(
+ status = CheckStatus.ERROR,
+ message = "The check service returned an error (${response.code}). Your work is saved — try again shortly."
+ )
+ else -> parseStrict(text)
+ }
+ }
+ } catch (e: IOException) {
+ CheckResponse(
+ status = CheckStatus.ERROR,
+ message = "No connection to the check service. Writing and notebooks keep working offline; checking needs internet."
+ )
+ }
+ }
+
+ /** Strict parsing: malformed AI JSON becomes a clean, visible error state. */
+ internal fun parseStrict(text: String): CheckResponse =
+ try {
+ json.decodeFromString(CheckResponse.serializer(), text)
+ } catch (e: Exception) {
+ CheckResponse(
+ status = CheckStatus.ERROR,
+ message = "The check service sent an unreadable response. Please try again."
+ )
+ }
+}
diff --git a/app/src/main/java/com/inkproof/app/check/BackendInkRecognizer.kt b/app/src/main/java/com/inkproof/app/check/BackendInkRecognizer.kt
new file mode 100644
index 0000000..d73de97
--- /dev/null
+++ b/app/src/main/java/com/inkproof/app/check/BackendInkRecognizer.kt
@@ -0,0 +1,181 @@
+package com.inkproof.app.check
+
+import android.graphics.Bitmap
+import android.graphics.Canvas
+import android.graphics.Color
+import android.graphics.Paint
+import android.graphics.Path
+import android.util.Base64
+import com.inkproof.app.model.RecognizedLine
+import com.inkproof.app.model.Stroke
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.withContext
+import kotlinx.serialization.Serializable
+import kotlinx.serialization.json.Json
+import okhttp3.MediaType.Companion.toMediaType
+import okhttp3.OkHttpClient
+import okhttp3.Request
+import okhttp3.RequestBody.Companion.toRequestBody
+import java.io.ByteArrayOutputStream
+import java.util.concurrent.TimeUnit
+
+/**
+ * Cloud fallback recognizer: renders the SELECTED strokes (never a whole
+ * page, never a screenshot of the screen) to a small black-on-white PNG
+ * and asks the InkProof backend to transcribe it (Gemini multimodal).
+ *
+ * Only ever invoked by [HybridRecognizer] after on-device recognition came
+ * back uncertain, which itself only happens during an explicit user action
+ * (RECOGNIZE / CHECK MY WORK). No background calls, no secrets on-device.
+ */
+class BackendInkRecognizer(
+ private val baseUrl: String,
+ client: OkHttpClient? = null
+) : HandwritingRecognizer {
+
+ override val name: String = "backend-ink"
+
+ private val json = Json { ignoreUnknownKeys = true; coerceInputValues = true }
+
+ private val http: OkHttpClient = client ?: OkHttpClient.Builder()
+ .connectTimeout(15, TimeUnit.SECONDS)
+ .readTimeout(90, TimeUnit.SECONDS)
+ .build()
+
+ override suspend fun isAvailable(): Boolean = baseUrl.isNotBlank()
+
+ override suspend fun recognize(strokes: List): RecognitionResult =
+ withContext(Dispatchers.IO) {
+ if (strokes.isEmpty() || baseUrl.isBlank()) {
+ return@withContext RecognitionResult(emptyList(), 0f, uncertain = true)
+ }
+ runCatching {
+ val png = renderStrokes(strokes)
+ ?: return@withContext RecognitionResult(emptyList(), 0f, uncertain = true)
+ val payload = json.encodeToString(
+ RecognizeRequest.serializer(),
+ RecognizeRequest(
+ image_base64 = Base64.encodeToString(png, Base64.NO_WRAP),
+ mime = "image/png"
+ )
+ )
+ val request = Request.Builder()
+ .url(baseUrl.trimEnd('/') + "/api/recognize")
+ .post(payload.toRequestBody("application/json; charset=utf-8".toMediaType()))
+ .build()
+ http.newCall(request).execute().use { response ->
+ val text = response.body?.string().orEmpty()
+ if (!response.isSuccessful) {
+ return@use RecognitionResult(emptyList(), 0f, uncertain = true)
+ }
+ val parsed = json.decodeFromString(RecognizeResponse.serializer(), text)
+ if (parsed.status != "ok" || parsed.lines.isEmpty()) {
+ return@use RecognitionResult(emptyList(), 0f, uncertain = true)
+ }
+ RecognitionResult(
+ lines = parsed.lines.mapIndexed { i, l ->
+ RecognizedLine(
+ lineIndex = if (l.index >= 0) l.index else i,
+ text = MathNormalizer.normalize(l.text),
+ confidence = l.confidence.coerceIn(0f, 1f)
+ )
+ },
+ confidence = parsed.confidence.coerceIn(0f, 1f),
+ uncertain = parsed.uncertain
+ )
+ }
+ }.getOrElse { RecognitionResult(emptyList(), 0f, uncertain = true) }
+ }
+
+ /** Black ink on white, padded and scaled so the longest side is ~1024px. */
+ private fun renderStrokes(strokes: List): ByteArray? {
+ var minX = Float.MAX_VALUE; var minY = Float.MAX_VALUE
+ var maxX = -Float.MAX_VALUE; var maxY = -Float.MAX_VALUE
+ for (s in strokes) for (p in s.points) {
+ if (p.x < minX) minX = p.x
+ if (p.x > maxX) maxX = p.x
+ if (p.y < minY) minY = p.y
+ if (p.y > maxY) maxY = p.y
+ }
+ if (maxX <= minX || maxY <= minY) return null
+ val w = maxX - minX
+ val h = maxY - minY
+ val scale = (1024f / maxOf(w, h)).coerceIn(0.25f, 6f)
+ val pad = 24
+ val bw = (w * scale).toInt() + pad * 2
+ val bh = (h * scale).toInt() + pad * 2
+ if (bw <= 0 || bh <= 0 || bw > 4096 || bh > 4096) return null
+
+ val bitmap = Bitmap.createBitmap(bw, bh, Bitmap.Config.ARGB_8888)
+ val canvas = Canvas(bitmap)
+ canvas.drawColor(Color.WHITE)
+ val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
+ color = Color.BLACK
+ style = Paint.Style.STROKE
+ strokeCap = Paint.Cap.ROUND
+ strokeJoin = Paint.Join.ROUND
+ }
+ for (s in strokes) {
+ paint.strokeWidth = (s.baseWidth * scale).coerceIn(2f, 24f)
+ val path = Path()
+ s.points.forEachIndexed { i, p ->
+ val x = (p.x - minX) * scale + pad
+ val y = (p.y - minY) * scale + pad
+ if (i == 0) path.moveTo(x, y) else path.lineTo(x, y)
+ }
+ canvas.drawPath(path, paint)
+ }
+ val out = ByteArrayOutputStream()
+ bitmap.compress(Bitmap.CompressFormat.PNG, 100, out)
+ bitmap.recycle()
+ return out.toByteArray()
+ }
+
+ @Serializable
+ private data class RecognizeRequest(val image_base64: String, val mime: String)
+
+ @Serializable
+ private data class RecognizeResponse(
+ val status: String = "error",
+ val lines: List = emptyList(),
+ val confidence: Float = 0f,
+ val uncertain: Boolean = true
+ )
+
+ @Serializable
+ private data class RecognizeLine(
+ val index: Int = -1,
+ val text: String = "",
+ val confidence: Float = 0.8f
+ )
+}
+
+/**
+ * On-device first; cloud only as an explicit-action fallback.
+ *
+ * - If the local result is confident, the cloud is NEVER contacted.
+ * - If the local result is uncertain and a backend is configured, one
+ * cloud attempt is made; a confident cloud reading wins, otherwise the
+ * honest uncertain local result is returned (InkProof never guesses).
+ */
+class HybridRecognizer(
+ private val primary: HandwritingRecognizer,
+ private val fallback: HandwritingRecognizer?
+) : HandwritingRecognizer {
+
+ override val name: String =
+ "hybrid(${primary.name}+${fallback?.name ?: "none"})"
+
+ override suspend fun isAvailable(): Boolean =
+ primary.isAvailable() || fallback?.isAvailable() == true
+
+ override suspend fun recognize(strokes: List): RecognitionResult {
+ val local = runCatching { primary.recognize(strokes) }
+ .getOrElse { RecognitionResult(emptyList(), 0f, uncertain = true) }
+ if (!local.uncertain) return local
+ val cloud = fallback ?: return local
+ if (!cloud.isAvailable()) return local
+ val remote = runCatching { cloud.recognize(strokes) }.getOrNull() ?: return local
+ return if (!remote.uncertain && remote.lines.isNotEmpty()) remote else local
+ }
+}
diff --git a/app/src/main/java/com/inkproof/app/check/CheckProvider.kt b/app/src/main/java/com/inkproof/app/check/CheckProvider.kt
new file mode 100644
index 0000000..c1c3efe
--- /dev/null
+++ b/app/src/main/java/com/inkproof/app/check/CheckProvider.kt
@@ -0,0 +1,28 @@
+package com.inkproof.app.check
+
+import com.inkproof.app.model.CheckRequest
+import com.inkproof.app.model.CheckResponse
+
+/**
+ * Replaceable provider for CHECK MY WORK / SOLVE.
+ *
+ * Implementations:
+ * - [BackendCheckProvider]: calls the InkProof backend (which protects API
+ * keys, calls the AI + symbolic math engine, and returns validated JSON).
+ * - [MockCheckProvider]: deterministic offline provider for development.
+ */
+interface CheckProvider {
+ val name: String
+ suspend fun check(request: CheckRequest): CheckResponse
+ suspend fun solve(request: CheckRequest): CheckResponse
+}
+
+/**
+ * Replaceable symbolic math verification abstraction.
+ * The production implementation lives on the backend (e.g. WolframProvider);
+ * the client only ever sees its conclusions inside the structured response.
+ */
+interface MathVerificationProvider {
+ val name: String
+ suspend fun isEquivalent(expressionA: String, expressionB: String): Boolean?
+}
diff --git a/app/src/main/java/com/inkproof/app/check/CheckWorkEngine.kt b/app/src/main/java/com/inkproof/app/check/CheckWorkEngine.kt
new file mode 100644
index 0000000..1441b33
--- /dev/null
+++ b/app/src/main/java/com/inkproof/app/check/CheckWorkEngine.kt
@@ -0,0 +1,208 @@
+package com.inkproof.app.check
+
+import com.inkproof.app.data.repo.CheckRepository
+import com.inkproof.app.data.repo.PageRepository
+import com.inkproof.app.model.CheckAction
+import com.inkproof.app.model.CheckRequest
+import com.inkproof.app.model.CheckResponse
+import com.inkproof.app.model.CheckStatus
+import com.inkproof.app.model.Question
+import com.inkproof.app.model.QuestionContentType
+import com.inkproof.app.model.RecognizedLine
+import com.inkproof.app.model.Stroke
+import com.inkproof.app.model.newId
+
+/**
+ * Orchestrates CHECK MY WORK / SOLVE.
+ *
+ * Pipeline:
+ * Question object + solution strokes (ONLY that question's strokes)
+ * -> handwriting recognition (strokes, never screenshots)
+ * -> structured CheckRequest
+ * -> provider (backend or mock)
+ * -> validated structured CheckResponse
+ * -> cached by (question, contentVersion, solutionVersion, action)
+ *
+ * The Question object is the single source of truth for what the problem is.
+ * If the question is typed, it is passed through verbatim — never OCR'd.
+ * If handwriting can't be read confidently, the result is UNCLEAR; the
+ * engine never guesses.
+ */
+class CheckWorkEngine(
+ private val pageRepository: PageRepository,
+ private val checkRepository: CheckRepository,
+ private val recognizer: HandwritingRecognizer,
+ private val provider: CheckProvider,
+ /** Below this recognition confidence InkProof reports UNCLEAR. */
+ private val confidenceThreshold: Float = 0.4f
+) {
+
+ private fun tooUncertain(result: RecognitionResult): Boolean =
+ result.uncertain || result.lines.isEmpty() ||
+ result.confidence < confidenceThreshold
+
+ /** Check one specific question. Other questions/pages are never touched. */
+ suspend fun checkQuestion(questionId: String, action: CheckAction): CheckResponse {
+ val question = pageRepository.question(questionId)
+ ?: return CheckResponse(
+ status = CheckStatus.ERROR,
+ message = "This question no longer exists."
+ )
+
+ // Cache hit: same question content + same solution ink + same action.
+ checkRepository.cached(
+ question.id, question.contentVersion, question.solutionVersion, action
+ )?.let { return it }
+
+ val questionPart = resolveQuestionText(question)
+ if (questionPart == null) {
+ return CheckResponse(
+ status = CheckStatus.UNCLEAR,
+ summary = "I couldn't confidently read the question.",
+ message = "I couldn't confidently read the handwritten question. Type it or rewrite it, then try again."
+ )
+ }
+ val (questionText, questionSource, questionConfidence) = questionPart
+ if (questionText.isBlank()) {
+ return CheckResponse(
+ status = CheckStatus.ERROR,
+ message = "This question is empty. Add the problem before checking."
+ )
+ }
+
+ // ONLY this question's solution strokes — isolation by construction.
+ val solutionStrokes = pageRepository.solutionStrokes(question.id)
+ val solutionLines: List
+ if (action == CheckAction.CHECK) {
+ if (solutionStrokes.isEmpty()) {
+ return CheckResponse(
+ status = CheckStatus.INCOMPLETE,
+ questionEcho = questionText,
+ summary = "No solution yet.",
+ message = "Write your solution in the solution area first — InkProof checks YOUR work."
+ )
+ }
+ val recognition = recognizer.recognize(solutionStrokes)
+ if (tooUncertain(recognition)) {
+ return CheckResponse(
+ status = CheckStatus.UNCLEAR,
+ questionEcho = questionText,
+ summary = "I couldn't confidently read this work.",
+ message = "I couldn't confidently read the handwriting in your solution. InkProof won't guess — try writing a little larger, or check a lasso selection."
+ )
+ }
+ solutionLines = recognition.lines
+ } else {
+ solutionLines = emptyList()
+ }
+
+ val request = CheckRequest(
+ requestId = newId(),
+ action = if (action == CheckAction.CHECK) "check" else "solve",
+ questionId = question.id,
+ questionText = questionText,
+ questionSource = questionSource,
+ questionConfidence = questionConfidence,
+ solutionLines = solutionLines,
+ contentVersion = question.contentVersion,
+ solutionVersion = question.solutionVersion
+ )
+
+ val response = when (action) {
+ CheckAction.CHECK -> provider.check(request)
+ CheckAction.SOLVE -> provider.solve(request)
+ }
+
+ // Only cache meaningful outcomes; transient errors should retry.
+ if (response.status != CheckStatus.ERROR) {
+ checkRepository.store(
+ question.id, question.contentVersion, question.solutionVersion, action, response
+ )
+ }
+ return response
+ }
+
+ /**
+ * Check an explicit lasso selection (freeform pages).
+ * Priority: explicit selection > current question > never page-wide guessing.
+ */
+ suspend fun checkSelection(
+ pageId: String,
+ selectedStrokes: List,
+ action: CheckAction
+ ): CheckResponse {
+ if (selectedStrokes.isEmpty()) {
+ return CheckResponse(
+ status = CheckStatus.ERROR,
+ message = "Nothing is selected. Lasso the work you want to check."
+ )
+ }
+ // If the whole selection belongs to one question, use the question flow
+ // so its typed statement (source of truth) is used.
+ val questionIds = selectedStrokes.mapNotNull { it.questionId }.distinct()
+ if (questionIds.size == 1 && selectedStrokes.all { it.questionId == questionIds[0] }) {
+ return checkQuestion(questionIds[0], action)
+ }
+
+ val recognition = recognizer.recognize(selectedStrokes)
+ if (tooUncertain(recognition)) {
+ return CheckResponse(
+ status = CheckStatus.UNCLEAR,
+ summary = "I couldn't confidently read this selection.",
+ message = "I couldn't confidently read the selected handwriting. Select again or write more clearly — InkProof never guesses."
+ )
+ }
+ // Freeform: the first recognized line is treated as the problem
+ // statement and the rest as work, and this is shown transparently.
+ val questionText = recognition.lines.first().text
+ val work = recognition.lines.drop(1)
+ val request = CheckRequest(
+ requestId = newId(),
+ action = if (action == CheckAction.CHECK) "check" else "solve",
+ questionId = "selection:$pageId",
+ questionText = questionText,
+ questionSource = "handwritten-selection",
+ questionConfidence = recognition.confidence,
+ solutionLines = work,
+ contentVersion = 0,
+ solutionVersion = 0
+ )
+ return when (action) {
+ CheckAction.CHECK -> provider.check(request)
+ CheckAction.SOLVE -> provider.solve(request)
+ }
+ }
+
+ /**
+ * Resolve the question statement.
+ * - typed/pasted text is used verbatim (never OCR'd)
+ * - handwritten questions are recognized from ONLY the question strokes
+ * - unreadable handwriting -> null (caller reports UNCLEAR; no guessing)
+ */
+ private suspend fun resolveQuestionText(question: Question): Triple? {
+ return when (question.contentType) {
+ QuestionContentType.TYPED, QuestionContentType.PASTED ->
+ Triple(question.typedText.orEmpty(), "typed", 1f)
+
+ QuestionContentType.IMAGE, QuestionContentType.PDF ->
+ // The media itself is the source; typed caption may accompany it.
+ Triple(
+ question.typedText ?: "(imported ${question.contentType.name.lowercase()} question)",
+ question.contentType.name.lowercase(),
+ 1f
+ )
+
+ QuestionContentType.HANDWRITTEN -> {
+ val strokes = pageRepository.questionStrokes(question.id)
+ if (strokes.isEmpty()) return Triple("", "handwritten", 0f)
+ val recognition = recognizer.recognize(strokes)
+ if (tooUncertain(recognition)) return null
+ Triple(
+ recognition.lines.joinToString(" ") { it.text },
+ "handwritten",
+ recognition.confidence
+ )
+ }
+ }
+ }
+}
diff --git a/app/src/main/java/com/inkproof/app/check/HandwritingRecognizer.kt b/app/src/main/java/com/inkproof/app/check/HandwritingRecognizer.kt
new file mode 100644
index 0000000..dfdabaa
--- /dev/null
+++ b/app/src/main/java/com/inkproof/app/check/HandwritingRecognizer.kt
@@ -0,0 +1,64 @@
+package com.inkproof.app.check
+
+import com.inkproof.app.model.RecognizedLine
+import com.inkproof.app.model.Stroke
+
+/** Result of recognizing a set of ink strokes. */
+data class RecognitionResult(
+ val lines: List,
+ /** Overall confidence 0..1. */
+ val confidence: Float,
+ /** True when the recognizer could not produce a confident reading. */
+ val uncertain: Boolean = false
+)
+
+/**
+ * Replaceable handwriting recognition abstraction.
+ *
+ * Implementations receive ONLY the strokes of the region being recognized
+ * (one question's solution, one question's handwritten statement, or one
+ * lasso selection) — never a whole page and never a screenshot.
+ */
+interface HandwritingRecognizer {
+ /** Human-readable implementation name, e.g. "local-digital-ink". */
+ val name: String
+
+ suspend fun isAvailable(): Boolean
+
+ /**
+ * Recognize math handwriting from raw strokes. Strokes keep original
+ * order, coordinates, pressure and timestamps.
+ */
+ suspend fun recognize(strokes: List): RecognitionResult
+}
+
+/**
+ * Groups strokes into visual lines by vertical position, so recognition and
+ * step-checking can work line by line (step by step).
+ */
+object LineSegmenter {
+ fun segment(strokes: List): List> {
+ if (strokes.isEmpty()) return emptyList()
+ val sorted = strokes.sortedBy { it.bounds().centerY }
+ val heights = sorted.map { it.bounds().height }.sorted()
+ val medianHeight = heights[heights.size / 2].coerceAtLeast(8f)
+ val gapThreshold = medianHeight * 0.9f
+
+ val lines = ArrayList>()
+ var current = mutableListOf(sorted.first())
+ var currentBottom = sorted.first().bounds().bottom
+ for (s in sorted.drop(1)) {
+ val b = s.bounds()
+ if (b.top > currentBottom + gapThreshold) {
+ lines.add(current)
+ current = mutableListOf(s)
+ } else {
+ current.add(s)
+ }
+ currentBottom = maxOf(currentBottom, b.bottom)
+ }
+ lines.add(current)
+ // Within a line, order strokes left-to-right by writing position.
+ return lines.map { line -> line.sortedBy { it.bounds().left } }
+ }
+}
diff --git a/app/src/main/java/com/inkproof/app/check/LocalDigitalInkRecognizer.kt b/app/src/main/java/com/inkproof/app/check/LocalDigitalInkRecognizer.kt
new file mode 100644
index 0000000..a600249
--- /dev/null
+++ b/app/src/main/java/com/inkproof/app/check/LocalDigitalInkRecognizer.kt
@@ -0,0 +1,137 @@
+package com.inkproof.app.check
+
+import com.google.android.gms.tasks.Tasks
+import com.google.mlkit.common.model.DownloadConditions
+import com.google.mlkit.common.model.RemoteModelManager
+import com.google.mlkit.vision.digitalink.DigitalInkRecognition
+import com.google.mlkit.vision.digitalink.DigitalInkRecognitionModel
+import com.google.mlkit.vision.digitalink.DigitalInkRecognitionModelIdentifier
+import com.google.mlkit.vision.digitalink.DigitalInkRecognizerOptions
+import com.google.mlkit.vision.digitalink.Ink
+import com.google.mlkit.vision.digitalink.RecognitionContext
+import com.google.mlkit.vision.digitalink.WritingArea
+import com.inkproof.app.model.RecognizedLine
+import com.inkproof.app.model.Stroke
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.withContext
+
+/**
+ * On-device digital ink recognition (ML Kit).
+ *
+ * Works from the actual stroke data — order, coordinates and timestamps —
+ * not from screenshots.
+ *
+ * Accuracy levers used (per ML Kit guidance):
+ * - the model download is ENSURED inside [recognize] — previously a
+ * missing model made perfectly neat handwriting come back "unclear";
+ * - every line is recognized with a [RecognitionContext] carrying the
+ * line's [WritingArea] and the previously recognized lines as
+ * pre-context;
+ * - raw candidates are post-processed by [MathNormalizer] (x2 -> x^2,
+ * unicode minus/superscripts, etc.) — normalization only, no guessing.
+ *
+ * If the model is unavailable or confidence is too low, the result is marked
+ * uncertain — InkProof NEVER guesses at unreadable handwriting.
+ */
+class LocalDigitalInkRecognizer : HandwritingRecognizer {
+
+ override val name: String = "local-digital-ink"
+
+ /**
+ * ML Kit digital ink ships language/text models (no dedicated public math
+ * model), so en-US is used on-device for basic equation text. A cloud
+ * math-specific recognizer can be swapped in behind [HandwritingRecognizer]
+ * without touching callers.
+ */
+ private fun modelIdentifier(): DigitalInkRecognitionModelIdentifier? =
+ runCatching {
+ DigitalInkRecognitionModelIdentifier.fromLanguageTag("en-US")
+ }.getOrNull()
+
+ private fun ensureModel(id: DigitalInkRecognitionModelIdentifier): DigitalInkRecognitionModel? =
+ runCatching {
+ val model = DigitalInkRecognitionModel.builder(id).build()
+ val manager = RemoteModelManager.getInstance()
+ if (!Tasks.await(manager.isModelDownloaded(model))) {
+ Tasks.await(
+ manager.download(model, DownloadConditions.Builder().build())
+ )
+ }
+ model
+ }.getOrNull()
+
+ override suspend fun isAvailable(): Boolean = withContext(Dispatchers.IO) {
+ val id = modelIdentifier() ?: return@withContext false
+ ensureModel(id) != null
+ }
+
+ override suspend fun recognize(strokes: List): RecognitionResult =
+ withContext(Dispatchers.IO) {
+ if (strokes.isEmpty()) {
+ return@withContext RecognitionResult(emptyList(), 0f, uncertain = true)
+ }
+ val id = modelIdentifier()
+ ?: return@withContext RecognitionResult(emptyList(), 0f, uncertain = true)
+ // The model MUST be present before recognizing; otherwise neat
+ // handwriting is wrongly reported as unreadable.
+ val model = ensureModel(id)
+ ?: return@withContext RecognitionResult(emptyList(), 0f, uncertain = true)
+ runCatching {
+ val recognizer = DigitalInkRecognition.getClient(
+ DigitalInkRecognizerOptions.builder(model).build()
+ )
+ val lines = LineSegmenter.segment(strokes)
+ val recognized = ArrayList()
+ var totalConfidence = 0f
+ var preContext = ""
+ lines.forEachIndexed { index, lineStrokes ->
+ val inkBuilder = Ink.builder()
+ var minX = Float.MAX_VALUE
+ var maxX = -Float.MAX_VALUE
+ var minY = Float.MAX_VALUE
+ var maxY = -Float.MAX_VALUE
+ for (s in lineStrokes) {
+ val sb = Ink.Stroke.builder()
+ for (p in s.points) {
+ sb.addPoint(Ink.Point.create(p.x, p.y, s.createdAt + p.t))
+ if (p.x < minX) minX = p.x
+ if (p.x > maxX) maxX = p.x
+ if (p.y < minY) minY = p.y
+ if (p.y > maxY) maxY = p.y
+ }
+ inkBuilder.addStroke(sb.build())
+ }
+ // WritingArea + preContext materially improve accuracy
+ // (documented ML Kit recognition-context levers).
+ val context = RecognitionContext.builder()
+ .setWritingArea(
+ WritingArea(
+ (maxX - minX).coerceAtLeast(1f),
+ (maxY - minY).coerceAtLeast(1f)
+ )
+ )
+ .setPreContext(preContext.takeLast(20))
+ .build()
+ val result =
+ Tasks.await(recognizer.recognize(inkBuilder.build(), context))
+ val best = result.candidates.firstOrNull()
+ val text = MathNormalizer.normalize(best?.text?.trim().orEmpty())
+ // ML Kit score: lower is better when present; map defensively.
+ val conf = if (text.isBlank()) 0f else 0.85f
+ totalConfidence += conf
+ if (text.isNotBlank()) {
+ recognized.add(RecognizedLine(index, text, conf))
+ preContext = text
+ }
+ }
+ val avg = if (lines.isEmpty()) 0f else totalConfidence / lines.size
+ RecognitionResult(
+ lines = recognized,
+ confidence = avg,
+ uncertain = recognized.isEmpty() || avg < 0.4f
+ )
+ }.getOrElse {
+ RecognitionResult(emptyList(), 0f, uncertain = true)
+ }
+ }
+}
diff --git a/app/src/main/java/com/inkproof/app/check/MathNormalizer.kt b/app/src/main/java/com/inkproof/app/check/MathNormalizer.kt
new file mode 100644
index 0000000..88602be
--- /dev/null
+++ b/app/src/main/java/com/inkproof/app/check/MathNormalizer.kt
@@ -0,0 +1,68 @@
+package com.inkproof.app.check
+
+/**
+ * Conservative post-processing for recognized math text.
+ *
+ * The on-device model is a general TEXT model, so common math notation
+ * comes back slightly mangled ("x2" for x², unicode minus signs, stray
+ * spacing). These rules only normalize UNAMBIGUOUS cases — they never
+ * guess at what the student "probably meant". Anything ambiguous is left
+ * exactly as recognized so the user can correct it in the preview.
+ */
+object MathNormalizer {
+
+ // A single letter followed by digits, where the letter is NOT part of a
+ // word (so "x2" -> "x^2" and "3x2" -> "3x^2", but "sin2x" is untouched).
+ private val IMPLICIT_POWER = Regex("(? ASCII minus.
+ s = s.replace('\u2212', '-') // −
+ .replace('\u2013', '-') // –
+ .replace('\u2014', '-') // —
+
+ // Unicode superscripts -> caret notation.
+ s = s.replace("\u00B2", "^2")
+ .replace("\u00B3", "^3")
+ .replace("\u00B9", "^1")
+ .replace("\u2070", "^0")
+ .replace("\u2074", "^4")
+ .replace("\u2075", "^5")
+ .replace("\u2076", "^6")
+ .replace("\u2077", "^7")
+ .replace("\u2078", "^8")
+ .replace("\u2079", "^9")
+
+ // Arrow variants -> ASCII (keeps "lim x->0" machine-friendly).
+ s = s.replace("\u2192", "->")
+
+ // Multiplication look-alikes.
+ s = s.replace('\u00D7', '*') // ×
+ .replace('\u22C5', '*') // ⋅
+ .replace('\u2219', '*') // ∙
+
+ // O/o used as zero between digits (e.g. "1O" -> "10").
+ s = O_AFTER_DIGIT.replace(s, "0")
+ s = O_BEFORE_DIGIT.replace(s, "0")
+
+ // Implicit exponent: standalone letter followed by digits is a
+ // power in handwritten math ("x2-5x+6" -> "x^2-5x+6"). Skipped
+ // when the letter ends a word (sin2x, log2 stay untouched).
+ s = IMPLICIT_POWER.replace(s) { m ->
+ "${m.groupValues[1]}^${m.groupValues[2]}"
+ }
+
+ // Tidy spacing: collapse runs, remove spaces around ^.
+ s = s.replace(Regex("\\s*\\^\\s*"), "^")
+ s = s.replace(Regex("\\s+"), " ").trim()
+
+ return s
+ }
+}
diff --git a/app/src/main/java/com/inkproof/app/check/MockCheckProvider.kt b/app/src/main/java/com/inkproof/app/check/MockCheckProvider.kt
new file mode 100644
index 0000000..ac144c6
--- /dev/null
+++ b/app/src/main/java/com/inkproof/app/check/MockCheckProvider.kt
@@ -0,0 +1,164 @@
+package com.inkproof.app.check
+
+import com.inkproof.app.model.CheckRequest
+import com.inkproof.app.model.CheckResponse
+import com.inkproof.app.model.CheckStatus
+import com.inkproof.app.model.CheckStep
+import com.inkproof.app.model.StepStatus
+import kotlinx.coroutines.delay
+
+/**
+ * Deterministic development provider so the full CHECK MY WORK UX can be
+ * exercised with no API credentials.
+ *
+ * Isolation rules:
+ * - It only ever uses the question/solution INSIDE the request it receives.
+ * No hardcoded demo question is ever substituted for the user's problem.
+ * - The scenario is selected from the request content, so the same input
+ * always produces the same output (good for tests).
+ */
+class MockCheckProvider(
+ private val simulatedLatencyMs: Long = 600
+) : CheckProvider {
+
+ override val name: String = "mock"
+
+ override suspend fun check(request: CheckRequest): CheckResponse {
+ delay(simulatedLatencyMs)
+
+ if (request.questionText.isBlank()) {
+ return CheckResponse(
+ status = CheckStatus.ERROR,
+ message = "This question has no content yet. Add the problem before checking."
+ )
+ }
+ if (request.solutionLines.isEmpty()) {
+ return CheckResponse(
+ status = CheckStatus.INCOMPLETE,
+ confidence = 1f,
+ questionEcho = request.questionText,
+ summary = "No solution steps found.",
+ message = "Write your solution in the solution area, then check again.",
+ verifiedBy = "mock"
+ )
+ }
+
+ // Deterministic scenario from the actual submitted content.
+ val scenario = scenarioFor(request)
+ val steps = request.solutionLines.mapIndexed { i, line ->
+ CheckStep(
+ stepId = "step_${i + 1}",
+ status = StepStatus.CORRECT,
+ expression = line.text,
+ explanation = "This step follows from the previous line."
+ )
+ }
+
+ return when (scenario) {
+ Scenario.CORRECT -> CheckResponse(
+ status = CheckStatus.CORRECT,
+ confidence = 0.97f,
+ questionEcho = request.questionText,
+ steps = steps,
+ summary = "Every step checks out. Nicely done.",
+ finalAnswer = steps.lastOrNull()?.expression,
+ verifiedBy = "mock"
+ )
+
+ Scenario.INCORRECT -> {
+ val errorIndex = (steps.size / 2).coerceAtLeast(if (steps.size > 1) 1 else 0)
+ val marked = steps.mapIndexed { i, s ->
+ when {
+ i < errorIndex -> s
+ i == errorIndex -> s.copy(
+ status = StepStatus.INCORRECT,
+ explanation = "The operation applied here does not preserve equality. Re-check the arithmetic on both sides.",
+ hint = "Compare this line carefully with the one above it."
+ )
+ else -> s.copy(
+ status = StepStatus.DEPENDENT_ON_PREVIOUS_ERROR,
+ explanation = "This step builds on the earlier mistake, so it can't be marked correct on its own."
+ )
+ }
+ }
+ CheckResponse(
+ status = CheckStatus.INCORRECT,
+ confidence = 0.95f,
+ questionEcho = request.questionText,
+ firstErrorStep = "step_${errorIndex + 1}",
+ steps = marked,
+ hints = listOf(
+ "Look at what changed between step $errorIndex and step ${errorIndex + 1}.",
+ "One side of the equation was changed without applying the same change to the other side.",
+ "Undo the operation in step ${errorIndex + 1} and redo it on both sides."
+ ),
+ summary = "First mistake found at step ${errorIndex + 1}.",
+ fullSolution = "Mock full solution: rework from step ${errorIndex + 1} applying each operation to both sides.",
+ verifiedBy = "mock"
+ )
+ }
+
+ Scenario.INCOMPLETE -> CheckResponse(
+ status = CheckStatus.INCOMPLETE,
+ confidence = 0.9f,
+ questionEcho = request.questionText,
+ steps = steps,
+ summary = "The work so far is fine, but the problem isn't finished.",
+ hints = listOf("You've set things up correctly — keep going to isolate the unknown."),
+ verifiedBy = "mock"
+ )
+
+ Scenario.UNCLEAR -> CheckResponse(
+ status = CheckStatus.UNCLEAR,
+ confidence = 0.3f,
+ questionEcho = request.questionText,
+ summary = "I couldn't confidently read this step.",
+ message = "I couldn't confidently read part of the handwriting. You can edit the transcription or select the work again — InkProof never guesses.",
+ verifiedBy = "mock"
+ )
+ }
+ }
+
+ override suspend fun solve(request: CheckRequest): CheckResponse {
+ delay(simulatedLatencyMs)
+ if (request.questionText.isBlank()) {
+ return CheckResponse(
+ status = CheckStatus.ERROR,
+ message = "This question has no content yet. Add the problem before solving."
+ )
+ }
+ return CheckResponse(
+ status = CheckStatus.CORRECT,
+ confidence = 0.9f,
+ questionEcho = request.questionText,
+ summary = "Mock worked solution for: ${request.questionText}",
+ fullSolution = "Mock mode: a fully worked solution for \"${request.questionText}\" would appear here, step by step.",
+ finalAnswer = "mock answer",
+ verifiedBy = "mock"
+ )
+ }
+
+ private enum class Scenario { CORRECT, INCORRECT, INCOMPLETE, UNCLEAR }
+
+ private fun scenarioFor(request: CheckRequest): Scenario {
+ val q = request.questionText.lowercase()
+ // Explicit test keywords first (used by automated tests + demos).
+ return when {
+ "mock:correct" in q -> Scenario.CORRECT
+ "mock:incorrect" in q -> Scenario.INCORRECT
+ "mock:incomplete" in q -> Scenario.INCOMPLETE
+ "mock:unclear" in q -> Scenario.UNCLEAR
+ else -> {
+ // Stable pseudo-random pick based on content hash.
+ val h = (request.questionText.hashCode() xor
+ request.solutionLines.size.hashCode()) and 0x7fffffff
+ when (h % 4) {
+ 0 -> Scenario.CORRECT
+ 1 -> Scenario.INCORRECT
+ 2 -> Scenario.INCOMPLETE
+ else -> Scenario.UNCLEAR
+ }
+ }
+ }
+ }
+}
diff --git a/app/src/main/java/com/inkproof/app/check/MockRecognizer.kt b/app/src/main/java/com/inkproof/app/check/MockRecognizer.kt
new file mode 100644
index 0000000..595933c
--- /dev/null
+++ b/app/src/main/java/com/inkproof/app/check/MockRecognizer.kt
@@ -0,0 +1,27 @@
+package com.inkproof.app.check
+
+import com.inkproof.app.model.RecognizedLine
+import com.inkproof.app.model.Stroke
+
+/**
+ * Development-only recognizer. It does NOT invent mathematics: it reports
+ * each detected handwriting line as unrecognized placeholder text with the
+ * stroke counts, so mock flows exercise the UI without pretending to read ink.
+ *
+ * Mock data is isolated: this class is only wired up when mock mode is on.
+ */
+class MockRecognizer : HandwritingRecognizer {
+
+ override val name: String = "mock-recognizer"
+
+ override suspend fun isAvailable(): Boolean = true
+
+ override suspend fun recognize(strokes: List): RecognitionResult {
+ if (strokes.isEmpty()) return RecognitionResult(emptyList(), 0f, uncertain = true)
+ val lines = LineSegmenter.segment(strokes)
+ val recognized = lines.mapIndexed { index, line ->
+ RecognizedLine(index, "[handwritten line ${index + 1}: ${line.size} strokes]", 0.99f)
+ }
+ return RecognitionResult(recognized, 0.99f, uncertain = false)
+ }
+}
diff --git a/app/src/main/java/com/inkproof/app/data/db/Daos.kt b/app/src/main/java/com/inkproof/app/data/db/Daos.kt
new file mode 100644
index 0000000..05da886
--- /dev/null
+++ b/app/src/main/java/com/inkproof/app/data/db/Daos.kt
@@ -0,0 +1,226 @@
+package com.inkproof.app.data.db
+
+import androidx.room.Dao
+import androidx.room.Delete
+import androidx.room.Insert
+import androidx.room.OnConflictStrategy
+import androidx.room.Query
+import androidx.room.Transaction
+import androidx.room.Update
+import kotlinx.coroutines.flow.Flow
+
+@Dao
+interface FolderDao {
+ @Insert(onConflict = OnConflictStrategy.REPLACE)
+ suspend fun upsert(folder: FolderEntity)
+
+ @Query("SELECT * FROM folders ORDER BY name COLLATE NOCASE")
+ fun observeAll(): Flow>
+
+ @Query("SELECT * FROM folders WHERE id = :id")
+ suspend fun byId(id: String): FolderEntity?
+
+ @Query("DELETE FROM folders WHERE id = :id")
+ suspend fun delete(id: String)
+}
+
+@Dao
+interface NotebookDao {
+ @Insert(onConflict = OnConflictStrategy.REPLACE)
+ suspend fun upsert(notebook: NotebookEntity)
+
+ @Query("SELECT * FROM notebooks ORDER BY updatedAt DESC")
+ fun observeAll(): Flow>
+
+ @Query("SELECT * FROM notebooks WHERE folderId = :folderId ORDER BY updatedAt DESC")
+ fun observeInFolder(folderId: String): Flow>
+
+ @Query("SELECT * FROM notebooks WHERE id = :id")
+ suspend fun byId(id: String): NotebookEntity?
+
+ @Query("UPDATE notebooks SET title = :title, updatedAt = :now WHERE id = :id")
+ suspend fun rename(id: String, title: String, now: Long)
+
+ @Query("UPDATE notebooks SET favorite = :favorite WHERE id = :id")
+ suspend fun setFavorite(id: String, favorite: Boolean)
+
+ @Query("UPDATE notebooks SET folderId = :folderId, updatedAt = :now WHERE id = :id")
+ suspend fun moveToFolder(id: String, folderId: String?, now: Long)
+
+ @Query("UPDATE notebooks SET folderId = NULL WHERE folderId = :folderId")
+ suspend fun clearFolder(folderId: String)
+
+ @Query("UPDATE notebooks SET updatedAt = :now WHERE id = :id")
+ suspend fun touch(id: String, now: Long)
+
+ @Query("DELETE FROM notebooks WHERE id = :id")
+ suspend fun delete(id: String)
+
+ @Query("SELECT * FROM notebooks WHERE title LIKE '%' || :query || '%' ORDER BY updatedAt DESC")
+ suspend fun search(query: String): List
+}
+
+@Dao
+interface PageDao {
+ @Insert(onConflict = OnConflictStrategy.REPLACE)
+ suspend fun upsert(page: PageEntity)
+
+ @Query("SELECT * FROM pages WHERE notebookId = :notebookId ORDER BY orderIndex")
+ fun observePages(notebookId: String): Flow>
+
+ @Query("SELECT * FROM pages WHERE notebookId = :notebookId ORDER BY orderIndex")
+ suspend fun pagesFor(notebookId: String): List
+
+ @Query("SELECT * FROM pages WHERE id = :id")
+ suspend fun byId(id: String): PageEntity?
+
+ @Query("DELETE FROM pages WHERE id = :id")
+ suspend fun delete(id: String)
+
+ @Query("UPDATE pages SET orderIndex = :orderIndex WHERE id = :id")
+ suspend fun setOrder(id: String, orderIndex: Int)
+
+ @Query("UPDATE pages SET template = :template, updatedAt = :now WHERE id = :id")
+ suspend fun setTemplate(id: String, template: String, now: Long)
+
+ @Query("SELECT COUNT(*) FROM pages WHERE notebookId = :notebookId")
+ suspend fun countFor(notebookId: String): Int
+}
+
+@Dao
+interface QuestionDao {
+ @Insert(onConflict = OnConflictStrategy.REPLACE)
+ suspend fun upsert(question: QuestionEntity)
+
+ @Query("SELECT * FROM questions WHERE pageId = :pageId ORDER BY orderIndex")
+ fun observeForPage(pageId: String): Flow>
+
+ @Query("SELECT * FROM questions WHERE pageId = :pageId ORDER BY orderIndex")
+ suspend fun forPage(pageId: String): List
+
+ @Query("SELECT * FROM questions WHERE id = :id")
+ suspend fun byId(id: String): QuestionEntity?
+
+ @Query("DELETE FROM questions WHERE id = :id")
+ suspend fun delete(id: String)
+
+ @Query("UPDATE questions SET solutionVersion = solutionVersion + 1 WHERE id = :id")
+ suspend fun bumpSolutionVersion(id: String)
+
+ @Query("UPDATE questions SET contentVersion = contentVersion + 1 WHERE id = :id")
+ suspend fun bumpContentVersion(id: String)
+
+ @Query("UPDATE questions SET typedText = :text, contentVersion = contentVersion + 1 WHERE id = :id")
+ suspend fun updateTypedText(id: String, text: String)
+
+ @Query("SELECT * FROM questions WHERE typedText LIKE '%' || :query || '%'")
+ suspend fun search(query: String): List
+}
+
+@Dao
+interface StrokeDao {
+ @Insert(onConflict = OnConflictStrategy.REPLACE)
+ suspend fun upsert(stroke: StrokeEntity)
+
+ @Insert(onConflict = OnConflictStrategy.REPLACE)
+ suspend fun upsertAll(strokes: List)
+
+ @Query("SELECT * FROM strokes WHERE pageId = :pageId ORDER BY createdAt")
+ suspend fun forPage(pageId: String): List
+
+ @Query("SELECT * FROM strokes WHERE questionId = :questionId AND role = :role ORDER BY createdAt")
+ suspend fun forQuestionRole(questionId: String, role: String): List
+
+ @Query("DELETE FROM strokes WHERE id = :id")
+ suspend fun delete(id: String)
+
+ @Query("DELETE FROM strokes WHERE id IN (:ids)")
+ suspend fun deleteAll(ids: List)
+
+ @Query("DELETE FROM strokes WHERE pageId = :pageId")
+ suspend fun deleteForPage(pageId: String)
+
+ @Query("SELECT COUNT(*) FROM strokes WHERE pageId = :pageId")
+ suspend fun countForPage(pageId: String): Int
+}
+
+@Dao
+interface TextObjectDao {
+ @Insert(onConflict = OnConflictStrategy.REPLACE)
+ suspend fun upsert(obj: TextObjectEntity)
+
+ @Query("SELECT * FROM text_objects WHERE pageId = :pageId")
+ suspend fun forPage(pageId: String): List
+
+ @Query("DELETE FROM text_objects WHERE id = :id")
+ suspend fun delete(id: String)
+}
+
+@Dao
+interface ImageObjectDao {
+ @Insert(onConflict = OnConflictStrategy.REPLACE)
+ suspend fun upsert(obj: ImageObjectEntity)
+
+ @Query("SELECT * FROM image_objects WHERE pageId = :pageId")
+ suspend fun forPage(pageId: String): List
+
+ @Query("DELETE FROM image_objects WHERE id = :id")
+ suspend fun delete(id: String)
+}
+
+@Dao
+interface CheckResultDao {
+ @Insert(onConflict = OnConflictStrategy.REPLACE)
+ suspend fun upsert(result: CheckResultEntity)
+
+ @Query(
+ "SELECT * FROM check_results WHERE questionId = :questionId AND contentVersion = :contentVersion " +
+ "AND solutionVersion = :solutionVersion AND action = :action LIMIT 1"
+ )
+ suspend fun find(
+ questionId: String,
+ contentVersion: Long,
+ solutionVersion: Long,
+ action: String
+ ): CheckResultEntity?
+
+ @Query("SELECT * FROM check_results WHERE questionId = :questionId ORDER BY createdAt DESC")
+ suspend fun historyFor(questionId: String): List
+
+ @Query("DELETE FROM check_results WHERE questionId = :questionId")
+ suspend fun clearFor(questionId: String)
+
+ @Query("DELETE FROM check_results")
+ suspend fun clearAll()
+}
+
+@Dao
+interface MaintenanceDao {
+ @Transaction
+ @Query("DELETE FROM strokes WHERE pageId IN (SELECT id FROM pages WHERE notebookId = :notebookId)")
+ suspend fun deleteStrokesForNotebook(notebookId: String)
+
+ @Query("DELETE FROM questions WHERE pageId IN (SELECT id FROM pages WHERE notebookId = :notebookId)")
+ suspend fun deleteQuestionsForNotebook(notebookId: String)
+
+ @Query("DELETE FROM pages WHERE notebookId = :notebookId")
+ suspend fun deletePagesForNotebook(notebookId: String)
+
+ @Query("DELETE FROM strokes WHERE pageId = :pageId")
+ suspend fun deleteStrokesForPage(pageId: String)
+
+ @Query("DELETE FROM questions WHERE pageId = :pageId")
+ suspend fun deleteQuestionsForPage(pageId: String)
+
+ @Query("DELETE FROM text_objects WHERE pageId = :pageId")
+ suspend fun deleteTextForPage(pageId: String)
+
+ @Query("DELETE FROM text_objects WHERE pageId IN (SELECT id FROM pages WHERE notebookId = :notebookId)")
+ suspend fun deleteTextForNotebook(notebookId: String)
+
+ @Query("DELETE FROM image_objects WHERE pageId = :pageId")
+ suspend fun deleteImagesForPage(pageId: String)
+
+ @Query("DELETE FROM image_objects WHERE pageId IN (SELECT id FROM pages WHERE notebookId = :notebookId)")
+ suspend fun deleteImagesForNotebook(notebookId: String)
+}
diff --git a/app/src/main/java/com/inkproof/app/data/db/Entities.kt b/app/src/main/java/com/inkproof/app/data/db/Entities.kt
new file mode 100644
index 0000000..4dbb5e2
--- /dev/null
+++ b/app/src/main/java/com/inkproof/app/data/db/Entities.kt
@@ -0,0 +1,151 @@
+package com.inkproof.app.data.db
+
+import androidx.room.ColumnInfo
+import androidx.room.Entity
+import androidx.room.Index
+import androidx.room.PrimaryKey
+
+@Entity(tableName = "folders")
+data class FolderEntity(
+ @PrimaryKey val id: String,
+ val name: String,
+ val parentId: String? = null,
+ val createdAt: Long,
+ val updatedAt: Long
+)
+
+@Entity(
+ tableName = "notebooks",
+ indices = [Index("folderId")]
+)
+data class NotebookEntity(
+ @PrimaryKey val id: String,
+ val folderId: String? = null,
+ val title: String,
+ val coverColor: Int,
+ val favorite: Boolean = false,
+ val createdAt: Long,
+ val updatedAt: Long
+)
+
+@Entity(
+ tableName = "pages",
+ indices = [Index("notebookId")]
+)
+data class PageEntity(
+ @PrimaryKey val id: String,
+ val notebookId: String,
+ val orderIndex: Int,
+ /** PageKind name: NOTE, MATH_QUESTION, PDF. */
+ val kind: String,
+ /** PageTemplate name. */
+ val template: String,
+ /** Paper background color (ARGB). Independent of template and app theme. */
+ val paperColor: Int = -197640, // PaperColors.WHITE
+ val widthPts: Float = 1600f,
+ val heightPts: Float = 2200f,
+ /** For PDF pages: path of the rendered source page. */
+ val pdfPath: String? = null,
+ val pdfPageIndex: Int = 0,
+ val createdAt: Long,
+ val updatedAt: Long
+)
+
+@Entity(
+ tableName = "questions",
+ indices = [Index("pageId")]
+)
+data class QuestionEntity(
+ @PrimaryKey val id: String,
+ val pageId: String,
+ val orderIndex: Int,
+ val contentType: String,
+ val typedText: String? = null,
+ val mediaPath: String? = null,
+ val questionTop: Float,
+ val questionBottom: Float,
+ val solutionTop: Float,
+ val solutionBottom: Float,
+ val contentVersion: Long,
+ val solutionVersion: Long,
+ val createdAt: Long
+)
+
+@Entity(
+ tableName = "strokes",
+ indices = [Index("pageId"), Index("questionId")]
+)
+data class StrokeEntity(
+ @PrimaryKey val id: String,
+ val pageId: String,
+ val questionId: String? = null,
+ /** StrokeRole name. */
+ val role: String,
+ /** ToolType name. */
+ val tool: String,
+ val color: Int,
+ val baseWidth: Float,
+ /** ShapeType name when the stroke is a snapped shape. */
+ val shapeType: String? = null,
+ /** Packed point data; see [StrokeCodec]. */
+ @ColumnInfo(typeAffinity = ColumnInfo.BLOB) val points: ByteArray,
+ val createdAt: Long
+) {
+ override fun equals(other: Any?): Boolean =
+ other is StrokeEntity && other.id == id
+
+ override fun hashCode(): Int = id.hashCode()
+}
+
+@Entity(
+ tableName = "text_objects",
+ indices = [Index("pageId")]
+)
+data class TextObjectEntity(
+ @PrimaryKey val id: String,
+ val pageId: String,
+ val questionId: String? = null,
+ val text: String,
+ val x: Float,
+ val y: Float,
+ val widthPts: Float,
+ val fontSize: Float,
+ val color: Int,
+ val createdAt: Long
+)
+
+@Entity(
+ tableName = "image_objects",
+ indices = [Index("pageId")]
+)
+data class ImageObjectEntity(
+ @PrimaryKey val id: String,
+ val pageId: String,
+ val questionId: String? = null,
+ val path: String,
+ val x: Float,
+ val y: Float,
+ val widthPts: Float,
+ val heightPts: Float,
+ val createdAt: Long
+)
+
+/**
+ * Cached CHECK/SOLVE results, keyed by question + versions + action so that
+ * editing the solution invalidates older results automatically.
+ */
+@Entity(
+ tableName = "check_results",
+ indices = [Index(value = ["questionId", "contentVersion", "solutionVersion", "action"], unique = true)]
+)
+data class CheckResultEntity(
+ @PrimaryKey val id: String,
+ val questionId: String,
+ val contentVersion: Long,
+ val solutionVersion: Long,
+ /** CheckAction name. */
+ val action: String,
+ /** Raw structured JSON of the CheckResponse. */
+ val resultJson: String,
+ val createdAt: Long
+)
diff --git a/app/src/main/java/com/inkproof/app/data/db/InkProofDatabase.kt b/app/src/main/java/com/inkproof/app/data/db/InkProofDatabase.kt
new file mode 100644
index 0000000..147eaa4
--- /dev/null
+++ b/app/src/main/java/com/inkproof/app/data/db/InkProofDatabase.kt
@@ -0,0 +1,63 @@
+package com.inkproof.app.data.db
+
+import android.content.Context
+import androidx.room.Database
+import androidx.room.Room
+import androidx.room.RoomDatabase
+import androidx.room.migration.Migration
+import androidx.sqlite.db.SupportSQLiteDatabase
+
+@Database(
+ entities = [
+ FolderEntity::class,
+ NotebookEntity::class,
+ PageEntity::class,
+ QuestionEntity::class,
+ StrokeEntity::class,
+ TextObjectEntity::class,
+ ImageObjectEntity::class,
+ CheckResultEntity::class
+ ],
+ version = 2,
+ exportSchema = false
+)
+abstract class InkProofDatabase : RoomDatabase() {
+ abstract fun folderDao(): FolderDao
+ abstract fun notebookDao(): NotebookDao
+ abstract fun pageDao(): PageDao
+ abstract fun questionDao(): QuestionDao
+ abstract fun strokeDao(): StrokeDao
+ abstract fun textObjectDao(): TextObjectDao
+ abstract fun imageObjectDao(): ImageObjectDao
+ abstract fun checkResultDao(): CheckResultDao
+ abstract fun maintenanceDao(): MaintenanceDao
+
+ companion object {
+ @Volatile
+ private var instance: InkProofDatabase? = null
+
+ fun get(context: Context): InkProofDatabase =
+ instance ?: synchronized(this) {
+ instance ?: Room.databaseBuilder(
+ context.applicationContext,
+ InkProofDatabase::class.java,
+ "inkproof.db"
+ ).addMigrations(MIGRATION_1_2).build().also { instance = it }
+ }
+
+ /** v1 → v2: per-page paper color (default = white paper). */
+ val MIGRATION_1_2 = object : Migration(1, 2) {
+ override fun migrate(db: SupportSQLiteDatabase) {
+ db.execSQL(
+ "ALTER TABLE pages ADD COLUMN paperColor INTEGER NOT NULL DEFAULT -197640"
+ )
+ }
+ }
+
+ /** In-memory database for tests. */
+ fun inMemory(context: Context): InkProofDatabase =
+ Room.inMemoryDatabaseBuilder(context, InkProofDatabase::class.java)
+ .allowMainThreadQueries()
+ .build()
+ }
+}
diff --git a/app/src/main/java/com/inkproof/app/data/db/StrokeCodec.kt b/app/src/main/java/com/inkproof/app/data/db/StrokeCodec.kt
new file mode 100644
index 0000000..2a777c2
--- /dev/null
+++ b/app/src/main/java/com/inkproof/app/data/db/StrokeCodec.kt
@@ -0,0 +1,47 @@
+package com.inkproof.app.data.db
+
+import com.inkproof.app.model.StrokePoint
+import java.nio.ByteBuffer
+import java.nio.ByteOrder
+
+/**
+ * Packs stroke points into a compact binary blob:
+ * [count:int] then per point [x:float][y:float][pressure:float][t:int (ms offset)].
+ *
+ * This keeps page loads fast even with thousands of strokes, while remaining
+ * a fully editable vector representation (never a bitmap).
+ */
+object StrokeCodec {
+ private const val VERSION: Int = 1
+
+ fun encode(points: List): ByteArray {
+ val buf = ByteBuffer.allocate(8 + points.size * 16).order(ByteOrder.LITTLE_ENDIAN)
+ buf.putInt(VERSION)
+ buf.putInt(points.size)
+ for (p in points) {
+ buf.putFloat(p.x)
+ buf.putFloat(p.y)
+ buf.putFloat(p.pressure)
+ buf.putInt(p.t.toInt())
+ }
+ return buf.array()
+ }
+
+ fun decode(bytes: ByteArray): List {
+ if (bytes.size < 8) return emptyList()
+ val buf = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN)
+ val version = buf.getInt()
+ if (version != VERSION) return emptyList()
+ val count = buf.getInt()
+ if (count < 0 || bytes.size < 8 + count * 16) return emptyList()
+ val out = ArrayList(count)
+ repeat(count) {
+ val x = buf.getFloat()
+ val y = buf.getFloat()
+ val pr = buf.getFloat()
+ val t = buf.getInt().toLong()
+ out.add(StrokePoint(x, y, pr, t))
+ }
+ return out
+ }
+}
diff --git a/app/src/main/java/com/inkproof/app/data/repo/CheckRepository.kt b/app/src/main/java/com/inkproof/app/data/repo/CheckRepository.kt
new file mode 100644
index 0000000..62680d7
--- /dev/null
+++ b/app/src/main/java/com/inkproof/app/data/repo/CheckRepository.kt
@@ -0,0 +1,65 @@
+package com.inkproof.app.data.repo
+
+import com.inkproof.app.data.db.CheckResultEntity
+import com.inkproof.app.data.db.InkProofDatabase
+import com.inkproof.app.model.CheckAction
+import com.inkproof.app.model.CheckResponse
+import com.inkproof.app.model.newId
+import kotlinx.serialization.json.Json
+
+/**
+ * Caches CHECK/SOLVE results keyed by
+ * (questionId, contentVersion, solutionVersion, action).
+ *
+ * Editing the solution bumps solutionVersion, which automatically invalidates
+ * older cached results — they simply stop matching the key.
+ */
+class CheckRepository(private val db: InkProofDatabase) {
+
+ private val json = Json {
+ ignoreUnknownKeys = true
+ encodeDefaults = true
+ }
+
+ suspend fun cached(
+ questionId: String,
+ contentVersion: Long,
+ solutionVersion: Long,
+ action: CheckAction
+ ): CheckResponse? {
+ val row = db.checkResultDao().find(questionId, contentVersion, solutionVersion, action.name)
+ ?: return null
+ return runCatching {
+ json.decodeFromString(CheckResponse.serializer(), row.resultJson)
+ }.getOrNull()
+ }
+
+ suspend fun store(
+ questionId: String,
+ contentVersion: Long,
+ solutionVersion: Long,
+ action: CheckAction,
+ response: CheckResponse
+ ) {
+ db.checkResultDao().upsert(
+ CheckResultEntity(
+ id = newId(),
+ questionId = questionId,
+ contentVersion = contentVersion,
+ solutionVersion = solutionVersion,
+ action = action.name,
+ resultJson = json.encodeToString(CheckResponse.serializer(), response),
+ createdAt = System.currentTimeMillis()
+ )
+ )
+ }
+
+ suspend fun history(questionId: String): List =
+ db.checkResultDao().historyFor(questionId).mapNotNull {
+ runCatching {
+ json.decodeFromString(CheckResponse.serializer(), it.resultJson)
+ }.getOrNull()
+ }
+
+ suspend fun clearAll() = db.checkResultDao().clearAll()
+}
diff --git a/app/src/main/java/com/inkproof/app/data/repo/LibraryRepository.kt b/app/src/main/java/com/inkproof/app/data/repo/LibraryRepository.kt
new file mode 100644
index 0000000..e3c5e1d
--- /dev/null
+++ b/app/src/main/java/com/inkproof/app/data/repo/LibraryRepository.kt
@@ -0,0 +1,208 @@
+package com.inkproof.app.data.repo
+
+import com.inkproof.app.data.db.FolderEntity
+import com.inkproof.app.data.db.InkProofDatabase
+import com.inkproof.app.data.db.NotebookEntity
+import com.inkproof.app.data.db.PageEntity
+import com.inkproof.app.model.PageKind
+import com.inkproof.app.model.PageTemplate
+import com.inkproof.app.model.newId
+import kotlinx.coroutines.flow.Flow
+
+/**
+ * Library management: workspace -> folders -> notebooks -> pages.
+ * Everything is persisted immediately; nothing lives only in UI state.
+ */
+class LibraryRepository(private val db: InkProofDatabase) {
+
+ fun observeNotebooks(): Flow> = db.notebookDao().observeAll()
+ fun observeFolders(): Flow> = db.folderDao().observeAll()
+ fun observePages(notebookId: String): Flow> =
+ db.pageDao().observePages(notebookId)
+
+ suspend fun notebook(id: String): NotebookEntity? = db.notebookDao().byId(id)
+ suspend fun page(id: String): PageEntity? = db.pageDao().byId(id)
+ suspend fun pagesFor(notebookId: String): List = db.pageDao().pagesFor(notebookId)
+
+ suspend fun createFolder(name: String): FolderEntity {
+ val now = System.currentTimeMillis()
+ val folder = FolderEntity(id = newId(), name = name, createdAt = now, updatedAt = now)
+ db.folderDao().upsert(folder)
+ return folder
+ }
+
+ /** Deleting a folder moves its notebooks back to the workspace root. */
+ suspend fun deleteFolder(id: String) {
+ db.notebookDao().clearFolder(id)
+ db.folderDao().delete(id)
+ }
+
+ suspend fun renameFolder(id: String, name: String) {
+ val folder = db.folderDao().byId(id) ?: return
+ db.folderDao().upsert(folder.copy(name = name, updatedAt = System.currentTimeMillis()))
+ }
+
+ suspend fun moveNotebookToFolder(notebookId: String, folderId: String?) {
+ db.notebookDao().moveToFolder(notebookId, folderId, System.currentTimeMillis())
+ }
+
+ suspend fun createNotebook(
+ title: String,
+ folderId: String? = null,
+ coverColor: Int = 0xFF1A2238.toInt(),
+ firstPageKind: PageKind = PageKind.NOTE,
+ firstPageTemplate: PageTemplate = PageTemplate.RULED
+ ): NotebookEntity {
+ val now = System.currentTimeMillis()
+ val notebook = NotebookEntity(
+ id = newId(), folderId = folderId, title = title,
+ coverColor = coverColor, createdAt = now, updatedAt = now
+ )
+ db.notebookDao().upsert(notebook)
+ createPage(notebook.id, firstPageKind, firstPageTemplate)
+ return notebook
+ }
+
+ suspend fun renameNotebook(id: String, title: String) {
+ db.notebookDao().rename(id, title, System.currentTimeMillis())
+ }
+
+ suspend fun setFavorite(id: String, favorite: Boolean) {
+ db.notebookDao().setFavorite(id, favorite)
+ }
+
+ suspend fun touchNotebook(id: String) {
+ db.notebookDao().touch(id, System.currentTimeMillis())
+ }
+
+ suspend fun deleteNotebook(id: String) {
+ // Cascade delete: strokes/questions/objects -> pages -> notebook.
+ db.maintenanceDao().deleteStrokesForNotebook(id)
+ db.maintenanceDao().deleteQuestionsForNotebook(id)
+ db.maintenanceDao().deleteTextForNotebook(id)
+ db.maintenanceDao().deleteImagesForNotebook(id)
+ db.maintenanceDao().deletePagesForNotebook(id)
+ db.notebookDao().delete(id)
+ }
+
+ /** Duplicate a notebook: fresh IDs for notebook, every page and every stroke. */
+ suspend fun duplicateNotebook(id: String): NotebookEntity? {
+ val source = db.notebookDao().byId(id) ?: return null
+ val now = System.currentTimeMillis()
+ val copy = source.copy(
+ id = newId(),
+ title = source.title + " (copy)",
+ createdAt = now,
+ updatedAt = now
+ )
+ db.notebookDao().upsert(copy)
+ for (page in db.pageDao().pagesFor(id)) {
+ val newPageId = newId()
+ db.pageDao().upsert(page.copy(id = newPageId, notebookId = copy.id, createdAt = now, updatedAt = now))
+ val questionIdMap = HashMap()
+ for (q in db.questionDao().forPage(page.id)) {
+ val newQid = newId()
+ questionIdMap[q.id] = newQid
+ db.questionDao().upsert(q.copy(id = newQid, pageId = newPageId, createdAt = now))
+ }
+ for (s in db.strokeDao().forPage(page.id)) {
+ db.strokeDao().upsert(
+ s.copy(
+ id = newId(),
+ pageId = newPageId,
+ questionId = s.questionId?.let { questionIdMap[it] }
+ )
+ )
+ }
+ }
+ return copy
+ }
+
+ /** Creating a page always creates a brand new, empty, independent page. */
+ suspend fun createPage(
+ notebookId: String,
+ kind: PageKind = PageKind.NOTE,
+ template: PageTemplate = PageTemplate.RULED,
+ pdfPath: String? = null,
+ pdfPageIndex: Int = 0
+ ): PageEntity {
+ val now = System.currentTimeMillis()
+ val index = db.pageDao().countFor(notebookId)
+ val page = PageEntity(
+ id = newId(),
+ notebookId = notebookId,
+ orderIndex = index,
+ kind = kind.name,
+ template = template.name,
+ pdfPath = pdfPath,
+ pdfPageIndex = pdfPageIndex,
+ createdAt = now,
+ updatedAt = now
+ )
+ db.pageDao().upsert(page)
+ db.notebookDao().touch(notebookId, now)
+ return page
+ }
+
+ /**
+ * Move a page up (-1) or down (+1) in its notebook.
+ * Order indices are re-normalized so they stay dense and consistent.
+ */
+ suspend fun movePage(pageId: String, delta: Int) {
+ val page = db.pageDao().byId(pageId) ?: return
+ val pages = db.pageDao().pagesFor(page.notebookId).toMutableList()
+ val from = pages.indexOfFirst { it.id == pageId }
+ if (from == -1) return
+ val to = (from + delta).coerceIn(0, pages.lastIndex)
+ if (to == from) return
+ val moved = pages.removeAt(from)
+ pages.add(to, moved)
+ pages.forEachIndexed { index, p ->
+ if (p.orderIndex != index) db.pageDao().setOrder(p.id, index)
+ }
+ db.notebookDao().touch(page.notebookId, System.currentTimeMillis())
+ }
+
+ /** Deleting a page removes the page AND all of its content. */
+ suspend fun deletePage(pageId: String) {
+ db.maintenanceDao().deleteStrokesForPage(pageId)
+ db.maintenanceDao().deleteQuestionsForPage(pageId)
+ db.maintenanceDao().deleteTextForPage(pageId)
+ db.maintenanceDao().deleteImagesForPage(pageId)
+ db.pageDao().delete(pageId)
+ }
+
+ suspend fun reorderPages(notebookId: String, orderedPageIds: List) {
+ orderedPageIds.forEachIndexed { index, pageId ->
+ db.pageDao().setOrder(pageId, index)
+ }
+ db.notebookDao().touch(notebookId, System.currentTimeMillis())
+ }
+
+ /** Direct page update (used by importers to adjust page size). */
+ suspend fun upsertPage(page: PageEntity) {
+ db.pageDao().upsert(page)
+ }
+
+ /** Changing templates never destroys content. */
+ suspend fun setTemplate(pageId: String, template: PageTemplate) {
+ db.pageDao().setTemplate(pageId, template.name, System.currentTimeMillis())
+ }
+
+ /** Paper color is per-page and never touches stroke data. */
+ suspend fun setPaperColor(pageId: String, color: Int) {
+ val page = db.pageDao().byId(pageId) ?: return
+ db.pageDao().upsert(
+ page.copy(paperColor = color, updatedAt = System.currentTimeMillis())
+ )
+ }
+
+ suspend fun search(query: String): List {
+ if (query.isBlank()) return emptyList()
+ val byTitle = db.notebookDao().search(query.trim())
+ val byQuestion = db.questionDao().search(query.trim())
+ .mapNotNull { q -> db.pageDao().byId(q.pageId)?.notebookId }
+ .mapNotNull { db.notebookDao().byId(it) }
+ return (byTitle + byQuestion).distinctBy { it.id }
+ }
+}
diff --git a/app/src/main/java/com/inkproof/app/data/repo/Mappers.kt b/app/src/main/java/com/inkproof/app/data/repo/Mappers.kt
new file mode 100644
index 0000000..62f0857
--- /dev/null
+++ b/app/src/main/java/com/inkproof/app/data/repo/Mappers.kt
@@ -0,0 +1,98 @@
+package com.inkproof.app.data.repo
+
+import com.inkproof.app.data.db.QuestionEntity
+import com.inkproof.app.data.db.StrokeCodec
+import com.inkproof.app.data.db.StrokeEntity
+import com.inkproof.app.data.db.TextObjectEntity
+import com.inkproof.app.model.Question
+import com.inkproof.app.model.QuestionContentType
+import com.inkproof.app.model.ShapeType
+import com.inkproof.app.model.Stroke
+import com.inkproof.app.model.StrokeRole
+import com.inkproof.app.model.TextObject
+import com.inkproof.app.model.ToolType
+
+fun Stroke.toEntity(): StrokeEntity = StrokeEntity(
+ id = id,
+ pageId = pageId,
+ questionId = questionId,
+ role = role.name,
+ tool = tool.name,
+ color = color,
+ baseWidth = baseWidth,
+ shapeType = shapeType?.name,
+ points = StrokeCodec.encode(points),
+ createdAt = createdAt
+)
+
+fun StrokeEntity.toModel(): Stroke = Stroke(
+ id = id,
+ pageId = pageId,
+ questionId = questionId,
+ role = runCatching { StrokeRole.valueOf(role) }.getOrDefault(StrokeRole.FREEFORM),
+ tool = runCatching { ToolType.valueOf(tool) }.getOrDefault(ToolType.PEN),
+ color = color,
+ baseWidth = baseWidth,
+ points = StrokeCodec.decode(points),
+ createdAt = createdAt,
+ shapeType = shapeType?.let { runCatching { ShapeType.valueOf(it) }.getOrNull() }
+)
+
+fun Question.toEntity(): QuestionEntity = QuestionEntity(
+ id = id,
+ pageId = pageId,
+ orderIndex = orderIndex,
+ contentType = contentType.name,
+ typedText = typedText,
+ mediaPath = mediaPath,
+ questionTop = questionTop,
+ questionBottom = questionBottom,
+ solutionTop = solutionTop,
+ solutionBottom = solutionBottom,
+ contentVersion = contentVersion,
+ solutionVersion = solutionVersion,
+ createdAt = createdAt
+)
+
+fun TextObject.toEntity(): TextObjectEntity = TextObjectEntity(
+ id = id,
+ pageId = pageId,
+ questionId = questionId,
+ text = text,
+ x = x,
+ y = y,
+ widthPts = widthPts,
+ fontSize = fontSize,
+ color = color,
+ createdAt = createdAt
+)
+
+fun TextObjectEntity.toModel(): TextObject = TextObject(
+ id = id,
+ pageId = pageId,
+ questionId = questionId,
+ text = text,
+ x = x,
+ y = y,
+ widthPts = widthPts,
+ fontSize = fontSize,
+ color = color,
+ createdAt = createdAt
+)
+
+fun QuestionEntity.toModel(): Question = Question(
+ id = id,
+ pageId = pageId,
+ orderIndex = orderIndex,
+ contentType = runCatching { QuestionContentType.valueOf(contentType) }
+ .getOrDefault(QuestionContentType.TYPED),
+ typedText = typedText,
+ mediaPath = mediaPath,
+ questionTop = questionTop,
+ questionBottom = questionBottom,
+ solutionTop = solutionTop,
+ solutionBottom = solutionBottom,
+ contentVersion = contentVersion,
+ solutionVersion = solutionVersion,
+ createdAt = createdAt
+)
diff --git a/app/src/main/java/com/inkproof/app/data/repo/PageRepository.kt b/app/src/main/java/com/inkproof/app/data/repo/PageRepository.kt
new file mode 100644
index 0000000..11b7edb
--- /dev/null
+++ b/app/src/main/java/com/inkproof/app/data/repo/PageRepository.kt
@@ -0,0 +1,155 @@
+package com.inkproof.app.data.repo
+
+import com.inkproof.app.data.db.InkProofDatabase
+import com.inkproof.app.model.Question
+import com.inkproof.app.model.QuestionContentType
+import com.inkproof.app.model.Stroke
+import com.inkproof.app.model.StrokeRole
+import com.inkproof.app.model.newId
+import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.map
+
+/**
+ * Page-scoped content: strokes and questions.
+ *
+ * Isolation guarantees:
+ * - loading a page loads ONLY that page's strokes/questions
+ * - strokes are always written with their owning pageId
+ * - solution strokes are tagged with their questionId at write time,
+ * so checking a question never needs page-wide guessing.
+ */
+class PageRepository(private val db: InkProofDatabase) {
+
+ // ----- Strokes -----
+
+ suspend fun strokesForPage(pageId: String): List =
+ db.strokeDao().forPage(pageId).map { it.toModel() }
+
+ suspend fun addStroke(stroke: Stroke) {
+ db.strokeDao().upsert(stroke.toEntity())
+ if (stroke.questionId != null && stroke.role == StrokeRole.SOLUTION) {
+ db.questionDao().bumpSolutionVersion(stroke.questionId)
+ }
+ if (stroke.questionId != null && stroke.role == StrokeRole.QUESTION) {
+ db.questionDao().bumpContentVersion(stroke.questionId)
+ }
+ }
+
+ suspend fun addStrokes(strokes: List) {
+ if (strokes.isEmpty()) return
+ db.strokeDao().upsertAll(strokes.map { it.toEntity() })
+ strokes.mapNotNull { s -> s.questionId?.takeIf { s.role == StrokeRole.SOLUTION } }
+ .distinct()
+ .forEach { db.questionDao().bumpSolutionVersion(it) }
+ }
+
+ suspend fun updateStrokes(strokes: List) {
+ if (strokes.isEmpty()) return
+ db.strokeDao().upsertAll(strokes.map { it.toEntity() })
+ // Geometry changes alter what recognition would read -> invalidate caches.
+ bumpVersionsFor(strokes)
+ }
+
+ suspend fun bumpVersionsFor(strokes: List) {
+ strokes.mapNotNull { s -> s.questionId?.takeIf { s.role == StrokeRole.SOLUTION } }
+ .distinct()
+ .forEach { db.questionDao().bumpSolutionVersion(it) }
+ }
+
+ suspend fun deleteStrokes(strokes: List) {
+ if (strokes.isEmpty()) return
+ db.strokeDao().deleteAll(strokes.map { it.id })
+ strokes.mapNotNull { s -> s.questionId?.takeIf { s.role == StrokeRole.SOLUTION } }
+ .distinct()
+ .forEach { db.questionDao().bumpSolutionVersion(it) }
+ }
+
+ suspend fun solutionStrokes(questionId: String): List =
+ db.strokeDao().forQuestionRole(questionId, StrokeRole.SOLUTION.name).map { it.toModel() }
+
+ suspend fun questionStrokes(questionId: String): List =
+ db.strokeDao().forQuestionRole(questionId, StrokeRole.QUESTION.name).map { it.toModel() }
+
+ // ----- Text objects -----
+
+ suspend fun textObjectsForPage(pageId: String): List =
+ db.textObjectDao().forPage(pageId).map { it.toModel() }
+
+ suspend fun upsertTextObject(obj: com.inkproof.app.model.TextObject) {
+ db.textObjectDao().upsert(obj.toEntity())
+ }
+
+ suspend fun deleteTextObject(id: String) {
+ db.textObjectDao().delete(id)
+ }
+
+ // ----- Questions -----
+
+ fun observeQuestions(pageId: String): Flow> =
+ db.questionDao().observeForPage(pageId).map { list -> list.map { it.toModel() } }
+
+ suspend fun questionsForPage(pageId: String): List =
+ db.questionDao().forPage(pageId).map { it.toModel() }
+
+ suspend fun question(id: String): Question? = db.questionDao().byId(id)?.toModel()
+
+ suspend fun createQuestion(
+ pageId: String,
+ contentType: QuestionContentType,
+ typedText: String? = null,
+ mediaPath: String? = null,
+ questionTop: Float,
+ questionHeight: Float = 260f,
+ solutionHeight: Float = 700f
+ ): Question {
+ val index = db.questionDao().forPage(pageId).size
+ val question = Question(
+ id = newId(),
+ pageId = pageId,
+ orderIndex = index,
+ contentType = contentType,
+ typedText = typedText,
+ mediaPath = mediaPath,
+ questionTop = questionTop,
+ questionBottom = questionTop + questionHeight,
+ solutionTop = questionTop + questionHeight,
+ solutionBottom = questionTop + questionHeight + solutionHeight
+ )
+ db.questionDao().upsert(question.toEntity())
+ return question
+ }
+
+ suspend fun updateQuestionText(questionId: String, text: String) {
+ db.questionDao().updateTypedText(questionId, text)
+ }
+
+ suspend fun deleteQuestion(questionId: String) {
+ val strokes = db.strokeDao().forQuestionRole(questionId, StrokeRole.SOLUTION.name) +
+ db.strokeDao().forQuestionRole(questionId, StrokeRole.QUESTION.name)
+ db.strokeDao().deleteAll(strokes.map { it.id })
+ db.checkResultDao().clearFor(questionId)
+ db.questionDao().delete(questionId)
+ }
+
+ /**
+ * Associate a stroke with the question whose solution region contains it.
+ * Priority: explicit lasso association > containing question region > freeform.
+ */
+ suspend fun classifyStroke(pageId: String, stroke: Stroke): Stroke {
+ val questions = questionsForPage(pageId)
+ val b = stroke.bounds()
+ val solutionOwner = questions.firstOrNull { q ->
+ b.centerY >= q.solutionTop && b.centerY <= q.solutionBottom
+ }
+ if (solutionOwner != null) {
+ return stroke.copy(questionId = solutionOwner.id, role = StrokeRole.SOLUTION)
+ }
+ val questionOwner = questions.firstOrNull { q ->
+ b.centerY >= q.questionTop && b.centerY < q.questionBottom
+ }
+ if (questionOwner != null) {
+ return stroke.copy(questionId = questionOwner.id, role = StrokeRole.QUESTION)
+ }
+ return stroke.copy(questionId = null, role = StrokeRole.FREEFORM)
+ }
+}
diff --git a/app/src/main/java/com/inkproof/app/data/settings/SettingsStore.kt b/app/src/main/java/com/inkproof/app/data/settings/SettingsStore.kt
new file mode 100644
index 0000000..c40c3ed
--- /dev/null
+++ b/app/src/main/java/com/inkproof/app/data/settings/SettingsStore.kt
@@ -0,0 +1,161 @@
+package com.inkproof.app.data.settings
+
+import android.content.Context
+import androidx.datastore.preferences.core.booleanPreferencesKey
+import androidx.datastore.preferences.core.edit
+import androidx.datastore.preferences.core.floatPreferencesKey
+import androidx.datastore.preferences.core.intPreferencesKey
+import androidx.datastore.preferences.core.longPreferencesKey
+import androidx.datastore.preferences.core.stringPreferencesKey
+import androidx.datastore.preferences.preferencesDataStore
+import com.inkproof.app.BuildConfig
+import com.inkproof.app.model.PenPalette
+import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.map
+
+private val Context.dataStore by preferencesDataStore(name = "inkproof_settings")
+
+data class Settings(
+ // Appearance: "system" | "light" | "dark"
+ val appTheme: String = "system",
+ // Handwriting stabilization: "off" | "low" | "medium" | "high"
+ val stabilization: String = "medium",
+ // Canvas
+ val continueFromLastPage: Boolean = true,
+ val keepScreenAwake: Boolean = true,
+ val fullScreenCanvas: Boolean = false,
+ val fingerWriting: Boolean = false,
+ // Writing
+ val defaultPenColor: Int = PenPalette.INK_NAVY,
+ val defaultPenWidth: Float = 3.0f,
+ val pressureEnabled: Boolean = true,
+ val holdToShapeMs: Long = 400L,
+ val eraserRadius: Float = 18f,
+ /** Stylus button double-press toggles eraser <-> previous tool. */
+ val stylusDoubleTap: Boolean = true,
+ // Math
+ val recognitionConfidenceThreshold: Float = 0.4f,
+ val autoShowHints: Boolean = false,
+ // AI
+ val mockMode: Boolean = BuildConfig.DEFAULT_MOCK_MODE,
+ /** Empty = use the build-time BuildConfig.BACKEND_BASE_URL. */
+ val backendUrl: String = "",
+ val lastPageByNotebook: String = ""
+)
+
+class SettingsStore(private val context: Context) {
+
+ private object Keys {
+ val APP_THEME = stringPreferencesKey("app_theme")
+ val STABILIZATION = stringPreferencesKey("stabilization")
+ val CONTINUE_LAST = booleanPreferencesKey("continue_from_last_page")
+ val KEEP_AWAKE = booleanPreferencesKey("keep_screen_awake")
+ val FULL_SCREEN = booleanPreferencesKey("full_screen_canvas")
+ val FINGER_WRITING = booleanPreferencesKey("finger_writing")
+ val PEN_COLOR = intPreferencesKey("default_pen_color")
+ val PEN_WIDTH = floatPreferencesKey("default_pen_width")
+ val PRESSURE = booleanPreferencesKey("pressure_enabled")
+ val HOLD_MS = longPreferencesKey("hold_to_shape_ms")
+ val ERASER_RADIUS = floatPreferencesKey("eraser_radius")
+ val STYLUS_DOUBLE_TAP = booleanPreferencesKey("stylus_double_tap")
+ val RECOGNITION_CONFIDENCE = floatPreferencesKey("recognition_confidence")
+ val AUTO_HINTS = booleanPreferencesKey("auto_show_hints")
+ val MOCK_MODE = booleanPreferencesKey("mock_mode")
+ val BACKEND_URL = stringPreferencesKey("backend_url")
+ val LAST_PAGES = stringPreferencesKey("last_page_by_notebook")
+ }
+
+ val settings: Flow = context.dataStore.data.map { p ->
+ Settings(
+ appTheme = p[Keys.APP_THEME] ?: "system",
+ stabilization = p[Keys.STABILIZATION] ?: "medium",
+ continueFromLastPage = p[Keys.CONTINUE_LAST] ?: true,
+ keepScreenAwake = p[Keys.KEEP_AWAKE] ?: true,
+ fullScreenCanvas = p[Keys.FULL_SCREEN] ?: false,
+ fingerWriting = p[Keys.FINGER_WRITING] ?: false,
+ defaultPenColor = p[Keys.PEN_COLOR] ?: PenPalette.INK_NAVY,
+ defaultPenWidth = p[Keys.PEN_WIDTH] ?: 3.0f,
+ pressureEnabled = p[Keys.PRESSURE] ?: true,
+ holdToShapeMs = p[Keys.HOLD_MS] ?: 400L,
+ eraserRadius = p[Keys.ERASER_RADIUS] ?: 18f,
+ stylusDoubleTap = p[Keys.STYLUS_DOUBLE_TAP] ?: true,
+ recognitionConfidenceThreshold = p[Keys.RECOGNITION_CONFIDENCE] ?: 0.4f,
+ autoShowHints = p[Keys.AUTO_HINTS] ?: false,
+ mockMode = p[Keys.MOCK_MODE] ?: BuildConfig.DEFAULT_MOCK_MODE,
+ backendUrl = p[Keys.BACKEND_URL] ?: "",
+ lastPageByNotebook = p[Keys.LAST_PAGES] ?: ""
+ )
+ }
+
+ suspend fun setAppTheme(value: String) =
+ context.dataStore.edit { it[Keys.APP_THEME] = value }
+
+ suspend fun setStabilization(value: String) =
+ context.dataStore.edit { it[Keys.STABILIZATION] = value }
+
+ suspend fun setContinueFromLastPage(value: Boolean) =
+ context.dataStore.edit { it[Keys.CONTINUE_LAST] = value }
+
+ suspend fun setKeepScreenAwake(value: Boolean) =
+ context.dataStore.edit { it[Keys.KEEP_AWAKE] = value }
+
+ suspend fun setFullScreenCanvas(value: Boolean) =
+ context.dataStore.edit { it[Keys.FULL_SCREEN] = value }
+
+ suspend fun setFingerWriting(value: Boolean) =
+ context.dataStore.edit { it[Keys.FINGER_WRITING] = value }
+
+ suspend fun setDefaultPenColor(value: Int) =
+ context.dataStore.edit { it[Keys.PEN_COLOR] = value }
+
+ suspend fun setDefaultPenWidth(value: Float) =
+ context.dataStore.edit { it[Keys.PEN_WIDTH] = value }
+
+ suspend fun setPressureEnabled(value: Boolean) =
+ context.dataStore.edit { it[Keys.PRESSURE] = value }
+
+ suspend fun setHoldToShapeMs(value: Long) =
+ context.dataStore.edit { it[Keys.HOLD_MS] = value }
+
+ suspend fun setEraserRadius(value: Float) =
+ context.dataStore.edit { it[Keys.ERASER_RADIUS] = value }
+
+ suspend fun setStylusDoubleTap(value: Boolean) =
+ context.dataStore.edit { it[Keys.STYLUS_DOUBLE_TAP] = value }
+
+ suspend fun setRecognitionConfidence(value: Float) =
+ context.dataStore.edit { it[Keys.RECOGNITION_CONFIDENCE] = value }
+
+ suspend fun setAutoShowHints(value: Boolean) =
+ context.dataStore.edit { it[Keys.AUTO_HINTS] = value }
+
+ suspend fun setMockMode(value: Boolean) =
+ context.dataStore.edit { it[Keys.MOCK_MODE] = value }
+
+ /** Runtime backend URL override; blank returns to the built-in default. */
+ suspend fun setBackendUrl(value: String) =
+ context.dataStore.edit { it[Keys.BACKEND_URL] = value.trim() }
+
+ /** Remember the last open page per notebook ("Continue from last page"). */
+ suspend fun setLastPage(notebookId: String, pageId: String) =
+ context.dataStore.edit { prefs ->
+ val map = decodeLastPages(prefs[Keys.LAST_PAGES] ?: "").toMutableMap()
+ map[notebookId] = pageId
+ // Keep the map bounded.
+ while (map.size > 50) map.remove(map.keys.first())
+ prefs[Keys.LAST_PAGES] = encodeLastPages(map)
+ }
+
+ companion object {
+ fun decodeLastPages(encoded: String): Map =
+ encoded.split(';')
+ .filter { it.contains('=') }
+ .associate {
+ val idx = it.indexOf('=')
+ it.substring(0, idx) to it.substring(idx + 1)
+ }
+
+ fun encodeLastPages(map: Map): String =
+ map.entries.joinToString(";") { "${it.key}=${it.value}" }
+ }
+}
diff --git a/app/src/main/java/com/inkproof/app/ink/CanvasCamera.kt b/app/src/main/java/com/inkproof/app/ink/CanvasCamera.kt
new file mode 100644
index 0000000..f2a3f51
--- /dev/null
+++ b/app/src/main/java/com/inkproof/app/ink/CanvasCamera.kt
@@ -0,0 +1,69 @@
+package com.inkproof.app.ink
+
+import android.graphics.Matrix
+
+/**
+ * Maps between page space (document units) and screen space.
+ * Strokes are stored in page space so ink stays sharp at any zoom.
+ */
+class CanvasCamera {
+ var scale: Float = 1f
+ private set
+ var offsetX: Float = 0f
+ private set
+ var offsetY: Float = 0f
+ private set
+
+ var minScale: Float = 0.25f
+ var maxScale: Float = 6f
+
+ private val matrix = Matrix()
+ private val inverse = Matrix()
+ private val tmp = FloatArray(2)
+
+ fun matrix(): Matrix {
+ matrix.reset()
+ matrix.postScale(scale, scale)
+ matrix.postTranslate(offsetX, offsetY)
+ return matrix
+ }
+
+ fun screenToPageX(sx: Float): Float = (sx - offsetX) / scale
+ fun screenToPageY(sy: Float): Float = (sy - offsetY) / scale
+ fun pageToScreenX(px: Float): Float = px * scale + offsetX
+ fun pageToScreenY(py: Float): Float = py * scale + offsetY
+
+ fun panBy(dxScreen: Float, dyScreen: Float) {
+ offsetX += dxScreen
+ offsetY += dyScreen
+ }
+
+ /** Zoom around a screen-space focal point. */
+ fun zoomBy(factor: Float, focusX: Float, focusY: Float) {
+ val newScale = (scale * factor).coerceIn(minScale, maxScale)
+ val actual = newScale / scale
+ // Keep the focal point fixed on screen.
+ offsetX = focusX - (focusX - offsetX) * actual
+ offsetY = focusY - (focusY - offsetY) * actual
+ scale = newScale
+ }
+
+ fun set(scale: Float, offsetX: Float, offsetY: Float) {
+ this.scale = scale.coerceIn(minScale, maxScale)
+ this.offsetX = offsetX
+ this.offsetY = offsetY
+ }
+
+ /** Fit a page of the given size into the given viewport with padding. */
+ fun fitPage(pageWidth: Float, pageHeight: Float, viewWidth: Float, viewHeight: Float) {
+ if (pageWidth <= 0 || viewWidth <= 0) return
+ val padding = 24f
+ val s = minOf(
+ (viewWidth - padding * 2) / pageWidth,
+ (viewHeight - padding * 2) / pageHeight
+ ).coerceIn(minScale, maxScale)
+ scale = s
+ offsetX = (viewWidth - pageWidth * s) / 2f
+ offsetY = padding
+ }
+}
diff --git a/app/src/main/java/com/inkproof/app/ink/InkCanvasView.kt b/app/src/main/java/com/inkproof/app/ink/InkCanvasView.kt
new file mode 100644
index 0000000..1f344a8
--- /dev/null
+++ b/app/src/main/java/com/inkproof/app/ink/InkCanvasView.kt
@@ -0,0 +1,1329 @@
+package com.inkproof.app.ink
+
+import android.content.Context
+import android.graphics.Bitmap
+import android.graphics.BitmapFactory
+import android.graphics.Canvas
+import android.graphics.Color
+import android.graphics.DashPathEffect
+import android.graphics.Paint
+import android.graphics.Path
+import android.graphics.Picture
+import android.graphics.RectF
+import android.os.SystemClock
+import android.util.AttributeSet
+import android.view.HapticFeedbackConstants
+import android.view.MotionEvent
+import android.view.ScaleGestureDetector
+import android.view.View
+import com.inkproof.app.model.DetectedShape
+import com.inkproof.app.model.PageTemplate
+import com.inkproof.app.model.PenStyle
+import com.inkproof.app.model.Question
+import com.inkproof.app.model.Stroke
+import com.inkproof.app.model.StrokePoint
+import com.inkproof.app.model.ShapeType
+import com.inkproof.app.model.StrokeRole
+import com.inkproof.app.model.TextObject
+import com.inkproof.app.model.ToolType
+import kotlin.math.ceil
+import kotlin.math.abs
+import kotlin.math.hypot
+
+/**
+ * The InkProof handwriting canvas.
+ *
+ * Latency architecture:
+ * Stylus MotionEvent -> input layer (this view) -> active stroke points
+ * -> immediate render in onDraw -> stroke committed to the persistent
+ * model only on pen-up (via [Listener.onStrokeCommitted]).
+ *
+ * - The active stroke is drawn directly every frame; nothing waits for
+ * state frameworks, databases, JSON, OCR or the network.
+ * - Committed strokes are recorded into a [Picture] display list that is
+ * rebuilt only when the stroke set changes — never per stylus point.
+ * - All stroke geometry lives in page space, so ink is sharp at any zoom.
+ *
+ * Input policy (OnePlus Stylo 2 first):
+ * - stylus (TOOL_TYPE_STYLUS) writes; TOOL_TYPE_ERASER erases
+ * - the primary stylus button temporarily switches to the eraser
+ * - fingers navigate: one-finger pan, two-finger pan, pinch zoom
+ * - palm: finger touches are ignored for navigation while the stylus is
+ * in contact or hovered recently (real tool-type data, not timing hacks)
+ */
+class InkCanvasView @JvmOverloads constructor(
+ context: Context,
+ attrs: AttributeSet? = null
+) : View(context, attrs) {
+
+ interface Listener {
+ /** A finished stroke should be persisted (async, off the UI thread). */
+ fun onStrokeCommitted(stroke: Stroke)
+
+ /** Strokes removed by the eraser in one gesture. */
+ fun onStrokesErased(strokes: List)
+
+ /** Lasso selection changed; bounds are in screen coordinates. */
+ fun onSelectionChanged(strokes: List, screenBounds: RectF?)
+
+ /** A lasso selection was moved: same IDs, new coordinates. */
+ fun onStrokesMoved(before: List, after: List)
+
+ /** Camera (zoom) changed — for zoom indicators. */
+ fun onCameraChanged(scale: Float) {}
+
+ /**
+ * TEXT tool tap: [existing] is the tapped text object (edit) or null
+ * (create a new one at the tapped page position).
+ */
+ fun onTextTap(pageX: Float, pageY: Float, existing: TextObject?) {}
+
+ /**
+ * Continuous scrolling carried the viewport onto a neighbor page:
+ * make [pageId] current. The view has already prepared a camera
+ * handoff so the transition is seamless.
+ */
+ fun onScrollToPage(pageId: String) {}
+ }
+
+ /** Read-only preview of an adjacent page for continuous scrolling. */
+ class NeighborPage(
+ val pageId: String,
+ val width: Float,
+ val height: Float,
+ val template: PageTemplate,
+ val paperColor: Int,
+ val strokes: List
+ )
+
+ var listener: Listener? = null
+
+ // ----- page state -----
+ var pageId: String = ""
+ private set
+ var pageWidth: Float = 1600f
+ private set
+ var pageHeight: Float = 2200f
+ private set
+ var template: PageTemplate = PageTemplate.RULED
+ set(value) { field = value; invalidate() }
+
+ /** Page paper color — a PAGE property, independent of the app theme. */
+ var paperColor: Int = com.inkproof.app.model.PaperColors.WHITE
+ set(value) { field = value; invalidate() }
+
+ // ----- continuous vertical scrolling across page boundaries -----
+ /** Gap between stacked pages, in page units. */
+ private val pageGap = 64f
+ private var neighborAbove: NeighborPage? = null
+ private var neighborBelow: NeighborPage? = null
+ private var neighborAbovePicture: Picture? = null
+ private var neighborBelowPicture: Picture? = null
+
+ /** Camera state to apply when the next setPage is a scroll handoff. */
+ private var handoffPageId: String? = null
+ private var handoffOffsetY = 0f
+
+ /** Provide read-only previews of the adjacent pages (or null at ends). */
+ fun setNeighbors(above: NeighborPage?, below: NeighborPage?) {
+ neighborAbove = above
+ neighborBelow = below
+ neighborAbovePicture = above?.let { buildNeighborPicture(it) }
+ neighborBelowPicture = below?.let { buildNeighborPicture(it) }
+ invalidate()
+ }
+
+ private fun buildNeighborPicture(n: NeighborPage): Picture {
+ val picture = Picture()
+ val c = picture.beginRecording(
+ n.width.toInt().coerceAtLeast(1), n.height.toInt().coerceAtLeast(1)
+ )
+ TemplateRenderer.draw(c, n.template, n.width, n.height, n.paperColor)
+ for (s in n.strokes) StrokeRenderer.draw(c, s)
+ picture.endRecording()
+ return picture
+ }
+
+ /**
+ * After a finger pan, check whether the viewport center crossed onto a
+ * neighbor page; if so, prepare a seamless camera handoff and ask the
+ * host to switch pages. Never fires while the stylus is working.
+ */
+ private fun maybeScrollToNeighbor() {
+ if (handoffPageId != null) return // switch already in flight
+ if (drawing || lassoActive || draggingSelection || resizingSelection) return
+ val centerPageY = camera.screenToPageY(height / 2f)
+ val below = neighborBelow
+ val above = neighborAbove
+ if (below != null && centerPageY > pageHeight + pageGap) {
+ val shift = (pageHeight + pageGap) * camera.scale
+ handoffPageId = below.pageId
+ handoffOffsetY = camera.offsetY + shift
+ listener?.onScrollToPage(below.pageId)
+ } else if (above != null && centerPageY < -pageGap) {
+ val shift = (above.height + pageGap) * camera.scale
+ handoffPageId = above.pageId
+ handoffOffsetY = camera.offsetY - shift
+ listener?.onScrollToPage(above.pageId)
+ }
+ }
+
+ private var pdfBackground: Bitmap? = null
+ private var questions: List = emptyList()
+ private var textObjects: List = emptyList()
+
+ // ----- text tool tap -----
+ private var textTapPending = false
+ private var textTapX = 0f
+ private var textTapY = 0f
+
+ // ----- tool state -----
+ var penStyle: PenStyle = PenStyle()
+ var holdToShapeMs: Long = 400L
+ var fingerWritingEnabled: Boolean = false
+
+ /** Jitter smoothing for the active stroke; zero added latency. */
+ private val stabilizer = StrokeStabilizer(StrokeStabilizer.Level.MEDIUM)
+ var stabilization: StrokeStabilizer.Level
+ get() = stabilizer.level
+ set(value) { stabilizer.level = value }
+
+ /** Shape drawn by the explicit SHAPE tool (picked in the toolbar). */
+ var activeShapeKind: ShapeType = ShapeType.RECTANGLE
+
+ // ----- stylus button double-press -> toggle eraser -----
+ // Driven ONLY by real hardware button state transitions (never faked
+ // from screen taps). See StylusDoubleTapDetector for the OnePlus note.
+ var stylusDoubleTapEnabled: Boolean = true
+ var onStylusDoubleTap: (() -> Unit)? = null
+ private val stylusDoubleTap = StylusDoubleTapDetector()
+ private var stylusButtonWasDown = false
+
+ private fun trackStylusButton(event: MotionEvent) {
+ if (!stylusDoubleTapEnabled) {
+ stylusButtonWasDown = false
+ return
+ }
+ val mask = MotionEvent.BUTTON_STYLUS_PRIMARY or
+ MotionEvent.BUTTON_STYLUS_SECONDARY
+ val down = (event.buttonState and mask) != 0
+ if (down && !stylusButtonWasDown &&
+ stylusDoubleTap.onButtonPress(SystemClock.uptimeMillis())
+ ) {
+ performHapticFeedback(HapticFeedbackConstants.KEYBOARD_TAP)
+ onStylusDoubleTap?.invoke()
+ }
+ stylusButtonWasDown = down
+ }
+
+ private val camera = CanvasCamera()
+
+ // ----- committed strokes (page order) -----
+ private val strokes = ArrayList()
+ private var committedPicture: Picture? = null
+ private var pictureDirty = true
+
+ // ----- active stroke -----
+ private var activePointerId = -1
+ private var activeToolOverride: ToolType? = null
+ private val activePoints = ArrayList(512)
+ private var activeStartUptime = 0L
+ private var drawing = false
+
+ // ----- hold to shape -----
+ private var snappedShape: DetectedShape? = null
+ private var lastSignificantMove = 0L
+ private val holdCheck = Runnable { maybeSnapShape() }
+
+ // ----- eraser -----
+ private val erasedThisGesture = ArrayList()
+ var eraserRadiusPage: Float = 18f
+
+ // ----- lasso -----
+ private val lassoPoints = ArrayList(256)
+ private var lassoActive = false
+ private val selection = ArrayList()
+ private var selectionBoundsPage: RectF? = null
+ private var draggingSelection = false
+ private var dragStartX = 0f
+ private var dragStartY = 0f
+ private var dragDX = 0f
+ private var dragDY = 0f
+ private var selectionBefore: List = emptyList()
+
+ // ----- selection resize (corner handle) -----
+ private var resizingSelection = false
+ private var resizeOrigBounds = RectF()
+ private val resizeHandlePaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
+ style = Paint.Style.FILL
+ color = 0xFF4B6BD6.toInt()
+ }
+ private val resizeHandleRing = Paint(Paint.ANTI_ALIAS_FLAG).apply {
+ style = Paint.Style.STROKE
+ color = 0xFFFFFFFF.toInt()
+ strokeWidth = 2.5f
+ }
+
+ // ----- navigation -----
+ private var navPointerId1 = -1
+ private var navPointerId2 = -1
+ private var lastNavX = 0f
+ private var lastNavY = 0f
+ private var navigating = false
+ private var lastStylusContact = 0L
+
+ private val scaleDetector = ScaleGestureDetector(
+ context,
+ object : ScaleGestureDetector.SimpleOnScaleGestureListener() {
+ override fun onScale(detector: ScaleGestureDetector): Boolean {
+ camera.zoomBy(detector.scaleFactor, detector.focusX, detector.focusY)
+ listener?.onCameraChanged(camera.scale)
+ invalidate()
+ return true
+ }
+ }
+ ).apply { isQuickScaleEnabled = false }
+
+ // ----- hover cursor -----
+ private var hoverX = -1f
+ private var hoverY = -1f
+ private var hovering = false
+
+ // ----- paints -----
+ private val backgroundPaint = Paint().apply { color = 0xFFECEEF3.toInt() }
+
+ /**
+ * Surrounding chrome color (outside the page). Follows the app theme;
+ * the PAGE itself keeps its chosen template/background.
+ */
+ fun setChromeColor(color: Int) {
+ backgroundPaint.color = color
+ invalidate()
+ }
+ private val lassoPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
+ style = Paint.Style.STROKE
+ color = 0xFF4B6BD6.toInt()
+ strokeWidth = 2.5f
+ pathEffect = DashPathEffect(floatArrayOf(14f, 10f), 0f)
+ }
+ private val selectionFill = Paint(Paint.ANTI_ALIAS_FLAG).apply {
+ style = Paint.Style.FILL
+ color = 0x144B6BD6
+ }
+ private val selectionStroke = Paint(Paint.ANTI_ALIAS_FLAG).apply {
+ style = Paint.Style.STROKE
+ color = 0xFF4B6BD6.toInt()
+ strokeWidth = 2f
+ pathEffect = DashPathEffect(floatArrayOf(10f, 8f), 0f)
+ }
+ private val hoverPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
+ style = Paint.Style.STROKE
+ color = 0x664B6BD6
+ strokeWidth = 1.5f
+ }
+ private val snapHintPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
+ style = Paint.Style.STROKE
+ color = 0x554B6BD6
+ strokeWidth = 2f
+ pathEffect = DashPathEffect(floatArrayOf(8f, 8f), 0f)
+ }
+ private val regionLabelPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
+ color = 0xFF9AA3B5.toInt()
+ textSize = 22f
+ isFakeBoldText = true
+ letterSpacing = 0.12f
+ }
+ private val regionLinePaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
+ style = Paint.Style.STROKE
+ color = 0xFFD8DDE8.toInt()
+ strokeWidth = 2f
+ pathEffect = DashPathEffect(floatArrayOf(2f, 8f), 0f)
+ }
+ private val solutionTint = Paint().apply { color = 0x06003C8F }
+ private val questionTextPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
+ color = 0xFF222838.toInt()
+ textSize = 34f
+ }
+ private val textObjPaint = Paint(Paint.ANTI_ALIAS_FLAG)
+ private val questionMediaPaint = Paint(Paint.FILTER_BITMAP_FLAG)
+ /** Decoded question media (imported image / PDF crop), keyed by path. */
+ private val questionMediaCache = HashMap()
+
+ init {
+ setLayerType(LAYER_TYPE_HARDWARE, null)
+ }
+
+ // ================= public API =================
+
+ /** Load a page. ONLY this page's strokes are ever held by the view. */
+ fun setPage(
+ pageId: String,
+ width: Float,
+ height: Float,
+ template: PageTemplate,
+ strokes: List,
+ questions: List,
+ pdfBackground: Bitmap?,
+ textObjects: List = emptyList(),
+ paperColor: Int = com.inkproof.app.model.PaperColors.WHITE
+ ) {
+ this.pageId = pageId
+ this.pageWidth = width
+ this.pageHeight = height
+ this.template = template
+ this.paperColor = paperColor
+ this.questions = questions
+ this.pdfBackground = pdfBackground
+ this.textObjects = textObjects
+ this.strokes.clear()
+ this.strokes.addAll(strokes)
+ clearSelectionInternal()
+ activePoints.clear()
+ snappedShape = null
+ drawing = false
+ pictureDirty = true
+ if (handoffPageId == pageId) {
+ // Seamless continuation of a continuous scroll: keep zoom and
+ // horizontal position, shift vertically by exactly one page.
+ camera.set(camera.scale, camera.offsetX, handoffOffsetY)
+ handoffPageId = null
+ } else if (width > 0 && this.width > 0) {
+ handoffPageId = null
+ camera.fitPage(width, height, this.width.toFloat(), this.height.toFloat())
+ }
+ // Stale until the host provides the new page's neighbors.
+ neighborAbove = null
+ neighborBelow = null
+ neighborAbovePicture = null
+ neighborBelowPicture = null
+ invalidate()
+ }
+
+ fun setQuestions(questions: List) {
+ this.questions = questions
+ invalidate()
+ }
+
+ fun setTextObjects(objects: List) {
+ this.textObjects = objects
+ pictureDirty = true
+ invalidate()
+ }
+
+ fun allStrokes(): List = strokes.toList()
+
+ /** Apply external mutations (undo/redo, paste) without a full reload. */
+ fun applyAdd(added: List) {
+ strokes.addAll(added)
+ pictureDirty = true
+ invalidate()
+ }
+
+ fun applyRemove(removed: List) {
+ val ids = removed.mapTo(HashSet()) { it.id }
+ strokes.removeAll { it.id in ids }
+ selection.removeAll { it.id in ids }
+ if (selection.isEmpty()) clearSelectionInternal()
+ pictureDirty = true
+ invalidate()
+ }
+
+ fun applyReplace(after: List) {
+ val byId = after.associateBy { it.id }
+ for (i in strokes.indices) {
+ byId[strokes[i].id]?.let { strokes[i] = it }
+ }
+ pictureDirty = true
+ invalidate()
+ }
+
+ fun currentSelection(): List = selection.toList()
+
+ fun clearSelection() {
+ clearSelectionInternal()
+ listener?.onSelectionChanged(emptyList(), null)
+ invalidate()
+ }
+
+ fun selectionScreenBounds(): RectF? = selectionBoundsPage?.let { pageRectToScreen(it) }
+
+ fun zoomToFit() {
+ camera.fitPage(pageWidth, pageHeight, width.toFloat(), height.toFloat())
+ listener?.onCameraChanged(camera.scale)
+ invalidate()
+ }
+
+ fun cameraScale(): Float = camera.scale
+
+ // ================= layout =================
+
+ override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
+ super.onSizeChanged(w, h, oldw, oldh)
+ if (oldw == 0 && oldh == 0) {
+ camera.fitPage(pageWidth, pageHeight, w.toFloat(), h.toFloat())
+ }
+ }
+
+ // ================= input =================
+
+ override fun onHoverEvent(event: MotionEvent): Boolean {
+ if (event.getToolType(0) == MotionEvent.TOOL_TYPE_STYLUS ||
+ event.getToolType(0) == MotionEvent.TOOL_TYPE_ERASER
+ ) {
+ trackStylusButton(event)
+ }
+ when (event.actionMasked) {
+ MotionEvent.ACTION_HOVER_ENTER, MotionEvent.ACTION_HOVER_MOVE -> {
+ hovering = true
+ hoverX = event.x
+ hoverY = event.y
+ if (event.getToolType(0) == MotionEvent.TOOL_TYPE_STYLUS ||
+ event.getToolType(0) == MotionEvent.TOOL_TYPE_ERASER
+ ) {
+ lastStylusContact = SystemClock.uptimeMillis()
+ }
+ invalidate()
+ }
+ MotionEvent.ACTION_HOVER_EXIT -> {
+ hovering = false
+ invalidate()
+ }
+ }
+ return true
+ }
+
+ override fun onTouchEvent(event: MotionEvent): Boolean {
+ val action = event.actionMasked
+ val index = event.actionIndex
+ val toolType = event.getToolType(index)
+ val isStylus = toolType == MotionEvent.TOOL_TYPE_STYLUS ||
+ toolType == MotionEvent.TOOL_TYPE_ERASER
+
+ if (isStylus) {
+ lastStylusContact = SystemClock.uptimeMillis()
+ trackStylusButton(event)
+ }
+
+ when (action) {
+ MotionEvent.ACTION_DOWN -> {
+ if (isStylus || (fingerWritingEnabled && !stylusRecentlyActive())) {
+ // Low-latency: deliver every input sample immediately.
+ requestUnbufferedDispatch(event)
+ beginStylusGesture(event, index, toolType)
+ } else {
+ beginFingerGesture(event, index)
+ }
+ }
+
+ MotionEvent.ACTION_POINTER_DOWN -> {
+ if (drawing || lassoActive || draggingSelection || resizingSelection) {
+ // Palm or extra finger while the pen is working: ignore it.
+ return true
+ }
+ if (isStylus) {
+ // Stylus lands while fingers were navigating: stylus wins.
+ cancelNavigation()
+ beginStylusGesture(event, index, toolType)
+ } else if (navigating) {
+ navPointerId2 = event.getPointerId(index)
+ }
+ }
+
+ MotionEvent.ACTION_MOVE -> {
+ when {
+ drawing -> extendActiveStroke(event)
+ lassoActive -> extendLasso(event)
+ resizingSelection -> resizeSelection(event)
+ draggingSelection -> moveSelection(event)
+ navigating -> {
+ scaleDetector.onTouchEvent(event)
+ panWithFingers(event)
+ }
+ }
+ }
+
+ MotionEvent.ACTION_POINTER_UP -> {
+ val pid = event.getPointerId(index)
+ if (pid == navPointerId2) navPointerId2 = -1
+ if (pid == navPointerId1) {
+ navPointerId1 = navPointerId2
+ navPointerId2 = -1
+ if (navPointerId1 != -1) {
+ val i = event.findPointerIndex(navPointerId1)
+ if (i != -1) { lastNavX = event.getX(i); lastNavY = event.getY(i) }
+ }
+ }
+ if (pid == activePointerId) finishActiveGesture(event, cancelled = false)
+ }
+
+ MotionEvent.ACTION_UP -> {
+ if (navigating) scaleDetector.onTouchEvent(event)
+ finishActiveGesture(event, cancelled = false)
+ cancelNavigation()
+ }
+
+ MotionEvent.ACTION_CANCEL -> {
+ finishActiveGesture(event, cancelled = true)
+ cancelNavigation()
+ }
+ }
+ return true
+ }
+
+ private fun stylusRecentlyActive(): Boolean =
+ SystemClock.uptimeMillis() - lastStylusContact < 400
+
+ // ----- stylus gestures -----
+
+ private fun beginStylusGesture(event: MotionEvent, index: Int, toolType: Int) {
+ val px = camera.screenToPageX(event.getX(index))
+ val py = camera.screenToPageY(event.getY(index))
+ activePointerId = event.getPointerId(index)
+
+ // Hardware eraser end or primary stylus button -> eraser.
+ val buttonEraser = (event.buttonState and MotionEvent.BUTTON_STYLUS_PRIMARY) != 0
+ val tool = when {
+ toolType == MotionEvent.TOOL_TYPE_ERASER || buttonEraser -> ToolType.ERASER
+ else -> penStyle.tool
+ }
+ activeToolOverride = tool
+
+ // Grabbing the corner handle starts a resize; tapping inside an
+ // existing selection starts a move.
+ val sel = selectionBoundsPage
+ if (selection.isNotEmpty() && sel != null && tool != ToolType.ERASER) {
+ if (nearResizeHandle(px, py, sel)) {
+ resizingSelection = true
+ resizeOrigBounds.set(sel)
+ selectionBefore = selection.toList()
+ return
+ }
+ if (sel.contains(px, py)) {
+ draggingSelection = true
+ dragStartX = px
+ dragStartY = py
+ dragDX = 0f
+ dragDY = 0f
+ selectionBefore = selection.toList()
+ return
+ }
+ }
+ if (selection.isNotEmpty()) {
+ clearSelection()
+ }
+
+ when (tool) {
+ ToolType.ERASER -> {
+ drawing = true
+ erasedThisGesture.clear()
+ eraseAt(px, py)
+ }
+ ToolType.LASSO -> {
+ lassoActive = true
+ lassoPoints.clear()
+ lassoPoints.add(StrokePoint(px, py, 1f, 0))
+ }
+ ToolType.PAN -> {
+ navigating = true
+ navPointerId1 = activePointerId
+ lastNavX = event.getX(index)
+ lastNavY = event.getY(index)
+ }
+ ToolType.TEXT -> {
+ textTapPending = true
+ textTapX = px
+ textTapY = py
+ }
+ else -> {
+ drawing = true
+ activePoints.clear()
+ activeStartUptime = event.eventTime
+ lastSignificantMove = SystemClock.uptimeMillis()
+ snappedShape = null
+ stabilizer.reset()
+ stabilizer.filter(px, py)
+ activePoints.add(
+ StrokePoint(px, py, event.getPressure(index).coerceIn(0.05f, 1.5f), 0)
+ )
+ scheduleHoldCheck()
+ }
+ }
+ invalidate()
+ }
+
+ private fun extendActiveStroke(event: MotionEvent) {
+ val pointerIndex = event.findPointerIndex(activePointerId)
+ if (pointerIndex == -1) return
+
+ if (activeToolOverride == ToolType.ERASER) {
+ for (h in 0 until event.historySize) {
+ eraseAt(
+ camera.screenToPageX(event.getHistoricalX(pointerIndex, h)),
+ camera.screenToPageY(event.getHistoricalY(pointerIndex, h))
+ )
+ }
+ eraseAt(
+ camera.screenToPageX(event.getX(pointerIndex)),
+ camera.screenToPageY(event.getY(pointerIndex))
+ )
+ invalidate()
+ return
+ }
+
+ // Append every batched historical sample — no point skipping.
+ val t0 = activeStartUptime
+ var moved = false
+ for (h in 0 until event.historySize) {
+ moved = appendPoint(
+ camera.screenToPageX(event.getHistoricalX(pointerIndex, h)),
+ camera.screenToPageY(event.getHistoricalY(pointerIndex, h)),
+ event.getHistoricalPressure(pointerIndex, h),
+ event.getHistoricalEventTime(h) - t0
+ ) || moved
+ }
+ moved = appendPoint(
+ camera.screenToPageX(event.getX(pointerIndex)),
+ camera.screenToPageY(event.getY(pointerIndex)),
+ event.getPressure(pointerIndex),
+ event.eventTime - t0
+ ) || moved
+
+ if (moved) {
+ lastSignificantMove = SystemClock.uptimeMillis()
+ if (snappedShape != null) {
+ // User kept drawing after a snap preview: revert to raw ink.
+ snappedShape = null
+ }
+ scheduleHoldCheck()
+ }
+ invalidate()
+ }
+
+ /** Returns true when the sample represents significant movement. */
+ private fun appendPoint(px: Float, py: Float, pressure: Float, t: Long): Boolean {
+ val last = activePoints.lastOrNull()
+ // Shapes and the lasso want raw geometry; ink gets stabilized.
+ val p = if (activeToolOverride == ToolType.PEN ||
+ activeToolOverride == ToolType.HIGHLIGHTER
+ ) stabilizer.filter(px, py) else floatArrayOf(px, py)
+ activePoints.add(StrokePoint(p[0], p[1], pressure.coerceIn(0.05f, 1.5f), t))
+ if (last == null) return true
+ return hypot(px - last.x, py - last.y) > 2.5f / camera.scale
+ }
+
+ private fun finishActiveGesture(event: MotionEvent, cancelled: Boolean) {
+ removeCallbacks(holdCheck)
+ when {
+ textTapPending -> {
+ textTapPending = false
+ if (!cancelled) {
+ listener?.onTextTap(textTapX, textTapY, hitTextObject(textTapX, textTapY))
+ }
+ }
+
+ resizingSelection -> {
+ resizingSelection = false
+ if (!cancelled && selectionBefore.isNotEmpty()) {
+ val after = selection.toList()
+ listener?.onStrokesMoved(selectionBefore, after)
+ listener?.onSelectionChanged(after, selectionScreenBounds())
+ }
+ }
+
+ draggingSelection -> {
+ draggingSelection = false
+ if (!cancelled && (abs(dragDX) > 0.5f || abs(dragDY) > 0.5f)) {
+ val after = selection.toList()
+ listener?.onStrokesMoved(selectionBefore, after)
+ listener?.onSelectionChanged(after, selectionScreenBounds())
+ }
+ }
+
+ drawing && activeToolOverride == ToolType.ERASER -> {
+ drawing = false
+ if (erasedThisGesture.isNotEmpty()) {
+ listener?.onStrokesErased(erasedThisGesture.toList())
+ erasedThisGesture.clear()
+ }
+ }
+
+ drawing -> {
+ drawing = false
+ if (!cancelled) commitActiveStroke()
+ activePoints.clear()
+ snappedShape = null
+ }
+
+ lassoActive -> {
+ lassoActive = false
+ if (!cancelled) completeLasso()
+ lassoPoints.clear()
+ }
+ }
+ activePointerId = -1
+ activeToolOverride = null
+ invalidate()
+ }
+
+ private fun commitActiveStroke() {
+ if (activePoints.isEmpty() || pageId.isEmpty()) return
+ // Explicit SHAPE tool: the drag start/end define the chosen shape.
+ if (activeToolOverride == ToolType.SHAPE && activePoints.size >= 2) {
+ val first = activePoints.first()
+ val last = activePoints.last()
+ if (hypot(last.x - first.x, last.y - first.y) >= 8f) {
+ val shapeStroke = Stroke(
+ pageId = pageId,
+ tool = ToolType.PEN,
+ color = penStyle.color,
+ baseWidth = penStyle.baseWidth,
+ points = ShapeFactory.create(activeShapeKind, first.x, first.y, last.x, last.y),
+ shapeType = activeShapeKind
+ )
+ val classified = classifyByRegion(shapeStroke)
+ strokes.add(classified)
+ pictureDirty = true
+ listener?.onStrokeCommitted(classified)
+ }
+ return
+ }
+ val snap = snappedShape
+ val stroke = if (snap != null) {
+ Stroke(
+ pageId = pageId,
+ tool = ToolType.PEN,
+ color = penStyle.color,
+ baseWidth = penStyle.baseWidth,
+ points = snap.points,
+ shapeType = snap.type
+ )
+ } else {
+ // Endpoint fidelity: the stroke must end exactly where the pen
+ // lifted, even when stabilization trailed slightly behind.
+ val pts = activePoints.toMutableList()
+ if (stabilizer.level != StrokeStabilizer.Level.OFF && pts.size >= 2 &&
+ (penStyle.tool == ToolType.PEN || penStyle.tool == ToolType.HIGHLIGHTER)
+ ) {
+ val tail = pts.last()
+ pts[pts.size - 1] =
+ tail.copy(x = stabilizer.lastRawX, y = stabilizer.lastRawY)
+ }
+ Stroke(
+ pageId = pageId,
+ tool = penStyle.tool,
+ color = penStyle.color,
+ baseWidth = penStyle.baseWidth,
+ points = pts
+ )
+ }
+ val classified = classifyByRegion(stroke)
+ strokes.add(classified)
+ pictureDirty = true
+ listener?.onStrokeCommitted(classified)
+ }
+
+ /** Tag strokes with the question whose region contains them. */
+ private fun classifyByRegion(stroke: Stroke): Stroke {
+ if (questions.isEmpty()) return stroke
+ val b = stroke.bounds()
+ for (q in questions) {
+ if (b.centerY >= q.solutionTop && b.centerY <= q.solutionBottom) {
+ return stroke.copy(questionId = q.id, role = StrokeRole.SOLUTION)
+ }
+ if (b.centerY >= q.questionTop && b.centerY < q.questionBottom) {
+ return stroke.copy(questionId = q.id, role = StrokeRole.QUESTION)
+ }
+ }
+ return stroke
+ }
+
+ // ----- hold-to-shape -----
+
+ private fun scheduleHoldCheck() {
+ removeCallbacks(holdCheck)
+ postDelayed(holdCheck, holdToShapeMs)
+ }
+
+ private fun maybeSnapShape() {
+ if (!drawing || activeToolOverride == ToolType.ERASER) return
+ // Hold-to-shape applies to freehand PEN ink only; the SHAPE tool
+ // draws the chosen shape explicitly.
+ if (penStyle.tool != ToolType.PEN || activeToolOverride == ToolType.SHAPE) return
+ val still = SystemClock.uptimeMillis() - lastSignificantMove >= holdToShapeMs - 30
+ if (!still || activePoints.size < 8) return
+ val detected = ShapeDetector.detect(activePoints)
+ if (detected != null) {
+ snappedShape = detected
+ performHapticFeedback(HapticFeedbackConstants.CLOCK_TICK)
+ invalidate()
+ }
+ }
+
+ // ----- eraser -----
+
+ private fun eraseAt(px: Float, py: Float) {
+ val r = eraserRadiusPage
+ var removedAny = false
+ val iterator = strokes.listIterator(strokes.size)
+ // Iterate from top-most stroke down.
+ while (iterator.hasPrevious()) {
+ val s = iterator.previous()
+ val b = s.bounds()
+ val reach = r + s.baseWidth / 2f
+ if (px < b.left - reach || px > b.right + reach ||
+ py < b.top - reach || py > b.bottom + reach
+ ) continue
+ // Segment-accurate: snapped shapes (2-point lines, sparse corner
+ // polygons) are erasable anywhere along their edges.
+ if (StrokeHitTester.hits(s, px, py, r)) {
+ iterator.remove()
+ erasedThisGesture.add(s)
+ removedAny = true
+ }
+ }
+ if (removedAny) {
+ pictureDirty = true
+ invalidate()
+ }
+ }
+
+ // ----- lasso -----
+
+ private fun extendLasso(event: MotionEvent) {
+ val pointerIndex = event.findPointerIndex(activePointerId)
+ if (pointerIndex == -1) return
+ val px = camera.screenToPageX(event.getX(pointerIndex))
+ val py = camera.screenToPageY(event.getY(pointerIndex))
+ val last = lassoPoints.lastOrNull()
+ if (last == null || hypot(px - last.x, py - last.y) > 3f / camera.scale) {
+ lassoPoints.add(StrokePoint(px, py, 1f, 0))
+ invalidate()
+ }
+ }
+
+ private fun completeLasso() {
+ if (lassoPoints.size < 3) return
+ val polyX = FloatArray(lassoPoints.size) { lassoPoints[it].x }
+ val polyY = FloatArray(lassoPoints.size) { lassoPoints[it].y }
+ selection.clear()
+ for (s in strokes) {
+ var inside = 0
+ val step = (s.points.size / 16).coerceAtLeast(1)
+ var sampled = 0
+ var i = 0
+ while (i < s.points.size) {
+ val p = s.points[i]
+ if (pointInPolygon(p.x, p.y, polyX, polyY)) inside++
+ sampled++
+ i += step
+ }
+ if (sampled > 0 && inside >= (sampled + 1) / 2) selection.add(s)
+ }
+ if (selection.isEmpty()) {
+ clearSelectionInternal()
+ listener?.onSelectionChanged(emptyList(), null)
+ } else {
+ var bounds: RectF? = null
+ for (s in selection) {
+ val b = s.bounds()
+ val r = RectF(b.left, b.top, b.right, b.bottom)
+ if (bounds == null) bounds = r else bounds.union(r)
+ }
+ bounds?.inset(-16f, -16f)
+ selectionBoundsPage = bounds
+ listener?.onSelectionChanged(selection.toList(), selectionScreenBounds())
+ }
+ }
+
+ private fun moveSelection(event: MotionEvent) {
+ val pointerIndex = event.findPointerIndex(activePointerId)
+ if (pointerIndex == -1) return
+ val px = camera.screenToPageX(event.getX(pointerIndex))
+ val py = camera.screenToPageY(event.getY(pointerIndex))
+ val dx = px - dragStartX - dragDX
+ val dy = py - dragStartY - dragDY
+ dragDX += dx
+ dragDY += dy
+ if (dx == 0f && dy == 0f) return
+
+ val ids = selection.mapTo(HashSet()) { it.id }
+ for (i in strokes.indices) {
+ if (strokes[i].id in ids) {
+ strokes[i] = strokes[i].translated(dx, dy)
+ }
+ }
+ for (i in selection.indices) {
+ selection[i] = selection[i].translated(dx, dy)
+ }
+ selectionBoundsPage?.offset(dx, dy)
+ pictureDirty = true
+ invalidate()
+ }
+
+ // ----- selection resize -----
+
+ private fun nearResizeHandle(px: Float, py: Float, sel: RectF): Boolean {
+ val grab = 26f / camera.scale
+ return hypot(px - sel.right, py - sel.bottom) <= grab
+ }
+
+ private fun resizeSelection(event: MotionEvent) {
+ val pointerIndex = event.findPointerIndex(activePointerId)
+ if (pointerIndex == -1 && event.pointerCount > 0) return
+ val i = if (pointerIndex == -1) 0 else pointerIndex
+ val px = camera.screenToPageX(event.getX(i))
+ val py = camera.screenToPageY(event.getY(i))
+ val orig = resizeOrigBounds
+ if (orig.width() < 1f || orig.height() < 1f) return
+ val sx = ((px - orig.left) / orig.width()).coerceIn(0.05f, 20f)
+ val sy = ((py - orig.top) / orig.height()).coerceIn(0.05f, 20f)
+
+ // Always scale from the ORIGINAL strokes to avoid cumulative drift.
+ val scaled = selectionBefore.map { it.scaled(sx, sy, orig.left, orig.top) }
+ val byId = scaled.associateBy { it.id }
+ for (j in strokes.indices) {
+ byId[strokes[j].id]?.let { strokes[j] = it }
+ }
+ selection.clear()
+ selection.addAll(scaled)
+ selectionBoundsPage = RectF(
+ orig.left, orig.top,
+ orig.left + orig.width() * sx,
+ orig.top + orig.height() * sy
+ )
+ pictureDirty = true
+ invalidate()
+ }
+
+ /** Delete the current selection (invoked from the contextual menu). */
+ fun deleteSelection() {
+ if (selection.isEmpty()) return
+ val removed = selection.toList()
+ applyRemove(removed)
+ listener?.onStrokesErased(removed)
+ clearSelection()
+ }
+
+ fun recolorSelection(color: Int) {
+ if (selection.isEmpty()) return
+ val before = selection.toList()
+ val after = before.map { it.copy(color = color) }
+ for (i in selection.indices) selection[i] = after[i]
+ applyReplace(after)
+ listener?.onStrokesMoved(before, after)
+ }
+
+ fun setSelectionWidth(width: Float) {
+ if (selection.isEmpty()) return
+ val before = selection.toList()
+ val after = before.map { it.copy(baseWidth = width) }
+ for (i in selection.indices) selection[i] = after[i]
+ applyReplace(after)
+ listener?.onStrokesMoved(before, after)
+ }
+
+ private fun clearSelectionInternal() {
+ selection.clear()
+ selectionBoundsPage = null
+ draggingSelection = false
+ }
+
+ // ----- finger navigation -----
+
+ private fun beginFingerGesture(event: MotionEvent, index: Int) {
+ if (stylusRecentlyActive() && !drawing) {
+ // Likely a resting palm: ignore navigation to avoid page jumps.
+ return
+ }
+ if (drawing || lassoActive) return
+
+ val px = camera.screenToPageX(event.getX(index))
+ val py = camera.screenToPageY(event.getY(index))
+ val sel = selectionBoundsPage
+ if (selection.isNotEmpty() && sel != null && sel.contains(px, py)) {
+ activePointerId = event.getPointerId(index)
+ draggingSelection = true
+ dragStartX = px
+ dragStartY = py
+ dragDX = 0f
+ dragDY = 0f
+ selectionBefore = selection.toList()
+ return
+ }
+
+ navigating = true
+ navPointerId1 = event.getPointerId(index)
+ lastNavX = event.getX(index)
+ lastNavY = event.getY(index)
+ scaleDetector.onTouchEvent(event)
+ }
+
+ private fun panWithFingers(event: MotionEvent) {
+ val i = event.findPointerIndex(navPointerId1)
+ if (i == -1) return
+ if (scaleDetector.isInProgress) {
+ // Pinch handles both zoom and its own focal panning.
+ val fx = scaleDetector.focusX
+ val fy = scaleDetector.focusY
+ camera.panBy(fx - lastNavX, fy - lastNavY)
+ lastNavX = fx
+ lastNavY = fy
+ } else {
+ val x = event.getX(i)
+ val y = event.getY(i)
+ camera.panBy(x - lastNavX, y - lastNavY)
+ lastNavX = x
+ lastNavY = y
+ }
+ maybeScrollToNeighbor()
+ invalidate()
+ }
+
+ private fun cancelNavigation() {
+ navigating = false
+ navPointerId1 = -1
+ navPointerId2 = -1
+ }
+
+ // ================= rendering =================
+
+ override fun onDraw(canvas: Canvas) {
+ canvas.drawRect(0f, 0f, width.toFloat(), height.toFloat(), backgroundPaint)
+
+ canvas.save()
+ canvas.concat(camera.matrix())
+
+ // 0. Neighbor pages (read-only) for continuous vertical scrolling.
+ neighborAbovePicture?.let { pic ->
+ val above = neighborAbove ?: return@let
+ canvas.save()
+ canvas.translate(0f, -(above.height + pageGap))
+ canvas.drawPicture(pic)
+ canvas.restore()
+ }
+ neighborBelowPicture?.let { pic ->
+ canvas.save()
+ canvas.translate(0f, pageHeight + pageGap)
+ canvas.drawPicture(pic)
+ canvas.restore()
+ }
+
+ // 1. Page background + template (paper color is per-page)
+ TemplateRenderer.draw(canvas, template, pageWidth, pageHeight, paperColor)
+ pdfBackground?.let {
+ canvas.drawBitmap(it, null, RectF(0f, 0f, pageWidth, pageHeight), null)
+ }
+
+ // 2. Question region guides (subtle, page-space)
+ drawQuestionRegions(canvas)
+
+ // 3. Committed strokes via display list (rebuilt only on change)
+ if (pictureDirty || committedPicture == null) {
+ rebuildPicture()
+ }
+ committedPicture?.let { canvas.drawPicture(it) }
+
+ // 4. Active stroke — immediate, nothing between stylus and pixels
+ if (drawing && activeToolOverride != ToolType.ERASER && activePoints.isNotEmpty()) {
+ val snap = snappedShape
+ if (activeToolOverride == ToolType.SHAPE && activePoints.size >= 2) {
+ // Live preview of the explicit shape being dragged out.
+ val first = activePoints.first()
+ val last = activePoints.last()
+ StrokeRenderer.draw(
+ canvas,
+ Stroke(
+ pageId = pageId,
+ tool = ToolType.PEN,
+ color = penStyle.color,
+ baseWidth = penStyle.baseWidth,
+ points = ShapeFactory.create(
+ activeShapeKind, first.x, first.y, last.x, last.y
+ ),
+ shapeType = activeShapeKind
+ )
+ )
+ } else if (snap != null) {
+ val preview = Stroke(
+ pageId = pageId,
+ tool = ToolType.PEN,
+ color = penStyle.color,
+ baseWidth = penStyle.baseWidth,
+ points = snap.points,
+ shapeType = snap.type
+ )
+ StrokeRenderer.draw(canvas, preview)
+ // Subtle hold feedback: dashed hint around the snapped shape.
+ val b = preview.bounds()
+ canvas.drawRoundRect(
+ RectF(b.left - 12f, b.top - 12f, b.right + 12f, b.bottom + 12f),
+ 10f, 10f, snapHintPaint
+ )
+ } else {
+ StrokeRenderer.draw(
+ canvas,
+ Stroke(
+ pageId = pageId,
+ tool = penStyle.tool,
+ color = penStyle.color,
+ baseWidth = penStyle.baseWidth,
+ points = activePoints
+ )
+ )
+ }
+ }
+
+ // 5. Lasso in progress
+ if (lassoActive && lassoPoints.size > 1) {
+ canvas.drawPath(StrokeRenderer.centerlinePath(lassoPoints), lassoPaint)
+ }
+
+ // 6. Selection highlight + corner resize handle
+ selectionBoundsPage?.let { b ->
+ canvas.drawRoundRect(b, 12f, 12f, selectionFill)
+ canvas.drawRoundRect(b, 12f, 12f, selectionStroke)
+ val handleR = 9f / camera.scale
+ canvas.drawCircle(b.right, b.bottom, handleR, resizeHandlePaint)
+ canvas.drawCircle(b.right, b.bottom, handleR, resizeHandleRing)
+ }
+
+ canvas.restore()
+
+ // 7. Hover cursor (screen space)
+ if (hovering && !drawing) {
+ val radius = when (penStyle.tool) {
+ ToolType.ERASER -> eraserRadiusPage * camera.scale
+ else -> (penStyle.baseWidth * camera.scale / 2f).coerceAtLeast(3f)
+ }
+ canvas.drawCircle(hoverX, hoverY, radius, hoverPaint)
+ }
+ }
+
+ private fun rebuildPicture() {
+ val picture = Picture()
+ val c = picture.beginRecording(pageWidth.toInt() + 1, pageHeight.toInt() + 1)
+ for (t in textObjects) {
+ textObjPaint.textSize = t.fontSize
+ textObjPaint.color = t.color
+ drawWrappedText(c, t.text, t.x, t.y, t.widthPts, textObjPaint)
+ }
+ for (s in strokes) {
+ StrokeRenderer.draw(c, s)
+ }
+ picture.endRecording()
+ committedPicture = picture
+ pictureDirty = false
+ }
+
+ // ----- text objects -----
+
+ private fun hitTextObject(px: Float, py: Float): TextObject? =
+ textObjects.lastOrNull { t ->
+ val height = estimateTextHeight(t)
+ px >= t.x - 8f && px <= t.x + t.widthPts + 8f &&
+ py >= t.y - t.fontSize - 8f && py <= t.y - t.fontSize + height + 8f
+ }
+
+ private fun estimateTextHeight(t: TextObject): Float {
+ textObjPaint.textSize = t.fontSize
+ var lines = 0
+ for (raw in t.text.split('\n')) {
+ val w = textObjPaint.measureText(raw.ifEmpty { " " })
+ lines += ceil((w / t.widthPts).toDouble()).toInt().coerceAtLeast(1)
+ }
+ return lines * t.fontSize * 1.3f + t.fontSize * 0.4f
+ }
+
+ private fun drawQuestionRegions(canvas: Canvas) {
+ if (questions.isEmpty()) return
+ for ((index, q) in questions.withIndex()) {
+ // Divider above the question block.
+ canvas.drawLine(24f, q.questionTop, pageWidth - 24f, q.questionTop, regionLinePaint)
+ canvas.drawText("QUESTION ${index + 1}", 32f, q.questionTop + 30f, regionLabelPaint)
+ // Typed/pasted question statements are rendered on the page.
+ val text = q.typedText
+ if (!text.isNullOrBlank()) {
+ drawWrappedText(canvas, text, 36f, q.questionTop + 78f, pageWidth - 72f, questionTextPaint)
+ }
+ // Imported image / PDF-page question statements.
+ val media = q.mediaPath
+ if (!media.isNullOrBlank()) {
+ val bmp = questionMediaCache.getOrPut(media) {
+ runCatching { BitmapFactory.decodeFile(media) }.getOrNull()
+ }
+ if (bmp != null && bmp.width > 0) {
+ val availW = pageWidth - 72f
+ val availH = (q.questionBottom - q.questionTop - 90f)
+ .coerceAtLeast(40f)
+ val scale = minOf(availW / bmp.width, availH / bmp.height)
+ val dst = RectF(
+ 36f, q.questionTop + 48f,
+ 36f + bmp.width * scale,
+ q.questionTop + 48f + bmp.height * scale
+ )
+ canvas.drawBitmap(bmp, null, dst, questionMediaPaint)
+ }
+ }
+ // Solution band tint + label.
+ canvas.drawRect(0f, q.solutionTop, pageWidth, q.solutionBottom, solutionTint)
+ canvas.drawLine(24f, q.solutionTop, pageWidth - 24f, q.solutionTop, regionLinePaint)
+ canvas.drawText("YOUR SOLUTION", 32f, q.solutionTop + 30f, regionLabelPaint)
+ canvas.drawLine(
+ 24f, q.solutionBottom, pageWidth - 24f, q.solutionBottom, regionLinePaint
+ )
+ }
+ }
+
+ private fun drawWrappedText(
+ canvas: Canvas,
+ text: String,
+ x: Float,
+ y: Float,
+ maxWidth: Float,
+ paint: Paint
+ ) {
+ var cursorY = y
+ for (rawLine in text.split('\n')) {
+ var line = rawLine
+ while (line.isNotEmpty()) {
+ val count = paint.breakText(line, true, maxWidth, null)
+ if (count <= 0) break
+ // Prefer breaking at a space.
+ var cut = count
+ if (count < line.length) {
+ val lastSpace = line.substring(0, count).lastIndexOf(' ')
+ if (lastSpace > count / 2) cut = lastSpace + 1
+ }
+ canvas.drawText(line.substring(0, cut).trimEnd(), x, cursorY, paint)
+ line = line.substring(cut)
+ cursorY += paint.textSize * 1.3f
+ }
+ if (rawLine.isEmpty()) cursorY += paint.textSize * 1.3f
+ }
+ }
+
+ // ----- helpers -----
+
+ private fun pageRectToScreen(r: RectF): RectF = RectF(
+ camera.pageToScreenX(r.left),
+ camera.pageToScreenY(r.top),
+ camera.pageToScreenX(r.right),
+ camera.pageToScreenY(r.bottom)
+ )
+
+ companion object {
+ fun pointInPolygon(x: Float, y: Float, polyX: FloatArray, polyY: FloatArray): Boolean {
+ var inside = false
+ var j = polyX.size - 1
+ for (i in polyX.indices) {
+ if ((polyY[i] > y) != (polyY[j] > y) &&
+ x < (polyX[j] - polyX[i]) * (y - polyY[i]) / (polyY[j] - polyY[i]) + polyX[i]
+ ) {
+ inside = !inside
+ }
+ j = i
+ }
+ return inside
+ }
+ }
+}
diff --git a/app/src/main/java/com/inkproof/app/ink/ShapeDetector.kt b/app/src/main/java/com/inkproof/app/ink/ShapeDetector.kt
new file mode 100644
index 0000000..233bd0e
--- /dev/null
+++ b/app/src/main/java/com/inkproof/app/ink/ShapeDetector.kt
@@ -0,0 +1,341 @@
+package com.inkproof.app.ink
+
+import com.inkproof.app.model.DetectedShape
+import com.inkproof.app.model.ShapeType
+import com.inkproof.app.model.StrokePoint
+import kotlin.math.abs
+import kotlin.math.atan2
+import kotlin.math.cos
+import kotlin.math.hypot
+import kotlin.math.max
+import kotlin.math.min
+import kotlin.math.sin
+
+/**
+ * Pure-geometry shape recognition for DRAW -> HOLD -> SNAP TO SHAPE.
+ *
+ * Runs ONCE when the hold threshold fires — never continuously during
+ * writing. Deterministic and fully unit-tested.
+ */
+object ShapeDetector {
+
+ /**
+ * Minimum stroke size (page units) worth snapping. Deliberately LARGE:
+ * handwritten glyphs (o, x, parentheses, operators) are typically well
+ * under this, so ordinary writing — especially math notation — can
+ * never be mistaken for a shape. False negatives are fine; false
+ * positives are not.
+ */
+ private const val MIN_SIZE = 90f
+
+ /** Overall confidence gate: below this, keep the handwriting. */
+ private const val MIN_CONFIDENCE = 0.72f
+
+ fun detect(points: List): DetectedShape? {
+ if (points.size < 12) return null
+ val b = bounds(points)
+ if (max(b.width, b.height) < MIN_SIZE) return null
+
+ val found = detectArrow(points)
+ ?: detectLine(points)
+ ?: detectCircleOrEllipse(points)
+ ?: detectPolygon(points)
+ ?: return null
+ // Uncertain geometry => DO NOTHING; the ink stays exactly as drawn.
+ return if (found.confidence >= MIN_CONFIDENCE) found else null
+ }
+
+ // ----- arrow -----
+
+ /**
+ * Single-stroke arrow: a dominant straight shaft followed by a short
+ * doubling-back arrowhead near the tip (corners only in the tail).
+ */
+ private fun detectArrow(points: List): DetectedShape? {
+ val n = points.size
+ val corners = findCorners(points)
+ if (corners.isEmpty()) return null
+ val firstCorner = corners.first()
+ // Shaft must dominate the stroke; all corners live in the tail.
+ if (firstCorner < n * 0.55f) return null
+
+ val start = points.first()
+ // The corner finder reports a point slightly inside the turn; the real
+ // tip is the farthest point from the start in the head region (the
+ // barbs double back toward the start, so they are always closer).
+ var tipIndex = firstCorner
+ var tipDist = 0f
+ for (i in (firstCorner - n / 10).coerceAtLeast(0) until n) {
+ val d = hypot(points[i].x - start.x, points[i].y - start.y)
+ if (d > tipDist) {
+ tipDist = d
+ tipIndex = i
+ }
+ }
+ val tip = points[tipIndex]
+ val chord = hypot(tip.x - start.x, tip.y - start.y)
+ if (chord < MIN_SIZE) return null
+
+ val shaft = points.subList(0, minOf(firstCorner, tipIndex) + 1)
+ val maxDev = shaft.maxOf { distanceToSegment(it, start, tip) }
+ if (maxDev > chord * 0.08f + 6f) return null
+
+ // The tail must stay close to the tip (it is the head, not a new edge).
+ val tail = points.subList(firstCorner, n)
+ val headSpan = tail.maxOf { hypot(it.x - tip.x, it.y - tip.y) }
+ if (headSpan > chord * 0.45f || headSpan < chord * 0.07f) return null
+
+ val angle = atan2(tip.y - start.y, tip.x - start.x).toDouble()
+ val headLen = headSpan.coerceIn(chord * 0.12f, chord * 0.3f)
+ val a1 = angle + Math.toRadians(150.0)
+ val a2 = angle - Math.toRadians(150.0)
+ val barb1 = StrokePoint(
+ tip.x + headLen * cos(a1).toFloat(),
+ tip.y + headLen * sin(a1).toFloat(), 0.7f, 2
+ )
+ val barb2 = StrokePoint(
+ tip.x + headLen * cos(a2).toFloat(),
+ tip.y + headLen * sin(a2).toFloat(), 0.7f, 4
+ )
+ return DetectedShape(
+ type = ShapeType.ARROW,
+ points = listOf(
+ StrokePoint(start.x, start.y, 0.7f, 0),
+ StrokePoint(tip.x, tip.y, 0.7f, 1),
+ barb1,
+ StrokePoint(tip.x, tip.y, 0.7f, 3),
+ barb2
+ ),
+ confidence = 0.8f
+ )
+ }
+
+ // ----- line / arrow -----
+
+ private fun detectLine(points: List): DetectedShape? {
+ val first = points.first()
+ val last = points.last()
+ val chord = hypot(last.x - first.x, last.y - first.y)
+ if (chord < MIN_SIZE) return null
+
+ val maxDeviation = points.maxOf { distanceToSegment(it, first, last) }
+ if (maxDeviation > chord * 0.055f + 4f) return null
+
+ val snapped = snapAngle(first, last)
+ return DetectedShape(
+ type = ShapeType.LINE,
+ points = listOf(
+ StrokePoint(first.x, first.y, 0.7f, 0),
+ StrokePoint(snapped.first, snapped.second, 0.7f, 1)
+ ),
+ confidence = 1f - (maxDeviation / (chord + 1f))
+ )
+ }
+
+ /** Snap nearly-horizontal/vertical/45° lines to the exact angle. */
+ private fun snapAngle(first: StrokePoint, last: StrokePoint): Pair {
+ val dx = last.x - first.x
+ val dy = last.y - first.y
+ val len = hypot(dx, dy)
+ val angle = atan2(dy, dx)
+ val step = Math.PI / 4
+ val snappedAngle = (Math.round(angle / step) * step)
+ return if (abs(angle - snappedAngle.toFloat()) < Math.toRadians(7.0).toFloat()) {
+ Pair(
+ first.x + len * cos(snappedAngle).toFloat(),
+ first.y + len * sin(snappedAngle).toFloat()
+ )
+ } else {
+ Pair(last.x, last.y)
+ }
+ }
+
+ // ----- circle / ellipse -----
+
+ private fun detectCircleOrEllipse(points: List): DetectedShape? {
+ val first = points.first()
+ val last = points.last()
+ val b = bounds(points)
+ val size = max(b.width, b.height)
+ // Closed-ish curve?
+ if (hypot(last.x - first.x, last.y - first.y) > size * 0.28f) return null
+
+ val cx = b.centerX
+ val cy = b.centerY
+ val rx = b.width / 2f
+ val ry = b.height / 2f
+ if (rx < MIN_SIZE / 2 || ry < MIN_SIZE / 2) return null
+
+ // Points should hug the fitted ellipse.
+ var err = 0f
+ for (p in points) {
+ val nx = (p.x - cx) / rx
+ val ny = (p.y - cy) / ry
+ err += abs(hypot(nx, ny) - 1f)
+ }
+ err /= points.size
+ if (err > 0.19f) return null
+
+ // Corner-ness check: rectangles also "hug" an ellipse loosely, but
+ // have large flat runs; measure direction-change distribution.
+ if (cornerCount(points) >= 3) return null
+
+ val isCircle = abs(rx - ry) < 0.18f * max(rx, ry)
+ val type = if (isCircle) ShapeType.CIRCLE else ShapeType.ELLIPSE
+ val r = (rx + ry) / 2f
+ val out = ArrayList(65)
+ for (i in 0..64) {
+ val a = 2 * Math.PI * i / 64
+ val px = if (isCircle) cx + r * cos(a).toFloat() else cx + rx * cos(a).toFloat()
+ val py = if (isCircle) cy + r * sin(a).toFloat() else cy + ry * sin(a).toFloat()
+ out.add(StrokePoint(px, py, 0.7f, i.toLong()))
+ }
+ return DetectedShape(type, out, 1f - err)
+ }
+
+ // ----- polygons (triangle / rectangle / square / generic) -----
+
+ private fun detectPolygon(points: List): DetectedShape? {
+ val first = points.first()
+ val last = points.last()
+ val b = bounds(points)
+ val size = max(b.width, b.height)
+ if (hypot(last.x - first.x, last.y - first.y) > size * 0.4f) return null
+
+ val interior = findCorners(points)
+ val window = (points.size / 12).coerceIn(2, 8)
+ val vertices = ArrayList()
+ // The stroke's start/end seam of a closed shape is usually a corner
+ // itself (people start drawing rectangles at a corner) — findCorners
+ // only sees interior indices, so test the seam explicitly.
+ if (seamIsCorner(points, window)) {
+ val seam = points.first()
+ val nearDuplicate = interior.firstOrNull()?.let { idx ->
+ hypot(points[idx].x - seam.x, points[idx].y - seam.y) < size * 0.08f
+ } ?: false
+ if (!nearDuplicate) vertices.add(seam)
+ }
+ interior.mapTo(vertices) { points[it] }
+ // ONLY triangle and rectangle/square are supported polygon snaps.
+ // Anything else (5+ corners, ambiguous quads) stays handwriting —
+ // a generic polygon fallback is exactly how scribbles turn into
+ // "curved garbage", so there is none.
+ return when (vertices.size) {
+ 3 -> DetectedShape(ShapeType.TRIANGLE, closeRing(vertices), 0.85f)
+ 4 -> tryRectangle(vertices, b) // non-rectangular quad => null
+ else -> null
+ }
+ }
+
+ private fun tryRectangle(vertices: List, b: B): DetectedShape? {
+ // Check whether the 4 corners are near the bounding box corners.
+ val boxCorners = listOf(
+ Pair(b.left, b.top), Pair(b.right, b.top),
+ Pair(b.right, b.bottom), Pair(b.left, b.bottom)
+ )
+ val tolerance = 0.22f * max(b.width, b.height)
+ val matched = BooleanArray(4)
+ for (v in vertices) {
+ var bestI = -1
+ var bestD = Float.MAX_VALUE
+ boxCorners.forEachIndexed { i, c ->
+ val d = hypot(v.x - c.first, v.y - c.second)
+ if (d < bestD) { bestD = d; bestI = i }
+ }
+ if (bestD <= tolerance && !matched[bestI]) matched[bestI] = true
+ }
+ if (matched.count { it } < 4) return null
+
+ val isSquare = abs(b.width - b.height) < 0.15f * max(b.width, b.height)
+ val type = if (isSquare) ShapeType.SQUARE else ShapeType.RECTANGLE
+ val (l, t, r, bo) = if (isSquare) {
+ val s = (b.width + b.height) / 2f
+ listOf(b.centerX - s / 2, b.centerY - s / 2, b.centerX + s / 2, b.centerY + s / 2)
+ } else {
+ listOf(b.left, b.top, b.right, b.bottom)
+ }
+ val ring = listOf(
+ StrokePoint(l, t, 0.7f, 0),
+ StrokePoint(r, t, 0.7f, 1),
+ StrokePoint(r, bo, 0.7f, 2),
+ StrokePoint(l, bo, 0.7f, 3)
+ )
+ return DetectedShape(type, closeRing(ring), 0.9f)
+ }
+
+ private fun closeRing(vertices: List): List =
+ vertices + vertices.first().copy(t = vertices.size.toLong())
+
+ // ----- corner detection -----
+
+ internal fun findCorners(points: List): List {
+ val n = points.size
+ if (n < 8) return emptyList()
+ val window = (n / 12).coerceIn(2, 8)
+ val corners = ArrayList()
+ var lastCorner = -window * 2
+ for (i in window until n - window) {
+ val a = points[i - window]
+ val b = points[i]
+ val c = points[i + window]
+ val v1x = b.x - a.x; val v1y = b.y - a.y
+ val v2x = c.x - b.x; val v2y = c.y - b.y
+ val l1 = hypot(v1x, v1y); val l2 = hypot(v2x, v2y)
+ if (l1 < 1e-3 || l2 < 1e-3) continue
+ val dot = (v1x * v2x + v1y * v2y) / (l1 * l2)
+ val angle = Math.acos(dot.coerceIn(-1f, 1f).toDouble())
+ if (angle > Math.toRadians(45.0) && i - lastCorner > window * 2) {
+ corners.add(i)
+ lastCorner = i
+ }
+ }
+ return corners
+ }
+
+ private fun cornerCount(points: List): Int = findCorners(points).size
+
+ /** Is the junction between stroke end and stroke start itself a corner? */
+ private fun seamIsCorner(points: List, window: Int): Boolean {
+ val n = points.size
+ if (n < window * 2 + 2) return false
+ val endA = points[n - 1 - window]
+ val endB = points[n - 1]
+ val startA = points[0]
+ val startB = points[window]
+ var v1x = endB.x - endA.x; var v1y = endB.y - endA.y
+ var v2x = startB.x - startA.x; var v2y = startB.y - startA.y
+ val l1 = hypot(v1x, v1y); val l2 = hypot(v2x, v2y)
+ if (l1 < 1e-3f || l2 < 1e-3f) return false
+ v1x /= l1; v1y /= l1; v2x /= l2; v2y /= l2
+ val dot = (v1x * v2x + v1y * v2y).coerceIn(-1f, 1f)
+ return Math.acos(dot.toDouble()) > Math.toRadians(45.0)
+ }
+
+ // ----- helpers -----
+
+ private data class B(val left: Float, val top: Float, val right: Float, val bottom: Float) {
+ val width get() = right - left
+ val height get() = bottom - top
+ val centerX get() = (left + right) / 2
+ val centerY get() = (top + bottom) / 2
+ }
+
+ private fun bounds(points: List): B {
+ var minX = Float.MAX_VALUE; var minY = Float.MAX_VALUE
+ var maxX = -Float.MAX_VALUE; var maxY = -Float.MAX_VALUE
+ for (p in points) {
+ minX = min(minX, p.x); minY = min(minY, p.y)
+ maxX = max(maxX, p.x); maxY = max(maxY, p.y)
+ }
+ return B(minX, minY, maxX, maxY)
+ }
+
+ private fun distanceToSegment(p: StrokePoint, a: StrokePoint, b: StrokePoint): Float {
+ val dx = b.x - a.x; val dy = b.y - a.y
+ val len2 = dx * dx + dy * dy
+ if (len2 < 1e-6f) return hypot(p.x - a.x, p.y - a.y)
+ var t = ((p.x - a.x) * dx + (p.y - a.y) * dy) / len2
+ t = t.coerceIn(0f, 1f)
+ return hypot(p.x - (a.x + t * dx), p.y - (a.y + t * dy))
+ }
+}
diff --git a/app/src/main/java/com/inkproof/app/ink/ShapeFactory.kt b/app/src/main/java/com/inkproof/app/ink/ShapeFactory.kt
new file mode 100644
index 0000000..a92208c
--- /dev/null
+++ b/app/src/main/java/com/inkproof/app/ink/ShapeFactory.kt
@@ -0,0 +1,86 @@
+package com.inkproof.app.ink
+
+import com.inkproof.app.model.ShapeType
+import com.inkproof.app.model.StrokePoint
+import kotlin.math.abs
+import kotlin.math.atan2
+import kotlin.math.cos
+import kotlin.math.hypot
+import kotlin.math.max
+import kotlin.math.min
+import kotlin.math.sin
+
+/**
+ * Builds clean vector shapes for the explicit SHAPE tool: the user picks a
+ * shape kind, drags from (x0,y0) to (x1,y1), and gets a real editable vector
+ * stroke (movable, resizable, recolorable, erasable, lasso-selectable).
+ */
+object ShapeFactory {
+
+ fun create(kind: ShapeType, x0: Float, y0: Float, x1: Float, y1: Float): List =
+ when (kind) {
+ ShapeType.LINE -> listOf(pt(x0, y0, 0), pt(x1, y1, 1))
+ ShapeType.ARROW -> arrow(x0, y0, x1, y1)
+ ShapeType.RECTANGLE -> rect(x0, y0, x1, y1)
+ ShapeType.SQUARE -> square(x0, y0, x1, y1)
+ ShapeType.ELLIPSE -> ellipse(x0, y0, x1, y1, forceCircle = false)
+ ShapeType.CIRCLE -> ellipse(x0, y0, x1, y1, forceCircle = true)
+ ShapeType.TRIANGLE -> triangle(x0, y0, x1, y1)
+ ShapeType.POLYGON -> rect(x0, y0, x1, y1)
+ }
+
+ private fun pt(x: Float, y: Float, t: Long) = StrokePoint(x, y, 0.7f, t)
+
+ private fun arrow(x0: Float, y0: Float, x1: Float, y1: Float): List {
+ val chord = hypot(x1 - x0, y1 - y0)
+ val head = (chord * 0.22f).coerceIn(14f, 64f)
+ val angle = atan2((y1 - y0).toDouble(), (x1 - x0).toDouble())
+ val a1 = angle + Math.toRadians(150.0)
+ val a2 = angle - Math.toRadians(150.0)
+ return listOf(
+ pt(x0, y0, 0),
+ pt(x1, y1, 1),
+ pt(x1 + head * cos(a1).toFloat(), y1 + head * sin(a1).toFloat(), 2),
+ pt(x1, y1, 3),
+ pt(x1 + head * cos(a2).toFloat(), y1 + head * sin(a2).toFloat(), 4)
+ )
+ }
+
+ private fun rect(x0: Float, y0: Float, x1: Float, y1: Float): List {
+ val l = min(x0, x1); val t = min(y0, y1)
+ val r = max(x0, x1); val b = max(y0, y1)
+ return listOf(pt(l, t, 0), pt(r, t, 1), pt(r, b, 2), pt(l, b, 3), pt(l, t, 4))
+ }
+
+ private fun square(x0: Float, y0: Float, x1: Float, y1: Float): List {
+ val side = max(abs(x1 - x0), abs(y1 - y0))
+ val sx = if (x1 >= x0) 1f else -1f
+ val sy = if (y1 >= y0) 1f else -1f
+ return rect(x0, y0, x0 + side * sx, y0 + side * sy)
+ }
+
+ private fun ellipse(
+ x0: Float, y0: Float, x1: Float, y1: Float, forceCircle: Boolean
+ ): List {
+ val cx = (x0 + x1) / 2f
+ val cy = (y0 + y1) / 2f
+ var rx = abs(x1 - x0) / 2f
+ var ry = abs(y1 - y0) / 2f
+ if (forceCircle) {
+ val r = (rx + ry) / 2f
+ rx = r; ry = r
+ }
+ val n = 48
+ return (0..n).map { i ->
+ val a = i * 2.0 * Math.PI / n
+ pt(cx + rx * cos(a).toFloat(), cy + ry * sin(a).toFloat(), i.toLong())
+ }
+ }
+
+ private fun triangle(x0: Float, y0: Float, x1: Float, y1: Float): List {
+ val l = min(x0, x1); val t = min(y0, y1)
+ val r = max(x0, x1); val b = max(y0, y1)
+ val apexX = (l + r) / 2f
+ return listOf(pt(apexX, t, 0), pt(r, b, 1), pt(l, b, 2), pt(apexX, t, 3))
+ }
+}
diff --git a/app/src/main/java/com/inkproof/app/ink/StrokeHitTester.kt b/app/src/main/java/com/inkproof/app/ink/StrokeHitTester.kt
new file mode 100644
index 0000000..9413bc9
--- /dev/null
+++ b/app/src/main/java/com/inkproof/app/ink/StrokeHitTester.kt
@@ -0,0 +1,43 @@
+package com.inkproof.app.ink
+
+import com.inkproof.app.model.Stroke
+import kotlin.math.hypot
+
+/**
+ * Geometric hit testing for the eraser (and any pointer-vs-stroke test).
+ *
+ * The old implementation only tested distance to stroke POINTS, which made
+ * snapped shapes (a straight line is just 2 points) impossible to erase in
+ * the middle. This tests distance to every SEGMENT of the stroke.
+ */
+object StrokeHitTester {
+
+ /** True when the circle (px, py, radius) touches the rendered stroke. */
+ fun hits(stroke: Stroke, px: Float, py: Float, radius: Float): Boolean {
+ val reach = radius + stroke.baseWidth / 2f
+ val pts = stroke.points
+ if (pts.isEmpty()) return false
+ if (pts.size == 1) {
+ return hypot(pts[0].x - px, pts[0].y - py) <= reach
+ }
+ for (i in 0 until pts.size - 1) {
+ if (distanceToSegment(px, py, pts[i].x, pts[i].y, pts[i + 1].x, pts[i + 1].y) <= reach) {
+ return true
+ }
+ }
+ return false
+ }
+
+ fun distanceToSegment(
+ px: Float, py: Float,
+ ax: Float, ay: Float,
+ bx: Float, by: Float
+ ): Float {
+ val dx = bx - ax
+ val dy = by - ay
+ val lenSq = dx * dx + dy * dy
+ if (lenSq < 1e-6f) return hypot(px - ax, py - ay)
+ val t = (((px - ax) * dx + (py - ay) * dy) / lenSq).coerceIn(0f, 1f)
+ return hypot(px - (ax + t * dx), py - (ay + t * dy))
+ }
+}
diff --git a/app/src/main/java/com/inkproof/app/ink/StrokeRenderer.kt b/app/src/main/java/com/inkproof/app/ink/StrokeRenderer.kt
new file mode 100644
index 0000000..1079a12
--- /dev/null
+++ b/app/src/main/java/com/inkproof/app/ink/StrokeRenderer.kt
@@ -0,0 +1,133 @@
+package com.inkproof.app.ink
+
+import android.graphics.Canvas
+import android.graphics.Paint
+import android.graphics.Path
+import com.inkproof.app.model.Stroke
+import com.inkproof.app.model.StrokePoint
+import com.inkproof.app.model.ToolType
+import kotlin.math.hypot
+
+/**
+ * Renders vector strokes.
+ *
+ * Pen strokes are rendered as a filled, pressure-tapered ribbon so ink looks
+ * like real pen writing. Highlighters are flat translucent strokes.
+ * All geometry is computed in page space — sharp at any zoom.
+ */
+object StrokeRenderer {
+
+ private val fillPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
+ style = Paint.Style.FILL
+ }
+ private val strokePaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
+ style = Paint.Style.STROKE
+ strokeCap = Paint.Cap.ROUND
+ strokeJoin = Paint.Join.ROUND
+ }
+ private val highlighterPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
+ style = Paint.Style.STROKE
+ strokeCap = Paint.Cap.SQUARE
+ strokeJoin = Paint.Join.ROUND
+ }
+
+ fun draw(canvas: Canvas, stroke: Stroke) {
+ if (stroke.points.isEmpty()) return
+ when (stroke.tool) {
+ ToolType.HIGHLIGHTER -> {
+ highlighterPaint.color = stroke.color
+ highlighterPaint.strokeWidth = stroke.baseWidth
+ canvas.drawPath(centerlinePath(stroke.points), highlighterPaint)
+ }
+ else -> {
+ if (stroke.shapeType != null || stroke.points.size < 3) {
+ // Shapes and dots: uniform width centerline.
+ strokePaint.color = stroke.color
+ strokePaint.strokeWidth = stroke.baseWidth
+ if (stroke.points.size == 1) {
+ val p = stroke.points[0]
+ fillPaint.color = stroke.color
+ canvas.drawCircle(p.x, p.y, stroke.baseWidth / 2f, fillPaint)
+ } else {
+ canvas.drawPath(centerlinePath(stroke.points), strokePaint)
+ }
+ } else {
+ fillPaint.color = stroke.color
+ canvas.drawPath(ribbonPath(stroke.points, stroke.baseWidth), fillPaint)
+ }
+ }
+ }
+ }
+
+ /** Smooth centerline through the points using quadratic midpoints. */
+ fun centerlinePath(points: List): Path {
+ val path = Path()
+ if (points.isEmpty()) return path
+ path.moveTo(points[0].x, points[0].y)
+ if (points.size == 1) {
+ path.lineTo(points[0].x + 0.1f, points[0].y)
+ return path
+ }
+ for (i in 1 until points.size - 1) {
+ val midX = (points[i].x + points[i + 1].x) / 2f
+ val midY = (points[i].y + points[i + 1].y) / 2f
+ path.quadTo(points[i].x, points[i].y, midX, midY)
+ }
+ path.lineTo(points.last().x, points.last().y)
+ return path
+ }
+
+ /**
+ * Builds a filled outline whose width follows pressure, producing
+ * natural tapered ink. Pure geometry — unit-testable.
+ */
+ fun ribbonPath(points: List, baseWidth: Float): Path {
+ val n = points.size
+ val half = FloatArray(n)
+ for (i in 0 until n) {
+ val pr = points[i].pressure.coerceIn(0.05f, 1.5f)
+ half[i] = (baseWidth * (0.45f + 0.75f * pr)) / 2f
+ }
+ // Light smoothing of widths to avoid wobble.
+ for (pass in 0 until 2) {
+ for (i in 1 until n - 1) {
+ half[i] = (half[i - 1] + half[i] * 2 + half[i + 1]) / 4f
+ }
+ }
+
+ val leftX = FloatArray(n); val leftY = FloatArray(n)
+ val rightX = FloatArray(n); val rightY = FloatArray(n)
+ for (i in 0 until n) {
+ val prev = points[(i - 1).coerceAtLeast(0)]
+ val next = points[(i + 1).coerceAtMost(n - 1)]
+ var dx = next.x - prev.x
+ var dy = next.y - prev.y
+ val len = hypot(dx, dy)
+ if (len < 1e-4f) { dx = 1f; dy = 0f } else { dx /= len; dy /= len }
+ // Normal
+ val nx = -dy; val ny = dx
+ leftX[i] = points[i].x + nx * half[i]
+ leftY[i] = points[i].y + ny * half[i]
+ rightX[i] = points[i].x - nx * half[i]
+ rightY[i] = points[i].y - ny * half[i]
+ }
+
+ val path = Path()
+ path.moveTo(leftX[0], leftY[0])
+ for (i in 1 until n - 1) {
+ path.quadTo(leftX[i], leftY[i], (leftX[i] + leftX[i + 1]) / 2f, (leftY[i] + leftY[i + 1]) / 2f)
+ }
+ path.lineTo(leftX[n - 1], leftY[n - 1])
+ // Round end cap
+ path.lineTo(rightX[n - 1], rightY[n - 1])
+ for (i in n - 2 downTo 1) {
+ path.quadTo(rightX[i], rightY[i], (rightX[i] + rightX[i - 1]) / 2f, (rightY[i] + rightY[i - 1]) / 2f)
+ }
+ path.lineTo(rightX[0], rightY[0])
+ path.close()
+ // Start/end caps as circles for smooth round ends.
+ path.addCircle(points[0].x, points[0].y, half[0], Path.Direction.CW)
+ path.addCircle(points[n - 1].x, points[n - 1].y, half[n - 1], Path.Direction.CW)
+ return path
+ }
+}
diff --git a/app/src/main/java/com/inkproof/app/ink/StrokeStabilizer.kt b/app/src/main/java/com/inkproof/app/ink/StrokeStabilizer.kt
new file mode 100644
index 0000000..335608e
--- /dev/null
+++ b/app/src/main/java/com/inkproof/app/ink/StrokeStabilizer.kt
@@ -0,0 +1,74 @@
+package com.inkproof.app.ink
+
+import kotlin.math.hypot
+import kotlin.math.min
+
+/**
+ * Real-time handwriting stabilization.
+ *
+ * An adaptive exponential moving average smooths sub-millimetre jitter while
+ * deliberately letting fast, intentional movement through almost unfiltered —
+ * that is what preserves corners and natural handwriting character.
+ *
+ * LATENCY: zero added frames. Every input sample produces an output sample
+ * immediately; smoothing only nudges WHERE the point lands, never WHEN it
+ * appears. The caller preserves the raw final position on stroke completion
+ * so strokes always reach exactly where the pen lifted.
+ */
+class StrokeStabilizer(var level: Level = Level.MEDIUM) {
+
+ enum class Level(
+ /** Base smoothing factor: fraction of the raw sample kept (1 = off). */
+ internal val baseAlpha: Float,
+ /** Travel distance (page units) at which smoothing fully yields. */
+ internal val cornerDistance: Float
+ ) {
+ OFF(1f, 0f),
+ LOW(0.55f, 10f),
+ MEDIUM(0.38f, 14f),
+ HIGH(0.24f, 18f);
+
+ companion object {
+ fun fromName(name: String?): Level =
+ entries.firstOrNull { it.name.equals(name, ignoreCase = true) } ?: MEDIUM
+ }
+ }
+
+ private var hasLast = false
+ private var lastX = 0f
+ private var lastY = 0f
+
+ var lastRawX = 0f
+ private set
+ var lastRawY = 0f
+ private set
+
+ /** Call at every stroke start. */
+ fun reset() {
+ hasLast = false
+ }
+
+ /**
+ * Filter one incoming sample; returns the point to render/store.
+ * The first sample of a stroke always passes through untouched.
+ */
+ fun filter(rawX: Float, rawY: Float): FloatArray {
+ lastRawX = rawX
+ lastRawY = rawY
+ if (level == Level.OFF || !hasLast) {
+ hasLast = true
+ lastX = rawX
+ lastY = rawY
+ return floatArrayOf(rawX, rawY)
+ }
+ val travel = hypot(rawX - lastX, rawY - lastY)
+ // Fast movement (long travel) = intent: let it through (alpha → 1).
+ // Slow movement (short travel) = jitter: smooth it (alpha → base).
+ val passThrough = if (level.cornerDistance <= 0f) 1f
+ else min(1f, travel / level.cornerDistance)
+ val alpha = level.baseAlpha + (1f - level.baseAlpha) * passThrough
+ lastX += (rawX - lastX) * alpha
+ lastY += (rawY - lastY) * alpha
+ return floatArrayOf(lastX, lastY)
+ }
+}
diff --git a/app/src/main/java/com/inkproof/app/ink/StylusDoubleTap.kt b/app/src/main/java/com/inkproof/app/ink/StylusDoubleTap.kt
new file mode 100644
index 0000000..b056005
--- /dev/null
+++ b/app/src/main/java/com/inkproof/app/ink/StylusDoubleTap.kt
@@ -0,0 +1,55 @@
+package com.inkproof.app.ink
+
+import com.inkproof.app.model.ToolType
+
+/**
+ * Detects a stylus-button DOUBLE press from real hardware button events.
+ *
+ * InkProof only reacts to events Android actually delivers
+ * (MotionEvent.BUTTON_STYLUS_PRIMARY / BUTTON_STYLUS_SECONDARY state
+ * transitions, including while hovering). It never fakes the gesture from
+ * screen taps — tapping the page is writing, not a gesture.
+ *
+ * Note for OnePlus Stylo owners: the pencil's "double-tap the barrel"
+ * gesture is handled by OnePlus firmware and is not currently exposed to
+ * third-party apps as a public event. If the OEM maps it to a stylus
+ * button event, this detector picks it up automatically.
+ */
+class StylusDoubleTapDetector(private val windowMs: Long = 600L) {
+
+ private var lastPressAt = Long.MIN_VALUE / 2
+
+ /**
+ * Call on each button press transition (up -> down).
+ * @return true when this press completes a double press.
+ */
+ fun onButtonPress(nowMs: Long): Boolean {
+ val isDouble = nowMs - lastPressAt in 0..windowMs
+ lastPressAt = if (isDouble) Long.MIN_VALUE / 2 else nowMs
+ return isDouble
+ }
+
+ fun reset() {
+ lastPressAt = Long.MIN_VALUE / 2
+ }
+}
+
+/**
+ * Eraser <-> previous-tool toggle. Pure state machine so the exact
+ * restoration rules are unit-tested:
+ * - any tool -> ERASER remembers that tool
+ * - ERASER -> restores the remembered tool
+ * - a remembered ERASER (edge case) falls back to PEN
+ */
+object StylusEraserToggle {
+
+ data class Result(val tool: ToolType, val remembered: ToolType)
+
+ fun toggle(current: ToolType, remembered: ToolType): Result =
+ if (current == ToolType.ERASER) {
+ val restore = if (remembered == ToolType.ERASER) ToolType.PEN else remembered
+ Result(tool = restore, remembered = restore)
+ } else {
+ Result(tool = ToolType.ERASER, remembered = current)
+ }
+}
diff --git a/app/src/main/java/com/inkproof/app/ink/TemplateRenderer.kt b/app/src/main/java/com/inkproof/app/ink/TemplateRenderer.kt
new file mode 100644
index 0000000..85371be
--- /dev/null
+++ b/app/src/main/java/com/inkproof/app/ink/TemplateRenderer.kt
@@ -0,0 +1,146 @@
+package com.inkproof.app.ink
+
+import android.graphics.Canvas
+import android.graphics.Paint
+import com.inkproof.app.model.PageTemplate
+import com.inkproof.app.model.PaperColors
+
+/**
+ * Draws page background templates. Templates and paper colors are visual
+ * only — switching them never touches stroke data.
+ *
+ * Paper COLOR is independent of TEMPLATE: any combination works
+ * (black + grid, slate + ruled, warm white + blank, …). Template line
+ * colors adapt automatically so rules/grids stay subtle-but-visible on
+ * both light and dark paper.
+ */
+object TemplateRenderer {
+
+ private val paperPaint = Paint().apply { style = Paint.Style.FILL }
+ private val shadowPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
+ color = 0x22000000
+ style = Paint.Style.FILL
+ }
+ private val linePaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
+ style = Paint.Style.STROKE
+ strokeWidth = 1f
+ }
+ private val dotPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
+ style = Paint.Style.FILL
+ }
+
+ const val RULE_SPACING = 56f
+ const val GRID_SPACING = 48f
+
+ /** True when ink/lines need to be light to stay visible on this paper. */
+ fun isDarkPaper(paperColor: Int): Boolean = PaperColors.isDark(paperColor)
+
+ /** Subtle line color (fine grids, rules) adapted to the paper. */
+ fun subtleLine(paperColor: Int): Int =
+ if (isDarkPaper(paperColor)) 0x2EFFFFFF else 0xFFE3E7EF.toInt()
+
+ /** Slightly stronger line color (major grids, dots). */
+ fun strongLine(paperColor: Int): Int =
+ if (isDarkPaper(paperColor)) 0x4DFFFFFF else 0xFFCBD2E0.toInt()
+
+ /** Accent line color (worksheet margin). */
+ fun accentLine(paperColor: Int): Int =
+ if (isDarkPaper(paperColor)) 0x59FF8A80 else 0xFFF2C4C4.toInt()
+
+ fun draw(
+ canvas: Canvas,
+ template: PageTemplate,
+ width: Float,
+ height: Float,
+ paperColor: Int = PaperColors.WHITE
+ ) {
+ // Paper with a soft shadow edge.
+ canvas.drawRect(3f, 5f, width + 3f, height + 5f, shadowPaint)
+ paperPaint.color = paperColor
+ canvas.drawRect(0f, 0f, width, height, paperPaint)
+
+ val subtle = subtleLine(paperColor)
+ val strong = strongLine(paperColor)
+
+ when (template) {
+ PageTemplate.BLANK -> Unit
+
+ PageTemplate.RULED -> {
+ linePaint.color = subtle
+ var y = RULE_SPACING * 2
+ while (y < height - RULE_SPACING / 2) {
+ canvas.drawLine(32f, y, width - 32f, y, linePaint)
+ y += RULE_SPACING
+ }
+ }
+
+ PageTemplate.GRID -> {
+ linePaint.color = subtle
+ var x = GRID_SPACING
+ while (x < width) {
+ canvas.drawLine(x, 0f, x, height, linePaint)
+ x += GRID_SPACING
+ }
+ var y = GRID_SPACING
+ while (y < height) {
+ canvas.drawLine(0f, y, width, y, linePaint)
+ y += GRID_SPACING
+ }
+ }
+
+ PageTemplate.DOT_GRID -> {
+ dotPaint.color = strong
+ var x = GRID_SPACING
+ while (x < width) {
+ var y = GRID_SPACING
+ while (y < height) {
+ canvas.drawCircle(x, y, 1.6f, dotPaint)
+ y += GRID_SPACING
+ }
+ x += GRID_SPACING
+ }
+ }
+
+ PageTemplate.ENGINEERING -> {
+ // Fine grid
+ linePaint.color =
+ if (isDarkPaper(paperColor)) 0x17FFFFFF else 0xFFF0F3F8.toInt()
+ val fine = GRID_SPACING / 4f
+ var x = fine
+ while (x < width) {
+ canvas.drawLine(x, 0f, x, height, linePaint)
+ x += fine
+ }
+ var y = fine
+ while (y < height) {
+ canvas.drawLine(0f, y, width, y, linePaint)
+ y += fine
+ }
+ // Major grid
+ linePaint.color = strong
+ x = GRID_SPACING
+ while (x < width) {
+ canvas.drawLine(x, 0f, x, height, linePaint)
+ x += GRID_SPACING
+ }
+ y = GRID_SPACING
+ while (y < height) {
+ canvas.drawLine(0f, y, width, y, linePaint)
+ y += GRID_SPACING
+ }
+ }
+
+ PageTemplate.MATH_WORKSHEET -> {
+ // Ruled body with a left margin — a classic worksheet layout.
+ linePaint.color = subtle
+ var y = RULE_SPACING * 2
+ while (y < height - RULE_SPACING / 2) {
+ canvas.drawLine(32f, y, width - 32f, y, linePaint)
+ y += RULE_SPACING
+ }
+ linePaint.color = accentLine(paperColor)
+ canvas.drawLine(120f, 0f, 120f, height, linePaint)
+ }
+ }
+ }
+}
diff --git a/app/src/main/java/com/inkproof/app/ink/ThumbnailRenderer.kt b/app/src/main/java/com/inkproof/app/ink/ThumbnailRenderer.kt
new file mode 100644
index 0000000..2765ade
--- /dev/null
+++ b/app/src/main/java/com/inkproof/app/ink/ThumbnailRenderer.kt
@@ -0,0 +1,33 @@
+package com.inkproof.app.ink
+
+import android.graphics.Bitmap
+import android.graphics.Canvas
+import com.inkproof.app.model.PageTemplate
+import com.inkproof.app.model.Stroke
+
+/**
+ * Renders real page content into small bitmaps for library/page cards.
+ * Every thumbnail reflects the page's actual strokes — no fake previews.
+ */
+object ThumbnailRenderer {
+
+ fun render(
+ strokes: List,
+ template: PageTemplate,
+ pageWidth: Float,
+ pageHeight: Float,
+ targetWidth: Int = 280,
+ paperColor: Int = com.inkproof.app.model.PaperColors.WHITE
+ ): Bitmap {
+ val scale = targetWidth / pageWidth
+ val targetHeight = (pageHeight * scale).toInt().coerceAtLeast(1)
+ val bitmap = Bitmap.createBitmap(targetWidth, targetHeight, Bitmap.Config.ARGB_8888)
+ val canvas = Canvas(bitmap)
+ canvas.scale(scale, scale)
+ TemplateRenderer.draw(canvas, template, pageWidth, pageHeight, paperColor)
+ for (s in strokes) {
+ StrokeRenderer.draw(canvas, s)
+ }
+ return bitmap
+ }
+}
diff --git a/app/src/main/java/com/inkproof/app/ink/UndoRedoStack.kt b/app/src/main/java/com/inkproof/app/ink/UndoRedoStack.kt
new file mode 100644
index 0000000..d9b22cd
--- /dev/null
+++ b/app/src/main/java/com/inkproof/app/ink/UndoRedoStack.kt
@@ -0,0 +1,54 @@
+package com.inkproof.app.ink
+
+import com.inkproof.app.model.Stroke
+
+/** An undoable canvas operation. */
+sealed class CanvasOp {
+ /** Strokes that were added (draw, paste, snapped shape). */
+ data class Add(val strokes: List) : CanvasOp()
+
+ /** Strokes that were removed (eraser, lasso delete). */
+ data class Remove(val strokes: List) : CanvasOp()
+
+ /** Strokes replaced (move, recolor, resize): before -> after by ID. */
+ data class Replace(val before: List, val after: List) : CanvasOp()
+}
+
+/**
+ * Classic bounded undo/redo stack. Pure Kotlin, unit-tested.
+ * Applying is done by the caller via [UndoRedoListener]; the stack only
+ * tracks operation history.
+ */
+class UndoRedoStack(private val capacity: Int = 100) {
+
+ private val undoStack = ArrayDeque()
+ private val redoStack = ArrayDeque()
+
+ val canUndo: Boolean get() = undoStack.isNotEmpty()
+ val canRedo: Boolean get() = redoStack.isNotEmpty()
+
+ fun push(op: CanvasOp) {
+ undoStack.addLast(op)
+ if (undoStack.size > capacity) undoStack.removeFirst()
+ redoStack.clear()
+ }
+
+ /** Returns the op to revert, or null. */
+ fun undo(): CanvasOp? {
+ val op = undoStack.removeLastOrNull() ?: return null
+ redoStack.addLast(op)
+ return op
+ }
+
+ /** Returns the op to re-apply, or null. */
+ fun redo(): CanvasOp? {
+ val op = redoStack.removeLastOrNull() ?: return null
+ undoStack.addLast(op)
+ return op
+ }
+
+ fun clear() {
+ undoStack.clear()
+ redoStack.clear()
+ }
+}
diff --git a/app/src/main/java/com/inkproof/app/model/CheckModels.kt b/app/src/main/java/com/inkproof/app/model/CheckModels.kt
new file mode 100644
index 0000000..be0e3bc
--- /dev/null
+++ b/app/src/main/java/com/inkproof/app/model/CheckModels.kt
@@ -0,0 +1,88 @@
+package com.inkproof.app.model
+
+import kotlinx.serialization.SerialName
+import kotlinx.serialization.Serializable
+
+/** Action requested by the user. CHECK and SOLVE are deliberately distinct. */
+enum class CheckAction { CHECK, SOLVE }
+
+/** Overall outcome of a check. */
+@Serializable
+enum class CheckStatus {
+ @SerialName("correct") CORRECT,
+ @SerialName("incorrect") INCORRECT,
+ @SerialName("incomplete") INCOMPLETE,
+ @SerialName("unclear") UNCLEAR,
+ @SerialName("unsupported") UNSUPPORTED,
+ @SerialName("error") ERROR
+}
+
+/** Status of one step inside a solution. */
+@Serializable
+enum class StepStatus {
+ @SerialName("correct") CORRECT,
+ @SerialName("incorrect") INCORRECT,
+ @SerialName("dependent_on_previous_error") DEPENDENT_ON_PREVIOUS_ERROR,
+ @SerialName("unclear") UNCLEAR,
+ @SerialName("skipped") SKIPPED
+}
+
+/** One recognized line of the student's handwriting, sent to the backend. */
+@Serializable
+data class RecognizedLine(
+ @SerialName("line_index") val lineIndex: Int,
+ val text: String,
+ val confidence: Float
+)
+
+/**
+ * The payload for a CHECK / SOLVE call.
+ *
+ * Isolation guarantee: a request only ever carries ONE question and the
+ * solution lines recognized from that question's solution region. It never
+ * contains other questions, other pages, or page screenshots.
+ */
+@Serializable
+data class CheckRequest(
+ @SerialName("request_id") val requestId: String,
+ val action: String,
+ @SerialName("question_id") val questionId: String,
+ @SerialName("question_text") val questionText: String,
+ @SerialName("question_source") val questionSource: String,
+ @SerialName("question_confidence") val questionConfidence: Float,
+ @SerialName("solution_lines") val solutionLines: List,
+ @SerialName("content_version") val contentVersion: Long,
+ @SerialName("solution_version") val solutionVersion: Long
+)
+
+@Serializable
+data class CheckStep(
+ @SerialName("step_id") val stepId: String,
+ val status: StepStatus,
+ val expression: String = "",
+ val explanation: String? = null,
+ val hint: String? = null
+)
+
+/**
+ * Structured result of CHECK MY WORK / SOLVE.
+ * The app owns the UI; the AI only supplies this structured data.
+ */
+@Serializable
+data class CheckResponse(
+ val status: CheckStatus,
+ val confidence: Float = 0f,
+ @SerialName("question_echo") val questionEcho: String? = null,
+ @SerialName("first_error_step") val firstErrorStep: String? = null,
+ val steps: List = emptyList(),
+ /** Progressive hints: general -> specific -> very specific. */
+ val hints: List = emptyList(),
+ @SerialName("final_answer") val finalAnswer: String? = null,
+ @SerialName("full_solution") val fullSolution: String? = null,
+ /** Human-readable summary shown in the result header. */
+ val summary: String? = null,
+ /** Set when status is ERROR / UNCLEAR / UNSUPPORTED. */
+ val message: String? = null,
+ /** How the math was verified: "symbolic", "ai", "mock". */
+ @SerialName("verified_by") val verifiedBy: String? = null
+)
diff --git a/app/src/main/java/com/inkproof/app/model/ClipboardOps.kt b/app/src/main/java/com/inkproof/app/model/ClipboardOps.kt
new file mode 100644
index 0000000..6bc88c1
--- /dev/null
+++ b/app/src/main/java/com/inkproof/app/model/ClipboardOps.kt
@@ -0,0 +1,22 @@
+package com.inkproof.app.model
+
+/**
+ * Clipboard semantics: a paste is a NEW independent copy — new stroke IDs,
+ * same appearance, offset position. Never shared references.
+ */
+object ClipboardOps {
+ fun cloneForPaste(
+ clipboard: List,
+ targetPageId: String,
+ dx: Float = 48f,
+ dy: Float = 48f
+ ): List = clipboard.map { s ->
+ s.translated(dx, dy).copy(
+ id = newId(),
+ pageId = targetPageId,
+ // Pasted ink is freeform until it lands in a question region.
+ questionId = null,
+ role = StrokeRole.FREEFORM
+ )
+ }
+}
diff --git a/app/src/main/java/com/inkproof/app/model/Ids.kt b/app/src/main/java/com/inkproof/app/model/Ids.kt
new file mode 100644
index 0000000..b23bd70
--- /dev/null
+++ b/app/src/main/java/com/inkproof/app/model/Ids.kt
@@ -0,0 +1,6 @@
+package com.inkproof.app.model
+
+import java.util.UUID
+
+/** Every entity in InkProof has a globally unique, persistent ID. */
+fun newId(): String = UUID.randomUUID().toString()
diff --git a/app/src/main/java/com/inkproof/app/model/Page.kt b/app/src/main/java/com/inkproof/app/model/Page.kt
new file mode 100644
index 0000000..a4356ff
--- /dev/null
+++ b/app/src/main/java/com/inkproof/app/model/Page.kt
@@ -0,0 +1,21 @@
+package com.inkproof.app.model
+
+/** Background templates for pages. Changing a template never destroys content. */
+enum class PageTemplate {
+ BLANK,
+ RULED,
+ GRID,
+ DOT_GRID,
+ ENGINEERING,
+ MATH_WORKSHEET
+}
+
+/** The two page concepts in InkProof. */
+enum class PageKind {
+ /** Freeform mathematics / notes. */
+ NOTE,
+ /** Structured Question -> Solution page. */
+ MATH_QUESTION,
+ /** An imported PDF page with ink annotation on top. */
+ PDF
+}
diff --git a/app/src/main/java/com/inkproof/app/model/PaperColors.kt b/app/src/main/java/com/inkproof/app/model/PaperColors.kt
new file mode 100644
index 0000000..a7040ea
--- /dev/null
+++ b/app/src/main/java/com/inkproof/app/model/PaperColors.kt
@@ -0,0 +1,36 @@
+package com.inkproof.app.model
+
+/**
+ * Per-page paper colors. Paper color is a PAGE property, independent of
+ * both the app theme (light/dark UI) and the page template (ruled/grid/…):
+ * a user can run a light UI with black pages, a dark UI with white pages,
+ * or any other combination. Changing paper color never touches ink.
+ */
+object PaperColors {
+ val WHITE = 0xFFFCFBF8.toInt()
+ val WARM_WHITE = 0xFFF8F3E9.toInt()
+ val GREY = 0xFFE9EBEF.toInt()
+ val SLATE = 0xFF3B4252.toInt()
+ val DARK_GREY = 0xFF2A2D34.toInt()
+ val NEAR_BLACK = 0xFF1A1C20.toInt()
+ val BLACK = 0xFF0E0F12.toInt()
+
+ /** Label → color, in picker order. */
+ val all: List> = listOf(
+ "White" to WHITE,
+ "Warm white" to WARM_WHITE,
+ "Grey" to GREY,
+ "Slate" to SLATE,
+ "Dark grey" to DARK_GREY,
+ "Near black" to NEAR_BLACK,
+ "Black" to BLACK
+ )
+
+ /** Relative luminance below ~0.5 counts as dark paper. */
+ fun isDark(color: Int): Boolean {
+ val r = (color shr 16 and 0xFF) / 255f
+ val g = (color shr 8 and 0xFF) / 255f
+ val b = (color and 0xFF) / 255f
+ return (0.2126f * r + 0.7152f * g + 0.0722f * b) < 0.5f
+ }
+}
diff --git a/app/src/main/java/com/inkproof/app/model/Question.kt b/app/src/main/java/com/inkproof/app/model/Question.kt
new file mode 100644
index 0000000..e8e4eee
--- /dev/null
+++ b/app/src/main/java/com/inkproof/app/model/Question.kt
@@ -0,0 +1,40 @@
+package com.inkproof.app.model
+
+/** How the question content was provided. */
+enum class QuestionContentType {
+ TYPED,
+ HANDWRITTEN,
+ IMAGE,
+ PDF,
+ PASTED
+}
+
+/**
+ * A math Question is a first-class document object, not a visual line.
+ *
+ * It owns:
+ * - the question content (typed text, ink region, or imported media)
+ * - a dedicated solution region where the student writes
+ * - version counters used to invalidate cached check results
+ */
+data class Question(
+ val id: String = newId(),
+ val pageId: String,
+ val orderIndex: Int,
+ val contentType: QuestionContentType = QuestionContentType.TYPED,
+ /** Typed/pasted question text. Never OCR'd — it is already text. */
+ val typedText: String? = null,
+ /** Path to an imported image/PDF-crop, when applicable. */
+ val mediaPath: String? = null,
+ /** Vertical band (page space) that holds the question content. */
+ val questionTop: Float,
+ val questionBottom: Float,
+ /** Vertical band (page space) reserved for the student's solution. */
+ val solutionTop: Float,
+ val solutionBottom: Float,
+ /** Incremented whenever question content changes. */
+ val contentVersion: Long = 1,
+ /** Incremented whenever solution ink changes. */
+ val solutionVersion: Long = 0,
+ val createdAt: Long = System.currentTimeMillis()
+)
diff --git a/app/src/main/java/com/inkproof/app/model/Shapes.kt b/app/src/main/java/com/inkproof/app/model/Shapes.kt
new file mode 100644
index 0000000..74cec35
--- /dev/null
+++ b/app/src/main/java/com/inkproof/app/model/Shapes.kt
@@ -0,0 +1,23 @@
+package com.inkproof.app.model
+
+/** Shape types supported by hold-to-snap shape recognition. */
+enum class ShapeType {
+ LINE,
+ ARROW,
+ CIRCLE,
+ ELLIPSE,
+ RECTANGLE,
+ SQUARE,
+ TRIANGLE,
+ POLYGON
+}
+
+/**
+ * Result of geometric shape detection on a raw ink stroke.
+ * [points] are the cleaned vector points of the snapped shape, in page space.
+ */
+data class DetectedShape(
+ val type: ShapeType,
+ val points: List,
+ val confidence: Float
+)
diff --git a/app/src/main/java/com/inkproof/app/model/Stroke.kt b/app/src/main/java/com/inkproof/app/model/Stroke.kt
new file mode 100644
index 0000000..c5e0889
--- /dev/null
+++ b/app/src/main/java/com/inkproof/app/model/Stroke.kt
@@ -0,0 +1,91 @@
+package com.inkproof.app.model
+
+/**
+ * A single sampled point on a stroke.
+ *
+ * Coordinates are in page space (document units), independent of zoom/pan,
+ * so ink stays sharp at any zoom level.
+ */
+data class StrokePoint(
+ val x: Float,
+ val y: Float,
+ val pressure: Float,
+ /** Milliseconds since the start of the stroke; useful for recognition. */
+ val t: Long
+)
+
+/** Which logical region of a page a stroke belongs to. */
+enum class StrokeRole {
+ /** Freeform content not bound to a question. */
+ FREEFORM,
+ /** Ink that is part of a question statement. */
+ QUESTION,
+ /** Ink that is part of a student solution. */
+ SOLUTION
+}
+
+/**
+ * The persistent, editable vector stroke model.
+ * Strokes are never flattened into bitmaps in the document model.
+ */
+data class Stroke(
+ val id: String = newId(),
+ val pageId: String,
+ /** Non-null when the stroke belongs to a Question object. */
+ val questionId: String? = null,
+ val role: StrokeRole = StrokeRole.FREEFORM,
+ val tool: ToolType = ToolType.PEN,
+ val color: Int,
+ val baseWidth: Float,
+ val points: List,
+ val createdAt: Long = System.currentTimeMillis(),
+ /** Set when this stroke is a snapped vector shape. */
+ val shapeType: ShapeType? = null
+) {
+ val isHighlighter: Boolean get() = tool == ToolType.HIGHLIGHTER
+
+ fun bounds(): Bounds {
+ if (points.isEmpty()) return Bounds(0f, 0f, 0f, 0f)
+ var minX = Float.MAX_VALUE; var minY = Float.MAX_VALUE
+ var maxX = -Float.MAX_VALUE; var maxY = -Float.MAX_VALUE
+ for (p in points) {
+ if (p.x < minX) minX = p.x
+ if (p.y < minY) minY = p.y
+ if (p.x > maxX) maxX = p.x
+ if (p.y > maxY) maxY = p.y
+ }
+ return Bounds(minX, minY, maxX, maxY)
+ }
+
+ fun translated(dx: Float, dy: Float): Stroke =
+ copy(points = points.map { it.copy(x = it.x + dx, y = it.y + dy) })
+
+ /** Scale around a pivot; the rendered width scales by the mean factor. */
+ fun scaled(sx: Float, sy: Float, pivotX: Float, pivotY: Float): Stroke =
+ copy(
+ points = points.map {
+ it.copy(
+ x = pivotX + (it.x - pivotX) * sx,
+ y = pivotY + (it.y - pivotY) * sy
+ )
+ },
+ baseWidth = (baseWidth * (sx + sy) / 2f).coerceIn(0.5f, 60f)
+ )
+}
+
+data class Bounds(val left: Float, val top: Float, val right: Float, val bottom: Float) {
+ val width: Float get() = right - left
+ val height: Float get() = bottom - top
+ val centerX: Float get() = (left + right) / 2f
+ val centerY: Float get() = (top + bottom) / 2f
+
+ fun union(other: Bounds): Bounds = Bounds(
+ minOf(left, other.left), minOf(top, other.top),
+ maxOf(right, other.right), maxOf(bottom, other.bottom)
+ )
+
+ fun contains(x: Float, y: Float): Boolean = x in left..right && y in top..bottom
+
+ fun intersects(other: Bounds): Boolean =
+ left <= other.right && other.left <= right && top <= other.bottom && other.top <= bottom
+}
diff --git a/app/src/main/java/com/inkproof/app/model/TextObject.kt b/app/src/main/java/com/inkproof/app/model/TextObject.kt
new file mode 100644
index 0000000..b92d247
--- /dev/null
+++ b/app/src/main/java/com/inkproof/app/model/TextObject.kt
@@ -0,0 +1,15 @@
+package com.inkproof.app.model
+
+/** A typed text box placed on a page (editable, persistent). */
+data class TextObject(
+ val id: String = newId(),
+ val pageId: String,
+ val questionId: String? = null,
+ val text: String,
+ val x: Float,
+ val y: Float,
+ val widthPts: Float = 600f,
+ val fontSize: Float = 34f,
+ val color: Int = 0xFF222838.toInt(),
+ val createdAt: Long = System.currentTimeMillis()
+)
diff --git a/app/src/main/java/com/inkproof/app/model/Tool.kt b/app/src/main/java/com/inkproof/app/model/Tool.kt
new file mode 100644
index 0000000..02ce734
--- /dev/null
+++ b/app/src/main/java/com/inkproof/app/model/Tool.kt
@@ -0,0 +1,54 @@
+package com.inkproof.app.model
+
+/** Drawing / interaction tools available in the editor. */
+enum class ToolType {
+ PEN,
+ HIGHLIGHTER,
+ ERASER,
+ LASSO,
+ SHAPE,
+ TEXT,
+ PAN
+}
+
+/** Style of the currently selected ink tool. */
+data class PenStyle(
+ val tool: ToolType = ToolType.PEN,
+ val color: Int = 0xFF1A2238.toInt(),
+ val baseWidth: Float = 3.0f,
+ val pressureEnabled: Boolean = true
+)
+
+object PenPalette {
+ val INK_BLACK = 0xFF212121.toInt()
+ val INK_NAVY = 0xFF1A2238.toInt()
+ val INK_BLUE = 0xFF2458C5.toInt()
+ val INK_RED = 0xFFC62828.toInt()
+ val INK_GREEN = 0xFF2E7D32.toInt()
+ val INK_PURPLE = 0xFF6A3AB2.toInt()
+ val INK_ORANGE = 0xFFE07B00.toInt()
+ val INK_TEAL = 0xFF00796B.toInt()
+
+ val HL_YELLOW = 0x66FFEB3B
+ val HL_GREEN = 0x6669F0AE
+ val HL_BLUE = 0x6640C4FF
+ val HL_PINK = 0x66FF80AB
+ val HL_ORANGE = 0x66FFB74D
+
+ val INK_WHITE = 0xFFFFFFFF.toInt()
+ val INK_GREY = 0xFF8E939E.toInt()
+ val INK_LIGHT_GREY = 0xFFC5CAD3.toInt()
+ val INK_DARK_GREY = 0xFF4A4F58.toInt()
+ val INK_YELLOW = 0xFFE0A800.toInt()
+ val INK_PINK = 0xFFD81B74.toInt()
+ val INK_CYAN = 0xFF00A6C0.toInt()
+
+ val penColors = listOf(
+ INK_BLACK, INK_DARK_GREY, INK_GREY, INK_LIGHT_GREY, INK_WHITE,
+ INK_RED, INK_ORANGE, INK_YELLOW, INK_GREEN, INK_TEAL, INK_CYAN,
+ INK_BLUE, INK_NAVY, INK_PURPLE, INK_PINK
+ )
+ val highlighterColors = listOf(HL_YELLOW, HL_GREEN, HL_BLUE, HL_PINK, HL_ORANGE)
+ val penWidths = listOf(1.5f, 2.5f, 3.5f, 5f, 8f)
+ val highlighterWidths = listOf(12f, 18f, 26f)
+}
diff --git a/app/src/main/java/com/inkproof/app/pdf/ImageImporter.kt b/app/src/main/java/com/inkproof/app/pdf/ImageImporter.kt
new file mode 100644
index 0000000..61627e8
--- /dev/null
+++ b/app/src/main/java/com/inkproof/app/pdf/ImageImporter.kt
@@ -0,0 +1,69 @@
+package com.inkproof.app.pdf
+
+import android.content.Context
+import android.graphics.BitmapFactory
+import android.net.Uri
+import com.inkproof.app.data.repo.LibraryRepository
+import com.inkproof.app.model.PageKind
+import com.inkproof.app.model.PageTemplate
+import com.inkproof.app.model.newId
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.withContext
+import java.io.File
+import java.io.FileOutputStream
+
+/**
+ * Imports an image (gallery/photo picker): the image becomes the background
+ * of a new annotatable page, exactly like an imported PDF page — ink goes on
+ * top as normal vector strokes, so lasso/eraser/CHECK all work.
+ */
+class ImageImporter(
+ private val context: Context,
+ private val library: LibraryRepository
+) {
+ suspend fun import(uri: Uri, notebookTitle: String): String? = withContext(Dispatchers.IO) {
+ try {
+ val dir = File(context.filesDir, "images")
+ dir.mkdirs()
+ val local = File(dir, "${newId()}.img")
+ context.contentResolver.openInputStream(uri)?.use { input ->
+ FileOutputStream(local).use { output -> input.copyTo(output) }
+ } ?: return@withContext null
+
+ // Read dimensions only; the canvas decodes lazily when needed.
+ val opts = BitmapFactory.Options().apply { inJustDecodeBounds = true }
+ BitmapFactory.decodeFile(local.absolutePath, opts)
+ if (opts.outWidth <= 0 || opts.outHeight <= 0) {
+ local.delete()
+ return@withContext null
+ }
+
+ val pageWidth = 1600f
+ val pageHeight = (pageWidth * opts.outHeight / opts.outWidth)
+ .coerceIn(400f, 6000f)
+
+ val notebook = library.createNotebook(
+ title = notebookTitle,
+ firstPageKind = PageKind.PDF,
+ firstPageTemplate = PageTemplate.BLANK
+ )
+ library.pagesFor(notebook.id).forEach { library.deletePage(it.id) }
+ val page = library.createPage(
+ notebookId = notebook.id,
+ kind = PageKind.PDF,
+ template = PageTemplate.BLANK,
+ pdfPath = local.absolutePath
+ )
+ // Match the page aspect to the image.
+ updatePageSize(page.id, pageWidth, pageHeight)
+ notebook.id
+ } catch (e: Exception) {
+ null
+ }
+ }
+
+ private suspend fun updatePageSize(pageId: String, width: Float, height: Float) {
+ val page = library.page(pageId) ?: return
+ library.upsertPage(page.copy(widthPts = width, heightPts = height))
+ }
+}
diff --git a/app/src/main/java/com/inkproof/app/pdf/ImportClassifier.kt b/app/src/main/java/com/inkproof/app/pdf/ImportClassifier.kt
new file mode 100644
index 0000000..94883f3
--- /dev/null
+++ b/app/src/main/java/com/inkproof/app/pdf/ImportClassifier.kt
@@ -0,0 +1,80 @@
+package com.inkproof.app.pdf
+
+/**
+ * Decides what InkProof can do with a picked file — BEFORE trying to import,
+ * so unsupported formats are rejected gracefully with a clear reason instead
+ * of crashing or silently failing.
+ */
+object ImportClassifier {
+
+ enum class Kind { PDF, IMAGE, TEXT, HTML, CSV, UNSUPPORTED }
+
+ data class Result(
+ val kind: Kind,
+ /** Human-readable reason shown when kind == UNSUPPORTED. */
+ val reason: String = ""
+ )
+
+ private val imageExts = setOf("png", "jpg", "jpeg", "webp", "bmp", "gif")
+ private val textExts = setOf("txt", "md", "markdown", "log")
+ private val htmlExts = setOf("html", "htm", "xhtml")
+ private val officeExts = mapOf(
+ "doc" to "Word", "docx" to "Word", "rtf" to "RTF",
+ "odt" to "OpenDocument",
+ "xls" to "Excel", "xlsx" to "Excel", "ods" to "OpenDocument",
+ "ppt" to "PowerPoint", "pptx" to "PowerPoint", "odp" to "OpenDocument"
+ )
+
+ /**
+ * Classify by MIME type first (what the document provider reports),
+ * falling back to the file extension.
+ */
+ fun classify(mimeType: String?, fileName: String?): Result {
+ val mime = mimeType?.lowercase()?.substringBefore(';')?.trim().orEmpty()
+ val ext = fileName?.substringAfterLast('.', "")?.lowercase().orEmpty()
+
+ // --- direct, fully supported formats ---
+ if (mime == "application/pdf" || ext == "pdf") return Result(Kind.PDF)
+ if (mime.startsWith("image/svg") || ext == "svg") {
+ return Result(
+ Kind.UNSUPPORTED,
+ "SVG vector images aren't supported yet. Convert to PNG or JPG first."
+ )
+ }
+ if (mime.startsWith("image/") || ext in imageExts) return Result(Kind.IMAGE)
+ if (mime == "text/csv" || mime == "text/comma-separated-values" || ext == "csv" ||
+ ext == "tsv" || mime == "text/tab-separated-values"
+ ) return Result(Kind.CSV)
+ if (mime == "text/html" || mime == "application/xhtml+xml" || ext in htmlExts) {
+ return Result(Kind.HTML)
+ }
+ if (mime.startsWith("text/") || ext in textExts || mime == "application/json" ||
+ ext == "json"
+ ) return Result(Kind.TEXT)
+
+ // --- known office formats: honest rejection with a workaround ---
+ val office = officeExts[ext] ?: when (mime) {
+ "application/msword",
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document" -> "Word"
+ "application/vnd.ms-excel",
+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" -> "Excel"
+ "application/vnd.ms-powerpoint",
+ "application/vnd.openxmlformats-officedocument.presentationml.presentation" -> "PowerPoint"
+ "application/rtf", "text/rtf" -> "RTF"
+ else -> null
+ }
+ if (office != null) {
+ return Result(
+ Kind.UNSUPPORTED,
+ "$office files can't be opened directly. " +
+ "Export the document as a PDF and import that instead."
+ )
+ }
+
+ return Result(
+ Kind.UNSUPPORTED,
+ "This file type isn't supported. InkProof can import PDF, images " +
+ "(PNG, JPG, WEBP, BMP), and text files (TXT, MD, HTML, CSV)."
+ )
+ }
+}
diff --git a/app/src/main/java/com/inkproof/app/pdf/PdfExporter.kt b/app/src/main/java/com/inkproof/app/pdf/PdfExporter.kt
new file mode 100644
index 0000000..26357b7
--- /dev/null
+++ b/app/src/main/java/com/inkproof/app/pdf/PdfExporter.kt
@@ -0,0 +1,63 @@
+package com.inkproof.app.pdf
+
+import android.content.Context
+import android.graphics.BitmapFactory
+import android.graphics.RectF
+import android.graphics.pdf.PdfDocument
+import com.inkproof.app.data.repo.LibraryRepository
+import com.inkproof.app.data.repo.PageRepository
+import com.inkproof.app.ink.StrokeRenderer
+import com.inkproof.app.ink.TemplateRenderer
+import com.inkproof.app.model.PageTemplate
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.withContext
+import java.io.File
+import java.io.FileOutputStream
+
+/** Exports a notebook (including annotated PDF pages) to a flat PDF file. */
+class PdfExporter(
+ private val context: Context,
+ private val library: LibraryRepository,
+ private val pages: PageRepository
+) {
+ suspend fun export(notebookId: String): File? = withContext(Dispatchers.IO) {
+ try {
+ val notebook = library.notebook(notebookId) ?: return@withContext null
+ val doc = PdfDocument()
+ val notebookPages = library.pagesFor(notebookId)
+ notebookPages.forEachIndexed { index, page ->
+ val info = PdfDocument.PageInfo.Builder(
+ page.widthPts.toInt(), page.heightPts.toInt(), index + 1
+ ).create()
+ val pdfPage = doc.startPage(info)
+ val canvas = pdfPage.canvas
+ val template = runCatching { PageTemplate.valueOf(page.template) }
+ .getOrDefault(PageTemplate.BLANK)
+ TemplateRenderer.draw(
+ canvas, template, page.widthPts, page.heightPts, page.paperColor
+ )
+ page.pdfPath?.let { path ->
+ BitmapFactory.decodeFile(path)?.let { bmp ->
+ canvas.drawBitmap(
+ bmp, null, RectF(0f, 0f, page.widthPts, page.heightPts), null
+ )
+ bmp.recycle()
+ }
+ }
+ for (stroke in pages.strokesForPage(page.id)) {
+ StrokeRenderer.draw(canvas, stroke)
+ }
+ doc.finishPage(pdfPage)
+ }
+ val outDir = File(context.filesDir, "exports")
+ outDir.mkdirs()
+ val safeTitle = notebook.title.replace(Regex("[^A-Za-z0-9 _-]"), "_")
+ val outFile = File(outDir, "$safeTitle.pdf")
+ FileOutputStream(outFile).use { doc.writeTo(it) }
+ doc.close()
+ outFile
+ } catch (e: Exception) {
+ null
+ }
+ }
+}
diff --git a/app/src/main/java/com/inkproof/app/pdf/PdfImporter.kt b/app/src/main/java/com/inkproof/app/pdf/PdfImporter.kt
new file mode 100644
index 0000000..2eedbcb
--- /dev/null
+++ b/app/src/main/java/com/inkproof/app/pdf/PdfImporter.kt
@@ -0,0 +1,81 @@
+package com.inkproof.app.pdf
+
+import android.content.Context
+import android.graphics.Bitmap
+import android.graphics.pdf.PdfRenderer
+import android.net.Uri
+import android.os.ParcelFileDescriptor
+import com.inkproof.app.data.repo.LibraryRepository
+import com.inkproof.app.model.PageKind
+import com.inkproof.app.model.PageTemplate
+import com.inkproof.app.model.newId
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.withContext
+import java.io.File
+import java.io.FileOutputStream
+
+/**
+ * Imports a PDF: each source page becomes an InkProof PDF page whose
+ * background is the rendered page image; ink annotation goes on top as
+ * normal vector strokes.
+ */
+class PdfImporter(
+ private val context: Context,
+ private val library: LibraryRepository
+) {
+ suspend fun import(uri: Uri, notebookTitle: String): String? = withContext(Dispatchers.IO) {
+ try {
+ val dir = File(context.filesDir, "pdf/${newId()}")
+ dir.mkdirs()
+ val local = File(dir, "source.pdf")
+ context.contentResolver.openInputStream(uri)?.use { input ->
+ FileOutputStream(local).use { output -> input.copyTo(output) }
+ } ?: return@withContext null
+
+ val notebook = library.createNotebook(
+ title = notebookTitle,
+ firstPageKind = PageKind.PDF,
+ firstPageTemplate = PageTemplate.BLANK
+ )
+ // createNotebook creates one page; remove it and add real PDF pages.
+ library.pagesFor(notebook.id).forEach { library.deletePage(it.id) }
+
+ ParcelFileDescriptor.open(local, ParcelFileDescriptor.MODE_READ_ONLY).use { fd ->
+ PdfRenderer(fd).use { renderer ->
+ for (i in 0 until renderer.pageCount) {
+ val page = renderer.openPage(i)
+ try {
+ val scale = 2f
+ val bitmap = Bitmap.createBitmap(
+ (page.width * scale).toInt(),
+ (page.height * scale).toInt(),
+ Bitmap.Config.ARGB_8888
+ )
+ bitmap.eraseColor(android.graphics.Color.WHITE)
+ page.render(
+ bitmap, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY
+ )
+ val imageFile = File(dir, "page_$i.png")
+ FileOutputStream(imageFile).use { out ->
+ bitmap.compress(Bitmap.CompressFormat.PNG, 90, out)
+ }
+ bitmap.recycle()
+ library.createPage(
+ notebookId = notebook.id,
+ kind = PageKind.PDF,
+ template = PageTemplate.BLANK,
+ pdfPath = imageFile.absolutePath,
+ pdfPageIndex = i
+ )
+ } finally {
+ page.close()
+ }
+ }
+ }
+ }
+ notebook.id
+ } catch (e: Exception) {
+ null
+ }
+ }
+}
diff --git a/app/src/main/java/com/inkproof/app/pdf/TextImporter.kt b/app/src/main/java/com/inkproof/app/pdf/TextImporter.kt
new file mode 100644
index 0000000..90f5514
--- /dev/null
+++ b/app/src/main/java/com/inkproof/app/pdf/TextImporter.kt
@@ -0,0 +1,124 @@
+package com.inkproof.app.pdf
+
+import android.content.Context
+import android.net.Uri
+import com.inkproof.app.data.repo.LibraryRepository
+import com.inkproof.app.data.repo.PageRepository
+import com.inkproof.app.model.PageKind
+import com.inkproof.app.model.PageTemplate
+import com.inkproof.app.model.TextObject
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.withContext
+
+/**
+ * Imports plain-text-ish formats (TXT, MD, HTML, CSV, JSON) into a new
+ * notebook as editable [TextObject]s — one block per page, paginated by
+ * line count. HTML is stripped to text; CSV columns are joined readably.
+ */
+class TextImporter(
+ private val context: Context,
+ private val library: LibraryRepository,
+ private val pages: PageRepository
+) {
+ companion object {
+ /** Cap raw input so a giant log file can't lock the UI or DB. */
+ const val MAX_BYTES = 500_000
+ const val LINES_PER_PAGE = 46
+ const val MAX_LINE_CHARS = 110
+ }
+
+ suspend fun import(
+ uri: Uri,
+ notebookTitle: String,
+ kind: ImportClassifier.Kind
+ ): String? = withContext(Dispatchers.IO) {
+ try {
+ val raw = context.contentResolver.openInputStream(uri)?.use { input ->
+ input.readBytes().let { bytes ->
+ if (bytes.size > MAX_BYTES) bytes.copyOf(MAX_BYTES) else bytes
+ }
+ }?.toString(Charsets.UTF_8) ?: return@withContext null
+
+ val text = when (kind) {
+ ImportClassifier.Kind.HTML -> stripHtml(raw)
+ ImportClassifier.Kind.CSV -> formatCsv(raw)
+ else -> raw
+ }.trim()
+ if (text.isEmpty()) return@withContext null
+
+ val lines = wrapLines(text)
+ val pageChunks = lines.chunked(LINES_PER_PAGE).ifEmpty { listOf(listOf("")) }
+
+ val notebook = library.createNotebook(
+ title = notebookTitle,
+ firstPageKind = PageKind.NOTE,
+ firstPageTemplate = PageTemplate.RULED
+ )
+ val existing = library.pagesFor(notebook.id)
+ pageChunks.forEachIndexed { index, chunk ->
+ val page = if (index == 0 && existing.isNotEmpty()) existing.first()
+ else library.createPage(
+ notebookId = notebook.id,
+ kind = PageKind.NOTE,
+ template = PageTemplate.RULED
+ )
+ pages.upsertTextObject(
+ TextObject(
+ pageId = page.id,
+ text = chunk.joinToString("\n"),
+ x = 60f,
+ y = 80f,
+ widthPts = 1480f,
+ fontSize = 30f
+ )
+ )
+ }
+ notebook.id
+ } catch (e: Exception) {
+ null
+ }
+ }
+
+ /** Remove tags/scripts/styles and decode the most common entities. */
+ fun stripHtml(html: String): String =
+ html
+ .replace(Regex("(?is)<(script|style)[^>]*>.*?\\1>"), " ")
+ .replace(Regex("(?i)
"), "\n")
+ .replace(Regex("(?i)(p|div|h[1-6]|li|tr)>"), "\n")
+ .replace(Regex("<[^>]+>"), " ")
+ .replace(" ", " ")
+ .replace("&", "&")
+ .replace("<", "<")
+ .replace(">", ">")
+ .replace(""", "\"")
+ .replace("'", "'")
+ .replace(Regex("[ \\t]+"), " ")
+ .replace(Regex("\\n{3,}"), "\n\n")
+ .trim()
+
+ /** Join CSV columns with a readable separator, row per line. */
+ fun formatCsv(csv: String): String =
+ csv.lineSequence()
+ .map { line -> line.split(',').joinToString(" | ") { it.trim().trim('"') } }
+ .joinToString("\n")
+
+ /** Soft-wrap very long lines so they fit the page width. */
+ fun wrapLines(text: String): List {
+ val out = ArrayList()
+ text.lines().forEach { line ->
+ if (line.length <= MAX_LINE_CHARS) {
+ out.add(line)
+ } else {
+ var rest = line
+ while (rest.length > MAX_LINE_CHARS) {
+ val cut = rest.lastIndexOf(' ', MAX_LINE_CHARS)
+ .let { if (it <= 0) MAX_LINE_CHARS else it }
+ out.add(rest.substring(0, cut))
+ rest = rest.substring(cut).trimStart()
+ }
+ if (rest.isNotEmpty()) out.add(rest)
+ }
+ }
+ return out
+ }
+}
diff --git a/app/src/main/java/com/inkproof/app/ui/MainActivity.kt b/app/src/main/java/com/inkproof/app/ui/MainActivity.kt
new file mode 100644
index 0000000..a79ca94
--- /dev/null
+++ b/app/src/main/java/com/inkproof/app/ui/MainActivity.kt
@@ -0,0 +1,61 @@
+package com.inkproof.app.ui
+
+import android.os.Bundle
+import androidx.activity.ComponentActivity
+import androidx.activity.compose.setContent
+import androidx.activity.enableEdgeToEdge
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.collectAsState
+import androidx.compose.runtime.getValue
+import androidx.navigation.NavType
+import androidx.navigation.compose.NavHost
+import androidx.navigation.compose.composable
+import androidx.navigation.compose.rememberNavController
+import androidx.navigation.navArgument
+import com.inkproof.app.ui.editor.EditorScreen
+import com.inkproof.app.ui.library.LibraryScreen
+import com.inkproof.app.ui.settings.SettingsScreen
+import com.inkproof.app.ui.theme.InkProofTheme
+
+class MainActivity : ComponentActivity() {
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ enableEdgeToEdge()
+ val app = application as com.inkproof.app.InkProofApp
+ setContent {
+ val settings by app.settingsStore.settings
+ .collectAsState(initial = com.inkproof.app.data.settings.Settings())
+ InkProofTheme(themeMode = settings.appTheme) {
+ InkProofNavHost()
+ }
+ }
+ }
+}
+
+@Composable
+fun InkProofNavHost() {
+ val navController = rememberNavController()
+ NavHost(navController = navController, startDestination = "library") {
+ composable("library") {
+ LibraryScreen(
+ onOpenNotebook = { notebookId ->
+ navController.navigate("editor/$notebookId")
+ },
+ onOpenSettings = { navController.navigate("settings") }
+ )
+ }
+ composable(
+ route = "editor/{notebookId}",
+ arguments = listOf(navArgument("notebookId") { type = NavType.StringType })
+ ) { backStackEntry ->
+ val notebookId = backStackEntry.arguments?.getString("notebookId").orEmpty()
+ EditorScreen(
+ notebookId = notebookId,
+ onBack = { navController.popBackStack() }
+ )
+ }
+ composable("settings") {
+ SettingsScreen(onBack = { navController.popBackStack() })
+ }
+ }
+}
diff --git a/app/src/main/java/com/inkproof/app/ui/editor/CheckPanel.kt b/app/src/main/java/com/inkproof/app/ui/editor/CheckPanel.kt
new file mode 100644
index 0000000..ebe7ef9
--- /dev/null
+++ b/app/src/main/java/com/inkproof/app/ui/editor/CheckPanel.kt
@@ -0,0 +1,393 @@
+package com.inkproof.app.ui.editor
+
+import androidx.compose.foundation.background
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.Spacer
+import androidx.compose.foundation.layout.fillMaxHeight
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.height
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.layout.width
+import androidx.compose.foundation.rememberScrollState
+import androidx.compose.foundation.shape.CircleShape
+import androidx.compose.foundation.shape.RoundedCornerShape
+import androidx.compose.foundation.verticalScroll
+import androidx.compose.material.icons.Icons
+import androidx.compose.material.icons.filled.Check
+import androidx.compose.material.icons.filled.Close
+import androidx.compose.material.icons.filled.QuestionMark
+import androidx.compose.material.icons.outlined.SubdirectoryArrowRight
+import androidx.compose.material3.Button
+import androidx.compose.material3.ButtonDefaults
+import androidx.compose.material3.CircularProgressIndicator
+import androidx.compose.material3.Icon
+import androidx.compose.material3.IconButton
+import androidx.compose.material3.MaterialTheme
+import androidx.compose.material3.OutlinedButton
+import androidx.compose.material3.Surface
+import androidx.compose.material3.Text
+import androidx.compose.material3.TextButton
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableIntStateOf
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.unit.dp
+import com.inkproof.app.model.CheckResponse
+import com.inkproof.app.model.CheckStatus
+import com.inkproof.app.model.StepStatus
+import com.inkproof.app.ui.theme.ErrorRed
+import com.inkproof.app.ui.theme.ErrorRedSoft
+import com.inkproof.app.ui.theme.InkNavy
+import com.inkproof.app.ui.theme.MutedText
+import com.inkproof.app.ui.theme.ProofGreen
+import com.inkproof.app.ui.theme.ProofGreenSoft
+import com.inkproof.app.ui.theme.WarnAmber
+import com.inkproof.app.ui.theme.WarnAmberSoft
+import com.inkproof.app.model.CheckAction
+
+/**
+ * Compact side panel for CHECK MY WORK results.
+ * The student's handwriting stays visible — this never covers the canvas.
+ */
+@Composable
+fun CheckPanel(
+ state: CheckUiState,
+ onDismiss: () -> Unit,
+ onTryAgain: () -> Unit,
+ onRetryCheck: (String, CheckAction) -> Unit,
+ onSelectRegion: () -> Unit = {},
+ onEditQuestion: (String) -> Unit = {},
+ autoShowFirstHint: Boolean = false
+) {
+ Surface(
+ color = MaterialTheme.colorScheme.surface,
+ shadowElevation = 8.dp,
+ modifier = Modifier
+ .width(360.dp)
+ .fillMaxHeight()
+ ) {
+ when (state) {
+ is CheckUiState.Hidden -> Unit
+
+ is CheckUiState.Loading -> Box(
+ contentAlignment = Alignment.Center,
+ modifier = Modifier.fillMaxSize()
+ ) {
+ Column(horizontalAlignment = Alignment.CenterHorizontally) {
+ CircularProgressIndicator(color = ProofGreen)
+ Spacer(Modifier.height(16.dp))
+ Text(
+ if (state.action == CheckAction.CHECK) "Checking your work…"
+ else "Working out a solution…",
+ style = MaterialTheme.typography.titleSmall
+ )
+ Spacer(Modifier.height(6.dp))
+ Text(
+ "Reading only this question and your solution.",
+ style = MaterialTheme.typography.bodySmall,
+ color = MutedText
+ )
+ }
+ }
+
+ is CheckUiState.Result -> ResultContent(
+ response = state.response,
+ action = state.action,
+ questionId = state.questionId,
+ onDismiss = onDismiss,
+ onTryAgain = onTryAgain,
+ onRetryCheck = onRetryCheck,
+ onSelectRegion = onSelectRegion,
+ onEditQuestion = onEditQuestion,
+ autoShowFirstHint = autoShowFirstHint
+ )
+ }
+ }
+}
+
+@Composable
+private fun ResultContent(
+ response: CheckResponse,
+ action: CheckAction,
+ questionId: String?,
+ onDismiss: () -> Unit,
+ onTryAgain: () -> Unit,
+ onRetryCheck: (String, CheckAction) -> Unit,
+ onSelectRegion: () -> Unit = {},
+ onEditQuestion: (String) -> Unit = {},
+ autoShowFirstHint: Boolean = false
+) {
+ // When enabled in settings, the first hint is revealed automatically
+ // for a wrong/incomplete answer (never the full solution).
+ val initialHints =
+ if (autoShowFirstHint &&
+ response.hints.isNotEmpty() &&
+ (response.status == CheckStatus.INCORRECT || response.status == CheckStatus.INCOMPLETE)
+ ) 1 else 0
+ var hintsRevealed by remember(response) { mutableIntStateOf(initialHints) }
+ var solutionRevealed by remember(response) { mutableStateOf(false) }
+
+ val (headerColor, headerBg, headerText) = when (response.status) {
+ CheckStatus.CORRECT -> Triple(ProofGreen, ProofGreenSoft, "Correct")
+ CheckStatus.INCORRECT -> Triple(ErrorRed, ErrorRedSoft, "First mistake found")
+ CheckStatus.INCOMPLETE -> Triple(WarnAmber, WarnAmberSoft, "Incomplete")
+ CheckStatus.UNCLEAR -> Triple(WarnAmber, WarnAmberSoft, "Hard to read")
+ CheckStatus.UNSUPPORTED -> Triple(
+ MutedText, MaterialTheme.colorScheme.surfaceVariant, "Not supported yet"
+ )
+ CheckStatus.ERROR -> Triple(ErrorRed, ErrorRedSoft, "Something went wrong")
+ }
+
+ Column(Modifier.fillMaxSize()) {
+ // Header
+ Surface(color = headerBg) {
+ Row(
+ verticalAlignment = Alignment.CenterVertically,
+ modifier = Modifier
+ .fillMaxWidth()
+ .padding(start = 18.dp, end = 6.dp, top = 14.dp, bottom = 14.dp)
+ ) {
+ Column(Modifier.weight(1f)) {
+ Text(
+ if (action == CheckAction.SOLVE) "Solution" else headerText,
+ style = MaterialTheme.typography.titleMedium,
+ color = headerColor
+ )
+ response.summary?.let {
+ Text(
+ it,
+ style = MaterialTheme.typography.bodySmall,
+ color = MutedText
+ )
+ }
+ }
+ IconButton(onClick = onDismiss) {
+ Icon(Icons.Filled.Close, "Close", tint = MutedText)
+ }
+ }
+ }
+
+ Column(
+ modifier = Modifier
+ .weight(1f)
+ .verticalScroll(rememberScrollState())
+ .padding(18.dp)
+ ) {
+ // Question echo — full transparency about what was analyzed.
+ response.questionEcho?.takeIf { it.isNotBlank() }?.let {
+ Text("QUESTION", style = MaterialTheme.typography.labelMedium, color = MutedText)
+ Spacer(Modifier.height(4.dp))
+ Text(it, style = MaterialTheme.typography.bodyMedium)
+ Spacer(Modifier.height(16.dp))
+ }
+
+ // Error / info message
+ response.message?.let {
+ Surface(
+ shape = RoundedCornerShape(10.dp),
+ color = headerBg,
+ modifier = Modifier.fillMaxWidth()
+ ) {
+ Text(
+ it,
+ style = MaterialTheme.typography.bodyMedium,
+ modifier = Modifier.padding(12.dp)
+ )
+ }
+ Spacer(Modifier.height(16.dp))
+ }
+
+ // Steps
+ if (response.steps.isNotEmpty()) {
+ Text("STEPS", style = MaterialTheme.typography.labelMedium, color = MutedText)
+ Spacer(Modifier.height(8.dp))
+ response.steps.forEach { step ->
+ StepRow(
+ step = step,
+ isFirstError = step.stepId == response.firstErrorStep
+ )
+ Spacer(Modifier.height(8.dp))
+ }
+ Spacer(Modifier.height(8.dp))
+ }
+
+ // Progressive hints
+ if (response.hints.isNotEmpty() && response.status != CheckStatus.CORRECT) {
+ Text("HINTS", style = MaterialTheme.typography.labelMedium, color = MutedText)
+ Spacer(Modifier.height(8.dp))
+ response.hints.take(hintsRevealed).forEachIndexed { i, hint ->
+ Surface(
+ shape = RoundedCornerShape(10.dp),
+ color = MaterialTheme.colorScheme.surfaceVariant,
+ modifier = Modifier
+ .fillMaxWidth()
+ .padding(bottom = 8.dp)
+ ) {
+ Row(Modifier.padding(12.dp)) {
+ Text(
+ "${i + 1}",
+ style = MaterialTheme.typography.labelLarge,
+ color = InkNavy,
+ modifier = Modifier.padding(end = 10.dp)
+ )
+ Text(hint, style = MaterialTheme.typography.bodyMedium)
+ }
+ }
+ }
+ if (hintsRevealed < response.hints.size) {
+ OutlinedButton(onClick = { hintsRevealed++ }) {
+ Text(if (hintsRevealed == 0) "Get a hint" else "Next hint")
+ }
+ Spacer(Modifier.height(8.dp))
+ }
+ }
+
+ // Full solution (hidden by default)
+ response.fullSolution?.let { solution ->
+ Spacer(Modifier.height(8.dp))
+ if (solutionRevealed || action == CheckAction.SOLVE) {
+ Text("SOLUTION", style = MaterialTheme.typography.labelMedium, color = MutedText)
+ Spacer(Modifier.height(6.dp))
+ Surface(
+ shape = RoundedCornerShape(10.dp),
+ color = ProofGreenSoft,
+ modifier = Modifier.fillMaxWidth()
+ ) {
+ Column(Modifier.padding(12.dp)) {
+ Text(solution, style = MaterialTheme.typography.bodyMedium)
+ response.finalAnswer?.let {
+ Spacer(Modifier.height(8.dp))
+ Text(
+ "Answer: $it",
+ style = MaterialTheme.typography.titleSmall,
+ color = ProofGreen
+ )
+ }
+ }
+ }
+ } else {
+ TextButton(onClick = { solutionRevealed = true }) {
+ Text("Show solution", color = MutedText)
+ }
+ }
+ }
+ }
+
+ // UNCLEAR recovery: fix what the app couldn't read, don't just retry.
+ if (questionId != null && response.status == CheckStatus.UNCLEAR) {
+ Row(
+ modifier = Modifier
+ .fillMaxWidth()
+ .padding(horizontal = 14.dp)
+ ) {
+ OutlinedButton(
+ onClick = onSelectRegion,
+ modifier = Modifier.weight(1f)
+ ) { Text("Select region") }
+ Spacer(Modifier.width(10.dp))
+ OutlinedButton(
+ onClick = { onEditQuestion(questionId) },
+ modifier = Modifier.weight(1f)
+ ) { Text("Edit question") }
+ }
+ }
+
+ // Footer actions
+ Row(
+ modifier = Modifier
+ .fillMaxWidth()
+ .padding(14.dp)
+ ) {
+ OutlinedButton(
+ onClick = onTryAgain,
+ modifier = Modifier.weight(1f)
+ ) { Text("Try again") }
+ Spacer(Modifier.width(10.dp))
+ if (questionId != null &&
+ (response.status == CheckStatus.UNCLEAR || response.status == CheckStatus.ERROR)
+ ) {
+ Button(
+ onClick = { onRetryCheck(questionId, action) },
+ colors = ButtonDefaults.buttonColors(containerColor = InkNavy),
+ modifier = Modifier.weight(1f)
+ ) { Text("Check again") }
+ } else {
+ Button(
+ onClick = onDismiss,
+ colors = ButtonDefaults.buttonColors(containerColor = ProofGreen),
+ modifier = Modifier.weight(1f)
+ ) { Text("Done") }
+ }
+ }
+ }
+}
+
+@Composable
+private fun StepRow(step: com.inkproof.app.model.CheckStep, isFirstError: Boolean) {
+ val (icon, tint, bg) = when (step.status) {
+ StepStatus.CORRECT -> Triple(Icons.Filled.Check, ProofGreen, Color.Transparent)
+ StepStatus.INCORRECT -> Triple(Icons.Filled.Close, ErrorRed, ErrorRedSoft)
+ StepStatus.DEPENDENT_ON_PREVIOUS_ERROR ->
+ Triple(Icons.Outlined.SubdirectoryArrowRight, MutedText, Color.Transparent)
+ StepStatus.UNCLEAR -> Triple(Icons.Filled.QuestionMark, WarnAmber, WarnAmberSoft)
+ StepStatus.SKIPPED -> Triple(Icons.Filled.QuestionMark, MutedText, Color.Transparent)
+ }
+
+ Surface(
+ shape = RoundedCornerShape(10.dp),
+ color = bg,
+ modifier = Modifier.fillMaxWidth()
+ ) {
+ Row(modifier = Modifier.padding(10.dp)) {
+ Box(
+ contentAlignment = Alignment.Center,
+ modifier = Modifier
+ .size(24.dp)
+ .clip(CircleShape)
+ .background(tint.copy(alpha = 0.12f))
+ ) {
+ Icon(icon, null, tint = tint, modifier = Modifier.size(14.dp))
+ }
+ Spacer(Modifier.width(10.dp))
+ Column {
+ Row(verticalAlignment = Alignment.CenterVertically) {
+ Text(
+ step.expression.ifBlank { step.stepId },
+ style = MaterialTheme.typography.bodyMedium,
+ modifier = Modifier.weight(1f, fill = false)
+ )
+ if (isFirstError) {
+ Spacer(Modifier.width(8.dp))
+ Text(
+ "FIRST MISTAKE",
+ style = MaterialTheme.typography.labelSmall,
+ color = ErrorRed
+ )
+ }
+ }
+ step.explanation?.takeIf { it.isNotBlank() }?.let {
+ Spacer(Modifier.height(2.dp))
+ Text(it, style = MaterialTheme.typography.bodySmall, color = MutedText)
+ }
+ step.hint?.takeIf { it.isNotBlank() }?.let {
+ Spacer(Modifier.height(2.dp))
+ Text(
+ "Hint: $it",
+ style = MaterialTheme.typography.bodySmall,
+ color = WarnAmber
+ )
+ }
+ }
+ }
+ }
+}
diff --git a/app/src/main/java/com/inkproof/app/ui/editor/EditorScreen.kt b/app/src/main/java/com/inkproof/app/ui/editor/EditorScreen.kt
new file mode 100644
index 0000000..d2c8707
--- /dev/null
+++ b/app/src/main/java/com/inkproof/app/ui/editor/EditorScreen.kt
@@ -0,0 +1,1712 @@
+package com.inkproof.app.ui.editor
+
+import android.app.Activity
+import android.app.Application
+import android.graphics.RectF
+import android.view.WindowManager
+import android.widget.Toast
+import androidx.compose.animation.AnimatedVisibility
+import androidx.compose.animation.fadeIn
+import androidx.compose.animation.fadeOut
+import androidx.compose.animation.slideInHorizontally
+import androidx.compose.animation.slideOutHorizontally
+import androidx.activity.compose.rememberLauncherForActivityResult
+import androidx.activity.result.contract.ActivityResultContracts
+import androidx.compose.foundation.Image
+import androidx.compose.foundation.background
+import androidx.compose.foundation.border
+import androidx.compose.foundation.clickable
+import androidx.compose.foundation.combinedClickable
+import androidx.compose.foundation.horizontalScroll
+import androidx.compose.foundation.rememberScrollState
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.PaddingValues
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.Spacer
+import androidx.compose.foundation.layout.fillMaxHeight
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.height
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.layout.width
+import androidx.compose.foundation.lazy.LazyColumn
+import androidx.compose.foundation.lazy.itemsIndexed
+import androidx.compose.foundation.shape.CircleShape
+import androidx.compose.foundation.shape.RoundedCornerShape
+import androidx.compose.material.icons.Icons
+import androidx.compose.material.icons.automirrored.filled.ArrowBack
+import androidx.compose.material.icons.automirrored.filled.ArrowForward
+import androidx.compose.material.icons.automirrored.filled.Redo
+import androidx.compose.material.icons.automirrored.filled.Undo
+import androidx.compose.material.icons.filled.Add
+import androidx.compose.material3.Slider
+import androidx.compose.material.icons.filled.MoreVert
+import androidx.compose.material.icons.outlined.Category
+import androidx.compose.material.icons.outlined.Delete
+import androidx.compose.material.icons.outlined.Edit
+import androidx.compose.material.icons.outlined.Gesture
+import androidx.compose.material.icons.outlined.HighlightAlt
+import androidx.compose.material.icons.outlined.Backspace
+import androidx.compose.material.icons.outlined.BorderColor
+import androidx.compose.material.icons.outlined.TextFields
+import androidx.compose.material3.AlertDialog
+import androidx.compose.material3.DropdownMenu
+import androidx.compose.material3.DropdownMenuItem
+import androidx.compose.material3.Icon
+import androidx.compose.material3.IconButton
+import androidx.compose.material3.MaterialTheme
+import androidx.compose.material3.OutlinedTextField
+import androidx.compose.material3.Surface
+import androidx.compose.material3.Text
+import androidx.compose.material3.TextButton
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.collectAsState
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.graphics.asImageBitmap
+import androidx.compose.ui.graphics.toArgb
+import androidx.compose.ui.layout.ContentScale
+import androidx.compose.ui.platform.LocalContext
+import androidx.compose.ui.text.font.FontWeight
+import androidx.compose.ui.text.style.TextOverflow
+import androidx.compose.ui.unit.dp
+import androidx.compose.ui.viewinterop.AndroidView
+import androidx.lifecycle.ViewModel
+import androidx.lifecycle.ViewModelProvider
+import androidx.lifecycle.viewmodel.compose.viewModel
+import com.inkproof.app.ink.InkCanvasView
+import com.inkproof.app.ink.ThumbnailRenderer
+import com.inkproof.app.model.CheckAction
+import com.inkproof.app.model.PageKind
+import com.inkproof.app.model.PageTemplate
+import com.inkproof.app.model.PaperColors
+import com.inkproof.app.model.PenPalette
+import com.inkproof.app.model.QuestionContentType
+import com.inkproof.app.model.Stroke
+import com.inkproof.app.model.ToolType
+import androidx.compose.material3.CircularProgressIndicator
+import com.inkproof.app.ui.theme.Divider
+import com.inkproof.app.ui.theme.InkNavy
+import com.inkproof.app.ui.theme.MutedText
+import com.inkproof.app.ui.theme.ProofGreen
+import com.inkproof.app.ui.theme.WarnAmber
+
+class EditorViewModelFactory(
+ private val application: Application,
+ private val notebookId: String
+) : ViewModelProvider.Factory {
+ @Suppress("UNCHECKED_CAST")
+ override fun create(modelClass: Class): T =
+ EditorViewModel(application, notebookId) as T
+}
+
+@Composable
+fun EditorScreen(
+ notebookId: String,
+ onBack: () -> Unit
+) {
+ val context = LocalContext.current
+ val viewModel: EditorViewModel = viewModel(
+ key = "editor-$notebookId",
+ factory = EditorViewModelFactory(
+ context.applicationContext as Application, notebookId
+ )
+ )
+
+ val pageContent by viewModel.pageContent.collectAsState()
+ val pages by viewModel.pages.collectAsState()
+ val penStyle by viewModel.penStyle.collectAsState()
+ val canUndo by viewModel.canUndo.collectAsState()
+ val canRedo by viewModel.canRedo.collectAsState()
+ val selection by viewModel.selection.collectAsState()
+ val checkState by viewModel.checkState.collectAsState()
+ val settings by viewModel.settings.collectAsState()
+ val title by viewModel.notebookTitle.collectAsState()
+
+ var canvasRef by remember { mutableStateOf(null) }
+ var shapeKind by remember { mutableStateOf(com.inkproof.app.model.ShapeType.RECTANGLE) }
+ var showQuestionComposer by remember { mutableStateOf(false) }
+ val questionImageLauncher = rememberLauncherForActivityResult(
+ ActivityResultContracts.OpenDocument()
+ ) { uri -> uri?.let { viewModel.createQuestionFromMedia(it, isPdf = false) } }
+ val questionPdfLauncher = rememberLauncherForActivityResult(
+ ActivityResultContracts.OpenDocument()
+ ) { uri -> uri?.let { viewModel.createQuestionFromMedia(it, isPdf = true) } }
+ var editQuestionId by remember { mutableStateOf(null) }
+ var showTemplatePicker by remember { mutableStateOf(false) }
+ var showPaperColorPicker by remember { mutableStateOf(false) }
+ var showPageRail by remember { mutableStateOf(true) }
+ // TEXT tool tap target: (pageX, pageY, existing object or null).
+ var textDialog by remember {
+ mutableStateOf?>(null)
+ }
+
+ // Keep screen awake while writing (setting).
+ LaunchedEffect(settings.keepScreenAwake) {
+ val window = (context as? Activity)?.window ?: return@LaunchedEffect
+ if (settings.keepScreenAwake) {
+ window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
+ } else {
+ window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
+ }
+ }
+
+ // Full-screen canvas: hide system bars while the editor is open.
+ androidx.compose.runtime.DisposableEffect(settings.fullScreenCanvas) {
+ val window = (context as? Activity)?.window
+ val controller = window?.let {
+ androidx.core.view.WindowCompat.getInsetsController(it, it.decorView)
+ }
+ if (settings.fullScreenCanvas && controller != null) {
+ controller.systemBarsBehavior =
+ androidx.core.view.WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
+ controller.hide(androidx.core.view.WindowInsetsCompat.Type.systemBars())
+ }
+ onDispose {
+ controller?.show(androidx.core.view.WindowInsetsCompat.Type.systemBars())
+ }
+ }
+
+ // Toasts
+ LaunchedEffect(Unit) {
+ viewModel.toast.collect { msg ->
+ Toast.makeText(context, msg, Toast.LENGTH_SHORT).show()
+ }
+ }
+
+ // Pushes undo/redo/paste mutations into the canvas.
+ LaunchedEffect(canvasRef) {
+ val view = canvasRef ?: return@LaunchedEffect
+ viewModel.canvasMutations.collect { mutation ->
+ when (mutation) {
+ is CanvasMutation.Add -> view.applyAdd(mutation.strokes)
+ is CanvasMutation.Remove -> view.applyRemove(mutation.strokes)
+ is CanvasMutation.Replace -> view.applyReplace(mutation.strokes)
+ }
+ }
+ }
+
+ // Load page content into the canvas when it changes.
+ LaunchedEffect(pageContent?.loadToken, canvasRef) {
+ val content = pageContent ?: return@LaunchedEffect
+ val view = canvasRef ?: return@LaunchedEffect
+ view.setPage(
+ pageId = content.page.id,
+ width = content.page.widthPts,
+ height = content.page.heightPts,
+ template = runCatching { PageTemplate.valueOf(content.page.template) }
+ .getOrDefault(PageTemplate.RULED),
+ strokes = content.strokes,
+ questions = content.questions,
+ pdfBackground = content.pdfBackground,
+ textObjects = content.textObjects,
+ paperColor = content.page.paperColor
+ )
+ }
+
+ // Read-only previews of the adjacent pages for continuous scrolling.
+ LaunchedEffect(pageContent?.loadToken, pages, canvasRef) {
+ val content = pageContent ?: return@LaunchedEffect
+ val view = canvasRef ?: return@LaunchedEffect
+ val app = context.applicationContext as com.inkproof.app.InkProofApp
+ val idx = pages.indexOfFirst { it.id == content.page.id }
+
+ suspend fun neighbor(i: Int): InkCanvasView.NeighborPage? {
+ val p = pages.getOrNull(i) ?: return null
+ return InkCanvasView.NeighborPage(
+ pageId = p.id,
+ width = p.widthPts,
+ height = p.heightPts,
+ template = runCatching { PageTemplate.valueOf(p.template) }
+ .getOrDefault(PageTemplate.RULED),
+ paperColor = p.paperColor,
+ strokes = app.pageRepository.strokesForPage(p.id)
+ )
+ }
+ if (idx >= 0) view.setNeighbors(neighbor(idx - 1), neighbor(idx + 1))
+ }
+
+ // Chrome (outside the page) follows the app theme; the page keeps its template.
+ val chromeColor = MaterialTheme.colorScheme.background
+ LaunchedEffect(chromeColor, canvasRef) {
+ canvasRef?.setChromeColor(chromeColor.toArgb())
+ }
+
+ // Keep tool config in sync.
+ LaunchedEffect(penStyle, settings.holdToShapeMs, settings.fingerWriting, settings.eraserRadius, settings.stabilization, settings.stylusDoubleTap, shapeKind, canvasRef) {
+ canvasRef?.let {
+ it.penStyle = penStyle
+ it.holdToShapeMs = settings.holdToShapeMs
+ it.fingerWritingEnabled = settings.fingerWriting
+ it.eraserRadiusPage = settings.eraserRadius
+ it.stabilization =
+ com.inkproof.app.ink.StrokeStabilizer.Level.fromName(settings.stabilization)
+ it.activeShapeKind = shapeKind
+ it.stylusDoubleTapEnabled = settings.stylusDoubleTap
+ it.onStylusDoubleTap = { viewModel.stylusToggleEraser() }
+ }
+ }
+
+ Column(Modifier.fillMaxSize().background(MaterialTheme.colorScheme.background)) {
+ EditorToolbar(
+ title = title,
+ penStyle = penStyle,
+ canUndo = canUndo,
+ canRedo = canRedo,
+ shapeKind = shapeKind,
+ onShapeKind = { shapeKind = it },
+ eraserRadius = settings.eraserRadius,
+ onEraserRadius = viewModel::setEraserRadius,
+ onBack = onBack,
+ onTool = viewModel::setTool,
+ onColor = viewModel::setColor,
+ onWidth = viewModel::setWidth,
+ onUndo = viewModel::undo,
+ onRedo = viewModel::redo,
+ onAddQuestion = { showQuestionComposer = true },
+ onAddPage = { kind -> viewModel.addPage(kind) },
+ onDeletePage = viewModel::deleteCurrentPage,
+ onTemplates = { showTemplatePicker = true },
+ onPaperColor = { showPaperColorPicker = true },
+ onExportPdf = viewModel::exportPdf,
+ onZoomFit = { canvasRef?.zoomToFit() },
+ onTogglePages = { showPageRail = !showPageRail },
+ onPaste = viewModel::paste
+ )
+
+ Row(Modifier.fillMaxSize()) {
+ // ----- page rail -----
+ AnimatedVisibility(visible = showPageRail) {
+ PageRail(
+ pages = pages,
+ currentPageId = pageContent?.page?.id,
+ onSelect = viewModel::selectPage,
+ onMove = { pageId, delta -> viewModel.movePage(pageId, delta) },
+ onAdd = {
+ viewModel.addPage(
+ if (pageContent?.page?.kind == PageKind.MATH_QUESTION.name)
+ PageKind.MATH_QUESTION else PageKind.NOTE,
+ runCatching {
+ PageTemplate.valueOf(pageContent?.page?.template ?: "RULED")
+ }.getOrDefault(PageTemplate.RULED)
+ )
+ }
+ )
+ }
+
+ // ----- canvas -----
+ Box(Modifier.weight(1f).fillMaxHeight()) {
+ AndroidView(
+ factory = { ctx ->
+ InkCanvasView(ctx).also { view ->
+ view.listener = object : InkCanvasView.Listener {
+ override fun onStrokeCommitted(stroke: Stroke) {
+ viewModel.onStrokeCommitted(stroke)
+ }
+
+ override fun onStrokesErased(strokes: List) {
+ viewModel.onStrokesErased(strokes)
+ }
+
+ override fun onSelectionChanged(
+ strokes: List,
+ screenBounds: RectF?
+ ) {
+ viewModel.onSelectionChanged(strokes, screenBounds)
+ }
+
+ override fun onStrokesMoved(
+ before: List,
+ after: List
+ ) {
+ viewModel.onStrokesMoved(before, after)
+ }
+
+ override fun onTextTap(
+ pageX: Float,
+ pageY: Float,
+ existing: com.inkproof.app.model.TextObject?
+ ) {
+ textDialog = Triple(pageX, pageY, existing)
+ }
+
+ override fun onScrollToPage(pageId: String) {
+ viewModel.selectPage(pageId)
+ }
+ }
+ canvasRef = view
+ }
+ },
+ modifier = Modifier.fillMaxSize()
+ )
+
+ // ----- lasso contextual actions -----
+ val (selectedStrokes, selectionBounds) = selection
+ if (selectedStrokes.isNotEmpty() && selectionBounds != null) {
+ SelectionActions(
+ bounds = selectionBounds,
+ onCheck = { viewModel.checkSelection(CheckAction.CHECK) },
+ onSolve = { viewModel.checkSelection(CheckAction.SOLVE) },
+ onCopy = viewModel::copySelection,
+ onCut = {
+ viewModel.copySelection()
+ canvasRef?.deleteSelection()
+ },
+ onDuplicate = {
+ viewModel.copySelection()
+ viewModel.paste()
+ },
+ onRecognize = viewModel::recognizeSelection,
+ onDelete = { canvasRef?.deleteSelection() },
+ onRecolor = { color -> canvasRef?.recolorSelection(color) },
+ onWidth = { w -> canvasRef?.setSelectionWidth(w) },
+ onDismiss = { canvasRef?.clearSelection() }
+ )
+ }
+
+ // ----- page navigation pill -----
+ val pageIndex = pages.indexOfFirst { it.id == pageContent?.page?.id }
+ if (pages.isNotEmpty() && pageIndex >= 0) {
+ PageNavPill(
+ index = pageIndex,
+ count = pages.size,
+ onPrev = { viewModel.selectPage(pages[pageIndex - 1].id) },
+ onNext = { viewModel.selectPage(pages[pageIndex + 1].id) },
+ onShowPages = { showPageRail = !showPageRail },
+ modifier = Modifier
+ .align(Alignment.BottomStart)
+ .padding(16.dp)
+ )
+ }
+
+ // ----- per-question CHECK buttons -----
+ val content = pageContent
+ if (content != null && content.questions.isNotEmpty() &&
+ checkState is CheckUiState.Hidden
+ ) {
+ QuestionActionsOverlay(
+ questions = content.questions,
+ onCheck = { qid -> viewModel.checkQuestion(qid, CheckAction.CHECK) },
+ onSolve = { qid -> viewModel.checkQuestion(qid, CheckAction.SOLVE) },
+ onEditText = { qid, text -> viewModel.updateQuestionText(qid, text) },
+ onDeleteQuestion = { qid -> viewModel.deleteQuestion(qid) },
+ modifier = Modifier
+ .align(Alignment.BottomEnd)
+ .padding(20.dp)
+ )
+ }
+ }
+
+ // ----- check result side panel -----
+ AnimatedVisibility(
+ visible = checkState !is CheckUiState.Hidden,
+ enter = slideInHorizontally(initialOffsetX = { it }) + fadeIn(),
+ exit = slideOutHorizontally(targetOffsetX = { it }) + fadeOut()
+ ) {
+ CheckPanel(
+ state = checkState,
+ onDismiss = viewModel::dismissCheck,
+ onTryAgain = viewModel::dismissCheck,
+ onRetryCheck = { qid, action -> viewModel.checkQuestion(qid, action) },
+ onSelectRegion = {
+ // Let the student lasso exactly the work to be read.
+ viewModel.setTool(ToolType.LASSO)
+ viewModel.dismissCheck()
+ },
+ onEditQuestion = { qid ->
+ editQuestionId = qid
+ viewModel.dismissCheck()
+ },
+ autoShowFirstHint = settings.autoShowHints
+ )
+ }
+ }
+ }
+
+ // SELECT → RECOGNIZE MATH result. Never replaces handwriting silently.
+ val recognitionUi by viewModel.recognition.collectAsState()
+ recognitionUi?.let { rec ->
+ var editMode by remember(rec) { mutableStateOf(false) }
+ var editedText by remember(rec) { mutableStateOf(rec.text) }
+ AlertDialog(
+ onDismissRequest = viewModel::dismissRecognition,
+ title = { Text("Recognize math") },
+ text = {
+ when {
+ rec.loading -> Row(verticalAlignment = Alignment.CenterVertically) {
+ CircularProgressIndicator(modifier = Modifier.size(22.dp))
+ Spacer(Modifier.width(12.dp))
+ Text("Reading your selection…")
+ }
+ rec.uncertain && rec.text.isBlank() -> Text(
+ "I couldn't confidently read this selection. " +
+ "Try selecting a cleaner region, or write a little larger."
+ )
+ editMode -> OutlinedTextField(
+ value = editedText,
+ onValueChange = { editedText = it },
+ minLines = 2,
+ modifier = Modifier.fillMaxWidth()
+ )
+ else -> Column {
+ Surface(
+ shape = RoundedCornerShape(10.dp),
+ color = MaterialTheme.colorScheme.surfaceVariant,
+ modifier = Modifier.fillMaxWidth()
+ ) {
+ Text(
+ rec.text,
+ style = MaterialTheme.typography.titleMedium,
+ modifier = Modifier.padding(14.dp)
+ )
+ }
+ Spacer(Modifier.height(8.dp))
+ Text(
+ if (rec.uncertain)
+ "Low confidence (${(rec.confidence * 100).toInt()}%) — please verify."
+ else "Confidence ${(rec.confidence * 100).toInt()}%. " +
+ "Your handwriting stays untouched.",
+ style = MaterialTheme.typography.bodySmall,
+ color = if (rec.uncertain) WarnAmber else MutedText
+ )
+ }
+ }
+ },
+ confirmButton = {
+ when {
+ rec.loading -> Unit
+ rec.uncertain && rec.text.isBlank() -> TextButton(
+ onClick = viewModel::recognizeSelection
+ ) { Text("Try again") }
+ else -> TextButton(
+ enabled = (if (editMode) editedText else rec.text).isNotBlank(),
+ onClick = {
+ viewModel.acceptRecognition(
+ (if (editMode) editedText else rec.text).trim()
+ )
+ }
+ ) { Text("Accept") }
+ }
+ },
+ dismissButton = {
+ Row {
+ if (!rec.loading && rec.text.isNotBlank() && !editMode) {
+ TextButton(onClick = { editMode = true }) { Text("Edit") }
+ }
+ TextButton(onClick = viewModel::dismissRecognition) { Text("Cancel") }
+ }
+ }
+ )
+ }
+
+ editQuestionId?.let { qid ->
+ val question = pageContent?.questions?.firstOrNull { it.id == qid }
+ if (question == null) {
+ editQuestionId = null
+ } else {
+ var editText by remember(qid) {
+ mutableStateOf(question.typedText.orEmpty())
+ }
+ AlertDialog(
+ onDismissRequest = { editQuestionId = null },
+ title = { Text("Edit question") },
+ text = {
+ Column {
+ Text(
+ "Fix the question statement, then run the check again.",
+ style = MaterialTheme.typography.bodySmall,
+ color = MutedText
+ )
+ Spacer(Modifier.height(10.dp))
+ OutlinedTextField(
+ value = editText,
+ onValueChange = { editText = it },
+ minLines = 2,
+ modifier = Modifier.fillMaxWidth()
+ )
+ }
+ },
+ confirmButton = {
+ TextButton(
+ enabled = editText.isNotBlank(),
+ onClick = {
+ viewModel.updateQuestionText(qid, editText.trim())
+ editQuestionId = null
+ }
+ ) { Text("Save") }
+ },
+ dismissButton = {
+ TextButton(onClick = { editQuestionId = null }) { Text("Cancel") }
+ }
+ )
+ }
+ }
+
+ if (showQuestionComposer) {
+ QuestionComposerDialog(
+ onDismiss = { showQuestionComposer = false },
+ onCreate = { type, text ->
+ viewModel.createQuestion(type, text)
+ showQuestionComposer = false
+ },
+ onImportImage = {
+ showQuestionComposer = false
+ questionImageLauncher.launch(arrayOf("image/*"))
+ },
+ onImportPdf = {
+ showQuestionComposer = false
+ questionPdfLauncher.launch(arrayOf("application/pdf"))
+ }
+ )
+ }
+
+ if (showPaperColorPicker) {
+ val currentPaper = pageContent?.page?.paperColor ?: PaperColors.WHITE
+ AlertDialog(
+ onDismissRequest = { showPaperColorPicker = false },
+ title = { Text("Page color") },
+ text = {
+ Column {
+ Text(
+ "Paper color is per page and never changes your ink.",
+ style = MaterialTheme.typography.bodySmall,
+ color = MutedText
+ )
+ Spacer(Modifier.height(12.dp))
+ PaperColors.all.chunked(4).forEach { row ->
+ Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {
+ row.forEach { (label, color) ->
+ Column(
+ horizontalAlignment = Alignment.CenterHorizontally,
+ modifier = Modifier.clickable {
+ viewModel.setPaperColor(color)
+ showPaperColorPicker = false
+ }
+ ) {
+ Box(
+ modifier = Modifier
+ .size(44.dp)
+ .clip(RoundedCornerShape(10.dp))
+ .background(Color(color))
+ .border(
+ if (color == currentPaper) 3.dp else 1.dp,
+ if (color == currentPaper) InkNavy else Divider,
+ RoundedCornerShape(10.dp)
+ )
+ )
+ Spacer(Modifier.height(4.dp))
+ Text(
+ label,
+ style = MaterialTheme.typography.labelSmall,
+ color = MutedText
+ )
+ }
+ }
+ }
+ Spacer(Modifier.height(10.dp))
+ }
+ }
+ },
+ confirmButton = {
+ TextButton(onClick = { showPaperColorPicker = false }) { Text("Done") }
+ }
+ )
+ }
+
+ if (showTemplatePicker) {
+ TemplatePickerDialog(
+ onDismiss = { showTemplatePicker = false },
+ onPick = { template ->
+ viewModel.setTemplate(template)
+ showTemplatePicker = false
+ }
+ )
+ }
+
+ textDialog?.let { (tapX, tapY, existing) ->
+ TextObjectDialog(
+ existing = existing,
+ onDismiss = { textDialog = null },
+ onSave = { text ->
+ val pageId = pageContent?.page?.id
+ if (pageId != null && text.isNotBlank()) {
+ val obj = existing?.copy(text = text)
+ ?: com.inkproof.app.model.TextObject(
+ pageId = pageId, text = text, x = tapX, y = tapY
+ )
+ viewModel.addOrUpdateText(obj)
+ }
+ textDialog = null
+ },
+ onDelete = existing?.let { obj ->
+ {
+ viewModel.deleteText(obj.id)
+ textDialog = null
+ }
+ }
+ )
+ }
+}
+
+// ============================= text dialog =============================
+
+@Composable
+private fun TextObjectDialog(
+ existing: com.inkproof.app.model.TextObject?,
+ onDismiss: () -> Unit,
+ onSave: (String) -> Unit,
+ onDelete: (() -> Unit)?
+) {
+ var text by remember { mutableStateOf(existing?.text ?: "") }
+ AlertDialog(
+ onDismissRequest = onDismiss,
+ title = { Text(if (existing == null) "Add text" else "Edit text") },
+ text = {
+ OutlinedTextField(
+ value = text,
+ onValueChange = { text = it },
+ placeholder = { Text("Type text to place on the page…") },
+ minLines = 2,
+ maxLines = 6,
+ modifier = Modifier.fillMaxWidth()
+ )
+ },
+ confirmButton = {
+ TextButton(onClick = { onSave(text) }, enabled = text.isNotBlank()) {
+ Text(if (existing == null) "Add" else "Save")
+ }
+ },
+ dismissButton = {
+ Row {
+ if (onDelete != null) {
+ TextButton(onClick = onDelete) {
+ Text("Delete", color = MaterialTheme.colorScheme.error)
+ }
+ }
+ TextButton(onClick = onDismiss) { Text("Cancel") }
+ }
+ }
+ )
+}
+
+// ============================= toolbar =============================
+
+@Composable
+private fun EditorToolbar(
+ title: String,
+ penStyle: com.inkproof.app.model.PenStyle,
+ canUndo: Boolean,
+ canRedo: Boolean,
+ shapeKind: com.inkproof.app.model.ShapeType,
+ onShapeKind: (com.inkproof.app.model.ShapeType) -> Unit,
+ eraserRadius: Float,
+ onEraserRadius: (Float) -> Unit,
+ onBack: () -> Unit,
+ onTool: (ToolType) -> Unit,
+ onColor: (Int) -> Unit,
+ onWidth: (Float) -> Unit,
+ onUndo: () -> Unit,
+ onRedo: () -> Unit,
+ onAddQuestion: () -> Unit,
+ onAddPage: (PageKind) -> Unit,
+ onDeletePage: () -> Unit,
+ onTemplates: () -> Unit,
+ onPaperColor: () -> Unit,
+ onExportPdf: () -> Unit,
+ onZoomFit: () -> Unit,
+ onTogglePages: () -> Unit,
+ onPaste: () -> Unit
+) {
+ var customColorOpen by remember { mutableStateOf(false) }
+ var overflowOpen by remember { mutableStateOf(false) }
+
+ Surface(color = MaterialTheme.colorScheme.surface, shadowElevation = 2.dp) {
+ Column {
+ Row(
+ verticalAlignment = Alignment.CenterVertically,
+ modifier = Modifier
+ .fillMaxWidth()
+ .height(56.dp)
+ .padding(horizontal = 8.dp)
+ ) {
+ IconButton(onClick = onBack) {
+ Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back")
+ }
+ Text(
+ title,
+ style = MaterialTheme.typography.titleMedium,
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis,
+ modifier = Modifier.width(160.dp)
+ )
+ Spacer(Modifier.width(12.dp))
+
+ // Tools — selecting a tool shows its options in the horizontal
+ // contextual strip below (Notewise-style). No vertical menus
+ // ever cover the notebook.
+ ToolButton(
+ selected = penStyle.tool == ToolType.PEN,
+ icon = { Icon(Icons.Outlined.Edit, "Pen") },
+ onClick = { onTool(ToolType.PEN) }
+ )
+ ToolButton(
+ selected = penStyle.tool == ToolType.HIGHLIGHTER,
+ icon = { Icon(Icons.Outlined.BorderColor, "Highlighter") },
+ onClick = { onTool(ToolType.HIGHLIGHTER) }
+ )
+ ToolButton(
+ selected = penStyle.tool == ToolType.ERASER,
+ icon = { Icon(Icons.Outlined.Backspace, "Eraser") },
+ onClick = { onTool(ToolType.ERASER) }
+ )
+ ToolButton(
+ selected = penStyle.tool == ToolType.LASSO,
+ icon = { Icon(Icons.Outlined.HighlightAlt, "Lasso") },
+ onClick = { onTool(ToolType.LASSO) }
+ )
+ ToolButton(
+ selected = penStyle.tool == ToolType.SHAPE,
+ icon = { Icon(Icons.Outlined.Category, "Shapes") },
+ onClick = { onTool(ToolType.SHAPE) }
+ )
+ ToolButton(
+ selected = penStyle.tool == ToolType.TEXT,
+ icon = { Icon(Icons.Outlined.TextFields, "Text") },
+ onClick = { onTool(ToolType.TEXT) }
+ )
+ ToolButton(
+ selected = penStyle.tool == ToolType.PAN,
+ icon = { Icon(Icons.Outlined.Gesture, "Pan") },
+ onClick = { onTool(ToolType.PAN) }
+ )
+
+ // Current color indicator
+ Box(
+ modifier = Modifier
+ .padding(horizontal = 6.dp)
+ .size(22.dp)
+ .clip(CircleShape)
+ .background(Color(penStyle.color))
+ .border(1.5.dp, Divider, CircleShape)
+ .clickable { customColorOpen = true }
+ )
+
+ Spacer(Modifier.weight(1f))
+
+ IconButton(onClick = onUndo, enabled = canUndo) {
+ Icon(Icons.AutoMirrored.Filled.Undo, "Undo",
+ tint = if (canUndo) MaterialTheme.colorScheme.onSurface else Divider)
+ }
+ IconButton(onClick = onRedo, enabled = canRedo) {
+ Icon(Icons.AutoMirrored.Filled.Redo, "Redo",
+ tint = if (canRedo) MaterialTheme.colorScheme.onSurface else Divider)
+ }
+
+ // + QUESTION is always available: questions are first-class
+ // objects on any normal page, never a special page type.
+ run {
+ Surface(
+ shape = RoundedCornerShape(10.dp),
+ color = MaterialTheme.colorScheme.secondaryContainer,
+ modifier = Modifier
+ .padding(horizontal = 6.dp)
+ .clickable(onClick = onAddQuestion)
+ ) {
+ Row(
+ verticalAlignment = Alignment.CenterVertically,
+ modifier = Modifier.padding(horizontal = 12.dp, vertical = 7.dp)
+ ) {
+ Icon(
+ Icons.Filled.Add, null,
+ tint = ProofGreen, modifier = Modifier.size(16.dp)
+ )
+ Spacer(Modifier.width(4.dp))
+ Text(
+ "Question",
+ style = MaterialTheme.typography.labelLarge,
+ color = MaterialTheme.colorScheme.onSecondaryContainer
+ )
+ }
+ }
+ }
+
+ Box {
+ IconButton(onClick = { overflowOpen = true }) {
+ Icon(Icons.Filled.MoreVert, "More")
+ }
+ DropdownMenu(expanded = overflowOpen, onDismissRequest = { overflowOpen = false }) {
+ DropdownMenuItem(
+ text = { Text("Add note page") },
+ onClick = { overflowOpen = false; onAddPage(PageKind.NOTE) }
+ )
+ DropdownMenuItem(
+ text = { Text("Add question page") },
+ onClick = { overflowOpen = false; onAddPage(PageKind.MATH_QUESTION) }
+ )
+ DropdownMenuItem(
+ text = { Text("Delete this page") },
+ onClick = { overflowOpen = false; onDeletePage() }
+ )
+ DropdownMenuItem(
+ text = { Text("Page template…") },
+ onClick = { overflowOpen = false; onTemplates() }
+ )
+ DropdownMenuItem(
+ text = { Text("Page color…") },
+ onClick = { overflowOpen = false; onPaperColor() }
+ )
+ DropdownMenuItem(
+ text = { Text("Paste") },
+ onClick = { overflowOpen = false; onPaste() }
+ )
+ DropdownMenuItem(
+ text = { Text("Zoom to fit") },
+ onClick = { overflowOpen = false; onZoomFit() }
+ )
+ DropdownMenuItem(
+ text = { Text("Show/hide pages") },
+ onClick = { overflowOpen = false; onTogglePages() }
+ )
+ DropdownMenuItem(
+ text = { Text("Export PDF") },
+ onClick = { overflowOpen = false; onExportPdf() }
+ )
+ }
+ }
+ }
+
+ // Horizontal contextual options for the active tool — compact,
+ // scrollable sideways when width-constrained, never a tall menu.
+ ToolOptionsStrip(
+ penStyle = penStyle,
+ shapeKind = shapeKind,
+ onShapeKind = onShapeKind,
+ eraserRadius = eraserRadius,
+ onEraserRadius = onEraserRadius,
+ onColor = onColor,
+ onWidth = onWidth,
+ onCustomColor = { customColorOpen = true }
+ )
+ }
+ }
+
+ if (customColorOpen) {
+ CustomColorDialog(
+ initialColor = penStyle.color,
+ onPick = { picked -> onColor(picked); customColorOpen = false },
+ onDismiss = { customColorOpen = false }
+ )
+ }
+}
+
+/**
+ * Notewise-style contextual strip: one compact horizontal row of options
+ * for the active tool, directly under the main toolbar. Scrolls
+ * horizontally when the screen is narrow; never a vertical dropdown.
+ */
+@Composable
+private fun ToolOptionsStrip(
+ penStyle: com.inkproof.app.model.PenStyle,
+ shapeKind: com.inkproof.app.model.ShapeType,
+ onShapeKind: (com.inkproof.app.model.ShapeType) -> Unit,
+ eraserRadius: Float,
+ onEraserRadius: (Float) -> Unit,
+ onColor: (Int) -> Unit,
+ onWidth: (Float) -> Unit,
+ onCustomColor: () -> Unit
+) {
+ val tool = penStyle.tool
+ val hasOptions = tool == ToolType.PEN || tool == ToolType.HIGHLIGHTER ||
+ tool == ToolType.ERASER || tool == ToolType.SHAPE
+ if (!hasOptions) return
+
+ Row(
+ verticalAlignment = Alignment.CenterVertically,
+ horizontalArrangement = Arrangement.spacedBy(8.dp),
+ modifier = Modifier
+ .fillMaxWidth()
+ .height(42.dp)
+ .horizontalScroll(rememberScrollState())
+ .padding(horizontal = 12.dp)
+ ) {
+ when (tool) {
+ ToolType.PEN, ToolType.HIGHLIGHTER -> {
+ val colors = if (tool == ToolType.HIGHLIGHTER) {
+ PenPalette.highlighterColors
+ } else {
+ PenPalette.penColors
+ }
+ val widths = if (tool == ToolType.HIGHLIGHTER) {
+ PenPalette.highlighterWidths
+ } else {
+ PenPalette.penWidths
+ }
+ colors.forEach { c ->
+ Box(
+ modifier = Modifier
+ .size(24.dp)
+ .clip(CircleShape)
+ .background(Color(c))
+ .border(
+ if (c == penStyle.color) 2.5.dp else 1.dp,
+ if (c == penStyle.color) {
+ MaterialTheme.colorScheme.primary
+ } else {
+ Divider
+ },
+ CircleShape
+ )
+ .clickable { onColor(c) }
+ )
+ }
+ if (tool == ToolType.PEN) {
+ Box(
+ contentAlignment = Alignment.Center,
+ modifier = Modifier
+ .size(24.dp)
+ .clip(CircleShape)
+ .border(1.dp, Divider, CircleShape)
+ .clickable(onClick = onCustomColor)
+ ) {
+ Icon(
+ Icons.Filled.Add,
+ contentDescription = "Custom color",
+ tint = MutedText,
+ modifier = Modifier.size(14.dp)
+ )
+ }
+ }
+ Box(
+ Modifier
+ .padding(horizontal = 4.dp)
+ .size(1.dp, 24.dp)
+ .background(Divider)
+ )
+ widths.forEach { w ->
+ Box(
+ contentAlignment = Alignment.Center,
+ modifier = Modifier
+ .size(32.dp)
+ .clip(CircleShape)
+ .background(
+ if (w == penStyle.baseWidth) {
+ MaterialTheme.colorScheme.primaryContainer
+ } else {
+ Color.Transparent
+ }
+ )
+ .clickable { onWidth(w) }
+ ) {
+ Box(
+ modifier = Modifier
+ .size((w * 1.4f).coerceIn(4f, 22f).dp)
+ .clip(CircleShape)
+ .background(Color(penStyle.color))
+ )
+ }
+ }
+ }
+
+ ToolType.ERASER -> {
+ listOf("Small" to 10f, "Medium" to 18f, "Large" to 34f)
+ .forEach { (label, r) ->
+ val selected = eraserRadius == r
+ Surface(
+ shape = RoundedCornerShape(16.dp),
+ color = if (selected) {
+ MaterialTheme.colorScheme.primaryContainer
+ } else {
+ MaterialTheme.colorScheme.surfaceVariant
+ },
+ modifier = Modifier.clickable { onEraserRadius(r) }
+ ) {
+ Row(
+ verticalAlignment = Alignment.CenterVertically,
+ modifier = Modifier
+ .padding(horizontal = 12.dp, vertical = 6.dp)
+ ) {
+ Box(
+ Modifier
+ .size((r / 1.8f).coerceIn(6f, 20f).dp)
+ .clip(CircleShape)
+ .border(
+ 1.5.dp,
+ MaterialTheme.colorScheme.outline,
+ CircleShape
+ )
+ )
+ Spacer(Modifier.width(8.dp))
+ Text(
+ label,
+ style = MaterialTheme.typography.labelLarge,
+ fontWeight = if (selected) FontWeight.Bold else null
+ )
+ }
+ }
+ }
+ }
+
+ ToolType.SHAPE -> {
+ listOf(
+ com.inkproof.app.model.ShapeType.LINE to "Line",
+ com.inkproof.app.model.ShapeType.ARROW to "Arrow",
+ com.inkproof.app.model.ShapeType.RECTANGLE to "Rectangle",
+ com.inkproof.app.model.ShapeType.SQUARE to "Square",
+ com.inkproof.app.model.ShapeType.CIRCLE to "Circle",
+ com.inkproof.app.model.ShapeType.ELLIPSE to "Ellipse",
+ com.inkproof.app.model.ShapeType.TRIANGLE to "Triangle"
+ ).forEach { (kind, label) ->
+ val selected = shapeKind == kind
+ Surface(
+ shape = RoundedCornerShape(16.dp),
+ color = if (selected) {
+ MaterialTheme.colorScheme.primaryContainer
+ } else {
+ MaterialTheme.colorScheme.surfaceVariant
+ },
+ modifier = Modifier.clickable { onShapeKind(kind) }
+ ) {
+ Text(
+ label,
+ style = MaterialTheme.typography.labelLarge,
+ fontWeight = if (selected) FontWeight.Bold else null,
+ modifier = Modifier
+ .padding(horizontal = 14.dp, vertical = 7.dp)
+ )
+ }
+ }
+ }
+
+ else -> Unit
+ }
+ }
+}
+
+@Composable
+private fun ToolButton(
+ selected: Boolean,
+ icon: @Composable () -> Unit,
+ onClick: () -> Unit
+) {
+ Surface(
+ shape = RoundedCornerShape(10.dp),
+ color = if (selected) MaterialTheme.colorScheme.primaryContainer else Color.Transparent,
+ contentColor = if (selected) InkNavy else MutedText,
+ modifier = Modifier
+ .padding(horizontal = 2.dp)
+ .size(40.dp)
+ .clickable(onClick = onClick)
+ ) {
+ Box(contentAlignment = Alignment.Center, modifier = Modifier.fillMaxSize()) {
+ icon()
+ }
+ }
+}
+
+/** Simple HSV color picker: hue / saturation / brightness sliders with live preview. */
+@Composable
+private fun CustomColorDialog(
+ initialColor: Int,
+ onPick: (Int) -> Unit,
+ onDismiss: () -> Unit
+) {
+ val initialHsv = remember(initialColor) {
+ FloatArray(3).also { android.graphics.Color.colorToHSV(initialColor, it) }
+ }
+ var hue by remember { mutableStateOf(initialHsv[0]) }
+ var sat by remember { mutableStateOf(initialHsv[1]) }
+ var value by remember { mutableStateOf(initialHsv[2]) }
+ val preview = android.graphics.Color.HSVToColor(floatArrayOf(hue, sat, value))
+
+ AlertDialog(
+ onDismissRequest = onDismiss,
+ title = { Text("Custom color") },
+ text = {
+ Column {
+ Box(
+ modifier = Modifier
+ .fillMaxWidth()
+ .height(48.dp)
+ .clip(RoundedCornerShape(10.dp))
+ .background(Color(preview))
+ .border(1.dp, Divider, RoundedCornerShape(10.dp))
+ )
+ Spacer(Modifier.height(16.dp))
+ Text("Hue", style = MaterialTheme.typography.labelMedium, color = MutedText)
+ Slider(value = hue, onValueChange = { hue = it }, valueRange = 0f..360f)
+ Text("Saturation", style = MaterialTheme.typography.labelMedium, color = MutedText)
+ Slider(value = sat, onValueChange = { sat = it }, valueRange = 0f..1f)
+ Text("Brightness", style = MaterialTheme.typography.labelMedium, color = MutedText)
+ Slider(value = value, onValueChange = { value = it }, valueRange = 0f..1f)
+ }
+ },
+ confirmButton = {
+ TextButton(onClick = { onPick(preview) }) { Text("Use color") }
+ },
+ dismissButton = {
+ TextButton(onClick = onDismiss) { Text("Cancel") }
+ }
+ )
+}
+
+// ============================= page rail =============================
+
+@Composable
+private fun PageRail(
+ pages: List,
+ currentPageId: String?,
+ onSelect: (String) -> Unit,
+ onMove: (String, Int) -> Unit,
+ onAdd: () -> Unit
+) {
+ Surface(
+ color = MaterialTheme.colorScheme.surface,
+ modifier = Modifier
+ .width(120.dp)
+ .fillMaxHeight()
+ ) {
+ LazyColumn(
+ contentPadding = PaddingValues(10.dp),
+ verticalArrangement = Arrangement.spacedBy(10.dp),
+ modifier = Modifier.fillMaxSize()
+ ) {
+ itemsIndexed(pages, key = { _, p -> p.id }) { index, page ->
+ PageThumb(
+ index = index,
+ pageId = page.id,
+ selected = page.id == currentPageId,
+ canMoveUp = index > 0,
+ canMoveDown = index < pages.lastIndex,
+ onClick = { onSelect(page.id) },
+ onMove = { delta -> onMove(page.id, delta) }
+ )
+ }
+ item {
+ Surface(
+ shape = RoundedCornerShape(10.dp),
+ color = MaterialTheme.colorScheme.surfaceVariant,
+ modifier = Modifier
+ .fillMaxWidth()
+ .height(52.dp)
+ .clickable(onClick = onAdd)
+ ) {
+ Box(contentAlignment = Alignment.Center, modifier = Modifier.fillMaxSize()) {
+ Icon(Icons.Filled.Add, "Add page", tint = MutedText)
+ }
+ }
+ }
+ }
+ }
+}
+
+@OptIn(androidx.compose.foundation.ExperimentalFoundationApi::class)
+@Composable
+private fun PageThumb(
+ index: Int,
+ pageId: String,
+ selected: Boolean,
+ canMoveUp: Boolean,
+ canMoveDown: Boolean,
+ onClick: () -> Unit,
+ onMove: (Int) -> Unit
+) {
+ val context = LocalContext.current
+ var thumb by remember(pageId) { mutableStateOf(null) }
+ var pageMenu by remember { mutableStateOf(false) }
+
+ LaunchedEffect(pageId, selected) {
+ val app = context.applicationContext as com.inkproof.app.InkProofApp
+ val page = app.libraryRepository.page(pageId) ?: return@LaunchedEffect
+ val strokes = app.pageRepository.strokesForPage(pageId)
+ val template = runCatching { PageTemplate.valueOf(page.template) }
+ .getOrDefault(PageTemplate.BLANK)
+ thumb = ThumbnailRenderer.render(
+ strokes, template, page.widthPts, page.heightPts, 160, page.paperColor
+ )
+ }
+
+ Column(horizontalAlignment = Alignment.CenterHorizontally) {
+ Box {
+ Surface(
+ shape = RoundedCornerShape(8.dp),
+ border = androidx.compose.foundation.BorderStroke(
+ if (selected) 2.5.dp else 1.dp,
+ if (selected) InkNavy else Divider
+ ),
+ modifier = Modifier
+ .fillMaxWidth()
+ .height(120.dp)
+ .combinedClickable(onClick = onClick, onLongClick = { pageMenu = true })
+ ) {
+ thumb?.let {
+ Image(
+ bitmap = it.asImageBitmap(),
+ contentDescription = "Page ${index + 1}",
+ contentScale = ContentScale.Crop,
+ alignment = Alignment.TopCenter,
+ modifier = Modifier.fillMaxSize()
+ )
+ }
+ }
+ DropdownMenu(expanded = pageMenu, onDismissRequest = { pageMenu = false }) {
+ if (canMoveUp) {
+ DropdownMenuItem(
+ text = { Text("Move up") },
+ onClick = { pageMenu = false; onMove(-1) }
+ )
+ }
+ if (canMoveDown) {
+ DropdownMenuItem(
+ text = { Text("Move down") },
+ onClick = { pageMenu = false; onMove(1) }
+ )
+ }
+ }
+ }
+ Text(
+ "${index + 1}",
+ style = MaterialTheme.typography.bodySmall,
+ color = if (selected) InkNavy else MutedText,
+ modifier = Modifier.padding(top = 2.dp)
+ )
+ }
+}
+
+// ============================= selection actions =============================
+
+@Composable
+private fun SelectionActions(
+ bounds: RectF,
+ onCheck: () -> Unit,
+ onSolve: () -> Unit,
+ onCopy: () -> Unit,
+ onCut: () -> Unit,
+ onDuplicate: () -> Unit,
+ onRecognize: () -> Unit,
+ onDelete: () -> Unit,
+ onRecolor: (Int) -> Unit,
+ onWidth: (Float) -> Unit,
+ onDismiss: () -> Unit
+) {
+ val density = LocalContext.current.resources.displayMetrics.density
+ var recolorOpen by remember { mutableStateOf(false) }
+ var widthOpen by remember { mutableStateOf(false) }
+ var moreOpen by remember { mutableStateOf(false) }
+ val yOffset = ((bounds.top / density) - 56f).coerceAtLeast(8f)
+ val xOffset = (bounds.left / density).coerceAtLeast(8f)
+
+ Surface(
+ shape = RoundedCornerShape(12.dp),
+ shadowElevation = 6.dp,
+ color = MaterialTheme.colorScheme.surface,
+ modifier = Modifier.padding(start = xOffset.dp, top = yOffset.dp)
+ ) {
+ Row(
+ verticalAlignment = Alignment.CenterVertically,
+ modifier = Modifier.padding(horizontal = 6.dp, vertical = 4.dp)
+ ) {
+ TextButton(onClick = onCheck) { Text("Check my work", color = ProofGreen) }
+ TextButton(onClick = onSolve) { Text("Solve") }
+ TextButton(onClick = onCopy) { Text("Copy") }
+ TextButton(onClick = { recolorOpen = true }) { Text("Color") }
+ TextButton(onClick = { widthOpen = true }) { Text("Width") }
+ IconButton(onClick = onDelete) {
+ Icon(
+ Icons.Outlined.Delete, "Delete selection",
+ tint = MaterialTheme.colorScheme.error
+ )
+ }
+ Box {
+ IconButton(onClick = { moreOpen = true }) {
+ Icon(Icons.Filled.MoreVert, "More selection actions")
+ }
+ DropdownMenu(expanded = moreOpen, onDismissRequest = { moreOpen = false }) {
+ DropdownMenuItem(
+ text = { Text("Recognize math") },
+ onClick = { moreOpen = false; onRecognize() }
+ )
+ DropdownMenuItem(
+ text = { Text("Cut") },
+ onClick = { moreOpen = false; onCut() }
+ )
+ DropdownMenuItem(
+ text = { Text("Duplicate") },
+ onClick = { moreOpen = false; onDuplicate() }
+ )
+ DropdownMenuItem(
+ text = { Text("Deselect") },
+ onClick = { moreOpen = false; onDismiss() }
+ )
+ }
+ }
+ DropdownMenu(expanded = recolorOpen, onDismissRequest = { recolorOpen = false }) {
+ Column(Modifier.padding(horizontal = 10.dp, vertical = 6.dp)) {
+ PenPalette.penColors.chunked(6).forEach { rowColors ->
+ Row {
+ rowColors.forEach { c ->
+ Box(
+ modifier = Modifier
+ .padding(3.dp)
+ .size(28.dp)
+ .clip(CircleShape)
+ .background(Color(c))
+ .border(1.dp, MaterialTheme.colorScheme.outline, CircleShape)
+ .clickable { onRecolor(c); recolorOpen = false }
+ )
+ }
+ }
+ }
+ }
+ }
+ DropdownMenu(expanded = widthOpen, onDismissRequest = { widthOpen = false }) {
+ Row(
+ verticalAlignment = Alignment.CenterVertically,
+ modifier = Modifier.padding(horizontal = 10.dp, vertical = 6.dp)
+ ) {
+ PenPalette.penWidths.forEach { w ->
+ Box(
+ contentAlignment = Alignment.Center,
+ modifier = Modifier
+ .padding(3.dp)
+ .size(36.dp)
+ .clip(CircleShape)
+ .clickable { onWidth(w); widthOpen = false }
+ ) {
+ Box(
+ Modifier
+ .size((w * 1.8f).coerceIn(4f, 26f).dp)
+ .clip(CircleShape)
+ .background(MaterialTheme.colorScheme.onSurface)
+ )
+ }
+ }
+ }
+ }
+ }
+ }
+}
+
+// ============================= page navigation pill =============================
+
+@Composable
+private fun PageNavPill(
+ index: Int,
+ count: Int,
+ onPrev: () -> Unit,
+ onNext: () -> Unit,
+ onShowPages: () -> Unit,
+ modifier: Modifier = Modifier
+) {
+ Surface(
+ shape = RoundedCornerShape(50),
+ shadowElevation = 4.dp,
+ color = MaterialTheme.colorScheme.surface,
+ modifier = modifier
+ ) {
+ Row(verticalAlignment = Alignment.CenterVertically) {
+ IconButton(onClick = onPrev, enabled = index > 0) {
+ Icon(
+ Icons.AutoMirrored.Filled.ArrowBack, "Previous page",
+ modifier = Modifier.size(18.dp),
+ tint = if (index > 0) MaterialTheme.colorScheme.onSurface
+ else MaterialTheme.colorScheme.outline
+ )
+ }
+ Text(
+ "${index + 1} / $count",
+ style = MaterialTheme.typography.labelLarge,
+ modifier = Modifier
+ .clip(RoundedCornerShape(8.dp))
+ .clickable(onClick = onShowPages)
+ .padding(horizontal = 6.dp, vertical = 8.dp)
+ )
+ IconButton(onClick = onNext, enabled = index < count - 1) {
+ Icon(
+ Icons.AutoMirrored.Filled.ArrowForward, "Next page",
+ modifier = Modifier.size(18.dp),
+ tint = if (index < count - 1) MaterialTheme.colorScheme.onSurface
+ else MaterialTheme.colorScheme.outline
+ )
+ }
+ }
+ }
+}
+
+// ============================= question overlay =============================
+
+@Composable
+private fun QuestionActionsOverlay(
+ questions: List,
+ onCheck: (String) -> Unit,
+ onSolve: (String) -> Unit,
+ onEditText: (String, String) -> Unit,
+ onDeleteQuestion: (String) -> Unit,
+ modifier: Modifier = Modifier
+) {
+ var expanded by remember { mutableStateOf(questions.size == 1) }
+ var editFor by remember { mutableStateOf(null) }
+
+ Surface(
+ shape = RoundedCornerShape(16.dp),
+ shadowElevation = 6.dp,
+ color = MaterialTheme.colorScheme.surface,
+ modifier = modifier.width(280.dp)
+ ) {
+ Column(Modifier.padding(14.dp)) {
+ Row(
+ verticalAlignment = Alignment.CenterVertically,
+ modifier = Modifier
+ .fillMaxWidth()
+ .clickable { expanded = !expanded }
+ ) {
+ Text(
+ "Check my work",
+ style = MaterialTheme.typography.titleSmall,
+ color = ProofGreen,
+ modifier = Modifier.weight(1f)
+ )
+ Text(
+ if (expanded) "Hide" else "${questions.size}",
+ style = MaterialTheme.typography.labelMedium,
+ color = MutedText
+ )
+ }
+ if (expanded) {
+ questions.forEachIndexed { index, q ->
+ Spacer(Modifier.height(10.dp))
+ Surface(
+ shape = RoundedCornerShape(10.dp),
+ color = MaterialTheme.colorScheme.surfaceVariant
+ ) {
+ Column(Modifier.padding(10.dp)) {
+ Row(verticalAlignment = Alignment.CenterVertically) {
+ Text(
+ "Q${index + 1}",
+ style = MaterialTheme.typography.labelLarge,
+ color = InkNavy,
+ modifier = Modifier.weight(1f)
+ )
+ TextButton(onClick = { editFor = q }) {
+ Text("Edit", style = MaterialTheme.typography.labelMedium)
+ }
+ TextButton(onClick = { onDeleteQuestion(q.id) }) {
+ Text(
+ "Delete",
+ style = MaterialTheme.typography.labelMedium,
+ color = MaterialTheme.colorScheme.error
+ )
+ }
+ }
+ q.typedText?.takeIf { it.isNotBlank() }?.let {
+ Text(
+ it,
+ style = MaterialTheme.typography.bodySmall,
+ color = MutedText,
+ maxLines = 2,
+ overflow = TextOverflow.Ellipsis
+ )
+ }
+ Spacer(Modifier.height(6.dp))
+ Row {
+ Surface(
+ shape = RoundedCornerShape(8.dp),
+ color = ProofGreen,
+ modifier = Modifier.clickable { onCheck(q.id) }
+ ) {
+ Text(
+ "Check my work",
+ style = MaterialTheme.typography.labelLarge,
+ color = MaterialTheme.colorScheme.onSecondary,
+ modifier = Modifier.padding(
+ horizontal = 12.dp, vertical = 7.dp
+ )
+ )
+ }
+ Spacer(Modifier.width(8.dp))
+ Surface(
+ shape = RoundedCornerShape(8.dp),
+ color = Color.Transparent,
+ border = androidx.compose.foundation.BorderStroke(1.dp, Divider),
+ modifier = Modifier.clickable { onSolve(q.id) }
+ ) {
+ Text(
+ "Solve",
+ style = MaterialTheme.typography.labelLarge,
+ color = MutedText,
+ modifier = Modifier.padding(
+ horizontal = 12.dp, vertical = 7.dp
+ )
+ )
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ editFor?.let { q ->
+ var text by remember(q.id) { mutableStateOf(q.typedText.orEmpty()) }
+ AlertDialog(
+ onDismissRequest = { editFor = null },
+ title = { Text("Edit question") },
+ text = {
+ OutlinedTextField(
+ value = text,
+ onValueChange = { text = it },
+ label = { Text("Question") },
+ minLines = 2
+ )
+ },
+ confirmButton = {
+ TextButton(onClick = { onEditText(q.id, text); editFor = null }) { Text("Save") }
+ },
+ dismissButton = {
+ TextButton(onClick = { editFor = null }) { Text("Cancel") }
+ }
+ )
+ }
+}
+
+// ============================= dialogs =============================
+
+@Composable
+private fun QuestionComposerDialog(
+ onDismiss: () -> Unit,
+ onCreate: (QuestionContentType, String?) -> Unit,
+ onImportImage: () -> Unit,
+ onImportPdf: () -> Unit
+) {
+ var mode by remember { mutableStateOf(QuestionContentType.TYPED) }
+ var text by remember { mutableStateOf("") }
+ val context = LocalContext.current
+ val clipboard = context.getSystemService(android.content.ClipboardManager::class.java)
+
+ AlertDialog(
+ onDismissRequest = onDismiss,
+ title = { Text("New question") },
+ text = {
+ Column {
+ Text(
+ "Add the problem the easiest way for you. Your solution gets its own handwriting area below it.",
+ style = MaterialTheme.typography.bodyMedium,
+ color = MutedText
+ )
+ Spacer(Modifier.height(12.dp))
+ Row(
+ horizontalArrangement = Arrangement.spacedBy(8.dp),
+ modifier = Modifier.horizontalScroll(rememberScrollState())
+ ) {
+ ModeChip("Write by hand", mode == QuestionContentType.HANDWRITTEN) {
+ mode = QuestionContentType.HANDWRITTEN
+ }
+ ModeChip("Type", mode == QuestionContentType.TYPED) {
+ mode = QuestionContentType.TYPED
+ }
+ ModeChip("Paste", mode == QuestionContentType.PASTED) {
+ mode = QuestionContentType.PASTED
+ val pasted = clipboard?.primaryClip
+ ?.takeIf { it.itemCount > 0 }
+ ?.getItemAt(0)
+ ?.coerceToText(context)
+ ?.toString()
+ if (!pasted.isNullOrBlank()) text = pasted
+ }
+ ModeChip("Import image", selected = false, onClick = onImportImage)
+ ModeChip("Import PDF", selected = false, onClick = onImportPdf)
+ }
+ Spacer(Modifier.height(12.dp))
+ when (mode) {
+ QuestionContentType.HANDWRITTEN -> Text(
+ "A question area will be added to the page — write the problem there with your stylus. InkProof recognizes only that region.",
+ style = MaterialTheme.typography.bodySmall,
+ color = MutedText
+ )
+ else -> OutlinedTextField(
+ value = text,
+ onValueChange = { text = it },
+ label = { Text("Question (e.g. Solve 2x + 6 = 14)") },
+ minLines = 2
+ )
+ }
+ }
+ },
+ confirmButton = {
+ TextButton(onClick = {
+ onCreate(mode, text.takeIf { it.isNotBlank() })
+ }) { Text("Add question") }
+ },
+ dismissButton = {
+ TextButton(onClick = onDismiss) { Text("Cancel") }
+ }
+ )
+}
+
+@Composable
+private fun ModeChip(label: String, selected: Boolean, onClick: () -> Unit) {
+ Surface(
+ shape = RoundedCornerShape(50),
+ color = if (selected) MaterialTheme.colorScheme.primaryContainer
+ else MaterialTheme.colorScheme.surfaceVariant,
+ modifier = Modifier.clickable(onClick = onClick)
+ ) {
+ Text(
+ label,
+ style = MaterialTheme.typography.labelLarge,
+ color = if (selected) InkNavy else MutedText,
+ modifier = Modifier.padding(horizontal = 14.dp, vertical = 8.dp)
+ )
+ }
+}
+
+@Composable
+private fun TemplatePickerDialog(
+ onDismiss: () -> Unit,
+ onPick: (PageTemplate) -> Unit
+) {
+ AlertDialog(
+ onDismissRequest = onDismiss,
+ title = { Text("Page template") },
+ text = {
+ Column {
+ Text(
+ "Changing the template never touches your ink.",
+ style = MaterialTheme.typography.bodySmall,
+ color = MutedText,
+ modifier = Modifier.padding(bottom = 8.dp)
+ )
+ listOf(
+ PageTemplate.BLANK to "Blank",
+ PageTemplate.RULED to "Ruled",
+ PageTemplate.GRID to "Grid",
+ PageTemplate.DOT_GRID to "Dot grid",
+ PageTemplate.ENGINEERING to "Engineering grid",
+ PageTemplate.MATH_WORKSHEET to "Math worksheet"
+ ).forEach { (template, label) ->
+ Text(
+ label,
+ style = MaterialTheme.typography.bodyLarge,
+ modifier = Modifier
+ .fillMaxWidth()
+ .clickable { onPick(template) }
+ .padding(vertical = 10.dp)
+ )
+ }
+ }
+ },
+ confirmButton = {
+ TextButton(onClick = onDismiss) { Text("Cancel") }
+ }
+ )
+}
diff --git a/app/src/main/java/com/inkproof/app/ui/editor/EditorViewModel.kt b/app/src/main/java/com/inkproof/app/ui/editor/EditorViewModel.kt
new file mode 100644
index 0000000..60a90e0
--- /dev/null
+++ b/app/src/main/java/com/inkproof/app/ui/editor/EditorViewModel.kt
@@ -0,0 +1,589 @@
+package com.inkproof.app.ui.editor
+
+import android.app.Application
+import android.graphics.Bitmap
+import android.graphics.BitmapFactory
+import android.graphics.RectF
+import androidx.lifecycle.AndroidViewModel
+import androidx.lifecycle.viewModelScope
+import com.inkproof.app.InkProofApp
+import com.inkproof.app.data.db.PageEntity
+import com.inkproof.app.data.settings.Settings
+import com.inkproof.app.ink.CanvasOp
+import com.inkproof.app.ink.UndoRedoStack
+import com.inkproof.app.model.CheckAction
+import com.inkproof.app.model.CheckResponse
+import com.inkproof.app.model.PageKind
+import com.inkproof.app.model.PageTemplate
+import com.inkproof.app.model.PenStyle
+import com.inkproof.app.model.Question
+import com.inkproof.app.model.QuestionContentType
+import com.inkproof.app.model.Stroke
+import com.inkproof.app.model.TextObject
+import com.inkproof.app.model.ToolType
+import com.inkproof.app.model.newId
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.flow.MutableSharedFlow
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.SharedFlow
+import kotlinx.coroutines.flow.SharingStarted
+import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.flow.first
+import kotlinx.coroutines.flow.stateIn
+import kotlinx.coroutines.launch
+import java.io.File
+
+/** One fully-loaded page, ready for the canvas. */
+data class PageContent(
+ val page: PageEntity,
+ val strokes: List,
+ val questions: List,
+ val pdfBackground: Bitmap?,
+ val textObjects: List = emptyList(),
+ /** Monotonic token so re-loading the same page still refreshes the view. */
+ val loadToken: Long
+)
+
+/** Mutations the ViewModel pushes INTO the canvas view (undo/redo/paste). */
+sealed class CanvasMutation {
+ data class Add(val strokes: List) : CanvasMutation()
+ data class Remove(val strokes: List) : CanvasMutation()
+ data class Replace(val strokes: List) : CanvasMutation()
+}
+
+sealed class CheckUiState {
+ data object Hidden : CheckUiState()
+ data class Loading(val questionId: String?, val action: CheckAction) : CheckUiState()
+ data class Result(
+ val questionId: String?,
+ val action: CheckAction,
+ val response: CheckResponse
+ ) : CheckUiState()
+}
+
+class EditorViewModel(
+ application: Application,
+ private val notebookId: String
+) : AndroidViewModel(application) {
+
+ private val app = application as InkProofApp
+ private val library = app.libraryRepository
+ private val pageRepo = app.pageRepository
+
+ val settings: StateFlow = app.settingsStore.settings
+ .stateIn(viewModelScope, SharingStarted.Eagerly, Settings())
+
+ val pages: StateFlow> = library.observePages(notebookId)
+ .stateIn(viewModelScope, SharingStarted.Eagerly, emptyList())
+
+ private val _notebookTitle = MutableStateFlow("")
+ val notebookTitle: StateFlow = _notebookTitle
+
+ private val _pageContent = MutableStateFlow(null)
+ val pageContent: StateFlow = _pageContent
+
+ private val _penStyle = MutableStateFlow(PenStyle())
+ val penStyle: StateFlow = _penStyle
+
+ private val _canvasMutations = MutableSharedFlow(extraBufferCapacity = 16)
+ val canvasMutations: SharedFlow = _canvasMutations
+
+ private val _canUndo = MutableStateFlow(false)
+ val canUndo: StateFlow = _canUndo
+ private val _canRedo = MutableStateFlow(false)
+ val canRedo: StateFlow = _canRedo
+
+ private val _selection = MutableStateFlow, RectF?>>(emptyList() to null)
+ val selection: StateFlow, RectF?>> = _selection
+
+ private val _checkState = MutableStateFlow(CheckUiState.Hidden)
+ val checkState: StateFlow = _checkState
+
+ private val _toast = MutableSharedFlow(extraBufferCapacity = 4)
+ val toast: SharedFlow = _toast
+
+ private val undoRedo = UndoRedoStack()
+ private var clipboard: List = emptyList()
+ private var loadCounter = 0L
+
+ init {
+ viewModelScope.launch {
+ _notebookTitle.value = library.notebook(notebookId)?.title.orEmpty()
+ // Apply writing defaults.
+ val s = app.settingsStore.settings.first()
+ _penStyle.value = PenStyle(
+ tool = ToolType.PEN,
+ color = s.defaultPenColor,
+ baseWidth = s.defaultPenWidth,
+ pressureEnabled = s.pressureEnabled
+ )
+ val pageList = library.pagesFor(notebookId)
+ // Continue from last page when enabled and the page still exists.
+ val remembered = if (s.continueFromLastPage) {
+ com.inkproof.app.data.settings.SettingsStore
+ .decodeLastPages(s.lastPageByNotebook)[notebookId]
+ } else null
+ val target = pageList.firstOrNull { it.id == remembered } ?: pageList.firstOrNull()
+ target?.let { selectPage(it.id) }
+ }
+ }
+
+ // ================= pages =================
+
+ fun selectPage(pageId: String) {
+ viewModelScope.launch(Dispatchers.IO) {
+ val page = library.page(pageId) ?: return@launch
+ val strokes = pageRepo.strokesForPage(pageId)
+ val questions = pageRepo.questionsForPage(pageId)
+ val textObjects = pageRepo.textObjectsForPage(pageId)
+ val pdf = page.pdfPath?.let { path ->
+ if (File(path).exists()) BitmapFactory.decodeFile(path) else null
+ }
+ undoRedo.clear()
+ updateUndoState()
+ clearSelectionState()
+ _checkState.value = CheckUiState.Hidden
+ _pageContent.value =
+ PageContent(page, strokes, questions, pdf, textObjects, ++loadCounter)
+ library.touchNotebook(notebookId)
+ app.settingsStore.setLastPage(notebookId, pageId)
+ }
+ }
+
+ fun movePage(pageId: String, delta: Int) {
+ viewModelScope.launch(Dispatchers.IO) { library.movePage(pageId, delta) }
+ }
+
+ fun addPage(kind: PageKind = PageKind.NOTE, template: PageTemplate = PageTemplate.RULED) {
+ viewModelScope.launch {
+ val page = library.createPage(notebookId, kind, template)
+ selectPage(page.id)
+ }
+ }
+
+ fun deleteCurrentPage() {
+ val current = _pageContent.value?.page ?: return
+ viewModelScope.launch {
+ val all = library.pagesFor(notebookId)
+ if (all.size <= 1) {
+ _toast.emit("A notebook needs at least one page.")
+ return@launch
+ }
+ val index = all.indexOfFirst { it.id == current.id }
+ library.deletePage(current.id)
+ val remaining = library.pagesFor(notebookId)
+ remaining.getOrNull((index - 1).coerceAtLeast(0))?.let { selectPage(it.id) }
+ }
+ }
+
+ fun setTemplate(template: PageTemplate) {
+ val current = _pageContent.value?.page ?: return
+ viewModelScope.launch {
+ library.setTemplate(current.id, template)
+ selectPage(current.id)
+ }
+ }
+
+ fun setPaperColor(color: Int) {
+ val current = _pageContent.value?.page ?: return
+ viewModelScope.launch {
+ library.setPaperColor(current.id, color)
+ selectPage(current.id)
+ }
+ }
+
+ // ================= tools =================
+
+ // Last non-eraser tool, restored by the stylus double-press toggle.
+ private var rememberedTool: ToolType = ToolType.PEN
+
+ fun setTool(tool: ToolType) {
+ if (tool != ToolType.ERASER) rememberedTool = tool
+ _penStyle.value = _penStyle.value.copy(tool = tool)
+ }
+
+ /** Stylus button double-press: eraser <-> previous tool. */
+ fun stylusToggleEraser() {
+ val result = com.inkproof.app.ink.StylusEraserToggle.toggle(
+ current = _penStyle.value.tool,
+ remembered = rememberedTool
+ )
+ rememberedTool = result.remembered
+ _penStyle.value = _penStyle.value.copy(tool = result.tool)
+ }
+
+ fun setColor(color: Int) {
+ _penStyle.value = _penStyle.value.copy(color = color)
+ }
+
+ fun setEraserRadius(radius: Float) {
+ viewModelScope.launch { app.settingsStore.setEraserRadius(radius) }
+ }
+
+ fun setWidth(width: Float) {
+ _penStyle.value = _penStyle.value.copy(baseWidth = width)
+ }
+
+ // ================= stroke persistence (async, never blocks drawing) =====
+
+ fun onStrokeCommitted(stroke: Stroke) {
+ undoRedo.push(CanvasOp.Add(listOf(stroke)))
+ updateUndoState()
+ viewModelScope.launch(Dispatchers.IO) { pageRepo.addStroke(stroke) }
+ }
+
+ fun onStrokesErased(strokes: List) {
+ if (strokes.isEmpty()) return
+ undoRedo.push(CanvasOp.Remove(strokes))
+ updateUndoState()
+ viewModelScope.launch(Dispatchers.IO) { pageRepo.deleteStrokes(strokes) }
+ }
+
+ fun onStrokesMoved(before: List, after: List) {
+ undoRedo.push(CanvasOp.Replace(before, after))
+ updateUndoState()
+ viewModelScope.launch(Dispatchers.IO) { pageRepo.updateStrokes(after) }
+ }
+
+ fun onSelectionChanged(strokes: List, bounds: RectF?) {
+ _selection.value = strokes to bounds
+ }
+
+ private fun clearSelectionState() {
+ _selection.value = emptyList() to null
+ }
+
+ // ================= undo / redo =================
+
+ fun undo() {
+ val op = undoRedo.undo() ?: return
+ updateUndoState()
+ viewModelScope.launch(Dispatchers.IO) {
+ when (op) {
+ is CanvasOp.Add -> {
+ pageRepo.deleteStrokes(op.strokes)
+ _canvasMutations.emit(CanvasMutation.Remove(op.strokes))
+ }
+ is CanvasOp.Remove -> {
+ pageRepo.addStrokes(op.strokes)
+ _canvasMutations.emit(CanvasMutation.Add(op.strokes))
+ }
+ is CanvasOp.Replace -> {
+ pageRepo.updateStrokes(op.before)
+ _canvasMutations.emit(CanvasMutation.Replace(op.before))
+ }
+ }
+ }
+ }
+
+ fun redo() {
+ val op = undoRedo.redo() ?: return
+ updateUndoState()
+ viewModelScope.launch(Dispatchers.IO) {
+ when (op) {
+ is CanvasOp.Add -> {
+ pageRepo.addStrokes(op.strokes)
+ _canvasMutations.emit(CanvasMutation.Add(op.strokes))
+ }
+ is CanvasOp.Remove -> {
+ pageRepo.deleteStrokes(op.strokes)
+ _canvasMutations.emit(CanvasMutation.Remove(op.strokes))
+ }
+ is CanvasOp.Replace -> {
+ pageRepo.updateStrokes(op.after)
+ _canvasMutations.emit(CanvasMutation.Replace(op.after))
+ }
+ }
+ }
+ }
+
+ private fun updateUndoState() {
+ _canUndo.value = undoRedo.canUndo
+ _canRedo.value = undoRedo.canRedo
+ }
+
+ // ================= on-demand recognition =================
+
+ /** Result of SELECT → RECOGNIZE MATH. Null = no dialog. */
+ data class RecognitionUi(
+ val loading: Boolean,
+ val text: String = "",
+ val confidence: Float = 0f,
+ val uncertain: Boolean = false
+ )
+
+ private val _recognition = MutableStateFlow(null)
+ val recognition: StateFlow = _recognition
+
+ /**
+ * Recognize ONLY the lasso-selected strokes, locally. Never called
+ * automatically — never while writing — and never replaces the ink.
+ */
+ fun recognizeSelection() {
+ val (strokes, _) = _selection.value
+ if (strokes.isEmpty()) {
+ viewModelScope.launch { _toast.emit("Select some handwriting first") }
+ return
+ }
+ _recognition.value = RecognitionUi(loading = true)
+ viewModelScope.launch {
+ val result = runCatching {
+ app.recognizer(settings.value.mockMode, settings.value.backendUrl)
+ .recognize(strokes)
+ }.getOrNull()
+ if (result == null || result.lines.isEmpty()) {
+ _recognition.value = RecognitionUi(
+ loading = false, text = "", confidence = 0f, uncertain = true
+ )
+ return@launch
+ }
+ val threshold = settings.value.recognitionConfidenceThreshold
+ _recognition.value = RecognitionUi(
+ loading = false,
+ text = result.lines.joinToString("\n") { it.text },
+ confidence = result.confidence,
+ uncertain = result.uncertain || result.confidence < threshold
+ )
+ }
+ }
+
+ fun dismissRecognition() {
+ _recognition.value = null
+ }
+
+ /** ACCEPT: place the recognized text next to the selection as a
+ * text object. The original handwriting is never touched. */
+ fun acceptRecognition(text: String) {
+ val content = _pageContent.value ?: return
+ val (strokes, _) = _selection.value
+ val bounds = strokes.firstOrNull()?.let {
+ var minX = Float.MAX_VALUE; var minY = Float.MAX_VALUE; var maxX = 0f
+ for (s in strokes) {
+ val b = s.bounds()
+ if (b.left < minX) minX = b.left
+ if (b.top < minY) minY = b.top
+ if (b.right > maxX) maxX = b.right
+ }
+ Triple(minX, minY, maxX)
+ }
+ addOrUpdateText(
+ TextObject(
+ pageId = content.page.id,
+ text = text,
+ x = bounds?.third?.plus(24f) ?: 80f,
+ y = bounds?.second ?: 80f,
+ fontSize = 30f
+ )
+ )
+ _recognition.value = null
+ }
+
+ // ================= copy / paste =================
+
+ fun copySelection() {
+ val (strokes, _) = _selection.value
+ clipboard = strokes
+ viewModelScope.launch { _toast.emit("${strokes.size} strokes copied") }
+ }
+
+ fun paste() {
+ val pageId = _pageContent.value?.page?.id ?: return
+ if (clipboard.isEmpty()) return
+ val pasted = com.inkproof.app.model.ClipboardOps.cloneForPaste(clipboard, pageId)
+ undoRedo.push(CanvasOp.Add(pasted))
+ updateUndoState()
+ viewModelScope.launch(Dispatchers.IO) {
+ pageRepo.addStrokes(pasted)
+ _canvasMutations.emit(CanvasMutation.Add(pasted))
+ }
+ }
+
+ // ================= questions =================
+
+ fun createQuestion(contentType: QuestionContentType, typedText: String?) {
+ val content = _pageContent.value ?: return
+ viewModelScope.launch(Dispatchers.IO) {
+ val existing = pageRepo.questionsForPage(content.page.id)
+ val top = (existing.maxOfOrNull { it.solutionBottom } ?: 60f) + 40f
+ pageRepo.createQuestion(
+ pageId = content.page.id,
+ contentType = contentType,
+ typedText = typedText,
+ questionTop = top
+ )
+ refreshQuestions()
+ }
+ }
+
+ /**
+ * Create a Question whose statement is an imported image or the first
+ * page of an imported PDF (§ imported regions become Question objects).
+ * The media is copied into app storage and rendered inside the
+ * question band; the solution area below stays normal handwriting.
+ */
+ fun createQuestionFromMedia(uri: android.net.Uri, isPdf: Boolean) {
+ val content = _pageContent.value ?: return
+ viewModelScope.launch(Dispatchers.IO) {
+ val bitmap = runCatching {
+ if (isPdf) renderPdfFirstPage(uri)
+ else app.contentResolver.openInputStream(uri)?.use {
+ BitmapFactory.decodeStream(it)
+ }
+ }.getOrNull()
+ if (bitmap == null) {
+ _toast.emit(
+ if (isPdf) "Couldn't read that PDF." else "Couldn't read that image."
+ )
+ return@launch
+ }
+ val dir = java.io.File(app.filesDir, "question_media").apply { mkdirs() }
+ val file = java.io.File(dir, "${newId()}.png")
+ runCatching {
+ java.io.FileOutputStream(file).use { out ->
+ bitmap.compress(Bitmap.CompressFormat.PNG, 92, out)
+ }
+ }.onFailure {
+ _toast.emit("Couldn't save the imported file.")
+ return@launch
+ }
+
+ // Scale the question band to the media's aspect ratio.
+ val pageWidth = 1600f
+ val availW = pageWidth - 72f
+ val mediaHeight = (availW / bitmap.width * bitmap.height)
+ .coerceIn(120f, 620f)
+ val existing = pageRepo.questionsForPage(content.page.id)
+ val top = (existing.maxOfOrNull { it.solutionBottom } ?: 60f) + 40f
+ pageRepo.createQuestion(
+ pageId = content.page.id,
+ contentType = if (isPdf) QuestionContentType.PDF else QuestionContentType.IMAGE,
+ mediaPath = file.absolutePath,
+ questionTop = top,
+ questionHeight = mediaHeight + 110f
+ )
+ refreshQuestions()
+ _toast.emit("Question added from ${if (isPdf) "PDF" else "image"}")
+ }
+ }
+
+ private fun renderPdfFirstPage(uri: android.net.Uri): Bitmap? =
+ app.contentResolver.openFileDescriptor(uri, "r")?.use { pfd ->
+ android.graphics.pdf.PdfRenderer(pfd).use { renderer ->
+ if (renderer.pageCount == 0) return@use null
+ val page = renderer.openPage(0)
+ try {
+ val scale = (1400f / page.width).coerceIn(1f, 4f)
+ val bmp = Bitmap.createBitmap(
+ (page.width * scale).toInt(),
+ (page.height * scale).toInt(),
+ Bitmap.Config.ARGB_8888
+ )
+ bmp.eraseColor(android.graphics.Color.WHITE)
+ page.render(
+ bmp, null, null,
+ android.graphics.pdf.PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY
+ )
+ bmp
+ } finally {
+ page.close()
+ }
+ }
+ }
+
+ fun updateQuestionText(questionId: String, text: String) {
+ viewModelScope.launch(Dispatchers.IO) {
+ pageRepo.updateQuestionText(questionId, text)
+ refreshQuestions()
+ }
+ }
+
+ fun deleteQuestion(questionId: String) {
+ val content = _pageContent.value ?: return
+ viewModelScope.launch(Dispatchers.IO) {
+ pageRepo.deleteQuestion(questionId)
+ // Strokes of the question were deleted too: full reload.
+ selectPage(content.page.id)
+ }
+ }
+
+ private suspend fun refreshQuestions() {
+ val content = _pageContent.value ?: return
+ // Re-read strokes too so recently drawn ink is never wiped from the view.
+ _pageContent.value = content.copy(
+ strokes = pageRepo.strokesForPage(content.page.id),
+ questions = pageRepo.questionsForPage(content.page.id),
+ loadToken = ++loadCounter
+ )
+ }
+
+ // ================= text objects =================
+
+ fun addOrUpdateText(obj: TextObject) {
+ val content = _pageContent.value ?: return
+ viewModelScope.launch(Dispatchers.IO) {
+ pageRepo.upsertTextObject(obj)
+ refreshTextObjects(content.page.id)
+ }
+ }
+
+ fun deleteText(id: String) {
+ val content = _pageContent.value ?: return
+ viewModelScope.launch(Dispatchers.IO) {
+ pageRepo.deleteTextObject(id)
+ refreshTextObjects(content.page.id)
+ }
+ }
+
+ private suspend fun refreshTextObjects(pageId: String) {
+ val content = _pageContent.value ?: return
+ if (content.page.id != pageId) return
+ // Re-read strokes too: content.strokes may be stale (ink drawn since
+ // the page load is persisted asynchronously) and must not be wiped.
+ _pageContent.value = content.copy(
+ strokes = pageRepo.strokesForPage(pageId),
+ textObjects = pageRepo.textObjectsForPage(pageId),
+ loadToken = ++loadCounter
+ )
+ }
+
+ // ================= CHECK MY WORK / SOLVE =================
+
+ private fun engine() = app.checkEngine(
+ mockMode = settings.value.mockMode,
+ confidenceThreshold = settings.value.recognitionConfidenceThreshold,
+ backendUrl = settings.value.backendUrl
+ )
+
+ fun checkQuestion(questionId: String, action: CheckAction) {
+ _checkState.value = CheckUiState.Loading(questionId, action)
+ viewModelScope.launch(Dispatchers.IO) {
+ val response = engine().checkQuestion(questionId, action)
+ _checkState.value = CheckUiState.Result(questionId, action, response)
+ }
+ }
+
+ fun checkSelection(action: CheckAction) {
+ val pageId = _pageContent.value?.page?.id ?: return
+ val (strokes, _) = _selection.value
+ _checkState.value = CheckUiState.Loading(null, action)
+ viewModelScope.launch(Dispatchers.IO) {
+ val response = engine().checkSelection(pageId, strokes, action)
+ _checkState.value = CheckUiState.Result(null, action, response)
+ }
+ }
+
+ fun dismissCheck() {
+ _checkState.value = CheckUiState.Hidden
+ }
+
+ // ================= export =================
+
+ fun exportPdf() {
+ viewModelScope.launch(Dispatchers.IO) {
+ val file = app.pdfExporter.export(notebookId)
+ _toast.emit(
+ if (file != null) "Exported to ${file.name}" else "Export failed."
+ )
+ }
+ }
+}
diff --git a/app/src/main/java/com/inkproof/app/ui/library/LibraryScreen.kt b/app/src/main/java/com/inkproof/app/ui/library/LibraryScreen.kt
new file mode 100644
index 0000000..e92fb7b
--- /dev/null
+++ b/app/src/main/java/com/inkproof/app/ui/library/LibraryScreen.kt
@@ -0,0 +1,709 @@
+package com.inkproof.app.ui.library
+
+import androidx.activity.compose.rememberLauncherForActivityResult
+import androidx.activity.result.PickVisualMediaRequest
+import androidx.activity.result.contract.ActivityResultContracts
+import androidx.compose.foundation.ExperimentalFoundationApi
+import androidx.compose.foundation.Image
+import androidx.compose.foundation.combinedClickable
+import androidx.compose.foundation.horizontalScroll
+import androidx.compose.foundation.rememberScrollState
+import androidx.compose.foundation.background
+import androidx.compose.foundation.border
+import androidx.compose.foundation.clickable
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.PaddingValues
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.Spacer
+import androidx.compose.foundation.layout.aspectRatio
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.height
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.layout.width
+import androidx.compose.foundation.lazy.grid.GridCells
+import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
+import androidx.compose.foundation.lazy.grid.items
+import androidx.compose.foundation.shape.RoundedCornerShape
+import androidx.compose.material.icons.Icons
+import androidx.compose.material.icons.filled.Add
+import androidx.compose.material.icons.filled.Favorite
+import androidx.compose.material.icons.filled.MoreVert
+import androidx.compose.material.icons.filled.Search
+import androidx.compose.material.icons.outlined.Calculate
+import androidx.compose.material.icons.outlined.Description
+import androidx.compose.material.icons.outlined.FavoriteBorder
+import androidx.compose.material.icons.outlined.FileOpen
+import androidx.compose.material.icons.outlined.Image
+import androidx.compose.material.icons.outlined.NoteAdd
+import androidx.compose.material.icons.outlined.PictureAsPdf
+import androidx.compose.material.icons.outlined.Settings
+import androidx.compose.material3.AlertDialog
+import androidx.compose.material3.DropdownMenu
+import androidx.compose.material3.DropdownMenuItem
+import androidx.compose.material3.ExperimentalMaterial3Api
+import androidx.compose.material3.FloatingActionButton
+import androidx.compose.material3.Icon
+import androidx.compose.material3.IconButton
+import androidx.compose.material3.MaterialTheme
+import androidx.compose.material3.OutlinedTextField
+import androidx.compose.material3.Scaffold
+import androidx.compose.material3.Surface
+import androidx.compose.material3.Text
+import androidx.compose.material3.TextButton
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.collectAsState
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.graphics.asImageBitmap
+import androidx.compose.ui.layout.ContentScale
+import androidx.compose.ui.text.style.TextOverflow
+import androidx.compose.ui.unit.dp
+import androidx.lifecycle.viewmodel.compose.viewModel
+import com.inkproof.app.data.db.FolderEntity
+import com.inkproof.app.data.db.NotebookEntity
+import com.inkproof.app.ui.theme.InkNavy
+import com.inkproof.app.ui.theme.MutedText
+import java.text.SimpleDateFormat
+import java.util.Date
+import java.util.Locale
+
+@OptIn(ExperimentalMaterial3Api::class)
+@Composable
+fun LibraryScreen(
+ onOpenNotebook: (String) -> Unit,
+ onOpenSettings: () -> Unit,
+ viewModel: LibraryViewModel = viewModel()
+) {
+ val notebooks by viewModel.notebooks.collectAsState()
+ val thumbnails by viewModel.thumbnails.collectAsState()
+ val searchQuery by viewModel.searchQuery.collectAsState()
+ val searchResults by viewModel.searchResults.collectAsState()
+ val navigateTo by viewModel.navigateTo.collectAsState()
+ val folders by viewModel.folders.collectAsState()
+ val selectedFolderId by viewModel.selectedFolderId.collectAsState()
+
+ var showCreateMenu by remember { mutableStateOf(false) }
+ var createDialog by remember { mutableStateOf(null) }
+ var pendingPdfTitle by remember { mutableStateOf("") }
+ var newFolderDialog by remember { mutableStateOf(false) }
+ var folderOptionsFor by remember { mutableStateOf(null) }
+
+ val pdfLauncher = rememberLauncherForActivityResult(
+ ActivityResultContracts.OpenDocument()
+ ) { uri ->
+ if (uri != null) viewModel.importPdf(uri, pendingPdfTitle)
+ }
+ val imageLauncher = rememberLauncherForActivityResult(
+ ActivityResultContracts.PickVisualMedia()
+ ) { uri ->
+ if (uri != null) viewModel.importImage(uri, "Imported image")
+ }
+ val anyFileLauncher = rememberLauncherForActivityResult(
+ ActivityResultContracts.OpenDocument()
+ ) { uri ->
+ if (uri != null) viewModel.importAny(uri)
+ }
+ val importError by viewModel.importError.collectAsState()
+
+ LaunchedEffect(navigateTo) {
+ navigateTo?.let {
+ viewModel.consumeNavigation()
+ onOpenNotebook(it)
+ }
+ }
+ LaunchedEffect(notebooks) { viewModel.refreshThumbnails(notebooks) }
+
+ val shown = (searchResults ?: notebooks).let { list ->
+ // Folder filter applies only when not searching.
+ if (searchResults == null && selectedFolderId != null) {
+ list.filter { it.folderId == selectedFolderId }
+ } else list
+ }
+ val favorites = shown.filter { it.favorite }
+
+ Scaffold(
+ containerColor = MaterialTheme.colorScheme.background,
+ floatingActionButton = {
+ Box {
+ FloatingActionButton(
+ onClick = { showCreateMenu = true },
+ containerColor = InkNavy,
+ contentColor = MaterialTheme.colorScheme.onPrimary
+ ) {
+ Icon(Icons.Filled.Add, contentDescription = "Create")
+ }
+ DropdownMenu(
+ expanded = showCreateMenu,
+ onDismissRequest = { showCreateMenu = false }
+ ) {
+ DropdownMenuItem(
+ text = { Text("New note") },
+ leadingIcon = { Icon(Icons.Outlined.NoteAdd, null) },
+ onClick = { showCreateMenu = false; createDialog = CreateKind.NOTE }
+ )
+ DropdownMenuItem(
+ text = { Text("New math question") },
+ leadingIcon = { Icon(Icons.Outlined.Calculate, null) },
+ onClick = { showCreateMenu = false; createDialog = CreateKind.MATH }
+ )
+ DropdownMenuItem(
+ text = { Text("Import PDF") },
+ leadingIcon = { Icon(Icons.Outlined.PictureAsPdf, null) },
+ onClick = {
+ showCreateMenu = false
+ pendingPdfTitle = "Imported PDF"
+ pdfLauncher.launch(arrayOf("application/pdf"))
+ }
+ )
+ DropdownMenuItem(
+ text = { Text("Import image") },
+ leadingIcon = { Icon(Icons.Outlined.Image, null) },
+ onClick = {
+ showCreateMenu = false
+ imageLauncher.launch(
+ PickVisualMediaRequest(
+ ActivityResultContracts.PickVisualMedia.ImageOnly
+ )
+ )
+ }
+ )
+ DropdownMenuItem(
+ text = { Text("Import file…") },
+ leadingIcon = { Icon(Icons.Outlined.FileOpen, null) },
+ onClick = {
+ showCreateMenu = false
+ anyFileLauncher.launch(arrayOf("*/*"))
+ }
+ )
+ }
+ }
+ }
+ ) { padding ->
+ Column(
+ modifier = Modifier
+ .fillMaxSize()
+ .padding(padding)
+ .padding(horizontal = 28.dp)
+ ) {
+ // Header
+ Row(
+ modifier = Modifier
+ .fillMaxWidth()
+ .padding(top = 20.dp, bottom = 4.dp),
+ verticalAlignment = Alignment.CenterVertically
+ ) {
+ Column(Modifier.weight(1f)) {
+ Text("InkProof", style = MaterialTheme.typography.headlineMedium)
+ Text(
+ "Prove your work.",
+ style = MaterialTheme.typography.bodyMedium,
+ color = MutedText
+ )
+ }
+ IconButton(onClick = onOpenSettings) {
+ Icon(Icons.Outlined.Settings, contentDescription = "Settings", tint = MutedText)
+ }
+ }
+
+ // Search
+ OutlinedTextField(
+ value = searchQuery,
+ onValueChange = { viewModel.search(it) },
+ placeholder = { Text("Search notebooks and questions") },
+ leadingIcon = { Icon(Icons.Filled.Search, null, tint = MutedText) },
+ singleLine = true,
+ shape = RoundedCornerShape(14.dp),
+ modifier = Modifier
+ .fillMaxWidth()
+ .padding(vertical = 12.dp)
+ )
+
+ // Folder chips
+ FolderChipsRow(
+ folders = folders,
+ selectedFolderId = selectedFolderId,
+ onSelect = viewModel::selectFolder,
+ onNewFolder = { newFolderDialog = true },
+ onFolderOptions = { folderOptionsFor = it }
+ )
+
+ if (shown.isEmpty()) {
+ EmptyLibrary()
+ } else {
+ LazyVerticalGrid(
+ columns = GridCells.Adaptive(190.dp),
+ horizontalArrangement = Arrangement.spacedBy(18.dp),
+ verticalArrangement = Arrangement.spacedBy(18.dp),
+ contentPadding = PaddingValues(bottom = 96.dp, top = 6.dp),
+ modifier = Modifier.fillMaxSize()
+ ) {
+ if (favorites.isNotEmpty() && searchResults == null) {
+ items(favorites, key = { "fav-${it.id}" }) { nb ->
+ NotebookCard(
+ notebook = nb,
+ thumbnail = thumbnails[nb.id],
+ folders = folders,
+ onOpen = { onOpenNotebook(nb.id) },
+ onRename = { viewModel.rename(nb.id, it) },
+ onDelete = { viewModel.delete(nb.id) },
+ onDuplicate = { viewModel.duplicate(nb.id) },
+ onToggleFavorite = { viewModel.toggleFavorite(nb) },
+ onMoveToFolder = { viewModel.moveToFolder(nb.id, it) }
+ )
+ }
+ }
+ items(
+ shown.filter { !it.favorite || searchResults != null },
+ key = { it.id }
+ ) { nb ->
+ NotebookCard(
+ notebook = nb,
+ thumbnail = thumbnails[nb.id],
+ folders = folders,
+ onOpen = { onOpenNotebook(nb.id) },
+ onRename = { viewModel.rename(nb.id, it) },
+ onDelete = { viewModel.delete(nb.id) },
+ onDuplicate = { viewModel.duplicate(nb.id) },
+ onToggleFavorite = { viewModel.toggleFavorite(nb) },
+ onMoveToFolder = { viewModel.moveToFolder(nb.id, it) }
+ )
+ }
+ }
+ }
+ }
+ }
+
+ createDialog?.let { kind ->
+ CreateNotebookDialog(
+ kind = kind,
+ onDismiss = { createDialog = null },
+ onCreate = { title ->
+ when (kind) {
+ CreateKind.NOTE -> viewModel.createNote(title)
+ CreateKind.MATH -> viewModel.createMathQuestion(title)
+ }
+ createDialog = null
+ }
+ )
+ }
+
+ importError?.let { message ->
+ AlertDialog(
+ onDismissRequest = { viewModel.consumeImportError() },
+ title = { Text("Can't import this file") },
+ text = { Text(message) },
+ confirmButton = {
+ TextButton(onClick = { viewModel.consumeImportError() }) { Text("OK") }
+ }
+ )
+ }
+
+ if (newFolderDialog) {
+ var name by remember { mutableStateOf("") }
+ AlertDialog(
+ onDismissRequest = { newFolderDialog = false },
+ title = { Text("New folder") },
+ text = {
+ OutlinedTextField(
+ value = name,
+ onValueChange = { name = it },
+ label = { Text("Folder name") },
+ singleLine = true
+ )
+ },
+ confirmButton = {
+ TextButton(
+ onClick = { viewModel.createFolder(name); newFolderDialog = false },
+ enabled = name.isNotBlank()
+ ) { Text("Create") }
+ },
+ dismissButton = {
+ TextButton(onClick = { newFolderDialog = false }) { Text("Cancel") }
+ }
+ )
+ }
+
+ folderOptionsFor?.let { folder ->
+ var name by remember(folder.id) { mutableStateOf(folder.name) }
+ AlertDialog(
+ onDismissRequest = { folderOptionsFor = null },
+ title = { Text("Folder") },
+ text = {
+ Column {
+ OutlinedTextField(
+ value = name,
+ onValueChange = { name = it },
+ label = { Text("Folder name") },
+ singleLine = true
+ )
+ Spacer(Modifier.height(10.dp))
+ Text(
+ "Deleting a folder keeps its notebooks — they move back to the library.",
+ style = MaterialTheme.typography.bodySmall,
+ color = MutedText
+ )
+ }
+ },
+ confirmButton = {
+ TextButton(
+ onClick = {
+ viewModel.renameFolder(folder.id, name)
+ folderOptionsFor = null
+ },
+ enabled = name.isNotBlank()
+ ) { Text("Save") }
+ },
+ dismissButton = {
+ Row {
+ TextButton(onClick = {
+ viewModel.deleteFolder(folder.id)
+ folderOptionsFor = null
+ }) { Text("Delete", color = MaterialTheme.colorScheme.error) }
+ TextButton(onClick = { folderOptionsFor = null }) { Text("Cancel") }
+ }
+ }
+ )
+ }
+}
+
+enum class CreateKind { NOTE, MATH }
+
+@OptIn(ExperimentalFoundationApi::class)
+@Composable
+private fun FolderChipsRow(
+ folders: List,
+ selectedFolderId: String?,
+ onSelect: (String?) -> Unit,
+ onNewFolder: () -> Unit,
+ onFolderOptions: (FolderEntity) -> Unit
+) {
+ Row(
+ horizontalArrangement = Arrangement.spacedBy(8.dp),
+ verticalAlignment = Alignment.CenterVertically,
+ modifier = Modifier
+ .fillMaxWidth()
+ .horizontalScroll(rememberScrollState())
+ .padding(bottom = 10.dp)
+ ) {
+ FolderChip(
+ label = "All",
+ selected = selectedFolderId == null,
+ onClick = { onSelect(null) }
+ )
+ folders.forEach { folder ->
+ FolderChip(
+ label = folder.name,
+ selected = selectedFolderId == folder.id,
+ onClick = { onSelect(folder.id) },
+ onLongClick = { onFolderOptions(folder) }
+ )
+ }
+ FolderChip(
+ label = "+ New folder",
+ selected = false,
+ onClick = onNewFolder
+ )
+ }
+}
+
+@OptIn(ExperimentalFoundationApi::class)
+@Composable
+private fun FolderChip(
+ label: String,
+ selected: Boolean,
+ onClick: () -> Unit,
+ onLongClick: (() -> Unit)? = null
+) {
+ Surface(
+ shape = RoundedCornerShape(50),
+ color = if (selected) InkNavy else MaterialTheme.colorScheme.surface,
+ contentColor = if (selected) MaterialTheme.colorScheme.onPrimary
+ else MaterialTheme.colorScheme.onSurface,
+ tonalElevation = if (selected) 0.dp else 1.dp,
+ border = androidx.compose.foundation.BorderStroke(
+ 1.dp,
+ if (selected) InkNavy else MaterialTheme.colorScheme.outlineVariant
+ ),
+ modifier = Modifier.clip(RoundedCornerShape(50))
+ ) {
+ Text(
+ label,
+ style = MaterialTheme.typography.labelLarge,
+ maxLines = 1,
+ modifier = Modifier
+ .combinedClickable(onClick = onClick, onLongClick = onLongClick)
+ .padding(horizontal = 16.dp, vertical = 8.dp)
+ )
+ }
+}
+
+@Composable
+private fun CreateNotebookDialog(
+ kind: CreateKind,
+ onDismiss: () -> Unit,
+ onCreate: (String) -> Unit
+) {
+ var title by remember {
+ mutableStateOf(if (kind == CreateKind.MATH) "Math questions" else "")
+ }
+ AlertDialog(
+ onDismissRequest = onDismiss,
+ title = {
+ Text(if (kind == CreateKind.MATH) "New math question" else "New note")
+ },
+ text = {
+ Column {
+ if (kind == CreateKind.MATH) {
+ Text(
+ "You solve it. InkProof checks it.",
+ style = MaterialTheme.typography.bodyMedium,
+ color = MutedText,
+ modifier = Modifier.padding(bottom = 10.dp)
+ )
+ }
+ OutlinedTextField(
+ value = title,
+ onValueChange = { title = it },
+ label = { Text("Title") },
+ singleLine = true
+ )
+ }
+ },
+ confirmButton = {
+ TextButton(onClick = { onCreate(title) }) { Text("Create") }
+ },
+ dismissButton = {
+ TextButton(onClick = onDismiss) { Text("Cancel") }
+ }
+ )
+}
+
+@Composable
+private fun NotebookCard(
+ notebook: NotebookEntity,
+ thumbnail: android.graphics.Bitmap?,
+ folders: List,
+ onOpen: () -> Unit,
+ onRename: (String) -> Unit,
+ onDelete: () -> Unit,
+ onDuplicate: () -> Unit,
+ onToggleFavorite: () -> Unit,
+ onMoveToFolder: (String?) -> Unit
+) {
+ var menuOpen by remember { mutableStateOf(false) }
+ var renameOpen by remember { mutableStateOf(false) }
+ var deleteConfirm by remember { mutableStateOf(false) }
+ var moveOpen by remember { mutableStateOf(false) }
+
+ Surface(
+ shape = MaterialTheme.shapes.medium,
+ color = MaterialTheme.colorScheme.surface,
+ tonalElevation = 1.dp,
+ shadowElevation = 2.dp,
+ modifier = Modifier.clickable(onClick = onOpen)
+ ) {
+ Column {
+ Box(
+ modifier = Modifier
+ .fillMaxWidth()
+ .aspectRatio(0.78f)
+ .clip(RoundedCornerShape(topStart = 14.dp, topEnd = 14.dp))
+ .background(MaterialTheme.colorScheme.surfaceVariant)
+ ) {
+ if (thumbnail != null) {
+ Image(
+ bitmap = thumbnail.asImageBitmap(),
+ contentDescription = null,
+ contentScale = ContentScale.Crop,
+ alignment = Alignment.TopCenter,
+ modifier = Modifier.fillMaxSize()
+ )
+ } else {
+ Icon(
+ Icons.Outlined.Description,
+ contentDescription = null,
+ tint = MutedText,
+ modifier = Modifier
+ .align(Alignment.Center)
+ .size(42.dp)
+ )
+ }
+ if (notebook.favorite) {
+ Icon(
+ Icons.Filled.Favorite,
+ contentDescription = null,
+ tint = MaterialTheme.colorScheme.error,
+ modifier = Modifier
+ .align(Alignment.TopEnd)
+ .padding(8.dp)
+ .size(18.dp)
+ )
+ }
+ }
+ Row(
+ verticalAlignment = Alignment.CenterVertically,
+ modifier = Modifier.padding(start = 14.dp, end = 4.dp, top = 8.dp, bottom = 8.dp)
+ ) {
+ Column(Modifier.weight(1f)) {
+ Text(
+ notebook.title,
+ style = MaterialTheme.typography.titleSmall,
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis
+ )
+ Text(
+ SimpleDateFormat("MMM d, yyyy", Locale.getDefault())
+ .format(Date(notebook.updatedAt)),
+ style = MaterialTheme.typography.bodySmall,
+ color = MutedText
+ )
+ }
+ Box {
+ IconButton(onClick = { menuOpen = true }) {
+ Icon(Icons.Filled.MoreVert, contentDescription = "More", tint = MutedText)
+ }
+ DropdownMenu(expanded = menuOpen, onDismissRequest = { menuOpen = false }) {
+ DropdownMenuItem(
+ text = { Text(if (notebook.favorite) "Unfavorite" else "Favorite") },
+ leadingIcon = {
+ Icon(
+ if (notebook.favorite) Icons.Filled.Favorite
+ else Icons.Outlined.FavoriteBorder,
+ null
+ )
+ },
+ onClick = { menuOpen = false; onToggleFavorite() }
+ )
+ DropdownMenuItem(
+ text = { Text("Rename") },
+ onClick = { menuOpen = false; renameOpen = true }
+ )
+ DropdownMenuItem(
+ text = { Text("Duplicate") },
+ onClick = { menuOpen = false; onDuplicate() }
+ )
+ DropdownMenuItem(
+ text = { Text("Move to folder…") },
+ onClick = { menuOpen = false; moveOpen = true }
+ )
+ DropdownMenuItem(
+ text = { Text("Delete", color = MaterialTheme.colorScheme.error) },
+ onClick = { menuOpen = false; deleteConfirm = true }
+ )
+ }
+ }
+ }
+ }
+ }
+
+ if (renameOpen) {
+ var title by remember { mutableStateOf(notebook.title) }
+ AlertDialog(
+ onDismissRequest = { renameOpen = false },
+ title = { Text("Rename notebook") },
+ text = {
+ OutlinedTextField(value = title, onValueChange = { title = it }, singleLine = true)
+ },
+ confirmButton = {
+ TextButton(onClick = { onRename(title); renameOpen = false }) { Text("Rename") }
+ },
+ dismissButton = {
+ TextButton(onClick = { renameOpen = false }) { Text("Cancel") }
+ }
+ )
+ }
+
+ if (moveOpen) {
+ AlertDialog(
+ onDismissRequest = { moveOpen = false },
+ title = { Text("Move to folder") },
+ text = {
+ Column {
+ if (folders.isEmpty()) {
+ Text(
+ "No folders yet. Create one from the folder row on the library screen.",
+ style = MaterialTheme.typography.bodyMedium,
+ color = MutedText
+ )
+ } else {
+ Text(
+ "No folder (library)",
+ style = MaterialTheme.typography.bodyLarge,
+ modifier = Modifier
+ .fillMaxWidth()
+ .clickable { onMoveToFolder(null); moveOpen = false }
+ .padding(vertical = 10.dp)
+ )
+ folders.forEach { folder ->
+ Text(
+ folder.name +
+ if (notebook.folderId == folder.id) " ✓" else "",
+ style = MaterialTheme.typography.bodyLarge,
+ modifier = Modifier
+ .fillMaxWidth()
+ .clickable { onMoveToFolder(folder.id); moveOpen = false }
+ .padding(vertical = 10.dp)
+ )
+ }
+ }
+ }
+ },
+ confirmButton = {},
+ dismissButton = {
+ TextButton(onClick = { moveOpen = false }) { Text("Cancel") }
+ }
+ )
+ }
+
+ if (deleteConfirm) {
+ AlertDialog(
+ onDismissRequest = { deleteConfirm = false },
+ title = { Text("Delete notebook?") },
+ text = { Text("\"${notebook.title}\" and all of its pages will be permanently deleted.") },
+ confirmButton = {
+ TextButton(onClick = { onDelete(); deleteConfirm = false }) {
+ Text("Delete", color = MaterialTheme.colorScheme.error)
+ }
+ },
+ dismissButton = {
+ TextButton(onClick = { deleteConfirm = false }) { Text("Cancel") }
+ }
+ )
+ }
+}
+
+@Composable
+private fun EmptyLibrary() {
+ Column(
+ modifier = Modifier
+ .fillMaxSize()
+ .padding(top = 80.dp),
+ horizontalAlignment = Alignment.CenterHorizontally
+ ) {
+ Icon(
+ Icons.Outlined.Calculate,
+ contentDescription = null,
+ tint = MutedText,
+ modifier = Modifier.size(56.dp)
+ )
+ Spacer(Modifier.height(16.dp))
+ Text("No notebooks yet", style = MaterialTheme.typography.titleLarge)
+ Spacer(Modifier.height(6.dp))
+ Text(
+ "You solve it. InkProof checks it.\nCreate a math question to get started.",
+ style = MaterialTheme.typography.bodyMedium,
+ color = MutedText,
+ modifier = Modifier.width(320.dp)
+ )
+ }
+}
diff --git a/app/src/main/java/com/inkproof/app/ui/library/LibraryViewModel.kt b/app/src/main/java/com/inkproof/app/ui/library/LibraryViewModel.kt
new file mode 100644
index 0000000..96e1593
--- /dev/null
+++ b/app/src/main/java/com/inkproof/app/ui/library/LibraryViewModel.kt
@@ -0,0 +1,198 @@
+package com.inkproof.app.ui.library
+
+import android.app.Application
+import android.graphics.Bitmap
+import android.net.Uri
+import androidx.lifecycle.AndroidViewModel
+import androidx.lifecycle.viewModelScope
+import com.inkproof.app.InkProofApp
+import com.inkproof.app.data.db.FolderEntity
+import com.inkproof.app.data.db.NotebookEntity
+import com.inkproof.app.ink.ThumbnailRenderer
+import com.inkproof.app.model.PageKind
+import com.inkproof.app.pdf.ImportClassifier
+import com.inkproof.app.model.PageTemplate
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.SharingStarted
+import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.flow.stateIn
+import kotlinx.coroutines.launch
+
+class LibraryViewModel(application: Application) : AndroidViewModel(application) {
+
+ private val app = application as InkProofApp
+ private val library = app.libraryRepository
+ private val pages = app.pageRepository
+
+ val notebooks: StateFlow> = library.observeNotebooks()
+ .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), emptyList())
+
+ val folders: StateFlow> = library.observeFolders()
+ .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), emptyList())
+
+ /** null = show everything. */
+ private val _selectedFolderId = MutableStateFlow(null)
+ val selectedFolderId: StateFlow = _selectedFolderId
+
+ fun selectFolder(folderId: String?) { _selectedFolderId.value = folderId }
+
+ private val _thumbnails = MutableStateFlow
"))
+ assertFalse(text.contains("alert"))
+ assertFalse(text.contains("color:red"))
+ // …but the readable content, including decoded entities, survives.
+ assertTrue(text.contains("Quadratics"))
+ assertTrue(text.contains("& show work"))
+ assertTrue(text.contains(""))
+ }
+
+ @Test
+ fun `formatCsv joins columns readably`() {
+ val out = importer.formatCsv("name,score\n\"Asha\",95\nRavi,88")
+ val lines = out.lines()
+ assertEquals("name | score", lines[0])
+ assertEquals("Asha | 95", lines[1])
+ assertEquals("Ravi | 88", lines[2])
+ }
+
+ @Test
+ fun `wrapLines keeps short lines and wraps long ones at spaces`() {
+ val short = "a short line"
+ val long = (1..40).joinToString(" ") { "word$it" } // > 110 chars
+ val wrapped = importer.wrapLines("$short\n$long")
+ assertEquals(short, wrapped.first())
+ assertTrue(wrapped.size > 2)
+ wrapped.forEach { assertTrue(it.length <= TextImporter.MAX_LINE_CHARS + 10) }
+ // No content lost.
+ assertEquals(
+ (short + " " + long).replace(" ", ""),
+ wrapped.joinToString("").replace(" ", "")
+ )
+ }
+}
diff --git a/app/src/test/java/com/inkproof/app/UndoRedoStackTest.kt b/app/src/test/java/com/inkproof/app/UndoRedoStackTest.kt
new file mode 100644
index 0000000..bdd9ed7
--- /dev/null
+++ b/app/src/test/java/com/inkproof/app/UndoRedoStackTest.kt
@@ -0,0 +1,66 @@
+package com.inkproof.app
+
+import com.inkproof.app.ink.CanvasOp
+import com.inkproof.app.ink.UndoRedoStack
+import com.inkproof.app.model.Stroke
+import com.inkproof.app.model.StrokePoint
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class UndoRedoStackTest {
+
+ private fun stroke(id: String) = Stroke(
+ id = id, pageId = "page", color = 0, baseWidth = 3f,
+ points = listOf(StrokePoint(0f, 0f, 1f, 0))
+ )
+
+ @Test
+ fun `undo and redo return operations in order`() {
+ val stack = UndoRedoStack()
+ val a = CanvasOp.Add(listOf(stroke("a")))
+ val b = CanvasOp.Add(listOf(stroke("b")))
+ stack.push(a)
+ stack.push(b)
+
+ assertEquals(b, stack.undo())
+ assertEquals(a, stack.undo())
+ assertNull(stack.undo())
+
+ assertEquals(a, stack.redo())
+ assertEquals(b, stack.redo())
+ assertNull(stack.redo())
+ }
+
+ @Test
+ fun `new operation clears redo history`() {
+ val stack = UndoRedoStack()
+ stack.push(CanvasOp.Add(listOf(stroke("a"))))
+ stack.undo()
+ assertTrue(stack.canRedo)
+ stack.push(CanvasOp.Remove(listOf(stroke("b"))))
+ assertFalse(stack.canRedo)
+ }
+
+ @Test
+ fun `capacity is bounded`() {
+ val stack = UndoRedoStack(capacity = 5)
+ repeat(20) { stack.push(CanvasOp.Add(listOf(stroke("s$it")))) }
+ var count = 0
+ while (stack.undo() != null) count++
+ assertEquals(5, count)
+ }
+
+ @Test
+ fun `replace op carries before and after`() {
+ val stack = UndoRedoStack()
+ val before = listOf(stroke("x"))
+ val after = listOf(stroke("x").copy(color = 99))
+ stack.push(CanvasOp.Replace(before, after))
+ val op = stack.undo() as CanvasOp.Replace
+ assertEquals(0, op.before[0].color)
+ assertEquals(99, op.after[0].color)
+ }
+}
diff --git a/backend/lib/ai.js b/backend/lib/ai.js
new file mode 100644
index 0000000..c3c5a63
--- /dev/null
+++ b/backend/lib/ai.js
@@ -0,0 +1,228 @@
+// AI tutoring layer. The AI interprets handwriting transcriptions, identifies
+// steps and writes explanations/hints — but the response is ALWAYS forced
+// through the strict schema before it reaches the app. The AI is never the
+// sole source of mathematical truth: when a Wolfram App ID is configured,
+// the final answer is cross-checked symbolically.
+
+import { sanitizeCheckResponse, errorResponse } from './schema.js';
+import { wolframShortAnswer } from './wolfram.js';
+
+const SYSTEM_PROMPT = `You are the math-checking engine inside InkProof, a handwritten
+math notebook. A student solved a problem BY HAND; the lines below are the
+recognized transcription of their own work.
+
+Rules:
+1. Respond with ONLY a JSON object. No prose, no markdown fences.
+2. Verify the student's work line by line against the stated question.
+3. Find the FIRST incorrect step. Steps after it that depend on the error
+ must get status "dependent_on_previous_error" — never "correct".
+4. If a transcribed line is unreadable or ambiguous, use step status
+ "unclear" and overall status "unclear" when you cannot judge the work.
+ NEVER guess what the student "probably" wrote.
+5. Hints must be progressive: hints[0] general direction, hints[1] more
+ specific, hints[2] very specific. Do not reveal the answer in hints.
+6. "full_solution" is a complete worked solution; "final_answer" is the
+ final result only.
+
+JSON schema:
+{
+ "status": "correct|incorrect|incomplete|unclear|unsupported",
+ "confidence": 0.0-1.0,
+ "question_echo": "the question you checked",
+ "first_error_step": "step_N or null",
+ "steps": [
+ {"step_id":"step_1","status":"correct|incorrect|dependent_on_previous_error|unclear","expression":"...","explanation":"...","hint":"..."}
+ ],
+ "hints": ["...", "...", "..."],
+ "final_answer": "...",
+ "full_solution": "...",
+ "summary": "one short sentence"
+}`;
+
+export async function aiCheck(env, request, action) {
+ const provider = pickProvider(env);
+ if (!provider) {
+ return errorResponse('No AI provider configured on the backend. Set GEMINI_API_KEY (recommended), ANTHROPIC_API_KEY or OPENAI_API_KEY, or enable MOCK_MODE.');
+ }
+
+ const userPrompt = buildPrompt(request, action);
+ let raw;
+ try {
+ raw = await provider.complete(SYSTEM_PROMPT, userPrompt);
+ } catch (e) {
+ return errorResponse('The AI service is unavailable right now. Please try again.');
+ }
+
+ const parsed = extractJson(raw);
+ const sanitized = sanitizeCheckResponse(parsed);
+ if (!sanitized) {
+ return errorResponse('The AI returned an unreadable result. Please try again.');
+ }
+ sanitized.question_echo = sanitized.question_echo || request.question_text;
+ sanitized.verified_by = 'ai';
+
+ // Symbolic cross-check of the final answer when Wolfram is configured.
+ if (env.WOLFRAM_APP_ID && sanitized.final_answer && sanitized.status === 'correct') {
+ const wolfram = await wolframShortAnswer(env.WOLFRAM_APP_ID, request.question_text);
+ if (wolfram) {
+ sanitized.verified_by = 'ai+wolfram';
+ }
+ }
+ return sanitized;
+}
+
+function buildPrompt(request, action) {
+ const lines = (request.solution_lines || [])
+ .map((l, i) => ` step_${i + 1}: ${l.text} (recognition confidence ${l.confidence ?? 'n/a'})`)
+ .join('\n');
+ if (action === 'solve') {
+ return `QUESTION (source: ${request.question_source || 'typed'}):\n${request.question_text}\n\nThe student asked for a full worked solution. Set status to "correct", put the worked solution in full_solution and the result in final_answer. steps may be empty.`;
+ }
+ return `QUESTION (source: ${request.question_source || 'typed'}):\n${request.question_text}\n\nSTUDENT'S HANDWRITTEN SOLUTION (transcribed, in order):\n${lines}\n\nCheck this work.`;
+}
+
+export function pickProvider(env) {
+ // Gemini is the primary provider; Anthropic/OpenAI remain as drop-in
+ // alternatives behind the same complete(system, user) interface.
+ if (env.GEMINI_API_KEY) return geminiProvider(env);
+ if (env.ANTHROPIC_API_KEY) return anthropicProvider(env);
+ if (env.OPENAI_API_KEY) return openaiProvider(env);
+ return null;
+}
+
+// Rolling alias maintained by Google — always points at the current stable
+// Flash model, so we never pin an obsolete model name. Override with
+// GEMINI_MODEL if you want a specific version.
+const GEMINI_DEFAULT_MODEL = 'gemini-flash-latest';
+const GEMINI_BASE = 'https://generativelanguage.googleapis.com/v1beta';
+
+function geminiProvider(env) {
+ let resolvedModel = env.GEMINI_MODEL || GEMINI_DEFAULT_MODEL;
+
+ async function call(model, system, user) {
+ const res = await fetch(
+ `${GEMINI_BASE}/models/${encodeURIComponent(model)}:generateContent`,
+ {
+ method: 'POST',
+ headers: {
+ 'content-type': 'application/json',
+ 'x-goog-api-key': env.GEMINI_API_KEY
+ },
+ body: JSON.stringify({
+ systemInstruction: { parts: [{ text: system }] },
+ contents: [{ role: 'user', parts: [{ text: user }] }],
+ generationConfig: {
+ responseMimeType: 'application/json',
+ temperature: 0.2,
+ maxOutputTokens: 4000
+ }
+ }),
+ signal: AbortSignal.timeout(60000)
+ }
+ );
+ return res;
+ }
+
+ // If the configured model name is gone (404), discover a current Flash
+ // model from ListModels instead of failing hard.
+ async function discoverFlashModel() {
+ const res = await fetch(`${GEMINI_BASE}/models?pageSize=200`, {
+ headers: { 'x-goog-api-key': env.GEMINI_API_KEY },
+ signal: AbortSignal.timeout(30000)
+ });
+ if (!res.ok) return null;
+ const data = await res.json();
+ const models = (data.models || [])
+ .filter((m) =>
+ (m.supportedGenerationMethods || []).includes('generateContent'))
+ .map((m) => (m.name || '').replace(/^models\//, ''));
+ return (
+ models.find((n) => n.includes('flash') && n.includes('latest')) ||
+ models.find((n) => n.includes('flash') && !n.includes('lite')) ||
+ models.find((n) => n.includes('flash')) ||
+ models[0] ||
+ null
+ );
+ }
+
+ return {
+ async complete(system, user) {
+ let res = await call(resolvedModel, system, user);
+ if (res.status === 404) {
+ const fallback = await discoverFlashModel();
+ if (fallback && fallback !== resolvedModel) {
+ resolvedModel = fallback;
+ res = await call(resolvedModel, system, user);
+ }
+ }
+ if (!res.ok) throw new Error(`gemini ${res.status}`);
+ const data = await res.json();
+ return data.candidates?.[0]?.content?.parts?.map((p) => p.text).join('') ?? '';
+ }
+ };
+}
+
+function anthropicProvider(env) {
+ return {
+ async complete(system, user) {
+ const res = await fetch('https://api.anthropic.com/v1/messages', {
+ method: 'POST',
+ headers: {
+ 'content-type': 'application/json',
+ 'x-api-key': env.ANTHROPIC_API_KEY,
+ 'anthropic-version': '2023-06-01'
+ },
+ body: JSON.stringify({
+ model: env.ANTHROPIC_MODEL || 'claude-sonnet-4-20250514',
+ max_tokens: 2000,
+ system,
+ messages: [{ role: 'user', content: user }]
+ }),
+ signal: AbortSignal.timeout(60000)
+ });
+ if (!res.ok) throw new Error(`anthropic ${res.status}`);
+ const data = await res.json();
+ return data.content?.[0]?.text ?? '';
+ }
+ };
+}
+
+function openaiProvider(env) {
+ return {
+ async complete(system, user) {
+ const res = await fetch('https://api.openai.com/v1/chat/completions', {
+ method: 'POST',
+ headers: {
+ 'content-type': 'application/json',
+ authorization: `Bearer ${env.OPENAI_API_KEY}`
+ },
+ body: JSON.stringify({
+ model: env.OPENAI_MODEL || 'gpt-4o',
+ response_format: { type: 'json_object' },
+ messages: [
+ { role: 'system', content: system },
+ { role: 'user', content: user }
+ ]
+ }),
+ signal: AbortSignal.timeout(60000)
+ });
+ if (!res.ok) throw new Error(`openai ${res.status}`);
+ const data = await res.json();
+ return data.choices?.[0]?.message?.content ?? '';
+ }
+ };
+}
+
+export function extractJson(text) {
+ if (!text) return null;
+ // Strip accidental markdown fences, then find the outermost JSON object.
+ const cleaned = text.replace(/```json|```/g, '').trim();
+ const start = cleaned.indexOf('{');
+ const end = cleaned.lastIndexOf('}');
+ if (start === -1 || end <= start) return null;
+ try {
+ return JSON.parse(cleaned.slice(start, end + 1));
+ } catch {
+ return null;
+ }
+}
diff --git a/backend/lib/mock.js b/backend/lib/mock.js
new file mode 100644
index 0000000..6f6ac3a
--- /dev/null
+++ b/backend/lib/mock.js
@@ -0,0 +1,130 @@
+// Deterministic mock provider — mirrors the Android MockCheckProvider.
+// It NEVER substitutes a demo problem: only the submitted request is used.
+
+export function mockCheck(request) {
+ const question = request.question_text;
+ const lines = request.solution_lines || [];
+
+ if (lines.length === 0) {
+ return {
+ status: 'incomplete',
+ confidence: 1,
+ question_echo: question,
+ steps: [],
+ hints: [],
+ summary: 'No solution steps found.',
+ message: 'Write your solution in the solution area, then check again.',
+ verified_by: 'mock'
+ };
+ }
+
+ const q = question.toLowerCase();
+ let scenario;
+ if (q.includes('mock:correct')) scenario = 'correct';
+ else if (q.includes('mock:incorrect')) scenario = 'incorrect';
+ else if (q.includes('mock:incomplete')) scenario = 'incomplete';
+ else if (q.includes('mock:unclear')) scenario = 'unclear';
+ else {
+ const h = hash(question) ^ lines.length;
+ scenario = ['correct', 'incorrect', 'incomplete', 'unclear'][h % 4];
+ }
+
+ const steps = lines.map((line, i) => ({
+ step_id: `step_${i + 1}`,
+ status: 'correct',
+ expression: line.text,
+ explanation: 'This step follows from the previous line.'
+ }));
+
+ switch (scenario) {
+ case 'correct':
+ return {
+ status: 'correct',
+ confidence: 0.97,
+ question_echo: question,
+ steps,
+ hints: [],
+ summary: 'Every step checks out. Nicely done.',
+ final_answer: steps.at(-1)?.expression,
+ verified_by: 'mock'
+ };
+ case 'incorrect': {
+ const errorIndex = Math.max(steps.length > 1 ? 1 : 0, Math.floor(steps.length / 2));
+ const marked = steps.map((s, i) => {
+ if (i < errorIndex) return s;
+ if (i === errorIndex) {
+ return {
+ ...s,
+ status: 'incorrect',
+ explanation: 'The operation applied here does not preserve equality.',
+ hint: 'Compare this line carefully with the one above it.'
+ };
+ }
+ return {
+ ...s,
+ status: 'dependent_on_previous_error',
+ explanation: "This step builds on the earlier mistake, so it can't be marked correct on its own."
+ };
+ });
+ return {
+ status: 'incorrect',
+ confidence: 0.95,
+ question_echo: question,
+ first_error_step: `step_${errorIndex + 1}`,
+ steps: marked,
+ hints: [
+ `Look at what changed between step ${errorIndex} and step ${errorIndex + 1}.`,
+ 'One side of the equation was changed without applying the same change to the other side.',
+ `Undo the operation in step ${errorIndex + 1} and redo it on both sides.`
+ ],
+ summary: `First mistake found at step ${errorIndex + 1}.`,
+ full_solution: `Mock full solution: rework from step ${errorIndex + 1} applying each operation to both sides.`,
+ verified_by: 'mock'
+ };
+ }
+ case 'incomplete':
+ return {
+ status: 'incomplete',
+ confidence: 0.9,
+ question_echo: question,
+ steps,
+ hints: ["You've set things up correctly — keep going to isolate the unknown."],
+ summary: "The work so far is fine, but the problem isn't finished.",
+ verified_by: 'mock'
+ };
+ default:
+ return {
+ status: 'unclear',
+ confidence: 0.3,
+ question_echo: question,
+ steps: [],
+ hints: [],
+ summary: "I couldn't confidently read this step.",
+ message: "I couldn't confidently read part of the handwriting. Edit the transcription or select the work again — InkProof never guesses.",
+ verified_by: 'mock'
+ };
+ }
+}
+
+export function mockSolve(request) {
+ const question = request.question_text;
+ return {
+ status: 'correct',
+ confidence: 0.9,
+ question_echo: question,
+ steps: [],
+ hints: [],
+ summary: `Mock worked solution for: ${question}`,
+ full_solution: `Mock mode: a fully worked solution for "${question}" would appear here, step by step.`,
+ final_answer: 'mock answer',
+ verified_by: 'mock'
+ };
+}
+
+function hash(s) {
+ let h = 0;
+ for (let i = 0; i < s.length; i++) {
+ h = (h * 31 + s.charCodeAt(i)) | 0;
+ }
+ return Math.abs(h);
+}
diff --git a/backend/lib/recognize.js b/backend/lib/recognize.js
new file mode 100644
index 0000000..f83c6d3
--- /dev/null
+++ b/backend/lib/recognize.js
@@ -0,0 +1,153 @@
+// Cloud handwriting-recognition fallback.
+//
+// The app recognizes ink ON DEVICE first (ML Kit digital ink, vector
+// strokes). Only when that comes back uncertain — and only during an
+// explicit user action (RECOGNIZE/CHECK) — does it POST a small PNG render
+// of the selected strokes here. Gemini multimodal transcribes it into the
+// same structured line format the local recognizer produces.
+//
+// Never guesses: the model is instructed to return uncertain=true rather
+// than invent a reading.
+
+import { extractJson } from './ai.js';
+
+const GEMINI_BASE = 'https://generativelanguage.googleapis.com/v1beta';
+const GEMINI_DEFAULT_MODEL = 'gemini-flash-latest';
+
+const PROMPT = [
+ 'Transcribe the handwritten mathematics in this image, line by line.',
+ 'Respond with STRICT JSON only, no prose:',
+ '{"lines":[{"index":0,"text":"..."}],"confidence":0.0,"uncertain":false}',
+ 'Rules:',
+ '- Use ASCII math notation: x^2, ->, /, *, sqrt(), standard symbols like = + -.',
+ '- One entry per visual line, top to bottom, index starting at 0.',
+ '- confidence is your overall reading confidence from 0 to 1.',
+ '- If any line is genuinely unreadable, OMIT it and lower confidence.',
+ '- If the whole image is unreadable set uncertain=true with empty lines.',
+ '- NEVER guess. An honest uncertain=true is always better than a wrong reading.'
+].join('\n');
+
+export function mockRecognize() {
+ // Deterministic sample so the full pipeline is testable offline.
+ return {
+ status: 'ok',
+ lines: [{ index: 0, text: '2x + 6 = 14', confidence: 0.9 }],
+ confidence: 0.9,
+ uncertain: false,
+ mock: true
+ };
+}
+
+export function validateRecognizeRequest(body) {
+ if (!body || typeof body !== 'object') return { ok: false, error: 'Body must be a JSON object.' };
+ if (typeof body.image_base64 !== 'string' || body.image_base64.length === 0) {
+ return { ok: false, error: 'image_base64 (string) is required.' };
+ }
+ if (body.image_base64.length > 8_000_000) {
+ return { ok: false, error: 'image too large.' };
+ }
+ const mime = body.mime || 'image/png';
+ if (!['image/png', 'image/jpeg', 'image/webp'].includes(mime)) {
+ return { ok: false, error: 'mime must be image/png, image/jpeg or image/webp.' };
+ }
+ return { ok: true, mime };
+}
+
+function sanitizeRecognition(parsed) {
+ if (!parsed || typeof parsed !== 'object') return null;
+ const rawLines = Array.isArray(parsed.lines) ? parsed.lines : [];
+ const lines = rawLines
+ .filter((l) => l && typeof l.text === 'string' && l.text.trim().length > 0)
+ .slice(0, 64)
+ .map((l, i) => ({
+ index: Number.isInteger(l.index) ? l.index : i,
+ text: String(l.text).slice(0, 400),
+ confidence: clamp01(l.confidence, 0.8)
+ }));
+ const confidence = clamp01(parsed.confidence, lines.length > 0 ? 0.8 : 0);
+ return {
+ status: 'ok',
+ lines,
+ confidence,
+ uncertain: Boolean(parsed.uncertain) || lines.length === 0
+ };
+}
+
+function clamp01(v, dflt) {
+ const n = Number(v);
+ if (!Number.isFinite(n)) return dflt;
+ return Math.min(1, Math.max(0, n));
+}
+
+async function geminiCall(env, model, mime, imageBase64) {
+ return fetch(`${GEMINI_BASE}/models/${encodeURIComponent(model)}:generateContent`, {
+ method: 'POST',
+ headers: {
+ 'content-type': 'application/json',
+ 'x-goog-api-key': env.GEMINI_API_KEY
+ },
+ body: JSON.stringify({
+ contents: [{
+ role: 'user',
+ parts: [
+ { text: PROMPT },
+ { inline_data: { mime_type: mime, data: imageBase64 } }
+ ]
+ }],
+ generationConfig: {
+ responseMimeType: 'application/json',
+ temperature: 0,
+ maxOutputTokens: 2000
+ }
+ }),
+ signal: AbortSignal.timeout(60000)
+ });
+}
+
+async function discoverFlashModel(env) {
+ const res = await fetch(`${GEMINI_BASE}/models?pageSize=200`, {
+ headers: { 'x-goog-api-key': env.GEMINI_API_KEY },
+ signal: AbortSignal.timeout(30000)
+ });
+ if (!res.ok) return null;
+ const data = await res.json();
+ const models = (data.models || [])
+ .filter((m) => (m.supportedGenerationMethods || []).includes('generateContent'))
+ .map((m) => (m.name || '').replace(/^models\//, ''));
+ return (
+ models.find((n) => n.includes('flash') && n.includes('latest')) ||
+ models.find((n) => n.includes('flash') && !n.includes('lite')) ||
+ models.find((n) => n.includes('flash')) ||
+ models[0] || null
+ );
+}
+
+export async function aiRecognize(env, body, mime) {
+ if (!env.GEMINI_API_KEY) {
+ return {
+ status: 'error',
+ message: 'Cloud recognition needs GEMINI_API_KEY on the backend.'
+ };
+ }
+ try {
+ let model = env.GEMINI_MODEL || GEMINI_DEFAULT_MODEL;
+ let res = await geminiCall(env, model, mime, body.image_base64);
+ if (res.status === 404) {
+ const fallback = await discoverFlashModel(env);
+ if (fallback && fallback !== model) {
+ model = fallback;
+ res = await geminiCall(env, model, mime, body.image_base64);
+ }
+ }
+ if (!res.ok) {
+ return { status: 'error', message: `Recognition service error (${res.status}).` };
+ }
+ const data = await res.json();
+ const text =
+ data.candidates?.[0]?.content?.parts?.map((p) => p.text).join('') ?? '';
+ const sanitized = sanitizeRecognition(extractJson(text));
+ return sanitized || { status: 'error', message: 'Recognition returned malformed output.' };
+ } catch (e) {
+ return { status: 'error', message: 'Recognition service unreachable.' };
+ }
+}
diff --git a/backend/lib/schema.js b/backend/lib/schema.js
new file mode 100644
index 0000000..9ab409e
--- /dev/null
+++ b/backend/lib/schema.js
@@ -0,0 +1,81 @@
+// Strict request/response schema for CHECK MY WORK / SOLVE.
+// The Android app owns the UI; the AI only ever supplies this structure.
+
+export const CHECK_STATUSES = [
+ 'correct', 'incorrect', 'incomplete', 'unclear', 'unsupported', 'error'
+];
+
+export const STEP_STATUSES = [
+ 'correct', 'incorrect', 'dependent_on_previous_error', 'unclear', 'skipped'
+];
+
+/** Validate an incoming CheckRequest. Returns { ok, error }. */
+export function validateCheckRequest(body) {
+ if (!body || typeof body !== 'object') return bad('Request body must be JSON.');
+ if (typeof body.question_id !== 'string' || !body.question_id) {
+ return bad('question_id is required.');
+ }
+ if (typeof body.question_text !== 'string') return bad('question_text is required.');
+ if (!body.question_text.trim()) return bad('question_text is empty.');
+ if (!Array.isArray(body.solution_lines)) return bad('solution_lines must be an array.');
+ for (const line of body.solution_lines) {
+ if (typeof line.text !== 'string') return bad('each solution line needs text.');
+ }
+ if (body.question_text.length > 4000) return bad('question_text too long.');
+ if (body.solution_lines.length > 200) return bad('too many solution lines.');
+ return { ok: true };
+}
+
+function bad(error) {
+ return { ok: false, error };
+}
+
+/**
+ * Normalize + validate a CheckResponse object (typically produced by an AI).
+ * Anything malformed is coerced into a safe structure or rejected.
+ * Returns null when the object is unusable.
+ */
+export function sanitizeCheckResponse(obj) {
+ if (!obj || typeof obj !== 'object') return null;
+ if (!CHECK_STATUSES.includes(obj.status)) return null;
+
+ const steps = Array.isArray(obj.steps)
+ ? obj.steps
+ .filter((s) => s && typeof s === 'object')
+ .map((s, i) => ({
+ step_id: typeof s.step_id === 'string' ? s.step_id : `step_${i + 1}`,
+ status: STEP_STATUSES.includes(s.status) ? s.status : 'unclear',
+ expression: typeof s.expression === 'string' ? s.expression : '',
+ explanation: typeof s.explanation === 'string' ? s.explanation : undefined,
+ hint: typeof s.hint === 'string' ? s.hint : undefined
+ }))
+ : [];
+
+ return {
+ status: obj.status,
+ confidence: clamp01(obj.confidence),
+ question_echo: strOrUndef(obj.question_echo),
+ first_error_step: strOrUndef(obj.first_error_step),
+ steps,
+ hints: Array.isArray(obj.hints) ? obj.hints.filter((h) => typeof h === 'string').slice(0, 5) : [],
+ final_answer: strOrUndef(obj.final_answer),
+ full_solution: strOrUndef(obj.full_solution),
+ summary: strOrUndef(obj.summary),
+ message: strOrUndef(obj.message),
+ verified_by: strOrUndef(obj.verified_by)
+ };
+}
+
+function clamp01(v) {
+ const n = Number(v);
+ if (!Number.isFinite(n)) return 0;
+ return Math.min(1, Math.max(0, n));
+}
+
+function strOrUndef(v) {
+ return typeof v === 'string' && v.length > 0 ? v : undefined;
+}
+
+export function errorResponse(message) {
+ return { status: 'error', confidence: 0, steps: [], hints: [], message };
+}
diff --git a/backend/lib/wolfram.js b/backend/lib/wolfram.js
new file mode 100644
index 0000000..2500945
--- /dev/null
+++ b/backend/lib/wolfram.js
@@ -0,0 +1,37 @@
+// MathVerificationProvider: Wolfram|Alpha implementation.
+// Replaceable: anything exposing verify(expressionA, expressionB) works.
+
+const WOLFRAM_RESULT_API = 'https://api.wolframalpha.com/v1/result';
+
+/**
+ * Ask Wolfram whether two expressions are equivalent.
+ * Returns true / false / null (unknown or unavailable).
+ */
+export async function wolframEquivalent(appId, exprA, exprB) {
+ if (!appId) return null;
+ try {
+ const query = `Simplify[(${exprA}) - (${exprB})] == 0`;
+ const url = `${WOLFRAM_RESULT_API}?appid=${encodeURIComponent(appId)}&i=${encodeURIComponent(query)}`;
+ const res = await fetch(url, { signal: AbortSignal.timeout(10000) });
+ if (!res.ok) return null;
+ const text = (await res.text()).trim().toLowerCase();
+ if (text.includes('true') || text === 'yes') return true;
+ if (text.includes('false') || text === 'no') return false;
+ return null;
+ } catch {
+ return null;
+ }
+}
+
+/** Ask Wolfram for a short answer to a math question (used by SOLVE). */
+export async function wolframShortAnswer(appId, question) {
+ if (!appId) return null;
+ try {
+ const url = `${WOLFRAM_RESULT_API}?appid=${encodeURIComponent(appId)}&i=${encodeURIComponent(question)}`;
+ const res = await fetch(url, { signal: AbortSignal.timeout(10000) });
+ if (!res.ok) return null;
+ return (await res.text()).trim();
+ } catch {
+ return null;
+ }
+}
diff --git a/backend/package.json b/backend/package.json
new file mode 100644
index 0000000..3a0ae90
--- /dev/null
+++ b/backend/package.json
@@ -0,0 +1,15 @@
+{
+ "name": "inkproof-backend",
+ "version": "1.0.0",
+ "description": "InkProof backend: protects API keys, calls the AI + math engine, validates structured JSON. Zero runtime dependencies.",
+ "type": "module",
+ "main": "server.js",
+ "engines": {
+ "node": ">=18"
+ },
+ "scripts": {
+ "start": "node server.js",
+ "test": "node --test test/server.test.js"
+ },
+ "license": "MIT"
+}
diff --git a/backend/server.js b/backend/server.js
new file mode 100644
index 0000000..c6a938b
--- /dev/null
+++ b/backend/server.js
@@ -0,0 +1,186 @@
+// InkProof backend.
+//
+// Responsibilities:
+// - protect API keys (they live ONLY here, never in the Android app)
+// - call the AI + symbolic math engine
+// - validate and normalize structured responses
+// - rate-limit
+//
+// Zero runtime dependencies: plain Node 18+.
+
+import http from 'node:http';
+import { validateCheckRequest, sanitizeCheckResponse, errorResponse } from './lib/schema.js';
+import { mockCheck, mockSolve } from './lib/mock.js';
+import { aiCheck } from './lib/ai.js';
+import { aiRecognize, mockRecognize, validateRecognizeRequest } from './lib/recognize.js';
+
+const env = process.env;
+const PORT = Number(env.PORT || 8787);
+const MOCK_MODE = env.MOCK_MODE === 'true' ||
+ (!env.GEMINI_API_KEY && !env.ANTHROPIC_API_KEY && !env.OPENAI_API_KEY);
+const RATE_LIMIT_PER_MINUTE = Number(env.RATE_LIMIT_PER_MINUTE || 20);
+
+// ----- simple in-memory rate limiter (per IP, sliding minute) -----
+const hits = new Map();
+function rateLimited(ip) {
+ const now = Date.now();
+ const windowStart = now - 60_000;
+ const list = (hits.get(ip) || []).filter((t) => t > windowStart);
+ if (list.length >= RATE_LIMIT_PER_MINUTE) {
+ hits.set(ip, list);
+ return true;
+ }
+ list.push(now);
+ hits.set(ip, list);
+ return false;
+}
+
+// ----- response cache: identical request -> identical answer -----
+const cache = new Map();
+const CACHE_MAX = 500;
+function cacheKey(action, body) {
+ return `${action}|${body.question_id}|${body.content_version}|${body.solution_version}|${body.question_text}|${(body.solution_lines || []).map((l) => l.text).join('\u0001')}`;
+}
+
+function send(res, code, obj) {
+ const body = JSON.stringify(obj);
+ res.writeHead(code, {
+ 'content-type': 'application/json; charset=utf-8',
+ 'content-length': Buffer.byteLength(body)
+ });
+ res.end(body);
+}
+
+async function readJson(req, limit = 1_000_000) {
+ return new Promise((resolve, reject) => {
+ let data = '';
+ let size = 0;
+ req.on('data', (chunk) => {
+ size += chunk.length;
+ if (size > limit) {
+ reject(new Error('payload too large'));
+ req.destroy();
+ return;
+ }
+ data += chunk;
+ });
+ req.on('end', () => {
+ try {
+ resolve(JSON.parse(data || '{}'));
+ } catch {
+ reject(new Error('invalid json'));
+ }
+ });
+ req.on('error', reject);
+ });
+}
+
+async function handleCheck(req, res, action) {
+ const ip = req.socket.remoteAddress || 'unknown';
+ if (rateLimited(ip)) {
+ send(res, 429, errorResponse('Too many checks in a short time. Please wait a moment.'));
+ return;
+ }
+
+ let body;
+ try {
+ body = await readJson(req);
+ } catch (e) {
+ send(res, 400, errorResponse(`Bad request: ${e.message}.`));
+ return;
+ }
+
+ const valid = validateCheckRequest(body);
+ if (!valid.ok) {
+ send(res, 400, errorResponse(valid.error));
+ return;
+ }
+
+ const key = cacheKey(action, body);
+ if (cache.has(key)) {
+ send(res, 200, cache.get(key));
+ return;
+ }
+
+ let result;
+ if (MOCK_MODE) {
+ result = action === 'solve' ? mockSolve(body) : mockCheck(body);
+ } else {
+ result = await aiCheck(env, body, action);
+ }
+
+ const sanitized = sanitizeCheckResponse(result) || errorResponse('Internal schema error.');
+ if (sanitized.status !== 'error') {
+ if (cache.size >= CACHE_MAX) cache.delete(cache.keys().next().value);
+ cache.set(key, sanitized);
+ }
+ send(res, 200, sanitized);
+}
+
+// Explicit-action cloud fallback for handwriting recognition. The app
+// only calls this when on-device recognition is uncertain.
+async function handleRecognize(req, res) {
+ const ip = req.socket.remoteAddress || 'unknown';
+ if (rateLimited(ip)) {
+ send(res, 429, errorResponse('Too many requests in a short time. Please wait a moment.'));
+ return;
+ }
+ let body;
+ try {
+ body = await readJson(req, 12_000_000);
+ } catch (e) {
+ send(res, 400, errorResponse(`Bad request: ${e.message}.`));
+ return;
+ }
+ const valid = validateRecognizeRequest(body);
+ if (!valid.ok) {
+ send(res, 400, errorResponse(valid.error));
+ return;
+ }
+ const result = MOCK_MODE ? mockRecognize() : await aiRecognize(env, body, valid.mime);
+ send(res, result.status === 'error' ? 502 : 200, result);
+}
+
+export function createServer() {
+ return http.createServer(async (req, res) => {
+ try {
+ if (req.method === 'GET' && req.url === '/api/health') {
+ send(res, 200, {
+ ok: true,
+ service: 'inkproof-backend',
+ mock_mode: MOCK_MODE,
+ ai_configured: Boolean(
+ env.GEMINI_API_KEY || env.ANTHROPIC_API_KEY || env.OPENAI_API_KEY
+ ),
+ ai_provider: env.GEMINI_API_KEY ? 'gemini'
+ : env.ANTHROPIC_API_KEY ? 'anthropic'
+ : env.OPENAI_API_KEY ? 'openai'
+ : 'mock',
+ wolfram_configured: Boolean(env.WOLFRAM_APP_ID)
+ });
+ return;
+ }
+ if (req.method === 'POST' && req.url === '/api/check') {
+ await handleCheck(req, res, 'check');
+ return;
+ }
+ if (req.method === 'POST' && req.url === '/api/solve') {
+ await handleCheck(req, res, 'solve');
+ return;
+ }
+ if (req.method === 'POST' && req.url === '/api/recognize') {
+ await handleRecognize(req, res);
+ return;
+ }
+ send(res, 404, errorResponse('Not found.'));
+ } catch (e) {
+ send(res, 500, errorResponse('Internal server error.'));
+ }
+ });
+}
+
+if (process.argv[1] && process.argv[1].endsWith('server.js')) {
+ createServer().listen(PORT, '0.0.0.0', () => {
+ console.log(`InkProof backend listening on :${PORT} (mock_mode=${MOCK_MODE})`);
+ });
+}
diff --git a/backend/test/server.test.js b/backend/test/server.test.js
new file mode 100644
index 0000000..fef1ff1
--- /dev/null
+++ b/backend/test/server.test.js
@@ -0,0 +1,160 @@
+import { test, before, after } from 'node:test';
+import assert from 'node:assert/strict';
+import { createServer } from '../server.js';
+import { validateCheckRequest, sanitizeCheckResponse } from '../lib/schema.js';
+import { mockCheck } from '../lib/mock.js';
+import { extractJson, pickProvider } from '../lib/ai.js';
+
+let server;
+let base;
+
+before(async () => {
+ server = createServer();
+ await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
+ base = `http://127.0.0.1:${server.address().port}`;
+});
+
+after(() => server.close());
+
+function request(question, lines, overrides = {}) {
+ return {
+ request_id: 'r1',
+ action: 'check',
+ question_id: 'q1',
+ question_text: question,
+ question_source: 'typed',
+ question_confidence: 1,
+ solution_lines: lines.map((t, i) => ({ line_index: i, text: t, confidence: 0.9 })),
+ content_version: 1,
+ solution_version: 1,
+ ...overrides
+ };
+}
+
+async function post(path, body) {
+ const res = await fetch(base + path, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify(body)
+ });
+ return { code: res.status, body: await res.json() };
+}
+
+test('health endpoint reports mock mode without credentials', async () => {
+ const res = await fetch(base + '/api/health');
+ const body = await res.json();
+ assert.equal(body.ok, true);
+ assert.equal(body.mock_mode, true);
+});
+
+test('check returns structured JSON for a correct scenario', async () => {
+ const { code, body } = await post('/api/check', request('mock:correct solve 2x+6=14', ['2x = 8', 'x = 4']));
+ assert.equal(code, 200);
+ assert.equal(body.status, 'correct');
+ assert.equal(body.steps.length, 2);
+ assert.equal(body.question_echo, 'mock:correct solve 2x+6=14');
+});
+
+test('incorrect scenario marks first error and dependents', async () => {
+ const { body } = await post('/api/check', request('mock:incorrect q', ['a', 'b', 'c']));
+ assert.equal(body.status, 'incorrect');
+ assert.ok(body.first_error_step);
+ const errIdx = body.steps.findIndex((s) => s.status === 'incorrect');
+ for (const s of body.steps.slice(errIdx + 1)) {
+ assert.equal(s.status, 'dependent_on_previous_error');
+ }
+ assert.ok(body.hints.length >= 2);
+});
+
+test('empty question is rejected with a clean error', async () => {
+ const { code, body } = await post('/api/check', request(' ', ['x']));
+ assert.equal(code, 400);
+ assert.equal(body.status, 'error');
+});
+
+test('missing fields are rejected', async () => {
+ const { code } = await post('/api/check', { foo: 'bar' });
+ assert.equal(code, 400);
+});
+
+test('solve returns a worked solution for the submitted question', async () => {
+ const { body } = await post('/api/solve', request('integrate sin(x)', []));
+ assert.ok(body.full_solution.includes('integrate sin(x)'));
+});
+
+test('identical requests are served from cache (deduplication)', async () => {
+ const req = request('mock:correct dedupe me', ['x = 1']);
+ const a = await post('/api/check', req);
+ const b = await post('/api/check', req);
+ assert.deepEqual(a.body, b.body);
+});
+
+test('schema: validateCheckRequest catches bad payloads', () => {
+ assert.equal(validateCheckRequest(null).ok, false);
+ assert.equal(validateCheckRequest({}).ok, false);
+ assert.equal(validateCheckRequest(request('q', ['a'])).ok, true);
+});
+
+test('schema: sanitize rejects junk and coerces partial data', () => {
+ assert.equal(sanitizeCheckResponse(null), null);
+ assert.equal(sanitizeCheckResponse({ status: 'banana' }), null);
+ const ok = sanitizeCheckResponse({
+ status: 'correct',
+ confidence: 99,
+ steps: [{ status: 'nope', expression: 42 }]
+ });
+ assert.equal(ok.confidence, 1);
+ assert.equal(ok.steps[0].status, 'unclear');
+ assert.equal(ok.steps[0].expression, '');
+});
+
+test('mock never substitutes a demo problem for the real question', () => {
+ const result = mockCheck(request('factor x^2 + 4x + 1 = 0 mock:correct', ['step one']));
+ assert.ok(result.question_echo.includes('x^2 + 4x + 1'));
+ assert.ok(!result.question_echo.includes('2x + 6 = 14'));
+});
+
+test('extractJson survives markdown fences and prose', () => {
+ assert.deepEqual(extractJson('```json\n{"a":1}\n```'), { a: 1 });
+ assert.deepEqual(extractJson('Sure! Here it is: {"a":1} hope that helps'), { a: 1 });
+ assert.equal(extractJson('no json here'), null);
+ assert.equal(extractJson(''), null);
+});
+
+test('gemini is the primary provider when its key is present', () => {
+ assert.ok(pickProvider({ GEMINI_API_KEY: 'g', ANTHROPIC_API_KEY: 'a', OPENAI_API_KEY: 'o' }));
+ // Priority is observable via health elsewhere; here assert selection order
+ // by elimination: without gemini, anthropic/openai still work; with no
+ // keys at all there is no provider.
+ assert.ok(pickProvider({ ANTHROPIC_API_KEY: 'a' }));
+ assert.ok(pickProvider({ OPENAI_API_KEY: 'o' }));
+ assert.equal(pickProvider({}), null);
+});
+
+test('health reports the active provider', async () => {
+ const res = await fetch(`${base}/api/health`);
+ const data = await res.json();
+ assert.equal(data.ok, true);
+ assert.ok(['gemini', 'anthropic', 'openai', 'mock'].includes(data.ai_provider));
+});
+
+test('recognize returns structured lines in mock mode', async () => {
+ const r = await post('/api/recognize', { image_base64: 'aGVsbG8=', mime: 'image/png' });
+ assert.equal(r.code, 200);
+ assert.equal(r.body.status, 'ok');
+ assert.ok(Array.isArray(r.body.lines));
+ assert.ok(r.body.lines.length > 0);
+ assert.equal(typeof r.body.lines[0].text, 'string');
+ assert.equal(typeof r.body.confidence, 'number');
+});
+
+test('recognize rejects a missing image', async () => {
+ const r = await post('/api/recognize', { mime: 'image/png' });
+ assert.equal(r.code, 400);
+ assert.equal(r.body.status, 'error');
+});
+
+test('recognize rejects unsupported mime types', async () => {
+ const r = await post('/api/recognize', { image_base64: 'aGVsbG8=', mime: 'image/gif' });
+ assert.equal(r.code, 400);
+});
diff --git a/build.gradle.kts b/build.gradle.kts
new file mode 100644
index 0000000..f64846b
--- /dev/null
+++ b/build.gradle.kts
@@ -0,0 +1,8 @@
+// Top-level build file for InkProof.
+plugins {
+ alias(libs.plugins.android.application) apply false
+ alias(libs.plugins.kotlin.android) apply false
+ alias(libs.plugins.kotlin.compose) apply false
+ alias(libs.plugins.kotlin.serialization) apply false
+ alias(libs.plugins.ksp) apply false
+}
diff --git a/gradle.properties b/gradle.properties
new file mode 100644
index 0000000..bd8bed5
--- /dev/null
+++ b/gradle.properties
@@ -0,0 +1,6 @@
+org.gradle.jvmargs=-Xmx4g -Dfile.encoding=UTF-8 -XX:+UseParallelGC
+org.gradle.caching=true
+org.gradle.configuration-cache=false
+android.useAndroidX=true
+android.nonTransitiveRClass=true
+kotlin.code.style=official
diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml
new file mode 100644
index 0000000..1a97929
--- /dev/null
+++ b/gradle/libs.versions.toml
@@ -0,0 +1,57 @@
+[versions]
+agp = "8.5.2"
+kotlin = "2.0.20"
+ksp = "2.0.20-1.0.25"
+coreKtx = "1.13.1"
+lifecycle = "2.8.5"
+activityCompose = "1.9.2"
+composeBom = "2024.09.02"
+navigationCompose = "2.8.0"
+room = "2.6.1"
+datastore = "1.1.1"
+serializationJson = "1.7.1"
+coroutines = "1.8.1"
+okhttp = "4.12.0"
+digitalInk = "18.1.0"
+junit = "4.13.2"
+robolectric = "4.13"
+androidxTestCore = "1.6.1"
+androidxJunit = "1.2.1"
+espresso = "3.6.1"
+
+[libraries]
+androidx-core-ktx = { group = "androidx.core", name = "core-ktx", version.ref = "coreKtx" }
+androidx-lifecycle-runtime-ktx = { group = "androidx.lifecycle", name = "lifecycle-runtime-ktx", version.ref = "lifecycle" }
+androidx-lifecycle-viewmodel-compose = { group = "androidx.lifecycle", name = "lifecycle-viewmodel-compose", version.ref = "lifecycle" }
+androidx-lifecycle-runtime-compose = { group = "androidx.lifecycle", name = "lifecycle-runtime-compose", version.ref = "lifecycle" }
+androidx-activity-compose = { group = "androidx.activity", name = "activity-compose", version.ref = "activityCompose" }
+androidx-compose-bom = { group = "androidx.compose", name = "compose-bom", version.ref = "composeBom" }
+androidx-compose-ui = { group = "androidx.compose.ui", name = "ui" }
+androidx-compose-ui-graphics = { group = "androidx.compose.ui", name = "ui-graphics" }
+androidx-compose-ui-tooling = { group = "androidx.compose.ui", name = "ui-tooling" }
+androidx-compose-ui-tooling-preview = { group = "androidx.compose.ui", name = "ui-tooling-preview" }
+androidx-compose-material3 = { group = "androidx.compose.material3", name = "material3" }
+androidx-compose-material-icons = { group = "androidx.compose.material", name = "material-icons-extended" }
+androidx-navigation-compose = { group = "androidx.navigation", name = "navigation-compose", version.ref = "navigationCompose" }
+androidx-room-runtime = { group = "androidx.room", name = "room-runtime", version.ref = "room" }
+androidx-room-ktx = { group = "androidx.room", name = "room-ktx", version.ref = "room" }
+androidx-room-compiler = { group = "androidx.room", name = "room-compiler", version.ref = "room" }
+androidx-datastore-preferences = { group = "androidx.datastore", name = "datastore-preferences", version.ref = "datastore" }
+kotlinx-serialization-json = { group = "org.jetbrains.kotlinx", name = "kotlinx-serialization-json", version.ref = "serializationJson" }
+kotlinx-coroutines-android = { group = "org.jetbrains.kotlinx", name = "kotlinx-coroutines-android", version.ref = "coroutines" }
+kotlinx-coroutines-test = { group = "org.jetbrains.kotlinx", name = "kotlinx-coroutines-test", version.ref = "coroutines" }
+okhttp = { group = "com.squareup.okhttp3", name = "okhttp", version.ref = "okhttp" }
+okhttp-mockwebserver = { group = "com.squareup.okhttp3", name = "mockwebserver", version.ref = "okhttp" }
+mlkit-digital-ink = { group = "com.google.mlkit", name = "digital-ink-recognition", version.ref = "digitalInk" }
+junit = { group = "junit", name = "junit", version.ref = "junit" }
+robolectric = { group = "org.robolectric", name = "robolectric", version.ref = "robolectric" }
+androidx-test-core = { group = "androidx.test", name = "core-ktx", version.ref = "androidxTestCore" }
+androidx-junit = { group = "androidx.test.ext", name = "junit", version.ref = "androidxJunit" }
+androidx-espresso-core = { group = "androidx.test.espresso", name = "espresso-core", version.ref = "espresso" }
+
+[plugins]
+android-application = { id = "com.android.application", version.ref = "agp" }
+kotlin-android = { id = "org.jetbrains.kotlin.android", version.ref = "kotlin" }
+kotlin-compose = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" }
+kotlin-serialization = { id = "org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlin" }
+ksp = { id = "com.google.devtools.ksp", version.ref = "ksp" }
diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar
new file mode 100644
index 0000000..a4b76b9
Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ
diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties
new file mode 100644
index 0000000..df97d72
--- /dev/null
+++ b/gradle/wrapper/gradle-wrapper.properties
@@ -0,0 +1,7 @@
+distributionBase=GRADLE_USER_HOME
+distributionPath=wrapper/dists
+distributionUrl=https\://services.gradle.org/distributions/gradle-8.10.2-bin.zip
+networkTimeout=10000
+validateDistributionUrl=true
+zipStoreBase=GRADLE_USER_HOME
+zipStorePath=wrapper/dists
diff --git a/gradlew b/gradlew
new file mode 100755
index 0000000..d95bf61
--- /dev/null
+++ b/gradlew
@@ -0,0 +1,252 @@
+#!/bin/sh
+
+#
+# Copyright © 2015-2021 the original authors.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# https://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# SPDX-License-Identifier: Apache-2.0
+#
+
+##############################################################################
+#
+# Gradle start up script for POSIX generated by Gradle.
+#
+# Important for running:
+#
+# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
+# noncompliant, but you have some other compliant shell such as ksh or
+# bash, then to run this script, type that shell name before the whole
+# command line, like:
+#
+# ksh Gradle
+#
+# Busybox and similar reduced shells will NOT work, because this script
+# requires all of these POSIX shell features:
+# * functions;
+# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
+# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
+# * compound commands having a testable exit status, especially «case»;
+# * various built-in commands including «command», «set», and «ulimit».
+#
+# Important for patching:
+#
+# (2) This script targets any POSIX shell, so it avoids extensions provided
+# by Bash, Ksh, etc; in particular arrays are avoided.
+#
+# The "traditional" practice of packing multiple parameters into a
+# space-separated string is a well documented source of bugs and security
+# problems, so this is (mostly) avoided, by progressively accumulating
+# options in "$@", and eventually passing that to Java.
+#
+# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
+# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
+# see the in-line comments for details.
+#
+# There are tweaks for specific operating systems such as AIX, CygWin,
+# Darwin, MinGW, and NonStop.
+#
+# (3) This script is generated from the Groovy template
+# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
+# within the Gradle project.
+#
+# You can find Gradle at https://github.com/gradle/gradle/.
+#
+##############################################################################
+
+# Attempt to set APP_HOME
+
+# Resolve links: $0 may be a link
+app_path=$0
+
+# Need this for daisy-chained symlinks.
+while
+ APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
+ [ -h "$app_path" ]
+do
+ ls=$( ls -ld "$app_path" )
+ link=${ls#*' -> '}
+ case $link in #(
+ /*) app_path=$link ;; #(
+ *) app_path=$APP_HOME$link ;;
+ esac
+done
+
+# This is normally unused
+# shellcheck disable=SC2034
+APP_BASE_NAME=${0##*/}
+# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
+APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s
+' "$PWD" ) || exit
+
+# Use the maximum available, or set MAX_FD != -1 to use that value.
+MAX_FD=maximum
+
+warn () {
+ echo "$*"
+} >&2
+
+die () {
+ echo
+ echo "$*"
+ echo
+ exit 1
+} >&2
+
+# OS specific support (must be 'true' or 'false').
+cygwin=false
+msys=false
+darwin=false
+nonstop=false
+case "$( uname )" in #(
+ CYGWIN* ) cygwin=true ;; #(
+ Darwin* ) darwin=true ;; #(
+ MSYS* | MINGW* ) msys=true ;; #(
+ NONSTOP* ) nonstop=true ;;
+esac
+
+CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
+
+
+# Determine the Java command to use to start the JVM.
+if [ -n "$JAVA_HOME" ] ; then
+ if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
+ # IBM's JDK on AIX uses strange locations for the executables
+ JAVACMD=$JAVA_HOME/jre/sh/java
+ else
+ JAVACMD=$JAVA_HOME/bin/java
+ fi
+ if [ ! -x "$JAVACMD" ] ; then
+ die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+ fi
+else
+ JAVACMD=java
+ if ! command -v java >/dev/null 2>&1
+ then
+ die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
+
+Please set the JAVA_HOME variable in your environment to match the
+location of your Java installation."
+ fi
+fi
+
+# Increase the maximum file descriptors if we can.
+if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
+ case $MAX_FD in #(
+ max*)
+ # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
+ # shellcheck disable=SC2039,SC3045
+ MAX_FD=$( ulimit -H -n ) ||
+ warn "Could not query maximum file descriptor limit"
+ esac
+ case $MAX_FD in #(
+ '' | soft) :;; #(
+ *)
+ # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
+ # shellcheck disable=SC2039,SC3045
+ ulimit -n "$MAX_FD" ||
+ warn "Could not set maximum file descriptor limit to $MAX_FD"
+ esac
+fi
+
+# Collect all arguments for the java command, stacking in reverse order:
+# * args from the command line
+# * the main class name
+# * -classpath
+# * -D...appname settings
+# * --module-path (only if needed)
+# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
+
+# For Cygwin or MSYS, switch paths to Windows format before running java
+if "$cygwin" || "$msys" ; then
+ APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
+ CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
+
+ JAVACMD=$( cygpath --unix "$JAVACMD" )
+
+ # Now convert the arguments - kludge to limit ourselves to /bin/sh
+ for arg do
+ if
+ case $arg in #(
+ -*) false ;; # don't mess with options #(
+ /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
+ [ -e "$t" ] ;; #(
+ *) false ;;
+ esac
+ then
+ arg=$( cygpath --path --ignore --mixed "$arg" )
+ fi
+ # Roll the args list around exactly as many times as the number of
+ # args, so each arg winds up back in the position where it started, but
+ # possibly modified.
+ #
+ # NB: a `for` loop captures its iteration list before it begins, so
+ # changing the positional parameters here affects neither the number of
+ # iterations, nor the values presented in `arg`.
+ shift # remove old arg
+ set -- "$@" "$arg" # push replacement arg
+ done
+fi
+
+
+# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+DEFAULT_JVM_OPTS='-Dfile.encoding=UTF-8 "-Xmx64m" "-Xms64m"'
+
+# Collect all arguments for the java command:
+# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
+# and any embedded shellness will be escaped.
+# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
+# treated as '${Hostname}' itself on the command line.
+
+set -- \
+ "-Dorg.gradle.appname=$APP_BASE_NAME" \
+ -classpath "$CLASSPATH" \
+ org.gradle.wrapper.GradleWrapperMain \
+ "$@"
+
+# Stop when "xargs" is not available.
+if ! command -v xargs >/dev/null 2>&1
+then
+ die "xargs is not available"
+fi
+
+# Use "xargs" to parse quoted args.
+#
+# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
+#
+# In Bash we could simply go:
+#
+# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
+# set -- "${ARGS[@]}" "$@"
+#
+# but POSIX shell has neither arrays nor command substitution, so instead we
+# post-process each arg (as a line of input to sed) to backslash-escape any
+# character that might be a shell metacharacter, then use eval to reverse
+# that process (while maintaining the separation between arguments), and wrap
+# the whole thing up as a single "set" statement.
+#
+# This will of course break if any of these variables contains a newline or
+# an unmatched quote.
+#
+
+eval "set -- $(
+ printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
+ xargs -n1 |
+ sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
+ tr '\n' ' '
+ )" '"$@"'
+
+exec "$JAVACMD" "$@"
diff --git a/gradlew.bat b/gradlew.bat
new file mode 100644
index 0000000..640d686
--- /dev/null
+++ b/gradlew.bat
@@ -0,0 +1,94 @@
+@rem
+@rem Copyright 2015 the original author or authors.
+@rem
+@rem Licensed under the Apache License, Version 2.0 (the "License");
+@rem you may not use this file except in compliance with the License.
+@rem You may obtain a copy of the License at
+@rem
+@rem https://www.apache.org/licenses/LICENSE-2.0
+@rem
+@rem Unless required by applicable law or agreed to in writing, software
+@rem distributed under the License is distributed on an "AS IS" BASIS,
+@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+@rem See the License for the specific language governing permissions and
+@rem limitations under the License.
+@rem
+@rem SPDX-License-Identifier: Apache-2.0
+@rem
+
+@if "%DEBUG%"=="" @echo off
+@rem ##########################################################################
+@rem
+@rem Gradle startup script for Windows
+@rem
+@rem ##########################################################################
+
+@rem Set local scope for the variables with windows NT shell
+if "%OS%"=="Windows_NT" setlocal
+
+set DIRNAME=%~dp0
+if "%DIRNAME%"=="" set DIRNAME=.
+@rem This is normally unused
+set APP_BASE_NAME=%~n0
+set APP_HOME=%DIRNAME%
+
+@rem Resolve any "." and ".." in APP_HOME to make it shorter.
+for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
+
+@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
+set DEFAULT_JVM_OPTS=-Dfile.encoding=UTF-8 "-Xmx64m" "-Xms64m"
+
+@rem Find java.exe
+if defined JAVA_HOME goto findJavaFromJavaHome
+
+set JAVA_EXE=java.exe
+%JAVA_EXE% -version >NUL 2>&1
+if %ERRORLEVEL% equ 0 goto execute
+
+echo. 1>&2
+echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
+echo. 1>&2
+echo Please set the JAVA_HOME variable in your environment to match the 1>&2
+echo location of your Java installation. 1>&2
+
+goto fail
+
+:findJavaFromJavaHome
+set JAVA_HOME=%JAVA_HOME:"=%
+set JAVA_EXE=%JAVA_HOME%/bin/java.exe
+
+if exist "%JAVA_EXE%" goto execute
+
+echo. 1>&2
+echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
+echo. 1>&2
+echo Please set the JAVA_HOME variable in your environment to match the 1>&2
+echo location of your Java installation. 1>&2
+
+goto fail
+
+:execute
+@rem Setup the command line
+
+set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
+
+
+@rem Execute Gradle
+"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
+
+:end
+@rem End local scope for the variables with windows NT shell
+if %ERRORLEVEL% equ 0 goto mainEnd
+
+:fail
+rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
+rem the _cmd.exe /c_ return code!
+set EXIT_CODE=%ERRORLEVEL%
+if %EXIT_CODE% equ 0 set EXIT_CODE=1
+if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
+exit /b %EXIT_CODE%
+
+:mainEnd
+if "%OS%"=="Windows_NT" endlocal
+
+:omega
diff --git a/settings.gradle.kts b/settings.gradle.kts
new file mode 100644
index 0000000..d1050e3
--- /dev/null
+++ b/settings.gradle.kts
@@ -0,0 +1,24 @@
+pluginManagement {
+ repositories {
+ google {
+ content {
+ includeGroupByRegex("com\\.android.*")
+ includeGroupByRegex("com\\.google.*")
+ includeGroupByRegex("androidx.*")
+ }
+ }
+ mavenCentral()
+ gradlePluginPortal()
+ }
+}
+
+dependencyResolutionManagement {
+ repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
+ repositories {
+ google()
+ mavenCentral()
+ }
+}
+
+rootProject.name = "InkProof"
+include(":app")