Commit graph

184 commits

Author SHA1 Message Date
Huang Xin
8e2270aba4
feat(tts): preview voices and pick a default voice per language (#7322)
Some checks are pending
CodeQL Advanced / Analyze (actions) (push) Waiting to run
CodeQL Advanced / Analyze (javascript-typescript) (push) Waiting to run
CodeQL Advanced / Analyze (rust) (push) Waiting to run
Publish Docker image / build (linux/amd64, ubuntu-latest) (push) Waiting to run
Publish Docker image / build (linux/arm64, ubuntu-24.04-arm) (push) Waiting to run
Publish Docker image / merge (push) Blocked by required conditions
Build with Nix / tests (push) Waiting to run
PR checks / koplugin_rust_lint (push) Waiting to run
PR checks / nix_flake_check (push) Waiting to run
PR checks / rust_lint (push) Waiting to run
PR checks / build_web_app (push) Waiting to run
PR checks / test_web_app (1) (push) Waiting to run
PR checks / test_web_app (2) (push) Waiting to run
PR checks / test_web_browser (push) Waiting to run
PR checks / test_extensions (push) Waiting to run
PR checks / build_tauri_app (push) Waiting to run
Scorecard supply-chain security / Scorecard analysis (push) Waiting to run
Deploy to vercel on merge / build_and_deploy (push) Waiting to run
* feat(tts): preview voices and pick a default voice per language

Settings > TTS gets a Voice Library page, and the player's voice list
is rebuilt on the same component (VoiceList). Each row shows the
voice's gender, its language and region, and a play button.

- Opened from the library, the page lists every language that has
  voices, with a gender filter. Previews read a sample sentence in the
  voice's language (75 languages, gender-neutral wording).
- With a book open, only the book language's voices are listed, and
  previews read whole sentences from the start of the current page:
  at least 5 s of estimated speech, at most 400 characters.
- Choosing a voice in Settings makes it the default for that language
  only. Picking one in the player sets that language's default too, and
  TTSController switches to a language's engine when the reading
  language changes.
- In the player, a preview pauses reading. Picking the voice just
  heard resumes reading with it; leaving the list keeps it paused.
- Readest Voice previews need a signed-in reader; the other engines
  don't. /api/tts/readest/stream takes a `preview` lane: any signed-in
  plan, any offered voice, one segment of at most 400 characters, and a
  6,000-character daily floor for plans without Readest Voice. The
  voice service sees an ordinary listening window under its own client
  id, so its contract is unchanged.
- Gender comes from a generated map for Edge, from the voice id for
  Kokoro voices (Readest Voice and custom services), and from
  AVSpeechSynthesisVoice on iOS. Android and Web Speech report none, so
  those rows have no badge.
- The Voice Library lists Linux Speech Dispatcher voices (#7314) as it
  does Android and iOS system voices.

Tests that fail without the change (old file put back, new test run):
- tts-readest-stream-route.test.ts: 6 preview tests, e.g. "expected
  403 to be 200" and "expected { error: 'PLAN_REQUIRED' } to deeply
  equal { error: 'VOICE_TIER_REQUIRED' }".
- tts-controller-readest.test.ts: 4 tests on the per-language engine,
  e.g. "expected Mock{ name: 'edge-tts', ... } to be Mock{ name:
  'readest-tts', ... }".
- edgeTTS.test.ts: "expected undefined to be 'female'";
  readest-voice-catalog.test.ts: 2 gender tests.
- useTTSControl.test.tsx: "reads on with the new voice when asked to,
  though reading is stopped" fails with "expected vi.fn() to be called
  at least once".
- tts-voice-library.test.ts, Linux: "expected [] to deeply equal
  [ 'de' ]".

Checks on this tree, rebased on origin/main 6ab667bd2: pnpm test (15365
passed, 16 skipped), pnpm test:browser (934 passed, 1 skipped), pnpm
lint, pnpm format:check, pnpm fmt:check, pnpm clippy:check, pnpm
test:rust (206 passed).

Real use, macOS tauri dev build (before the rebase onto 6ab667bd2,
which changed only the native client and the library's platform list):
- Edge previews synthesized in about 2 s and played 7-12 s samples to
  the end. A macOS system voice spoke its sample. Starting a second
  preview stopped the first.
- In a German EPUB, the Voice Library listed only German voices and
  the preview read the page's heading and first sentence.
- Player: reading, then preview, then picking the voice resumed reading
  with it. Preview, then back, left reading paused until Play.
- Both screens in dark, light, e-ink, RTL and phone width.
- Found while testing: WebKit could not decode the 1-sample silent WAV
  that unlocks autoplay; previews now prime with a 0.1 s clip.

Not run:
- A Readest Voice preview end to end: a dev origin can't reach the
  production voice service, so the route tests cover the lane. Apps can
  preview Readest voices once the web server is deployed.
- iOS (the Swift change was only parsed), Android, and Linux previews.
- OmniVoice voices have no gender badge until the readest-voice catalog
  export adds a gender field.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(tts): page preview text from a section document without a root

CodeRabbit asked for a guard in textFromBlock for a section document
that a remount left without a root, where createTreeWalker(null) would
throw and leave the preview button loading. The reader's progress
range is a live Range (foliate builds it with doc.createRange()), so
removing the root collapses it onto the document. closestBlock() then
finds no block, getPagePreviewText() returns null before any tree
walker is made, and the preview reads the sample text instead.

The new test removes a page's root and checks that the range now sits
on the document and that the preview text is null. jsdom throws
"parameter 1 is not of type 'Node'" for createTreeWalker(null), so the
test fails if the walker is ever reached in that state.

Checks: tts-voice-preview-text.test.ts (7 passed); the pre-push hook
runs format:check, lint and the full suite on this commit.

Raised by CodeRabbit on #7322.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 13:37:48 +01:00
Huang Xin
50c4ae8258
feat(tts): read aloud with Speech Dispatcher voices on Linux (#7314)
* feat(tts): read aloud with Speech Dispatcher voices on Linux

Read Aloud on Linux can now use the voices installed in Speech
Dispatcher (eSpeak NG, or Piper through a module) under System TTS.
The native-tts plugin speaks SSIP over the daemon's Unix socket with
no speech library linked, so the AppImage uses the host daemon and the
Flatpak needs --filesystem=xdg-run/speech-dispatcher:ro
(docs/linux-system-tts.md). Each reader window gets its own
connection, closed when the window is destroyed. If the daemon or its
voices are unavailable, the other engines remain.

- Voices keep their Speech Dispatcher names; eSpeak NG's per-variant
  copies ("English (America)+Annie") are dropped, so English lists 9
  voices instead of 945. The module is appended only when two modules
  list voices.
- Pause stops the sentence and Play reads it again, as on Android. A
  speechd PAUSE holds back the restarted SPEAK, and RESUME then
  cancels it, so Play skipped the paused sentence.
- A closing window cancels its speech: speechd finishes a disconnected
  client's message.
- Events that arrive before the speak reply are kept, and an aborted
  utterance is canceled by ID so a late reply cannot stop its
  replacement. Rates go to speechd as given, without the mobile
  exponent.

Tests that fail without the change:
- Rust (plugin): pause_cancels_so_the_restarted_sentence_is_not_held_back
  (left "PAUSE SELF\r\n", right "CANCEL SELF\r\n");
  lists_each_espeak_voice_once_rather_than_once_per_variant (4 voices,
  expected 2); closing_a_reader_window_silences_its_speech (left "",
  right "CANCEL SELF\r\n").
- TS: 8 tests in native-tts-client.test.ts and tts-controller.test.ts
  fail against the old NativeTTSClient/TTSController, 7 on assertions
  (e.g. "expected [] to deeply equal [ 'boundary', 'end' ]",
  "expected null not to be null" for the Linux system voices) and one
  on its 5 s timeout (overlapping speak replies).

Real use, Linux CEF dev build, isolated HOME, host speech-dispatcher
0.12.1 with its eSpeak NG module:
- Pause/Play 3 of 3 re-read the paused sentence with no "Speech
  interrupted"; before the fix 3 of 3 skipped it.
- Speak on a selection while paused speaks (before: silent).
- Picker lists 9 System TTS voices; choosing another voice and pressing
  Play reads on in that voice.
- Speed: 2.7 s per sentence at 1.5x, 5.2 s at 0.95x.
- Closing the book at +1.4 s into a sentence: speech ends 1 s later;
  without the cancel it ran 3.6 s to the sentence's end.
- SPEECHD_ADDRESS at a missing socket: "System TTS unavailable" is
  logged and Read Aloud falls back to Edge TTS.

Checks: plugin cargo test (36 passed), pnpm test:rust (204 passed),
the two TS suites (171 passed), pnpm lint, pnpm fmt:check, pnpm
clippy:check, cargo check of the plugin for x86_64-pc-windows-gnu and
aarch64-linux-android.

Not run: the AppImage and Flatpak packages, two reader windows reading
at once, light/dark/e-ink (no UI changed). Chinese books get no System
TTS voice: eSpeak NG labels them cmn/yue and language matching expects
zh.

Closes #6805

Reported by ell1e on GitHub.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(tts): keep a slow Speech Dispatcher voice list from disabling System TTS

Every command waited at most 3 s, and a timeout closes the connection
because a late reply would answer the next command. eSpeak NG sends
about 15k voice rows for LIST SYNTHESIS_VOICES: 0.4 s here, warm or
cold, so a slow machine or module could run past 3 s. voices() then
took the dead connection for a module without voices and failed with
"Speech Dispatcher has no installed voices".

The voice list now gets 10 s, under the reader's 15 s engine init
limit. A lost connection ends the listing with its cause ("Speech
Dispatcher did not answer in time while listing piper voices"); a
module that answers with an error is still skipped.

Raised by CodeRabbit on #7314.

Tests that fail without the change:
- waits_for_a_slow_voice_list: the reply comes 3.5 s after the request;
  fails at "a voice list slower than one command must still arrive".
- a_lost_connection_while_listing_voices_reports_the_cause: left
  Some("Speech Dispatcher has no installed voices"), right
  Some("Speech Dispatcher disconnected while listing espeak-ng voices").

Checks: plugin cargo test --lib (38 passed), pnpm test:rust (204
passed), pnpm fmt:check, pnpm clippy:check, cargo fmt --check in the
plugin. Real daemon (speech-dispatcher 0.12.1, eSpeak NG): init()
lists 141 voices in 0.43 s.

Not run: a real slow module (the delay is simulated in the test), and
the Tauri app after this change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(tts): give every reader speed its own Speech Dispatcher rate

The reader offers 0.5x to 3x (the speed ruler and RSVP's rate list),
but the Linux bridge sent (rate - 1) * 100 clamped to SSIP's -100..100,
so 2x, 2.5x and 3x all became 100 and sounded the same, and 0.5x only
reached -50. 0.5x-1x now spreads over -100..0 and 1x-3x over 0..100.

Raised by CodeRabbit on #7314.

Test that fails without the change:
every_reader_speed_has_its_own_ssip_rate, left
[-50, -25, 0, 50, 100, 100, 100], right [-100, -50, 0, 25, 50, 75, 100]
for 0.5, 0.75, 1, 1.5, 2, 2.5, 3.

Real daemon (speech-dispatcher 0.12.1, eSpeak NG), one sentence spoken
through SpeechDispatcher at each speed, begin to end: 0.5x 12.17 s,
1x 5.57 s, 1.5x 3.91 s, 2x 2.97 s, 2.5x 2.29 s, 3x 1.82 s (0.46x,
1.42x, 1.88x, 2.44x, 3.05x of 1x).

Checks: plugin cargo test --lib (39 passed), pnpm test:rust (204
passed), pnpm fmt:check, pnpm clippy:check, cargo fmt --check in the
plugin.

Not run: the speed ruler in the Tauri app after this change; the
mapping from the ruler to set_rate is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 10:38:54 +01:00
Huang Xin
6e2390fe5e
feat(metadata): search for book covers in app (#7290)
Add Google, Bing and DuckDuckGo image search from Edit Metadata, using the
book title and author. Allow device-local custom search engine templates.
Show the original engine page with explicit image selection, then require
app-owned confirmation before a native fetch so remote pages cannot silently
forge a cover selection. Stage the confirmed image through the existing
cover-save flow. Support desktop and mobile native browsers, with an external search
and file-import fallback on web.

Verification on origin/main 617db1aa3:
- Five affected frontend suites: 50 tests passed; pnpm lint passed.
- Rust formatting and CEF Clippy passed; 202 Rust library tests and four
  native bridge model tests passed.
- Regression for editing a search field beneath an overlapping notification
  failed before the fix (expected aria-pressed false, received true) and
  passes with the fix. Chooser regression failed with the old query input.
- Forged native browser results now wait for app-owned confirmation before
  fetching; confirmation and cancellation tests pass. Verified on Android
  that a forged result stops there, then fetch and Save pass after confirmation.
- Native CEF app: Bing cover selection/save/reload, DuckDuckGo native keyboard
  editing, custom engines and phone/dark/RTL/e-ink layouts exercised.
- Android 15 emulator, WebView 124: Bing query editing, iframe selection,
  confirmation, native download and persisted cover after app restart passed.
  DuckDuckGo input editing and selection passed; two proxy downloads timed out.
  Custom engine add/persist/launch/remove passed.
- Google presented a network challenge on Android; iOS was not built or run.
- Full unit suite is run by the pre-push hook and CI.

Fixes #6653
Reported by lifesucksdude101 on GitHub

Co-authored-by: Claude Code <noreply@anthropic.com>
2026-11-03 15:07:39 +01:00
Huang Xin
263d76cb14
feat(android): choose the system dictionary lookup app (#4937) (#7272)
* feat(android): choose the system dictionary lookup app (#4937)

Add System Dictionary > Lookup App on Android. It lists every app that
handles ACTION_PROCESS_TEXT, browsers left out, plus "Ask Every Time".
The chosen app gets every lookup directly. Before, a remembered app
counted only when a browser was among the handlers and two or more
dictionaries remained, so on ROMs where a search app registers the
intent but doesn't answer the https browser probe (Baidu on HyperOS),
lookups always fell through to the system chooser.

The picker replaces the System Lookup App reset row from #4568. That
row could never appear: get_lookup_dictionary and
clear_lookup_dictionary had no Rust commands, so Tauri forwarded them
as getLookupDictionary and the plugin answered "No command
getLookupDictionary found" (seen on 0.12.16). The new get_lookup_apps
and set_lookup_app commands are wired through commands.rs, mobile.rs,
desktop.rs and lib.rs.

Test that fails without the change: LookupDispatchTest
noBrowserPresent_chosenApp_launchesChosenDirectly failed with
"expected:<DispatchExplicit(handler=LookupHandler(packageName=org.goldendict.android,
...))> but was:<LookupDispatch$DispatchImplicit>"; 9/9 pass with it.

Verified on origin/main ab8025cb4 plus this change:
- pnpm test --run: 14961 passed, 16 skipped.
- pnpm lint, pnpm format:check: passed (one existing info finding in
  nativePageTurn.ts).
- pnpm fmt:check, cargo fmt -p tauri-plugin-native-bridge --check,
  pnpm clippy:check, pnpm test:rust (203 passed), lookup_models tests
  (4 passed): passed. Run before rebasing onto ab8025cb4, which changes
  no Rust.
- Gradle :tauri-plugin-native-bridge:testFossGenericPenDebugUnitTest
  LookupDispatchTest: 9 passed.
- Release APK on a Xiaomi 13, HyperOS 3 / Android 16. Before (0.12.16):
  a lookup opened the system chooser with Eudic, Read aloud, Baidu
  Search and Baidu Translate. After: the picker listed those four;
  choosing Eudic in Settings sent "hobbit" straight to Eudic's popup,
  the choice survived a force-stop and relaunch, and "Ask Every Time"
  brought the system chooser back. Checked the row in dark mode, e-ink
  and RTL.

Not run: lookups were triggered by calling the plugin's
show_lookup_popover over CDP, not by selecting a word with System
Dictionary switched on, to avoid changing a synced setting on the test
device. Not tried on a vivo device or with the light theme. HyperOS asks
"Allow Readest to open Eudic?" on the first direct launch; that prompt
is the OS's.

Fuzzy matching for imported dictionaries, also asked for in #4937, is
not part of this change.

Reported by Zephyros-X on GitHub.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(dictionary): label the unset lookup app Default and revert a failed save

Address CodeRabbit's review on #7272:
- "Ask Every Time" promised more than it did. Without a browser, Android's
  own chooser offers "Always", and with a browser Readest's chooser
  remembers the pick. The option now reads "Default", which reuses the
  existing translated key. Forcing a chooser on every lookup would undo
  #4559's remember-the-pick behaviour, so that is left to the maintainer.
- setLookupApp now resolves whether the native save happened, and the
  picker puts the previous selection back when it didn't.

Tests that fail without the change: "puts the picker back when the choice
cannot be saved", plus the setLookupApp result tests ("expected undefined
to be true / false"), and the options list ("expected [ 'Ask Every Time',
... ] to deeply equal [ 'Default', ... ]").

Verified: pnpm test --run 14963 passed, 16 skipped; pnpm lint and
pnpm format:check passed. Release APK on the Xiaomi 13 (HyperOS 3):
the picker shows Default, Eudic, Read aloud, Baidu Search and Baidu
Translate. Picking Eudic sent "riddle" straight to Eudic, and Default
brought back the system chooser. The failed-save revert is covered by
the unit test only, since the bridge doesn't fail on the device.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 20:20:05 +01:00
Huang Xin
74e770e0c4
feat(ios): add fullscreen system dictionary setting (#7269)
* feat(ios): add fullscreen system dictionary setting

Add System Dictionary > Fullscreen on native iOS, retaining the compact
default. Persist the preference, preserve edits during asynchronous
dictionary hydration, and forward the option through the mobile bridge.
Use an opaque UIKit container so fullscreen definitions remain readable
under the app's light and dark appearances.

Regression evidence: the pending-load store tests failed before the
hydration fix with "expected false to be true" and "expected true to be
false". Both now pass, alongside save/reload and iOS-only dispatch tests. The
loading-guard UI test also failed with "expected false to be true" before
disabling the switch until hydration completes.

Verified on origin/main ee1a95503 plus this change:
- pnpm test --run: 14933 passed, 16 skipped.
- pnpm lint and pnpm format:check: passed; lint reports one existing
  informational finding in nativePageTurn.ts.
- pnpm fmt:check, pnpm clippy:check and pnpm test:rust: passed;
  203 Rust tests passed, with warnings from existing dependencies/macros.
- cargo fmt -p tauri-plugin-native-bridge --check and lookup_models
  integration tests: passed (2 tests).
- pnpm build: passed.
- iOS release build and real iPadOS 27 reader lookup verified before the
  final main update and startup guard: compact/fullscreen, light/dark,
  rotation, persistence
  for both switch values after relaunch, and settings in RTL/e-ink mode.
- Native dictionary close action: isolated iPad simulator test passed.

Not exercised on a physical iPhone or older iOS. Physical XCTest automation
was blocked by device authorization timeouts; native close was tested in
an isolated simulator. Web/browser and other native platform end-to-end
suites were not run locally for this iOS presentation change.

Closes #7101.
Reported by arssher on GitHub.

Co-Authored-By: Claude Code <noreply@anthropic.com>

* fix(ios): keep dictionary fullscreen disabled after failed loading

Return an explicit success result from dictionary hydration and enable the
fullscreen preference only after successful loading. Preserve the replica
hydration callback's existing void return contract.

The regression cases use the real dictionary loader and save implementation.
Before this fix, both service-initialization and file-check failures allowed
a click to replace persisted dictionary metadata with an empty list:
"expected [] to deeply equal [ { id: 'saved-dictionary', ... } ]".
Both cases now preserve the saved dictionary and preferences.

Verification:
- pnpm test --run: 14935 passed, 16 skipped across 1232 files.
- Focused dictionary and replica tests: 103 passed across four files.
- pnpm lint: passed, with one existing informational Biome finding.
- pnpm format:check and git diff --check: passed.
- pnpm build: passed.

This follow-up changes TypeScript only. Native device verification and Rust
checks are recorded on the original feature commit and PR; they were not
repeated for this failed-load guard.

Reported by arssher on GitHub (#7101).

Co-Authored-By: Claude Code <noreply@anthropic.com>

---------

Co-authored-by: Claude Code <noreply@anthropic.com>
2026-11-02 18:40:56 +01:00
Huang Xin
4f9395859c
fix(security): remediate Dependabot dependency alerts (#7248)
* fix(security): upgrade direct ZIP readers to 9.0.5

Upgrade the app, native narration reader and Windows thumbnail provider;
adapt fallible filenames and optional data offsets. Update both app
lockfiles and the thumbnail lock while preserving unrelated pins.

Verified: 201 app Rust tests, 24 native TTS tests, 6 thumbnail tests under
Wine (1 existing ignored), strict app clippy, formatting and locked CEF
Linux dependency graph. Thumbnail strict clippy reproduces 3 existing
lints on the original source; it passes with those CLI lint allowances.
CEF compilation and native Windows device testing were not run.

This is a dependency/API migration covered by existing archive tests;
no new application behavior is intended. The Windows updater retains
ZIP 4 because its patched release requires an incompatible Tauri family.

Co-Authored-By: Claude Code <noreply@anthropic.com>

* fix(security): update vulnerable JavaScript dependencies

Raise patched dependency floors, scope the modern minimatch upgrade to
v10 consumers, and patch deepmerge prototype writes in both merge loops.
Upgrade the SVG renderer and keep its font shaper external so Node can
load its WASM asset when generating PNGs.

Regression tests fail before the fixes: deepmerge inherits attacker
properties; minimatch expands 256 patterns instead of 64 and performs
500500 comparisons instead of zero. The unpatched image upgrade fails
with a dynamic require of fs / missing hb.wasm. All 31 new tests pass
with the fixes, including actual translation and PDF vendor consumers.

Verified: full unit suite 14714 passed/16 skipped; final focused tests
31 passed; lint, formatting, frozen install, web build and Tauri frontend
build passed. Final web build was repeated after the renderer patch.
Nix hashes still need CI regeneration; CEF compilation was not run.
Version-based audits still flag patched deepmerge and legacy minimatch
3/5, which lack this advisory's vulnerable optimizer.

Co-Authored-By: Claude Code <noreply@anthropic.com>

* build(nix): request fresh security dependency hashes

Invalidate the pnpm and Cargo fixed-output hashes so the PR dependency
check computes the updated stores instead of substituting old cached
stores. Replace both values with the CI-reported hashes before merge.

Verified the diff changes only the two affected hash fields; local Nix
is unavailable. CI verification is pending on this commit.

Co-Authored-By: Claude Code <noreply@anthropic.com>

* build(nix): pin regenerated security dependency hashes

Use the pnpm and Cargo hashes calculated by the PR dependency check
(run 41428540045). Both fetchers completed and reported their actual
fixed-output hashes. Replace the temporary empty values.

Verified against the CI log's pnpm-deps and vendor-staging got values;
git diff --check passes. The final hash-check rerun is pending.

Co-Authored-By: Claude Code <noreply@anthropic.com>

---------

Co-authored-by: Claude Code <noreply@anthropic.com>
2026-11-02 11:50:57 +01:00
Huang Xin
08c1627611
fix(ios): capture readable shared pages when loading stalls (#7241)
* fix(ios): capture readable shared pages when loading stalls

Try capturing the parsed, nonempty DOM before the clipping deadline when
WKWebView has not delivered didFinish. Keep the hard deadline active while
JavaScript evaluation is pending, and preserve normal post-load settling.

Verified: 14,657 unit tests passed (16 skipped); pnpm lint, fmt:check,
clippy:check, and 201 Rust unit tests passed. Five capture-script regression
tests pass. Before the change, the unfinished-document and empty-SPA tests
failed with HTML returned where null was expected.

Linux WebKit captured the reported article and final URL with its Disqus
iframe deliberately stalled. Both reported URLs loaded naturally here.
Native Swift compilation and iOS app verification were not run because
Xcode and the iOS simulator are unavailable; macOS-hosted verification is
pending.

Reported by emceesenior-code on GitHub

Co-Authored-By: Claude Code <noreply@anthropic.com>

* fix(ios): wait for rendered text before clipping

WKWebView can finish navigation before a client-rendered page inserts its
article. A fixed settle delay could capture only navigation text and send
the converter into login-wall recovery.

Poll automatic capture readiness within the existing load budget, using
the converter's 400-character text floor. At 27 seconds allow short parsed
pages so real login walls retain their recovery path. Keep the 30-second
deadline active during evaluation and leave manual capture immediate.

Verified on the published PR head c9ec7d79 plus this change:
- The navigation-only SPA and whitespace-padding regression tests failed
  before the Swift change (HTML returned instead of null); all 8 now pass.
- Full unit suite: 14,660 passed, 16 skipped across 1,221 passing files.
- pnpm lint, pnpm fmt:check and pnpm clippy:check passed.
- pnpm test:rust: 203 passed, 0 failed.
- Native simulator build/package passed. On iPhone 17 / iOS 27.0, an
  8-second delayed article and a public shared conversation imported via
  the share extension and retained their final content in the reader.
- Ordinary, stalled-frame/redirect, short-login, blank and unfinished-main
  captures behaved as expected; manual Capture and Cancel passed.

Not tested on a physical device or other iOS versions. The text floor is
an initial-readiness heuristic, not a guarantee of semantic completeness.

Related to #6867. Reported by emceesenior-code on GitHub.

Co-Authored-By: Claude Code <noreply@anthropic.com>

* fix(ios): keep capture retries active until timeout

A blank readiness result at 27 seconds stopped polling when no navigation
settle callback remained. Content rendered at 28 seconds was then missed
and the operation timed out at 30 seconds.

Continue half-second readiness checks after 27 seconds, retaining the
relaxed text floor and the existing completion and hard-timeout guards.

The new regression compiles the actual capture method with a deterministic
clock and WebView boundary on macOS. Before the change it returned timeout
for the 28-second article and made only one blank-page probe. Afterward
it captures the late article and stops blank-page polling at the deadline.
All 9 capture tests pass. Full unit suite: 14,661 passed, 16 skipped.
pnpm lint, pnpm fmt:check, pnpm clippy:check and 203 Rust tests also pass.
The scheduler regression is skipped on non-macOS hosts.

Native build/package passed. In the installed iPhone 17 / iOS 27.0 app,
a stalled iframe with article text inserted at 28 seconds timed out before
the fix and captured the complete article afterward. A blank page still
returned the existing hard-timeout error. The actual share-extension import
also passed and retained all 12 article paragraphs in the reader.

Related to #6867. Reported by emceesenior-code on GitHub.

Co-Authored-By: Claude Code <noreply@anthropic.com>

* test: remove iOS capture harnesses (owner: useless testing)

Remove the extracted-source capture tests and their Swift scheduler fixture at the user’s request. Verification and local verification hooks were skipped as explicitly requested for this test-only deletion.

Co-Authored-By: Claude Code <noreply@anthropic.com>

---------

Co-authored-by: Claude Code <noreply@anthropic.com>
2026-11-02 10:39:12 +01:00
Huang Xin
477381c8ac
fix(tts): play local AAC narration natively on Linux (#7240)
* fix(tts): play local AAC narration natively on Linux

Decode AAC-LC/ALAC MP4 narration with Symphonia 0.6.1 and send PCM to
CPAL, with SoundTouch preserving pitch when playback speed changes.
Read stored EPUB entries as byte windows and DEFLATE entries through a
bounded in-memory checkpoint index, without extracting audio to cache.
Reuse the native narration clock and controls; retain browser playback
for remote audio and local MP3/Ogg/Opus/WebM sources.

Cover source integrity, exact seeks and MP4 edit timing, bounded output,
audible playback position, ordered controls and cancellation of pending
loads. Run the native plugin and lifecycle regressions in PR CI.

Regression evidence: without the Linux source-descriptor change,
"hands Linux the raw compressed ZIP entry without reading its audio
bytes" fails because getMediaSource returns null instead of the path
and raw ZIP entry. Transport and device-stream lifecycle regressions
were also verified to fail before their corresponding fixes.

Verified on current origin/main: full Vitest suite (14687 passed,
16 skipped), lint, format check, web build, Rust formatting and CEF
Clippy with warnings denied. CEF unit tests: 201 app + 24 plugin tests
passed; 3 transport/device-stream lifecycle regressions passed.
Nix cargoDeps realization and actionlint passed. Full Nix app build
and mobile device tests not run.

Linux CEF runtime with Symphonia 0.6.1: captured audible AAC, verified
forward/backward seeks, rate, pause/frozen clock, abort, and compressed
EPUB playback through all three paragraph highlights to completion.
No reporter EPUB was supplied; used generated narration fixtures.
One earlier app run exited SIGBUS during a shared-target rebuild;
cause unconfirmed, fresh launch after checks passed the sequence.

Reported by DeathStroke19891 on GitHub. Fixes #7084.

Co-Authored-By: Claude Code <noreply@anthropic.com>

* fix(tts): enqueue Linux controls before async dispatch

Tauri schedules async command invocations independently, so pause/resume
could reach the Linux worker in reverse order even when blocking reply
waiters were kept separate. Dispatch Linux playout_control directly from
the synchronous plugin handler, then resolve its worker reply off-thread.
Retain the same IPC payload, ACL parsing, asset scope and non-Linux paths.
This also allows abort to cancel a pending load without waiting for its
reply, which a frontend promise chain would delay.

Regression evidence: reverse the first polls of the old command futures
and the ordering assertion fails with ["resume", "pause"] instead of
["pause", "resume"]. The updated production-handler regression asserts
pause/resume/load/abort enqueue before any response future is polled,
then runs response tasks and blocking waiters in reverse order.

Verified Rust formatting, CEF Clippy with warnings denied, 201 app and
24 plugin unit tests, 3 lifecycle regressions, and a rebuilt CEF app.
Runtime: 40 rapid pause/resume cycles preserved final state, pause froze
the clock, and abort canceled a 226 MB compressed recording load in
about 19 ms. Invalid payload and out-of-scope path rejections passed.
Independent review verified ACL handling and non-Linux routing.
Frontend checks are rerun by the repository's pre-push hook.

Co-Authored-By: Claude Code <noreply@anthropic.com>

* refactor(tts): hide narration platforms (owner: remove the linux flag)

Move native source selection and backend capabilities into
NativeNarrationPlayer. MediaOverlayClient retains one native flag and
uses streaming, queueing, and cancellation capabilities without OS checks.
Preserve local ZIP playback, browser fallbacks, and mobile staging.

Validation: 93 focused tests passed; full Vitest suite passed 1,220 files
and 14,691 tests (4 files and 16 tests skipped). TypeScript, Biome lint,
format checking, and git diff --check passed. Lint reports one existing
informational diagnostic in nativePageTurn.ts. New loadSource tests fail
before delegation exists and pass afterward. In an isolated Linux CEF
app, compressed AAC playback advanced through all three paragraph
highlights using the native clock. Mobile device checks were not run.

Co-Authored-By: Claude Code <noreply@anthropic.com>

* fix(tts): finish canceled narration loads without errors

A native load can be canceled independently of the speak signal. Suppress
load failures when either signal was aborted, retaining the original
playback signal across invalidation so Rust cancellation errors are also
recognized. Other load failures still yield playback errors.

Validation: eight regression cases fail without this guard, yielding an
error instead of completing the generator. All 95 focused native/client/
player tests pass with the fix, including genuine load failures. TypeScript,
Biome lint and formatting, and git diff --check pass. In isolated Linux CEF,
stopping a large compressed recording during loading closes the player,
leaves native playback stopped, and logs no playback error. Mobile device
checks were not run. The pre-push hook runs the full frontend suite.

Co-Authored-By: Claude Code <noreply@anthropic.com>

---------

Co-authored-by: Claude Code <noreply@anthropic.com>
2026-11-02 08:54:20 +01:00
Kel
f815ae6416
fix(android): continue recorded narration while screen locked (#7194)
* fix(android): recover missed narration end events

When Android reaches the end of recorded narration while the WebView is suspended, its native ended event may not reach JavaScript. Treat the native no-current-item position as the same terminal event and deduplicate a delayed native callback so the controller can advance.

Regression test: recovers an ended event missed while the WebView was suspended failed on upstream main with expected one call, received zero; it now passes.

Checks: 78 focused narration tests passed; pnpm lint passed (one existing informational diagnostic); full suite reached 14,438 passed and 43 skipped, with one unrelated tts-paragraph-boundary Windows timeout that also repeats alone. The four initial PDF failures were corrected by restoring the worktree vendor assets and all four reruns passed.

Reported by kelvinalfaro on GitHub in #7193.

* fix(android): queue next narration file while locked

* test(tts): preserve desktop media overlay capabilities

* fix(android): rework the locked-screen narration handover

The queued handover lost what it was meant to keep. The plugin's new load
fields never reached JS (the Rust PlayoutControlResponse carries only
`session`), so after a handover every block ended after one poll. On wake
the next section sought back to 0 s and replayed audio heard under lock,
and stanzas of the old file still behind were sought inside the new one.

- The playlist follows rules that depend only on the order of loads and
  queues: `load` jumps to a file already in the playlist and drops the ones
  before it, `queue` keeps only the file it follows. JS mirrors them without
  any new response fields, and a rollover racing a load cannot split them.
- When JS runs again, `NativeNarrationPlayer.sync()` reads where the player
  got to: clips of a file it played past are skipped, the next section joins
  the rolled-over file where it is, and a lost rollover or end of file is
  found from the position.
- An `ended` that lands while no clip wait is listening still ends the
  block: this was the "playing" in silence, with Pause and Play doing
  nothing, after unlock.
- Only while a section's last file plays is the next one queued, and never
  for multi-track audiobooks or on iOS. A queueing failure no longer drops
  the next section's opening preload. Staged copies are kept only while in
  the playlist.

Verified on the Android emulator (API 35) with a six-poem narrated EPUB,
freezing the WebView renderer (kill -STOP) to model the suspended WebView:
- main: audio stopped at the end of poem 1; after the thaw stanzas 2-3 were
  replayed, then it stuck "playing" in silence, and Pause/Play did not resume.
- this change, frozen 60 s: ExoPlayer rolled into poem 2; after the thaw
  poem 2 was passed over and poem 3 played. Frozen 10 s / awake 1 s for
  90 s: one unbroken audio track through all six poems. Screen on: one
  continuous track, the highlight following; pause/resume and previous
  sentence across a boundary work.
Not verified on a physical device or on iOS.

Tests: media-overlay-android-handover.test.ts. Without each part of the
change its tests fail on assertions: no rollover handling ("expected
[ 'load poem2.mp3' ] to deeply equal []", "expected [ 'seek poem2.mp3 6s' ]
to deeply equal []"), no end-of-file position read ("expected 'stuck' to
deeply equal [ { code: 'end' } ]"), no ended check in the clip wait (same),
no guard on a late rollover event ("expected [ { code: 'end' } ] to be
'stuck'"). The two ended tests fail the same way on main.

Reported by kelvinalfaro on GitHub (#7193).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(android): keep offering the next narration file until it is queued

The next section's file was offered to the client once per section, when the
cached opening was built. In a section recorded across several files that
offer comes while an earlier file plays, so it was declined and never made
again: with the WebView suspended, narration stopped at the section's end.

- The loaded next section is kept with the cached opening and offered on
  every preload; an offer for a file already queued does no work.
- A section's own next file is queued too, while the one before it plays,
  so a boundary inside a section crosses without JS as well.

Verified on the Android emulator with a narrated EPUB whose third stanza of
each poem is its own file, freezing the WebView renderer:
- 73590cbd0: frozen after the poem's last file started, it stopped at that
  file's end (poem 2 never queued); frozen inside the first file, it stopped
  at that file's end.
- this change: the first case rolled on into poem 2, then after the thaw
  skipped the stanzas heard and rolled into poem 3; the second rolled into
  the third-stanza file.

Tests: "offers the next section to the client on every preload, loading it
once" fails without the change with "expected preloadSection to be called 2
times, but got 1 times"; "an offer repeated on every preload queues the file
once" with "expected 4 to be 2"; "queues the section's own next file while
an earlier one plays" with "expected [ 'load poem1.mp3' ] to include
'queue poem1-c.mp3'".

Raised by CodeRabbit's review of 73590cbd0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(android): queue the next narrated section, and drop a queue that went stale

- The file offered for queueing was the adjacent section's, so a section
  with no recording between two narrated ones (an interlude, a page the
  narrator skips) left nothing queued, though playback steps over it. The
  next narrated section is now found the way the section change finds it.
  The text opening still comes from the adjacent section.
- A queue whose file was still resolving when another file loaded could
  land after the new file and play the old section's audio. The player now
  checks, with nothing awaited before the command, that the file the queued
  one follows is still the one playing.

Verified on the Android emulator with a narrated EPUB that puts an
unnarrated interlude page after each poem, freezing the WebView renderer
8 s into poem 1:
- 9ed692479: poem 1 ended and the playlist ended with it; silent until
  the thaw.
- this change: poem 1 rolled on into poem 2 across the interlude; after the
  thaw, poem 2's stanzas were passed over and poem 3 played.
The split-file book from 9ed692479 behaves as before. The stale-queue race
is covered by the unit test only.

Tests: "offers the next narrated section, stepping over one without a
recording" fails without the change with "expected preloadSection to be
called once, but got 0 times"; "a queue still resolving when another file
loads is dropped" with "expected [ 'queue poem2.mp3' ] to deeply equal []".

Raised by CodeRabbit's review of 9ed692479.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(tts): reconcile Android narration ends and late rollovers by position

Two follow-ups from CodeRabbit's review of b18827d30, both about matching
JS to where ExoPlayer really is after the WebView slept.

- When both the loaded file and the queued one finished under lock and
  every event was lost, the position read said only index -1, so JS still
  thought the first file was current and replayed the queued one. The
  plugin now keeps the item the playlist ended on and reports it as
  endedIndex once nothing is current; sync() rolls to it.
- A late item-ended event named an index that a later queue had reused:
  after a position read found A -> B and C was queued, A's event (index 0)
  rolled JS on to C and ended B's stanza while B was still playing. The
  event now only prompts a position read, which rolls only when the
  player really moved.

Verified:
- "after a lock longer than the queued file, with every event lost" fails
  without the endedIndex change (expected 'stuck' not to be 'stuck').
- "a late rollover event from before the next queue does not end the file
  playing" fails without the event change (expected [{ code: 'end' }] to
  be 'stuck'). Both pass with it; src/__tests__/services/tts 920 passed.
- pnpm lint, format:check, fmt:check, clippy:check, test:rust (201 passed).
- Android emulator (API 35, x86_64 debug APK), split-narration book:
  screen on, one ExoPlayer track across four sections with the highlight
  following; renderer frozen 50 s and 12 s, narration continued into the
  next section on thaw with nothing replayed. The lost-event cases can't
  be produced there (SIGSTOP queues events, it doesn't drop them), so
  they are covered by the unit tests only.

Reported by kelvinalfaro on GitHub (#7193).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(tts): drop narration end signals that belong to a replaced file

Follow-ups from CodeRabbit's review of ce477e976. Since an end of file can
now be found by polling, the `ended` event and a slow position read can both
arrive after JS has moved on and loaded the next file, and each ended that
new file's wait at once.

- An `ended` event now only ends playback when a position read confirms the
  player is still at an end (both plugins clear the current item before
  they send it, iOS included).
- A position read that overlapped a load is dropped: the player counts
  loads, and sync() ignores a reply when the count changed while it waited.

The third finding, a queue that lands after the playlist ended, needed no
change: the next run sees the player still on the old file and loads the
queued one, which the plugin jumps to. A test now covers that.

Verified:
- "a late ended event does not end the file loaded since" and "a position
  read taken before a load does not end the file loaded" fail without the
  change (expected [{ code: 'end' }] to be 'stuck'); they pass with it.
  "a file queued after the playlist ended is loaded, not waited on" passes
  before and after.
- src/__tests__/services/tts: 924 passed. pnpm lint, format:check.
- Android emulator (API 35, x86_64 debug APK), split-narration book: played
  to the end of the book with the screen on, and TTS stopped 0.2 s after
  ExoPlayer ended. Renderer frozen 12 s: continued into the next section
  on the thaw. iOS not run: its plugin clears the index before `ended`,
  read from NativeTTSPlugin.swift only.

Reported by kelvinalfaro on GitHub (#7193).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Kel <1563599+kelvinalfaro@users.noreply.github.com>
Co-authored-by: Huang Xin <chrox.huang@gmail.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 17:27:13 +08:00
Huang Xin
1166393eb9
fix(android): keep the page-turn cover below the keyboard, closes #7171 (#7191)
Some checks are pending
CodeQL Advanced / Analyze (actions) (push) Waiting to run
CodeQL Advanced / Analyze (javascript-typescript) (push) Waiting to run
CodeQL Advanced / Analyze (rust) (push) Waiting to run
Publish Docker image / build (linux/amd64, ubuntu-latest) (push) Waiting to run
Publish Docker image / build (linux/arm64, ubuntu-24.04-arm) (push) Waiting to run
Publish Docker image / merge (push) Blocked by required conditions
Build with Nix / tests (push) Waiting to run
PR checks / test_web_app (2) (push) Waiting to run
PR checks / nix_flake_check (push) Waiting to run
PR checks / rust_lint (push) Waiting to run
PR checks / koplugin_rust_lint (push) Waiting to run
PR checks / build_web_app (push) Waiting to run
PR checks / test_web_app (1) (push) Waiting to run
PR checks / test_extensions (push) Waiting to run
PR checks / build_tauri_app (push) Waiting to run
Scorecard supply-chain security / Scorecard analysis (push) Waiting to run
Deploy to vercel on merge / build_and_deploy (push) Waiting to run
With Curl or Page Flip on, keys on the on-screen keyboard did nothing while
the in-book settings were open. The native page cover is a not-focusable
PopupWindow, which Android stacks above the input method. Because the cover
belongs to a different app than the keyboard, InputDispatcher dropped every
key touch that passed through it ("Dropping untrusted touch event due to
com.bilingify.readest ... PopupWindow").

Both native cover popups (the paper-turn surface and the turn-time page
cover) now use INPUT_METHOD_NEEDED, which orders them below the IME, and
SOFT_INPUT_ADJUST_NOTHING so the keyboard never moves them.

Verified:
- Test that fails without the change: NativePaperTurnTest
  keepsTheNativeCoverBelowTheKeyboard, on a Xiaomi 13 (Android 16). On the old
  code it fails with "Cover is Z-ordered below the keyboard expected:<131072>
  but was:<0>". With the fix it was not rerun on device (the run was stopped
  at the phone); the real-app check below covers it.
- Real app, Xiaomi 13, release APK of this commit (md5 checked on device),
  Sogou keyboard. Before: window stack PopupWindow above InputMethod, key taps
  ignored, the untrusted-touch log line above. After, with Page Flip and with
  Curl (fresh app start): InputMethod above the cover; typing in Default Font
  Size gave "1" then "16" and typing in Custom Content CSS gave "p" and
  Backspace cleared it; no untrusted-touch lines; forward and backward turns
  still animate in place at full size.
- pnpm test (14411 passed), pnpm lint, pnpm format:check, pnpm fmt:check,
  pnpm clippy:check, pnpm test:rust (203 passed).
- Not run: the turn-time page cover in NativeBridgePlugin has no test of its
  own; it gets the same two flags.

Reported by lambda3141 on GitHub.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 20:01:26 +01:00
Will McDonald
716aadae2e
fix(ios): keep the orientation lock when the scene is resizable (#7146)
Some checks are pending
CodeQL Advanced / Analyze (actions) (push) Waiting to run
CodeQL Advanced / Analyze (javascript-typescript) (push) Waiting to run
CodeQL Advanced / Analyze (rust) (push) Waiting to run
Publish Docker image / build (linux/amd64, ubuntu-latest) (push) Waiting to run
Publish Docker image / build (linux/arm64, ubuntu-24.04-arm) (push) Waiting to run
Publish Docker image / merge (push) Blocked by required conditions
Build with Nix / tests (push) Waiting to run
PR checks / nix_flake_check (push) Waiting to run
PR checks / rust_lint (push) Waiting to run
PR checks / koplugin_rust_lint (push) Waiting to run
PR checks / build_web_app (push) Waiting to run
PR checks / test_web_app (1) (push) Waiting to run
PR checks / test_web_app (2) (push) Waiting to run
PR checks / test_extensions (push) Waiting to run
PR checks / build_tauri_app (push) Waiting to run
Scorecard supply-chain security / Scorecard analysis (push) Waiting to run
Deploy to vercel on merge / build_and_deploy (push) Waiting to run
* fix(ios): keep the orientation lock when the scene is resizable

Readest doesn't require full screen, so on an iPad or on the iPhone Duo's
inner display iOS treats the scene as resizable. It then ignores the
supported-orientations mask and refuses requestGeometryUpdate ("The
current windowing mode does not allow for programmatic changes to
interface orientation"), so the reader's orientation lock did nothing.

On iOS 26+, also report prefersInterfaceOrientationLocked from the root
view controller. The lock engages once the scene is in a locked
orientation and holds it there; auto releases it.

* fix(ios): lock through the iOS 26 preference only when the geometry request fails

Release any earlier lock before requesting a new orientation, so it can't
block the request. Where the request works, landscape can still flip 180
degrees.

* ci: rerun checks
2026-10-30 19:29:21 +01:00
Sunny Modi
a8efa756d5
feat(tts): let custom TTS services set their audio format and voices (#7155)
* feat(tts): let custom TTS services set their audio format and voices

Custom TTS always requested `response_format: mp3` and, for a service
that can't list its voices, fell back to OpenAI's voice names. A
LiteLLM gateway in front of Gemini TTS fails on both: it only returns
WAV, and it rejects `alloy` ("No matching speaker voice found").

Each service now has:
- Format: MP3 (unchanged default), WAV, or Default (no format sent, so
  the service answers in its own).
- Voices: optional comma-separated names (e.g. "Kore, Puck") used
  instead of asking the service or falling back to OpenAI's names.

The iOS native player picked AVURLAsset's decoder from a hardcoded
.mp3 temp file name; it now names the file .wav when the audio has a
RIFF header. The editor's Test button plays WAV with the right type.

Verified:
- Fails without the change: with the provider and the customTTS
  adapter put back to main, "requests the configured audio format, or
  none for the service default" fails with `expected 'mp3' to be 'wav'`,
  "uses the voice names typed for a service instead of asking it" gets
  the OpenAI voices (`expected [ [ 's1:alloy', 'alloy' ], …(10) ] to
  deeply equal [ [ 's1:Kore', 'Kore' ], …(2) ]`), the cache scope test
  fails on the unchanged scope, and the adapter round-trip drops the
  new fields. All pass with the change.
- pnpm test (14284 passed), pnpm lint, pnpm format:check, pnpm fmt:check.
- Web (pnpm dev-web, self-hosted, Chrome) against a mock speech server
  that rejects mp3 and any voice but Gemini's: MP3 shows the 400; WAV
  and Default play the sample to the end; with no Voices the request
  uses `alloy` and gets the voice error, with "Kore, Puck" the editor
  reports 2 voices and the sample plays with Kore. Settings survive
  save and reopen. The new rows checked in light, dark, e-ink and RTL.
- Not run: clippy:check and test:rust (no Rust changed; CI rust_lint
  covers them); WAV playback on an iOS device.

Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>

* fix(tts): sync an explicit MP3 and cleared voices; no format for MiMo

Replica sync merges per field, and a field missing from an update
leaves the old value on other devices. Switching a service back to MP3
stored no format, and clearing Voices stored nothing, so other devices
kept WAV or the old names. MP3 is now stored as 'mp3' and a cleared
list as '', like a cleared API key. An explicit 'mp3' stays out of the
audio cache key, so MP3 caches are kept.

MiMo always answers in MP3, so its editor no longer shows Format.

Verified:
- Fail before the fix: "saves MP3 and cleared voices explicitly, so
  other devices change too" (updateService not called with
  responseFormat 'mp3', voices ''), "offers no format for MiMo, which
  always answers in MP3" (the Format select is rendered), and the cache
  scope test (explicit 'mp3' changed the scope). All pass after it.
- pnpm test (14286 passed), pnpm lint, pnpm format:check.
- Not run: real use of cross-device sync (needs two signed-in devices).

Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>

* fix(tts): unwrap a WAV a proxy wrapped in another WAV

LiteLLM wraps Gemini 3.8 TTS's whole WAV, C2PA provenance manifest
included, in a WAV of its own as if it were raw PCM. Players read the
inner header and the manifest as samples: a click before every sentence
and ~130 ms of static after it. Rebuild a plain WAV from the inner
fmt and data chunks; other audio passes through untouched.

Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>

* refactor(tts): play the inner WAV as the service sent it

The WAV a proxy wraps is the service's own, intact file; its C2PA chunk
sits after the audio, where players skip it. Hand that file back instead
of rebuilding one from its fmt and data chunks.

Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>

---------

Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>
2026-10-30 18:48:22 +01:00
Will McDonald
454ae3cbb8
feat(ios): book mode on iPhone Duo's inner display (#7137)
* fix(ios): build Swift packages with SwiftPM's native build system on Xcode 27.1

Swift 6.4 (Xcode 27.1) builds packages with the Swift Build backend by
default. It writes the library under out/Products/<Config>-<platform>
instead of <triple>/<config>, so the tauri crate failed to link with
"could not find native static library Tauri". In release it also makes
the plugins' @_cdecl entry points (init_plugin_*) local to the prelinked
object, so the app link failed with undefined init_plugin_* symbols. Pass
--build-system native, which keeps the old layout and exported symbols.

* feat(ios): book mode on iPhone Duo's inner display

On the inner display in landscape the hinge runs down the middle and each
half is about the size of the cover display. Show a book there as two
pages, one either side of the hinge, or as one page:

- A `duoBookMode` view setting (default on) gives exactly two columns, or a
  two-page spread for fixed layouts. Off, the page is one column at the
  reader's own width. A header button, the View menu's spread choice and a
  Layout panel row switch it; the button and row appear only on the Duo.
- `get_safe_area_insets` reports the hinge status and the `.division`
  reserved region. While the device is part way folded the spine gap (and
  the header/footer padding) widens to keep text out of the crease. A hinge
  interaction tells JS to refetch, because folding part way does not resize
  the web view. The hinge code compiles only against the iOS 27.1 SDK.
- The layout follows the pose as the device folds, unfolds or turns, and
  the spine-centred insets now also apply to fixed-layout spreads.

Every other pose and device keeps the reader's own settings: the resolver
returns them unchanged (parity tests cover the doc's viewports) and the
re-layout effect runs only on the Duo. Scrolled flow is left alone.

* feat(ios): show two pages whenever iPhone Duo is part way folded

Holding the inner display part way open in landscape is the book pose, so
show two pages there by default, whatever the book-mode toggle says. Flat,
the toggle still decides. A Layout panel row ("Two Pages When Partly
Folded") turns it off. Part way folded is the hinge status `partial` or an
active vertical folding region, so it doesn't depend on either alone.

* fix(ios): address review on iPhone Duo book mode

- Forward hinge updates within one status too (the folding region can
  change with the angle), at most every 250ms with a trailing update.
- Resolve the Duo layout after the book opens, so a pose that arrives
  while it opens is not lost before the re-layout effect has a renderer.
- Keep the effective spread when Separate Cover Page changes.

* test(reader): give the image-gallery viewer test a themeStore getState

FoliateViewer now resolves the iPhone Duo layout through
useThemeStore.getState(). The image-gallery test landed on main after
this branch was cut and still mocked useThemeStore as a bare hook, so
the rebased suite reported 2 unhandled rejections. Same mock as the
relocate and transform-listener tests.

Verified: the file reports 2 errors before and none after;
full pnpm test passes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(reader): keep the Duo page still while the toolbars show (owner: "since the header/footer toolbars are temporary it should never change the layout of the content")

Book mode sized its columns from the live safe-area insets. On iPhone
Duo the toolbar brings back the 84pt side status strip, so opening it in
inner landscape cut max-inline-size from 713px to 650px and re-paginated.
It now uses getReadingScreenInsets, the side insets the reading page
already keeps with the status bar hidden.

The Duo re-layout effect also ran on every safe-area refetch and hinge
update and re-applied margins and gap each time; foliate re-renders on
every such write, even with the same value. It is now keyed on the
resolved layout values, so it only writes when the layout changes.

Verified:
- useDuoPose.test.ts fails without the fix (maxInlineSize 650, expected
  713) and passes with it.
- iPhone Duo simulator (iOS 27.1), with a MutationObserver on the
  renderer: showing and hiding the toolbars in inner landscape writes no
  layout attributes and leaves text edges and location unchanged; open <->
  partial in inner portrait writes nothing; partial in landscape writes
  once for the crease gap.
- pnpm test and pnpm lint pass.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(reader): apply the insets current when a book finishes opening

openBook runs once from the mount effect and applied the margins after
its awaits through the first render's closure. On iPhone Duo the book
opens while the status bar still shows (an 82pt top strip in inner
portrait); the reader hides it before the open finishes, and the inset
effect skips while there is no renderer, so the page kept a 126px top
margin until something else re-applied the margins. It now calls the
latest applyMarginAndGap through a ref.

Verified:
- foliate-viewer-open-margins.test.tsx fails without the fix
  (expected '126px' to be '44px') and passes with it.
- iPhone Duo simulator (iOS 27.1): the book opens with margin-top 44px
  in inner portrait; before, the top band stayed until a toolbar toggle.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(reader): keep the Duo page and toolbars still while the toolbars toggle (owner: "since the header/footer toolbars are temporary it should never change the layout of the content")

On iPhone Duo the status strip comes and goes with the toolbars, and
its live inset lands a moment after each.

- The reading page kept only the side insets seen with the status bar
  hidden; in inner portrait the strip is an 82pt top inset, so the top
  margin went 44px <-> 126px on every toggle. The top is kept too.
- The toolbars followed the live insets, so they drew without the strip,
  then re-spaced when it arrived (and again while hiding). They now use
  the insets recorded while the status bar shows.
- Both records kept a single window size, so after a rotation the first
  toggle had no record. They are kept per window size.

Verified:
- insets.test.ts (portrait top kept), useSafeAreaInsets.test.tsx (shown
  insets recorded) and useDuoPose.test.ts (record kept per size: expected
  650 to be 713) fail without the change and pass with it.
- iPhone Duo simulator (iOS 27.1), MutationObserver on the renderer plus
  per-frame header/footer button positions: toggling the toolbars in
  inner landscape, inner portrait, part way folded and on the cover
  display writes no layout attribute, keeps the location, and the
  header/footer buttons do not move sideways once shown. Not fixed: the
  first toolbar show at a window size after launch, before any record
  exists, still re-spaces the toolbars once.
- pnpm test and pnpm lint pass.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(reader): lay the Duo book out the same flat and part way open (owner: "Why partially open and fully open has layout shift, please don't do that.")

Two pages reserved the crease gutter only while the folding region was
active, so folding part way widened the spine gap from the derived ~32px
to 72px and re-paginated, and unfolding did it again. UIKit reports the
region while flat too (inactive), so two pages now always keep the gap
clear of it; being part way folded still needs the region active.

Verified:
- duo.test.ts "lays the book out the same flat and part way folded"
  fails without the change (columnGapPx 0 flat vs 73 folded) and passes.
- iPhone Duo simulator (iOS 27.1): flat <-> part way open in inner
  landscape, three times, writes no renderer attribute; text edges stay at
  440/512px either side of the 455.5-495.5 region and the location holds.
- pnpm test and pnpm lint pass.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(reader): re-apply the Duo layout after every rotation

The Duo re-layout effect resolved the layout during render from the
window size and store snapshots, which React does not track: after a
rotation it sometimes committed the new values without running the
effect (its hook tag showed no HasEffect), so the page kept the other
orientation's column width until something unrelated, such as a toolbar
toggle, re-laid it out. The effect now resolves the layout when it runs,
keyed on the pose, fold, insets and settings, and writes only attributes
that change. It also waits 150ms for the window to settle: turning the
device passes through a 669x669 viewport for ~50ms, and a layout written
then (max-inline-size 576px) was an extra re-pagination, or stuck if no
later trigger came.

Verified on the iPhone Duo simulator (iOS 27.1), with a MutationObserver
on the renderer: four rotations each wrote one batch at the final size
(720px portrait, 713px landscape) and none at 669x669; before, a
rotation with the toolbars hidden wrote nothing and left 713px in
portrait. No unit test: the skipped effect depends on WebKit's
resize timing, which jsdom does not reproduce. pnpm test and pnpm lint
pass.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(ios): cancel the pending trailing hinge event before an immediate send

The trailing hinge update was a fire-and-forget asyncAfter guarded by a
flag. An immediate send cleared the flag but left the old callback
queued, so a second trailing update could be scheduled before the first
ran, sending duo-fold-changed closer than 250ms apart. The trailing
update is now a DispatchWorkItem that every send cancels, so at most one
is pending. Answers the CodeRabbit review on the hinge throttle.

Verified on the iPhone Duo simulator (iOS 27.1): flat <-> part way open
still reaches JS (fold status open / partial, region 455.5/40). No unit
test: the native bridge has no Swift test target; the JS side dedupes
fold and inset updates, and the Duo re-layout writes only changed
attributes, so extra events never re-laid out the page.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(reader): drop the Duo two-page settings rows (owner: "They should be the default and it's not necessary for the option.")

Two pages either side of the hinge is how the Duo's inner display shows
a book in landscape, so the Layout panel's "Two Pages When Unfolded" and
"Two Pages When Partly Folded" rows and the duoFoldedBookMode setting are
removed, with their strings. Part way open no longer forces two pages:
the page is laid out the same flat and part way open whichever the
reader chose. The header button still switches to one page and back.

This also settles the CodeRabbit finding on the View menu's Single Page
while part way folded: nothing forces two pages any more.

Verified:
- duo.test.ts "keeps the page the reader chose, flat or part way open"
  fails before the change (2 columns, expected 1) and passes after.
- iPhone Duo simulator (iOS 27.1): one page from the header writes one
  batch (1 column, 720px); part way open and back write nothing and keep
  the location; two pages again writes one batch (2 columns, 713px, gap
  72px). The web bundle has no "Two Pages When" string.
- pnpm test (1206 files) and pnpm lint pass.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(reader): match the Duo inset and fold notes to the code

docs/safe-area-insets.md and the comments still described the earlier
behaviour: only side insets kept, toolbars on the live insets, hinge
events only on a status change, a re-layout on every change, and the
removed duoFoldedBookMode. They now say the reading page keeps the top
and sides recorded with the status bar hidden (one record per window
size), the toolbars use the insets recorded with it shown, hinge updates
are throttled with one cancellable trailing update, and FoliateViewer
writes only changed attributes once the window settles. "Part way" in
the doc is "partly" (CodeRabbit).

Checked by reading each statement against the code it names.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Huang Xin <chrox.huang@gmail.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 01:31:12 +08:00
Huang Xin
145e3318d6
feat(reader): Page Flip page-turn style on Android, iOS and desktop (#7160)
* feat(reader): add Page Flip page-turn style on Android, iOS and desktop

Page Flip lifts the whole sheet over the spine instead of curling a
corner. It is a separate Animation Style next to Page Curl, offered in
the apps only; a spread and the web turn it as a Page Curl.

The sheet follows a physical profile model ported from page-turn-core
(MIT, notice kept in each port): PageFlipModel.kt, PageFlipModel.swift
and pageFlipModel.ts are line-for-line ports and share the same tests.
Android draws it in NativePaperView (GLES 3), iOS in NativePaperView
(Metal), and desktop in the captured-turn WebGL renderer, which asks
for WebGL 2 only for surfaces built for Page Flip. A released flip
settles on its own physics instead of a fixed easing.

On macOS a backward turn showed the previous page for a few frames
while it was captured. macOS now covers the webview with a snapshot
during that capture, as Android and iOS already do, which also fixes
the same flash for Page Curl on macOS.

Verified:
- pnpm test (1199 files pass), pnpm lint, pnpm fmt:check,
  pnpm clippy:check, pnpm test:rust, browser tests for the renderer.
- Tests that fail without the change:
  - page-flip-model.test.ts: without the unturn phase a tap's return
    jumps, "expected 0.13785… to be less than 0.12".
  - captured-turn.browser.test.ts "settles a chosen Page Flip on its
    own physics in both directions": without the settle it fails with
    "expected 0 to be greater than 4".
  - ControlPanelUpdateReset.test.tsx "offers Page Flip in the apps" and
    "shows a synced Page Flip as Page Curl on the web".
- Android: taps and drags in both directions on a phone, with an
  earlier build of this change.
- macOS: forward flip recorded at about 60 fps.

Not run:
- The macOS backward cover in the app (a system permission prompt
  blocked the run).
- Android after moving the flip choice to the turn host (rebuild
  pending).
- iOS on a simulator or device; the Metal shaders were compiled at
  runtime with makeLibrary(source:) only.
- Windows and Linux have no native cover, so a backward turn there
  still shows the previous page briefly, for both styles.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(ios): build Swift plugins with SwiftPM's native build system

Swift 6.4 (Xcode 27.1) builds packages with Swift Build by default. It
writes the static libraries to `Products/<Config>-<sdk>` instead of the
triple directory swift-rs links from, and prelinks each module so the
@_cdecl entry points (init_plugin_*, register_plugin, run_plugin_command)
are local symbols Rust cannot link.

An incremental iOS build therefore linked whatever plugin libraries an
older build had left in the triple directory: the app built and
installed, but ran old plugin Swift ("No command paper_curl found for
plugin native-bridge", so no native page turn worked). A clean build
failed with "could not find native static library `Tauri`", then with
undefined `_init_plugin_*` symbols once pointed at the new directory.
Passing `--build-system native` restores the layout and the exported
symbols.

Verified:
- With the plugin build caches cleared, `pnpm dev-ios` fails without
  the change ("could not find native static library `Tauri`") and
  builds and installs with it.
- On an iPhone XS Max (iOS 18.7) the new build turns a page with the
  native turn and logs no error, where the old build failed every turn.
- rustfmt --check on the changed file.

Not run: the simulator build, and a build with an older Xcode (not
checked which older SwiftPM versions accept `--build-system native`).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 12:57:43 +01:00
Huang Xin
c811741af8
feat(ios): turn pages with the native paper curl (#7046)
Some checks failed
PR checks / test_web_app (1) (push) Has been cancelled
CodeQL Advanced / Analyze (actions) (push) Has been cancelled
CodeQL Advanced / Analyze (javascript-typescript) (push) Has been cancelled
CodeQL Advanced / Analyze (rust) (push) Has been cancelled
PR checks / test_web_app (2) (push) Has been cancelled
Publish Docker image / build (linux/amd64, ubuntu-latest) (push) Has been cancelled
Publish Docker image / build (linux/arm64, ubuntu-24.04-arm) (push) Has been cancelled
Build with Nix / tests (push) Has been cancelled
PR checks / nix_flake_check (push) Has been cancelled
PR checks / rust_lint (push) Has been cancelled
PR checks / koplugin_rust_lint (push) Has been cancelled
PR checks / build_web_app (push) Has been cancelled
PR checks / test_extensions (push) Has been cancelled
PR checks / build_tauri_app (push) Has been cancelled
Scorecard supply-chain security / Scorecard analysis (push) Has been cancelled
Deploy to vercel on merge / build_and_deploy (push) Has been cancelled
Publish Docker image / merge (push) Has been cancelled
* fix(reader): give a reloaded page its own native paper owner

The native paper scene outlives a page reload (a WebContent crash or a
full navigation), but NativePageTurn numbered its readers from a module
counter that restarts at 0. A reloaded reader came back as owner 1, so
the native side kept the old page's generation and rejected every
capture with ready:false. Taps then did nothing until the app restarted.
Each page load now starts the counter at a random 30-bit value, which
stays within the Kotlin side's Int.

Found while bringing the native curl to iOS: after a page reload in the
iPhone 17 Pro simulator, a capture with owner 1 returned ready:false
while the same capture with a fresh owner returned the texture.

Verified:
- native-page-turn.test.ts 'gives a reader on a reloaded page a new
  native owner' fails without the change ("expected 1 to be 2") and
  passes with it.
- iOS simulator build with the change: two page reloads, each followed
  by a native curl to the next page.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(ios): turn pages with the native paper curl

#7001 gave Android a native paper curl; iOS kept the captured curl,
which snapshots each page as a 2x JPEG and turns spreads and PDFs less
cleanly. iOS now runs the same NativePageTurn commands against a Swift
twin of the Android renderer:

- NativePaperMesh.swift ports the 64-hinge mesh line for line.
- NativePaperTurn.swift keeps the Android command semantics (owners,
  generations, turn ids, at most three resident pages, aborts, the
  3 s request deadline). Pages come from WKWebView.takeSnapshot at full
  screen scale, regions snapped to device pixels. A Metal sheet sits
  above the web view, where takeSnapshot never sees it, and presents
  with the Core Animation transaction that shows or hides it. Rendering
  runs on the main thread, so a scene is ready when its command
  returns. A passive gesture recognizer tracks the finger; CADisplayLink
  settles a released sheet.
- Snapshots are redrawn as 8-bit BGRA before upload: MTKTextureLoader
  failed on WebKit's snapshot images with "Image decoding failed".
- paper_curl is routed to iOS in Rust, and useCapturedTurn uses the
  native controller and page buffer on iOS as on Android (one or two
  columns, fixed layouts included).

Verified:
- useCapturedTurn-scrollLock.test.ts: the recovery-path cases now run on
  iOS too. The three native iOS cases failed before the hook change
  ("expected invalidateNativePages to be called 1 times, but got 0").
- The Swift mesh, compiled with swiftc on macOS, matches the browser
  fixtures the Android JVM test uses (396 and 402 vertices). With the
  bend band changed from 0.7 to 0.69 it fails at component 0. The
  landed spread leaf mirrors its column in LTR and RTL.
- iPhone 17 Pro simulator (iOS 26.3) on a devtools sim build, driven
  over the WebKit inspector and recorded with simctl:
  - Alice EPUB: tap forward and back, next/next/prev queued, slow drag,
    flick and a drag pulled back (each lands on the expected page), and
    a forced two-column spread. Only paper_curl IPC, no
    capture_webview_region.
  - Naval PDF, paginated at 100%: forward (captured, navigated under
    the cover, captured again) and back (resident start).
  - The flat cover matches the live page: pre-motion frames differ by
    0.0-0.06 grey levels in light, Nord and dark Nord, with no step at
    the hand-off back to the live page.
- pnpm test (14124 passed), pnpm lint, format:check, clippy:check,
  fmt:check.

Not run: a physical iPhone or iPad; native finger tracking (simulated
touches never reach UIKit, so drags used the JS move path); RTL books;
CBZ. Once in the simulator, after an openurl import failure and a page
reload, every takeSnapshot stopped completing, including main's
capture_webview_region. A relaunch cleared it, and it didn't recur
across three reloads during turns. The 3 s deadline fails such a turn
instead of hanging it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(ios): drop the native paper scene when the page reloads

The native scene belongs to the plugin and outlives the page. If the
page reloaded during a turn (a WebContent crash mid-drag, which
WebViewLifecycleManager answers with a reload), the old page never sent
finish, cancel or dispose. The scene stayed active with its sheet over
the web view, and refused the reloaded reader's new owner, so the page
looked frozen and native turns stayed off until the app restarted.

WebViewLifecycleManager now reports a terminated WebContent process and
every committed main-frame navigation, and the plugin resets the native
scene on either. The page-curl doc also no longer says MTKTextureLoader
uploads the snapshots.

Verified on the iPhone 17 Pro simulator (iOS 26.3), Alice EPUB, with a
JS drag held mid-turn (start sent, no touchend):
- Before: after location.reload(), the half-turned sheet stayed over the
  page, every capture returned ready:false and next() did not turn.
- After: the reload clears the sheet and next() curls natively to the
  next page. Killing the WebContent process mid-turn does the same
  after the web view recovers.

There are no Swift unit tests in this plugin, so the simulator runs
before and after are the check.

Reported by coderabbitai on GitHub.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 08:54:45 +02:00
Sadikh Seyidzadeh
ca1a252664
fix(reader): add native Android paper curl and stabilize page turns (#7001)
* Fix paper curl rendering and backward page turns

* Add native Android paper curl and stabilize page turns

* Preserve active paper turns and scope capture failure recovery

* Clarify frame timing fraction in page curl documentation

* chore: point the foliate-js submodule back at readest/foliate-js

The pointer (6381a92) is the head of readest/foliate-js#139 and is
fetchable from readest/foliate-js through refs/pull/139/head.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Hide cancelled native paper scenes and document rendering lifecycle

* fix(android): clip native paper regions to the WebView

Chrome's CSS viewport can overhang the WebView: on a Pixel 7 the reader
is 412.19 x 915.05 CSS px, 1082 x 2402 px at 2.625, on a 1080 x 2400 px
WebView. PixelCopy clipped that request to the window and stretched the
rest over the 1082 x 2402 bitmap, so the native sheet and the page cover
drew about 2 px larger than the live page. The page appeared to shrink
when the live WebView took over before and after a curl.

The native page region, its capture and cover_webview_region now convert
CSS px through webViewRegion(), which clips to the WebView bounds.

Verified:
- NativePaperRegionTest fails on the unclipped arithmetic
  ("arrays first differed at element [2]; expected:<1080> but was:<1082>")
  and passes with the clip; all 24 native-bridge JVM tests pass.
- x86_64 debug APK on an API 35 emulator (Pixel 7 profile): in a screen
  recording, consecutive flat frames of the same page jumped by (2, 2) px
  29 times before the fix and 0 times after.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(android): turn two-column spreads with the native paper curl

Landscape (two-column) EPUB spreads fell back to the captured curl, which
captures at a 2x cap as JPEG and stretches the CSS viewport overhang into
the bitmap, so the sheet looked soft and shifted by two pixels. The native
scene now turns a spread too, modelled on the single-column path: the
inner column stays flat, the outer column turns as a leaf hinged at the
spine, and the leaf's back shows the facing page of the destination
spread. Backward turns replay the previous spread's forward turn in
reverse, as single-column does. The JS side passes the column count with
`start` and enables the native path and page buffer for up to two
columns on Android only.

Verified:
- NativePaperMeshTest: the spread mesh matches the browser mesh built by
  buildPageCurlMesh(..., 2), and a landed leaf mirrors its column (LTR and
  RTL). Both failed on the stub first ("expected:<2412> but was:<2376>").
- NativePaperTurnTest (API 35 emulator, 19/19): with the spread branch
  disabled the new spread test fails "Native frame at 4,320
  expected:<-65536> but was:<-13121737>"; it passes with it.
- native-page-turn.test.ts: 'tells the native scene how many columns the
  spread shows' failed first, passes now.
- Emulator, landscape Alice in Wonderland: tap/drag forward and back,
  cancel, all land on the expected page; logcat shows paper_curl only, no
  capture_webview_region. During a slow drag the inner column differs from
  the live page by a mean 0.64 grey levels (6.13 with the captured curl)
  at the same sharpness, so no blur and no 2 px shift.
- Not run: iOS (unchanged, still single-column only), a physical device.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(android): turn PDF and fixed-layout pages with the native paper curl

Fixed-layout books (PDF, CBZ, fixed EPUB) fell back to the captured curl,
which grabs the page as a 2x JPEG. They now use the native scene too:

- foliate-js: the fixed-layout renderer names its pages with
  getPageTurnKey(), including the side shown in a portrait spread.
- NativePageTurn no longer requires previewPage. A renderer without it
  captures the current page, navigates under the native cover, then
  captures the destination. Pages already resident (turning back) start
  at once.
- On Android the page buffer follows native eligibility, so PDF sheets
  cover only the renderer, as EPUB sheets do.
- The capture subscription now ignores a view-state write that changes no
  field. The bookmark ribbon rewrites its unchanged visibility on every
  relocation; that dropped the current sheet between capture and start of
  every cold turn, so each PDF turn failed with "Native page textures are
  not ready" and fell back to an unanimated jump. Found with CDP logpoints
  on the emulator.

Verified:
- fixed-layout-page-turn-key.browser.test.ts walks LTR/RTL books in
  portrait, landscape and single-page spreads; without the portrait-side
  prediction it fails "expected '2:left' to be '1:right'".
- native-page-turn.test.ts 'turns a renderer without page previews...'
  failed first ("JPEG path must not run"), passes now.
- useCapturedTurn-scrollLock.test.ts 'keeps native book textures when a
  view state is rewritten unchanged' failed first ("expected
  invalidateNativePages to not be called at all, but actually been called
  1 times"). The recovery-path cases for fixed curl and curl without
  preview now expect the native path.
- Related unit suites (633 tests) and lint pass. Fixed-layout browser
  files pass one by one; run together they hit "Cannot connect to the
  iframe", which main does the same.
- Android emulator (API 35), Alice PDF: portrait, landscape single page
  and landscape two-page spreads. Taps, slow drag, tap/swipe back and a
  cancelled drag all land on the right page with an animated curl; only
  paper_curl IPC, no capture_webview_region, no interrupted turns.
- Not run: a physical device, iOS (unchanged), CBZ.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(android): keep a cancelled native paper cover hidden when its scene arrives

The native scene is prepared on the GL thread. A cancel that reached the
main thread first hid the cover, and the late start callback then set
alpha back to 1 and resumed dragging, so the stale sheet covered the
live page until finish. The callback now leaves a cancelled scene
hidden and not dragging; animate settles it back and finish ends it.

Verified with NativePaperTurnTest
aCancelBeforeTheSceneIsReadyKeepsTheCoverHidden on the API 35 emulator:
without the fix it fails "A cancelled scene must not restore its cover
expected:<0.0> but was:<1.0>"; with it all 20 NativePaperTurnTest cases
and the plugin JVM tests pass. Raised by CodeRabbit on PR 7001.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(android): keep the resident native page when its replacement upload turns stale

Uploading a page that was already resident reused its texture id. If the
request turned stale after texImage2D, the upload deleted that id and
dropped the key, while JS, which only reads the bank on success, still
counted the page as resident; the next scene failed with "Native page
textures are not ready". The replacement now goes into a new texture;
a stale one deletes only itself, and a valid one replaces the old.

Verified with NativePaperTurnTest aStaleReplacementUploadKeepsTheResidentPage
on the API 35 emulator: without the fix it fails "The resident page stays
in the bank"; with it all 21 NativePaperTurnTest cases and the plugin JVM
tests pass. Not run: the app on a device with this change. Raised by
CodeRabbit on PR 7001.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(page-curl): describe native curl for spreads and fixed layouts

The doc still limited the Android native path to single-column reflowable
books. It now covers two-column spreads, fixed layouts without previews,
capture clipping to the WebView and unchanged reader-state writes, and
lists the fixed-layout page-key browser test. Docs only; checked against
the code in useCapturedTurn.ts, nativePageTurn.ts and NativePaperTurn.kt.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* chore(foliate-js): point at the merged readest/foliate-js#139

foliate-js#139 was squash-merged as 4b6b9f8. Its tree is identical to the
PR head 2610185 this branch tested, so no code changes; the submodule
now resolves from readest/foliate-js main.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Huang Xin <chrox.huang@gmail.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 06:12:38 +02:00
Kel
5da26ee82a
Import pasted text into the library (#6992)
* feat(library): import pasted text from Add menu

Add a titled text editor with a user-initiated clipboard read and manual paste fallback. Import the generated TXT through the existing library path and retain the draft on failure.

Baseline: the Add-menu regression failed on unchanged upstream because From Pasted Text was absent; the failed-import regression failed before the draft-retention fix. Verified: 15 focused tests, lint/type checking, changed-file Biome, diff check, production web build, and Chromium desktop/narrow/e-ink import checks. Full suite: 13,980 passed, 16 skipped, 2 failures in unchanged tts-paragraph-boundary.test.ts.

Reported by sojudu on GitHub. Fixes #6747.

* fix(library): rework the pasted-text dialog to the design system (#6747)

The dialog now opens with a one-line description (DESIGN.md 2.9), puts
Paste beside the Text label as a flat action, keeps the error above the
action row, and uses ghost Cancel + btn-contrast Import like Import Web
Novel. The book title is optional: a blank title falls back to the
text's first line (shown as the placeholder), so 40 pasted articles
don't all import as "Pasted Text". "From Pasted Text" moves below
"From Directory" so the local entries stay together.

Title-to-filename handling moves to createTextBookFile in utils/txt so
the iOS share path can use it too. "Briefing: today" becomes
"Briefing - today" instead of "Briefing- today".

Verified: text-book-file.test.ts and the new placeholder/first-line
dialog tests fail without the change (createTextBookFile is not a
function; placeholder expected 'Morning briefing'); all pass with it.
On the iOS 26.3 simulator (debug build): Add menu -> From Pasted Text,
Paste (iOS paste prompt) filled the text, the title placeholder showed
the first line, Import added the book. Checked light and dark mode;
e-ink mode was not checked on iOS.

Reported by emceesenior-code on GitHub.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(ios): accept shared text in the share sheet (#6747)

Readest didn't appear in the iOS share sheet for text (an AI reply, a
selection): the extension only activated for web URLs and pages. It
can't use NSExtensionActivationSupportsText, because a .txt shared from
Files is public.plain-text too and that hung the share sheet. On the
iOS 26.3 simulator a Files .txt carries public.plain-text AND
public.file-url, while shared text carries public.plain-text alone, so
the rule is now a predicate that accepts web URLs (not file URLs),
Safari pages (the JS preprocessing plist) and plain text that is not a
file.

The extension previews the text (first line as title), writes it to
App Group SharedClips/ as .txt and queues a textFile save. The host
reads it with the existing read_share_clip_html command and imports it
as a TXT book through the shared ingest path, keeping the picked
group. Text counts as a URL only when it is nothing but one.

The htmlFile ingress test now gives convertToEpubWithWorker a book; it
returned undefined before, so the hook fell back to clip_url and the
"not called" check passed only by microtask timing.

Verified on the iOS 26.3 simulator (debug build): a Safari selection
shows Readest in the share sheet (it didn't before), Save opens
Readest and adds the text book; a Safari page share still captures the
DOM (htmlFile queued) and imports; a Files .txt share shows a single
Readest entry that goes through the document import and opens the
book. The new ingress test fails without the hook change (ingestFile
called 0 times) and the activation-rule tests fail on the old
project.yml.

Requested by sojudu on GitHub.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* chore(i18n): translate pasted and shared text strings

Extracted with i18n:extract; all 34 locales filled, none left untranslated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(library): keep the pasted-text draft through a slow paste or dismiss

From the CodeRabbit review on #6992:
- A clipboard read that resolves after the user typed, or after the dialog
  was reopened, no longer replaces the newer draft.
- Escape, the backdrop and swipe-to-dismiss do nothing while an import is
  running, so its completion can't close a reopened dialog.

Verified: import-pasted-text-dialog.test.tsx. Without the fix, "keeps text
typed while the clipboard read was pending" fails (textarea value is the
clipboard text) and "cannot be dismissed while an import is running" fails
(onClose called once).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Kel <1563599+kelvinalfaro@users.noreply.github.com>
Co-authored-by: Huang Xin <chrox.huang@gmail.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 18:13:47 +02:00
Huang Xin
27694ba28b
fix(ios): play stored narration audio in place from the book file (#7019)
Part of #6989. Follow-up to #7004 (web/desktop) and #7010 (Android).

iOS still read a stored audio entry into a Blob and wrote it to the app
cache before AVPlayer could play it. With a book whose narration is one
921 MB track, that copied the whole track through the WebView before the
first word, and again on every chapter.

AVPlayer now reads the entry's byte window of the book file directly. The
playout "load" action carries the window and its MIME type, as on Android,
and the item plays through an AVURLAsset with a private scheme whose
AVAssetResourceLoaderDelegate answers reads from bytes [start, end) of the
file. A window the player can't open still falls back to a staged copy.

The loopback media proxy was not used: it binds its socket once per process
and never rebinds, and iOS can reclaim a suspended app's listening socket,
which is when narration sits paused on the lock screen.

Verified:
- media-overlay-native.test.ts "plays a stored audio entry from its window
  of the book file without copying it" fails without the change with
  `expected "vi.fn()" to not be called at all, but actually been called 1
  times` (loadBlob copied the entry), and passes with it.
- iOS simulator (iPhone 17 Pro, iOS 26.3), 921 MB single-track book:
  first audio 5.4 s after Read Aloud (13.6 s on main), 0.27 s after the
  native load; chapter 2, 8 h into the track, 5.5 s (18.1 s on main).
  WebContent stayed near 540 MB (peaked at 1.26 GB on main), and no
  mo-narration file was written. Pause and resume, backgrounded playback
  across a chapter seek, and a pause of 60 s in the background all work.
- iPad simulator (desktop user agent): plays the window, no staged copy.
- pnpm test, pnpm lint, format:check, fmt:check, clippy:check, test:rust.

Reported by DeathStroke19891 on GitHub.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 13:04:55 +02:00
Huang Xin
8eceead103
fix(android): play stored narration audio in place from the book file (#7010)
* fix(android): play stored narration audio in place from the book file

On Android, Media Overlay narration from a stored audio entry read the
whole entry into the WebView, then wrote it to a cache file for ExoPlayer.
For one large shared track that never finished: on the emulator with the
921 MB test book, Read Aloud failed with "Failed to fetch" after 56 s and
played nothing.

ExoPlayer now reads the entry's byte window of the EPUB directly through
a small FileWindowDataSource, using the { path, start, end } that
BookDoc.getMediaSource() returns. The window goes through the native-tts
playout "load" action as optional start/end. iOS keeps staging a copy,
since AVPlayer can't take a byte window; a book ExoPlayer can't open (a
content:// path) falls back to the copy too. NativeNarrationPlayer now
records a path only after the native load succeeds, so that fallback
doesn't reuse the failed path.

Verification:
- media-overlay-android-native.test.ts "plays a stored audio entry from its
  window of the book file without copying it" fails without the change:
  expected "vi.fn()" to not be called at all, but actually been called
  1 times (loadBlob copied the entry). It passes with it.
- "stages the entry when the player cannot open the book file" failed with
  loadPath recording the path before the load (writeFile called 0 times),
  and passes after reordering.
- FileWindowDataSourceTest (3 JVM tests) passes; seeking to dataSpec.position
  instead of start + position fails all 3.
- Android emulator (API 35, debug x86_64 APK), raw CDP:
  - 921 MB book: first audio 3.6 s after Read Aloud (0.6 s after speak),
    no staged copy, app PSS +41 MB. The installed 0.12.16 build failed
    after 56 s with no audio.
  - Chapter 2, 8 h into the track: first audio 1.9 s at 8:00:15.
  - Pause holds the position; resume continues.
  - 5 MB book: first audio 3.4 s.
- Related vitest suites, pnpm lint, format:check, clippy:check pass.
- Not run: pnpm test:rust (this host lacks the GTK link libraries); iOS
  (unchanged path, covered by a unit test only); an external content://
  book on a device.

Part of #6989. Reported by DeathStroke19891 on GitHub.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(android): keep the book file out of the narration staging cache

Two review findings on the in-place narration path:

- After a window load, NativeNarrationPlayer recorded the book path under
  the audio href. A later load() of that href then reused it as the staged
  copy and played the whole EPUB. #stageBlob now reuses a path only when
  the player staged it.
- After ExoPlayer failed on an item, playoutLoadedPath still matched, so
  loading the same file again only seeked the failed player. onPlayerError
  now clears it, and the next load prepares afresh.

Verification:
- native-narration-player.test.ts "stages a copy of an entry it last played
  from the book file" fails without the fix: expected "vi.fn()" to be
  called once, but got 0 times (writeFile). It passes with it.
- Android emulator (API 35, debug APK), loading a non-audio window of the
  EPUB twice: 1 "Native narration playback failed" log before the fix,
  2 after. The 921 MB book still plays in place: first audio 1.9 s, no
  staged copy.
- TTS vitest suites (179), pnpm lint and format:check pass.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 10:24:14 +02:00
k6G52m4Dz75W
e563bbb1c4
chore(android): bump tauri-plugin-webview-upgrade for light e-ink dialogs (#6799)
Bumps the tauri-plugin-webview-upgrade submodule to c861233, which adds
an App Startup initializer (tauri-plugin-webview-upgrade#4) pinning
MODE_NIGHT_NO at process attach on e-ink devices: the outdated-WebView
alert - and every other appcompat dialog in the process - stays light
regardless of the system dark mode. Device detection mirrors the
eink_identity.rs whitelist (tightened in #6833).

The initializer logic was verified on a Hanvon Clear7 (Android 14,
WebView 109): with it present, the outdated-WebView alert renders light
in both system appearances, where it previously flipped dark with system
night mode on.
2026-10-15 15:22:14 +02:00
Huang Xin
2813ad7e6a
fix: iOS reader polish for drawing dock, short sheets, bookshelf header and read aloud (#6778)
* fix(reader): fill the drawing dock's bottom safe area with its own background

The dock was lifted above the home indicator by the bottom inset, leaving a
transparent gap where the reader footer showed through. It now sits at the
bottom edge and pads the inset with its own background.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(library): title the bookshelf editor with the selected shelf on phones

On phones the selected shelf's name becomes the page title beside the back
button and the tabs, icons only, get a centered row of their own, so the
built-in shelves and the add button fit on one line. Wrapped rows are now
centered on the screen rather than within the slot beside the back button.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(tts): keep a hidden mini player hidden through brief stalls between paragraphs

The buffering probe catches the short wait while the next paragraph loads,
which re-showed the card and re-armed its linger, and the end of buffering
showed it again. A hidden card now comes back only when a stall lasts 500ms,
and the end of buffering just restarts the countdown.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(ui): only full-height sheets clear the status bar and show a back button

A content-height sheet such as a confirmation, or a sheet snapped short of
the screen, rests at the bottom: it no longer pads its drag handle for the
status bar or shows the back button.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(tts): stop the word highlight stepping back at a sentence start on iOS

chunk-start fires as the item is handed to AVPlayer, which can take a few
hundred ms to open it. The media clock ran ahead from the event and lit the
second word, then the next poll pulled it back to the first. The clock now
holds until a poll sees the item playing, and the position reports playing
from timeControlStatus rather than the rate, which is set while loading.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(tts): preload the next chapter's opening for Edge TTS and custom voices

Only windowed engines carried preloads past a chapter end, so with Edge TTS
or a custom service a chapter change started with nothing synthesized. A new
preloadsAudio capability marks engines whose preloads keep the audio; they
now fill their usual handful of paragraphs from the next chapter too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs: run selected unit test files with pnpm test --run

pnpm test -- <files> forwards the separator and runs more than the files
asked for.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* chore(agent): update agent memories

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(tts): keep the iOS word clock from stepping back on pause or running ahead on resume

Pausing froze the clock at the last poll, up to 250ms behind where it had
got, so the highlight could step back a word. Resuming restarted it before
AVPlayer was rendering again. Pause now freezes the extrapolated position,
and resume polls and lets the player report when it is playing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(tts): preload the next chunk's opening at the end of a chunk

A section over 512 KB of HTML is read in chunks, and the live document ends
at each chunk's end. The cross-boundary preload took that for the chapter's
end and preloaded the next section, so moving to the next chunk found nothing
synthesized. It now starts a throwaway reader at the next chunk's anchor in a
fresh copy of the section, and only goes on to the next section after the
last chunk.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(ui): drag a content-height sheet up instead of setting its height

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(tts): use the contrast button for play/pause in the full player

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(tts): preload the next section in the language it is read in, and more

- A section file with only xml:lang is rendered with the book's language as
  its lang, which is what the live read speaks it in. The fresh copy used to
  preload the next section kept xml:lang (zh-CN vs zh), so its audio was
  cached under keys playback never looked up and each new section started
  with a wait. The fresh copy now takes the book's language the same way.
- E-ink drops the tinted sentence under the word highlight in word mode.
- The lyric sheet follows the document read, not only the section index, so
  a section read in chunks no longer shows the first chunk's lines under the
  next chunk's position.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(tts): resize the full player on desktop and size the lyric text

- A corner grip resizes the full Read Aloud player with the pointer on
  desktop, up to the whole window, and the size is kept for the next time
  it opens. Once sized, the lyric sheet takes the height it is given.
- A−/A+ in the lyric view step the line size from 12 to 38px, kept per
  device.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(tts): keep the lyric size and player size working when storage is blocked

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 00:25:00 +02:00
esmaeelE
7893fa9167
Support handwriting annotation (#6674)
Some checks are pending
CodeQL Advanced / Analyze (actions) (push) Waiting to run
CodeQL Advanced / Analyze (javascript-typescript) (push) Waiting to run
CodeQL Advanced / Analyze (rust) (push) Waiting to run
Publish Docker image / build (linux/arm64, ubuntu-24.04-arm) (push) Waiting to run
Publish Docker image / build (linux/amd64, ubuntu-latest) (push) Waiting to run
Publish Docker image / merge (push) Blocked by required conditions
Build with Nix / tests (push) Waiting to run
PR checks / test_extensions (push) Waiting to run
PR checks / test_web_app (2) (push) Waiting to run
PR checks / nix_flake_check (push) Waiting to run
PR checks / rust_lint (push) Waiting to run
PR checks / koplugin_rust_lint (push) Waiting to run
PR checks / build_web_app (push) Waiting to run
PR checks / test_web_app (1) (push) Waiting to run
PR checks / build_tauri_app (push) Waiting to run
Scorecard supply-chain security / Scorecard analysis (push) Waiting to run
Deploy to vercel on merge / build_and_deploy (push) Waiting to run
* Add handwriting annotations with optional BOOX pen support (#3673)

- services/handwriting: platform-neutral ink model (normalized,
  page-relative coords, versioned schema), coordinate transform,
  canvas renderer, editor with undo/redo/erase, capability detection,
  and BookConfig persistence (device-local, excluded from cloud sync
  like the existing paired-audiobook field). 44 unit tests.
- Generic pointer-event backend works everywhere (web/desktop/iOS/
  non-BOOX Android); BOOX raw-drawing is an additive fast path chosen
  automatically via detectPenCapabilities().
- Native bridge: query_pen_capabilities/start_raw_drawing/
  stop_raw_drawing/set_raw_drawing_enabled commands added to
  tauri-plugin-native-bridge (Rust: commands/mobile/desktop/lib/
  build.rs + permissions).
- BOOX Pen SDK isolated behind a new Gradle 'pen' flavor dimension
  (genericPen default / booxPen opt-in) so default/FOSS builds never
  add BOOX's Maven repo or dependency; rationale and build docs in
  android/README-pen.md. PenInputController interface keeps every
  Onyx SDK type out of NativeBridgePlugin.kt.
- Reader UI: HandwritingOverlay/Canvas/Toolbar + useHandwriting hook,
  mounted in BooksGrid next to FoliateViewer. PDF pages are keyed
  precisely by page index; EPUB ink is anchored per-section (documented
  limitation: reflow has no fixed page).

Verified: tsc --noEmit clean, biome clean, full handwriting test
suite green (44/44).

NOT verified (no Android SDK/NDK or BOOX hardware in this
environment): android/src/booxPen/** has not been compiled — see
android/README-pen.md for what to check before shipping the booxPen
flavor. The Rust plugin changes have not been built with cargo/tauri
CLI (not installed here) but follow the existing refresh_eink_screen
command's pattern exactly across every layer they touch.

* add handwritten

* chore(android): update icons and add Android build docs

- Regenerate app icons with pnpm tauri icon
- Simplify ic_launcher.xml via tauri android init
- Add ANDROID_BUILD.md with build instructions

* docs(android): document build fixes for Android APK build

- Java 21 requirement (Gradle 8.14.3 fails on Java 25)
- AGP downgraded from 8.11.0 to 8.7.3
- Aliyun Maven mirror for offline Google repo access
- buildToolsVersion 35.0.0 pinning
- compileSdk warning suppression

* test(browser): update annotation popup screenshots for added handwriting tool

* chore: drop Android icon regeneration and local build doc from PR

* fix(test): restore upstream ExportMarkdownDialog test and add getConfig mock

* refactor(handwriting): rework ink anchoring, persistence and BOOX pen path

Ink placement:
- Key fixed-layout ink by section index instead of the location counter,
  which collided for adjacent PDF pages.
- Anchor reflowable ink to the page-start CFI and reuse any stored anchor
  inside the visible range, so ink no longer repeats on every page of a
  chapter.
- Normalize fixed-layout ink to the page frame, so it follows zoom and pan.
- Disable handwriting in scrolled mode.

Persistence:
- Clearing the last inked page now sticks (the store merges partials).
- Imports update the store before the live editor reloads.
- Save on committed edits only, debounced to disk; simplify strokes on
  commit instead of on export.
- Ink written by a newer schema is never overwritten.

UI:
- Enter via View menu > Handwriting Mode; drop the always-visible floating
  button and the selection-popup tool.
- Single toolbar below the safe-area inset; no color swatches on B&W e-ink.
- The Notebook falls back to Notes when the Handwriting tab has nothing to
  show; rows are labelled by chapter and sorted in reading order.
- JSON export works for books that only have ink.
- Drop the restyle feature.

BOOX:
- Run the pen SDK on the WebView with density scaling, close the previous
  session on restart, and deliver each stroke on pen-up with normalized
  pressure.
- Only use raw drawing when an EMR pen digitizer is present, so pen-less
  readers keep finger drawing.
- Make the opt-in booxPen flavor build: repository in the app module,
  support-library exclusion, libc++ pickFirst, no stripping of prebuilt SDK
  libraries, and R8 rules.
- Remove the unused set_raw_drawing_enabled command.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(handwriting): tap ink to edit it; show every anchor on a reflowed page

- A single tap on existing ink enters handwriting mode instead of turning
  the page. Single clicks now carry their main-window position so overlays
  can hit-test them.
- A reflowed page shows the ink of every anchor in its visible range, not
  just one, so a smaller font no longer hides ink drawn on the next page.
  Eraser, Clear Page and Undo cover all of them as one step; new strokes
  go to the page's primary anchor.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(handwriting): pin reflowable ink to the content it marks

Ink in reflowable books was stored in page coordinates, so any font,
spacing or margin change left it over the wrong text. Each stroke is now
bound to content and re-placed from the current layout:

- Ink over text or images binds to the range of words and elements it
  covers (underlines bind to the line above) and is stored normalized to
  that range's box. Re-fitting to the new box keeps its shape and topology
  through font size, font family, line height and margin changes.
- Margin ink binds to the nearest character and scales uniformly; strokes
  written in one burst share an anchor so a note stays in one piece.
- Reflowable ink is keyed per section; the notebook labels rows by the
  chapter of the inked text and jumps straight to it.
- Fixed-layout ink stays normalized to the page, which already tracks
  zoom and pan.

This replaces the page-start anchors and the multi-anchor workaround.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(handwriting): drawings as annotations; shape-aware morphing

Each drawing is now an `ink` booknote: listed with the other annotations
in the left sidebar (pen icon and the text it marks), navigable and
deletable there. A reflowable book gets one note per anchor, a fixed-layout
book one per page. Ink notes travel by file sync; Readest Cloud has no field
for stroke data yet, so they are kept out of its push. The notebook's
Handwriting tab and the separate handwriting import/export are removed; a
notebook canvas is left for a follow-up.

Pinned ink now morphs by its shape:
- flow (underline, strike-through): follows its words, split per line on a
  re-wrap; marks are resampled so they stay continuous.
- box (circle, box, scribble): fitted to the content it encloses, so an
  edge brushing the next line no longer widens it to the whole line.
- span (bar or bracket beside a paragraph): stretched along its lines,
  kept at its distance from the text edge.
- rigid (margin notes): moves and scales with the nearest character.
Boxes are measured within one column, so a range wrapping onto the next
page can no longer blow a drawing up across two pages.

Ink also shows in scrolled mode (read-only) for every loaded section or
page, and follows a PDF pinch live instead of jumping when it commits.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(handwriting): redesign drawing mode; one annotation per session

- Drawing starts from a pen button in the reader header (the View menu
  item is gone; tapping existing ink still opens it for editing).
- While drawing, the reader's header and footer give way to the mode's own
  bars: a top bar (Drawing, Done) and a bottom dock with the pen (color and
  size in a popover), eraser, undo, redo and page turning. Nothing can cover
  Done any more.
- Strokes still save as they are drawn, but everything drawn in one visit
  to drawing mode is one annotation in the sidebar, instead of one per
  stroke. Each stroke keeps its own text anchor (or page in fixed layout).
- A short underline that encloses nothing binds to the word it marks,
  rather than to whichever character happened to be nearest.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(handwriting): draw in scrolled mode

Scrolled views show several sections (or PDF pages) at once, so drawing
was limited to paginated mode. Each finished stroke and eraser sweep is now
routed to the section or page it is drawn over, pinned with that section's
text anchoring (or normalized to that PDF page), while the live stroke
draws over the per-section ink layers. Undo follows the page last drawn
on, and the dock's arrows scroll a screen at a time.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(handwriting): stronger strokes and room for the drawing bars

Pen widths are heavier (default 0.006 of the page width) and a finger
stroke no longer carries pressure: touch reports contact size, not
pressure, which thinned every finger stroke. Ordinary pen pressure now
draws the full pen width, so existing strokes render stronger too.

Drawing mode lives in the reader view state, and the viewer reserves
the top bar and dock bands in its margins (paged) and scroll padding
(scrolled) while it is on, the way the TTS mini player does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(handwriting): draw committed strokes as smoothly as live ones

A stroke was simplified on commit to within a pixel and then drawn as a
polyline, so small loops turned angular and pressure changed in steps
once the pen lifted. Keep points to a fifth of a pixel and wherever the
pressure changes, and draw strokes as quadratic curves through the
samples. Also add the drawingEnabled view state to two test fixtures.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(handwriting): fill pen strokes as one antialiased outline

A pen stroke was stroked as many short pieces of different widths. Each
piece antialiased its own edge with round caps, so at every joint the soft
edges blended twice and the width stepped, which read as a jagged edge
next to native ink. Trace the stroke's outline around samples every 1.5px,
with the width interpolated along the curve, and fill it once. A single
contour has no inner edges for the rasterizer to blend, and points where
the inner side of a tight turn would fold back are skipped so no hole
opens there.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(handwriting): start every drawing session with the pen

The eraser toggle outlived the drawing session, so turning drawing back on
after erasing left the eraser active and the first strokes wiped ink
instead of drawing, which looked like strokes were not being recorded.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(handwriting): keep a Pencil stroke drawn right after a tap

iOS WebKit read a quick tap followed by a drag as its own double-tap or
text-selection gesture and withheld that touch from the page entirely, so
the stroke never reached the canvas. touch-action: none only stops panning
and zooming. The drawing surface now cancels the default of its touch
events, which leaves the touch sequence to the page while pointer events
still arrive, and is unselectable with no callout.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(handwriting): draw from the instant annotation tools, save from the dock

Draw moves from its own header button into the header's instant
annotation tools. The top drawing bar is gone: its Done becomes a save
icon as the dock's last button, and only the dock's band is reserved
below the text.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(handwriting): add a marker tool beside the pen

A marker draws a broad translucent band of even width with flat ends, for
highlighting what is under it. It is stroked as one path, so it does not
darken where it crosses itself, while separate marks still mix where they
cross. It ignores pressure, keeps its own highlighter colors and widths,
and the eraser sizes itself to one marker band instead of three. The dock
shows pen, marker and eraser side by side; tapping the active tool opens
its options. Marker ink is stored with tool: 'marker'; pen ink is
unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(handwriting): match the pen and marker buttons to the rest of the dock

The tool buttons used a different icon set and a wider pill with a color
dot and caret. They now use the dock's line icons in the same square
button, with the active tool's ink color as a thin band under its icon.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(sidebar): lead each annotation with an icon for its kind

Bookmarks, highlights, notes and drawings each start with a small round
badge, so the kind of an item reads at a glance. The badge carries the
kind's name for screen readers and replaces the inline pencil drawings
used to show.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(handwriting): save a drawing and keep drawing; close from the dock

Save now finishes the current drawing as one annotation and stays in
drawing mode, so the next strokes start a new annotation, with a short
toast when there was ink to save. A Close button at the end of the dock
leaves drawing mode. Strokes are still saved as they are drawn, so
neither discards anything.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(sync): sync handwriting strokes through Readest Cloud

Adds an ink jsonb column to book_notes (migration 026, folded into the
base schema) and carries ink notes through the notes sync instead of
leaving them to file sync only.

- The sync transform maps strokes to and from the column. Other notes
  never send the key, so an upsert does not clear stored strokes, and a
  pulled row without strokes carries no key, so merging it cannot wipe
  strokes held locally.
- Drawings are pushed when they change and never get an xpointer, which
  keeps every KOReader plugin version from importing one as a highlight.
- Committed points are rounded to 1/10000 of the page (pressure to
  1/100), which more than halves what each drawing stores and syncs.

The column has to exist before a server running this code receives a
drawing, so apply the migration to the database first.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Readest Agent <agent@readest.local>
Co-authored-by: Huang Xin <chrox.huang@gmail.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 21:31:38 +02:00
Huang Xin
4c3ccfe85d
chore(android): link WebView APK downloads in the outdated-WebView dialog (#6649)
Some checks failed
Build with Nix / tests (push) Has been cancelled
PR checks / nix_flake_check (push) Has been cancelled
Deploy to vercel on merge / build_and_deploy (push) Has been cancelled
CodeQL Advanced / Analyze (actions) (push) Has been cancelled
CodeQL Advanced / Analyze (javascript-typescript) (push) Has been cancelled
CodeQL Advanced / Analyze (rust) (push) Has been cancelled
Publish Docker image / build (linux/amd64, ubuntu-latest) (push) Has been cancelled
Publish Docker image / build (linux/arm64, ubuntu-24.04-arm) (push) Has been cancelled
PR checks / rust_lint (push) Has been cancelled
PR checks / koplugin_rust_lint (push) Has been cancelled
PR checks / build_web_app (push) Has been cancelled
PR checks / test_web_app (1) (push) Has been cancelled
PR checks / test_web_app (2) (push) Has been cancelled
PR checks / test_extensions (push) Has been cancelled
PR checks / build_tauri_app (push) Has been cancelled
Scorecard supply-chain security / Scorecard analysis (push) Has been cancelled
Publish Docker image / merge (push) Has been cancelled
Bump tauri-plugin-webview-upgrade to c7f9774 (readest/tauri-plugin-webview-upgrade#3).
The dialog shown on devices whose WebView is too old now ends with "You can
download the WebView APK from APKMirror or Uptodown.", with both names as
hyperlinks to monolithic WebView builds the plugin can load. Translated into
all 14 bundled locales.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 08:46:04 +02:00
Huang Xin
d1a7a0435b
fix(widget): keep E-ink reading widget text legible in dark mode (#6628)
* fix(widget): keep E-ink reading widget text legible in dark mode

E-ink mode forced pure black text and a black progress fill on the
reading widget, but the card background follows the system appearance,
so with the phone in dark mode the widget showed black text on a dark
card.

The E-ink ink is now a theme-attribute color (colorForeground: black on
the light card, white on the night card) used by both the text and the
progress fill. On Android 12+ the launcher resolves it when applying the
RemoteViews, so a dark-mode switch repaints correctly without a widget
update; older versions resolve it in the app process at update time.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(widget): assert the E-ink progress fill contrasts with the card

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 18:09:00 +02:00
k6G52m4Dz75W
747dfd5021
feat(android): automatic e-ink full refresh every N page turns (#6525)
* feat(android): auto e-ink full refresh every N pages

Readers without spare buttons can't reach the manual "Refresh Page"
page-turner action, so ghosting has no on-demand clear. Add an
opt-in `einkAutoRefreshInterval` view setting that fires a deep full
refresh every N page turns in e-ink mode, resetting when a manual
refresh is triggered.

Co-Authored-By: Claude <noreply@anthropic.com>

* i18n(android): translate e-ink auto-refresh strings, tag settings row

Follow-up to the every-N-pages auto full refresh:

- Add the new "Auto Refresh" / "Every 5/10/15/20 pages" labels to all
  34 non-en locales, mirroring how "Refresh Page" shipped its strings.
- Give the Auto Refresh row a data-setting-id so it matches its sibling
  page-turner rows.
- Document that the auto path has no Android gate on purpose: a synced
  per-book config can carry a non-zero interval off Android, where the
  bridge rejects and the refresh is swallowed as a soft no-op.

* refactor(android): move e-ink auto-refresh to Device settings, rename to Auto Full Refresh

The every-N-pages full refresh is a display behavior, not a keybinding, so it
belongs under Control > Device next to E-Ink Mode rather than in Page Turner.
Shown only on Android and disabled while E-Ink Mode is off, matching the manual
Refresh Page gating and sibling rows. Relabels the setting "Auto Full Refresh"
and updates the key across all 34 locales.

* fix(android): skip e-ink auto-refresh on no-op boundary turns, register in command palette

Pressing next/prev at the book's end/start doesn't move, so it must not count
toward the refresh interval — otherwise hammering at the boundary flashes the
panel without any page actually changing. Guard on renderer.atEnd/atStart.
Also add the missing command-palette entry for settings.control.autoFullRefresh,
matching its Device-group siblings, and document that native swipe (committed by
the paginator, not routed through viewPagination) is intentionally not counted.

* feat(android): gate Auto Full Refresh on a real full-refresh capability probe

The "Auto Full Refresh" row appeared on every Android e-ink toggle, but a
deep refresh only works where a known vendor hook (Onyx / NTX / Rockchip) is
present. Showing it on a panel we cannot drive — or a phone — misleads users
into expecting flashes that never come.

Expose EinkRefreshController.isSupported() as the is_eink_refresh_supported
bridge command. It reuses the same per-vendor reflection the refresh path
already runs, but only resolves the method/enum handles (never invokes them),
so the probe is pure class-level reflection that never touches the panel. The
UI memoizes it once per session and only renders the row when a mechanism is
actually detected.

* fix(android): hide the manual Refresh Page slot without a full-refresh hook

Mirror the Auto Full Refresh capability gate on the bindable "Refresh Page"
page-turner action. Previously the slot appeared whenever the per-book e-ink
render toggle was on, so on a normal Android phone it could be bound yet the
press was a silent no-op (no vendor hook to drive). Gate it on the same
is_eink_refresh_supported probe so the action only surfaces where it visibly
flashes the panel.

* fix(android): grant the e-ink refresh capability command its ACL permission

The is_eink_refresh_supported command was wired end-to-end but not added to
the plugin's default.toml. The app grants only native-bridge:default, so the
new command was denied by Tauri's ACL at runtime; because the probe is
memoized with a catch-to-false, the Auto Full Refresh row and the manual
Refresh Page slot would have silently never appeared on any device,
including real e-ink hardware. Add allow-is-eink-refresh-supported next to
its refresh-eink-screen sibling.

Also harden the probe against the same silent-hide failure mode:
- only cache a successful probe; a transient rejection now clears the memo so
  a later call can retry instead of latching the options hidden.
- drop the never-populated `error` field from the capability response.
- soften the isSupported() KDoc to a best-effort hook-presence signal.

* refactor(android): share the e-ink refresh probe and self-correct auto-refresh

Extract a useEinkRefreshSupported() hook so the 'Auto Full Refresh' row and the
'Refresh Page' slot read one memoized probe instead of two duplicate effects.

Drop the renderer.atEnd/atStart boundary skip from the auto-refresh counter:
those flags are section-page based, so on fixed-layout / one-page-per-section
books they read true on nearly every real turn and would starve the counter.

Add a runtime self-correction: skip refreshes once the probe settles false, and
downgrade the flag when the native side reports a refresh actually failed, so a
stubbed or hidden-API gated hook stops issuing doomed requests.

Correct the coverage comment to name only the turn gestures that route through
the counter.

* fix(android): stop treating a transient refresh miss as permanent

The auto-refresh loop latched the device as unsupported after a single
{ success:false } refresh, but that same signal also comes back for momentary
conditions on a fully supported device (detached window, zero-sized view, one-off
vendor exception). One miss silently disabled auto-refresh and hid the user's
chosen option for the whole session.

Remove the runtime downgrade entirely: the loop now skips only when the startup
capability probe authoritatively settled false (the synced-config path onto a
non-e-ink device), and refresh outcomes no longer change that flag. This also
eliminates the race where a settled downgrade was resurrected by the in-flight
probe fulfilling afterward.

* fix(android): make the e-ink capability probe retryable on inconclusive reads

The capability command always resolved { supported:false }, even when the probe
couldn't really decide, so the JS retry path documented in bridge.ts was dead
and a momentary bridge-not-ready or reflection failure could latch the option
hidden for the whole session.

Native: the reflection handles now cache only definitive absences (NoSuchMethod /
ClassNotFound); a hard reflection/linkage Error propagates and the command
rejects, which the JS probe treats as inconclusive and retries. refresh() keeps
its handle reads inside the try, so it still never throws.

Hook: seed the initial value from the already-settled cache (no hidden->visible
flicker on re-open) and retry a bounded number of times while the probe is still
inconclusive, recovering if a later read settles. bridge.ts logs the rejection so
an inconclusive probe is distinguishable from a genuine negative in the field.

Adds unit tests for the hook's seed / definitive / retry / give-up paths.

* refactor(android): align e-ink capability probe naming and count-scope comment

Make isEinkRefreshSupported() resolve a plain boolean so it matches the
is* predicate convention and can never be mistaken for the truthy response
object, and expand the auto-refresh counter comment to honestly list the
hands-free turn sources (auto page turn, TTS page-follow, auto-scroll) that
bypass it.

* docs(android): describe the e-ink probe as best-effort presence, not a guarantee

isSupported() only checks that a vendor refresh method resolves; a stubbed or
partially hidden hook can resolve yet throw at refresh() time. Reword the KDoc
so the capability gate's claim matches what the reflection probe actually
verifies, instead of implying a confirmed panel update.

* fix(android): probe each e-ink hook independently in the capability check

The `||` chain aborted on the first vendor hook whose lazy initializer threw a
hard reflection/linkage Error (deliberately uncached as the inconclusive
signal), never reaching a later hook that actually exists. A device whose only
working mechanism is NTX/Rockchip was reported inconclusive and ultimately
hidden, even though refresh() probes all three independently. Evaluate each
hook on its own: any resolved handle is authoritative support, and the Error is
propagated only when none is present, preserving retry-on-inconclusive.

* fix(android): fall the refresh-interval select back on an unknown synced value

The Auto Full Refresh select passed the stored interval straight through, so a
value outside {0,5,10,15,20} — e.g. from another platform/version or an older
synced config — matched no option and rendered an empty select. Extract the
interval options and guard the value, mirroring the pageTurnStyle select. Also
rename MAX_PROBE_ATTEMPTS to MAX_PROBE_RETRIES, since it bounds the retries
after the first unconditional probe rather than the total attempt count.

* fix(android): normalize the Auto Full Refresh interval at the state seed

An out-of-range synced einkAutoRefreshInterval (e.g. 7 from another
platform/version) now only masked the select as "Off" while the raw value kept
persisting and driving noteEinkPageTurn, so the shown option disagreed with the
actual refresh cadence. Seed the state through a normalizer to the valid set;
the mount effect then persists the corrected value, so display, persisted
config, and refresh behavior all agree. This also removes the per-render
guard the display no longer needs.

* fix(android): cache only definitive e-ink hook absences, not any Exception

Each lazy caught every Exception as a definitive "no hook" and cached null, but
Android surfaces a hidden-API-blocked lookup as NoSuchMethodException — a plain
Exception — so a present-but-unresolvable hook was latched unsupported for the
whole process and shared into refresh(). The code also contradicted its own KDoc
("NoSuchMethod/ClassNotFound is definitive"). Narrow each hook's definitive-
absence catch to NoSuchMethodException/ClassNotFoundException; any other
reflection failure now propagates, which `by lazy` leaves uncached so the next
probe retries it as an inconclusive rejection rather than a wrong negative.

* fix(android): stop the refresh-interval select from rewriting synced values

Normalizing the seeded interval made the mount effect persist 0 whenever the
synced value was outside {0,5,10,15,20}, so merely opening settings destroyed a
value another client or version wrote and propagated that off. Drop the
coercion: bind the select to the stored value directly (single source, no second
interval list) and let the mount write stay idempotent. A value our own UI never
produces renders unselected rather than being silently zeroed — the honest,
non-destructive choice.

* fix(android): show an out-of-set refresh interval as its own select option

A synced value outside {0,5,10,15,20} matched no option, so the controlled
select rendered blank and hid the active interval while refreshes still fired on
that cadence. Append the stored value as an extra option (displayed, not
rewritten) so the shown value matches what noteEinkPageTurn reads, without
coercing or persisting a change the user never made.

* refactor(android): reuse the e-ink refresh counter reset helper

The auto-refresh path reset the WeakMap inline while the manual refresh action
already used resetEinkRefreshCounter, leaving two reset sites that could drift.
Route the auto path through the same helper.

* docs(android): note scrolled-mode turns are full viewports before counting

In scrolled mode both 'pan' and 'page' advance a full viewport (the caller's
panDistance is ignored on that branch), so every turn reaching the counter is one
page. Document this so the Every-N-pages label and the actual refresh cadence are
shown to agree, and to stop a future reader mistaking a scrolled key-pan for a
short 3-line move that should not count.

* fix(android): keep the first inconclusive cause when probing e-ink hooks

isSupported() overwrote `inconclusive` on each hook, so when several failed the
earlier — usually more meaningful — cause (e.g. a LinkageError on the primary
Onyx hook) was dropped before the command layer could log and reject with it.
Retain the first throwable instead of the last.

* fix(android): guard the interval persist effect and log a resolved refresh no-op

Mirror the sibling equality guard on the einkAutoRefreshInterval persist effect so
opening the panel no longer writes an unchanged global view setting (and pushes a
redundant replica) on mount. And on the auto-refresh path, inspect the resolved
{ success: false } — reachable only on a supported device whose vendor hook failed
at refresh time — with a debug log; rejections (off-Android) still stay silent.

* fix(android): stop a stale refresh binding from swallowing the key

On a device the capability probe authoritatively ruled out, the hidden "Refresh
Page" row leaves no way to unbind a previously-configured key, yet
handleHardwarePageTurn still claimed the 'refresh' action — the button was
intercepted and did nothing. When getCachedEinkRefreshSupported() is false the
handler now declines the key so it falls through to its normal behavior, making
the stale binding inert. Unsettled (null) still claims the chord so a transient
probe gap can't leak the key mid-read.

* feat(android): fold the Hanvon hook into the e-ink capability probe

The upstream Hanvon refresh probe lives only in [refresh]; the capability
gate that hides "Auto Full Refresh" / "Refresh Page" probed just the three
View-reflection hooks, so it would hide the options on Hanvon readers whose
service-based hook is the one that actually works there. Extract a shared
[resolveHanvon] handle used by both [refresh] and [isSupported], and give
[isSupported] a Context to resolve it with, so the option is offered wherever
a real full-refresh mechanism exists.

* docs(android): reflect the Hanvon hook in the e-ink capability-probe comments

The probe now also resolves the Hanvon service via a Context lookup, so the
remaining "pure reflection" wording and the three-vendor hook list are no
longer accurate. Comment-only; no behavior change.

* fix(reader): defer the e-ink auto refresh until the turn settles

The native full-refresh hook deep-refreshes whatever is on the panel at call
time, so firing it before view.next/prev commits refreshed the outgoing page
while the incoming page landed as an ordinary update and kept its ghosting -
defeating the point of the every-N-pages cleanup. Schedule refreshEinkScreen
on the navigation promise's settle instead, for scrolled, pan-fallback and
ordinary turns alike.

Correct the FoliateView prev/next return type to Promise<void>; the foliate
implementation already resolves a turn promise despite the old void
declaration (see useCapturedTurn), so narrow its local TurnFn accordingly.

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-10-01 16:22:21 +02:00
Ava Johnson
0e609a0991
feat(widget): currently reading Android widget and widget options (#6518)
* feat(widget): bookshelf widget header size and Text to Speech options

Add a header size option (12-32sp, default 14) whose gap under the header
scales with it, and a Text to Speech option that shows or hides the TTS bar.
The header checkbox is "Show Header" and "Book title" becomes "Book Title".
The provider is renamed to BookshelfWidgetProvider.

Move the shared pieces out for reuse: the number stepper, flat button and
header gap helpers, the TTS bar layout and binding, the cover image helpers,
and a coalescer for the widget refresh.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* feat(widget): currently reading Android widget

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* feat: show remaining time and pages together, in a 1h 30m format

The reader footer joins both into one sentence when both settings are on. The
footer, widget and quota reset text share one duration format; the library tile
keeps its short rounded-hours form.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* fix(widget): skip the reading widget snapshot write once the widget is removed

A widget removed while its cover was being written had its snapshot saved
after onDeleted had already cleaned up, leaving it orphaned. Re-check that the
widget is still bound right before writing.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* fix(widget): keep refreshing when the reference page count can't load

Load failures are logged and the widget falls back to the plain page number
instead of rejecting the whole refresh.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* fix(i18n): correct translations found in review

- French: the participle agrees with the feminine time and pages
  ("restantes"), and "left in book" is "Il reste {{time}} dans le livre".
- Italian: the widget's time-and-pages form uses "rimanenti".
- Italian and Spanish: "left in book" matches the chapter form.
- Tibetan: tsheg between syllables. German and Portuguese: the reset countdown
  reads as upcoming. Hebrew: hyphen between the ו prefix and a numeral.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-authored-by: Huang Xin <chrox.huang@gmail.com>
2026-10-01 12:05:49 +02:00
kad-air
3e1f410c61
fix(ios): hide the status bar through the view controller for Xcode 27 builds (#6508)
Apps built with the iOS 27 SDK can no longer hide the status bar with
UIApplication.setStatusBarHidden (SDK 26 builds still can), so on Xcode 27
builds the reader never hid it. Hide it through the root view controller
instead: tao's TaoUIViewController implements prefersStatusBarHidden and
setPrefersStatusBarHidden:, with UIViewControllerBasedStatusBarAppearance
on. This works for SDK 26 and SDK 27 builds and is the only change on
devices other than iPhone Duo. With view-controller-based appearance the
in-app browser's own preferredStatusBarStyle now applies.

The bridge hides it through the webview's window, which exists before a
CarPlay-first launch attaches a scene, resolves once the safe area has
followed, and reports statusBarHidden with the insets.

On iPhone Duo, hiding the status bar also removes the side strip's inset
(84pt on the inner display). The reading page keeps the side insets
recorded with the status bar hidden, so opening the toolbar does not
re-paginate, while the header and footer bars follow the live insets; the
insets are re-read after each show/hide, and the landscape status-bar rule
is limited to compact-height windows on the Duo. Off the Duo none of this
runs: no re-read, base's landscape rule, and page insets equal to the live
ones.


Claude-Session: https://claude.ai/code/session_01SEQcYorVTWVVeNkGLdJ8Jw

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 11:20:25 +02:00
kad-air
9928d6a70a
fix(ios): keep chrome and page content clear of iPhone Duo's side status strip (#6312)
On iPhone Duo (iOS 27.1) the status bar is a vertical strip along one long
edge on the cover display and on the inner display in landscape, reported
as a large left or right safe-area inset. Readest only applied top/bottom
insets, so buttons, sheets, popups, the page and corner decorations sat
under it.

Everything here is gated on an explicit iPhone Duo flag so no other device
changes: the native bridge reports isIPhoneDuo from the model identifier
(iPhone19,4; SIMULATOR_MODEL_IDENTIFIER in the simulator), since iOS has no
foldable API and viewport size cannot identify the device. On the Duo:

- Bars, sheets, panels and pages are padded by the horizontal insets (a
  side panel only on its screen edge); edge-anchored controls, toasts and
  edge gestures are offset past the strip.
- The viewer container is inset instead of folding the insets into the
  paginator margins, which put only part of them on the outer edge; a
  two-column spread spanning the full width is inset symmetrically so the
  spine lands on the fold.
- Popups clamp to the safe region, with their points shifted back to the
  cell's coordinates (clamping alone moved them by the inset).
- Every pose keeps the mobile bars.

Off the Duo each path is main's code; every existing test passes
unmodified, and new parity tests cover iPhone portrait/landscape, iPad,
Android and desktop.


Claude-Session: https://claude.ai/code/session_01SEQcYorVTWVVeNkGLdJ8Jw

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 08:02:54 +02:00
Huang Xin
6e567ef310
fix(reader): stop the sidebar-width flash on Windows and Linux page turns (#6509)
With the sidebar open, every captured page turn on Windows and the Linux
CEF runtime flashed: the page jumped left over a black strip as wide as
the sidebar, then snapped back.

The snapshot asked Page.captureScreenshot for a clip of the reader cell.
Chromium implements a clip by emulating on the live view: it offsets the
viewport to the clip origin and resizes the view to the clip size for the
capture, then restores both. With the sidebar closed the cell starts at
the left edge, so nothing visibly moved.

Capture the whole view with no clip, which skips the emulation, and crop
the cell out while decoding with createImageBitmap. Cropping in Rust would
mean a JPEG decode and re-encode, about 75 ms per turn.

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-30 17:04:37 +02:00
Huang Xin
6bcd170de4
fix(reader): animate page turns for PDF and comics on Windows and Linux, closes #6380 (#6506)
Some checks are pending
CodeQL Advanced / Analyze (actions) (push) Waiting to run
CodeQL Advanced / Analyze (javascript-typescript) (push) Waiting to run
CodeQL Advanced / Analyze (rust) (push) Waiting to run
Publish Docker image / build (linux/amd64, ubuntu-latest) (push) Waiting to run
Publish Docker image / build (linux/arm64, ubuntu-24.04-arm) (push) Waiting to run
Publish Docker image / merge (push) Blocked by required conditions
Build with Nix / tests (push) Waiting to run
PR checks / nix_flake_check (push) Waiting to run
PR checks / rust_lint (push) Waiting to run
PR checks / koplugin_rust_lint (push) Waiting to run
PR checks / build_web_app (push) Waiting to run
PR checks / test_web_app (1) (push) Waiting to run
PR checks / test_web_app (2) (push) Waiting to run
PR checks / test_extensions (push) Waiting to run
PR checks / build_tauri_app (push) Waiting to run
Scorecard supply-chain security / Scorecard analysis (push) Waiting to run
Deploy to vercel on merge / build_and_deploy (push) Waiting to run
* fix(reader): animate page turns for PDF and comics on Windows and Linux, closes #6380

Fixed-layout books (PDF, CBZ/CBR, fixed-layout EPUB) only animate through
the captured page turn, which needs a native snapshot of the webview. That
snapshot existed on macOS, iOS and Android only, so Windows and the Linux
CEF runtime rejected it and every turn on those books was instant.

Both engines are Chromium, so both now take the snapshot with the DevTools
protocol's Page.captureScreenshot, clipped to the reader cell: WebView2's
CallDevToolsProtocolMethod on Windows, the CEF browser's DevTools message
observer on Linux. The clip returns exactly the region at device
resolution, and captureBeyondViewport stays off so the live page never
reflows. JPEG, as on Android: about 35 ms per full cell against 86 ms for
PNG.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* build(nix): bump cargoHash for the native-bridge dependency edges

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(reader): release the CEF screenshot observer when no result arrives

The observer and its registration hold each other, so a capture that
never gets a result (the DevTools agent detached, or the wait timed out)
kept both alive. Take the registration on agent detach, and on timeout
from the caller on the UI thread.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-30 16:08:42 +02:00
k6G52m4Dz75W
2a25092ac9
feat(android): probe the Hanvon eink service for full refresh (#6505)
Hanvon readers do not patch android.view.View; they register a system
service under the "eink" name whose sendOneFullFrame() performs the same
one-shot full-panel update the stock readers use. Add it as a fourth
probe in the chain so the Refresh Page action works on Hanvon devices.
2026-09-30 15:49:10 +02:00
Huang Xin
4eb7b6d7c2
fix(ios): keep swipe brightness in sync with the system brightness, closes #6374 (#6502)
* fix(ios): keep swipe brightness in sync with the system brightness, closes #6374

With System Screen Brightness on, a swipe or slider change was a temporary
override that iOS handed back whenever the app resigned active, so opening
Control Center or going Home snapped the screen back to the old level. The
next swipe then started from the stale in-app value, because Control Center
never fires visibilitychange, and jumped instead of adjusting smoothly.

- set_screen_brightness takes a `persist` flag; system-mode swipes and the
  slider write through to the system brightness instead of overriding it
- the swipe re-reads the device brightness on touch down in system mode
- manual mode re-applies its level natively when the app becomes active,
  so it also survives a Control Center trip

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(reader): hold system-mode swipe writes until the touch-down reading lands

A swipe that activated before the async brightness read resolved discarded
the fresh reading and wrote from the stale base. Tag each read with its
gesture, ignore readings from earlier gestures, and skip brightness writes
while the current gesture's reading is pending.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-30 14:24:00 +02:00
Huang Xin
37edd27c54
fix(reader): keep the footer clear of rounded screen corners on iPhone (#6474)
The footer corner clearance from #6429 only had a radius source on
Android, so on iPhones the footer ends still ran into the rounded display
corners with a small bottom margin or page gap.

The iOS native bridge now reports the bottom corner radius too (iOS 26+).
A window's own effective radius is 0, but a window-sized child view with a
container-concentric corner configuration resolves to the display corner
radius, all with public UIKit API. Older iOS keeps the current layout.

Closes #6449

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-29 19:02:56 +02:00
Huang Xin
d3cd0ac5e8
fix(ios): resume audiobook natively after a CarPlay interruption ends (#6462) 2026-09-29 20:50:12 +08:00
Huang Xin
5ebdd113d3
feat(tts): native desktop Now Playing for macOS, Windows and Linux (#6457) 2026-09-29 19:50:27 +08:00
Ava Johnson
e0943140f8
feat(widget): improve bookshelf widget configuration (#6440)
* feat(android): improve bookshelf widget configuration

* feat: open bookshelf editor from widget links

* fix(widget): address review feedback on the bookshelf editor and widget config screen

- addNewBookshelf no longer sets selectedId as a side effect inside a
  setDraft updater (updaters must be pure; under double-invocation the
  committed draft and the selected id could disagree, crashing
  selected.useGlobalGrouping on the next render). Draft and selectedId
  are now derived from one computed result and applied together.
- BookshelvesDialog's close() now closes immediately when there's no
  editor to flush (the window before settingsHydrated resolves),
  instead of silently no-oping via editor.current?.flush() short-circuiting.
- BookshelfWidgetConfigureActivity's Edit/Add buttons now persist the
  current picks via a separate persistSettings() instead of save(), so
  they never set RESULT_OK or finish() the configure activity - that
  result is reserved for actually tapping Save, not for a shortcut into
  the app.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* fix(widget): clear stale widget-request params when the bookshelf editor never mounted

Address further review feedback:

- Extracted BookshelvesEditor's clearWidgetRequestParams into a shared,
  module-level helper (it was only doing half the job).
- BookshelvesDialog's close() now also clears editBookshelf/addBookshelf/t
  when there's no mounted editor to have consumed them itself (dismissed
  before settings finished hydrating) - otherwise a later, unrelated
  normal open would replay the stale widget request.
- Fixed editor.browser.test.tsx's settings fixture the same way already
  done for editor.test.tsx: DEFAULT_SYSTEM_SETTINGS has no `version`,
  which useEnsureSettingsLoaded treats as "not hydrated", so
  BookshelvesEditor never mounted in any of that file's tests.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* i18n(widget): translate the Shelf name label

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* refactor(widget): offer Edit only when reconfiguring, drop Add

Opening the app from a first placement makes the launcher drop the
widget being placed, so the configure dialog's Edit button silently lost
it. Edit is now only offered for a widget that has been saved before
(i.e. reconfiguring a placed one), where it saves the dialog and opens
the shelf in the Bookshelves editor.

Add is removed with its readest://widget-add-shelf link and the editor's
addBookshelf handling: a new shelf still had to be picked in a second
reconfigure, and the in-app "+" already creates one.

Also fixes the catalog deserialization test, which lacked the labels
this PR made required.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(bookshelves): resolve a widget Edit tap against the open draft

A shelf deleted in the open editor is still in the saved shelves until
its removal lands, so an Edit tap naming it selected an id missing from
the draft and the editor crashed dereferencing it. Resolve the request
against the draft and keep the current tab when the shelf is gone.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
Co-authored-by: Huang Xin <chrox.huang@gmail.com>
2026-09-29 07:14:28 +02:00
Ava Johnson
e2e0dfaa9e
feat(widget): configurable Android bookshelf widget (#6430)
* feat(android): add moveTaskToBack native command

Lets JS send the app to the background like the system Home button,
without killing the process. Wired end to end: Kotlin command, Rust
command/mobile/desktop stubs, permission entry and the bridge.ts wrapper.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* fix(android): consume the back-key UP paired with an intercepted DOWN

The UP guard re-read the live interception flag, so if JS released
interception between DOWN and UP (e.g. a screen unmounting in its Back
handler) the UP fell through to onBackPressedDispatcher and re-forwarded
the same press. Record the DOWN-time decision and use it for the UP.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* fix(widget): keep Library blank while a widget-tap link resolves

Tapping a widget book briefly showed the Library before the reader
opened. checkPendingLaunchLink holds the Library blank from launch until
useOpenLaunchLinks knows whether a book link is pending.

The gate is released immediately only when staying put (book missing,
download failed, no link). When navigating away it is released on
unmount instead, since router.push does not block until the route swaps.
On Android the launch URL arrives both live and via getCurrent(); the
cold-start read dedupes as a replay, so it must not treat an already
queued link as "nothing pending".

Book and annotation links share one openBook path in a single
useOpenLaunchLinks hook, mounted once per route (the player included),
which reads the cold-start URL once, dedupes replays and waits for the
library. The Library placeholder is held until it is known whether any
link claimed the launch. So an annotation link to a cloud-only book
downloads it first and one to an audiobook opens the player.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* refactor(bookshelves): extract grouping, sorting and exclusivity sections

Moves the Grouping and Sorting fieldsets and the Exclusive switches into
controlled components so another screen can edit a BookshelfDefinition
with the same UI. The "Use global ..." switches only render when a
global value is passed; the Bookshelves editor passes both, so its
behavior is unchanged. The Exclusivity block takes its tie-rule text and
Include label from the caller, and an optional validity check.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* feat(widget): configurable Android bookshelf widget

Extends the reading widget into a configurable Android bookshelf widget.
Each placed instance owns its own BookshelfDefinition (filters, sort and
grouping, evaluated with the same code as the Library) plus a grid size,
title toggle and mosaic-covers option. The shelf's name is the widget's
heading, and a group axis shows mosaic group tiles alongside any ungrouped
books, in the order the Library shows them (one tagged `items` list).

All instances are evaluated together, so an exclusive widget claims its
books from the others as exclusive shelves do, the older widget (lower
id) winning a shared book. Deleting a widget only frees its books in the
others on the next app refresh. A widget whose
snapshot is unchanged is not pushed to native again, unless native reported
a tile it could not draw (a missing cover), which is retried.

A refresh in progress makes a later overlapping one (the debounce, the
throttle and the immediate TTS-state publish can land close together) a
no-op rather than race the same cache; the next trigger picks up whatever
is current by then.

iOS now answers get_bookshelf_widget_instances and set_bookshelf_widget_settings
as no-ops (it has only the one default snapshot), and move_task_to_back
rejects there outright - it has no public API to background the app -
instead of the bridge failing with an unknown-command error.

The shelf is stored as opaque JSON per appWidgetId that native never
parses, is per-device, and bypasses bookshelf sync. The transport bar
appears only on instances whose shelf matches the playing book. The
layout fills its grid by weight rather than trusting launcher-reported
sizes. Adds the configure Activity shim, which holds the launcher's
request until the settings screen saves or cancels, the get/set
instance-settings plugin commands, and instrumented + unit tests.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* feat(widget): in-app widget settings screen using the shared bookshelf editor

The native configure Activity hands off to readest://widget-settings/{id},
an in-app screen that edits the instance's own bookshelf with the same
filter, grouping and sorting sections as the Bookshelves editor, plus the
widget-only name (the heading), title toggle, grid size and mosaic-covers
option. Edits are a draft: Save stores them, refreshes the widget and
places it, while Cancel, Back and Home discard them and cancel the
placement, like other widgets' configure screens.

The Exclusive and include switches use widget-specific wording, and Save
refreshes every widget because exclusivity couples their books.

The widget's settings and group links join the shared launch-link hook,
and a group tap carries the group's id, so opening it needs no lookup.

Leaving pops the SPA navigation and backgrounds the app so the reveal
happens off-screen. Also handles the widget-group deep link from
group tiles, resolving parent groups through the library's group ids.
Widget-only links reject the https web host.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* refactor(widget): rename reading widget to bookshelf widget

Mechanical rename ahead of extending the widget beyond "currently
reading" books: files, identifiers, resources, the plugin command
(update_bookshelf_widget, including the iOS method) and the prefs file.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* refactor: extract shared back-navigation helper

popNavigationOrGoToLibrary replaces the duplicated "pop history, else go
to the library" Back handling in the player page. The Status grouping's
comment is also condensed.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* fix(widget): address review feedback on bookshelf widget

- Reject update_bookshelf_widget/set_bookshelf_widget_settings when
  appWidgetId isn't a currently bound widget instance, instead of
  silently writing an orphaned preference/cover entry.
- Restore the coalesced-rerun queue in refreshBookshelfWidget: a plain
  running guard could drop a refresh requested while one was already
  in flight, with no other trigger to recover it (e.g. the
  widget-settings page's Save).
- Widen the PendingIntent request-code stride to
  id * MAX_GRID_SIZE * MAX_GRID_SIZE + itemIndex to avoid collisions
  at high widget ids.
- Scope group-tile thumbnail cache keys per widget instance
  (coverKey) instead of by group id alone, so two widgets sharing a
  group with different filters/mosaic settings don't overwrite each
  other's cover file.
- Write thumbnails atomically (temp file + rename) so a reader never
  sees a partially-written file and concurrent writers can't corrupt
  a shared cover.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* fix(widget): report thumbnail-write failures and clean up group covers on delete

- writeBitmapAtomically now returns false (and always cleans up its
  temp file) when encoding or the rename fails, instead of silently
  reporting success; propagated through writeThumbnail and
  writeGroupTileThumbnail so a failed write is retried like any other
  failed tile.
- BookshelfWidgetStore.clear deletes the deleted widget's own
  group-tile cover files (from its last snapshot's coverKeys), instead
  of only clearing its preferences, so widget churn doesn't leave
  orphaned PNGs behind. Book thumbnails, which are shared across
  widgets, are left alone.
- refreshBookshelfWidget: a caller queued during an in-progress run now
  gets a promise that settles only once the coalesced rerun actually
  finishes, instead of resolving immediately - so a caller like the
  widget-settings page's Save, which acts right after awaiting this,
  can't proceed before its own refresh has happened.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* fix(widget): delete group covers superseded by a refresh, not just on delete

writeSnapshot now diffs the widget's previous snapshot against the new
one and deletes any group-cover file the old one owned that the new
one doesn't - e.g. a group dropped by a filter change, or a groupBy
change that replaces the whole tile set. Previously only clear()
(widget removal) cleaned up group covers, so this churn left orphaned
PNGs behind until the widget was deleted entirely.

clear() and writeSnapshot now share a groupCoverKeys/deleteGroupCovers
helper pair instead of duplicating the delete loop. An unparseable new
snapshot skips cleanup rather than deleting every existing cover, and
the new snapshot is persisted before old covers are deleted, so a
process death in between leaks an orphan file instead of leaving the
still-stored old snapshot pointing at an already-deleted cover.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* fix(widget): harden group-cover cleanup against escaping keys and torn writes

- deleteGroupCovers now checks canonical containment before deleting,
  matching the writers (writeThumbnail/writeGroupTileThumbnail), so a
  stored coverKey can never resolve outside the covers dir.
- writeSnapshot commits the new snapshot to disk synchronously (not
  the usual async apply) before deleting superseded group covers, so
  a process death between the two can't leave the still-stored old
  snapshot pointing at an already-deleted cover file.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* refactor(widget): show an existing bookshelf, picked in a native screen

A widget now points at one of the app's bookshelves instead of carrying
its own filter/sort/grouping/exclusivity copy, so users build shelves in
one place. It is evaluated exactly as the Library evaluates it (same
sort and exclusivity), even while hidden there, and falls back to
Recently read when its shelf is deleted.

- The configure Activity is a native dialog: shelf list, rows, columns,
  titles. The app publishes its shelves and the translated labels
  (set_bookshelf_widget_catalog), so placing a widget no longer starts
  the WebView. A running app refreshes right away; otherwise the widget
  shows a tap-to-open placeholder until the app next publishes.
- Removes the in-app /widget-settings screen, its deep link,
  move_task_to_back, the back-key UP change and the extracted
  Bookshelves sections, which only existed for that screen.
- Keeps the provider's ReadingWidgetProvider component name: renaming it
  made Android delete every placed widget on upgrade.
- Grids over 9 tiles decode covers at half size and a rejected
  updateAppWidget is caught, so a big grid on a small screen can't crash
  every launch.
- Group tiles show the translated group name; a launch link waiting on a
  library that failed to load no longer keeps the Library blank; a
  widget removed mid-refresh doesn't get its snapshot written back.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
Co-authored-by: Huang Xin <chrox.huang@gmail.com>
2026-09-28 18:46:00 +02:00
David Fernandez
ff6ef54303
fix(reader): keep the footer clear of rounded screen corners on Android (#6429)
* fix(reader): keep the footer clear of rounded screen corners on Android

On phones with rounded display corners the footer's ends (pages left,
reading progress) sit inside the corner arc and get clipped, especially
with a small bottom margin. The safe-area insets only cover the display
cutout, so the reader never knew about the corners.

The native bridge now reports the bottom corner radius (Android 12+,
WindowInsets.getRoundedCorner). The footer works out how far the arc
reaches inward at the height of its text and uses that as a minimum
inline padding. Only the footer moves, and only when the arc would touch
the text; the book layout and margins are unchanged. Platforms without
the API report no radius and keep the current layout.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(reader): clear only the footer sides that meet a rounded corner

With books side by side, a cell shares only its outer bottom corner with
the screen, but the footer padded both of its ends. Carry the left and
right corner radii separately from BooksGrid and work out the clearance
for each footer end on its own.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-28 23:32:03 +08:00
Kel
85920ceef7
fix(android): open Readest from TTS media controls (#6370)
Some checks are pending
CodeQL Advanced / Analyze (actions) (push) Waiting to run
CodeQL Advanced / Analyze (javascript-typescript) (push) Waiting to run
CodeQL Advanced / Analyze (rust) (push) Waiting to run
Publish Docker image / build (linux/amd64, ubuntu-latest) (push) Waiting to run
Publish Docker image / build (linux/arm64, ubuntu-24.04-arm) (push) Waiting to run
Publish Docker image / merge (push) Blocked by required conditions
Build with Nix / tests (push) Waiting to run
PR checks / test_web_app (2) (push) Waiting to run
PR checks / nix_flake_check (push) Waiting to run
PR checks / rust_lint (push) Waiting to run
PR checks / koplugin_rust_lint (push) Waiting to run
PR checks / build_web_app (push) Waiting to run
PR checks / test_web_app (1) (push) Waiting to run
PR checks / test_extensions (push) Waiting to run
PR checks / build_tauri_app (push) Waiting to run
Scorecard supply-chain security / Scorecard analysis (push) Waiting to run
Deploy to vercel on merge / build_and_deploy (push) Waiting to run
Co-authored-by: Kel <1563599+kelvinalfaro@users.noreply.github.com>
Co-authored-by: Huang Xin <chrox.huang@gmail.com>
2026-09-23 17:53:26 +02:00
Kel
49a55274f3
fix(android-auto): play cold EPUBs in media service (#6341)
* fix(android-auto): play cold EPUBs in media service

* fix(android-auto): wait for cold playback paths

* fix(android-auto): persist each cold EPUB speech position

* fix(android-auto): release cold playback on WebView activation

---------

Co-authored-by: Kel <1563599+kelvinalfaro@users.noreply.github.com>
Co-authored-by: Huang Xin <chrox.huang@gmail.com>
2026-09-21 21:25:06 +02:00
Huang Xin
f45e13f9f5
feat(ios): add CarPlay recent books and fix scene handoff (#6339)
* fix(ios): prevent blank windows when opening files on iPad

* test(ios): remove config-only scene assertions

* feat(ios): start recent books from CarPlay and restore phone scene
2026-09-21 19:57:32 +02:00
Kel
a11c06b22c
feat(android): browse and resume books in Android Auto (#6285)
Some checks are pending
CodeQL Advanced / Analyze (actions) (push) Waiting to run
CodeQL Advanced / Analyze (javascript-typescript) (push) Waiting to run
CodeQL Advanced / Analyze (rust) (push) Waiting to run
Publish Docker image / build (linux/amd64, ubuntu-latest) (push) Waiting to run
Publish Docker image / build (linux/arm64, ubuntu-24.04-arm) (push) Waiting to run
Publish Docker image / merge (push) Blocked by required conditions
Build with Nix / tests (push) Waiting to run
PR checks / test_web_app (2) (push) Waiting to run
PR checks / nix_flake_check (push) Waiting to run
PR checks / rust_lint (push) Waiting to run
PR checks / koplugin_rust_lint (push) Waiting to run
PR checks / build_web_app (push) Waiting to run
PR checks / test_web_app (1) (push) Waiting to run
PR checks / test_extensions (push) Waiting to run
PR checks / build_tauri_app (push) Waiting to run
Scorecard supply-chain security / Scorecard analysis (push) Waiting to run
Deploy to vercel on merge / build_and_deploy (push) Waiting to run
* feat(android): browse and resume books in Android Auto

* fix(android-auto): route cold audiobooks and sync handoffs

* fix(media): isolate stale session teardown

* fix(android-auto): gate the browse tree, harden selection, withhold from Play

Review follow-ups on the Android Auto browse work.

Exposure:
- cap the published slice at 10 books (JS) with an independent native ceiling
- publish an empty library while App Lock is engaged, and clear the persisted
  native copy rather than just stopping publishing
- validate every media browser caller in onGetRoot (own uid / platform
  signature / MEDIA_CONTENT_CONTROL / pinned certificate), in shadow mode:
  the verdict is logged but not enforced until the certificates have been
  observed on real head units

Correctness:
- exclude cloud-only rows: downloadedAt never syncs, so a synced book carries
  undefined and `!== null` admitted every one of them
- fail a stuck browse selection into STATE_ERROR after 20s instead of leaving
  Android Auto pinned on STATE_BUFFERING
- route a selection through useOpenBookLink so it waits for hydration, fetches
  a cloud-only file, and routes audiobooks to the player; mount that hook on
  /player so a car selection works while the player is open
- ignore transport commands that arrive with no active session, so a headset
  play button no longer starts the silent keep-alive player
- stop overwriting the live session's title/scrubber while a selection is
  pending
- keep the session owner across an idle deactivation, so a book paused past
  the 30-minute timeout can still move its scrubber
- do not rethrow from setActive: the caller is `void bind(...)`, so it became
  an unhandled rejection and skipped action-handler registration
- reset the cover on unbind so the next book cannot inherit it

Release:
- resolve the car meta-data name through a manifest placeholder so Android Auto
  ships to the FOSS/GitHub builds and is withheld from Google Play until the
  in-car audio path is validated (Play rejected 11020; see #5038, #5235)
- move the browse-tree labels into Android string resources

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* feat(android-auto): validate media browser callers in shadow mode

The browse service is exported so Android Auto can bind it, which means any
installed app can call onGetRoot and read library titles, authors and cover
URIs. Validate the caller against its own uid, the platform signature,
MEDIA_CONTENT_CONTROL, and a certificate pin.

Enforcement is OFF. The verdict and the caller's certificate hashes are logged
instead ("browse caller"), because an allowlist built from guessed hashes is
how a real head unit gets locked out. Collect the hashes from logcat on real
hardware, pin them, then flip ENFORCE_BROWSE_VALIDATION.

The decision is a pure function over plain data so it is unit-testable without
a device; the PackageManager lookups stay in the service and are cached per
caller because onGetRoot runs on a binder thread.

Verified on the Android Automotive emulator (android-34-ext9 arm64): the real
car media app reaches onGetRoot and resolves to PLATFORM_SIGNED with no pins,
so AAOS is already admitted. Phone projection is still unmeasured — the
Desktop Head Unit links over ADB but never takes video focus on the API 35
emulator, so gearhead's browse request never arrives.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix(android-auto): read the caller's current signer, not its rotation lineage

signingCertificateHistory is the key-rotation lineage, not the present
identity. Reading it reported TWO certificates for Android Auto — a retired
key plus today's — and because a caller must match every certificate it
presents, pinning would have had to include the retired key and would break
on the next rotation.

apkContentsSigners is the current signer set. Verified against the installed
gearhead APK on an API 35 Play Store emulator: apksigner reports one signer,
1ca8dcc0…, and the service now logs exactly that.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix(android-auto): close the browse authorization gaps found in review

Five review findings, all reproduced against the code first.

onLoadChildren authorized the caller (CWE-200). A browser client picks the
parentId it subscribes to, so it could request LIBRARY_ROOT_ID directly no
matter which root onGetRoot handed back — the root decision was only
advisory. Re-check the in-flight caller via getCurrentBrowserInfo() before
serving any children.

onGetRoot now refuses a denied caller outright (CWE-862). An empty root still
completes the connection, and a completed connection hands over the
media-session token, which drives onPlay/onPlayFromMediaId — the session
callbacks authorize nothing. Google's Android for Cars guidance is to return
null for an untrusted package. EMPTY_ROOT_ID is gone with it.

The selection watchdog no longer lets a previous session suppress the
timeout. A successful handoff cancels the watchdog in activateSession(), so
reaching the Runnable always means the selection failed; sessionActive can
still be true when a DIFFERENT book was already playing, and returning early
there left that live session pinned in STATE_BUFFERING. Republish its real
state instead.

Listener registration cleans up after a partial failure. Listeners are only
published to eventListeners once the whole sequence succeeds, so the ones
registered before a rejection were unreachable and leaked, and
eventListenerInited stayed true, blocking every retry for the session.

The artwork push rechecks binding ownership after its await. unbind() plus a
new bind can land while updateMetadata() is in flight; clearing #pushArtwork
on the stale completion consumed the NEW binding's one-shot cover push.

Not taken: withholding Android Auto from the FOSS flavor too. Shipping it to
the GitHub builds while holding it back from Play is deliberate — the car
path can only be exercised on hardware that runs those builds.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

---------

Co-authored-by: Kel <1563599+kelvinalfaro@users.noreply.github.com>
Co-authored-by: Huang Xin <chrox.huang@gmail.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-19 23:21:58 +08:00
Huang Xin
4a8cbe6e97
fix(ios): keep reader screen awake with native idle timer (#6261)
Some checks are pending
CodeQL Advanced / Analyze (actions) (push) Waiting to run
CodeQL Advanced / Analyze (javascript-typescript) (push) Waiting to run
CodeQL Advanced / Analyze (rust) (push) Waiting to run
Publish Docker image / build (linux/amd64, ubuntu-latest) (push) Waiting to run
Publish Docker image / build (linux/arm64, ubuntu-24.04-arm) (push) Waiting to run
Publish Docker image / merge (push) Blocked by required conditions
Build with Nix / tests (push) Waiting to run
PR checks / build_web_app (push) Waiting to run
PR checks / test_web_app (1) (push) Waiting to run
PR checks / test_web_app (2) (push) Waiting to run
PR checks / nix_flake_check (push) Waiting to run
PR checks / rust_lint (push) Waiting to run
PR checks / koplugin_rust_lint (push) Waiting to run
PR checks / test_extensions (push) Waiting to run
PR checks / build_tauri_app (push) Waiting to run
Scorecard supply-chain security / Scorecard analysis (push) Waiting to run
Deploy to vercel on merge / build_and_deploy (push) Waiting to run
2026-09-18 11:46:15 +08:00
Huang Xin
ed1ab3de9d
fix(ios): restore cross-page selection with native touch forwarding (#6255)
Some checks are pending
CodeQL Advanced / Analyze (actions) (push) Waiting to run
CodeQL Advanced / Analyze (javascript-typescript) (push) Waiting to run
CodeQL Advanced / Analyze (rust) (push) Waiting to run
Publish Docker image / build (linux/amd64, ubuntu-latest) (push) Waiting to run
Publish Docker image / build (linux/arm64, ubuntu-24.04-arm) (push) Waiting to run
Publish Docker image / merge (push) Blocked by required conditions
Build with Nix / tests (push) Waiting to run
PR checks / test_web_app (2) (push) Waiting to run
PR checks / nix_flake_check (push) Waiting to run
PR checks / rust_lint (push) Waiting to run
PR checks / koplugin_rust_lint (push) Waiting to run
PR checks / build_web_app (push) Waiting to run
PR checks / test_web_app (1) (push) Waiting to run
PR checks / test_extensions (push) Waiting to run
PR checks / build_tauri_app (push) Waiting to run
Scorecard supply-chain security / Scorecard analysis (push) Waiting to run
Deploy to vercel on merge / build_and_deploy (push) Waiting to run
2026-09-17 20:46:58 +02:00
Huang Xin
963cf53109
fix(android): follow system theme in reading widget (#6131) 2026-09-07 21:21:07 +02:00
Huang Xin
7c8a0a468a
feat: support authenticated web novel imports (#6119)
* feat: reuse browser sessions for authenticated novel imports

* fix: preserve Windows domain cookies during session renewal

* docs: describe native browser session fetching

* fix: keep web novel import progress steady between chapters

* fix(test): hold curl overlay until capture assertions finish

* fix: address authenticated novel import review findings
2026-09-07 17:39:26 +02:00
Huang Xin
62b0162d91
feat: unify web imports with signed-in page clipping (#6117)
* feat: unify web imports with signed-in page clipping

* docs: describe web page clipping
2026-09-07 14:12:59 +02:00
kad-air
af75a4778f
feat(reader): hinge the two-column Page Curl at the spine (#6107)
* feat(reader): hinge the two-column page curl at the spine (#6106)

With two columns on screen the Page Curl treated the whole spread as one
sheet hinged at the outer screen edge. Now the outer column turns as a
leaf hinged at the spine: the fold stops at the middle, the roll
tightens to nothing so the leaf lands on the inner column as an exact
mirror, and the inner column stays flat until covered.

The back of the leaf shows the incoming page. After the instant
navigation the controller captures the inner column of the new spread
under a native cover view (iOS: a snapshot sibling above the webview
that takeSnapshot does not render), clipping the overlay to the leaf
side so the platform snapshot sees the live column. Where the host
cannot cover (Android, desktop) the back is theme paper and the overlay
fades out over the last stretch so the live page takes over smoothly.

Single-column turns are unchanged.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(reader): re-check the capture gate while capturing the incoming column

A dialog can open during any of the awaits in the two-column incoming
capture, and the platform snapshot includes its composited pixels. Check
isCaptureAllowed after pixel preparation, after the capture, and before
the bitmap reaches the renderer, matching the outgoing capture path.

Adds a regression test that closes the gate while the incoming capture
is pending and asserts the bitmap is never committed, plus the happy
path that it is.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-07 10:37:31 +02:00
Huang Xin
655c72ad5a
feat(linux): ship Readest on the tauri CEF runtime (#6074)
* feat(linux): build and ship Readest on the tauri CEF runtime

Linux now builds against upstream tauri `feat/cef` (git) and the plugins on
plugins-workspace `feat/cef`, while macOS/Windows/mobile keep the readest
fork untouched:

- `pnpm tauri:cef dev|build` (scripts/tauri-cef.mjs) runs @tauri-apps/cli-cef
  with `--features cef`, cargo `--no-default-features` and the Linux-only
  `[patch.crates-io]` in src-tauri/.cargo/cef.toml, swapping the committed
  Cargo.cef.lock in for the run so Cargo.lock stays in the fork state.
- The fork crates are no longer workspace members (a member clashes on
  `links` with the git copy); the tauri-plugins fork carried no changes and
  is removed, tauri-plugin-fs comes from crates.io at 2.5.1.
- App: `cef = ["tauri/cef"]` (the fork gets a no-op stub), explicit runtime
  type, `cef_entry_point`, `--no-first-run` for CEF, commands generic over
  the runtime, xdg-portal dialogs on Linux (rfd's GTK thread crashes CEF),
  rangefile reads and pointer-driven move/resize on the Linux CEF runtime,
  Chromium reported in the About dialog, deb/rpm depend on libwebkit2gtk
  while plugins still pull the wry runtime.
- Build-generated permission files are untracked; turso registers `batch`.
- CI Linux legs use `pnpm tauri:cef`.

Submodules: packages/tauri -> feat/cef-feature-stub, tauri-plugin-turso ->
fix/register-batch-command (both need pushing).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* feat(linux): let the CEF wrapper run an unpacked tauri CLI for offline builds

Flatpak builds have no network, so `TAURI_CEF_CLI` points scripts/tauri-cef.mjs
at an unpacked copy of @tauri-apps/cli-cef instead of `pnpm dlx`.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* chore(linux): take the CEF stack from the readest forks

- src-tauri/.cargo/cef.toml: tauri and the plugins now come from the readest
  forks' feat/cef branches (upstream feat/cef plus the DevTools-close fix in
  tauri-runtime-cef); Cargo.cef.lock re-resolved against them.
- tauri-plugin-turso: point at main, which merged the batch command fix.
- CI: STRACE_MODE=0 for the Linux legs so the CEF AppImage bundler
  (quick-sharun) does not launch the app under Xvfb and hang (#4906).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* feat(linux): make the CEF runtime the default tauri build on Linux

`pnpm tauri` now goes through scripts/tauri.mjs (the former tauri-cef.mjs):
on Linux its dev, build and bundle commands run the feat/cef tauri CLI
with the CEF feature, cargo config and Cargo.cef.lock swap, and every
other platform or command passes straight through to @tauri-apps/cli.
The separate `tauri:cef` script goes away, so the release and nightly
workflows, the local Linux build script and the docs use plain
`pnpm tauri build` again.

The tauri webdriver harness (scripts/test-tauri.sh) still calls the
`tauri` binary directly and keeps the wry runtime on Linux, since
tauri-driver needs WebKitWebDriver.

Cargo.cef.lock picks up the quick-xml 0.41 bump from main.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* chore(nix): refresh cargoHash for the reshaped Cargo.lock

Dropping the packages/tauri-plugins submodule and the tauri-plugin-fs
path patch changed the vendored cargo dependency set, so the Nix
fixed-output hash moves to the value the nix-deps-check job reported.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(linux): harden the CEF wrapper and pointer window drag

Review follow-ups on the CEF runtime work:

- scripts/tauri.mjs parks the wry Cargo.lock in Cargo.lock.wry, created
  exclusively, so two CEF commands in one checkout cannot swap lockfiles
  over each other, and a killed run leaves an obvious file to move back.
- The CEF runtime alias, entry point and runtime attributes are gated on
  Linux as well as the `cef` feature; elsewhere the feature is a no-op.
- Pointer-driven window move/resize applies the last pointer delta when
  the button is released before the pending animation frame, and does
  not start tracking when the button was already released while the
  window state was being read.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-05 20:09:06 +02:00
Huang Xin
84b3d16e86
fix(sync): fit OAuth tokens in Windows keychain (#6033)
Persist only refresh tokens and use tagged UTF-8 for Windows secure items while retaining legacy UTF-16 reads.
2026-09-02 20:43:01 +02:00