diff --git a/.gitignore b/.gitignore index c23fe5a..aff5831 100644 --- a/.gitignore +++ b/.gitignore @@ -6,7 +6,7 @@ build/ # Local configuration file (sdk path, etc) local.properties -build-run.ps1 +*.ps1 .actrc .secrets .env @@ -15,9 +15,13 @@ release.keystore *.keystore *.jks +# Others +docs/*.md # Log/OS Files *.log +*.logcat +*.csv app/release* app/instrumentation* diff --git a/AGENTS.md b/AGENTS.md index 4a7cb90..f077823 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -8,17 +8,21 @@ - `app/src/main/java/com/nosferatu/launcher/NosferatuApp.kt`: app-level wiring (Room DB, parser strategies, scanner, repository). - `app/src/main/java/com/nosferatu/launcher/repository/LibraryRepository.kt`: sync flow between filesystem and Room. - `app/src/main/java/com/nosferatu/launcher/library/LibraryViewModel.kt`: UI state orchestration via Flows. -- `app/src/main/java/com/nosferatu/launcher/library/LibraryConfig.kt`: all persisted user settings (SharedPreferences `library_prefs`): root path, font size, line height, page margins, **background mode**. -- `app/src/main/java/com/nosferatu/launcher/ui/AppColors.kt`: app-wide color theme helpers — `AppColors`, `LocalAppColors`, `bgColorFor()`, `contentColorFor()`, `appColorsFor()`. +- `app/src/main/java/com/nosferatu/launcher/library/LibraryConfig.kt`: all persisted user settings (SharedPreferences `library_prefs`): root path, font size, line height, page margins, **background mode**. Note: recently extended to also persist `fontChoice` (float) and expose `updateFontChoice()`. +- `app/src/main/java/com/nosferatu/launcher/ui/AppColors.kt`: app-wide color theme helpers — `AppColors`, `LocalAppColors`, `bgColorFor()`, `contentColorFor()`, `appColorsFor()` (currently a minimal two-color model; there's an accompanying UI plan to expand it to more semantic tokens). - `app/src/main/java/com/nosferatu/launcher/ui/MainActivity.kt`: Compose home/library/settings shell + storage permission flow + background-mode theme wiring. +- `app/src/main/java/com/nosferatu/launcher/ui/MainActivity.kt`: Compose home/library/settings shell + storage permission flow + background-mode theme wiring. `MainActivity` was updated to reuse the application `libraryConfig` instance instead of creating a local one. - `app/src/main/java/com/nosferatu/launcher/ui/screens/settings/SettingsChoices.kt`: settings composables including `BackgroundColorOption` (writes to `LibraryConfig.backgroundMode`). - `app/src/main/java/com/nosferatu/launcher/reader/ReaderActivity.kt`: Readium reader + locator persistence + background theme application. +- `app/src/main/java/com/nosferatu/launcher/reader/ReaderActivity.kt`: Readium reader + locator persistence + background theme application. `ReaderActivity` now uses the application-level `libraryConfig` instance so in-reader preference changes propagate to the rest of the app. - `app/src/main/java/com/nosferatu/launcher/ui/components/fontsettings/TextSettingsOverlay.kt`: in-reader font size / line-height panel (`ReaderTextSettings`, `SliderRow`). - `app/src/main/java/com/nosferatu/launcher/data/Ebook.kt`: data model and `EbookFormat` enum (EPUB, PDF, CBZ) + `CoverImage` wrapper. - `app/src/main/java/com/nosferatu/launcher/parser/BookParser.kt`: parsing orchestration, detailed logging, and fallback behaviour when a parser strategy is missing. +- `PLAN-UI-IMPROVEMENT.md`: repository-level UI improvement plan with technical appendix and implementation to-do list. +- `app/src/main/java/com/nosferatu/launcher/parser/BookParser.kt`: parsing orchestration, detailed logging, and fallback behaviour when a parser strategy is missing. ## Architecture and data flow -- Runtime DI is manual (no Hilt/Koin): `NosferatuApp` constructs `LibraryRepository`; activities create `LibraryViewModel` via `LibraryViewModelFactory`. +- Runtime DI is manual (no Hilt/Koin): `NosferatuApp` constructs `LibraryRepository`; activities create `LibraryViewModel` via `LibraryViewModelFactory`. Note: `NosferatuApp.libraryConfig` is exposed as an application-scoped `val` and reused by activities. - Library sync path: `LibraryViewModel.scanBooks()` -> `LibraryRepository.syncLibrary()` -> `LibraryScanner.scanDirectory()` -> `BookParser.parseMetadata()` -> `BookDao.insertBook()`. - Scanner constraints are intentional: `walkTopDown().maxDepth(2)` and skips dot folders + `Android` (`LibraryScanner.kt`). - Metadata parser is strategy-based by extension (`BookParser.kt` + `ParserStrategy.kt`); currently only `EbookFormat.EPUB` is mapped in app wiring. @@ -66,7 +70,7 @@ The app supports three background modes, stored as a Float in SharedPreferences ## Integrations and boundaries - External storage access is central (`READ/WRITE_EXTERNAL_STORAGE`, `MANAGE_EXTERNAL_STORAGE`, legacy external storage flags in `AndroidManifest.xml`). - Readium stack: `readium-shared`, `readium-streamer`, `readium-navigator`, `readium-adapter-pdfium` (see `app/build.gradle`, `libs.versions.toml`). -- Readium preferences are applied via `EpubPreferences(fontSize, lineHeight, theme)` — both at `EpubNavigatorFactory.createFragmentFactory(initialPreferences = …)` and at runtime via `navigator.submitPreferences(…)` inside `applyReaderPreferences()`. +- Readium preferences are applied via `EpubPreferences(fontSize, lineHeight, theme)` — both at `EpubNavigatorFactory.createFragmentFactory(initialPreferences = …)` and at runtime via `navigator.submitPreferences(…)` inside `applyReaderPreferences()`. Note: `fontFamily`/custom-font support is not guaranteed by the navigator; see `PLAN-UI-IMPROVEMENT.md` for options (CSS injection, embedding fonts) and next steps. - EPUB metadata/covers are extracted with `epublib` + zip/OPF parsing; covers are resized and written under app internal `files/covers` (`CoverManager.kt`). - Additional repositories beyond Google/MavenCentral are required (`settings.gradle`): psiegman GitHub Maven repo + JitPack. @@ -80,3 +84,130 @@ The app supports three background modes, stored as a Float in SharedPreferences - Note: `EbookFormat` (in `data/Ebook.kt`) now contains PDF and CBZ values. These formats exist in the data model but are only discoverable by the scanner if a corresponding ParserStrategy is wired in `NosferatuApp.kt` (scanner filters by `parser.supportedFormats`). - Implementation detail: `BookParser.parseMetadata` calls `EbookFormat.fromExtension` to map file extensions to the enum; that method throws on unknown extensions. `LibraryScanner.extractMetadata` catches parsing exceptions and returns null, but if you add callers, be aware of the potential IllegalArgumentException from `fromExtension`. +## Recent UI & Settings updates (2026-04-04) + +Summary of recent changes you should know about when editing UI or settings: + +- `LibraryConfig` now persists `fontChoice` (float) and exposes `updateFontChoice()` so font selection is observable app-wide. See `app/src/main/java/com/nosferatu/launcher/library/LibraryConfig.kt`. +- Runtime font handling: `MainActivity` and `ReaderActivity` were extended to resolve a runtime font resource named `literata_regular` in `app/src/main/res/font/`. When `fontChoice` selects Literata the app attempts to build a `Typography`/`Typeface` using that resource; if missing the code falls back to system defaults. Place custom fonts under `app/src/main/res/font/` (NOT `res/fonts`) and name them accordingly for the current wiring. +- Reader UI: `ReaderActivity` now applies the selected Typeface to its native TextViews (header/footer/menu) via `applyTypefaceToReaderUI()` and also applies the runtime Typography to the overlay Compose controls. +- Selection rows (Settings): The right-side checkmark was replaced with a new, reusable `SingleChoiceOptionRow` composable (`app/src/main/java/com/nosferatu/launcher/ui/components/common/SingleChoiceOptionRow.kt`). Visual pattern: + - subtle selected-row background (semantic token `selectedRowBackground` in `AppColors`) + - 8dp left accent dot (uses `LocalAppColors.current.accent`) + - selected label displayed semibold + - full-row click target preserved and `semantics.selected` set for accessibility +- `AppColors` extended with `selectedRowBackground` (see `app/src/main/java/com/nosferatu/launcher/ui/AppColors.kt`). Use `LocalAppColors.current.selectedRowBackground` for subtle tints that adapt to Light/Cream/Dark themes. +- `SelectionSubMenu` (in `SettingsScreen.kt`) now preselects the option whose numeric value is nearest to the saved `currentValue` (nearest-floating logic), so custom in-reader adjustments map to the closest preset row on app start. +- `res/values/dimens.xml` has been added/expanded with tokens used by settings and reader UI (notable: `row_min_height = 56dp`, spacing tokens). Prefer `dimensionResource()` instead of hardcoded dp in Compose where practical. +- UI polish: `SectionHeader` composable exists for section titles and many settings rows now respect min-height, spacing tokens, and semantic colors. + +Build notes and gotchas: +- If you encounter the resource merger error "file name must end with .xml" when adding fonts, ensure the font file is placed in `res/font/` (font resources) and not `res/fonts/` (a mistaken folder that can trigger the error). The live repo fixes moved a misplaced font into `app/src/main/res/font/`. +- Readium/EPUB content: Readium's navigator does not guarantee that a custom `fontFamily` will be respected for EPUB body text. If you need EPUB-level font enforcement, plan for one of: + 1. Injecting CSS with an `@font-face` + applying it to the publication views (requires navigator support or fragment-level injection), or + 2. Embedding fonts inside the EPUB (editorial work per-publication). + +Guardrails for agents (added): +- When changing single-choice settings rows, use `SingleChoiceOptionRow` and the `selectedRowBackground` semantic token; do not restore trailing checkmarks or radio buttons without product sign-off. +- Do not hardcode color overlays per-theme; use `AppColors.selectedRowBackground` so the tint adapts to Light/Cream/Dark. +- When adding fonts: place files under `app/src/main/res/font/` and reference by resource name (current code expects `literata_regular`). If you change the resource name, update `MainActivity` and `ReaderActivity` runtime resolution accordingly. +- When touching `ReaderActivity.onCreate`, remember `setTheme()` must run before `setContentView()`. +- If you modify `SelectionSubMenu` selection logic, preserve the nearest-option behavior that maps custom user values to the closest preset. + +Quick file map for the recent edits: +- `app/src/main/java/com/nosferatu/launcher/library/LibraryConfig.kt` — added `fontChoice` persistence. +- `app/src/main/java/com/nosferatu/launcher/ui/AppColors.kt` — added `selectedRowBackground` and theme mappings. +- `app/src/main/java/com/nosferatu/launcher/ui/components/common/SingleChoiceOptionRow.kt` — new reusable row composable. +- `app/src/main/java/com/nosferatu/launcher/ui/screens/settings/SettingsScreen.kt` — replaced trailing checkmarks with `SingleChoiceOptionRow`; added nearest-option selection logic. +- `app/src/main/java/com/nosferatu/launcher/ui/MainActivity.kt` — dynamic Typography resolution for `fontChoice`. +- `app/src/main/java/com/nosferatu/launcher/reader/ReaderActivity.kt` — `applyTypefaceToReaderUI()` + overlay typography sync. +- `app/src/main/res/values/dimens.xml` — new tokens used throughout the UI. + +Acceptance test checklist for reviewers: +# AGENTS Guide - nosferatu-launcher + +## Scope +- Single-module Android app (`:app`) with Gradle Kotlin/Compose + Room + Readium. +- Main goal: local EPUB library sync + distraction-free reader UI. + +## Project map (start here) +- `app/src/main/java/com/nosferatu/launcher/NosferatuApp.kt`: app-level wiring (Room DB, parser strategies, scanner, repository). +- `app/src/main/java/com/nosferatu/launcher/repository/LibraryRepository.kt`: sync flow between filesystem and Room (now optionally persists TOC entries via `TocDao`). +- `app/src/main/java/com/nosferatu/launcher/library/LibraryViewModel.kt`: UI state orchestration via Flows. +- `app/src/main/java/com/nosferatu/launcher/library/LibraryConfig.kt`: persisted user settings (SharedPreferences `library_prefs`): root path, font size, line height, page margins, background mode, and `fontChoice`. +- `app/src/main/java/com/nosferatu/launcher/ui/AppColors.kt`: app-wide color theme helpers — `AppColors`, `LocalAppColors`, `bgColorFor()`, `contentColorFor()`, `appColorsFor()`. +- `app/src/main/java/com/nosferatu/launcher/ui/MainActivity.kt`: Compose home/library/settings shell + storage permission flow + background-mode theme wiring. +- `app/src/main/java/com/nosferatu/launcher/ui/screens/settings/SettingsChoices.kt`: settings composables including `BackgroundColorOption`. +- `app/src/main/java/com/nosferatu/launcher/reader/ReaderActivity.kt`: Readium reader, locator persistence, DB-first TOC loading, and TOC UI (bottom sheet). +- `app/src/main/java/com/nosferatu/launcher/ui/components/fontsettings/TextSettingsOverlay.kt`: in-reader font size / line-height panel (`ReaderTextSettings`, `SliderRow`). +- `app/src/main/java/com/nosferatu/launcher/data/Ebook.kt` and `EbookEntity.kt`: data model; `EbookEntity` now includes `tocImported: Boolean`. +- `app/src/main/java/com/nosferatu/launcher/data/database/AppDatabase.kt`: Room DB container — now includes `TocEntryEntity` and DB version is 5. +- `app/src/main/java/com/nosferatu/launcher/data/TocEntryEntity.kt`: new Room entity for persistent TOC rows. +- `app/src/main/java/com/nosferatu/launcher/data/TocDao.kt`: new DAO for TOC rows (`getForBook`, `insertAll`, `deleteForBook`, `replaceForBook`). +- `app/src/main/java/com/nosferatu/launcher/parser/TocParser.kt`: new parser to extract nav.xhtml / NCX TOC entries from EPUBs. +- `app/src/main/java/com/nosferatu/launcher/parser/BookParser.kt`: metadata parsing orchestration (existing). + +## Architecture and data flow (updated) +- Runtime DI is manual (no Hilt/Koin): `NosferatuApp` constructs `LibraryRepository`; activities create `LibraryViewModel` via `LibraryViewModelFactory`. +- Library sync path: `LibraryViewModel.scanBooks()` -> `LibraryRepository.syncLibrary()` -> `LibraryScanner.scanDirectory()` -> `BookParser.parseMetadata()` -> `BookDao.insertBook()` → optionally `TocParser.parse()` → `TocDao.replaceForBook()`. +- New behavior: during `syncLibrary()` the repository parses the book's TOC (EPUB nav.xhtml / NCX) and stores entries into `toc_entries` when `TocDao` is available. Books are marked with `tocImported=true` to avoid reprocessing unchanged files. + +## TOC Persistence (2026-04-05) +Summary: TOC extraction and persistence were added to improve Reader startup and TOC panel responsiveness. Key facts: +- Persistent TOC storage: `TocEntryEntity` + `TocDao` store flattened TOC rows per `bookId`. +- Parsing: `TocParser` extracts navigational items from `nav.xhtml` (preferred) and falls back to NCX where required. +- Sync behavior: `LibraryRepository.syncLibrary()` will skip TOC parsing for books already flagged with `tocImported=true` (and unchanged file timestamp). When persisted, the repository sets `tocImported=true` on the corresponding `EbookEntity`. +- Reader: `ReaderActivity.openTocPanel()` now prefers DB-sourced TOC entries (fast), with a runtime extraction fallback when DB entries are missing. +- Logging: extensive `Log.d/w/e` messages were added around TOC parsing, persistence, DB loads, matching statistics, and navigation actions to help debug TOC storage and rendering. + +## Build and developer workflows +Keep the same Gradle commands. Note: there are new unit tests; prefer running the test task when making parser/DAO changes: +```powershell +.\gradlew.bat clean +.\gradlew.bat assembleDebug +.\gradlew.bat test --console=plain +``` + +## Codebase-specific conventions (notes) +- DB uses Room with `fallbackToDestructiveMigration(true)` in `AppDatabase` (schema changes can wipe local data). The DB version was bumped to **5** to account for `tocImported` and `TocEntryEntity` additions. +- New schema fields: `EbookEntity.tocImported: Boolean` (default `false`). Update any code constructing `EbookEntity` (use `toEntity()` helper in `Ebook.kt`). +- New DAO query: `BookDao.isTocImported(path: String): Boolean?` is available to check whether a file's TOC has already been imported. +- Logging: maintain `Log` tags and diagnostic messages when modifying sync/reader code paths — these messages are intentionally fine-grained for diagnosing TOC parse/persist/match problems. + +## Integrations and boundaries +- No new external dependencies were added for TOC parsing — parser uses existing zip/OPF utilities and epublib helpers where applicable. + +## Guardrails for agents (updated) +- Do not assume formats beyond EPUB are enabled until parser strategies are wired in `NosferatuApp.kt`. +- If changing scan behavior, preserve current exclusion/depth semantics unless explicitly requested. +- **DB schema changes:** the DB version is now 5 and `fallbackToDestructiveMigration(true)` is still enabled. If you need to preserve user data, add a Room `Migration` from previous versions instead of relying on destructive migration. +- When touching `ReaderActivity.onCreate`, `setTheme()` **must** be called before `setContentView()`. +- When adding reading preferences, update both navigator initialization and `applyReaderPreferences()`. +- When adding or modifying TOC persistence or matching logic, keep these in mind: + - `LibraryRepository.syncLibrary()` now parses and persists TOC entries when `TocDao` is present and only for books where `tocImported` is false or the file changed. + - `ReaderActivity.openTocPanel()` prefers DB-sourced TOC and falls back to runtime extraction when needed. + - `BookDao.isTocImported(path)` is used to avoid redundant TOC work. + +## Recent TOC-related edits (quick file map) +- `app/src/main/java/com/nosferatu/launcher/data/TocEntryEntity.kt` — new Room entity for TOC rows. +- `app/src/main/java/com/nosferatu/launcher/data/TocDao.kt` — new DAO with `getForBook`, `insertAll`, `deleteForBook`, `replaceForBook`. +- `app/src/main/java/com/nosferatu/launcher/parser/TocParser.kt` — new EPUB TOC extraction (nav.xhtml / NCX). +- `app/src/main/java/com/nosferatu/launcher/repository/LibraryRepository.kt` — wired TOC parsing/persistence; added skip logic when `tocImported=true`; added detailed debug logging around parsing/persistence. +- `app/src/main/java/com/nosferatu/launcher/data/EbookEntity.kt` — added `tocImported: Boolean` field. +- `app/src/main/java/com/nosferatu/launcher/data/Ebook.kt` — `toEntity()` populates `tocImported=false` by default. +- `app/src/main/java/com/nosferatu/launcher/data/BookDao.kt` — added `isTocImported(path: String): Boolean?`. +- `app/src/main/java/com/nosferatu/launcher/reader/ReaderActivity.kt` — open TOC UI now loads from DB first and contains additional logging for loads, matches, and navigation. +- `app/src/test/java/.../TocDaoTest.kt` and `app/src/test/java/.../TocParserTest.kt` — unit tests added for DAO and parser (Robolectric/unit tests). + +## Acceptance test checklist for reviewers (TOC additions) +1. Run `.\gradlew.bat test --console=plain` — unit tests should pass (new DAO/parser tests included). +2. Run `.\gradlew.bat assembleDebug` to build the app. +3. Perform a full library sync with a sample EPUB that contains a `nav.xhtml`/NCX — verify that `toc_entries` table is populated and `books.tocImported` is set to `1` for the imported book. +4. Open a book in the Reader: the TOC bottom sheet should open quickly (DB-sourced) and navigating entries should jump to the expected sections. Logs contain debug lines about DB loads and matched/unmatched counts. +5. If you need to preserve existing user databases, implement a Room `Migration` from previous schema versions instead of relying on destructive migration. + +## Next steps & suggestions +- If product requires non-destructive upgrades, I can add a Room `Migration` from v4→v5 that adds `tocImported` and the `toc_entries` table without losing data. +- Add integration tests that run `LibraryRepository.syncLibrary()` against a temporary EPUB fixture and assert `toc_entries` + `books.tocImported` behavior. + +**Note:** This document is intentionally developer-facing. If you'd like, I can also add a short README section that describes how to inspect the `toc_entries` table (adb shell / Room inspector) and example log lines to look for when diagnosing TOC issues. diff --git a/GAPS.md b/GAPS.md new file mode 100644 index 0000000..498d2eb --- /dev/null +++ b/GAPS.md @@ -0,0 +1,106 @@ +GAPS: Confronto UI e passaggi per allineare MuPDF a `activity_reader` +===================================================================== + +Data: 2026-06-28 + +Obiettivo +--------- +Identificare le differenze grafiche e funzionali tra la UI reader dell'app (`app/src/main/res/layout/activity_reader.xml`) e la UI del modulo MuPDF (`lib/src/main/res/layout/document_activity.xml`), e definire i passaggi concreti necessari per rendere l'`Activity` di MuPDF visivamente equivalente alla `activity_reader`, mantenendo l'architettura e le scelte implementative di MuPDF (senza riscriverne il rendering bitmap/gestures). + +Sintesi rapida +--------------- +- `activity_reader.xml` (app) usa ConstraintLayout, supporta attributi di tema (`?attr/...`), un footer immersivo con progress bar e testo, status bar composable, ComposeView per i controlli font e token di tema condivisi. +- `document_activity.xml` (lib/MuPDF) è RelativeLayout con `PageView` custom e top/bottom bar XML, usa colori hard-coded e view IDs diversi; gestisce direttamente gestures e rendering in `PageView`. + +Principali gap grafici e semantici +--------------------------------- +1) Theming/colori +- activity_reader: usa attributi `?attr/readerBackgroundColor`, `?attr/readerTextColor`, `?attr/readerProgressBackgroundColor` (tema applicazione). Colori non hard-coded. +- document_activity: sfondi e barre con colori hard-coded (`#505050`, `#303030`, `#FFFFFF`). + +2) Struttura top/bottom bars e footer +- activity_reader ha `menu_top_bar`, `menu_bottom_bar`, `immersive_footer` con `ProgressBar` + `TextView` separati e visibilità controllata; usa constraint layout quindi il posizionamento è consistente su diversi dispositivi. +- document_activity usa `top_bar`, `action_bar`, `bottom_bar` all'interno di RelativeLayout con visibilità `gone` ed elementi con dimensioni e posizionamenti differenti. Mancano la `immersive_footer` e alcune view di menu presenti in `activity_reader`. + +3) Seek/progress styling +- activity_reader usa `ProgressBar` con tint via attribute e `SeekBar` con `?attr/readerTextColor`. +- document_activity ha `SeekBar` e `TextView` ma stili e drawable dei thumb/line sono differenti (seppur presenti). Il posizionamento del label non corrisponde al layout moderno. + +4) Iconografia e dimensioni +- activity_reader usa icone e dimensioni da `@dimen/` e tints via attr; document_activity incorpora drawables bianchi e bottoni con background `@drawable/button` senza supporto automatico per tint dinamico dal tema host. + +5) Fonts e tipografia +- activity_reader applica runtime Typeface/`Typography` (via `LibraryConfig.fontChoice`) e usa Compose overlay per le impostazioni; document_activity usa TextView con font system default, non legge `library_prefs` per `fontChoice` nativamente. + +6) Insets & safe area +- Entrambe gestiscono insets ma in modo differente: activity_reader usa ConstraintLayout + attr; document_activity applica `onApplyWindowInsetsListener` su `topBar` e `bottomBar`. + +7) Compose integration +- activity_reader integra una `ComposeView` per i controlli font in overlay; MuPDF rimane interamente XML/Java e non prevede Compose nella sua UI. + +8) IDs e punti di estensione +- Gli ID non corrispondono (es. `menu_page_text` vs `page_label`) — serve una mappatura per allineare comportamento e styling. + +Passaggi consigliati per allineamento grafico (mantendo MuPDF internals) +------------------------------------------------------------------------ +Di seguito una lista operativa, ordinata per priorità e con suggerimenti implementativi specifici. + +Fase 1 — Preparazione risorse e tematizzazione (basso rischio) +- A1. Estrarre colori hard-coded da `lib/src/main/res/layout/document_activity.xml` in `lib/src/main/res/values/colors.xml` e sostituire con riferimenti semantici (es. `@color/reader_bg`, `@color/reader_topbar_bg`, `@color/reader_text_on_bg`). +- A2. Aggiungere in `lib/src/main/res/values/attrs.xml` attributi personalizzati opzionali per il reader (es. `readerBackgroundColor`, `readerTextColor`, `readerProgressBackgroundColor`). +- A3. Modificare `document_activity.xml` per usare `?attr/readerBackgroundColor`/`?attr/readerTextColor` dove possibile (fall-back a `@color/reader_bg` se attr non fornito). +- A4. DocumentActivity: leggere `library_prefs` (SharedPreferences `library_prefs`) in `onCreate()` e applicare colori dinamicamente se l'app host non imposta gli attrs (compatibilità retrograda). + +Fase 2 — Allineamento struttura e view (moderato rischio) +- B1. Aggiungere alla layout `document_activity.xml` una sezione `immersive_footer` compatibile al footer di `activity_reader`: inserire `ProgressBar` orizzontale e `TextView` (id: `immersive_progress_bar`, `immersive_footer_text`) posizionati sopra il `bottom_bar` o al bottom della root. Usare gli stessi id per facilitarne il binding. +- B2. Rinominare o aggiungere alias id per view chiave per mappare i nomi usati nell'app host (es. mantenere `page_label` ma aggiungere `menu_page_text` come alias o aggiornare `DocumentActivity` per scrivere anche su `menu_page_text`). +- B3. Aggiornare `page_seekbar` styling: usare gli stessi drawable (o mappare a `@drawable/seek_line`/`seek_thumb` già presenti) e applicare `progressTint`/`thumbTint` via attributi. + +Fase 3 — Tipografia, icone e dimensioni (moderato/alto rischio) +- C1. Applicare supporto `fontChoice`: in `DocumentActivity.onCreate()` leggere `library_prefs.getFloat("font_choice", 0f)` e, quando è selezionata la font "literata" (o altra), usare `ResourcesCompat.getFont()` per costruire un `Typeface` e applicarla alle TextView `title_label`, `page_label`, `menu_book_title`, `menu_book_author`, `immersive_footer_text`. +- C2. Aggiornare i bottoni top/bottom (ImageButton/ImageView) per usare `android:tint="?attr/readerTextColor"` o applicare programmaticamente il tint al runtime in `onCreate()`. +- C3. Sostituire misure hard-coded con dimensioni da `lib/src/main/res/values/dimens.xml` (es. `reader_icon_size`, `reader_icon_padding`, `reader_progress_height`) per parità con `app`. + +Fase 4 — Comportamento visibilità e animazioni (alto rischio) +- D1. Allineare le regole di show/hide delle barre: modificare `DocumentActivity.toggleUI()` per rispettare la stessa logica di `activity_reader` (es. animazioni, visibilità del footer immersivo, status bar clock). Assicurarsi che la logica rispetti ancora input/tap/gestures implementati in `PageView`. +- D2. Mappare eventi navigatori (bookmark toggle / settings) alle stesse callback dell'app host dove applicabile (es. inviare broadcast/Intent o usare `ReturnToLibraryActivity` behavior esistente). + +Mappatura id / view raccomandata +-------------------------------- +- document_activity.xml `page_seekbar` → `menu_seek_bar` (allineare comportamenti) +- `page_label` → creare alias `menu_page_text` o aggiornare DocumentActivity a impostare entrambi +- Aggiungere `immersive_progress_bar` e `immersive_footer_text` (id identici a `activity_reader`) per render indistinguibile il footer. + +Modifiche Java consigliate (sintesi) +----------------------------------- +- Leggere `library_prefs` e `fontChoice` in `onCreate()` e applicare colore/font. +- Dopo il `setContentView()` eseguire `findViewById()` per i nuovi id aggiunti e collegare la logica già presente (es. aggiornare `pageLabel` e `pageSeekbar` con i nuovi riferimenti). +- Quando si disegna/aggiorna pagina, update anche `immersive_progress_bar` e `immersive_footer_text` per indicare progress/posizione corrente. +- Applicare tint su ImageView/ImageButton con `setColorFilter(readerTextColor)` quando attr non gestiti dal tema. + +Test e verifiche +----------------- +- Testare su dispositivi con density e dimensioni diverse: verifica riconciliazione di insets, safe-area e padding della `immersive_footer`. +- Verificare gesti (`PageView`) per non introdurre lag dopo l'aggiunta di View extra o animazioni. +- Verificare memory profile (bitmap allocations) su low-memory device. +- Verificare che `MainActivity.openBook()` e l'extra `ReturnToLibraryActivity` non vengano alterati. + +Rischi e trade-off +------------------ +- Spostare logica di theming e font nel modulo `lib` aumenta il coupling con l'app host. Soluzione: leggere preferenze da `library_prefs` ma mantenere il comportamento per default indipendente. +- Aggiungere Compose alla UI di `lib` richiede dipendenza su AndroidX Compose nel modulo `lib` — preferibile usare solo una `ComposeView` come bridge (minimo impatto) oppure mantenere tutto in XML. + +Esempio sequenza di lavoro consigliata +------------------------------------- +1. A1, A2, A3: estrazione colori + attrs + fallback via `library_prefs` (giorno 1). +2. B1, B2, B3: aggiunta `immersive_footer` e mappatura id; aggiornare `DocumentActivity` per bind (giorno 2). +3. C1..C3: tipografia, tint, dimens (giorno 3). +4. D1..D2: affinamento della visibilità e comportamento (giorno 4). +5. E1: (opzionale) add `ComposeView` per `ReaderTextSettings` e integrare preferenze. + +Deliverable di esempio che posso preparare +----------------------------------------- +- Patch che estrae colori hard-coded in `lib/src/main/res/values/colors.xml` e modifica `document_activity.xml` per usare `?attr/readerBackgroundColor` (con fallback a `@color/reader_bg`). +- Patch che aggiunge `immersive_footer` (layout+ids) e wiring minimo in `DocumentActivity` per aggiornare il progress bar. + +Se vuoi, applico la patch iniziale (A1+A2+A3) ora e poi procediamo con le fasi successive a step controllati. \ No newline at end of file diff --git a/MuPDF-DOCS.md b/MuPDF-DOCS.md new file mode 100644 index 0000000..ec0ce7d --- /dev/null +++ b/MuPDF-DOCS.md @@ -0,0 +1,156 @@ +MuPDF Module - Integration & UI Notes +===================================== + +Data: 2026-06-28 + +Scopo +----- +Documento tecnico di riferimento per il modulo `lib/` che contiene l'integrazione MuPDF (Java). Scopo: fornire una mappa rapida dei file, delle classi principali, delle risorse UI e delle linee guida pratiche per apportare modifiche alla UI del reader contenuto in `lib` in modo coerente con l'app principale. + +Posizione del modulo +--------------------- +- Modulo: `lib/` +- È incluso nel progetto root: `settings.gradle` contiene `include ':lib'`. +- `app/build.gradle` dichiara `api project(':lib')`. + +AndroidManifest +---------------- +- `lib/src/main/AndroidManifest.xml` dichiara l'`Activity` principale: `com.artifex.mupdf.mini.DocumentActivity`. + +Build +----- +- Il modulo usa classico packaging Android (sorgenti Java + risorse XML). Modifiche alle risorse o al codice richiedono un rebuild di `:lib` (la build di `:app` lo include automaticamente quando `api project(':lib')` è dichiarato). + +File e classi chiave +-------------------- +- `lib/src/main/java/com/artifex/mupdf/mini/DocumentActivity.java` + - Entry point UI del reader MuPDF fornito dal modulo. + - Gestisce: apertura documento da `Uri` (intent data), ricerca, outline, zoom, layout text-size (`layoutEm`), paginazione, preferenze locali, e comunicazione con `PageView`. + - Intent extras: legge l'extra `".ReturnToLibraryActivity"` per comportamento di ritorno. + - Preferenze locali: usa `getPreferences(Context.MODE_PRIVATE)` per chiavi locali come `layoutEm`, `fitPage`, e salva pagina corrente con `prefs.getInt(key, 0)` dove `key` è l'URI string. + - Metodi utili per estendere/modificare UI: `showSearch()`, `hideSearch()`, `toggleUI()`, `loadPage()`, `relayoutDocument()`, `applyInsets()`, `onPageViewSizeChanged()`. + +- `lib/src/main/java/com/artifex/mupdf/mini/PageView.java` + - Custom View che disegna la pagina (bitmap) e gestisce input touch/gestures (tap, long press, fling, pinch-zoom). + - Espone `setActionListener(DocumentActivity)` e richiama callback su `actionListener` per azioni: `gotoURI()`, `gotoPage()`, `toggleUI()`, `goForward()`, `goBackward()`, `onPageViewSizeChanged(...)`, `onPageViewZoomChanged(...)`. + - Punto centrale per modifiche del comportamento di navigazione tattile e rendering interattivo. + +- `lib/src/main/java/com/artifex/mupdf/mini/OutlineActivity.java` + - Attività semplice basata su `ListActivity` che mostra il sommario (outline) come lista. + +- `lib/src/main/java/com/artifex/mupdf/mini/Worker.java` + - Helper per eseguire task in background e pubblicare i risultati sull'UI thread. + +Risorse (layout, menu, drawable, strings) +----------------------------------------- +- Layout principale: `lib/src/main/res/layout/document_activity.xml` + - ID utili da conoscere per modifiche UI: + - `@id/page_view` (tipo `com.artifex.mupdf.mini.PageView`) - area di rendering + - `@id/background_layout` + - `@id/top_bar`, `@id/action_bar`, `@id/search_bar`, `@id/bottom_bar` + - `@id/title_label`, `@id/search_button`, `@id/search_text`, `@id/search_close_button` + - `@id/zoom_button`, `@id/layout_button`, `@id/outline_button` + - `@id/page_seekbar`, `@id/page_label` + - Notare: molti elementi hanno `android:visibility="gone"` di default e vengono mostrati da `DocumentActivity`. + +- Menu: `lib/src/main/res/menu/layout_menu.xml` (preset layout sizes 6pt..16pt) +- Stringhe: `lib/src/main/res/values/strings.xml` (hint ricerca, toast, password dialog) +- Drawable: icone e asset grafici in `lib/src/main/res/drawable/` (es. `ic_search_white_24dp.xml`, `button.xml`, `seek_thumb.xml`) + +Come l'app host invoca il reader +-------------------------------- +- L'apertura standard dal resto dell'app usa `MainActivity.openBook()` che crea un `Intent` indirizzato a `com.artifex.mupdf.mini.DocumentActivity` con `data = File(book.filePath).toUri()` e l'extra `".ReturnToLibraryActivity" = 1`. +- Questo significa che il flusso di produzione per l'apertura dei documenti passa al modulo `lib` e ad `DocumentActivity`. + +Linee guida per modifiche UI nel modulo `lib` +-------------------------------------------- +Queste raccomandazioni mirano a mantenere il modulo `lib` modificabile e ben integrato con l'app principale (`:app`) senza rompere l'integrazione. + +1) Preferire risorse stilizzate +- Rimuovere colori hard-coded in `document_activity.xml` (es. `android:background="#505050"`) e spostarli in `lib/src/main/res/values/colors.xml` come nomi semantici (es. `reader_bg`, `reader_topbar_bg`, `reader_text_on_bg`). +- Usare attributi di tema (`?attr/readerBackground`) se prevedi sovrascrittura dal modulo host. Questo facilita l'adattamento dei temi Light/Dark/Crema dall'app principale. + +2) Esporre opzioni via Intent extras +- Per meglio integrare `LibraryConfig` (impostazioni dell'app host), aggiungi supporto a Intent extras opzionali per controllare: `bg_mode` (int), `show_top_bar` (boolean), `initial_page` (int), `return_to_library` (boolean). DocumentActivity deve verificare prima gli extras e poi eventualmente cadere sul valore di default. +- Esempio di lettura preferenza condivisa (se non fornito nell'intent): + SharedPreferences appPrefs = getSharedPreferences("library_prefs", Context.MODE_PRIVATE); + float bgMode = appPrefs.getFloat("background_mode", 0f); + +3) Evitare duplicazione delle preferenze +- Attualmente `DocumentActivity` usa `getPreferences(Context.MODE_PRIVATE)` per preferenze locali. Se vuoi che il reader segua le stesse preferenze dell'app (es. sfondo, fontChoice), leggi `library_prefs` (shared preferences pubbliche dell'app) oppure accetta tali valori tramite intent extras. Questo mantiene il modulo `lib` indipendente ma configurabile. + +4) Separare layout e logica +- Evita di introdurre logica UI complessa direttamente in `DocumentActivity`: estrai helper/utility in nuove classi (es. `ReaderUiController`) per facilitare unit testing e mantenimento. +- Mantieni `PageView` concentrata sul rendering e sugli eventi tattili; la manipolazione dello stato visuale (mostra/nascondi barre, animazioni) può essere delegata. + +5) Integrazione con temi dell'app host +- Se l'app host usa `LibraryConfig.backgroundMode`, considera di fornire un mapping tra i valori (0/1/2) e i colori del modulo `lib`. +- Implementazione minimal-friendly: leggere `library_prefs` al `onCreate()` di `DocumentActivity` e applicare i colori corrispondenti ai container (`backgroundLayout.setBackgroundColor(...)`, `topBar.setBackgroundColor(...)`). + +6) Test e regressioni +- Poiché `PageView` gestisce gesti e rendering su bitmap, qualsiasi modifica alla misura dei container o padding può influire sulla navigazione; testare: + - pinch/zoom + - tap left/center/right per avanti/indietro/toggle UI + - scrolling/fling + - ricerca e highlighting (search hits) + +7) Icone e risorse +- Per aggiornare le icone nelle barre, sostituisci i drawable in `lib/src/main/res/drawable/`. Se vuoi condividere le stesse icone dell'app host, considera di usare la stessa resource qualifier e nomi concordati oppure passare le risorse via Intent (meno comune). + +8) Accessibilità e dimensioni +- `document_activity.xml` usa misure fisse (48dp per barra, 16/24sp text size). Se il prodotto richiede adattamento dinamico per dimensione testo o preferenze accessibilità, esponi `layoutEm` e/o dimensioni come risorse o preferenze facilmente sovrascrivibili. + +Esempi pratici (snippet) +------------------------- +- Leggere `background_mode` condiviso dall'app host: + +``` +SharedPreferences appPrefs = getSharedPreferences("library_prefs", Context.MODE_PRIVATE); +int bgMode = (int) appPrefs.getFloat("background_mode", 0f); +switch (bgMode) { + case 1: backgroundLayout.setBackgroundColor(Color.parseColor("#FFF8E1")); break; // crema + case 2: backgroundLayout.setBackgroundColor(Color.parseColor("#222222")); break; // dark + default: backgroundLayout.setBackgroundColor(Color.WHITE); break; +} +``` + +- Esporre extra intent per showTopBar: +``` +boolean showTopBar = getIntent().getBooleanExtra("SHOW_TOP_BAR", false); +if (showTopBar) topBar.setVisibility(View.VISIBLE); +``` + +Punti di attenzione +------------------- +- `PageView` manipola direttamente bitmaps: evitare memory leak (riciclare bitmap esistenti come già fatto). Se aggiungi embedding di fonts o immagini grandi, segui le stesse precauzioni di memoria. +- L'app host può comunicare comportamento al modulo `lib` in due modi: 1) tramite `Intent` extras all'apertura, 2) tramite `SharedPreferences` comuni (`library_prefs`). Scegli uno stile e documentalo in entrambe le parti. +- Se vuoi spostare il modulo verso Compose, valuta un wrapper che continui a esporre la `DocumentActivity` per compatibilità; la migrazione completa di `PageView` e rendering bitmap richiederà lavoro significativo. + +Testing rapido +-------------- +- Per provare le modifiche al modulo `lib`: + +```powershell +# dalla root del repo +.\gradlew.bat :app:assembleDebug +# Installare sul device/emulator e aprire un libro dalla UI +``` + +- Controllare i log con tag `MuPDF`, `MuPDF-Worker` per diagnostica. + +Risorse utili nel codice +------------------------ +- `lib/src/main/java/com/artifex/mupdf/mini/DocumentActivity.java` (logica UI principale) +- `lib/src/main/java/com/artifex/mupdf/mini/PageView.java` (rendering & gestures) +- `lib/src/main/java/com/artifex/mupdf/mini/OutlineActivity.java` +- `lib/src/main/res/layout/document_activity.xml` +- `lib/src/main/res/menu/layout_menu.xml` +- `lib/src/main/res/values/strings.xml` +- `lib/src/main/res/drawable/*` (icone + stili bottoni) + +Note finali +----------- +Questo documento è pensato come guida pratica per modifiche UI al modulo `lib` in modo che rimangano coerenti con il resto dell'app (`:app`). Se vuoi, posso: +- creare un esempio patch che estrae i colori hardcoded in `colors.xml` e legge `background_mode` dalle `library_prefs` per applicare il tema; +- aggiungere Intent-extras formali e aggiornare `MainActivity.openBook()` per passare `bg_mode` e `SHOW_TOP_BAR`. + diff --git a/PLAN-Template.md b/PLAN-Template.md new file mode 100644 index 0000000..d881de4 --- /dev/null +++ b/PLAN-Template.md @@ -0,0 +1,333 @@ +# PLAN.md + +## 1. Objective +Describe in 3-6 lines what must be implemented and why. +Include the product goal, not only the technical task. + +Example: +Implement bookmark navigation in the reader so users can save positions, open a bookmark list, and jump back quickly without introducing heavy search or performance regressions. + +--- + +## 2. Scope +List what is included and what is explicitly excluded. + +### In scope +- Feature A +- Feature B +- UI change C + +### Out of scope +- Full redesign +- Search/indexing +- Backend changes +- Unrelated refactors + +--- + +## 3. Product intent +Explain the UX or business logic the implementation must preserve. + +Questions this section should answer: +- What user problem is being solved? +- What should the feature feel like? +- What should the user understand immediately? +- What tradeoffs are intentional? + +--- + +## 4. Codebase context +Give the coding agent just enough architecture to work safely. + +Include: +- relevant modules +- relevant files +- current flow of data/state +- existing design system/theme hooks +- persistence layer involved +- known patterns already used in repo + +Example: +- Reader screen uses XML + Readium + Compose overlay +- Theme depends on `LibraryConfig.backgroundMode` +- `ReaderActivity.setTheme()` must be called before `setContentView()` + +--- + +## 5. Constraints +List hard technical constraints, performance constraints, compatibility constraints, and team rules. + +Examples: +- Must support old Android devices +- No expensive background processing +- No DB migration unless explicitly justified +- Preserve existing resume-reading behavior +- Must work in all themes + +--- + +## 6. Guardrails +State the “do not break” rules. + +Examples: +- Do not change scan behavior +- Do not alter persistence format without documenting it +- Do not remove existing logging +- Do not move theme initialization order +- Do not introduce heavy dependencies + +--- + +## 7. Current state +Describe the current implementation and what is wrong with it. + +Useful format: +- Current component: +- Current behavior: +- Problem: +- Impact: + +This helps the agent avoid guessing. + +--- + +## 8. Target behavior +Describe the final behavior from the user’s perspective. + +Use short bullet points: +- When user taps X, Y opens +- If state is active, icon becomes filled +- If data is empty, show empty state +- After success, show lightweight feedback + +This section should read like a functional contract. + +--- + +## 9. Implementation strategy +Explain the preferred technical direction before task breakdown. + +Include: +- suggested persistence choice +- suggested UI primitives +- data identity strategy +- preferred reuse points +- acceptable simplifications for V1 + +Example: +Use SharedPreferences for V1 bookmark persistence unless a Room model already exists and can be reused safely. + +--- + +## 10. Files to inspect first +Give the agent the smallest set of entry points. + +Example: +- `app/src/main/java/.../ReaderActivity.kt` +- `app/src/main/res/layout/activity_reader.xml` +- `app/src/main/java/.../LibraryConfig.kt` + +This speeds up execution and reduces wandering. + +--- + +## 11. Proposed file changes +Split into: +- files to modify +- files to create +- files not to touch + +### Modify +- `...` + +### Create +- `...` + +### Do not touch unless necessary +- `...` + +--- + +## 12. Data model / state model +If the feature introduces state or persistence, define it clearly. + +Include: +- fields +- ownership +- lifetime +- storage location +- identity rules + +Example: +Bookmark: +- bookId +- locatorJson +- href +- progression +- createdAt + +--- + +## 13. UI model +Describe the UI pieces that should exist. + +Example: +- `BookmarkToggleButton` +- `BookmarkListPanel` +- `TocPanel` +- `EmptyBookmarksState` + +For each, specify: +- purpose +- state inputs +- outputs/callbacks +- theme expectations + +--- + +## 14. Task breakdown +This is the most important section for coding agents. + +Split work into small ordered tasks. +Each task should be independently completable and testable. + +Recommended structure: + +### Task 1 — [short title] +**Goal** +What this task accomplishes. + +**Files** +- `...` + +**Work** +- step 1 +- step 2 +- step 3 + +**Done when** +- observable outcome 1 +- observable outcome 2 + +Repeat for each task. + +--- + +## 15. Suggested implementation order +Give the exact sequence. + +Example: +1. Add persistence layer +2. Add UI state lookup +3. Wire icon state +4. Add panel +5. Add navigation callbacks +6. Polish empty states + +This prevents random-order edits. + +--- + +## 16. Edge cases +List failure modes and expected behavior. + +Examples: +- No TOC available +- No bookmarks yet +- Invalid saved locator +- Book file missing +- Bookmark target no longer navigable +- Theme change while panel is open + +--- + +## 17. Performance requirements +Be explicit. + +Examples: +- No full text indexing +- No O(n) scan on every page turn if avoidable +- No expensive EPUB reparsing once publication is open +- UI updates must remain lightweight + +--- + +## 18. Accessibility requirements +Include only concrete items the agent can implement. + +Examples: +- contentDescription on icon buttons +- 48dp tap targets +- selected state not conveyed only by color +- readable contrast in all themes + +--- + +## 19. Testing plan +Define how the implementation should be validated. + +### Build checks +- `./gradlew assembleDebug` + +### Manual checks +- Open reader +- Tap chapter button +- Navigate to chapter +- Add bookmark +- Reopen reader +- Verify bookmark persists + +### Regression checks +- Existing resume-reading still works +- Theme switching still works + +--- + +## 20. Acceptance criteria +Write crisp yes/no conditions. + +Examples: +- Left button opens TOC +- Right button opens bookmark list +- Top-right button toggles bookmark +- Bookmark persists across restart +- No search is introduced +- Build passes + +--- + +## 21. Definition of Done +Broader than acceptance criteria. + +Include: +- Code compiles +- Feature works +- No obvious regression +- Logs remain useful +- New files are documented +- No dead code introduced +- Any tradeoffs/limitations are documented [web:280][web:286] + +--- + +## 22. Deliverables expected from the coding agent +Tell the agent what to return at the end. + +Example: +- summary of files changed +- summary of architectural choices +- known limitations +- commands run +- follow-up recommendations + +--- + +## 23. Open questions +Only include if there are still unresolved decisions. + +Examples: +- Should bookmarks be newest-first or location-first? +- Should TOC and bookmarks be separate panels or tabs? +- Should bookmark preview include snippet text? + +If these are unresolved, the agent should stop and ask before proceeding. \ No newline at end of file diff --git a/PLAN-UI-ALIGNMENT.md b/PLAN-UI-ALIGNMENT.md new file mode 100644 index 0000000..edb30fb --- /dev/null +++ b/PLAN-UI-ALIGNMENT.md @@ -0,0 +1,275 @@ +PLAN: UI Alignment — Make MuPDF reader visually match `activity_reader` +===================================================================== + +1. Objective +------------ +Allineare la UI del modulo `lib` (MuPDF: `DocumentActivity`) alla UI dell'app principale definita in `app/src/main/res/layout/activity_reader.xml`, in modo che il reader fornito da MuPDF risulti, a livello grafico e di comportamento visuale, indistinguibile dall'`activity_reader` dell'app. Il lavoro deve preservare l'implementazione interna di MuPDF (rendering bitmap, gestione gestures in `PageView`) e minimizzare il coupling distruttivo tra `lib` e `app`. + +2. Scope +-------- +### In scope +- Tema (colori/tints) e mapping dei token di tema da `LibraryConfig.backgroundMode` a `lib` colors. +- Estrarre risorse (`colors`, `dimens`, `attrs`) nel modulo `lib` e usare attributi di tema con fallback a SharedPreferences. +- Aggiungere footer immersivo (`ProgressBar` + `TextView`) e mappare id per allineare i binding. +- Applicare supporto runtime per `fontChoice` (Typeface) nelle TextView rilevanti. +- Aggiornare drawables/buttons per supportare `tint` dinamico dal tema host. +- Mappare comportamenti di visibilità delle barre e fornire hook per animazioni/overlay. +- Fornire istruzioni e test manuali per validazione grafica e regressioni funzionali. + +### Out of scope +- Riscrivere `PageView` (rendering/gestures) in Compose o cambiare il core rendering. +- Migrazioni DB o modifiche a `LibraryRepository`/parser. +- Aggiungere test automatizzati estesi (questo piano include come step opzionale la creazione di test manuali o unitari di binding minimi). + +3. Product intent +----------------- +- L'utente deve percepire la stessa esperienza visiva e feed visivi (footer, progress bar, titoli, icone) quando apre un libro, indipendentemente dal fatto che il reader sia MuPDF (`:lib`) o il navigator Readium. +- Mantenere la stabilità delle gesture e delle performance; evitare operazioni che introducano lag nel rendering delle pagine. +- Rendere configurabile il reader `lib` sia tramite Intent extras (apertura) sia tramite `library_prefs` per fallback, favorendo Intent extras per la configurazione puntuale. + +4. Codebase context +------------------- +- Modulo host: `app/` con `activity_reader.xml` (ConstraintLayout), Compose overlay (`font_controls_container`), `LibraryConfig` osservabile per `backgroundMode`, `fontChoice`. +- MuPDF module: `lib/` con `DocumentActivity.java`, `PageView.java`, layout `lib/src/main/res/layout/document_activity.xml`. +- Build: `settings.gradle` includes `:lib`, `app/build.gradle` depends on `project(':lib')`. +- Theme hooks: `app` uses `?attr/readerBackgroundColor`, etc.; `lib` currently hard-codes colori. +- Constraint: `DocumentActivity.setTheme()` behavior not applicable for `lib` (Activity uses full-screen with no theme attrs from host), but we can read `library_prefs` and apply colors programmatically or use attributes if host provides styled context. + +5. Constraints +-------------- +- Non cambiare il rendering/gestures di `PageView`. +- Non introdurre dipendenze Compose complete nel modulo `lib` (possono essere aggiunte solo come `ComposeView` bridge opzionale). +- Le modifiche devono compilare con l'attuale Gradle setup e non rompere il package `com.artifex.mupdf.mini` public API. +- Evitare modifiche breaking all'Intent contract (`ReturnToLibraryActivity`). + +6. Guardrails +------------- +- Non modificare file di business logic non-UI in `lib` (parser, worker, doc opener). +- Non rimuovere la gestione di memoria/bitmap attuale (riciclare bitmap è obbligatorio). +- Non aggiungere risorse con nomi che possano collidere con l'app host senza prefisso `mupdf_` o `reader_` nel modulo `lib`. + +7. Current state +---------------- +- Current component: `lib/src/main/res/layout/document_activity.xml` (RelativeLayout) + `DocumentActivity` (Java) + `PageView`. +- Current behavior: interactive PDF/EPUB rendering via MuPDF, top/bottom bars toggled, search, outline, page seek. +- Problem: visual styles (colori, dimensions, footer, tint, font) non allineati col `activity_reader` e non leggono le preferenze `LibraryConfig` dell'app host. +- Impact: UX incoerente quando l'app apre libri (muPdF sembra visivamente diverso), più costi di QA e di manutenzione. + +8. Target behavior +------------------ +- Quando l'app apre un libro con `MainActivity.openBook()`, la UI di `DocumentActivity` appare visivamente identica a `activity_reader`: stesso background, stessa tipografia per header/footer, stesso footer con progress bar e testo di posizione, icone e tints coerenti con il tema. +- Il comportamento di navigazione e gestures non cambia. +- L'app host può forzare il tema per `lib` inviando Intent extras (es. `bg_mode`, `SHOW_TOP_BAR`) o tramite `library_prefs` per default persistente. + +9. Implementation strategy +-------------------------- +- Minimal invasive strategy: introdurre risorse e hook nel modulo `lib` per leggere attributi di tema e preferenze condivise; applicare i cambiamenti programmaticamente in `DocumentActivity` subito dopo `setContentView()`. +- Preferire Intent extras per configurazioni runtime (miglior isolamento), con fallback su `library_prefs` per retrocompatibilità. +- Mantieni `PageView` intatto; delega UI visiva e animazioni a nuovi helper `ReaderUiController` integrato in `DocumentActivity`. + +10. Files to inspect first +-------------------------- +- `lib/src/main/java/com/artifex/mupdf/mini/DocumentActivity.java` +- `lib/src/main/res/layout/document_activity.xml` +- `lib/src/main/java/com/artifex/mupdf/mini/PageView.java` +- `app/src/main/res/layout/activity_reader.xml` +- `app/src/main/java/com/nosferatu/launcher/library/LibraryConfig.kt` + +11. Proposed file changes +------------------------- +### Modify +- `lib/src/main/res/layout/document_activity.xml` (use attr refs, add footer views, rename/add ids) +- `lib/src/main/java/com/artifex/mupdf/mini/DocumentActivity.java` (bind new ids, read Intent extras / library_prefs, apply colors/fonts/tint, update progress updates) +- `lib/src/main/res/drawable/*` (update button backgrounds to allow tint) +- `lib/src/main/res/values/strings.xml` (add any missing labels if needed) + +### Create +- `lib/src/main/res/values/colors.xml` (reader_bg, reader_topbar_bg, reader_text_on_bg, reader_progress_bg, ...) +- `lib/src/main/res/values/attrs.xml` (declare `readerBackgroundColor`, `readerTextColor`, `readerProgressBackgroundColor`) +- `lib/src/main/res/values/dimens.xml` (reader_icon_size, reader_icon_padding, reader_progress_height, spacing tokens) +- `lib/src/main/java/com/artifex/mupdf/mini/ReaderUiController.java` (helper to encapsulate UI bindings and animations) + +### Do not touch unless necessary +- `lib/src/main/java/com/artifex/mupdf/mini/PageView.java` (rendering/gestures) +- `lib/src/main/java/com/artifex/mupdf/mini/Worker.java` (background queue) + +12. Data model / state model +--------------------------- +No new persistence required. Configuration sources: +- Intent extras (transient per open): `bg_mode` (int), `SHOW_TOP_BAR` (boolean), `initial_page` (int), `font_choice` (int) +- SharedPreferences fallback: `library_prefs` keys `background_mode`, `font_choice` (existing) + +13. UI model +------------ +- `ReaderUiController` responsibilities: + - Bind views: topBar, actionBar, immersiveFooter (progress + text), menuBottomBar, pageSeekbar, pageLabel. + - Apply theme tokens (colors, tints) and fonts. + - Provide `show()`/`hide()`/`toggle()` with optional animations respecting `PageView` gestures. + - Update progress and page label on page changes. + +14. Task breakdown +------------------ +### Task 1 — Extract colors & attrs (A1, A2, A3) +Goal +- Remove hard-coded colors and expose theme attrs and color resources. +Files +- `lib/src/main/res/layout/document_activity.xml` +- create `lib/src/main/res/values/colors.xml` +- create `lib/src/main/res/values/attrs.xml` +Work +- Add `colors.xml` with semantic color names. +- Add `attrs.xml` declaring `readerBackgroundColor`, `readerTextColor`, `readerProgressBackgroundColor`. +- Update `document_activity.xml` to reference `?attr/...` where feasible and fallback to `@color/reader_bg`. +Done when +- `DocumentActivity` shows UI using colors from resources/attrs rather than hard-coded values. + +### Task 2 — Add dimens & drawables adjustments (C3) +Goal +- Harmonize dimensions and make button drawables tintable. +Files +- `lib/src/main/res/values/dimens.xml` +- `lib/src/main/res/drawable/button.xml` and icons +Work +- Create `dimens.xml` with sizes matching `app` tokens. +- Update `button.xml` to use tintable shapes (use `android:tint` support or `tint` attribute in ImageButton usage). +Done when +- Buttons and icon sizes match application style and respond to tint color. + +### Task 3 — Add immersive footer and id mapping (B1, B2, B3) +Goal +- Add `immersive_footer` with `immersive_progress_bar` and `immersive_footer_text`. Map ids to match `activity_reader`. +Files +- `lib/src/main/res/layout/document_activity.xml` +- `lib/src/main/java/com/artifex/mupdf/mini/DocumentActivity.java` +Work +- Insert footer layout at bottom of `document_activity.xml` using existing RelativeLayout anchors. +- After `setContentView()`, `findViewById()` for new ids and wire progress updates from page load code. +- Ensure `page_seekbar` uses same drawables and max/progress logic as app seek bar. +Done when +- Footer appears and updates during navigation with the same layout as `activity_reader`. + +### Task 4 — Implement ReaderUiController and bind in DocumentActivity (4.X) +Goal +- Encapsulate UI logic into `ReaderUiController` to keep `DocumentActivity` focused. +Files +- `lib/src/main/java/com/artifex/mupdf/mini/ReaderUiController.java` +- Update `DocumentActivity.java` to construct and use `ReaderUiController`. +Work +- Implement methods: `applyTheme(int bgMode, int fontChoice)`, `updateProgress(int page, int pageCount)`, `toggleUI()`. +- Ensure any show/hide respects `PageView` state and does not disable gesture regions. +Done when +- UI code is moved into controller and `DocumentActivity` calls controller methods on page events. + +### Task 5 — FontChoice support (C1) +Goal +- Read `font_choice` from Intent extras or `library_prefs` and apply Typeface to relevant TextViews. +Files +- `DocumentActivity.java`, `ReaderUiController.java` +Work +- Use `ResourcesCompat.getFont(context, resId)` if `literata` packaged; fallback to default Typeface. +- Apply to `titleLabel`, `pageLabel`, `menu_book_title`, `menu_book_author`, `immersive_footer_text`. +Done when +- On fontChoice change, the UI text reflects chosen font. + +### Task 6 — Tint and icons (C2) +Goal +- Apply `readerTextColor` as tint to icon ImageViews +Files +- `DocumentActivity.java`, drawables modifications +Work +- Set `imageView.setColorFilter(readerTextColor)` in controller or use `android:tint` in XML where supported. +Done when +- Icons match theme color at runtime. + +### Task 7 — Behavior parity and animations (D1, D2) +Goal +- Align toggle/show-hide behavior and hook bookmark/settings actions to host flows where applicable. +Files +- `DocumentActivity.java`, `ReaderUiController.java` +Work +- Update `toggleUI()` to mirror the host animations/visibility states; wire `btn_bookmark_toggle` to existing actions (if host expects broadcast or repo updates, provide hooks). +Done when +- UI toggles visually like `activity_reader` and bookmark/settings buttons trigger appropriate callbacks. + +### Task 8 — Optional Compose overlay (E1) +Goal +- Add a `ComposeView` for `ReaderTextSettings` if desired. +Files +- `document_activity.xml` (add ComposeView), possible small Gradle changes +Work +- Add `ComposeView` with id `font_controls_container` and populate with `ReaderTextSettings` via `setContent` using the same `LibraryConfig` (read via fallback or passed as configuration). +Done when +- Compose overlay shows and modifies preferences used by `DocumentActivity`. + +15. Suggested implementation order +--------------------------------- +1. Task 1 (A1-A3): Colors & attrs +2. Task 2: Dimens & drawables +3. Task 3: Footer & id mapping +4. Task 4: ReaderUiController & wiring +5. Task 5: FontChoice +6. Task 6: Icon tint +7. Task 7: Behavior parity and polish +8. Task 8: Optional Compose overlay + +16. Edge cases +-------------- +- No font resource found for chosen `fontChoice` → fallback to default system Typeface. +- Host does not provide `library_prefs` (rare in test contexts) → use resource defaults. +- Large document opening memory pressure → avoid allocating large temporary bitmaps in UI-binding code. +- Intent with `file://` URIs not allowed by platform → respect existing DocumentActivity behavior and error messages. + +17. Performance requirements +---------------------------- +- Do not allocate large objects on UI thread. All page decoding remains in `Worker` as today. +- UI updates (text, progress) must be O(1) per page change and not trigger full re-layouts. + +18. Accessibility requirements +------------------------------ +- Ensure `contentDescription` present for icon buttons (use existing strings or add new ones to `strings.xml`). +- Maintain 48dp touch targets for ImageViews (use dimens tokens). +- Ensure color contrast sufficient across themes. + +19. Testing plan +---------------- +### Build checks +- `.\gradlew.bat :app:assembleDebug` + +### Manual checks +- Open a sample document via UI. Verify visual parity of background, header/footer, progress bar and icon tints compared to `activity_reader`. +- Test tap/gesture navigation: left tap -> backward, middle -> toggle UI, right -> forward. +- Change `library_prefs.background_mode` and reopen document; verify colors applied. +- Switch `fontChoice` and verify Typeface applied. + +### Regression checks +- Ensure `PageView` gestures unaffected. +- Ensure `ReturnToLibraryActivity` behavior unchanged. +- Verify memory usage during page navigation on low-memory emulator. + +20. Acceptance criteria +---------------------- +- Visual parity: Background, header/footer, progress bar and icon tints match `activity_reader` in all three `background_mode` values. +- No regression in gestures or navigation performance. +- `MainActivity.openBook()` still works with existing Intent contract. +- Font choice and theme color apply at open-time and after preference changes. + +21. Definition of Done +---------------------- +- Code compiles and app assembles. +- Manual acceptance tests pass. +- Changes limited to `lib` resources and `DocumentActivity` helper with non-invasive approach. +- New resources documented in `MuPDF-DOCS.md` and change summary included in a PR description. + +22. Deliverables expected from the coding agent +---------------------------------------------- +- Patch/branch implementing Task 1 (colors/attrs) and Task 3 (immersive footer) as an initial PR. +- `PLAN-UI-ALIGNMENT.md` (this document) included in repo. +- Short README snippet in PR describing how to validate visually. + +23. Open questions +------------------ +- Prefer Intent extras or `library_prefs` as primary configuration channel? Recommendation: prefer Intent extras (explicit, per-open) and use `library_prefs` as fallback. +- Do you want the optional Compose overlay (Task 8) included in v1 or postponed? + + + diff --git a/TECH-STATUS.md b/TECH-STATUS.md new file mode 100644 index 0000000..b34f823 --- /dev/null +++ b/TECH-STATUS.md @@ -0,0 +1,125 @@ +# TECH-STATUS + +Data: 2026-06-28 + +Questo documento fornisce un'analisi tecnica estensiva dello stato attuale dell'applicazione `nosferatu-launcher`, basata sul codice sorgente e sulla documentazione presente nella repo. + +## Executive summary + +- Progetto single-module Android (Kotlin + Jetpack Compose + Room). Il flusso di apertura dei documenti in produzione utilizza MuPDF (modulo `:lib`) tramite `com.artifex.mupdf.mini.DocumentActivity`; il codice include anche componenti Readium per funzionalità EPUB avanzate. +- Architettura semplice e manuale: `NosferatuApp` costruisce i componenti (Room, repository, scanner, parser); non è presente DI framework (no Hilt/Koin). +- Implementazione robusta per EPUB: parsing metadati, gestione copertine, persistenza TOC (nuova). Il reader principale è MuPDF (modulo `:lib`) e `ReaderActivity` fornisce un'integrazione Readium alternativa/avanzata (navigator, CSS injection). +- Rischi principali: migrazioni Room distruttive (fallbackToDestructiveMigration), gestione permessi storage complessa, font/compatibilità (in particolare per l'approccio di iniezione CSS), mancanza di completezza dei parser per PDF/CBZ. + +## Architettura e flusso dati + +- Entrypoint runtime: `NosferatuApp` costruisce `LibraryRepository`. Le Activity creano `LibraryViewModel` tramite `LibraryViewModelFactory`. +- Sync library: `LibraryViewModel.scanBooks()` → `LibraryRepository.syncLibrary()` → `LibraryScanner.scanDirectory()` → `BookParser.parseMetadata()` → `BookDao.insertBook()` → opzionalmente `TocParser.parse()` → `TocDao.replaceForBook()`. +-- Reader: l'apertura standard dalla UI (`MainActivity.openBook()`) avvia MuPDF `DocumentActivity` (`com.artifex.mupdf.mini.DocumentActivity`) dal modulo `:lib`. Il progetto contiene anche `ReaderActivity` che inizializza un navigator Readium (`EpubNavigatorFragment`) e fornisce funzionalità avanzate per EPUB (percorsi alternativi o test). +- Configurazioni utente: `LibraryConfig` (SharedPreferences `library_prefs`) espone stato osservabile (`mutableFloatStateOf`, `mutableStateOf`) per Compose. + +## Moduli principali + +- app (UI shell + settings): `MainActivity.kt`, composables per libreria e impostazioni. +- Library sync: `LibraryRepository.kt`, `LibraryScanner.kt`, `LibraryViewModel.kt`. +- Parser: `BookParser.kt` (strategy-based), `ParserStrategy` implementazioni (EPUB è mappato), `TocParser.kt` per TOC extraction. +- Reader: `ReaderActivity.kt`, `EpubNavigatorFactory` + `EpubPreferences`, CSS injector e fallback per iniezione font. + - MuPDF module: `:lib` (incluso come `project(':lib')` in `app/build.gradle`) che fornisce `com.artifex.mupdf.mini.DocumentActivity` ed è usato come reader principale per l'apertura dei documenti. +- Persistence: Room (`AppDatabase.kt`), entità `EbookEntity` (ora con `tocImported`), `TocEntryEntity`, DAO `BookDao`, `TocDao`. +- UI theme: `AppColors.kt`, `LocalAppColors`, gestione `backgroundMode` (0: light, 1: sepia, 2: dark), `SingleChoiceOptionRow`/`SelectionSubMenu`. + +## Implementazione chiave e osservazioni + +- `LibraryConfig` (app/src/main/java/com/nosferatu/launcher/library/LibraryConfig.kt) + - Conserva `backgroundMode`, `fontSizeScale` (default 0.85f), `fontChoice`, `forceBold`, `volumeKeys`, `invertTouches`. + - Espone API `updateBackgroundMode()`, `updateFontChoice()`, ecc. Usa SharedPreferences e state osservabile per Compose. + +- Theming: `AppColors.kt` mappa il `backgroundMode` su palette Compose e fornisce `selectedRowBackground` per le righe selezionate. + +- `MainActivity` (app/src/main/java/.../MainActivity.kt) + - UI Compose app-wide; costruisce dinamicamente la `Typography` tentando di risolvere una risorsa font `literata_regular` in `res/font`. + - Richiede permessi storage (gestione Android 11+ con `MANAGE_EXTERNAL_STORAGE` fallback). + - Nota: crea localmente un `LibraryConfig` via `remember { LibraryConfig(this) }` — possibile incongruenza rispetto all'idea di usare l'istanza applicazione-scoped (verificare coerenza con `NosferatuApp`). + - `openBook()` avvia MuPDF `DocumentActivity` (`com.artifex.mupdf.mini.DocumentActivity`) passando un file URI: questo rende il flusso principale di apertura dei libri basato sul modulo `:lib`. + +- `ReaderActivity` (app/src/main/java/.../reader/ReaderActivity.kt) + - Chiama `setTheme()` prima di `setContentView()` (corretto) e inizializza Readium. + - Applica ottimizzazioni per dispositivi a bassa memoria (disabilita publisher styles, riduce fontWeight, ecc.). + - Implementa un meccanismo robusto di iniezione CSS/font: 1) cerca asset `assets/fonts/literata_regular.ttf`; 2) prova `res/font/literata_regular`; 3) scrive su `files/` e riferisce con file://; 4) fallback log e tentativi via reflection per chiamare `evaluateJavascript` sul fragment/navigator. + - TOC: preferisce caricare TOC da DB (persisted `TocEntryEntity`) e ha fallback runtime se DB vuoto. + +- `BookParser` e strategie + - `BookParser.parseMetadata` determina `EbookFormat` da estensione e invoca `ParserStrategy` corrispondente. Se non esiste strategy, ritorna un `Ebook` minimo e logga. + - `EbookFormat.fromExtension` può lanciare eccezione su estensioni sconosciute — `LibraryScanner.extractMetadata` cattura eccezioni e ritorna null per saltare file non-parsabili. + +- Persistence / DB + - Room con `fallbackToDestructiveMigration(true)` (AppDatabase) — DB version 5 attuale (tocImported + toc_entries aggiunti). + - Nuova tabella `toc_entries` + `TocDao` per velocizzare l'apertura TOC nel reader. + +## Test e quality + +- Ci sono test unitari aggiunti per `TocDao` e `TocParser`. Verificare `app/src/test` per copertura. +- Non sono presenti test strumentati estesi; mancano integrazione end-to-end per `syncLibrary()` ↔ reader. +- Raccomandazione: aggiungere test di integrazione che eseguono `LibraryRepository.syncLibrary()` su fixture EPUB e validano persistenza TOC + `tocImported`. + +## Known issues, rischi e technical debt + +1. Migrazioni DB distruttive: `fallbackToDestructiveMigration(true)` implica perdita dati su aggiornamenti di schema. Se si vuole preservare dati reali, è necessario aggiungere `Migration` da v4→v5. +2. Permessi storage: uso di `MANAGE_EXTERNAL_STORAGE` e logica Android 11+ aumenta la superficie di rischio e richiede gestione UX chiara per gli utenti. +3. Font/Readium: Readium potrebbe non rispettare `fontFamily` per il body; iniezione CSS è fragile e usa reflection ed heuristics — fonte di fragilità e di bug su diversi dispositivi/vers. navigator. +4. Parser incompleti: `EbookFormat` include PDF/CBZ, ma le `ParserStrategy` potrebbero non essere registrate per questi formati — scanner può scoprire file ma parsing non garantito. +5. Hardcoded strings in Kotlin (italiano) limitano localizzazione. +6. Costruzione `LibraryConfig` duplicata: `MainActivity` crea un'istanza locale invece di riutilizzare potenzialmente `NosferatuApp.libraryConfig` (incoerenza da verificare). +7. Iniezioni JS/CSS complesse nella `ReaderActivity` (reflection) — difficile da testare e soggetta a regressioni. +8. Gestione memory pressure: ci sono ottimizzazioni (fontSize default 0.85, disable publisher styles) ma servono test su dispositivi reali per validarne l'efficacia. +9. Build fragility su Windows: file-locking `R.jar` noto; istruzioni esistenti ma attenzione in CI Windows. + +## Raccomandazioni prioritarie (breve) + +1. Aggiungere Room `Migration` non-distruttiva da v4→v5 oppure fornire script di migrazione e avviso agli utenti. +2. Consolidare `LibraryConfig` come singola istanza condivisa (application-scoped) e usare quella in `MainActivity`/`ReaderActivity` per garantire consistenza runtime. +3. Externalizzare stringhe testuali nelle risorse `strings.xml` per localizzazione. +4. Limitare l'uso di reflection per la CSS injection; investigare API ufficiali del navigator o richiedere feature upstream a Readium. +5. Creare test di integrazione per `LibraryRepository.syncLibrary()` con fixture EPUB e per `TocParser`. +6. Documentare chiaramente le aspettative sui font (nome risorsa `literata_regular`, percorso `res/font` o `assets/fonts`) e semplificare l'installazione per QA. +7. Decidere policy su supporto PDF/CBZ: 1) implementare ParserStrategy, o 2) filtrare scanner per EPUB-only. +8. Aggiungere CI (es. GitHub Actions) che lanci `./gradlew assembleDebug` e i test unitari su Linux; aggiungere matrix Windows solo se necessario. + +## Next steps operativi suggeriti + +- (A) Implementare Migration Room v4→v5 (alto impatto, alto priorità). +- (B) Aggiungere integrazione test per sync+TOC (medio impatto). +- (C) Consolidare `LibraryConfig` e rimuovere istanze duplicate (basso impatto ma migliora coerenza). +- (D) Rivedere font-embedding: prefer asset o `res/font` con dimensione limitata; evitare embed base64 se > 800KB. +- (E) Audit permessi storage e UX di richiesta permessi (Android 11+). + +## Quick checklist per validazione manuale + +- Build: + +```powershell +.\gradlew.bat clean +.\gradlew.bat assembleDebug +.\gradlew.bat test --console=plain +``` + +- Test funzionale minimo: + - Effettuare `scanBooks()` da UI o chiamare `LibraryViewModel.scanBooks()`; verificare che `toc_entries` sia popolata per EPUB con `nav.xhtml`. + - Aprire libro dalla UI: l'apertura standard usa MuPDF `DocumentActivity`; verificare anche `ReaderActivity` (Readium) per percorsi alternativi e che la TOC (quando persistita) carichi dal DB e la navigazione salti alle posizioni attese. + - Controllare i log con tag `LibraryRepository`, `ReaderActivity`, `BookParser` per messaggi diagnostici. + +## File rilevanti (mappa rapida) + +- `app/src/main/java/com/nosferatu/launcher/NosferatuApp.kt` — wiring app-level +- `app/src/main/java/com/nosferatu/launcher/repository/LibraryRepository.kt` — sync + TOC persistence +- `app/src/main/java/com/nosferatu/launcher/library/LibraryConfig.kt` — preferenze utente osservabili +- `app/src/main/java/com/nosferatu/launcher/parser/BookParser.kt` — parsing metadata +- `app/src/main/java/com/nosferatu/launcher/parser/TocParser.kt` — TOC extraction +- `app/src/main/java/com/nosferatu/launcher/reader/ReaderActivity.kt` — Readium integration + CSS/font injection +- `app/src/main/java/com/nosferatu/launcher/ui/AppColors.kt` — tema & semantic tokens + - `lib/` — MuPDF module (project `:lib`) che fornisce `com.artifex.mupdf.mini.DocumentActivity`, usato per l'apertura predefinita dei documenti dalla UI. +- `app/src/main/java/com/nosferatu/launcher/data/*` — entità Room, DAO, `Ebook.kt`, `EbookEntity.kt` + +--- + +Se vuoi, aggiorno subito la checklist per i task prioritari (Migration, test d'integrazione) e creo le issue o le PR template per procedere. In alternativa posso generare un piano di implementazione dettagliato per il punto (A) Migration. diff --git a/app/build.gradle b/app/build.gradle index bd65357..5c2539b 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -60,6 +60,8 @@ android { } dependencies { + api project(':lib') + implementation(platform(libs.androidx.compose.bom)) implementation libs.androidx.runtime diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index c9ba42d..aaf8f51 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -1,20 +1,22 @@ - + xmlns:tools="http://schemas.android.com/tools"> + tools:ignore="AllFilesAccessPolicy,ScopedStorage" /> + android:persistent="true" + android:debuggable="true" + tools:ignore="HardcodedDebugMode"> + diff --git a/app/src/main/assets/fonts/literata_regular.ttf b/app/src/main/assets/fonts/literata_regular.ttf new file mode 100644 index 0000000..1cd5bc5 Binary files /dev/null and b/app/src/main/assets/fonts/literata_regular.ttf differ diff --git a/app/src/main/ic_launcher-playstore.png b/app/src/main/ic_launcher-playstore.png new file mode 100644 index 0000000..2c6bec7 Binary files /dev/null and b/app/src/main/ic_launcher-playstore.png differ diff --git a/app/src/main/java/com/nosferatu/launcher/NosferatuApp.kt b/app/src/main/java/com/nosferatu/launcher/NosferatuApp.kt index ae6c1f9..ae3d827 100644 --- a/app/src/main/java/com/nosferatu/launcher/NosferatuApp.kt +++ b/app/src/main/java/com/nosferatu/launcher/NosferatuApp.kt @@ -18,12 +18,14 @@ package com.nosferatu.launcher import android.app.Application +import android.webkit.WebView import com.nosferatu.launcher.data.EbookFormat import com.nosferatu.launcher.data.database.AppDatabase import com.nosferatu.launcher.library.* import com.nosferatu.launcher.parser.BookParser import com.nosferatu.launcher.parser.EpubParser import com.nosferatu.launcher.repository.LibraryRepository +import org.readium.r2.navigator.BuildConfig class NosferatuApp : Application() { @@ -48,7 +50,13 @@ class NosferatuApp : Application() { bookDao = database.bookDao(), scanner = scanner, coverManager = coverManager, - libraryConfig = libraryConfig + libraryConfig = libraryConfig, + tocDao = database.tocDao() ) } + + override fun onCreate() { + super.onCreate() + WebView.setWebContentsDebuggingEnabled(true) + } } \ No newline at end of file diff --git a/app/src/main/java/com/nosferatu/launcher/data/BookDao.kt b/app/src/main/java/com/nosferatu/launcher/data/BookDao.kt index 8bbf4b2..674c8ab 100644 --- a/app/src/main/java/com/nosferatu/launcher/data/BookDao.kt +++ b/app/src/main/java/com/nosferatu/launcher/data/BookDao.kt @@ -32,6 +32,9 @@ interface BookDao { @Query("SELECT * FROM books WHERE filePath = :absolutePath") suspend fun getBookByPath(absolutePath: String): EbookEntity? + @Query("SELECT tocImported FROM books WHERE filePath = :path") + suspend fun isTocImported(path: String): Boolean? + @Query("SELECT filePath FROM books") suspend fun getAllFilePaths(): List diff --git a/app/src/main/java/com/nosferatu/launcher/data/Ebook.kt b/app/src/main/java/com/nosferatu/launcher/data/Ebook.kt index 31c6e12..e191df0 100644 --- a/app/src/main/java/com/nosferatu/launcher/data/Ebook.kt +++ b/app/src/main/java/com/nosferatu/launcher/data/Ebook.kt @@ -16,7 +16,8 @@ data class Ebook( format = this.format.name, coverPath = coverPath, lastLocationJson = null, - progression = 0.0 + progression = 0.0, + tocImported = false ) } } diff --git a/app/src/main/java/com/nosferatu/launcher/data/EbookEntity.kt b/app/src/main/java/com/nosferatu/launcher/data/EbookEntity.kt index 5848059..5654571 100644 --- a/app/src/main/java/com/nosferatu/launcher/data/EbookEntity.kt +++ b/app/src/main/java/com/nosferatu/launcher/data/EbookEntity.kt @@ -14,4 +14,5 @@ data class EbookEntity( val coverPath: String? = null, val lastLocationJson: String? = null, val progression: Double = 0.0, + val tocImported: Boolean = false ) \ No newline at end of file diff --git a/app/src/main/java/com/nosferatu/launcher/data/TocDao.kt b/app/src/main/java/com/nosferatu/launcher/data/TocDao.kt new file mode 100644 index 0000000..4026084 --- /dev/null +++ b/app/src/main/java/com/nosferatu/launcher/data/TocDao.kt @@ -0,0 +1,28 @@ +package com.nosferatu.launcher.data + +import androidx.room.Dao +import androidx.room.Insert +import androidx.room.OnConflictStrategy +import androidx.room.Query +import androidx.room.Transaction + +@Dao +interface TocDao { + + @Query("SELECT * FROM toc_entries WHERE bookId = :bookId ORDER BY position ASC") + suspend fun getForBook(bookId: Long): List + + @Insert(onConflict = OnConflictStrategy.REPLACE) + suspend fun insertAll(entries: List) + + @Query("DELETE FROM toc_entries WHERE bookId = :bookId") + suspend fun deleteForBook(bookId: Long) + + @Transaction + suspend fun replaceForBook(bookId: Long, entries: List) { + deleteForBook(bookId) + if (entries.isNotEmpty()) { + insertAll(entries) + } + } +} diff --git a/app/src/main/java/com/nosferatu/launcher/data/TocEntryEntity.kt b/app/src/main/java/com/nosferatu/launcher/data/TocEntryEntity.kt new file mode 100644 index 0000000..248adce --- /dev/null +++ b/app/src/main/java/com/nosferatu/launcher/data/TocEntryEntity.kt @@ -0,0 +1,18 @@ +package com.nosferatu.launcher.data + +import androidx.room.Entity +import androidx.room.Index +import androidx.room.PrimaryKey + +@Entity( + tableName = "toc_entries", + indices = [Index(value = ["bookId"])]) +data class TocEntryEntity( + @PrimaryKey(autoGenerate = true) val id: Long = 0, + val bookId: Long, + val title: String?, + val href: String?, + val locatorJson: String?, + val position: Int = 0, + val createdAt: Long = System.currentTimeMillis(), +) diff --git a/app/src/main/java/com/nosferatu/launcher/data/database/AppDatabase.kt b/app/src/main/java/com/nosferatu/launcher/data/database/AppDatabase.kt index 2bd888f..dfdeca4 100644 --- a/app/src/main/java/com/nosferatu/launcher/data/database/AppDatabase.kt +++ b/app/src/main/java/com/nosferatu/launcher/data/database/AppDatabase.kt @@ -6,10 +6,13 @@ import androidx.room.Room import androidx.room.RoomDatabase import com.nosferatu.launcher.data.BookDao import com.nosferatu.launcher.data.EbookEntity +import com.nosferatu.launcher.data.TocDao +import com.nosferatu.launcher.data.TocEntryEntity -@Database(entities = [EbookEntity::class], version = 3, exportSchema = false) +@Database(entities = [EbookEntity::class, TocEntryEntity::class], version = 5, exportSchema = false) abstract class AppDatabase : RoomDatabase() { abstract fun bookDao(): BookDao + abstract fun tocDao(): TocDao companion object { @Volatile diff --git a/app/src/main/java/com/nosferatu/launcher/library/LibraryConfig.kt b/app/src/main/java/com/nosferatu/launcher/library/LibraryConfig.kt index 2124a73..d794c09 100644 --- a/app/src/main/java/com/nosferatu/launcher/library/LibraryConfig.kt +++ b/app/src/main/java/com/nosferatu/launcher/library/LibraryConfig.kt @@ -20,6 +20,7 @@ class LibraryConfig(private val context: Context) { private const val KEY_ROOT_PATH = "root_path" private const val KEY_BACKGROUND_MODE = "background_mode" private const val KEY_FONT_SIZE = "font_size_scale" + private const val KEY_FONT_CHOICE = "font_choice" private const val KEY_FORCE_BOLD = "force_bold" private const val KEY_VOLUME_KEYS = "volume_keys" private const val KEY_INVERT_TOUCHES = "invert_touches" @@ -32,7 +33,9 @@ class LibraryConfig(private val context: Context) { // Fallback to user home on non-Android environments (tests) System.getProperty("user.home") ?: "/" } - private const val DEFAULT_FONT_SIZE = 1.1f + // 🔴 OPTIMIZATION: Reduced from 1.1f to 0.85f for low-memory devices + // Smaller font = smaller rendering viewport = fewer tiles = less memory + private const val DEFAULT_FONT_SIZE = 0.85f private const val DEFAULT_BACKGROUND_MODE = 0.0f // 0 = bianco, 1 = panna, 2 = nero } @@ -58,6 +61,16 @@ class LibraryConfig(private val context: Context) { ) private set + var fontChoice by mutableFloatStateOf( + prefs.getFloat(KEY_FONT_CHOICE, 0.0f) + ) + private set + + fun updateFontChoice(newValue: Float) { + fontChoice = newValue + prefs.edit().putFloat(KEY_FONT_CHOICE, newValue).apply() + } + fun updateFontSize(newValue: Float) { fontSizeScale = newValue prefs.edit().putFloat(KEY_FONT_SIZE, newValue).apply() diff --git a/app/src/main/java/com/nosferatu/launcher/library/ReaderConfig.kt b/app/src/main/java/com/nosferatu/launcher/library/ReaderConfig.kt new file mode 100644 index 0000000..87bac60 --- /dev/null +++ b/app/src/main/java/com/nosferatu/launcher/library/ReaderConfig.kt @@ -0,0 +1,43 @@ +package com.nosferatu.launcher.library + +import android.content.Context +import android.util.Log +import androidx.compose.runtime.mutableFloatStateOf +import androidx.compose.runtime.getValue +import androidx.compose.runtime.setValue +import androidx.compose.runtime.getValue +import androidx.compose.runtime.setValue + +class ReaderConfig(private val context: Context) { + private val prefs = context.getSharedPreferences("reader_prefs", Context.MODE_PRIVATE) + private val TAG = "ReaderConfig" + + init { + val loaded = prefs.getFloat(KEY_READING_BACKGROUND_MODE, -1f) + Log.d(TAG, "init: loaded readingBackgroundMode=$loaded from reader_prefs") + } + + companion object { + private const val KEY_READING_BACKGROUND_MODE = "reading_background_mode" + } + + // -1f means "use global app background mode" + var readingBackgroundMode by mutableFloatStateOf(prefs.getFloat(KEY_READING_BACKGROUND_MODE, -1f)) + private set + + fun updateReadingBackgroundMode(newValue: Float) { + val committed = prefs.edit().putFloat(KEY_READING_BACKGROUND_MODE, newValue).commit() + if (committed) { + readingBackgroundMode = newValue + Log.d(TAG, "updateReadingBackgroundMode: saved $newValue to reader_prefs (committed)") + } else { + readingBackgroundMode = newValue + Log.w(TAG, "updateReadingBackgroundMode: failed to commit $newValue to reader_prefs, but updated in-memory value") + } + } + + fun clearReadingBackgroundMode() { + readingBackgroundMode = -1f + prefs.edit().remove(KEY_READING_BACKGROUND_MODE).apply() + } +} diff --git a/app/src/main/java/com/nosferatu/launcher/parser/TocParser.kt b/app/src/main/java/com/nosferatu/launcher/parser/TocParser.kt new file mode 100644 index 0000000..84b0e32 --- /dev/null +++ b/app/src/main/java/com/nosferatu/launcher/parser/TocParser.kt @@ -0,0 +1,176 @@ +package com.nosferatu.launcher.parser + +import android.util.Log +import android.util.Xml +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import org.xmlpull.v1.XmlPullParser +import java.io.ByteArrayInputStream +import java.io.File +import java.io.InputStream +import java.util.zip.ZipFile + +data class TocItem( + val title: String?, + val href: String?, + val position: Int, + val locatorJson: String? = null +) + +class TocParser { + private val TAG = "TocParser" + + suspend fun parse(file: File): List = withContext(Dispatchers.IO) { + val results = mutableListOf() + try { + ZipFile(file).use { zip -> + val opfPath = getOpfPath(zip) ?: return@withContext results + val opfEntry = zip.getEntry(opfPath) ?: return@withContext results + + val opfContent = zip.getInputStream(opfEntry).use { it.readBytes() } + + val manifest = parseManifest(ByteArrayInputStream(opfContent)) + + // Prefer item with properties containing 'nav' + val navHref = manifest.values.firstOrNull { it.third.contains("nav") }?.first + ?: manifest.values.firstOrNull { it.second == "application/x-dtbncx+xml" }?.first + ?: manifest.values.firstOrNull { it.first.endsWith(".ncx", true) }?.first + ?: manifest.values.firstOrNull { it.first.contains("nav", true) }?.first + + if (navHref != null) { + val fullPath = resolvePath(opfPath, navHref) + val navEntry = zip.getEntry(fullPath) + if (navEntry != null) { + // Decide NCX vs XHTML by extension or media-type + val isNcx = navHref.endsWith(".ncx", true) || + manifest.values.firstOrNull { it.first == navHref }?.second == "application/x-dtbncx+xml" + + val items = if (isNcx) { + parseNcx(zip.getInputStream(navEntry)) + } else { + parseNavHtml(zip.getInputStream(navEntry)) + } + + results.addAll(items.mapIndexed { idx, pair -> TocItem(pair.first, pair.second, idx) }) + } else { + Log.w(TAG, "Nav entry not found in zip: $fullPath") + } + } else { + Log.w(TAG, "No nav or NCX found in OPF manifest for: ${file.name}") + } + } + } catch (e: Exception) { + Log.e(TAG, "Error parsing TOC for file: ${file.name}", e) + } + results + } + + private fun getOpfPath(zip: ZipFile): String? { + val entry = zip.getEntry("META-INF/container.xml") ?: return null + val parser = Xml.newPullParser() + parser.setInput(zip.getInputStream(entry), "UTF-8") + + var eventType = parser.eventType + while (eventType != XmlPullParser.END_DOCUMENT) { + if (eventType == XmlPullParser.START_TAG && parser.name == "rootfile") { + val path = parser.getAttributeValue(null, "full-path") + return path + } + eventType = parser.next() + } + return null + } + + private fun parseManifest(input: InputStream): Map> { + val manifest = mutableMapOf>() + val content = input.bufferedReader().use { it.readText() } + val parser = Xml.newPullParser().apply { + setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true) + setInput(ByteArrayInputStream(content.toByteArray(Charsets.UTF_8)), "UTF-8") + } + + var eventType = parser.eventType + while (eventType != XmlPullParser.END_DOCUMENT) { + if (eventType == XmlPullParser.START_TAG && parser.name == "item") { + val id = parser.getAttributeValue(null, "id") + val href = parser.getAttributeValue(null, "href") + val type = parser.getAttributeValue(null, "media-type") ?: "" + val props = parser.getAttributeValue(null, "properties") ?: "" + if (id != null && href != null) { + manifest[id] = Triple(href, type, props) + } + } + eventType = parser.next() + } + return manifest + } + + private fun resolvePath(basePath: String, relativePath: String): String { + val parent = File(basePath).parent ?: "" + return if (parent.isEmpty()) relativePath else "$parent/$relativePath" + } + + private fun parseNcx(input: InputStream): List> { + val result = mutableListOf>() + val parser = Xml.newPullParser().apply { + setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true) + setInput(input, "UTF-8") + } + + var eventType = parser.eventType + var currentText: String? = null + var currentSrc: String? = null + + while (eventType != XmlPullParser.END_DOCUMENT) { + if (eventType == XmlPullParser.START_TAG) { + when (parser.name) { + "text" -> currentText = parser.nextText() + "content" -> currentSrc = parser.getAttributeValue(null, "src") + } + } else if (eventType == XmlPullParser.END_TAG && parser.name == "navPoint") { + result.add(Pair(currentText, currentSrc)) + currentText = null + currentSrc = null + } + eventType = parser.next() + } + + return result + } + + private fun parseNavHtml(input: InputStream): List> { + val result = mutableListOf>() + val parser = Xml.newPullParser().apply { + setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true) + setInput(input, "UTF-8") + } + + var eventType = parser.eventType + var insideA = false + var href: String? = null + var text: String? = null + + while (eventType != XmlPullParser.END_DOCUMENT) { + if (eventType == XmlPullParser.START_TAG) { + if (parser.name.equals("a", true)) { + href = parser.getAttributeValue(null, "href") + insideA = true + } + } else if (eventType == XmlPullParser.TEXT) { + if (insideA) { + text = (parser.text ?: text)?.trim() + } + } else if (eventType == XmlPullParser.END_TAG) { + if (parser.name.equals("a", true) && insideA) { + result.add(Pair(text, href)) + insideA = false + href = null + text = null + } + } + eventType = parser.next() + } + + return result + } +} diff --git a/app/src/main/java/com/nosferatu/launcher/reader/Bookmark.kt b/app/src/main/java/com/nosferatu/launcher/reader/Bookmark.kt new file mode 100644 index 0000000..b2e15e5 --- /dev/null +++ b/app/src/main/java/com/nosferatu/launcher/reader/Bookmark.kt @@ -0,0 +1,9 @@ +package com.nosferatu.launcher.reader + +data class Bookmark( + val locatorJson: String, + val href: String, + val progression: Double, + val chapterTitle: String?, + val createdAt: Long +) diff --git a/app/src/main/java/com/nosferatu/launcher/reader/BookmarkStore.kt b/app/src/main/java/com/nosferatu/launcher/reader/BookmarkStore.kt new file mode 100644 index 0000000..07ea9c9 --- /dev/null +++ b/app/src/main/java/com/nosferatu/launcher/reader/BookmarkStore.kt @@ -0,0 +1,77 @@ +package com.nosferatu.launcher.reader + +import android.content.Context +import org.json.JSONArray +import org.json.JSONObject + +class BookmarkStore(private val context: Context) { + private val prefs = context.getSharedPreferences("bookmarks_prefs", Context.MODE_PRIVATE) + // New implementation: use a string-based book identifier (e.g. filename) to scope bookmarks. + private fun sanitizeBookKey(raw: String): String = raw.replace(Regex("[^A-Za-z0-9_.-]"), "_") + private fun keyFor(bookKey: String) = "book_${'$'}{sanitizeBookKey(bookKey)}_bookmarks" + + fun listBookmarksForBookKey(bookKey: String): List { + val key = keyFor(bookKey) + val json = prefs.getString(key, "[]") ?: "[]" + val arr = JSONArray(json) + val out = mutableListOf() + for (i in 0 until arr.length()) { + val obj = arr.optJSONObject(i) ?: continue + val locator = obj.optString("locatorJson") + val href = obj.optString("href") + val progression = obj.optDouble("progression", 0.0) + val title = if (obj.has("chapterTitle")) obj.optString("chapterTitle") else null + val createdAt = obj.optLong("createdAt", 0L) + out.add(Bookmark(locator, href, progression, title, createdAt)) + } + return out + } + + fun addBookmarkForBookKey(bookKey: String, bookmark: Bookmark) { + val key = keyFor(bookKey) + val arr = JSONArray(prefs.getString(key, "[]") ?: "[]") + // avoid duplicates by locatorJson + for (i in 0 until arr.length()) { + val obj = arr.optJSONObject(i) ?: continue + if (obj.optString("locatorJson") == bookmark.locatorJson) return + } + val obj = JSONObject() + obj.put("locatorJson", bookmark.locatorJson) + obj.put("href", bookmark.href) + obj.put("progression", bookmark.progression) + obj.put("chapterTitle", bookmark.chapterTitle) + obj.put("createdAt", bookmark.createdAt) + // store book identifier for future compatibility/migration/debug + obj.put("bookKey", bookKey) + arr.put(obj) + prefs.edit().putString(key, arr.toString()).apply() + } + + fun removeBookmarkForBookKey(bookKey: String, locatorJson: String) { + val key = keyFor(bookKey) + val arr = JSONArray(prefs.getString(key, "[]") ?: "[]") + val out = JSONArray() + for (i in 0 until arr.length()) { + val obj = arr.optJSONObject(i) ?: continue + if (obj.optString("locatorJson") != locatorJson) out.put(obj) + } + prefs.edit().putString(key, out.toString()).apply() + } + + fun isBookmarkedForBookKey(bookKey: String, locatorJson: String): Boolean { + val key = keyFor(bookKey) + val arr = JSONArray(prefs.getString(key, "[]") ?: "[]") + for (i in 0 until arr.length()) { + val obj = arr.optJSONObject(i) ?: continue + if (obj.optString("locatorJson") == locatorJson) return true + } + return false + } + + // Backwards-compatible overloads that accept a numeric bookId (keeps existing callers working) + private fun keyFor(bookId: Long) = keyFor(bookId.toString()) + fun listBookmarks(bookId: Long): List = listBookmarksForBookKey(bookId.toString()) + fun addBookmark(bookId: Long, bookmark: Bookmark) = addBookmarkForBookKey(bookId.toString(), bookmark) + fun removeBookmark(bookId: Long, locatorJson: String) = removeBookmarkForBookKey(bookId.toString(), locatorJson) + fun isBookmarked(bookId: Long, locatorJson: String): Boolean = isBookmarkedForBookKey(bookId.toString(), locatorJson) +} diff --git a/app/src/main/java/com/nosferatu/launcher/reader/EpubCacheManager.kt b/app/src/main/java/com/nosferatu/launcher/reader/EpubCacheManager.kt new file mode 100644 index 0000000..e1c160d --- /dev/null +++ b/app/src/main/java/com/nosferatu/launcher/reader/EpubCacheManager.kt @@ -0,0 +1,223 @@ +package com.nosferatu.launcher.reader + +import android.content.Context +import android.util.Log +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import java.io.File +import java.security.MessageDigest +import java.util.zip.ZipFile + +/** + * EpubCacheManager: Filesystem-based extracted EPUB cache for reader optimization. + * + * Purpose: + * - Extract EPUBs to a deterministic cache location on first open + * - Reuse extracted content on subsequent opens (cache hit) + * - Avoid repeated ZIP/container work on old devices + * - Minimize ReaderActivity critical path startup work + * + * Cache Model: + * - Location: cacheDir/readium_publications// + * - Cache key: SHA256(sourcePath + lastModified + fileLength) + * - Validation: directory exists + source metadata still matches + * - No Room involvement: filesystem cache only + * + * Safety: + * - Cache is reconstructible (not source of truth) + * - Graceful fallback if cache unavailable + * - Per-entry error handling (one EPUB failure doesn't block others) + */ +class EpubCacheManager(private val context: Context) { + companion object { + private const val TAG = "EpubCacheManager" + private const val CACHE_DIR = "readium_publications" + } + + /** + * Get or create extracted EPUB path. + * + * @param sourceEpubFile Original EPUB file (must exist and be readable) + * @return Extracted directory path (valid for Readium), or null if failed + * + * On success: returns path to extracted EPUB directory ready for Readium + * On cache hit: returns path immediately (very fast) + * On cache miss: extracts EPUB and returns path + * On error: returns null (caller should fall back to direct open) + */ + suspend fun getExtractedPath(sourceEpubFile: File): File? = withContext(Dispatchers.IO) { + try { + if (!sourceEpubFile.exists() || !sourceEpubFile.isFile) { + Log.w(TAG, "getExtractedPath: source file doesn't exist or isn't a file: ${sourceEpubFile.absolutePath}") + return@withContext null + } + + // Phase 1: Derive cache key from source metadata + val cacheKey = deriveCacheKey(sourceEpubFile) + Log.d(TAG, "getExtractedPath: source=${sourceEpubFile.name} key=$cacheKey") + + // Phase 2: Check if valid cache exists + val cacheDir = getCacheDirForKey(cacheKey) + if (isValidCache(cacheDir, sourceEpubFile)) { + Log.d(TAG, "getExtractedPath: CACHE HIT - $cacheKey") + return@withContext cacheDir + } + + Log.d(TAG, "getExtractedPath: CACHE MISS - extracting to $cacheKey") + + // Phase 3: Extract EPUB to cache + val extractedPath = extractEpubToCache(sourceEpubFile, cacheKey) + if (extractedPath == null) { + Log.w(TAG, "getExtractedPath: extraction FAILED for ${sourceEpubFile.name}") + return@withContext null + } + + Log.d(TAG, "getExtractedPath: extraction SUCCESS - $cacheKey") + extractedPath + } catch (e: Exception) { + Log.e(TAG, "getExtractedPath: FATAL error - ${e.message}", e) + null + } + } + + /** + * Derive deterministic cache key from source file metadata. + * + * Key components: + * - sourcePath: ensures different copy locations have different caches + * - lastModified: detects file changes + * - fileLength: additional change detection + * + * Example: sourcePath=/storage/book.epub, lastModified=1712350000000, length=500000 + * Result: SHA256 hash of concatenated string + */ + private fun deriveCacheKey(file: File): String { + val keyInput = "${file.absolutePath}|${file.lastModified()}|${file.length()}" + val digest = MessageDigest.getInstance("SHA-256") + val hashBytes = digest.digest(keyInput.toByteArray()) + return hashBytes.joinToString("") { "%02x".format(it) } + } + + /** + * Get cache directory for a given key. + */ + private fun getCacheDirForKey(cacheKey: String): File { + return File(context.cacheDir, "$CACHE_DIR/$cacheKey") + } + + /** + * Check if cached directory is valid. + * + * Validity rules: + * 1. Directory exists + * 2. Source file still exists + * 3. Source metadata (path + lastModified + length) matches the key + */ + private fun isValidCache(cacheDir: File, sourceFile: File): Boolean { + try { + if (!cacheDir.exists() || !cacheDir.isDirectory) { + Log.d(TAG, "isValidCache: cache dir doesn't exist: ${cacheDir.absolutePath}") + return false + } + + if (!sourceFile.exists()) { + Log.d(TAG, "isValidCache: source file no longer exists") + return false + } + + // Re-derive key from current source metadata + val currentKey = deriveCacheKey(sourceFile) + val keyFromPath = cacheDir.name + + if (currentKey != keyFromPath) { + Log.d(TAG, "isValidCache: key mismatch (current=$currentKey, cached=$keyFromPath)") + return false + } + + Log.d(TAG, "isValidCache: cache is VALID") + return true + } catch (e: Exception) { + Log.w(TAG, "isValidCache: error during validation - ${e.message}") + return false + } + } + + /** + * Extract EPUB to cache directory. + * + * Strategy: + * 1. Ensure cache directory exists + * 2. Open source EPUB as ZIP + * 3. Extract all entries to cache directory + * 4. Verify extraction succeeded + * + * @return Cache directory if successful, null if failed + */ + private fun extractEpubToCache(sourceFile: File, cacheKey: String): File? { + return try { + val cacheDir = getCacheDirForKey(cacheKey) + + // Ensure clean extraction (delete partial cache if exists) + if (cacheDir.exists()) { + Log.d(TAG, "extractEpubToCache: removing existing cache dir (partial extraction?)") + cacheDir.deleteRecursively() + } + cacheDir.mkdirs() + + Log.d(TAG, "extractEpubToCache: opening ZIP ${sourceFile.name}") + + // Extract all ZIP entries + var extractedCount = 0 + ZipFile(sourceFile).use { zip -> + zip.entries().asSequence().forEach { entry -> + val targetFile = File(cacheDir, entry.name) + + if (entry.isDirectory) { + targetFile.mkdirs() + } else { + targetFile.parentFile?.mkdirs() + zip.getInputStream(entry).use { input -> + targetFile.outputStream().use { output -> + input.copyTo(output) + } + } + extractedCount++ + } + } + } + + Log.d(TAG, "extractEpubToCache: extracted $extractedCount files to ${cacheDir.absolutePath}") + + // Verify extraction + if (!cacheDir.exists() || cacheDir.listFiles().isNullOrEmpty()) { + Log.e(TAG, "extractEpubToCache: cache dir is empty after extraction!") + return null + } + + cacheDir + } catch (e: Exception) { + Log.e(TAG, "extractEpubToCache: extraction FAILED - ${e.message}", e) + null + } + } + + /** + * Optional: Clean up orphaned cache entries (not called automatically). + * + * Call this periodically or on app startup to remove old caches. + */ + suspend fun cleanupOrphanedCaches() = withContext(Dispatchers.IO) { + try { + val cacheRootDir = File(context.cacheDir, CACHE_DIR) + if (!cacheRootDir.exists()) return@withContext + + val cleanedCount = cacheRootDir.listFiles()?.count { + it.deleteRecursively() + } ?: 0 + + Log.d(TAG, "cleanupOrphanedCaches: removed $cleanedCount orphaned directories") + } catch (e: Exception) { + Log.w(TAG, "cleanupOrphanedCaches: cleanup failed - ${e.message}") + } + } +} diff --git a/app/src/main/java/com/nosferatu/launcher/reader/NosferatuDocumentActivity.kt b/app/src/main/java/com/nosferatu/launcher/reader/NosferatuDocumentActivity.kt new file mode 100644 index 0000000..96830c9 --- /dev/null +++ b/app/src/main/java/com/nosferatu/launcher/reader/NosferatuDocumentActivity.kt @@ -0,0 +1,405 @@ +package com.nosferatu.launcher.reader + +import android.app.AlertDialog +import android.content.BroadcastReceiver +import android.content.Context +import android.content.Intent +import android.content.IntentFilter +import android.os.BatteryManager +import android.os.Bundle +import android.util.Log +import android.view.View +import android.widget.FrameLayout +import android.widget.ImageView +import android.widget.TextView +import android.widget.Toast +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.darkColorScheme +import androidx.compose.material3.lightColorScheme +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.ComposeView +import androidx.compose.ui.platform.ViewCompositionStrategy +import androidx.compose.ui.res.stringResource +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.LifecycleOwner +import androidx.lifecycle.LifecycleRegistry +import androidx.lifecycle.ViewModelStore +import androidx.lifecycle.ViewModelStoreOwner +import androidx.lifecycle.setViewTreeLifecycleOwner +import androidx.lifecycle.setViewTreeViewModelStoreOwner +import androidx.savedstate.SavedStateRegistry +import androidx.savedstate.SavedStateRegistryController +import androidx.savedstate.SavedStateRegistryOwner +import androidx.savedstate.setViewTreeSavedStateRegistryOwner +import com.artifex.mupdf.mini.DocumentActivity +import com.nosferatu.launcher.NosferatuApp +import com.nosferatu.launcher.R +import com.nosferatu.launcher.library.LibraryConfig +import com.nosferatu.launcher.library.LibraryViewModel +import com.nosferatu.launcher.library.LibraryViewModelFactory +import com.nosferatu.launcher.ui.LocalAppColors +import com.nosferatu.launcher.ui.appColorsFor +import com.nosferatu.launcher.ui.components.common.SingleChoiceOptionRow +import com.nosferatu.launcher.ui.components.fontsettings.ReaderTextSettings +import java.text.DateFormat +import java.util.Date + +/** + * Host-integration subclass of the MuPDF [DocumentActivity]. + * + * [DocumentActivity] exposes `onReaderSettingsRequested()`, `onBookmarkToggleRequested()` + * and `onBookmarksRequested()` as no-op hooks meant to be overridden by the host app. + * Previously the app launched [DocumentActivity] directly, so the gear/bookmark/bookmarks + * chrome buttons rendered correctly but did nothing when tapped. This subclass wires them + * to real behavior: + * - page bookmarks, reusing the same [BookmarkStore]/[Bookmark] storage used by the + * Readium [ReaderActivity]; + * - an in-reader text/background settings panel that mirrors [ReaderSettingsBottomSheet]'s + * content (font size slider + background choice), hosted in the `font_controls_container` + * `ComposeView` bridge added to `document_activity.xml`. + * + * [DocumentActivity] extends the plain `android.app.Activity` (not `ComponentActivity`), so it + * does not provide the `ViewTreeLifecycleOwner`/`ViewTreeViewModelStoreOwner`/ + * `ViewTreeSavedStateRegistryOwner` that Compose's `ComposeView` requires. This class supplies a + * minimal, self-contained implementation of those owners instead of changing `DocumentActivity`'s + * base class (keeping the `:lib` module's MuPDF internals untouched). + */ +class NosferatuDocumentActivity : + DocumentActivity(), + LifecycleOwner, + ViewModelStoreOwner, + SavedStateRegistryOwner { + + private val lifecycleRegistry = LifecycleRegistry(this) + private val store = ViewModelStore() + private val savedStateRegistryController = SavedStateRegistryController.create(this) + + override val lifecycle: Lifecycle get() = lifecycleRegistry + override val viewModelStore: ViewModelStore get() = store + override val savedStateRegistry: SavedStateRegistry get() = savedStateRegistryController.savedStateRegistry + + private val bookmarkStore by lazy { BookmarkStore(this) } + private val overlayLibraryConfig by lazy { LibraryConfig(this) } + private var fontControlsVisible = false + + private var statusBarClockTimer: java.util.Timer? = null + private var statusBarBatteryReceiver: BroadcastReceiver? = null + + private var bookId: Long = -1 + private val viewModel: LibraryViewModel by lazy { + LibraryViewModelFactory((application as NosferatuApp).repository).create(LibraryViewModel::class.java) + } + + companion object { + // Keeps the default library_prefs font size scale (0.85) mapped to MuPDF's default + // reflow em-size (8pt), so existing users see an unchanged default layout. + private const val BASE_LAYOUT_EM_PER_SCALE = 8f / 0.85f + private const val MIN_LAYOUT_EM = 4f + private const val TAG = "NosferatuDocumentActivity" + } + + override fun onCreate(savedInstanceState: Bundle?) { + savedStateRegistryController.performRestore(savedInstanceState) + super.onCreate(savedInstanceState) + lifecycleRegistry.currentState = Lifecycle.State.CREATED + + bookId = intent.getLongExtra("BOOK_ID", -1) + Log.d(TAG, "onCreate: bookId=$bookId") + + window.decorView.let { root -> + root.setViewTreeLifecycleOwner(this) + root.setViewTreeViewModelStoreOwner(this) + root.setViewTreeSavedStateRegistryOwner(this) + } + + setupFontControlsOverlay() + setupCustomStatusBar() + } + + override fun onSaveInstanceState(outState: Bundle) { + super.onSaveInstanceState(outState) + savedStateRegistryController.performSave(outState) + } + + override fun onStart() { + super.onStart() + lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START) + } + + override fun onResume() { + super.onResume() + lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_RESUME) + } + + override fun onPause() { + lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_PAUSE) + super.onPause() + } + + override fun onStop() { + savePagePosition() + lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_STOP) + super.onStop() + } + + override fun onDestroy() { + lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_DESTROY) + store.clear() + statusBarClockTimer?.cancel() + statusBarBatteryReceiver?.let { + try { + unregisterReceiver(it) + } catch (e: Exception) { + Log.w(TAG, "Error unregistering battery receiver: ${e.message}") + } + } + super.onDestroy() + } + + // --- Status bar (clock + battery), mirrors ReaderActivity.setupCustomStatusBar() ---- + + private fun Int.statusBarDpToPx(): Int = (this * resources.displayMetrics.density).toInt() + + private fun setupCustomStatusBar() { + try { + val container = findViewById(R.id.reader_status_bar_container) ?: return + val statusBarView = layoutInflater.inflate(R.layout.reader_status_bar, container, false) + container.addView(statusBarView) + + val clockTextView = statusBarView.findViewById(R.id.reader_status_clock) + val batteryPercentageView = statusBarView.findViewById(R.id.reader_battery_percentage) + val batteryFillView = statusBarView.findViewById(R.id.reader_battery_fill) + + // Clock update timer (every second) + statusBarClockTimer = kotlin.concurrent.timer(initialDelay = 0, period = 1000) { + try { + val now = System.currentTimeMillis() + val timeStr = java.text.SimpleDateFormat("HH:mm", java.util.Locale.getDefault()).format(java.util.Date(now)) + this@NosferatuDocumentActivity.runOnUiThread { + try { clockTextView.text = timeStr } catch (_: Exception) {} + } + } catch (e: Exception) { + Log.w(TAG, "Clock update failed: ${e.message}") + } + } + + fun applyBatteryUi(percentage: Int) { + try { + batteryPercentageView.text = "$percentage%" + val totalPx = 18.statusBarDpToPx() + val fillWidth = (totalPx * percentage) / 100 + val p = batteryFillView.layoutParams + p.width = fillWidth + batteryFillView.layoutParams = p + } catch (_: Exception) {} + } + + val intentFilter = IntentFilter(Intent.ACTION_BATTERY_CHANGED) + + // Populate initial battery state from sticky intent + try { + val sticky = registerReceiver(null, intentFilter) + if (sticky != null) { + val level = sticky.getIntExtra(BatteryManager.EXTRA_LEVEL, -1) + val scale = sticky.getIntExtra(BatteryManager.EXTRA_SCALE, -1) + val percentage = if (level >= 0 && scale > 0) (level * 100) / scale else 0 + runOnUiThread { applyBatteryUi(percentage) } + } + } catch (t: Throwable) { + Log.w(TAG, "Initial battery sticky intent failed: ${t.message}") + } + + statusBarBatteryReceiver = object : BroadcastReceiver() { + override fun onReceive(context: Context?, intent: Intent?) { + val level = intent?.getIntExtra(BatteryManager.EXTRA_LEVEL, -1) ?: -1 + val scale = intent?.getIntExtra(BatteryManager.EXTRA_SCALE, -1) ?: -1 + val percentage = if (level >= 0 && scale > 0) (level * 100) / scale else 0 + runOnUiThread { applyBatteryUi(percentage) } + } + } + + try { + registerReceiver(statusBarBatteryReceiver, intentFilter) + } catch (t: Throwable) { + Log.w(TAG, "registerReceiver failed: ${t.message}") + } + } catch (t: Throwable) { + Log.w(TAG, "setupCustomStatusBar failed: ${t.message}") + } + } + + // --- Position saving ----------------------------------------------------------------- + + private fun savePagePosition() { + if (bookId == -1L) return + try { + // Create a JSON-like string to represent the page position, similar to Readium's locator format + val locationJson = """{"page":$currentPage,"totalPages":$pageCount}""" + val progression = if (pageCount > 0) currentPage.toDouble() / pageCount.toDouble() else 0.0 + Log.d(TAG, "Saving position for bookId=$bookId: page=$currentPage/$pageCount, progression=$progression") + viewModel.saveBookPosition(bookId, locationJson, progression) + } catch (e: Exception) { + Log.w(TAG, "Error saving page position: ${e.message}") + } + } + + // --- Page bookmarks ----------------------------------------------------------------- + + private fun pageBookmarkKey(page: Int) = "page:$page" + + // Called by DocumentActivity on every page load; piggy-back to refresh the bookmark icon. + override fun showPageNumber(pageNumber: Int) { + super.showPageNumber(pageNumber) + updateBookmarkIcon() + } + + private fun updateBookmarkIcon() { + val button = bookmarkToggleButton as? ImageView ?: return + val bookmarked = bookmarkStore.isBookmarkedForBookKey(key, pageBookmarkKey(currentPage)) + button.setImageResource(if (bookmarked) R.drawable.ic_bookmark_filled else R.drawable.ic_bookmark_outline) + } + + override fun onBookmarkToggleRequested() { + val pageKey = pageBookmarkKey(currentPage) + if (bookmarkStore.isBookmarkedForBookKey(key, pageKey)) { + bookmarkStore.removeBookmarkForBookKey(key, pageKey) + Toast.makeText(this, getString(R.string.bookmark_removed), Toast.LENGTH_SHORT).show() + } else { + val progression = if (pageCount > 0) currentPage.toDouble() / pageCount.toDouble() else 0.0 + val label = getString(R.string.reader_bookmark_page_label, currentPage + 1) + bookmarkStore.addBookmarkForBookKey( + key, + Bookmark(pageKey, "", progression, label, System.currentTimeMillis()) + ) + Toast.makeText(this, getString(R.string.bookmark_added), Toast.LENGTH_SHORT).show() + } + updateBookmarkIcon() + } + + override fun onBookmarksRequested() { + val bookmarks = bookmarkStore.listBookmarksForBookKey(key) + if (bookmarks.isEmpty()) { + Toast.makeText(this, getString(R.string.no_bookmarks), Toast.LENGTH_SHORT).show() + return + } + + val dateFormat = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT) + val labels = bookmarks.map { bookmark -> + "${bookmark.chapterTitle} — ${dateFormat.format(Date(bookmark.createdAt))}" + }.toTypedArray() + + AlertDialog.Builder(this) + .setTitle(getString(R.string.bookmarks_title)) + .setItems(labels) { _, index -> showBookmarkActionDialog(bookmarks[index]) } + .setNegativeButton(android.R.string.cancel, null) + .show() + } + + private fun showBookmarkActionDialog(bookmark: Bookmark) { + AlertDialog.Builder(this) + .setTitle(bookmark.chapterTitle) + .setItems(arrayOf(getString(R.string.open_bookmark), getString(R.string.remove_bookmark))) { _, which -> + if (which == 0) { + bookmark.locatorJson.removePrefix("page:").toIntOrNull()?.let { gotoPage(it) } + } else { + bookmarkStore.removeBookmarkForBookKey(key, bookmark.locatorJson) + Toast.makeText(this, getString(R.string.bookmark_removed), Toast.LENGTH_SHORT).show() + updateBookmarkIcon() + } + } + .show() + } + + // --- In-reader settings overlay (text size + background) ---------------------------- + + private fun setupFontControlsOverlay() { + val container = findViewById(R.id.font_controls_container) ?: return + container.setViewCompositionStrategy(ViewCompositionStrategy.DisposeOnViewTreeLifecycleDestroyed) + container.setContent { + val appColors = appColorsFor(overlayLibraryConfig.backgroundMode) + val isDark = overlayLibraryConfig.backgroundMode.toInt() == 2 + val colorScheme = if (isDark) { + darkColorScheme().copy( + background = appColors.bg, + surface = appColors.surface, + onBackground = appColors.onBg, + onSurface = appColors.onBg + ) + } else { + lightColorScheme( + background = appColors.bg, + surface = appColors.surface, + onBackground = appColors.onBg, + onSurface = appColors.onBg + ) + } + + MaterialTheme(colorScheme = colorScheme) { + CompositionLocalProvider(LocalAppColors provides appColors) { + Column(modifier = Modifier.fillMaxWidth().background(appColors.bg)) { + ReaderTextSettings( + libraryConfig = overlayLibraryConfig, + onPreferenceChanged = { applyFontSizeToDocument() } + ) + + val currentBgMode = overlayLibraryConfig.backgroundMode.toInt() + SingleChoiceOptionRow( + label = stringResource(id = R.string.color_white), + selected = currentBgMode == 0, + onClick = { changeBackgroundMode(0f) } + ) + SingleChoiceOptionRow( + label = stringResource(id = R.string.color_cream), + selected = currentBgMode == 1, + onClick = { changeBackgroundMode(1f) } + ) + SingleChoiceOptionRow( + label = stringResource(id = R.string.color_black), + selected = currentBgMode == 2, + onClick = { changeBackgroundMode(2f) } + ) + } + } + } + } + } + + private fun changeBackgroundMode(mode: Float) { + if (overlayLibraryConfig.backgroundMode.toInt() == mode.toInt()) return + overlayLibraryConfig.updateBackgroundMode(mode) + // Background mode drives setTheme()/applyReaderTheme(), which must run before + // setContentView(); recreate() is the simplest safe way to re-apply it everywhere. + recreate() + } + + private fun applyFontSizeToDocument() { + // Font size only affects reflowable documents (EPUB/FB2/MOBI opened via MuPDF); a + // fixed-layout PDF page is a rasterized bitmap and cannot reflow to a new text size. + if (!isReflowable) return + layoutEm = (overlayLibraryConfig.fontSizeScale * BASE_LAYOUT_EM_PER_SCALE).coerceAtLeast(MIN_LAYOUT_EM) + relayoutDocument() + } + + override fun onReaderSettingsRequested() { + toggleFontControls() + } + + private fun toggleFontControls() { + val container = findViewById(R.id.font_controls_container) ?: return + fontControlsVisible = !fontControlsVisible + container.visibility = if (fontControlsVisible) View.VISIBLE else View.GONE + } + + // Hide the settings overlay whenever the reader chrome itself is hidden (page tap), + // mirroring ReaderActivity.toggleMenu()'s behavior for font_controls_container. + override fun onReaderUiVisibilityChanged(visible: Boolean) { + if (!visible && fontControlsVisible) { + fontControlsVisible = false + findViewById(R.id.font_controls_container)?.visibility = View.GONE + } + } +} diff --git a/app/src/main/java/com/nosferatu/launcher/reader/ReaderActivity.kt b/app/src/main/java/com/nosferatu/launcher/reader/ReaderActivity.kt index 57f6a68..754f72d 100644 --- a/app/src/main/java/com/nosferatu/launcher/reader/ReaderActivity.kt +++ b/app/src/main/java/com/nosferatu/launcher/reader/ReaderActivity.kt @@ -8,11 +8,20 @@ import android.widget.ImageView import android.widget.ProgressBar import android.widget.SeekBar import android.widget.TextView +import android.content.BroadcastReceiver +import android.content.Context +import android.content.Intent +import android.content.IntentFilter +import android.os.BatteryManager +import kotlin.concurrent.timer +import java.util.Timer import androidx.activity.viewModels import androidx.appcompat.app.AppCompatActivity import androidx.compose.ui.platform.ComposeView import androidx.core.view.ViewCompat +import androidx.core.view.WindowCompat import androidx.core.view.WindowInsetsCompat +import androidx.core.view.WindowInsetsControllerCompat import androidx.lifecycle.Lifecycle import androidx.lifecycle.lifecycleScope import androidx.lifecycle.repeatOnLifecycle @@ -28,7 +37,14 @@ import androidx.compose.material3.darkColorScheme import androidx.compose.material3.lightColorScheme import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.toArgb import com.nosferatu.launcher.ui.components.fontsettings.ReaderTextSettings +import androidx.core.content.res.ResourcesCompat +import android.graphics.Typeface +import androidx.compose.material3.Typography +import androidx.compose.ui.text.font.Font +import androidx.compose.ui.text.font.FontFamily +import androidx.compose.ui.res.stringResource import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext @@ -55,16 +71,46 @@ import org.readium.r2.streamer.parser.epub.EpubParser import java.io.File import com.nosferatu.launcher.reader.TestReaderInjector import com.nosferatu.launcher.reader.TestNavigatorFragment +import android.app.AlertDialog +import android.widget.Toast +import java.text.DateFormat +import java.net.URLDecoder +import com.google.android.material.bottomsheet.BottomSheetDialog +import com.google.android.material.bottomsheet.BottomSheetBehavior +import androidx.recyclerview.widget.RecyclerView +import androidx.recyclerview.widget.LinearLayoutManager +import android.view.LayoutInflater +import android.view.ViewGroup +import android.graphics.Color as AndroidColor +import android.app.ActivityManager +import android.util.Base64 +import android.graphics.drawable.ColorDrawable +import androidx.compose.ui.platform.ViewCompositionStrategy +import com.nosferatu.launcher.library.ReaderConfig +import com.nosferatu.launcher.ui.components.common.SingleChoiceOptionRow +import androidx.compose.foundation.layout.Column @OptIn(ExperimentalReadiumApi::class) class ReaderActivity : AppCompatActivity(), EpubNavigatorFragment.Listener { private val _tag = "ReaderActivity" + private val LOW_MEMORY_THRESHOLD_MB = 1500 // 1.5 GB threshold for lean mode + // Internal exception used only for control-flow to indicate asset was used + private class AssetUsedException : Exception() private var publication: Publication? = null private val viewModel: LibraryViewModel by viewModels { LibraryViewModelFactory((application as NosferatuApp).repository) } private var _lastKnownLocator: Locator? = null private var bookId: Long = -1 + private var bookKey: String = "" + private val bookmarkStore by lazy { BookmarkStore(this) } + // TOC bottom-sheet state + private var tocDialog: BottomSheetDialog? = null + private var tocAdapter: TocAdapter? = null + private var tocRecycler: RecyclerView? = null + private var tocFlatLabels: Array? = null + private val tocFlatLocators: MutableList = mutableListOf() + private var tocSelectedIndex: Int = -1 private val assetRetriever by lazy { AssetRetriever(contentResolver, DefaultHttpClient()) } private val publicationOpener by lazy { @@ -73,11 +119,15 @@ class ReaderActivity : AppCompatActivity(), EpubNavigatorFragment.Listener { contentProtections = emptyList() ) } + private val epubCacheManager by lazy { EpubCacheManager(this) } private var isMenuVisible = false private var isFontBarVisible = false private var isSeeking = false private val libraryConfig by lazy { LibraryConfig(this) } + private val readerConfig by lazy { ReaderConfig(this) } + private var statusBarClockTimer: Timer? = null + private var statusBarBatteryReceiver: BroadcastReceiver? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) @@ -88,6 +138,8 @@ class ReaderActivity : AppCompatActivity(), EpubNavigatorFragment.Listener { 2 -> setTheme(R.style.Theme_NosferatuReader_Dark) else -> setTheme(R.style.Theme_NosferatuReader) } + // Hide system status bar (match MainActivity behavior) + hideSystemUI() setContentView(R.layout.activity_reader) // Setup UI Insets @@ -104,12 +156,52 @@ class ReaderActivity : AppCompatActivity(), EpubNavigatorFragment.Listener { onBackPressedDispatcher.onBackPressed() } + // bookmark toggle (top-right) + findViewById(R.id.btn_bookmark_toggle).setOnClickListener { + toggleBookmark() + } + + // tooltips for accessibility and desktop hover + ViewCompat.setTooltipText(findViewById(R.id.btn_back), getString(R.string.cd_back)) + ViewCompat.setTooltipText(findViewById(R.id.btn_bookmark_toggle), getString(R.string.cd_bookmark_toggle)) + // reader settings button tooltip and click + try { + val settingsBtn = findViewById(R.id.btn_reader_settings) + ViewCompat.setTooltipText(settingsBtn, getString(R.string.cd_reader_settings)) + settingsBtn.setOnClickListener { v -> showReaderSettingsPopup(v) } + } catch (t: Throwable) { + // if the view is not present for any reason, ignore + } + setupSettingsPanel() + // Apply initial typeface according to stored preference + applyTypefaceToReaderUI() + // Setup custom XML-based status bar (clock + battery) + setupCustomStatusBar() + // Ensure the custom reader status bar is always visible + try { + findViewById(R.id.reader_status_bar_container)?.visibility = View.VISIBLE + } catch (t: Throwable) { + Log.w(_tag, "set status bar visible failed: ${t.message}") + } + + // bookmarks panel trigger (bottom bar) + findViewById(R.id.btn_bookmarks).setOnClickListener { + openBookmarksPanel() + } + // TOC panel trigger (bottom-left) + findViewById(R.id.btn_toc).setOnClickListener { + openTocPanel() + } + ViewCompat.setTooltipText(findViewById(R.id.btn_toc), getString(R.string.cd_open_toc)) + ViewCompat.setTooltipText(findViewById(R.id.btn_bookmarks), getString(R.string.bookmarks_title)) // Book Loading Logic val bookPath = intent.getStringExtra("BOOK_PATH") ?: return finish() val lastLocationJson = intent.getStringExtra("LAST_LOCATION_JSON") bookId = intent.getLongExtra("BOOK_ID", -1) + // Derive a stable string identifier for this book (use filename). This scopes bookmarks per-file. + bookKey = try { File(bookPath).name } catch (_: Exception) { bookPath } // If tests enabled fake navigator, avoid initializing Readium and populate minimal UI if (TestReaderInjector.useFakeNavigator) { @@ -147,13 +239,31 @@ class ReaderActivity : AppCompatActivity(), EpubNavigatorFragment.Listener { lifecycleScope.launch { try { + val readerStartTime = System.currentTimeMillis() + Log.d(_tag, "onCreate: reader startup BEGIN") + publication = openPublication(File(bookPath)) + val pubOpenDuration = System.currentTimeMillis() - readerStartTime + Log.d(_tag, "onCreate: publication opened in ${pubOpenDuration}ms") val initialLocator = lastLocationJson?.let { try { Locator.fromJSON(JSONObject(it)) } catch (e: Exception) { null } } // Inizializziamo il navigatore con le preferenze attuali da LibraryConfig + val navigatorStartTime = System.currentTimeMillis() + + // 🔴 LOW-MEMORY DETECTION: rilevare se il device ha memoria limitata + val isLowMemoryDevice = isLowMemoryDevice() + val shouldDisablePublisherStyles = isLowMemoryDevice + Log.d(_tag, "Readium init: lowMemoryDevice=$isLowMemoryDevice, disablePublisherStyles=$shouldDisablePublisherStyles") + // Log reader vs app theme for debugging persistence + try { + Log.d(_tag, "Reader theme check: readerConfig.readingBackgroundMode=${readerConfig.readingBackgroundMode}, libraryConfig.backgroundMode=${libraryConfig.backgroundMode}") + } catch (t: Throwable) { + Log.w(_tag, "Reader theme check failed: ${t.message}") + } + val navigatorFactory = EpubNavigatorFactory( publication = publication!!, configuration = EpubNavigatorFactory.Configuration( @@ -162,9 +272,11 @@ class ReaderActivity : AppCompatActivity(), EpubNavigatorFragment.Listener { ).createFragmentFactory( initialPreferences = EpubPreferences( fontSize = libraryConfig.fontSizeScale.toDouble(), - fontWeight = if (libraryConfig.forceBold) 2.0 else null, + // 🔴 OPTIMIZATION: Disable bold on low-memory (reduces glyph rendering complexity) + fontWeight = if (libraryConfig.forceBold && !isLowMemoryDevice) 2.0 else null, columnCount = ColumnCount.ONE, - publisherStyles = true, + // 🔴 OPTIMIZATION: Disabilitare publisher styles su device low-end + publisherStyles = !shouldDisablePublisherStyles, theme = when (libraryConfig.backgroundMode.toInt()) { 1 -> Theme.SEPIA 2 -> Theme.DARK @@ -174,6 +286,8 @@ class ReaderActivity : AppCompatActivity(), EpubNavigatorFragment.Listener { initialLocator = initialLocator, listener = this@ReaderActivity ) + val navigatorDuration = System.currentTimeMillis() - navigatorStartTime + Log.d(_tag, "onCreate: navigator setup in ${navigatorDuration}ms") supportFragmentManager.fragmentFactory = navigatorFactory @@ -186,18 +300,36 @@ class ReaderActivity : AppCompatActivity(), EpubNavigatorFragment.Listener { val navigator = supportFragmentManager.findFragmentByTag("EpubNavigator") as? EpubNavigatorFragment navigator?.addInputListener(readerInputListener) + // Ensure restored navigator receives current reader preferences (handles fragment restore path) + try { + applyReaderPreferences() + } catch (t: Throwable) { + Log.w(_tag, "applyReaderPreferences on restored navigator failed: ${t.message}") + } + if (navigator != null) { setupProgressBarSeek(navigator) + // 🎨 Initial CSS injection (theme-aware) + try { + injectThemeAwareCss() + } catch (t: Throwable) { + Log.w(_tag, "injectThemeAwareCss initial injection failed: ${t.message}") + } launch { repeatOnLifecycle(Lifecycle.State.STARTED) { navigator.currentLocator.collect { locator -> _lastKnownLocator = locator updateUiWithLocator(locator) + updateBookmarkIcon() + updateTocSelection() } } } } + val totalDuration = System.currentTimeMillis() - readerStartTime + Log.d(_tag, "onCreate: READER STARTUP COMPLETE in ${totalDuration}ms") + } catch (e: Exception) { Log.e(_tag, "Errore fatale apertura libro: ${e.message}") finish() @@ -205,24 +337,84 @@ class ReaderActivity : AppCompatActivity(), EpubNavigatorFragment.Listener { } } + // Expose configs to fragments so they can update the shared instances + fun provideLibraryConfig(): LibraryConfig = libraryConfig + fun provideReaderConfig(): ReaderConfig = readerConfig + + /** + * 🔴 OPTIMIZATION: Rilevare se il device è low-memory (< 1.5 GB RAM) + * Su device Tegra 3 con 1GB RAM, Readium non riesce a gestire i tile del rendering + * quando publisher styles sono abilitati. + */ + private fun isLowMemoryDevice(): Boolean { + return try { + val activityManager = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager + val memInfo = ActivityManager.MemoryInfo() + activityManager.getMemoryInfo(memInfo) + + val totalMemoryMB = memInfo.totalMem / (1024 * 1024) + val availableMemoryMB = memInfo.availMem / (1024 * 1024) + val result = totalMemoryMB < LOW_MEMORY_THRESHOLD_MB + + // 🔴 DETAILED LOGGING: Per diagnostica memory pressure su Tegra 3 + Log.d(_tag, "📊 MEMORY STATUS: Total=${totalMemoryMB}MB, Available=${availableMemoryMB}MB, LowMemoryMode=$result") + if (availableMemoryMB < 300) { + Log.w(_tag, "⚠️ CRITICAL: Available memory only ${availableMemoryMB}MB - expect performance issues") + } + + result + } catch (e: Exception) { + Log.w(_tag, "Failed to check system memory: ${e.message}", e) + false + } + } + private fun setupSettingsPanel() { val settingsContainer = findViewById(R.id.font_controls_container) - val btnToggle = findViewById(R.id.btn_font_settings) settingsContainer.setContent { + // Use the global app background for the in-reader font controls val appColors = appColorsFor(libraryConfig.backgroundMode) val isDark = libraryConfig.backgroundMode.toInt() == 2 val colorScheme = if (isDark) { darkColorScheme().copy( - background = Color(0xFF222222), - surface = Color(0xFF222222), - onBackground = Color(0xFFEEEEEE), - onSurface = Color(0xFFEEEEEE) + background = appColors.bg, + surface = appColors.surface, + onBackground = appColors.onBg, + onSurface = appColors.onBg ) } else { - lightColorScheme(surface = Color.White) + lightColorScheme( + background = appColors.bg, + surface = appColors.surface, + onBackground = appColors.onBg, + onSurface = appColors.onBg + ) } - MaterialTheme(colorScheme = colorScheme) { + // Build typography for overlay using the same runtime font detection + val baseTypography = Typography() + val ctx = this@ReaderActivity + val resId = ctx.resources.getIdentifier("literata_regular", "font", ctx.packageName) + val chosenFamily = if (resId != 0) FontFamily(Font(resId)) else FontFamily.Default + val typography = if (libraryConfig.fontChoice.toInt() == 1) baseTypography.copy( + displayLarge = baseTypography.displayLarge.copy(fontFamily = chosenFamily), + displayMedium = baseTypography.displayMedium.copy(fontFamily = chosenFamily), + displaySmall = baseTypography.displaySmall.copy(fontFamily = chosenFamily), + headlineLarge = baseTypography.headlineLarge.copy(fontFamily = chosenFamily), + headlineMedium = baseTypography.headlineMedium.copy(fontFamily = chosenFamily), + headlineSmall = baseTypography.headlineSmall.copy(fontFamily = chosenFamily), + titleLarge = baseTypography.titleLarge.copy(fontFamily = chosenFamily), + titleMedium = baseTypography.titleMedium.copy(fontFamily = chosenFamily), + titleSmall = baseTypography.titleSmall.copy(fontFamily = chosenFamily), + bodyLarge = baseTypography.bodyLarge.copy(fontFamily = chosenFamily), + bodyMedium = baseTypography.bodyMedium.copy(fontFamily = chosenFamily), + bodySmall = baseTypography.bodySmall.copy(fontFamily = chosenFamily), + labelLarge = baseTypography.labelLarge.copy(fontFamily = chosenFamily), + labelMedium = baseTypography.labelMedium.copy(fontFamily = chosenFamily), + labelSmall = baseTypography.labelSmall.copy(fontFamily = chosenFamily) + ) else baseTypography + + MaterialTheme(colorScheme = colorScheme, typography = typography) { CompositionLocalProvider(LocalAppColors provides appColors) { ReaderTextSettings( libraryConfig = libraryConfig, @@ -232,32 +424,748 @@ class ReaderActivity : AppCompatActivity(), EpubNavigatorFragment.Listener { } } - btnToggle.setOnClickListener { - isFontBarVisible = !isFontBarVisible - settingsContainer.visibility = if (isFontBarVisible) View.VISIBLE else View.GONE + // The in-reader font controls remain in the layout but are not toggled from a reader button. + // Font selection is persisted in `LibraryConfig` and applied via `applyReaderPreferences()`/`applyTypefaceToReaderUI()`. + } + + private fun showReaderSettingsPopup(anchor: View) { + try { + val fragment = ReaderSettingsBottomSheet() + fragment.show(supportFragmentManager, "ReaderSettings") + } catch (t: Throwable) { + Log.w(_tag, "showReaderSettingsPopup failed: ${t.message}") } } - private fun applyReaderPreferences() { + fun applyReaderPreferences() { val fragment = supportFragmentManager.findFragmentByTag("EpubNavigator") val navigator = fragment as? EpubNavigatorFragment val testNavigator = fragment as? TestNavigatorFragment + // 🔴 LOW-MEMORY OPTIMIZATION: applicare anche al runtime + val isLowMemoryDevice = isLowMemoryDevice() + val shouldDisablePublisherStyles = isLowMemoryDevice + + val effectiveBgModeInt = if (readerConfig.readingBackgroundMode >= 0f) readerConfig.readingBackgroundMode.toInt() else libraryConfig.backgroundMode.toInt() + val newPreferences = EpubPreferences( fontSize = libraryConfig.fontSizeScale.toDouble(), - fontWeight = if (libraryConfig.forceBold) 2.0 else null, + // 🔴 OPTIMIZATION: Disable bold on low-memory (reduces rendering overhead) + fontWeight = if (libraryConfig.forceBold && !isLowMemoryDevice) 2.0 else null, columnCount = ColumnCount.ONE, - publisherStyles = true, - theme = when (libraryConfig.backgroundMode.toInt()) { + // 🔴 OPTIMIZATION: Non applicare publisher styles su low-memory + publisherStyles = !shouldDisablePublisherStyles, + theme = when (effectiveBgModeInt) { 1 -> Theme.SEPIA 2 -> Theme.DARK else -> Theme.LIGHT } ) - Log.d(_tag, "Applicazione nuove preferenze: Font=${newPreferences.fontSize}, Bold=${libraryConfig.forceBold}, PublisherStyles=${newPreferences.publisherStyles}") + Log.d(_tag, "applyReaderPreferences: Font=${newPreferences.fontSize}, Bold=${libraryConfig.forceBold}, PublisherStyles=${newPreferences.publisherStyles}, LowMemory=$isLowMemoryDevice") navigator?.submitPreferences(newPreferences) testNavigator?.submitPreferences(newPreferences) + // 🎨 Re-inject CSS after applying preferences so theme/font changes take effect + try { + injectThemeAwareCss() + } catch (t: Throwable) { + Log.w(_tag, "injectThemeAwareCss reinjection failed: ${t.message}") + } + // Apply the selected font to the reader UI elements (header/footer/menu) + applyTypefaceToReaderUI() + } + + /** + * Inject theme-aware CSS into the Readium navigator if possible. + * This attempts to evaluate JavaScript in the navigator fragment; if not + * available, it logs a warning and returns. + */ + private fun injectThemeAwareCss() { + val fragment = supportFragmentManager.findFragmentByTag("EpubNavigator") as? EpubNavigatorFragment ?: return + + // Generate base CSS using reader-specific theme if present + val effectiveBg = if (readerConfig.readingBackgroundMode >= 0f) readerConfig.readingBackgroundMode.toInt() else libraryConfig.backgroundMode.toInt() + // Generate base CSS + var css = ThemeAwareCssInjector.generateLeanCss( + backgroundMode = effectiveBg, + fontChoice = libraryConfig.fontChoice.toInt() + ) + + // If user selected Literata and device has sufficient memory, attempt to embed or reference the font. + try { + val wantLiterata = libraryConfig.fontChoice.toInt() == 1 + val lowMem = isLowMemoryDevice() + if (wantLiterata && !lowMem) { + // 1) Prefer an asset copy if the developer placed the TTF in assets/fonts/ + try { + assets.open("fonts/literata_regular.ttf").use { _ -> + // Asset exists: reference via android_asset URL + val fontFace = "@font-face { font-family: 'LiterataCustom'; src: url('file:///android_asset/fonts/literata_regular.ttf') format('truetype'); font-weight: normal; font-style: normal; font-display: swap; }" + val override = "body { font-family: 'LiterataCustom', ${ThemeAwareCssInjector.getThemeColors(effectiveBg, libraryConfig.fontChoice.toInt()).fontFamily} !important; }" + css = fontFace + "\n" + override + "\n" + css + Log.d(_tag, "injectThemeAwareCss: using literata from assets/fonts/literata_regular.ttf") + // Asset used, skip further checks + throw AssetUsedException() + } + } catch (ae: AssetUsedException) { + // intentional control flow to skip further checks + } catch (e: Exception) { + // asset not found, continue to try resources + } + + // 2) Try resource in res/font (if packaged as a font resource) + val resId = resources.getIdentifier("literata_regular", "font", packageName) + if (resId != 0) { + try { + val inp = resources.openRawResource(resId) + val bytes = inp.readBytes() + inp.close() + val maxEmbedBytes = 800 * 1024 // 800 KB cap for embedded font + if (bytes.size <= maxEmbedBytes) { + val b64 = Base64.encodeToString(bytes, Base64.NO_WRAP) + val fontFace = "@font-face { font-family: 'LiterataCustom'; src: url('data:font/ttf;base64,$b64') format('truetype'); font-weight: normal; font-style: normal; font-display: swap; }" + val override = "body { font-family: 'LiterataCustom', ${ThemeAwareCssInjector.getThemeColors(effectiveBg, libraryConfig.fontChoice.toInt()).fontFamily} !important; }" + css = fontFace + "\n" + override + "\n" + css + Log.d(_tag, "injectThemeAwareCss: embedded Literata font (${bytes.size} bytes) from res/font") + } else { + // 3) If too large, write to internal files dir and reference via file:// + try { + val outDir = File(filesDir, "fonts") + if (!outDir.exists()) outDir.mkdirs() + val outFile = File(outDir, "literata_regular.ttf") + if (!outFile.exists() || outFile.length() != bytes.size.toLong()) { + outFile.writeBytes(bytes) + } + val fontFace = "@font-face { font-family: 'LiterataCustom'; src: url('file://${outFile.absolutePath}') format('truetype'); font-weight: normal; font-style: normal; font-display: swap; }" + val override = "body { font-family: 'LiterataCustom', ${ThemeAwareCssInjector.getThemeColors(effectiveBg, libraryConfig.fontChoice.toInt()).fontFamily} !important; }" + css = fontFace + "\n" + override + "\n" + css + Log.d(_tag, "injectThemeAwareCss: wrote Literata to files dir and referencing ${outFile.absolutePath}") + } catch (wf: Exception) { + Log.w(_tag, "injectThemeAwareCss: failed to write literata to files dir: ${wf.message}") + } + } + } catch (e: Exception) { + Log.w(_tag, "injectThemeAwareCss: failed reading font resource for embed: ${e.message}") + } + } else { + Log.d(_tag, "injectThemeAwareCss: literata resource not found (resId=0) and no asset available") + } + } + } catch (e: Exception) { + // Ignore AssetUsedException control-flow or other unexpected errors + if (e is AssetUsedException) { + // no-op + } else { + Log.w(_tag, "injectThemeAwareCss: embed/reference check failed: ${e.message}") + } + } + // Safely quote the CSS for embedding in JS + val quotedCss = try { + JSONObject.quote(css) + } catch (e: Exception) { + // Fallback - simple escaping + "\"" + css.replace("\\", "\\\\").replace("\"", "\\\"").replace("\n", "\\n") + "\"" + } + + val jsCode = """ + (function() { + try { + var styleEl = document.getElementById('nosferatu-theme-injected'); + if (!styleEl) { + styleEl = document.createElement('style'); + styleEl.id = 'nosferatu-theme-injected'; + document.head.appendChild(styleEl); + } + styleEl.textContent = $quotedCss; + console.log('Nosferatu theme CSS injected'); + } catch (e) { + console.warn('Nosferatu CSS injection failed', e); + } + })(); + """.trimIndent() + + try { + // Try common method names via reflection to maximize compatibility + val cls = fragment::class.java + // Try evaluateJavaScript(String) + val evalOne = cls.methods.firstOrNull { it.name.equals("evaluateJavaScript", ignoreCase = true) && it.parameterCount == 1 } + if (evalOne != null) { + evalOne.invoke(fragment, jsCode) + Log.d(_tag, "injectThemeAwareCss: invoked evaluateJavaScript(String) on fragment") + return + } + + // Try evaluateJavascript(String, ValueCallback) + val evalTwo = cls.methods.firstOrNull { it.name.equals("evaluateJavascript", ignoreCase = true) && it.parameterCount >= 1 } + if (evalTwo != null) { + // If method expects two args, pass null for callback + if (evalTwo.parameterCount == 1) { + evalTwo.invoke(fragment, jsCode) + } else { + evalTwo.invoke(fragment, jsCode, null) + } + Log.d(_tag, "injectThemeAwareCss: invoked evaluateJavascript on fragment") + return + } + + // Fallback: attempt to evaluate via fragment's view webviews + val view = fragment.view + if (view != null) { + // Search for a WebView instance inside the fragment's view hierarchy + val webView = findWebViewInView(view) + if (webView != null) { + try { + webView.evaluateJavascript(jsCode, null) + Log.d(_tag, "injectThemeAwareCss: injected via WebView.evaluateJavascript") + return + } catch (e: Exception) { + Log.w(_tag, "injectThemeAwareCss: WebView.evaluateJavascript failed: ${e.message}") + } + } + } + + Log.w(_tag, "injectThemeAwareCss: no compatible evaluate method found on navigator fragment") + } catch (e: Exception) { + Log.w(_tag, "injectThemeAwareCss failed: ${e.message}", e) + } + } + + // Recursively search for a WebView in the view hierarchy + private fun findWebViewInView(root: View): android.webkit.WebView? { + if (root is android.webkit.WebView) return root + if (root !is ViewGroup) return null + for (i in 0 until root.childCount) { + val child = root.getChildAt(i) + val found = findWebViewInView(child) + if (found != null) return found + } + return null + } + + private fun isCurrentLocatorBookmarked(): Boolean { + val locator = _lastKnownLocator ?: return false + val locatorJson = locator.toJSON().toString() + return bookmarkStore.isBookmarkedForBookKey(bookKey, locatorJson) + } + + private fun updateBookmarkIcon() { + try { + val btn = findViewById(R.id.btn_bookmark_toggle) + val isBookmarked = isCurrentLocatorBookmarked() + btn.setImageResource(if (isBookmarked) R.drawable.ic_bookmark_filled else R.drawable.ic_bookmark_outline) + } catch (t: Throwable) { + // ignore + } + } + + private fun updateTocSelection() { + try { + val adapter = tocAdapter ?: return + val recycler = tocRecycler ?: return + val current = _lastKnownLocator ?: return + val currentHref = current.href?.toString() ?: return + + // try to find by href prefix first + var sel = tocFlatLocators.indexOfFirst { it?.href?.toString()?.startsWith(currentHref) == true } + + if (sel < 0) { + val currProg = current.locations.totalProgression ?: 0.0 + var bestIdx = -1 + var bestDiff = Double.MAX_VALUE + for (i in tocFlatLocators.indices) { + val loc = tocFlatLocators[i] ?: continue + val prog = loc.locations.totalProgression ?: continue + val diff = kotlin.math.abs(currProg - prog) + if (diff < bestDiff) { bestDiff = diff; bestIdx = i } + } + sel = bestIdx + } + + if (sel >= 0 && sel < adapter.itemCount) { + adapter.select(sel) + recycler.scrollToPosition(sel) + tocSelectedIndex = sel + } + } catch (t: Throwable) { + // ignore + } + } + + private fun toggleBookmark() { + val locator = _lastKnownLocator + if (locator == null) { + Toast.makeText(this, getString(R.string.no_bookmarks), Toast.LENGTH_SHORT).show() + return + } + val locatorJson = locator.toJSON().toString() + val href = locator.href.toString() + val prog = locator.locations.totalProgression ?: 0.0 + val title = locator.title + val now = System.currentTimeMillis() + if (bookmarkStore.isBookmarkedForBookKey(bookKey, locatorJson)) { + bookmarkStore.removeBookmarkForBookKey(bookKey, locatorJson) + Toast.makeText(this, getString(R.string.bookmark_removed), Toast.LENGTH_SHORT).show() + } else { + val bm = Bookmark(locatorJson, href, prog, title, now) + bookmarkStore.addBookmarkForBookKey(bookKey, bm) + Toast.makeText(this, getString(R.string.bookmark_added), Toast.LENGTH_SHORT).show() + } + updateBookmarkIcon() + } + + private fun openBookmarksPanel() { + val list = bookmarkStore.listBookmarksForBookKey(bookKey) + if (list.isEmpty()) { + Toast.makeText(this, getString(R.string.no_bookmarks), Toast.LENGTH_SHORT).show() + return + } + val labels = list.mapIndexed { idx, bm -> + "Segnalibro ${idx + 1}" + }.toTypedArray() + AlertDialog.Builder(this) + .setTitle(getString(R.string.bookmarks_title)) + .setItems(labels) { dialog, which -> + val chosen = list[which] + // Show action dialog: Apri or Rimuovi + val detailTitle = (chosen.chapterTitle ?: chosen.href) ?: labels[which] + AlertDialog.Builder(this) + .setTitle("${labels[which]} — $detailTitle") + .setItems(arrayOf(getString(R.string.open_bookmark), getString(R.string.remove_bookmark))) { d, index -> + when (index) { + 0 -> { + // Open + try { + val locatorObj = try { Locator.fromJSON(JSONObject(chosen.locatorJson)) } catch (e: Exception) { null } + val navigator = supportFragmentManager.findFragmentByTag("EpubNavigator") as? EpubNavigatorFragment + if (navigator != null && locatorObj != null) { + lifecycleScope.launch { navigator.go(locatorObj, animated = false) } + } + } catch (t: Throwable) { /* ignore */ } + } + 1 -> { + // Remove + bookmarkStore.removeBookmarkForBookKey(bookKey, chosen.locatorJson) + Toast.makeText(this, getString(R.string.bookmark_removed), Toast.LENGTH_SHORT).show() + } + } + } + .show() + } + .setNegativeButton(android.R.string.cancel, null) + .show() + } + + private fun applyTypefaceToReaderUI() { + try { + val resId = resources.getIdentifier("literata_regular", "font", packageName) + val tf: Typeface? = if (libraryConfig.fontChoice.toInt() == 1 && resId != 0) { + ResourcesCompat.getFont(this, resId) + } else Typeface.DEFAULT + + //val header = findViewById(R.id.immersive_header_title) + val footer = findViewById(R.id.immersive_footer_text) + val page = findViewById(R.id.menu_page_text) + val title = findViewById(R.id.menu_book_title) + val author = findViewById(R.id.menu_book_author) + + //header.typeface = tf + footer.typeface = tf + page.typeface = tf + title.typeface = tf + author.typeface = tf + } catch (t: Throwable) { + Log.w(_tag, "Impossibile applicare il font personalizzato: ${t.message}") + } + } + + // --- TOC extraction & panel ------------------------------------------------- + private data class TocNode(val title: String?, val href: String?, val children: List = emptyList()) + + private fun extractToc(pub: Publication?): List { + if (pub == null) return emptyList() + try { + val cls = pub.javaClass + val candidateNames = arrayOf("getTableOfContents", "getToc", "getTableOfContent", "tableOfContents") + var tocObj: Any? = null + for (name in candidateNames) { + try { + val m = cls.getMethod(name) + tocObj = m.invoke(pub) + if (tocObj != null) break + } catch (nm: NoSuchMethodException) { + // try next + } + } + if (tocObj == null) return emptyList() + if (tocObj !is List<*>) return emptyList() + + fun mapLink(linkObj: Any?): TocNode? { + if (linkObj == null) return null + try { + val lcls = linkObj.javaClass + val getTitle = try { lcls.getMethod("getTitle") } catch (_: Exception) { null } + val getHref = try { lcls.getMethod("getHref") } catch (_: Exception) { null } + val getChildren = try { lcls.getMethod("getChildren") } catch (_: Exception) { null } + val title = getTitle?.invoke(linkObj) as? String + val hrefObj = getHref?.invoke(linkObj) + val hrefStr = hrefObj?.toString() + val children = mutableListOf() + if (getChildren != null) { + val ch = getChildren.invoke(linkObj) + if (ch is List<*>) { + for (c in ch) { + val mapped = mapLink(c) + if (mapped != null) children.add(mapped) + } + } + } + return TocNode(title, hrefStr, children) + } catch (t: Throwable) { + return null + } + } + + val out = mutableListOf() + for (item in tocObj as List<*>) { + val node = mapLink(item) + if (node != null) out.add(node) + } + return out + } catch (t: Throwable) { + Log.w(_tag, "TOC extract failed: ${t.message}") + return emptyList() + } + } + + private fun flattenToc(nodes: List, depth: Int = 0, out: MutableList>) { + for (n in nodes) { + out.add(n to depth) + if (n.children.isNotEmpty()) flattenToc(n.children, depth + 1, out) + } + } + + // Normalize hrefs for matching: strip fragment, leading ./ or /, and trim + private fun normalizeHrefForMatch(href: String?): String? { + if (href == null) return null + var h = href + // remove fragment + val hashIdx = h.indexOf('#') + if (hashIdx >= 0) h = h.substring(0, hashIdx) + // remove query + val qIdx = h.indexOf('?') + if (qIdx >= 0) h = h.substring(0, qIdx) + h = h.trim() + h = h.removePrefix("./").removePrefix("/") + // decode percent-encoding if present + try { + h = URLDecoder.decode(h, "UTF-8") + } catch (_: Exception) { } + // strip common extensions used in EPUBs + h = h.replace(Regex("\\.(x?html?|xml|ncx|opf|htm|xht)", RegexOption.IGNORE_CASE), "") + return if (h.isEmpty()) null else h + } + + // Heuristic matcher: try exact, suffix, contains, last-segment match + private fun findBestPositionForHref(href: String?, positions: List): Locator? { + if (href == null) return null + val target = normalizeHrefForMatch(href) ?: return null + + val normalized = positions.map { pos -> + val ph = pos.href?.toString() + Pair(pos, normalizeHrefForMatch(ph)) + } + + // exact + normalized.firstOrNull { it.second == target }?.let { return it.first } + + // endsWith (covers paths like "OPS/ch1.xhtml" vs "ch1.xhtml") + normalized.firstOrNull { it.second != null && it.second!!.endsWith(target) }?.let { return it.first } + + // contains + normalized.firstOrNull { it.second != null && it.second!!.contains(target) }?.let { return it.first } + + // last segment match + val targetLast = target.substringAfterLast('/') + normalized.firstOrNull { it.second != null && it.second!!.substringAfterLast('/') == targetLast }?.let { return it.first } + + return null + } + + private fun getRuntimeTypeface(): Typeface? { + val resId = resources.getIdentifier("literata_regular", "font", packageName) + return if (libraryConfig.fontChoice.toInt() == 1 && resId != 0) { + try { ResourcesCompat.getFont(this, resId) } catch (_: Exception) { null } + } else null + } + + // RecyclerView adapter for the TOC bottom sheet (supports headers and items) + private inner class TocAdapter( + private val items: List>, + private val onClick: (Int) -> Unit + ) : RecyclerView.Adapter() { + var selectedIndex: Int = -1 + + private val VIEW_TYPE_HEADER = 0 + private val VIEW_TYPE_ITEM = 1 + + // Precompute theme colors and runtime typeface (respect reader-only theme if set) + private val effectiveBgForToc = if (readerConfig.readingBackgroundMode >= 0f) readerConfig.readingBackgroundMode.toInt() else libraryConfig.backgroundMode.toInt() + private val appColors = appColorsFor(effectiveBgForToc.toFloat()) + private val selectedBgColor = appColors.selectedRowBackground.toArgb() + private val textColorInt = appColors.onBg.toArgb() + private val iconColorInt = appColors.onBg.toArgb() + private val runtimeTf = getRuntimeTypeface() + + inner class HeaderVH(val view: View) : RecyclerView.ViewHolder(view) { + val title: TextView = view.findViewById(R.id.toc_item_title) + init { + view.setOnClickListener { val pos = bindingAdapterPosition; if (pos != RecyclerView.NO_POSITION) onClick(pos) } + } + } + + inner class ItemVH(val view: View) : RecyclerView.ViewHolder(view) { + val icon: ImageView = view.findViewById(R.id.toc_item_icon) + val title: TextView = view.findViewById(R.id.toc_item_title) + init { + view.setOnClickListener { val pos = bindingAdapterPosition; if (pos != RecyclerView.NO_POSITION) onClick(pos) } + } + } + + override fun getItemViewType(position: Int): Int { + val (node, depth) = items[position] + return if (depth == 0 && node.children.isNotEmpty()) VIEW_TYPE_HEADER else VIEW_TYPE_ITEM + } + + override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { + return if (viewType == VIEW_TYPE_HEADER) { + val v = LayoutInflater.from(parent.context).inflate(R.layout.item_toc_header, parent, false) + HeaderVH(v) + } else { + val v = LayoutInflater.from(parent.context).inflate(R.layout.item_toc, parent, false) + ItemVH(v) + } + } + + override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { + val (node, depth) = items[position] + val titleStr = node.title ?: node.href ?: "-" + + val base = resources.getDimensionPixelSize(R.dimen.spacing_16) + val padStart = base + depth * (base / 2) + + if (holder is HeaderVH) { + holder.title.text = titleStr + holder.title.setPadding(padStart, holder.title.paddingTop, holder.title.paddingRight, holder.title.paddingBottom) + holder.title.contentDescription = titleStr + holder.title.setTextColor(textColorInt) + runtimeTf?.let { holder.title.typeface = it } + // header styling + if (position == selectedIndex) { + holder.view.setBackgroundColor(selectedBgColor) + } else { + holder.view.setBackgroundResource(0) + } + } else if (holder is ItemVH) { + holder.title.text = titleStr + holder.title.setPadding(padStart, holder.title.paddingTop, holder.title.paddingRight, holder.title.paddingBottom) + holder.title.contentDescription = titleStr + holder.title.setTextColor(textColorInt) + runtimeTf?.let { holder.title.typeface = it } + + // icon: parents show chevron, leaves show toc/book icon + if (node.children.isNotEmpty()) { + holder.icon.setImageResource(R.drawable.ic_expand_more) + } else { + holder.icon.setImageResource(R.drawable.ic_toc) + } + holder.icon.setColorFilter(iconColorInt) + + if (position == selectedIndex) { + holder.view.setBackgroundColor(selectedBgColor) + holder.title.setTypeface(null, Typeface.BOLD) + } else { + holder.view.setBackgroundResource(0) + holder.title.setTypeface(null, Typeface.NORMAL) + } + } + } + + override fun getItemCount(): Int = items.size + + fun select(idx: Int) { + val prev = selectedIndex + selectedIndex = idx + if (prev >= 0) notifyItemChanged(prev) + if (idx >= 0) notifyItemChanged(idx) + } + } + + private fun openTocPanel() { + // Try loading TOC from DB first, fall back to runtime extraction + lifecycleScope.launch { + val repo = (application as NosferatuApp).repository + + val dbEntries = try { + withContext(Dispatchers.IO) { repo.getTocEntriesForBook(bookId) } + } catch (t: Throwable) { + Log.w(_tag, "Failed to load TOC from DB: ${t.message}") + emptyList() + } + + Log.d(_tag, "openTocPanel: loaded ${dbEntries.size} entries from DB for bookId=$bookId") + + val tocNodes: List = if (dbEntries.isNotEmpty()) { + dbEntries.sortedBy { it.position }.map { TocNode(it.title, it.href, emptyList()) } + } else { + Log.d(_tag, "openTocPanel: DB empty, extracting runtime TOC from publication") + val runtime = extractToc(publication) + Log.d(_tag, "openTocPanel: runtime extract returned ${runtime.size} TOC nodes") + runtime + } + + if (tocNodes.isEmpty()) { + withContext(Dispatchers.Main) { + Toast.makeText(this@ReaderActivity, "Indice non disponibile", Toast.LENGTH_SHORT).show() + } + return@launch + } + + val flat = mutableListOf>() + flattenToc(tocNodes, 0, flat) + val labels = flat.map { (node, depth) -> + val title = node.title ?: node.href ?: "-" + "${"\u00A0".repeat(depth * 2)}$title" + }.toTypedArray() + + // store labels so other code can reference them + tocFlatLabels = labels + tocFlatLocators.clear() + for (i in labels.indices) tocFlatLocators.add(null) + + val pub = publication + if (pub == null) { + withContext(Dispatchers.Main) { + Toast.makeText(this@ReaderActivity, "Impossibile navigare al capitolo selezionato", Toast.LENGTH_SHORT).show() + } + return@launch + } + + // Compute mapping between TOC hrefs and publication positions in background + val hrefs = flat.map { it.first.href } + val positions = try { pub.positions() } catch (_: Throwable) { emptyList() } + + val matched = hrefs.map { href -> + findBestPositionForHref(href, positions) + } + + val matchedCount = matched.count { it != null } + val unmatchedCount = matched.count { it == null } + Log.d(_tag, "openTocPanel: matched positions=$matchedCount unmatched=$unmatchedCount for ${hrefs.size} hrefs") + + tocFlatLocators.clear() + tocFlatLocators.addAll(matched) + + // determine selected index based on current locator + val current = _lastKnownLocator + var selected = -1 + if (current != null) { + val currentHref = current.href?.toString() + val currentProg = current.locations.totalProgression ?: 0.0 + if (currentHref != null) { + selected = matched.indexOfFirst { it?.href?.toString()?.startsWith(currentHref) == true } + } + if (selected < 0) { + // fallback to nearest progression + var bestIdx = -1 + var bestDiff = Double.MAX_VALUE + for (i in matched.indices) { + val m = matched[i] ?: continue + val prog = m.locations.totalProgression ?: continue + val diff = kotlin.math.abs(currentProg - prog) + if (diff < bestDiff) { bestDiff = diff; bestIdx = i } + } + selected = bestIdx + } + } + + tocSelectedIndex = selected + + // Show bottom-sheet on main thread with a RecyclerView for better UX + withContext(Dispatchers.Main) { + val dialog = BottomSheetDialog(this@ReaderActivity) + val content = layoutInflater.inflate(R.layout.bottom_sheet_toc, null) + val recycler = content.findViewById(R.id.toc_recycler) + + val adapter = TocAdapter(flat) { which -> + Log.d(_tag, "openTocPanel: user selected TOC index=$which") + val chosenLocator = tocFlatLocators.getOrNull(which) + val navigator = supportFragmentManager.findFragmentByTag("EpubNavigator") as? EpubNavigatorFragment + if (navigator != null && chosenLocator != null) { + lifecycleScope.launch { + Log.d(_tag, "openTocPanel: navigating to locator href=${chosenLocator.href} progression=${chosenLocator.locations.totalProgression}") + navigator.go(chosenLocator, animated = false) + } + dialog.dismiss() + } else { + lifecycleScope.launch { + try { + Log.d(_tag, "openTocPanel: fallback navigation for index=$which, href=${hrefs.getOrNull(which)}") + val pos = try { pub.positions() } catch (_: Throwable) { emptyList() } + val target = findBestPositionForHref(hrefs[which], pos) + if (target != null) { + val nav = supportFragmentManager.findFragmentByTag("EpubNavigator") as? EpubNavigatorFragment + if (nav != null) { + Log.d(_tag, "openTocPanel: fallback resolved locator href=${target.href} progression=${target.locations.totalProgression}") + nav.go(target, animated = false) + } + } else { + withContext(Dispatchers.Main) { + Toast.makeText(this@ReaderActivity, getString(R.string.toc_navigation_failed), Toast.LENGTH_SHORT).show() + } + } + } catch (t: Throwable) { + Log.w(_tag, "TOC navigation error: ${t.message}") + } + } + dialog.dismiss() + } + } + + recycler.layoutManager = LinearLayoutManager(this@ReaderActivity) + recycler.adapter = adapter + + // set initial selection and expose adapter/recycler for updates + adapter.select(tocSelectedIndex) + if (tocSelectedIndex >= 0) recycler.scrollToPosition(tocSelectedIndex) + + dialog.setContentView(content) + dialog.setOnDismissListener { + tocDialog = null + tocAdapter = null + tocRecycler = null + } + + tocDialog = dialog + tocAdapter = adapter + tocRecycler = recycler + dialog.show() + + // expand sheet and animate entrance + val bottomSheet = dialog.findViewById(com.google.android.material.R.id.design_bottom_sheet) + if (bottomSheet != null) { + try { + // Apply reader theme background to the bottom sheet so it matches the reader theme + try { + val effectiveSheetBg = if (readerConfig.readingBackgroundMode >= 0f) readerConfig.readingBackgroundMode.toInt() else libraryConfig.backgroundMode.toInt() + val sheetColor = appColorsFor(effectiveSheetBg.toFloat()).bg.toArgb() + bottomSheet.setBackgroundColor(sheetColor) + } catch (_: Exception) { } + val behavior = BottomSheetBehavior.from(bottomSheet) + behavior.state = BottomSheetBehavior.STATE_EXPANDED + } catch (_: Exception) { } + } + } + } } private fun updateUiWithLocator(locator: Locator) { @@ -267,7 +1175,7 @@ class ReaderActivity : AppCompatActivity(), EpubNavigatorFragment.Listener { val bookTitle = publication?.metadata?.title?.uppercase() ?: (TestReaderInjector.fakeTitle?.uppercase() ?: "") val bookAuthor = publication?.metadata?.authors?.firstOrNull()?.name ?: TestReaderInjector.fakeAuthor - findViewById(R.id.immersive_header_title).text = chapterTitle.uppercase() + //findViewById(R.id.immersive_header_title).text = chapterTitle.uppercase() findViewById(R.id.immersive_footer_text).text = getString(com.nosferatu.launcher.R.string.reader_footer_format, bookTitle, percent) findViewById(R.id.immersive_progress_bar).progress = percent @@ -325,7 +1233,6 @@ class ReaderActivity : AppCompatActivity(), EpubNavigatorFragment.Listener { val bottomBar = findViewById(R.id.menu_bottom_bar) val immersiveFooter = findViewById(R.id.immersive_footer) val fontContainer = findViewById(R.id.font_controls_container) - val btnFontSettings = findViewById(R.id.btn_font_settings) if (isMenuVisible) { topBar.visibility = View.VISIBLE @@ -337,13 +1244,64 @@ class ReaderActivity : AppCompatActivity(), EpubNavigatorFragment.Listener { immersiveFooter.visibility = View.VISIBLE isFontBarVisible = false fontContainer.visibility = View.GONE - btnFontSettings.rotation = 0f + } + } + + private fun hideSystemUI() { + try { + val windowInsetsController = WindowCompat.getInsetsController(window, window.decorView) + windowInsetsController.systemBarsBehavior = + WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE + windowInsetsController.hide(WindowInsetsCompat.Type.statusBars()) + } catch (t: Throwable) { + Log.w(_tag, "hideSystemUI failed: ${t.message}") } } private suspend fun openPublication(file: File): Publication = withContext(Dispatchers.IO) { - val asset = assetRetriever.retrieve(file).getOrElse { throw Exception("Asset fallito") } - publicationOpener.open(asset, allowUserInteraction = true).getOrElse { throw Exception("Opener fallito") } + val startTime = System.currentTimeMillis() + Log.d(_tag, "openPublication: START - ${file.name}") + + // 🔴 AGGRESSIVE: Force garbage collection before EPUB rendering + // On 1GB device, this helps free up memory for Chromium tile allocation + System.gc() + Thread.sleep(50) // Brief pause to let GC complete + + // 🔴 LOG MEMORY STATUS AT EPUB OPEN TIME + val activityManager = getSystemService(Context.ACTIVITY_SERVICE) as? ActivityManager + val memInfo = ActivityManager.MemoryInfo() + activityManager?.getMemoryInfo(memInfo) + val availableMB = memInfo.availMem / (1024 * 1024) + Log.d(_tag, "📊 EPUB OPEN: Available memory = ${availableMB}MB after GC") + + // Phase 1: Check if extracted cache is available (Phase 1 timing) + val cacheStartTime = System.currentTimeMillis() + val extractedPath = epubCacheManager.getExtractedPath(file) + val cacheLookupTime = System.currentTimeMillis() - cacheStartTime + + val sourceFile = extractedPath ?: file + Log.d(_tag, "openPublication: cache lookup ${cacheLookupTime}ms - using ${sourceFile.name}") + + // Phase 2: Open publication from extracted cache or fallback to original + val openStartTime = System.currentTimeMillis() + val asset = assetRetriever.retrieve(sourceFile).getOrElse { + Log.e(_tag, "openPublication: asset retrieval failed, falling back to source file") + assetRetriever.retrieve(file).getOrElse { throw Exception("Asset fallito") } + } + val assetRetrievalTime = System.currentTimeMillis() - openStartTime + + // Phase 3: Open publication + val pubOpenStartTime = System.currentTimeMillis() + val pub = publicationOpener.open(asset, allowUserInteraction = true).getOrElse { + throw Exception("Opener fallito") + } + val pubOpenTime = System.currentTimeMillis() - pubOpenStartTime + + val totalTime = System.currentTimeMillis() - startTime + Log.d(_tag, "openPublication: COMPLETE in ${totalTime}ms") + Log.d(_tag, "openPublication: cache_lookup=${cacheLookupTime}ms asset_retrieval=${assetRetrievalTime}ms pub_open=${pubOpenTime}ms") + + pub } private fun saveLocation(bookId: Long, locator: Locator?) { @@ -361,6 +1319,15 @@ class ReaderActivity : AppCompatActivity(), EpubNavigatorFragment.Listener { override fun onDestroy() { publication?.close() + // Cleanup status bar timer and receiver + statusBarClockTimer?.cancel() + statusBarBatteryReceiver?.let { + try { + unregisterReceiver(it) + } catch (e: Exception) { + Log.w(_tag, "Error unregistering battery receiver: ${e.message}") + } + } super.onDestroy() } @@ -405,6 +1372,93 @@ class ReaderActivity : AppCompatActivity(), EpubNavigatorFragment.Listener { navigator.go(target, animated = false) } + private fun setupCustomStatusBar() { + try { + val container = findViewById(R.id.reader_status_bar_container) ?: return + val statusBarView = layoutInflater.inflate(R.layout.reader_status_bar, container, false) + container.addView(statusBarView) + + val clockTextView = statusBarView.findViewById(R.id.reader_status_clock) + val batteryPercentageView = statusBarView.findViewById(R.id.reader_battery_percentage) + val batteryFillView = statusBarView.findViewById(R.id.reader_battery_fill) + + // Setup clock update timer (every second) - update UI on main thread + statusBarClockTimer = kotlin.concurrent.timer(initialDelay = 0, period = 1000) { + try { + val now = System.currentTimeMillis() + val timeStr = java.text.SimpleDateFormat("HH:mm", java.util.Locale.getDefault()).format(java.util.Date(now)) + this@ReaderActivity.runOnUiThread { + try { clockTextView.text = timeStr } catch (_: Exception) {} + } + } catch (e: Exception) { + Log.w(_tag, "Clock update failed: ${e.message}") + } + } + + // Setup battery update receiver + val intentFilter = android.content.IntentFilter(android.content.Intent.ACTION_BATTERY_CHANGED) + + // Populate initial battery state from sticky intent + try { + val sticky = registerReceiver(null, intentFilter) + if (sticky != null) { + try { + val level = sticky.getIntExtra(android.os.BatteryManager.EXTRA_LEVEL, -1) + val scale = sticky.getIntExtra(android.os.BatteryManager.EXTRA_SCALE, -1) + val percentage = if (level >= 0 && scale > 0) (level * 100) / scale else 0 + runOnUiThread { + try { + batteryPercentageView.text = "$percentage%" + val totalPx = 18.dpToPx() + val fillWidth = (totalPx * percentage) / 100 + val p = batteryFillView.layoutParams + p.width = fillWidth + batteryFillView.layoutParams = p + } catch (_: Exception) {} + } + } catch (e: Exception) { + Log.w(_tag, "Initial battery read failed: ${e.message}") + } + } + } catch (t: Throwable) { + Log.w(_tag, "Initial battery sticky intent failed: ${t.message}") + } + + statusBarBatteryReceiver = object : android.content.BroadcastReceiver() { + override fun onReceive(context: android.content.Context?, intent: android.content.Intent?) { + try { + val level = intent?.getIntExtra(android.os.BatteryManager.EXTRA_LEVEL, -1) ?: -1 + val scale = intent?.getIntExtra(android.os.BatteryManager.EXTRA_SCALE, -1) ?: -1 + val percentage = if (level >= 0 && scale > 0) (level * 100) / scale else 0 + runOnUiThread { + try { + batteryPercentageView.text = "$percentage%" + val totalPx = 18.dpToPx() + val fillWidth = (totalPx * percentage) / 100 + val p = batteryFillView.layoutParams + p.width = fillWidth + batteryFillView.layoutParams = p + } catch (e: Exception) { + Log.w(_tag, "Battery UI update failed: ${e.message}") + } + } + } catch (e: Exception) { + Log.w(_tag, "Battery update failed: ${e.message}") + } + } + } + + // Register battery receiver (no permission param) + try { + registerReceiver(statusBarBatteryReceiver, intentFilter) + } catch (t: Throwable) { + Log.w(_tag, "registerReceiver failed: ${t.message}") + } + } catch (t: Throwable) { + Log.w(_tag, "setupCustomStatusBar failed: ${t.message}") + } + } + override fun dispatchKeyEvent(event: KeyEvent): Boolean { if (libraryConfig.volumeKeys && event.action == KeyEvent.ACTION_DOWN) { val navigator = supportFragmentManager.findFragmentByTag("EpubNavigator") as? EpubNavigatorFragment diff --git a/app/src/main/java/com/nosferatu/launcher/reader/ReaderSettingsBottomSheet.kt b/app/src/main/java/com/nosferatu/launcher/reader/ReaderSettingsBottomSheet.kt new file mode 100644 index 0000000..ebeb383 --- /dev/null +++ b/app/src/main/java/com/nosferatu/launcher/reader/ReaderSettingsBottomSheet.kt @@ -0,0 +1,172 @@ +package com.nosferatu.launcher.reader + +import android.os.Bundle +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.view.ViewGroup.LayoutParams +import android.content.DialogInterface +import androidx.core.view.WindowCompat +import androidx.core.view.WindowInsetsCompat +import androidx.core.view.WindowInsetsControllerCompat +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.darkColorScheme +import androidx.compose.material3.lightColorScheme +import androidx.compose.material3.Typography +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.ui.platform.ComposeView +import androidx.compose.ui.platform.ViewCompositionStrategy +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.graphics.toArgb +import com.google.android.material.bottomsheet.BottomSheetBehavior +import com.google.android.material.bottomsheet.BottomSheetDialogFragment +import com.nosferatu.launcher.R +import com.nosferatu.launcher.library.LibraryConfig +import com.nosferatu.launcher.library.ReaderConfig +import com.nosferatu.launcher.ui.LocalAppColors +import com.nosferatu.launcher.ui.appColorsFor +import com.nosferatu.launcher.ui.components.fontsettings.ReaderTextSettings +import com.nosferatu.launcher.ui.components.common.SingleChoiceOptionRow + +class ReaderSettingsBottomSheet : BottomSheetDialogFragment() { + + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { + val root = inflater.inflate(R.layout.reader_settings_popup, container, false) + val compose = root.findViewById(R.id.reader_settings_compose) + + // Safe composition strategy + try { compose.setViewCompositionStrategy(ViewCompositionStrategy.DisposeOnDetachedFromWindow) } catch (_: Exception) {} + + compose.setContent { + val act = activity as? ReaderActivity + val ctx = requireContext() + val libraryConfig = act?.provideLibraryConfig() ?: LibraryConfig(ctx) + val readerConfig = act?.provideReaderConfig() ?: ReaderConfig(ctx) + + val selectionBgMode = if (readerConfig.readingBackgroundMode >= 0f) readerConfig.readingBackgroundMode.toInt() else libraryConfig.backgroundMode.toInt() + val appColors = appColorsFor(libraryConfig.backgroundMode) + val isDark = libraryConfig.backgroundMode.toInt() == 2 + val colorScheme = if (isDark) { + darkColorScheme().copy( + background = appColors.bg, + surface = appColors.surface, + onBackground = appColors.onBg, + onSurface = appColors.onBg + ) + } else { + lightColorScheme( + background = appColors.bg, + surface = appColors.surface, + onBackground = appColors.onBg, + onSurface = appColors.onBg + ) + } + + val baseTypography = Typography() + + MaterialTheme(colorScheme = colorScheme, typography = baseTypography) { + CompositionLocalProvider(LocalAppColors provides appColors) { + Column( + modifier = androidx.compose.ui.Modifier + .fillMaxWidth() + .background(appColors.bg) + ) { + ReaderTextSettings( + libraryConfig = libraryConfig, + onPreferenceChanged = { (activity as? ReaderActivity)?.applyReaderPreferences() } + ) + val whiteLabel = stringResource(id = R.string.color_white) + val creamLabel = stringResource(id = R.string.color_cream) + val blackLabel = stringResource(id = R.string.color_black) + + SingleChoiceOptionRow(label = whiteLabel, selected = (selectionBgMode == 0), onClick = { + readerConfig.updateReadingBackgroundMode(0f) + (activity as? ReaderActivity)?.applyReaderPreferences() + dismiss() + }) + SingleChoiceOptionRow(label = creamLabel, selected = (selectionBgMode == 1), onClick = { + readerConfig.updateReadingBackgroundMode(1f) + (activity as? ReaderActivity)?.applyReaderPreferences() + dismiss() + }) + SingleChoiceOptionRow(label = blackLabel, selected = (selectionBgMode == 2), onClick = { + readerConfig.updateReadingBackgroundMode(2f) + (activity as? ReaderActivity)?.applyReaderPreferences() + dismiss() + }) + } + } + } + } + + return root + } + + override fun onStart() { + super.onStart() + try { + val dlg = dialog + val bottomSheet = dlg?.findViewById(com.google.android.material.R.id.design_bottom_sheet) + if (bottomSheet != null) { + val lp = bottomSheet.layoutParams + lp?.width = LayoutParams.MATCH_PARENT + lp?.height = LayoutParams.WRAP_CONTENT + bottomSheet.layoutParams = lp + bottomSheet.requestLayout() + + // Apply theme background + try { + val libraryConfig = LibraryConfig(requireContext()) + bottomSheet.setBackgroundColor(appColorsFor(libraryConfig.backgroundMode).bg.toArgb()) + } catch (_: Exception) {} + + try { + val behavior = BottomSheetBehavior.from(bottomSheet) + try { behavior.isFitToContents = true } catch (_: Throwable) {} + try { behavior.isHideable = true } catch (_: Throwable) {} + try { behavior.skipCollapsed = false } catch (_: Throwable) {} + + bottomSheet.post { + try { + val contentH = if (bottomSheet.height > 0) bottomSheet.height else bottomSheet.measuredHeight + if (contentH > 0) { + try { behavior.peekHeight = contentH } catch (_: Throwable) {} + } + try { behavior.state = BottomSheetBehavior.STATE_COLLAPSED } catch (_: Throwable) {} + } catch (_: Throwable) {} + } + } catch (_: Exception) {} + // Try to hide system status bar on the dialog's window so it doesn't show when the sheet appears + try { + val dlgWindow = dlg?.window + if (dlgWindow != null) { + try { WindowCompat.setDecorFitsSystemWindows(dlgWindow, false) } catch (_: Throwable) {} + val dlgController = WindowCompat.getInsetsController(dlgWindow, dlgWindow.decorView) + dlgController?.let { + try { it.systemBarsBehavior = WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE } catch (_: Throwable) {} + try { it.hide(WindowInsetsCompat.Type.statusBars()) } catch (_: Throwable) {} + } + } + } catch (_: Exception) {} + } + } catch (_: Exception) {} + } + + override fun onDismiss(dialog: DialogInterface) { + super.onDismiss(dialog) + // Ensure the activity re-applies immersive/hide-status behavior when the sheet is dismissed + try { + val act = activity ?: return + val controller = WindowCompat.getInsetsController(act.window, act.window.decorView) + controller?.let { + try { + it.systemBarsBehavior = WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE + it.hide(WindowInsetsCompat.Type.statusBars()) + } catch (_: Exception) {} + } + } catch (_: Exception) {} + } +} diff --git a/app/src/main/java/com/nosferatu/launcher/reader/ThemeAwareCssInjector.kt b/app/src/main/java/com/nosferatu/launcher/reader/ThemeAwareCssInjector.kt new file mode 100644 index 0000000..c749778 --- /dev/null +++ b/app/src/main/java/com/nosferatu/launcher/reader/ThemeAwareCssInjector.kt @@ -0,0 +1,121 @@ +package com.nosferatu.launcher.reader + +import android.util.Log + +object ThemeAwareCssInjector { + private const val TAG = "ThemeAwareCssInjector" + + data class ThemeColors( + val background: String, + val foreground: String, + val accent: String, + val fontFamily: String + ) + + fun getThemeColors(backgroundMode: Int, fontChoice: Int): ThemeColors { + val (bg, fg, accent) = when (backgroundMode) { + 1 -> Triple("#FFF8E1", "#333333", "#D4A574") // Cream + 2 -> Triple("#222222", "#E8E8E8", "#BB86FC") // Dark + else -> Triple("#FFFFFF", "#000000", "#6200EE") // Light + } + + val font = when (fontChoice) { + 1 -> "Georgia, serif" // Literata fallback + else -> "system-ui, -apple-system, sans-serif" + } + + return ThemeColors(bg, fg, accent, font) + } + + fun generateLeanCss(backgroundMode: Int, fontChoice: Int): String { + val colors = getThemeColors(backgroundMode, fontChoice) + + Log.d(TAG, "Generating CSS: bg=${colors.background}, fg=${colors.foreground}, font=${colors.fontFamily}") + + return """ + /* === Nosferatu Theme-Aware Lean CSS === */ + + body { + background-color: ${colors.background} !important; + color: ${colors.foreground} !important; + font-family: ${colors.fontFamily} !important; + line-height: 1.6 !important; + margin: 1em !important; + padding: 0.5em !important; + } + + p { + margin: 0.5em 0 !important; + orphans: 3; + widows: 3; + } + + h1, h2, h3, h4, h5, h6 { + color: ${colors.accent} !important; + font-weight: 700 !important; + line-height: 1.3 !important; + margin-top: 1.5em !important; + margin-bottom: 0.5em !important; + } + + h1 { font-size: 1.8em; } + h2 { font-size: 1.5em; } + h3 { font-size: 1.3em; } + + a { + color: ${colors.accent} !important; + text-decoration: underline !important; + } + + strong, b { + font-weight: 700 !important; + } + + em, i { + font-style: italic !important; + } + + blockquote { + border-left: 3px solid ${colors.accent} !important; + margin-left: 1em !important; + padding-left: 1em !important; + opacity: 0.9 !important; + } + + code, pre { + background-color: ${if (backgroundMode == 2) "#333333" else "#f0f0f0"} !important; + font-family: 'Courier New', monospace !important; + padding: 0.2em 0.4em !important; + border-radius: 2px !important; + } + + img { + max-width: 100% !important; + height: auto !important; + display: block !important; + } + + hr { + border: none !important; + border-top: 1px solid ${colors.accent} !important; + } + + table { + width: 100% !important; + border-collapse: collapse !important; + } + + th, td { + border: 1px solid ${colors.accent} !important; + padding: 0.5em !important; + text-align: left !important; + } + + /* Disable publisher styles selectively */ + .publisher-style { display: none !important; } + + /* Support common EPUB classes */ + .toc, .ncx { display: none !important; } + """.trimIndent() + } +} diff --git a/app/src/main/java/com/nosferatu/launcher/repository/LibraryRepository.kt b/app/src/main/java/com/nosferatu/launcher/repository/LibraryRepository.kt index 5014573..2cf67bc 100644 --- a/app/src/main/java/com/nosferatu/launcher/repository/LibraryRepository.kt +++ b/app/src/main/java/com/nosferatu/launcher/repository/LibraryRepository.kt @@ -4,6 +4,9 @@ import android.net.Uri import android.util.Log import androidx.documentfile.provider.DocumentFile import com.nosferatu.launcher.data.BookDao +import com.nosferatu.launcher.data.TocDao +import com.nosferatu.launcher.data.TocEntryEntity +import com.nosferatu.launcher.parser.TocParser import com.nosferatu.launcher.library.CoverManager import com.nosferatu.launcher.library.LibraryConfig import com.nosferatu.launcher.library.LibraryScanner @@ -14,7 +17,8 @@ class LibraryRepository( private val bookDao: BookDao, private val scanner: LibraryScanner, private val coverManager: CoverManager, - private val libraryConfig: LibraryConfig + private val libraryConfig: LibraryConfig, + private val tocDao: TocDao? = null ) { val allBooks = bookDao.getAllBooksFlow() private val _tag = "LibraryRepository" @@ -34,19 +38,82 @@ class LibraryRepository( // Add books/update books filesOnDisk.forEach { file -> Log.d(_tag, "Processing file: ${file.absolutePath}") - val existingBook = bookDao.getBookByPath(file.absolutePath) - if (existingBook == null || existingBook.lastModified != file.lastModified()) { - val metadata = scanner.extractMetadata(file) ?: return@forEach - val coverPath = coverManager.saveCover(metadata.title, metadata.coverImage) + // Load existing book record (if any) + val existingBook = try { + bookDao.getBookByPath(file.absolutePath) + } catch (e: Exception) { + Log.w(_tag, "Failed to read existing book for path ${file.absolutePath}: ${e.message}") + null + } + + // If book already imported and TOC was previously imported and file unchanged, skip work + val wasTocImported = try { bookDao.isTocImported(file.absolutePath) } catch (e: Exception) { null } + if (existingBook != null && wasTocImported == true && existingBook.lastModified == file.lastModified()) { + Log.d(_tag, "Skipping file (TOC already imported and unchanged): ${file.absolutePath} (bookId=${existingBook.id})") + return@forEach + } - val entity = metadata.toEntity( - lastModified = file.lastModified(), - coverPath = coverPath - ) + val metadata = scanner.extractMetadata(file) + if (metadata == null) { + Log.w(_tag, "Failed to extract metadata for file: ${file.absolutePath}, skipping") + return@forEach + } + val coverPath = coverManager.saveCover(metadata.title, metadata.coverImage) + + val entity = metadata.toEntity( + lastModified = file.lastModified(), + coverPath = coverPath + ) + + // Insert or replace the book entry + try { bookDao.insertBook(entity) - Log.d(_tag, "Cover saved at: $coverPath for book ${entity.id}") + Log.d(_tag, "Inserted/updated book: ${entity.title} path=${entity.filePath}") + } catch (e: Exception) { + Log.w(_tag, "Insert/update failed for ${file.absolutePath}: ${e.message}") + } + + // If a TocDao is available, parse TOC and persist entries for this book (unless flagged) + if (tocDao != null) { + try { + val stored = bookDao.getBookByPath(file.absolutePath) + if (stored == null) { + Log.w(_tag, "Unable to determine book id after insert for ${file.absolutePath}, skipping TOC persistence") + } else if (stored.tocImported && stored.lastModified == file.lastModified()) { + Log.d(_tag, "TOC already imported for bookId=${stored.id}, skipping TOC parsing") + } else { + Log.d(_tag, "Parsing TOC for file: ${file.absolutePath}") + val tocItems = TocParser().parse(file) + Log.d(_tag, "TocParser returned ${tocItems.size} items for file: ${file.absolutePath}") + + val entries = tocItems.map { item -> + TocEntryEntity( + bookId = stored.id, + title = item.title, + href = item.href, + locatorJson = item.locatorJson, + position = item.position + ) + } + + Log.d(_tag, "Persisting ${entries.size} TOC entries for bookId=${stored.id}") + tocDao.replaceForBook(stored.id, entries) + Log.d(_tag, "Persisted ${entries.size} TOC entries for bookId=${stored.id}") + + // Mark the book as having had its TOC imported to avoid reprocessing + try { + val updated = stored.copy(tocImported = true) + bookDao.updateBook(updated) + Log.d(_tag, "Marked book id=${stored.id} tocImported=true") + } catch (e: Exception) { + Log.w(_tag, "Unable to update tocImported flag for bookId=${stored.id}: ${e.message}") + } + } + } catch (e: Exception) { + Log.e(_tag, "Error parsing/persisting TOC for file: ${file.absolutePath}", e) + } } } @@ -67,4 +134,15 @@ class LibraryRepository( Log.d(_tag, "Deleting all books") bookDao.deleteBooks() } + + suspend fun getTocEntriesForBook(bookId: Long): List = withContext(Dispatchers.IO) { + try { + val entries = tocDao?.getForBook(bookId) ?: emptyList() + Log.d(_tag, "Loaded ${entries.size} TOC entries from DB for bookId=$bookId") + entries + } catch (e: Exception) { + Log.w(_tag, "Error loading TOC entries for bookId=$bookId: ${e.message}") + emptyList() + } + } } \ No newline at end of file diff --git a/app/src/main/java/com/nosferatu/launcher/ui/AppColors.kt b/app/src/main/java/com/nosferatu/launcher/ui/AppColors.kt index 0268d14..8904d53 100644 --- a/app/src/main/java/com/nosferatu/launcher/ui/AppColors.kt +++ b/app/src/main/java/com/nosferatu/launcher/ui/AppColors.kt @@ -3,21 +3,75 @@ package com.nosferatu.launcher.ui import androidx.compose.runtime.compositionLocalOf import androidx.compose.ui.graphics.Color -data class AppColors(val bg: Color, val onBg: Color) +data class AppColors( + val bg: Color, + val surface: Color, + val onBg: Color, + val onBgMuted: Color, + val onBgFaint: Color, + val divider: Color, + val accent: Color, + val progressTrack: Color + , + // subtle background used to indicate a selected row in lists + val selectedRowBackground: Color +) -/** Accessed anywhere in the Compose tree without passing LibraryConfig down every call-site. */ -val LocalAppColors = compositionLocalOf { AppColors(Color.White, Color.Black) } +/** Default light palette for composition-local fallback. */ +val LocalAppColors = compositionLocalOf { + AppColors( + bg = Color.White, + surface = Color(0xFFF5F5F5), + onBg = Color(0xFF333333), + onBgMuted = Color(0xFF666666), + onBgFaint = Color(0xFFAAAAAA), + divider = Color(0xFFE0E0E0), + accent = Color(0xFFe94560), + progressTrack = Color(0xFFEEEEEE) + , + selectedRowBackground = Color.Black.copy(alpha = 0.04f) + ) +} -fun bgColorFor(mode: Float): Color = when (mode.toInt()) { - 1 -> Color(0xFFFFF8E1) // cream - 2 -> Color(0xFF222222) // dark charcoal — easier on the eyes than pure black - else -> Color.White +fun appColorsFor(mode: Float): AppColors = when (mode.toInt()) { + 1 -> AppColors( + bg = Color(0xFFFFF8E1), + surface = Color(0xFFF0E6D0), + onBg = Color(0xFF333333), + onBgMuted = Color(0xFF7A6A50), + onBgFaint = Color(0xFFB0A080), + divider = Color(0xFFD8C9A8), + accent = Color(0xFFe94560), + progressTrack = Color(0xFFEDE0C8) + , + selectedRowBackground = Color.Black.copy(alpha = 0.04f) + ) + 2 -> AppColors( + bg = Color(0xFF222222), + surface = Color(0xFF2C2C2C), + onBg = Color(0xFFEEEEEE), + onBgMuted = Color(0xFF999999), + onBgFaint = Color(0xFF666666), + divider = Color(0xFF3A3A3A), + accent = Color(0xFFe94560), + progressTrack = Color(0xFF444444) + , + selectedRowBackground = Color.White.copy(alpha = 0.06f) + ) + else -> AppColors( + bg = Color.White, + surface = Color(0xFFF5F5F5), + onBg = Color(0xFF333333), + onBgMuted = Color(0xFF666666), + onBgFaint = Color(0xFFAAAAAA), + divider = Color(0xFFE0E0E0), + accent = Color(0xFFe94560), + progressTrack = Color(0xFFEEEEEE) + , + selectedRowBackground = Color.Black.copy(alpha = 0.04f) + ) } -fun contentColorFor(mode: Float): Color = - if (mode.toInt() == 2) Color(0xFFEEEEEE) else Color.Black +fun bgColorFor(mode: Float): Color = appColorsFor(mode).bg -fun appColorsFor(mode: Float) = AppColors( - bg = bgColorFor(mode), - onBg = contentColorFor(mode) -) +fun contentColorFor(mode: Float): Color = appColorsFor(mode).onBg diff --git a/app/src/main/java/com/nosferatu/launcher/ui/MainActivity.kt b/app/src/main/java/com/nosferatu/launcher/ui/MainActivity.kt index 3ac2ef5..8dc7729 100644 --- a/app/src/main/java/com/nosferatu/launcher/ui/MainActivity.kt +++ b/app/src/main/java/com/nosferatu/launcher/ui/MainActivity.kt @@ -18,6 +18,11 @@ import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.systemBarsPadding import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Typography +import androidx.compose.ui.text.font.Font +import androidx.compose.ui.text.font.FontFamily +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.platform.LocalContext import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.material3.darkColorScheme @@ -36,7 +41,7 @@ import com.nosferatu.launcher.NosferatuApp import com.nosferatu.launcher.data.EbookEntity import com.nosferatu.launcher.library.LibraryViewModel import com.nosferatu.launcher.library.LibraryViewModelFactory -import com.nosferatu.launcher.reader.ReaderActivity +import java.io.File import com.nosferatu.launcher.ui.components.books.BooksFilterBar import com.nosferatu.launcher.ui.components.books.BooksScreenLibraryList import com.nosferatu.launcher.ui.components.common.BottomBar @@ -75,19 +80,54 @@ class MainActivity: AppCompatActivity() { checkAndRequestPermissions() } + val appColors = appColorsFor(libraryConfig.backgroundMode) val isDark = libraryConfig.backgroundMode.toInt() == 2 val colorScheme = if (isDark) { darkColorScheme().copy( - background = Color(0xFF222222), - surface = Color(0xFF222222), - onBackground = Color(0xFFEEEEEE), - onSurface = Color(0xFFEEEEEE) + background = appColors.bg, + surface = appColors.surface, + onBackground = appColors.onBg, + onSurface = appColors.onBg ) } else { - lightColorScheme(surface = Color.White) + lightColorScheme( + background = appColors.bg, + surface = appColors.surface, + onBackground = appColors.onBg, + onSurface = appColors.onBg + ) } - val appColors = appColorsFor(libraryConfig.backgroundMode) - MaterialTheme(colorScheme = colorScheme) { + // Build typography dynamically based on libraryConfig.fontChoice + val baseTypography = Typography() + val chosenFontFamily = run { + // Try to resolve font resource named "literata_regular" in res/font at runtime + val ctx = this@MainActivity + val resId = ctx.resources.getIdentifier("literata_regular", "font", ctx.packageName) + if (resId != 0) FontFamily(Font(resId)) else FontFamily.Default + } + + val typography = if (libraryConfig.fontChoice.toInt() == 1) { + // copy base typography replacing fontFamily on common styles + baseTypography.copy( + displayLarge = baseTypography.displayLarge.copy(fontFamily = chosenFontFamily), + displayMedium = baseTypography.displayMedium.copy(fontFamily = chosenFontFamily), + displaySmall = baseTypography.displaySmall.copy(fontFamily = chosenFontFamily), + headlineLarge = baseTypography.headlineLarge.copy(fontFamily = chosenFontFamily), + headlineMedium = baseTypography.headlineMedium.copy(fontFamily = chosenFontFamily), + headlineSmall = baseTypography.headlineSmall.copy(fontFamily = chosenFontFamily), + titleLarge = baseTypography.titleLarge.copy(fontFamily = chosenFontFamily), + titleMedium = baseTypography.titleMedium.copy(fontFamily = chosenFontFamily), + titleSmall = baseTypography.titleSmall.copy(fontFamily = chosenFontFamily), + bodyLarge = baseTypography.bodyLarge.copy(fontFamily = chosenFontFamily), + bodyMedium = baseTypography.bodyMedium.copy(fontFamily = chosenFontFamily), + bodySmall = baseTypography.bodySmall.copy(fontFamily = chosenFontFamily), + labelLarge = baseTypography.labelLarge.copy(fontFamily = chosenFontFamily), + labelMedium = baseTypography.labelMedium.copy(fontFamily = chosenFontFamily), + labelSmall = baseTypography.labelSmall.copy(fontFamily = chosenFontFamily) + ) + } else baseTypography + + MaterialTheme(colorScheme = colorScheme, typography = typography) { CompositionLocalProvider(LocalAppColors provides appColors) { Scaffold( modifier = Modifier @@ -191,9 +231,17 @@ class MainActivity: AppCompatActivity() { } private fun openBook(book: EbookEntity) { - val intent = Intent(this, ReaderActivity::class.java).apply { - putExtra("BOOK_PATH", book.filePath) - putExtra("LAST_LOCATION_JSON", book.lastLocationJson) + // MuPDF DocumentActivity expects the document URI as intent data and an + // optional ReturnToLibraryActivity extra. Construct a file:// URI for the + // book path and pass the package-scoped ReturnToLibraryActivity flag so + // the DocumentActivity can return to the library when finished. + val fileUri = File(book.filePath).toUri() + Log.d(_tag, "Opening book: ${book.title}, fileUri: $fileUri") + val intent = Intent(this, com.nosferatu.launcher.reader.NosferatuDocumentActivity::class.java).apply { + data = fileUri + // Use the package-scoped key that DocumentActivity reads + putExtra("${packageName}.ReturnToLibraryActivity", 1) + // Pass the book ID for position saving putExtra("BOOK_ID", book.id) addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION) } diff --git a/app/src/main/java/com/nosferatu/launcher/ui/Navigation.kt b/app/src/main/java/com/nosferatu/launcher/ui/Navigation.kt index 4dd1cd1..8aa993a 100644 --- a/app/src/main/java/com/nosferatu/launcher/ui/Navigation.kt +++ b/app/src/main/java/com/nosferatu/launcher/ui/Navigation.kt @@ -3,11 +3,11 @@ package com.nosferatu.launcher.ui import com.nosferatu.launcher.R enum class ScreenSelectionTab(val labelRes: Int, val iconRes: Int) { - Home(com.nosferatu.launcher.R.string.tab_home, R.drawable.ic_home), - MyBooks(com.nosferatu.launcher.R.string.tab_my_books, R.drawable.ic_books), - More(com.nosferatu.launcher.R.string.tab_more, R.drawable.ic_more); + Home(R.string.tab_home, R.drawable.ic_home), + MyBooks(R.string.tab_library, R.drawable.ic_books), + More(R.string.tab_settings, R.drawable.ic_settings_icon); companion object { - val all = entries + val all = listOf(Home, MyBooks, More) } } \ No newline at end of file diff --git a/app/src/main/java/com/nosferatu/launcher/ui/components/books/BooksFilterBar.kt b/app/src/main/java/com/nosferatu/launcher/ui/components/books/BooksFilterBar.kt index eb2de48..2edf17f 100644 --- a/app/src/main/java/com/nosferatu/launcher/ui/components/books/BooksFilterBar.kt +++ b/app/src/main/java/com/nosferatu/launcher/ui/components/books/BooksFilterBar.kt @@ -13,6 +13,7 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.dp +import androidx.compose.ui.res.dimensionResource import com.nosferatu.launcher.library.LibraryFilterTab import com.nosferatu.launcher.ui.states.LibraryUiState import com.nosferatu.launcher.ui.LocalAppColors @@ -28,9 +29,9 @@ fun BooksFilterBar( Row( modifier = Modifier .fillMaxWidth() - .height(48.dp) - .padding(horizontal = 16.dp, vertical = 16.dp), - horizontalArrangement = Arrangement.spacedBy(20.dp) + .height(dimensionResource(id = com.nosferatu.launcher.R.dimen.touch_target_min)) + .padding(horizontal = dimensionResource(id = com.nosferatu.launcher.R.dimen.spacing_16), vertical = dimensionResource(id = com.nosferatu.launcher.R.dimen.spacing_16)), + horizontalArrangement = Arrangement.spacedBy(dimensionResource(id = com.nosferatu.launcher.R.dimen.spacing_20)) ) { BooksScreenFilterTabItem(stringResource(id = com.nosferatu.launcher.R.string.tab_books), filter == LibraryFilterTab.ALL, onClick = { onFilterChange(LibraryFilterTab.ALL) }) BooksScreenFilterTabItem(stringResource(id = com.nosferatu.launcher.R.string.tab_authors), filter == LibraryFilterTab.AUTHORS, onClick = { onFilterChange(LibraryFilterTab.AUTHORS) }) @@ -39,7 +40,7 @@ fun BooksFilterBar( Box( modifier = Modifier .fillMaxWidth() - .height(1.dp) + .height(dimensionResource(id = com.nosferatu.launcher.R.dimen.divider_1)) .background(LocalAppColors.current.onBg.copy(alpha = 0.3f)) ) } diff --git a/app/src/main/java/com/nosferatu/launcher/ui/components/books/BooksScreenAuthorItem.kt b/app/src/main/java/com/nosferatu/launcher/ui/components/books/BooksScreenAuthorItem.kt index 57c325e..2e9fa35 100644 --- a/app/src/main/java/com/nosferatu/launcher/ui/components/books/BooksScreenAuthorItem.kt +++ b/app/src/main/java/com/nosferatu/launcher/ui/components/books/BooksScreenAuthorItem.kt @@ -16,6 +16,7 @@ import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp +import androidx.compose.ui.res.dimensionResource import com.nosferatu.launcher.R import com.nosferatu.launcher.ui.LocalAppColors @@ -29,7 +30,7 @@ fun BooksScreenAuthorItem( modifier = Modifier .fillMaxWidth() .clickable { onToggle() } - .padding(16.dp), + .padding(dimensionResource(id = com.nosferatu.launcher.R.dimen.spacing_16)), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceBetween ) { @@ -43,7 +44,7 @@ fun BooksScreenAuthorItem( id = if (isExpanded) R.drawable.ic_expand_less else R.drawable.ic_expand_more ), contentDescription = null, - modifier = Modifier.size(24.dp), + modifier = Modifier.size(dimensionResource(id = com.nosferatu.launcher.R.dimen.icon_small)), tint = LocalAppColors.current.onBg ) } diff --git a/app/src/main/java/com/nosferatu/launcher/ui/components/books/BooksScreenBookItem.kt b/app/src/main/java/com/nosferatu/launcher/ui/components/books/BooksScreenBookItem.kt index 29bacf9..c56fd69 100644 --- a/app/src/main/java/com/nosferatu/launcher/ui/components/books/BooksScreenBookItem.kt +++ b/app/src/main/java/com/nosferatu/launcher/ui/components/books/BooksScreenBookItem.kt @@ -6,6 +6,7 @@ import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.aspectRatio +import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width @@ -15,12 +16,13 @@ import androidx.compose.runtime.Composable import androidx.compose.ui.res.stringResource import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier -import androidx.compose.ui.graphics.Color +import androidx.compose.foundation.background import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp +import androidx.compose.ui.res.dimensionResource import coil.compose.AsyncImage import com.nosferatu.launcher.data.EbookEntity import java.io.File @@ -36,14 +38,14 @@ fun BooksScreenBookItem( modifier = Modifier .fillMaxWidth() .clickable(onClick = onClick) - .padding(16.dp), + .padding(dimensionResource(id = com.nosferatu.launcher.R.dimen.spacing_16)), verticalAlignment = Alignment.CenterVertically ) { Box( modifier = Modifier - .width(55.dp) - .aspectRatio(0.75f) - .border(0.5.dp, LocalAppColors.current.onBg.copy(alpha = 0.4f)) + .width(dimensionResource(id = com.nosferatu.launcher.R.dimen.cover_width)) + .aspectRatio(2f / 3f) + .border(dimensionResource(id = com.nosferatu.launcher.R.dimen.divider_thin), LocalAppColors.current.onBg.copy(alpha = 0.4f)) ) { if (book.coverPath != null) { AsyncImage( @@ -51,17 +53,25 @@ fun BooksScreenBookItem( contentDescription = null, contentScale = ContentScale.FillBounds ) + } else { + Box( + modifier = Modifier + .fillMaxSize() + .background(LocalAppColors.current.accent) + ) } } Column( modifier = Modifier .weight(1f) - .padding(horizontal = 12.dp) + .padding(horizontal = dimensionResource(id = com.nosferatu.launcher.R.dimen.spacing_md)) ) { Text( text = book.title, - style = MaterialTheme.typography.bodyLarge.copy(fontWeight = FontWeight.Bold), + style = MaterialTheme.typography.bodyLarge.copy(fontWeight = FontWeight.SemiBold), + color = LocalAppColors.current.onBg, + fontSize = 15.sp, maxLines = 1, overflow = TextOverflow.Ellipsis ) @@ -71,13 +81,15 @@ fun BooksScreenBookItem( Text( text = stringResource(id = com.nosferatu.launcher.R.string.unknown_author), style = MaterialTheme.typography.bodySmall, - color = Color.Gray + color = LocalAppColors.current.onBgMuted, + fontSize = 13.sp ) } else { Text( text = book.author, style = MaterialTheme.typography.bodySmall, - color = Color.Gray + color = LocalAppColors.current.onBgMuted, + fontSize = 13.sp ) } } @@ -85,13 +97,14 @@ fun BooksScreenBookItem( Column(horizontalAlignment = Alignment.End) { val isNew = book.lastLocationJson == null + val isReading = !isNew Text( text = if (isNew) stringResource(id = com.nosferatu.launcher.R.string.status_unread) else stringResource(id = com.nosferatu.launcher.R.string.status_reading), fontSize = 10.sp, fontWeight = FontWeight.ExtraBold, - color = if (isNew) LocalAppColors.current.onBg else LocalAppColors.current.onBg.copy(alpha = 0.6f) + color = if (isReading) LocalAppColors.current.accent else LocalAppColors.current.onBg ) - Text(text = book.format, fontSize = 10.sp, color = LocalAppColors.current.onBg.copy(alpha = 0.4f)) + Text(text = book.format, fontSize = 11.sp, color = LocalAppColors.current.onBgFaint) } } } \ No newline at end of file diff --git a/app/src/main/java/com/nosferatu/launcher/ui/components/books/BooksScreenLibraryList.kt b/app/src/main/java/com/nosferatu/launcher/ui/components/books/BooksScreenLibraryList.kt index 370c040..5ec2a86 100644 --- a/app/src/main/java/com/nosferatu/launcher/ui/components/books/BooksScreenLibraryList.kt +++ b/app/src/main/java/com/nosferatu/launcher/ui/components/books/BooksScreenLibraryList.kt @@ -16,6 +16,7 @@ import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.dp +import androidx.compose.ui.res.dimensionResource import com.nosferatu.launcher.data.EbookEntity import com.nosferatu.launcher.library.LibraryFilterTab import com.nosferatu.launcher.ui.states.LibraryUiState @@ -113,15 +114,15 @@ private fun ListDivider() { Box( modifier = Modifier .fillMaxWidth() - .height(0.5.dp) - .padding(horizontal = 16.dp) + .height(dimensionResource(id = com.nosferatu.launcher.R.dimen.divider_thin)) + .padding(horizontal = dimensionResource(id = com.nosferatu.launcher.R.dimen.spacing_16)) ) { HorizontalDivider( modifier = Modifier .fillMaxWidth(0.9f) - .align(Alignment.Center) - .background(Color.Black), - thickness = 0.5.dp + .align(Alignment.Center), + thickness = dimensionResource(id = com.nosferatu.launcher.R.dimen.divider_thin), + color = LocalAppColors.current.divider ) } } \ No newline at end of file diff --git a/app/src/main/java/com/nosferatu/launcher/ui/components/common/BatteryStatus.kt b/app/src/main/java/com/nosferatu/launcher/ui/components/common/BatteryStatus.kt index ca14bd2..0cbdc64 100644 --- a/app/src/main/java/com/nosferatu/launcher/ui/components/common/BatteryStatus.kt +++ b/app/src/main/java/com/nosferatu/launcher/ui/components/common/BatteryStatus.kt @@ -6,7 +6,9 @@ import android.content.Intent import android.content.IntentFilter import android.os.BatteryManager import androidx.compose.foundation.background +import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.border +import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxHeight @@ -25,6 +27,7 @@ import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color +import com.nosferatu.launcher.ui.LocalAppColors import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp @@ -32,36 +35,43 @@ import androidx.compose.ui.unit.dp @Composable fun BatteryStatus() { val context = LocalContext.current - var batteryLevel by remember { mutableIntStateOf(0) } + var batteryPercent by remember { mutableIntStateOf(-1) } DisposableEffect(context) { val receiver = object : BroadcastReceiver() { override fun onReceive(context: Context?, intent: Intent?) { - batteryLevel = intent?.getIntExtra(BatteryManager.EXTRA_LEVEL, -1) ?: -1 + val level = intent?.getIntExtra(BatteryManager.EXTRA_LEVEL, -1) ?: -1 + val scale = intent?.getIntExtra(BatteryManager.EXTRA_SCALE, -1) ?: -1 + batteryPercent = if (level >= 0 && scale > 0) (level * 100) / scale else -1 } } context.registerReceiver(receiver, IntentFilter(Intent.ACTION_BATTERY_CHANGED)) onDispose { context.unregisterReceiver(receiver) } } - Row(verticalAlignment = Alignment.Companion.CenterVertically) { + val colors = LocalAppColors.current + Row(verticalAlignment = Alignment.CenterVertically) { + val displayText = if (batteryPercent >= 0) "$batteryPercent%" else "--%" Text( - text = "$batteryLevel%", - style = MaterialTheme.typography.bodySmall.copy(fontWeight = FontWeight.Companion.Bold), - modifier = Modifier.Companion.padding(end = 4.dp) + text = displayText, + style = MaterialTheme.typography.bodySmall.copy(fontWeight = FontWeight.Bold), + color = colors.onBg, + modifier = Modifier.padding(end = 4.dp) ) + Box( - modifier = Modifier.Companion + modifier = Modifier .width(18.dp) .height(10.dp) - .border(1.dp, Color.Companion.Black) + .border(BorderStroke(1.dp, colors.onBg.copy(alpha = 0.6f)), shape = RoundedCornerShape(2.dp)) .padding(1.dp) ) { + val fraction = if (batteryPercent >= 0) (batteryPercent.coerceIn(0,100) / 100f) else 0f Box( - modifier = Modifier.Companion - .fillMaxWidth(batteryLevel / 100f) + modifier = Modifier + .fillMaxWidth(fraction) .fillMaxHeight() - .background(Color.Companion.Black) + .background(colors.onBg) ) } } diff --git a/app/src/main/java/com/nosferatu/launcher/ui/components/common/CustomStatusBar.kt b/app/src/main/java/com/nosferatu/launcher/ui/components/common/CustomStatusBar.kt index c4552de..a0e8426 100644 --- a/app/src/main/java/com/nosferatu/launcher/ui/components/common/CustomStatusBar.kt +++ b/app/src/main/java/com/nosferatu/launcher/ui/components/common/CustomStatusBar.kt @@ -12,6 +12,7 @@ import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.dp +import androidx.compose.ui.res.dimensionResource import com.nosferatu.launcher.ui.LocalAppColors @Composable @@ -22,7 +23,7 @@ fun CustomStatusBar() { Row( modifier = Modifier .fillMaxWidth() - .padding(horizontal = 16.dp, vertical = 8.dp), + .padding(horizontal = dimensionResource(id = com.nosferatu.launcher.R.dimen.spacing_16), vertical = dimensionResource(id = com.nosferatu.launcher.R.dimen.spacing_sm)), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceBetween ) { @@ -31,7 +32,7 @@ fun CustomStatusBar() { } HorizontalDivider( modifier = Modifier.fillMaxWidth(), - thickness = 0.5.dp, + thickness = dimensionResource(id = com.nosferatu.launcher.R.dimen.divider_thin), color = colors.onBg ) } diff --git a/app/src/main/java/com/nosferatu/launcher/ui/components/common/SectionHeader.kt b/app/src/main/java/com/nosferatu/launcher/ui/components/common/SectionHeader.kt new file mode 100644 index 0000000..a0e88e0 --- /dev/null +++ b/app/src/main/java/com/nosferatu/launcher/ui/components/common/SectionHeader.kt @@ -0,0 +1,30 @@ +package com.nosferatu.launcher.ui.components.common + +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.res.dimensionResource +import com.nosferatu.launcher.R +import com.nosferatu.launcher.ui.LocalAppColors + +@Composable +fun SectionHeader(title: String, modifier: Modifier = Modifier) { + val colors = LocalAppColors.current + Text( + text = title.uppercase(), + style = MaterialTheme.typography.labelLarge.copy(fontWeight = FontWeight.Black), + color = colors.onBgMuted, + modifier = modifier + .fillMaxWidth() + .padding( + start = dimensionResource(id = R.dimen.spacing_16), + end = dimensionResource(id = R.dimen.spacing_16), + top = dimensionResource(id = R.dimen.spacing_lg), + bottom = dimensionResource(id = R.dimen.spacing_sm) + ) + ) +} diff --git a/app/src/main/java/com/nosferatu/launcher/ui/components/common/SingleChoiceOptionRow.kt b/app/src/main/java/com/nosferatu/launcher/ui/components/common/SingleChoiceOptionRow.kt new file mode 100644 index 0000000..b52500b --- /dev/null +++ b/app/src/main/java/com/nosferatu/launcher/ui/components/common/SingleChoiceOptionRow.kt @@ -0,0 +1,63 @@ +package com.nosferatu.launcher.ui.components.common + +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.* +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.res.dimensionResource +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.semantics.selected +import com.nosferatu.launcher.R +import com.nosferatu.launcher.ui.LocalAppColors + +@Composable +fun SingleChoiceOptionRow( + label: String, + selected: Boolean, + onClick: () -> Unit, + modifier: Modifier = Modifier +) { + val colors = LocalAppColors.current + + Row( + modifier = modifier + .fillMaxWidth() + .heightIn(min = dimensionResource(id = R.dimen.row_min_height)) + .background(if (selected) colors.selectedRowBackground else androidx.compose.ui.graphics.Color.Transparent) + .clickable(role = Role.Button) { onClick() } + .semantics { this.selected = selected } + .padding(horizontal = dimensionResource(id = R.dimen.spacing_16), vertical = dimensionResource(id = R.dimen.spacing_sm)), + verticalAlignment = Alignment.CenterVertically + ) { + // leading indicator (8dp dot) or placeholder + val dotSize = dimensionResource(id = R.dimen.spacing_sm) + if (selected) { + Box( + modifier = Modifier + .size(dotSize) + .clip(CircleShape) + .background(colors.accent) + ) + } else { + Spacer(modifier = Modifier.size(dotSize)) + } + + Spacer(modifier = Modifier.width(dimensionResource(id = R.dimen.spacing_md))) + + Text( + text = label, + style = MaterialTheme.typography.bodyLarge, + fontWeight = if (selected) FontWeight.SemiBold else FontWeight.Normal, + color = if (selected) colors.onBg else colors.onBgMuted + ) + } +} diff --git a/app/src/main/java/com/nosferatu/launcher/ui/components/fontsettings/TextSettingsOverlay.kt b/app/src/main/java/com/nosferatu/launcher/ui/components/fontsettings/TextSettingsOverlay.kt index 3a850f7..1978950 100644 --- a/app/src/main/java/com/nosferatu/launcher/ui/components/fontsettings/TextSettingsOverlay.kt +++ b/app/src/main/java/com/nosferatu/launcher/ui/components/fontsettings/TextSettingsOverlay.kt @@ -91,7 +91,8 @@ fun SliderRow( Box( modifier = Modifier .weight(1f) - .height(36.dp), // Altezza identica a ControlTextButton + .height(36.dp) + .background(LocalAppColors.current.bg), // evita che colori Material3 interni traspariscano contentAlignment = Alignment.Center ) { Slider( @@ -114,7 +115,7 @@ fun SliderRow( modifier = Modifier .fillMaxWidth() .height(1.dp) - .background(Color.LightGray.copy(alpha = 0.3f)), + .background(LocalAppColors.current.progressTrack.copy(alpha = 0.3f)), contentAlignment = Alignment.CenterStart ) { val fraction = (sliderState.value - minValue) / (maxValue - minValue) diff --git a/app/src/main/java/com/nosferatu/launcher/ui/components/home/HomeSection.kt b/app/src/main/java/com/nosferatu/launcher/ui/components/home/HomeSection.kt index 3762316..a04267a 100644 --- a/app/src/main/java/com/nosferatu/launcher/ui/components/home/HomeSection.kt +++ b/app/src/main/java/com/nosferatu/launcher/ui/components/home/HomeSection.kt @@ -9,6 +9,7 @@ import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.dp +import androidx.compose.ui.res.dimensionResource import com.nosferatu.launcher.ui.LocalAppColors @Composable @@ -20,14 +21,14 @@ fun HomeSection( Column( modifier = modifier .fillMaxWidth() - .padding(top = 24.dp) + .padding(top = dimensionResource(id = com.nosferatu.launcher.R.dimen.spacing_lg)) ) { Text( text = title.uppercase(), style = MaterialTheme.typography.labelLarge, color = LocalAppColors.current.onBg, modifier = Modifier - .padding(start = 16.dp, end = 16.dp, bottom = 8.dp) + .padding(start = dimensionResource(id = com.nosferatu.launcher.R.dimen.spacing_16), end = dimensionResource(id = com.nosferatu.launcher.R.dimen.spacing_16), bottom = dimensionResource(id = com.nosferatu.launcher.R.dimen.spacing_sm)) ) content() } diff --git a/app/src/main/java/com/nosferatu/launcher/ui/components/home/TopActionBar.kt b/app/src/main/java/com/nosferatu/launcher/ui/components/home/TopActionBar.kt index 2eb630b..71bbc94 100644 --- a/app/src/main/java/com/nosferatu/launcher/ui/components/home/TopActionBar.kt +++ b/app/src/main/java/com/nosferatu/launcher/ui/components/home/TopActionBar.kt @@ -24,6 +24,7 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.draw.rotate import androidx.compose.ui.res.painterResource import androidx.compose.ui.unit.dp +import androidx.compose.ui.res.dimensionResource import com.nosferatu.launcher.R import com.nosferatu.launcher.library.LibraryViewModel import androidx.compose.runtime.collectAsState @@ -54,30 +55,10 @@ fun TopActionBar( .fillMaxWidth() .background(colors.bg) ) { - Box( - modifier = Modifier - .fillMaxWidth() - .height(48.dp) - .padding(horizontal = 16.dp), - contentAlignment = Alignment.CenterEnd, - ) { - Icon( - painter = painterResource(id = R.drawable.ic_sync_icon), - contentDescription = null, - modifier = Modifier - .size(24.dp) - .rotate(if (isScanning) rotation else 0f) - .clickable( - enabled = !isScanning, - onClick = onSyncClick - ), - tint = if (isScanning) Color.Gray else colors.onBg - ) - } HorizontalDivider( modifier = Modifier.fillMaxWidth(), - thickness = 0.5.dp, - color = colors.onBg.copy(alpha = 0.3f) + thickness = dimensionResource(id = R.dimen.divider_thin), + color = colors.divider ) } } \ No newline at end of file diff --git a/app/src/main/java/com/nosferatu/launcher/ui/screens/HomeScreen.kt b/app/src/main/java/com/nosferatu/launcher/ui/screens/HomeScreen.kt index 43f9914..830ccbd 100644 --- a/app/src/main/java/com/nosferatu/launcher/ui/screens/HomeScreen.kt +++ b/app/src/main/java/com/nosferatu/launcher/ui/screens/HomeScreen.kt @@ -7,12 +7,14 @@ import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding + import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.runtime.Composable import androidx.compose.ui.res.stringResource import androidx.compose.ui.Modifier -import androidx.compose.ui.graphics.Color +// color handled via LocalAppColors import androidx.compose.ui.unit.dp +import androidx.compose.ui.res.dimensionResource import com.nosferatu.launcher.data.EbookEntity import com.nosferatu.launcher.ui.components.home.HomeReadingNowItem import com.nosferatu.launcher.ui.components.home.HomeSection @@ -27,8 +29,9 @@ fun HomeScreen( onSyncClick: () -> Unit ) { val readingNowItems = uiState.books - .filter { it.lastLocationJson != null} - .take(2) + .filter { it.lastLocationJson != null } + .sortedByDescending { it.progression } + .take(4) val bg = LocalAppColors.current.bg @@ -47,17 +50,21 @@ fun HomeScreen( if (readingNowItems.isNotEmpty()) { item { HomeSection(title = stringResource(id = com.nosferatu.launcher.R.string.in_reading)) { - Row( - modifier = Modifier - .fillMaxWidth() - .padding(horizontal = 16.dp), - horizontalArrangement = Arrangement.spacedBy(24.dp) - ) { - readingNowItems.take(2).forEach { book -> - HomeReadingNowItem( - book = book, - onClick = { onOpenBook(book) } - ) + // Render as simple 2-column grid using chunked rows so we don't nest lazy containers. + Column(modifier = Modifier.padding(horizontal = dimensionResource(id = com.nosferatu.launcher.R.dimen.spacing_16))) { + readingNowItems.chunked(2).forEach { row -> + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.spacedBy(dimensionResource(id = com.nosferatu.launcher.R.dimen.spacing_16)) + ) { + row.forEach { book -> + HomeReadingNowItem( + book = book, + onClick = { onOpenBook(book) } + ) + } + // single-item rows left as-is (no weight spacer to avoid internal API exposure) + } } } } diff --git a/app/src/main/java/com/nosferatu/launcher/ui/screens/settings/SettingsChoices.kt b/app/src/main/java/com/nosferatu/launcher/ui/screens/settings/SettingsChoices.kt index 281c7ff..821db3e 100644 --- a/app/src/main/java/com/nosferatu/launcher/ui/screens/settings/SettingsChoices.kt +++ b/app/src/main/java/com/nosferatu/launcher/ui/screens/settings/SettingsChoices.kt @@ -21,3 +21,13 @@ enum class BackgroundColorOption(val labelRes: Int, val value: Float) { entries.find { kotlin.math.abs(it.value - value) < 0.01f } ?: WHITE } } + +enum class FontChoiceOption(val labelRes: Int, val value: Float) { + DEFAULT(com.nosferatu.launcher.R.string.font_choice_default, 0.0f), + LITERATA(com.nosferatu.launcher.R.string.font_choice_literata, 1.0f); + + companion object { + fun fromValue(value: Float): FontChoiceOption = + entries.find { kotlin.math.abs(it.value - value) < 0.01f } ?: DEFAULT + } +} diff --git a/app/src/main/java/com/nosferatu/launcher/ui/screens/settings/SettingsScreen.kt b/app/src/main/java/com/nosferatu/launcher/ui/screens/settings/SettingsScreen.kt index 220804c..e90a6b5 100644 --- a/app/src/main/java/com/nosferatu/launcher/ui/screens/settings/SettingsScreen.kt +++ b/app/src/main/java/com/nosferatu/launcher/ui/screens/settings/SettingsScreen.kt @@ -1,3 +1,4 @@ +@file:OptIn(kotlin.ExperimentalStdlibApi::class) package com.nosferatu.launcher.ui.screens.settings import android.util.Log @@ -9,6 +10,9 @@ import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.ui.res.painterResource import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.res.stringResource @@ -17,13 +21,21 @@ import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp +import androidx.compose.ui.res.dimensionResource +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.ui.draw.clip +import com.nosferatu.launcher.ui.components.common.SectionHeader +import com.nosferatu.launcher.ui.components.common.SingleChoiceOptionRow import com.nosferatu.launcher.library.LibraryConfig import com.nosferatu.launcher.ui.LocalAppColors +import com.nosferatu.launcher.R import kotlin.math.abs sealed class SettingsNavigation { object Main : SettingsNavigation() - data class SubMenu(val key: SettingKey) : SettingsNavigation() + data class Category(val categoryRes: Int) : SettingsNavigation() + data class SubMenu(val key: SettingKey, val parentCategoryRes: Int? = null) : SettingsNavigation() } @Composable @@ -35,16 +47,28 @@ fun SettingsScreen(libraryConfig: LibraryConfig) { Box(modifier = Modifier.fillMaxSize().background(colors.bg)) { when (val nav = currentNav) { is SettingsNavigation.Main -> { - SettingsMainList(onNavigate = { key -> - when (key) { - SettingKey.FONT_SIZE, SettingKey.BACKGROUND_COLOR, - SettingKey.FORCE_BOLD, SettingKey.VOLUME_KEYS, SettingKey.INVERT_TOUCHES -> - currentNav = SettingsNavigation.SubMenu(key) - else -> Log.d("Settings", "Azione per $key") - } + SettingsMainList(onOpenCategory = { categoryRes -> + currentNav = SettingsNavigation.Category(categoryRes) }, contentColor = colors.onBg) } + is SettingsNavigation.Category -> { + val items = settingsList.filter { it.categoryRes == nav.categoryRes } + CategorySubMenu( + title = stringResource(id = nav.categoryRes), + items = items, + onBack = { currentNav = SettingsNavigation.Main }, + onOpenSetting = { key -> + when (key) { + SettingKey.FONT_CHOICE, SettingKey.FONT_SIZE, SettingKey.BACKGROUND_COLOR, + SettingKey.FORCE_BOLD, SettingKey.VOLUME_KEYS, SettingKey.INVERT_TOUCHES -> + currentNav = SettingsNavigation.SubMenu(key, parentCategoryRes = nav.categoryRes) + else -> Log.d("Settings", "Azione per $key") + } + } + ) + } + is SettingsNavigation.SubMenu -> { when (nav.key) { SettingKey.FONT_SIZE -> SelectionSubMenu( @@ -53,34 +77,43 @@ fun SettingsScreen(libraryConfig: LibraryConfig) { options = FontSizeOption.entries.toTypedArray(), getLabelRes = { it.labelRes }, getValue = { it.value }, - onBack = { currentNav = SettingsNavigation.Main }, + onBack = { currentNav = if (nav.parentCategoryRes != null) SettingsNavigation.Category(nav.parentCategoryRes) else SettingsNavigation.Main }, onSelect = { libraryConfig.updateFontSize(it.value) } ) + SettingKey.FONT_CHOICE -> SelectionSubMenu( + title = stringResource(id = com.nosferatu.launcher.R.string.setting_font_choice), + currentValue = libraryConfig.fontChoice, + options = FontChoiceOption.entries.toTypedArray(), + getLabelRes = { it.labelRes }, + getValue = { it.value }, + onBack = { currentNav = if (nav.parentCategoryRes != null) SettingsNavigation.Category(nav.parentCategoryRes) else SettingsNavigation.Main }, + onSelect = { libraryConfig.updateFontChoice(it.value) } + ) SettingKey.BACKGROUND_COLOR -> SelectionSubMenu( title = stringResource(id = com.nosferatu.launcher.R.string.setting_background_color), currentValue = libraryConfig.backgroundMode, options = BackgroundColorOption.entries.toTypedArray(), getLabelRes = { it.labelRes }, getValue = { it.value }, - onBack = { currentNav = SettingsNavigation.Main }, + onBack = { currentNav = if (nav.parentCategoryRes != null) SettingsNavigation.Category(nav.parentCategoryRes) else SettingsNavigation.Main }, onSelect = { libraryConfig.updateBackgroundMode(it.value) } ) SettingKey.FORCE_BOLD -> BooleanSubMenu( title = stringResource(id = com.nosferatu.launcher.R.string.force_bold_title), currentValue = libraryConfig.forceBold, - onBack = { currentNav = SettingsNavigation.Main }, + onBack = { currentNav = if (nav.parentCategoryRes != null) SettingsNavigation.Category(nav.parentCategoryRes) else SettingsNavigation.Main }, onSelect = { libraryConfig.updateForceBold(it) } ) SettingKey.VOLUME_KEYS -> BooleanSubMenu( title = stringResource(id = com.nosferatu.launcher.R.string.setting_volume_keys), currentValue = libraryConfig.volumeKeys, - onBack = { currentNav = SettingsNavigation.Main }, + onBack = { currentNav = if (nav.parentCategoryRes != null) SettingsNavigation.Category(nav.parentCategoryRes) else SettingsNavigation.Main }, onSelect = { libraryConfig.updateVolumeKeys(it) } ) SettingKey.INVERT_TOUCHES -> BooleanSubMenu( title = stringResource(id = com.nosferatu.launcher.R.string.setting_invert_touches), currentValue = libraryConfig.invertTouches, - onBack = { currentNav = SettingsNavigation.Main }, + onBack = { currentNav = if (nav.parentCategoryRes != null) SettingsNavigation.Category(nav.parentCategoryRes) else SettingsNavigation.Main }, onSelect = { libraryConfig.updateInvertTouches(it) } ) else -> currentNav = SettingsNavigation.Main @@ -106,28 +139,27 @@ fun SelectionSubMenu( Column(modifier = Modifier.fillMaxSize().background(bg)) { Row( - modifier = Modifier.fillMaxWidth().clickable { onBack() }.padding(16.dp), + modifier = Modifier.fillMaxWidth().padding(dimensionResource(id = R.dimen.spacing_16)), verticalAlignment = Alignment.CenterVertically ) { - Text(text = stringResource(id = com.nosferatu.launcher.R.string.back_arrow), modifier = Modifier.padding(end = 16.dp), fontWeight = FontWeight.Black, color = contentColor) + IconButton(onClick = onBack, modifier = Modifier.size(dimensionResource(id = R.dimen.touch_target_min))) { + Icon(painter = painterResource(id = R.drawable.ic_arrow_back), contentDescription = stringResource(id = R.string.cd_back), tint = contentColor) + } Text(text = title.uppercase(), style = MaterialTheme.typography.labelLarge, fontWeight = FontWeight.Black, color = contentColor) } - HorizontalDivider(thickness = 1.dp, color = contentColor.copy(alpha = 0.2f)) + HorizontalDivider(thickness = dimensionResource(id = com.nosferatu.launcher.R.dimen.divider_1), color = contentColor.copy(alpha = 0.2f)) + + // select the option whose value is nearest to the saved/current value + val nearestOption = options.minByOrNull { abs(getValue(it) - currentValue) } options.forEach { option -> - val isSelected = abs(getValue(option) - currentValue) < 0.01f - Column(modifier = Modifier.fillMaxWidth().clickable { onSelect(option) }.padding(16.dp)) { - Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) { - Text( - text = stringResource(id = getLabelRes(option)), - style = MaterialTheme.typography.bodyLarge, - fontWeight = if (isSelected) FontWeight.Bold else FontWeight.Normal, - color = if (isSelected) contentColor else contentColor.copy(alpha = 0.7f) - ) - if (isSelected) Text(text = stringResource(id = com.nosferatu.launcher.R.string.check_mark), fontWeight = FontWeight.Black, color = contentColor) - } - } - HorizontalDivider(modifier = Modifier.padding(horizontal = 16.dp), thickness = 0.5.dp, color = contentColor.copy(alpha = 0.12f)) + val isSelected = option == nearestOption + SingleChoiceOptionRow( + label = stringResource(id = getLabelRes(option)), + selected = isSelected, + onClick = { onSelect(option) } + ) + HorizontalDivider(modifier = Modifier.padding(horizontal = dimensionResource(id = R.dimen.spacing_16)), thickness = dimensionResource(id = com.nosferatu.launcher.R.dimen.divider_thin), color = contentColor.copy(alpha = 0.12f)) } } } @@ -149,50 +181,126 @@ fun BooleanSubMenu( Column(modifier = Modifier.fillMaxSize().background(bg)) { Row( - modifier = Modifier.fillMaxWidth().clickable { onBack() }.padding(16.dp), + modifier = Modifier.fillMaxWidth().padding(dimensionResource(id = R.dimen.spacing_16)), verticalAlignment = Alignment.CenterVertically ) { - Text(text = stringResource(id = com.nosferatu.launcher.R.string.back_arrow), modifier = Modifier.padding(end = 16.dp), fontWeight = FontWeight.Black, color = contentColor) + IconButton(onClick = onBack) { + Icon(painter = painterResource(id = R.drawable.ic_arrow_back), contentDescription = stringResource(id = R.string.cd_back), tint = contentColor) + } Text(text = title.uppercase(), style = MaterialTheme.typography.labelLarge, fontWeight = FontWeight.Black, color = contentColor) } - HorizontalDivider(thickness = 1.dp, color = contentColor.copy(alpha = 0.2f)) + HorizontalDivider(thickness = dimensionResource(id = R.dimen.divider_1), color = contentColor.copy(alpha = 0.2f)) options.forEach { (value, labelRes) -> val isSelected = value == currentValue - Column(modifier = Modifier.fillMaxWidth().clickable { onSelect(value) }.padding(16.dp)) { - Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) { - Text( - text = stringResource(id = labelRes), - style = MaterialTheme.typography.bodyLarge, - fontWeight = if (isSelected) FontWeight.Bold else FontWeight.Normal, - color = if (isSelected) contentColor else contentColor.copy(alpha = 0.7f) - ) - if (isSelected) Text(text = stringResource(id = com.nosferatu.launcher.R.string.check_mark), fontWeight = FontWeight.Black, color = contentColor) - } + SingleChoiceOptionRow( + label = stringResource(id = labelRes), + selected = isSelected, + onClick = { onSelect(value) } + ) + HorizontalDivider(modifier = Modifier.padding(horizontal = dimensionResource(id = R.dimen.spacing_16)), thickness = dimensionResource(id = com.nosferatu.launcher.R.dimen.divider_thin), color = contentColor.copy(alpha = 0.12f)) + } + } +} + +@Composable +fun CategorySubMenu( + title: String, + items: List, + onBack: () -> Unit, + onOpenSetting: (SettingKey) -> Unit +) { + val bg = LocalAppColors.current.bg + val contentColor = LocalAppColors.current.onBg + + Column(modifier = Modifier.fillMaxSize().background(bg)) { + Row( + modifier = Modifier.fillMaxWidth().padding(dimensionResource(id = R.dimen.spacing_16)), + verticalAlignment = Alignment.CenterVertically + ) { + IconButton(onClick = onBack) { + Icon(painter = painterResource(id = R.drawable.ic_arrow_back), contentDescription = stringResource(id = R.string.cd_back), tint = contentColor) + } + Text(text = title.uppercase(), style = MaterialTheme.typography.labelLarge, fontWeight = FontWeight.Black, color = contentColor) + } + HorizontalDivider(thickness = dimensionResource(id = R.dimen.divider_1), color = contentColor.copy(alpha = 0.2f)) + + items.forEachIndexed { index, item -> + Row( + modifier = Modifier + .fillMaxWidth() + .clickable { onOpenSetting(item.key) } + .heightIn(min = dimensionResource(id = R.dimen.row_min_height)) + .padding(dimensionResource(id = R.dimen.spacing_16)), + verticalAlignment = Alignment.CenterVertically + ) { + Text(text = stringResource(id = item.titleRes), color = contentColor.copy(alpha = 0.87f), style = MaterialTheme.typography.bodyLarge) + Spacer(modifier = Modifier.weight(1f)) + Text(text = "›", color = contentColor.copy(alpha = 0.4f), fontSize = 20.sp) + } + + if (index < items.size - 1) { + HorizontalDivider(modifier = Modifier.padding(horizontal = dimensionResource(id = R.dimen.spacing_16)), thickness = dimensionResource(id = R.dimen.divider_thin), color = contentColor.copy(alpha = 0.12f)) } - HorizontalDivider(modifier = Modifier.padding(horizontal = 16.dp), thickness = 0.5.dp, color = contentColor.copy(alpha = 0.12f)) } } } + @Composable -private fun SettingsMainList(onNavigate: (SettingKey) -> Unit, contentColor: Color) { - val groupedSettings = settingsList.groupBy { it.categoryRes } - LazyColumn(modifier = Modifier.fillMaxSize()) { - groupedSettings.forEach { (category, items) -> +private fun SettingsMainList(onOpenCategory: (Int) -> Unit, contentColor: Color) { + val groupedSettings = settingsList.groupBy { it.categoryRes }.entries.toList() + LazyColumn( + modifier = Modifier.fillMaxSize(), + contentPadding = PaddingValues(vertical = 8.dp) + ) { + // top title row, clickable to open first category + item { + Row( + modifier = Modifier + .fillMaxWidth() + .clickable { if (groupedSettings.isNotEmpty()) onOpenCategory(groupedSettings[0].key) } + .padding(dimensionResource(id = R.dimen.spacing_16)), + verticalAlignment = Alignment.CenterVertically + ) { + Text(text = stringResource(id = R.string.settings_title), style = MaterialTheme.typography.titleLarge, fontWeight = FontWeight.Black, color = contentColor) + } + } + + groupedSettings.forEachIndexed { index, entry -> + val category = entry.key + item { - Text( - text = stringResource(id = category).uppercase(), - style = MaterialTheme.typography.labelLarge.copy(fontWeight = FontWeight.Black, fontSize = 12.sp), - color = contentColor, - modifier = Modifier.padding(start = 16.dp, top = 24.dp, end = 16.dp, bottom = 8.dp) - ) + Row( + modifier = Modifier + .fillMaxWidth() + .clickable { onOpenCategory(category) } + .heightIn(min = dimensionResource(id = R.dimen.row_min_height)) + .padding(dimensionResource(id = R.dimen.spacing_16)), + verticalAlignment = Alignment.CenterVertically + ) { + Text( + text = stringResource(id = category), + color = contentColor.copy(alpha = 0.87f), + style = MaterialTheme.typography.bodyLarge + ) + Spacer(modifier = Modifier.weight(1f)) + Text(text = "›", color = contentColor.copy(alpha = 0.4f)) + } } - itemsIndexed(items) { index, setting -> - Column(modifier = Modifier.fillMaxWidth().clickable { onNavigate(setting.key) }.padding(16.dp)) { - Text(text = stringResource(id = setting.titleRes), color = contentColor.copy(alpha = 0.87f)) + + if (index < groupedSettings.size - 1) { + item { + HorizontalDivider( + modifier = Modifier.padding(horizontal = dimensionResource(id = R.dimen.spacing_16)), + thickness = dimensionResource(id = R.dimen.divider_thin), + color = contentColor.copy(alpha = 0.12f) + ) } - if (index < items.size - 1) HorizontalDivider(modifier = Modifier.padding(horizontal = 16.dp), thickness = 0.5.dp, color = contentColor.copy(alpha = 0.12f)) + } + + item { + Spacer(modifier = Modifier.height(dimensionResource(id = R.dimen.spacing_16))) } } } diff --git a/app/src/main/res/drawable/battery_box.xml b/app/src/main/res/drawable/battery_box.xml new file mode 100644 index 0000000..b30f8b6 --- /dev/null +++ b/app/src/main/res/drawable/battery_box.xml @@ -0,0 +1,9 @@ + + + + + + diff --git a/app/src/main/res/drawable/ic_arrow_back.xml b/app/src/main/res/drawable/ic_arrow_back.xml new file mode 100644 index 0000000..bb04c47 --- /dev/null +++ b/app/src/main/res/drawable/ic_arrow_back.xml @@ -0,0 +1,9 @@ + + + diff --git a/app/src/main/res/drawable/ic_bookmark_filled.xml b/app/src/main/res/drawable/ic_bookmark_filled.xml new file mode 100644 index 0000000..404d03c --- /dev/null +++ b/app/src/main/res/drawable/ic_bookmark_filled.xml @@ -0,0 +1,10 @@ + + + + diff --git a/app/src/main/res/drawable/ic_bookmark_outline.xml b/app/src/main/res/drawable/ic_bookmark_outline.xml new file mode 100644 index 0000000..bfa8a36 --- /dev/null +++ b/app/src/main/res/drawable/ic_bookmark_outline.xml @@ -0,0 +1,12 @@ + + + + diff --git a/app/src/main/res/drawable/ic_search.xml b/app/src/main/res/drawable/ic_search.xml new file mode 100644 index 0000000..957e565 --- /dev/null +++ b/app/src/main/res/drawable/ic_search.xml @@ -0,0 +1,10 @@ + + + + diff --git a/app/src/main/res/drawable/ic_settings_icon.xml b/app/src/main/res/drawable/ic_settings_icon.xml new file mode 100644 index 0000000..dae79dc --- /dev/null +++ b/app/src/main/res/drawable/ic_settings_icon.xml @@ -0,0 +1,9 @@ + + + diff --git a/app/src/main/res/drawable/ic_toc.xml b/app/src/main/res/drawable/ic_toc.xml new file mode 100644 index 0000000..11bd225 --- /dev/null +++ b/app/src/main/res/drawable/ic_toc.xml @@ -0,0 +1,10 @@ + + + + diff --git a/app/src/main/res/font/literata_regular.ttf b/app/src/main/res/font/literata_regular.ttf new file mode 100644 index 0000000..1cd5bc5 Binary files /dev/null and b/app/src/main/res/font/literata_regular.ttf differ diff --git a/app/src/main/res/layout/activity_reader.xml b/app/src/main/res/layout/activity_reader.xml index b66a800..1c14847 100644 --- a/app/src/main/res/layout/activity_reader.xml +++ b/app/src/main/res/layout/activity_reader.xml @@ -17,17 +17,20 @@ app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent" /> + + + + + + - @@ -185,16 +218,16 @@ android:id="@+id/menu_book_title" android:layout_width="0dp" android:layout_height="wrap_content" - android:textStyle="bold" + android:textSize="15sp" android:textColor="?attr/readerTextColor" android:gravity="center" android:maxLines="1" android:ellipsize="end" - android:layout_marginHorizontal="8dp" + android:layout_marginHorizontal="@dimen/reader_menu_title_margin_horizontal" app:layout_constraintTop_toTopOf="@id/btn_toc" app:layout_constraintBottom_toTopOf="@+id/menu_book_author" app:layout_constraintStart_toEndOf="@id/btn_toc" - app:layout_constraintEnd_toStartOf="@+id/btn_search" + app:layout_constraintEnd_toStartOf="@+id/btn_bookmarks" app:layout_constraintVertical_chainStyle="packed" tools:text="TITOLO LIBRO" /> @@ -202,9 +235,9 @@ android:id="@+id/menu_book_author" android:layout_width="0dp" android:layout_height="wrap_content" - android:textSize="11sp" + android:textSize="12sp" android:textColor="?attr/readerTextColor" - android:alpha="0.6" + android:alpha="0.75" android:gravity="center" android:maxLines="1" android:ellipsize="end" @@ -214,15 +247,21 @@ app:layout_constraintEnd_toEndOf="@id/menu_book_title" tools:text="AUTORE LIBRO" /> - + + \ No newline at end of file diff --git a/app/src/main/res/layout/bottom_sheet_toc.xml b/app/src/main/res/layout/bottom_sheet_toc.xml new file mode 100644 index 0000000..d6335f7 --- /dev/null +++ b/app/src/main/res/layout/bottom_sheet_toc.xml @@ -0,0 +1,25 @@ + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/layout/item_toc.xml b/app/src/main/res/layout/item_toc.xml new file mode 100644 index 0000000..d94c988 --- /dev/null +++ b/app/src/main/res/layout/item_toc.xml @@ -0,0 +1,35 @@ + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/layout/item_toc_header.xml b/app/src/main/res/layout/item_toc_header.xml new file mode 100644 index 0000000..f4d3240 --- /dev/null +++ b/app/src/main/res/layout/item_toc_header.xml @@ -0,0 +1,15 @@ + + \ No newline at end of file diff --git a/app/src/main/res/layout/reader_settings_popup.xml b/app/src/main/res/layout/reader_settings_popup.xml new file mode 100644 index 0000000..3f4d4f2 --- /dev/null +++ b/app/src/main/res/layout/reader_settings_popup.xml @@ -0,0 +1,13 @@ + + + + + + diff --git a/app/src/main/res/layout/reader_status_bar.xml b/app/src/main/res/layout/reader_status_bar.xml new file mode 100644 index 0000000..c31e7cc --- /dev/null +++ b/app/src/main/res/layout/reader_status_bar.xml @@ -0,0 +1,74 @@ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml b/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml new file mode 100644 index 0000000..65291b9 --- /dev/null +++ b/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml b/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml new file mode 100644 index 0000000..65291b9 --- /dev/null +++ b/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/app/src/main/res/mipmap-hdpi/ic_launcher.webp b/app/src/main/res/mipmap-hdpi/ic_launcher.webp new file mode 100644 index 0000000..fb1b942 Binary files /dev/null and b/app/src/main/res/mipmap-hdpi/ic_launcher.webp differ diff --git a/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.webp b/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.webp new file mode 100644 index 0000000..41bff41 Binary files /dev/null and b/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.webp differ diff --git a/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp b/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp new file mode 100644 index 0000000..225f832 Binary files /dev/null and b/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp differ diff --git a/app/src/main/res/mipmap-mdpi/ic_launcher.webp b/app/src/main/res/mipmap-mdpi/ic_launcher.webp new file mode 100644 index 0000000..8bd16d3 Binary files /dev/null and b/app/src/main/res/mipmap-mdpi/ic_launcher.webp differ diff --git a/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.webp b/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.webp new file mode 100644 index 0000000..db31d1d Binary files /dev/null and b/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.webp differ diff --git a/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp b/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp new file mode 100644 index 0000000..80012eb Binary files /dev/null and b/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp differ diff --git a/app/src/main/res/mipmap-xhdpi/ic_launcher.webp b/app/src/main/res/mipmap-xhdpi/ic_launcher.webp new file mode 100644 index 0000000..1627261 Binary files /dev/null and b/app/src/main/res/mipmap-xhdpi/ic_launcher.webp differ diff --git a/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.webp b/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.webp new file mode 100644 index 0000000..1059be2 Binary files /dev/null and b/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.webp differ diff --git a/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp b/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp new file mode 100644 index 0000000..e1e8d4a Binary files /dev/null and b/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp differ diff --git a/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp b/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp new file mode 100644 index 0000000..b2aebb8 Binary files /dev/null and b/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp differ diff --git a/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.webp b/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.webp new file mode 100644 index 0000000..0f21875 Binary files /dev/null and b/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.webp differ diff --git a/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp b/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp new file mode 100644 index 0000000..af394d8 Binary files /dev/null and b/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp differ diff --git a/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp b/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp new file mode 100644 index 0000000..dbae701 Binary files /dev/null and b/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp differ diff --git a/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.webp b/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.webp new file mode 100644 index 0000000..84680ca Binary files /dev/null and b/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.webp differ diff --git a/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp b/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp new file mode 100644 index 0000000..89f3a42 Binary files /dev/null and b/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp differ diff --git a/app/src/main/res/values/attrs.xml b/app/src/main/res/values/attrs.xml index c2f7342..f439b87 100644 --- a/app/src/main/res/values/attrs.xml +++ b/app/src/main/res/values/attrs.xml @@ -1,5 +1,8 @@ + + + diff --git a/app/src/main/res/values/colors.xml b/app/src/main/res/values/colors.xml index a1c7347..390f739 100644 --- a/app/src/main/res/values/colors.xml +++ b/app/src/main/res/values/colors.xml @@ -3,9 +3,13 @@ #e94560 #FFFFFF #333333 + #E0E0E0 + #F5F5F5 #EDE0C8 #FAF4E8 #333333 + #EDE0C8 #222222 #EEEEEE + #444444 \ No newline at end of file diff --git a/app/src/main/res/values/dimens.xml b/app/src/main/res/values/dimens.xml new file mode 100644 index 0000000..ad7b58d --- /dev/null +++ b/app/src/main/res/values/dimens.xml @@ -0,0 +1,31 @@ + + + + 4dp + 8dp + 12dp + 16dp + 24dp + 32dp + + + 3dp + 48dp + 12dp + 20dp + 16dp + 16dp + 8dp + + + 48dp + 24dp + 0.5dp + 20dp + 1dp + 55dp + 56dp + + + 20dp + diff --git a/app/src/main/res/values/ic_launcher_background.xml b/app/src/main/res/values/ic_launcher_background.xml new file mode 100644 index 0000000..beab31f --- /dev/null +++ b/app/src/main/res/values/ic_launcher_background.xml @@ -0,0 +1,4 @@ + + + #000000 + \ No newline at end of file diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index cd2ee5a..2d70cee 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -16,6 +16,7 @@ In Lettura Dimensione Testo ← + Impostazioni Carattere Predefinito Dimensioni Testo @@ -38,8 +39,8 @@ Libri Autori Home - Miei Libri - Altro + Libreria + Impostazioni Piccola Media @@ -49,4 +50,22 @@ Disabilitato %1$d%% %1$s - %2$d%% + + Predefinito + Literata + Aggiungi o rimuovi segnalibro + Impostazioni carattere + Indietro + Apri indice + Impostazioni lettore + Segnalibro aggiunto + Segnalibro rimosso + Segnalibri + Nessun segnalibro + Apri + Rimuovi + Pagina %1$d + Carattere + Indice + Impossibile navigare al capitolo selezionato \ No newline at end of file diff --git a/app/src/main/res/values/themes.xml b/app/src/main/res/values/themes.xml index 309fe9f..f65acdc 100644 --- a/app/src/main/res/values/themes.xml +++ b/app/src/main/res/values/themes.xml @@ -4,17 +4,23 @@ @color/reader_bg_light @color/reader_bg_light @color/reader_text_light + @color/reader_progress_bg + @color/primary_color \ No newline at end of file diff --git a/app/src/test/java/com/nosferatu/launcher/data/TocDaoTest.kt b/app/src/test/java/com/nosferatu/launcher/data/TocDaoTest.kt new file mode 100644 index 0000000..001ba22 --- /dev/null +++ b/app/src/test/java/com/nosferatu/launcher/data/TocDaoTest.kt @@ -0,0 +1,75 @@ +package com.nosferatu.launcher.data + +import android.content.Context +import androidx.room.Room +import androidx.room.RoomDatabase +import com.nosferatu.launcher.data.database.AppDatabase +import kotlinx.coroutines.runBlocking +import org.junit.After +import org.junit.Assert.* +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment + +@RunWith(RobolectricTestRunner::class) +class TocDaoTest { + private lateinit var db: AppDatabase + private lateinit var dao: TocDao + + @Before + fun setUp() { + val context = RuntimeEnvironment.getApplication() + db = Room.inMemoryDatabaseBuilder(context, AppDatabase::class.java) + .allowMainThreadQueries() + .setJournalMode(RoomDatabase.JournalMode.TRUNCATE) + .build() + dao = db.tocDao() + } + + @After + fun tearDown() { + db.close() + } + + @Test + fun insertAndGetForBook() = runBlocking { + val entries = listOf( + TocEntryEntity(bookId = 1L, title = "Chapter 1", href = "chap1.xhtml", locatorJson = "{\"href\":\"chap1.xhtml\"}", position = 0), + TocEntryEntity(bookId = 1L, title = "Chapter 2", href = "chap2.xhtml", locatorJson = "{\"href\":\"chap2.xhtml\"}", position = 1), + ) + dao.insertAll(entries) + val got = dao.getForBook(1L) + assertEquals(2, got.size) + assertEquals("Chapter 1", got[0].title) + assertEquals("chap2.xhtml", got[1].href) + } + + @Test + fun replaceForBookDeletesAndInserts() = runBlocking { + val initial = listOf( + TocEntryEntity(bookId = 2L, title = "Old", href = "old.xhtml", locatorJson = null, position = 0) + ) + dao.insertAll(initial) + assertEquals(1, dao.getForBook(2L).size) + val newEntries = listOf( + TocEntryEntity(bookId = 2L, title = "New A", href = "a.xhtml", locatorJson = null, position = 0), + TocEntryEntity(bookId = 2L, title = "New B", href = "b.xhtml", locatorJson = null, position = 1), + ) + dao.replaceForBook(2L, newEntries) + val got = dao.getForBook(2L) + assertEquals(2, got.size) + assertEquals("New A", got[0].title) + } + + @Test + fun deleteForBookRemovesAll() = runBlocking { + dao.insertAll(listOf( + TocEntryEntity(bookId = 3L, title = "One", href = null, locatorJson = null, position = 0) + )) + assertEquals(1, dao.getForBook(3L).size) + dao.deleteForBook(3L) + assertTrue(dao.getForBook(3L).isEmpty()) + } +} diff --git a/app/src/test/java/com/nosferatu/launcher/parser/TocParserTest.kt b/app/src/test/java/com/nosferatu/launcher/parser/TocParserTest.kt new file mode 100644 index 0000000..47a6250 --- /dev/null +++ b/app/src/test/java/com/nosferatu/launcher/parser/TocParserTest.kt @@ -0,0 +1,124 @@ +package com.nosferatu.launcher.parser + +import kotlinx.coroutines.runBlocking +import org.junit.Assert.* +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import java.io.File +import java.io.FileOutputStream +import java.util.zip.ZipEntry +import java.util.zip.ZipOutputStream + +@RunWith(RobolectricTestRunner::class) +class TocParserTest { + + private fun addEntry(zos: ZipOutputStream, name: String, content: String) { + val entry = ZipEntry(name) + zos.putNextEntry(entry) + zos.write(content.toByteArray(Charsets.UTF_8)) + zos.closeEntry() + } + + @Test + fun parseNavXhtml() { + runBlocking { + val tmp = File.createTempFile("test_nav", ".epub") + ZipOutputStream(FileOutputStream(tmp)).use { zos -> + val containerXml = """ + + + + + + + """.trimIndent() + + val packageOpf = """ + + + + + + + + + """.trimIndent() + + val navXhtml = """ + + + + + + + """.trimIndent() + + addEntry(zos, "META-INF/container.xml", containerXml) + addEntry(zos, "OPS/package.opf", packageOpf) + addEntry(zos, "OPS/nav.xhtml", navXhtml) + } + + val parser = TocParser() + val items = parser.parse(tmp) + assertEquals(2, items.size) + assertEquals("Chapter 1", items[0].title) + assertEquals("chapter1.xhtml", items[0].href) + assertEquals("Chapter 2", items[1].title) + tmp.delete() + } + } + + @Test + fun parseNcx() { + runBlocking { + val tmp = File.createTempFile("test_ncx", ".epub") + ZipOutputStream(FileOutputStream(tmp)).use { zos -> + val containerXml = """ + + + + + + + """.trimIndent() + + val packageOpf = """ + + + + + + + """.trimIndent() + + val ncx = """ + + + + Chapter A + Chapter B + + + """.trimIndent() + + addEntry(zos, "META-INF/container.xml", containerXml) + addEntry(zos, "OPS/package.opf", packageOpf) + addEntry(zos, "OPS/toc.ncx", ncx) + } + + val parser = TocParser() + val items = parser.parse(tmp) + assertEquals(2, items.size) + assertEquals("Chapter A", items[0].title) + assertEquals("a.xhtml", items[0].href) + assertEquals("Chapter B", items[1].title) + tmp.delete() + } + } +} diff --git a/docs/UI-CHANGES.md b/docs/UI-CHANGES.md new file mode 100644 index 0000000..60573dc --- /dev/null +++ b/docs/UI-CHANGES.md @@ -0,0 +1,44 @@ +# UI Changes — 2026-04-04 + +Questo documento riepiloga le modifiche UI implementate nell'ambito del piano *UI Improvement* (P0/P1). + +## Sommario rapido +- TOC: conversione da dialog a BottomSheet con RecyclerView gerarchico (header + item + icone). Implementazione in `ReaderActivity` + layout sotto `app/src/main/res/layout/`. +- Matching TOC→posizioni: nuove euristiche (`normalizeHrefForMatch`, `findBestPositionForHref`) per migliorare il mapping tra href e Locator. +- Segnalibri: persistence leggera (SharedPreferences) con `BookmarkStore` e UI (toggle top-right, panel segnalibri). +- Font runtime: `LibraryConfig.fontChoice` + risoluzione runtime di `literata_regular` in `MainActivity` e `ReaderActivity`. +- Settings polish: `SingleChoiceOptionRow`, `selectedRowBackground` semantic token in `AppColors` e `row_min_height` centralizzato. +- Accessibilità e polish: `contentDescription`, tooltip per i pulsanti, touch-target >= 48dp, animazioni leggere (toggle rotation, bottom-sheet expand), ripple/selectable backgrounds. + +## Come verificare (Acceptance checklist) +1. Aggiungi un EPUB nella libreria e aprilo. +2. Apri il menu in lettura (tap centrale), poi premi il pulsante TOC (bottom-left): si apre un bottom-sheet gerarchico con header e voci. +3. Seleziona una voce TOC: il lettore dovrebbe navigare al capitolo scelto e chiudere il bottom-sheet. +4. Premi il pulsante segnalibro (top-right): l'icona passa da outline a filled; apri il pannello segnalibri (bottom-right) e verifica che il segnalibro sia presente. +5. Imposta `Literata` posizionando `literata_regular.ttf` in `app/src/main/res/font/` e riavvia l'app: le UI overlay e le TextView di header/footer adottano il Typeface (nota: Readium può non applicare il font al body dell'EPUB). + +## File principali modificati +- `app/src/main/java/com/nosferatu/launcher/reader/ReaderActivity.kt` — TOC bottom-sheet, matcher, bookmark wiring, tooltips. +- `app/src/main/res/layout/bottom_sheet_toc.xml` — layout sheet container. +- `app/src/main/res/layout/item_toc.xml` — item row (icon + title). +- `app/src/main/res/layout/item_toc_header.xml` — header row style. +- `app/src/main/res/values/strings.xml` — nuove stringhe di accessibilità e messaggi. +- `app/src/main/java/com/nosferatu/launcher/library/LibraryConfig.kt` — `fontChoice` persistence. +- `app/src/main/java/com/nosferatu/launcher/ui/AppColors.kt` — `selectedRowBackground` token. +- `app/src/main/java/com/nosferatu/launcher/ui/components/common/SingleChoiceOptionRow.kt` — nuova composable (se presente). + +(Altre modifiche rilevanti: `MainActivity.kt`, `SettingsScreen.kt`, `dimens.xml`, `BookmarkStore.kt`, `Bookmark.kt`.) + +## Limitazioni note +- Readium non garantisce che `fontFamily` personalizzati siano applicati ai contenuti EPUB; per forzare l'uso di un font occorre valutare: 1) iniezione CSS con `@font-face`, o 2) embedding del font all'interno degli EPUB. +- Le euristiche di matching possono fallire su TOC con href molto particolari (URI con query complesse, riferimenti temporanei o id HTML non standard). +- Persistenza segnalibri: V1 basata su `SharedPreferences` (JSON). Valutare migrazione a Room se i segnalibri diventano numerosi o servono query avanzate. + +## Prossimi passi consigliati +- Aggiungere comportamento collapsible per gruppi TOC (es. header espandibile) per una UX più chiara. +- Audit accessibilità completo (TalkBack, contrasto, navigazione tastiera). +- Migrazione opzionale store segnalibri a Room con migration path. + +--- + +Se vuoi, posso generare un breve CHANGELOG in `CHANGELOG.md` o convertire questa pagina in un formato HTML per renderla consultabile direttamente nel repo. \ No newline at end of file diff --git a/docs/UI-NOTES.md b/docs/UI-NOTES.md new file mode 100644 index 0000000..1309f4a --- /dev/null +++ b/docs/UI-NOTES.md @@ -0,0 +1,53 @@ +# UI Implementation Notes — 2026-04-04 + +Queste sono note tecniche per manutentori e sviluppatori che lavorano sulle modifiche UI implementate. + +## TOC +- L'estrazione del TOC usa reflection per accomodare possibili varianti dell'API Readium (`getTableOfContents`, `getToc`, ecc.). +- La mappatura TOC→posizioni usa `publication.positions()` (suspend). Calcolo eseguito in `lifecycleScope.launch` per evitare blocchi UI. +- Funzioni chiave in `ReaderActivity.kt`: + - `extractToc(pub: Publication?)` — recupera struttura TOC in un modello `TocNode(title, href, children)`. + - `flattenToc(...)` — crea lista indentata per RecyclerView. + - `normalizeHrefForMatch(href)` — rimuove fragment/query, decodifica percent-encoding, rimuove estensioni comuni e normalizza. + - `findBestPositionForHref(href, positions)` — euristiche: exact, endsWith, contains, last-segment. + +## Performance & sicurezza +- `publication.positions()` può essere pesante per alcuni EPUB: la chiamata è effettuata una volta per mappare TOC verso posizioni; considerare caching se necessario. +- Evitare di chiamare `positions()` su ogni singola navigazione; la strategia corrente tenta mappe precompute. + +## Font runtime +- L'app prova a risolvere la risorsa `literata_regular` con `resources.getIdentifier("literata_regular", "font", packageName)`. +- Posizionare il file `literata_regular.ttf` in `app/src/main/res/font/` e usare il nome risorsa `literata_regular`. +- Nota: per applicare il font al body dell'EPUB potrebbe essere necessario iniettare CSS o modificare il publication rendering layer. + +## Reader lifecycle +- IMPORTANT: `setTheme()` deve essere chiamato prima di `setContentView()` per garantire che gli attributi XML siano risolti correttamente. +- `EpubNavigatorFragment.currentLocator` è un Flow; l'UI osserva e aggiorna header/footer, progress bar, icona segnalibro e la selezione TOC quando il bottom-sheet è aperto. + +## Bookmark store (V1) +- Implementazione attuale: `BookmarkStore` usa `SharedPreferences` per salvare JSON per libro. +- Strategia di identità: `locatorJson` (chiave), `href`, `progression`, `chapterTitle`, `createdAt`. +- Rimozioni e aperture segnalibri avvengono su AlertDialog/BottomSheet a seconda del flusso. + +## Accessibilità +- Tutti i pulsanti critici hanno `contentDescription` e tooltip via `ViewCompat.setTooltipText(...)`. +- Ridotto uso di colori per stato: selezione ha sia background tint che semibold per non dipendere solo dal colore. +- Rispettare `row_min_height` in `dimens.xml` per touch target. + +## Consigli per sviluppo futuro +- Migrare `BookmarkStore` a Room se servono query o sincronizzazione cloud. +- Aggiungere test end-to-end per: TOC navigation, bookmark add/remove, font selection fallback. +- Aggiungere eventi di logging per misurare latenza di `positions()` su EPUB grandi. + +## Comandi utili per sviluppatori +- Build & assemble (Windows PowerShell): + +```powershell +.\gradlew.bat clean assembleDebug --console=plain +``` + +- To run the app locally, use Android Studio or `adb install` on the generated apk under `app/build/outputs/apk/debug/`. + +--- + +Se vuoi, inserisco queste note anche in `app/README-UI.md` con link rapidi ai posti nel codice dove intervenire. \ No newline at end of file diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 59d25af..3a18549 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -33,6 +33,7 @@ navigationRuntimeKtx = "2.9.6" foundationLayout = "1.10.1" foundationVersion = "1.10.2" runtimeVersion = "1.10.3" +constraintlayout = "2.2.1" [libraries] # Core & Utils @@ -87,6 +88,7 @@ androidx-navigation-runtime-ktx = { group = "androidx.navigation", name = "navig androidx-compose-foundation-layout = { group = "androidx.compose.foundation", name = "foundation-layout", version.ref = "foundationLayout" } androidx-foundation = { group = "androidx.compose.foundation", name = "foundation", version.ref = "foundationVersion" } androidx-compose-runtime = { group = "androidx.compose.runtime", name = "runtime", version.ref = "runtimeVersion" } +androidx-constraintlayout = { group = "androidx.constraintlayout", name = "constraintlayout", version.ref = "constraintlayout" } [plugins] android-application = { id = "com.android.application", version.ref = "agp" } diff --git a/lib/build.gradle b/lib/build.gradle new file mode 100644 index 0000000..97dcdfc --- /dev/null +++ b/lib/build.gradle @@ -0,0 +1,69 @@ +apply plugin: 'com.android.library' +apply plugin: 'maven-publish' + +group = 'com.artifex.mupdf' +version = '1.27.1a' + +dependencies { + implementation 'androidx.appcompat:appcompat:1.1.+' + implementation libs.androidx.constraintlayout + if (file('../jni/build.gradle').isFile()) + api project(':jni') + else + api 'com.artifex.mupdf:fitz:1.27.1' +} + +android { + namespace 'com.artifex.mupdf.mini' + compileSdkVersion 34 + defaultConfig { + minSdkVersion 21 + targetSdkVersion 35 + } + publishing { + singleVariant("release") { + withSourcesJar() + } + } +} + +project.afterEvaluate { + publishing { + publications { + release(MavenPublication) { + artifactId 'mini' + artifact(bundleReleaseAar) + + pom { + name = 'mini' + url = 'http://www.mupdf.com' + licenses { + license { + name = 'GNU Affero General Public License' + url = 'https://www.gnu.org/licenses/agpl-3.0.html' + } + } + } + pom.withXml { + final dependenciesNode = asNode().appendNode('dependencies') + configurations.implementation.allDependencies.each { + def dependencyNode = dependenciesNode.appendNode('dependency') + dependencyNode.appendNode('groupId', it.group) + dependencyNode.appendNode('artifactId', it.name) + dependencyNode.appendNode('version', it.version) + } + } + } + } + repositories { + maven { + name 'Local' + if (project.hasProperty('MAVEN_REPO')) { + url = MAVEN_REPO + } else { + url = "file://${System.properties['user.home']}/MAVEN" + } + } + } + } +} diff --git a/lib/src/main/AndroidManifest.xml b/lib/src/main/AndroidManifest.xml new file mode 100644 index 0000000..4771a0f --- /dev/null +++ b/lib/src/main/AndroidManifest.xml @@ -0,0 +1,34 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/lib/src/main/java/com/artifex/mupdf/mini/ContentInputStream.java b/lib/src/main/java/com/artifex/mupdf/mini/ContentInputStream.java new file mode 100644 index 0000000..c776b7c --- /dev/null +++ b/lib/src/main/java/com/artifex/mupdf/mini/ContentInputStream.java @@ -0,0 +1,95 @@ +package com.artifex.mupdf.mini; + +import com.artifex.mupdf.fitz.SeekableInputStream; + +import android.util.Log; +import android.content.ContentResolver; +import android.net.Uri; + +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.io.PrintWriter; +import java.io.StringWriter; + +public class ContentInputStream implements SeekableInputStream { + private final String APP = "MuPDF"; + + protected ContentResolver cr; + protected Uri uri; + protected InputStream is; + protected long length, p; + protected boolean mustReopenStream; + + public ContentInputStream(ContentResolver cr, Uri uri, long size) throws IOException { + this.cr = cr; + this.uri = uri; + length = size; + mustReopenStream = false; + reopenStream(); + } + + public long seek(long offset, int whence) throws IOException { + long newp = p; + switch (whence) { + case SEEK_SET: + newp = offset; + break; + case SEEK_CUR: + newp = p + offset; + break; + case SEEK_END: + if (length < 0) { + byte[] buf = new byte[16384]; + int k; + while ((k = is.read(buf)) != -1) + p += k; + length = p; + } + newp = length + offset; + break; + } + + if (newp < p) { + if (!mustReopenStream) { + try { + is.skip(newp - p); + } catch (IOException x) { + Log.i(APP, "Unable to skip backwards, reopening input stream"); + mustReopenStream = true; + } + } + if (mustReopenStream) { + reopenStream(); + is.skip(newp); + } + } else if (newp > p) { + is.skip(newp - p); + } + return p = newp; + } + + public long position() throws IOException { + return p; + } + + public int read(byte[] buf) throws IOException { + int n = is.read(buf); + if (n > 0) + p += n; + else if (n < 0 && length < 0) + length = p; + return n; + } + + public void reopenStream() throws IOException { + if (is != null) + { + is.close(); + is = null; + } + is = cr.openInputStream(uri); + p = 0; + } + +} diff --git a/lib/src/main/java/com/artifex/mupdf/mini/DocumentActivity.java b/lib/src/main/java/com/artifex/mupdf/mini/DocumentActivity.java new file mode 100644 index 0000000..0b7e0c6 --- /dev/null +++ b/lib/src/main/java/com/artifex/mupdf/mini/DocumentActivity.java @@ -0,0 +1,1151 @@ +package com.artifex.mupdf.mini; + +import com.artifex.mupdf.fitz.*; +import com.artifex.mupdf.fitz.android.*; + +import android.Manifest; +import android.app.Activity; +import android.app.AlertDialog; +import android.content.ContentResolver; +import android.content.Context; +import android.content.DialogInterface; +import android.content.Intent; +import android.content.SharedPreferences; +import android.content.pm.PackageManager; +import android.database.Cursor; +import android.graphics.Bitmap; +import android.graphics.Insets; +import android.graphics.drawable.ColorDrawable; +import android.net.Uri; +import android.os.Build; +import android.os.Bundle; +import android.os.FileUriExposedException; +import android.os.ParcelFileDescriptor; +import android.provider.OpenableColumns; +import android.text.Editable; +import android.text.TextPaint; +import android.text.TextWatcher; +import android.text.method.PasswordTransformationMethod; +import android.util.DisplayMetrics; +import android.util.Log; +import android.view.KeyEvent; +import android.view.View; +import android.view.Window; +import android.view.WindowInsets; +import android.view.WindowManager; +import android.view.inputmethod.EditorInfo; +import android.view.inputmethod.InputMethodManager; +import android.widget.EditText; +import android.widget.ImageView; +import android.widget.ProgressBar; +import android.widget.SeekBar; +import android.widget.TextView; +import android.widget.Toast; + +import androidx.core.app.ActivityCompat; +import androidx.core.content.ContextCompat; +import androidx.core.view.ViewCompat; +import androidx.core.view.WindowInsetsCompat; + +import android.content.IntentFilter; +import android.os.BatteryManager; +import android.view.LayoutInflater; +import android.widget.FrameLayout; +import android.view.ViewGroup; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.Locale; +import java.util.Timer; +import java.util.TimerTask; + +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Stack; + +public class DocumentActivity extends Activity +{ + private final String APP = "MuPDF"; + + public final int NAVIGATE_REQUEST = 1; + + protected final int MAXIMUM_OUTLINE_ITEMS = 1000; + protected final int MAXIMUM_OUTLINE_DEPTH = 4; + + protected final float EXCLUSION_HEIGHT_FACTOR = 2.0f; + + protected Worker worker; + protected SharedPreferences prefs; + + protected Document doc; + + protected String key; + protected String mimetype; + protected SeekableInputStream stream; + protected byte[] buffer; + + protected boolean returnToLibraryActivity; + protected boolean hasLoaded; + protected boolean isReflowable; + protected boolean fitPage; + protected String title; + protected ArrayList flatOutline; + protected float layoutW, layoutH, layoutEm; + protected float displayDPI; + protected int canvasW, canvasH; + protected float pageZoom; + + protected View currentBar; + protected PageView pageView; + protected View actionBar; + protected TextView titleLabel; + protected View searchButton; + protected View searchBar; + protected EditText searchText; + protected View searchCloseButton; + protected View searchBackwardButton; + protected View searchForwardButton; + protected View zoomButton; + protected View backButton; + protected View readerSettingsButton; + protected View bookmarkToggleButton; + protected View tocButton; + protected View bookmarksButton; + protected View bottomBar; + protected View immersiveFooter; + protected View backgroundLayout; + protected View topBar; + protected TextView pageLabel; + protected TextView menuBookTitle; + protected TextView menuBookAuthor; + protected TextView immersiveFooterText; + protected ProgressBar immersiveProgressBar; + protected SeekBar pageSeekbar; + protected ReaderUiController uiController; + + // Helper: convert dp to pixels + protected int dpToPx(int dp) { + return (int)(dp * getResources().getDisplayMetrics().density + 0.5f); + } + + protected boolean pageCountChanged; + protected int pageCount; + protected int currentPage; + protected int searchHitPage; + protected String searchNeedle; + protected boolean stopSearch; + protected Stack history; + protected boolean wentBack; + protected boolean toggledUI; + protected Insets systemInsets = Insets.NONE; + protected boolean newSearchHitPage; + private int bottomBarPaddingLeft; + private int bottomBarPaddingTop; + private int bottomBarPaddingRight; + private int bottomBarPaddingBottom; + private int immersiveFooterPaddingLeft; + private int immersiveFooterPaddingTop; + private int immersiveFooterPaddingRight; + private int immersiveFooterPaddingBottom; + + private String toHex(byte[] digest) { + StringBuilder builder = new StringBuilder(2 * digest.length); + for (byte b : digest) + builder.append(String.format("%02x", b)); + return builder.toString(); + } + + private void openInput(Uri uri, long size, String mimetype) throws IOException { + ContentResolver cr = getContentResolver(); + + Log.i(APP, "Opening document " + uri); + + InputStream is = cr.openInputStream(uri); + byte[] buf = null; + int used = -1; + try { + final int limit = 8 * 1024 * 1024; + if (size < 0) { // size is unknown + buf = new byte[limit]; + used = is.read(buf); + boolean atEOF = is.read() == -1; + if (used < 0 || (used == limit && !atEOF)) // no or partial data + buf = null; + } else if (size <= limit) { // size is known and below limit + buf = new byte[(int) size]; + used = is.read(buf); + if (used < 0 || used < size) // no or partial data + buf = null; + } + if (buf != null && buf.length != used) { + byte[] newbuf = new byte[used]; + System.arraycopy(buf, 0, newbuf, 0, used); + buf = newbuf; + } + } catch (OutOfMemoryError e) { + buf = null; + } finally { + is.close(); + } + + if (buf != null) { + Log.i(APP, " Opening document from memory buffer of size " + buf.length); + buffer = buf; + } else { + Log.i(APP, " Opening document from stream"); + stream = new ContentInputStream(cr, uri, size); + } + } + + public void onCreate(Bundle savedInstanceState) { + applyReaderTheme(); + super.onCreate(savedInstanceState); + requestWindowFeature(Window.FEATURE_NO_TITLE); + getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); + + DisplayMetrics metrics = new DisplayMetrics(); + getWindowManager().getDefaultDisplay().getMetrics(metrics); + displayDPI = metrics.densityDpi; + + try { + setContentView(R.layout.document_activity); + } catch (RuntimeException inflateError) { + Log.e(APP, "Failed to inflate document_activity layout", inflateError); + Toast.makeText(this, getString(R.string.toast_no_document_uri), Toast.LENGTH_SHORT).show(); + finish(); + return; + } + actionBar = findViewById(R.id.action_bar); + searchBar = findViewById(R.id.search_bar); + bottomBar = findViewById(R.id.menu_bottom_bar); + immersiveFooter = findViewById(R.id.immersive_footer); + backgroundLayout = findViewById(R.id.background_layout); + topBar = findViewById(R.id.menu_top_bar); + + + + if (bottomBar != null) { + bottomBarPaddingLeft = bottomBar.getPaddingLeft(); + bottomBarPaddingTop = bottomBar.getPaddingTop(); + bottomBarPaddingRight = bottomBar.getPaddingRight(); + bottomBarPaddingBottom = bottomBar.getPaddingBottom(); + } + if (immersiveFooter != null) { + immersiveFooterPaddingLeft = immersiveFooter.getPaddingLeft(); + immersiveFooterPaddingTop = immersiveFooter.getPaddingTop(); + immersiveFooterPaddingRight = immersiveFooter.getPaddingRight(); + immersiveFooterPaddingBottom = immersiveFooter.getPaddingBottom(); + } + + currentBar = actionBar; + + Uri uri = getIntent().getData(); + mimetype = getIntent().getType(); + + if (uri == null) { + Toast.makeText(this, getString(R.string.toast_no_document_uri), Toast.LENGTH_SHORT).show(); + return; + } + + returnToLibraryActivity = getIntent().getIntExtra(getComponentName().getPackageName() + ".ReturnToLibraryActivity", 0) != 0; + + key = uri.toString(); + + Log.i(APP, "OPEN URI " + uri.toString()); + Log.i(APP, " MAGIC (Intent) " + mimetype); + + title = ""; + long size = -1; + Cursor cursor = null; + + try { + cursor = getContentResolver().query(uri, null, null, null, null, null); + if (cursor != null && cursor.moveToFirst()){ + int idx; + + idx = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME); + if (idx >= 0 && cursor.getType(idx) == Cursor.FIELD_TYPE_STRING) + title = cursor.getString(idx); + + idx = cursor.getColumnIndex(OpenableColumns.SIZE); + if (idx >= 0 && cursor.getType(idx) == Cursor.FIELD_TYPE_INTEGER) + size = cursor.getLong(idx); + + if (size == 0) + size = -1; + } + } catch (Exception x) { + // Ignore any exception and depend on default values for title + // and size (unless one was decoded + } finally { + if (cursor != null) + cursor.close(); + } + + Log.i(APP, " NAME " + title); + Log.i(APP, " SIZE " + size); + + if (mimetype == null || mimetype.equals("application/octet-stream")) { + mimetype = getContentResolver().getType(uri); + Log.i(APP, " MAGIC (Resolver) " + mimetype); + } + if (mimetype == null || mimetype.equals("application/octet-stream")) { + mimetype = title; + Log.i(APP, " MAGIC (Filename) " + mimetype); + } + + try { + openInput(uri, size, mimetype); + } catch (Exception x) { + Log.e(APP, x.toString()); + String text = x.getMessage(); + if (text == null) + text = x.getClass().getName(); + Toast.makeText(this, text, Toast.LENGTH_SHORT).show(); + } + + titleLabel = (TextView)findViewById(R.id.title_label); + titleLabel.setText(title); + menuBookTitle = (TextView)findViewById(R.id.menu_book_title); + menuBookAuthor = (TextView)findViewById(R.id.menu_book_author); + if (menuBookTitle != null) { + menuBookTitle.setText(title); + } + if (menuBookAuthor != null) { + menuBookAuthor.setText(""); + } + + history = new Stack(); + + worker = new Worker(this); + worker.start(); + + prefs = getPreferences(Context.MODE_PRIVATE); + layoutEm = prefs.getFloat("layoutEm", 8); + fitPage = prefs.getBoolean("fitPage", false); + currentPage = prefs.getInt(key, 0); + searchHitPage = -1; + hasLoaded = false; + + pageView = (PageView)findViewById(R.id.page_view); + if (actionBar == null || searchBar == null || bottomBar == null || topBar == null || backgroundLayout == null || pageView == null) { + Log.e(APP, "Missing required reader views. actionBar=" + actionBar + + " searchBar=" + searchBar + + " bottomBar=" + bottomBar + + " topBar=" + topBar + + " backgroundLayout=" + backgroundLayout + + " pageView=" + pageView); + Toast.makeText(this, getString(R.string.toast_no_document_uri), Toast.LENGTH_SHORT).show(); + finish(); + return; + } + pageView.setActionListener(this); + + pageLabel = (TextView)findViewById(R.id.menu_page_text); + immersiveFooterText = (TextView)findViewById(R.id.immersive_footer_text); + immersiveProgressBar = (ProgressBar)findViewById(R.id.immersive_progress_bar); + pageSeekbar = (SeekBar)findViewById(R.id.menu_seek_bar); + if (pageSeekbar == null) { + Log.e(APP, "Missing menu_seek_bar view in document_activity layout"); + Toast.makeText(this, getString(R.string.toast_no_document_uri), Toast.LENGTH_SHORT).show(); + finish(); + return; + } + pageSeekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { + public int newProgress = -1; + public void onProgressChanged(SeekBar seekbar, int progress, boolean fromUser) { + if (fromUser) { + newProgress = progress; + showPageNumber(progress + 1); + } + } + public void onStartTrackingTouch(SeekBar seekbar) {} + public void onStopTrackingTouch(SeekBar seekbar) { + gotoPage(newProgress); + } + }); + + searchButton = findViewById(R.id.search_button); + if (searchButton == null) { + Log.e(APP, "Missing search_button view in document_activity layout"); + Toast.makeText(this, getString(R.string.toast_no_document_uri), Toast.LENGTH_SHORT).show(); + finish(); + return; + } + backButton = findViewById(R.id.btn_back); + readerSettingsButton = findViewById(R.id.btn_reader_settings); + bookmarkToggleButton = findViewById(R.id.btn_bookmark_toggle); + tocButton = findViewById(R.id.btn_toc); + bookmarksButton = findViewById(R.id.btn_bookmarks); + ImageView zoomIcon = (ImageView) findViewById(R.id.zoom_button); + ImageView backIcon = (ImageView) backButton; + ImageView settingsIcon = (ImageView) readerSettingsButton; + ImageView bookmarkIcon = (ImageView) bookmarkToggleButton; + ImageView tocIcon = (ImageView) tocButton; + ImageView bookmarksIcon = (ImageView) bookmarksButton; + ImageView searchCloseIcon = (ImageView) findViewById(R.id.search_close_button); + ImageView searchBackwardIcon = (ImageView) findViewById(R.id.search_backward_button); + ImageView searchForwardIcon = (ImageView) findViewById(R.id.search_forward_button); + + uiController = new ReaderUiController( + backgroundLayout, + topBar, + bottomBar, + immersiveFooter, + titleLabel, + pageLabel, + immersiveFooterText, + immersiveProgressBar, + backIcon, + settingsIcon, + bookmarkIcon, + tocIcon, + bookmarksIcon, + (ImageView) searchButton, + zoomIcon, + searchCloseIcon, + searchBackwardIcon, + searchForwardIcon + ); + uiController.applyTheme(readBackgroundMode(), readFontChoice()); + + if (backButton != null) { + backButton.setOnClickListener(new View.OnClickListener() { + public void onClick(View v) { + onBackPressed(); + } + }); + } + + if (readerSettingsButton != null) { + readerSettingsButton.setOnClickListener(new View.OnClickListener() { + public void onClick(View v) { + onReaderSettingsRequested(); + } + }); + } + + if (bookmarkToggleButton != null) { + bookmarkToggleButton.setOnClickListener(new View.OnClickListener() { + public void onClick(View v) { + onBookmarkToggleRequested(); + } + }); + } + + if (tocButton != null) { + tocButton.setOnClickListener(new View.OnClickListener() { + public void onClick(View v) { + openOutlinePanel(); + } + }); + } + + if (bookmarksButton != null) { + bookmarksButton.setOnClickListener(new View.OnClickListener() { + public void onClick(View v) { + onBookmarksRequested(); + } + }); + } + + searchButton.setOnClickListener(new View.OnClickListener() { + public void onClick(View v) { + showSearch(); + } + }); + searchText = (EditText)findViewById(R.id.search_text); + searchText.setOnEditorActionListener(new TextView.OnEditorActionListener() { + public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { + if (actionId == EditorInfo.IME_NULL && event.getAction() == KeyEvent.ACTION_DOWN) { + search(1); + return true; + } + if (actionId == EditorInfo.IME_ACTION_SEARCH) { + search(1); + return true; + } + return false; + } + }); + searchText.addTextChangedListener(new TextWatcher() { + public void afterTextChanged(Editable s) {} + public void beforeTextChanged(CharSequence s, int start, int count, int after) {} + public void onTextChanged(CharSequence s, int start, int before, int count) { + resetSearch(); + } + }); + searchCloseButton = findViewById(R.id.search_close_button); + searchCloseButton.setOnClickListener(new View.OnClickListener() { + public void onClick(View v) { + hideSearch(); + } + }); + searchBackwardButton = findViewById(R.id.search_backward_button); + searchBackwardButton.setOnClickListener(new View.OnClickListener() { + public void onClick(View v) { + search(-1); + } + }); + searchForwardButton = findViewById(R.id.search_forward_button); + searchForwardButton.setOnClickListener(new View.OnClickListener() { + public void onClick(View v) { + search(1); + } + }); + + zoomButton = findViewById(R.id.zoom_button); + zoomButton.setOnClickListener(new View.OnClickListener() { + public void onClick(View v) { + fitPage = !fitPage; + loadPage(); + } + }); + + backgroundLayout.setOnApplyWindowInsetsListener(new View.OnApplyWindowInsetsListener() { + public WindowInsets onApplyWindowInsets(View v, WindowInsets windowInsets) + { + applyInsets(windowInsets); + return windowInsets; + } + }); + + if (Build.VERSION.SDK_INT >= 29) + bottomBar.addOnLayoutChangeListener(new View.OnLayoutChangeListener() { + public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) { + View parent = (View) v.getParent(); + android.graphics.Rect exclusion; + + exclusion = new android.graphics.Rect(0, 0, v.getWidth(), v.getHeight()); + v.setSystemGestureExclusionRects(Collections.singletonList(exclusion)); + + int extended_top = parent.getHeight() - (int) (EXCLUSION_HEIGHT_FACTOR * v.getHeight()); + exclusion = new android.graphics.Rect(0, extended_top, parent.getWidth(), parent.getHeight()); + parent.setSystemGestureExclusionRects(Collections.singletonList(exclusion)); + } + }); + } + + protected void showPageNumber(int pageNumber) { + if (pageCountChanged && bottomBar.getVisibility() == View.VISIBLE) + { + // set width of longest possible text as minimum width this + // ensures that the size of pageLabel doesn't change whether + // it renders 1 / pageCount or pageCount / pageCount, + // which makes pageSeekbar to the left of pageLabel also have + // a stable width. + + TextPaint paint = pageLabel.getPaint(); + float maxWidth = + pageLabel.getPaddingLeft() + + paint.measureText(pageCount + " / " + pageCount) + // longest possible text + pageLabel.getPaddingRight(); + int minWidth = (int) Math.ceil(maxWidth); + if (minWidth > 0) + { + pageLabel.setMinWidth(minWidth); + pageCountChanged = false; + } + } + + if (uiController != null) { + uiController.updateProgress(pageNumber, pageCount); + } else { + pageLabel.setText(pageNumber + " / " + pageCount); + } + } + + protected int readBackgroundMode() { + try { + return (int) getSharedPreferences("library_prefs", MODE_PRIVATE).getFloat("background_mode", 0f); + } catch (Throwable t) { + return 0; + } + } + + private void applyReaderTheme() { + switch (readBackgroundMode()) { + case 1: + setTheme(R.style.Theme_MuPdfReader_Cream); + break; + case 2: + setTheme(R.style.Theme_MuPdfReader_Dark); + break; + default: + setTheme(R.style.Theme_MuPdfReader); + break; + } + } + + private int readFontChoice() { + try { + int fromIntent = getIntent().getIntExtra("font_choice", -1); + if (fromIntent >= 0) { + return fromIntent; + } + return (int) getSharedPreferences("library_prefs", MODE_PRIVATE).getFloat("font_choice", 0f); + } catch (Throwable t) { + return 0; + } + } + + protected void applyInsets(WindowInsets windowInsets) { + systemInsets = Insets.NONE; + Insets systemBarInsets = windowInsets.getInsets(WindowInsets.Type.systemBars()); + systemInsets = Insets.max(systemInsets, systemBarInsets); + Insets cutoutInsets = windowInsets.getInsets(WindowInsets.Type.displayCutout()); + systemInsets = Insets.max(systemInsets, cutoutInsets); + + + if (bottomBar != null) { + bottomBar.setPadding( + bottomBarPaddingLeft, + bottomBarPaddingTop, + bottomBarPaddingRight, + bottomBarPaddingBottom + systemInsets.bottom + ); + } + if (immersiveFooter != null) { + immersiveFooter.setPadding( + immersiveFooterPaddingLeft, + immersiveFooterPaddingTop, + immersiveFooterPaddingRight, + immersiveFooterPaddingBottom + systemInsets.bottom + ); + } + } + + public boolean onKeyUp(int keyCode, KeyEvent event) { + switch (keyCode) { + case KeyEvent.KEYCODE_PAGE_UP: + case KeyEvent.KEYCODE_COMMA: + case KeyEvent.KEYCODE_B: + goBackward(); + return true; + case KeyEvent.KEYCODE_PAGE_DOWN: + case KeyEvent.KEYCODE_PERIOD: + case KeyEvent.KEYCODE_SPACE: + goForward(); + return true; + case KeyEvent.KEYCODE_M: + history.push(currentPage); + return true; + case KeyEvent.KEYCODE_T: + if (!history.empty()) { + currentPage = history.pop(); + loadPage(); + } + return true; + } + return super.onKeyUp(keyCode, event); + } + + public void onPageViewSizeChanged(int w, int h) { + pageZoom = 1; + canvasW = w; + canvasH = h; + layoutW = canvasW * 72 / displayDPI; + layoutH = canvasH * 72 / displayDPI; + if (!hasLoaded) { + hasLoaded = true; + openDocument(); + } else if (isReflowable) { + relayoutDocument(); + } else { + loadPage(); + } + } + + public void onPageViewZoomChanged(float zoom) { + if (zoom != pageZoom) { + pageZoom = zoom; + loadPage(); + } + } + + protected void openDocument() { + worker.add(new Worker.Task() { + boolean needsPassword; + public void work() { + Log.i(APP, "open document"); + if (buffer != null) + doc = Document.openDocument(buffer, mimetype); + else + doc = Document.openDocument(stream, mimetype); + needsPassword = doc.needsPassword(); + } + public void run() { + if (needsPassword) + askPassword(R.string.dlog_password_message); + else + loadDocument(); + } + }); + } + + protected void askPassword(int message) { + final EditText passwordView = new EditText(this); + passwordView.setInputType(EditorInfo.TYPE_TEXT_VARIATION_PASSWORD); + passwordView.setTransformationMethod(PasswordTransformationMethod.getInstance()); + + AlertDialog.Builder builder = new AlertDialog.Builder(this); + builder.setTitle(R.string.dlog_password_title); + builder.setMessage(message); + builder.setView(passwordView); + builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int id) { + checkPassword(passwordView.getText().toString()); + } + }); + builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int id) { + finish(); + } + }); + builder.setOnCancelListener(new DialogInterface.OnCancelListener() { + public void onCancel(DialogInterface dialog) { + finish(); + } + }); + builder.create().show(); + } + + protected void checkPassword(final String password) { + worker.add(new Worker.Task() { + boolean passwordOkay; + public void work() { + Log.i(APP, "check password"); + passwordOkay = doc.authenticatePassword(password); + } + public void run() { + if (passwordOkay) + loadDocument(); + else + askPassword(R.string.dlog_password_retry); + } + }); + } + + public void onPause() { + super.onPause(); + if (prefs != null) { + SharedPreferences.Editor editor = prefs.edit(); + editor.putFloat("layoutEm", layoutEm); + editor.putBoolean("fitPage", fitPage); + editor.putInt(key, currentPage); + editor.apply(); + } + } + + @Override + public void onDestroy() { + super.onDestroy(); + } + + public void onBackPressed() { + if (history.empty()) { + super.onBackPressed(); + if (returnToLibraryActivity) { + Intent intent = getPackageManager().getLaunchIntentForPackage(getComponentName().getPackageName()); + startActivity(intent); + } + } else { + currentPage = history.pop(); + loadPage(); + } + } + + public void onActivityResult(int request, int result, Intent data) { + if (request == NAVIGATE_REQUEST && result >= RESULT_FIRST_USER) + gotoPage(result - RESULT_FIRST_USER); + } + + protected void showKeyboard() { + InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); + if (imm != null) + imm.showSoftInput(searchText, 0); + } + + protected void hideKeyboard() { + InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); + if (imm != null) + imm.hideSoftInputFromWindow(searchText.getWindowToken(), 0); + } + + protected void resetSearch() { + stopSearch = true; + searchHitPage = -1; + searchNeedle = null; + pageView.resetHits(); + } + + protected void runSearch(final int startPage, final int direction, final String needle) { + stopSearch = false; + worker.add(new Worker.Task() { + int searchPage = startPage; + public void work() { + if (stopSearch || needle != searchNeedle) + return; + for (int i = 0; i < 9; ++i) { + Log.i(APP, "search page " + searchPage); + Page page = doc.loadPage(searchPage); + Quad[][] hits = page.search(searchNeedle); + page.destroy(); + if (hits != null && hits.length > 0) { + newSearchHitPage = true; + searchHitPage = searchPage; + break; + } + searchPage += direction; + if (searchPage < 0 || searchPage >= pageCount) + break; + } + } + public void run() { + if (stopSearch || needle != searchNeedle) { + showPageNumber(currentPage + 1); + } else if (searchHitPage == currentPage) { + loadPage(); + } else if (searchHitPage >= 0) { + history.push(currentPage); + currentPage = searchHitPage; + loadPage(); + } else { + if (searchPage >= 0 && searchPage < pageCount) { + showPageNumber(searchPage + 1); + worker.add(this); + } else { + showPageNumber(currentPage + 1); + Log.i(APP, "search not found"); + Toast.makeText(DocumentActivity.this, getString(R.string.toast_search_not_found), Toast.LENGTH_SHORT).show(); + } + } + } + }); + } + + protected void search(int direction) { + hideKeyboard(); + int startPage; + if (searchHitPage == currentPage) + startPage = currentPage + direction; + else + startPage = currentPage; + searchHitPage = -1; + searchNeedle = searchText.getText().toString(); + if (searchNeedle.length() == 0) + searchNeedle = null; + if (searchNeedle != null) + if (startPage >= 0 && startPage < pageCount) + runSearch(startPage, direction, searchNeedle); + } + + protected void loadDocument() { + worker.add(new Worker.Task() { + public void work() { + try { + Log.i(APP, "load document"); + String metaTitle = doc.getMetaData(Document.META_INFO_TITLE); + if (metaTitle != null && !metaTitle.equals("")) + title = metaTitle; + isReflowable = doc.isReflowable(); + if (isReflowable) { + Log.i(APP, "layout document"); + doc.layout(layoutW, layoutH, layoutEm); + } + pageCount = doc.countPages(); + pageCountChanged = true; + } catch (Throwable x) { + doc = null; + pageCount = 1; + pageCountChanged = true; + currentPage = 0; + throw x; + } + } + public void run() { + pageCountChanged = true; + if (currentPage < 0 || currentPage >= pageCount) + currentPage = 0; + titleLabel.setText(title); + if (!isReflowable) + zoomButton.setVisibility(View.VISIBLE); + loadPage(); + loadOutline(); + } + }); + } + + protected void relayoutDocument() { + worker.add(new Worker.Task() { + public void work() { + try { + long mark = doc.makeBookmark(doc.locationFromPageNumber(currentPage)); + Log.i(APP, "relayout document"); + doc.layout(layoutW, layoutH, layoutEm); + pageCount = doc.countPages(); + currentPage = doc.pageNumberFromLocation(doc.findBookmark(mark)); + } catch (Throwable x) { + pageCount = 1; + currentPage = 0; + throw x; + } + } + public void run() { + history.clear(); + pageCountChanged = true; + loadPage(); + loadOutline(); + } + }); + } + + private void loadOutline() { + worker.add(new Worker.Task() { + boolean outlineTruncated = false; + private void flattenOutline(Outline[] outline, String indent, int depth) { + for (Outline node : outline) { + if (node.title != null) + { + int outlinePage = doc.pageNumberFromLocation(doc.resolveLink(node)); + if (flatOutline.size() >= MAXIMUM_OUTLINE_ITEMS) + outlineTruncated = true; + else + flatOutline.add(new OutlineActivity.Item(indent + node.title, node.uri, outlinePage)); + } + if (node.down != null) + { + if (depth >= MAXIMUM_OUTLINE_DEPTH || flatOutline.size() >= MAXIMUM_OUTLINE_ITEMS) + outlineTruncated = true; + else + flattenOutline(node.down, indent + " ", depth + 1); + } + } + } + public void work() { + Log.i(APP, "load outline"); + Outline[] outline = doc.loadOutline(); + if (outline != null) { + flatOutline = new ArrayList(); + flattenOutline(outline, "", 0); + } else { + flatOutline = null; + } + } + public void run() { + if (tocButton != null) { + tocButton.setVisibility(flatOutline != null ? View.VISIBLE : View.GONE); + } + if (outlineTruncated) + Toast.makeText(DocumentActivity.this, getString(R.string.toast_outline_too_large), Toast.LENGTH_SHORT).show(); + } + }); + } + + private void openOutlinePanel() { + if (flatOutline == null || flatOutline.isEmpty()) { + onTocRequested(); + return; + } + + Intent intent = new Intent(DocumentActivity.this, OutlineActivity.class); + Bundle bundle = new Bundle(); + bundle.putInt("POSITION", currentPage); + bundle.putSerializable("OUTLINE", flatOutline); + intent.putExtras(bundle); + startActivityForResult(intent, NAVIGATE_REQUEST); + } + + protected void loadPage() { + final int pageNumber = currentPage; + final float zoom = pageZoom; + stopSearch = true; + worker.add(new Worker.Task() { + public Bitmap bitmap; + public Rect[] linkBounds; + public String[] linkURIs; + public Quad[][] hits; + public void work() { + try { + Log.i(APP, "load page " + pageNumber); + Page page = doc.loadPage(pageNumber); + Log.i(APP, "draw page " + pageNumber + " zoom=" + zoom); + Matrix ctm; + if (fitPage) + ctm = AndroidDrawDevice.fitPage(page, canvasW, canvasH); + else + ctm = AndroidDrawDevice.fitPageWidth(page, canvasW); + Link[] links = page.getLinks(); + if (links == null) + { + linkBounds = new Rect[0]; + linkURIs = new String[0]; + } + else + { + linkBounds = new Rect[links.length]; + linkURIs = new String[links.length]; + for (int i = 0; i < links.length; i++) + { + linkBounds[i] = links[i].getBounds().transform(ctm); + linkURIs[i] = links[i].getURI(); + } + } + if (searchNeedle != null) { + hits = page.search(searchNeedle); + if (hits != null) + for (Quad[] hit : hits) + for (Quad chr : hit) + chr.transform(ctm); + } + if (zoom != 1) + ctm.scale(zoom); + bitmap = AndroidDrawDevice.drawPage(page, ctm); + } catch (Throwable x) { + Log.e(APP, x.getMessage()); + } + } + public void run() { + if (bitmap != null) + pageView.setBitmap(bitmap, zoom, wentBack, toggledUI, newSearchHitPage, linkBounds, linkURIs, hits); + else + pageView.setError(); + showPageNumber(currentPage + 1); + pageSeekbar.setMax(pageCount - 1); + pageSeekbar.setProgress(pageNumber); + wentBack = false; + toggledUI = false; + newSearchHitPage = false; + } + }); + } + + protected void showSearch() { + currentBar = searchBar; + actionBar.setVisibility(View.GONE); + searchBar.setVisibility(View.VISIBLE); + searchBar.requestFocus(); + showKeyboard(); + } + + protected void hideSearch() { + currentBar = actionBar; + actionBar.setVisibility(View.VISIBLE); + searchBar.setVisibility(View.GONE); + hideKeyboard(); + resetSearch(); + } + + public void toggleUI() { + toggledUI = true; + if (bottomBar.getVisibility() == View.VISIBLE) { + if (uiController != null) { + uiController.setBarsVisible(false, currentBar, true); + } else { + topBar.setVisibility(View.GONE); + currentBar.setVisibility(View.GONE); + bottomBar.setVisibility(View.GONE); + if (immersiveFooter != null) + immersiveFooter.setVisibility(View.VISIBLE); + } + onReaderUiVisibilityChanged(false); + if (currentBar == searchBar) + hideKeyboard(); + } else { + if (uiController != null) { + uiController.setBarsVisible(true, currentBar, true); + } else { + topBar.setVisibility(View.VISIBLE); + currentBar.setVisibility(View.VISIBLE); + bottomBar.setVisibility(View.VISIBLE); + if (immersiveFooter != null) + immersiveFooter.setVisibility(View.GONE); + } + onReaderUiVisibilityChanged(true); + showPageNumber(currentPage + 1); + if (currentBar == searchBar) { + searchBar.requestFocus(); + showKeyboard(); + } + } + } + + /** + * Lightweight integration hook for host-specific behavior. + * Override in custom builds if UI visibility events must be forwarded. + */ + protected void onReaderUiVisibilityChanged(boolean visible) { + // no-op by default + } + + /** + * Host integration hook for reader settings action. + */ + protected void onReaderSettingsRequested() { + // no-op by default + } + + /** + * Host integration hook for bookmark toggle action. + */ + protected void onBookmarkToggleRequested() { + // no-op by default + } + + /** + * Host integration hook when TOC action is requested but no outline is available. + */ + protected void onTocRequested() { + // no-op by default + } + + /** + * Host integration hook for bookmarks list action. + */ + protected void onBookmarksRequested() { + // no-op by default + } + + public void goBackward() { + if (currentPage > 0) { + wentBack = true; + currentPage --; + loadPage(); + } + } + + public void goForward() { + if (currentPage < pageCount - 1) { + currentPage ++; + loadPage(); + } + } + + public void gotoPage(int p) { + if (p >= 0 && p < pageCount && p != currentPage) { + history.push(currentPage); + currentPage = p; + loadPage(); + } + } + + public void gotoPage(String uri) { + gotoPage(doc.pageNumberFromLocation(doc.resolveLink(uri))); + } + + public void gotoURI(String uri) { + Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri)); + intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); // FLAG_ACTIVITY_NEW_DOCUMENT in API>=21 + try { + startActivity(intent); + } catch (FileUriExposedException x) { + Log.e(APP, x.toString()); + Toast.makeText(DocumentActivity.this, getString(R.string.toast_file_uris_not_allowed) + uri, Toast.LENGTH_LONG).show(); + } catch (Throwable x) { + Log.e(APP, x.getMessage()); + Toast.makeText(DocumentActivity.this, x.getMessage(), Toast.LENGTH_SHORT).show(); + } + } +} diff --git a/lib/src/main/java/com/artifex/mupdf/mini/OutlineActivity.java b/lib/src/main/java/com/artifex/mupdf/mini/OutlineActivity.java new file mode 100644 index 0000000..a75968f --- /dev/null +++ b/lib/src/main/java/com/artifex/mupdf/mini/OutlineActivity.java @@ -0,0 +1,62 @@ +package com.artifex.mupdf.mini; + +import android.app.ListActivity; +import android.os.Bundle; +import android.util.Log; +import android.view.View; +import android.view.Window; +import android.view.WindowManager; +import android.widget.ArrayAdapter; +import android.widget.ListView; + +import java.io.Serializable; +import java.util.ArrayList; + +public class OutlineActivity extends ListActivity +{ + private final String APP = "MuPDF"; + + public static class Item implements Serializable { + public String title; + public String uri; + public int page; + public Item(String title, String uri, int page) { + this.title = title; + this.uri = uri; + this.page = page; + } + public String toString() { + return title; + } + } + + protected ArrayAdapter adapter; + + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + requestWindowFeature(Window.FEATURE_NO_TITLE); + getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); + + adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1); + setListAdapter(adapter); + + Bundle bundle = getIntent().getExtras(); + int currentPage = bundle.getInt("POSITION"); + ArrayList outline = (ArrayList)bundle.getSerializable("OUTLINE"); + int found = -1; + for (int i = 0; i < outline.size(); ++i) { + Item item = outline.get(i); + if (found < 0 && item.page >= currentPage) + found = i; + adapter.add(item); + } + if (found >= 0) + setSelection(found); + } + + protected void onListItemClick(ListView l, View v, int position, long id) { + Item item = adapter.getItem(position); + setResult(RESULT_FIRST_USER + item.page); + finish(); + } +} diff --git a/lib/src/main/java/com/artifex/mupdf/mini/PageView.java b/lib/src/main/java/com/artifex/mupdf/mini/PageView.java new file mode 100644 index 0000000..d974f55 --- /dev/null +++ b/lib/src/main/java/com/artifex/mupdf/mini/PageView.java @@ -0,0 +1,348 @@ +package com.artifex.mupdf.mini; + +import com.artifex.mupdf.fitz.*; + +import android.content.Context; +import android.graphics.Bitmap; +import android.graphics.Canvas; +import android.graphics.Paint; +import android.graphics.Path; +import android.util.AttributeSet; +import android.util.Log; +import android.view.GestureDetector; +import android.view.MotionEvent; +import android.view.ScaleGestureDetector; +import android.view.View; +import android.widget.Scroller; + +public class PageView extends View implements + GestureDetector.OnGestureListener, + ScaleGestureDetector.OnScaleGestureListener +{ + private final String APP = "MuPDF"; + + protected DocumentActivity actionListener; + + protected float pageScale, viewScale, minScale, maxScale; + protected Bitmap bitmap; + protected int bitmapW, bitmapH; + protected int canvasW, canvasH; + protected int scrollX, scrollY; + protected Rect[] linkBounds; + protected String[] linkURIs; + protected Quad[][] hits; + protected boolean showLinks; + + protected GestureDetector detector; + protected ScaleGestureDetector scaleDetector; + protected Scroller scroller; + protected boolean error; + protected Paint errorPaint; + protected Path errorPath; + protected Paint linkPaint; + protected Paint hitPaint; + + public PageView(Context ctx, AttributeSet atts) { + super(ctx, atts); + + scroller = new Scroller(ctx); + detector = new GestureDetector(ctx, this); + scaleDetector = new ScaleGestureDetector(ctx, this); + + pageScale = 1; + viewScale = 1; + minScale = 1; + maxScale = 8; + + linkPaint = new Paint(); + linkPaint.setARGB(32, 0, 0, 255); + + hitPaint = new Paint(); + hitPaint.setARGB(32, 255, 0, 0); + hitPaint.setStyle(Paint.Style.FILL); + + errorPaint = new Paint(); + errorPaint.setARGB(255, 255, 80, 80); + errorPaint.setStrokeWidth(5); + errorPaint.setStyle(Paint.Style.STROKE); + + errorPath = new Path(); + errorPath.moveTo(-100, -100); + errorPath.lineTo(100, 100); + errorPath.moveTo(100, -100); + errorPath.lineTo(-100, 100); + } + + public void setActionListener(DocumentActivity l) { + actionListener = l; + } + + public synchronized void setError() { + if (bitmap != null) + bitmap.recycle(); + error = true; + linkBounds = new Rect[0]; + linkURIs = new String[0]; + hits = null; + bitmap = null; + scroller.forceFinished(true); + invalidate(); + } + + public synchronized void setBitmap(Bitmap b, float zoom, boolean wentBack, boolean toggledUI, boolean scrollToFirstSearchHit, Rect[] lbs, String[] lus, Quad[][] hs) { + if (bitmap != null) + bitmap.recycle(); + error = false; + linkBounds = lbs; + linkURIs = lus; + hits = hs; + bitmap = b; + bitmapW = (int)(bitmap.getWidth() * viewScale / zoom); + bitmapH = (int)(bitmap.getHeight() * viewScale / zoom); + scroller.forceFinished(true); + if (scrollToFirstSearchHit && hits != null) + { + float top = bitmapH; + float left = bitmapW; + + for (Quad[] hit : hits) + { + for (Quad q : hit) { + if (q.ul_x * viewScale < left) left = q.ul_x * viewScale; + if (q.ll_x * viewScale < left) left = q.ll_x * viewScale; + if (q.lr_x * viewScale < left) left = q.lr_x * viewScale; + if (q.ur_x * viewScale < left) left = q.ur_x * viewScale; + + if (q.ul_y * viewScale < top) top = q.ul_y * viewScale; + if (q.ll_y * viewScale < top) top = q.ll_y * viewScale; + if (q.lr_y * viewScale < top) top = q.lr_y * viewScale; + if (q.ur_y * viewScale < top) top = q.ur_y * viewScale; + } + } + + scrollX = (int) (left + 0.5f) - canvasW / 2; + scrollY = (int) (top + 0.5f) - canvasH / 2; + + if (scrollX < 0) scrollX = 0; + if (scrollY < 0) scrollY = 0; + if (scrollX > bitmapW - canvasW) scrollX = bitmapW - canvasW; + if (scrollY > bitmapW - canvasW) scrollY = bitmapW - canvasW; + } + else if (!toggledUI && pageScale == zoom) + { + scrollX = wentBack ? bitmapW - canvasW : 0; + scrollY = wentBack ? bitmapH - canvasH : 0; + } + pageScale = zoom; + invalidate(); + } + + public void resetHits() { + hits = null; + invalidate(); + } + + public void onSizeChanged(int w, int h, int ow, int oh) { + canvasW = w; + canvasH = h; + if (actionListener != null) + actionListener.onPageViewSizeChanged(w, h); + } + + public boolean onTouchEvent(MotionEvent event) { + detector.onTouchEvent(event); + scaleDetector.onTouchEvent(event); + return true; + } + + public boolean onDown(MotionEvent e) { + scroller.forceFinished(true); + return true; + } + + public void onShowPress(MotionEvent e) { } + + public void onLongPress(MotionEvent e) { + showLinks = !showLinks; + invalidate(); + } + + public boolean onSingleTapUp(MotionEvent e) { + boolean foundLink = false; + float x = e.getX(); + float y = e.getY(); + if (showLinks && linkBounds != null) { + float dx = (bitmapW <= canvasW) ? (bitmapW - canvasW) / 2 : scrollX; + float dy = (bitmapH <= canvasH) ? (bitmapH - canvasH) / 2 : scrollY; + float mx = (x + dx) / viewScale; + float my = (y + dy) / viewScale; + for (int i = 0; i < linkBounds.length; i++) { + Rect b = linkBounds[i]; + if (mx >= b.x0 && mx <= b.x1 && my >= b.y0 && my <= b.y1) { + if (Link.isExternal(linkURIs[i]) && actionListener != null) + actionListener.gotoURI(linkURIs[i]); + else if (actionListener != null) + actionListener.gotoPage(linkURIs[i]); + foundLink = true; + break; + } + } + } + if (!foundLink) { + float a = canvasW / 3; + float b = a * 2; + if (x <= a) goBackward(); + if (x >= b) goForward(); + if (x > a && x < b && actionListener != null) actionListener.toggleUI(); + } + invalidate(); + return true; + } + + public synchronized boolean onScroll(MotionEvent e1, MotionEvent e2, float dx, float dy) { + if (bitmap != null) { + scrollX += (int)dx; + scrollY += (int)dy; + scroller.forceFinished(true); + invalidate(); + } + return true; + } + + public synchronized boolean onFling(MotionEvent e1, MotionEvent e2, float dx, float dy) { + if (bitmap != null) { + int maxX = bitmapW > canvasW ? bitmapW - canvasW : 0; + int maxY = bitmapH > canvasH ? bitmapH - canvasH : 0; + scroller.forceFinished(true); + scroller.fling(scrollX, scrollY, (int)-dx, (int)-dy, 0, maxX, 0, maxY); + invalidate(); + } + return true; + } + + public boolean onScaleBegin(ScaleGestureDetector det) { + return true; + } + + public synchronized boolean onScale(ScaleGestureDetector det) { + if (bitmap != null) { + float focusX = det.getFocusX(); + float focusY = det.getFocusY(); + float scaleFactor = det.getScaleFactor(); + float pageFocusX = (focusX + scrollX) / viewScale; + float pageFocusY = (focusY + scrollY) / viewScale; + viewScale *= scaleFactor; + if (viewScale < minScale) viewScale = minScale; + if (viewScale > maxScale) viewScale = maxScale; + bitmapW = (int)(bitmap.getWidth() * viewScale / pageScale); + bitmapH = (int)(bitmap.getHeight() * viewScale / pageScale); + scrollX = (int)(pageFocusX * viewScale - focusX); + scrollY = (int)(pageFocusY * viewScale - focusY); + scroller.forceFinished(true); + invalidate(); + } + return true; + } + + public void onScaleEnd(ScaleGestureDetector det) { + if (actionListener != null) + actionListener.onPageViewZoomChanged(viewScale); + } + + public void goBackward() { + scroller.forceFinished(true); + if (scrollY <= 0) { + if (scrollX <= 0) { + if (actionListener != null) + actionListener.goBackward(); + return; + } + scroller.startScroll(scrollX, scrollY, -canvasW * 9 / 10, bitmapH - canvasH - scrollY, 500); + } else { + scroller.startScroll(scrollX, scrollY, 0, -canvasH * 9 / 10, 250); + } + invalidate(); + } + + public void goForward() { + scroller.forceFinished(true); + if (scrollY + canvasH >= bitmapH) { + if (scrollX + canvasW >= bitmapW) { + if (actionListener != null) + actionListener.goForward(); + return; + } + scroller.startScroll(scrollX, scrollY, canvasW * 9 / 10, -scrollY, 500); + } else { + scroller.startScroll(scrollX, scrollY, 0, canvasH * 9 / 10, 250); + } + invalidate(); + } + + private android.graphics.Rect dst = new android.graphics.Rect(); + private Path path = new Path(); + + public synchronized void onDraw(Canvas canvas) { + int x, y; + + if (bitmap == null) { + if (error) { + canvas.translate(canvasW / 2, canvasH / 2); + canvas.drawPath(errorPath, errorPaint); + } + return; + } + + if (scroller.computeScrollOffset()) { + scrollX = scroller.getCurrX(); + scrollY = scroller.getCurrY(); + invalidate(); /* keep animating */ + } + + if (bitmapW <= canvasW) { + scrollX = 0; + x = (canvasW - bitmapW) / 2; + } else { + if (scrollX < 0) scrollX = 0; + if (scrollX > bitmapW - canvasW) scrollX = bitmapW - canvasW; + x = -scrollX; + } + + if (bitmapH <= canvasH) { + scrollY = 0; + y = (canvasH - bitmapH) / 2; + } else { + if (scrollY < 0) scrollY = 0; + if (scrollY > bitmapH - canvasH) scrollY = bitmapH - canvasH; + y = -scrollY; + } + + dst.set(x, y, x + bitmapW, y + bitmapH); + canvas.drawBitmap(bitmap, null, dst, null); + + if (showLinks && linkBounds != null) { + for (Rect b : linkBounds) { + canvas.drawRect( + x + b.x0 * viewScale, + y + b.y0 * viewScale, + x + b.x1 * viewScale, + y + b.y1 * viewScale, + linkPaint + ); + } + } + + if (hits != null && hits.length > 0) { + for (Quad[] h : hits) + for (Quad q : h) { + path.rewind(); + path.moveTo(x + q.ul_x * viewScale, y + q.ul_y * viewScale); + path.lineTo(x + q.ll_x * viewScale, y + q.ll_y * viewScale); + path.lineTo(x + q.lr_x * viewScale, y + q.lr_y * viewScale); + path.lineTo(x + q.ur_x * viewScale, y + q.ur_y * viewScale); + path.close(); + canvas.drawPath(path, hitPaint); + } + } + } +} diff --git a/lib/src/main/java/com/artifex/mupdf/mini/ReaderUiController.java b/lib/src/main/java/com/artifex/mupdf/mini/ReaderUiController.java new file mode 100644 index 0000000..2119bbe --- /dev/null +++ b/lib/src/main/java/com/artifex/mupdf/mini/ReaderUiController.java @@ -0,0 +1,261 @@ +package com.artifex.mupdf.mini; + +import android.content.Context; +import android.content.res.ColorStateList; +import android.content.res.Resources; +import android.graphics.Color; +import android.graphics.Typeface; +import android.util.TypedValue; +import android.view.View; +import android.widget.ImageView; +import android.widget.ProgressBar; +import android.widget.TextView; + +import androidx.annotation.AttrRes; +import androidx.annotation.ColorInt; +import androidx.core.content.ContextCompat; +import androidx.core.content.res.ResourcesCompat; + +/** + * Keeps MuPDF reader UI updates in one place without touching core rendering/gesture logic. + */ +public class ReaderUiController { + private static final long BAR_ANIM_DURATION_MS = 140L; + + private final View backgroundLayout; + private final View topBar; + private final View bottomBar; + private final View immersiveFooter; + private final TextView titleLabel; + private final TextView pageLabel; + private final TextView immersiveFooterText; + private final ProgressBar immersiveProgressBar; + private final ImageView[] tintableIcons; + + public ReaderUiController( + View backgroundLayout, + View topBar, + View bottomBar, + View immersiveFooter, + TextView titleLabel, + TextView pageLabel, + TextView immersiveFooterText, + ProgressBar immersiveProgressBar, + ImageView... tintableIcons + ) { + this.backgroundLayout = backgroundLayout; + this.topBar = topBar; + this.bottomBar = bottomBar; + this.immersiveFooter = immersiveFooter; + this.titleLabel = titleLabel; + this.pageLabel = pageLabel; + this.immersiveFooterText = immersiveFooterText; + this.immersiveProgressBar = immersiveProgressBar; + this.tintableIcons = tintableIcons; + } + + public void applyTheme(int bgMode, int fontChoice) { + Context context = resolveContext(); + FallbackPalette fallback = fallbackPaletteFor(bgMode); + + int bgColor = fallback.bgColor; + int barColor = fallback.barColor; + int textColor = fallback.textColor; + int progressTrackColor = fallback.progressTrackColor; + + if (context != null) { + bgColor = resolveColorAttr(context, R.attr.readerBackgroundColor, fallback.bgColor); + barColor = resolveColorAttr(context, R.attr.readerChromeBackgroundColor, fallback.barColor); + textColor = resolveColorAttr(context, R.attr.readerTextColor, fallback.textColor); + progressTrackColor = resolveColorAttr( + context, + R.attr.readerProgressBackgroundColor, + fallback.progressTrackColor + ); + } + + if (backgroundLayout != null) backgroundLayout.setBackgroundColor(bgColor); + if (topBar != null) topBar.setBackgroundColor(barColor); + if (bottomBar != null) bottomBar.setBackgroundColor(barColor); + if (immersiveFooter != null) immersiveFooter.setBackgroundColor(bgColor); + + if (pageLabel != null) pageLabel.setTextColor(textColor); + if (immersiveFooterText != null) immersiveFooterText.setTextColor(textColor); + if (titleLabel != null) titleLabel.setTextColor(textColor); + + if (immersiveProgressBar != null) { + immersiveProgressBar.setProgressTintList(ColorStateList.valueOf(textColor)); + immersiveProgressBar.setProgressBackgroundTintList(ColorStateList.valueOf(progressTrackColor)); + } + + if (tintableIcons != null) { + for (ImageView icon : tintableIcons) { + if (icon == null || icon.getDrawable() == null) continue; + icon.setColorFilter(textColor); + } + } + + applyFontChoice(fontChoice); + } + + private Context resolveContext() { + if (backgroundLayout != null) return backgroundLayout.getContext(); + if (titleLabel != null) return titleLabel.getContext(); + if (pageLabel != null) return pageLabel.getContext(); + if (immersiveFooterText != null) return immersiveFooterText.getContext(); + return null; + } + + private static final class FallbackPalette { + @ColorInt final int bgColor; + @ColorInt final int barColor; + @ColorInt final int textColor; + @ColorInt final int progressTrackColor; + + FallbackPalette(@ColorInt int bgColor, @ColorInt int barColor, @ColorInt int textColor, @ColorInt int progressTrackColor) { + this.bgColor = bgColor; + this.barColor = barColor; + this.textColor = textColor; + this.progressTrackColor = progressTrackColor; + } + } + + // Mirrors the per-mode values declared in lib/res/values/styles.xml (Theme.MuPdfReader*), + // used only if attribute resolution fails (e.g. context without the reader theme applied). + private FallbackPalette fallbackPaletteFor(int bgMode) { + switch (bgMode) { + case 1: // cream + return new FallbackPalette( + Color.parseColor("#FAF4E8"), + Color.parseColor("#EDE0C8"), + Color.parseColor("#333333"), + Color.parseColor("#EDE0C8") + ); + case 2: // dark + return new FallbackPalette( + Color.parseColor("#222222"), + Color.parseColor("#222222"), + Color.parseColor("#EEEEEE"), + Color.parseColor("#444444") + ); + default: // light/default + return new FallbackPalette( + Color.parseColor("#FFFFFF"), + Color.parseColor("#FFFFFF"), + Color.parseColor("#333333"), + Color.parseColor("#E0E0E0") + ); + } + } + + @ColorInt + private int resolveColorAttr(Context context, @AttrRes int attr, @ColorInt int fallbackColor) { + TypedValue tv = new TypedValue(); + if (!context.getTheme().resolveAttribute(attr, tv, true)) { + return fallbackColor; + } + + if (tv.resourceId != 0) { + return resolveColorResource(context, tv.resourceId, fallbackColor); + } + + if (tv.type >= TypedValue.TYPE_FIRST_COLOR_INT && tv.type <= TypedValue.TYPE_LAST_COLOR_INT) { + return tv.data; + } + + return fallbackColor; + } + + @ColorInt + private int resolveColorResource(Context context, int resId, @ColorInt int fallbackColor) { + if (resId == 0) return fallbackColor; + try { + return ContextCompat.getColor(context, resId); + } catch (Resources.NotFoundException ex) { + return fallbackColor; + } + } + + private void applyFontChoice(int fontChoice) { + Typeface typeface = Typeface.DEFAULT; + if (fontChoice == 1) { + Context context = null; + if (backgroundLayout != null) { + context = backgroundLayout.getContext(); + } else if (titleLabel != null) { + context = titleLabel.getContext(); + } + + if (context != null) { + int resId = context.getResources().getIdentifier("literata_regular", "font", context.getPackageName()); + if (resId != 0) { + Typeface resolved = ResourcesCompat.getFont(context, resId); + if (resolved != null) { + typeface = resolved; + } + } + } + } + + if (titleLabel != null) titleLabel.setTypeface(typeface); + if (pageLabel != null) pageLabel.setTypeface(typeface); + if (immersiveFooterText != null) immersiveFooterText.setTypeface(typeface); + } + + public void updateProgress(int pageNumber, int pageCount) { + String label = pageNumber + " / " + pageCount; + if (pageLabel != null) { + pageLabel.setText(label); + } + if (immersiveFooterText != null) { + immersiveFooterText.setText(label); + } + if (immersiveProgressBar != null) { + immersiveProgressBar.setMax(Math.max(pageCount, 1)); + immersiveProgressBar.setProgress(Math.max(0, Math.min(pageNumber, pageCount))); + } + } + + public void setBarsVisible(boolean visible, View currentBar) { + setBarsVisible(visible, currentBar, false); + } + + public void setBarsVisible(boolean visible, View currentBar, boolean animated) { + int barsVis = visible ? View.VISIBLE : View.GONE; + int footerVis = visible ? View.GONE : View.VISIBLE; + if (!animated) { + if (topBar != null) topBar.setVisibility(barsVis); + if (currentBar != null) currentBar.setVisibility(barsVis); + if (bottomBar != null) bottomBar.setVisibility(barsVis); + if (immersiveFooter != null) immersiveFooter.setVisibility(footerVis); + return; + } + + animateVisibility(topBar, visible); + animateVisibility(currentBar, visible); + animateVisibility(bottomBar, visible); + animateVisibility(immersiveFooter, !visible); + } + + private void animateVisibility(View view, boolean visible) { + if (view == null) return; + + if (visible) { + if (view.getVisibility() == View.VISIBLE && view.getAlpha() >= 1f) return; + view.animate().cancel(); + view.setAlpha(0f); + view.setVisibility(View.VISIBLE); + view.animate().alpha(1f).setDuration(BAR_ANIM_DURATION_MS).start(); + } else { + if (view.getVisibility() != View.VISIBLE) return; + view.animate().cancel(); + view.animate().alpha(0f).setDuration(BAR_ANIM_DURATION_MS).withEndAction(new Runnable() { + @Override + public void run() { + view.setVisibility(View.GONE); + view.setAlpha(1f); + } + }).start(); + } + } +} diff --git a/lib/src/main/java/com/artifex/mupdf/mini/Worker.java b/lib/src/main/java/com/artifex/mupdf/mini/Worker.java new file mode 100644 index 0000000..7f8e137 --- /dev/null +++ b/lib/src/main/java/com/artifex/mupdf/mini/Worker.java @@ -0,0 +1,60 @@ +package com.artifex.mupdf.mini; + +import android.app.Activity; +import android.util.Log; +import android.widget.Toast; + +import java.util.concurrent.LinkedBlockingQueue; + +public class Worker implements Runnable +{ + private final String APP = "MuPDF-Worker"; + + public static class Task implements Runnable { + public void work() {} /* The 'work' method will be executed on the background thread. */ + public void run() {} /* The 'run' method will be executed on the UI thread. */ + } + + protected Activity activity; + protected LinkedBlockingQueue queue; + protected boolean alive; + + public Worker(Activity act) { + activity = act; + queue = new LinkedBlockingQueue(); + } + + public void start() { + alive = true; + new Thread(this).start(); + } + + public void stop() { + alive = false; + } + + public void add(Task task) { + try { + queue.put(task); + } catch (InterruptedException x) { + Log.e(APP, x.getMessage()); + } + } + + public void run() { + while (alive) { + try { + Task task = queue.take(); + task.work(); + activity.runOnUiThread(task); + } catch (final Throwable x) { + Log.e(APP, x.getMessage()); + activity.runOnUiThread(new Runnable() { + public void run() { + Toast.makeText(activity, x.getMessage(), Toast.LENGTH_SHORT).show(); + } + }); + } + } + } +} diff --git a/lib/src/main/res/drawable/battery_box.xml b/lib/src/main/res/drawable/battery_box.xml new file mode 100644 index 0000000..b30f8b6 --- /dev/null +++ b/lib/src/main/res/drawable/battery_box.xml @@ -0,0 +1,9 @@ + + + + + + diff --git a/lib/src/main/res/drawable/button.xml b/lib/src/main/res/drawable/button.xml new file mode 100644 index 0000000..7943397 --- /dev/null +++ b/lib/src/main/res/drawable/button.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/lib/src/main/res/drawable/font_size_down.xml b/lib/src/main/res/drawable/font_size_down.xml new file mode 100644 index 0000000..b8628e7 --- /dev/null +++ b/lib/src/main/res/drawable/font_size_down.xml @@ -0,0 +1,9 @@ + + + diff --git a/lib/src/main/res/drawable/font_size_up.xml b/lib/src/main/res/drawable/font_size_up.xml new file mode 100644 index 0000000..769f4e8 --- /dev/null +++ b/lib/src/main/res/drawable/font_size_up.xml @@ -0,0 +1,9 @@ + + + diff --git a/lib/src/main/res/drawable/ic_arrow_back.xml b/lib/src/main/res/drawable/ic_arrow_back.xml new file mode 100644 index 0000000..bb04c47 --- /dev/null +++ b/lib/src/main/res/drawable/ic_arrow_back.xml @@ -0,0 +1,9 @@ + + + diff --git a/lib/src/main/res/drawable/ic_book_placeholder.xml b/lib/src/main/res/drawable/ic_book_placeholder.xml new file mode 100644 index 0000000..f024064 --- /dev/null +++ b/lib/src/main/res/drawable/ic_book_placeholder.xml @@ -0,0 +1,9 @@ + + + diff --git a/lib/src/main/res/drawable/ic_bookmark_filled.xml b/lib/src/main/res/drawable/ic_bookmark_filled.xml new file mode 100644 index 0000000..404d03c --- /dev/null +++ b/lib/src/main/res/drawable/ic_bookmark_filled.xml @@ -0,0 +1,10 @@ + + + + diff --git a/lib/src/main/res/drawable/ic_bookmark_outline.xml b/lib/src/main/res/drawable/ic_bookmark_outline.xml new file mode 100644 index 0000000..bfa8a36 --- /dev/null +++ b/lib/src/main/res/drawable/ic_bookmark_outline.xml @@ -0,0 +1,12 @@ + + + + diff --git a/lib/src/main/res/drawable/ic_books.xml b/lib/src/main/res/drawable/ic_books.xml new file mode 100644 index 0000000..cf5ebd7 --- /dev/null +++ b/lib/src/main/res/drawable/ic_books.xml @@ -0,0 +1,9 @@ + + + diff --git a/lib/src/main/res/drawable/ic_chevron_left.xml b/lib/src/main/res/drawable/ic_chevron_left.xml new file mode 100644 index 0000000..7be4f88 --- /dev/null +++ b/lib/src/main/res/drawable/ic_chevron_left.xml @@ -0,0 +1,10 @@ + + + + \ No newline at end of file diff --git a/lib/src/main/res/drawable/ic_chevron_right.xml b/lib/src/main/res/drawable/ic_chevron_right.xml new file mode 100644 index 0000000..7eb2d23 --- /dev/null +++ b/lib/src/main/res/drawable/ic_chevron_right.xml @@ -0,0 +1,10 @@ + + + + \ No newline at end of file diff --git a/lib/src/main/res/drawable/ic_close.xml b/lib/src/main/res/drawable/ic_close.xml new file mode 100644 index 0000000..0398723 --- /dev/null +++ b/lib/src/main/res/drawable/ic_close.xml @@ -0,0 +1,10 @@ + + + + \ No newline at end of file diff --git a/lib/src/main/res/drawable/ic_expand_less.xml b/lib/src/main/res/drawable/ic_expand_less.xml new file mode 100644 index 0000000..ec60c63 --- /dev/null +++ b/lib/src/main/res/drawable/ic_expand_less.xml @@ -0,0 +1,9 @@ + + + diff --git a/lib/src/main/res/drawable/ic_expand_more.xml b/lib/src/main/res/drawable/ic_expand_more.xml new file mode 100644 index 0000000..65f7d7e --- /dev/null +++ b/lib/src/main/res/drawable/ic_expand_more.xml @@ -0,0 +1,9 @@ + + + diff --git a/lib/src/main/res/drawable/ic_home.xml b/lib/src/main/res/drawable/ic_home.xml new file mode 100644 index 0000000..dcaa977 --- /dev/null +++ b/lib/src/main/res/drawable/ic_home.xml @@ -0,0 +1,9 @@ + + + diff --git a/lib/src/main/res/drawable/ic_more.xml b/lib/src/main/res/drawable/ic_more.xml new file mode 100644 index 0000000..9f5ff5b --- /dev/null +++ b/lib/src/main/res/drawable/ic_more.xml @@ -0,0 +1,9 @@ + + + diff --git a/lib/src/main/res/drawable/ic_search.xml b/lib/src/main/res/drawable/ic_search.xml new file mode 100644 index 0000000..957e565 --- /dev/null +++ b/lib/src/main/res/drawable/ic_search.xml @@ -0,0 +1,10 @@ + + + + diff --git a/lib/src/main/res/drawable/ic_settings_icon.xml b/lib/src/main/res/drawable/ic_settings_icon.xml new file mode 100644 index 0000000..dae79dc --- /dev/null +++ b/lib/src/main/res/drawable/ic_settings_icon.xml @@ -0,0 +1,9 @@ + + + diff --git a/lib/src/main/res/drawable/ic_sync_icon.xml b/lib/src/main/res/drawable/ic_sync_icon.xml new file mode 100644 index 0000000..1c366cb --- /dev/null +++ b/lib/src/main/res/drawable/ic_sync_icon.xml @@ -0,0 +1,9 @@ + + + diff --git a/lib/src/main/res/drawable/ic_theme_dark.xml b/lib/src/main/res/drawable/ic_theme_dark.xml new file mode 100644 index 0000000..19fe2a5 --- /dev/null +++ b/lib/src/main/res/drawable/ic_theme_dark.xml @@ -0,0 +1,9 @@ + + + diff --git a/lib/src/main/res/drawable/ic_theme_light.xml b/lib/src/main/res/drawable/ic_theme_light.xml new file mode 100644 index 0000000..bb8db64 --- /dev/null +++ b/lib/src/main/res/drawable/ic_theme_light.xml @@ -0,0 +1,9 @@ + + + diff --git a/lib/src/main/res/drawable/ic_toc.xml b/lib/src/main/res/drawable/ic_toc.xml new file mode 100644 index 0000000..11bd225 --- /dev/null +++ b/lib/src/main/res/drawable/ic_toc.xml @@ -0,0 +1,10 @@ + + + + diff --git a/lib/src/main/res/drawable/ic_zoom_out_map.xml b/lib/src/main/res/drawable/ic_zoom_out_map.xml new file mode 100644 index 0000000..c30c8b3 --- /dev/null +++ b/lib/src/main/res/drawable/ic_zoom_out_map.xml @@ -0,0 +1,10 @@ + + + + \ No newline at end of file diff --git a/lib/src/main/res/layout/document_activity.xml b/lib/src/main/res/layout/document_activity.xml new file mode 100644 index 0000000..3634eda --- /dev/null +++ b/lib/src/main/res/layout/document_activity.xml @@ -0,0 +1,349 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/lib/src/main/res/layout/reader_status_bar.xml b/lib/src/main/res/layout/reader_status_bar.xml new file mode 100644 index 0000000..c31e7cc --- /dev/null +++ b/lib/src/main/res/layout/reader_status_bar.xml @@ -0,0 +1,74 @@ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/lib/src/main/res/menu/layout_menu.xml b/lib/src/main/res/menu/layout_menu.xml new file mode 100644 index 0000000..4bc834a --- /dev/null +++ b/lib/src/main/res/menu/layout_menu.xml @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + diff --git a/lib/src/main/res/values/attrs.xml b/lib/src/main/res/values/attrs.xml new file mode 100644 index 0000000..c95f4dc --- /dev/null +++ b/lib/src/main/res/values/attrs.xml @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/lib/src/main/res/values/colors.xml b/lib/src/main/res/values/colors.xml new file mode 100644 index 0000000..316b652 --- /dev/null +++ b/lib/src/main/res/values/colors.xml @@ -0,0 +1,20 @@ + + + + #A0A0A0 + #33FFFFFF + + + #FFFFFF + #333333 + #E0E0E0 + + #EDE0C8 + #FAF4E8 + #333333 + #EDE0C8 + + #222222 + #EEEEEE + #444444 + diff --git a/lib/src/main/res/values/dimens.xml b/lib/src/main/res/values/dimens.xml new file mode 100644 index 0000000..4bc9c53 --- /dev/null +++ b/lib/src/main/res/values/dimens.xml @@ -0,0 +1,21 @@ + + + + 8dp + 12dp + 16dp + + + 48dp + 12dp + 48dp + 12dp + 16sp + 12sp + 8dp + 3dp + 16dp + 16dp + 16dp + 20dp + \ No newline at end of file diff --git a/lib/src/main/res/values/strings.xml b/lib/src/main/res/values/strings.xml new file mode 100644 index 0000000..2f3d0fe --- /dev/null +++ b/lib/src/main/res/values/strings.xml @@ -0,0 +1,23 @@ + + + Password: + The document is encrypted. + Invalid password. + Search… + Search not found. + Outline too large, truncated. + No document uri to open. + Android does not allow following file:// link: + Back + Search + Zoom + Layout + Open table of contents + Reader settings + Toggle bookmark + Open bookmarks + Close + Previous search result + Next search result + - / - + diff --git a/lib/src/main/res/values/styles.xml b/lib/src/main/res/values/styles.xml new file mode 100644 index 0000000..cabf5f7 --- /dev/null +++ b/lib/src/main/res/values/styles.xml @@ -0,0 +1,25 @@ + + + + + + + + + + diff --git a/settings.gradle b/settings.gradle index 0d8744b..7580415 100644 --- a/settings.gradle +++ b/settings.gradle @@ -16,8 +16,10 @@ dependencyResolutionManagement { maven { url = uri("https://jitpack.io") } + maven { url 'https://maven.ghostscript.com' } } } rootProject.name = "nosferatu-launcher" -include ':app' \ No newline at end of file +include ':app' +include ':lib' \ No newline at end of file