Merge branch 'master' of https://github.com/jpirnay/crosspoint-reader into feat-koysnc-xpath
This commit is contained in:
+1
@@ -0,0 +1 @@
|
||||
../../.skills/SKILL.md
|
||||
@@ -0,0 +1,872 @@
|
||||
# CrossPoint Reader Development Guide
|
||||
|
||||
Project: Open-source e-reader firmware for Xteink X4 (ESP32-C3)
|
||||
Mission: Provide a lightweight, high-performance reading experience focused on EPUB rendering on constrained hardware.
|
||||
|
||||
## AI Agent Identity and Cognitive Rules
|
||||
* Role: Senior Embedded Systems Engineer (ESP-IDF/Arduino-ESP32 specialized).
|
||||
* Primary Constraint: 380KB RAM is the hard ceiling. Stability is non-negotiable.
|
||||
* Evidence-Based Reasoning: Before proposing a change, you MUST cite the specific file path and line numbers that justify the modification.
|
||||
* Anti-Hallucination: Do not assume the existence of libraries or ESP-IDF functions. If you are unsure of an API's availability for the ESP32-C3 RISC-V target, check the open-x4-sdk or official docs first.
|
||||
* No Unfounded Claims: Do not claim performance gains or memory savings without explaining the technical mechanism (e.g., DRAM vs IRAM usage).
|
||||
* Resource Justification: You must justify any new heap allocation (new, malloc, std::vector) or explain why a stack/static alternative was rejected.
|
||||
* Verification: After suggesting a fix, instruct the user on how to verify it (e.g., monitoring heap via Serial or checking a specific cache file).
|
||||
---
|
||||
|
||||
## Development Environment Awareness
|
||||
|
||||
**CRITICAL**: Detect the host platform at session start to choose appropriate tools and commands.
|
||||
|
||||
### Platform Detection
|
||||
```bash
|
||||
# Detect platform (run once per session)
|
||||
uname -s
|
||||
# Returns: MINGW64_NT-* (Windows Git Bash), Linux, Darwin (macOS)
|
||||
```
|
||||
|
||||
**Detection Required**: Run `uname -s` at session start to determine platform
|
||||
|
||||
### Platform-Specific Behaviors
|
||||
- **Windows (Git Bash)**: Unix commands, `C:\` paths in Windows but `/` in bash, limited glob (use `find`+`xargs`)
|
||||
- **Linux/WSL**: Full bash, Unix paths, native glob support
|
||||
|
||||
**Cross-Platform Code Formatting**:
|
||||
```bash
|
||||
find src -name "*.cpp" -o -name "*.h" | xargs clang-format -i
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Platform and Hardware Constraints
|
||||
|
||||
### Hardware Specs
|
||||
* MCU: ESP32-C3 (Single-core RISC-V @ 160MHz)
|
||||
* RAM: ~380KB usable (VERY LIMITED - primary project constraint)
|
||||
* **NO PSRAM**: ESP32-C3 has no PSRAM capability (unlike ESP32-S3)
|
||||
* **Single Buffer Mode**: Only ONE 48KB framebuffer (not double-buffered)
|
||||
* Flash: 16MB (Instruction storage and static data)
|
||||
* Display: 800x480 E-Ink (Slow refresh, monochrome, 1-2s full update)
|
||||
* Framebuffer: 48,000 bytes (800 × 480 ÷ 8)
|
||||
* Storage: SD Card (Used for books and aggressive caching)
|
||||
|
||||
### The Resource Protocol
|
||||
1. Stack Safety: Limit local function variables to < 256 bytes. The ESP32-C3 default stack is small; use std::unique_ptr or static pools for larger buffers.
|
||||
2. Heap Fragmentation: Avoid repeated new/delete in loops. Allocate buffers once during onEnter() and reuse them.
|
||||
3. Flash Persistence: Large constant data (UI strings, lookup tables) MUST be marked static const to stay in Flash (Instruction Bus), freeing DRAM.
|
||||
4. String Policy: Prohibit std::string and Arduino String in hot paths. Use std::string_view for read-only access and snprintf with fixed char[] buffers for construction.
|
||||
5. UI Strings: All user-facing text must use the `tr()` macro (e.g., `tr(STR_LOADING)`) for i18n support. Never hardcode UI strings directly. For the avoidance of doubt, logging messages (LOG_DBG/LOG_ERR) can be hardcoded, but user-facing text must use `tr()`.
|
||||
6. `constexpr` First: Compile-time constants and lookup tables must be `constexpr`, not just `static const`. This moves computation to compile time, enables dead-branch elimination, and guarantees flash placement. Use `static constexpr` for class-level constants.
|
||||
7. `std::vector` Pre-allocation: Always call `.reserve(N)` before any `push_back()` loop. Each growth event allocates a new block (2×), copies all elements, then frees the old one — three heap operations that fragment DRAM. When the final size is unknown, estimate conservatively.
|
||||
8. SPIFFS Write Throttling: Never write a settings file on every user interaction. Guard all writes with a value-change check (`if (newVal == _current) return;`). Progress saves during reading must be debounced — write on activity exit or every N page turns, not on every turn. SPIFFS sectors have a finite erase cycle limit.
|
||||
|
||||
---
|
||||
|
||||
## Project Architecture
|
||||
|
||||
### Build System: PlatformIO
|
||||
|
||||
**PlatformIO is BOTH a VS Code extension AND a CLI tool**:
|
||||
|
||||
1. **VS Code Extension** (Recommended):
|
||||
* Extension ID: `platformio.platformio-ide` (see `.vscode/extensions.json`)
|
||||
* Provides: Toolbar buttons, IntelliSense, integrated build/upload/monitor
|
||||
* Configuration: `.vscode/c_cpp_properties.json`, `.vscode/tasks.json`
|
||||
* Usage: Click Build (✓), Upload (→), or Monitor (🔌) buttons
|
||||
|
||||
2. **CLI Tool** (`pio` command):
|
||||
* **Installation**: Python package (typically `pip install platformio`)
|
||||
* **Windows Location**: `C:\Users\<user>\AppData\Local\Programs\Python\Python3xx\Scripts\pio.exe`
|
||||
* **Verify**: `which pio` (Git Bash) or `where.exe pio` (cmd)
|
||||
* **Usage**: `pio run`, `pio run -t upload`, etc.
|
||||
|
||||
**Configuration Files**:
|
||||
* `platformio.ini`: Main build configuration (committed to git)
|
||||
* `platformio.local.ini`: Local overrides (gitignored, create if needed)
|
||||
* `partitions.csv`: ESP32 flash partition layout
|
||||
|
||||
### Build Environment
|
||||
* **Standard**: C++20 (`-std=c++2a`). No Exceptions, No RTTI.
|
||||
* **Logging**: ALWAYS use `LOG_INF`, `LOG_DBG`, or `LOG_ERR` from `Logging.h`. Raw Serial output is deprecated.
|
||||
* **Environments** (in `platformio.ini`):
|
||||
* `default`: Development (LOG_LEVEL=2, serial enabled)
|
||||
* `gh_release`: Production (LOG_LEVEL=0)
|
||||
* `gh_release_rc`: Release candidate (LOG_LEVEL=1)
|
||||
* `slim`: Minimal build (no serial logging)
|
||||
|
||||
### Critical Build Flags
|
||||
These flags in `platformio.ini` fundamentally affect firmware behavior:
|
||||
|
||||
```cpp
|
||||
-DEINK_DISPLAY_SINGLE_BUFFER_MODE=1 // Single framebuffer (saves 48KB RAM!)
|
||||
-DARDUINO_USB_MODE=1 // Enable USB CDC
|
||||
-DARDUINO_USB_CDC_ON_BOOT=1 // Serial available immediately at boot
|
||||
-DXML_CONTEXT_BYTES=1024 // XML parser memory limit (EPUB parsing)
|
||||
-DUSE_UTF8_LONG_NAMES=1 // SD card long filename support
|
||||
-DMINIZ_NO_ZLIB_COMPATIBLE_NAMES=1 // Avoid zlib name conflicts
|
||||
-DXML_GE=0 // Disable XML general entities (security)
|
||||
```
|
||||
|
||||
**SINGLE_BUFFER_MODE implications**:
|
||||
- Only ONE framebuffer exists (not double-buffered)
|
||||
- Grayscale rendering requires temporary buffer allocation (`renderer.storeBwBuffer()`)
|
||||
- Must call `renderer.restoreBwBuffer()` to free temporary buffers
|
||||
- See [lib/GfxRenderer/GfxRenderer.cpp:439-440](lib/GfxRenderer/GfxRenderer.cpp) for malloc usage
|
||||
|
||||
### Directory Structure
|
||||
* lib/: Internal libraries (Epub engine, GfxRenderer, UITheme, I18n)
|
||||
* lib/hal/: Hardware Abstraction Layer (HalDisplay, HalGPIO, HalStorage)
|
||||
* lib/I18n/: Internationalization (translations in `translations/*.yaml`, generated string tables)
|
||||
* src/activities/: UI logic using the Activity Lifecycle (onEnter, loop, onExit)
|
||||
* open-x4-sdk/: Low-level SDK (EInkDisplay, InputManager, BatteryMonitor, SDCardManager)
|
||||
* .crosspoint/: SD-based binary cache for EPUB metadata and pre-rendered layout sections
|
||||
|
||||
### Hardware Abstraction Layer (HAL)
|
||||
|
||||
**CRITICAL**: Always use HAL classes, NOT SDK classes directly.
|
||||
|
||||
| HAL Class | Wraps SDK Class | Purpose | Singleton Macro |
|
||||
|-----------|----------------|---------|-----------------|
|
||||
| `HalDisplay` | `EInkDisplay` | E-ink display control | *(none)* |
|
||||
| `HalGPIO` | `InputManager` | Button input handling | *(none)* |
|
||||
| `HalStorage` | `SDCardManager` | SD card file I/O | `Storage` |
|
||||
|
||||
**Location**: [lib/hal/](lib/hal/)
|
||||
|
||||
**Why HAL?**
|
||||
- Provides consistent error logging per module
|
||||
- Abstracts SDK implementation details
|
||||
- Centralizes resource management
|
||||
|
||||
**Example - HalStorage**:
|
||||
```cpp
|
||||
#include <HalStorage.h>
|
||||
|
||||
// Use Storage singleton (defined via macro)
|
||||
FsFile file;
|
||||
if (Storage.openFileForRead("MODULE", "/path/to/file.bin", file)) {
|
||||
// Read from file
|
||||
file.close(); // Explicit close required
|
||||
}
|
||||
```
|
||||
|
||||
**Usage**: See example above. Uses `FsFile` (SdFat), NOT Arduino `File`.
|
||||
|
||||
---
|
||||
|
||||
## Coding Standards
|
||||
|
||||
### Naming Conventions
|
||||
* Classes: PascalCase (e.g., EpubReaderActivity)
|
||||
* Methods/Variables: camelCase (e.g., renderPage())
|
||||
* Constants: UPPER_SNAKE_CASE (e.g., MAX_BUFFER_SIZE)
|
||||
* Private Members: memberVariable (no prefix)
|
||||
* File Names: Match Class names (e.g., EpubReaderActivity.cpp)
|
||||
|
||||
### Header Guards
|
||||
* Use #pragma once for all header files.
|
||||
|
||||
### Memory Safety and RAII
|
||||
* Smart Pointers: Prefer std::unique_ptr. Avoid std::shared_ptr (unnecessary atomic overhead for a single-core RISC-V).
|
||||
* RAII: Use destructors for cleanup, but call file.close() or vTaskDelete() explicitly for deterministic resource release.
|
||||
|
||||
### ESP32-C3 Platform Pitfalls
|
||||
|
||||
#### `std::string_view` and Null Termination
|
||||
`string_view` is *not* null-terminated. Passing `.data()` to any C-style API (`drawText`, `snprintf`, `strcmp`, SdFat file paths) is undefined behaviour when the view is a substring or a view of a non-null-terminated buffer.
|
||||
|
||||
**Rule**: `string_view` is safe only when passing to C++ APIs that accept `string_view`. For any C API boundary, convert explicitly:
|
||||
```cpp
|
||||
// WRONG - undefined behaviour if view is a substring:
|
||||
renderer.drawText(font, x, y, myView.data(), true);
|
||||
|
||||
// CORRECT - guaranteed null-terminated:
|
||||
renderer.drawText(font, x, y, std::string(myView).c_str(), true);
|
||||
|
||||
// CORRECT - for short strings, use a stack buffer:
|
||||
char buf[64];
|
||||
snprintf(buf, sizeof(buf), "%.*s", (int)myView.size(), myView.data());
|
||||
```
|
||||
|
||||
#### `IRAM_ATTR` and Flash Cache Safety
|
||||
All code runs from flash via the instruction cache. During SPI flash operations (OTA write, SPIFFS commit, NVS update) the cache is briefly suspended. Any code that can execute during this window — ISRs in particular — must reside in IRAM or it will crash silently.
|
||||
|
||||
```cpp
|
||||
// ISR handler: must be in IRAM
|
||||
void IRAM_ATTR gpioISR() { ... }
|
||||
|
||||
// Data accessed from IRAM_ATTR code: must be in DRAM, never a flash const
|
||||
static DRAM_ATTR uint32_t isrEventFlags = 0;
|
||||
```
|
||||
|
||||
**Rules**:
|
||||
- All ISR handlers: `IRAM_ATTR`
|
||||
- Data read by `IRAM_ATTR` code: `DRAM_ATTR` (a flash-resident `static const` will fault)
|
||||
- Normal task code does **not** need `IRAM_ATTR`
|
||||
|
||||
#### ISR vs Task Shared State
|
||||
`xSemaphoreTake()` (mutex) **cannot** be called from ISR context — it will crash. Use the correct primitive for each communication direction:
|
||||
|
||||
| Direction | Correct primitive |
|
||||
|---|---|
|
||||
| ISR → task (data) | `xQueueSendFromISR()` + `portYIELD_FROM_ISR()` |
|
||||
| ISR → task (signal) | `xSemaphoreGiveFromISR()` + `portYIELD_FROM_ISR()` |
|
||||
| Task → task | `xSemaphoreTake()` / mutex |
|
||||
| Simple flag (single writer ISR) | `volatile bool` + `portENTER_CRITICAL_ISR()` |
|
||||
|
||||
#### RISC-V Alignment
|
||||
ESP32-C3 faults on unaligned multi-byte loads. Never cast a `uint8_t*` buffer to a wider pointer type and dereference it directly. Use `memcpy` for any unaligned read:
|
||||
|
||||
```cpp
|
||||
// WRONG — faults if buf is not 4-byte aligned:
|
||||
uint32_t val = *reinterpret_cast<const uint32_t*>(buf);
|
||||
|
||||
// CORRECT:
|
||||
uint32_t val;
|
||||
memcpy(&val, buf, sizeof(val));
|
||||
```
|
||||
|
||||
This applies to all cache deserialization code and any raw buffer-to-struct casting. `__attribute__((packed))` structs have the same hazard when accessed via member reference.
|
||||
|
||||
#### Template and `std::function` Bloat
|
||||
Each template instantiation generates a separate binary copy. `std::function<void()>` adds ~2–4 KB per unique signature and heap-allocates its closure. Avoid both in library code and any path called from the render loop:
|
||||
|
||||
```cpp
|
||||
// Avoid — heap-allocating, large binary footprint:
|
||||
std::function<void()> callback;
|
||||
|
||||
// Prefer — zero overhead:
|
||||
void (*callback)() = nullptr;
|
||||
|
||||
// For member function + context (common activity callback pattern):
|
||||
struct Callback { void* ctx; void (*fn)(void*); };
|
||||
```
|
||||
|
||||
When a template is necessary, limit instantiations: use explicit template instantiation in a `.cpp` file to prevent the compiler from generating duplicates across translation units.
|
||||
|
||||
---
|
||||
|
||||
### Error Handling Philosophy
|
||||
|
||||
**Source**: [src/main.cpp:132-143](src/main.cpp), [lib/GfxRenderer/GfxRenderer.cpp:10](lib/GfxRenderer/GfxRenderer.cpp)
|
||||
|
||||
**Pattern Hierarchy**:
|
||||
1. **LOG_ERR + return false** (90%): `LOG_ERR("MOD", "Failed: %s", reason); return false;`
|
||||
2. **LOG_ERR + fallback**: `LOG_ERR("MOD", "Unavailable"); useDefault();`
|
||||
3. **assert(false)**: Only for fatal "impossible" states (framebuffer missing)
|
||||
4. **ESP.restart()**: Only for recovery (OTA complete)
|
||||
|
||||
**Rules**: NO exceptions, NO abort(), ALWAYS log before error return
|
||||
|
||||
### Acceptable malloc/free Patterns
|
||||
|
||||
**Source**: [src/activities/home/HomeActivity.cpp:166](src/activities/home/HomeActivity.cpp), [lib/GfxRenderer/GfxRenderer.cpp:439-440](lib/GfxRenderer/GfxRenderer.cpp)
|
||||
|
||||
Despite "prefer stack allocation," malloc is acceptable for:
|
||||
1. **Large temporary buffers** (> 256 bytes, won't fit on stack)
|
||||
2. **One-time allocations** during activity initialization
|
||||
3. **Bitmap rendering buffers** (variable size, used briefly)
|
||||
|
||||
**Pattern**:
|
||||
```cpp
|
||||
// Allocate
|
||||
auto* buffer = static_cast<uint8_t*>(malloc(bufferSize));
|
||||
if (!buffer) {
|
||||
LOG_ERR("MODULE", "malloc failed: %d bytes", bufferSize);
|
||||
return false; // Handle allocation failure
|
||||
}
|
||||
|
||||
// Use buffer
|
||||
processData(buffer, bufferSize);
|
||||
|
||||
// Free immediately after use
|
||||
free(buffer);
|
||||
buffer = nullptr;
|
||||
```
|
||||
|
||||
**Rules**:
|
||||
- **ALWAYS check for nullptr** after malloc
|
||||
- **Free immediately** after use (don't hold across multiple operations)
|
||||
- **Set to nullptr** after free (avoid use-after-free)
|
||||
- **Document size**: Comment why stack allocation was rejected
|
||||
|
||||
**Examples in codebase**:
|
||||
- Cover image buffers: [HomeActivity.cpp:166](src/activities/home/HomeActivity.cpp#L166)
|
||||
- Text chunk buffers: [TxtReaderActivity.cpp:259](src/activities/reader/TxtReaderActivity.cpp#L259)
|
||||
- Bitmap rendering: [GfxRenderer.cpp:439-440](lib/GfxRenderer/GfxRenderer.cpp#L439-L440)
|
||||
- OTA update buffer: [OtaUpdater.cpp:40](src/network/OtaUpdater.cpp#L40)
|
||||
|
||||
---
|
||||
|
||||
## UI and Orientation Guidelines
|
||||
|
||||
### Orientation-Aware Logic
|
||||
* No Hardcoding: Never assume 800 or 480. Use renderer.getScreenWidth() and renderer.getScreenHeight().
|
||||
* Viewable Area: Use renderer.getOrientedViewableTRBL() to stay within physical bezel margins.
|
||||
|
||||
### Logical Button Mapping
|
||||
|
||||
**Source**: [src/MappedInputManager.cpp:20-55](src/MappedInputManager.cpp)
|
||||
|
||||
Constraint: Physical button positions are fixed on hardware, but their logical functions change based on user settings and screen orientation.
|
||||
|
||||
**Button Categories**:
|
||||
1. **Physical Fixed** (Up/Down side buttons):
|
||||
- `Button::Up` → Always `HalGPIO::BTN_UP`
|
||||
- `Button::Down` → Always `HalGPIO::BTN_DOWN`
|
||||
|
||||
2. **User Remappable** (Front buttons):
|
||||
- `Button::Back` → Maps to `SETTINGS.frontButtonBack` (hardware index)
|
||||
- `Button::Confirm` → Maps to `SETTINGS.frontButtonConfirm`
|
||||
- `Button::Left` → Maps to `SETTINGS.frontButtonLeft`
|
||||
- `Button::Right` → Maps to `SETTINGS.frontButtonRight`
|
||||
|
||||
3. **Reader-Specific** (Page navigation with optional swap):
|
||||
- `Button::PageBack` → Uses side button (swappable via `SETTINGS.sideButtonLayout`)
|
||||
- `Button::PageForward` → Uses side button (swappable)
|
||||
|
||||
**Implementation**:
|
||||
- Activities use **logical buttons** (e.g., `Button::Confirm`)
|
||||
- `MappedInputManager` translates to **physical hardware buttons**
|
||||
- User can remap front buttons in settings
|
||||
- Orientation changes handled separately by renderer coordinate transforms
|
||||
|
||||
**Rule**: Always use `MappedInputManager::Button::*` enums, never raw `HalGPIO::BTN_*` indices (except in ButtonRemapActivity).
|
||||
|
||||
### UITheme (The GUI Macro)
|
||||
* Rule: All UI rendering must go through the GUI macro (UITheme).
|
||||
* Do not hardcode fonts, colors, or positioning. This ensures orientation-aware layout consistency.
|
||||
|
||||
---
|
||||
|
||||
## Common Patterns
|
||||
|
||||
### Singleton Access
|
||||
**Available Singletons**:
|
||||
```cpp
|
||||
#define SETTINGS CrossPointSettings::getInstance() // User settings
|
||||
#define APP_STATE CrossPointState::getInstance() // Runtime state
|
||||
#define GUI UITheme::getInstance() // Current theme
|
||||
#define Storage HalStorage::getInstance() // SD card I/O
|
||||
#define I18N I18n::getInstance() // Internationalization
|
||||
```
|
||||
|
||||
### Activity Lifecycle and Memory Management
|
||||
|
||||
**Source**: [src/main.cpp:132-143](src/main.cpp)
|
||||
|
||||
**CRITICAL**: Activities are **heap-allocated** and **deleted on exit**.
|
||||
|
||||
```cpp
|
||||
// main.cpp navigation pattern
|
||||
void exitActivity() {
|
||||
if (currentActivity) {
|
||||
currentActivity->onExit();
|
||||
delete currentActivity; // Activity deleted here!
|
||||
currentActivity = nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
void enterNewActivity(Activity* activity) {
|
||||
currentActivity = activity; // Heap-allocated activity
|
||||
currentActivity->onEnter();
|
||||
}
|
||||
```
|
||||
|
||||
**Memory Implications**:
|
||||
- Activity navigation = `delete` old activity + `new` create next activity
|
||||
- Any memory allocated in `onEnter()` MUST be freed in `onExit()`
|
||||
- FreeRTOS tasks MUST be deleted in `onExit()` before activity destruction
|
||||
- File handles MUST be closed in `onExit()`
|
||||
|
||||
**Activity Pattern**:
|
||||
```cpp
|
||||
void onEnter() { Activity::onEnter(); /* alloc: buffer, tasks */ render(); }
|
||||
void loop() { mappedInput.update(); /* handle input */ }
|
||||
void onExit() { /* free: vTaskDelete, free buffer, close files */ Activity::onExit(); }
|
||||
```
|
||||
|
||||
**Critical**: Free resources in reverse order. Delete tasks BEFORE activity destruction.
|
||||
|
||||
### FreeRTOS Task Guidelines
|
||||
|
||||
**Source**: [src/activities/util/KeyboardEntryActivity.cpp:45-50](src/activities/util/KeyboardEntryActivity.cpp)
|
||||
|
||||
**Pattern**: See Activity Lifecycle above. `xTaskCreate(&taskTrampoline, "Name", stackSize, this, 1, &handle)`
|
||||
|
||||
**Stack Sizing** (in BYTES, not words):
|
||||
- **2048**: Simple rendering (most activities)
|
||||
- **4096**: Network, EPUB parsing
|
||||
- Monitor: `uxTaskGetStackHighWaterMark()` if crashes
|
||||
|
||||
**Rules**: Always `vTaskDelete()` in `onExit()` before destruction. Use mutex if shared state.
|
||||
|
||||
### Global Font Loading
|
||||
|
||||
**Source**: [src/main.cpp:40-115](src/main.cpp)
|
||||
|
||||
**All fonts are loaded as global static objects** at firmware startup:
|
||||
- Bookerly: 12, 14, 16, 18pt (4 styles each: regular, bold, italic, bold-italic)
|
||||
- Noto Sans: 12, 14, 16, 18pt (4 styles each)
|
||||
- OpenDyslexic: 8, 10, 12, 14pt (4 styles each)
|
||||
- Ubuntu UI fonts: 10, 12pt (2 styles)
|
||||
|
||||
**Total**: ~80+ global `EpdFont` and `EpdFontFamily` objects
|
||||
|
||||
**Compilation Flag**:
|
||||
```cpp
|
||||
#ifndef OMIT_FONTS
|
||||
// Most fonts loaded here
|
||||
#endif
|
||||
```
|
||||
|
||||
**Implications**:
|
||||
- Fonts stored in **Flash** (marked as `static const` in `lib/EpdFont/builtinFonts/`)
|
||||
- Font rendering data cached in **DRAM** when first used
|
||||
- `OMIT_FONTS` can reduce binary size for minimal builds
|
||||
- Font IDs defined in [src/fontIds.h](src/fontIds.h)
|
||||
|
||||
**Usage**:
|
||||
```cpp
|
||||
#include "fontIds.h"
|
||||
|
||||
renderer.insertFont(FONT_UI_MEDIUM, ui12FontFamily);
|
||||
renderer.drawText(FONT_UI_MEDIUM, x, y, "Hello", true);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Testing and Debugging
|
||||
|
||||
### Build Commands
|
||||
|
||||
**Via CLI**:
|
||||
```bash
|
||||
# Build firmware (default environment)
|
||||
pio run
|
||||
|
||||
# Build and upload to device
|
||||
pio run -t upload
|
||||
|
||||
# Build specific environment
|
||||
pio run -e gh_release
|
||||
|
||||
# Clean build artifacts
|
||||
pio run -t clean
|
||||
|
||||
# Upload filesystem data (if using SPIFFS/LittleFS)
|
||||
pio run -t uploadfs
|
||||
```
|
||||
|
||||
**Via VS Code**:
|
||||
* Use PlatformIO toolbar: Build (✓), Upload (→), Clean (🗑️)
|
||||
* Or Command Palette: `PlatformIO: Build`, `PlatformIO: Upload`, etc.
|
||||
|
||||
### Monitoring and Debugging
|
||||
|
||||
```bash
|
||||
# Enhanced monitor with color/logging (recommended)
|
||||
python3 scripts/debugging_monitor.py
|
||||
|
||||
# Standard PlatformIO monitor
|
||||
pio device monitor
|
||||
|
||||
# Combined upload + monitor
|
||||
pio run -t upload && pio device monitor
|
||||
```
|
||||
|
||||
**Via VS Code**: Click Monitor (🔌) button in PlatformIO toolbar
|
||||
|
||||
### Code Quality
|
||||
|
||||
```bash
|
||||
# Static analysis (cppcheck)
|
||||
pio check
|
||||
|
||||
# Format code (clang-format) - Windows Git Bash
|
||||
find src -name "*.cpp" -o -name "*.h" | xargs clang-format -i
|
||||
|
||||
# Format code (clang-format) - Linux
|
||||
clang-format -i src/**/*.cpp src/**/*.h
|
||||
```
|
||||
|
||||
### Debugging Crashes
|
||||
|
||||
**Common Crash Causes**:
|
||||
|
||||
1. **Out of Memory** (Most common):
|
||||
```cpp
|
||||
LOG_DBG("MEM", "Free heap: %d bytes", ESP.getFreeHeap());
|
||||
```
|
||||
- Monitor heap usage throughout activity lifecycle
|
||||
- Check if large allocations (>10KB) occur before crash
|
||||
- Verify buffers are freed in `onExit()`
|
||||
|
||||
2. **Stack Overflow**:
|
||||
```cpp
|
||||
LOG_DBG("TASK", "Stack high water: %d", uxTaskGetStackHighWaterMark(taskHandle));
|
||||
```
|
||||
- Occurs during deep recursion or large local variables
|
||||
- Increase task stack size in `xTaskCreate()` (2048 → 4096)
|
||||
- Move large buffers to heap with malloc
|
||||
|
||||
3. **Use-After-Free**:
|
||||
- Activity deleted but task still running
|
||||
- Always `vTaskDelete()` in `onExit()` BEFORE activity destruction
|
||||
- Set pointers to `nullptr` after `free()`
|
||||
|
||||
4. **Corrupt Cache Files**:
|
||||
- Delete `.crosspoint/` directory on SD card
|
||||
- Forces clean re-parse of all EPUBs
|
||||
- Check file format versions in [docs/file-formats.md](docs/file-formats.md)
|
||||
|
||||
5. **Watchdog Timeout**:
|
||||
- Loop/task blocked for >5 seconds
|
||||
- Add `vTaskDelay(1)` in tight loops
|
||||
- Check for blocking I/O operations
|
||||
|
||||
**Verification Steps**:
|
||||
1. Check serial output for stack traces
|
||||
2. Monitor heap with `ESP.getFreeHeap()` before/after operations
|
||||
3. Verify task deletion with task list (`vTaskList()`)
|
||||
4. Test with `LOG_LEVEL=2` (debug logging enabled)
|
||||
|
||||
---
|
||||
|
||||
## Git Workflow and Repository Awareness
|
||||
|
||||
### Repository Detection Protocol
|
||||
|
||||
**CRITICAL**: ALWAYS verify repository context before git operations. This could be:
|
||||
- A **fork** with `origin` pointing to personal repo, `upstream` to main repo
|
||||
- A **direct clone** with `origin` pointing to main repo
|
||||
- Multiple collaborator remotes
|
||||
|
||||
**Verification Commands** (run at session start):
|
||||
```bash
|
||||
# Check current branch
|
||||
git branch --show-current
|
||||
|
||||
# Check all remotes
|
||||
git remote -v
|
||||
|
||||
# Identify main branch name (could be 'main' or 'master')
|
||||
git symbolic-ref refs/remotes/origin/HEAD 2>/dev/null | sed 's@^refs/remotes/origin/@@'
|
||||
|
||||
# Check working tree status
|
||||
git status --short
|
||||
```
|
||||
|
||||
**Example Output** (forked repository):
|
||||
```text
|
||||
origin https://github.com/<your-username>/crosspoint-reader.git (fetch/push)
|
||||
upstream https://github.com/crosspoint-reader/crosspoint-reader.git (fetch/push)
|
||||
```
|
||||
|
||||
### Git Operation Rules
|
||||
|
||||
1. **Never assume branch names**:
|
||||
```bash
|
||||
# Bad: git push origin main
|
||||
# Good: git push origin $(git branch --show-current)
|
||||
```
|
||||
|
||||
2. **Never assume remote names or write permissions**:
|
||||
- **Forked repos**: Push to `origin` (your fork), submit PR to `upstream`
|
||||
- **Direct contributors**: May push feature branches to `upstream`
|
||||
- **Always ask**: "Should I push to origin or create a PR?"
|
||||
|
||||
3. **Check for upstream changes before starting work**:
|
||||
```bash
|
||||
# Sync fork with upstream (if applicable)
|
||||
git fetch upstream
|
||||
git merge upstream/main # or upstream/master
|
||||
```
|
||||
|
||||
4. **Use explicit remote and branch names**:
|
||||
```bash
|
||||
# Check remotes first
|
||||
git remote -v
|
||||
|
||||
# Use explicit syntax
|
||||
git push <remote> <branch>
|
||||
```
|
||||
|
||||
### Branch Naming Convention
|
||||
|
||||
**For feature/fix branches**:
|
||||
```text
|
||||
feature/<short-description> # New features
|
||||
fix/<issue-number>-<description> # Bug fixes
|
||||
refactor/<component-name> # Code refactoring
|
||||
docs/<topic> # Documentation updates
|
||||
```
|
||||
|
||||
**Examples**:
|
||||
- `feature/sd-download-progress`
|
||||
- `fix/123-orientation-crash`
|
||||
- `refactor/hal-storage`
|
||||
|
||||
### Commit Message Format
|
||||
|
||||
**Pattern**:
|
||||
```text
|
||||
<type>: <short summary (50 chars max)>
|
||||
|
||||
<optional detailed description>
|
||||
|
||||
```
|
||||
|
||||
**Types**: `feat`, `fix`, `refactor`, `docs`, `test`, `chore`, `perf`
|
||||
|
||||
**Example**:
|
||||
```text
|
||||
feat: add real-time SD download progress bar
|
||||
|
||||
Implements progress tracking for book downloads using
|
||||
UITheme progress bar component with heap-safe updates.
|
||||
|
||||
Tested in all 4 orientations with 5MB+ files.
|
||||
```
|
||||
|
||||
### When to Commit
|
||||
|
||||
**DO commit when**:
|
||||
- User explicitly requests: "commit these changes"
|
||||
- Feature is complete and tested on device
|
||||
- Bug fix is verified working
|
||||
- Refactoring preserves all functionality
|
||||
- All tests pass (`pio run` succeeds)
|
||||
|
||||
**DO NOT commit when**:
|
||||
- Changes are untested on actual hardware
|
||||
- Build fails or has warnings
|
||||
- Experimenting or debugging in progress
|
||||
- User hasn't explicitly requested commit
|
||||
- Files excluded by `.gitignore` would be included — always run `git status` and cross-check against `.gitignore` before staging (e.g., `*.generated.h`, `.pio/`, `compile_commands.json`, `platformio.local.ini`)
|
||||
|
||||
**Rule**: **If uncertain, ASK before committing.**
|
||||
|
||||
---
|
||||
|
||||
## Generated Files and Build Artifacts
|
||||
|
||||
### Files Generated by Build Scripts
|
||||
|
||||
**NEVER manually edit these files** - they are regenerated automatically:
|
||||
|
||||
1. **HTML Headers** (generated by `scripts/build_html.py`):
|
||||
- `src/network/html/*.generated.h`
|
||||
- **Source**: HTML templates in `data/html/` directory
|
||||
- **Triggered**: During PlatformIO `pre:` build step
|
||||
- **To modify**: Edit source HTML in `data/html/`, not generated headers
|
||||
|
||||
2. **I18n Headers** (generated by `scripts/gen_i18n.py`):
|
||||
- `lib/I18n/I18nKeys.h`, `lib/I18n/I18nStrings.h`, `lib/I18n/I18nStrings.cpp`
|
||||
- **Source**: YAML translation files in `lib/I18n/translations/` (one per language)
|
||||
- **To modify**: Edit source YAML files, then run `python scripts/gen_i18n.py lib/I18n/translations lib/I18n/`
|
||||
- **Commit**: Source YAML files + `I18nKeys.h` and `I18nStrings.h` (needed for IDE symbol resolution), but NOT `I18nStrings.cpp`
|
||||
|
||||
3. **Build Artifacts** (in `.gitignore`):
|
||||
- `.pio/` - PlatformIO build output
|
||||
- `build/` - Compiled binaries
|
||||
- `*.generated.h` - Any auto-generated headers
|
||||
- `compile_commands.json` - LSP/IDE metadata
|
||||
|
||||
### Modifying Generated Content Workflow
|
||||
|
||||
**To change HTML pages**:
|
||||
1. Edit source: `data/html/<pagename>.html`
|
||||
2. Build: `pio run` (auto-triggers `scripts/build_html.py`)
|
||||
3. Generated headers update: `src/network/html/<pagename>Html.generated.h`
|
||||
4. **Commit ONLY** source HTML, NOT generated `.generated.h` files
|
||||
|
||||
**To add/modify translations (i18n)**:
|
||||
1. Edit or add YAML file: `lib/I18n/translations/<language>.yaml`
|
||||
- Each file must contain: `_language_name`, `_language_code`, `_order`, and `STR_*` keys
|
||||
- English (`english.yaml`) is the reference; missing keys in other languages fall back to English
|
||||
2. Run generator: `python scripts/gen_i18n.py lib/I18n/translations lib/I18n/`
|
||||
3. Generated files update: `I18nKeys.h`, `I18nStrings.h`, `I18nStrings.cpp`
|
||||
4. **Commit** source YAML files + `I18nKeys.h` and `I18nStrings.h` (IDE needs these for symbol resolution), but NOT `I18nStrings.cpp`
|
||||
|
||||
**To use translated strings in code**:
|
||||
```cpp
|
||||
#include <I18n.h>
|
||||
// Use tr() macro with StrId enum (defined in generated I18nKeys.h)
|
||||
renderer.drawText(FONT_UI, x, y, tr(STR_LOADING), true);
|
||||
```
|
||||
|
||||
**To add custom fonts**:
|
||||
1. Place source fonts in `lib/EpdFont/fontsrc/` (gitignored)
|
||||
2. Run conversion script (see `lib/EpdFont/README`)
|
||||
3. Update global font objects in `src/main.cpp:40-115`
|
||||
4. Add font ID constant to `src/fontIds.h`
|
||||
|
||||
---
|
||||
|
||||
## Local Development Configuration
|
||||
|
||||
### platformio.local.ini (Personal Overrides)
|
||||
|
||||
**Purpose**: Personal development settings that should NEVER be committed.
|
||||
|
||||
**Use Cases**:
|
||||
- Serial port configuration (varies by machine)
|
||||
- Debug flags for specific testing
|
||||
- Local build optimizations
|
||||
- Developer-specific paths
|
||||
|
||||
**Example** `platformio.local.ini`:
|
||||
```ini
|
||||
# platformio.local.ini (gitignored)
|
||||
[env:default]
|
||||
upload_port = COM7 # Windows: COMx, Linux: /dev/ttyUSBx
|
||||
monitor_port = COM7
|
||||
|
||||
build_flags =
|
||||
${base.build_flags}
|
||||
-DMY_DEBUG_FLAG=1 # Personal debug flags
|
||||
-DTEST_FEATURE_ENABLED=1
|
||||
```
|
||||
|
||||
**Configuration Hierarchy**:
|
||||
1. `platformio.ini` - **Committed**, shared project settings
|
||||
2. `platformio.local.ini` - **Gitignored**, personal overrides
|
||||
3. Local file extends/overrides base config
|
||||
|
||||
**Rules**:
|
||||
- **NEVER commit** `platformio.local.ini`
|
||||
- **NEVER put** personal info (serial ports, credentials) in main `platformio.ini`
|
||||
- Use `${base.build_flags}` to extend (not replace) base flags
|
||||
|
||||
---
|
||||
|
||||
## Testing and Verification Workflow
|
||||
|
||||
### Testing Checklist
|
||||
|
||||
**AI agent scope** (what you CAN verify):
|
||||
1. ✅ **Build**: `pio run -t clean && pio run` (0 errors/warnings)
|
||||
2. ✅ **Quality**: `pio check` + `find src -name "*.cpp" -o -name "*.h" | xargs clang-format -i`
|
||||
3. ✅ **Format**: Commit messages (`feat:`/`fix:`), no `.gitignore`-excluded files staged (e.g., `*.generated.h`, `.pio/`, `platformio.local.ini`)
|
||||
4. ✅ **CI**: Fix GitHub Actions failures before review
|
||||
5. ✅ **Code review**: Ensure orientation-aware logic is correct in all 4 modes by inspecting switch/case coverage
|
||||
|
||||
**Human tester scope** (flag these for the user):
|
||||
6. 🔲 **Device**: Test on hardware
|
||||
7. 🔲 **Orientations**: Verify all 4 modes (Portrait/Inverted/Landscape CW/CCW)
|
||||
8. 🔲 **Heap**: `ESP.getFreeHeap()` > 50KB, no leaks
|
||||
9. 🔲 **Cache**: If EPUB modified, delete `.crosspoint/` and verify re-parse
|
||||
|
||||
### CI/CD Pipeline Awareness
|
||||
|
||||
**GitHub Actions** run automatically on pull requests:
|
||||
|
||||
| Workflow | File | Purpose |
|
||||
|----------|------|---------|
|
||||
| Build Check | `.github/workflows/ci.yml` | Verifies code compiles |
|
||||
| Format Check | `.github/workflows/pr-formatting-check.yml` | Validates clang-format |
|
||||
| Release Build | `.github/workflows/release.yml` | Production releases |
|
||||
| RC Build | `.github/workflows/release_candidate.yml` | Release candidates |
|
||||
|
||||
**Rules**:
|
||||
- **Fix CI failures BEFORE** requesting review
|
||||
- CI runs on: Push to PR, PR updates
|
||||
- Format check fails → Run clang-format locally
|
||||
- Build check fails → Fix compile errors
|
||||
|
||||
---
|
||||
|
||||
## Serial Monitoring and Live Debugging
|
||||
|
||||
### Serial Monitor Options
|
||||
|
||||
1. **Enhanced**: `python3 scripts/debugging_monitor.py` (color-coded, recommended)
|
||||
2. **Standard**: `pio device monitor` (basic, no colors)
|
||||
3. **VS Code**: Monitor (🔌) button (IDE-integrated)
|
||||
|
||||
### Live Debugging Patterns
|
||||
|
||||
**Heap**: `LOG_DBG("MEM", "Free: %d", ESP.getFreeHeap());` (every 5s in loop)
|
||||
**Stack**: `uxTaskGetStackHighWaterMark(nullptr)` (< 512 bytes → increase stack)
|
||||
**Flush**: `logSerial.flush();` (force output before crash)
|
||||
|
||||
**Port Detection**: Windows: `mode` | Linux: `ls /dev/ttyUSB* /dev/ttyACM*` or `dmesg | grep tty`
|
||||
|
||||
---
|
||||
|
||||
## Cache Management and Invalidation
|
||||
|
||||
### Cache Structure on SD Card
|
||||
|
||||
**Location**: `.crosspoint/` directory on SD card root
|
||||
|
||||
**Structure**: `.crosspoint/epub_<hash>/{book.bin, progress.bin, cover.bmp, sections/*.bin}`
|
||||
|
||||
**Hash**: `std::hash<std::string>{}(filepath)` → Moving/renaming file = new hash = lost progress
|
||||
|
||||
### Cache Invalidation Rules
|
||||
|
||||
**Cache is automatically invalidated when**:
|
||||
1. **File format version changes** (see `docs/file-formats.md`)
|
||||
- `book.bin` version number incremented
|
||||
- `section.bin` version number incremented
|
||||
2. **Render settings change**:
|
||||
- Font family or size (`SETTINGS.fontFamily`, `SETTINGS.fontSize`)
|
||||
- Line spacing (`SETTINGS.lineSpacing`)
|
||||
- Paragraph spacing (`SETTINGS.extraParagraphSpacing`)
|
||||
- Screen margins (`SETTINGS.screenMargin`)
|
||||
3. **Viewport dimensions change**:
|
||||
- Screen orientation change
|
||||
- Display resolution change
|
||||
4. **Book file modified**:
|
||||
- Moved, renamed, or content changed (new hash)
|
||||
|
||||
**Manual Cache Clear** (safe operations):
|
||||
```bash
|
||||
# Delete ALL caches (forces full regeneration)
|
||||
rm -rf /path/to/sd/.crosspoint/
|
||||
|
||||
# Delete specific book cache
|
||||
rm -rf /path/to/sd/.crosspoint/epub_<hash>/
|
||||
|
||||
# Keep progress, delete only rendered sections
|
||||
rm -rf /path/to/sd/.crosspoint/epub_<hash>/sections/
|
||||
```
|
||||
|
||||
**When to Clear Cache**:
|
||||
- EPUB parsing errors after code changes to `lib/Epub/`
|
||||
- Corrupt rendering (missing text, wrong layout)
|
||||
- Testing cache generation logic
|
||||
- After modifying:
|
||||
- `lib/Epub/Epub/Section.cpp`
|
||||
- `lib/Epub/Epub/BookMetadataCache.cpp`
|
||||
- Render settings in `CrossPointSettings`
|
||||
|
||||
### Cache File Format Versioning
|
||||
|
||||
**Source**: `lib/Epub/Epub/Section.cpp`, `lib/Epub/Epub/BookMetadataCache.cpp`
|
||||
|
||||
**Current Versions** (as of docs/file-formats.md):
|
||||
- `book.bin`: **Version 5** (metadata structure)
|
||||
- `section.bin`: **Version 12** (layout structure)
|
||||
|
||||
**Version Increment Rules**:
|
||||
1. **ALWAYS increment version** BEFORE changing binary structure
|
||||
2. Version mismatch → Cache auto-invalidated and regenerated
|
||||
3. Document format changes in `docs/file-formats.md`
|
||||
|
||||
**Example** (incrementing section format version):
|
||||
```cpp
|
||||
// lib/Epub/Epub/Section.cpp
|
||||
static constexpr uint8_t SECTION_FILE_VERSION = 13; // Was 12, now 13
|
||||
|
||||
// Add new field to structure
|
||||
struct PageLine {
|
||||
// ... existing fields ...
|
||||
uint16_t newField; // New field added
|
||||
};
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
Philosophy: We are building a dedicated e-reader, not a Swiss Army knife. If a feature adds RAM pressure without significantly improving the reading experience, it is Out of Scope.
|
||||
+3
-1
@@ -13,6 +13,8 @@ This guide explains the multi-language support system in CrossPoint Reader.
|
||||
- Czech
|
||||
- Russian
|
||||
- Ukrainian
|
||||
- Polish
|
||||
- Danish
|
||||
|
||||
---
|
||||
|
||||
@@ -68,7 +70,7 @@ STR_BROWSE_FILES: "Buscar archivos"
|
||||
**Rules:**
|
||||
- Use UTF-8 encoding
|
||||
- Every line must follow the format: `KEY: "value"`
|
||||
- Keys must be valid C++ identifiers (uppercase, strats with STR_)
|
||||
- Keys must be valid C++ identifiers (uppercase, starts with STR_)
|
||||
- Keys must be unique within a file
|
||||
- String values must be quoted
|
||||
- Use `\n` for newlines, `\\` for literal backslashes, `\"` for literal quotes inside values
|
||||
|
||||
@@ -50,3 +50,6 @@ If you'd like to add your name to this list, please open a PR adding yourself an
|
||||
|
||||
## Belarusian
|
||||
- [Dexif](https://github.com/dexif)
|
||||
|
||||
## Danish
|
||||
- [hajisan](https://github.com/hajisan)
|
||||
|
||||
@@ -858,3 +858,30 @@ float Epub::calculateProgress(const int currentSpineIndex, const float currentSp
|
||||
const float totalProgress = static_cast<float>(prevChapterSize) + sectionProgSize;
|
||||
return totalProgress / static_cast<float>(bookSize);
|
||||
}
|
||||
|
||||
int Epub::resolveHrefToSpineIndex(const std::string& href) const {
|
||||
if (!bookMetadataCache || !bookMetadataCache->isLoaded()) return -1;
|
||||
|
||||
// Extract filename (remove #anchor)
|
||||
std::string target = href;
|
||||
size_t hashPos = target.find('#');
|
||||
if (hashPos != std::string::npos) target = target.substr(0, hashPos);
|
||||
|
||||
// Same-file reference (anchor-only)
|
||||
if (target.empty()) return -1;
|
||||
|
||||
// Extract just the filename for comparison
|
||||
size_t targetSlash = target.find_last_of('/');
|
||||
std::string targetFilename = (targetSlash != std::string::npos) ? target.substr(targetSlash + 1) : target;
|
||||
|
||||
for (int i = 0; i < getSpineItemsCount(); i++) {
|
||||
const auto& spineHref = getSpineItem(i).href;
|
||||
// Try exact match first
|
||||
if (spineHref == target) return i;
|
||||
// Then filename-only match
|
||||
size_t spineSlash = spineHref.find_last_of('/');
|
||||
std::string spineFilename = (spineSlash != std::string::npos) ? spineHref.substr(spineSlash + 1) : spineHref;
|
||||
if (spineFilename == targetFilename) return i;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
@@ -72,4 +72,5 @@ class Epub {
|
||||
size_t getBookSize() const;
|
||||
float calculateProgress(int currentSpineIndex, float currentSpineRead) const;
|
||||
CssParser* getCssParser() const { return cssParser.get(); }
|
||||
int resolveHrefToSpineIndex(const std::string& href) const;
|
||||
};
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstring>
|
||||
|
||||
struct FootnoteEntry {
|
||||
char number[24];
|
||||
char href[64];
|
||||
|
||||
FootnoteEntry() {
|
||||
number[0] = '\0';
|
||||
href[0] = '\0';
|
||||
}
|
||||
};
|
||||
@@ -67,6 +67,18 @@ bool Page::serialize(FsFile& file) const {
|
||||
}
|
||||
}
|
||||
|
||||
// Serialize footnotes (clamp to MAX_FOOTNOTES_PER_PAGE to match addFootnote/deserialize limits)
|
||||
const uint16_t fnCount = std::min<uint16_t>(footnotes.size(), MAX_FOOTNOTES_PER_PAGE);
|
||||
serialization::writePod(file, fnCount);
|
||||
for (uint16_t i = 0; i < fnCount; i++) {
|
||||
const auto& fn = footnotes[i];
|
||||
if (file.write(fn.number, sizeof(fn.number)) != sizeof(fn.number) ||
|
||||
file.write(fn.href, sizeof(fn.href)) != sizeof(fn.href)) {
|
||||
LOG_ERR("PGE", "Failed to write footnote");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -92,5 +104,24 @@ std::unique_ptr<Page> Page::deserialize(FsFile& file) {
|
||||
}
|
||||
}
|
||||
|
||||
// Deserialize footnotes
|
||||
uint16_t fnCount;
|
||||
serialization::readPod(file, fnCount);
|
||||
if (fnCount > MAX_FOOTNOTES_PER_PAGE) {
|
||||
LOG_ERR("PGE", "Invalid footnote count %u", fnCount);
|
||||
return nullptr;
|
||||
}
|
||||
page->footnotes.resize(fnCount);
|
||||
for (uint16_t i = 0; i < fnCount; i++) {
|
||||
auto& entry = page->footnotes[i];
|
||||
if (file.read(entry.number, sizeof(entry.number)) != sizeof(entry.number) ||
|
||||
file.read(entry.href, sizeof(entry.href)) != sizeof(entry.href)) {
|
||||
LOG_ERR("PGE", "Failed to read footnote %u", i);
|
||||
return nullptr;
|
||||
}
|
||||
entry.number[sizeof(entry.number) - 1] = '\0';
|
||||
entry.href[sizeof(entry.href) - 1] = '\0';
|
||||
}
|
||||
|
||||
return page;
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
#include "FootnoteEntry.h"
|
||||
#include "blocks/ImageBlock.h"
|
||||
#include "blocks/TextBlock.h"
|
||||
|
||||
@@ -57,6 +58,19 @@ class Page {
|
||||
public:
|
||||
// the list of block index and line numbers on this page
|
||||
std::vector<std::shared_ptr<PageElement>> elements;
|
||||
std::vector<FootnoteEntry> footnotes;
|
||||
static constexpr uint16_t MAX_FOOTNOTES_PER_PAGE = 16;
|
||||
|
||||
void addFootnote(const char* number, const char* href) {
|
||||
if (footnotes.size() >= MAX_FOOTNOTES_PER_PAGE) return; // Cap per-page footnotes
|
||||
FootnoteEntry entry;
|
||||
strncpy(entry.number, number, sizeof(entry.number) - 1);
|
||||
entry.number[sizeof(entry.number) - 1] = '\0';
|
||||
strncpy(entry.href, href, sizeof(entry.href) - 1);
|
||||
entry.href[sizeof(entry.href) - 1] = '\0';
|
||||
footnotes.push_back(entry);
|
||||
}
|
||||
|
||||
void render(GfxRenderer& renderer, int fontId, int xOffset, int yOffset) const;
|
||||
bool serialize(FsFile& file) const;
|
||||
static std::unique_ptr<Page> deserialize(FsFile& file);
|
||||
|
||||
@@ -29,6 +29,7 @@ class TextBlock final : public Block {
|
||||
const BlockStyle& getBlockStyle() const { return blockStyle; }
|
||||
const std::vector<std::string>& getWords() const { return words; }
|
||||
bool isEmpty() override { return words.empty(); }
|
||||
size_t wordCount() const { return words.size(); }
|
||||
// given a renderer works out where to break the words into lines
|
||||
void render(const GfxRenderer& renderer, int fontId, int x, int y) const;
|
||||
BlockType getType() override { return TEXT_BLOCK; }
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// from
|
||||
// based on
|
||||
// https://github.com/atomic14/diy-esp32-epub-reader/blob/2c2f57fdd7e2a788d14a0bcb26b9e845a47aac42/lib/Epub/RubbishHtmlParser/htmlEntities.cpp
|
||||
|
||||
#include "htmlEntities.h"
|
||||
@@ -10,67 +10,105 @@ struct EntityPair {
|
||||
const char* value;
|
||||
};
|
||||
|
||||
static const EntityPair ENTITY_LOOKUP[] = {
|
||||
{""", "\""}, {"⁄", "⁄"}, {"&", "&"}, {"<", "<"}, {">", ">"},
|
||||
{"À", "À"}, {"Á", "Á"}, {"Â", "Â"}, {"Ã", "Ã"}, {"Ä", "Ä"},
|
||||
{"Å", "Å"}, {"Æ", "Æ"}, {"Ç", "Ç"}, {"È", "È"}, {"É", "É"},
|
||||
{"Ê", "Ê"}, {"Ë", "Ë"}, {"Ì", "Ì"}, {"Í", "Í"}, {"Î", "Î"},
|
||||
{"Ï", "Ï"}, {"Ð", "Ð"}, {"Ñ", "Ñ"}, {"Ò", "Ò"}, {"Ó", "Ó"},
|
||||
{"Ô", "Ô"}, {"Õ", "Õ"}, {"Ö", "Ö"}, {"Ø", "Ø"}, {"Ù", "Ù"},
|
||||
{"Ú", "Ú"}, {"Û", "Û"}, {"Ü", "Ü"}, {"Ý", "Ý"}, {"Þ", "Þ"},
|
||||
{"ß", "ß"}, {"à", "à"}, {"á", "á"}, {"â", "â"}, {"ã", "ã"},
|
||||
{"ä", "ä"}, {"å", "å"}, {"æ", "æ"}, {"ç", "ç"}, {"è", "è"},
|
||||
{"é", "é"}, {"ê", "ê"}, {"ë", "ë"}, {"ì", "ì"}, {"í", "í"},
|
||||
{"î", "î"}, {"ï", "ï"}, {"ð", "ð"}, {"ñ", "ñ"}, {"ò", "ò"},
|
||||
{"ó", "ó"}, {"ô", "ô"}, {"õ", "õ"}, {"ö", "ö"}, {"ø", "ø"},
|
||||
{"ù", "ù"}, {"ú", "ú"}, {"û", "û"}, {"ü", "ü"}, {"ý", "ý"},
|
||||
{"þ", "þ"}, {"ÿ", "ÿ"}, {" ", "\xC2\xA0"}, {"¡", "¡"}, {"¢", "¢"},
|
||||
{"£", "£"}, {"¤", "¤"}, {"¥", "¥"}, {"¦", "¦"}, {"§", "§"},
|
||||
{"¨", "¨"}, {"©", "©"}, {"ª", "ª"}, {"«", "«"}, {"¬", "¬"},
|
||||
{"­", ""}, {"®", "®"}, {"¯", "¯"}, {"°", "°"}, {"±", "±"},
|
||||
{"²", "²"}, {"³", "³"}, {"´", "´"}, {"µ", "µ"}, {"¶", "¶"},
|
||||
{"¸", "¸"}, {"¹", "¹"}, {"º", "º"}, {"»", "»"}, {"¼", "¼"},
|
||||
{"½", "½"}, {"¾", "¾"}, {"¿", "¿"}, {"×", "×"}, {"÷", "÷"},
|
||||
{"∀", "∀"}, {"∂", "∂"}, {"∃", "∃"}, {"∅", "∅"}, {"∇", "∇"},
|
||||
{"∈", "∈"}, {"∉", "∉"}, {"∋", "∋"}, {"∏", "∏"}, {"∑", "∑"},
|
||||
{"−", "−"}, {"∗", "∗"}, {"√", "√"}, {"∝", "∝"}, {"∞", "∞"},
|
||||
{"∠", "∠"}, {"∧", "∧"}, {"∨", "∨"}, {"∩", "∩"}, {"∪", "∪"},
|
||||
{"∫", "∫"}, {"∴", "∴"}, {"∼", "∼"}, {"≅", "≅"}, {"≈", "≈"},
|
||||
{"≠", "≠"}, {"≡", "≡"}, {"≤", "≤"}, {"≥", "≥"}, {"⊂", "⊂"},
|
||||
{"⊃", "⊃"}, {"⊄", "⊄"}, {"⊆", "⊆"}, {"⊇", "⊇"}, {"⊕", "⊕"},
|
||||
{"⊗", "⊗"}, {"⊥", "⊥"}, {"⋅", "⋅"}, {"Α", "Α"}, {"Β", "Β"},
|
||||
{"Γ", "Γ"}, {"Δ", "Δ"}, {"Ε", "Ε"}, {"Ζ", "Ζ"}, {"Η", "Η"},
|
||||
{"Θ", "Θ"}, {"Ι", "Ι"}, {"Κ", "Κ"}, {"Λ", "Λ"}, {"Μ", "Μ"},
|
||||
{"Ν", "Ν"}, {"Ξ", "Ξ"}, {"Ο", "Ο"}, {"Π", "Π"}, {"Ρ", "Ρ"},
|
||||
{"Σ", "Σ"}, {"Τ", "Τ"}, {"Υ", "Υ"}, {"Φ", "Φ"}, {"Χ", "Χ"},
|
||||
{"Ψ", "Ψ"}, {"Ω", "Ω"}, {"α", "α"}, {"β", "β"}, {"γ", "γ"},
|
||||
{"δ", "δ"}, {"ε", "ε"}, {"ζ", "ζ"}, {"η", "η"}, {"θ", "θ"},
|
||||
{"ι", "ι"}, {"κ", "κ"}, {"λ", "λ"}, {"μ", "μ"}, {"ν", "ν"},
|
||||
{"ξ", "ξ"}, {"ο", "ο"}, {"π", "π"}, {"ρ", "ρ"}, {"ς", "ς"},
|
||||
{"σ", "σ"}, {"τ", "τ"}, {"υ", "υ"}, {"φ", "φ"}, {"χ", "χ"},
|
||||
{"ψ", "ψ"}, {"ω", "ω"}, {"ϑ", "ϑ"}, {"ϒ", "ϒ"}, {"ϖ", "ϖ"},
|
||||
{"Œ", "Œ"}, {"œ", "œ"}, {"Š", "Š"}, {"š", "š"}, {"Ÿ", "Ÿ"},
|
||||
{"ƒ", "ƒ"}, {"ˆ", "ˆ"}, {"˜", "˜"}, {" ", " "}, {" ", " "},
|
||||
{" ", " "}, {"‌", ""}, {"‍", ""}, {"‎", ""}, {"‏", ""},
|
||||
{"–", "–"}, {"—", "—"}, {"‘", "‘"}, {"’", "’"}, {"‚", "‚"},
|
||||
{"“", "“"}, {"”", "”"}, {"„", "„"}, {"†", "†"}, {"‡", "‡"},
|
||||
{"•", "•"}, {"…", "…"}, {"‰", "‰"}, {"′", "′"}, {"″", "″"},
|
||||
{"‹", "‹"}, {"›", "›"}, {"‾", "‾"}, {"€", "€"}, {"™", "™"},
|
||||
{"←", "←"}, {"↑", "↑"}, {"→", "→"}, {"↓", "↓"}, {"↔", "↔"},
|
||||
{"↵", "↵"}, {"⌈", "⌈"}, {"⌉", "⌉"}, {"⌊", "⌊"}, {"⌋", "⌋"},
|
||||
{"◊", "◊"}, {"♠", "♠"}, {"♣", "♣"}, {"♥", "♥"}, {"♦", "♦"}};
|
||||
// Sorted lexicographically by key to allow binary search.
|
||||
static constexpr EntityPair ENTITY_LOOKUP[] = {
|
||||
{"Æ", "Æ"}, {"Á", "Á"}, {"Â", "Â"}, {"À", "À"}, {"Α", "Α"},
|
||||
{"Å", "Å"}, {"Ã", "Ã"}, {"Ä", "Ä"}, {"Β", "Β"}, {"Ç", "Ç"},
|
||||
{"Χ", "Χ"}, {"‡", "‡"}, {"Δ", "Δ"}, {"Ð", "Ð"}, {"É", "É"},
|
||||
{"Ê", "Ê"}, {"È", "È"}, {"Ε", "Ε"}, {"Η", "Η"}, {"Ë", "Ë"},
|
||||
{"Γ", "Γ"}, {"Í", "Í"}, {"Î", "Î"}, {"Ì", "Ì"}, {"Ι", "Ι"},
|
||||
{"Ï", "Ï"}, {"Κ", "Κ"}, {"Λ", "Λ"}, {"Μ", "Μ"}, {"Ñ", "Ñ"},
|
||||
{"Ν", "Ν"}, {"Œ", "Œ"}, {"Ó", "Ó"}, {"Ô", "Ô"}, {"Ò", "Ò"},
|
||||
{"Ω", "Ω"}, {"Ο", "Ο"}, {"Ø", "Ø"}, {"Õ", "Õ"}, {"Ö", "Ö"},
|
||||
{"Φ", "Φ"}, {"Π", "Π"}, {"″", "″"}, {"Ψ", "Ψ"}, {"Ρ", "Ρ"},
|
||||
{"Š", "Š"}, {"Σ", "Σ"}, {"Þ", "Þ"}, {"Τ", "Τ"}, {"Θ", "Θ"},
|
||||
{"Ú", "Ú"}, {"Û", "Û"}, {"Ù", "Ù"}, {"Υ", "Υ"}, {"Ü", "Ü"},
|
||||
{"Ξ", "Ξ"}, {"Ý", "Ý"}, {"Ÿ", "Ÿ"}, {"Ζ", "Ζ"}, {"á", "á"},
|
||||
{"â", "â"}, {"´", "´"}, {"æ", "æ"}, {"à", "à"}, {"α", "α"},
|
||||
{"&", "&"}, {"∧", "∧"}, {"∠", "∠"}, {"å", "å"}, {"≈", "≈"},
|
||||
{"ã", "ã"}, {"ä", "ä"}, {"„", "„"}, {"β", "β"}, {"¦", "¦"},
|
||||
{"•", "•"}, {"∩", "∩"}, {"ç", "ç"}, {"¸", "¸"}, {"¢", "¢"},
|
||||
{"χ", "χ"}, {"ˆ", "ˆ"}, {"♣", "♣"}, {"≅", "≅"}, {"©", "©"},
|
||||
{"↵", "↵"}, {"∪", "∪"}, {"¤", "¤"}, {"†", "†"}, {"↓", "↓"},
|
||||
{"°", "°"}, {"δ", "δ"}, {"♦", "♦"}, {"÷", "÷"}, {"é", "é"},
|
||||
{"ê", "ê"}, {"è", "è"}, {"∅", "∅"}, {" ", " "}, {" ", " "},
|
||||
{"ε", "ε"}, {"≡", "≡"}, {"η", "η"}, {"ð", "ð"}, {"ë", "ë"},
|
||||
{"€", "€"}, {"∃", "∃"}, {"ƒ", "ƒ"}, {"∀", "∀"}, {"½", "½"},
|
||||
{"¼", "¼"}, {"¾", "¾"}, {"⁄", "⁄"}, {"γ", "γ"}, {"≥", "≥"},
|
||||
{">", ">"}, {"↔", "↔"}, {"♥", "♥"}, {"…", "…"}, {"í", "í"},
|
||||
{"î", "î"}, {"¡", "¡"}, {"ì", "ì"}, {"∞", "∞"}, {"∫", "∫"},
|
||||
{"ι", "ι"}, {"¿", "¿"}, {"∈", "∈"}, {"ï", "ï"}, {"κ", "κ"},
|
||||
{"λ", "λ"}, {"«", "«"}, {"←", "←"}, {"⌈", "⌈"}, {"“", "\u201C"},
|
||||
{"≤", "≤"}, {"⌊", "⌊"}, {"∗", "∗"}, {"◊", "◊"}, {"‎", "\u200E"},
|
||||
{"‹", "‹"}, {"‘", "\u2018"}, {"<", "<"}, {"¯", "¯"}, {"—", "—"},
|
||||
{"µ", "µ"}, {"−", "−"}, {"μ", "μ"}, {"∇", "∇"}, {" ", "\xC2\xA0"},
|
||||
{"–", "–"}, {"≠", "≠"}, {"∋", "∋"}, {"¬", "¬"}, {"∉", "∉"},
|
||||
{"⊄", "⊄"}, {"ñ", "ñ"}, {"ν", "ν"}, {"ó", "ó"}, {"ô", "ô"},
|
||||
{"œ", "œ"}, {"ò", "ò"}, {"‾", "‾"}, {"ω", "ω"}, {"ο", "ο"},
|
||||
{"⊕", "⊕"}, {"∨", "∨"}, {"ª", "ª"}, {"º", "º"}, {"ø", "ø"},
|
||||
{"õ", "õ"}, {"⊗", "⊗"}, {"ö", "ö"}, {"¶", "¶"}, {"∂", "∂"},
|
||||
{"‰", "‰"}, {"⊥", "⊥"}, {"φ", "φ"}, {"π", "π"}, {"ϖ", "ϖ"},
|
||||
{"±", "±"}, {"£", "£"}, {"′", "′"}, {"∏", "∏"}, {"∝", "∝"},
|
||||
{"ψ", "ψ"}, {""", "\""}, {"√", "√"}, {"»", "»"}, {"→", "→"},
|
||||
{"⌉", "⌉"}, {"”", "\u201D"}, {"®", "®"}, {"⌋", "⌋"}, {"ρ", "ρ"},
|
||||
{"‏", "\u200F"}, {"›", "›"}, {"’", "\u2019"}, {"‚", "‚"}, {"š", "š"},
|
||||
{"⋅", "⋅"}, {"§", "§"}, {"­", "\xC2\xAD"}, {"σ", "σ"}, {"ς", "ς"},
|
||||
{"∼", "∼"}, {"♠", "♠"}, {"⊂", "⊂"}, {"⊆", "⊆"}, {"∑", "∑"},
|
||||
{"¹", "¹"}, {"²", "²"}, {"³", "³"}, {"⊃", "⊃"}, {"⊇", "⊇"},
|
||||
{"ß", "ß"}, {"τ", "τ"}, {"∴", "∴"}, {"θ", "θ"}, {"ϑ", "ϑ"},
|
||||
{" ", " "}, {"þ", "þ"}, {"˜", "˜"}, {"×", "×"}, {"™", "™"},
|
||||
{"ú", "ú"}, {"↑", "↑"}, {"û", "û"}, {"ù", "ù"}, {"¨", "¨"},
|
||||
{"ϒ", "ϒ"}, {"υ", "υ"}, {"ü", "ü"}, {"ξ", "ξ"}, {"ý", "ý"},
|
||||
{"¥", "¥"}, {"ÿ", "ÿ"}, {"ζ", "ζ"}, {"‍", "\u200D"}, {"‌", "\u200C"},
|
||||
};
|
||||
|
||||
static const size_t ENTITY_LOOKUP_COUNT = sizeof(ENTITY_LOOKUP) / sizeof(ENTITY_LOOKUP[0]);
|
||||
|
||||
// Lookup a single HTML entity and return its UTF-8 value
|
||||
const char* lookupHtmlEntity(const char* entity, int len) {
|
||||
for (size_t i = 0; i < ENTITY_LOOKUP_COUNT; i++) {
|
||||
const char* key = ENTITY_LOOKUP[i].key;
|
||||
// Verify the table is sorted at compile time.
|
||||
static constexpr int constexprStrcmp(const char* a, const char* b) {
|
||||
for (size_t i = 0;; i++) {
|
||||
if (a[i] != b[i]) return (unsigned char)a[i] < (unsigned char)b[i] ? -1 : 1;
|
||||
if (a[i] == '\0') return 0;
|
||||
}
|
||||
}
|
||||
|
||||
static constexpr bool isTableSorted() {
|
||||
for (size_t i = 1; i < ENTITY_LOOKUP_COUNT; i++) {
|
||||
if (constexprStrcmp(ENTITY_LOOKUP[i - 1].key, ENTITY_LOOKUP[i].key) >= 0) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
static_assert(isTableSorted(), "ENTITY_LOOKUP must be sorted lexicographically by key");
|
||||
|
||||
// Lookup a single HTML entity and return its UTF-8 value.
|
||||
const char* lookupHtmlEntity(const char* entity, size_t len) {
|
||||
if (entity == nullptr || len == 0) return nullptr;
|
||||
|
||||
size_t lo = 0;
|
||||
size_t hi = ENTITY_LOOKUP_COUNT;
|
||||
|
||||
while (lo < hi) {
|
||||
const size_t mid = lo + (hi - lo) / 2;
|
||||
const char* key = ENTITY_LOOKUP[mid].key;
|
||||
const size_t keyLen = strlen(key);
|
||||
if (static_cast<size_t>(len) == keyLen && memcmp(entity, key, keyLen) == 0) {
|
||||
return ENTITY_LOOKUP[i].value;
|
||||
const size_t cmpLen = (len < keyLen) ? len : keyLen;
|
||||
int cmp = memcmp(entity, key, cmpLen);
|
||||
if (cmp == 0) {
|
||||
// safety net: if prefix equal, shorter string is considered smaller
|
||||
if (len < keyLen)
|
||||
cmp = -1;
|
||||
else if (len > keyLen)
|
||||
cmp = 1;
|
||||
else
|
||||
cmp = 0;
|
||||
}
|
||||
|
||||
if (cmp == 0) return ENTITY_LOOKUP[mid].value;
|
||||
if (cmp < 0)
|
||||
hi = mid;
|
||||
else
|
||||
lo = mid + 1;
|
||||
}
|
||||
|
||||
return nullptr; // Entity not found
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// from
|
||||
// based on
|
||||
// https://github.com/atomic14/diy-esp32-epub-reader/blob/2c2f57fdd7e2a788d14a0bcb26b9e845a47aac42/lib/Epub/RubbishHtmlParser/htmlEntities.cpp
|
||||
|
||||
#pragma once
|
||||
@@ -6,4 +6,4 @@
|
||||
|
||||
// Lookup a single HTML entity (including & and ;) and return its UTF-8 value
|
||||
// Returns nullptr if entity is not found
|
||||
const char* lookupHtmlEntity(const char* entity, int len);
|
||||
const char* lookupHtmlEntity(const char* entity, size_t len);
|
||||
|
||||
@@ -49,6 +49,24 @@ bool matches(const char* tag_name, const char* possible_tags[], const int possib
|
||||
return false;
|
||||
}
|
||||
|
||||
const char* getAttribute(const XML_Char** atts, const char* attrName) {
|
||||
if (!atts) return nullptr;
|
||||
for (int i = 0; atts[i]; i += 2) {
|
||||
if (strcmp(atts[i], attrName) == 0) return atts[i + 1];
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
bool isInternalEpubLink(const char* href) {
|
||||
if (!href || href[0] == '\0') return false;
|
||||
if (strncmp(href, "http://", 7) == 0 || strncmp(href, "https://", 8) == 0) return false;
|
||||
if (strncmp(href, "mailto:", 7) == 0) return false;
|
||||
if (strncmp(href, "ftp://", 6) == 0) return false;
|
||||
if (strncmp(href, "tel:", 4) == 0) return false;
|
||||
if (strncmp(href, "javascript:", 11) == 0) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool isHeaderOrBlock(const char* name) {
|
||||
return matches(name, HEADER_TAGS, NUM_HEADER_TAGS) || matches(name, BLOCK_TAGS, NUM_BLOCK_TAGS);
|
||||
}
|
||||
@@ -121,6 +139,7 @@ void ChapterHtmlSlimParser::startNewTextBlock(const BlockStyle& blockStyle) {
|
||||
makePages();
|
||||
}
|
||||
currentTextBlock.reset(new ParsedText(extraParagraphSpacing, hyphenationEnabled, blockStyle));
|
||||
wordsExtractedInBlock = 0;
|
||||
}
|
||||
|
||||
void XMLCALL ChapterHtmlSlimParser::startElement(void* userData, const XML_Char* name, const XML_Char** atts) {
|
||||
@@ -430,6 +449,50 @@ void XMLCALL ChapterHtmlSlimParser::startElement(void* userData, const XML_Char*
|
||||
}
|
||||
}
|
||||
|
||||
// Detect internal <a href="..."> links (footnotes, cross-references)
|
||||
// Note: <aside epub:type="footnote"> elements are rendered as normal content
|
||||
// without special handling. Links pointing to them are collected as footnotes.
|
||||
if (strcmp(name, "a") == 0) {
|
||||
const char* href = getAttribute(atts, "href");
|
||||
|
||||
bool isInternalLink = isInternalEpubLink(href);
|
||||
|
||||
// Special case: javascript:void(0) links with data attributes
|
||||
// Example: <a href="javascript:void(0)"
|
||||
// data-xyz="{"name":"OPS/ch2.xhtml","frag":"id46"}">
|
||||
if (href && strncmp(href, "javascript:", 11) == 0) {
|
||||
isInternalLink = false;
|
||||
// TODO: Parse data-* attributes to extract actual href
|
||||
}
|
||||
|
||||
if (isInternalLink) {
|
||||
// Flush buffer before style change
|
||||
if (self->partWordBufferIndex > 0) {
|
||||
self->flushPartWordBuffer();
|
||||
self->nextWordContinues = true;
|
||||
}
|
||||
self->insideFootnoteLink = true;
|
||||
self->footnoteLinkDepth = self->depth;
|
||||
strncpy(self->currentFootnoteLinkHref, href, sizeof(self->currentFootnoteLinkHref) - 1);
|
||||
self->currentFootnoteLinkHref[sizeof(self->currentFootnoteLinkHref) - 1] = '\0';
|
||||
self->currentFootnoteLinkText[0] = '\0';
|
||||
self->currentFootnoteLinkTextLen = 0;
|
||||
|
||||
// Apply underline style to visually indicate the link
|
||||
self->underlineUntilDepth = std::min(self->underlineUntilDepth, self->depth);
|
||||
StyleStackEntry entry;
|
||||
entry.depth = self->depth;
|
||||
entry.hasUnderline = true;
|
||||
entry.underline = true;
|
||||
self->inlineStyleStack.push_back(entry);
|
||||
self->updateEffectiveInlineStyle();
|
||||
|
||||
// Skip CSS resolution — we already handled styling for this <a> tag
|
||||
self->depth += 1;
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Compute CSS style for this element
|
||||
CssStyle cssStyle;
|
||||
if (self->cssParser) {
|
||||
@@ -582,6 +645,19 @@ void XMLCALL ChapterHtmlSlimParser::characterData(void* userData, const XML_Char
|
||||
return;
|
||||
}
|
||||
|
||||
// Collect footnote link display text (for the number label)
|
||||
// Skip whitespace and brackets to normalize noterefs like "[1]" → "1"
|
||||
if (self->insideFootnoteLink) {
|
||||
for (int i = 0; i < len; i++) {
|
||||
unsigned char c = static_cast<unsigned char>(s[i]);
|
||||
if (isWhitespace(c) || c == '[' || c == ']') continue;
|
||||
if (self->currentFootnoteLinkTextLen < static_cast<int>(sizeof(self->currentFootnoteLinkText)) - 1) {
|
||||
self->currentFootnoteLinkText[self->currentFootnoteLinkTextLen++] = c;
|
||||
self->currentFootnoteLinkText[self->currentFootnoteLinkTextLen] = '\0';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (int i = 0; i < len; i++) {
|
||||
if (isWhitespace(s[i])) {
|
||||
// Currently looking at whitespace, if there's anything in the partWordBuffer, flush it
|
||||
@@ -685,7 +761,7 @@ void XMLCALL ChapterHtmlSlimParser::characterData(void* userData, const XML_Char
|
||||
void XMLCALL ChapterHtmlSlimParser::defaultHandlerExpand(void* userData, const XML_Char* s, const int len) {
|
||||
// Check if this looks like an entity reference (&...;)
|
||||
if (len >= 3 && s[0] == '&' && s[len - 1] == ';') {
|
||||
const char* utf8Value = lookupHtmlEntity(s, len);
|
||||
const char* utf8Value = lookupHtmlEntity(s, static_cast<size_t>(len));
|
||||
if (utf8Value != nullptr) {
|
||||
// Known entity: expand to its UTF-8 value
|
||||
characterData(userData, utf8Value, strlen(utf8Value));
|
||||
@@ -743,6 +819,21 @@ void XMLCALL ChapterHtmlSlimParser::endElement(void* userData, const XML_Char* n
|
||||
|
||||
self->depth -= 1;
|
||||
|
||||
// Closing a footnote link — create entry from collected text and href
|
||||
if (self->insideFootnoteLink && self->depth == self->footnoteLinkDepth) {
|
||||
if (self->currentFootnoteLinkText[0] != '\0' && self->currentFootnoteLinkHref[0] != '\0') {
|
||||
FootnoteEntry entry;
|
||||
strncpy(entry.number, self->currentFootnoteLinkText, sizeof(entry.number) - 1);
|
||||
entry.number[sizeof(entry.number) - 1] = '\0';
|
||||
strncpy(entry.href, self->currentFootnoteLinkHref, sizeof(entry.href) - 1);
|
||||
entry.href[sizeof(entry.href) - 1] = '\0';
|
||||
int wordIndex =
|
||||
self->wordsExtractedInBlock + (self->currentTextBlock ? static_cast<int>(self->currentTextBlock->size()) : 0);
|
||||
self->pendingFootnotes.push_back({wordIndex, entry});
|
||||
}
|
||||
self->insideFootnoteLink = false;
|
||||
}
|
||||
|
||||
// Leaving skip
|
||||
if (self->skipUntilDepth == self->depth) {
|
||||
self->skipUntilDepth = INT_MAX;
|
||||
@@ -910,6 +1001,15 @@ void ChapterHtmlSlimParser::addLineToPage(std::shared_ptr<TextBlock> line) {
|
||||
currentPageNextY = 0;
|
||||
}
|
||||
|
||||
// Track cumulative words to assign footnotes to the page containing their anchor
|
||||
wordsExtractedInBlock += line->wordCount();
|
||||
auto footnoteIt = pendingFootnotes.begin();
|
||||
while (footnoteIt != pendingFootnotes.end() && footnoteIt->first <= wordsExtractedInBlock) {
|
||||
currentPage->addFootnote(footnoteIt->second.number, footnoteIt->second.href);
|
||||
++footnoteIt;
|
||||
}
|
||||
pendingFootnotes.erase(pendingFootnotes.begin(), footnoteIt);
|
||||
|
||||
// Apply horizontal left inset (margin + padding) as x position offset
|
||||
const int16_t xOffset = line->getBlockStyle().leftInset();
|
||||
currentPage->elements.push_back(std::make_shared<PageLine>(line, xOffset, currentPageNextY));
|
||||
@@ -947,6 +1047,16 @@ void ChapterHtmlSlimParser::makePages() {
|
||||
renderer, fontId, effectiveWidth,
|
||||
[this](const std::shared_ptr<TextBlock>& textBlock) { addLineToPage(textBlock); });
|
||||
|
||||
// Fallback: transfer any remaining pending footnotes to current page.
|
||||
// Normally addLineToPage handles this via word-index tracking, but this catches
|
||||
// edge cases where a footnote's word index equals the exact block size.
|
||||
if (!pendingFootnotes.empty() && currentPage) {
|
||||
for (const auto& [idx, fn] : pendingFootnotes) {
|
||||
currentPage->addFootnote(fn.number, fn.href);
|
||||
}
|
||||
pendingFootnotes.clear();
|
||||
}
|
||||
|
||||
// Apply bottom spacing after the paragraph (stored in pixels)
|
||||
if (blockStyle.marginBottom > 0) {
|
||||
currentPageNextY += blockStyle.marginBottom;
|
||||
|
||||
@@ -5,7 +5,9 @@
|
||||
#include <climits>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <vector>
|
||||
|
||||
#include "../FootnoteEntry.h"
|
||||
#include "../ParsedText.h"
|
||||
#include "../blocks/ImageBlock.h"
|
||||
#include "../blocks/TextBlock.h"
|
||||
@@ -66,6 +68,15 @@ class ChapterHtmlSlimParser {
|
||||
int tableRowIndex = 0;
|
||||
int tableColIndex = 0;
|
||||
|
||||
// Footnote link tracking
|
||||
bool insideFootnoteLink = false;
|
||||
int footnoteLinkDepth = -1;
|
||||
char currentFootnoteLinkText[24] = {};
|
||||
int currentFootnoteLinkTextLen = 0;
|
||||
char currentFootnoteLinkHref[64] = {};
|
||||
std::vector<std::pair<int, FootnoteEntry>> pendingFootnotes; // <wordIndex, entry>
|
||||
int wordsExtractedInBlock = 0;
|
||||
|
||||
void updateEffectiveInlineStyle();
|
||||
void startNewTextBlock(const BlockStyle& blockStyle);
|
||||
void flushPartWordBuffer();
|
||||
|
||||
@@ -0,0 +1,320 @@
|
||||
_language_name: "Dansk"
|
||||
_language_code: "DA"
|
||||
_order: "15"
|
||||
|
||||
STR_CROSSPOINT: "CrossPoint"
|
||||
STR_BOOTING: "STARTER"
|
||||
STR_SLEEPING: "HVILE"
|
||||
STR_ENTERING_SLEEP: "Går i hvile"
|
||||
STR_BROWSE_FILES: "Gennemsøg filer"
|
||||
STR_FILE_TRANSFER: "Filoverførelse"
|
||||
STR_SETTINGS_TITLE: "Indstillinger"
|
||||
STR_CALIBRE_LIBRARY: "Calibre bibliotek"
|
||||
STR_CONTINUE_READING: "Fortsæt med at læse"
|
||||
STR_NO_OPEN_BOOK: "Ingen åben bog"
|
||||
STR_START_READING: "Start læsning nedenfor"
|
||||
STR_BOOKS: "Bøger"
|
||||
STR_NO_BOOKS_FOUND: "Ingen bøger fundet"
|
||||
STR_SELECT_CHAPTER: "Vælg kapitel"
|
||||
STR_NO_CHAPTERS: "Ingen kapitler"
|
||||
STR_END_OF_BOOK: "Bogen er færdig"
|
||||
STR_EMPTY_CHAPTER: "Tomt kapitel"
|
||||
STR_INDEXING: "Indekserer"
|
||||
STR_MEMORY_ERROR: "Hukommelsesfejl"
|
||||
STR_PAGE_LOAD_ERROR: "Fejl ved sideindlæsning"
|
||||
STR_EMPTY_FILE: "Tom fil"
|
||||
STR_OUT_OF_BOUNDS: "Uden for grænsen"
|
||||
STR_LOADING: "Indlæser..."
|
||||
STR_LOADING_POPUP: "Indlæser"
|
||||
STR_LOAD_XTC_FAILED: "Mislykkedes at indlæse XTC"
|
||||
STR_LOAD_TXT_FAILED: "Mislykkedes at indlæse TXT"
|
||||
STR_LOAD_EPUB_FAILED: "Mislykkedes at indlæse EPUB"
|
||||
STR_SD_CARD_ERROR: "SD kort fejl"
|
||||
STR_WIFI_NETWORKS: "Trådløse netværk"
|
||||
STR_NO_NETWORKS: "Intet netværk fundet"
|
||||
STR_NETWORKS_FOUND: "%zu netværk fundet"
|
||||
STR_SCANNING: "Skanner..."
|
||||
STR_CONNECTING: "Forbinder..."
|
||||
STR_CONNECTED: "Forbundet!"
|
||||
STR_CONNECTION_FAILED: "Forbindelsen mislykkedes"
|
||||
STR_CONNECTION_TIMEOUT: "Forbindelses timeout"
|
||||
STR_FORGET_NETWORK: "Glem netværk?"
|
||||
STR_SAVE_PASSWORD: "Gem adgangskode til næste gang?"
|
||||
STR_REMOVE_PASSWORD: "Fjern gemt adgangskode?"
|
||||
STR_PRESS_OK_SCAN: "Tryk OK for at scanne igen"
|
||||
STR_PRESS_ANY_CONTINUE: "Tryk på en knap for at fortsætte"
|
||||
STR_SELECT_HINT: "VENSTRE/HØJRE: Vælg | OK: Bekræft"
|
||||
STR_HOW_CONNECT: "Hvordan vil du oprette forbindelse?"
|
||||
STR_JOIN_NETWORK: "Tilslut netværk"
|
||||
STR_CREATE_HOTSPOT: "Opret Hotspot"
|
||||
STR_JOIN_DESC: "Opret forbindelse til et eksisterende WiFi-netværk"
|
||||
STR_HOTSPOT_DESC: "Opret et WiFi-netværk andre kan tilslutte sig"
|
||||
STR_STARTING_HOTSPOT: "Starter Hotspot..."
|
||||
STR_HOTSPOT_MODE: "Hotspot-tilstand"
|
||||
STR_CONNECT_WIFI_HINT: "Opret forbindelse fra din enhed til dette WiFi-netværk"
|
||||
STR_OPEN_URL_HINT: "Åbn denne URL i din browser"
|
||||
STR_OR_HTTP_PREFIX: "eller http://"
|
||||
STR_SCAN_QR_HINT: "eller scan QR-kode med din telefon:"
|
||||
STR_CALIBRE_WIRELESS: "Calibre Wireless"
|
||||
STR_CALIBRE_WEB_URL: "Calibre Web URL"
|
||||
STR_CONNECT_WIRELESS: "Opret forbindelse som trådløs enhed"
|
||||
STR_NETWORK_LEGEND: "* = Krypteret | + = Gemt"
|
||||
STR_MAC_ADDRESS: "MAC-adresse:"
|
||||
STR_CHECKING_WIFI: "Tjekker WiFi..."
|
||||
STR_ENTER_WIFI_PASSWORD: "Indtast WiFi-adgangskode"
|
||||
STR_ENTER_TEXT: "Indtast tekst"
|
||||
STR_TO_PREFIX: "til "
|
||||
STR_CALIBRE_DISCOVERING: "Opdager Calibre..."
|
||||
STR_CALIBRE_CONNECTING_TO: "Forbinder til "
|
||||
STR_CALIBRE_CONNECTED_TO: "Forbundet til "
|
||||
STR_CALIBRE_WAITING_COMMANDS: "Venter på kommandoer..."
|
||||
STR_CONNECTION_FAILED_RETRYING: "(Forbindelsen mislykkedes, prøver igen)"
|
||||
STR_CALIBRE_DISCONNECTED: "Calibre afbrudt"
|
||||
STR_CALIBRE_WAITING_TRANSFER: "Venter på overførelse..."
|
||||
STR_CALIBRE_TRANSFER_HINT: "Hvis overførslen mislykkes, aktiver\\n'Ignorer ledig plads' i Calibres\\nSmartDevice-plugin-indstillinger."
|
||||
STR_CALIBRE_RECEIVING: "Modtager: "
|
||||
STR_CALIBRE_RECEIVED: "Modtaget: "
|
||||
STR_CALIBRE_WAITING_MORE: "Venter på mere..."
|
||||
STR_CALIBRE_FAILED_CREATE_FILE: "Kunne ikke oprette fil"
|
||||
STR_CALIBRE_PASSWORD_REQUIRED: "Adgangskode påkrævet"
|
||||
STR_CALIBRE_TRANSFER_INTERRUPTED: "Overførelse afbrudt"
|
||||
STR_CALIBRE_INSTRUCTION_1: "1) Installer CrossPoint Reader-plugin"
|
||||
STR_CALIBRE_INSTRUCTION_2: "2) Vær på det samme WiFi-netværk"
|
||||
STR_CALIBRE_INSTRUCTION_3: "3) I Calibre: \"Send til enhed\""
|
||||
STR_CALIBRE_INSTRUCTION_4: "\"Hold denne skærm åben under afsendelse\""
|
||||
STR_CAT_DISPLAY: "Skærm"
|
||||
STR_CAT_READER: "Læser"
|
||||
STR_CAT_CONTROLS: "Brugerflade"
|
||||
STR_CAT_SYSTEM: "System"
|
||||
STR_SLEEP_SCREEN: "Hvile-skærm"
|
||||
STR_SLEEP_COVER_MODE: "Hvile-skærm omslag-tilstand"
|
||||
STR_STATUS_BAR: "Statuslinje"
|
||||
STR_HIDE_BATTERY: "Skjul batteri %"
|
||||
STR_EXTRA_SPACING: "Ekstra afsnitsafstand"
|
||||
STR_TEXT_AA: "Tekst Anti-Aliasing"
|
||||
STR_SHORT_PWR_BTN: "Kort tryk på tænd/sluk-knap"
|
||||
STR_ORIENTATION: "Læseretning"
|
||||
STR_FRONT_BTN_LAYOUT: "Knaplayout foran"
|
||||
STR_SIDE_BTN_LAYOUT: "Knaplayout på siden (læser)"
|
||||
STR_LONG_PRESS_SKIP: "Langt tryk spring kapitel over"
|
||||
STR_FONT_FAMILY: "Læser skrifttype"
|
||||
STR_EXT_READER_FONT: "Ekstern læserskrifttype"
|
||||
STR_EXT_CHINESE_FONT: "Læserskrifttype"
|
||||
STR_EXT_UI_FONT: "Brugergrænseflade skrifttype"
|
||||
STR_FONT_SIZE: "Brugergrænseflade skriftstørrelse"
|
||||
STR_LINE_SPACING: "Linjeafstand"
|
||||
STR_ASCII_LETTER_SPACING: "ASCII bogstavafstand"
|
||||
STR_ASCII_DIGIT_SPACING: "ASCII cifreafstand"
|
||||
STR_CJK_SPACING: "CJK afstand"
|
||||
STR_COLOR_MODE: "Farvetilstand"
|
||||
STR_SCREEN_MARGIN: "Skærmmargen"
|
||||
STR_PARA_ALIGNMENT: "Afsnitsjustering"
|
||||
STR_HYPHENATION: "Orddeling"
|
||||
STR_TIME_TO_SLEEP: "Tid til hvile"
|
||||
STR_REFRESH_FREQ: "Opdateringsfrekvens"
|
||||
STR_CALIBRE_SETTINGS: "Calibre-indstillinger"
|
||||
STR_KOREADER_SYNC: "KOReader Sync"
|
||||
STR_CHECK_UPDATES: "Søg efter opdateringer"
|
||||
STR_LANGUAGE: "Sprog"
|
||||
STR_SELECT_WALLPAPER: "Vælg baggrundsbillede"
|
||||
STR_CLEAR_READING_CACHE: "Ryd læsecache"
|
||||
STR_CALIBRE: "Calibre"
|
||||
STR_USERNAME: "Brugernavn"
|
||||
STR_PASSWORD: "Adgangskode"
|
||||
STR_SYNC_SERVER_URL: "Synkroniseringsserver-URL"
|
||||
STR_DOCUMENT_MATCHING: "Dokumentsammenkobling"
|
||||
STR_AUTHENTICATE: "Godkend"
|
||||
STR_KOREADER_USERNAME: "KOReader brugernavn"
|
||||
STR_KOREADER_PASSWORD: "KOReader adgangskode"
|
||||
STR_FILENAME: "Filnavn"
|
||||
STR_BINARY: "Binær"
|
||||
STR_SET_CREDENTIALS_FIRST: "Angiv legitimationsoplysninger først"
|
||||
STR_WIFI_CONN_FAILED: "WiFi-forbindelsen mislykkedes"
|
||||
STR_AUTHENTICATING: "Godkender..."
|
||||
STR_AUTH_SUCCESS: "Godkendt!"
|
||||
STR_KOREADER_AUTH: "KOReader-godkendelse"
|
||||
STR_SYNC_READY: "KOReader-synkronisering er klar til brug"
|
||||
STR_AUTH_FAILED: "Godkendelse mislykkedes"
|
||||
STR_DONE: "Færdig"
|
||||
STR_CLEAR_CACHE_WARNING_1: "Dette vil rydde alle cachelagrede bogdata."
|
||||
STR_CLEAR_CACHE_WARNING_2: "Al læsefremskridt vil gå tabt!"
|
||||
STR_CLEAR_CACHE_WARNING_3: "Bøger skal indekseres igen"
|
||||
STR_CLEAR_CACHE_WARNING_4: "når de åbnes igen."
|
||||
STR_CLEARING_CACHE: "Rydder cache..."
|
||||
STR_CACHE_CLEARED: "Cache ryddet"
|
||||
STR_ITEMS_REMOVED: "elementer fjernet"
|
||||
STR_FAILED_LOWER: "mislykkedes"
|
||||
STR_CLEAR_CACHE_FAILED: "Kunne ikke rydde cache"
|
||||
STR_CHECK_SERIAL_OUTPUT: "Tjek serielt output for detaljer"
|
||||
STR_DARK: "Mørk"
|
||||
STR_LIGHT: "Lys"
|
||||
STR_CUSTOM: "Brugerdefineret"
|
||||
STR_COVER: "Omslag"
|
||||
STR_NONE_OPT: "Ingen"
|
||||
STR_FIT: "Tilpas"
|
||||
STR_CROP: "Beskær"
|
||||
STR_NO_PROGRESS: "Ingen fremskridt"
|
||||
STR_FULL_OPT: "Fuld"
|
||||
STR_NEVER: "Aldrig"
|
||||
STR_IN_READER: "I læseren"
|
||||
STR_ALWAYS: "Altid"
|
||||
STR_IGNORE: "Ignorer"
|
||||
STR_SLEEP: "Hvile"
|
||||
STR_PAGE_TURN: "Sideskift"
|
||||
STR_PORTRAIT: "Portræt"
|
||||
STR_LANDSCAPE_CW: "Liggende med uret"
|
||||
STR_INVERTED: "Inverteret"
|
||||
STR_LANDSCAPE_CCW: "Liggende mod uret"
|
||||
STR_FRONT_LAYOUT_BCLR: "Bck, Cnfrm, Lft, Rght"
|
||||
STR_FRONT_LAYOUT_LRBC: "Lft, Rght, Bck, Cnfrm"
|
||||
STR_FRONT_LAYOUT_LBCR: "Lft, Bck, Cnfrm, Rght"
|
||||
STR_PREV_NEXT: "Forrige/Næste"
|
||||
STR_NEXT_PREV: "Næste/Forrige"
|
||||
STR_BOOKERLY: "Bookerly"
|
||||
STR_NOTO_SANS: "Noto Sans"
|
||||
STR_OPEN_DYSLEXIC: "Open Dyslexic"
|
||||
STR_SMALL: "Lille"
|
||||
STR_MEDIUM: "Mellem"
|
||||
STR_LARGE: "Stor"
|
||||
STR_X_LARGE: "Ekstra stor"
|
||||
STR_TIGHT: "Tæt"
|
||||
STR_NORMAL: "Normal"
|
||||
STR_WIDE: "Bred"
|
||||
STR_JUSTIFY: "Justeret"
|
||||
STR_ALIGN_LEFT: "Venstre"
|
||||
STR_CENTER: "Centreret"
|
||||
STR_ALIGN_RIGHT: "Højre"
|
||||
STR_MIN_1: "1 min"
|
||||
STR_MIN_5: "5 min"
|
||||
STR_MIN_10: "10 min"
|
||||
STR_MIN_15: "15 min"
|
||||
STR_MIN_30: "30 min"
|
||||
STR_PAGES_1: "1 side"
|
||||
STR_PAGES_5: "5 sider"
|
||||
STR_PAGES_10: "10 sider"
|
||||
STR_PAGES_15: "15 sider"
|
||||
STR_PAGES_30: "30 sider"
|
||||
STR_UPDATE: "Opdater"
|
||||
STR_CHECKING_UPDATE: "Søger efter opdatering..."
|
||||
STR_NEW_UPDATE: "Ny opdatering tilgængelig!"
|
||||
STR_CURRENT_VERSION: "Nuværende version: "
|
||||
STR_NEW_VERSION: "Ny version: "
|
||||
STR_UPDATING: "Opdaterer..."
|
||||
STR_NO_UPDATE: "Ingen opdatering tilgængelig"
|
||||
STR_UPDATE_FAILED: "Opdatering mislykkedes"
|
||||
STR_UPDATE_COMPLETE: "Opdatering færdig"
|
||||
STR_POWER_ON_HINT: "Hold tænd/sluk-knappen nede for at tænde igen"
|
||||
STR_EXTERNAL_FONT: "Ekstern skrifttype"
|
||||
STR_BUILTIN_DISABLED: "Indbygget (deaktiveret)"
|
||||
STR_NO_ENTRIES: "Ingen poster fundet"
|
||||
STR_DOWNLOADING: "Downloader..."
|
||||
STR_DOWNLOAD_FAILED: "Download mislykkedes"
|
||||
STR_ERROR_MSG: "Fejl:"
|
||||
STR_UNNAMED: "Unavngivet"
|
||||
STR_NO_SERVER_URL: "Ingen server-URL konfigureret"
|
||||
STR_FETCH_FEED_FAILED: "Kunne ikke hente feed"
|
||||
STR_PARSE_FEED_FAILED: "Kunne ikke fortolke feed"
|
||||
STR_NETWORK_PREFIX: "Netværk: "
|
||||
STR_IP_ADDRESS_PREFIX: "IP-adresse: "
|
||||
STR_SCAN_QR_WIFI_HINT: "eller scan QR-kode med din telefon for at oprette forbindelse til WiFi."
|
||||
STR_ERROR_GENERAL_FAILURE: "Fejl: Generel fejl"
|
||||
STR_ERROR_NETWORK_NOT_FOUND: "Fejl: Netværk ikke fundet"
|
||||
STR_ERROR_CONNECTION_TIMEOUT: "Fejl: Forbindelses timeout"
|
||||
STR_SD_CARD: "SD-kort"
|
||||
STR_BACK: "« Tilbage"
|
||||
STR_EXIT: "« Afslut"
|
||||
STR_HOME: "« Hjem"
|
||||
STR_SAVE: "« Gem"
|
||||
STR_SELECT: "Vælg"
|
||||
STR_TOGGLE: "Skift"
|
||||
STR_CONFIRM: "Bekræft"
|
||||
STR_CANCEL: "Annuller"
|
||||
STR_CONNECT: "Forbind"
|
||||
STR_OPEN: "Åbn"
|
||||
STR_DOWNLOAD: "Download"
|
||||
STR_RETRY: "Prøv igen"
|
||||
STR_YES: "Ja"
|
||||
STR_NO: "Nej"
|
||||
STR_STATE_ON: "TÆNDT"
|
||||
STR_STATE_OFF: "SLUKKET"
|
||||
STR_SET: "Indstil"
|
||||
STR_NOT_SET: "Ikke indstillet"
|
||||
STR_DIR_LEFT: "Venstre"
|
||||
STR_DIR_RIGHT: "Højre"
|
||||
STR_DIR_UP: "Op"
|
||||
STR_DIR_DOWN: "Ned"
|
||||
STR_CAPS_ON: "CAPS"
|
||||
STR_CAPS_OFF: "caps"
|
||||
STR_OK_BUTTON: "OK"
|
||||
STR_ON_MARKER: "[ON]"
|
||||
STR_SLEEP_COVER_FILTER: "Hvile-skærm omslag-filter"
|
||||
STR_FILTER_CONTRAST: "Kontrast"
|
||||
STR_STATUS_BAR_FULL_PERCENT: "Fuld m/ procent"
|
||||
STR_STATUS_BAR_FULL_BOOK: "Fuld m/ boglinje"
|
||||
STR_STATUS_BAR_BOOK_ONLY: "Kun boglinje"
|
||||
STR_STATUS_BAR_FULL_CHAPTER: "Fuld m/ kapitellinje"
|
||||
STR_UI_THEME: "Brugergrænseflade tema"
|
||||
STR_THEME_CLASSIC: "Klassisk"
|
||||
STR_THEME_LYRA: "Lyra"
|
||||
STR_THEME_LYRA_EXTENDED: "Lyra Extended"
|
||||
STR_SUNLIGHT_FADING_FIX: "Sollysfading-rettelse"
|
||||
STR_REMAP_FRONT_BUTTONS: "Omtildel frontknapper"
|
||||
STR_OPDS_BROWSER: "OPDS Browser"
|
||||
STR_COVER_CUSTOM: "Omslag + Brugerdefineret"
|
||||
STR_RECENTS: "Seneste"
|
||||
STR_MENU_RECENT_BOOKS: "Seneste bøger"
|
||||
STR_NO_RECENT_BOOKS: "Ingen seneste bøger"
|
||||
STR_CALIBRE_DESC: "Brug Calibre trådløs enhedsoverførelse"
|
||||
STR_FORGET_AND_REMOVE: "Glem netværk og fjern gemt adgangskode?"
|
||||
STR_FORGET_BUTTON: "Glem"
|
||||
STR_CALIBRE_STARTING: "Starter Calibre..."
|
||||
STR_CALIBRE_SETUP: "Opsætning"
|
||||
STR_CALIBRE_STATUS: "Status"
|
||||
STR_CLEAR_BUTTON: "Ryd"
|
||||
STR_DEFAULT_VALUE: "Standard"
|
||||
STR_REMAP_PROMPT: "Tryk på en frontknap for hver rolle"
|
||||
STR_UNASSIGNED: "Ikke tildelt"
|
||||
STR_ALREADY_ASSIGNED: "Allerede tildelt"
|
||||
STR_REMAP_RESET_HINT: "Sideknap op: Nulstil til standardlayout"
|
||||
STR_REMAP_CANCEL_HINT: "Sideknap ned: Annuller omtildeling"
|
||||
STR_HW_BACK_LABEL: "Tilbage (1. knap)"
|
||||
STR_HW_CONFIRM_LABEL: "Bekræft (2. knap)"
|
||||
STR_HW_LEFT_LABEL: "Venstre (3. knap)"
|
||||
STR_HW_RIGHT_LABEL: "Højre (4. knap)"
|
||||
STR_GO_TO_PERCENT: "Gå til %"
|
||||
STR_GO_HOME_BUTTON: "Gå til start"
|
||||
STR_SYNC_PROGRESS: "Synkroniser fremskridt"
|
||||
STR_DELETE_CACHE: "Slet bogcache"
|
||||
STR_CHAPTER_PREFIX: "Kapitel: "
|
||||
STR_PAGES_SEPARATOR: " sider | "
|
||||
STR_BOOK_PREFIX: "Bog: "
|
||||
STR_KBD_SHIFT: "shift"
|
||||
STR_KBD_SHIFT_CAPS: "SHIFT"
|
||||
STR_KBD_LOCK: "LOCK"
|
||||
STR_CALIBRE_URL_HINT: "Tilføj /opds til din URL for Calibre"
|
||||
STR_PERCENT_STEP_HINT: "Venstre/Højre: 1% Op/Ned: 10%"
|
||||
STR_SYNCING_TIME: "Synkroniserer tid..."
|
||||
STR_CALC_HASH: "Beregner dokument-hash..."
|
||||
STR_HASH_FAILED: "Kunne ikke beregne dokument-hash"
|
||||
STR_FETCH_PROGRESS: "Henter fjernfremskridt..."
|
||||
STR_UPLOAD_PROGRESS: "Uploader fremskridt..."
|
||||
STR_NO_CREDENTIALS_MSG: "Ingen legitimationsoplysninger konfigureret"
|
||||
STR_KOREADER_SETUP_HINT: "Opsæt KOReader-konto i Indstillinger"
|
||||
STR_PROGRESS_FOUND: "Fremskridt fundet!"
|
||||
STR_REMOTE_LABEL: "Ekstern:"
|
||||
STR_LOCAL_LABEL: "Lokal:"
|
||||
STR_PAGE_OVERALL_FORMAT: "Side %d, %.2f%% samlet"
|
||||
STR_PAGE_TOTAL_OVERALL_FORMAT: "Side %d/%d, %.2f%% samlet"
|
||||
STR_DEVICE_FROM_FORMAT: " Fra: %s"
|
||||
STR_APPLY_REMOTE: "Anvend fjernfremskridt"
|
||||
STR_UPLOAD_LOCAL: "Upload lokalt fremskridt"
|
||||
STR_NO_REMOTE_MSG: "Ingen fjernfremskridt fundet"
|
||||
STR_UPLOAD_PROMPT: "Upload nuværende position?"
|
||||
STR_UPLOAD_SUCCESS: "Fremskridt uploadet!"
|
||||
STR_SYNC_FAILED_MSG: "Synkronisering mislykkedes"
|
||||
STR_SECTION_PREFIX: "Afsnit "
|
||||
STR_UPLOAD: "Upload"
|
||||
STR_BOOK_S_STYLE: "Bogens stil"
|
||||
STR_EMBEDDED_STYLE: "Indlejret stil"
|
||||
STR_OPDS_SERVER_URL: "OPDS Server URL"
|
||||
STR_SCREENSHOT_BUTTON: "Tag skærmbillede"
|
||||
@@ -331,4 +331,7 @@ STR_UPLOAD: "Upload"
|
||||
STR_BOOK_S_STYLE: "Book's Style"
|
||||
STR_EMBEDDED_STYLE: "Embedded Style"
|
||||
STR_OPDS_SERVER_URL: "OPDS Server URL"
|
||||
STR_SCREENSHOT_BUTTON: "Take screenshot"
|
||||
STR_FOOTNOTES: "Footnotes"
|
||||
STR_NO_FOOTNOTES: "No footnotes on this page"
|
||||
STR_LINK: "[link]"
|
||||
STR_SCREENSHOT_BUTTON: "Take screenshot"
|
||||
|
||||
@@ -63,7 +63,7 @@ STR_MAC_ADDRESS: "Adres MAC:"
|
||||
STR_CHECKING_WIFI: "Sprawdzanie WiFi..."
|
||||
STR_ENTER_WIFI_PASSWORD: "Wprowadź hasło WiFi"
|
||||
STR_ENTER_TEXT: "Wprowadź tekst"
|
||||
STR_TO_PREFIX: "do "
|
||||
STR_TO_PREFIX: "Z "
|
||||
STR_CALIBRE_DISCOVERING: "Odkrywanie Calibre..."
|
||||
STR_CALIBRE_CONNECTING_TO: "Łączenie do "
|
||||
STR_CALIBRE_CONNECTED_TO: "Podłączony do "
|
||||
@@ -87,21 +87,21 @@ STR_CAT_READER: "Czytnik"
|
||||
STR_CAT_CONTROLS: "Sterowanie"
|
||||
STR_CAT_SYSTEM: "System"
|
||||
STR_SLEEP_SCREEN: "Wygaszacz ekranu"
|
||||
STR_SLEEP_COVER_MODE: "Tryb ekranu uśpienia z okładką"
|
||||
STR_SLEEP_COVER_MODE: "Okładki wygaszacza"
|
||||
STR_STATUS_BAR: "Status Bar"
|
||||
STR_HIDE_BATTERY: "Ukryj % baterii"
|
||||
STR_EXTRA_SPACING: "Dodatkowe odstępy paragrafów"
|
||||
STR_TEXT_AA: "Wygładzanie tekstu"
|
||||
STR_SHORT_PWR_BTN: "Krótkie naciśnięcie przycisku zasilania"
|
||||
STR_SHORT_PWR_BTN: "Krótkie naciśnięcie zasilania"
|
||||
STR_ORIENTATION: "Układ czytania"
|
||||
STR_FRONT_BTN_LAYOUT: "Układ przednich przycisków"
|
||||
STR_SIDE_BTN_LAYOUT: "Układ przycisków bocznych(czytnik)"
|
||||
STR_SIDE_BTN_LAYOUT: "Układ przycisków bocznych"
|
||||
STR_LONG_PRESS_SKIP: "Przytrzymaj aby przeskoczyć rozdział"
|
||||
STR_FONT_FAMILY: "Czcionka"
|
||||
STR_EXT_READER_FONT: "Zewnętrzna czcionka czytnika"
|
||||
STR_EXT_CHINESE_FONT: "Czcionka czytnika"
|
||||
STR_EXT_UI_FONT: "Czcionka UI"
|
||||
STR_FONT_SIZE: "Rozmiar czcionki UI"
|
||||
STR_FONT_SIZE: "Rozmiar czcionki"
|
||||
STR_LINE_SPACING: "Odstępy między wierszami"
|
||||
STR_ASCII_LETTER_SPACING: "Odstępy liter ASCII"
|
||||
STR_ASCII_DIGIT_SPACING: "Odstępy cyfr ASCII"
|
||||
@@ -160,7 +160,7 @@ STR_IN_READER: "W czytniku"
|
||||
STR_ALWAYS: "Zawsze"
|
||||
STR_IGNORE: "Ignoruj"
|
||||
STR_SLEEP: "Uśpienie"
|
||||
STR_PAGE_TURN: "Obrót strony"
|
||||
STR_PAGE_TURN: "Nast. str."
|
||||
STR_PORTRAIT: "Pionowo"
|
||||
STR_LANDSCAPE_CW: "Poziomo L"
|
||||
STR_INVERTED: "Odwrócony"
|
||||
@@ -168,8 +168,8 @@ STR_LANDSCAPE_CCW: "Poziomo P"
|
||||
STR_FRONT_LAYOUT_BCLR: "Wstecz, Potwierdź, Lewo, Prawo"
|
||||
STR_FRONT_LAYOUT_LRBC: "Lewo, Prawo, Wstecz, Potwierdź"
|
||||
STR_FRONT_LAYOUT_LBCR: "Lewo, Wstecz, Potwierdź, Prawo"
|
||||
STR_PREV_NEXT: "Poprzedni/Następny"
|
||||
STR_NEXT_PREV: "Następny/Poprzedni"
|
||||
STR_PREV_NEXT: "Poprz./Nast."
|
||||
STR_NEXT_PREV: "Nast./Poprz."
|
||||
STR_BOOKERLY: "Bookerly"
|
||||
STR_NOTO_SANS: "Noto Sans"
|
||||
STR_OPEN_DYSLEXIC: "Open Dyslexic"
|
||||
@@ -177,13 +177,13 @@ STR_SMALL: "Mały"
|
||||
STR_MEDIUM: "Średni"
|
||||
STR_LARGE: "Duży"
|
||||
STR_X_LARGE: "B. duży"
|
||||
STR_TIGHT: "Ciasno"
|
||||
STR_NORMAL: "Normalnie"
|
||||
STR_WIDE: "Szeroko"
|
||||
STR_JUSTIFY: "Wyrównanie"
|
||||
STR_ALIGN_LEFT: "Lewej"
|
||||
STR_CENTER: "Środkuj"
|
||||
STR_ALIGN_RIGHT: "Prawej"
|
||||
STR_TIGHT: "Małe"
|
||||
STR_NORMAL: "Normalne"
|
||||
STR_WIDE: "Duże"
|
||||
STR_JUSTIFY: "Wyrównane"
|
||||
STR_ALIGN_LEFT: "Lewo"
|
||||
STR_CENTER: "Środek"
|
||||
STR_ALIGN_RIGHT: "Prawo"
|
||||
STR_MIN_1: "1 min"
|
||||
STR_MIN_5: "5 min"
|
||||
STR_MIN_10: "10 min"
|
||||
@@ -220,13 +220,13 @@ STR_SCAN_QR_WIFI_HINT: "albo skanuj kod QR telefonem aby połączyć się do Wif
|
||||
STR_ERROR_GENERAL_FAILURE: "Błąd: Ogólny"
|
||||
STR_ERROR_NETWORK_NOT_FOUND: "Błąd: Sieci nie znaleziono"
|
||||
STR_ERROR_CONNECTION_TIMEOUT: "Błąd: Przekroczono limit czasu połączenia"
|
||||
STR_SD_CARD: "karta S"
|
||||
STR_SD_CARD: "Karta SD"
|
||||
STR_BACK: "« Wstecz"
|
||||
STR_EXIT: "« Wyjdź"
|
||||
STR_HOME: "« Home"
|
||||
STR_SAVE: "« Zapisz"
|
||||
STR_SELECT: "Wybierz"
|
||||
STR_TOGGLE: "Przełącz"
|
||||
STR_TOGGLE: "Zmień"
|
||||
STR_CONFIRM: "Potwierdź"
|
||||
STR_CANCEL: "Anuluj"
|
||||
STR_CONNECT: "Połącz"
|
||||
@@ -237,8 +237,8 @@ STR_YES: "Tak"
|
||||
STR_NO: "Nie"
|
||||
STR_SHOW: "Pokaż"
|
||||
STR_HIDE: "Ukryj"
|
||||
STR_STATE_ON: "ON"
|
||||
STR_STATE_OFF: "OFF"
|
||||
STR_STATE_ON: "Wł."
|
||||
STR_STATE_OFF: "Wył."
|
||||
STR_SET: "Ustawiono"
|
||||
STR_NOT_SET: "Nie ustawiono"
|
||||
STR_DIR_LEFT: "Lewo"
|
||||
@@ -249,11 +249,11 @@ STR_CAPS_ON: "CAPS"
|
||||
STR_CAPS_OFF: "caps"
|
||||
STR_OK_BUTTON: "OK"
|
||||
STR_ON_MARKER: "[ON]"
|
||||
STR_SLEEP_COVER_FILTER: "Filtr okładki uśpionego ekranu"
|
||||
STR_SLEEP_COVER_FILTER: "Filtr okładek wygaszacza"
|
||||
STR_FILTER_CONTRAST: "Kontrast"
|
||||
STR_CUSTOMISE_STATUS_BAR: "Dostosowanie paska statusu"
|
||||
STR_CHAPTER_PAGE_COUNT: "Strona rozdziału"
|
||||
STR_BOOK_PROGRESS_PERCENTAGE: "Pasek postępu książki"
|
||||
STR_BOOK_PROGRESS_PERCENTAGE: "Postęp książki"
|
||||
STR_PROGRESS_BAR: "Pasek postępu"
|
||||
STR_PROGRESS_BAR_THICKNESS: "Grubość paska postępu"
|
||||
STR_PROGRESS_BAR_THIN: "Cienki"
|
||||
@@ -306,9 +306,9 @@ STR_KBD_SHIFT: "shift"
|
||||
STR_KBD_SHIFT_CAPS: "SHIFT"
|
||||
STR_KBD_LOCK: "LOCK"
|
||||
STR_CALIBRE_URL_HINT: "Dla Calibre, dodaj /opds do adresu URL"
|
||||
STR_PERCENT_STEP_HINT: "Left/Right: 1% Up/Down: 10%"
|
||||
STR_PERCENT_STEP_HINT: "Lewo/Prawo: 1% Góra/Dół: 10%"
|
||||
STR_SYNCING_TIME: "Synchronizacja czasu..."
|
||||
STR_CALC_HASH: "Obliczanie sumu kontrolnekj..."
|
||||
STR_CALC_HASH: "Obliczanie sumy kontrolnej..."
|
||||
STR_HASH_FAILED: "Błąd obliczania sumy kontrolnej"
|
||||
STR_FETCH_PROGRESS: "Pobieranie zdalnego postępu.."
|
||||
STR_UPLOAD_PROGRESS: "Postęp wysyłania..."
|
||||
@@ -329,6 +329,6 @@ STR_SYNC_FAILED_MSG: "Synchronizacja nieudana"
|
||||
STR_SECTION_PREFIX: "Sekcja "
|
||||
STR_UPLOAD: "Wyślij"
|
||||
STR_BOOK_S_STYLE: "Styl książki"
|
||||
STR_EMBEDDED_STYLE: "Styl wbudowany"
|
||||
STR_EMBEDDED_STYLE: "Style wbudowane w EPUB"
|
||||
STR_OPDS_SERVER_URL: "URL serwera OPDS"
|
||||
STR_SCREENSHOT_BUTTON: "Zrób zrzut ekranu"
|
||||
|
||||
@@ -235,6 +235,8 @@ STR_DOWNLOAD: "Descarcă"
|
||||
STR_RETRY: "Reîncercare"
|
||||
STR_YES: "Da"
|
||||
STR_NO: "Nu"
|
||||
STR_SHOW: "Afișează"
|
||||
STR_HIDE: "Ascunde"
|
||||
STR_STATE_ON: "Pornit"
|
||||
STR_STATE_OFF: "Oprit"
|
||||
STR_SET: "Setare"
|
||||
@@ -249,6 +251,21 @@ STR_OK_BUTTON: "OK"
|
||||
STR_ON_MARKER: "[ON]"
|
||||
STR_SLEEP_COVER_FILTER: "Filtru ecran de repaus"
|
||||
STR_FILTER_CONTRAST: "Contrast"
|
||||
STR_CUSTOMISE_STATUS_BAR: "Customizaţi bara de stare"
|
||||
STR_CHAPTER_PAGE_COUNT: "Număr de pagini în capitol"
|
||||
STR_BOOK_PROGRESS_PERCENTAGE: "Progres carte procentual"
|
||||
STR_PROGRESS_BAR: "Bară de progres"
|
||||
STR_PROGRESS_BAR_THICKNESS: "Grosime bară de progres"
|
||||
STR_PROGRESS_BAR_THIN: "Subţire"
|
||||
STR_PROGRESS_BAR_MEDIUM: "Medie"
|
||||
STR_PROGRESS_BAR_THICK: "Groasă"
|
||||
STR_BOOK: "Carte"
|
||||
STR_CHAPTER: "Capitol"
|
||||
STR_EXAMPLE_CHAPTER: "Capitolul 21"
|
||||
STR_EXAMPLE_BOOK: "Titlul cărţii"
|
||||
STR_PREVIEW: "Previzualizare"
|
||||
STR_TITLE: "Titlu"
|
||||
STR_BATTERY: "Baterie"
|
||||
STR_UI_THEME: "Tema UI"
|
||||
STR_THEME_CLASSIC: "Clasic"
|
||||
STR_THEME_LYRA: "Lyra"
|
||||
@@ -281,7 +298,7 @@ STR_GO_TO_PERCENT: "Săriţi la %"
|
||||
STR_GO_HOME_BUTTON: "Acasă"
|
||||
STR_SYNC_PROGRESS: "Progres sincronizare"
|
||||
STR_DELETE_CACHE: "Ştergere cache cărţi"
|
||||
STR_CHAPTER_PREFIX: "Capitol: "
|
||||
STR_DISPLAY_QR: "Afișați pagina ca cod QR"
|
||||
STR_PAGES_SEPARATOR: " pagini | "
|
||||
STR_BOOK_PREFIX: "Carte: "
|
||||
STR_KBD_SHIFT: "shift"
|
||||
|
||||
@@ -235,6 +235,8 @@ STR_DOWNLOAD: "Скачать"
|
||||
STR_RETRY: "Повторить"
|
||||
STR_YES: "Да"
|
||||
STR_NO: "Нет"
|
||||
STR_SHOW: "Показать"
|
||||
STR_HIDE: "Скрыть"
|
||||
STR_STATE_ON: "ВКЛ"
|
||||
STR_STATE_OFF: "ВЫКЛ"
|
||||
STR_SET: "Установлено"
|
||||
@@ -249,6 +251,20 @@ STR_OK_BUTTON: "OK"
|
||||
STR_ON_MARKER: "[ВКЛ]"
|
||||
STR_SLEEP_COVER_FILTER: "Фильтр экрана сна"
|
||||
STR_FILTER_CONTRAST: "Контраст"
|
||||
STR_CUSTOMISE_STATUS_BAR: "Настройка строки состояния"
|
||||
STR_CHAPTER_PAGE_COUNT: "Количество страниц главы"
|
||||
STR_BOOK_PROGRESS_PERCENTAGE: "% прочтения книги"
|
||||
STR_PROGRESS_BAR: "Полоса прогресса"
|
||||
STR_PROGRESS_BAR_THICKNESS: "Толщина индикатора прогресса"
|
||||
STR_PROGRESS_BAR_THIN: "Тонкий"
|
||||
STR_PROGRESS_BAR_MEDIUM: "Средний"
|
||||
STR_PROGRESS_BAR_THICK: "Толстый"
|
||||
STR_BOOK: "Книга"
|
||||
STR_CHAPTER: "Глава"
|
||||
STR_EXAMPLE_BOOK: "Название книги"
|
||||
STR_PREVIEW: "Предпросмотр"
|
||||
STR_TITLE: "Заглавие"
|
||||
STR_BATTERY: "Батарея"
|
||||
STR_UI_THEME: "Тема интерфейса"
|
||||
STR_THEME_CLASSIC: "Классическая"
|
||||
STR_THEME_LYRA: "Lyra"
|
||||
@@ -282,6 +298,7 @@ STR_GO_HOME_BUTTON: "На главную"
|
||||
STR_SYNC_PROGRESS: "Синхронизировать прогресс"
|
||||
STR_DELETE_CACHE: "Удалить кэш книги"
|
||||
STR_CHAPTER_PREFIX: "Глава:"
|
||||
STR_DISPLAY_QR: "Показать страницу в виде QR-кода"
|
||||
STR_PAGES_SEPARATOR: "стр. |"
|
||||
STR_BOOK_PREFIX: "Книга:"
|
||||
STR_KBD_SHIFT: "shift"
|
||||
|
||||
@@ -234,6 +234,8 @@ STR_OPEN: "Відкрити"
|
||||
STR_DOWNLOAD: "Завант."
|
||||
STR_RETRY: "Повтор."
|
||||
STR_YES: "Так"
|
||||
STR_SHOW: "Показати"
|
||||
STR_HIDE: "Сховати"
|
||||
STR_NO: "Ні"
|
||||
STR_STATE_ON: "УВІМК"
|
||||
STR_STATE_OFF: "ВИМК"
|
||||
@@ -249,6 +251,21 @@ STR_OK_BUTTON: "OK"
|
||||
STR_ON_MARKER: "[УВІМК]"
|
||||
STR_SLEEP_COVER_FILTER: "Фільтр обкладинки екрана сну"
|
||||
STR_FILTER_CONTRAST: "Контраст"
|
||||
STR_CUSTOMISE_STATUS_BAR: "Налаштувати рядок стану"
|
||||
STR_CHAPTER_PAGE_COUNT: "Кількість сторінок розділу"
|
||||
STR_BOOK_PROGRESS_PERCENTAGE: "Відсоток прочитаного"
|
||||
STR_PROGRESS_BAR: "Рядок прогресу"
|
||||
STR_PROGRESS_BAR_THICKNESS: "Товщина рядку прогресу"
|
||||
STR_PROGRESS_BAR_THIN: "Тонкий"
|
||||
STR_PROGRESS_BAR_MEDIUM: "Середній"
|
||||
STR_PROGRESS_BAR_THICK: "Жирний"
|
||||
STR_BOOK: "Книга"
|
||||
STR_CHAPTER: "Розділ"
|
||||
STR_EXAMPLE_CHAPTER: "Розділ 21"
|
||||
STR_EXAMPLE_BOOK: "Назва книги"
|
||||
STR_PREVIEW: "Перегляд"
|
||||
STR_TITLE: "Назва"
|
||||
STR_BATTERY: "Акумулятор"
|
||||
STR_UI_THEME: "Тема інтерфейсу"
|
||||
STR_THEME_CLASSIC: "Класична"
|
||||
STR_THEME_LYRA: "Lyra"
|
||||
@@ -281,6 +298,7 @@ STR_GO_TO_PERCENT: "Перейти до %"
|
||||
STR_GO_HOME_BUTTON: "На головну"
|
||||
STR_SYNC_PROGRESS: "Прогрес синхронізації"
|
||||
STR_DELETE_CACHE: "Видалити кеш книги"
|
||||
STR_DISPLAY_QR: "Показати сторінку як QR-код"
|
||||
STR_CHAPTER_PREFIX: "Розділ: "
|
||||
STR_PAGES_SEPARATOR: " сторінок | "
|
||||
STR_BOOK_PREFIX: "Книга: "
|
||||
@@ -313,4 +331,7 @@ STR_UPLOAD: "Завантажити"
|
||||
STR_BOOK_S_STYLE: "Стиль книги"
|
||||
STR_EMBEDDED_STYLE: "Вбудований стиль"
|
||||
STR_OPDS_SERVER_URL: "URL сервера OPDS"
|
||||
STR_FOOTNOTES: "Зноски"
|
||||
STR_NO_FOOTNOTES: "На цій сторінці немає зносок"
|
||||
STR_LINK: "[посилання]"
|
||||
STR_SCREENSHOT_BUTTON: "Знімок екрана"
|
||||
|
||||
+14
-47
@@ -1,61 +1,28 @@
|
||||
#include "Activity.h"
|
||||
|
||||
#include <HalPowerManager.h>
|
||||
#include "ActivityManager.h"
|
||||
|
||||
void Activity::renderTaskTrampoline(void* param) {
|
||||
auto* self = static_cast<Activity*>(param);
|
||||
self->renderTaskLoop();
|
||||
}
|
||||
void Activity::onEnter() { LOG_DBG("ACT", "Entering activity: %s", name.c_str()); }
|
||||
|
||||
void Activity::renderTaskLoop() {
|
||||
while (true) {
|
||||
ulTaskNotifyTake(pdTRUE, portMAX_DELAY);
|
||||
{
|
||||
HalPowerManager::Lock powerLock; // Ensure we don't go into low-power mode while rendering
|
||||
RenderLock lock(*this);
|
||||
render(std::move(lock));
|
||||
}
|
||||
}
|
||||
}
|
||||
void Activity::onExit() { LOG_DBG("ACT", "Exiting activity: %s", name.c_str()); }
|
||||
|
||||
void Activity::onEnter() {
|
||||
xTaskCreate(&renderTaskTrampoline, name.c_str(),
|
||||
8192, // Stack size
|
||||
this, // Parameters
|
||||
1, // Priority
|
||||
&renderTaskHandle // Task handle
|
||||
);
|
||||
assert(renderTaskHandle != nullptr && "Failed to create render task");
|
||||
LOG_DBG("ACT", "Entering activity: %s", name.c_str());
|
||||
}
|
||||
|
||||
void Activity::onExit() {
|
||||
RenderLock lock(*this); // Ensure we don't delete the task while it's rendering
|
||||
if (renderTaskHandle) {
|
||||
vTaskDelete(renderTaskHandle);
|
||||
renderTaskHandle = nullptr;
|
||||
}
|
||||
|
||||
LOG_DBG("ACT", "Exiting activity: %s", name.c_str());
|
||||
}
|
||||
|
||||
void Activity::requestUpdate() {
|
||||
// Using direct notification to signal the render task to update
|
||||
// Increment counter so multiple rapid calls won't be lost
|
||||
if (renderTaskHandle) {
|
||||
xTaskNotify(renderTaskHandle, 1, eIncrement);
|
||||
}
|
||||
}
|
||||
void Activity::requestUpdate(bool immediate) { activityManager.requestUpdate(immediate); }
|
||||
|
||||
void Activity::requestUpdateAndWait() {
|
||||
// FIXME @ngxson : properly implement this using freeRTOS notification
|
||||
activityManager.requestUpdate(true);
|
||||
delay(100);
|
||||
}
|
||||
|
||||
// RenderLock
|
||||
void Activity::onGoHome() { activityManager.goHome(); }
|
||||
|
||||
Activity::RenderLock::RenderLock(Activity& activity) : activity(activity) {
|
||||
xSemaphoreTake(activity.renderingMutex, portMAX_DELAY);
|
||||
void Activity::onSelectBook(const std::string& path) { activityManager.goToReader(path); }
|
||||
|
||||
void Activity::startActivityForResult(std::unique_ptr<Activity>&& activity, ActivityResultHandler resultHandler) {
|
||||
this->resultHandler = std::move(resultHandler);
|
||||
activityManager.pushActivity(std::move(activity));
|
||||
}
|
||||
|
||||
Activity::RenderLock::~RenderLock() { xSemaphoreGive(activity.renderingMutex); }
|
||||
void Activity::setResult(ActivityResult&& result) { this->result = std::move(result); }
|
||||
|
||||
void Activity::finish() { activityManager.popActivity(); }
|
||||
|
||||
+28
-30
@@ -1,16 +1,16 @@
|
||||
#pragma once
|
||||
#include <HardwareSerial.h>
|
||||
#include <Logging.h>
|
||||
#include <freertos/FreeRTOS.h>
|
||||
#include <freertos/semphr.h>
|
||||
#include <freertos/task.h>
|
||||
|
||||
#include <cassert>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
|
||||
#include "ActivityManager.h" // for using the ActivityManager singleton
|
||||
#include "ActivityResult.h"
|
||||
#include "GfxRenderer.h"
|
||||
#include "MappedInputManager.h"
|
||||
#include "RenderLock.h"
|
||||
|
||||
class Activity {
|
||||
protected:
|
||||
@@ -18,44 +18,42 @@ class Activity {
|
||||
GfxRenderer& renderer;
|
||||
MappedInputManager& mappedInput;
|
||||
|
||||
// Task to render and display the activity
|
||||
TaskHandle_t renderTaskHandle = nullptr;
|
||||
[[noreturn]] static void renderTaskTrampoline(void* param);
|
||||
[[noreturn]] virtual void renderTaskLoop();
|
||||
|
||||
// Mutex to protect rendering operations from being deleted mid-render
|
||||
SemaphoreHandle_t renderingMutex = nullptr;
|
||||
|
||||
public:
|
||||
ActivityResultHandler resultHandler;
|
||||
ActivityResult result;
|
||||
|
||||
explicit Activity(std::string name, GfxRenderer& renderer, MappedInputManager& mappedInput)
|
||||
: name(std::move(name)), renderer(renderer), mappedInput(mappedInput), renderingMutex(xSemaphoreCreateMutex()) {
|
||||
assert(renderingMutex != nullptr && "Failed to create rendering mutex");
|
||||
}
|
||||
virtual ~Activity() {
|
||||
vSemaphoreDelete(renderingMutex);
|
||||
renderingMutex = nullptr;
|
||||
};
|
||||
class RenderLock;
|
||||
: name(std::move(name)), renderer(renderer), mappedInput(mappedInput) {}
|
||||
virtual ~Activity() = default;
|
||||
virtual void onEnter();
|
||||
virtual void onExit();
|
||||
virtual void loop() {}
|
||||
|
||||
virtual void render(RenderLock&&) {}
|
||||
virtual void requestUpdate();
|
||||
|
||||
// If immediate is true, the update will be triggered immediately.
|
||||
// Otherwise, it will be deferred until the end of the current loop iteration.
|
||||
virtual void requestUpdate(bool immediate = false);
|
||||
|
||||
// Request an immediate render and block until it completes.
|
||||
virtual void requestUpdateAndWait();
|
||||
|
||||
virtual bool skipLoopDelay() { return false; }
|
||||
virtual bool preventAutoSleep() { return false; }
|
||||
virtual bool isReaderActivity() const { return false; }
|
||||
|
||||
// RAII helper to lock rendering mutex for the duration of a scope.
|
||||
class RenderLock {
|
||||
Activity& activity;
|
||||
// Start a new activity without destroying the current one
|
||||
// Note: requestUpdate() will be invoked automatically once resultHandler finishes
|
||||
void startActivityForResult(std::unique_ptr<Activity>&& activity, ActivityResultHandler resultHandler);
|
||||
|
||||
public:
|
||||
explicit RenderLock(Activity& activity);
|
||||
RenderLock(const RenderLock&) = delete;
|
||||
RenderLock& operator=(const RenderLock&) = delete;
|
||||
~RenderLock();
|
||||
};
|
||||
// Set the result to be passed back to the previous activity when this activity finishes
|
||||
void setResult(ActivityResult&& result);
|
||||
|
||||
// Finish this activity and return to the previous one on the stack (if any)
|
||||
void finish();
|
||||
|
||||
// Convenience method to facilitate API transition to ActivityManager
|
||||
// TODO: remove this in near future
|
||||
void onGoHome();
|
||||
void onSelectBook(const std::string& path);
|
||||
};
|
||||
|
||||
@@ -0,0 +1,252 @@
|
||||
#include "ActivityManager.h"
|
||||
|
||||
#include <HalPowerManager.h>
|
||||
|
||||
#include "boot_sleep/BootActivity.h"
|
||||
#include "boot_sleep/SleepActivity.h"
|
||||
#include "browser/OpdsBookBrowserActivity.h"
|
||||
#include "home/HomeActivity.h"
|
||||
#include "home/MyLibraryActivity.h"
|
||||
#include "home/RecentBooksActivity.h"
|
||||
#include "network/CrossPointWebServerActivity.h"
|
||||
#include "reader/ReaderActivity.h"
|
||||
#include "settings/SettingsActivity.h"
|
||||
#include "util/FullScreenMessageActivity.h"
|
||||
|
||||
void ActivityManager::begin() {
|
||||
xTaskCreate(&renderTaskTrampoline, "ActivityManagerRender",
|
||||
8192, // Stack size
|
||||
this, // Parameters
|
||||
1, // Priority
|
||||
&renderTaskHandle // Task handle
|
||||
);
|
||||
assert(renderTaskHandle != nullptr && "Failed to create render task");
|
||||
}
|
||||
|
||||
void ActivityManager::renderTaskTrampoline(void* param) {
|
||||
auto* self = static_cast<ActivityManager*>(param);
|
||||
self->renderTaskLoop();
|
||||
}
|
||||
|
||||
void ActivityManager::renderTaskLoop() {
|
||||
while (true) {
|
||||
ulTaskNotifyTake(pdTRUE, portMAX_DELAY);
|
||||
// Acquire the lock before reading currentActivity to avoid a TOCTOU race
|
||||
// where the main task deletes the activity between the null-check and render().
|
||||
RenderLock lock;
|
||||
if (currentActivity) {
|
||||
HalPowerManager::Lock powerLock; // Ensure we don't go into low-power mode while rendering
|
||||
currentActivity->render(std::move(lock));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void ActivityManager::loop() {
|
||||
if (currentActivity) {
|
||||
// Note: do not hold a lock here, the loop() method must be responsible for acquire one if needed
|
||||
currentActivity->loop();
|
||||
}
|
||||
|
||||
while (pendingAction != PendingAction::None) {
|
||||
if (pendingAction == PendingAction::Pop) {
|
||||
RenderLock lock;
|
||||
|
||||
if (!currentActivity) {
|
||||
// Should never happen in practice
|
||||
LOG_ERR("ACT", "Pop set but currentActivity is null; ignoring pop request");
|
||||
pendingAction = PendingAction::None;
|
||||
continue;
|
||||
}
|
||||
|
||||
ActivityResult pendingResult = std::move(currentActivity->result);
|
||||
|
||||
// Destroy the current activity
|
||||
exitActivity(lock);
|
||||
pendingAction = PendingAction::None;
|
||||
|
||||
if (stackActivities.empty()) {
|
||||
LOG_DBG("ACT", "No more activities on stack, going home");
|
||||
lock.unlock(); // goHome may acquire its own lock
|
||||
goHome();
|
||||
continue; // Will launch goHome immediately
|
||||
|
||||
} else {
|
||||
currentActivity = std::move(stackActivities.back());
|
||||
stackActivities.pop_back();
|
||||
LOG_DBG("ACT", "Popped from activity stack, new size = %zu", stackActivities.size());
|
||||
// Handle result if necessary
|
||||
if (currentActivity->resultHandler) {
|
||||
LOG_DBG("ACT", "Handling result for popped activity");
|
||||
|
||||
// Move it here to avoid the case where handler calling another startActivityForResult()
|
||||
auto handler = std::move(currentActivity->resultHandler);
|
||||
currentActivity->resultHandler = nullptr;
|
||||
lock.unlock(); // Handler may acquire its own lock
|
||||
handler(pendingResult);
|
||||
}
|
||||
|
||||
// Request an update to ensure the popped activity gets re-rendered
|
||||
if (pendingAction == PendingAction::None) {
|
||||
requestUpdate();
|
||||
}
|
||||
|
||||
// Handler may request another pending action, we will handle it in the next loop iteration
|
||||
continue;
|
||||
}
|
||||
|
||||
} else if (pendingActivity) {
|
||||
// Current activity has requested a new activity to be launched
|
||||
RenderLock lock;
|
||||
|
||||
if (pendingAction == PendingAction::Replace) {
|
||||
// Destroy the current activity
|
||||
exitActivity(lock);
|
||||
// Clear the stack
|
||||
while (!stackActivities.empty()) {
|
||||
stackActivities.back()->onExit();
|
||||
stackActivities.pop_back();
|
||||
}
|
||||
} else if (pendingAction == PendingAction::Push) {
|
||||
// Move current activity to stack
|
||||
stackActivities.push_back(std::move(currentActivity));
|
||||
LOG_DBG("ACT", "Pushed to activity stack, new size = %zu", stackActivities.size());
|
||||
}
|
||||
pendingAction = PendingAction::None;
|
||||
currentActivity = std::move(pendingActivity);
|
||||
|
||||
lock.unlock(); // onEnter may acquire its own lock
|
||||
currentActivity->onEnter();
|
||||
|
||||
// onEnter may request another pending action, we will handle it in the next loop iteration
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
if (requestedUpdate) {
|
||||
requestedUpdate = false;
|
||||
// Using direct notification to signal the render task to update
|
||||
// Increment counter so multiple rapid calls won't be lost
|
||||
if (renderTaskHandle) {
|
||||
xTaskNotify(renderTaskHandle, 1, eIncrement);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void ActivityManager::exitActivity(const RenderLock& lock) {
|
||||
// Note: lock must be held by the caller
|
||||
if (currentActivity) {
|
||||
currentActivity->onExit();
|
||||
currentActivity.reset();
|
||||
}
|
||||
}
|
||||
|
||||
void ActivityManager::replaceActivity(std::unique_ptr<Activity>&& newActivity) {
|
||||
// Note: no lock here, this is usually called by loop() and we may run into deadlock
|
||||
if (currentActivity) {
|
||||
// Defer launch if we're currently in an activity, to avoid deleting the current activity
|
||||
// leading to the "delete this" problem
|
||||
pendingActivity = std::move(newActivity);
|
||||
pendingAction = PendingAction::Replace;
|
||||
} else {
|
||||
// No current activity, safe to launch immediately
|
||||
currentActivity = std::move(newActivity);
|
||||
currentActivity->onEnter();
|
||||
}
|
||||
}
|
||||
|
||||
void ActivityManager::goToFileTransfer() {
|
||||
replaceActivity(std::make_unique<CrossPointWebServerActivity>(renderer, mappedInput));
|
||||
}
|
||||
|
||||
void ActivityManager::goToSettings() { replaceActivity(std::make_unique<SettingsActivity>(renderer, mappedInput)); }
|
||||
|
||||
void ActivityManager::goToMyLibrary(std::string path) {
|
||||
replaceActivity(std::make_unique<MyLibraryActivity>(renderer, mappedInput, std::move(path)));
|
||||
}
|
||||
|
||||
void ActivityManager::goToRecentBooks() {
|
||||
replaceActivity(std::make_unique<RecentBooksActivity>(renderer, mappedInput));
|
||||
}
|
||||
|
||||
void ActivityManager::goToBrowser() {
|
||||
replaceActivity(std::make_unique<OpdsBookBrowserActivity>(renderer, mappedInput));
|
||||
}
|
||||
|
||||
void ActivityManager::goToReader(std::string path) {
|
||||
replaceActivity(std::make_unique<ReaderActivity>(renderer, mappedInput, std::move(path)));
|
||||
}
|
||||
|
||||
void ActivityManager::goToSleep() {
|
||||
replaceActivity(std::make_unique<SleepActivity>(renderer, mappedInput));
|
||||
loop(); // Important: sleep screen must be rendered immediately, the caller will go to sleep right after this returns
|
||||
}
|
||||
|
||||
void ActivityManager::goToBoot() { replaceActivity(std::make_unique<BootActivity>(renderer, mappedInput)); }
|
||||
|
||||
void ActivityManager::goToFullScreenMessage(std::string message, EpdFontFamily::Style style) {
|
||||
replaceActivity(std::make_unique<FullScreenMessageActivity>(renderer, mappedInput, std::move(message), style));
|
||||
}
|
||||
|
||||
void ActivityManager::goHome() { replaceActivity(std::make_unique<HomeActivity>(renderer, mappedInput)); }
|
||||
|
||||
void ActivityManager::pushActivity(std::unique_ptr<Activity>&& activity) {
|
||||
if (pendingActivity) {
|
||||
// Should never happen in practice
|
||||
LOG_ERR("ACT", "pendingActivity while pushActivity is not expected");
|
||||
pendingActivity.reset();
|
||||
}
|
||||
pendingActivity = std::move(activity);
|
||||
pendingAction = PendingAction::Push;
|
||||
}
|
||||
|
||||
void ActivityManager::popActivity() {
|
||||
if (pendingActivity) {
|
||||
// Should never happen in practice
|
||||
LOG_ERR("ACT", "pendingActivity while popActivity is not expected");
|
||||
pendingActivity.reset();
|
||||
}
|
||||
pendingAction = PendingAction::Pop;
|
||||
}
|
||||
|
||||
bool ActivityManager::preventAutoSleep() const { return currentActivity && currentActivity->preventAutoSleep(); }
|
||||
|
||||
bool ActivityManager::isReaderActivity() const { return currentActivity && currentActivity->isReaderActivity(); }
|
||||
|
||||
bool ActivityManager::skipLoopDelay() const { return currentActivity && currentActivity->skipLoopDelay(); }
|
||||
|
||||
void ActivityManager::requestUpdate(bool immediate) {
|
||||
if (immediate) {
|
||||
if (renderTaskHandle) {
|
||||
xTaskNotify(renderTaskHandle, 1, eIncrement);
|
||||
}
|
||||
} else {
|
||||
// Deferring the update until current loop is finished
|
||||
// This is to avoid multiple updates being requested in the same loop
|
||||
requestedUpdate = true;
|
||||
}
|
||||
}
|
||||
// RenderLock
|
||||
|
||||
RenderLock::RenderLock() {
|
||||
xSemaphoreTake(activityManager.renderingMutex, portMAX_DELAY);
|
||||
isLocked = true;
|
||||
}
|
||||
|
||||
RenderLock::RenderLock(Activity& /* unused */) {
|
||||
xSemaphoreTake(activityManager.renderingMutex, portMAX_DELAY);
|
||||
isLocked = true;
|
||||
}
|
||||
|
||||
RenderLock::~RenderLock() {
|
||||
if (isLocked) {
|
||||
xSemaphoreGive(activityManager.renderingMutex);
|
||||
isLocked = false;
|
||||
}
|
||||
}
|
||||
|
||||
void RenderLock::unlock() {
|
||||
if (isLocked) {
|
||||
xSemaphoreGive(activityManager.renderingMutex);
|
||||
isLocked = false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
#pragma once
|
||||
|
||||
#include <freertos/FreeRTOS.h>
|
||||
#include <freertos/semphr.h>
|
||||
#include <freertos/task.h>
|
||||
|
||||
#include <cassert>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "GfxRenderer.h"
|
||||
#include "MappedInputManager.h"
|
||||
#include "RenderLock.h"
|
||||
|
||||
class Activity; // forward declaration
|
||||
class RenderLock; // forward declaration
|
||||
|
||||
/**
|
||||
* ActivityManager
|
||||
*
|
||||
* This mirrors the same concept of Activity in Android, where an activity represents a single screen of the UI. The
|
||||
* manager is responsible for launching activities, and ensuring that only one activity is active at a time.
|
||||
*
|
||||
* It also provides a stack mechanism to allow activities to launch sub-activities and get back the results when the
|
||||
* sub-activity is done. For example, the WebServer activity can launch a WifiSelect activity to let the user choose a
|
||||
* wifi network, and get back the selected network when the user is done.
|
||||
*
|
||||
* Main differences from Android's ActivityManager:
|
||||
* - No onPause/onResume, since we don't have a concept of background activities
|
||||
* - onActivityResult is implemented via a callback instead of a separate method, for simplicity
|
||||
*/
|
||||
class ActivityManager {
|
||||
protected:
|
||||
GfxRenderer& renderer;
|
||||
MappedInputManager& mappedInput;
|
||||
std::vector<std::unique_ptr<Activity>> stackActivities;
|
||||
std::unique_ptr<Activity> currentActivity;
|
||||
|
||||
void exitActivity(const RenderLock& lock);
|
||||
|
||||
// Pending activity to be launched on next loop iteration
|
||||
std::unique_ptr<Activity> pendingActivity;
|
||||
enum class PendingAction { None, Push, Pop, Replace };
|
||||
PendingAction pendingAction = PendingAction::None;
|
||||
|
||||
// Task to render and display the activity
|
||||
TaskHandle_t renderTaskHandle = nullptr;
|
||||
static void renderTaskTrampoline(void* param);
|
||||
[[noreturn]] virtual void renderTaskLoop();
|
||||
|
||||
// Whether to trigger a render after the current loop()
|
||||
// This variable must only be set by the main loop, to avoid race conditions
|
||||
bool requestedUpdate = false;
|
||||
|
||||
public:
|
||||
explicit ActivityManager(GfxRenderer& renderer, MappedInputManager& mappedInput)
|
||||
: renderer(renderer), mappedInput(mappedInput), renderingMutex(xSemaphoreCreateMutex()) {
|
||||
assert(renderingMutex != nullptr && "Failed to create rendering mutex");
|
||||
stackActivities.reserve(10);
|
||||
}
|
||||
~ActivityManager() { assert(false); /* should never be called */ };
|
||||
|
||||
// Mutex to protect rendering operations from race conditions
|
||||
// Must only be used via RenderLock
|
||||
SemaphoreHandle_t renderingMutex = nullptr;
|
||||
|
||||
void begin();
|
||||
void loop();
|
||||
|
||||
// Will replace currentActivity and drop all activities on stack
|
||||
void replaceActivity(std::unique_ptr<Activity>&& newActivity);
|
||||
|
||||
// goTo... functions are convenient wrapper for replaceActivity()
|
||||
void goToFileTransfer();
|
||||
void goToSettings();
|
||||
void goToMyLibrary(std::string path = {});
|
||||
void goToRecentBooks();
|
||||
void goToBrowser();
|
||||
void goToReader(std::string path);
|
||||
void goToSleep();
|
||||
void goToBoot();
|
||||
void goToFullScreenMessage(std::string message, EpdFontFamily::Style style = EpdFontFamily::REGULAR);
|
||||
void goHome();
|
||||
|
||||
// This will move current activity to stack instead of deleting it
|
||||
void pushActivity(std::unique_ptr<Activity>&& activity);
|
||||
|
||||
// Remove the currentActivity, returning the last one on stack
|
||||
// Note: if popActivity() on last activity on the stack, we will goHome()
|
||||
void popActivity();
|
||||
|
||||
bool preventAutoSleep() const;
|
||||
bool isReaderActivity() const;
|
||||
bool skipLoopDelay() const;
|
||||
|
||||
// If immediate is true, the update will be triggered immediately.
|
||||
// Otherwise, it will be deferred until the end of the current loop iteration.
|
||||
void requestUpdate(bool immediate = false);
|
||||
};
|
||||
|
||||
extern ActivityManager activityManager; // singleton, to be defined in main.cpp
|
||||
@@ -0,0 +1,66 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
#include <functional>
|
||||
#include <string>
|
||||
#include <type_traits>
|
||||
#include <utility>
|
||||
#include <variant>
|
||||
|
||||
struct WifiResult {
|
||||
bool connected = false;
|
||||
std::string ssid;
|
||||
std::string ip;
|
||||
};
|
||||
|
||||
struct KeyboardResult {
|
||||
std::string text;
|
||||
};
|
||||
|
||||
struct MenuResult {
|
||||
int action = -1;
|
||||
uint8_t orientation = 0;
|
||||
};
|
||||
|
||||
struct ChapterResult {
|
||||
int spineIndex = 0;
|
||||
};
|
||||
|
||||
struct PercentResult {
|
||||
int percent = 0;
|
||||
};
|
||||
|
||||
struct PageResult {
|
||||
uint32_t page = 0;
|
||||
};
|
||||
|
||||
struct SyncResult {
|
||||
int spineIndex = 0;
|
||||
int page = 0;
|
||||
};
|
||||
|
||||
enum class NetworkMode;
|
||||
|
||||
struct NetworkModeResult {
|
||||
NetworkMode mode;
|
||||
};
|
||||
|
||||
struct FootnoteResult {
|
||||
std::string href;
|
||||
};
|
||||
|
||||
using ResultVariant = std::variant<std::monostate, WifiResult, KeyboardResult, MenuResult, ChapterResult, PercentResult,
|
||||
PageResult, SyncResult, NetworkModeResult, FootnoteResult>;
|
||||
|
||||
struct ActivityResult {
|
||||
bool isCancelled = false;
|
||||
ResultVariant data;
|
||||
|
||||
explicit ActivityResult() = default;
|
||||
|
||||
template <typename ResultType, typename = std::enable_if_t<std::is_constructible_v<ResultVariant, ResultType&&>>>
|
||||
// cppcheck-suppress noExplicitConstructor
|
||||
ActivityResult(ResultType&& result) : data{std::forward<ResultType>(result)} {}
|
||||
};
|
||||
|
||||
using ActivityResultHandler = std::function<void(const ActivityResult&)>;
|
||||
@@ -1,53 +0,0 @@
|
||||
#include "ActivityWithSubactivity.h"
|
||||
|
||||
#include <HalPowerManager.h>
|
||||
|
||||
void ActivityWithSubactivity::renderTaskLoop() {
|
||||
while (true) {
|
||||
ulTaskNotifyTake(pdTRUE, portMAX_DELAY);
|
||||
{
|
||||
HalPowerManager::Lock powerLock; // Ensure we don't go into low-power mode while rendering
|
||||
RenderLock lock(*this);
|
||||
if (!subActivity) {
|
||||
render(std::move(lock));
|
||||
}
|
||||
// If subActivity is set, consume the notification but skip parent render
|
||||
// Note: the sub-activity will call its render() from its own display task
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void ActivityWithSubactivity::exitActivity() {
|
||||
// No need to lock, since onExit() already acquires its own lock
|
||||
if (subActivity) {
|
||||
LOG_DBG("ACT", "Exiting subactivity...");
|
||||
subActivity->onExit();
|
||||
subActivity.reset();
|
||||
}
|
||||
}
|
||||
|
||||
void ActivityWithSubactivity::enterNewActivity(Activity* activity) {
|
||||
// Acquire lock to avoid 2 activities rendering at the same time during transition
|
||||
RenderLock lock(*this);
|
||||
subActivity.reset(activity);
|
||||
subActivity->onEnter();
|
||||
}
|
||||
|
||||
void ActivityWithSubactivity::loop() {
|
||||
if (subActivity) {
|
||||
subActivity->loop();
|
||||
}
|
||||
}
|
||||
|
||||
void ActivityWithSubactivity::requestUpdate() {
|
||||
if (!subActivity) {
|
||||
Activity::requestUpdate();
|
||||
}
|
||||
// Sub-activity should call their own requestUpdate() from their loop() function
|
||||
}
|
||||
|
||||
void ActivityWithSubactivity::onExit() {
|
||||
// No need to lock, onExit() already acquires its own lock
|
||||
exitActivity();
|
||||
Activity::onExit();
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
#pragma once
|
||||
#include <memory>
|
||||
|
||||
#include "Activity.h"
|
||||
|
||||
class ActivityWithSubactivity : public Activity {
|
||||
protected:
|
||||
std::unique_ptr<Activity> subActivity = nullptr;
|
||||
void exitActivity();
|
||||
void enterNewActivity(Activity* activity);
|
||||
[[noreturn]] void renderTaskLoop() override;
|
||||
|
||||
public:
|
||||
explicit ActivityWithSubactivity(std::string name, GfxRenderer& renderer, MappedInputManager& mappedInput)
|
||||
: Activity(std::move(name), renderer, mappedInput) {}
|
||||
void loop() override;
|
||||
// Note: when a subactivity is active, parent requestUpdate() calls are ignored;
|
||||
// the subactivity should request its own renders. This pauses parent rendering until exit.
|
||||
void requestUpdate() override;
|
||||
void onExit() override;
|
||||
};
|
||||
@@ -0,0 +1,16 @@
|
||||
#pragma once
|
||||
|
||||
class Activity; // forward declaration
|
||||
|
||||
// RAII helper to lock rendering mutex for the duration of a scope.
|
||||
class RenderLock {
|
||||
bool isLocked = false;
|
||||
|
||||
public:
|
||||
explicit RenderLock();
|
||||
explicit RenderLock(Activity&); // unused for now, but keep for compatibility
|
||||
RenderLock(const RenderLock&) = delete;
|
||||
RenderLock& operator=(const RenderLock&) = delete;
|
||||
~RenderLock();
|
||||
void unlock();
|
||||
};
|
||||
@@ -21,7 +21,7 @@ constexpr int PAGE_ITEMS = 23;
|
||||
} // namespace
|
||||
|
||||
void OpdsBookBrowserActivity::onEnter() {
|
||||
ActivityWithSubactivity::onEnter();
|
||||
Activity::onEnter();
|
||||
|
||||
state = BrowserState::CHECK_WIFI;
|
||||
entries.clear();
|
||||
@@ -37,7 +37,7 @@ void OpdsBookBrowserActivity::onEnter() {
|
||||
}
|
||||
|
||||
void OpdsBookBrowserActivity::onExit() {
|
||||
ActivityWithSubactivity::onExit();
|
||||
Activity::onExit();
|
||||
|
||||
// Turn off WiFi when exiting
|
||||
WiFi.mode(WIFI_OFF);
|
||||
@@ -49,7 +49,7 @@ void OpdsBookBrowserActivity::onExit() {
|
||||
void OpdsBookBrowserActivity::loop() {
|
||||
// Handle WiFi selection subactivity
|
||||
if (state == BrowserState::WIFI_SELECTION) {
|
||||
ActivityWithSubactivity::loop();
|
||||
// Should already handled by the WifiSelectionActivity
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -136,7 +136,7 @@ void OpdsBookBrowserActivity::loop() {
|
||||
}
|
||||
}
|
||||
|
||||
void OpdsBookBrowserActivity::render(Activity::RenderLock&&) {
|
||||
void OpdsBookBrowserActivity::render(RenderLock&&) {
|
||||
renderer.clearScreen();
|
||||
|
||||
const auto pageWidth = renderer.getScreenWidth();
|
||||
@@ -279,7 +279,7 @@ void OpdsBookBrowserActivity::navigateToEntry(const OpdsEntry& entry) {
|
||||
statusMessage = tr(STR_LOADING);
|
||||
entries.clear();
|
||||
selectorIndex = 0;
|
||||
requestUpdate();
|
||||
requestUpdate(true); // Force update to show loading state immediately before fetch
|
||||
|
||||
fetchFeed(currentPath);
|
||||
}
|
||||
@@ -308,7 +308,7 @@ void OpdsBookBrowserActivity::downloadBook(const OpdsEntry& book) {
|
||||
statusMessage = book.title;
|
||||
downloadProgress = 0;
|
||||
downloadTotal = 0;
|
||||
requestUpdate();
|
||||
requestUpdate(true);
|
||||
|
||||
// Build full download URL
|
||||
std::string downloadUrl = UrlUtils::buildUrl(SETTINGS.opdsServerUrl, book.href);
|
||||
@@ -326,7 +326,7 @@ void OpdsBookBrowserActivity::downloadBook(const OpdsEntry& book) {
|
||||
HttpDownloader::downloadToFile(downloadUrl, filename, [this](const size_t downloaded, const size_t total) {
|
||||
downloadProgress = downloaded;
|
||||
downloadTotal = total;
|
||||
requestUpdate();
|
||||
requestUpdate(true); // Force update to refresh progress bar
|
||||
});
|
||||
|
||||
if (result == HttpDownloader::OK) {
|
||||
@@ -364,18 +364,16 @@ void OpdsBookBrowserActivity::launchWifiSelection() {
|
||||
state = BrowserState::WIFI_SELECTION;
|
||||
requestUpdate();
|
||||
|
||||
enterNewActivity(new WifiSelectionActivity(renderer, mappedInput,
|
||||
[this](const bool connected) { onWifiSelectionComplete(connected); }));
|
||||
startActivityForResult(std::make_unique<WifiSelectionActivity>(renderer, mappedInput),
|
||||
[this](const ActivityResult& result) { onWifiSelectionComplete(!result.isCancelled); });
|
||||
}
|
||||
|
||||
void OpdsBookBrowserActivity::onWifiSelectionComplete(const bool connected) {
|
||||
exitActivity();
|
||||
|
||||
if (connected) {
|
||||
LOG_DBG("OPDS", "WiFi connected via selection, fetching feed");
|
||||
state = BrowserState::LOADING;
|
||||
statusMessage = tr(STR_LOADING);
|
||||
requestUpdate();
|
||||
requestUpdate(true); // Force update to show loading state immediately before fetch
|
||||
fetchFeed(currentPath);
|
||||
} else {
|
||||
LOG_DBG("OPDS", "WiFi selection cancelled/failed");
|
||||
@@ -385,6 +383,5 @@ void OpdsBookBrowserActivity::onWifiSelectionComplete(const bool connected) {
|
||||
WiFi.mode(WIFI_OFF);
|
||||
state = BrowserState::ERROR;
|
||||
errorMessage = tr(STR_WIFI_CONN_FAILED);
|
||||
requestUpdate();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "../ActivityWithSubactivity.h"
|
||||
#include "../Activity.h"
|
||||
#include "util/ButtonNavigator.h"
|
||||
|
||||
/**
|
||||
@@ -13,7 +13,7 @@
|
||||
* Supports navigation through catalog hierarchy and downloading EPUBs.
|
||||
* When WiFi connection fails, launches WiFi selection to let user connect.
|
||||
*/
|
||||
class OpdsBookBrowserActivity final : public ActivityWithSubactivity {
|
||||
class OpdsBookBrowserActivity final : public Activity {
|
||||
public:
|
||||
enum class BrowserState {
|
||||
CHECK_WIFI, // Checking WiFi connection
|
||||
@@ -24,14 +24,13 @@ class OpdsBookBrowserActivity final : public ActivityWithSubactivity {
|
||||
ERROR // Error state with message
|
||||
};
|
||||
|
||||
explicit OpdsBookBrowserActivity(GfxRenderer& renderer, MappedInputManager& mappedInput,
|
||||
const std::function<void()>& onGoHome)
|
||||
: ActivityWithSubactivity("OpdsBookBrowser", renderer, mappedInput), onGoHome(onGoHome) {}
|
||||
explicit OpdsBookBrowserActivity(GfxRenderer& renderer, MappedInputManager& mappedInput)
|
||||
: Activity("OpdsBookBrowser", renderer, mappedInput) {}
|
||||
|
||||
void onEnter() override;
|
||||
void onExit() override;
|
||||
void loop() override;
|
||||
void render(Activity::RenderLock&&) override;
|
||||
void render(RenderLock&&) override;
|
||||
|
||||
private:
|
||||
ButtonNavigator buttonNavigator;
|
||||
@@ -45,8 +44,6 @@ class OpdsBookBrowserActivity final : public ActivityWithSubactivity {
|
||||
size_t downloadProgress = 0;
|
||||
size_t downloadTotal = 0;
|
||||
|
||||
const std::function<void()> onGoHome;
|
||||
|
||||
void checkAndConnectWifi();
|
||||
void launchWifiSelection();
|
||||
void onWifiSelectionComplete(bool connected);
|
||||
|
||||
@@ -211,7 +211,7 @@ void HomeActivity::loop() {
|
||||
}
|
||||
}
|
||||
|
||||
void HomeActivity::render(Activity::RenderLock&&) {
|
||||
void HomeActivity::render(RenderLock&&) {
|
||||
const auto& metrics = UITheme::getInstance().getMetrics();
|
||||
const auto pageWidth = renderer.getScreenWidth();
|
||||
const auto pageHeight = renderer.getScreenHeight();
|
||||
@@ -258,3 +258,15 @@ void HomeActivity::render(Activity::RenderLock&&) {
|
||||
loadRecentCovers(metrics.homeCoverHeight);
|
||||
}
|
||||
}
|
||||
|
||||
void HomeActivity::onSelectBook(const std::string& path) { activityManager.goToReader(path); }
|
||||
|
||||
void HomeActivity::onMyLibraryOpen() { activityManager.goToMyLibrary(); }
|
||||
|
||||
void HomeActivity::onRecentsOpen() { activityManager.goToRecentBooks(); }
|
||||
|
||||
void HomeActivity::onSettingsOpen() { activityManager.goToSettings(); }
|
||||
|
||||
void HomeActivity::onFileTransferOpen() { activityManager.goToFileTransfer(); }
|
||||
|
||||
void HomeActivity::onOpdsBrowserOpen() { activityManager.goToBrowser(); }
|
||||
|
||||
@@ -20,12 +20,12 @@ class HomeActivity final : public Activity {
|
||||
bool coverBufferStored = false; // Track if cover buffer is stored
|
||||
uint8_t* coverBuffer = nullptr; // HomeActivity's own buffer for cover image
|
||||
std::vector<RecentBook> recentBooks;
|
||||
const std::function<void(const std::string& path)> onSelectBook;
|
||||
const std::function<void()> onMyLibraryOpen;
|
||||
const std::function<void()> onRecentsOpen;
|
||||
const std::function<void()> onSettingsOpen;
|
||||
const std::function<void()> onFileTransferOpen;
|
||||
const std::function<void()> onOpdsBrowserOpen;
|
||||
void onSelectBook(const std::string& path);
|
||||
void onMyLibraryOpen();
|
||||
void onRecentsOpen();
|
||||
void onSettingsOpen();
|
||||
void onFileTransferOpen();
|
||||
void onOpdsBrowserOpen();
|
||||
|
||||
int getMenuItemCount() const;
|
||||
bool storeCoverBuffer(); // Store frame buffer for cover image
|
||||
@@ -35,20 +35,10 @@ class HomeActivity final : public Activity {
|
||||
void loadRecentCovers(int coverHeight);
|
||||
|
||||
public:
|
||||
explicit HomeActivity(GfxRenderer& renderer, MappedInputManager& mappedInput,
|
||||
const std::function<void(const std::string& path)>& onSelectBook,
|
||||
const std::function<void()>& onMyLibraryOpen, const std::function<void()>& onRecentsOpen,
|
||||
const std::function<void()>& onSettingsOpen, const std::function<void()>& onFileTransferOpen,
|
||||
const std::function<void()>& onOpdsBrowserOpen)
|
||||
: Activity("Home", renderer, mappedInput),
|
||||
onSelectBook(onSelectBook),
|
||||
onMyLibraryOpen(onMyLibraryOpen),
|
||||
onRecentsOpen(onRecentsOpen),
|
||||
onSettingsOpen(onSettingsOpen),
|
||||
onFileTransferOpen(onFileTransferOpen),
|
||||
onOpdsBrowserOpen(onOpdsBrowserOpen) {}
|
||||
explicit HomeActivity(GfxRenderer& renderer, MappedInputManager& mappedInput)
|
||||
: Activity("Home", renderer, mappedInput) {}
|
||||
void onEnter() override;
|
||||
void onExit() override;
|
||||
void loop() override;
|
||||
void render(Activity::RenderLock&&) override;
|
||||
void render(RenderLock&&) override;
|
||||
};
|
||||
|
||||
@@ -196,7 +196,7 @@ std::string getFileName(std::string filename) {
|
||||
return filename.substr(0, pos);
|
||||
}
|
||||
|
||||
void MyLibraryActivity::render(Activity::RenderLock&&) {
|
||||
void MyLibraryActivity::render(RenderLock&&) {
|
||||
renderer.clearScreen();
|
||||
|
||||
const auto pageWidth = renderer.getScreenWidth();
|
||||
|
||||
@@ -17,25 +17,15 @@ class MyLibraryActivity final : public Activity {
|
||||
std::string basepath = "/";
|
||||
std::vector<std::string> files;
|
||||
|
||||
// Callbacks
|
||||
const std::function<void(const std::string& path)> onSelectBook;
|
||||
const std::function<void()> onGoHome;
|
||||
|
||||
// Data loading
|
||||
void loadFiles();
|
||||
size_t findEntry(const std::string& name) const;
|
||||
|
||||
public:
|
||||
explicit MyLibraryActivity(GfxRenderer& renderer, MappedInputManager& mappedInput,
|
||||
const std::function<void()>& onGoHome,
|
||||
const std::function<void(const std::string& path)>& onSelectBook,
|
||||
std::string initialPath = "/")
|
||||
: Activity("MyLibrary", renderer, mappedInput),
|
||||
basepath(initialPath.empty() ? "/" : std::move(initialPath)),
|
||||
onSelectBook(onSelectBook),
|
||||
onGoHome(onGoHome) {}
|
||||
explicit MyLibraryActivity(GfxRenderer& renderer, MappedInputManager& mappedInput, std::string initialPath = "/")
|
||||
: Activity("MyLibrary", renderer, mappedInput), basepath(initialPath.empty() ? "/" : std::move(initialPath)) {}
|
||||
void onEnter() override;
|
||||
void onExit() override;
|
||||
void loop() override;
|
||||
void render(Activity::RenderLock&&) override;
|
||||
void render(RenderLock&&) override;
|
||||
};
|
||||
|
||||
@@ -83,7 +83,7 @@ void RecentBooksActivity::loop() {
|
||||
});
|
||||
}
|
||||
|
||||
void RecentBooksActivity::render(Activity::RenderLock&&) {
|
||||
void RecentBooksActivity::render(RenderLock&&) {
|
||||
renderer.clearScreen();
|
||||
|
||||
const auto pageWidth = renderer.getScreenWidth();
|
||||
|
||||
@@ -18,20 +18,14 @@ class RecentBooksActivity final : public Activity {
|
||||
// Recent tab state
|
||||
std::vector<RecentBook> recentBooks;
|
||||
|
||||
// Callbacks
|
||||
const std::function<void(const std::string& path)> onSelectBook;
|
||||
const std::function<void()> onGoHome;
|
||||
|
||||
// Data loading
|
||||
void loadRecentBooks();
|
||||
|
||||
public:
|
||||
explicit RecentBooksActivity(GfxRenderer& renderer, MappedInputManager& mappedInput,
|
||||
const std::function<void()>& onGoHome,
|
||||
const std::function<void(const std::string& path)>& onSelectBook)
|
||||
: Activity("RecentBooks", renderer, mappedInput), onSelectBook(onSelectBook), onGoHome(onGoHome) {}
|
||||
explicit RecentBooksActivity(GfxRenderer& renderer, MappedInputManager& mappedInput)
|
||||
: Activity("RecentBooks", renderer, mappedInput) {}
|
||||
void onEnter() override;
|
||||
void onExit() override;
|
||||
void loop() override;
|
||||
void render(Activity::RenderLock&&) override;
|
||||
void render(RenderLock&&) override;
|
||||
};
|
||||
|
||||
@@ -16,7 +16,7 @@ constexpr const char* HOSTNAME = "crosspoint";
|
||||
} // namespace
|
||||
|
||||
void CalibreConnectActivity::onEnter() {
|
||||
ActivityWithSubactivity::onEnter();
|
||||
Activity::onEnter();
|
||||
|
||||
requestUpdate();
|
||||
state = CalibreConnectState::WIFI_SELECTION;
|
||||
@@ -28,11 +28,19 @@ void CalibreConnectActivity::onEnter() {
|
||||
currentUploadName.clear();
|
||||
lastCompleteName.clear();
|
||||
lastCompleteAt = 0;
|
||||
lastProcessedCompleteAt = 0;
|
||||
exitRequested = false;
|
||||
|
||||
if (WiFi.status() != WL_CONNECTED) {
|
||||
enterNewActivity(new WifiSelectionActivity(renderer, mappedInput,
|
||||
[this](const bool connected) { onWifiSelectionComplete(connected); }));
|
||||
startActivityForResult(std::make_unique<WifiSelectionActivity>(renderer, mappedInput),
|
||||
[this](const ActivityResult& result) {
|
||||
if (!result.isCancelled) {
|
||||
const auto& wifi = std::get<WifiResult>(result.data);
|
||||
connectedIP = wifi.ip;
|
||||
connectedSSID = wifi.ssid;
|
||||
}
|
||||
onWifiSelectionComplete(!result.isCancelled);
|
||||
});
|
||||
} else {
|
||||
connectedIP = WiFi.localIP().toString().c_str();
|
||||
connectedSSID = WiFi.SSID().c_str();
|
||||
@@ -41,7 +49,7 @@ void CalibreConnectActivity::onEnter() {
|
||||
}
|
||||
|
||||
void CalibreConnectActivity::onExit() {
|
||||
ActivityWithSubactivity::onExit();
|
||||
Activity::onExit();
|
||||
|
||||
stopWebServer();
|
||||
MDNS.end();
|
||||
@@ -55,18 +63,10 @@ void CalibreConnectActivity::onExit() {
|
||||
|
||||
void CalibreConnectActivity::onWifiSelectionComplete(const bool connected) {
|
||||
if (!connected) {
|
||||
exitActivity();
|
||||
onComplete();
|
||||
activityManager.popActivity();
|
||||
return;
|
||||
}
|
||||
|
||||
if (subActivity) {
|
||||
connectedIP = static_cast<WifiSelectionActivity*>(subActivity.get())->getConnectedIP();
|
||||
} else {
|
||||
connectedIP = WiFi.localIP().toString().c_str();
|
||||
}
|
||||
connectedSSID = WiFi.SSID().c_str();
|
||||
exitActivity();
|
||||
startWebServer();
|
||||
}
|
||||
|
||||
@@ -99,11 +99,6 @@ void CalibreConnectActivity::stopWebServer() {
|
||||
}
|
||||
|
||||
void CalibreConnectActivity::loop() {
|
||||
if (subActivity) {
|
||||
subActivity->loop();
|
||||
return;
|
||||
}
|
||||
|
||||
if (mappedInput.wasPressed(MappedInputManager::Button::Back)) {
|
||||
exitRequested = true;
|
||||
}
|
||||
@@ -147,14 +142,18 @@ void CalibreConnectActivity::loop() {
|
||||
currentUploadName.clear();
|
||||
changed = true;
|
||||
}
|
||||
if (status.lastCompleteAt != 0 && status.lastCompleteAt != lastCompleteAt) {
|
||||
// Only update lastCompleteAt if the server has a NEW value (not one we already processed)
|
||||
// This prevents restoring an old value after the 6s timeout clears it
|
||||
if (status.lastCompleteAt != 0 && status.lastCompleteAt != lastProcessedCompleteAt) {
|
||||
lastCompleteAt = status.lastCompleteAt;
|
||||
lastCompleteName = status.lastCompleteName;
|
||||
lastProcessedCompleteAt = status.lastCompleteAt; // Mark this value as processed
|
||||
changed = true;
|
||||
}
|
||||
if (lastCompleteAt > 0 && (millis() - lastCompleteAt) >= 6000) {
|
||||
lastCompleteAt = 0;
|
||||
lastCompleteName.clear();
|
||||
// Note: we DON'T reset lastProcessedCompleteAt here, so we won't re-process the old server value
|
||||
changed = true;
|
||||
}
|
||||
if (changed) {
|
||||
@@ -163,12 +162,12 @@ void CalibreConnectActivity::loop() {
|
||||
}
|
||||
|
||||
if (exitRequested) {
|
||||
onComplete();
|
||||
activityManager.popActivity();
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
void CalibreConnectActivity::render(Activity::RenderLock&&) {
|
||||
void CalibreConnectActivity::render(RenderLock&&) {
|
||||
const auto& metrics = UITheme::getInstance().getMetrics();
|
||||
const auto pageWidth = renderer.getScreenWidth();
|
||||
const auto pageHeight = renderer.getScreenHeight();
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
#include <memory>
|
||||
#include <string>
|
||||
|
||||
#include "activities/ActivityWithSubactivity.h"
|
||||
#include "activities/Activity.h"
|
||||
#include "network/CrossPointWebServer.h"
|
||||
|
||||
enum class CalibreConnectState { WIFI_SELECTION, SERVER_STARTING, SERVER_RUNNING, ERROR };
|
||||
@@ -13,9 +13,8 @@ enum class CalibreConnectState { WIFI_SELECTION, SERVER_STARTING, SERVER_RUNNING
|
||||
* CalibreConnectActivity starts the file transfer server in STA mode,
|
||||
* but renders Calibre-specific instructions instead of the web transfer UI.
|
||||
*/
|
||||
class CalibreConnectActivity final : public ActivityWithSubactivity {
|
||||
class CalibreConnectActivity final : public Activity {
|
||||
CalibreConnectState state = CalibreConnectState::WIFI_SELECTION;
|
||||
const std::function<void()> onComplete;
|
||||
|
||||
std::unique_ptr<CrossPointWebServer> webServer;
|
||||
std::string connectedIP;
|
||||
@@ -26,6 +25,7 @@ class CalibreConnectActivity final : public ActivityWithSubactivity {
|
||||
std::string currentUploadName;
|
||||
std::string lastCompleteName;
|
||||
unsigned long lastCompleteAt = 0;
|
||||
unsigned long lastProcessedCompleteAt = 0; // Track which server value we've already processed
|
||||
bool exitRequested = false;
|
||||
|
||||
void renderServerRunning() const;
|
||||
@@ -35,13 +35,12 @@ class CalibreConnectActivity final : public ActivityWithSubactivity {
|
||||
void stopWebServer();
|
||||
|
||||
public:
|
||||
explicit CalibreConnectActivity(GfxRenderer& renderer, MappedInputManager& mappedInput,
|
||||
const std::function<void()>& onComplete)
|
||||
: ActivityWithSubactivity("CalibreConnect", renderer, mappedInput), onComplete(onComplete) {}
|
||||
explicit CalibreConnectActivity(GfxRenderer& renderer, MappedInputManager& mappedInput)
|
||||
: Activity("CalibreConnect", renderer, mappedInput) {}
|
||||
void onEnter() override;
|
||||
void onExit() override;
|
||||
void loop() override;
|
||||
void render(Activity::RenderLock&&) override;
|
||||
void render(RenderLock&&) override;
|
||||
bool skipLoopDelay() override { return webServer && webServer->isRunning(); }
|
||||
bool preventAutoSleep() override { return webServer && webServer->isRunning(); }
|
||||
};
|
||||
|
||||
@@ -33,7 +33,7 @@ constexpr uint16_t DNS_PORT = 53;
|
||||
} // namespace
|
||||
|
||||
void CrossPointWebServerActivity::onEnter() {
|
||||
ActivityWithSubactivity::onEnter();
|
||||
Activity::onEnter();
|
||||
|
||||
LOG_DBG("WEBACT", "Free heap at onEnter: %d bytes", ESP.getFreeHeap());
|
||||
|
||||
@@ -48,14 +48,18 @@ void CrossPointWebServerActivity::onEnter() {
|
||||
|
||||
// Launch network mode selection subactivity
|
||||
LOG_DBG("WEBACT", "Launching NetworkModeSelectionActivity...");
|
||||
enterNewActivity(new NetworkModeSelectionActivity(
|
||||
renderer, mappedInput, [this](const NetworkMode mode) { onNetworkModeSelected(mode); },
|
||||
[this]() { onGoBack(); } // Cancel goes back to home
|
||||
));
|
||||
startActivityForResult(std::make_unique<NetworkModeSelectionActivity>(renderer, mappedInput),
|
||||
[this](const ActivityResult& result) {
|
||||
if (result.isCancelled) {
|
||||
onGoHome();
|
||||
} else {
|
||||
onNetworkModeSelected(std::get<NetworkModeResult>(result.data).mode);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
void CrossPointWebServerActivity::onExit() {
|
||||
ActivityWithSubactivity::onExit();
|
||||
Activity::onExit();
|
||||
|
||||
LOG_DBG("WEBACT", "Free heap at onExit start: %d bytes", ESP.getFreeHeap());
|
||||
|
||||
@@ -107,18 +111,20 @@ void CrossPointWebServerActivity::onNetworkModeSelected(const NetworkMode mode)
|
||||
networkMode = mode;
|
||||
isApMode = (mode == NetworkMode::CREATE_HOTSPOT);
|
||||
|
||||
// Exit mode selection subactivity
|
||||
exitActivity();
|
||||
|
||||
if (mode == NetworkMode::CONNECT_CALIBRE) {
|
||||
exitActivity();
|
||||
enterNewActivity(new CalibreConnectActivity(renderer, mappedInput, [this] {
|
||||
exitActivity();
|
||||
state = WebServerActivityState::MODE_SELECTION;
|
||||
enterNewActivity(new NetworkModeSelectionActivity(
|
||||
renderer, mappedInput, [this](const NetworkMode nextMode) { onNetworkModeSelected(nextMode); },
|
||||
[this]() { onGoBack(); }));
|
||||
}));
|
||||
startActivityForResult(
|
||||
std::make_unique<CalibreConnectActivity>(renderer, mappedInput), [this](const ActivityResult& result) {
|
||||
state = WebServerActivityState::MODE_SELECTION;
|
||||
|
||||
startActivityForResult(std::make_unique<NetworkModeSelectionActivity>(renderer, mappedInput),
|
||||
[this](const ActivityResult& result) {
|
||||
if (result.isCancelled) {
|
||||
onGoHome();
|
||||
} else {
|
||||
onNetworkModeSelected(std::get<NetworkModeResult>(result.data).mode);
|
||||
}
|
||||
});
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -129,8 +135,15 @@ void CrossPointWebServerActivity::onNetworkModeSelected(const NetworkMode mode)
|
||||
|
||||
state = WebServerActivityState::WIFI_SELECTION;
|
||||
LOG_DBG("WEBACT", "Launching WifiSelectionActivity...");
|
||||
enterNewActivity(new WifiSelectionActivity(renderer, mappedInput,
|
||||
[this](const bool connected) { onWifiSelectionComplete(connected); }));
|
||||
startActivityForResult(std::make_unique<WifiSelectionActivity>(renderer, mappedInput),
|
||||
[this](const ActivityResult& result) {
|
||||
if (!result.isCancelled) {
|
||||
const auto& wifi = std::get<WifiResult>(result.data);
|
||||
connectedIP = wifi.ip;
|
||||
connectedSSID = wifi.ssid;
|
||||
}
|
||||
onWifiSelectionComplete(!result.isCancelled);
|
||||
});
|
||||
} else {
|
||||
// AP mode - start access point
|
||||
state = WebServerActivityState::AP_STARTING;
|
||||
@@ -144,12 +157,8 @@ void CrossPointWebServerActivity::onWifiSelectionComplete(const bool connected)
|
||||
|
||||
if (connected) {
|
||||
// Get connection info before exiting subactivity
|
||||
connectedIP = static_cast<WifiSelectionActivity*>(subActivity.get())->getConnectedIP();
|
||||
connectedSSID = WiFi.SSID().c_str();
|
||||
isApMode = false;
|
||||
|
||||
exitActivity();
|
||||
|
||||
// Start mDNS for hostname resolution
|
||||
if (MDNS.begin(AP_HOSTNAME)) {
|
||||
LOG_DBG("WEBACT", "mDNS started: http://%s.local/", AP_HOSTNAME);
|
||||
@@ -159,11 +168,16 @@ void CrossPointWebServerActivity::onWifiSelectionComplete(const bool connected)
|
||||
startWebServer();
|
||||
} else {
|
||||
// User cancelled - go back to mode selection
|
||||
exitActivity();
|
||||
state = WebServerActivityState::MODE_SELECTION;
|
||||
enterNewActivity(new NetworkModeSelectionActivity(
|
||||
renderer, mappedInput, [this](const NetworkMode mode) { onNetworkModeSelected(mode); },
|
||||
[this]() { onGoBack(); }));
|
||||
|
||||
startActivityForResult(std::make_unique<NetworkModeSelectionActivity>(renderer, mappedInput),
|
||||
[this](const ActivityResult& result) {
|
||||
if (result.isCancelled) {
|
||||
onGoHome();
|
||||
} else {
|
||||
onNetworkModeSelected(std::get<NetworkModeResult>(result.data).mode);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -186,7 +200,7 @@ void CrossPointWebServerActivity::startAccessPoint() {
|
||||
|
||||
if (!apStarted) {
|
||||
LOG_ERR("WEBACT", "ERROR: Failed to start Access Point!");
|
||||
onGoBack();
|
||||
onGoHome();
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -236,16 +250,12 @@ void CrossPointWebServerActivity::startWebServer() {
|
||||
|
||||
// Force an immediate render since we're transitioning from a subactivity
|
||||
// that had its own rendering task. We need to make sure our display is shown.
|
||||
{
|
||||
RenderLock lock(*this);
|
||||
render(std::move(lock));
|
||||
}
|
||||
LOG_DBG("WEBACT", "Rendered File Transfer screen");
|
||||
requestUpdate();
|
||||
} else {
|
||||
LOG_ERR("WEBACT", "ERROR: Failed to start web server!");
|
||||
webServer.reset();
|
||||
// Go back on error
|
||||
onGoBack();
|
||||
onGoHome();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -259,12 +269,6 @@ void CrossPointWebServerActivity::stopWebServer() {
|
||||
}
|
||||
|
||||
void CrossPointWebServerActivity::loop() {
|
||||
if (subActivity) {
|
||||
// Forward loop to subactivity
|
||||
subActivity->loop();
|
||||
return;
|
||||
}
|
||||
|
||||
// Handle different states
|
||||
if (state == WebServerActivityState::SERVER_RUNNING) {
|
||||
// Handle DNS requests for captive portal (AP mode only)
|
||||
@@ -322,7 +326,7 @@ void CrossPointWebServerActivity::loop() {
|
||||
mappedInput.update();
|
||||
// Check for exit button inside loop for responsiveness
|
||||
if (mappedInput.wasPressed(MappedInputManager::Button::Back)) {
|
||||
onGoBack();
|
||||
onGoHome();
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -332,13 +336,13 @@ void CrossPointWebServerActivity::loop() {
|
||||
|
||||
// Handle exit on Back button (also check outside loop)
|
||||
if (mappedInput.wasPressed(MappedInputManager::Button::Back)) {
|
||||
onGoBack();
|
||||
onGoHome();
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void CrossPointWebServerActivity::render(Activity::RenderLock&&) {
|
||||
void CrossPointWebServerActivity::render(RenderLock&&) {
|
||||
// Only render our own UI when server is running
|
||||
// Subactivities handle their own rendering
|
||||
if (state == WebServerActivityState::SERVER_RUNNING || state == WebServerActivityState::AP_STARTING) {
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
#include <string>
|
||||
|
||||
#include "NetworkModeSelectionActivity.h"
|
||||
#include "activities/ActivityWithSubactivity.h"
|
||||
#include "activities/Activity.h"
|
||||
#include "network/CrossPointWebServer.h"
|
||||
|
||||
// Web server activity states
|
||||
@@ -27,9 +27,8 @@ enum class WebServerActivityState {
|
||||
* - Handles client requests in its loop() function
|
||||
* - Cleans up the server and shuts down WiFi on exit
|
||||
*/
|
||||
class CrossPointWebServerActivity final : public ActivityWithSubactivity {
|
||||
class CrossPointWebServerActivity final : public Activity {
|
||||
WebServerActivityState state = WebServerActivityState::MODE_SELECTION;
|
||||
const std::function<void()> onGoBack;
|
||||
|
||||
// Network mode
|
||||
NetworkMode networkMode = NetworkMode::JOIN_NETWORK;
|
||||
@@ -54,13 +53,12 @@ class CrossPointWebServerActivity final : public ActivityWithSubactivity {
|
||||
void stopWebServer();
|
||||
|
||||
public:
|
||||
explicit CrossPointWebServerActivity(GfxRenderer& renderer, MappedInputManager& mappedInput,
|
||||
const std::function<void()>& onGoBack)
|
||||
: ActivityWithSubactivity("CrossPointWebServer", renderer, mappedInput), onGoBack(onGoBack) {}
|
||||
explicit CrossPointWebServerActivity(GfxRenderer& renderer, MappedInputManager& mappedInput)
|
||||
: Activity("CrossPointWebServer", renderer, mappedInput) {}
|
||||
void onEnter() override;
|
||||
void onExit() override;
|
||||
void loop() override;
|
||||
void render(Activity::RenderLock&&) override;
|
||||
void render(RenderLock&&) override;
|
||||
bool skipLoopDelay() override { return webServer && webServer->isRunning(); }
|
||||
bool preventAutoSleep() override { return webServer && webServer->isRunning(); }
|
||||
};
|
||||
|
||||
@@ -54,7 +54,7 @@ void NetworkModeSelectionActivity::loop() {
|
||||
});
|
||||
}
|
||||
|
||||
void NetworkModeSelectionActivity::render(Activity::RenderLock&&) {
|
||||
void NetworkModeSelectionActivity::render(RenderLock&&) {
|
||||
renderer.clearScreen();
|
||||
|
||||
const auto& metrics = UITheme::getInstance().getMetrics();
|
||||
@@ -83,3 +83,15 @@ void NetworkModeSelectionActivity::render(Activity::RenderLock&&) {
|
||||
|
||||
renderer.displayBuffer();
|
||||
}
|
||||
|
||||
void NetworkModeSelectionActivity::onModeSelected(NetworkMode mode) {
|
||||
setResult(NetworkModeResult{mode});
|
||||
finish();
|
||||
}
|
||||
|
||||
void NetworkModeSelectionActivity::onCancel() {
|
||||
ActivityResult result;
|
||||
result.isCancelled = true;
|
||||
setResult(std::move(result));
|
||||
finish();
|
||||
}
|
||||
|
||||
@@ -5,7 +5,6 @@
|
||||
#include "../Activity.h"
|
||||
#include "util/ButtonNavigator.h"
|
||||
|
||||
// Enum for network mode selection
|
||||
enum class NetworkMode { JOIN_NETWORK, CONNECT_CALIBRE, CREATE_HOTSPOT };
|
||||
|
||||
/**
|
||||
@@ -22,16 +21,14 @@ class NetworkModeSelectionActivity final : public Activity {
|
||||
|
||||
int selectedIndex = 0;
|
||||
|
||||
const std::function<void(NetworkMode)> onModeSelected;
|
||||
const std::function<void()> onCancel;
|
||||
|
||||
public:
|
||||
explicit NetworkModeSelectionActivity(GfxRenderer& renderer, MappedInputManager& mappedInput,
|
||||
const std::function<void(NetworkMode)>& onModeSelected,
|
||||
const std::function<void()>& onCancel)
|
||||
: Activity("NetworkModeSelection", renderer, mappedInput), onModeSelected(onModeSelected), onCancel(onCancel) {}
|
||||
explicit NetworkModeSelectionActivity(GfxRenderer& renderer, MappedInputManager& mappedInput)
|
||||
: Activity("NetworkModeSelection", renderer, mappedInput) {}
|
||||
void onEnter() override;
|
||||
void onExit() override;
|
||||
void loop() override;
|
||||
void render(Activity::RenderLock&&) override;
|
||||
void render(RenderLock&&) override;
|
||||
|
||||
void onModeSelected(NetworkMode mode);
|
||||
void onCancel();
|
||||
};
|
||||
|
||||
@@ -190,20 +190,19 @@ void WifiSelectionActivity::selectNetwork(const int index) {
|
||||
// Show password entry
|
||||
state = WifiSelectionState::PASSWORD_ENTRY;
|
||||
// Don't allow screen updates while changing activity
|
||||
enterNewActivity(new KeyboardEntryActivity(
|
||||
renderer, mappedInput, tr(STR_ENTER_WIFI_PASSWORD),
|
||||
"", // No initial text
|
||||
64, // Max password length
|
||||
false, // Show password by default (hard keyboard to use)
|
||||
[this](const std::string& text) {
|
||||
enteredPassword = text;
|
||||
exitActivity();
|
||||
},
|
||||
[this] {
|
||||
state = WifiSelectionState::NETWORK_LIST;
|
||||
exitActivity();
|
||||
requestUpdate();
|
||||
}));
|
||||
startActivityForResult(
|
||||
std::make_unique<KeyboardEntryActivity>(renderer, mappedInput, tr(STR_ENTER_WIFI_PASSWORD),
|
||||
"", // No initial text
|
||||
64, // Max password length
|
||||
false // Show password by default (hard keyboard to use)
|
||||
),
|
||||
[this](const ActivityResult& result) {
|
||||
if (result.isCancelled) {
|
||||
state = WifiSelectionState::NETWORK_LIST;
|
||||
} else {
|
||||
enteredPassword = std::get<KeyboardResult>(result.data).text;
|
||||
}
|
||||
});
|
||||
} else {
|
||||
// Connect directly for open networks
|
||||
attemptConnection();
|
||||
@@ -291,11 +290,6 @@ void WifiSelectionActivity::checkConnectionStatus() {
|
||||
}
|
||||
|
||||
void WifiSelectionActivity::loop() {
|
||||
if (subActivity) {
|
||||
subActivity->loop();
|
||||
return;
|
||||
}
|
||||
|
||||
// Check scan progress
|
||||
if (state == WifiSelectionState::SCANNING) {
|
||||
processWifiScanResults();
|
||||
@@ -467,7 +461,7 @@ std::string WifiSelectionActivity::getSignalStrengthIndicator(const int32_t rssi
|
||||
return " |"; // Very weak
|
||||
}
|
||||
|
||||
void WifiSelectionActivity::render(Activity::RenderLock&&) {
|
||||
void WifiSelectionActivity::render(RenderLock&&) {
|
||||
// Don't render if we're in PASSWORD_ENTRY state - we're just transitioning
|
||||
// from the keyboard subactivity back to the main activity
|
||||
if (state == WifiSelectionState::PASSWORD_ENTRY) {
|
||||
@@ -693,3 +687,13 @@ void WifiSelectionActivity::renderForgetPrompt() const {
|
||||
const auto labels = mappedInput.mapLabels(tr(STR_BACK), tr(STR_SELECT), tr(STR_DIR_LEFT), tr(STR_DIR_RIGHT));
|
||||
GUI.drawButtonHints(renderer, labels.btn1, labels.btn2, labels.btn3, labels.btn4);
|
||||
}
|
||||
|
||||
void WifiSelectionActivity::onComplete(const bool connected) {
|
||||
ActivityResult result;
|
||||
result.isCancelled = !connected;
|
||||
if (connected) {
|
||||
result.data = WifiResult{true, selectedSSID, connectedIP};
|
||||
}
|
||||
setResult(std::move(result));
|
||||
finish();
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "activities/ActivityWithSubactivity.h"
|
||||
#include "activities/Activity.h"
|
||||
#include "util/ButtonNavigator.h"
|
||||
|
||||
// Structure to hold WiFi network information
|
||||
@@ -15,6 +15,7 @@ struct WifiNetworkInfo {
|
||||
int32_t rssi;
|
||||
bool isEncrypted;
|
||||
bool hasSavedPassword; // Whether we have saved credentials for this network
|
||||
std::string ipAddress; // Populated after connection for display
|
||||
};
|
||||
|
||||
// WiFi selection states
|
||||
@@ -41,13 +42,12 @@ enum class WifiSelectionState {
|
||||
*
|
||||
* The onComplete callback receives true if connected successfully, false if cancelled.
|
||||
*/
|
||||
class WifiSelectionActivity final : public ActivityWithSubactivity {
|
||||
class WifiSelectionActivity final : public Activity {
|
||||
ButtonNavigator buttonNavigator;
|
||||
|
||||
WifiSelectionState state = WifiSelectionState::SCANNING;
|
||||
size_t selectedNetworkIndex = 0;
|
||||
std::vector<WifiNetworkInfo> networks;
|
||||
const std::function<void(bool connected)> onComplete;
|
||||
|
||||
// Selected network for connection
|
||||
std::string selectedSSID;
|
||||
@@ -95,17 +95,13 @@ class WifiSelectionActivity final : public ActivityWithSubactivity {
|
||||
void checkConnectionStatus();
|
||||
std::string getSignalStrengthIndicator(int32_t rssi) const;
|
||||
|
||||
void onComplete(bool connected);
|
||||
|
||||
public:
|
||||
explicit WifiSelectionActivity(GfxRenderer& renderer, MappedInputManager& mappedInput,
|
||||
const std::function<void(bool connected)>& onComplete, bool autoConnect = true)
|
||||
: ActivityWithSubactivity("WifiSelection", renderer, mappedInput),
|
||||
onComplete(onComplete),
|
||||
allowAutoConnect(autoConnect) {}
|
||||
explicit WifiSelectionActivity(GfxRenderer& renderer, MappedInputManager& mappedInput, bool autoConnect = true)
|
||||
: Activity("WifiSelection", renderer, mappedInput), allowAutoConnect(autoConnect) {}
|
||||
void onEnter() override;
|
||||
void onExit() override;
|
||||
void loop() override;
|
||||
void render(Activity::RenderLock&&) override;
|
||||
|
||||
// Get the IP address after successful connection
|
||||
const std::string& getConnectedIP() const { return connectedIP; }
|
||||
void render(RenderLock&&) override;
|
||||
};
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
#include "CrossPointSettings.h"
|
||||
#include "CrossPointState.h"
|
||||
#include "EpubReaderChapterSelectionActivity.h"
|
||||
#include "EpubReaderFootnotesActivity.h"
|
||||
#include "EpubReaderPercentSelectionActivity.h"
|
||||
#include "KOReaderCredentialStore.h"
|
||||
#include "KOReaderSyncActivity.h"
|
||||
@@ -60,7 +61,7 @@ void applyReaderOrientation(GfxRenderer& renderer, const uint8_t orientation) {
|
||||
} // namespace
|
||||
|
||||
void EpubReaderActivity::onEnter() {
|
||||
ActivityWithSubactivity::onEnter();
|
||||
Activity::onEnter();
|
||||
|
||||
if (!epub) {
|
||||
return;
|
||||
@@ -107,7 +108,7 @@ void EpubReaderActivity::onEnter() {
|
||||
}
|
||||
|
||||
void EpubReaderActivity::onExit() {
|
||||
ActivityWithSubactivity::onExit();
|
||||
Activity::onExit();
|
||||
|
||||
// Reset orientation back to portrait for the rest of the UI
|
||||
renderer.setOrientation(GfxRenderer::Orientation::Portrait);
|
||||
@@ -119,48 +120,9 @@ void EpubReaderActivity::onExit() {
|
||||
}
|
||||
|
||||
void EpubReaderActivity::loop() {
|
||||
// Pass input responsibility to sub activity if exists
|
||||
if (subActivity) {
|
||||
subActivity->loop();
|
||||
// Deferred exit: process after subActivity->loop() returns to avoid use-after-free
|
||||
if (pendingSubactivityExit) {
|
||||
pendingSubactivityExit = false;
|
||||
exitActivity();
|
||||
requestUpdate();
|
||||
skipNextButtonCheck = true; // Skip button processing to ignore stale events
|
||||
}
|
||||
// Deferred go home: process after subActivity->loop() returns to avoid race condition
|
||||
if (pendingGoHome) {
|
||||
pendingGoHome = false;
|
||||
exitActivity();
|
||||
if (onGoHome) {
|
||||
onGoHome();
|
||||
}
|
||||
return; // Don't access 'this' after callback
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Handle pending go home when no subactivity (e.g., from long press back)
|
||||
if (pendingGoHome) {
|
||||
pendingGoHome = false;
|
||||
if (onGoHome) {
|
||||
onGoHome();
|
||||
}
|
||||
return; // Don't access 'this' after callback
|
||||
}
|
||||
|
||||
// Skip button processing after returning from subactivity
|
||||
// This prevents stale button release events from triggering actions
|
||||
// We wait until: (1) all relevant buttons are released, AND (2) wasReleased events have been cleared
|
||||
if (skipNextButtonCheck) {
|
||||
const bool confirmCleared = !mappedInput.isPressed(MappedInputManager::Button::Confirm) &&
|
||||
!mappedInput.wasReleased(MappedInputManager::Button::Confirm);
|
||||
const bool backCleared = !mappedInput.isPressed(MappedInputManager::Button::Back) &&
|
||||
!mappedInput.wasReleased(MappedInputManager::Button::Back);
|
||||
if (confirmCleared && backCleared) {
|
||||
skipNextButtonCheck = false;
|
||||
}
|
||||
if (!epub) {
|
||||
// Should never happen
|
||||
finish();
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -169,26 +131,36 @@ void EpubReaderActivity::loop() {
|
||||
const int currentPage = section ? section->currentPage + 1 : 0;
|
||||
const int totalPages = section ? section->pageCount : 0;
|
||||
float bookProgress = 0.0f;
|
||||
if (epub && epub->getBookSize() > 0 && section && section->pageCount > 0) {
|
||||
if (epub->getBookSize() > 0 && section && section->pageCount > 0) {
|
||||
const float chapterProgress = static_cast<float>(section->currentPage) / static_cast<float>(section->pageCount);
|
||||
bookProgress = epub->calculateProgress(currentSpineIndex, chapterProgress) * 100.0f;
|
||||
}
|
||||
const int bookProgressPercent = clampPercent(static_cast<int>(bookProgress + 0.5f));
|
||||
exitActivity();
|
||||
enterNewActivity(new EpubReaderMenuActivity(
|
||||
this->renderer, this->mappedInput, epub->getTitle(), currentPage, totalPages, bookProgressPercent,
|
||||
SETTINGS.orientation, [this](const uint8_t orientation) { onReaderMenuBack(orientation); },
|
||||
[this](EpubReaderMenuActivity::MenuAction action) { onReaderMenuConfirm(action); }));
|
||||
startActivityForResult(std::make_unique<EpubReaderMenuActivity>(
|
||||
renderer, mappedInput, epub->getTitle(), currentPage, totalPages, bookProgressPercent,
|
||||
SETTINGS.orientation, !currentPageFootnotes.empty()),
|
||||
[this](const ActivityResult& result) {
|
||||
// Always apply orientation change even if the menu was cancelled
|
||||
const auto& menu = std::get<MenuResult>(result.data);
|
||||
applyOrientation(menu.orientation);
|
||||
if (!result.isCancelled) {
|
||||
onReaderMenuConfirm(static_cast<EpubReaderMenuActivity::MenuAction>(menu.action));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Long press BACK (1s+) goes to file selection
|
||||
if (mappedInput.isPressed(MappedInputManager::Button::Back) && mappedInput.getHeldTime() >= goHomeMs) {
|
||||
onGoBack();
|
||||
activityManager.goToMyLibrary(epub ? epub->getPath() : "");
|
||||
return;
|
||||
}
|
||||
|
||||
// Short press BACK goes directly to home
|
||||
// Short press BACK goes directly to home (or restores position if viewing footnote)
|
||||
if (mappedInput.wasReleased(MappedInputManager::Button::Back) && mappedInput.getHeldTime() < goHomeMs) {
|
||||
if (footnoteDepth > 0) {
|
||||
restoreSavedPosition();
|
||||
return;
|
||||
}
|
||||
onGoHome();
|
||||
return;
|
||||
}
|
||||
@@ -268,14 +240,6 @@ void EpubReaderActivity::loop() {
|
||||
}
|
||||
}
|
||||
|
||||
void EpubReaderActivity::onReaderMenuBack(const uint8_t orientation) {
|
||||
exitActivity();
|
||||
// Apply the user-selected orientation when the menu is dismissed.
|
||||
// This ensures the menu can be navigated without immediately rotating the screen.
|
||||
applyOrientation(orientation);
|
||||
requestUpdate();
|
||||
}
|
||||
|
||||
// Translate an absolute percent into a spine index plus a normalized position
|
||||
// within that spine so we can jump after the section is loaded.
|
||||
void EpubReaderActivity::jumpToPercent(int percent) {
|
||||
@@ -342,65 +306,44 @@ void EpubReaderActivity::jumpToPercent(int percent) {
|
||||
void EpubReaderActivity::onReaderMenuConfirm(EpubReaderMenuActivity::MenuAction action) {
|
||||
switch (action) {
|
||||
case EpubReaderMenuActivity::MenuAction::SELECT_CHAPTER: {
|
||||
// Calculate values BEFORE we start destroying things
|
||||
const int currentP = section ? section->currentPage : 0;
|
||||
const int totalP = section ? section->pageCount : 0;
|
||||
const int spineIdx = currentSpineIndex;
|
||||
const std::string path = epub->getPath();
|
||||
|
||||
// 1. Close the menu
|
||||
exitActivity();
|
||||
|
||||
// 2. Open the Chapter Selector
|
||||
enterNewActivity(new EpubReaderChapterSelectionActivity(
|
||||
this->renderer, this->mappedInput, epub, path, spineIdx, currentP, totalP,
|
||||
[this] {
|
||||
exitActivity();
|
||||
requestUpdate();
|
||||
},
|
||||
[this](const int newSpineIndex) {
|
||||
if (currentSpineIndex != newSpineIndex) {
|
||||
currentSpineIndex = newSpineIndex;
|
||||
startActivityForResult(
|
||||
std::make_unique<EpubReaderChapterSelectionActivity>(renderer, mappedInput, epub, path, spineIdx),
|
||||
[this](const ActivityResult& result) {
|
||||
if (!result.isCancelled && currentSpineIndex != std::get<ChapterResult>(result.data).spineIndex) {
|
||||
currentSpineIndex = std::get<ChapterResult>(result.data).spineIndex;
|
||||
nextPageNumber = 0;
|
||||
section.reset();
|
||||
}
|
||||
exitActivity();
|
||||
requestUpdate();
|
||||
},
|
||||
[this](const int newSpineIndex, const int newPage) {
|
||||
if (currentSpineIndex != newSpineIndex || (section && section->currentPage != newPage)) {
|
||||
currentSpineIndex = newSpineIndex;
|
||||
nextPageNumber = newPage;
|
||||
section.reset();
|
||||
}
|
||||
exitActivity();
|
||||
requestUpdate();
|
||||
}));
|
||||
|
||||
});
|
||||
break;
|
||||
}
|
||||
case EpubReaderMenuActivity::MenuAction::FOOTNOTES: {
|
||||
startActivityForResult(std::make_unique<EpubReaderFootnotesActivity>(renderer, mappedInput, currentPageFootnotes),
|
||||
[this](const ActivityResult& result) {
|
||||
if (!result.isCancelled) {
|
||||
const auto& footnoteResult = std::get<FootnoteResult>(result.data);
|
||||
navigateToHref(footnoteResult.href, true);
|
||||
}
|
||||
requestUpdate();
|
||||
});
|
||||
break;
|
||||
}
|
||||
case EpubReaderMenuActivity::MenuAction::GO_TO_PERCENT: {
|
||||
// Launch the slider-based percent selector and return here on confirm/cancel.
|
||||
float bookProgress = 0.0f;
|
||||
if (epub && epub->getBookSize() > 0 && section && section->pageCount > 0) {
|
||||
const float chapterProgress = static_cast<float>(section->currentPage) / static_cast<float>(section->pageCount);
|
||||
bookProgress = epub->calculateProgress(currentSpineIndex, chapterProgress) * 100.0f;
|
||||
}
|
||||
const int initialPercent = clampPercent(static_cast<int>(bookProgress + 0.5f));
|
||||
exitActivity();
|
||||
enterNewActivity(new EpubReaderPercentSelectionActivity(
|
||||
renderer, mappedInput, initialPercent,
|
||||
[this](const int percent) {
|
||||
// Apply the new position and exit back to the reader.
|
||||
jumpToPercent(percent);
|
||||
exitActivity();
|
||||
requestUpdate();
|
||||
},
|
||||
[this]() {
|
||||
// Cancel selection and return to the reader.
|
||||
exitActivity();
|
||||
requestUpdate();
|
||||
}));
|
||||
startActivityForResult(
|
||||
std::make_unique<EpubReaderPercentSelectionActivity>(renderer, mappedInput, initialPercent),
|
||||
[this](const ActivityResult& result) {
|
||||
if (!result.isCancelled) {
|
||||
jumpToPercent(std::get<PercentResult>(result.data).percent);
|
||||
}
|
||||
});
|
||||
break;
|
||||
}
|
||||
case EpubReaderMenuActivity::MenuAction::DISPLAY_QR: {
|
||||
@@ -421,55 +364,41 @@ void EpubReaderActivity::onReaderMenuConfirm(EpubReaderMenuActivity::MenuAction
|
||||
}
|
||||
}
|
||||
if (!fullText.empty()) {
|
||||
exitActivity();
|
||||
enterNewActivity(new QrDisplayActivity(renderer, mappedInput, fullText, [this]() {
|
||||
exitActivity();
|
||||
requestUpdate();
|
||||
}));
|
||||
startActivityForResult(std::make_unique<QrDisplayActivity>(renderer, mappedInput, fullText),
|
||||
[this](const ActivityResult& result) {});
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
// If no text or page loading failed, just close menu
|
||||
exitActivity();
|
||||
requestUpdate();
|
||||
break;
|
||||
}
|
||||
case EpubReaderMenuActivity::MenuAction::GO_HOME: {
|
||||
// Defer go home to avoid race condition with display task
|
||||
pendingGoHome = true;
|
||||
break;
|
||||
onGoHome();
|
||||
return;
|
||||
}
|
||||
case EpubReaderMenuActivity::MenuAction::DELETE_CACHE: {
|
||||
{
|
||||
RenderLock lock(*this);
|
||||
if (epub) {
|
||||
// 2. BACKUP: Read current progress
|
||||
// We use the current variables that track our position
|
||||
if (epub && section) {
|
||||
uint16_t backupSpine = currentSpineIndex;
|
||||
uint16_t backupPage = section->currentPage;
|
||||
uint16_t backupPageCount = section->pageCount;
|
||||
|
||||
section.reset();
|
||||
// 3. WIPE: Clear the cache directory
|
||||
epub->clearCache();
|
||||
|
||||
// 4. RESTORE: Re-setup the directory and rewrite the progress file
|
||||
epub->setupCacheDir();
|
||||
|
||||
saveProgress(backupSpine, backupPage, backupPageCount);
|
||||
}
|
||||
}
|
||||
// Defer go home to avoid race condition with display task
|
||||
pendingGoHome = true;
|
||||
break;
|
||||
onGoHome();
|
||||
return;
|
||||
}
|
||||
case EpubReaderMenuActivity::MenuAction::SCREENSHOT: {
|
||||
{
|
||||
RenderLock lock(*this);
|
||||
pendingScreenshot = true;
|
||||
}
|
||||
exitActivity();
|
||||
requestUpdate();
|
||||
break;
|
||||
}
|
||||
@@ -477,22 +406,19 @@ void EpubReaderActivity::onReaderMenuConfirm(EpubReaderMenuActivity::MenuAction
|
||||
if (KOREADER_STORE.hasCredentials()) {
|
||||
const int currentPage = section ? section->currentPage : 0;
|
||||
const int totalPages = section ? section->pageCount : 0;
|
||||
exitActivity();
|
||||
enterNewActivity(new KOReaderSyncActivity(
|
||||
renderer, mappedInput, epub, epub->getPath(), currentSpineIndex, currentPage, totalPages,
|
||||
[this]() {
|
||||
// On cancel - defer exit to avoid use-after-free
|
||||
pendingSubactivityExit = true;
|
||||
},
|
||||
[this](int newSpineIndex, int newPage) {
|
||||
// On sync complete - update position and defer exit
|
||||
if (currentSpineIndex != newSpineIndex || (section && section->currentPage != newPage)) {
|
||||
currentSpineIndex = newSpineIndex;
|
||||
nextPageNumber = newPage;
|
||||
section.reset();
|
||||
startActivityForResult(
|
||||
std::make_unique<KOReaderSyncActivity>(renderer, mappedInput, epub, epub->getPath(), currentSpineIndex,
|
||||
currentPage, totalPages),
|
||||
[this](const ActivityResult& result) {
|
||||
if (!result.isCancelled) {
|
||||
const auto& sync = std::get<SyncResult>(result.data);
|
||||
if (currentSpineIndex != sync.spineIndex || (section && section->currentPage != sync.page)) {
|
||||
currentSpineIndex = sync.spineIndex;
|
||||
nextPageNumber = sync.page;
|
||||
section.reset();
|
||||
}
|
||||
}
|
||||
pendingSubactivityExit = true;
|
||||
}));
|
||||
});
|
||||
}
|
||||
break;
|
||||
}
|
||||
@@ -527,7 +453,7 @@ void EpubReaderActivity::applyOrientation(const uint8_t orientation) {
|
||||
}
|
||||
|
||||
// TODO: Failure handling
|
||||
void EpubReaderActivity::render(Activity::RenderLock&& lock) {
|
||||
void EpubReaderActivity::render(RenderLock&& lock) {
|
||||
if (!epub) {
|
||||
return;
|
||||
}
|
||||
@@ -641,6 +567,10 @@ void EpubReaderActivity::render(Activity::RenderLock&& lock) {
|
||||
// TODO: prevent infinite loop if the page keeps failing to load for some reason
|
||||
return;
|
||||
}
|
||||
|
||||
// Collect footnotes from the loaded page
|
||||
currentPageFootnotes = std::move(p->footnotes);
|
||||
|
||||
const auto start = millis();
|
||||
renderContents(std::move(p), orientedMarginTop, orientedMarginRight, orientedMarginBottom, orientedMarginLeft);
|
||||
LOG_DBG("ERS", "Rendered page in %dms", millis() - start);
|
||||
@@ -757,3 +687,55 @@ void EpubReaderActivity::renderStatusBar() const {
|
||||
|
||||
GUI.drawStatusBar(renderer, bookProgress, currentPage, pageCount, title);
|
||||
}
|
||||
|
||||
void EpubReaderActivity::navigateToHref(const std::string& hrefStr, const bool savePosition) {
|
||||
if (!epub) return;
|
||||
|
||||
// Push current position onto saved stack
|
||||
if (savePosition && section && footnoteDepth < MAX_FOOTNOTE_DEPTH) {
|
||||
savedPositions[footnoteDepth] = {currentSpineIndex, section->currentPage};
|
||||
footnoteDepth++;
|
||||
LOG_DBG("ERS", "Saved position [%d]: spine %d, page %d", footnoteDepth, currentSpineIndex, section->currentPage);
|
||||
}
|
||||
|
||||
// Check for same-file anchor reference (#anchor only)
|
||||
bool sameFile = !hrefStr.empty() && hrefStr[0] == '#';
|
||||
|
||||
int targetSpineIndex;
|
||||
if (sameFile) {
|
||||
// Same file — navigate to page 0 of current spine item
|
||||
targetSpineIndex = currentSpineIndex;
|
||||
} else {
|
||||
targetSpineIndex = epub->resolveHrefToSpineIndex(hrefStr);
|
||||
}
|
||||
|
||||
if (targetSpineIndex < 0) {
|
||||
LOG_DBG("ERS", "Could not resolve href: %s", hrefStr.c_str());
|
||||
if (savePosition && footnoteDepth > 0) footnoteDepth--; // undo push
|
||||
return;
|
||||
}
|
||||
|
||||
{
|
||||
RenderLock lock(*this);
|
||||
currentSpineIndex = targetSpineIndex;
|
||||
nextPageNumber = 0;
|
||||
section.reset();
|
||||
}
|
||||
requestUpdate();
|
||||
LOG_DBG("ERS", "Navigated to spine %d for href: %s", targetSpineIndex, hrefStr.c_str());
|
||||
}
|
||||
|
||||
void EpubReaderActivity::restoreSavedPosition() {
|
||||
if (footnoteDepth <= 0) return;
|
||||
footnoteDepth--;
|
||||
const auto& pos = savedPositions[footnoteDepth];
|
||||
LOG_DBG("ERS", "Restoring position [%d]: spine %d, page %d", footnoteDepth, pos.spineIndex, pos.pageNumber);
|
||||
|
||||
{
|
||||
RenderLock lock(*this);
|
||||
currentSpineIndex = pos.spineIndex;
|
||||
nextPageNumber = pos.pageNumber;
|
||||
section.reset();
|
||||
}
|
||||
requestUpdate();
|
||||
}
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
#pragma once
|
||||
#include <Epub.h>
|
||||
#include <Epub/FootnoteEntry.h>
|
||||
#include <Epub/Section.h>
|
||||
|
||||
#include "EpubReaderMenuActivity.h"
|
||||
#include "activities/ActivityWithSubactivity.h"
|
||||
#include "activities/Activity.h"
|
||||
|
||||
class EpubReaderActivity final : public ActivityWithSubactivity {
|
||||
class EpubReaderActivity final : public Activity {
|
||||
std::shared_ptr<Epub> epub;
|
||||
std::unique_ptr<Section> section = nullptr;
|
||||
int currentSpineIndex = 0;
|
||||
@@ -18,12 +19,18 @@ class EpubReaderActivity final : public ActivityWithSubactivity {
|
||||
bool pendingPercentJump = false;
|
||||
// Normalized 0.0-1.0 progress within the target spine item, computed from book percentage.
|
||||
float pendingSpineProgress = 0.0f;
|
||||
bool pendingSubactivityExit = false; // Defer subactivity exit to avoid use-after-free
|
||||
bool pendingGoHome = false; // Defer go home to avoid race condition with display task
|
||||
bool pendingScreenshot = false;
|
||||
bool skipNextButtonCheck = false; // Skip button processing for one frame after subactivity exit
|
||||
const std::function<void()> onGoBack;
|
||||
const std::function<void()> onGoHome;
|
||||
|
||||
// Footnote support
|
||||
std::vector<FootnoteEntry> currentPageFootnotes;
|
||||
struct SavedPosition {
|
||||
int spineIndex;
|
||||
int pageNumber;
|
||||
};
|
||||
static constexpr int MAX_FOOTNOTE_DEPTH = 3;
|
||||
SavedPosition savedPositions[MAX_FOOTNOTE_DEPTH] = {};
|
||||
int footnoteDepth = 0;
|
||||
|
||||
void renderContents(std::unique_ptr<Page> page, int orientedMarginTop, int orientedMarginRight,
|
||||
int orientedMarginBottom, int orientedMarginLeft);
|
||||
@@ -31,19 +38,19 @@ class EpubReaderActivity final : public ActivityWithSubactivity {
|
||||
void saveProgress(int spineIndex, int currentPage, int pageCount);
|
||||
// Jump to a percentage of the book (0-100), mapping it to spine and page.
|
||||
void jumpToPercent(int percent);
|
||||
void onReaderMenuBack(uint8_t orientation);
|
||||
void onReaderMenuConfirm(EpubReaderMenuActivity::MenuAction action);
|
||||
void applyOrientation(uint8_t orientation);
|
||||
|
||||
// Footnote navigation
|
||||
void navigateToHref(const std::string& href, bool savePosition = false);
|
||||
void restoreSavedPosition();
|
||||
|
||||
public:
|
||||
explicit EpubReaderActivity(GfxRenderer& renderer, MappedInputManager& mappedInput, std::unique_ptr<Epub> epub,
|
||||
const std::function<void()>& onGoBack, const std::function<void()>& onGoHome)
|
||||
: ActivityWithSubactivity("EpubReader", renderer, mappedInput),
|
||||
epub(std::move(epub)),
|
||||
onGoBack(onGoBack),
|
||||
onGoHome(onGoHome) {}
|
||||
explicit EpubReaderActivity(GfxRenderer& renderer, MappedInputManager& mappedInput, std::unique_ptr<Epub> epub)
|
||||
: Activity("EpubReader", renderer, mappedInput), epub(std::move(epub)) {}
|
||||
void onEnter() override;
|
||||
void onExit() override;
|
||||
void loop() override;
|
||||
void render(Activity::RenderLock&& lock) override;
|
||||
void render(RenderLock&& lock) override;
|
||||
bool isReaderActivity() const override { return true; }
|
||||
};
|
||||
|
||||
@@ -26,7 +26,7 @@ int EpubReaderChapterSelectionActivity::getPageItems() const {
|
||||
}
|
||||
|
||||
void EpubReaderChapterSelectionActivity::onEnter() {
|
||||
ActivityWithSubactivity::onEnter();
|
||||
Activity::onEnter();
|
||||
|
||||
if (!epub) {
|
||||
return;
|
||||
@@ -41,26 +41,28 @@ void EpubReaderChapterSelectionActivity::onEnter() {
|
||||
requestUpdate();
|
||||
}
|
||||
|
||||
void EpubReaderChapterSelectionActivity::onExit() { ActivityWithSubactivity::onExit(); }
|
||||
void EpubReaderChapterSelectionActivity::onExit() { Activity::onExit(); }
|
||||
|
||||
void EpubReaderChapterSelectionActivity::loop() {
|
||||
if (subActivity) {
|
||||
subActivity->loop();
|
||||
return;
|
||||
}
|
||||
|
||||
const int pageItems = getPageItems();
|
||||
const int totalItems = getTotalItems();
|
||||
|
||||
if (mappedInput.wasReleased(MappedInputManager::Button::Confirm)) {
|
||||
const auto newSpineIndex = epub->getSpineIndexForTocIndex(selectorIndex);
|
||||
if (newSpineIndex == -1) {
|
||||
onGoBack();
|
||||
ActivityResult result;
|
||||
result.isCancelled = true;
|
||||
setResult(std::move(result));
|
||||
finish();
|
||||
} else {
|
||||
onSelectSpineIndex(newSpineIndex);
|
||||
setResult(ChapterResult{newSpineIndex});
|
||||
finish();
|
||||
}
|
||||
} else if (mappedInput.wasReleased(MappedInputManager::Button::Back)) {
|
||||
onGoBack();
|
||||
ActivityResult result;
|
||||
result.isCancelled = true;
|
||||
setResult(std::move(result));
|
||||
finish();
|
||||
}
|
||||
|
||||
buttonNavigator.onNextRelease([this, totalItems] {
|
||||
@@ -84,7 +86,7 @@ void EpubReaderChapterSelectionActivity::loop() {
|
||||
});
|
||||
}
|
||||
|
||||
void EpubReaderChapterSelectionActivity::render(Activity::RenderLock&&) {
|
||||
void EpubReaderChapterSelectionActivity::render(RenderLock&&) {
|
||||
renderer.clearScreen();
|
||||
|
||||
const auto pageWidth = renderer.getScreenWidth();
|
||||
|
||||
@@ -3,22 +3,16 @@
|
||||
|
||||
#include <memory>
|
||||
|
||||
#include "../ActivityWithSubactivity.h"
|
||||
#include "../Activity.h"
|
||||
#include "util/ButtonNavigator.h"
|
||||
|
||||
class EpubReaderChapterSelectionActivity final : public ActivityWithSubactivity {
|
||||
class EpubReaderChapterSelectionActivity final : public Activity {
|
||||
std::shared_ptr<Epub> epub;
|
||||
std::string epubPath;
|
||||
ButtonNavigator buttonNavigator;
|
||||
int currentSpineIndex = 0;
|
||||
int currentPage = 0;
|
||||
int totalPagesInSpine = 0;
|
||||
int selectorIndex = 0;
|
||||
|
||||
const std::function<void()> onGoBack;
|
||||
const std::function<void(int newSpineIndex)> onSelectSpineIndex;
|
||||
const std::function<void(int newSpineIndex, int newPage)> onSyncPosition;
|
||||
|
||||
// Number of items that fit on a page, derived from logical screen height.
|
||||
// This adapts automatically when switching between portrait and landscape.
|
||||
int getPageItems() const;
|
||||
@@ -29,21 +23,13 @@ class EpubReaderChapterSelectionActivity final : public ActivityWithSubactivity
|
||||
public:
|
||||
explicit EpubReaderChapterSelectionActivity(GfxRenderer& renderer, MappedInputManager& mappedInput,
|
||||
const std::shared_ptr<Epub>& epub, const std::string& epubPath,
|
||||
const int currentSpineIndex, const int currentPage,
|
||||
const int totalPagesInSpine, const std::function<void()>& onGoBack,
|
||||
const std::function<void(int newSpineIndex)>& onSelectSpineIndex,
|
||||
const std::function<void(int newSpineIndex, int newPage)>& onSyncPosition)
|
||||
: ActivityWithSubactivity("EpubReaderChapterSelection", renderer, mappedInput),
|
||||
const int currentSpineIndex)
|
||||
: Activity("EpubReaderChapterSelection", renderer, mappedInput),
|
||||
epub(epub),
|
||||
epubPath(epubPath),
|
||||
currentSpineIndex(currentSpineIndex),
|
||||
currentPage(currentPage),
|
||||
totalPagesInSpine(totalPagesInSpine),
|
||||
onGoBack(onGoBack),
|
||||
onSelectSpineIndex(onSelectSpineIndex),
|
||||
onSyncPosition(onSyncPosition) {}
|
||||
currentSpineIndex(currentSpineIndex) {}
|
||||
void onEnter() override;
|
||||
void onExit() override;
|
||||
void loop() override;
|
||||
void render(Activity::RenderLock&&) override;
|
||||
void render(RenderLock&&) override;
|
||||
};
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
#include "EpubReaderFootnotesActivity.h"
|
||||
|
||||
#include <GfxRenderer.h>
|
||||
#include <I18n.h>
|
||||
|
||||
#include <algorithm>
|
||||
|
||||
#include "MappedInputManager.h"
|
||||
#include "components/UITheme.h"
|
||||
#include "fontIds.h"
|
||||
|
||||
void EpubReaderFootnotesActivity::onEnter() {
|
||||
Activity::onEnter();
|
||||
selectedIndex = 0;
|
||||
requestUpdate();
|
||||
}
|
||||
|
||||
void EpubReaderFootnotesActivity::onExit() { Activity::onExit(); }
|
||||
|
||||
void EpubReaderFootnotesActivity::loop() {
|
||||
if (mappedInput.wasReleased(MappedInputManager::Button::Back)) {
|
||||
ActivityResult result;
|
||||
result.isCancelled = true;
|
||||
setResult(std::move(result));
|
||||
finish();
|
||||
return;
|
||||
}
|
||||
|
||||
if (mappedInput.wasReleased(MappedInputManager::Button::Confirm)) {
|
||||
if (selectedIndex >= 0 && selectedIndex < static_cast<int>(footnotes.size())) {
|
||||
setResult(FootnoteResult{footnotes[selectedIndex].href});
|
||||
finish();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
buttonNavigator.onNext([this] {
|
||||
if (!footnotes.empty()) {
|
||||
selectedIndex = (selectedIndex + 1) % footnotes.size();
|
||||
requestUpdate();
|
||||
}
|
||||
});
|
||||
|
||||
buttonNavigator.onPrevious([this] {
|
||||
if (!footnotes.empty()) {
|
||||
selectedIndex = (selectedIndex - 1 + footnotes.size()) % footnotes.size();
|
||||
requestUpdate();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
void EpubReaderFootnotesActivity::render(RenderLock&&) {
|
||||
renderer.clearScreen();
|
||||
|
||||
renderer.drawCenteredText(UI_12_FONT_ID, 15, tr(STR_FOOTNOTES), true, EpdFontFamily::BOLD);
|
||||
|
||||
if (footnotes.empty()) {
|
||||
renderer.drawCenteredText(UI_10_FONT_ID, 90, tr(STR_NO_FOOTNOTES));
|
||||
const auto labels = mappedInput.mapLabels(tr(STR_BACK), "", "", "");
|
||||
GUI.drawButtonHints(renderer, labels.btn1, labels.btn2, labels.btn3, labels.btn4);
|
||||
renderer.displayBuffer();
|
||||
return;
|
||||
}
|
||||
|
||||
constexpr int startY = 50;
|
||||
constexpr int lineHeight = 36;
|
||||
const int screenWidth = renderer.getScreenWidth();
|
||||
constexpr int marginLeft = 20;
|
||||
|
||||
const int visibleCount = std::max(1, (renderer.getScreenHeight() - startY) / lineHeight);
|
||||
if (selectedIndex < scrollOffset) scrollOffset = selectedIndex;
|
||||
if (selectedIndex >= scrollOffset + visibleCount) scrollOffset = selectedIndex - visibleCount + 1;
|
||||
|
||||
for (int i = scrollOffset; i < static_cast<int>(footnotes.size()) && i < scrollOffset + visibleCount; i++) {
|
||||
const int y = startY + (i - scrollOffset) * lineHeight;
|
||||
const bool isSelected = (i == selectedIndex);
|
||||
|
||||
if (isSelected) {
|
||||
renderer.fillRect(0, y, screenWidth, lineHeight, true);
|
||||
}
|
||||
|
||||
// Show footnote number and abbreviated href
|
||||
std::string label = footnotes[i].number;
|
||||
if (label.empty()) {
|
||||
label = tr(STR_LINK);
|
||||
}
|
||||
renderer.drawText(UI_10_FONT_ID, marginLeft, y + 4, label.c_str(), !isSelected);
|
||||
}
|
||||
|
||||
const auto labels = mappedInput.mapLabels(tr(STR_BACK), tr(STR_SELECT), "", "");
|
||||
GUI.drawButtonHints(renderer, labels.btn1, labels.btn2, labels.btn3, labels.btn4);
|
||||
|
||||
renderer.displayBuffer();
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
#pragma once
|
||||
|
||||
#include <Epub/FootnoteEntry.h>
|
||||
|
||||
#include <cstring>
|
||||
#include <functional>
|
||||
#include <vector>
|
||||
|
||||
#include "../Activity.h"
|
||||
#include "util/ButtonNavigator.h"
|
||||
|
||||
class EpubReaderFootnotesActivity final : public Activity {
|
||||
public:
|
||||
explicit EpubReaderFootnotesActivity(GfxRenderer& renderer, MappedInputManager& mappedInput,
|
||||
const std::vector<FootnoteEntry>& footnotes)
|
||||
: Activity("EpubReaderFootnotes", renderer, mappedInput), footnotes(footnotes) {}
|
||||
|
||||
void onEnter() override;
|
||||
void onExit() override;
|
||||
void loop() override;
|
||||
void render(RenderLock&&) override;
|
||||
|
||||
private:
|
||||
const std::vector<FootnoteEntry>& footnotes;
|
||||
int selectedIndex = 0;
|
||||
int scrollOffset = 0;
|
||||
ButtonNavigator buttonNavigator;
|
||||
};
|
||||
@@ -7,19 +7,43 @@
|
||||
#include "components/UITheme.h"
|
||||
#include "fontIds.h"
|
||||
|
||||
EpubReaderMenuActivity::EpubReaderMenuActivity(GfxRenderer& renderer, MappedInputManager& mappedInput,
|
||||
const std::string& title, const int currentPage, const int totalPages,
|
||||
const int bookProgressPercent, const uint8_t currentOrientation,
|
||||
const bool hasFootnotes)
|
||||
: Activity("EpubReaderMenu", renderer, mappedInput),
|
||||
menuItems(buildMenuItems(hasFootnotes)),
|
||||
title(title),
|
||||
pendingOrientation(currentOrientation),
|
||||
currentPage(currentPage),
|
||||
totalPages(totalPages),
|
||||
bookProgressPercent(bookProgressPercent) {}
|
||||
|
||||
std::vector<EpubReaderMenuActivity::MenuItem> EpubReaderMenuActivity::buildMenuItems(bool hasFootnotes) {
|
||||
std::vector<MenuItem> items;
|
||||
items.reserve(9);
|
||||
items.push_back({MenuAction::SELECT_CHAPTER, StrId::STR_SELECT_CHAPTER});
|
||||
if (hasFootnotes) {
|
||||
items.push_back({MenuAction::FOOTNOTES, StrId::STR_FOOTNOTES});
|
||||
}
|
||||
items.push_back({MenuAction::ROTATE_SCREEN, StrId::STR_ORIENTATION});
|
||||
items.push_back({MenuAction::GO_TO_PERCENT, StrId::STR_GO_TO_PERCENT});
|
||||
items.push_back({MenuAction::SCREENSHOT, StrId::STR_SCREENSHOT_BUTTON});
|
||||
items.push_back({MenuAction::DISPLAY_QR, StrId::STR_DISPLAY_QR});
|
||||
items.push_back({MenuAction::GO_HOME, StrId::STR_GO_HOME_BUTTON});
|
||||
items.push_back({MenuAction::SYNC, StrId::STR_SYNC_PROGRESS});
|
||||
items.push_back({MenuAction::DELETE_CACHE, StrId::STR_DELETE_CACHE});
|
||||
return items;
|
||||
}
|
||||
|
||||
void EpubReaderMenuActivity::onEnter() {
|
||||
ActivityWithSubactivity::onEnter();
|
||||
Activity::onEnter();
|
||||
requestUpdate();
|
||||
}
|
||||
|
||||
void EpubReaderMenuActivity::onExit() { ActivityWithSubactivity::onExit(); }
|
||||
void EpubReaderMenuActivity::onExit() { Activity::onExit(); }
|
||||
|
||||
void EpubReaderMenuActivity::loop() {
|
||||
if (subActivity) {
|
||||
subActivity->loop();
|
||||
return;
|
||||
}
|
||||
|
||||
// Handle navigation
|
||||
buttonNavigator.onNext([this] {
|
||||
selectedIndex = ButtonNavigator::nextIndex(selectedIndex, static_cast<int>(menuItems.size()));
|
||||
@@ -31,7 +55,6 @@ void EpubReaderMenuActivity::loop() {
|
||||
requestUpdate();
|
||||
});
|
||||
|
||||
// Use local variables for items we need to check after potential deletion
|
||||
if (mappedInput.wasReleased(MappedInputManager::Button::Confirm)) {
|
||||
const auto selectedAction = menuItems[selectedIndex].action;
|
||||
if (selectedAction == MenuAction::ROTATE_SCREEN) {
|
||||
@@ -41,22 +64,20 @@ void EpubReaderMenuActivity::loop() {
|
||||
return;
|
||||
}
|
||||
|
||||
// 1. Capture the callback and action locally
|
||||
auto actionCallback = onAction;
|
||||
|
||||
// 2. Execute the callback
|
||||
actionCallback(selectedAction);
|
||||
|
||||
// 3. CRITICAL: Return immediately. 'this' is likely deleted now.
|
||||
setResult(MenuResult{static_cast<int>(selectedAction), pendingOrientation});
|
||||
finish();
|
||||
return;
|
||||
} else if (mappedInput.wasReleased(MappedInputManager::Button::Back)) {
|
||||
// Return the pending orientation to the parent so it can apply on exit.
|
||||
onBack(pendingOrientation);
|
||||
return; // Also return here just in case
|
||||
ActivityResult result;
|
||||
result.isCancelled = true;
|
||||
result.data = MenuResult{-1, pendingOrientation};
|
||||
setResult(std::move(result));
|
||||
finish();
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
void EpubReaderMenuActivity::render(Activity::RenderLock&&) {
|
||||
void EpubReaderMenuActivity::render(RenderLock&&) {
|
||||
renderer.clearScreen();
|
||||
const auto pageWidth = renderer.getScreenWidth();
|
||||
const auto orientation = renderer.getOrientation();
|
||||
|
||||
@@ -2,18 +2,18 @@
|
||||
#include <Epub.h>
|
||||
#include <I18n.h>
|
||||
|
||||
#include <functional>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "../ActivityWithSubactivity.h"
|
||||
#include "../Activity.h"
|
||||
#include "util/ButtonNavigator.h"
|
||||
|
||||
class EpubReaderMenuActivity final : public ActivityWithSubactivity {
|
||||
class EpubReaderMenuActivity final : public Activity {
|
||||
public:
|
||||
// Menu actions available from the reader menu.
|
||||
enum class MenuAction {
|
||||
SELECT_CHAPTER,
|
||||
FOOTNOTES,
|
||||
GO_TO_PERCENT,
|
||||
ROTATE_SCREEN,
|
||||
SCREENSHOT,
|
||||
@@ -25,21 +25,12 @@ class EpubReaderMenuActivity final : public ActivityWithSubactivity {
|
||||
|
||||
explicit EpubReaderMenuActivity(GfxRenderer& renderer, MappedInputManager& mappedInput, const std::string& title,
|
||||
const int currentPage, const int totalPages, const int bookProgressPercent,
|
||||
const uint8_t currentOrientation, const std::function<void(uint8_t)>& onBack,
|
||||
const std::function<void(MenuAction)>& onAction)
|
||||
: ActivityWithSubactivity("EpubReaderMenu", renderer, mappedInput),
|
||||
title(title),
|
||||
pendingOrientation(currentOrientation),
|
||||
currentPage(currentPage),
|
||||
totalPages(totalPages),
|
||||
bookProgressPercent(bookProgressPercent),
|
||||
onBack(onBack),
|
||||
onAction(onAction) {}
|
||||
const uint8_t currentOrientation, const bool hasFootnotes);
|
||||
|
||||
void onEnter() override;
|
||||
void onExit() override;
|
||||
void loop() override;
|
||||
void render(Activity::RenderLock&&) override;
|
||||
void render(RenderLock&&) override;
|
||||
|
||||
private:
|
||||
struct MenuItem {
|
||||
@@ -47,15 +38,11 @@ class EpubReaderMenuActivity final : public ActivityWithSubactivity {
|
||||
StrId labelId;
|
||||
};
|
||||
|
||||
// Fixed menu layout (order matters for up/down navigation).
|
||||
const std::vector<MenuItem> menuItems = {{MenuAction::SELECT_CHAPTER, StrId::STR_SELECT_CHAPTER},
|
||||
{MenuAction::ROTATE_SCREEN, StrId::STR_ORIENTATION},
|
||||
{MenuAction::GO_TO_PERCENT, StrId::STR_GO_TO_PERCENT},
|
||||
{MenuAction::SCREENSHOT, StrId::STR_SCREENSHOT_BUTTON},
|
||||
{MenuAction::DISPLAY_QR, StrId::STR_DISPLAY_QR},
|
||||
{MenuAction::GO_HOME, StrId::STR_GO_HOME_BUTTON},
|
||||
{MenuAction::SYNC, StrId::STR_SYNC_PROGRESS},
|
||||
{MenuAction::DELETE_CACHE, StrId::STR_DELETE_CACHE}};
|
||||
static std::vector<MenuItem> buildMenuItems(bool hasFootnotes);
|
||||
|
||||
// Fixed menu layout
|
||||
const std::vector<MenuItem> menuItems;
|
||||
|
||||
int selectedIndex = 0;
|
||||
|
||||
ButtonNavigator buttonNavigator;
|
||||
@@ -66,7 +53,4 @@ class EpubReaderMenuActivity final : public ActivityWithSubactivity {
|
||||
int currentPage = 0;
|
||||
int totalPages = 0;
|
||||
int bookProgressPercent = 0;
|
||||
|
||||
const std::function<void(uint8_t)> onBack;
|
||||
const std::function<void(MenuAction)> onAction;
|
||||
};
|
||||
|
||||
@@ -14,12 +14,12 @@ constexpr int kLargeStep = 10;
|
||||
} // namespace
|
||||
|
||||
void EpubReaderPercentSelectionActivity::onEnter() {
|
||||
ActivityWithSubactivity::onEnter();
|
||||
Activity::onEnter();
|
||||
// Set up rendering task and mark first frame dirty.
|
||||
requestUpdate();
|
||||
}
|
||||
|
||||
void EpubReaderPercentSelectionActivity::onExit() { ActivityWithSubactivity::onExit(); }
|
||||
void EpubReaderPercentSelectionActivity::onExit() { Activity::onExit(); }
|
||||
|
||||
void EpubReaderPercentSelectionActivity::adjustPercent(const int delta) {
|
||||
// Apply delta and clamp within 0-100.
|
||||
@@ -33,19 +33,18 @@ void EpubReaderPercentSelectionActivity::adjustPercent(const int delta) {
|
||||
}
|
||||
|
||||
void EpubReaderPercentSelectionActivity::loop() {
|
||||
if (subActivity) {
|
||||
subActivity->loop();
|
||||
return;
|
||||
}
|
||||
|
||||
// Back cancels, confirm selects, arrows adjust the percent.
|
||||
if (mappedInput.wasReleased(MappedInputManager::Button::Back)) {
|
||||
onCancel();
|
||||
ActivityResult result;
|
||||
result.isCancelled = true;
|
||||
setResult(std::move(result));
|
||||
finish();
|
||||
return;
|
||||
}
|
||||
|
||||
if (mappedInput.wasReleased(MappedInputManager::Button::Confirm)) {
|
||||
onSelect(percent);
|
||||
setResult(PercentResult{percent});
|
||||
finish();
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -56,7 +55,7 @@ void EpubReaderPercentSelectionActivity::loop() {
|
||||
buttonNavigator.onPressAndContinuous({MappedInputManager::Button::Down}, [this] { adjustPercent(-kLargeStep); });
|
||||
}
|
||||
|
||||
void EpubReaderPercentSelectionActivity::render(Activity::RenderLock&&) {
|
||||
void EpubReaderPercentSelectionActivity::render(RenderLock&&) {
|
||||
renderer.clearScreen();
|
||||
|
||||
// Title and numeric percent value.
|
||||
|
||||
@@ -1,26 +1,20 @@
|
||||
#pragma once
|
||||
|
||||
#include <functional>
|
||||
|
||||
#include "MappedInputManager.h"
|
||||
#include "activities/ActivityWithSubactivity.h"
|
||||
#include "activities/Activity.h"
|
||||
#include "util/ButtonNavigator.h"
|
||||
|
||||
class EpubReaderPercentSelectionActivity final : public ActivityWithSubactivity {
|
||||
class EpubReaderPercentSelectionActivity final : public Activity {
|
||||
public:
|
||||
// Slider-style percent selector for jumping within a book.
|
||||
explicit EpubReaderPercentSelectionActivity(GfxRenderer& renderer, MappedInputManager& mappedInput,
|
||||
const int initialPercent, const std::function<void(int)>& onSelect,
|
||||
const std::function<void()>& onCancel)
|
||||
: ActivityWithSubactivity("EpubReaderPercentSelection", renderer, mappedInput),
|
||||
percent(initialPercent),
|
||||
onSelect(onSelect),
|
||||
onCancel(onCancel) {}
|
||||
const int initialPercent)
|
||||
: Activity("EpubReaderPercentSelection", renderer, mappedInput), percent(initialPercent) {}
|
||||
|
||||
void onEnter() override;
|
||||
void onExit() override;
|
||||
void loop() override;
|
||||
void render(Activity::RenderLock&&) override;
|
||||
void render(RenderLock&&) override;
|
||||
|
||||
private:
|
||||
// Current percent value (0-100) shown on the slider.
|
||||
@@ -28,11 +22,6 @@ class EpubReaderPercentSelectionActivity final : public ActivityWithSubactivity
|
||||
|
||||
ButtonNavigator buttonNavigator;
|
||||
|
||||
// Callback invoked when the user confirms a percent.
|
||||
const std::function<void(int)> onSelect;
|
||||
// Callback invoked when the user cancels the slider.
|
||||
const std::function<void()> onCancel;
|
||||
|
||||
// Change the current percent by a delta and clamp within bounds.
|
||||
void adjustPercent(int delta);
|
||||
};
|
||||
|
||||
@@ -51,11 +51,12 @@ void wifiOff() {
|
||||
} // namespace
|
||||
|
||||
void KOReaderSyncActivity::onWifiSelectionComplete(const bool success) {
|
||||
exitActivity();
|
||||
|
||||
if (!success) {
|
||||
LOG_DBG("KOSync", "WiFi connection failed, exiting");
|
||||
onCancel();
|
||||
ActivityResult result;
|
||||
result.isCancelled = true;
|
||||
setResult(std::move(result));
|
||||
finish();
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -66,7 +67,7 @@ void KOReaderSyncActivity::onWifiSelectionComplete(const bool success) {
|
||||
state = SYNCING;
|
||||
statusMessage = tr(STR_SYNCING_TIME);
|
||||
}
|
||||
requestUpdate();
|
||||
requestUpdate(true);
|
||||
|
||||
// Sync time with NTP before making API requests
|
||||
syncTimeWithNTP();
|
||||
@@ -75,7 +76,7 @@ void KOReaderSyncActivity::onWifiSelectionComplete(const bool success) {
|
||||
RenderLock lock(*this);
|
||||
statusMessage = tr(STR_CALC_HASH);
|
||||
}
|
||||
requestUpdate();
|
||||
requestUpdate(true);
|
||||
|
||||
performSync();
|
||||
}
|
||||
@@ -93,7 +94,7 @@ void KOReaderSyncActivity::performSync() {
|
||||
state = SYNC_FAILED;
|
||||
statusMessage = tr(STR_HASH_FAILED);
|
||||
}
|
||||
requestUpdate();
|
||||
requestUpdate(true);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -115,7 +116,7 @@ void KOReaderSyncActivity::performSync() {
|
||||
state = NO_REMOTE_PROGRESS;
|
||||
hasRemoteProgress = false;
|
||||
}
|
||||
requestUpdate();
|
||||
requestUpdate(true);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -125,7 +126,7 @@ void KOReaderSyncActivity::performSync() {
|
||||
state = SYNC_FAILED;
|
||||
statusMessage = KOReaderSyncClient::errorString(result);
|
||||
}
|
||||
requestUpdate();
|
||||
requestUpdate(true);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -149,7 +150,7 @@ void KOReaderSyncActivity::performSync() {
|
||||
selectedOption = 0; // Apply remote progress
|
||||
}
|
||||
}
|
||||
requestUpdate();
|
||||
requestUpdate(true);
|
||||
}
|
||||
|
||||
void KOReaderSyncActivity::performUpload() {
|
||||
@@ -158,7 +159,6 @@ void KOReaderSyncActivity::performUpload() {
|
||||
state = UPLOADING;
|
||||
statusMessage = tr(STR_UPLOAD_PROGRESS);
|
||||
}
|
||||
requestUpdate();
|
||||
requestUpdateAndWait();
|
||||
|
||||
// Convert current position to KOReader format
|
||||
@@ -188,11 +188,11 @@ void KOReaderSyncActivity::performUpload() {
|
||||
RenderLock lock(*this);
|
||||
state = UPLOAD_COMPLETE;
|
||||
}
|
||||
requestUpdate();
|
||||
requestUpdate(true);
|
||||
}
|
||||
|
||||
void KOReaderSyncActivity::onEnter() {
|
||||
ActivityWithSubactivity::onEnter();
|
||||
Activity::onEnter();
|
||||
|
||||
// Check for credentials first
|
||||
if (!KOREADER_STORE.hasCredentials()) {
|
||||
@@ -206,7 +206,7 @@ void KOReaderSyncActivity::onEnter() {
|
||||
LOG_DBG("KOSync", "Already connected to WiFi");
|
||||
state = SYNCING;
|
||||
statusMessage = tr(STR_SYNCING_TIME);
|
||||
requestUpdate();
|
||||
requestUpdate(true);
|
||||
|
||||
// Perform sync directly (will be handled in loop)
|
||||
xTaskCreate(
|
||||
@@ -218,7 +218,7 @@ void KOReaderSyncActivity::onEnter() {
|
||||
RenderLock lock(*self);
|
||||
self->statusMessage = tr(STR_CALC_HASH);
|
||||
}
|
||||
self->requestUpdate();
|
||||
self->requestUpdate(true);
|
||||
self->performSync();
|
||||
vTaskDelete(nullptr);
|
||||
},
|
||||
@@ -228,21 +228,17 @@ void KOReaderSyncActivity::onEnter() {
|
||||
|
||||
// Launch WiFi selection subactivity
|
||||
LOG_DBG("KOSync", "Launching WifiSelectionActivity...");
|
||||
enterNewActivity(new WifiSelectionActivity(renderer, mappedInput,
|
||||
[this](const bool connected) { onWifiSelectionComplete(connected); }));
|
||||
startActivityForResult(std::make_unique<WifiSelectionActivity>(renderer, mappedInput),
|
||||
[this](const ActivityResult& result) { onWifiSelectionComplete(!result.isCancelled); });
|
||||
}
|
||||
|
||||
void KOReaderSyncActivity::onExit() {
|
||||
ActivityWithSubactivity::onExit();
|
||||
Activity::onExit();
|
||||
|
||||
wifiOff();
|
||||
}
|
||||
|
||||
void KOReaderSyncActivity::render(Activity::RenderLock&&) {
|
||||
if (subActivity) {
|
||||
return;
|
||||
}
|
||||
|
||||
void KOReaderSyncActivity::render(RenderLock&&) {
|
||||
const auto pageWidth = renderer.getScreenWidth();
|
||||
|
||||
renderer.clearScreen();
|
||||
@@ -357,49 +353,50 @@ void KOReaderSyncActivity::render(Activity::RenderLock&&) {
|
||||
}
|
||||
|
||||
void KOReaderSyncActivity::loop() {
|
||||
if (subActivity) {
|
||||
subActivity->loop();
|
||||
return;
|
||||
}
|
||||
|
||||
if (state == NO_CREDENTIALS || state == SYNC_FAILED || state == UPLOAD_COMPLETE) {
|
||||
if (mappedInput.wasPressed(MappedInputManager::Button::Back)) {
|
||||
onCancel();
|
||||
if (mappedInput.wasReleased(MappedInputManager::Button::Back)) {
|
||||
ActivityResult result;
|
||||
result.isCancelled = true;
|
||||
setResult(std::move(result));
|
||||
finish();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (state == SHOWING_RESULT) {
|
||||
// Navigate options
|
||||
if (mappedInput.wasPressed(MappedInputManager::Button::Up) ||
|
||||
mappedInput.wasPressed(MappedInputManager::Button::Left)) {
|
||||
if (mappedInput.wasReleased(MappedInputManager::Button::Up) ||
|
||||
mappedInput.wasReleased(MappedInputManager::Button::Left)) {
|
||||
selectedOption = (selectedOption + 1) % 2; // Wrap around among 2 options
|
||||
requestUpdate();
|
||||
} else if (mappedInput.wasPressed(MappedInputManager::Button::Down) ||
|
||||
mappedInput.wasPressed(MappedInputManager::Button::Right)) {
|
||||
} else if (mappedInput.wasReleased(MappedInputManager::Button::Down) ||
|
||||
mappedInput.wasReleased(MappedInputManager::Button::Right)) {
|
||||
selectedOption = (selectedOption + 1) % 2; // Wrap around among 2 options
|
||||
requestUpdate();
|
||||
}
|
||||
|
||||
if (mappedInput.wasPressed(MappedInputManager::Button::Confirm)) {
|
||||
if (mappedInput.wasReleased(MappedInputManager::Button::Confirm)) {
|
||||
if (selectedOption == 0) {
|
||||
// Apply remote progress — WiFi no longer needed
|
||||
wifiOff();
|
||||
onSyncComplete(remotePosition.spineIndex, remotePosition.pageNumber);
|
||||
// Wifi will be turned off in onExit()
|
||||
setResult(SyncResult{remotePosition.spineIndex, remotePosition.pageNumber});
|
||||
finish();
|
||||
} else if (selectedOption == 1) {
|
||||
// Upload local progress
|
||||
performUpload();
|
||||
}
|
||||
}
|
||||
|
||||
if (mappedInput.wasPressed(MappedInputManager::Button::Back)) {
|
||||
onCancel();
|
||||
if (mappedInput.wasReleased(MappedInputManager::Button::Back)) {
|
||||
ActivityResult result;
|
||||
result.isCancelled = true;
|
||||
setResult(std::move(result));
|
||||
finish();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (state == NO_REMOTE_PROGRESS) {
|
||||
if (mappedInput.wasPressed(MappedInputManager::Button::Confirm)) {
|
||||
if (mappedInput.wasReleased(MappedInputManager::Button::Confirm)) {
|
||||
// Calculate hash if not done yet
|
||||
if (documentHash.empty()) {
|
||||
if (KOREADER_STORE.getMatchMethod() == DocumentMatchMethod::FILENAME) {
|
||||
@@ -411,8 +408,11 @@ void KOReaderSyncActivity::loop() {
|
||||
performUpload();
|
||||
}
|
||||
|
||||
if (mappedInput.wasPressed(MappedInputManager::Button::Back)) {
|
||||
onCancel();
|
||||
if (mappedInput.wasReleased(MappedInputManager::Button::Back)) {
|
||||
ActivityResult result;
|
||||
result.isCancelled = true;
|
||||
setResult(std::move(result));
|
||||
finish();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
|
||||
#include "KOReaderSyncClient.h"
|
||||
#include "ProgressMapper.h"
|
||||
#include "activities/ActivityWithSubactivity.h"
|
||||
#include "activities/Activity.h"
|
||||
|
||||
/**
|
||||
* Activity for syncing reading progress with KOReader sync server.
|
||||
@@ -18,16 +18,12 @@
|
||||
* 4. Show comparison and options (Apply/Upload)
|
||||
* 5. Apply or upload progress
|
||||
*/
|
||||
class KOReaderSyncActivity final : public ActivityWithSubactivity {
|
||||
class KOReaderSyncActivity final : public Activity {
|
||||
public:
|
||||
using OnCancelCallback = std::function<void()>;
|
||||
using OnSyncCompleteCallback = std::function<void(int newSpineIndex, int newPageNumber)>;
|
||||
|
||||
explicit KOReaderSyncActivity(GfxRenderer& renderer, MappedInputManager& mappedInput,
|
||||
const std::shared_ptr<Epub>& epub, const std::string& epubPath, int currentSpineIndex,
|
||||
int currentPage, int totalPagesInSpine, OnCancelCallback onCancel,
|
||||
OnSyncCompleteCallback onSyncComplete)
|
||||
: ActivityWithSubactivity("KOReaderSync", renderer, mappedInput),
|
||||
int currentPage, int totalPagesInSpine)
|
||||
: Activity("KOReaderSync", renderer, mappedInput),
|
||||
epub(epub),
|
||||
epubPath(epubPath),
|
||||
currentSpineIndex(currentSpineIndex),
|
||||
@@ -35,14 +31,12 @@ class KOReaderSyncActivity final : public ActivityWithSubactivity {
|
||||
totalPagesInSpine(totalPagesInSpine),
|
||||
remoteProgress{},
|
||||
remotePosition{},
|
||||
localProgress{},
|
||||
onCancel(std::move(onCancel)),
|
||||
onSyncComplete(std::move(onSyncComplete)) {}
|
||||
localProgress{} {}
|
||||
|
||||
void onEnter() override;
|
||||
void onExit() override;
|
||||
void loop() override;
|
||||
void render(Activity::RenderLock&&) override;
|
||||
void render(RenderLock&&) override;
|
||||
bool preventAutoSleep() override { return state == CONNECTING || state == SYNCING; }
|
||||
|
||||
private:
|
||||
@@ -79,9 +73,6 @@ class KOReaderSyncActivity final : public ActivityWithSubactivity {
|
||||
// Selection in result screen (0=Apply, 1=Upload)
|
||||
int selectedOption = 0;
|
||||
|
||||
OnCancelCallback onCancel;
|
||||
OnSyncCompleteCallback onSyncComplete;
|
||||
|
||||
void onWifiSelectionComplete(bool success);
|
||||
void performSync();
|
||||
void performUpload();
|
||||
|
||||
@@ -18,12 +18,12 @@ void QrDisplayActivity::onExit() { Activity::onExit(); }
|
||||
void QrDisplayActivity::loop() {
|
||||
if (mappedInput.wasReleased(MappedInputManager::Button::Back) ||
|
||||
mappedInput.wasReleased(MappedInputManager::Button::Confirm)) {
|
||||
onGoBack();
|
||||
finish();
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
void QrDisplayActivity::render(Activity::RenderLock&&) {
|
||||
void QrDisplayActivity::render(RenderLock&&) {
|
||||
renderer.clearScreen();
|
||||
auto metrics = UITheme::getInstance().getMetrics();
|
||||
const auto pageWidth = renderer.getScreenWidth();
|
||||
|
||||
@@ -7,16 +7,14 @@
|
||||
|
||||
class QrDisplayActivity final : public Activity {
|
||||
public:
|
||||
explicit QrDisplayActivity(GfxRenderer& renderer, MappedInputManager& mappedInput, const std::string& textPayload,
|
||||
const std::function<void()>& onGoBack)
|
||||
: Activity("QrDisplay", renderer, mappedInput), textPayload(textPayload), onGoBack(onGoBack) {}
|
||||
explicit QrDisplayActivity(GfxRenderer& renderer, MappedInputManager& mappedInput, const std::string& textPayload)
|
||||
: Activity("QrDisplay", renderer, mappedInput), textPayload(textPayload) {}
|
||||
|
||||
void onEnter() override;
|
||||
void onExit() override;
|
||||
void loop() override;
|
||||
void render(Activity::RenderLock&&) override;
|
||||
void render(RenderLock&&) override;
|
||||
|
||||
private:
|
||||
std::string textPayload;
|
||||
const std::function<void()> onGoBack;
|
||||
};
|
||||
|
||||
@@ -79,41 +79,34 @@ std::unique_ptr<Txt> ReaderActivity::loadTxt(const std::string& path) {
|
||||
|
||||
void ReaderActivity::goToLibrary(const std::string& fromBookPath) {
|
||||
// If coming from a book, start in that book's folder; otherwise start from root
|
||||
const auto initialPath = fromBookPath.empty() ? "/" : extractFolderPath(fromBookPath);
|
||||
onGoToLibrary(initialPath);
|
||||
auto initialPath = fromBookPath.empty() ? "/" : extractFolderPath(fromBookPath);
|
||||
activityManager.goToMyLibrary(std::move(initialPath));
|
||||
}
|
||||
|
||||
void ReaderActivity::onGoToEpubReader(std::unique_ptr<Epub> epub) {
|
||||
const auto epubPath = epub->getPath();
|
||||
currentBookPath = epubPath;
|
||||
exitActivity();
|
||||
enterNewActivity(new EpubReaderActivity(
|
||||
renderer, mappedInput, std::move(epub), [this, epubPath] { goToLibrary(epubPath); }, [this] { onGoBack(); }));
|
||||
activityManager.replaceActivity(std::make_unique<EpubReaderActivity>(renderer, mappedInput, std::move(epub)));
|
||||
}
|
||||
|
||||
void ReaderActivity::onGoToBmpViewer(const std::string& path) {
|
||||
exitActivity();
|
||||
enterNewActivity(new BmpViewerActivity(renderer, mappedInput, path, [this, path] { goToLibrary(path); }));
|
||||
activityManager.replaceActivity(std::make_unique<BmpViewerActivity>(renderer, mappedInput, path));
|
||||
}
|
||||
|
||||
void ReaderActivity::onGoToXtcReader(std::unique_ptr<Xtc> xtc) {
|
||||
const auto xtcPath = xtc->getPath();
|
||||
currentBookPath = xtcPath;
|
||||
exitActivity();
|
||||
enterNewActivity(new XtcReaderActivity(
|
||||
renderer, mappedInput, std::move(xtc), [this, xtcPath] { goToLibrary(xtcPath); }, [this] { onGoBack(); }));
|
||||
activityManager.replaceActivity(std::make_unique<XtcReaderActivity>(renderer, mappedInput, std::move(xtc)));
|
||||
}
|
||||
|
||||
void ReaderActivity::onGoToTxtReader(std::unique_ptr<Txt> txt) {
|
||||
const auto txtPath = txt->getPath();
|
||||
currentBookPath = txtPath;
|
||||
exitActivity();
|
||||
enterNewActivity(new TxtReaderActivity(
|
||||
renderer, mappedInput, std::move(txt), [this, txtPath] { goToLibrary(txtPath); }, [this] { onGoBack(); }));
|
||||
activityManager.replaceActivity(std::make_unique<TxtReaderActivity>(renderer, mappedInput, std::move(txt)));
|
||||
}
|
||||
|
||||
void ReaderActivity::onEnter() {
|
||||
ActivityWithSubactivity::onEnter();
|
||||
Activity::onEnter();
|
||||
|
||||
if (initialBookPath.empty()) {
|
||||
goToLibrary(); // Start from root when entering via Browse
|
||||
@@ -146,3 +139,5 @@ void ReaderActivity::onEnter() {
|
||||
onGoToEpubReader(std::move(epub));
|
||||
}
|
||||
}
|
||||
|
||||
void ReaderActivity::onGoBack() { finish(); }
|
||||
|
||||
@@ -1,18 +1,16 @@
|
||||
#pragma once
|
||||
#include <memory>
|
||||
|
||||
#include "../ActivityWithSubactivity.h"
|
||||
#include "../Activity.h"
|
||||
#include "activities/home/MyLibraryActivity.h"
|
||||
|
||||
class Epub;
|
||||
class Xtc;
|
||||
class Txt;
|
||||
|
||||
class ReaderActivity final : public ActivityWithSubactivity {
|
||||
class ReaderActivity final : public Activity {
|
||||
std::string initialBookPath;
|
||||
std::string currentBookPath; // Track current book path for navigation
|
||||
const std::function<void()> onGoBack;
|
||||
const std::function<void(const std::string&)> onGoToLibrary;
|
||||
static std::unique_ptr<Epub> loadEpub(const std::string& path);
|
||||
static std::unique_ptr<Xtc> loadXtc(const std::string& path);
|
||||
static std::unique_ptr<Txt> loadTxt(const std::string& path);
|
||||
@@ -27,14 +25,11 @@ class ReaderActivity final : public ActivityWithSubactivity {
|
||||
void onGoToTxtReader(std::unique_ptr<Txt> txt);
|
||||
void onGoToBmpViewer(const std::string& path);
|
||||
|
||||
void onGoBack();
|
||||
|
||||
public:
|
||||
explicit ReaderActivity(GfxRenderer& renderer, MappedInputManager& mappedInput, std::string initialBookPath,
|
||||
const std::function<void()>& onGoBack,
|
||||
const std::function<void(const std::string&)>& onGoToLibrary)
|
||||
: ActivityWithSubactivity("Reader", renderer, mappedInput),
|
||||
initialBookPath(std::move(initialBookPath)),
|
||||
onGoBack(onGoBack),
|
||||
onGoToLibrary(onGoToLibrary) {}
|
||||
explicit ReaderActivity(GfxRenderer& renderer, MappedInputManager& mappedInput, std::string initialBookPath)
|
||||
: Activity("Reader", renderer, mappedInput), initialBookPath(std::move(initialBookPath)) {}
|
||||
void onEnter() override;
|
||||
bool isReaderActivity() const override { return true; }
|
||||
};
|
||||
|
||||
@@ -23,7 +23,7 @@ constexpr uint8_t CACHE_VERSION = 2; // Increment when cache format cha
|
||||
} // namespace
|
||||
|
||||
void TxtReaderActivity::onEnter() {
|
||||
ActivityWithSubactivity::onEnter();
|
||||
Activity::onEnter();
|
||||
|
||||
if (!txt) {
|
||||
return;
|
||||
@@ -61,7 +61,7 @@ void TxtReaderActivity::onEnter() {
|
||||
}
|
||||
|
||||
void TxtReaderActivity::onExit() {
|
||||
ActivityWithSubactivity::onExit();
|
||||
Activity::onExit();
|
||||
|
||||
// Reset orientation back to portrait for the rest of the UI
|
||||
renderer.setOrientation(GfxRenderer::Orientation::Portrait);
|
||||
@@ -74,14 +74,9 @@ void TxtReaderActivity::onExit() {
|
||||
}
|
||||
|
||||
void TxtReaderActivity::loop() {
|
||||
if (subActivity) {
|
||||
subActivity->loop();
|
||||
return;
|
||||
}
|
||||
|
||||
// Long press BACK (1s+) goes to file selection
|
||||
if (mappedInput.isPressed(MappedInputManager::Button::Back) && mappedInput.getHeldTime() >= goHomeMs) {
|
||||
onGoBack();
|
||||
activityManager.goToMyLibrary(txt ? txt->getPath() : "");
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -325,7 +320,7 @@ bool TxtReaderActivity::loadPageAtOffset(size_t offset, std::vector<std::string>
|
||||
return !outLines.empty();
|
||||
}
|
||||
|
||||
void TxtReaderActivity::render(Activity::RenderLock&&) {
|
||||
void TxtReaderActivity::render(RenderLock&&) {
|
||||
if (!txt) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -5,18 +5,15 @@
|
||||
#include <vector>
|
||||
|
||||
#include "CrossPointSettings.h"
|
||||
#include "activities/ActivityWithSubactivity.h"
|
||||
#include "activities/Activity.h"
|
||||
|
||||
class TxtReaderActivity final : public ActivityWithSubactivity {
|
||||
class TxtReaderActivity final : public Activity {
|
||||
std::unique_ptr<Txt> txt;
|
||||
|
||||
int currentPage = 0;
|
||||
int totalPages = 1;
|
||||
int pagesUntilFullRefresh = 0;
|
||||
|
||||
const std::function<void()> onGoBack;
|
||||
const std::function<void()> onGoHome;
|
||||
|
||||
// Streaming text reader - stores file offsets for each page
|
||||
std::vector<size_t> pageOffsets; // File offset for start of each page
|
||||
std::vector<std::string> currentPageLines;
|
||||
@@ -45,14 +42,11 @@ class TxtReaderActivity final : public ActivityWithSubactivity {
|
||||
void loadProgress();
|
||||
|
||||
public:
|
||||
explicit TxtReaderActivity(GfxRenderer& renderer, MappedInputManager& mappedInput, std::unique_ptr<Txt> txt,
|
||||
const std::function<void()>& onGoBack, const std::function<void()>& onGoHome)
|
||||
: ActivityWithSubactivity("TxtReader", renderer, mappedInput),
|
||||
txt(std::move(txt)),
|
||||
onGoBack(onGoBack),
|
||||
onGoHome(onGoHome) {}
|
||||
explicit TxtReaderActivity(GfxRenderer& renderer, MappedInputManager& mappedInput, std::unique_ptr<Txt> txt)
|
||||
: Activity("TxtReader", renderer, mappedInput), txt(std::move(txt)) {}
|
||||
void onEnter() override;
|
||||
void onExit() override;
|
||||
void loop() override;
|
||||
void render(Activity::RenderLock&&) override;
|
||||
void render(RenderLock&&) override;
|
||||
bool isReaderActivity() const override { return true; }
|
||||
};
|
||||
|
||||
@@ -26,7 +26,7 @@ constexpr unsigned long goHomeMs = 1000;
|
||||
} // namespace
|
||||
|
||||
void XtcReaderActivity::onEnter() {
|
||||
ActivityWithSubactivity::onEnter();
|
||||
Activity::onEnter();
|
||||
|
||||
if (!xtc) {
|
||||
return;
|
||||
@@ -47,7 +47,7 @@ void XtcReaderActivity::onEnter() {
|
||||
}
|
||||
|
||||
void XtcReaderActivity::onExit() {
|
||||
ActivityWithSubactivity::onExit();
|
||||
Activity::onExit();
|
||||
|
||||
APP_STATE.readerActivityLoadCount = 0;
|
||||
APP_STATE.saveToFile();
|
||||
@@ -55,33 +55,22 @@ void XtcReaderActivity::onExit() {
|
||||
}
|
||||
|
||||
void XtcReaderActivity::loop() {
|
||||
// Pass input responsibility to sub activity if exists
|
||||
if (subActivity) {
|
||||
subActivity->loop();
|
||||
return;
|
||||
}
|
||||
|
||||
// Enter chapter selection activity
|
||||
if (mappedInput.wasReleased(MappedInputManager::Button::Confirm)) {
|
||||
if (xtc && xtc->hasChapters() && !xtc->getChapters().empty()) {
|
||||
exitActivity();
|
||||
enterNewActivity(new XtcReaderChapterSelectionActivity(
|
||||
this->renderer, this->mappedInput, xtc, currentPage,
|
||||
[this] {
|
||||
exitActivity();
|
||||
requestUpdate();
|
||||
},
|
||||
[this](const uint32_t newPage) {
|
||||
currentPage = newPage;
|
||||
exitActivity();
|
||||
requestUpdate();
|
||||
}));
|
||||
startActivityForResult(
|
||||
std::make_unique<XtcReaderChapterSelectionActivity>(renderer, mappedInput, xtc, currentPage),
|
||||
[this](const ActivityResult& result) {
|
||||
if (!result.isCancelled) {
|
||||
currentPage = std::get<PageResult>(result.data).page;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Long press BACK (1s+) goes to file selection
|
||||
if (mappedInput.isPressed(MappedInputManager::Button::Back) && mappedInput.getHeldTime() >= goHomeMs) {
|
||||
onGoBack();
|
||||
activityManager.goToMyLibrary(xtc ? xtc->getPath() : "");
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -135,7 +124,7 @@ void XtcReaderActivity::loop() {
|
||||
}
|
||||
}
|
||||
|
||||
void XtcReaderActivity::render(Activity::RenderLock&&) {
|
||||
void XtcReaderActivity::render(RenderLock&&) {
|
||||
if (!xtc) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -9,30 +9,24 @@
|
||||
|
||||
#include <Xtc.h>
|
||||
|
||||
#include "activities/ActivityWithSubactivity.h"
|
||||
#include "activities/Activity.h"
|
||||
|
||||
class XtcReaderActivity final : public ActivityWithSubactivity {
|
||||
class XtcReaderActivity final : public Activity {
|
||||
std::shared_ptr<Xtc> xtc;
|
||||
|
||||
uint32_t currentPage = 0;
|
||||
int pagesUntilFullRefresh = 0;
|
||||
|
||||
const std::function<void()> onGoBack;
|
||||
const std::function<void()> onGoHome;
|
||||
|
||||
void renderPage();
|
||||
void saveProgress() const;
|
||||
void loadProgress();
|
||||
|
||||
public:
|
||||
explicit XtcReaderActivity(GfxRenderer& renderer, MappedInputManager& mappedInput, std::unique_ptr<Xtc> xtc,
|
||||
const std::function<void()>& onGoBack, const std::function<void()>& onGoHome)
|
||||
: ActivityWithSubactivity("XtcReader", renderer, mappedInput),
|
||||
xtc(std::move(xtc)),
|
||||
onGoBack(onGoBack),
|
||||
onGoHome(onGoHome) {}
|
||||
explicit XtcReaderActivity(GfxRenderer& renderer, MappedInputManager& mappedInput, std::unique_ptr<Xtc> xtc)
|
||||
: Activity("XtcReader", renderer, mappedInput), xtc(std::move(xtc)) {}
|
||||
void onEnter() override;
|
||||
void onExit() override;
|
||||
void loop() override;
|
||||
void render(Activity::RenderLock&&) override;
|
||||
void render(RenderLock&&) override;
|
||||
bool isReaderActivity() const override { return true; }
|
||||
};
|
||||
|
||||
@@ -59,10 +59,14 @@ void XtcReaderChapterSelectionActivity::loop() {
|
||||
if (mappedInput.wasReleased(MappedInputManager::Button::Confirm)) {
|
||||
const auto& chapters = xtc->getChapters();
|
||||
if (!chapters.empty() && selectorIndex >= 0 && selectorIndex < static_cast<int>(chapters.size())) {
|
||||
onSelectPage(chapters[selectorIndex].startPage);
|
||||
setResult(PageResult{chapters[selectorIndex].startPage});
|
||||
finish();
|
||||
}
|
||||
} else if (mappedInput.wasReleased(MappedInputManager::Button::Back)) {
|
||||
onGoBack();
|
||||
ActivityResult result;
|
||||
result.isCancelled = true;
|
||||
setResult(std::move(result));
|
||||
finish();
|
||||
}
|
||||
|
||||
buttonNavigator.onNextRelease([this, totalItems] {
|
||||
@@ -86,7 +90,7 @@ void XtcReaderChapterSelectionActivity::loop() {
|
||||
});
|
||||
}
|
||||
|
||||
void XtcReaderChapterSelectionActivity::render(Activity::RenderLock&&) {
|
||||
void XtcReaderChapterSelectionActivity::render(RenderLock&&) {
|
||||
renderer.clearScreen();
|
||||
|
||||
const auto pageWidth = renderer.getScreenWidth();
|
||||
|
||||
@@ -12,24 +12,16 @@ class XtcReaderChapterSelectionActivity final : public Activity {
|
||||
uint32_t currentPage = 0;
|
||||
int selectorIndex = 0;
|
||||
|
||||
const std::function<void()> onGoBack;
|
||||
const std::function<void(uint32_t newPage)> onSelectPage;
|
||||
|
||||
int getPageItems() const;
|
||||
int findChapterIndexForPage(uint32_t page) const;
|
||||
|
||||
public:
|
||||
explicit XtcReaderChapterSelectionActivity(GfxRenderer& renderer, MappedInputManager& mappedInput,
|
||||
const std::shared_ptr<Xtc>& xtc, uint32_t currentPage,
|
||||
const std::function<void()>& onGoBack,
|
||||
const std::function<void(uint32_t newPage)>& onSelectPage)
|
||||
: Activity("XtcReaderChapterSelection", renderer, mappedInput),
|
||||
xtc(xtc),
|
||||
currentPage(currentPage),
|
||||
onGoBack(onGoBack),
|
||||
onSelectPage(onSelectPage) {}
|
||||
const std::shared_ptr<Xtc>& xtc, uint32_t currentPage)
|
||||
: Activity("XtcReaderChapterSelection", renderer, mappedInput), xtc(xtc), currentPage(currentPage) {}
|
||||
void onEnter() override;
|
||||
void onExit() override;
|
||||
void loop() override;
|
||||
void render(Activity::RenderLock&&) override;
|
||||
void render(RenderLock&&) override;
|
||||
bool isReaderActivity() const override { return true; }
|
||||
};
|
||||
|
||||
@@ -52,20 +52,20 @@ void ButtonRemapActivity::loop() {
|
||||
SETTINGS.frontButtonLeft = CrossPointSettings::FRONT_HW_LEFT;
|
||||
SETTINGS.frontButtonRight = CrossPointSettings::FRONT_HW_RIGHT;
|
||||
SETTINGS.saveToFile();
|
||||
onBack();
|
||||
finish();
|
||||
return;
|
||||
}
|
||||
|
||||
if (mappedInput.wasPressed(MappedInputManager::Button::Down)) {
|
||||
// Exit without changing settings.
|
||||
onBack();
|
||||
finish();
|
||||
return;
|
||||
}
|
||||
|
||||
{
|
||||
// Wait for the UI to refresh before accepting another assignment.
|
||||
// Make sure UI done rendering before accepting another assignment.
|
||||
// This avoids rapid double-presses that can advance the step without a visible redraw.
|
||||
requestUpdateAndWait();
|
||||
RenderLock lock(*this);
|
||||
|
||||
// Wait for a front button press to assign to the current role.
|
||||
const int pressedButton = mappedInput.getPressedFrontButton();
|
||||
@@ -86,7 +86,7 @@ void ButtonRemapActivity::loop() {
|
||||
// All roles assigned; save to settings and exit.
|
||||
applyTempMapping();
|
||||
SETTINGS.saveToFile();
|
||||
onBack();
|
||||
finish();
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -94,7 +94,7 @@ void ButtonRemapActivity::loop() {
|
||||
}
|
||||
}
|
||||
|
||||
void ButtonRemapActivity::render(Activity::RenderLock&&) {
|
||||
void ButtonRemapActivity::render(RenderLock&&) {
|
||||
const auto labelForHardware = [&](uint8_t hardwareIndex) -> const char* {
|
||||
for (uint8_t i = 0; i < kRoleCount; i++) {
|
||||
if (tempMapping[i] == hardwareIndex) {
|
||||
|
||||
@@ -7,20 +7,17 @@
|
||||
|
||||
class ButtonRemapActivity final : public Activity {
|
||||
public:
|
||||
explicit ButtonRemapActivity(GfxRenderer& renderer, MappedInputManager& mappedInput,
|
||||
const std::function<void()>& onBack)
|
||||
: Activity("ButtonRemap", renderer, mappedInput), onBack(onBack) {}
|
||||
explicit ButtonRemapActivity(GfxRenderer& renderer, MappedInputManager& mappedInput)
|
||||
: Activity("ButtonRemap", renderer, mappedInput) {}
|
||||
|
||||
void onEnter() override;
|
||||
void onExit() override;
|
||||
void loop() override;
|
||||
void render(Activity::RenderLock&&) override;
|
||||
void render(RenderLock&&) override;
|
||||
|
||||
private:
|
||||
// Rendering task state.
|
||||
|
||||
// Callback used to exit the remap flow back to the settings list.
|
||||
const std::function<void()> onBack;
|
||||
// Index of the logical role currently awaiting input.
|
||||
uint8_t currentStep = 0;
|
||||
// Temporary mapping from logical role -> hardware button index.
|
||||
|
||||
@@ -17,22 +17,17 @@ const StrId menuNames[MENU_ITEMS] = {StrId::STR_CALIBRE_WEB_URL, StrId::STR_USER
|
||||
} // namespace
|
||||
|
||||
void CalibreSettingsActivity::onEnter() {
|
||||
ActivityWithSubactivity::onEnter();
|
||||
Activity::onEnter();
|
||||
|
||||
selectedIndex = 0;
|
||||
requestUpdate();
|
||||
}
|
||||
|
||||
void CalibreSettingsActivity::onExit() { ActivityWithSubactivity::onExit(); }
|
||||
void CalibreSettingsActivity::onExit() { Activity::onExit(); }
|
||||
|
||||
void CalibreSettingsActivity::loop() {
|
||||
if (subActivity) {
|
||||
subActivity->loop();
|
||||
return;
|
||||
}
|
||||
|
||||
if (mappedInput.wasPressed(MappedInputManager::Button::Back)) {
|
||||
onBack();
|
||||
activityManager.popActivity();
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -56,62 +51,44 @@ void CalibreSettingsActivity::loop() {
|
||||
void CalibreSettingsActivity::handleSelection() {
|
||||
if (selectedIndex == 0) {
|
||||
// OPDS Server URL
|
||||
exitActivity();
|
||||
enterNewActivity(new KeyboardEntryActivity(
|
||||
renderer, mappedInput, tr(STR_CALIBRE_WEB_URL), SETTINGS.opdsServerUrl,
|
||||
127, // maxLength
|
||||
false, // not password
|
||||
[this](const std::string& url) {
|
||||
strncpy(SETTINGS.opdsServerUrl, url.c_str(), sizeof(SETTINGS.opdsServerUrl) - 1);
|
||||
SETTINGS.opdsServerUrl[sizeof(SETTINGS.opdsServerUrl) - 1] = '\0';
|
||||
SETTINGS.saveToFile();
|
||||
exitActivity();
|
||||
requestUpdate();
|
||||
},
|
||||
[this]() {
|
||||
exitActivity();
|
||||
requestUpdate();
|
||||
}));
|
||||
startActivityForResult(std::make_unique<KeyboardEntryActivity>(renderer, mappedInput, tr(STR_CALIBRE_WEB_URL),
|
||||
SETTINGS.opdsServerUrl, 127, false),
|
||||
[this](const ActivityResult& result) {
|
||||
if (!result.isCancelled) {
|
||||
const auto& kb = std::get<KeyboardResult>(result.data);
|
||||
strncpy(SETTINGS.opdsServerUrl, kb.text.c_str(), sizeof(SETTINGS.opdsServerUrl) - 1);
|
||||
SETTINGS.opdsServerUrl[sizeof(SETTINGS.opdsServerUrl) - 1] = '\0';
|
||||
SETTINGS.saveToFile();
|
||||
}
|
||||
});
|
||||
} else if (selectedIndex == 1) {
|
||||
// Username
|
||||
exitActivity();
|
||||
enterNewActivity(new KeyboardEntryActivity(
|
||||
renderer, mappedInput, tr(STR_USERNAME), SETTINGS.opdsUsername,
|
||||
63, // maxLength
|
||||
false, // not password
|
||||
[this](const std::string& username) {
|
||||
strncpy(SETTINGS.opdsUsername, username.c_str(), sizeof(SETTINGS.opdsUsername) - 1);
|
||||
SETTINGS.opdsUsername[sizeof(SETTINGS.opdsUsername) - 1] = '\0';
|
||||
SETTINGS.saveToFile();
|
||||
exitActivity();
|
||||
requestUpdate();
|
||||
},
|
||||
[this]() {
|
||||
exitActivity();
|
||||
requestUpdate();
|
||||
}));
|
||||
startActivityForResult(std::make_unique<KeyboardEntryActivity>(renderer, mappedInput, tr(STR_USERNAME),
|
||||
SETTINGS.opdsUsername, 63, false),
|
||||
[this](const ActivityResult& result) {
|
||||
if (!result.isCancelled) {
|
||||
const auto& kb = std::get<KeyboardResult>(result.data);
|
||||
strncpy(SETTINGS.opdsUsername, kb.text.c_str(), sizeof(SETTINGS.opdsUsername) - 1);
|
||||
SETTINGS.opdsUsername[sizeof(SETTINGS.opdsUsername) - 1] = '\0';
|
||||
SETTINGS.saveToFile();
|
||||
}
|
||||
});
|
||||
} else if (selectedIndex == 2) {
|
||||
// Password
|
||||
exitActivity();
|
||||
enterNewActivity(new KeyboardEntryActivity(
|
||||
renderer, mappedInput, tr(STR_PASSWORD), SETTINGS.opdsPassword,
|
||||
63, // maxLength
|
||||
false, // not password mode
|
||||
[this](const std::string& password) {
|
||||
strncpy(SETTINGS.opdsPassword, password.c_str(), sizeof(SETTINGS.opdsPassword) - 1);
|
||||
SETTINGS.opdsPassword[sizeof(SETTINGS.opdsPassword) - 1] = '\0';
|
||||
SETTINGS.saveToFile();
|
||||
exitActivity();
|
||||
requestUpdate();
|
||||
},
|
||||
[this]() {
|
||||
exitActivity();
|
||||
requestUpdate();
|
||||
}));
|
||||
startActivityForResult(std::make_unique<KeyboardEntryActivity>(renderer, mappedInput, tr(STR_PASSWORD),
|
||||
SETTINGS.opdsPassword, 63, false),
|
||||
[this](const ActivityResult& result) {
|
||||
if (!result.isCancelled) {
|
||||
const auto& kb = std::get<KeyboardResult>(result.data);
|
||||
strncpy(SETTINGS.opdsPassword, kb.text.c_str(), sizeof(SETTINGS.opdsPassword) - 1);
|
||||
SETTINGS.opdsPassword[sizeof(SETTINGS.opdsPassword) - 1] = '\0';
|
||||
SETTINGS.saveToFile();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
void CalibreSettingsActivity::render(Activity::RenderLock&&) {
|
||||
void CalibreSettingsActivity::render(RenderLock&&) {
|
||||
renderer.clearScreen();
|
||||
|
||||
const auto& metrics = UITheme::getInstance().getMetrics();
|
||||
|
||||
@@ -1,29 +1,25 @@
|
||||
#pragma once
|
||||
|
||||
#include <functional>
|
||||
|
||||
#include "activities/ActivityWithSubactivity.h"
|
||||
#include "activities/Activity.h"
|
||||
#include "util/ButtonNavigator.h"
|
||||
|
||||
/**
|
||||
* Submenu for OPDS Browser settings.
|
||||
* Shows OPDS Server URL and HTTP authentication options.
|
||||
*/
|
||||
class CalibreSettingsActivity final : public ActivityWithSubactivity {
|
||||
class CalibreSettingsActivity final : public Activity {
|
||||
public:
|
||||
explicit CalibreSettingsActivity(GfxRenderer& renderer, MappedInputManager& mappedInput,
|
||||
const std::function<void()>& onBack)
|
||||
: ActivityWithSubactivity("CalibreSettings", renderer, mappedInput), onBack(onBack) {}
|
||||
explicit CalibreSettingsActivity(GfxRenderer& renderer, MappedInputManager& mappedInput)
|
||||
: Activity("CalibreSettings", renderer, mappedInput) {}
|
||||
|
||||
void onEnter() override;
|
||||
void onExit() override;
|
||||
void loop() override;
|
||||
void render(Activity::RenderLock&&) override;
|
||||
void render(RenderLock&&) override;
|
||||
|
||||
private:
|
||||
ButtonNavigator buttonNavigator;
|
||||
|
||||
size_t selectedIndex = 0;
|
||||
const std::function<void()> onBack;
|
||||
void handleSelection();
|
||||
};
|
||||
|
||||
@@ -10,15 +10,15 @@
|
||||
#include "fontIds.h"
|
||||
|
||||
void ClearCacheActivity::onEnter() {
|
||||
ActivityWithSubactivity::onEnter();
|
||||
Activity::onEnter();
|
||||
|
||||
state = WARNING;
|
||||
requestUpdate();
|
||||
}
|
||||
|
||||
void ClearCacheActivity::onExit() { ActivityWithSubactivity::onExit(); }
|
||||
void ClearCacheActivity::onExit() { Activity::onExit(); }
|
||||
|
||||
void ClearCacheActivity::render(Activity::RenderLock&&) {
|
||||
void ClearCacheActivity::render(RenderLock&&) {
|
||||
const auto& metrics = UITheme::getInstance().getMetrics();
|
||||
const auto pageWidth = renderer.getScreenWidth();
|
||||
const auto pageHeight = renderer.getScreenHeight();
|
||||
|
||||
@@ -2,26 +2,25 @@
|
||||
|
||||
#include <functional>
|
||||
|
||||
#include "activities/ActivityWithSubactivity.h"
|
||||
#include "activities/Activity.h"
|
||||
|
||||
class ClearCacheActivity final : public ActivityWithSubactivity {
|
||||
class ClearCacheActivity final : public Activity {
|
||||
public:
|
||||
explicit ClearCacheActivity(GfxRenderer& renderer, MappedInputManager& mappedInput,
|
||||
const std::function<void()>& goBack)
|
||||
: ActivityWithSubactivity("ClearCache", renderer, mappedInput), goBack(goBack) {}
|
||||
explicit ClearCacheActivity(GfxRenderer& renderer, MappedInputManager& mappedInput)
|
||||
: Activity("ClearCache", renderer, mappedInput) {}
|
||||
|
||||
void onEnter() override;
|
||||
void onExit() override;
|
||||
void loop() override;
|
||||
bool skipLoopDelay() override { return true; } // Prevent power-saving mode
|
||||
void render(Activity::RenderLock&&) override;
|
||||
void render(RenderLock&&) override;
|
||||
|
||||
private:
|
||||
enum State { WARNING, CLEARING, SUCCESS, FAILED };
|
||||
|
||||
State state = WARNING;
|
||||
|
||||
const std::function<void()> goBack;
|
||||
void goBack() { finish(); }
|
||||
|
||||
int clearedCount = 0;
|
||||
int failedCount = 0;
|
||||
|
||||
@@ -12,8 +12,6 @@
|
||||
#include "fontIds.h"
|
||||
|
||||
void KOReaderAuthActivity::onWifiSelectionComplete(const bool success) {
|
||||
exitActivity();
|
||||
|
||||
if (!success) {
|
||||
{
|
||||
RenderLock lock(*this);
|
||||
@@ -51,7 +49,7 @@ void KOReaderAuthActivity::performAuthentication() {
|
||||
}
|
||||
|
||||
void KOReaderAuthActivity::onEnter() {
|
||||
ActivityWithSubactivity::onEnter();
|
||||
Activity::onEnter();
|
||||
|
||||
// Turn on WiFi
|
||||
WiFi.mode(WIFI_STA);
|
||||
@@ -74,12 +72,12 @@ void KOReaderAuthActivity::onEnter() {
|
||||
}
|
||||
|
||||
// Launch WiFi selection
|
||||
enterNewActivity(new WifiSelectionActivity(renderer, mappedInput,
|
||||
[this](const bool connected) { onWifiSelectionComplete(connected); }));
|
||||
startActivityForResult(std::make_unique<WifiSelectionActivity>(renderer, mappedInput),
|
||||
[this](const ActivityResult& result) { onWifiSelectionComplete(!result.isCancelled); });
|
||||
}
|
||||
|
||||
void KOReaderAuthActivity::onExit() {
|
||||
ActivityWithSubactivity::onExit();
|
||||
Activity::onExit();
|
||||
|
||||
// Turn off wifi
|
||||
WiFi.disconnect(false);
|
||||
@@ -88,7 +86,7 @@ void KOReaderAuthActivity::onExit() {
|
||||
delay(100);
|
||||
}
|
||||
|
||||
void KOReaderAuthActivity::render(Activity::RenderLock&&) {
|
||||
void KOReaderAuthActivity::render(RenderLock&&) {
|
||||
renderer.clearScreen();
|
||||
|
||||
const auto& metrics = UITheme::getInstance().getMetrics();
|
||||
@@ -115,15 +113,10 @@ void KOReaderAuthActivity::render(Activity::RenderLock&&) {
|
||||
}
|
||||
|
||||
void KOReaderAuthActivity::loop() {
|
||||
if (subActivity) {
|
||||
subActivity->loop();
|
||||
return;
|
||||
}
|
||||
|
||||
if (state == SUCCESS || state == FAILED) {
|
||||
if (mappedInput.wasPressed(MappedInputManager::Button::Back) ||
|
||||
mappedInput.wasPressed(MappedInputManager::Button::Confirm)) {
|
||||
onComplete();
|
||||
finish();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,22 +2,21 @@
|
||||
|
||||
#include <functional>
|
||||
|
||||
#include "activities/ActivityWithSubactivity.h"
|
||||
#include "activities/Activity.h"
|
||||
|
||||
/**
|
||||
* Activity for testing KOReader credentials.
|
||||
* Connects to WiFi and authenticates with the KOReader sync server.
|
||||
*/
|
||||
class KOReaderAuthActivity final : public ActivityWithSubactivity {
|
||||
class KOReaderAuthActivity final : public Activity {
|
||||
public:
|
||||
explicit KOReaderAuthActivity(GfxRenderer& renderer, MappedInputManager& mappedInput,
|
||||
const std::function<void()>& onComplete)
|
||||
: ActivityWithSubactivity("KOReaderAuth", renderer, mappedInput), onComplete(onComplete) {}
|
||||
explicit KOReaderAuthActivity(GfxRenderer& renderer, MappedInputManager& mappedInput)
|
||||
: Activity("KOReaderAuth", renderer, mappedInput) {}
|
||||
|
||||
void onEnter() override;
|
||||
void onExit() override;
|
||||
void loop() override;
|
||||
void render(Activity::RenderLock&&) override;
|
||||
void render(RenderLock&&) override;
|
||||
bool preventAutoSleep() override { return state == CONNECTING || state == AUTHENTICATING; }
|
||||
|
||||
private:
|
||||
@@ -27,8 +26,6 @@ class KOReaderAuthActivity final : public ActivityWithSubactivity {
|
||||
std::string statusMessage;
|
||||
std::string errorMessage;
|
||||
|
||||
const std::function<void()> onComplete;
|
||||
|
||||
void onWifiSelectionComplete(bool success);
|
||||
void performAuthentication();
|
||||
};
|
||||
|
||||
@@ -19,22 +19,17 @@ const StrId menuNames[MENU_ITEMS] = {StrId::STR_USERNAME, StrId::STR_PASSWORD, S
|
||||
} // namespace
|
||||
|
||||
void KOReaderSettingsActivity::onEnter() {
|
||||
ActivityWithSubactivity::onEnter();
|
||||
Activity::onEnter();
|
||||
|
||||
selectedIndex = 0;
|
||||
requestUpdate();
|
||||
}
|
||||
|
||||
void KOReaderSettingsActivity::onExit() { ActivityWithSubactivity::onExit(); }
|
||||
void KOReaderSettingsActivity::onExit() { Activity::onExit(); }
|
||||
|
||||
void KOReaderSettingsActivity::loop() {
|
||||
if (subActivity) {
|
||||
subActivity->loop();
|
||||
return;
|
||||
}
|
||||
|
||||
if (mappedInput.wasPressed(MappedInputManager::Button::Back)) {
|
||||
onBack();
|
||||
activityManager.popActivity();
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -58,59 +53,46 @@ void KOReaderSettingsActivity::loop() {
|
||||
void KOReaderSettingsActivity::handleSelection() {
|
||||
if (selectedIndex == 0) {
|
||||
// Username
|
||||
exitActivity();
|
||||
enterNewActivity(new KeyboardEntryActivity(
|
||||
renderer, mappedInput, tr(STR_KOREADER_USERNAME), KOREADER_STORE.getUsername(),
|
||||
64, // maxLength
|
||||
false, // not password
|
||||
[this](const std::string& username) {
|
||||
KOREADER_STORE.setCredentials(username, KOREADER_STORE.getPassword());
|
||||
KOREADER_STORE.saveToFile();
|
||||
exitActivity();
|
||||
requestUpdate();
|
||||
},
|
||||
[this]() {
|
||||
exitActivity();
|
||||
requestUpdate();
|
||||
}));
|
||||
startActivityForResult(std::make_unique<KeyboardEntryActivity>(renderer, mappedInput, tr(STR_KOREADER_USERNAME),
|
||||
KOREADER_STORE.getUsername(),
|
||||
64, // maxLength
|
||||
false), // not password
|
||||
[this](const ActivityResult& result) {
|
||||
if (!result.isCancelled) {
|
||||
const auto& kb = std::get<KeyboardResult>(result.data);
|
||||
KOREADER_STORE.setCredentials(kb.text, KOREADER_STORE.getPassword());
|
||||
KOREADER_STORE.saveToFile();
|
||||
}
|
||||
});
|
||||
} else if (selectedIndex == 1) {
|
||||
// Password
|
||||
exitActivity();
|
||||
enterNewActivity(new KeyboardEntryActivity(
|
||||
renderer, mappedInput, tr(STR_KOREADER_PASSWORD), KOREADER_STORE.getPassword(),
|
||||
64, // maxLength
|
||||
false, // show characters
|
||||
[this](const std::string& password) {
|
||||
KOREADER_STORE.setCredentials(KOREADER_STORE.getUsername(), password);
|
||||
KOREADER_STORE.saveToFile();
|
||||
exitActivity();
|
||||
requestUpdate();
|
||||
},
|
||||
[this]() {
|
||||
exitActivity();
|
||||
requestUpdate();
|
||||
}));
|
||||
startActivityForResult(std::make_unique<KeyboardEntryActivity>(renderer, mappedInput, tr(STR_KOREADER_PASSWORD),
|
||||
KOREADER_STORE.getPassword(),
|
||||
64, // maxLength
|
||||
false), // show characters
|
||||
[this](const ActivityResult& result) {
|
||||
if (!result.isCancelled) {
|
||||
const auto& kb = std::get<KeyboardResult>(result.data);
|
||||
KOREADER_STORE.setCredentials(KOREADER_STORE.getUsername(), kb.text);
|
||||
KOREADER_STORE.saveToFile();
|
||||
}
|
||||
});
|
||||
} else if (selectedIndex == 2) {
|
||||
// Sync Server URL - prefill with https:// if empty to save typing
|
||||
const std::string currentUrl = KOREADER_STORE.getServerUrl();
|
||||
const std::string prefillUrl = currentUrl.empty() ? "https://" : currentUrl;
|
||||
exitActivity();
|
||||
enterNewActivity(new KeyboardEntryActivity(
|
||||
renderer, mappedInput, tr(STR_SYNC_SERVER_URL), prefillUrl,
|
||||
128, // maxLength - URLs can be long
|
||||
false, // not password
|
||||
[this](const std::string& url) {
|
||||
// Clear if user just left the prefilled https://
|
||||
const std::string urlToSave = (url == "https://" || url == "http://") ? "" : url;
|
||||
KOREADER_STORE.setServerUrl(urlToSave);
|
||||
KOREADER_STORE.saveToFile();
|
||||
exitActivity();
|
||||
requestUpdate();
|
||||
},
|
||||
[this]() {
|
||||
exitActivity();
|
||||
requestUpdate();
|
||||
}));
|
||||
startActivityForResult(
|
||||
std::make_unique<KeyboardEntryActivity>(renderer, mappedInput, tr(STR_SYNC_SERVER_URL), prefillUrl,
|
||||
128, // maxLength - URLs can be long
|
||||
false), // not password
|
||||
[this](const ActivityResult& result) {
|
||||
if (!result.isCancelled) {
|
||||
const auto& kb = std::get<KeyboardResult>(result.data);
|
||||
const std::string urlToSave = (kb.text == "https://" || kb.text == "http://") ? "" : kb.text;
|
||||
KOREADER_STORE.setServerUrl(urlToSave);
|
||||
KOREADER_STORE.saveToFile();
|
||||
}
|
||||
});
|
||||
} else if (selectedIndex == 3) {
|
||||
// Document Matching - toggle between Filename and Binary
|
||||
const auto current = KOREADER_STORE.getMatchMethod();
|
||||
@@ -125,15 +107,11 @@ void KOReaderSettingsActivity::handleSelection() {
|
||||
// Can't authenticate without credentials - just show message briefly
|
||||
return;
|
||||
}
|
||||
exitActivity();
|
||||
enterNewActivity(new KOReaderAuthActivity(renderer, mappedInput, [this] {
|
||||
exitActivity();
|
||||
requestUpdate();
|
||||
}));
|
||||
startActivityForResult(std::make_unique<KOReaderAuthActivity>(renderer, mappedInput), [](const ActivityResult&) {});
|
||||
}
|
||||
}
|
||||
|
||||
void KOReaderSettingsActivity::render(Activity::RenderLock&&) {
|
||||
void KOReaderSettingsActivity::render(RenderLock&&) {
|
||||
renderer.clearScreen();
|
||||
|
||||
const auto& metrics = UITheme::getInstance().getMetrics();
|
||||
|
||||
@@ -1,30 +1,26 @@
|
||||
#pragma once
|
||||
|
||||
#include <functional>
|
||||
|
||||
#include "activities/ActivityWithSubactivity.h"
|
||||
#include "activities/Activity.h"
|
||||
#include "util/ButtonNavigator.h"
|
||||
|
||||
/**
|
||||
* Submenu for KOReader Sync settings.
|
||||
* Shows username, password, and authenticate options.
|
||||
*/
|
||||
class KOReaderSettingsActivity final : public ActivityWithSubactivity {
|
||||
class KOReaderSettingsActivity final : public Activity {
|
||||
public:
|
||||
explicit KOReaderSettingsActivity(GfxRenderer& renderer, MappedInputManager& mappedInput,
|
||||
const std::function<void()>& onBack)
|
||||
: ActivityWithSubactivity("KOReaderSettings", renderer, mappedInput), onBack(onBack) {}
|
||||
explicit KOReaderSettingsActivity(GfxRenderer& renderer, MappedInputManager& mappedInput)
|
||||
: Activity("KOReaderSettings", renderer, mappedInput) {}
|
||||
|
||||
void onEnter() override;
|
||||
void onExit() override;
|
||||
void loop() override;
|
||||
void render(Activity::RenderLock&&) override;
|
||||
void render(RenderLock&&) override;
|
||||
|
||||
private:
|
||||
ButtonNavigator buttonNavigator;
|
||||
|
||||
size_t selectedIndex = 0;
|
||||
const std::function<void()> onBack;
|
||||
|
||||
void handleSelection();
|
||||
};
|
||||
|
||||
@@ -58,7 +58,7 @@ void LanguageSelectActivity::handleSelection() {
|
||||
onBack();
|
||||
}
|
||||
|
||||
void LanguageSelectActivity::render(Activity::RenderLock&&) {
|
||||
void LanguageSelectActivity::render(RenderLock&&) {
|
||||
renderer.clearScreen();
|
||||
|
||||
const auto pageWidth = renderer.getScreenWidth();
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
|
||||
#include <functional>
|
||||
|
||||
#include "../ActivityWithSubactivity.h"
|
||||
#include "../Activity.h"
|
||||
#include "components/UITheme.h"
|
||||
#include "util/ButtonNavigator.h"
|
||||
|
||||
@@ -16,19 +16,18 @@ class MappedInputManager;
|
||||
*/
|
||||
class LanguageSelectActivity final : public Activity {
|
||||
public:
|
||||
explicit LanguageSelectActivity(GfxRenderer& renderer, MappedInputManager& mappedInput,
|
||||
const std::function<void()>& onBack)
|
||||
: Activity("LanguageSelect", renderer, mappedInput), onBack(onBack) {}
|
||||
explicit LanguageSelectActivity(GfxRenderer& renderer, MappedInputManager& mappedInput)
|
||||
: Activity("LanguageSelect", renderer, mappedInput) {}
|
||||
|
||||
void onEnter() override;
|
||||
void onExit() override;
|
||||
void loop() override;
|
||||
void render(Activity::RenderLock&&) override;
|
||||
void render(RenderLock&&) override;
|
||||
|
||||
private:
|
||||
void handleSelection();
|
||||
|
||||
std::function<void()> onBack;
|
||||
void onBack() { finish(); }
|
||||
ButtonNavigator buttonNavigator;
|
||||
int selectedIndex = 0;
|
||||
constexpr static uint8_t totalItems = getLanguageCount();
|
||||
|
||||
@@ -11,11 +11,9 @@
|
||||
#include "network/OtaUpdater.h"
|
||||
|
||||
void OtaUpdateActivity::onWifiSelectionComplete(const bool success) {
|
||||
exitActivity();
|
||||
|
||||
if (!success) {
|
||||
LOG_ERR("OTA", "WiFi connection failed, exiting");
|
||||
goBack();
|
||||
activityManager.popActivity();
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -34,7 +32,6 @@ void OtaUpdateActivity::onWifiSelectionComplete(const bool success) {
|
||||
RenderLock lock(*this);
|
||||
state = FAILED;
|
||||
}
|
||||
requestUpdate();
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -44,7 +41,6 @@ void OtaUpdateActivity::onWifiSelectionComplete(const bool success) {
|
||||
RenderLock lock(*this);
|
||||
state = NO_UPDATE;
|
||||
}
|
||||
requestUpdate();
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -52,11 +48,10 @@ void OtaUpdateActivity::onWifiSelectionComplete(const bool success) {
|
||||
RenderLock lock(*this);
|
||||
state = WAITING_CONFIRMATION;
|
||||
}
|
||||
requestUpdate();
|
||||
}
|
||||
|
||||
void OtaUpdateActivity::onEnter() {
|
||||
ActivityWithSubactivity::onEnter();
|
||||
Activity::onEnter();
|
||||
|
||||
// Turn on WiFi immediately
|
||||
LOG_DBG("OTA", "Turning on WiFi...");
|
||||
@@ -64,12 +59,12 @@ void OtaUpdateActivity::onEnter() {
|
||||
|
||||
// Launch WiFi selection subactivity
|
||||
LOG_DBG("OTA", "Launching WifiSelectionActivity...");
|
||||
enterNewActivity(new WifiSelectionActivity(renderer, mappedInput,
|
||||
[this](const bool connected) { onWifiSelectionComplete(connected); }));
|
||||
startActivityForResult(std::make_unique<WifiSelectionActivity>(renderer, mappedInput),
|
||||
[this](const ActivityResult& result) { onWifiSelectionComplete(!result.isCancelled); });
|
||||
}
|
||||
|
||||
void OtaUpdateActivity::onExit() {
|
||||
ActivityWithSubactivity::onExit();
|
||||
Activity::onExit();
|
||||
|
||||
// Turn off wifi
|
||||
WiFi.disconnect(false); // false = don't erase credentials, send disconnect frame
|
||||
@@ -78,12 +73,7 @@ void OtaUpdateActivity::onExit() {
|
||||
delay(100); // Allow WiFi hardware to fully power down
|
||||
}
|
||||
|
||||
void OtaUpdateActivity::render(Activity::RenderLock&&) {
|
||||
if (subActivity) {
|
||||
// Subactivity handles its own rendering
|
||||
return;
|
||||
}
|
||||
|
||||
void OtaUpdateActivity::render(RenderLock&&) {
|
||||
const auto& metrics = UITheme::getInstance().getMetrics();
|
||||
const auto pageWidth = renderer.getScreenWidth();
|
||||
const auto pageHeight = renderer.getScreenHeight();
|
||||
@@ -154,11 +144,6 @@ void OtaUpdateActivity::loop() {
|
||||
requestUpdate();
|
||||
}
|
||||
|
||||
if (subActivity) {
|
||||
subActivity->loop();
|
||||
return;
|
||||
}
|
||||
|
||||
if (state == WAITING_CONFIRMATION) {
|
||||
if (mappedInput.wasPressed(MappedInputManager::Button::Confirm)) {
|
||||
LOG_DBG("OTA", "New update available, starting download...");
|
||||
@@ -166,7 +151,6 @@ void OtaUpdateActivity::loop() {
|
||||
RenderLock lock(*this);
|
||||
state = UPDATE_IN_PROGRESS;
|
||||
}
|
||||
requestUpdate();
|
||||
requestUpdateAndWait();
|
||||
const auto res = updater.installUpdate();
|
||||
|
||||
@@ -188,7 +172,7 @@ void OtaUpdateActivity::loop() {
|
||||
}
|
||||
|
||||
if (mappedInput.wasPressed(MappedInputManager::Button::Back)) {
|
||||
goBack();
|
||||
activityManager.popActivity();
|
||||
}
|
||||
|
||||
return;
|
||||
@@ -196,14 +180,14 @@ void OtaUpdateActivity::loop() {
|
||||
|
||||
if (state == FAILED) {
|
||||
if (mappedInput.wasPressed(MappedInputManager::Button::Back)) {
|
||||
goBack();
|
||||
activityManager.popActivity();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (state == NO_UPDATE) {
|
||||
if (mappedInput.wasPressed(MappedInputManager::Button::Back)) {
|
||||
goBack();
|
||||
activityManager.popActivity();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
#pragma once
|
||||
|
||||
#include "activities/ActivityWithSubactivity.h"
|
||||
#include "activities/Activity.h"
|
||||
#include "network/OtaUpdater.h"
|
||||
|
||||
class OtaUpdateActivity : public ActivityWithSubactivity {
|
||||
class OtaUpdateActivity : public Activity {
|
||||
enum State {
|
||||
WIFI_SELECTION,
|
||||
CHECKING_FOR_UPDATE,
|
||||
@@ -18,7 +18,6 @@ class OtaUpdateActivity : public ActivityWithSubactivity {
|
||||
// Can't initialize this to 0 or the first render doesn't happen
|
||||
static constexpr unsigned int UNINITIALIZED_PERCENTAGE = 111;
|
||||
|
||||
const std::function<void()> goBack;
|
||||
State state = WIFI_SELECTION;
|
||||
unsigned int lastUpdaterPercentage = UNINITIALIZED_PERCENTAGE;
|
||||
OtaUpdater updater;
|
||||
@@ -26,13 +25,12 @@ class OtaUpdateActivity : public ActivityWithSubactivity {
|
||||
void onWifiSelectionComplete(bool success);
|
||||
|
||||
public:
|
||||
explicit OtaUpdateActivity(GfxRenderer& renderer, MappedInputManager& mappedInput,
|
||||
const std::function<void()>& goBack)
|
||||
: ActivityWithSubactivity("OtaUpdate", renderer, mappedInput), goBack(goBack), updater() {}
|
||||
explicit OtaUpdateActivity(GfxRenderer& renderer, MappedInputManager& mappedInput)
|
||||
: Activity("OtaUpdate", renderer, mappedInput), updater() {}
|
||||
void onEnter() override;
|
||||
void onExit() override;
|
||||
void loop() override;
|
||||
void render(Activity::RenderLock&&) override;
|
||||
void render(RenderLock&&) override;
|
||||
bool preventAutoSleep() override { return state == CHECKING_FOR_UPDATE || state == UPDATE_IN_PROGRESS; }
|
||||
bool skipLoopDelay() override { return true; } // Prevent power-saving mode
|
||||
};
|
||||
|
||||
@@ -67,16 +67,12 @@ void SettingsActivity::onEnter() {
|
||||
}
|
||||
|
||||
void SettingsActivity::onExit() {
|
||||
ActivityWithSubactivity::onExit();
|
||||
Activity::onExit();
|
||||
|
||||
UITheme::getInstance().reload(); // Re-apply theme in case it was changed
|
||||
}
|
||||
|
||||
void SettingsActivity::loop() {
|
||||
if (subActivity) {
|
||||
subActivity->loop();
|
||||
return;
|
||||
}
|
||||
bool hasChangedCategory = false;
|
||||
|
||||
// Handle actions with early return
|
||||
@@ -164,50 +160,38 @@ void SettingsActivity::toggleCurrentSetting() {
|
||||
SETTINGS.*(setting.valuePtr) = currentValue + setting.valueRange.step;
|
||||
}
|
||||
} else if (setting.type == SettingType::ACTION) {
|
||||
auto enterSubActivity = [this](Activity* activity) {
|
||||
exitActivity();
|
||||
enterNewActivity(activity);
|
||||
};
|
||||
|
||||
auto onComplete = [this] {
|
||||
exitActivity();
|
||||
requestUpdate();
|
||||
};
|
||||
|
||||
auto onCompleteBool = [this](bool) {
|
||||
exitActivity();
|
||||
requestUpdate();
|
||||
};
|
||||
auto resultHandler = [this](const ActivityResult&) { SETTINGS.saveToFile(); };
|
||||
|
||||
switch (setting.action) {
|
||||
case SettingAction::RemapFrontButtons:
|
||||
enterSubActivity(new ButtonRemapActivity(renderer, mappedInput, onComplete));
|
||||
startActivityForResult(std::make_unique<ButtonRemapActivity>(renderer, mappedInput), resultHandler);
|
||||
break;
|
||||
case SettingAction::CustomiseStatusBar:
|
||||
enterSubActivity(new StatusBarSettingsActivity(renderer, mappedInput, onComplete));
|
||||
startActivityForResult(std::make_unique<StatusBarSettingsActivity>(renderer, mappedInput), resultHandler);
|
||||
break;
|
||||
case SettingAction::KOReaderSync:
|
||||
enterSubActivity(new KOReaderSettingsActivity(renderer, mappedInput, onComplete));
|
||||
startActivityForResult(std::make_unique<KOReaderSettingsActivity>(renderer, mappedInput), resultHandler);
|
||||
break;
|
||||
case SettingAction::OPDSBrowser:
|
||||
enterSubActivity(new CalibreSettingsActivity(renderer, mappedInput, onComplete));
|
||||
startActivityForResult(std::make_unique<CalibreSettingsActivity>(renderer, mappedInput), resultHandler);
|
||||
break;
|
||||
case SettingAction::Network:
|
||||
enterSubActivity(new WifiSelectionActivity(renderer, mappedInput, onCompleteBool, false));
|
||||
startActivityForResult(std::make_unique<WifiSelectionActivity>(renderer, mappedInput, false), resultHandler);
|
||||
break;
|
||||
case SettingAction::ClearCache:
|
||||
enterSubActivity(new ClearCacheActivity(renderer, mappedInput, onComplete));
|
||||
startActivityForResult(std::make_unique<ClearCacheActivity>(renderer, mappedInput), resultHandler);
|
||||
break;
|
||||
case SettingAction::CheckForUpdates:
|
||||
enterSubActivity(new OtaUpdateActivity(renderer, mappedInput, onComplete));
|
||||
startActivityForResult(std::make_unique<OtaUpdateActivity>(renderer, mappedInput), resultHandler);
|
||||
break;
|
||||
case SettingAction::Language:
|
||||
enterSubActivity(new LanguageSelectActivity(renderer, mappedInput, onComplete));
|
||||
startActivityForResult(std::make_unique<LanguageSelectActivity>(renderer, mappedInput), resultHandler);
|
||||
break;
|
||||
case SettingAction::None:
|
||||
// Do nothing
|
||||
break;
|
||||
}
|
||||
return; // Results will be handled in the result handler, so we can return early here
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
@@ -215,7 +199,7 @@ void SettingsActivity::toggleCurrentSetting() {
|
||||
SETTINGS.saveToFile();
|
||||
}
|
||||
|
||||
void SettingsActivity::render(Activity::RenderLock&&) {
|
||||
void SettingsActivity::render(RenderLock&&) {
|
||||
renderer.clearScreen();
|
||||
|
||||
const auto pageWidth = renderer.getScreenWidth();
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "activities/ActivityWithSubactivity.h"
|
||||
#include "activities/Activity.h"
|
||||
#include "util/ButtonNavigator.h"
|
||||
|
||||
class CrossPointSettings;
|
||||
@@ -134,7 +134,7 @@ struct SettingInfo {
|
||||
}
|
||||
};
|
||||
|
||||
class SettingsActivity final : public ActivityWithSubactivity {
|
||||
class SettingsActivity final : public Activity {
|
||||
ButtonNavigator buttonNavigator;
|
||||
|
||||
int selectedCategoryIndex = 0; // Currently selected category
|
||||
@@ -148,8 +148,6 @@ class SettingsActivity final : public ActivityWithSubactivity {
|
||||
std::vector<SettingInfo> systemSettings;
|
||||
const std::vector<SettingInfo>* currentSettings = nullptr;
|
||||
|
||||
const std::function<void()> onGoHome;
|
||||
|
||||
static constexpr int categoryCount = 4;
|
||||
static const StrId categoryNames[categoryCount];
|
||||
|
||||
@@ -157,11 +155,10 @@ class SettingsActivity final : public ActivityWithSubactivity {
|
||||
void toggleCurrentSetting();
|
||||
|
||||
public:
|
||||
explicit SettingsActivity(GfxRenderer& renderer, MappedInputManager& mappedInput,
|
||||
const std::function<void()>& onGoHome)
|
||||
: ActivityWithSubactivity("Settings", renderer, mappedInput), onGoHome(onGoHome) {}
|
||||
explicit SettingsActivity(GfxRenderer& renderer, MappedInputManager& mappedInput)
|
||||
: Activity("Settings", renderer, mappedInput) {}
|
||||
void onEnter() override;
|
||||
void onExit() override;
|
||||
void loop() override;
|
||||
void render(Activity::RenderLock&&) override;
|
||||
void render(RenderLock&&) override;
|
||||
};
|
||||
|
||||
@@ -28,9 +28,6 @@ const StrId progressBarThicknessNames[PROGRESS_BAR_THICKNESS_ITEMS] = {
|
||||
constexpr int TITLE_ITEMS = 3;
|
||||
const StrId titleNames[TITLE_ITEMS] = {StrId::STR_BOOK, StrId::STR_CHAPTER, StrId::STR_HIDE};
|
||||
|
||||
const char* translatedShow = tr(STR_SHOW);
|
||||
const char* translatedHide = tr(STR_HIDE);
|
||||
|
||||
const int widthMargin = 10;
|
||||
const int verticalPreviewPadding = 50;
|
||||
const int verticalPreviewTextPadding = 40;
|
||||
@@ -61,7 +58,7 @@ void StatusBarSettingsActivity::onExit() { Activity::onExit(); }
|
||||
|
||||
void StatusBarSettingsActivity::loop() {
|
||||
if (mappedInput.wasPressed(MappedInputManager::Button::Back)) {
|
||||
onBack();
|
||||
finish();
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -117,7 +114,7 @@ void StatusBarSettingsActivity::handleSelection() {
|
||||
SETTINGS.saveToFile();
|
||||
}
|
||||
|
||||
void StatusBarSettingsActivity::render(Activity::RenderLock&&) {
|
||||
void StatusBarSettingsActivity::render(RenderLock&&) {
|
||||
renderer.clearScreen();
|
||||
|
||||
auto metrics = UITheme::getInstance().getMetrics();
|
||||
@@ -135,9 +132,9 @@ void StatusBarSettingsActivity::render(Activity::RenderLock&&) {
|
||||
[this](int index) {
|
||||
// Draw status for each setting
|
||||
if (index == 0) {
|
||||
return SETTINGS.statusBarChapterPageCount ? translatedShow : translatedHide;
|
||||
return SETTINGS.statusBarChapterPageCount ? tr(STR_SHOW) : tr(STR_HIDE);
|
||||
} else if (index == 1) {
|
||||
return SETTINGS.statusBarBookProgressPercentage ? translatedShow : translatedHide;
|
||||
return SETTINGS.statusBarBookProgressPercentage ? tr(STR_SHOW) : tr(STR_HIDE);
|
||||
} else if (index == 2) {
|
||||
return I18N.get(progressBarNames[SETTINGS.statusBarProgressBar]);
|
||||
} else if (index == 3) {
|
||||
@@ -145,9 +142,9 @@ void StatusBarSettingsActivity::render(Activity::RenderLock&&) {
|
||||
} else if (index == 4) {
|
||||
return I18N.get(titleNames[SETTINGS.statusBarTitle]);
|
||||
} else if (index == 5) {
|
||||
return SETTINGS.statusBarBattery ? translatedShow : translatedHide;
|
||||
return SETTINGS.statusBarBattery ? tr(STR_SHOW) : tr(STR_HIDE);
|
||||
} else {
|
||||
return translatedHide;
|
||||
return tr(STR_HIDE);
|
||||
}
|
||||
},
|
||||
true);
|
||||
|
||||
@@ -9,22 +9,18 @@
|
||||
// Reader status bar configuration activity
|
||||
class StatusBarSettingsActivity final : public Activity {
|
||||
public:
|
||||
explicit StatusBarSettingsActivity(GfxRenderer& renderer, MappedInputManager& mappedInput,
|
||||
const std::function<void()>& onBack)
|
||||
: Activity("StatusBarSettings", renderer, mappedInput), onBack(onBack) {}
|
||||
explicit StatusBarSettingsActivity(GfxRenderer& renderer, MappedInputManager& mappedInput)
|
||||
: Activity("StatusBarSettings", renderer, mappedInput) {}
|
||||
|
||||
void onEnter() override;
|
||||
void onExit() override;
|
||||
void loop() override;
|
||||
void render(Activity::RenderLock&&) override;
|
||||
void render(RenderLock&&) override;
|
||||
|
||||
private:
|
||||
ButtonNavigator buttonNavigator;
|
||||
|
||||
int selectedIndex = 0;
|
||||
|
||||
const std::function<void()> onBack;
|
||||
|
||||
static void taskTrampoline(void* param);
|
||||
void handleSelection();
|
||||
};
|
||||
|
||||
@@ -8,9 +8,8 @@
|
||||
#include "components/UITheme.h"
|
||||
#include "fontIds.h"
|
||||
|
||||
BmpViewerActivity::BmpViewerActivity(GfxRenderer& renderer, MappedInputManager& mappedInput, std::string path,
|
||||
std::function<void()> onGoBack)
|
||||
: Activity("BmpViewer", renderer, mappedInput), filePath(std::move(path)), onGoBack(std::move(onGoBack)) {}
|
||||
BmpViewerActivity::BmpViewerActivity(GfxRenderer& renderer, MappedInputManager& mappedInput, std::string path)
|
||||
: Activity("BmpViewer", renderer, mappedInput), filePath(std::move(path)) {}
|
||||
|
||||
void BmpViewerActivity::onEnter() {
|
||||
Activity::onEnter();
|
||||
@@ -95,7 +94,7 @@ void BmpViewerActivity::loop() {
|
||||
Activity::loop();
|
||||
|
||||
if (mappedInput.wasReleased(MappedInputManager::Button::Back)) {
|
||||
if (onGoBack) onGoBack();
|
||||
onGoHome();
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -8,8 +8,7 @@
|
||||
|
||||
class BmpViewerActivity final : public Activity {
|
||||
public:
|
||||
BmpViewerActivity(GfxRenderer& renderer, MappedInputManager& mappedInput, std::string filePath,
|
||||
std::function<void()> onGoBack);
|
||||
BmpViewerActivity(GfxRenderer& renderer, MappedInputManager& mappedInput, std::string filePath);
|
||||
|
||||
void onEnter() override;
|
||||
void onExit() override;
|
||||
@@ -17,5 +16,4 @@ class BmpViewerActivity final : public Activity {
|
||||
|
||||
private:
|
||||
std::string filePath;
|
||||
std::function<void()> onGoBack;
|
||||
};
|
||||
@@ -57,13 +57,13 @@ char KeyboardEntryActivity::getSelectedChar() const {
|
||||
return layout[selectedRow][selectedCol];
|
||||
}
|
||||
|
||||
void KeyboardEntryActivity::handleKeyPress() {
|
||||
bool KeyboardEntryActivity::handleKeyPress() {
|
||||
// Handle special row (bottom row with shift, space, backspace, done)
|
||||
if (selectedRow == SPECIAL_ROW) {
|
||||
if (selectedCol >= SHIFT_COL && selectedCol < SPACE_COL) {
|
||||
// Shift toggle (0 = lower case, 1 = upper case, 2 = shift lock)
|
||||
shiftState = (shiftState + 1) % 3;
|
||||
return;
|
||||
return true;
|
||||
}
|
||||
|
||||
if (selectedCol >= SPACE_COL && selectedCol < BACKSPACE_COL) {
|
||||
@@ -71,7 +71,7 @@ void KeyboardEntryActivity::handleKeyPress() {
|
||||
if (maxLength == 0 || text.length() < maxLength) {
|
||||
text += ' ';
|
||||
}
|
||||
return;
|
||||
return true;
|
||||
}
|
||||
|
||||
if (selectedCol >= BACKSPACE_COL && selectedCol < DONE_COL) {
|
||||
@@ -79,22 +79,20 @@ void KeyboardEntryActivity::handleKeyPress() {
|
||||
if (!text.empty()) {
|
||||
text.pop_back();
|
||||
}
|
||||
return;
|
||||
return true;
|
||||
}
|
||||
|
||||
if (selectedCol >= DONE_COL) {
|
||||
// Done button
|
||||
if (onComplete) {
|
||||
onComplete(text);
|
||||
}
|
||||
return;
|
||||
onComplete(text);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// Regular character
|
||||
const char c = getSelectedChar();
|
||||
if (c == '\0') {
|
||||
return;
|
||||
return true;
|
||||
}
|
||||
|
||||
if (maxLength == 0 || text.length() < maxLength) {
|
||||
@@ -104,6 +102,8 @@ void KeyboardEntryActivity::handleKeyPress() {
|
||||
shiftState = 0;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
void KeyboardEntryActivity::loop() {
|
||||
@@ -177,20 +177,19 @@ void KeyboardEntryActivity::loop() {
|
||||
|
||||
// Selection
|
||||
if (mappedInput.wasPressed(MappedInputManager::Button::Confirm)) {
|
||||
handleKeyPress();
|
||||
requestUpdate();
|
||||
if (handleKeyPress()) {
|
||||
requestUpdate();
|
||||
}
|
||||
// If handleKeyPress returns false, it means onComplete was triggered, no update needed
|
||||
}
|
||||
|
||||
// Cancel
|
||||
if (mappedInput.wasPressed(MappedInputManager::Button::Back)) {
|
||||
if (onCancel) {
|
||||
onCancel();
|
||||
}
|
||||
requestUpdate();
|
||||
onCancel();
|
||||
}
|
||||
}
|
||||
|
||||
void KeyboardEntryActivity::render(Activity::RenderLock&&) {
|
||||
void KeyboardEntryActivity::render(RenderLock&&) {
|
||||
renderer.clearScreen();
|
||||
|
||||
const auto pageWidth = renderer.getScreenWidth();
|
||||
@@ -321,3 +320,15 @@ void KeyboardEntryActivity::render(Activity::RenderLock&&) {
|
||||
|
||||
renderer.displayBuffer();
|
||||
}
|
||||
|
||||
void KeyboardEntryActivity::onComplete(std::string text) {
|
||||
setResult(KeyboardResult{std::move(text)});
|
||||
finish();
|
||||
}
|
||||
|
||||
void KeyboardEntryActivity::onCancel() {
|
||||
ActivityResult result;
|
||||
result.isCancelled = true;
|
||||
setResult(std::move(result));
|
||||
finish();
|
||||
}
|
||||
|
||||
@@ -10,21 +10,10 @@
|
||||
|
||||
/**
|
||||
* Reusable keyboard entry activity for text input.
|
||||
* Can be started from any activity that needs text entry.
|
||||
*
|
||||
* Usage:
|
||||
* 1. Create a KeyboardEntryActivity instance
|
||||
* 2. Set callbacks with setOnComplete() and setOnCancel()
|
||||
* 3. Call onEnter() to start the activity
|
||||
* 4. Call loop() in your main loop
|
||||
* 5. When complete or cancelled, callbacks will be invoked
|
||||
* Can be started from any activity that needs text entry via startActivityForResult()
|
||||
*/
|
||||
class KeyboardEntryActivity : public Activity {
|
||||
public:
|
||||
// Callback types
|
||||
using OnCompleteCallback = std::function<void(const std::string&)>;
|
||||
using OnCancelCallback = std::function<void()>;
|
||||
|
||||
/**
|
||||
* Constructor
|
||||
* @param renderer Reference to the GfxRenderer for drawing
|
||||
@@ -33,26 +22,21 @@ class KeyboardEntryActivity : public Activity {
|
||||
* @param initialText Initial text to show in the input field
|
||||
* @param maxLength Maximum length of input text (0 for unlimited)
|
||||
* @param isPassword If true, display asterisks instead of actual characters
|
||||
* @param onComplete Callback invoked when input is complete
|
||||
* @param onCancel Callback invoked when input is cancelled
|
||||
*/
|
||||
explicit KeyboardEntryActivity(GfxRenderer& renderer, MappedInputManager& mappedInput,
|
||||
std::string title = "Enter Text", std::string initialText = "",
|
||||
const size_t maxLength = 0, const bool isPassword = false,
|
||||
OnCompleteCallback onComplete = nullptr, OnCancelCallback onCancel = nullptr)
|
||||
const size_t maxLength = 0, const bool isPassword = false)
|
||||
: Activity("KeyboardEntry", renderer, mappedInput),
|
||||
title(std::move(title)),
|
||||
text(std::move(initialText)),
|
||||
maxLength(maxLength),
|
||||
isPassword(isPassword),
|
||||
onComplete(std::move(onComplete)),
|
||||
onCancel(std::move(onCancel)) {}
|
||||
isPassword(isPassword) {}
|
||||
|
||||
// Activity overrides
|
||||
void onEnter() override;
|
||||
void onExit() override;
|
||||
void loop() override;
|
||||
void render(Activity::RenderLock&&) override;
|
||||
void render(RenderLock&&) override;
|
||||
|
||||
private:
|
||||
std::string title;
|
||||
@@ -67,9 +51,9 @@ class KeyboardEntryActivity : public Activity {
|
||||
int selectedCol = 0;
|
||||
int shiftState = 0; // 0 = lower case, 1 = upper case, 2 = shift lock)
|
||||
|
||||
// Callbacks
|
||||
OnCompleteCallback onComplete;
|
||||
OnCancelCallback onCancel;
|
||||
// Handlers
|
||||
void onComplete(std::string text);
|
||||
void onCancel();
|
||||
|
||||
// Keyboard layout
|
||||
static constexpr int NUM_ROWS = 5;
|
||||
@@ -86,6 +70,6 @@ class KeyboardEntryActivity : public Activity {
|
||||
static constexpr int DONE_COL = 9;
|
||||
|
||||
char getSelectedChar() const;
|
||||
void handleKeyPress();
|
||||
bool handleKeyPress(); // false if onComplete was triggered
|
||||
int getRowLength(int row) const;
|
||||
};
|
||||
|
||||
+16
-85
@@ -18,16 +18,8 @@
|
||||
#include "KOReaderCredentialStore.h"
|
||||
#include "MappedInputManager.h"
|
||||
#include "RecentBooksStore.h"
|
||||
#include "activities/boot_sleep/BootActivity.h"
|
||||
#include "activities/boot_sleep/SleepActivity.h"
|
||||
#include "activities/browser/OpdsBookBrowserActivity.h"
|
||||
#include "activities/home/HomeActivity.h"
|
||||
#include "activities/home/MyLibraryActivity.h"
|
||||
#include "activities/home/RecentBooksActivity.h"
|
||||
#include "activities/network/CrossPointWebServerActivity.h"
|
||||
#include "activities/reader/ReaderActivity.h"
|
||||
#include "activities/settings/SettingsActivity.h"
|
||||
#include "activities/util/FullScreenMessageActivity.h"
|
||||
#include "activities/Activity.h"
|
||||
#include "activities/ActivityManager.h"
|
||||
#include "components/UITheme.h"
|
||||
#include "fontIds.h"
|
||||
#include "util/ButtonNavigator.h"
|
||||
@@ -37,8 +29,8 @@ HalDisplay display;
|
||||
HalGPIO gpio;
|
||||
MappedInputManager mappedInputManager(gpio);
|
||||
GfxRenderer renderer(display);
|
||||
ActivityManager activityManager(renderer, mappedInputManager);
|
||||
FontDecompressor fontDecompressor;
|
||||
Activity* currentActivity;
|
||||
|
||||
// Fonts
|
||||
EpdFont bookerly14RegularFont(&bookerly_14_regular);
|
||||
@@ -133,19 +125,6 @@ EpdFontFamily ui12FontFamily(&ui12RegularFont, &ui12BoldFont);
|
||||
unsigned long t1 = 0;
|
||||
unsigned long t2 = 0;
|
||||
|
||||
void exitActivity() {
|
||||
if (currentActivity) {
|
||||
currentActivity->onExit();
|
||||
delete currentActivity;
|
||||
currentActivity = nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
void enterNewActivity(Activity* activity) {
|
||||
currentActivity = activity;
|
||||
currentActivity->onEnter();
|
||||
}
|
||||
|
||||
// Verify power button press duration on wake-up from deep sleep
|
||||
// Pre-condition: isWakeupByPowerButton() == true
|
||||
void verifyPowerButtonDuration() {
|
||||
@@ -201,10 +180,10 @@ void waitForPowerRelease() {
|
||||
// Enter deep sleep mode
|
||||
void enterDeepSleep() {
|
||||
HalPowerManager::Lock powerLock; // Ensure we are at normal CPU frequency for sleep preparation
|
||||
APP_STATE.lastSleepFromReader = currentActivity && currentActivity->isReaderActivity();
|
||||
APP_STATE.lastSleepFromReader = activityManager.isReaderActivity();
|
||||
APP_STATE.saveToFile();
|
||||
exitActivity();
|
||||
enterNewActivity(new SleepActivity(renderer, mappedInputManager));
|
||||
|
||||
activityManager.goToSleep();
|
||||
|
||||
display.deepSleep();
|
||||
LOG_DBG("MAIN", "Power button press calibration value: %lu ms", t2 - t1);
|
||||
@@ -213,54 +192,10 @@ void enterDeepSleep() {
|
||||
powerManager.startDeepSleep(gpio);
|
||||
}
|
||||
|
||||
void onGoHome();
|
||||
void onGoToMyLibraryWithPath(const std::string& path);
|
||||
void onGoToRecentBooks();
|
||||
void onGoToReader(const std::string& initialEpubPath) {
|
||||
const std::string bookPath = initialEpubPath; // Copy before exitActivity() invalidates the reference
|
||||
exitActivity();
|
||||
enterNewActivity(new ReaderActivity(renderer, mappedInputManager, bookPath, onGoHome, onGoToMyLibraryWithPath));
|
||||
}
|
||||
|
||||
void onGoToFileTransfer() {
|
||||
exitActivity();
|
||||
enterNewActivity(new CrossPointWebServerActivity(renderer, mappedInputManager, onGoHome));
|
||||
}
|
||||
|
||||
void onGoToSettings() {
|
||||
exitActivity();
|
||||
enterNewActivity(new SettingsActivity(renderer, mappedInputManager, onGoHome));
|
||||
}
|
||||
|
||||
void onGoToMyLibrary() {
|
||||
exitActivity();
|
||||
enterNewActivity(new MyLibraryActivity(renderer, mappedInputManager, onGoHome, onGoToReader));
|
||||
}
|
||||
|
||||
void onGoToRecentBooks() {
|
||||
exitActivity();
|
||||
enterNewActivity(new RecentBooksActivity(renderer, mappedInputManager, onGoHome, onGoToReader));
|
||||
}
|
||||
|
||||
void onGoToMyLibraryWithPath(const std::string& path) {
|
||||
exitActivity();
|
||||
enterNewActivity(new MyLibraryActivity(renderer, mappedInputManager, onGoHome, onGoToReader, path));
|
||||
}
|
||||
|
||||
void onGoToBrowser() {
|
||||
exitActivity();
|
||||
enterNewActivity(new OpdsBookBrowserActivity(renderer, mappedInputManager, onGoHome));
|
||||
}
|
||||
|
||||
void onGoHome() {
|
||||
exitActivity();
|
||||
enterNewActivity(new HomeActivity(renderer, mappedInputManager, onGoToReader, onGoToMyLibrary, onGoToRecentBooks,
|
||||
onGoToSettings, onGoToFileTransfer, onGoToBrowser));
|
||||
}
|
||||
|
||||
void setupDisplayAndFonts() {
|
||||
display.begin();
|
||||
renderer.begin();
|
||||
activityManager.begin();
|
||||
LOG_DBG("MAIN", "Display initialized");
|
||||
|
||||
// Initialize font decompressor for compressed reader fonts
|
||||
@@ -310,8 +245,7 @@ void setup() {
|
||||
if (!Storage.begin()) {
|
||||
LOG_ERR("MAIN", "SD card initialization failed");
|
||||
setupDisplayAndFonts();
|
||||
exitActivity();
|
||||
enterNewActivity(new FullScreenMessageActivity(renderer, mappedInputManager, "SD card error", EpdFontFamily::BOLD));
|
||||
activityManager.goToFullScreenMessage("SD card error", EpdFontFamily::BOLD);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -344,8 +278,7 @@ void setup() {
|
||||
|
||||
setupDisplayAndFonts();
|
||||
|
||||
exitActivity();
|
||||
enterNewActivity(new BootActivity(renderer, mappedInputManager));
|
||||
activityManager.goToBoot();
|
||||
|
||||
APP_STATE.loadFromFile();
|
||||
RECENT_BOOKS.loadFromFile();
|
||||
@@ -354,14 +287,14 @@ void setup() {
|
||||
// crashed (indicated by readerActivityLoadCount > 0)
|
||||
if (APP_STATE.openEpubPath.empty() || !APP_STATE.lastSleepFromReader ||
|
||||
mappedInputManager.isPressed(MappedInputManager::Button::Back) || APP_STATE.readerActivityLoadCount > 0) {
|
||||
onGoHome();
|
||||
activityManager.goHome();
|
||||
} else {
|
||||
// Clear app state to avoid getting into a boot loop if the epub doesn't load
|
||||
const auto path = APP_STATE.openEpubPath;
|
||||
APP_STATE.openEpubPath = "";
|
||||
APP_STATE.readerActivityLoadCount++;
|
||||
APP_STATE.saveToFile();
|
||||
onGoToReader(path);
|
||||
activityManager.goToReader(path);
|
||||
}
|
||||
|
||||
// Ensure we're not still holding the power button before leaving setup
|
||||
@@ -401,7 +334,7 @@ void loop() {
|
||||
|
||||
// Check for any user activity (button press or release) or active background work
|
||||
static unsigned long lastActivityTime = millis();
|
||||
if (gpio.wasAnyPressed() || gpio.wasAnyReleased() || (currentActivity && currentActivity->preventAutoSleep())) {
|
||||
if (gpio.wasAnyPressed() || gpio.wasAnyReleased() || activityManager.preventAutoSleep()) {
|
||||
lastActivityTime = millis(); // Reset inactivity timer
|
||||
powerManager.setPowerSaving(false); // Restore normal CPU frequency on user activity
|
||||
}
|
||||
@@ -410,8 +343,8 @@ void loop() {
|
||||
if (gpio.isPressed(HalGPIO::BTN_POWER) && gpio.isPressed(HalGPIO::BTN_DOWN)) {
|
||||
if (screenshotButtonsReleased) {
|
||||
screenshotButtonsReleased = false;
|
||||
if (currentActivity) {
|
||||
Activity::RenderLock lock(*currentActivity);
|
||||
{
|
||||
RenderLock lock;
|
||||
ScreenshotUtil::takeScreenshot(renderer);
|
||||
}
|
||||
}
|
||||
@@ -439,9 +372,7 @@ void loop() {
|
||||
}
|
||||
|
||||
const unsigned long activityStartTime = millis();
|
||||
if (currentActivity) {
|
||||
currentActivity->loop();
|
||||
}
|
||||
activityManager.loop();
|
||||
const unsigned long activityDuration = millis() - activityStartTime;
|
||||
|
||||
const unsigned long loopDuration = millis() - loopStartTime;
|
||||
@@ -455,7 +386,7 @@ void loop() {
|
||||
// Add delay at the end of the loop to prevent tight spinning
|
||||
// When an activity requests skip loop delay (e.g., webserver running), use yield() for faster response
|
||||
// Otherwise, use longer delay to save power
|
||||
if (currentActivity && currentActivity->skipLoopDelay()) {
|
||||
if (activityManager.skipLoopDelay()) {
|
||||
powerManager.setPowerSaving(false); // Make sure we're at full performance when skipLoopDelay is requested
|
||||
yield(); // Give FreeRTOS a chance to run tasks, but return immediately
|
||||
} else {
|
||||
|
||||
Reference in New Issue
Block a user