33 Commits

Author SHA1 Message Date
Xuan-Son Nguyen
0991782fb4 feat: more power saving on idle (#801)
Some checks failed
CI (build) / clang-format (push) Has been cancelled
CI (build) / cppcheck (push) Has been cancelled
CI (build) / build (push) Has been cancelled
CI (build) / Test Status (push) Has been cancelled
## Summary

This PR extends the delay in main loop from 10ms to 50ms after the
device is idle for a while. This translates to extended battery life in
a longer period (see testing section above), while not hurting too much
the user experience.

With the help from [this
patch](https://github.com/ngxson/crosspoint-reader/tree/xsn/measure_cpu_usage),
I was able to measure the CPU usage on idle:

```
PR:
[20017] [MEM] Free: 150188 bytes, Total: 232092 bytes, Min Free: 150092 bytes
[20017] [IDLE] Idle time: 99.62% (CPU load: 0.38%)
[30042] [MEM] Free: 150188 bytes, Total: 232092 bytes, Min Free: 150092 bytes
[30042] [IDLE] Idle time: 99.63% (CPU load: 0.37%)
[40067] [MEM] Free: 150188 bytes, Total: 232092 bytes, Min Free: 150092 bytes
[40067] [IDLE] Idle time: 99.62% (CPU load: 0.38%)

master:
[20012] [MEM] Free: 195016 bytes, Total: 231532 bytes, Min Free: 132460 bytes
[20012] [IDLE] Idle time: 98.53% (CPU load: 1.47%)
[30017] [MEM] Free: 195016 bytes, Total: 231532 bytes, Min Free: 132460 bytes
[30017] [IDLE] Idle time: 98.53% (CPU load: 1.47%)
[40022] [MEM] Free: 195016 bytes, Total: 231532 bytes, Min Free: 132460 bytes
[40022] [IDLE] Idle time: 98.53% (CPU load: 1.47%)
```

While this is a x3.8 reduce in CPU usage, it doesn't translate to the
same amount of battery life extension in real life. The reasons are:
1. The CPU is not shut down completely
2. freeRTOS tick is still running (however, I planned to experiment with
tickless functionality)
3. Current leakage to other components, for example: voltage dividers,
eink screen, SD card, etc

A note on
[light-sleep](https://docs.espressif.com/projects/esp-idf/en/stable/esp32c3/api-reference/system/sleep_modes.html)
functionality: it is not possible in our use case because:
- Light-sleep for 50ms introduce too much overhead on wake up, it has
negative effect on battery life
- Light-sleep for longer period doesn't work because the ADC GPIO
buttons cannot be used as wake up source

## Testing (duration = 6 hrs)

To test this, I patched the `CrossPointSettings::getSleepTimeoutMs()` to
always returns a timeout of 6 hrs. This allow me to leave the device
idle for 6 hrs straight.

- On master branch, 6 hrs costs 26% battery life (100% --> 74%), meaning
battery life is ~23 hrs
- With this PR, 6 hrs costs 20% battery life (100% --> 80%), meaning
battery life is ~30 hrs

So in theory, this extends the battery by about 7 hrs. Even with some
error margin added, I think 3 hrs increase is possible with a normal
usage setup (i.e. only read ebooks, no wifi)

## Additional Context

Would appreciate if someone can test this with an oscilloscope.

---

### AI Usage

While CrossPoint doesn't have restrictions on AI tools in contributing,
please be transparent about their usage as it
helps set the right context for reviewers.

Did you use AI tools to help write this code? **NO**
2026-02-12 09:49:05 +01:00
jpirnay
3ae1007cbe fix: chore: make all debug messages uniform (#825)
## Summary

* Unify all serial port debug messages

## Additional Context

* All messages sent to the serial port now follow the "[timestamp]
[origin] payload" format (notable exception framework messages)

---

### AI Usage

While CrossPoint doesn't have restrictions on AI tools in contributing,
please be transparent about their usage as it
helps set the right context for reviewers.

Did you use AI tools to help write this code? No
2026-02-11 16:25:17 +01:00
Jonas Diemer
efb9b72e64 fix: Show "Back" in file browser if not in root, "Home" otherwise. (#822)
## Summary

Show "Back" in file browser if not in root, "Home" otherwise.

---

### AI Usage

While CrossPoint doesn't have restrictions on AI tools in contributing,
please be transparent about their usage as it
helps set the right context for reviewers.

Did you use AI tools to help write this code? YES
2026-02-11 16:44:10 +03:00
Dave Allie
4a210823a8 fix: Manually trigger GPIO update in File Browser mode (#819)
## Summary

* Manually trigger GPIO update in File Browser mode
* Previously just assumed that the GPIO data would update automatically
(presumably via yield), the data is currently updated in the main loop
(and now here as well during the middle of the processing loop).
* This allows the back button to be correctly detected instead of only
being checked once every 100ms or so for the button state.

## Additional Context

* Fixes
https://github.com/crosspoint-reader/crosspoint-reader/issues/579

---

### AI Usage

While CrossPoint doesn't have restrictions on AI tools in contributing,
please be transparent about their usage as it
helps set the right context for reviewers.

Did you use AI tools to help write this code? No


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

* **Bug Fixes**
* Enhanced input state detection in the web server interface for more
responsive and accurate user command recognition during high-frequency
operations.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-02-11 13:42:37 +03:00
Jonas Diemer
f5b85f5ca1 fix: Reduce MIN_SIZE_FOR_POPUP to 10KB (#809)
Noticed that the Indexing... popup went missing despite 3-5 seconds
delay. Reducing to 10KB, so we get a popup for delays > ~2s.


### AI Usage

While CrossPoint doesn't have restrictions on AI tools in contributing,
please be transparent about their usage as it
helps set the right context for reviewers.

Did you use AI tools to help write this code? no
2026-02-10 16:15:23 +01:00
Jonas Diemer
7e93411f46 docs: Update USER_GUIDE.md (#817)
Added explanation how to recover from broken config/cache.



### AI Usage

While CrossPoint doesn't have restrictions on AI tools in contributing,
please be transparent about their usage as it
helps set the right context for reviewers.

Did you use AI tools to help write this code? no
2026-02-10 23:23:14 +11:00
Dave Allie
44452a42e9 fix: Prevent sleeping when in OPDS browser / downloading books (#818)
## Summary

* Prevent sleeping when in OPDS browser / downloading books

## Additional Context

* Raised in
https://github.com/crosspoint-reader/crosspoint-reader/discussions/673

---

### AI Usage

While CrossPoint doesn't have restrictions on AI tools in contributing,
please be transparent about their usage as it
helps set the right context for reviewers.

Did you use AI tools to help write this code? No
2026-02-10 22:56:22 +11:00
jpirnay
0c2df24f5c feat: Extend python debugging monitor functionality (keyword filter / suppress) (#810)
## Summary

* I needed the ability to filter and or suppress debug messages
containig certain keywords (eg [GFX] for render related stuff)
* Update of debugging_monitor.py script for development work

## Additional Context
```
usage: debugging_monitor.py [-h] [--baud BAUD] [--filter FILTER] [--suppress SUPPRESS] [port]

ESP32 Monitor with Graph

positional arguments:
  port                 Serial port

options:
  -h, --help           show this help message and exit
  --baud BAUD          Baud rate
  --filter FILTER      Only display lines containing this keyword (case-insensitive)
  --suppress SUPPRESS  Suppress lines containing this keyword (case-insensitive)
```
* plus a couple of platform specific defaults (port, pip style)
---

### AI Usage

While CrossPoint doesn't have restrictions on AI tools in contributing,
please be transparent about their usage as it
helps set the right context for reviewers.

Did you use AI tools to help write this code? NO
2026-02-10 22:07:56 +11:00
Jonas Diemer
3a12ca2725 docs: Update USER_GUIDE.md (#808)
Added info about optimizing EPUB.

### AI Usage

While CrossPoint doesn't have restrictions on AI tools in contributing,
please be transparent about their usage as it
helps set the right context for reviewers.

Did you use AI tools to help write this code? no
2026-02-10 22:04:32 +11:00
Eliz
98e6789626 feat: Connect to last wifi by default (#752)
## Summary

* **What is the goal of this PR?** 

Use last connected network as default

* **What changes are included?**

- Refactor how an action type of Settings are handled
- Add a new System Settings option → Network
- Add the ability to forget a network in the Network Selection Screen
- Add the ability to Refresh network list
- Save the last connected network SSID
- Use the last connection whenever network is needed (OPDS, Koreader
sync, update etc)

## Additional Context

* Add any other information that might be helpful for the reviewer
(e.g., performance implications, potential risks,
  specific areas to focus on).


![IMG_6504](https://github.com/user-attachments/assets/e48fb013-b5c3-45c0-b284-e183e6fd5a68)

![IMG_6503](https://github.com/user-attachments/assets/78c4b6b6-4e7b-4656-b356-19d65ff6aa12)




https://github.com/user-attachments/assets/95bf34a8-44ce-4279-8cd8-f78524ce745b





---

### AI Usage

Did you use AI tools to help write this code? _** PARTIALLY: I wrote
most of it but I also used Gemini as assist.

---------

Co-authored-by: Eliz Kilic <elizk@google.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2026-02-10 20:41:44 +11:00
ThatCrispyToast
b5d28a3a9c feat: use natural sort in file browser (#722)
## Summary

* **What is the goal of this PR?** (e.g., Implements the new feature for
file uploading.)

Implement natural sort (e.g. "file1.txt, file2.txt, file10.txt" instead
of "file1.txt, file10.txt, file2.txt") for files in the
MyLibraryActivity menu

* **What changes are included?**

Modifies the `sortFileList` function under
`src/activities/home/MyLibraryActivity.cpp` to use natural sort as
opposed to lexicographical sort

## Additional Context

I wasn't entirely sure whether or not i should make this a configurable
option, but most file browsers and directory listing tools have this set
as an immutable default, so I opted against it.

* Add any other information that might be helpful for the reviewer
(e.g., performance implications, potential risks,
  specific areas to focus on).

---

### AI Usage

While CrossPoint doesn't have restrictions on AI tools in contributing,
please be transparent about their usage as it
helps set the right context for reviewers.

Did you use AI tools to help write this code? _**NO**_
2026-02-10 01:09:24 +03:00
harshit181
14ef625679 fix: issue if book href are absolute url and not relative to server (#741)
## Summary

fixing issue if book href are absolute url and not relative to the
server

## Additional Context

* Fixes
https://github.com/crosspoint-reader/crosspoint-reader/issues/632
* https://github.com/harshit181/RSSPub/issues/43

---

### AI Usage

While CrossPoint doesn't have restrictions on AI tools in contributing,
please be transparent about their usage as it
helps set the right context for reviewers.

Did you use AI tools to help write this code? _**<  PARTIALLY>**_
2026-02-09 22:12:21 +11:00
Istiak Tridip
64d161e88b feat: unify navigation handling with system-wide continuous navigation (#600)
This PR unifies navigation handling & adds system-wide support for
continuous navigation.

## Summary
Holding down a navigation button now continuously advances through items
until the button is released. This removes the need for repeated
press-and-release actions and makes navigation faster and smoother,
especially in long menus or documents.

When page-based navigation is available, it will navigate through pages.
If not, it will progress through menu items or similar list-based UI
elements.

Additionally, this PR fixes inconsistencies in wrap-around behavior and
navigation index calculations.

Places where the navigation system was updated:
- Home Page
- Settings Pages
- My Library Page
- WiFi Selection Page
- OPDS Browser Page
- Keyboard
- File Transfer Page
- XTC Chapter Selector Page
- EPUB Chapter Selector Page

I’ve tested this on the device as much as possible and tried to match
the existing behavior. Please let me know if I missed anything. Thanks 🙏


![crosspoint](https://github.com/user-attachments/assets/6a3c7482-f45e-4a77-b156-721bb3b679e6)

---

Following the request from @osteotek and @daveallie for system-wide
support, the old PR (#379) has been closed in favor of this
consolidated, system-wide implementation.

---

### AI Usage

Did you use AI tools to help write this code? _**PARTIALLY**_

---------

Co-authored-by: Dave Allie <dave@daveallie.com>
2026-02-09 20:19:34 +11:00
Fabio Barbon
e73bb3213f feat: Add Italian hyphenation support (#584)
## Summary

* **What is the goal of this PR?** Add Italian language hyphenation
support to improve text rendering for Italian books.
* **What changes are included?**

* Added Italian hyphenation trie (hyph-it.trie.h) generated from Typst's
hypher patterns
* Registered italianHyphenator in LanguageRegistry.cpp for language tag
it
  * Added Italian to the hyphenation evaluation test suite
  * Added Italian test data file with 5000 test cases

## Additional Context

* Add any other information that might be helpful for the reviewer
(e.g., performance implications, potential risks,
  specific areas to focus on).

---

### AI Usage

While CrossPoint doesn't have restrictions on AI tools in contributing,
please be transparent about their usage as it
helps set the right context for reviewers.

Did you use AI tools to help write this code? _**NO**_

---------

Co-authored-by: drbourbon <fabio@MacBook-Air-di-Fabio.local>
2026-02-09 19:55:58 +11:00
Dave Allie
6202bfd651 Merge branch 'release/1.0.0' 2026-02-09 17:18:24 +11:00
Jake Kenneally
9b04c2ec76 feat: Add percentage support to CSS properties (#738)
## Summary
- Closes #730

**What is the goal of this PR?**
- Adds percentage-based value support to CSS properties that accept
percentages (padding, margin, text-indent)
 
**What changes are included?**
- Adds `Percent` as another CSS unit
- Passes the viewport width to `fromCssStyle` so that we can resolve
percentage-based values
- Adds a fallback of using an emspace for text-indent if we have an
unresolvable value for whatever reason

## Additional Context

- This was missed in my CSS support feature, and the fallback when we
encounter a percentage value is to use px instead. This means 5% (which
would be ~30px on the screen) turns into 5px. When percentages are used
in `text-indent`, this fallback behavior makes the indent look like a
single space character. Whoops! 😬

My test EPUB has been updated
[here](https://github.com/jdk2pq/css-test-epub) with percentage based
CSS values at the end of the book.

---

### AI Usage

While CrossPoint doesn't have restrictions on AI tools in contributing,
please be transparent about their usage as it
helps set the right context for reviewers.

Did you use AI tools to help write this code? _**YES**_, Claude Code
2026-02-09 08:31:52 +11:00
Dave Allie
ffddc2472b Use GITHUB_REF_NAME over GITHUB_HEAD_REF in release candidate workflow 2026-02-09 08:22:20 +11:00
Dave Allie
5765bbe821 Add release candidate workflow 2026-02-09 08:16:36 +11:00
Dave Allie
b4b028be3a fix: Allow OTA update from RC build to full release (#778)
## Summary

* Allow OTA update from RC build to full release
* If all the segments match, then also check if the current version
contains "-rc"

---

### AI Usage

While CrossPoint doesn't have restrictions on AI tools in contributing,
please be transparent about their usage as it
helps set the right context for reviewers.

Did you use AI tools to help write this code? No
2026-02-09 08:08:19 +11:00
Yaroslav
f34d7d2aac fix(ui): Add Back label in KOReader Sync screen (#770)
## Summary

- Remove duplicate Cancel option 
- Add Back label

<img width="435" height="613" alt="image"
src="https://github.com/user-attachments/assets/a3af4133-46fa-46e6-8360-a15dd7c4fe2a"
/>


## Result

<img width="575" height="431" alt="image"
src="https://github.com/user-attachments/assets/6ccdac89-43df-45bf-bcfa-3a7cc4bd88e4"
/>


---

### AI Usage

Did you use AI tools to help write this code? _**< PARTIALLY >**_

Closes #754
2026-02-09 07:51:51 +11:00
Justin Mitchell
71769490fb fix: Add EPUB 3 cover image detection (#760)
I had an epub that just showed a blank cover and wouldnt work for the
sleep screen either, turns out it was an epub3 and I guess we didn't
support that. Super simple fix here
2026-02-09 07:49:49 +11:00
Jesse Vincent
cda0a3f898 feat: A web editor for settings (#667)
## Summary

This is an updated version of @itsthisjustin's #346 that builds on
current master and also deduplicates the settings list so we don't have
two copies of the settings. In the Web UI, it should organize the
settings a little closer to what you see on device.

## Additional Context

I tested this live on device and it seems to play nicely for me. It's
re-based on master since master's settings stuff has moved somewhat
since the original PR and addresses the sole review comment #346 - it
also means that I don't need to manually key in the URL for my OPDS
server. :)

---

### AI Usage

My changes were implemented with Claude Opus 4.5 and Claude Code 2.1.25.
I don't know if @itsthisjustin's original work used AI assistance.

Co-authored-by: Dave Allie <dave@daveallie.com>
2026-02-09 07:46:14 +11:00
Xuan-Son Nguyen
7f40c3f477 feat: add HalStorage (#656)
## Summary

Continue my changes to introduce the HAL infrastructure from
https://github.com/crosspoint-reader/crosspoint-reader/pull/522

This PR touches quite a lot of files, but most of them are just name
changing. It should not have any impacts to the end behavior.

## Additional Context

My plan is to firstly add this small shim layer, which sounds useless at
first, but then I'll implement an emulated driver which can be helpful
for testing and for development.

Currently, on my fork, I'm using a FS driver that allow "mounting" a
local directory from my computer to the device, much like the `-v` mount
option on docker. This allows me to quickly reset `.crosspoint`
directory if anything goes wrong. I plan to upstream this feature when
this PR get merged.

---

### AI Usage

While CrossPoint doesn't have restrictions on AI tools in contributing,
please be transparent about their usage as it
helps set the right context for reviewers.

Did you use AI tools to help write this code? NO
2026-02-09 07:29:14 +11:00
Xuan-Son Nguyen
a87eacc6ab perf: optimize drawPixel() (#748)
## Summary

Ref https://github.com/crosspoint-reader/crosspoint-reader/pull/737

This PR further reduce ~25ms from rendering time, testing inside the
Setting screen:

```
master:
[68440] [GFX] Time = 73 ms from clearScreen to displayBuffer

PR:
[97806] [GFX] Time = 47 ms from clearScreen to displayBuffer
```

And in extreme case (fill the entire screen with black or gray color):

```
master:
[1125] [   ] Test fillRectDither drawn in 327 ms
[1347] [   ] Test fillRect drawn in 222 ms

PR:
[1334] [   ] Test fillRectDither drawn in 225 ms
[1455] [   ] Test fillRect drawn in 121 ms
```

Note that
https://github.com/crosspoint-reader/crosspoint-reader/pull/737 is NOT
applied on top of this PR. But with 2 of them combined, it should reduce
from 47ms --> 42ms

## Details

This PR based on the fact that function calls are costly if the function
is small enough. For example, this simple call:

```
  int rotatedX = 0;
  int rotatedY = 0;
  rotateCoordinates(x, y, &rotatedX, &rotatedY);
```

Generated assembly code:

<img width="771" height="215" alt="image"
src="https://github.com/user-attachments/assets/37991659-3304-41c3-a3b2-fb967da53f82"
/>

This adds ~10 instructions just to prepare the registers prior to the
function call, plus some more instructions for the function's
epilogue/prologue. Inlining it removing all of these:

<img width="1471" height="832" alt="image"
src="https://github.com/user-attachments/assets/b67a22ee-93ba-4017-88ed-c973e28ec914"
/>

Of course, this optimization is not magic. It's only beneficial under 3
conditions:
- The function is small, not in size, but in terms of effective
instructions. For example, the `rotateCoordinates` is simply a jump
table, where each branch is just 3-4 inst
- The function has multiple input arguments, which requires some move to
put it onto the correct place
- The function is called very frequently (i.e. critical path)

---

### AI Usage

While CrossPoint doesn't have restrictions on AI tools in contributing,
please be transparent about their usage as it
helps set the right context for reviewers.

Did you use AI tools to help write this code? **NO**
2026-02-09 05:05:42 +11:00
Arthur Tazhitdinov
1caad578fc feat: wakeup target detection (#731)
## Summary

* If going to sleep was from the Reader view, wake up to the same book.
Otherwise, wakeup to the Home view
2026-02-09 05:01:30 +11:00
CaptainFrito
5b90b68e99 fix: Scrolling page items calculation (#716)
## Summary

Fix for the page skip issue detected
https://github.com/crosspoint-reader/crosspoint-reader/pull/700#issuecomment-3856374323
by user @whyte-j

Skipping down on the last page now skips to the last item, and up on the
first page to the first item, rather than wrapping around the list in a
weird way.

## Additional Context

The calculation was outdated after several changes were added afterwards

---

### AI Usage

While CrossPoint doesn't have restrictions on AI tools in contributing,
please be transparent about their usage as it
helps set the right context for reviewers.

Did you use AI tools to help write this code? _**NO**_
2026-02-09 04:58:46 +11:00
Jake Kenneally
67ddd60fce refactor: Rename "Embedded Style" to "Book's Embedded Style" (#746)
## Summary

**What is the goal of this PR?**
- Just a simple rename after feedback in #738

**What changes are included?**
- Renamed "Embedded Style" to "Book's Embedded Style" to more clearly
associate it with "Book's Style" option in "Paragraph Alignment"
settings

---

### AI Usage

While CrossPoint doesn't have restrictions on AI tools in contributing,
please be transparent about their usage as it
helps set the right context for reviewers.

Did you use AI tools to help write this code? _**NO**_
2026-02-08 20:34:06 +03:00
Xuan-Son Nguyen
76908d38e1 feat: optimize fillRectDither (#737)
## Summary

This PR optimizes the `fillRectDither` function, making it as fast as a
normal `fillRect`

Testing code:

```cpp
  {
    auto start_t = millis();
    renderer.fillRectDither(0, 0, renderer.getScreenWidth(), renderer.getScreenHeight(), Color::LightGray);
    auto elapsed = millis() - start_t;
    Serial.printf("[%lu] [   ] Test fillRectDither drawn in %lu ms\n", millis(), elapsed);
  }

  {
    auto start_t = millis();
    renderer.fillRect(0, 0, renderer.getScreenWidth(), renderer.getScreenHeight(), true);
    auto elapsed = millis() - start_t;
    Serial.printf("[%lu] [   ] Test fillRect drawn in %lu ms\n", millis(), elapsed);
  }
```

Before:

```
[1125] [   ] Test fillRectDither drawn in 327 ms
[1347] [   ] Test fillRect drawn in 222 ms
```

After:

```
[1065] [ ] Test fillRectDither drawn in 238 ms
[1287] [ ] Test fillRect drawn in 222 ms
```

## Visual validation

Before:

<img width="415" height="216" alt="Screenshot 2026-02-07 at 01 04 19"
src="https://github.com/user-attachments/assets/5802dbba-187b-4d2b-a359-1318d3932d38"
/>

After:

<img width="420" height="191" alt="Screenshot 2026-02-07 at 01 36 30"
src="https://github.com/user-attachments/assets/3c3c8e14-3f3a-4205-be78-6ed771dcddf4"
/>

## Details

The original version is quite slow because it does quite a lot of
computations. A single pixel needs around 20 instructions just to know
if it's black or white:

<img width="1170" height="693" alt="Screenshot 2026-02-07 at 00 15 54"
src="https://github.com/user-attachments/assets/7c5a55e7-0598-4340-8b7b-17307d7921cb"
/>

With the new, templated and more light-weight approach, each pixel takes
only 3-4 instructions, the modulo operator is translated into bitwise
ops:

<img width="1175" height="682" alt="Screenshot 2026-02-07 at 01 47 51"
src="https://github.com/user-attachments/assets/4ec2cf74-6cc0-4b5b-87d5-831563ef164f"
/>

---

### AI Usage

While CrossPoint doesn't have restrictions on AI tools in contributing,
please be transparent about their usage as it
helps set the right context for reviewers.

Did you use AI tools to help write this code? **NO**
2026-02-08 14:59:13 +03:00
Arthur Tazhitdinov
e6f5fa43e6 feat(ux): invert BACK button behavior in reader activities (#726)
## Summary

* Inverts back button behaviour while reading - short press to go home,
long press to open file browser

## Additional Context

* It seems counterintuitive that going into a book from home screen and
pressing back doesn’t take you back to the home screen. With the recent
books now displayed in the home view and a separate recents view, going
directly to the file browser is less necessary.
2026-02-07 10:17:00 -05:00
James Whyte
e7e31ac487 fix: increase lyra sideButtonHintsWidth to 30 (#727)
## Summary

Increase the width of Lyra's side button hints. It has been set to 30,
the same width as the classic theme.


Before:
<img width="457" height="742" alt="image"
src="https://github.com/user-attachments/assets/316e4679-fbf0-4f6e-b117-413075da1be2"
/>

After:
<img width="512" height="849" alt="image"
src="https://github.com/user-attachments/assets/3b0cf069-55ad-4d5a-a93c-4aeca3ff67f8"
/>



## Additional Context

Resolves
https://github.com/crosspoint-reader/crosspoint-reader/pull/700#issuecomment-3856983832

---

### AI Usage

While CrossPoint doesn't have restrictions on AI tools in contributing,
please be transparent about their usage as it
helps set the right context for reviewers.

Did you use AI tools to help write this code?
No
2026-02-07 10:15:41 -05:00
Jake Kenneally
9f78fd33e8 fix: Remove separations after style changes (#720)
Closes #182. Closes #710. Closes #711.

## Summary

**What is the goal of this PR?**
- A longer-term, more robust fix for the issue with spurious spaces
appearing after style changes. Replaces solution from #694.

**What changes are included?**
- Add continuation flags to determine if to add a space after a word or
if the word connects to the previous word. Replaces simple solution that
only considered ending punctuation.
- Fixed an issue with greedy line-breaking algorithm where punctuation
could appear on the next line, separated from the word, if there was a
style change between the word and punctuation

---

### AI Usage

While CrossPoint doesn't have restrictions on AI tools in contributing,
please be transparent about their usage as it
helps set the right context for reviewers.

Did you use AI tools to help write this code? _**YES**_, Claude Code
2026-02-06 19:10:37 +11:00
CaptainFrito
bd8132a260 fix: Lag before displaying covers on home screen (#721)
## Summary

Reduce/fix the lag on the home screen before recent book covers are
rendered

## Additional Context

We were previously rendering the screen in two steps, delaying the
recent book covers render to avoid a lag before the screen loads.
In this PR, we are now doing that only if at least one book doesn't have
the cover thumbnail generated yet. If all thumbs are already generated,
we load and display them right away, with no lag.

---

### AI Usage

While CrossPoint doesn't have restrictions on AI tools in contributing,
please be transparent about their usage as it
helps set the right context for reviewers.

Did you use AI tools to help write this code? _**NO **_
2026-02-06 18:58:32 +11:00
Jake Kenneally
f89ce514c8 feat: Add Settings for toggling CSS on or off (#717)
Closes #712 

## Summary

**What is the goal of this PR?** 

- To add new settings for toggling on/off embedded CSS styles in the
reader. This gives more control and customization to the user over how
the ereader experience looks.

**What changes are included?**

- Added new "Embedded Style" option to the Reader settings
- Added new "Book's Style" option for "Paragraph Alignment"
- User's selected "Paragraph Alignment" will take precedence and
override the embedded CSS `text-align` property, _unless_ the user has
"Book's Style" set as their "Paragraph Alignment"

## Additional Context

![IMG_6336](https://github.com/user-attachments/assets/dff619ef-986d-465e-b352-73a76baae334)


https://github.com/user-attachments/assets/9e404b13-c7e0-41c7-9406-4715f389166a


Addresses feedback from the community about the new CSS feature:
https://github.com/crosspoint-reader/crosspoint-reader/pull/700

---

### AI Usage

While CrossPoint doesn't have restrictions on AI tools in contributing,
please be transparent about their usage as it
helps set the right context for reviewers.

Did you use AI tools to help write this code? _**YES**_, Claude Code
2026-02-06 18:49:04 +11:00
87 changed files with 7185 additions and 732 deletions

View File

@@ -230,6 +230,7 @@ Accessible by pressing **Confirm** while inside a book.
Please note that this firmware is currently in active development. The following features are **not yet supported** but are planned for future updates: Please note that this firmware is currently in active development. The following features are **not yet supported** but are planned for future updates:
* **Images:** Embedded images in e-books will not render. * **Images:** Embedded images in e-books will not render.
* **Cover Images:** Large cover images embedded into EPUB require several seconds (~10s for ~2000 pixel tall image) to convert for sleep screen and home screen thumbnail. Consider optimizing the EPUB with e.g. https://github.com/bigbag/epub-to-xtc-converter to speed this up.
--- ---
@@ -242,3 +243,5 @@ pio device monitor
``` ```
If the device is stuck in a bootloop, press and release the Reset button. Then, press and hold on to the configured Back button and the Power Button to boot to the Home Screen. If the device is stuck in a bootloop, press and release the Reset button. Then, press and hold on to the configured Back button and the Power Button to boot to the Home Screen.
There can be issues with broken cache or config. In this case, delete the `.crosspoint` directory on your SD card (or consider deleting only `settings.bin`, `state.bin`, or `epub_*` cache directories in the `.crosspoint/` folder).

View File

@@ -13,7 +13,9 @@ fi
# --modified: files tracked by git that have been modified (staged or unstaged) # --modified: files tracked by git that have been modified (staged or unstaged)
# --exclude-standard: ignores files in .gitignore # --exclude-standard: ignores files in .gitignore
# Additionally exclude files in 'lib/EpdFont/builtinFonts/' as they are script-generated. # Additionally exclude files in 'lib/EpdFont/builtinFonts/' as they are script-generated.
# Also exclude files in 'lib/Epub/Epub/hyphenation/generated/' as they are script-generated.
git ls-files --exclude-standard ${GIT_LS_FILES_FLAGS} \ git ls-files --exclude-standard ${GIT_LS_FILES_FLAGS} \
| grep -E '\.(c|cpp|h|hpp)$' \ | grep -E '\.(c|cpp|h|hpp)$' \
| grep -v -E '^lib/EpdFont/builtinFonts/' \ | grep -v -E '^lib/EpdFont/builtinFonts/' \
| grep -v -E '^lib/Epub/Epub/hyphenation/generated/' \
| xargs -r clang-format -style=file -i | xargs -r clang-format -style=file -i

View File

@@ -1,9 +1,9 @@
#include "Epub.h" #include "Epub.h"
#include <FsHelpers.h> #include <FsHelpers.h>
#include <HalStorage.h>
#include <HardwareSerial.h> #include <HardwareSerial.h>
#include <JpegToBmpConverter.h> #include <JpegToBmpConverter.h>
#include <SDCardManager.h>
#include <ZipFile.h> #include <ZipFile.h>
#include "Epub/parsers/ContainerParser.h" #include "Epub/parsers/ContainerParser.h"
@@ -105,12 +105,12 @@ bool Epub::parseTocNcxFile() const {
const auto tmpNcxPath = getCachePath() + "/toc.ncx"; const auto tmpNcxPath = getCachePath() + "/toc.ncx";
FsFile tempNcxFile; FsFile tempNcxFile;
if (!SdMan.openFileForWrite("EBP", tmpNcxPath, tempNcxFile)) { if (!Storage.openFileForWrite("EBP", tmpNcxPath, tempNcxFile)) {
return false; return false;
} }
readItemContentsToStream(tocNcxItem, tempNcxFile, 1024); readItemContentsToStream(tocNcxItem, tempNcxFile, 1024);
tempNcxFile.close(); tempNcxFile.close();
if (!SdMan.openFileForRead("EBP", tmpNcxPath, tempNcxFile)) { if (!Storage.openFileForRead("EBP", tmpNcxPath, tempNcxFile)) {
return false; return false;
} }
const auto ncxSize = tempNcxFile.size(); const auto ncxSize = tempNcxFile.size();
@@ -145,7 +145,7 @@ bool Epub::parseTocNcxFile() const {
free(ncxBuffer); free(ncxBuffer);
tempNcxFile.close(); tempNcxFile.close();
SdMan.remove(tmpNcxPath.c_str()); Storage.remove(tmpNcxPath.c_str());
Serial.printf("[%lu] [EBP] Parsed TOC items\n", millis()); Serial.printf("[%lu] [EBP] Parsed TOC items\n", millis());
return true; return true;
@@ -162,12 +162,12 @@ bool Epub::parseTocNavFile() const {
const auto tmpNavPath = getCachePath() + "/toc.nav"; const auto tmpNavPath = getCachePath() + "/toc.nav";
FsFile tempNavFile; FsFile tempNavFile;
if (!SdMan.openFileForWrite("EBP", tmpNavPath, tempNavFile)) { if (!Storage.openFileForWrite("EBP", tmpNavPath, tempNavFile)) {
return false; return false;
} }
readItemContentsToStream(tocNavItem, tempNavFile, 1024); readItemContentsToStream(tocNavItem, tempNavFile, 1024);
tempNavFile.close(); tempNavFile.close();
if (!SdMan.openFileForRead("EBP", tmpNavPath, tempNavFile)) { if (!Storage.openFileForRead("EBP", tmpNavPath, tempNavFile)) {
return false; return false;
} }
const auto navSize = tempNavFile.size(); const auto navSize = tempNavFile.size();
@@ -202,7 +202,7 @@ bool Epub::parseTocNavFile() const {
free(navBuffer); free(navBuffer);
tempNavFile.close(); tempNavFile.close();
SdMan.remove(tmpNavPath.c_str()); Storage.remove(tmpNavPath.c_str());
Serial.printf("[%lu] [EBP] Parsed TOC nav items\n", millis()); Serial.printf("[%lu] [EBP] Parsed TOC nav items\n", millis());
return true; return true;
@@ -212,7 +212,7 @@ std::string Epub::getCssRulesCache() const { return cachePath + "/css_rules.cach
bool Epub::loadCssRulesFromCache() const { bool Epub::loadCssRulesFromCache() const {
FsFile cssCacheFile; FsFile cssCacheFile;
if (SdMan.openFileForRead("EBP", getCssRulesCache(), cssCacheFile)) { if (Storage.openFileForRead("EBP", getCssRulesCache(), cssCacheFile)) {
if (cssParser->loadFromCache(cssCacheFile)) { if (cssParser->loadFromCache(cssCacheFile)) {
cssCacheFile.close(); cssCacheFile.close();
Serial.printf("[%lu] [EBP] Loaded CSS rules from cache\n", millis()); Serial.printf("[%lu] [EBP] Loaded CSS rules from cache\n", millis());
@@ -238,32 +238,32 @@ void Epub::parseCssFiles() const {
// Extract CSS file to temp location // Extract CSS file to temp location
const auto tmpCssPath = getCachePath() + "/.tmp.css"; const auto tmpCssPath = getCachePath() + "/.tmp.css";
FsFile tempCssFile; FsFile tempCssFile;
if (!SdMan.openFileForWrite("EBP", tmpCssPath, tempCssFile)) { if (!Storage.openFileForWrite("EBP", tmpCssPath, tempCssFile)) {
Serial.printf("[%lu] [EBP] Could not create temp CSS file\n", millis()); Serial.printf("[%lu] [EBP] Could not create temp CSS file\n", millis());
continue; continue;
} }
if (!readItemContentsToStream(cssPath, tempCssFile, 1024)) { if (!readItemContentsToStream(cssPath, tempCssFile, 1024)) {
Serial.printf("[%lu] [EBP] Could not read CSS file: %s\n", millis(), cssPath.c_str()); Serial.printf("[%lu] [EBP] Could not read CSS file: %s\n", millis(), cssPath.c_str());
tempCssFile.close(); tempCssFile.close();
SdMan.remove(tmpCssPath.c_str()); Storage.remove(tmpCssPath.c_str());
continue; continue;
} }
tempCssFile.close(); tempCssFile.close();
// Parse the CSS file // Parse the CSS file
if (!SdMan.openFileForRead("EBP", tmpCssPath, tempCssFile)) { if (!Storage.openFileForRead("EBP", tmpCssPath, tempCssFile)) {
Serial.printf("[%lu] [EBP] Could not open temp CSS file for reading\n", millis()); Serial.printf("[%lu] [EBP] Could not open temp CSS file for reading\n", millis());
SdMan.remove(tmpCssPath.c_str()); Storage.remove(tmpCssPath.c_str());
continue; continue;
} }
cssParser->loadFromStream(tempCssFile); cssParser->loadFromStream(tempCssFile);
tempCssFile.close(); tempCssFile.close();
SdMan.remove(tmpCssPath.c_str()); Storage.remove(tmpCssPath.c_str());
} }
// Save to cache for next time // Save to cache for next time
FsFile cssCacheFile; FsFile cssCacheFile;
if (SdMan.openFileForWrite("EBP", getCssRulesCache(), cssCacheFile)) { if (Storage.openFileForWrite("EBP", getCssRulesCache(), cssCacheFile)) {
cssParser->saveToCache(cssCacheFile); cssParser->saveToCache(cssCacheFile);
cssCacheFile.close(); cssCacheFile.close();
} }
@@ -399,12 +399,12 @@ bool Epub::load(const bool buildIfMissing, const bool skipLoadingCss) {
} }
bool Epub::clearCache() const { bool Epub::clearCache() const {
if (!SdMan.exists(cachePath.c_str())) { if (!Storage.exists(cachePath.c_str())) {
Serial.printf("[%lu] [EPB] Cache does not exist, no action needed\n", millis()); Serial.printf("[%lu] [EPB] Cache does not exist, no action needed\n", millis());
return true; return true;
} }
if (!SdMan.removeDir(cachePath.c_str())) { if (!Storage.removeDir(cachePath.c_str())) {
Serial.printf("[%lu] [EPB] Failed to clear cache\n", millis()); Serial.printf("[%lu] [EPB] Failed to clear cache\n", millis());
return false; return false;
} }
@@ -414,11 +414,11 @@ bool Epub::clearCache() const {
} }
void Epub::setupCacheDir() const { void Epub::setupCacheDir() const {
if (SdMan.exists(cachePath.c_str())) { if (Storage.exists(cachePath.c_str())) {
return; return;
} }
SdMan.mkdir(cachePath.c_str()); Storage.mkdir(cachePath.c_str());
} }
const std::string& Epub::getCachePath() const { return cachePath; } const std::string& Epub::getCachePath() const { return cachePath; }
@@ -459,7 +459,7 @@ std::string Epub::getCoverBmpPath(bool cropped) const {
bool Epub::generateCoverBmp(bool cropped) const { bool Epub::generateCoverBmp(bool cropped) const {
// Already generated, return true // Already generated, return true
if (SdMan.exists(getCoverBmpPath(cropped).c_str())) { if (Storage.exists(getCoverBmpPath(cropped).c_str())) {
return true; return true;
} }
@@ -480,29 +480,29 @@ bool Epub::generateCoverBmp(bool cropped) const {
const auto coverJpgTempPath = getCachePath() + "/.cover.jpg"; const auto coverJpgTempPath = getCachePath() + "/.cover.jpg";
FsFile coverJpg; FsFile coverJpg;
if (!SdMan.openFileForWrite("EBP", coverJpgTempPath, coverJpg)) { if (!Storage.openFileForWrite("EBP", coverJpgTempPath, coverJpg)) {
return false; return false;
} }
readItemContentsToStream(coverImageHref, coverJpg, 1024); readItemContentsToStream(coverImageHref, coverJpg, 1024);
coverJpg.close(); coverJpg.close();
if (!SdMan.openFileForRead("EBP", coverJpgTempPath, coverJpg)) { if (!Storage.openFileForRead("EBP", coverJpgTempPath, coverJpg)) {
return false; return false;
} }
FsFile coverBmp; FsFile coverBmp;
if (!SdMan.openFileForWrite("EBP", getCoverBmpPath(cropped), coverBmp)) { if (!Storage.openFileForWrite("EBP", getCoverBmpPath(cropped), coverBmp)) {
coverJpg.close(); coverJpg.close();
return false; return false;
} }
const bool success = JpegToBmpConverter::jpegFileToBmpStream(coverJpg, coverBmp, cropped); const bool success = JpegToBmpConverter::jpegFileToBmpStream(coverJpg, coverBmp, cropped);
coverJpg.close(); coverJpg.close();
coverBmp.close(); coverBmp.close();
SdMan.remove(coverJpgTempPath.c_str()); Storage.remove(coverJpgTempPath.c_str());
if (!success) { if (!success) {
Serial.printf("[%lu] [EBP] Failed to generate BMP from JPG cover image\n", millis()); Serial.printf("[%lu] [EBP] Failed to generate BMP from JPG cover image\n", millis());
SdMan.remove(getCoverBmpPath(cropped).c_str()); Storage.remove(getCoverBmpPath(cropped).c_str());
} }
Serial.printf("[%lu] [EBP] Generated BMP from JPG cover image, success: %s\n", millis(), success ? "yes" : "no"); Serial.printf("[%lu] [EBP] Generated BMP from JPG cover image, success: %s\n", millis(), success ? "yes" : "no");
return success; return success;
@@ -518,7 +518,7 @@ std::string Epub::getThumbBmpPath(int height) const { return cachePath + "/thumb
bool Epub::generateThumbBmp(int height) const { bool Epub::generateThumbBmp(int height) const {
// Already generated, return true // Already generated, return true
if (SdMan.exists(getThumbBmpPath(height).c_str())) { if (Storage.exists(getThumbBmpPath(height).c_str())) {
return true; return true;
} }
@@ -536,18 +536,18 @@ bool Epub::generateThumbBmp(int height) const {
const auto coverJpgTempPath = getCachePath() + "/.cover.jpg"; const auto coverJpgTempPath = getCachePath() + "/.cover.jpg";
FsFile coverJpg; FsFile coverJpg;
if (!SdMan.openFileForWrite("EBP", coverJpgTempPath, coverJpg)) { if (!Storage.openFileForWrite("EBP", coverJpgTempPath, coverJpg)) {
return false; return false;
} }
readItemContentsToStream(coverImageHref, coverJpg, 1024); readItemContentsToStream(coverImageHref, coverJpg, 1024);
coverJpg.close(); coverJpg.close();
if (!SdMan.openFileForRead("EBP", coverJpgTempPath, coverJpg)) { if (!Storage.openFileForRead("EBP", coverJpgTempPath, coverJpg)) {
return false; return false;
} }
FsFile thumbBmp; FsFile thumbBmp;
if (!SdMan.openFileForWrite("EBP", getThumbBmpPath(height), thumbBmp)) { if (!Storage.openFileForWrite("EBP", getThumbBmpPath(height), thumbBmp)) {
coverJpg.close(); coverJpg.close();
return false; return false;
} }
@@ -559,11 +559,11 @@ bool Epub::generateThumbBmp(int height) const {
THUMB_TARGET_HEIGHT); THUMB_TARGET_HEIGHT);
coverJpg.close(); coverJpg.close();
thumbBmp.close(); thumbBmp.close();
SdMan.remove(coverJpgTempPath.c_str()); Storage.remove(coverJpgTempPath.c_str());
if (!success) { if (!success) {
Serial.printf("[%lu] [EBP] Failed to generate thumb BMP from JPG cover image\n", millis()); Serial.printf("[%lu] [EBP] Failed to generate thumb BMP from JPG cover image\n", millis());
SdMan.remove(getThumbBmpPath(height).c_str()); Storage.remove(getThumbBmpPath(height).c_str());
} }
Serial.printf("[%lu] [EBP] Generated thumb BMP from JPG cover image, success: %s\n", millis(), Serial.printf("[%lu] [EBP] Generated thumb BMP from JPG cover image, success: %s\n", millis(),
success ? "yes" : "no"); success ? "yes" : "no");
@@ -574,7 +574,7 @@ bool Epub::generateThumbBmp(int height) const {
// Write an empty bmp file to avoid generation attempts in the future // Write an empty bmp file to avoid generation attempts in the future
FsFile thumbBmp; FsFile thumbBmp;
SdMan.openFileForWrite("EBP", getThumbBmpPath(height), thumbBmp); Storage.openFileForWrite("EBP", getThumbBmpPath(height), thumbBmp);
thumbBmp.close(); thumbBmp.close();
return false; return false;
} }

View File

@@ -29,7 +29,7 @@ bool BookMetadataCache::beginContentOpfPass() {
Serial.printf("[%lu] [BMC] Beginning content opf pass\n", millis()); Serial.printf("[%lu] [BMC] Beginning content opf pass\n", millis());
// Open spine file for writing // Open spine file for writing
return SdMan.openFileForWrite("BMC", cachePath + tmpSpineBinFile, spineFile); return Storage.openFileForWrite("BMC", cachePath + tmpSpineBinFile, spineFile);
} }
bool BookMetadataCache::endContentOpfPass() { bool BookMetadataCache::endContentOpfPass() {
@@ -40,10 +40,10 @@ bool BookMetadataCache::endContentOpfPass() {
bool BookMetadataCache::beginTocPass() { bool BookMetadataCache::beginTocPass() {
Serial.printf("[%lu] [BMC] Beginning toc pass\n", millis()); Serial.printf("[%lu] [BMC] Beginning toc pass\n", millis());
if (!SdMan.openFileForRead("BMC", cachePath + tmpSpineBinFile, spineFile)) { if (!Storage.openFileForRead("BMC", cachePath + tmpSpineBinFile, spineFile)) {
return false; return false;
} }
if (!SdMan.openFileForWrite("BMC", cachePath + tmpTocBinFile, tocFile)) { if (!Storage.openFileForWrite("BMC", cachePath + tmpTocBinFile, tocFile)) {
spineFile.close(); spineFile.close();
return false; return false;
} }
@@ -98,16 +98,16 @@ bool BookMetadataCache::endWrite() {
bool BookMetadataCache::buildBookBin(const std::string& epubPath, const BookMetadata& metadata) { bool BookMetadataCache::buildBookBin(const std::string& epubPath, const BookMetadata& metadata) {
// Open all three files, writing to meta, reading from spine and toc // Open all three files, writing to meta, reading from spine and toc
if (!SdMan.openFileForWrite("BMC", cachePath + bookBinFile, bookFile)) { if (!Storage.openFileForWrite("BMC", cachePath + bookBinFile, bookFile)) {
return false; return false;
} }
if (!SdMan.openFileForRead("BMC", cachePath + tmpSpineBinFile, spineFile)) { if (!Storage.openFileForRead("BMC", cachePath + tmpSpineBinFile, spineFile)) {
bookFile.close(); bookFile.close();
return false; return false;
} }
if (!SdMan.openFileForRead("BMC", cachePath + tmpTocBinFile, tocFile)) { if (!Storage.openFileForRead("BMC", cachePath + tmpTocBinFile, tocFile)) {
bookFile.close(); bookFile.close();
spineFile.close(); spineFile.close();
return false; return false;
@@ -275,11 +275,11 @@ bool BookMetadataCache::buildBookBin(const std::string& epubPath, const BookMeta
} }
bool BookMetadataCache::cleanupTmpFiles() const { bool BookMetadataCache::cleanupTmpFiles() const {
if (SdMan.exists((cachePath + tmpSpineBinFile).c_str())) { if (Storage.exists((cachePath + tmpSpineBinFile).c_str())) {
SdMan.remove((cachePath + tmpSpineBinFile).c_str()); Storage.remove((cachePath + tmpSpineBinFile).c_str());
} }
if (SdMan.exists((cachePath + tmpTocBinFile).c_str())) { if (Storage.exists((cachePath + tmpTocBinFile).c_str())) {
SdMan.remove((cachePath + tmpTocBinFile).c_str()); Storage.remove((cachePath + tmpTocBinFile).c_str());
} }
return true; return true;
} }
@@ -364,7 +364,7 @@ void BookMetadataCache::createTocEntry(const std::string& title, const std::stri
/* ============= READING / LOADING FUNCTIONS ================ */ /* ============= READING / LOADING FUNCTIONS ================ */
bool BookMetadataCache::load() { bool BookMetadataCache::load() {
if (!SdMan.openFileForRead("BMC", cachePath + bookBinFile, bookFile)) { if (!Storage.openFileForRead("BMC", cachePath + bookBinFile, bookFile)) {
return false; return false;
} }

View File

@@ -1,6 +1,6 @@
#pragma once #pragma once
#include <SDCardManager.h> #include <HalStorage.h>
#include <algorithm> #include <algorithm>
#include <string> #include <string>

View File

@@ -1,5 +1,5 @@
#pragma once #pragma once
#include <SdFat.h> #include <HalStorage.h>
#include <utility> #include <utility>
#include <vector> #include <vector>

View File

@@ -1,6 +1,6 @@
#include "Section.h" #include "Section.h"
#include <SDCardManager.h> #include <HalStorage.h>
#include <Serialization.h> #include <Serialization.h>
#include "Page.h" #include "Page.h"
@@ -60,7 +60,7 @@ void Section::writeSectionFileHeader(const int fontId, const float lineCompressi
bool Section::loadSectionFile(const int fontId, const float lineCompression, const bool extraParagraphSpacing, bool Section::loadSectionFile(const int fontId, const float lineCompression, const bool extraParagraphSpacing,
const uint8_t paragraphAlignment, const uint16_t viewportWidth, const uint8_t paragraphAlignment, const uint16_t viewportWidth,
const uint16_t viewportHeight, const bool hyphenationEnabled, const bool embeddedStyle) { const uint16_t viewportHeight, const bool hyphenationEnabled, const bool embeddedStyle) {
if (!SdMan.openFileForRead("SCT", filePath, file)) { if (!Storage.openFileForRead("SCT", filePath, file)) {
return false; return false;
} }
@@ -110,12 +110,12 @@ bool Section::loadSectionFile(const int fontId, const float lineCompression, con
// Your updated class method (assuming you are using the 'SD' object, which is a wrapper for a specific filesystem) // Your updated class method (assuming you are using the 'SD' object, which is a wrapper for a specific filesystem)
bool Section::clearCache() const { bool Section::clearCache() const {
if (!SdMan.exists(filePath.c_str())) { if (!Storage.exists(filePath.c_str())) {
Serial.printf("[%lu] [SCT] Cache does not exist, no action needed\n", millis()); Serial.printf("[%lu] [SCT] Cache does not exist, no action needed\n", millis());
return true; return true;
} }
if (!SdMan.remove(filePath.c_str())) { if (!Storage.remove(filePath.c_str())) {
Serial.printf("[%lu] [SCT] Failed to clear cache\n", millis()); Serial.printf("[%lu] [SCT] Failed to clear cache\n", millis());
return false; return false;
} }
@@ -134,7 +134,7 @@ bool Section::createSectionFile(const int fontId, const float lineCompression, c
// Create cache directory if it doesn't exist // Create cache directory if it doesn't exist
{ {
const auto sectionsDir = epub->getCachePath() + "/sections"; const auto sectionsDir = epub->getCachePath() + "/sections";
SdMan.mkdir(sectionsDir.c_str()); Storage.mkdir(sectionsDir.c_str());
} }
// Retry logic for SD card timing issues // Retry logic for SD card timing issues
@@ -147,12 +147,12 @@ bool Section::createSectionFile(const int fontId, const float lineCompression, c
} }
// Remove any incomplete file from previous attempt before retrying // Remove any incomplete file from previous attempt before retrying
if (SdMan.exists(tmpHtmlPath.c_str())) { if (Storage.exists(tmpHtmlPath.c_str())) {
SdMan.remove(tmpHtmlPath.c_str()); Storage.remove(tmpHtmlPath.c_str());
} }
FsFile tmpHtml; FsFile tmpHtml;
if (!SdMan.openFileForWrite("SCT", tmpHtmlPath, tmpHtml)) { if (!Storage.openFileForWrite("SCT", tmpHtmlPath, tmpHtml)) {
continue; continue;
} }
success = epub->readItemContentsToStream(localPath, tmpHtml, 1024); success = epub->readItemContentsToStream(localPath, tmpHtml, 1024);
@@ -160,8 +160,8 @@ bool Section::createSectionFile(const int fontId, const float lineCompression, c
tmpHtml.close(); tmpHtml.close();
// If streaming failed, remove the incomplete file immediately // If streaming failed, remove the incomplete file immediately
if (!success && SdMan.exists(tmpHtmlPath.c_str())) { if (!success && Storage.exists(tmpHtmlPath.c_str())) {
SdMan.remove(tmpHtmlPath.c_str()); Storage.remove(tmpHtmlPath.c_str());
Serial.printf("[%lu] [SCT] Removed incomplete temp file after failed attempt\n", millis()); Serial.printf("[%lu] [SCT] Removed incomplete temp file after failed attempt\n", millis());
} }
} }
@@ -173,7 +173,7 @@ bool Section::createSectionFile(const int fontId, const float lineCompression, c
Serial.printf("[%lu] [SCT] Streamed temp HTML to %s (%d bytes)\n", millis(), tmpHtmlPath.c_str(), fileSize); Serial.printf("[%lu] [SCT] Streamed temp HTML to %s (%d bytes)\n", millis(), tmpHtmlPath.c_str(), fileSize);
if (!SdMan.openFileForWrite("SCT", filePath, file)) { if (!Storage.openFileForWrite("SCT", filePath, file)) {
return false; return false;
} }
writeSectionFileHeader(fontId, lineCompression, extraParagraphSpacing, paragraphAlignment, viewportWidth, writeSectionFileHeader(fontId, lineCompression, extraParagraphSpacing, paragraphAlignment, viewportWidth,
@@ -188,11 +188,11 @@ bool Section::createSectionFile(const int fontId, const float lineCompression, c
Hyphenator::setPreferredLanguage(epub->getLanguage()); Hyphenator::setPreferredLanguage(epub->getLanguage());
success = visitor.parseAndBuildPages(); success = visitor.parseAndBuildPages();
SdMan.remove(tmpHtmlPath.c_str()); Storage.remove(tmpHtmlPath.c_str());
if (!success) { if (!success) {
Serial.printf("[%lu] [SCT] Failed to parse XML and build pages\n", millis()); Serial.printf("[%lu] [SCT] Failed to parse XML and build pages\n", millis());
file.close(); file.close();
SdMan.remove(filePath.c_str()); Storage.remove(filePath.c_str());
return false; return false;
} }
@@ -210,7 +210,7 @@ bool Section::createSectionFile(const int fontId, const float lineCompression, c
if (hasFailedLutRecords) { if (hasFailedLutRecords) {
Serial.printf("[%lu] [SCT] Failed to write LUT due to invalid page positions\n", millis()); Serial.printf("[%lu] [SCT] Failed to write LUT due to invalid page positions\n", millis());
file.close(); file.close();
SdMan.remove(filePath.c_str()); Storage.remove(filePath.c_str());
return false; return false;
} }
@@ -223,7 +223,7 @@ bool Section::createSectionFile(const int fontId, const float lineCompression, c
} }
std::unique_ptr<Page> Section::loadPageFromSectionFile() { std::unique_ptr<Page> Section::loadPageFromSectionFile() {
if (!SdMan.openFileForRead("SCT", filePath, file)) { if (!Storage.openFileForRead("SCT", filePath, file)) {
return nullptr; return nullptr;
} }

View File

@@ -1,6 +1,6 @@
#pragma once #pragma once
#include <EpdFontFamily.h> #include <EpdFontFamily.h>
#include <SdFat.h> #include <HalStorage.h>
#include <list> #include <list>
#include <memory> #include <memory>

View File

@@ -1,6 +1,6 @@
#pragma once #pragma once
#include <SdFat.h> #include <HalStorage.h>
#include <string> #include <string>
#include <unordered_map> #include <unordered_map>

View File

@@ -8,6 +8,7 @@
#include "generated/hyph-en.trie.h" #include "generated/hyph-en.trie.h"
#include "generated/hyph-es.trie.h" #include "generated/hyph-es.trie.h"
#include "generated/hyph-fr.trie.h" #include "generated/hyph-fr.trie.h"
#include "generated/hyph-it.trie.h"
#include "generated/hyph-ru.trie.h" #include "generated/hyph-ru.trie.h"
namespace { namespace {
@@ -18,15 +19,17 @@ LanguageHyphenator frenchHyphenator(fr_patterns, isLatinLetter, toLowerLatin);
LanguageHyphenator germanHyphenator(de_patterns, isLatinLetter, toLowerLatin); LanguageHyphenator germanHyphenator(de_patterns, isLatinLetter, toLowerLatin);
LanguageHyphenator russianHyphenator(ru_ru_patterns, isCyrillicLetter, toLowerCyrillic); LanguageHyphenator russianHyphenator(ru_ru_patterns, isCyrillicLetter, toLowerCyrillic);
LanguageHyphenator spanishHyphenator(es_patterns, isLatinLetter, toLowerLatin); LanguageHyphenator spanishHyphenator(es_patterns, isLatinLetter, toLowerLatin);
LanguageHyphenator italianHyphenator(it_patterns, isLatinLetter, toLowerLatin);
using EntryArray = std::array<LanguageEntry, 5>; using EntryArray = std::array<LanguageEntry, 6>;
const EntryArray& entries() { const EntryArray& entries() {
static const EntryArray kEntries = {{{"english", "en", &englishHyphenator}, static const EntryArray kEntries = {{{"english", "en", &englishHyphenator},
{"french", "fr", &frenchHyphenator}, {"french", "fr", &frenchHyphenator},
{"german", "de", &germanHyphenator}, {"german", "de", &germanHyphenator},
{"russian", "ru", &russianHyphenator}, {"russian", "ru", &russianHyphenator},
{"spanish", "es", &spanishHyphenator}}}; {"spanish", "es", &spanishHyphenator},
{"italian", "it", &italianHyphenator}}};
return kEntries; return kEntries;
} }

View File

@@ -0,0 +1,113 @@
#pragma once
#include <cstddef>
#include <cstdint>
#include "../SerializedHyphenationTrie.h"
// Auto-generated by generate_hyphenation_trie.py. Do not edit manually.
alignas(4) constexpr uint8_t it_trie_data[] = {
0x00, 0x00, 0x05, 0xC4, 0x17, 0x0C, 0x33, 0x35, 0x0C, 0x29, 0x22, 0x0D, 0x3E, 0x0B, 0x47, 0x20,
0x0D, 0x16, 0x0B, 0x34, 0x0D, 0x21, 0x0C, 0x3D, 0x1F, 0x0C, 0x2A, 0x17, 0x2A, 0x0B, 0x02, 0x0C,
0x01, 0x02, 0x16, 0x02, 0x0D, 0x0C, 0x0C, 0x0D, 0x03, 0x0C, 0x01, 0x0C, 0x0E, 0x0D, 0x04, 0x02,
0x0B, 0xA0, 0x00, 0x42, 0x21, 0x6E, 0xFD, 0xA0, 0x00, 0x72, 0x21, 0x6E, 0xFD, 0xA1, 0x00, 0x61,
0x6D, 0xFD, 0x21, 0x69, 0xFB, 0x21, 0x74, 0xFD, 0x22, 0x70, 0x6E, 0xEC, 0xFD, 0xA0, 0x00, 0x91,
0x21, 0x6F, 0xFD, 0x21, 0x69, 0xFD, 0xA0, 0x00, 0xA2, 0x21, 0x73, 0xFD, 0x21, 0x70, 0xFD, 0xA0,
0x00, 0xC2, 0x21, 0x6D, 0xFD, 0x21, 0x75, 0xFD, 0x21, 0x63, 0xFD, 0x21, 0x72, 0xFD, 0xA0, 0x00,
0xE1, 0x21, 0x6F, 0xFD, 0x21, 0x72, 0xFD, 0x21, 0x74, 0xFD, 0x21, 0x6E, 0xFD, 0xA3, 0x01, 0x11,
0x61, 0x69, 0x6F, 0xDF, 0xEE, 0xFD, 0xA0, 0x00, 0xF2, 0x21, 0x65, 0xFD, 0x21, 0x6E, 0xFD, 0x21,
0x69, 0xFD, 0x21, 0x63, 0xFD, 0x21, 0x73, 0xFD, 0xA1, 0x01, 0x11, 0x69, 0xFD, 0xA0, 0x01, 0x12,
0x21, 0x75, 0xFD, 0x21, 0x65, 0xFD, 0x21, 0x78, 0xFD, 0xA0, 0x01, 0x32, 0x21, 0x6B, 0xFD, 0x21,
0x6E, 0xFD, 0xA0, 0x00, 0x71, 0x21, 0x65, 0xFD, 0x22, 0x61, 0x65, 0xF7, 0xFD, 0x21, 0x72, 0xFB,
0xA0, 0x01, 0x52, 0x21, 0x61, 0xFD, 0x21, 0x73, 0xFD, 0x21, 0x70, 0xFD, 0x21, 0x69, 0xFD, 0xA0,
0x01, 0x71, 0x21, 0x6F, 0xFD, 0x21, 0x63, 0xFD, 0x21, 0x72, 0xFD, 0x21, 0x61, 0xFD, 0xA0, 0x00,
0x61, 0x21, 0x6F, 0xFD, 0x21, 0x74, 0xFD, 0x41, 0x70, 0xFF, 0x50, 0x21, 0x6F, 0xFC, 0x21, 0x74,
0xFD, 0x22, 0x70, 0x72, 0xF3, 0xFD, 0x21, 0x61, 0xE8, 0x21, 0x72, 0xFD, 0xA0, 0x00, 0xF1, 0x22,
0x6C, 0x72, 0xFD, 0xFD, 0x21, 0x69, 0xE3, 0x21, 0x6C, 0xFD, 0x41, 0x65, 0xFF, 0x43, 0xA0, 0x01,
0x11, 0x25, 0x61, 0x68, 0x6F, 0x72, 0x73, 0xE8, 0xEE, 0xF6, 0xF9, 0xFD, 0xA0, 0x01, 0x82, 0x21,
0x72, 0xFD, 0x21, 0x63, 0xFD, 0x21, 0x73, 0xFD, 0x21, 0x69, 0xFD, 0x21, 0x65, 0xFD, 0xA0, 0x01,
0xA2, 0x21, 0x65, 0xFD, 0x21, 0x72, 0xFD, 0x21, 0x61, 0xFD, 0x41, 0x75, 0xFF, 0x4C, 0x42, 0x6C,
0x72, 0xFF, 0xFC, 0xFF, 0x48, 0x21, 0x62, 0xF9, 0x22, 0x68, 0x75, 0xEF, 0xFD, 0x47, 0x63, 0x64,
0x6C, 0x6E, 0x70, 0x72, 0x74, 0xFF, 0x5C, 0xFF, 0x5C, 0xFF, 0x5C, 0xFF, 0x5C, 0xFF, 0x5C, 0xFF,
0x5C, 0xFF, 0x5C, 0x21, 0x73, 0xEA, 0x21, 0x6E, 0xFD, 0x21, 0x61, 0xFD, 0xA1, 0x01, 0x11, 0x72,
0xFD, 0x41, 0x6E, 0xFF, 0x15, 0x21, 0x67, 0xFC, 0xA0, 0x01, 0xC2, 0x21, 0x74, 0xFD, 0x21, 0x6C,
0xFD, 0x22, 0x61, 0x65, 0xF4, 0xFD, 0x52, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x6C, 0x6E, 0x6F,
0x70, 0x72, 0x73, 0x74, 0x77, 0x68, 0x6A, 0x6B, 0x7A, 0xFE, 0xC2, 0xFE, 0xCD, 0xFE, 0xF7, 0xFF,
0x12, 0xFF, 0x20, 0xFF, 0x37, 0xFF, 0x46, 0xFF, 0x55, 0xFF, 0x6B, 0xFF, 0x8B, 0xFF, 0xA5, 0xFF,
0xC2, 0xFF, 0xE6, 0xFF, 0xFB, 0xFF, 0x88, 0xFF, 0x88, 0xFF, 0x88, 0xFF, 0x88, 0xA0, 0x01, 0xE2,
0xA0, 0x00, 0xD1, 0x24, 0x61, 0x65, 0x6F, 0x75, 0xFD, 0xFD, 0xFD, 0xFD, 0x21, 0x6F, 0xF4, 0x21,
0x61, 0xF1, 0xA0, 0x01, 0xE1, 0x21, 0x2E, 0xFD, 0x24, 0x69, 0x75, 0x79, 0x74, 0xEB, 0xF4, 0xF7,
0xFD, 0x21, 0x75, 0xDF, 0xA0, 0x00, 0x51, 0x22, 0x69, 0x77, 0xFA, 0xFD, 0x21, 0x69, 0xD7, 0xAE,
0x02, 0x01, 0x62, 0x63, 0x64, 0x66, 0x6D, 0x6E, 0x70, 0x73, 0x74, 0x76, 0x6C, 0x72, 0x2E, 0x27,
0xE3, 0xE3, 0xE3, 0xE3, 0xE3, 0xE3, 0xE3, 0xE3, 0xE3, 0xE3, 0xF5, 0xF5, 0xE3, 0xE3, 0x22, 0x2E,
0x27, 0xC4, 0xC7, 0xC6, 0x00, 0x51, 0x68, 0x2E, 0x27, 0x62, 0x72, 0x6E, 0xFF, 0xBF, 0xFF, 0xBF,
0xFF, 0xFB, 0xFF, 0xBF, 0xFE, 0xFB, 0xFF, 0xBF, 0xD0, 0x02, 0x01, 0x62, 0x63, 0x64, 0x66, 0x6B,
0x6D, 0x6E, 0x71, 0x73, 0x74, 0x7A, 0x68, 0x6C, 0x72, 0x2E, 0x27, 0xFF, 0xAA, 0xFF, 0xAA, 0xFF,
0xAA, 0xFF, 0xAA, 0xFF, 0xAA, 0xFF, 0xAA, 0xFF, 0xAA, 0xFF, 0xAA, 0xFF, 0xAA, 0xFF, 0xAA, 0xFF,
0xAA, 0xFF, 0xEB, 0xFF, 0xBC, 0xFF, 0xBC, 0xFF, 0xAA, 0xFF, 0xAA, 0xCE, 0x02, 0x01, 0x62, 0x64,
0x67, 0x6C, 0x6D, 0x6E, 0x70, 0x72, 0x73, 0x74, 0x76, 0x77, 0x2E, 0x27, 0xFF, 0x77, 0xFF, 0x77,
0xFF, 0x77, 0xFF, 0x77, 0xFF, 0x77, 0xFF, 0x77, 0xFF, 0x77, 0xFF, 0x89, 0xFF, 0x77, 0xFF, 0x77,
0xFF, 0x77, 0xFF, 0x77, 0xFF, 0x77, 0xFF, 0x77, 0xCA, 0x02, 0x01, 0x62, 0x67, 0x66, 0x6E, 0x6C,
0x72, 0x73, 0x74, 0x2E, 0x27, 0xFF, 0x4A, 0xFF, 0x4A, 0xFF, 0x4A, 0xFF, 0x4A, 0xFF, 0x5C, 0xFF,
0x5C, 0xFF, 0x4A, 0xFF, 0x4A, 0xFF, 0x4A, 0xFF, 0x4A, 0xA0, 0x02, 0x12, 0xA1, 0x00, 0x51, 0x74,
0xFD, 0xD1, 0x02, 0x01, 0x62, 0x64, 0x66, 0x67, 0x68, 0x6C, 0x6D, 0x6E, 0x70, 0x72, 0x73, 0x74,
0x76, 0x77, 0x7A, 0x2E, 0x27, 0xFF, 0x21, 0xFF, 0x21, 0xFF, 0x21, 0xFF, 0x21, 0xFF, 0xFB, 0xFF,
0x33, 0xFF, 0x21, 0xFF, 0x33, 0xFF, 0x21, 0xFF, 0x33, 0xFF, 0x21, 0xFF, 0x21, 0xFF, 0x21, 0xFF,
0x21, 0xFF, 0x21, 0xFF, 0x21, 0xFF, 0x21, 0x41, 0x70, 0xFD, 0x4D, 0xCB, 0x02, 0x01, 0x62, 0x64,
0x68, 0x69, 0x6C, 0x6D, 0x6E, 0x72, 0x76, 0x2E, 0x27, 0xFE, 0xE7, 0xFE, 0xE7, 0xFE, 0xE7, 0xFF,
0xFC, 0xFE, 0xF9, 0xFE, 0xE7, 0xFE, 0xE7, 0xFE, 0xE7, 0xFE, 0xE7, 0xFE, 0xE7, 0xFE, 0xE7, 0xC2,
0x02, 0x01, 0x2E, 0x27, 0xFE, 0xC3, 0xFE, 0xC3, 0xCB, 0x02, 0x01, 0x67, 0x66, 0x68, 0x6B, 0x6C,
0x6D, 0x72, 0x73, 0x74, 0x2E, 0x27, 0xFE, 0xBA, 0xFE, 0xBA, 0xFE, 0xCC, 0xFE, 0xBA, 0xFE, 0xCC,
0xFE, 0xBA, 0xFE, 0xCC, 0xFE, 0xBA, 0xFE, 0xBA, 0xFE, 0xBA, 0xFE, 0xBA, 0xA0, 0x02, 0x33, 0x42,
0x2E, 0x27, 0xFE, 0x93, 0xFE, 0x93, 0xD5, 0x02, 0x01, 0x62, 0x63, 0x64, 0x66, 0x67, 0x68, 0x6A,
0x6B, 0x6C, 0x6D, 0x6E, 0x70, 0x71, 0x72, 0x73, 0x74, 0x76, 0x77, 0x7A, 0x2E, 0x27, 0xFE, 0x8C,
0xFE, 0x8C, 0xFE, 0x8C, 0xFF, 0xF6, 0xFE, 0x8C, 0xFE, 0x9E, 0xFE, 0x9E, 0xFE, 0x8C, 0xFE, 0x8C,
0xFE, 0x8C, 0xFE, 0x8C, 0xFE, 0x8C, 0xFE, 0x8C, 0xFE, 0x8C, 0xFE, 0x8C, 0xFE, 0x8C, 0xFE, 0x8C,
0xFE, 0x8C, 0xFE, 0x8C, 0xFE, 0x8C, 0xFF, 0xF9, 0xCF, 0x02, 0x01, 0x62, 0x63, 0x66, 0x6C, 0x6D,
0x6E, 0x70, 0x71, 0x72, 0x73, 0x74, 0x76, 0x77, 0x2E, 0x27, 0xFE, 0x4A, 0xFE, 0x4A, 0xFE, 0x4A,
0xFE, 0x4A, 0xFE, 0x4A, 0xFE, 0x4A, 0xFE, 0x4A, 0xFE, 0x4A, 0xFE, 0x4A, 0xFE, 0x4A, 0xFE, 0x4A,
0xFE, 0x4A, 0xFE, 0x4A, 0xFE, 0x4A, 0xFE, 0x4A, 0xA0, 0x02, 0x62, 0xA1, 0x01, 0xE1, 0x6E, 0xFD,
0x21, 0x72, 0xF8, 0x21, 0x65, 0xFD, 0xA1, 0x01, 0xE1, 0x66, 0xFD, 0x41, 0x74, 0xFE, 0x07, 0x21,
0x69, 0xFC, 0x21, 0x65, 0xFD, 0xD3, 0x02, 0x01, 0x62, 0x63, 0x64, 0x66, 0x67, 0x6B, 0x6C, 0x6D,
0x6E, 0x70, 0x71, 0x72, 0x73, 0x74, 0x76, 0x7A, 0x68, 0x2E, 0x27, 0xFD, 0xFD, 0xFD, 0xFD, 0xFD,
0xFD, 0xFD, 0xFD, 0xFF, 0xE6, 0xFD, 0xFD, 0xFD, 0xFD, 0xFD, 0xFD, 0xFD, 0xFD, 0xFD, 0xFD, 0xFD,
0xFD, 0xFD, 0xFD, 0xFF, 0xF1, 0xFD, 0xFD, 0xFD, 0xFD, 0xFD, 0xFD, 0xFF, 0xFD, 0xFD, 0xFD, 0xFD,
0xFD, 0xA0, 0x02, 0x82, 0xA1, 0x01, 0xE1, 0x65, 0xFD, 0x21, 0x63, 0xF8, 0xA1, 0x01, 0xE1, 0x69,
0xFD, 0xCB, 0x02, 0x01, 0x64, 0x68, 0x6C, 0x6E, 0x70, 0x72, 0x73, 0x74, 0x7A, 0x2E, 0x27, 0xFD,
0xB1, 0xFD, 0xC3, 0xFD, 0xC3, 0xFF, 0xF3, 0xFD, 0xB1, 0xFD, 0xC3, 0xFF, 0xFB, 0xFD, 0xB1, 0xFD,
0xB1, 0xFD, 0xB1, 0xFD, 0xB1, 0xC3, 0x02, 0x01, 0x71, 0x2E, 0x27, 0xFD, 0x8D, 0xFD, 0x8D, 0xFD,
0x8D, 0xA0, 0x02, 0x53, 0xA1, 0x01, 0xE1, 0x73, 0xFD, 0xD5, 0x02, 0x01, 0x62, 0x63, 0x64, 0x66,
0x68, 0x67, 0x6B, 0x6C, 0x6D, 0x6E, 0x70, 0x71, 0x72, 0x73, 0x74, 0x76, 0x78, 0x77, 0x7A, 0x2E,
0x27, 0xFD, 0x79, 0xFD, 0x79, 0xFD, 0x79, 0xFD, 0x79, 0xFD, 0x8B, 0xFD, 0x79, 0xFD, 0x79, 0xFD,
0x79, 0xFD, 0x79, 0xFD, 0x79, 0xFD, 0x79, 0xFD, 0x79, 0xFD, 0x79, 0xFD, 0x79, 0xFF, 0xFB, 0xFD,
0x79, 0xFD, 0x79, 0xFD, 0x79, 0xFD, 0x79, 0xFD, 0x79, 0xFD, 0x79, 0x43, 0x6D, 0x2E, 0x27, 0xFD,
0x37, 0xFD, 0x37, 0xFD, 0x37, 0xA0, 0x02, 0xC2, 0xA1, 0x02, 0x32, 0x6D, 0xFD, 0x41, 0x6E, 0xFE,
0x8F, 0x4B, 0x62, 0x63, 0x64, 0x66, 0x67, 0x6D, 0x6E, 0x70, 0x73, 0x74, 0x76, 0xFD, 0x21, 0xFD,
0x21, 0xFD, 0x21, 0xFD, 0x21, 0xFD, 0x21, 0xFD, 0x21, 0xFD, 0x21, 0xFD, 0x21, 0xFD, 0x21, 0xFD,
0x21, 0xFD, 0x21, 0xA0, 0x02, 0xE1, 0x22, 0x2E, 0x27, 0xFD, 0xFD, 0xC7, 0x02, 0xA2, 0x68, 0x73,
0x70, 0x74, 0x7A, 0x2E, 0x27, 0xFF, 0xC0, 0xFF, 0xCD, 0xFF, 0xD2, 0xFF, 0xD6, 0xFC, 0xF7, 0xFF,
0xF8, 0xFF, 0xFB, 0xC1, 0x00, 0x51, 0x2E, 0xFC, 0xDF, 0x41, 0x68, 0xFF, 0x18, 0xA1, 0x00, 0x51,
0x63, 0xFC, 0xC1, 0x01, 0xE1, 0x73, 0xFE, 0xB6, 0xC2, 0x00, 0x51, 0x6B, 0x73, 0xFC, 0xCA, 0xFC,
0x06, 0xD2, 0x02, 0x01, 0x62, 0x63, 0x64, 0x66, 0x67, 0x68, 0x6C, 0x6D, 0x6E, 0x70, 0x72, 0x73,
0x74, 0x76, 0x77, 0x7A, 0x2E, 0x27, 0xFC, 0xC1, 0xFC, 0xC1, 0xFC, 0xC1, 0xFC, 0xC1, 0xFC, 0xC1,
0xFF, 0xE2, 0xFC, 0xD3, 0xFC, 0xC1, 0xFC, 0xC1, 0xFC, 0xC1, 0xFC, 0xD3, 0xFF, 0xEC, 0xFF, 0xF1,
0xFC, 0xC1, 0xFC, 0xC1, 0xFF, 0xF7, 0xFC, 0xC1, 0xFE, 0x2E, 0xC6, 0x02, 0x01, 0x63, 0x6C, 0x72,
0x76, 0x2E, 0x27, 0xFC, 0x88, 0xFC, 0x9A, 0xFC, 0x9A, 0xFC, 0x88, 0xFC, 0x88, 0xFD, 0xF5, 0x41,
0x72, 0xFB, 0xAF, 0xA0, 0x02, 0xF2, 0xC5, 0x02, 0x01, 0x68, 0x61, 0x79, 0x2E, 0x27, 0xFC, 0x7E,
0xFF, 0xF9, 0xFF, 0xFD, 0xFC, 0x6C, 0xFC, 0x6C, 0xCA, 0x02, 0x01, 0x62, 0x63, 0x66, 0x68, 0x6D,
0x70, 0x74, 0x77, 0x2E, 0x27, 0xFC, 0x5A, 0xFC, 0x5A, 0xFC, 0x5A, 0xFC, 0x5A, 0xFC, 0x5A, 0xFC,
0x5A, 0xFC, 0x5A, 0xFC, 0x5A, 0xFC, 0x5A, 0xFC, 0x5A, 0x42, 0x6F, 0x69, 0xFC, 0x48, 0xFC, 0x27,
0xCB, 0x02, 0x01, 0x62, 0x64, 0x6C, 0x6E, 0x70, 0x74, 0x73, 0x76, 0x7A, 0x2E, 0x27, 0xFC, 0x32,
0xFC, 0x32, 0xFC, 0x32, 0xFC, 0x32, 0xFC, 0x32, 0xFC, 0x32, 0xFC, 0x32, 0xFC, 0x32, 0xFC, 0x32,
0xFC, 0x32, 0xFD, 0x9F, 0x5A, 0x2E, 0x27, 0x61, 0x65, 0x6F, 0x62, 0x63, 0x64, 0x66, 0x67, 0x68,
0x6A, 0x6B, 0x6C, 0x6D, 0x6E, 0x70, 0x71, 0x72, 0x73, 0x74, 0x76, 0x77, 0x78, 0x79, 0x7A, 0xFB,
0xC2, 0xFB, 0xF9, 0xFC, 0x14, 0xFC, 0x23, 0xFC, 0x28, 0xFC, 0x2B, 0xFC, 0x64, 0xFC, 0x97, 0xFC,
0xC4, 0xFC, 0xED, 0xFD, 0x27, 0xFD, 0x4B, 0xFD, 0x54, 0xFD, 0x82, 0xFD, 0xC4, 0xFE, 0x11, 0xFE,
0x5D, 0xFE, 0x81, 0xFE, 0x95, 0xFF, 0x17, 0xFF, 0x4D, 0xFF, 0x86, 0xFF, 0xA2, 0xFF, 0xB4, 0xFF,
0xD5, 0xFF, 0xDC,
};
constexpr SerializedHyphenationPatterns it_patterns = {
it_trie_data,
sizeof(it_trie_data),
};

View File

@@ -1,8 +1,8 @@
#include "ChapterHtmlSlimParser.h" #include "ChapterHtmlSlimParser.h"
#include <GfxRenderer.h> #include <GfxRenderer.h>
#include <HalStorage.h>
#include <HardwareSerial.h> #include <HardwareSerial.h>
#include <SDCardManager.h>
#include <expat.h> #include <expat.h>
#include "../Page.h" #include "../Page.h"
@@ -11,7 +11,7 @@ const char* HEADER_TAGS[] = {"h1", "h2", "h3", "h4", "h5", "h6"};
constexpr int NUM_HEADER_TAGS = sizeof(HEADER_TAGS) / sizeof(HEADER_TAGS[0]); constexpr int NUM_HEADER_TAGS = sizeof(HEADER_TAGS) / sizeof(HEADER_TAGS[0]);
// Minimum file size (in bytes) to show indexing popup - smaller chapters don't benefit from it // Minimum file size (in bytes) to show indexing popup - smaller chapters don't benefit from it
constexpr size_t MIN_SIZE_FOR_POPUP = 50 * 1024; // 50KB constexpr size_t MIN_SIZE_FOR_POPUP = 10 * 1024; // 10KB
const char* BLOCK_TAGS[] = {"p", "li", "div", "br", "blockquote"}; const char* BLOCK_TAGS[] = {"p", "li", "div", "br", "blockquote"};
constexpr int NUM_BLOCK_TAGS = sizeof(BLOCK_TAGS) / sizeof(BLOCK_TAGS[0]); constexpr int NUM_BLOCK_TAGS = sizeof(BLOCK_TAGS) / sizeof(BLOCK_TAGS[0]);
@@ -482,7 +482,7 @@ bool ChapterHtmlSlimParser::parseAndBuildPages() {
} }
FsFile file; FsFile file;
if (!SdMan.openFileForRead("EHP", filepath, file)) { if (!Storage.openFileForRead("EHP", filepath, file)) {
XML_ParserFree(parser); XML_ParserFree(parser);
return false; return false;
} }

View File

@@ -36,8 +36,8 @@ ContentOpfParser::~ContentOpfParser() {
if (tempItemStore) { if (tempItemStore) {
tempItemStore.close(); tempItemStore.close();
} }
if (SdMan.exists((cachePath + itemCacheFile).c_str())) { if (Storage.exists((cachePath + itemCacheFile).c_str())) {
SdMan.remove((cachePath + itemCacheFile).c_str()); Storage.remove((cachePath + itemCacheFile).c_str());
} }
itemIndex.clear(); itemIndex.clear();
itemIndex.shrink_to_fit(); itemIndex.shrink_to_fit();
@@ -118,7 +118,7 @@ void XMLCALL ContentOpfParser::startElement(void* userData, const XML_Char* name
if (self->state == IN_PACKAGE && (strcmp(name, "manifest") == 0 || strcmp(name, "opf:manifest") == 0)) { if (self->state == IN_PACKAGE && (strcmp(name, "manifest") == 0 || strcmp(name, "opf:manifest") == 0)) {
self->state = IN_MANIFEST; self->state = IN_MANIFEST;
if (!SdMan.openFileForWrite("COF", self->cachePath + itemCacheFile, self->tempItemStore)) { if (!Storage.openFileForWrite("COF", self->cachePath + itemCacheFile, self->tempItemStore)) {
Serial.printf( Serial.printf(
"[%lu] [COF] Couldn't open temp items file for writing. This is probably going to be a fatal error.\n", "[%lu] [COF] Couldn't open temp items file for writing. This is probably going to be a fatal error.\n",
millis()); millis());
@@ -128,7 +128,7 @@ void XMLCALL ContentOpfParser::startElement(void* userData, const XML_Char* name
if (self->state == IN_PACKAGE && (strcmp(name, "spine") == 0 || strcmp(name, "opf:spine") == 0)) { if (self->state == IN_PACKAGE && (strcmp(name, "spine") == 0 || strcmp(name, "opf:spine") == 0)) {
self->state = IN_SPINE; self->state = IN_SPINE;
if (!SdMan.openFileForRead("COF", self->cachePath + itemCacheFile, self->tempItemStore)) { if (!Storage.openFileForRead("COF", self->cachePath + itemCacheFile, self->tempItemStore)) {
Serial.printf( Serial.printf(
"[%lu] [COF] Couldn't open temp items file for reading. This is probably going to be a fatal error.\n", "[%lu] [COF] Couldn't open temp items file for reading. This is probably going to be a fatal error.\n",
millis()); millis());
@@ -149,7 +149,7 @@ void XMLCALL ContentOpfParser::startElement(void* userData, const XML_Char* name
self->state = IN_GUIDE; self->state = IN_GUIDE;
// TODO Remove print // TODO Remove print
Serial.printf("[%lu] [COF] Entering guide state.\n", millis()); Serial.printf("[%lu] [COF] Entering guide state.\n", millis());
if (!SdMan.openFileForRead("COF", self->cachePath + itemCacheFile, self->tempItemStore)) { if (!Storage.openFileForRead("COF", self->cachePath + itemCacheFile, self->tempItemStore)) {
Serial.printf( Serial.printf(
"[%lu] [COF] Couldn't open temp items file for reading. This is probably going to be a fatal error.\n", "[%lu] [COF] Couldn't open temp items file for reading. This is probably going to be a fatal error.\n",
millis()); millis());
@@ -232,6 +232,14 @@ void XMLCALL ContentOpfParser::startElement(void* userData, const XML_Char* name
Serial.printf("[%lu] [COF] Found EPUB 3 nav document: %s\n", millis(), href.c_str()); Serial.printf("[%lu] [COF] Found EPUB 3 nav document: %s\n", millis(), href.c_str());
} }
} }
// EPUB 3: Check for cover image (properties contains "cover-image")
if (!properties.empty() && self->coverItemHref.empty()) {
if (properties == "cover-image" || properties.find("cover-image ") == 0 ||
properties.find(" cover-image") != std::string::npos) {
self->coverItemHref = href;
}
}
return; return;
} }

View File

@@ -1,6 +1,6 @@
#pragma once #pragma once
#include <SdFat.h> #include <HalStorage.h>
#include <cstdint> #include <cstdint>

View File

@@ -1,7 +1,7 @@
#include "JpegToBmpConverter.h" #include "JpegToBmpConverter.h"
#include <HalStorage.h>
#include <HardwareSerial.h> #include <HardwareSerial.h>
#include <SdFat.h>
#include <picojpeg.h> #include <picojpeg.h>
#include <cstdio> #include <cstdio>

View File

@@ -1,8 +1,8 @@
#include "KOReaderCredentialStore.h" #include "KOReaderCredentialStore.h"
#include <HalStorage.h>
#include <HardwareSerial.h> #include <HardwareSerial.h>
#include <MD5Builder.h> #include <MD5Builder.h>
#include <SDCardManager.h>
#include <Serialization.h> #include <Serialization.h>
// Initialize the static instance // Initialize the static instance
@@ -32,10 +32,10 @@ void KOReaderCredentialStore::obfuscate(std::string& data) const {
bool KOReaderCredentialStore::saveToFile() const { bool KOReaderCredentialStore::saveToFile() const {
// Make sure the directory exists // Make sure the directory exists
SdMan.mkdir("/.crosspoint"); Storage.mkdir("/.crosspoint");
FsFile file; FsFile file;
if (!SdMan.openFileForWrite("KRS", KOREADER_FILE, file)) { if (!Storage.openFileForWrite("KRS", KOREADER_FILE, file)) {
return false; return false;
} }
@@ -64,7 +64,7 @@ bool KOReaderCredentialStore::saveToFile() const {
bool KOReaderCredentialStore::loadFromFile() { bool KOReaderCredentialStore::loadFromFile() {
FsFile file; FsFile file;
if (!SdMan.openFileForRead("KRS", KOREADER_FILE, file)) { if (!Storage.openFileForRead("KRS", KOREADER_FILE, file)) {
Serial.printf("[%lu] [KRS] No credentials file found\n", millis()); Serial.printf("[%lu] [KRS] No credentials file found\n", millis());
return false; return false;
} }

View File

@@ -1,8 +1,8 @@
#include "KOReaderDocumentId.h" #include "KOReaderDocumentId.h"
#include <HalStorage.h>
#include <HardwareSerial.h> #include <HardwareSerial.h>
#include <MD5Builder.h> #include <MD5Builder.h>
#include <SDCardManager.h>
namespace { namespace {
// Extract filename from path (everything after last '/') // Extract filename from path (everything after last '/')
@@ -43,7 +43,7 @@ size_t KOReaderDocumentId::getOffset(int i) {
std::string KOReaderDocumentId::calculate(const std::string& filePath) { std::string KOReaderDocumentId::calculate(const std::string& filePath) {
FsFile file; FsFile file;
if (!SdMan.openFileForRead("KODoc", filePath, file)) { if (!Storage.openFileForRead("KODoc", filePath, file)) {
Serial.printf("[%lu] [KODoc] Failed to open file: %s\n", millis(), filePath.c_str()); Serial.printf("[%lu] [KODoc] Failed to open file: %s\n", millis(), filePath.c_str());
return ""; return "";
} }

View File

@@ -1,5 +1,5 @@
#pragma once #pragma once
#include <SdFat.h> #include <HalStorage.h>
#include <iostream> #include <iostream>

View File

@@ -15,13 +15,13 @@ bool Txt::load() {
return true; return true;
} }
if (!SdMan.exists(filepath.c_str())) { if (!Storage.exists(filepath.c_str())) {
Serial.printf("[%lu] [TXT] File does not exist: %s\n", millis(), filepath.c_str()); Serial.printf("[%lu] [TXT] File does not exist: %s\n", millis(), filepath.c_str());
return false; return false;
} }
FsFile file; FsFile file;
if (!SdMan.openFileForRead("TXT", filepath, file)) { if (!Storage.openFileForRead("TXT", filepath, file)) {
Serial.printf("[%lu] [TXT] Failed to open file: %s\n", millis(), filepath.c_str()); Serial.printf("[%lu] [TXT] Failed to open file: %s\n", millis(), filepath.c_str());
return false; return false;
} }
@@ -48,11 +48,11 @@ std::string Txt::getTitle() const {
} }
void Txt::setupCacheDir() const { void Txt::setupCacheDir() const {
if (!SdMan.exists(cacheBasePath.c_str())) { if (!Storage.exists(cacheBasePath.c_str())) {
SdMan.mkdir(cacheBasePath.c_str()); Storage.mkdir(cacheBasePath.c_str());
} }
if (!SdMan.exists(cachePath.c_str())) { if (!Storage.exists(cachePath.c_str())) {
SdMan.mkdir(cachePath.c_str()); Storage.mkdir(cachePath.c_str());
} }
} }
@@ -73,7 +73,7 @@ std::string Txt::findCoverImage() const {
// First priority: look for image with same name as txt file (e.g., mybook.jpg) // First priority: look for image with same name as txt file (e.g., mybook.jpg)
for (const auto& ext : extensions) { for (const auto& ext : extensions) {
std::string coverPath = folder + "/" + baseName + ext; std::string coverPath = folder + "/" + baseName + ext;
if (SdMan.exists(coverPath.c_str())) { if (Storage.exists(coverPath.c_str())) {
Serial.printf("[%lu] [TXT] Found matching cover image: %s\n", millis(), coverPath.c_str()); Serial.printf("[%lu] [TXT] Found matching cover image: %s\n", millis(), coverPath.c_str());
return coverPath; return coverPath;
} }
@@ -84,7 +84,7 @@ std::string Txt::findCoverImage() const {
for (const auto& name : coverNames) { for (const auto& name : coverNames) {
for (const auto& ext : extensions) { for (const auto& ext : extensions) {
std::string coverPath = folder + "/" + std::string(name) + ext; std::string coverPath = folder + "/" + std::string(name) + ext;
if (SdMan.exists(coverPath.c_str())) { if (Storage.exists(coverPath.c_str())) {
Serial.printf("[%lu] [TXT] Found fallback cover image: %s\n", millis(), coverPath.c_str()); Serial.printf("[%lu] [TXT] Found fallback cover image: %s\n", millis(), coverPath.c_str());
return coverPath; return coverPath;
} }
@@ -98,7 +98,7 @@ std::string Txt::getCoverBmpPath() const { return cachePath + "/cover.bmp"; }
bool Txt::generateCoverBmp() const { bool Txt::generateCoverBmp() const {
// Already generated, return true // Already generated, return true
if (SdMan.exists(getCoverBmpPath().c_str())) { if (Storage.exists(getCoverBmpPath().c_str())) {
return true; return true;
} }
@@ -122,10 +122,10 @@ bool Txt::generateCoverBmp() const {
// Copy BMP file to cache // Copy BMP file to cache
Serial.printf("[%lu] [TXT] Copying BMP cover image to cache\n", millis()); Serial.printf("[%lu] [TXT] Copying BMP cover image to cache\n", millis());
FsFile src, dst; FsFile src, dst;
if (!SdMan.openFileForRead("TXT", coverImagePath, src)) { if (!Storage.openFileForRead("TXT", coverImagePath, src)) {
return false; return false;
} }
if (!SdMan.openFileForWrite("TXT", getCoverBmpPath(), dst)) { if (!Storage.openFileForWrite("TXT", getCoverBmpPath(), dst)) {
src.close(); src.close();
return false; return false;
} }
@@ -144,10 +144,10 @@ bool Txt::generateCoverBmp() const {
// Convert JPG/JPEG to BMP (same approach as Epub) // Convert JPG/JPEG to BMP (same approach as Epub)
Serial.printf("[%lu] [TXT] Generating BMP from JPG cover image\n", millis()); Serial.printf("[%lu] [TXT] Generating BMP from JPG cover image\n", millis());
FsFile coverJpg, coverBmp; FsFile coverJpg, coverBmp;
if (!SdMan.openFileForRead("TXT", coverImagePath, coverJpg)) { if (!Storage.openFileForRead("TXT", coverImagePath, coverJpg)) {
return false; return false;
} }
if (!SdMan.openFileForWrite("TXT", getCoverBmpPath(), coverBmp)) { if (!Storage.openFileForWrite("TXT", getCoverBmpPath(), coverBmp)) {
coverJpg.close(); coverJpg.close();
return false; return false;
} }
@@ -157,7 +157,7 @@ bool Txt::generateCoverBmp() const {
if (!success) { if (!success) {
Serial.printf("[%lu] [TXT] Failed to generate BMP from JPG cover image\n", millis()); Serial.printf("[%lu] [TXT] Failed to generate BMP from JPG cover image\n", millis());
SdMan.remove(getCoverBmpPath().c_str()); Storage.remove(getCoverBmpPath().c_str());
} else { } else {
Serial.printf("[%lu] [TXT] Generated BMP from JPG cover image\n", millis()); Serial.printf("[%lu] [TXT] Generated BMP from JPG cover image\n", millis());
} }
@@ -175,7 +175,7 @@ bool Txt::readContent(uint8_t* buffer, size_t offset, size_t length) const {
} }
FsFile file; FsFile file;
if (!SdMan.openFileForRead("TXT", filepath, file)) { if (!Storage.openFileForRead("TXT", filepath, file)) {
return false; return false;
} }

View File

@@ -1,6 +1,6 @@
#pragma once #pragma once
#include <SDCardManager.h> #include <HalStorage.h>
#include <memory> #include <memory>
#include <string> #include <string>

View File

@@ -7,8 +7,8 @@
#include "Xtc.h" #include "Xtc.h"
#include <HalStorage.h>
#include <HardwareSerial.h> #include <HardwareSerial.h>
#include <SDCardManager.h>
bool Xtc::load() { bool Xtc::load() {
Serial.printf("[%lu] [XTC] Loading XTC: %s\n", millis(), filepath.c_str()); Serial.printf("[%lu] [XTC] Loading XTC: %s\n", millis(), filepath.c_str());
@@ -30,12 +30,12 @@ bool Xtc::load() {
} }
bool Xtc::clearCache() const { bool Xtc::clearCache() const {
if (!SdMan.exists(cachePath.c_str())) { if (!Storage.exists(cachePath.c_str())) {
Serial.printf("[%lu] [XTC] Cache does not exist, no action needed\n", millis()); Serial.printf("[%lu] [XTC] Cache does not exist, no action needed\n", millis());
return true; return true;
} }
if (!SdMan.removeDir(cachePath.c_str())) { if (!Storage.removeDir(cachePath.c_str())) {
Serial.printf("[%lu] [XTC] Failed to clear cache\n", millis()); Serial.printf("[%lu] [XTC] Failed to clear cache\n", millis());
return false; return false;
} }
@@ -45,17 +45,17 @@ bool Xtc::clearCache() const {
} }
void Xtc::setupCacheDir() const { void Xtc::setupCacheDir() const {
if (SdMan.exists(cachePath.c_str())) { if (Storage.exists(cachePath.c_str())) {
return; return;
} }
// Create directories recursively // Create directories recursively
for (size_t i = 1; i < cachePath.length(); i++) { for (size_t i = 1; i < cachePath.length(); i++) {
if (cachePath[i] == '/') { if (cachePath[i] == '/') {
SdMan.mkdir(cachePath.substr(0, i).c_str()); Storage.mkdir(cachePath.substr(0, i).c_str());
} }
} }
SdMan.mkdir(cachePath.c_str()); Storage.mkdir(cachePath.c_str());
} }
std::string Xtc::getTitle() const { std::string Xtc::getTitle() const {
@@ -114,7 +114,7 @@ std::string Xtc::getCoverBmpPath() const { return cachePath + "/cover.bmp"; }
bool Xtc::generateCoverBmp() const { bool Xtc::generateCoverBmp() const {
// Already generated // Already generated
if (SdMan.exists(getCoverBmpPath().c_str())) { if (Storage.exists(getCoverBmpPath().c_str())) {
return true; return true;
} }
@@ -166,7 +166,7 @@ bool Xtc::generateCoverBmp() const {
// Create BMP file // Create BMP file
FsFile coverBmp; FsFile coverBmp;
if (!SdMan.openFileForWrite("XTC", getCoverBmpPath(), coverBmp)) { if (!Storage.openFileForWrite("XTC", getCoverBmpPath(), coverBmp)) {
Serial.printf("[%lu] [XTC] Failed to create cover BMP file\n", millis()); Serial.printf("[%lu] [XTC] Failed to create cover BMP file\n", millis());
free(pageBuffer); free(pageBuffer);
return false; return false;
@@ -306,7 +306,7 @@ std::string Xtc::getThumbBmpPath(int height) const { return cachePath + "/thumb_
bool Xtc::generateThumbBmp(int height) const { bool Xtc::generateThumbBmp(int height) const {
// Already generated // Already generated
if (SdMan.exists(getThumbBmpPath(height).c_str())) { if (Storage.exists(getThumbBmpPath(height).c_str())) {
return true; return true;
} }
@@ -348,8 +348,8 @@ bool Xtc::generateThumbBmp(int height) const {
// Copy cover.bmp to thumb.bmp // Copy cover.bmp to thumb.bmp
if (generateCoverBmp()) { if (generateCoverBmp()) {
FsFile src, dst; FsFile src, dst;
if (SdMan.openFileForRead("XTC", getCoverBmpPath(), src)) { if (Storage.openFileForRead("XTC", getCoverBmpPath(), src)) {
if (SdMan.openFileForWrite("XTC", getThumbBmpPath(height), dst)) { if (Storage.openFileForWrite("XTC", getThumbBmpPath(height), dst)) {
uint8_t buffer[512]; uint8_t buffer[512];
while (src.available()) { while (src.available()) {
size_t bytesRead = src.read(buffer, sizeof(buffer)); size_t bytesRead = src.read(buffer, sizeof(buffer));
@@ -360,7 +360,7 @@ bool Xtc::generateThumbBmp(int height) const {
src.close(); src.close();
} }
Serial.printf("[%lu] [XTC] Copied cover to thumb (no scaling needed)\n", millis()); Serial.printf("[%lu] [XTC] Copied cover to thumb (no scaling needed)\n", millis());
return SdMan.exists(getThumbBmpPath(height).c_str()); return Storage.exists(getThumbBmpPath(height).c_str());
} }
return false; return false;
} }
@@ -394,7 +394,7 @@ bool Xtc::generateThumbBmp(int height) const {
// Create thumbnail BMP file - use 1-bit format for fast home screen rendering (no gray passes) // Create thumbnail BMP file - use 1-bit format for fast home screen rendering (no gray passes)
FsFile thumbBmp; FsFile thumbBmp;
if (!SdMan.openFileForWrite("XTC", getThumbBmpPath(height), thumbBmp)) { if (!Storage.openFileForWrite("XTC", getThumbBmpPath(height), thumbBmp)) {
Serial.printf("[%lu] [XTC] Failed to create thumb BMP file\n", millis()); Serial.printf("[%lu] [XTC] Failed to create thumb BMP file\n", millis());
free(pageBuffer); free(pageBuffer);
return false; return false;

View File

@@ -8,8 +8,8 @@
#include "XtcParser.h" #include "XtcParser.h"
#include <FsHelpers.h> #include <FsHelpers.h>
#include <HalStorage.h>
#include <HardwareSerial.h> #include <HardwareSerial.h>
#include <SDCardManager.h>
#include <cstring> #include <cstring>
@@ -34,7 +34,7 @@ XtcError XtcParser::open(const char* filepath) {
} }
// Open file // Open file
if (!SdMan.openFileForRead("XTC", filepath, m_file)) { if (!Storage.openFileForRead("XTC", filepath, m_file)) {
m_lastError = XtcError::FILE_NOT_FOUND; m_lastError = XtcError::FILE_NOT_FOUND;
return m_lastError; return m_lastError;
} }
@@ -444,7 +444,7 @@ XtcError XtcParser::loadPageStreaming(uint32_t pageIndex,
bool XtcParser::isValidXtcFile(const char* filepath) { bool XtcParser::isValidXtcFile(const char* filepath) {
FsFile file; FsFile file;
if (!SdMan.openFileForRead("XTC", filepath, file)) { if (!Storage.openFileForRead("XTC", filepath, file)) {
return false; return false;
} }

View File

@@ -7,7 +7,7 @@
#pragma once #pragma once
#include <SdFat.h> #include <HalStorage.h>
#include <functional> #include <functional>
#include <memory> #include <memory>

View File

@@ -1,7 +1,7 @@
#include "ZipFile.h" #include "ZipFile.h"
#include <HalStorage.h>
#include <HardwareSerial.h> #include <HardwareSerial.h>
#include <SDCardManager.h>
#include <miniz.h> #include <miniz.h>
#include <algorithm> #include <algorithm>
@@ -279,7 +279,7 @@ bool ZipFile::loadZipDetails() {
} }
bool ZipFile::open() { bool ZipFile::open() {
if (!SdMan.openFileForRead("ZIP", filePath, file)) { if (!Storage.openFileForRead("ZIP", filePath, file)) {
return false; return false;
} }
return true; return true;

View File

@@ -1,5 +1,5 @@
#pragma once #pragma once
#include <SdFat.h> #include <HalStorage.h>
#include <string> #include <string>
#include <unordered_map> #include <unordered_map>

65
lib/hal/HalStorage.cpp Normal file
View File

@@ -0,0 +1,65 @@
#include "HalStorage.h"
#include <SDCardManager.h>
#define SDCard SDCardManager::getInstance()
HalStorage HalStorage::instance;
HalStorage::HalStorage() {}
bool HalStorage::begin() { return SDCard.begin(); }
bool HalStorage::ready() const { return SDCard.ready(); }
std::vector<String> HalStorage::listFiles(const char* path, int maxFiles) { return SDCard.listFiles(path, maxFiles); }
String HalStorage::readFile(const char* path) { return SDCard.readFile(path); }
bool HalStorage::readFileToStream(const char* path, Print& out, size_t chunkSize) {
return SDCard.readFileToStream(path, out, chunkSize);
}
size_t HalStorage::readFileToBuffer(const char* path, char* buffer, size_t bufferSize, size_t maxBytes) {
return SDCard.readFileToBuffer(path, buffer, bufferSize, maxBytes);
}
bool HalStorage::writeFile(const char* path, const String& content) { return SDCard.writeFile(path, content); }
bool HalStorage::ensureDirectoryExists(const char* path) { return SDCard.ensureDirectoryExists(path); }
FsFile HalStorage::open(const char* path, const oflag_t oflag) { return SDCard.open(path, oflag); }
bool HalStorage::mkdir(const char* path, const bool pFlag) { return SDCard.mkdir(path, pFlag); }
bool HalStorage::exists(const char* path) { return SDCard.exists(path); }
bool HalStorage::remove(const char* path) { return SDCard.remove(path); }
bool HalStorage::rmdir(const char* path) { return SDCard.rmdir(path); }
bool HalStorage::openFileForRead(const char* moduleName, const char* path, FsFile& file) {
return SDCard.openFileForRead(moduleName, path, file);
}
bool HalStorage::openFileForRead(const char* moduleName, const std::string& path, FsFile& file) {
return openFileForRead(moduleName, path.c_str(), file);
}
bool HalStorage::openFileForRead(const char* moduleName, const String& path, FsFile& file) {
return openFileForRead(moduleName, path.c_str(), file);
}
bool HalStorage::openFileForWrite(const char* moduleName, const char* path, FsFile& file) {
return SDCard.openFileForWrite(moduleName, path, file);
}
bool HalStorage::openFileForWrite(const char* moduleName, const std::string& path, FsFile& file) {
return openFileForWrite(moduleName, path.c_str(), file);
}
bool HalStorage::openFileForWrite(const char* moduleName, const String& path, FsFile& file) {
return openFileForWrite(moduleName, path.c_str(), file);
}
bool HalStorage::removeDir(const char* path) { return SDCard.removeDir(path); }

54
lib/hal/HalStorage.h Normal file
View File

@@ -0,0 +1,54 @@
#pragma once
#include <SDCardManager.h>
#include <vector>
class HalStorage {
public:
HalStorage();
bool begin();
bool ready() const;
std::vector<String> listFiles(const char* path = "/", int maxFiles = 200);
// Read the entire file at `path` into a String. Returns empty string on failure.
String readFile(const char* path);
// Low-memory helpers:
// Stream the file contents to a `Print` (e.g. `Serial`, or any `Print`-derived object).
// Returns true on success, false on failure.
bool readFileToStream(const char* path, Print& out, size_t chunkSize = 256);
// Read up to `bufferSize-1` bytes into `buffer`, null-terminating it. Returns bytes read.
size_t readFileToBuffer(const char* path, char* buffer, size_t bufferSize, size_t maxBytes = 0);
// Write a string to `path` on the SD card. Overwrites existing file.
// Returns true on success.
bool writeFile(const char* path, const String& content);
// Ensure a directory exists, creating it if necessary. Returns true on success.
bool ensureDirectoryExists(const char* path);
FsFile open(const char* path, const oflag_t oflag = O_RDONLY);
bool mkdir(const char* path, const bool pFlag = true);
bool exists(const char* path);
bool remove(const char* path);
bool rmdir(const char* path);
bool openFileForRead(const char* moduleName, const char* path, FsFile& file);
bool openFileForRead(const char* moduleName, const std::string& path, FsFile& file);
bool openFileForRead(const char* moduleName, const String& path, FsFile& file);
bool openFileForWrite(const char* moduleName, const char* path, FsFile& file);
bool openFileForWrite(const char* moduleName, const std::string& path, FsFile& file);
bool openFileForWrite(const char* moduleName, const String& path, FsFile& file);
bool removeDir(const char* path);
static HalStorage& getInstance() { return instance; }
private:
static HalStorage instance;
bool initialized = false;
};
#define Storage HalStorage::getInstance()
// Downstream code must use Storage instead of SdMan
#ifdef SdMan
#undef SdMan
#endif

View File

@@ -1,32 +1,46 @@
#!/usr/bin/env python3
"""
ESP32 Serial Monitor with Memory Graph
This script provides a real-time serial monitor for ESP32 devices with
integrated memory usage graphing capabilities. It reads serial output,
parses memory information, and displays it in both console and graphical form.
"""
import sys import sys
import argparse import argparse
import re import re
import threading import threading
from datetime import datetime from datetime import datetime
from collections import deque from collections import deque
import time
# Try to import potentially missing packages # Try to import potentially missing packages
PACKAGE_MAPPING: dict[str, str] = {
"serial": "pyserial",
"colorama": "colorama",
"matplotlib": "matplotlib",
}
try: try:
import serial import serial
from colorama import init, Fore, Style from colorama import init, Fore, Style
import matplotlib.pyplot as plt import matplotlib.pyplot as plt
import matplotlib.animation as animation from matplotlib import animation
except ImportError as e: except ImportError as e:
missing_package = e.name ERROR_MSG = str(e).lower()
missing_packages = [pkg for mod, pkg in PACKAGE_MAPPING.items() if mod in ERROR_MSG]
if not missing_packages:
# Fallback if mapping doesn't cover
missing_packages = ["pyserial", "colorama", "matplotlib"]
print("\n" + "!" * 50) print("\n" + "!" * 50)
print(f" Error: The required package '{missing_package}' is not installed.") print(f" Error: Required package(s) not installed: {', '.join(missing_packages)}")
print("!" * 50) print("!" * 50)
print(f"\nTo fix this, please run the following command in your terminal:\n") print("\nTo fix this, please run the following command in your terminal:\n")
INSTALL_CMD = "pip install " if sys.platform.startswith("win") else "pip3 install "
install_cmd = "pip install " print(f" {INSTALL_CMD}{' '.join(missing_packages)}")
packages = []
if 'serial' in str(e): packages.append("pyserial")
if 'colorama' in str(e): packages.append("colorama")
if 'matplotlib' in str(e): packages.append("matplotlib")
print(f" {install_cmd}{' '.join(packages)}")
print("\nExiting...") print("\nExiting...")
sys.exit(1) sys.exit(1)
@@ -34,50 +48,92 @@ except ImportError as e:
# --- Global Variables for Data Sharing --- # --- Global Variables for Data Sharing ---
# Store last 50 data points # Store last 50 data points
MAX_POINTS = 50 MAX_POINTS = 50
time_data = deque(maxlen=MAX_POINTS) time_data: deque[str] = deque(maxlen=MAX_POINTS)
free_mem_data = deque(maxlen=MAX_POINTS) free_mem_data: deque[float] = deque(maxlen=MAX_POINTS)
total_mem_data = deque(maxlen=MAX_POINTS) total_mem_data: deque[float] = deque(maxlen=MAX_POINTS)
data_lock = threading.Lock() # Prevent reading while writing data_lock: threading.Lock = threading.Lock() # Prevent reading while writing
# Initialize colors # Initialize colors
init(autoreset=True) init(autoreset=True)
def get_color_for_line(line): # Color mapping for log lines
COLOR_KEYWORDS: dict[str, list[str]] = {
Fore.RED: ["ERROR", "[ERR]", "[SCT]", "FAILED", "WARNING"],
Fore.CYAN: ["[MEM]", "FREE:"],
Fore.MAGENTA: [
"[GFX]",
"[ERS]",
"DISPLAY",
"RAM WRITE",
"RAM COMPLETE",
"REFRESH",
"POWERING ON",
"FRAME BUFFER",
"LUT",
],
Fore.GREEN: [
"[EBP]",
"[BMC]",
"[ZIP]",
"[PARSER]",
"[EHP]",
"LOADING EPUB",
"CACHE",
"DECOMPRESSED",
"PARSING",
],
Fore.YELLOW: ["[ACT]", "ENTERING ACTIVITY", "EXITING ACTIVITY"],
Fore.BLUE: ["RENDERED PAGE", "[LOOP]", "DURATION", "WAIT COMPLETE"],
Fore.LIGHTYELLOW_EX: [
"[CPS]",
"SETTINGS",
"[CLEAR_CACHE]",
"[CHAP]",
"[OPDS]",
"[COF]",
],
Fore.LIGHTBLACK_EX: [
"ESP-ROM",
"BUILD:",
"RST:",
"BOOT:",
"SPIWP:",
"MODE:",
"LOAD:",
"ENTRY",
"[SD]",
"STARTING CROSSPOINT",
"VERSION",
],
Fore.LIGHTCYAN_EX: ["[RBS]"],
Fore.LIGHTMAGENTA_EX: [
"[KRS]",
"EINKDISPLAY:",
"STATIC FRAME",
"INITIALIZING",
"SPI INITIALIZED",
"GPIO PINS",
"RESETTING",
"SSD1677",
"E-INK",
],
Fore.LIGHTGREEN_EX: ["[FNS]", "FOOTNOTE"],
}
# pylint: disable=R0912
def get_color_for_line(line: str) -> str:
""" """
Classify log lines by type and assign appropriate colors. Classify log lines by type and assign appropriate colors.
""" """
line_upper = line.upper() line_upper = line.upper()
for color, keywords in COLOR_KEYWORDS.items():
if any(keyword in line_upper for keyword in ["ERROR", "[ERR]", "[SCT]", "FAILED", "WARNING"]): if any(keyword in line_upper for keyword in keywords):
return Fore.RED return color
if "[MEM]" in line_upper or "FREE:" in line_upper:
return Fore.CYAN
if any(keyword in line_upper for keyword in ["[GFX]", "[ERS]", "DISPLAY", "RAM WRITE", "RAM COMPLETE", "REFRESH", "POWERING ON", "FRAME BUFFER", "LUT"]):
return Fore.MAGENTA
if any(keyword in line_upper for keyword in ["[EBP]", "[BMC]", "[ZIP]", "[PARSER]", "[EHP]", "LOADING EPUB", "CACHE", "DECOMPRESSED", "PARSING"]):
return Fore.GREEN
if "[ACT]" in line_upper or "ENTERING ACTIVITY" in line_upper or "EXITING ACTIVITY" in line_upper:
return Fore.YELLOW
if any(keyword in line_upper for keyword in ["RENDERED PAGE", "[LOOP]", "DURATION", "WAIT COMPLETE"]):
return Fore.BLUE
if any(keyword in line_upper for keyword in ["[CPS]", "SETTINGS", "[CLEAR_CACHE]"]):
return Fore.LIGHTYELLOW_EX
if any(keyword in line_upper for keyword in ["ESP-ROM", "BUILD:", "RST:", "BOOT:", "SPIWP:", "MODE:", "LOAD:", "ENTRY", "[SD]", "STARTING CROSSPOINT", "VERSION"]):
return Fore.LIGHTBLACK_EX
if "[RBS]" in line_upper:
return Fore.LIGHTCYAN_EX
if "[KRS]" in line_upper:
return Fore.LIGHTMAGENTA_EX
if any(keyword in line_upper for keyword in ["EINKDISPLAY:", "STATIC FRAME", "INITIALIZING", "SPI INITIALIZED", "GPIO PINS", "RESETTING", "SSD1677", "E-INK"]):
return Fore.LIGHTMAGENTA_EX
if any(keyword in line_upper for keyword in ["[FNS]", "FOOTNOTE"]):
return Fore.LIGHTGREEN_EX
if any(keyword in line_upper for keyword in ["[CHAP]", "[OPDS]", "[COF]"]):
return Fore.LIGHTYELLOW_EX
return Fore.WHITE return Fore.WHITE
def parse_memory_line(line):
def parse_memory_line(line: str) -> tuple[int | None, int | None]:
""" """
Extracts Free and Total bytes from the specific log line. Extracts Free and Total bytes from the specific log line.
Format: [MEM] Free: 196344 bytes, Total: 226412 bytes, Min Free: 112620 bytes Format: [MEM] Free: 196344 bytes, Total: 226412 bytes, Min Free: 112620 bytes
@@ -93,12 +149,29 @@ def parse_memory_line(line):
return None, None return None, None
return None, None return None, None
def serial_worker(port, baud):
def serial_worker(port: str, baud: int, kwargs: dict[str, str]) -> None:
""" """
Runs in a background thread. Handles reading serial, printing to console, Runs in a background thread. Handles reading serial, printing to console,
and updating the data lists. and updating the data lists.
""" """
print(f"{Fore.CYAN}--- Opening {port} at {baud} baud ---{Style.RESET_ALL}") print(f"{Fore.CYAN}--- Opening {port} at {baud} baud ---{Style.RESET_ALL}")
filter_keyword = kwargs.get("filter", "").lower()
suppress = kwargs.get("suppress", "").lower()
if filter_keyword and suppress and filter_keyword == suppress:
print(
f"{Fore.YELLOW}Warning: Filter and Suppress keywords are the same. "
f"This may result in no output.{Style.RESET_ALL}"
)
if filter_keyword:
print(
f"{Fore.YELLOW}Filtering lines to only show those containing: "
f"'{filter_keyword}'{Style.RESET_ALL}"
)
if suppress:
print(
f"{Fore.YELLOW}Suppressing lines containing: '{suppress}'{Style.RESET_ALL}"
)
try: try:
ser = serial.Serial(port, baud, timeout=0.1) ser = serial.Serial(port, baud, timeout=0.1)
@@ -111,7 +184,7 @@ def serial_worker(port, baud):
try: try:
while True: while True:
try: try:
raw_data = ser.readline().decode('utf-8', errors='replace') raw_data = ser.readline().decode("utf-8", errors="replace")
if not raw_data: if not raw_data:
continue continue
@@ -127,88 +200,146 @@ def serial_worker(port, baud):
# Check for Memory Line # Check for Memory Line
if "[MEM]" in formatted_line: if "[MEM]" in formatted_line:
free_val, total_val = parse_memory_line(formatted_line) free_val, total_val = parse_memory_line(formatted_line)
if free_val is not None: if free_val is not None and total_val is not None:
with data_lock: with data_lock:
time_data.append(pc_time) time_data.append(pc_time)
free_mem_data.append(free_val / 1024) # Convert to KB free_mem_data.append(free_val / 1024) # Convert to KB
total_mem_data.append(total_val / 1024) # Convert to KB total_mem_data.append(total_val / 1024) # Convert to KB
# Apply filters
if filter_keyword and filter_keyword not in formatted_line.lower():
continue
if suppress and suppress in formatted_line.lower():
continue
# Print to console # Print to console
line_color = get_color_for_line(formatted_line) line_color = get_color_for_line(formatted_line)
print(f"{line_color}{formatted_line}") print(f"{line_color}{formatted_line}")
except OSError: except (OSError, UnicodeDecodeError):
print(f"{Fore.RED}Device disconnected.{Style.RESET_ALL}") print(f"{Fore.RED}Device disconnected or data error.{Style.RESET_ALL}")
break break
except Exception as e: except KeyboardInterrupt:
# If thread is killed violently (e.g. main exit), silence errors # If thread is killed violently (e.g. main exit), silence errors
pass pass
finally: finally:
if 'ser' in locals() and ser.is_open: if "ser" in locals() and ser.is_open:
ser.close() ser.close()
def update_graph(frame):
def update_graph(frame) -> list: # pylint: disable=unused-argument
""" """
Called by Matplotlib animation to redraw the chart. Called by Matplotlib animation to redraw the chart.
""" """
with data_lock: with data_lock:
if not time_data: if not time_data:
return return []
# Convert deques to lists for plotting # Convert deques to lists for plotting
x = list(time_data) x = list(time_data)
y_free = list(free_mem_data) y_free = list(free_mem_data)
y_total = list(total_mem_data) y_total = list(total_mem_data)
plt.cla() # Clear axis plt.cla() # Clear axis
# Plot Total RAM # Plot Total RAM
plt.plot(x, y_total, label='Total RAM (KB)', color='red', linestyle='--') plt.plot(x, y_total, label="Total RAM (KB)", color="red", linestyle="--")
# Plot Free RAM # Plot Free RAM
plt.plot(x, y_free, label='Free RAM (KB)', color='green', marker='o') plt.plot(x, y_free, label="Free RAM (KB)", color="green", marker="o")
# Fill area under Free RAM # Fill area under Free RAM
plt.fill_between(x, y_free, color='green', alpha=0.1) plt.fill_between(x, y_free, color="green", alpha=0.1)
plt.title("ESP32 Memory Monitor") plt.title("ESP32 Memory Monitor")
plt.ylabel("Memory (KB)") plt.ylabel("Memory (KB)")
plt.xlabel("Time") plt.xlabel("Time")
plt.legend(loc='upper left') plt.legend(loc="upper left")
plt.grid(True, linestyle=':', alpha=0.6) plt.grid(True, linestyle=":", alpha=0.6)
# Rotate date labels # Rotate date labels
plt.xticks(rotation=45, ha='right') plt.xticks(rotation=45, ha="right")
plt.tight_layout() plt.tight_layout()
def main(): return []
def main() -> None:
"""
Main entry point for the ESP32 monitor application.
Sets up argument parsing, starts serial monitoring thread, and initializes the memory graph.
"""
parser = argparse.ArgumentParser(description="ESP32 Monitor with Graph") parser = argparse.ArgumentParser(description="ESP32 Monitor with Graph")
parser.add_argument("port", nargs="?", default="/dev/ttyACM0", help="Serial port") if sys.platform.startswith("win"):
parser.add_argument("--baud", type=int, default=115200, help="Baud rate") default_port = "COM8"
elif sys.platform.startswith("darwin"):
default_port = "/dev/cu.usbmodem101"
else:
default_port = "/dev/ttyACM0"
default_baudrate = 115200
parser.add_argument(
"port",
nargs="?",
default=default_port,
help=f"Serial port (default: {default_port})",
)
parser.add_argument(
"--baud",
type=int,
default=default_baudrate,
help=f"Baud rate (default: {default_baudrate})",
)
parser.add_argument(
"--filter",
type=str,
default="",
help="Only display lines containing this keyword (case-insensitive)",
)
parser.add_argument(
"--suppress",
type=str,
default="",
help="Suppress lines containing this keyword (case-insensitive)",
)
args = parser.parse_args() args = parser.parse_args()
# 1. Start the Serial Reader in a separate thread # 1. Start the Serial Reader in a separate thread
# Daemon=True means this thread dies when the main program closes # Daemon=True means this thread dies when the main program closes
t = threading.Thread(target=serial_worker, args=(args.port, args.baud), daemon=True) myargs = vars(args) # Convert Namespace to dict for easier passing
t = threading.Thread(
target=serial_worker, args=(args.port, args.baud, myargs), daemon=True
)
t.start() t.start()
# 2. Set up the Graph (Main Thread) # 2. Set up the Graph (Main Thread)
try: try:
plt.style.use('light_background') import matplotlib.style as mplstyle # pylint: disable=import-outside-toplevel
except: default_styles = ("light_background", "ggplot", "seaborn", "dark_background", )
styles = list(mplstyle.available)
for default_style in default_styles:
if default_style in styles:
print(
f"\n{Fore.CYAN}--- Using Matplotlib style: {default_style} ---{Style.RESET_ALL}"
)
mplstyle.use(default_style)
break
except (AttributeError, ValueError):
pass pass
fig = plt.figure(figsize=(10, 6)) fig = plt.figure(figsize=(10, 6))
# Update graph every 1000ms # Update graph every 1000ms
ani = animation.FuncAnimation(fig, update_graph, interval=1000) _ = animation.FuncAnimation(
fig, update_graph, interval=1000, cache_frame_data=False
)
try: try:
print(f"{Fore.YELLOW}Starting Graph Window... (Close window to exit){Style.RESET_ALL}") print(
f"{Fore.YELLOW}Starting Graph Window... (Close window to exit){Style.RESET_ALL}"
)
plt.show() plt.show()
except KeyboardInterrupt: except KeyboardInterrupt:
print(f"\n{Fore.YELLOW}Exiting...{Style.RESET_ALL}") print(f"\n{Fore.YELLOW}Exiting...{Style.RESET_ALL}")
plt.close('all') # Force close any lingering plot windows plt.close("all") # Force close any lingering plot windows
if __name__ == "__main__": if __name__ == "__main__":
main() main()

View File

@@ -1,7 +1,7 @@
#include "CrossPointSettings.h" #include "CrossPointSettings.h"
#include <HalStorage.h>
#include <HardwareSerial.h> #include <HardwareSerial.h>
#include <SDCardManager.h>
#include <Serialization.h> #include <Serialization.h>
#include <cstring> #include <cstring>
@@ -79,10 +79,10 @@ void applyLegacyFrontButtonLayout(CrossPointSettings& settings) {
bool CrossPointSettings::saveToFile() const { bool CrossPointSettings::saveToFile() const {
// Make sure the directory exists // Make sure the directory exists
SdMan.mkdir("/.crosspoint"); Storage.mkdir("/.crosspoint");
FsFile outputFile; FsFile outputFile;
if (!SdMan.openFileForWrite("CPS", SETTINGS_FILE, outputFile)) { if (!Storage.openFileForWrite("CPS", SETTINGS_FILE, outputFile)) {
return false; return false;
} }
@@ -127,7 +127,7 @@ bool CrossPointSettings::saveToFile() const {
bool CrossPointSettings::loadFromFile() { bool CrossPointSettings::loadFromFile() {
FsFile inputFile; FsFile inputFile;
if (!SdMan.openFileForRead("CPS", SETTINGS_FILE, inputFile)) { if (!Storage.openFileForRead("CPS", SETTINGS_FILE, inputFile)) {
return false; return false;
} }

View File

@@ -1,7 +1,7 @@
#include "CrossPointState.h" #include "CrossPointState.h"
#include <HalStorage.h>
#include <HardwareSerial.h> #include <HardwareSerial.h>
#include <SDCardManager.h>
#include <Serialization.h> #include <Serialization.h>
namespace { namespace {
@@ -13,7 +13,7 @@ CrossPointState CrossPointState::instance;
bool CrossPointState::saveToFile() const { bool CrossPointState::saveToFile() const {
FsFile outputFile; FsFile outputFile;
if (!SdMan.openFileForWrite("CPS", STATE_FILE, outputFile)) { if (!Storage.openFileForWrite("CPS", STATE_FILE, outputFile)) {
return false; return false;
} }
@@ -28,7 +28,7 @@ bool CrossPointState::saveToFile() const {
bool CrossPointState::loadFromFile() { bool CrossPointState::loadFromFile() {
FsFile inputFile; FsFile inputFile;
if (!SdMan.openFileForRead("CPS", STATE_FILE, inputFile)) { if (!Storage.openFileForRead("CPS", STATE_FILE, inputFile)) {
return false; return false;
} }

View File

@@ -15,6 +15,7 @@ class MappedInputManager {
explicit MappedInputManager(HalGPIO& gpio) : gpio(gpio) {} explicit MappedInputManager(HalGPIO& gpio) : gpio(gpio) {}
void update() const { gpio.update(); }
bool wasPressed(Button button) const; bool wasPressed(Button button) const;
bool wasReleased(Button button) const; bool wasReleased(Button button) const;
bool isPressed(Button button) const; bool isPressed(Button button) const;

View File

@@ -1,8 +1,8 @@
#include "RecentBooksStore.h" #include "RecentBooksStore.h"
#include <Epub.h> #include <Epub.h>
#include <HalStorage.h>
#include <HardwareSerial.h> #include <HardwareSerial.h>
#include <SDCardManager.h>
#include <Serialization.h> #include <Serialization.h>
#include <Xtc.h> #include <Xtc.h>
@@ -53,10 +53,10 @@ void RecentBooksStore::updateBook(const std::string& path, const std::string& ti
bool RecentBooksStore::saveToFile() const { bool RecentBooksStore::saveToFile() const {
// Make sure the directory exists // Make sure the directory exists
SdMan.mkdir("/.crosspoint"); Storage.mkdir("/.crosspoint");
FsFile outputFile; FsFile outputFile;
if (!SdMan.openFileForWrite("RBS", RECENT_BOOKS_FILE, outputFile)) { if (!Storage.openFileForWrite("RBS", RECENT_BOOKS_FILE, outputFile)) {
return false; return false;
} }
@@ -83,7 +83,7 @@ RecentBook RecentBooksStore::getDataFromBook(std::string path) const {
lastBookFileName = path.substr(lastSlash + 1); lastBookFileName = path.substr(lastSlash + 1);
} }
Serial.printf("Loading recent book: %s\n", path.c_str()); Serial.printf("[%lu] [RBS] Loading recent book: %s\n", millis(), path.c_str());
// If epub, try to load the metadata for title/author and cover // If epub, try to load the metadata for title/author and cover
if (StringUtils::checkFileExtension(lastBookFileName, ".epub")) { if (StringUtils::checkFileExtension(lastBookFileName, ".epub")) {
@@ -106,7 +106,7 @@ RecentBook RecentBooksStore::getDataFromBook(std::string path) const {
bool RecentBooksStore::loadFromFile() { bool RecentBooksStore::loadFromFile() {
FsFile inputFile; FsFile inputFile;
if (!SdMan.openFileForRead("RBS", RECENT_BOOKS_FILE, inputFile)) { if (!Storage.openFileForRead("RBS", RECENT_BOOKS_FILE, inputFile)) {
return false; return false;
} }

101
src/SettingsList.h Normal file
View File

@@ -0,0 +1,101 @@
#pragma once
#include <vector>
#include "CrossPointSettings.h"
#include "KOReaderCredentialStore.h"
#include "activities/settings/SettingsActivity.h"
// Shared settings list used by both the device settings UI and the web settings API.
// Each entry has a key (for JSON API) and category (for grouping).
// ACTION-type entries and entries without a key are device-only.
inline std::vector<SettingInfo> getSettingsList() {
return {
// --- Display ---
SettingInfo::Enum("Sleep Screen", &CrossPointSettings::sleepScreen,
{"Dark", "Light", "Custom", "Cover", "None", "Cover + Custom"}, "sleepScreen", "Display"),
SettingInfo::Enum("Sleep Screen Cover Mode", &CrossPointSettings::sleepScreenCoverMode, {"Fit", "Crop"},
"sleepScreenCoverMode", "Display"),
SettingInfo::Enum("Sleep Screen Cover Filter", &CrossPointSettings::sleepScreenCoverFilter,
{"None", "Contrast", "Inverted"}, "sleepScreenCoverFilter", "Display"),
SettingInfo::Enum(
"Status Bar", &CrossPointSettings::statusBar,
{"None", "No Progress", "Full w/ Percentage", "Full w/ Book Bar", "Book Bar Only", "Full w/ Chapter Bar"},
"statusBar", "Display"),
SettingInfo::Enum("Hide Battery %", &CrossPointSettings::hideBatteryPercentage, {"Never", "In Reader", "Always"},
"hideBatteryPercentage", "Display"),
SettingInfo::Enum("Refresh Frequency", &CrossPointSettings::refreshFrequency,
{"1 page", "5 pages", "10 pages", "15 pages", "30 pages"}, "refreshFrequency", "Display"),
SettingInfo::Enum("UI Theme", &CrossPointSettings::uiTheme, {"Classic", "Lyra"}, "uiTheme", "Display"),
SettingInfo::Toggle("Sunlight Fading Fix", &CrossPointSettings::fadingFix, "fadingFix", "Display"),
// --- Reader ---
SettingInfo::Enum("Font Family", &CrossPointSettings::fontFamily, {"Bookerly", "Noto Sans", "Open Dyslexic"},
"fontFamily", "Reader"),
SettingInfo::Enum("Font Size", &CrossPointSettings::fontSize, {"Small", "Medium", "Large", "X Large"}, "fontSize",
"Reader"),
SettingInfo::Enum("Line Spacing", &CrossPointSettings::lineSpacing, {"Tight", "Normal", "Wide"}, "lineSpacing",
"Reader"),
SettingInfo::Value("Screen Margin", &CrossPointSettings::screenMargin, {5, 40, 5}, "screenMargin", "Reader"),
SettingInfo::Enum("Paragraph Alignment", &CrossPointSettings::paragraphAlignment,
{"Justify", "Left", "Center", "Right", "Book's Style"}, "paragraphAlignment", "Reader"),
SettingInfo::Toggle("Book's Embedded Style", &CrossPointSettings::embeddedStyle, "embeddedStyle", "Reader"),
SettingInfo::Toggle("Hyphenation", &CrossPointSettings::hyphenationEnabled, "hyphenationEnabled", "Reader"),
SettingInfo::Enum("Reading Orientation", &CrossPointSettings::orientation,
{"Portrait", "Landscape CW", "Inverted", "Landscape CCW"}, "orientation", "Reader"),
SettingInfo::Toggle("Extra Paragraph Spacing", &CrossPointSettings::extraParagraphSpacing,
"extraParagraphSpacing", "Reader"),
SettingInfo::Toggle("Text Anti-Aliasing", &CrossPointSettings::textAntiAliasing, "textAntiAliasing", "Reader"),
// --- Controls ---
SettingInfo::Enum("Side Button Layout (reader)", &CrossPointSettings::sideButtonLayout,
{"Prev, Next", "Next, Prev"}, "sideButtonLayout", "Controls"),
SettingInfo::Toggle("Long-press Chapter Skip", &CrossPointSettings::longPressChapterSkip, "longPressChapterSkip",
"Controls"),
SettingInfo::Enum("Short Power Button Click", &CrossPointSettings::shortPwrBtn, {"Ignore", "Sleep", "Page Turn"},
"shortPwrBtn", "Controls"),
// --- System ---
SettingInfo::Enum("Time to Sleep", &CrossPointSettings::sleepTimeout,
{"1 min", "5 min", "10 min", "15 min", "30 min"}, "sleepTimeout", "System"),
// --- KOReader Sync (web-only, uses KOReaderCredentialStore) ---
SettingInfo::DynamicString(
"KOReader Username", [] { return KOREADER_STORE.getUsername(); },
[](const std::string& v) {
KOREADER_STORE.setCredentials(v, KOREADER_STORE.getPassword());
KOREADER_STORE.saveToFile();
},
"koUsername", "KOReader Sync"),
SettingInfo::DynamicString(
"KOReader Password", [] { return KOREADER_STORE.getPassword(); },
[](const std::string& v) {
KOREADER_STORE.setCredentials(KOREADER_STORE.getUsername(), v);
KOREADER_STORE.saveToFile();
},
"koPassword", "KOReader Sync"),
SettingInfo::DynamicString(
"Sync Server URL", [] { return KOREADER_STORE.getServerUrl(); },
[](const std::string& v) {
KOREADER_STORE.setServerUrl(v);
KOREADER_STORE.saveToFile();
},
"koServerUrl", "KOReader Sync"),
SettingInfo::DynamicEnum(
"Document Matching", {"Filename", "Binary"},
[] { return static_cast<uint8_t>(KOREADER_STORE.getMatchMethod()); },
[](uint8_t v) {
KOREADER_STORE.setMatchMethod(static_cast<DocumentMatchMethod>(v));
KOREADER_STORE.saveToFile();
},
"koMatchMethod", "KOReader Sync"),
// --- OPDS Browser (web-only, uses CrossPointSettings char arrays) ---
SettingInfo::String("OPDS Server URL", SETTINGS.opdsServerUrl, sizeof(SETTINGS.opdsServerUrl), "opdsServerUrl",
"OPDS Browser"),
SettingInfo::String("OPDS Username", SETTINGS.opdsUsername, sizeof(SETTINGS.opdsUsername), "opdsUsername",
"OPDS Browser"),
SettingInfo::String("OPDS Password", SETTINGS.opdsPassword, sizeof(SETTINGS.opdsPassword), "opdsPassword",
"OPDS Browser"),
};
}

View File

@@ -1,7 +1,7 @@
#include "WifiCredentialStore.h" #include "WifiCredentialStore.h"
#include <HalStorage.h>
#include <HardwareSerial.h> #include <HardwareSerial.h>
#include <SDCardManager.h>
#include <Serialization.h> #include <Serialization.h>
// Initialize the static instance // Initialize the static instance
@@ -9,7 +9,7 @@ WifiCredentialStore WifiCredentialStore::instance;
namespace { namespace {
// File format version // File format version
constexpr uint8_t WIFI_FILE_VERSION = 1; constexpr uint8_t WIFI_FILE_VERSION = 2; // Increased version
// WiFi credentials file path // WiFi credentials file path
constexpr char WIFI_FILE[] = "/.crosspoint/wifi.bin"; constexpr char WIFI_FILE[] = "/.crosspoint/wifi.bin";
@@ -29,15 +29,16 @@ void WifiCredentialStore::obfuscate(std::string& data) const {
bool WifiCredentialStore::saveToFile() const { bool WifiCredentialStore::saveToFile() const {
// Make sure the directory exists // Make sure the directory exists
SdMan.mkdir("/.crosspoint"); Storage.mkdir("/.crosspoint");
FsFile file; FsFile file;
if (!SdMan.openFileForWrite("WCS", WIFI_FILE, file)) { if (!Storage.openFileForWrite("WCS", WIFI_FILE, file)) {
return false; return false;
} }
// Write header // Write header
serialization::writePod(file, WIFI_FILE_VERSION); serialization::writePod(file, WIFI_FILE_VERSION);
serialization::writeString(file, lastConnectedSsid); // Save last connected SSID
serialization::writePod(file, static_cast<uint8_t>(credentials.size())); serialization::writePod(file, static_cast<uint8_t>(credentials.size()));
// Write each credential // Write each credential
@@ -60,19 +61,25 @@ bool WifiCredentialStore::saveToFile() const {
bool WifiCredentialStore::loadFromFile() { bool WifiCredentialStore::loadFromFile() {
FsFile file; FsFile file;
if (!SdMan.openFileForRead("WCS", WIFI_FILE, file)) { if (!Storage.openFileForRead("WCS", WIFI_FILE, file)) {
return false; return false;
} }
// Read and verify version // Read and verify version
uint8_t version; uint8_t version;
serialization::readPod(file, version); serialization::readPod(file, version);
if (version != WIFI_FILE_VERSION) { if (version > WIFI_FILE_VERSION) {
Serial.printf("[%lu] [WCS] Unknown file version: %u\n", millis(), version); Serial.printf("[%lu] [WCS] Unknown file version: %u\n", millis(), version);
file.close(); file.close();
return false; return false;
} }
if (version >= 2) {
serialization::readString(file, lastConnectedSsid);
} else {
lastConnectedSsid.clear();
}
// Read credential count // Read credential count
uint8_t count; uint8_t count;
serialization::readPod(file, count); serialization::readPod(file, count);
@@ -128,6 +135,9 @@ bool WifiCredentialStore::removeCredential(const std::string& ssid) {
if (cred != credentials.end()) { if (cred != credentials.end()) {
credentials.erase(cred); credentials.erase(cred);
Serial.printf("[%lu] [WCS] Removed credentials for: %s\n", millis(), ssid.c_str()); Serial.printf("[%lu] [WCS] Removed credentials for: %s\n", millis(), ssid.c_str());
if (ssid == lastConnectedSsid) {
clearLastConnectedSsid();
}
return saveToFile(); return saveToFile();
} }
return false; // Not found return false; // Not found
@@ -146,8 +156,25 @@ const WifiCredential* WifiCredentialStore::findCredential(const std::string& ssi
bool WifiCredentialStore::hasSavedCredential(const std::string& ssid) const { return findCredential(ssid) != nullptr; } bool WifiCredentialStore::hasSavedCredential(const std::string& ssid) const { return findCredential(ssid) != nullptr; }
void WifiCredentialStore::setLastConnectedSsid(const std::string& ssid) {
if (lastConnectedSsid != ssid) {
lastConnectedSsid = ssid;
saveToFile();
}
}
const std::string& WifiCredentialStore::getLastConnectedSsid() const { return lastConnectedSsid; }
void WifiCredentialStore::clearLastConnectedSsid() {
if (!lastConnectedSsid.empty()) {
lastConnectedSsid.clear();
saveToFile();
}
}
void WifiCredentialStore::clearAll() { void WifiCredentialStore::clearAll() {
credentials.clear(); credentials.clear();
lastConnectedSsid.clear();
saveToFile(); saveToFile();
Serial.printf("[%lu] [WCS] Cleared all WiFi credentials\n", millis()); Serial.printf("[%lu] [WCS] Cleared all WiFi credentials\n", millis());
} }

View File

@@ -16,6 +16,7 @@ class WifiCredentialStore {
private: private:
static WifiCredentialStore instance; static WifiCredentialStore instance;
std::vector<WifiCredential> credentials; std::vector<WifiCredential> credentials;
std::string lastConnectedSsid;
static constexpr size_t MAX_NETWORKS = 8; static constexpr size_t MAX_NETWORKS = 8;
@@ -48,6 +49,11 @@ class WifiCredentialStore {
// Check if a network is saved // Check if a network is saved
bool hasSavedCredential(const std::string& ssid) const; bool hasSavedCredential(const std::string& ssid) const;
// Last connected network
void setLastConnectedSsid(const std::string& ssid);
const std::string& getLastConnectedSsid() const;
void clearLastConnectedSsid();
// Clear all credentials // Clear all credentials
void clearAll(); void clearAll();
}; };

View File

@@ -2,7 +2,7 @@
#include <Epub.h> #include <Epub.h>
#include <GfxRenderer.h> #include <GfxRenderer.h>
#include <SDCardManager.h> #include <HalStorage.h>
#include <Txt.h> #include <Txt.h>
#include <Xtc.h> #include <Xtc.h>
@@ -32,7 +32,7 @@ void SleepActivity::onEnter() {
void SleepActivity::renderCustomSleepScreen() const { void SleepActivity::renderCustomSleepScreen() const {
// Check if we have a /sleep directory // Check if we have a /sleep directory
auto dir = SdMan.open("/sleep"); auto dir = Storage.open("/sleep");
if (dir && dir.isDirectory()) { if (dir && dir.isDirectory()) {
std::vector<std::string> files; std::vector<std::string> files;
char name[500]; char name[500];
@@ -75,7 +75,7 @@ void SleepActivity::renderCustomSleepScreen() const {
APP_STATE.saveToFile(); APP_STATE.saveToFile();
const auto filename = "/sleep/" + files[randomFileIndex]; const auto filename = "/sleep/" + files[randomFileIndex];
FsFile file; FsFile file;
if (SdMan.openFileForRead("SLP", filename, file)) { if (Storage.openFileForRead("SLP", filename, file)) {
Serial.printf("[%lu] [SLP] Randomly loading: /sleep/%s\n", millis(), files[randomFileIndex].c_str()); Serial.printf("[%lu] [SLP] Randomly loading: /sleep/%s\n", millis(), files[randomFileIndex].c_str());
delay(100); delay(100);
Bitmap bitmap(file, true); Bitmap bitmap(file, true);
@@ -92,7 +92,7 @@ void SleepActivity::renderCustomSleepScreen() const {
// Look for sleep.bmp on the root of the sd card to determine if we should // Look for sleep.bmp on the root of the sd card to determine if we should
// render a custom sleep screen instead of the default. // render a custom sleep screen instead of the default.
FsFile file; FsFile file;
if (SdMan.openFileForRead("SLP", "/sleep.bmp", file)) { if (Storage.openFileForRead("SLP", "/sleep.bmp", file)) {
Bitmap bitmap(file, true); Bitmap bitmap(file, true);
if (bitmap.parseHeaders() == BmpReaderError::Ok) { if (bitmap.parseHeaders() == BmpReaderError::Ok) {
Serial.printf("[%lu] [SLP] Loading: /sleep.bmp\n", millis()); Serial.printf("[%lu] [SLP] Loading: /sleep.bmp\n", millis());
@@ -218,12 +218,12 @@ void SleepActivity::renderCoverSleepScreen() const {
// Handle XTC file // Handle XTC file
Xtc lastXtc(APP_STATE.openEpubPath, "/.crosspoint"); Xtc lastXtc(APP_STATE.openEpubPath, "/.crosspoint");
if (!lastXtc.load()) { if (!lastXtc.load()) {
Serial.println("[SLP] Failed to load last XTC"); Serial.printf("[%lu] [SLP] Failed to load last XTC\n", millis());
return (this->*renderNoCoverSleepScreen)(); return (this->*renderNoCoverSleepScreen)();
} }
if (!lastXtc.generateCoverBmp()) { if (!lastXtc.generateCoverBmp()) {
Serial.println("[SLP] Failed to generate XTC cover bmp"); Serial.printf("[%lu] [SLP] Failed to generate XTC cover bmp\n", millis());
return (this->*renderNoCoverSleepScreen)(); return (this->*renderNoCoverSleepScreen)();
} }
@@ -232,12 +232,12 @@ void SleepActivity::renderCoverSleepScreen() const {
// Handle TXT file - looks for cover image in the same folder // Handle TXT file - looks for cover image in the same folder
Txt lastTxt(APP_STATE.openEpubPath, "/.crosspoint"); Txt lastTxt(APP_STATE.openEpubPath, "/.crosspoint");
if (!lastTxt.load()) { if (!lastTxt.load()) {
Serial.println("[SLP] Failed to load last TXT"); Serial.printf("[%lu] [SLP] Failed to load last TXT\n", millis());
return (this->*renderNoCoverSleepScreen)(); return (this->*renderNoCoverSleepScreen)();
} }
if (!lastTxt.generateCoverBmp()) { if (!lastTxt.generateCoverBmp()) {
Serial.println("[SLP] No cover image found for TXT file"); Serial.printf("[%lu] [SLP] No cover image found for TXT file\n", millis());
return (this->*renderNoCoverSleepScreen)(); return (this->*renderNoCoverSleepScreen)();
} }
@@ -247,12 +247,12 @@ void SleepActivity::renderCoverSleepScreen() const {
Epub lastEpub(APP_STATE.openEpubPath, "/.crosspoint"); Epub lastEpub(APP_STATE.openEpubPath, "/.crosspoint");
// Skip loading css since we only need metadata here // Skip loading css since we only need metadata here
if (!lastEpub.load(true, true)) { if (!lastEpub.load(true, true)) {
Serial.println("[SLP] Failed to load last epub"); Serial.printf("[%lu] [SLP] Failed to load last epub\n", millis());
return (this->*renderNoCoverSleepScreen)(); return (this->*renderNoCoverSleepScreen)();
} }
if (!lastEpub.generateCoverBmp(cropped)) { if (!lastEpub.generateCoverBmp(cropped)) {
Serial.println("[SLP] Failed to generate cover bmp"); Serial.printf("[%lu] [SLP] Failed to generate cover bmp\n", millis());
return (this->*renderNoCoverSleepScreen)(); return (this->*renderNoCoverSleepScreen)();
} }
@@ -262,10 +262,10 @@ void SleepActivity::renderCoverSleepScreen() const {
} }
FsFile file; FsFile file;
if (SdMan.openFileForRead("SLP", coverBmpPath, file)) { if (Storage.openFileForRead("SLP", coverBmpPath, file)) {
Bitmap bitmap(file); Bitmap bitmap(file);
if (bitmap.parseHeaders() == BmpReaderError::Ok) { if (bitmap.parseHeaders() == BmpReaderError::Ok) {
Serial.printf("[SLP] Rendering sleep cover: %s\n", coverBmpPath.c_str()); Serial.printf("[%lu] [SLP] Rendering sleep cover: %s\n", millis(), coverBmpPath.c_str());
renderBitmapSleepScreen(bitmap); renderBitmapSleepScreen(bitmap);
return; return;
} }

View File

@@ -17,7 +17,6 @@
namespace { namespace {
constexpr int PAGE_ITEMS = 23; constexpr int PAGE_ITEMS = 23;
constexpr int SKIP_PAGE_MS = 700;
} // namespace } // namespace
void OpdsBookBrowserActivity::taskTrampoline(void* param) { void OpdsBookBrowserActivity::taskTrampoline(void* param) {
@@ -118,12 +117,6 @@ void OpdsBookBrowserActivity::loop() {
// Handle browsing state // Handle browsing state
if (state == BrowserState::BROWSING) { if (state == BrowserState::BROWSING) {
const bool prevReleased = mappedInput.wasReleased(MappedInputManager::Button::Up) ||
mappedInput.wasReleased(MappedInputManager::Button::Left);
const bool nextReleased = mappedInput.wasReleased(MappedInputManager::Button::Down) ||
mappedInput.wasReleased(MappedInputManager::Button::Right);
const bool skipPage = mappedInput.getHeldTime() > SKIP_PAGE_MS;
if (mappedInput.wasReleased(MappedInputManager::Button::Confirm)) { if (mappedInput.wasReleased(MappedInputManager::Button::Confirm)) {
if (!entries.empty()) { if (!entries.empty()) {
const auto& entry = entries[selectorIndex]; const auto& entry = entries[selectorIndex];
@@ -135,20 +128,29 @@ void OpdsBookBrowserActivity::loop() {
} }
} else if (mappedInput.wasReleased(MappedInputManager::Button::Back)) { } else if (mappedInput.wasReleased(MappedInputManager::Button::Back)) {
navigateBack(); navigateBack();
} else if (prevReleased && !entries.empty()) { }
if (skipPage) {
selectorIndex = ((selectorIndex / PAGE_ITEMS - 1) * PAGE_ITEMS + entries.size()) % entries.size(); // Handle navigation
} else { if (!entries.empty()) {
selectorIndex = (selectorIndex + entries.size() - 1) % entries.size(); buttonNavigator.onNextRelease([this] {
} selectorIndex = ButtonNavigator::nextIndex(selectorIndex, entries.size());
updateRequired = true; updateRequired = true;
} else if (nextReleased && !entries.empty()) { });
if (skipPage) {
selectorIndex = ((selectorIndex / PAGE_ITEMS + 1) * PAGE_ITEMS) % entries.size(); buttonNavigator.onPreviousRelease([this] {
} else { selectorIndex = ButtonNavigator::previousIndex(selectorIndex, entries.size());
selectorIndex = (selectorIndex + 1) % entries.size(); updateRequired = true;
} });
updateRequired = true;
buttonNavigator.onNextContinuous([this] {
selectorIndex = ButtonNavigator::nextPageIndex(selectorIndex, entries.size(), PAGE_ITEMS);
updateRequired = true;
});
buttonNavigator.onPreviousContinuous([this] {
selectorIndex = ButtonNavigator::previousPageIndex(selectorIndex, entries.size(), PAGE_ITEMS);
updateRequired = true;
});
} }
} }
} }

View File

@@ -9,6 +9,7 @@
#include <vector> #include <vector>
#include "../ActivityWithSubactivity.h" #include "../ActivityWithSubactivity.h"
#include "util/ButtonNavigator.h"
/** /**
* Activity for browsing and downloading books from an OPDS server. * Activity for browsing and downloading books from an OPDS server.
@@ -37,6 +38,7 @@ class OpdsBookBrowserActivity final : public ActivityWithSubactivity {
private: private:
TaskHandle_t displayTaskHandle = nullptr; TaskHandle_t displayTaskHandle = nullptr;
SemaphoreHandle_t renderingMutex = nullptr; SemaphoreHandle_t renderingMutex = nullptr;
ButtonNavigator buttonNavigator;
bool updateRequired = false; bool updateRequired = false;
BrowserState state = BrowserState::LOADING; BrowserState state = BrowserState::LOADING;
@@ -62,4 +64,5 @@ class OpdsBookBrowserActivity final : public ActivityWithSubactivity {
void navigateToEntry(const OpdsEntry& entry); void navigateToEntry(const OpdsEntry& entry);
void navigateBack(); void navigateBack();
void downloadBook(const OpdsEntry& book); void downloadBook(const OpdsEntry& book);
bool preventAutoSleep() override { return true; }
}; };

View File

@@ -3,7 +3,7 @@
#include <Bitmap.h> #include <Bitmap.h>
#include <Epub.h> #include <Epub.h>
#include <GfxRenderer.h> #include <GfxRenderer.h>
#include <SDCardManager.h> #include <HalStorage.h>
#include <Utf8.h> #include <Utf8.h>
#include <Xtc.h> #include <Xtc.h>
@@ -47,7 +47,7 @@ void HomeActivity::loadRecentBooks(int maxBooks) {
} }
// Skip if file no longer exists // Skip if file no longer exists
if (!SdMan.exists(book.path.c_str())) { if (!Storage.exists(book.path.c_str())) {
continue; continue;
} }
@@ -64,7 +64,7 @@ void HomeActivity::loadRecentCovers(int coverHeight) {
for (RecentBook& book : recentBooks) { for (RecentBook& book : recentBooks) {
if (!book.coverBmpPath.empty()) { if (!book.coverBmpPath.empty()) {
std::string coverPath = UITheme::getCoverThumbPath(book.coverBmpPath, coverHeight); std::string coverPath = UITheme::getCoverThumbPath(book.coverBmpPath, coverHeight);
if (!SdMan.exists(coverPath.c_str())) { if (!Storage.exists(coverPath.c_str())) {
// If epub, try to load the metadata for title/author and cover // If epub, try to load the metadata for title/author and cover
if (StringUtils::checkFileExtension(book.path, ".epub")) { if (StringUtils::checkFileExtension(book.path, ".epub")) {
Epub epub(book.path, "/.crosspoint"); Epub epub(book.path, "/.crosspoint");
@@ -196,13 +196,18 @@ void HomeActivity::freeCoverBuffer() {
} }
void HomeActivity::loop() { void HomeActivity::loop() {
const bool prevPressed = mappedInput.wasPressed(MappedInputManager::Button::Up) ||
mappedInput.wasPressed(MappedInputManager::Button::Left);
const bool nextPressed = mappedInput.wasPressed(MappedInputManager::Button::Down) ||
mappedInput.wasPressed(MappedInputManager::Button::Right);
const int menuCount = getMenuItemCount(); const int menuCount = getMenuItemCount();
buttonNavigator.onNext([this, menuCount] {
selectorIndex = ButtonNavigator::nextIndex(selectorIndex, menuCount);
updateRequired = true;
});
buttonNavigator.onPrevious([this, menuCount] {
selectorIndex = ButtonNavigator::previousIndex(selectorIndex, menuCount);
updateRequired = true;
});
if (mappedInput.wasReleased(MappedInputManager::Button::Confirm)) { if (mappedInput.wasReleased(MappedInputManager::Button::Confirm)) {
// Calculate dynamic indices based on which options are available // Calculate dynamic indices based on which options are available
int idx = 0; int idx = 0;
@@ -226,12 +231,6 @@ void HomeActivity::loop() {
} else if (menuSelectedIndex == settingsIdx) { } else if (menuSelectedIndex == settingsIdx) {
onSettingsOpen(); onSettingsOpen();
} }
} else if (prevPressed) {
selectorIndex = (selectorIndex + menuCount - 1) % menuCount;
updateRequired = true;
} else if (nextPressed) {
selectorIndex = (selectorIndex + 1) % menuCount;
updateRequired = true;
} }
} }

View File

@@ -8,6 +8,7 @@
#include "../Activity.h" #include "../Activity.h"
#include "./MyLibraryActivity.h" #include "./MyLibraryActivity.h"
#include "util/ButtonNavigator.h"
struct RecentBook; struct RecentBook;
struct Rect; struct Rect;
@@ -15,6 +16,7 @@ struct Rect;
class HomeActivity final : public Activity { class HomeActivity final : public Activity {
TaskHandle_t displayTaskHandle = nullptr; TaskHandle_t displayTaskHandle = nullptr;
SemaphoreHandle_t renderingMutex = nullptr; SemaphoreHandle_t renderingMutex = nullptr;
ButtonNavigator buttonNavigator;
int selectorIndex = 0; int selectorIndex = 0;
bool updateRequired = false; bool updateRequired = false;
bool recentsLoading = false; bool recentsLoading = false;

View File

@@ -1,7 +1,7 @@
#include "MyLibraryActivity.h" #include "MyLibraryActivity.h"
#include <GfxRenderer.h> #include <GfxRenderer.h>
#include <SDCardManager.h> #include <HalStorage.h>
#include <algorithm> #include <algorithm>
@@ -11,17 +11,58 @@
#include "util/StringUtils.h" #include "util/StringUtils.h"
namespace { namespace {
constexpr int SKIP_PAGE_MS = 700;
constexpr unsigned long GO_HOME_MS = 1000; constexpr unsigned long GO_HOME_MS = 1000;
} // namespace } // namespace
void sortFileList(std::vector<std::string>& strs) { void sortFileList(std::vector<std::string>& strs) {
std::sort(begin(strs), end(strs), [](const std::string& str1, const std::string& str2) { std::sort(begin(strs), end(strs), [](const std::string& str1, const std::string& str2) {
if (str1.back() == '/' && str2.back() != '/') return true; // Directories first
if (str1.back() != '/' && str2.back() == '/') return false; bool isDir1 = str1.back() == '/';
return lexicographical_compare( bool isDir2 = str2.back() == '/';
begin(str1), end(str1), begin(str2), end(str2), if (isDir1 != isDir2) return isDir1;
[](const char& char1, const char& char2) { return tolower(char1) < tolower(char2); });
// Start naive natural sort
const char* s1 = str1.c_str();
const char* s2 = str2.c_str();
// Iterate while both strings have characters
while (*s1 && *s2) {
// Check if both are at the start of a number
if (isdigit(*s1) && isdigit(*s2)) {
// Skip leading zeros and track them
const char* start1 = s1;
const char* start2 = s2;
while (*s1 == '0') s1++;
while (*s2 == '0') s2++;
// Count digits to compare lengths first
int len1 = 0, len2 = 0;
while (isdigit(s1[len1])) len1++;
while (isdigit(s2[len2])) len2++;
// Different length so return smaller integer value
if (len1 != len2) return len1 < len2;
// Same length so compare digit by digit
for (int i = 0; i < len1; i++) {
if (s1[i] != s2[i]) return s1[i] < s2[i];
}
// Numbers equal so advance pointers
s1 += len1;
s2 += len2;
} else {
// Regular case-insensitive character comparison
char c1 = tolower(*s1);
char c2 = tolower(*s2);
if (c1 != c2) return c1 < c2;
s1++;
s2++;
}
}
// One string is prefix of other
return *s1 == '\0' && *s2 != '\0';
}); });
} }
@@ -33,7 +74,7 @@ void MyLibraryActivity::taskTrampoline(void* param) {
void MyLibraryActivity::loadFiles() { void MyLibraryActivity::loadFiles() {
files.clear(); files.clear();
auto root = SdMan.open(basepath.c_str()); auto root = Storage.open(basepath.c_str());
if (!root || !root.isDirectory()) { if (!root || !root.isDirectory()) {
if (root) root.close(); if (root) root.close();
return; return;
@@ -109,13 +150,6 @@ void MyLibraryActivity::loop() {
return; return;
} }
const bool upReleased = mappedInput.wasReleased(MappedInputManager::Button::Left) ||
mappedInput.wasReleased(MappedInputManager::Button::Up);
;
const bool downReleased = mappedInput.wasReleased(MappedInputManager::Button::Right) ||
mappedInput.wasReleased(MappedInputManager::Button::Down);
const bool skipPage = mappedInput.getHeldTime() > SKIP_PAGE_MS;
const int pageItems = UITheme::getInstance().getNumberOfItemsPerPage(renderer, true, false, true, false); const int pageItems = UITheme::getInstance().getNumberOfItemsPerPage(renderer, true, false, true, false);
if (mappedInput.wasReleased(MappedInputManager::Button::Confirm)) { if (mappedInput.wasReleased(MappedInputManager::Button::Confirm)) {
@@ -157,21 +191,26 @@ void MyLibraryActivity::loop() {
} }
int listSize = static_cast<int>(files.size()); int listSize = static_cast<int>(files.size());
if (upReleased) {
if (skipPage) { buttonNavigator.onNextRelease([this, listSize] {
selectorIndex = std::max(static_cast<int>((selectorIndex / pageItems - 1) * pageItems), 0); selectorIndex = ButtonNavigator::nextIndex(static_cast<int>(selectorIndex), listSize);
} else {
selectorIndex = (selectorIndex + listSize - 1) % listSize;
}
updateRequired = true; updateRequired = true;
} else if (downReleased) { });
if (skipPage) {
selectorIndex = std::min(static_cast<int>((selectorIndex / pageItems + 1) * pageItems), listSize - 1); buttonNavigator.onPreviousRelease([this, listSize] {
} else { selectorIndex = ButtonNavigator::previousIndex(static_cast<int>(selectorIndex), listSize);
selectorIndex = (selectorIndex + 1) % listSize;
}
updateRequired = true; updateRequired = true;
} });
buttonNavigator.onNextContinuous([this, listSize, pageItems] {
selectorIndex = ButtonNavigator::nextPageIndex(static_cast<int>(selectorIndex), listSize, pageItems);
updateRequired = true;
});
buttonNavigator.onPreviousContinuous([this, listSize, pageItems] {
selectorIndex = ButtonNavigator::previousPageIndex(static_cast<int>(selectorIndex), listSize, pageItems);
updateRequired = true;
});
} }
void MyLibraryActivity::displayTaskLoop() { void MyLibraryActivity::displayTaskLoop() {
@@ -207,7 +246,7 @@ void MyLibraryActivity::render() const {
} }
// Help text // Help text
const auto labels = mappedInput.mapLabels("« Home", "Open", "Up", "Down"); const auto labels = mappedInput.mapLabels(basepath == "/" ? "« Home" : "« Back", "Open", "Up", "Down");
GUI.drawButtonHints(renderer, labels.btn1, labels.btn2, labels.btn3, labels.btn4); GUI.drawButtonHints(renderer, labels.btn1, labels.btn2, labels.btn3, labels.btn4);
renderer.displayBuffer(); renderer.displayBuffer();

View File

@@ -8,11 +8,14 @@
#include <vector> #include <vector>
#include "../Activity.h" #include "../Activity.h"
#include "RecentBooksStore.h"
#include "util/ButtonNavigator.h"
class MyLibraryActivity final : public Activity { class MyLibraryActivity final : public Activity {
private: private:
TaskHandle_t displayTaskHandle = nullptr; TaskHandle_t displayTaskHandle = nullptr;
SemaphoreHandle_t renderingMutex = nullptr; SemaphoreHandle_t renderingMutex = nullptr;
ButtonNavigator buttonNavigator;
size_t selectorIndex = 0; size_t selectorIndex = 0;
bool updateRequired = false; bool updateRequired = false;

View File

@@ -1,7 +1,7 @@
#include "RecentBooksActivity.h" #include "RecentBooksActivity.h"
#include <GfxRenderer.h> #include <GfxRenderer.h>
#include <SDCardManager.h> #include <HalStorage.h>
#include <algorithm> #include <algorithm>
@@ -12,7 +12,6 @@
#include "util/StringUtils.h" #include "util/StringUtils.h"
namespace { namespace {
constexpr int SKIP_PAGE_MS = 700;
constexpr unsigned long GO_HOME_MS = 1000; constexpr unsigned long GO_HOME_MS = 1000;
} // namespace } // namespace
@@ -28,7 +27,7 @@ void RecentBooksActivity::loadRecentBooks() {
for (const auto& book : books) { for (const auto& book : books) {
// Skip if file no longer exists // Skip if file no longer exists
if (!SdMan.exists(book.path.c_str())) { if (!Storage.exists(book.path.c_str())) {
continue; continue;
} }
recentBooks.push_back(book); recentBooks.push_back(book);
@@ -70,18 +69,11 @@ void RecentBooksActivity::onExit() {
} }
void RecentBooksActivity::loop() { void RecentBooksActivity::loop() {
const bool upReleased = mappedInput.wasReleased(MappedInputManager::Button::Left) ||
mappedInput.wasReleased(MappedInputManager::Button::Up);
;
const bool downReleased = mappedInput.wasReleased(MappedInputManager::Button::Right) ||
mappedInput.wasReleased(MappedInputManager::Button::Down);
const bool skipPage = mappedInput.getHeldTime() > SKIP_PAGE_MS;
const int pageItems = UITheme::getInstance().getNumberOfItemsPerPage(renderer, true, false, true, true); const int pageItems = UITheme::getInstance().getNumberOfItemsPerPage(renderer, true, false, true, true);
if (mappedInput.wasReleased(MappedInputManager::Button::Confirm)) { if (mappedInput.wasReleased(MappedInputManager::Button::Confirm)) {
if (!recentBooks.empty() && selectorIndex < static_cast<int>(recentBooks.size())) { if (!recentBooks.empty() && selectorIndex < static_cast<int>(recentBooks.size())) {
Serial.printf("Selected recent book: %s\n", recentBooks[selectorIndex].path.c_str()); Serial.printf("[%lu] [RBA] Selected recent book: %s\n", millis(), recentBooks[selectorIndex].path.c_str());
onSelectBook(recentBooks[selectorIndex].path); onSelectBook(recentBooks[selectorIndex].path);
return; return;
} }
@@ -92,21 +84,26 @@ void RecentBooksActivity::loop() {
} }
int listSize = static_cast<int>(recentBooks.size()); int listSize = static_cast<int>(recentBooks.size());
if (upReleased) {
if (skipPage) { buttonNavigator.onNextRelease([this, listSize] {
selectorIndex = std::max(static_cast<int>((selectorIndex / pageItems - 1) * pageItems), 0); selectorIndex = ButtonNavigator::nextIndex(static_cast<int>(selectorIndex), listSize);
} else {
selectorIndex = (selectorIndex + listSize - 1) % listSize;
}
updateRequired = true; updateRequired = true;
} else if (downReleased) { });
if (skipPage) {
selectorIndex = std::min(static_cast<int>((selectorIndex / pageItems + 1) * pageItems), listSize - 1); buttonNavigator.onPreviousRelease([this, listSize] {
} else { selectorIndex = ButtonNavigator::previousIndex(static_cast<int>(selectorIndex), listSize);
selectorIndex = (selectorIndex + 1) % listSize;
}
updateRequired = true; updateRequired = true;
} });
buttonNavigator.onNextContinuous([this, listSize, pageItems] {
selectorIndex = ButtonNavigator::nextPageIndex(static_cast<int>(selectorIndex), listSize, pageItems);
updateRequired = true;
});
buttonNavigator.onPreviousContinuous([this, listSize, pageItems] {
selectorIndex = ButtonNavigator::previousPageIndex(static_cast<int>(selectorIndex), listSize, pageItems);
updateRequired = true;
});
} }
void RecentBooksActivity::displayTaskLoop() { void RecentBooksActivity::displayTaskLoop() {

View File

@@ -9,11 +9,13 @@
#include "../Activity.h" #include "../Activity.h"
#include "RecentBooksStore.h" #include "RecentBooksStore.h"
#include "util/ButtonNavigator.h"
class RecentBooksActivity final : public Activity { class RecentBooksActivity final : public Activity {
private: private:
TaskHandle_t displayTaskHandle = nullptr; TaskHandle_t displayTaskHandle = nullptr;
SemaphoreHandle_t renderingMutex = nullptr; SemaphoreHandle_t renderingMutex = nullptr;
ButtonNavigator buttonNavigator;
size_t selectorIndex = 0; size_t selectorIndex = 0;
bool updateRequired = false; bool updateRequired = false;

View File

@@ -348,6 +348,9 @@ void CrossPointWebServerActivity::loop() {
// Yield and check for exit button every 64 iterations // Yield and check for exit button every 64 iterations
if ((i & 0x3F) == 0x3F) { if ((i & 0x3F) == 0x3F) {
yield(); yield();
// Force trigger an update of which buttons are being pressed so be have accurate state
// for back button checking
mappedInput.update();
// Check for exit button inside loop for responsiveness // Check for exit button inside loop for responsiveness
if (mappedInput.wasPressed(MappedInputManager::Button::Back)) { if (mappedInput.wasPressed(MappedInputManager::Button::Back)) {
onGoBack(); onGoBack();

View File

@@ -73,18 +73,15 @@ void NetworkModeSelectionActivity::loop() {
} }
// Handle navigation // Handle navigation
const bool prevPressed = mappedInput.wasPressed(MappedInputManager::Button::Up) || buttonNavigator.onNext([this] {
mappedInput.wasPressed(MappedInputManager::Button::Left); selectedIndex = ButtonNavigator::nextIndex(selectedIndex, MENU_ITEM_COUNT);
const bool nextPressed = mappedInput.wasPressed(MappedInputManager::Button::Down) || updateRequired = true;
mappedInput.wasPressed(MappedInputManager::Button::Right); });
if (prevPressed) { buttonNavigator.onPrevious([this] {
selectedIndex = (selectedIndex + MENU_ITEM_COUNT - 1) % MENU_ITEM_COUNT; selectedIndex = ButtonNavigator::previousIndex(selectedIndex, MENU_ITEM_COUNT);
updateRequired = true; updateRequired = true;
} else if (nextPressed) { });
selectedIndex = (selectedIndex + 1) % MENU_ITEM_COUNT;
updateRequired = true;
}
} }
void NetworkModeSelectionActivity::displayTaskLoop() { void NetworkModeSelectionActivity::displayTaskLoop() {

View File

@@ -6,6 +6,7 @@
#include <functional> #include <functional>
#include "../Activity.h" #include "../Activity.h"
#include "util/ButtonNavigator.h"
// Enum for network mode selection // Enum for network mode selection
enum class NetworkMode { JOIN_NETWORK, CONNECT_CALIBRE, CREATE_HOTSPOT }; enum class NetworkMode { JOIN_NETWORK, CONNECT_CALIBRE, CREATE_HOTSPOT };
@@ -22,6 +23,8 @@ enum class NetworkMode { JOIN_NETWORK, CONNECT_CALIBRE, CREATE_HOTSPOT };
class NetworkModeSelectionActivity final : public Activity { class NetworkModeSelectionActivity final : public Activity {
TaskHandle_t displayTaskHandle = nullptr; TaskHandle_t displayTaskHandle = nullptr;
SemaphoreHandle_t renderingMutex = nullptr; SemaphoreHandle_t renderingMutex = nullptr;
ButtonNavigator buttonNavigator;
int selectedIndex = 0; int selectedIndex = 0;
bool updateRequired = false; bool updateRequired = false;
const std::function<void(NetworkMode)> onModeSelected; const std::function<void(NetworkMode)> onModeSelected;

View File

@@ -21,7 +21,8 @@ void WifiSelectionActivity::onEnter() {
renderingMutex = xSemaphoreCreateMutex(); renderingMutex = xSemaphoreCreateMutex();
// Load saved WiFi credentials - SD card operations need lock as we use SPI for both // Load saved WiFi credentials - SD card operations need lock as we use SPI
// for both
xSemaphoreTake(renderingMutex, portMAX_DELAY); xSemaphoreTake(renderingMutex, portMAX_DELAY);
WIFI_STORE.loadFromFile(); WIFI_STORE.loadFromFile();
xSemaphoreGive(renderingMutex); xSemaphoreGive(renderingMutex);
@@ -37,6 +38,7 @@ void WifiSelectionActivity::onEnter() {
usedSavedPassword = false; usedSavedPassword = false;
savePromptSelection = 0; savePromptSelection = 0;
forgetPromptSelection = 0; forgetPromptSelection = 0;
autoConnecting = false;
// Cache MAC address for display // Cache MAC address for display
uint8_t mac[6]; uint8_t mac[6];
@@ -46,9 +48,7 @@ void WifiSelectionActivity::onEnter() {
mac[5]); mac[5]);
cachedMacAddress = std::string(macStr); cachedMacAddress = std::string(macStr);
// Trigger first update to show scanning message // Task creation
updateRequired = true;
xTaskCreate(&WifiSelectionActivity::taskTrampoline, "WifiSelectionTask", xTaskCreate(&WifiSelectionActivity::taskTrampoline, "WifiSelectionTask",
4096, // Stack size (larger for WiFi operations) 4096, // Stack size (larger for WiFi operations)
this, // Parameters this, // Parameters
@@ -56,7 +56,26 @@ void WifiSelectionActivity::onEnter() {
&displayTaskHandle // Task handle &displayTaskHandle // Task handle
); );
// Start WiFi scan // Attempt to auto-connect to the last network
if (allowAutoConnect) {
const std::string lastSsid = WIFI_STORE.getLastConnectedSsid();
if (!lastSsid.empty()) {
const auto* cred = WIFI_STORE.findCredential(lastSsid);
if (cred) {
Serial.printf("[%lu] [WIFI] Attempting to auto-connect to %s\n", millis(), lastSsid.c_str());
selectedSSID = cred->ssid;
enteredPassword = cred->password;
selectedRequiresPassword = !cred->password.empty();
usedSavedPassword = true;
autoConnecting = true;
attemptConnection();
updateRequired = true;
return;
}
}
}
// Fallback to scanning
startWifiScan(); startWifiScan();
} }
@@ -70,15 +89,17 @@ void WifiSelectionActivity::onExit() {
WiFi.scanDelete(); WiFi.scanDelete();
Serial.printf("[%lu] [WIFI] [MEM] Free heap after scanDelete: %d bytes\n", millis(), ESP.getFreeHeap()); Serial.printf("[%lu] [WIFI] [MEM] Free heap after scanDelete: %d bytes\n", millis(), ESP.getFreeHeap());
// Note: We do NOT disconnect WiFi here - the parent activity (CrossPointWebServerActivity) // Note: We do NOT disconnect WiFi here - the parent activity
// manages WiFi connection state. We just clean up the scan and task. // (CrossPointWebServerActivity) manages WiFi connection state. We just clean
// up the scan and task.
// Acquire mutex before deleting task to ensure task isn't using it // Acquire mutex before deleting task to ensure task isn't using it
// This prevents hangs/crashes if the task holds the mutex when deleted // This prevents hangs/crashes if the task holds the mutex when deleted
Serial.printf("[%lu] [WIFI] Acquiring rendering mutex before task deletion...\n", millis()); Serial.printf("[%lu] [WIFI] Acquiring rendering mutex before task deletion...\n", millis());
xSemaphoreTake(renderingMutex, portMAX_DELAY); xSemaphoreTake(renderingMutex, portMAX_DELAY);
// Delete the display task (we now hold the mutex, so task is blocked if it needs it) // Delete the display task (we now hold the mutex, so task is blocked if it
// needs it)
Serial.printf("[%lu] [WIFI] Deleting display task...\n", millis()); Serial.printf("[%lu] [WIFI] Deleting display task...\n", millis());
if (displayTaskHandle) { if (displayTaskHandle) {
vTaskDelete(displayTaskHandle); vTaskDelete(displayTaskHandle);
@@ -96,6 +117,7 @@ void WifiSelectionActivity::onExit() {
} }
void WifiSelectionActivity::startWifiScan() { void WifiSelectionActivity::startWifiScan() {
autoConnecting = false;
state = WifiSelectionState::SCANNING; state = WifiSelectionState::SCANNING;
networks.clear(); networks.clear();
updateRequired = true; updateRequired = true;
@@ -181,6 +203,7 @@ void WifiSelectionActivity::selectNetwork(const int index) {
selectedRequiresPassword = network.isEncrypted; selectedRequiresPassword = network.isEncrypted;
usedSavedPassword = false; usedSavedPassword = false;
enteredPassword.clear(); enteredPassword.clear();
autoConnecting = false;
// Check if we have saved credentials for this network // Check if we have saved credentials for this network
const auto* savedCred = WIFI_STORE.findCredential(selectedSSID); const auto* savedCred = WIFI_STORE.findCredential(selectedSSID);
@@ -223,7 +246,7 @@ void WifiSelectionActivity::selectNetwork(const int index) {
} }
void WifiSelectionActivity::attemptConnection() { void WifiSelectionActivity::attemptConnection() {
state = WifiSelectionState::CONNECTING; state = autoConnecting ? WifiSelectionState::AUTO_CONNECTING : WifiSelectionState::CONNECTING;
connectionStartTime = millis(); connectionStartTime = millis();
connectedIP.clear(); connectedIP.clear();
connectionError.clear(); connectionError.clear();
@@ -239,7 +262,7 @@ void WifiSelectionActivity::attemptConnection() {
} }
void WifiSelectionActivity::checkConnectionStatus() { void WifiSelectionActivity::checkConnectionStatus() {
if (state != WifiSelectionState::CONNECTING) { if (state != WifiSelectionState::CONNECTING && state != WifiSelectionState::AUTO_CONNECTING) {
return; return;
} }
@@ -251,6 +274,13 @@ void WifiSelectionActivity::checkConnectionStatus() {
char ipStr[16]; char ipStr[16];
snprintf(ipStr, sizeof(ipStr), "%d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]); snprintf(ipStr, sizeof(ipStr), "%d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]);
connectedIP = ipStr; connectedIP = ipStr;
autoConnecting = false;
// Save this as the last connected network - SD card operations need lock as
// we use SPI for both
xSemaphoreTake(renderingMutex, portMAX_DELAY);
WIFI_STORE.setLastConnectedSsid(selectedSSID);
xSemaphoreGive(renderingMutex);
// If we entered a new password, ask if user wants to save it // If we entered a new password, ask if user wants to save it
// Otherwise, immediately complete so parent can start web server // Otherwise, immediately complete so parent can start web server
@@ -260,7 +290,10 @@ void WifiSelectionActivity::checkConnectionStatus() {
updateRequired = true; updateRequired = true;
} else { } else {
// Using saved password or open network - complete immediately // Using saved password or open network - complete immediately
Serial.printf("[%lu] [WIFI] Connected with saved/open credentials, completing immediately\n", millis()); Serial.printf(
"[%lu] [WIFI] Connected with saved/open credentials, "
"completing immediately\n",
millis());
onComplete(true); onComplete(true);
} }
return; return;
@@ -299,7 +332,7 @@ void WifiSelectionActivity::loop() {
} }
// Check connection progress // Check connection progress
if (state == WifiSelectionState::CONNECTING) { if (state == WifiSelectionState::CONNECTING || state == WifiSelectionState::AUTO_CONNECTING) {
checkConnectionStatus(); checkConnectionStatus();
return; return;
} }
@@ -368,17 +401,16 @@ void WifiSelectionActivity::loop() {
} }
} }
// Go back to network list (whether Cancel or Forget network was selected) // Go back to network list (whether Cancel or Forget network was selected)
state = WifiSelectionState::NETWORK_LIST; startWifiScan();
updateRequired = true;
} else if (mappedInput.wasPressed(MappedInputManager::Button::Back)) { } else if (mappedInput.wasPressed(MappedInputManager::Button::Back)) {
// Skip forgetting, go back to network list // Skip forgetting, go back to network list
state = WifiSelectionState::NETWORK_LIST; startWifiScan();
updateRequired = true;
} }
return; return;
} }
// Handle connected state (should not normally be reached - connection completes immediately) // Handle connected state (should not normally be reached - connection
// completes immediately)
if (state == WifiSelectionState::CONNECTED) { if (state == WifiSelectionState::CONNECTED) {
// Safety fallback - immediately complete // Safety fallback - immediately complete
onComplete(true); onComplete(true);
@@ -389,12 +421,14 @@ void WifiSelectionActivity::loop() {
if (state == WifiSelectionState::CONNECTION_FAILED) { if (state == WifiSelectionState::CONNECTION_FAILED) {
if (mappedInput.wasPressed(MappedInputManager::Button::Back) || if (mappedInput.wasPressed(MappedInputManager::Button::Back) ||
mappedInput.wasPressed(MappedInputManager::Button::Confirm)) { mappedInput.wasPressed(MappedInputManager::Button::Confirm)) {
// If we used saved credentials, offer to forget the network // If we were auto-connecting or using a saved credential, offer to forget
if (usedSavedPassword) { // the network
if (autoConnecting || usedSavedPassword) {
autoConnecting = false;
state = WifiSelectionState::FORGET_PROMPT; state = WifiSelectionState::FORGET_PROMPT;
forgetPromptSelection = 0; // Default to "Cancel" forgetPromptSelection = 0; // Default to "Cancel"
} else { } else {
// Go back to network list on failure // Go back to network list on failure for non-saved credentials
state = WifiSelectionState::NETWORK_LIST; state = WifiSelectionState::NETWORK_LIST;
} }
updateRequired = true; updateRequired = true;
@@ -420,20 +454,33 @@ void WifiSelectionActivity::loop() {
return; return;
} }
// Handle UP/DOWN navigation if (mappedInput.wasPressed(MappedInputManager::Button::Right)) {
if (mappedInput.wasPressed(MappedInputManager::Button::Up) || startWifiScan();
mappedInput.wasPressed(MappedInputManager::Button::Left)) { return;
if (selectedNetworkIndex > 0) { }
selectedNetworkIndex--;
updateRequired = true; const bool leftPressed = mappedInput.wasPressed(MappedInputManager::Button::Left);
} if (leftPressed) {
} else if (mappedInput.wasPressed(MappedInputManager::Button::Down) || const bool hasSavedPassword = !networks.empty() && networks[selectedNetworkIndex].hasSavedPassword;
mappedInput.wasPressed(MappedInputManager::Button::Right)) { if (hasSavedPassword) {
if (!networks.empty() && selectedNetworkIndex < static_cast<int>(networks.size()) - 1) { selectedSSID = networks[selectedNetworkIndex].ssid;
selectedNetworkIndex++; state = WifiSelectionState::FORGET_PROMPT;
forgetPromptSelection = 0; // Default to "Cancel"
updateRequired = true; updateRequired = true;
return;
} }
} }
// Handle navigation
buttonNavigator.onNext([this] {
selectedNetworkIndex = ButtonNavigator::nextIndex(selectedNetworkIndex, networks.size());
updateRequired = true;
});
buttonNavigator.onPrevious([this] {
selectedNetworkIndex = ButtonNavigator::previousIndex(selectedNetworkIndex, networks.size());
updateRequired = true;
});
} }
} }
@@ -483,6 +530,9 @@ void WifiSelectionActivity::render() const {
renderer.clearScreen(); renderer.clearScreen();
switch (state) { switch (state) {
case WifiSelectionState::AUTO_CONNECTING:
renderConnecting();
break;
case WifiSelectionState::SCANNING: case WifiSelectionState::SCANNING:
renderConnecting(); // Reuse connecting screen with different message renderConnecting(); // Reuse connecting screen with different message
break; break;
@@ -586,7 +636,11 @@ void WifiSelectionActivity::renderNetworkList() const {
// Draw help text // Draw help text
renderer.drawText(SMALL_FONT_ID, 20, pageHeight - 75, "* = Encrypted | + = Saved"); renderer.drawText(SMALL_FONT_ID, 20, pageHeight - 75, "* = Encrypted | + = Saved");
const auto labels = mappedInput.mapLabels("« Back", "Connect", "", "");
const bool hasSavedPassword = !networks.empty() && networks[selectedNetworkIndex].hasSavedPassword;
const char* forgetLabel = hasSavedPassword ? "Forget" : "";
const auto labels = mappedInput.mapLabels("« Back", "Connect", forgetLabel, "Refresh");
GUI.drawButtonHints(renderer, labels.btn1, labels.btn2, labels.btn3, labels.btn4); GUI.drawButtonHints(renderer, labels.btn1, labels.btn2, labels.btn3, labels.btn4);
} }
@@ -690,8 +744,7 @@ void WifiSelectionActivity::renderForgetPrompt() const {
const auto height = renderer.getLineHeight(UI_10_FONT_ID); const auto height = renderer.getLineHeight(UI_10_FONT_ID);
const auto top = (pageHeight - height * 3) / 2; const auto top = (pageHeight - height * 3) / 2;
renderer.drawCenteredText(UI_12_FONT_ID, top - 40, "Connection Failed", true, EpdFontFamily::BOLD); renderer.drawCenteredText(UI_12_FONT_ID, top - 40, "Forget Network", true, EpdFontFamily::BOLD);
std::string ssidInfo = "Network: " + selectedSSID; std::string ssidInfo = "Network: " + selectedSSID;
if (ssidInfo.length() > 28) { if (ssidInfo.length() > 28) {
ssidInfo.replace(25, ssidInfo.length() - 25, "..."); ssidInfo.replace(25, ssidInfo.length() - 25, "...");

View File

@@ -10,6 +10,7 @@
#include <vector> #include <vector>
#include "activities/ActivityWithSubactivity.h" #include "activities/ActivityWithSubactivity.h"
#include "util/ButtonNavigator.h"
// Structure to hold WiFi network information // Structure to hold WiFi network information
struct WifiNetworkInfo { struct WifiNetworkInfo {
@@ -21,6 +22,7 @@ struct WifiNetworkInfo {
// WiFi selection states // WiFi selection states
enum class WifiSelectionState { enum class WifiSelectionState {
AUTO_CONNECTING, // Trying to connect to the last known network
SCANNING, // Scanning for networks SCANNING, // Scanning for networks
NETWORK_LIST, // Displaying available networks NETWORK_LIST, // Displaying available networks
PASSWORD_ENTRY, // Entering password for selected network PASSWORD_ENTRY, // Entering password for selected network
@@ -45,6 +47,7 @@ enum class WifiSelectionState {
class WifiSelectionActivity final : public ActivityWithSubactivity { class WifiSelectionActivity final : public ActivityWithSubactivity {
TaskHandle_t displayTaskHandle = nullptr; TaskHandle_t displayTaskHandle = nullptr;
SemaphoreHandle_t renderingMutex = nullptr; SemaphoreHandle_t renderingMutex = nullptr;
ButtonNavigator buttonNavigator;
bool updateRequired = false; bool updateRequired = false;
WifiSelectionState state = WifiSelectionState::SCANNING; WifiSelectionState state = WifiSelectionState::SCANNING;
int selectedNetworkIndex = 0; int selectedNetworkIndex = 0;
@@ -68,6 +71,12 @@ class WifiSelectionActivity final : public ActivityWithSubactivity {
// Whether network was connected using a saved password (skip save prompt) // Whether network was connected using a saved password (skip save prompt)
bool usedSavedPassword = false; bool usedSavedPassword = false;
// Whether to attempt auto-connect on entry
const bool allowAutoConnect;
// Whether we are attempting to auto-connect
bool autoConnecting = false;
// Save/forget prompt selection (0 = Yes, 1 = No) // Save/forget prompt selection (0 = Yes, 1 = No)
int savePromptSelection = 0; int savePromptSelection = 0;
int forgetPromptSelection = 0; int forgetPromptSelection = 0;
@@ -96,8 +105,10 @@ class WifiSelectionActivity final : public ActivityWithSubactivity {
public: public:
explicit WifiSelectionActivity(GfxRenderer& renderer, MappedInputManager& mappedInput, explicit WifiSelectionActivity(GfxRenderer& renderer, MappedInputManager& mappedInput,
const std::function<void(bool connected)>& onComplete) const std::function<void(bool connected)>& onComplete, bool autoConnect = true)
: ActivityWithSubactivity("WifiSelection", renderer, mappedInput), onComplete(onComplete) {} : ActivityWithSubactivity("WifiSelection", renderer, mappedInput),
onComplete(onComplete),
allowAutoConnect(autoConnect) {}
void onEnter() override; void onEnter() override;
void onExit() override; void onExit() override;
void loop() override; void loop() override;

View File

@@ -3,7 +3,7 @@
#include <Epub/Page.h> #include <Epub/Page.h>
#include <FsHelpers.h> #include <FsHelpers.h>
#include <GfxRenderer.h> #include <GfxRenderer.h>
#include <SDCardManager.h> #include <HalStorage.h>
#include "CrossPointSettings.h" #include "CrossPointSettings.h"
#include "CrossPointState.h" #include "CrossPointState.h"
@@ -77,7 +77,7 @@ void EpubReaderActivity::onEnter() {
epub->setupCacheDir(); epub->setupCacheDir();
FsFile f; FsFile f;
if (SdMan.openFileForRead("ERS", epub->getCachePath() + "/progress.bin", f)) { if (Storage.openFileForRead("ERS", epub->getCachePath() + "/progress.bin", f)) {
uint8_t data[6]; uint8_t data[6];
int dataSize = f.read(data, 6); int dataSize = f.read(data, 6);
if (dataSize == 4 || dataSize == 6) { if (dataSize == 4 || dataSize == 6) {
@@ -204,15 +204,15 @@ void EpubReaderActivity::loop() {
xSemaphoreGive(renderingMutex); xSemaphoreGive(renderingMutex);
} }
// Long press BACK (1s+) goes directly to home // Long press BACK (1s+) goes to file selection
if (mappedInput.isPressed(MappedInputManager::Button::Back) && mappedInput.getHeldTime() >= goHomeMs) { if (mappedInput.isPressed(MappedInputManager::Button::Back) && mappedInput.getHeldTime() >= goHomeMs) {
onGoHome(); onGoBack();
return; return;
} }
// Short press BACK goes to file selection // Short press BACK goes directly to home
if (mappedInput.wasReleased(MappedInputManager::Button::Back) && mappedInput.getHeldTime() < goHomeMs) { if (mappedInput.wasReleased(MappedInputManager::Button::Back) && mappedInput.getHeldTime() < goHomeMs) {
onGoBack(); onGoHome();
return; return;
} }
@@ -654,7 +654,7 @@ void EpubReaderActivity::renderScreen() {
void EpubReaderActivity::saveProgress(int spineIndex, int currentPage, int pageCount) { void EpubReaderActivity::saveProgress(int spineIndex, int currentPage, int pageCount) {
FsFile f; FsFile f;
if (SdMan.openFileForWrite("ERS", epub->getCachePath() + "/progress.bin", f)) { if (Storage.openFileForWrite("ERS", epub->getCachePath() + "/progress.bin", f)) {
uint8_t data[6]; uint8_t data[6];
data[0] = currentSpineIndex & 0xFF; data[0] = currentSpineIndex & 0xFF;
data[1] = (currentSpineIndex >> 8) & 0xFF; data[1] = (currentSpineIndex >> 8) & 0xFF;
@@ -664,9 +664,9 @@ void EpubReaderActivity::saveProgress(int spineIndex, int currentPage, int pageC
data[5] = (pageCount >> 8) & 0xFF; data[5] = (pageCount >> 8) & 0xFF;
f.write(data, 6); f.write(data, 6);
f.close(); f.close();
Serial.printf("[ERS] Progress saved: Chapter %d, Page %d\n", spineIndex, currentPage); Serial.printf("[%lu] [ERS] Progress saved: Chapter %d, Page %d\n", millis(), spineIndex, currentPage);
} else { } else {
Serial.printf("[ERS] Could not save progress!\n"); Serial.printf("[%lu] [ERS] Could not save progress!\n", millis());
} }
} }
void EpubReaderActivity::renderContents(std::unique_ptr<Page> page, const int orientedMarginTop, void EpubReaderActivity::renderContents(std::unique_ptr<Page> page, const int orientedMarginTop,

View File

@@ -6,11 +6,6 @@
#include "components/UITheme.h" #include "components/UITheme.h"
#include "fontIds.h" #include "fontIds.h"
namespace {
// Time threshold for treating a long press as a page-up/page-down
constexpr int SKIP_PAGE_MS = 700;
} // namespace
int EpubReaderChapterSelectionActivity::getTotalItems() const { return epub->getTocItemsCount(); } int EpubReaderChapterSelectionActivity::getTotalItems() const { return epub->getTocItemsCount(); }
int EpubReaderChapterSelectionActivity::getPageItems() const { int EpubReaderChapterSelectionActivity::getPageItems() const {
@@ -77,12 +72,6 @@ void EpubReaderChapterSelectionActivity::loop() {
return; return;
} }
const bool prevReleased = mappedInput.wasReleased(MappedInputManager::Button::Up) ||
mappedInput.wasReleased(MappedInputManager::Button::Left);
const bool nextReleased = mappedInput.wasReleased(MappedInputManager::Button::Down) ||
mappedInput.wasReleased(MappedInputManager::Button::Right);
const bool skipPage = mappedInput.getHeldTime() > SKIP_PAGE_MS;
const int pageItems = getPageItems(); const int pageItems = getPageItems();
const int totalItems = getTotalItems(); const int totalItems = getTotalItems();
@@ -95,21 +84,27 @@ void EpubReaderChapterSelectionActivity::loop() {
} }
} else if (mappedInput.wasReleased(MappedInputManager::Button::Back)) { } else if (mappedInput.wasReleased(MappedInputManager::Button::Back)) {
onGoBack(); onGoBack();
} else if (prevReleased) {
if (skipPage) {
selectorIndex = ((selectorIndex / pageItems - 1) * pageItems + totalItems) % totalItems;
} else {
selectorIndex = (selectorIndex + totalItems - 1) % totalItems;
}
updateRequired = true;
} else if (nextReleased) {
if (skipPage) {
selectorIndex = ((selectorIndex / pageItems + 1) * pageItems) % totalItems;
} else {
selectorIndex = (selectorIndex + 1) % totalItems;
}
updateRequired = true;
} }
buttonNavigator.onNextRelease([this, totalItems] {
selectorIndex = ButtonNavigator::nextIndex(selectorIndex, totalItems);
updateRequired = true;
});
buttonNavigator.onPreviousRelease([this, totalItems] {
selectorIndex = ButtonNavigator::previousIndex(selectorIndex, totalItems);
updateRequired = true;
});
buttonNavigator.onNextContinuous([this, totalItems, pageItems] {
selectorIndex = ButtonNavigator::nextPageIndex(selectorIndex, totalItems, pageItems);
updateRequired = true;
});
buttonNavigator.onPreviousContinuous([this, totalItems, pageItems] {
selectorIndex = ButtonNavigator::previousPageIndex(selectorIndex, totalItems, pageItems);
updateRequired = true;
});
} }
void EpubReaderChapterSelectionActivity::displayTaskLoop() { void EpubReaderChapterSelectionActivity::displayTaskLoop() {

View File

@@ -7,12 +7,14 @@
#include <memory> #include <memory>
#include "../ActivityWithSubactivity.h" #include "../ActivityWithSubactivity.h"
#include "util/ButtonNavigator.h"
class EpubReaderChapterSelectionActivity final : public ActivityWithSubactivity { class EpubReaderChapterSelectionActivity final : public ActivityWithSubactivity {
std::shared_ptr<Epub> epub; std::shared_ptr<Epub> epub;
std::string epubPath; std::string epubPath;
TaskHandle_t displayTaskHandle = nullptr; TaskHandle_t displayTaskHandle = nullptr;
SemaphoreHandle_t renderingMutex = nullptr; SemaphoreHandle_t renderingMutex = nullptr;
ButtonNavigator buttonNavigator;
int currentSpineIndex = 0; int currentSpineIndex = 0;
int currentPage = 0; int currentPage = 0;
int totalPagesInSpine = 0; int totalPagesInSpine = 0;

View File

@@ -48,16 +48,19 @@ void EpubReaderMenuActivity::loop() {
return; return;
} }
// Handle navigation
buttonNavigator.onNext([this] {
selectedIndex = ButtonNavigator::nextIndex(selectedIndex, static_cast<int>(menuItems.size()));
updateRequired = true;
});
buttonNavigator.onPrevious([this] {
selectedIndex = ButtonNavigator::previousIndex(selectedIndex, static_cast<int>(menuItems.size()));
updateRequired = true;
});
// Use local variables for items we need to check after potential deletion // Use local variables for items we need to check after potential deletion
if (mappedInput.wasReleased(MappedInputManager::Button::Up) || if (mappedInput.wasReleased(MappedInputManager::Button::Confirm)) {
mappedInput.wasReleased(MappedInputManager::Button::Left)) {
selectedIndex = (selectedIndex + menuItems.size() - 1) % menuItems.size();
updateRequired = true;
} else if (mappedInput.wasReleased(MappedInputManager::Button::Down) ||
mappedInput.wasReleased(MappedInputManager::Button::Right)) {
selectedIndex = (selectedIndex + 1) % menuItems.size();
updateRequired = true;
} else if (mappedInput.wasReleased(MappedInputManager::Button::Confirm)) {
const auto selectedAction = menuItems[selectedIndex].action; const auto selectedAction = menuItems[selectedIndex].action;
if (selectedAction == MenuAction::ROTATE_SCREEN) { if (selectedAction == MenuAction::ROTATE_SCREEN) {
// Cycle orientation preview locally; actual rotation happens on menu exit. // Cycle orientation preview locally; actual rotation happens on menu exit.

View File

@@ -9,6 +9,7 @@
#include <vector> #include <vector>
#include "../ActivityWithSubactivity.h" #include "../ActivityWithSubactivity.h"
#include "util/ButtonNavigator.h"
class EpubReaderMenuActivity final : public ActivityWithSubactivity { class EpubReaderMenuActivity final : public ActivityWithSubactivity {
public: public:
@@ -48,6 +49,7 @@ class EpubReaderMenuActivity final : public ActivityWithSubactivity {
bool updateRequired = false; bool updateRequired = false;
TaskHandle_t displayTaskHandle = nullptr; TaskHandle_t displayTaskHandle = nullptr;
SemaphoreHandle_t renderingMutex = nullptr; SemaphoreHandle_t renderingMutex = nullptr;
ButtonNavigator buttonNavigator;
std::string title = "Reader Menu"; std::string title = "Reader Menu";
uint8_t pendingOrientation = 0; uint8_t pendingOrientation = 0;
const std::vector<const char*> orientationLabels = {"Portrait", "Landscape CW", "Inverted", "Landscape CCW"}; const std::vector<const char*> orientationLabels = {"Portrait", "Landscape CW", "Inverted", "Landscape CCW"};

View File

@@ -79,25 +79,11 @@ void EpubReaderPercentSelectionActivity::loop() {
return; return;
} }
if (mappedInput.wasReleased(MappedInputManager::Button::Left)) { buttonNavigator.onPressAndContinuous({MappedInputManager::Button::Left}, [this] { adjustPercent(-kSmallStep); });
adjustPercent(-kSmallStep); buttonNavigator.onPressAndContinuous({MappedInputManager::Button::Right}, [this] { adjustPercent(kSmallStep); });
return;
}
if (mappedInput.wasReleased(MappedInputManager::Button::Right)) { buttonNavigator.onPressAndContinuous({MappedInputManager::Button::Up}, [this] { adjustPercent(kLargeStep); });
adjustPercent(kSmallStep); buttonNavigator.onPressAndContinuous({MappedInputManager::Button::Down}, [this] { adjustPercent(-kLargeStep); });
return;
}
if (mappedInput.wasReleased(MappedInputManager::Button::Up)) {
adjustPercent(kLargeStep);
return;
}
if (mappedInput.wasReleased(MappedInputManager::Button::Down)) {
adjustPercent(-kLargeStep);
return;
}
} }
void EpubReaderPercentSelectionActivity::renderScreen() { void EpubReaderPercentSelectionActivity::renderScreen() {

View File

@@ -7,6 +7,7 @@
#include "MappedInputManager.h" #include "MappedInputManager.h"
#include "activities/ActivityWithSubactivity.h" #include "activities/ActivityWithSubactivity.h"
#include "util/ButtonNavigator.h"
class EpubReaderPercentSelectionActivity final : public ActivityWithSubactivity { class EpubReaderPercentSelectionActivity final : public ActivityWithSubactivity {
public: public:
@@ -31,6 +32,7 @@ class EpubReaderPercentSelectionActivity final : public ActivityWithSubactivity
// FreeRTOS task and mutex for rendering. // FreeRTOS task and mutex for rendering.
TaskHandle_t displayTaskHandle = nullptr; TaskHandle_t displayTaskHandle = nullptr;
SemaphoreHandle_t renderingMutex = nullptr; SemaphoreHandle_t renderingMutex = nullptr;
ButtonNavigator buttonNavigator;
// Callback invoked when the user confirms a percent. // Callback invoked when the user confirms a percent.
const std::function<void(int)> onSelect; const std::function<void(int)> onSelect;

View File

@@ -317,7 +317,6 @@ void KOReaderSyncActivity::render() {
localProgress.percentage * 100); localProgress.percentage * 100);
renderer.drawText(UI_10_FONT_ID, 20, 320, localPageStr); renderer.drawText(UI_10_FONT_ID, 20, 320, localPageStr);
// Options
const int optionY = 350; const int optionY = 350;
const int optionHeight = 30; const int optionHeight = 30;
@@ -333,13 +332,8 @@ void KOReaderSyncActivity::render() {
} }
renderer.drawText(UI_10_FONT_ID, 20, optionY + optionHeight, "Upload local progress", selectedOption != 1); renderer.drawText(UI_10_FONT_ID, 20, optionY + optionHeight, "Upload local progress", selectedOption != 1);
// Cancel option // Bottom button hints: show Back and Select
if (selectedOption == 2) { const auto labels = mappedInput.mapLabels("Back", "Select", "", "");
renderer.fillRect(0, optionY + optionHeight * 2 - 2, pageWidth - 1, optionHeight);
}
renderer.drawText(UI_10_FONT_ID, 20, optionY + optionHeight * 2, "Cancel", selectedOption != 2);
const auto labels = mappedInput.mapLabels("", "Select", "", "");
GUI.drawButtonHints(renderer, labels.btn1, labels.btn2, labels.btn3, labels.btn4); GUI.drawButtonHints(renderer, labels.btn1, labels.btn2, labels.btn3, labels.btn4);
renderer.displayBuffer(); renderer.displayBuffer();
return; return;
@@ -349,7 +343,7 @@ void KOReaderSyncActivity::render() {
renderer.drawCenteredText(UI_10_FONT_ID, 280, "No remote progress found", true, EpdFontFamily::BOLD); renderer.drawCenteredText(UI_10_FONT_ID, 280, "No remote progress found", true, EpdFontFamily::BOLD);
renderer.drawCenteredText(UI_10_FONT_ID, 320, "Upload current position?"); renderer.drawCenteredText(UI_10_FONT_ID, 320, "Upload current position?");
const auto labels = mappedInput.mapLabels("Cancel", "Upload", "", ""); const auto labels = mappedInput.mapLabels("Back", "Upload", "", "");
GUI.drawButtonHints(renderer, labels.btn1, labels.btn2, labels.btn3, labels.btn4); GUI.drawButtonHints(renderer, labels.btn1, labels.btn2, labels.btn3, labels.btn4);
renderer.displayBuffer(); renderer.displayBuffer();
return; return;
@@ -392,11 +386,11 @@ void KOReaderSyncActivity::loop() {
// Navigate options // Navigate options
if (mappedInput.wasPressed(MappedInputManager::Button::Up) || if (mappedInput.wasPressed(MappedInputManager::Button::Up) ||
mappedInput.wasPressed(MappedInputManager::Button::Left)) { mappedInput.wasPressed(MappedInputManager::Button::Left)) {
selectedOption = (selectedOption + 2) % 3; // Wrap around selectedOption = (selectedOption + 1) % 2; // Wrap around among 2 options
updateRequired = true; updateRequired = true;
} else if (mappedInput.wasPressed(MappedInputManager::Button::Down) || } else if (mappedInput.wasPressed(MappedInputManager::Button::Down) ||
mappedInput.wasPressed(MappedInputManager::Button::Right)) { mappedInput.wasPressed(MappedInputManager::Button::Right)) {
selectedOption = (selectedOption + 1) % 3; selectedOption = (selectedOption + 1) % 2; // Wrap around among 2 options
updateRequired = true; updateRequired = true;
} }
@@ -407,9 +401,6 @@ void KOReaderSyncActivity::loop() {
} else if (selectedOption == 1) { } else if (selectedOption == 1) {
// Upload local progress // Upload local progress
performUpload(); performUpload();
} else {
// Cancel
onCancel();
} }
} }

View File

@@ -18,7 +18,7 @@
* 1. Connect to WiFi (if not connected) * 1. Connect to WiFi (if not connected)
* 2. Calculate document hash * 2. Calculate document hash
* 3. Fetch remote progress * 3. Fetch remote progress
* 4. Show comparison and options (Apply/Upload/Cancel) * 4. Show comparison and options (Apply/Upload)
* 5. Apply or upload progress * 5. Apply or upload progress
*/ */
class KOReaderSyncActivity final : public ActivityWithSubactivity { class KOReaderSyncActivity final : public ActivityWithSubactivity {
@@ -82,7 +82,7 @@ class KOReaderSyncActivity final : public ActivityWithSubactivity {
// Local progress as KOReader format (for display) // Local progress as KOReader format (for display)
KOReaderPosition localProgress; KOReaderPosition localProgress;
// Selection in result screen (0=Apply, 1=Upload, 2=Cancel) // Selection in result screen (0=Apply, 1=Upload)
int selectedOption = 0; int selectedOption = 0;
OnCancelCallback onCancel; OnCancelCallback onCancel;

View File

@@ -1,5 +1,7 @@
#include "ReaderActivity.h" #include "ReaderActivity.h"
#include <HalStorage.h>
#include "Epub.h" #include "Epub.h"
#include "EpubReaderActivity.h" #include "EpubReaderActivity.h"
#include "Txt.h" #include "Txt.h"
@@ -27,7 +29,7 @@ bool ReaderActivity::isTxtFile(const std::string& path) {
} }
std::unique_ptr<Epub> ReaderActivity::loadEpub(const std::string& path) { std::unique_ptr<Epub> ReaderActivity::loadEpub(const std::string& path) {
if (!SdMan.exists(path.c_str())) { if (!Storage.exists(path.c_str())) {
Serial.printf("[%lu] [ ] File does not exist: %s\n", millis(), path.c_str()); Serial.printf("[%lu] [ ] File does not exist: %s\n", millis(), path.c_str());
return nullptr; return nullptr;
} }
@@ -42,7 +44,7 @@ std::unique_ptr<Epub> ReaderActivity::loadEpub(const std::string& path) {
} }
std::unique_ptr<Xtc> ReaderActivity::loadXtc(const std::string& path) { std::unique_ptr<Xtc> ReaderActivity::loadXtc(const std::string& path) {
if (!SdMan.exists(path.c_str())) { if (!Storage.exists(path.c_str())) {
Serial.printf("[%lu] [ ] File does not exist: %s\n", millis(), path.c_str()); Serial.printf("[%lu] [ ] File does not exist: %s\n", millis(), path.c_str());
return nullptr; return nullptr;
} }
@@ -57,7 +59,7 @@ std::unique_ptr<Xtc> ReaderActivity::loadXtc(const std::string& path) {
} }
std::unique_ptr<Txt> ReaderActivity::loadTxt(const std::string& path) { std::unique_ptr<Txt> ReaderActivity::loadTxt(const std::string& path) {
if (!SdMan.exists(path.c_str())) { if (!Storage.exists(path.c_str())) {
Serial.printf("[%lu] [ ] File does not exist: %s\n", millis(), path.c_str()); Serial.printf("[%lu] [ ] File does not exist: %s\n", millis(), path.c_str());
return nullptr; return nullptr;
} }

View File

@@ -1,7 +1,7 @@
#include "TxtReaderActivity.h" #include "TxtReaderActivity.h"
#include <GfxRenderer.h> #include <GfxRenderer.h>
#include <SDCardManager.h> #include <HalStorage.h>
#include <Serialization.h> #include <Serialization.h>
#include <Utf8.h> #include <Utf8.h>
@@ -102,15 +102,15 @@ void TxtReaderActivity::loop() {
return; return;
} }
// Long press BACK (1s+) goes directly to home // Long press BACK (1s+) goes to file selection
if (mappedInput.isPressed(MappedInputManager::Button::Back) && mappedInput.getHeldTime() >= goHomeMs) { if (mappedInput.isPressed(MappedInputManager::Button::Back) && mappedInput.getHeldTime() >= goHomeMs) {
onGoHome(); onGoBack();
return; return;
} }
// Short press BACK goes to file selection // Short press BACK goes directly to home
if (mappedInput.wasReleased(MappedInputManager::Button::Back) && mappedInput.getHeldTime() < goHomeMs) { if (mappedInput.wasReleased(MappedInputManager::Button::Back) && mappedInput.getHeldTime() < goHomeMs) {
onGoBack(); onGoHome();
return; return;
} }
@@ -565,7 +565,7 @@ void TxtReaderActivity::renderStatusBar(const int orientedMarginRight, const int
void TxtReaderActivity::saveProgress() const { void TxtReaderActivity::saveProgress() const {
FsFile f; FsFile f;
if (SdMan.openFileForWrite("TRS", txt->getCachePath() + "/progress.bin", f)) { if (Storage.openFileForWrite("TRS", txt->getCachePath() + "/progress.bin", f)) {
uint8_t data[4]; uint8_t data[4];
data[0] = currentPage & 0xFF; data[0] = currentPage & 0xFF;
data[1] = (currentPage >> 8) & 0xFF; data[1] = (currentPage >> 8) & 0xFF;
@@ -578,7 +578,7 @@ void TxtReaderActivity::saveProgress() const {
void TxtReaderActivity::loadProgress() { void TxtReaderActivity::loadProgress() {
FsFile f; FsFile f;
if (SdMan.openFileForRead("TRS", txt->getCachePath() + "/progress.bin", f)) { if (Storage.openFileForRead("TRS", txt->getCachePath() + "/progress.bin", f)) {
uint8_t data[4]; uint8_t data[4];
if (f.read(data, 4) == 4) { if (f.read(data, 4) == 4) {
currentPage = data[0] + (data[1] << 8); currentPage = data[0] + (data[1] << 8);
@@ -609,7 +609,7 @@ bool TxtReaderActivity::loadPageIndexCache() {
std::string cachePath = txt->getCachePath() + "/index.bin"; std::string cachePath = txt->getCachePath() + "/index.bin";
FsFile f; FsFile f;
if (!SdMan.openFileForRead("TRS", cachePath, f)) { if (!Storage.openFileForRead("TRS", cachePath, f)) {
Serial.printf("[%lu] [TRS] No page index cache found\n", millis()); Serial.printf("[%lu] [TRS] No page index cache found\n", millis());
return false; return false;
} }
@@ -701,7 +701,7 @@ bool TxtReaderActivity::loadPageIndexCache() {
void TxtReaderActivity::savePageIndexCache() const { void TxtReaderActivity::savePageIndexCache() const {
std::string cachePath = txt->getCachePath() + "/index.bin"; std::string cachePath = txt->getCachePath() + "/index.bin";
FsFile f; FsFile f;
if (!SdMan.openFileForWrite("TRS", cachePath, f)) { if (!Storage.openFileForWrite("TRS", cachePath, f)) {
Serial.printf("[%lu] [TRS] Failed to save page index cache\n", millis()); Serial.printf("[%lu] [TRS] Failed to save page index cache\n", millis());
return; return;
} }

View File

@@ -9,7 +9,7 @@
#include <FsHelpers.h> #include <FsHelpers.h>
#include <GfxRenderer.h> #include <GfxRenderer.h>
#include <SDCardManager.h> #include <HalStorage.h>
#include "CrossPointSettings.h" #include "CrossPointSettings.h"
#include "CrossPointState.h" #include "CrossPointState.h"
@@ -102,15 +102,15 @@ void XtcReaderActivity::loop() {
} }
} }
// Long press BACK (1s+) goes directly to home // Long press BACK (1s+) goes to file selection
if (mappedInput.isPressed(MappedInputManager::Button::Back) && mappedInput.getHeldTime() >= goHomeMs) { if (mappedInput.isPressed(MappedInputManager::Button::Back) && mappedInput.getHeldTime() >= goHomeMs) {
onGoHome(); onGoBack();
return; return;
} }
// Short press BACK goes to file selection // Short press BACK goes directly to home
if (mappedInput.wasReleased(MappedInputManager::Button::Back) && mappedInput.getHeldTime() < goHomeMs) { if (mappedInput.wasReleased(MappedInputManager::Button::Back) && mappedInput.getHeldTime() < goHomeMs) {
onGoBack(); onGoHome();
return; return;
} }
@@ -372,7 +372,7 @@ void XtcReaderActivity::renderPage() {
void XtcReaderActivity::saveProgress() const { void XtcReaderActivity::saveProgress() const {
FsFile f; FsFile f;
if (SdMan.openFileForWrite("XTR", xtc->getCachePath() + "/progress.bin", f)) { if (Storage.openFileForWrite("XTR", xtc->getCachePath() + "/progress.bin", f)) {
uint8_t data[4]; uint8_t data[4];
data[0] = currentPage & 0xFF; data[0] = currentPage & 0xFF;
data[1] = (currentPage >> 8) & 0xFF; data[1] = (currentPage >> 8) & 0xFF;
@@ -385,7 +385,7 @@ void XtcReaderActivity::saveProgress() const {
void XtcReaderActivity::loadProgress() { void XtcReaderActivity::loadProgress() {
FsFile f; FsFile f;
if (SdMan.openFileForRead("XTR", xtc->getCachePath() + "/progress.bin", f)) { if (Storage.openFileForRead("XTR", xtc->getCachePath() + "/progress.bin", f)) {
uint8_t data[4]; uint8_t data[4];
if (f.read(data, 4) == 4) { if (f.read(data, 4) == 4) {
currentPage = data[0] | (data[1] << 8) | (data[2] << 16) | (data[3] << 24); currentPage = data[0] | (data[1] << 8) | (data[2] << 16) | (data[3] << 24);

View File

@@ -8,10 +8,6 @@
#include "components/UITheme.h" #include "components/UITheme.h"
#include "fontIds.h" #include "fontIds.h"
namespace {
constexpr int SKIP_PAGE_MS = 700;
} // namespace
int XtcReaderChapterSelectionActivity::getPageItems() const { int XtcReaderChapterSelectionActivity::getPageItems() const {
constexpr int lineHeight = 30; constexpr int lineHeight = 30;
@@ -78,13 +74,8 @@ void XtcReaderChapterSelectionActivity::onExit() {
} }
void XtcReaderChapterSelectionActivity::loop() { void XtcReaderChapterSelectionActivity::loop() {
const bool prevReleased = mappedInput.wasReleased(MappedInputManager::Button::Up) ||
mappedInput.wasReleased(MappedInputManager::Button::Left);
const bool nextReleased = mappedInput.wasReleased(MappedInputManager::Button::Down) ||
mappedInput.wasReleased(MappedInputManager::Button::Right);
const bool skipPage = mappedInput.getHeldTime() > SKIP_PAGE_MS;
const int pageItems = getPageItems(); const int pageItems = getPageItems();
const int totalItems = static_cast<int>(xtc->getChapters().size());
if (mappedInput.wasReleased(MappedInputManager::Button::Confirm)) { if (mappedInput.wasReleased(MappedInputManager::Button::Confirm)) {
const auto& chapters = xtc->getChapters(); const auto& chapters = xtc->getChapters();
@@ -93,29 +84,27 @@ void XtcReaderChapterSelectionActivity::loop() {
} }
} else if (mappedInput.wasReleased(MappedInputManager::Button::Back)) { } else if (mappedInput.wasReleased(MappedInputManager::Button::Back)) {
onGoBack(); onGoBack();
} else if (prevReleased) {
const int total = static_cast<int>(xtc->getChapters().size());
if (total == 0) {
return;
}
if (skipPage) {
selectorIndex = ((selectorIndex / pageItems - 1) * pageItems + total) % total;
} else {
selectorIndex = (selectorIndex + total - 1) % total;
}
updateRequired = true;
} else if (nextReleased) {
const int total = static_cast<int>(xtc->getChapters().size());
if (total == 0) {
return;
}
if (skipPage) {
selectorIndex = ((selectorIndex / pageItems + 1) * pageItems) % total;
} else {
selectorIndex = (selectorIndex + 1) % total;
}
updateRequired = true;
} }
buttonNavigator.onNextRelease([this, totalItems] {
selectorIndex = ButtonNavigator::nextIndex(selectorIndex, totalItems);
updateRequired = true;
});
buttonNavigator.onPreviousRelease([this, totalItems] {
selectorIndex = ButtonNavigator::previousIndex(selectorIndex, totalItems);
updateRequired = true;
});
buttonNavigator.onNextContinuous([this, totalItems, pageItems] {
selectorIndex = ButtonNavigator::nextPageIndex(selectorIndex, totalItems, pageItems);
updateRequired = true;
});
buttonNavigator.onPreviousContinuous([this, totalItems, pageItems] {
selectorIndex = ButtonNavigator::previousPageIndex(selectorIndex, totalItems, pageItems);
updateRequired = true;
});
} }
void XtcReaderChapterSelectionActivity::displayTaskLoop() { void XtcReaderChapterSelectionActivity::displayTaskLoop() {

View File

@@ -7,11 +7,13 @@
#include <memory> #include <memory>
#include "../Activity.h" #include "../Activity.h"
#include "util/ButtonNavigator.h"
class XtcReaderChapterSelectionActivity final : public Activity { class XtcReaderChapterSelectionActivity final : public Activity {
std::shared_ptr<Xtc> xtc; std::shared_ptr<Xtc> xtc;
TaskHandle_t displayTaskHandle = nullptr; TaskHandle_t displayTaskHandle = nullptr;
SemaphoreHandle_t renderingMutex = nullptr; SemaphoreHandle_t renderingMutex = nullptr;
ButtonNavigator buttonNavigator;
uint32_t currentPage = 0; uint32_t currentPage = 0;
int selectorIndex = 0; int selectorIndex = 0;
bool updateRequired = false; bool updateRequired = false;

View File

@@ -63,15 +63,16 @@ void CalibreSettingsActivity::loop() {
return; return;
} }
if (mappedInput.wasPressed(MappedInputManager::Button::Up) || // Handle navigation
mappedInput.wasPressed(MappedInputManager::Button::Left)) { buttonNavigator.onNext([this] {
selectedIndex = (selectedIndex + MENU_ITEMS - 1) % MENU_ITEMS;
updateRequired = true;
} else if (mappedInput.wasPressed(MappedInputManager::Button::Down) ||
mappedInput.wasPressed(MappedInputManager::Button::Right)) {
selectedIndex = (selectedIndex + 1) % MENU_ITEMS; selectedIndex = (selectedIndex + 1) % MENU_ITEMS;
updateRequired = true; updateRequired = true;
} });
buttonNavigator.onPrevious([this] {
selectedIndex = (selectedIndex + MENU_ITEMS - 1) % MENU_ITEMS;
updateRequired = true;
});
} }
void CalibreSettingsActivity::handleSelection() { void CalibreSettingsActivity::handleSelection() {

View File

@@ -6,6 +6,7 @@
#include <functional> #include <functional>
#include "activities/ActivityWithSubactivity.h" #include "activities/ActivityWithSubactivity.h"
#include "util/ButtonNavigator.h"
/** /**
* Submenu for OPDS Browser settings. * Submenu for OPDS Browser settings.
@@ -24,6 +25,7 @@ class CalibreSettingsActivity final : public ActivityWithSubactivity {
private: private:
TaskHandle_t displayTaskHandle = nullptr; TaskHandle_t displayTaskHandle = nullptr;
SemaphoreHandle_t renderingMutex = nullptr; SemaphoreHandle_t renderingMutex = nullptr;
ButtonNavigator buttonNavigator;
bool updateRequired = false; bool updateRequired = false;
int selectedIndex = 0; int selectedIndex = 0;

View File

@@ -1,8 +1,8 @@
#include "ClearCacheActivity.h" #include "ClearCacheActivity.h"
#include <GfxRenderer.h> #include <GfxRenderer.h>
#include <HalStorage.h>
#include <HardwareSerial.h> #include <HardwareSerial.h>
#include <SDCardManager.h>
#include "MappedInputManager.h" #include "MappedInputManager.h"
#include "components/UITheme.h" #include "components/UITheme.h"
@@ -107,7 +107,7 @@ void ClearCacheActivity::clearCache() {
Serial.printf("[%lu] [CLEAR_CACHE] Clearing cache...\n", millis()); Serial.printf("[%lu] [CLEAR_CACHE] Clearing cache...\n", millis());
// Open .crosspoint directory // Open .crosspoint directory
auto root = SdMan.open("/.crosspoint"); auto root = Storage.open("/.crosspoint");
if (!root || !root.isDirectory()) { if (!root || !root.isDirectory()) {
Serial.printf("[%lu] [CLEAR_CACHE] Failed to open cache directory\n", millis()); Serial.printf("[%lu] [CLEAR_CACHE] Failed to open cache directory\n", millis());
if (root) root.close(); if (root) root.close();
@@ -132,7 +132,7 @@ void ClearCacheActivity::clearCache() {
file.close(); // Close before attempting to delete file.close(); // Close before attempting to delete
if (SdMan.removeDir(fullPath.c_str())) { if (Storage.removeDir(fullPath.c_str())) {
clearedCount++; clearedCount++;
} else { } else {
Serial.printf("[%lu] [CLEAR_CACHE] Failed to remove: %s\n", millis(), fullPath.c_str()); Serial.printf("[%lu] [CLEAR_CACHE] Failed to remove: %s\n", millis(), fullPath.c_str());

View File

@@ -64,15 +64,16 @@ void KOReaderSettingsActivity::loop() {
return; return;
} }
if (mappedInput.wasPressed(MappedInputManager::Button::Up) || // Handle navigation
mappedInput.wasPressed(MappedInputManager::Button::Left)) { buttonNavigator.onNext([this] {
selectedIndex = (selectedIndex + MENU_ITEMS - 1) % MENU_ITEMS;
updateRequired = true;
} else if (mappedInput.wasPressed(MappedInputManager::Button::Down) ||
mappedInput.wasPressed(MappedInputManager::Button::Right)) {
selectedIndex = (selectedIndex + 1) % MENU_ITEMS; selectedIndex = (selectedIndex + 1) % MENU_ITEMS;
updateRequired = true; updateRequired = true;
} });
buttonNavigator.onPrevious([this] {
selectedIndex = (selectedIndex + MENU_ITEMS - 1) % MENU_ITEMS;
updateRequired = true;
});
} }
void KOReaderSettingsActivity::handleSelection() { void KOReaderSettingsActivity::handleSelection() {

View File

@@ -6,6 +6,7 @@
#include <functional> #include <functional>
#include "activities/ActivityWithSubactivity.h" #include "activities/ActivityWithSubactivity.h"
#include "util/ButtonNavigator.h"
/** /**
* Submenu for KOReader Sync settings. * Submenu for KOReader Sync settings.
@@ -24,6 +25,7 @@ class KOReaderSettingsActivity final : public ActivityWithSubactivity {
private: private:
TaskHandle_t displayTaskHandle = nullptr; TaskHandle_t displayTaskHandle = nullptr;
SemaphoreHandle_t renderingMutex = nullptr; SemaphoreHandle_t renderingMutex = nullptr;
ButtonNavigator buttonNavigator;
bool updateRequired = false; bool updateRequired = false;
int selectedIndex = 0; int selectedIndex = 0;

View File

@@ -10,63 +10,13 @@
#include "KOReaderSettingsActivity.h" #include "KOReaderSettingsActivity.h"
#include "MappedInputManager.h" #include "MappedInputManager.h"
#include "OtaUpdateActivity.h" #include "OtaUpdateActivity.h"
#include "SettingsList.h"
#include "activities/network/WifiSelectionActivity.h"
#include "components/UITheme.h" #include "components/UITheme.h"
#include "fontIds.h" #include "fontIds.h"
const char* SettingsActivity::categoryNames[categoryCount] = {"Display", "Reader", "Controls", "System"}; const char* SettingsActivity::categoryNames[categoryCount] = {"Display", "Reader", "Controls", "System"};
namespace {
constexpr int changeTabsMs = 700;
constexpr int displaySettingsCount = 8;
const SettingInfo displaySettings[displaySettingsCount] = {
// Should match with SLEEP_SCREEN_MODE
SettingInfo::Enum("Sleep Screen", &CrossPointSettings::sleepScreen,
{"Dark", "Light", "Custom", "Cover", "None", "Cover + Custom"}),
SettingInfo::Enum("Sleep Screen Cover Mode", &CrossPointSettings::sleepScreenCoverMode, {"Fit", "Crop"}),
SettingInfo::Enum("Sleep Screen Cover Filter", &CrossPointSettings::sleepScreenCoverFilter,
{"None", "Contrast", "Inverted"}),
SettingInfo::Enum(
"Status Bar", &CrossPointSettings::statusBar,
{"None", "No Progress", "Full w/ Percentage", "Full w/ Book Bar", "Book Bar Only", "Full w/ Chapter Bar"}),
SettingInfo::Enum("Hide Battery %", &CrossPointSettings::hideBatteryPercentage, {"Never", "In Reader", "Always"}),
SettingInfo::Enum("Refresh Frequency", &CrossPointSettings::refreshFrequency,
{"1 page", "5 pages", "10 pages", "15 pages", "30 pages"}),
SettingInfo::Enum("UI Theme", &CrossPointSettings::uiTheme, {"Classic", "Lyra"}),
SettingInfo::Toggle("Sunlight Fading Fix", &CrossPointSettings::fadingFix),
};
constexpr int readerSettingsCount = 10;
const SettingInfo readerSettings[readerSettingsCount] = {
SettingInfo::Enum("Font Family", &CrossPointSettings::fontFamily, {"Bookerly", "Noto Sans", "Open Dyslexic"}),
SettingInfo::Enum("Font Size", &CrossPointSettings::fontSize, {"Small", "Medium", "Large", "X Large"}),
SettingInfo::Enum("Line Spacing", &CrossPointSettings::lineSpacing, {"Tight", "Normal", "Wide"}),
SettingInfo::Value("Screen Margin", &CrossPointSettings::screenMargin, {5, 40, 5}),
SettingInfo::Enum("Paragraph Alignment", &CrossPointSettings::paragraphAlignment,
{"Justify", "Left", "Center", "Right", "Book's Style"}),
SettingInfo::Toggle("Book's Embedded Style", &CrossPointSettings::embeddedStyle),
SettingInfo::Toggle("Hyphenation", &CrossPointSettings::hyphenationEnabled),
SettingInfo::Enum("Reading Orientation", &CrossPointSettings::orientation,
{"Portrait", "Landscape CW", "Inverted", "Landscape CCW"}),
SettingInfo::Toggle("Extra Paragraph Spacing", &CrossPointSettings::extraParagraphSpacing),
SettingInfo::Toggle("Text Anti-Aliasing", &CrossPointSettings::textAntiAliasing)};
constexpr int controlsSettingsCount = 4;
const SettingInfo controlsSettings[controlsSettingsCount] = {
// Launches the remap wizard for front buttons.
SettingInfo::Action("Remap Front Buttons"),
SettingInfo::Enum("Side Button Layout (reader)", &CrossPointSettings::sideButtonLayout,
{"Prev, Next", "Next, Prev"}),
SettingInfo::Toggle("Long-press Chapter Skip", &CrossPointSettings::longPressChapterSkip),
SettingInfo::Enum("Short Power Button Click", &CrossPointSettings::shortPwrBtn, {"Ignore", "Sleep", "Page Turn"})};
constexpr int systemSettingsCount = 5;
const SettingInfo systemSettings[systemSettingsCount] = {
SettingInfo::Enum("Time to Sleep", &CrossPointSettings::sleepTimeout,
{"1 min", "5 min", "10 min", "15 min", "30 min"}),
SettingInfo::Action("KOReader Sync"), SettingInfo::Action("OPDS Browser"), SettingInfo::Action("Clear Cache"),
SettingInfo::Action("Check for updates")};
} // namespace
void SettingsActivity::taskTrampoline(void* param) { void SettingsActivity::taskTrampoline(void* param) {
auto* self = static_cast<SettingsActivity*>(param); auto* self = static_cast<SettingsActivity*>(param);
self->displayTaskLoop(); self->displayTaskLoop();
@@ -76,13 +26,42 @@ void SettingsActivity::onEnter() {
Activity::onEnter(); Activity::onEnter();
renderingMutex = xSemaphoreCreateMutex(); renderingMutex = xSemaphoreCreateMutex();
// Build per-category vectors from the shared settings list
displaySettings.clear();
readerSettings.clear();
controlsSettings.clear();
systemSettings.clear();
for (auto& setting : getSettingsList()) {
if (!setting.category) continue;
if (strcmp(setting.category, "Display") == 0) {
displaySettings.push_back(std::move(setting));
} else if (strcmp(setting.category, "Reader") == 0) {
readerSettings.push_back(std::move(setting));
} else if (strcmp(setting.category, "Controls") == 0) {
controlsSettings.push_back(std::move(setting));
} else if (strcmp(setting.category, "System") == 0) {
systemSettings.push_back(std::move(setting));
}
// Web-only categories (KOReader Sync, OPDS Browser) are skipped for device UI
}
// Append device-only ACTION items
controlsSettings.insert(controlsSettings.begin(),
SettingInfo::Action("Remap Front Buttons", SettingAction::RemapFrontButtons));
systemSettings.push_back(SettingInfo::Action("Network", SettingAction::Network));
systemSettings.push_back(SettingInfo::Action("KOReader Sync", SettingAction::KOReaderSync));
systemSettings.push_back(SettingInfo::Action("OPDS Browser", SettingAction::OPDSBrowser));
systemSettings.push_back(SettingInfo::Action("Clear Cache", SettingAction::ClearCache));
systemSettings.push_back(SettingInfo::Action("Check for updates", SettingAction::CheckForUpdates));
// Reset selection to first category // Reset selection to first category
selectedCategoryIndex = 0; selectedCategoryIndex = 0;
selectedSettingIndex = 0; selectedSettingIndex = 0;
// Initialize with first category (Display) // Initialize with first category (Display)
settingsList = displaySettings; currentSettings = &displaySettings;
settingsCount = displaySettingsCount; settingsCount = static_cast<int>(displaySettings.size());
// Trigger first update // Trigger first update
updateRequired = true; updateRequired = true;
@@ -136,49 +115,46 @@ void SettingsActivity::loop() {
return; return;
} }
const bool upReleased = mappedInput.wasReleased(MappedInputManager::Button::Up);
const bool downReleased = mappedInput.wasReleased(MappedInputManager::Button::Down);
const bool leftReleased = mappedInput.wasReleased(MappedInputManager::Button::Left);
const bool rightReleased = mappedInput.wasReleased(MappedInputManager::Button::Right);
const bool changeTab = mappedInput.getHeldTime() > changeTabsMs;
// Handle navigation // Handle navigation
if (upReleased && changeTab) { buttonNavigator.onNextRelease([this] {
selectedSettingIndex = ButtonNavigator::nextIndex(selectedSettingIndex, settingsCount + 1);
updateRequired = true;
});
buttonNavigator.onPreviousRelease([this] {
selectedSettingIndex = ButtonNavigator::previousIndex(selectedSettingIndex, settingsCount + 1);
updateRequired = true;
});
buttonNavigator.onNextContinuous([this, &hasChangedCategory] {
hasChangedCategory = true; hasChangedCategory = true;
selectedCategoryIndex = (selectedCategoryIndex > 0) ? (selectedCategoryIndex - 1) : (categoryCount - 1); selectedCategoryIndex = ButtonNavigator::nextIndex(selectedCategoryIndex, categoryCount);
updateRequired = true; updateRequired = true;
} else if (downReleased && changeTab) { });
buttonNavigator.onPreviousContinuous([this, &hasChangedCategory] {
hasChangedCategory = true; hasChangedCategory = true;
selectedCategoryIndex = (selectedCategoryIndex < categoryCount - 1) ? (selectedCategoryIndex + 1) : 0; selectedCategoryIndex = ButtonNavigator::previousIndex(selectedCategoryIndex, categoryCount);
updateRequired = true; updateRequired = true;
} else if (upReleased || leftReleased) { });
selectedSettingIndex = (selectedSettingIndex > 0) ? (selectedSettingIndex - 1) : (settingsCount);
updateRequired = true;
} else if (rightReleased || downReleased) {
selectedSettingIndex = (selectedSettingIndex < settingsCount) ? (selectedSettingIndex + 1) : 0;
updateRequired = true;
}
if (hasChangedCategory) { if (hasChangedCategory) {
selectedSettingIndex = (selectedSettingIndex == 0) ? 0 : 1; selectedSettingIndex = (selectedSettingIndex == 0) ? 0 : 1;
switch (selectedCategoryIndex) { switch (selectedCategoryIndex) {
case 0: // Display case 0:
settingsList = displaySettings; currentSettings = &displaySettings;
settingsCount = displaySettingsCount;
break; break;
case 1: // Reader case 1:
settingsList = readerSettings; currentSettings = &readerSettings;
settingsCount = readerSettingsCount;
break; break;
case 2: // Controls case 2:
settingsList = controlsSettings; currentSettings = &controlsSettings;
settingsCount = controlsSettingsCount;
break; break;
case 3: // System case 3:
settingsList = systemSettings; currentSettings = &systemSettings;
settingsCount = systemSettingsCount;
break; break;
} }
settingsCount = static_cast<int>(currentSettings->size());
} }
} }
@@ -188,7 +164,7 @@ void SettingsActivity::toggleCurrentSetting() {
return; return;
} }
const auto& setting = settingsList[selectedSetting]; const auto& setting = (*currentSettings)[selectedSetting];
if (setting.type == SettingType::TOGGLE && setting.valuePtr != nullptr) { if (setting.type == SettingType::TOGGLE && setting.valuePtr != nullptr) {
// Toggle the boolean value using the member pointer // Toggle the boolean value using the member pointer
@@ -205,46 +181,45 @@ void SettingsActivity::toggleCurrentSetting() {
SETTINGS.*(setting.valuePtr) = currentValue + setting.valueRange.step; SETTINGS.*(setting.valuePtr) = currentValue + setting.valueRange.step;
} }
} else if (setting.type == SettingType::ACTION) { } else if (setting.type == SettingType::ACTION) {
if (strcmp(setting.name, "Remap Front Buttons") == 0) { auto enterSubActivity = [this](Activity* activity) {
xSemaphoreTake(renderingMutex, portMAX_DELAY); xSemaphoreTake(renderingMutex, portMAX_DELAY);
exitActivity(); exitActivity();
enterNewActivity(new ButtonRemapActivity(renderer, mappedInput, [this] { enterNewActivity(activity);
exitActivity();
updateRequired = true;
}));
xSemaphoreGive(renderingMutex); xSemaphoreGive(renderingMutex);
} else if (strcmp(setting.name, "KOReader Sync") == 0) { };
xSemaphoreTake(renderingMutex, portMAX_DELAY);
auto onComplete = [this] {
exitActivity(); exitActivity();
enterNewActivity(new KOReaderSettingsActivity(renderer, mappedInput, [this] { updateRequired = true;
exitActivity(); };
updateRequired = true;
})); auto onCompleteBool = [this](bool) {
xSemaphoreGive(renderingMutex);
} else if (strcmp(setting.name, "OPDS Browser") == 0) {
xSemaphoreTake(renderingMutex, portMAX_DELAY);
exitActivity(); exitActivity();
enterNewActivity(new CalibreSettingsActivity(renderer, mappedInput, [this] { updateRequired = true;
exitActivity(); };
updateRequired = true;
})); switch (setting.action) {
xSemaphoreGive(renderingMutex); case SettingAction::RemapFrontButtons:
} else if (strcmp(setting.name, "Clear Cache") == 0) { enterSubActivity(new ButtonRemapActivity(renderer, mappedInput, onComplete));
xSemaphoreTake(renderingMutex, portMAX_DELAY); break;
exitActivity(); case SettingAction::KOReaderSync:
enterNewActivity(new ClearCacheActivity(renderer, mappedInput, [this] { enterSubActivity(new KOReaderSettingsActivity(renderer, mappedInput, onComplete));
exitActivity(); break;
updateRequired = true; case SettingAction::OPDSBrowser:
})); enterSubActivity(new CalibreSettingsActivity(renderer, mappedInput, onComplete));
xSemaphoreGive(renderingMutex); break;
} else if (strcmp(setting.name, "Check for updates") == 0) { case SettingAction::Network:
xSemaphoreTake(renderingMutex, portMAX_DELAY); enterSubActivity(new WifiSelectionActivity(renderer, mappedInput, onCompleteBool, false));
exitActivity(); break;
enterNewActivity(new OtaUpdateActivity(renderer, mappedInput, [this] { case SettingAction::ClearCache:
exitActivity(); enterSubActivity(new ClearCacheActivity(renderer, mappedInput, onComplete));
updateRequired = true; break;
})); case SettingAction::CheckForUpdates:
xSemaphoreGive(renderingMutex); enterSubActivity(new OtaUpdateActivity(renderer, mappedInput, onComplete));
break;
case SettingAction::None:
// Do nothing
break;
} }
} else { } else {
return; return;
@@ -283,24 +258,24 @@ void SettingsActivity::render() const {
GUI.drawTabBar(renderer, Rect{0, metrics.topPadding + metrics.headerHeight, pageWidth, metrics.tabBarHeight}, tabs, GUI.drawTabBar(renderer, Rect{0, metrics.topPadding + metrics.headerHeight, pageWidth, metrics.tabBarHeight}, tabs,
selectedSettingIndex == 0); selectedSettingIndex == 0);
const auto& settings = *currentSettings;
GUI.drawList( GUI.drawList(
renderer, renderer,
Rect{0, metrics.topPadding + metrics.headerHeight + metrics.tabBarHeight + metrics.verticalSpacing, pageWidth, Rect{0, metrics.topPadding + metrics.headerHeight + metrics.tabBarHeight + metrics.verticalSpacing, pageWidth,
pageHeight - (metrics.topPadding + metrics.headerHeight + metrics.tabBarHeight + metrics.buttonHintsHeight + pageHeight - (metrics.topPadding + metrics.headerHeight + metrics.tabBarHeight + metrics.buttonHintsHeight +
metrics.verticalSpacing * 2)}, metrics.verticalSpacing * 2)},
settingsCount, selectedSettingIndex - 1, [this](int index) { return std::string(settingsList[index].name); }, settingsCount, selectedSettingIndex - 1, [&settings](int index) { return std::string(settings[index].name); },
nullptr, nullptr, nullptr, nullptr,
[this](int i) { [&settings](int i) {
const auto& setting = settingsList[i];
std::string valueText = ""; std::string valueText = "";
if (settingsList[i].type == SettingType::TOGGLE && settingsList[i].valuePtr != nullptr) { if (settings[i].type == SettingType::TOGGLE && settings[i].valuePtr != nullptr) {
const bool value = SETTINGS.*(settingsList[i].valuePtr); const bool value = SETTINGS.*(settings[i].valuePtr);
valueText = value ? "ON" : "OFF"; valueText = value ? "ON" : "OFF";
} else if (settingsList[i].type == SettingType::ENUM && settingsList[i].valuePtr != nullptr) { } else if (settings[i].type == SettingType::ENUM && settings[i].valuePtr != nullptr) {
const uint8_t value = SETTINGS.*(settingsList[i].valuePtr); const uint8_t value = SETTINGS.*(settings[i].valuePtr);
valueText = settingsList[i].enumValues[value]; valueText = settings[i].enumValues[value];
} else if (settingsList[i].type == SettingType::VALUE && settingsList[i].valuePtr != nullptr) { } else if (settings[i].type == SettingType::VALUE && settings[i].valuePtr != nullptr) {
valueText = std::to_string(SETTINGS.*(settingsList[i].valuePtr)); valueText = std::to_string(SETTINGS.*(settings[i].valuePtr));
} }
return valueText; return valueText;
}); });

View File

@@ -8,47 +8,147 @@
#include <vector> #include <vector>
#include "activities/ActivityWithSubactivity.h" #include "activities/ActivityWithSubactivity.h"
#include "util/ButtonNavigator.h"
class CrossPointSettings; class CrossPointSettings;
enum class SettingType { TOGGLE, ENUM, ACTION, VALUE }; enum class SettingType { TOGGLE, ENUM, ACTION, VALUE, STRING };
enum class SettingAction {
None,
RemapFrontButtons,
KOReaderSync,
OPDSBrowser,
Network,
ClearCache,
CheckForUpdates,
};
struct SettingInfo { struct SettingInfo {
const char* name; const char* name;
SettingType type; SettingType type;
uint8_t CrossPointSettings::* valuePtr; uint8_t CrossPointSettings::* valuePtr = nullptr;
std::vector<std::string> enumValues; std::vector<std::string> enumValues;
SettingAction action = SettingAction::None;
struct ValueRange { struct ValueRange {
uint8_t min; uint8_t min;
uint8_t max; uint8_t max;
uint8_t step; uint8_t step;
}; };
ValueRange valueRange; ValueRange valueRange = {};
static SettingInfo Toggle(const char* name, uint8_t CrossPointSettings::* ptr) { const char* key = nullptr; // JSON API key (nullptr for ACTION types)
return {name, SettingType::TOGGLE, ptr}; const char* category = nullptr; // Category for web UI grouping
// Direct char[] string fields (for settings stored in CrossPointSettings)
char* stringPtr = nullptr;
size_t stringMaxLen = 0;
// Dynamic accessors (for settings stored outside CrossPointSettings, e.g. KOReaderCredentialStore)
std::function<uint8_t()> valueGetter;
std::function<void(uint8_t)> valueSetter;
std::function<std::string()> stringGetter;
std::function<void(const std::string&)> stringSetter;
static SettingInfo Toggle(const char* name, uint8_t CrossPointSettings::* ptr, const char* key = nullptr,
const char* category = nullptr) {
SettingInfo s;
s.name = name;
s.type = SettingType::TOGGLE;
s.valuePtr = ptr;
s.key = key;
s.category = category;
return s;
} }
static SettingInfo Enum(const char* name, uint8_t CrossPointSettings::* ptr, std::vector<std::string> values) { static SettingInfo Enum(const char* name, uint8_t CrossPointSettings::* ptr, std::vector<std::string> values,
return {name, SettingType::ENUM, ptr, std::move(values)}; const char* key = nullptr, const char* category = nullptr) {
SettingInfo s;
s.name = name;
s.type = SettingType::ENUM;
s.valuePtr = ptr;
s.enumValues = std::move(values);
s.key = key;
s.category = category;
return s;
} }
static SettingInfo Action(const char* name) { return {name, SettingType::ACTION, nullptr}; } static SettingInfo Action(const char* name, SettingAction action) {
SettingInfo s;
s.name = name;
s.type = SettingType::ACTION;
s.action = action;
return s;
}
static SettingInfo Value(const char* name, uint8_t CrossPointSettings::* ptr, const ValueRange valueRange) { static SettingInfo Value(const char* name, uint8_t CrossPointSettings::* ptr, const ValueRange valueRange,
return {name, SettingType::VALUE, ptr, {}, valueRange}; const char* key = nullptr, const char* category = nullptr) {
SettingInfo s;
s.name = name;
s.type = SettingType::VALUE;
s.valuePtr = ptr;
s.valueRange = valueRange;
s.key = key;
s.category = category;
return s;
}
static SettingInfo String(const char* name, char* ptr, size_t maxLen, const char* key = nullptr,
const char* category = nullptr) {
SettingInfo s;
s.name = name;
s.type = SettingType::STRING;
s.stringPtr = ptr;
s.stringMaxLen = maxLen;
s.key = key;
s.category = category;
return s;
}
static SettingInfo DynamicEnum(const char* name, std::vector<std::string> values, std::function<uint8_t()> getter,
std::function<void(uint8_t)> setter, const char* key = nullptr,
const char* category = nullptr) {
SettingInfo s;
s.name = name;
s.type = SettingType::ENUM;
s.enumValues = std::move(values);
s.valueGetter = std::move(getter);
s.valueSetter = std::move(setter);
s.key = key;
s.category = category;
return s;
}
static SettingInfo DynamicString(const char* name, std::function<std::string()> getter,
std::function<void(const std::string&)> setter, const char* key = nullptr,
const char* category = nullptr) {
SettingInfo s;
s.name = name;
s.type = SettingType::STRING;
s.stringGetter = std::move(getter);
s.stringSetter = std::move(setter);
s.key = key;
s.category = category;
return s;
} }
}; };
class SettingsActivity final : public ActivityWithSubactivity { class SettingsActivity final : public ActivityWithSubactivity {
TaskHandle_t displayTaskHandle = nullptr; TaskHandle_t displayTaskHandle = nullptr;
SemaphoreHandle_t renderingMutex = nullptr; SemaphoreHandle_t renderingMutex = nullptr;
ButtonNavigator buttonNavigator;
bool updateRequired = false; bool updateRequired = false;
int selectedCategoryIndex = 0; // Currently selected category int selectedCategoryIndex = 0; // Currently selected category
int selectedSettingIndex = 0; int selectedSettingIndex = 0;
int settingsCount = 0; int settingsCount = 0;
const SettingInfo* settingsList = nullptr;
// Per-category settings derived from shared list + device-only actions
std::vector<SettingInfo> displaySettings;
std::vector<SettingInfo> readerSettings;
std::vector<SettingInfo> controlsSettings;
std::vector<SettingInfo> systemSettings;
const std::vector<SettingInfo>* currentSettings = nullptr;
const std::function<void()> onGoHome; const std::function<void()> onGoHome;

View File

@@ -142,37 +142,24 @@ void KeyboardEntryActivity::handleKeyPress() {
} }
void KeyboardEntryActivity::loop() { void KeyboardEntryActivity::loop() {
// Navigation // Handle navigation
if (mappedInput.wasPressed(MappedInputManager::Button::Up)) { buttonNavigator.onPressAndContinuous({MappedInputManager::Button::Up}, [this] {
if (selectedRow > 0) { selectedRow = ButtonNavigator::previousIndex(selectedRow, NUM_ROWS);
selectedRow--;
// Clamp column to valid range for new row
const int maxCol = getRowLength(selectedRow) - 1;
if (selectedCol > maxCol) selectedCol = maxCol;
} else {
// Wrap to bottom row
selectedRow = NUM_ROWS - 1;
const int maxCol = getRowLength(selectedRow) - 1;
if (selectedCol > maxCol) selectedCol = maxCol;
}
updateRequired = true;
}
if (mappedInput.wasPressed(MappedInputManager::Button::Down)) { const int maxCol = getRowLength(selectedRow) - 1;
if (selectedRow < NUM_ROWS - 1) { if (selectedCol > maxCol) selectedCol = maxCol;
selectedRow++;
const int maxCol = getRowLength(selectedRow) - 1;
if (selectedCol > maxCol) selectedCol = maxCol;
} else {
// Wrap to top row
selectedRow = 0;
const int maxCol = getRowLength(selectedRow) - 1;
if (selectedCol > maxCol) selectedCol = maxCol;
}
updateRequired = true; updateRequired = true;
} });
if (mappedInput.wasPressed(MappedInputManager::Button::Left)) { buttonNavigator.onPressAndContinuous({MappedInputManager::Button::Down}, [this] {
selectedRow = ButtonNavigator::nextIndex(selectedRow, NUM_ROWS);
const int maxCol = getRowLength(selectedRow) - 1;
if (selectedCol > maxCol) selectedCol = maxCol;
updateRequired = true;
});
buttonNavigator.onPressAndContinuous({MappedInputManager::Button::Left}, [this] {
const int maxCol = getRowLength(selectedRow) - 1; const int maxCol = getRowLength(selectedRow) - 1;
// Special bottom row case // Special bottom row case
@@ -191,20 +178,14 @@ void KeyboardEntryActivity::loop() {
// At done button, move to backspace // At done button, move to backspace
selectedCol = BACKSPACE_COL; selectedCol = BACKSPACE_COL;
} }
updateRequired = true;
return;
}
if (selectedCol > 0) {
selectedCol--;
} else { } else {
// Wrap to end of current row selectedCol = ButtonNavigator::previousIndex(selectedCol, maxCol + 1);
selectedCol = maxCol;
} }
updateRequired = true;
}
if (mappedInput.wasPressed(MappedInputManager::Button::Right)) { updateRequired = true;
});
buttonNavigator.onPressAndContinuous({MappedInputManager::Button::Right}, [this] {
const int maxCol = getRowLength(selectedRow) - 1; const int maxCol = getRowLength(selectedRow) - 1;
// Special bottom row case // Special bottom row case
@@ -223,18 +204,11 @@ void KeyboardEntryActivity::loop() {
// At done button, wrap to beginning of row // At done button, wrap to beginning of row
selectedCol = SHIFT_COL; selectedCol = SHIFT_COL;
} }
updateRequired = true;
return;
}
if (selectedCol < maxCol) {
selectedCol++;
} else { } else {
// Wrap to beginning of current row selectedCol = ButtonNavigator::nextIndex(selectedCol, maxCol + 1);
selectedCol = 0;
} }
updateRequired = true; updateRequired = true;
} });
// Selection // Selection
if (mappedInput.wasPressed(MappedInputManager::Button::Confirm)) { if (mappedInput.wasPressed(MappedInputManager::Button::Confirm)) {

View File

@@ -9,6 +9,7 @@
#include <utility> #include <utility>
#include "../Activity.h" #include "../Activity.h"
#include "util/ButtonNavigator.h"
/** /**
* Reusable keyboard entry activity for text input. * Reusable keyboard entry activity for text input.
@@ -65,6 +66,7 @@ class KeyboardEntryActivity : public Activity {
bool isPassword; bool isPassword;
TaskHandle_t displayTaskHandle = nullptr; TaskHandle_t displayTaskHandle = nullptr;
SemaphoreHandle_t renderingMutex = nullptr; SemaphoreHandle_t renderingMutex = nullptr;
ButtonNavigator buttonNavigator;
bool updateRequired = false; bool updateRequired = false;
// Keyboard state // Keyboard state

View File

@@ -1,7 +1,7 @@
#include "BaseTheme.h" #include "BaseTheme.h"
#include <GfxRenderer.h> #include <GfxRenderer.h>
#include <SDCardManager.h> #include <HalStorage.h>
#include <Utf8.h> #include <Utf8.h>
#include <cstdint> #include <cstdint>
@@ -308,7 +308,7 @@ void BaseTheme::drawRecentBookCover(GfxRenderer& renderer, Rect rect, const std:
// First time: load cover from SD and render // First time: load cover from SD and render
FsFile file; FsFile file;
if (SdMan.openFileForRead("HOME", coverBmpPath, file)) { if (Storage.openFileForRead("HOME", coverBmpPath, file)) {
Bitmap bitmap(file); Bitmap bitmap(file);
if (bitmap.parseHeaders() == BmpReaderError::Ok) { if (bitmap.parseHeaders() == BmpReaderError::Ok) {
Serial.printf("Rendering bmp\n"); Serial.printf("Rendering bmp\n");

View File

@@ -1,7 +1,7 @@
#include "LyraTheme.h" #include "LyraTheme.h"
#include <GfxRenderer.h> #include <GfxRenderer.h>
#include <SDCardManager.h> #include <HalStorage.h>
#include <cstdint> #include <cstdint>
#include <string> #include <string>
@@ -283,7 +283,7 @@ void LyraTheme::drawRecentBookCover(GfxRenderer& renderer, Rect rect, const std:
// First time: load cover from SD and render // First time: load cover from SD and render
FsFile file; FsFile file;
if (SdMan.openFileForRead("HOME", coverBmpPath, file)) { if (Storage.openFileForRead("HOME", coverBmpPath, file)) {
Bitmap bitmap(file); Bitmap bitmap(file);
if (bitmap.parseHeaders() == BmpReaderError::Ok) { if (bitmap.parseHeaders() == BmpReaderError::Ok) {
float coverHeight = static_cast<float>(bitmap.getHeight()); float coverHeight = static_cast<float>(bitmap.getHeight());

View File

@@ -3,7 +3,7 @@
#include <GfxRenderer.h> #include <GfxRenderer.h>
#include <HalDisplay.h> #include <HalDisplay.h>
#include <HalGPIO.h> #include <HalGPIO.h>
#include <SDCardManager.h> #include <HalStorage.h>
#include <SPI.h> #include <SPI.h>
#include <builtinFonts/all.h> #include <builtinFonts/all.h>
@@ -27,6 +27,7 @@
#include "activities/util/FullScreenMessageActivity.h" #include "activities/util/FullScreenMessageActivity.h"
#include "components/UITheme.h" #include "components/UITheme.h"
#include "fontIds.h" #include "fontIds.h"
#include "util/ButtonNavigator.h"
HalDisplay display; HalDisplay display;
HalGPIO gpio; HalGPIO gpio;
@@ -293,7 +294,7 @@ void setup() {
// SD Card Initialization // SD Card Initialization
// We need 6 open files concurrently when parsing a new chapter // We need 6 open files concurrently when parsing a new chapter
if (!SdMan.begin()) { if (!Storage.begin()) {
Serial.printf("[%lu] [ ] SD card initialization failed\n", millis()); Serial.printf("[%lu] [ ] SD card initialization failed\n", millis());
setupDisplayAndFonts(); setupDisplayAndFonts();
exitActivity(); exitActivity();
@@ -304,6 +305,7 @@ void setup() {
SETTINGS.loadFromFile(); SETTINGS.loadFromFile();
KOREADER_STORE.loadFromFile(); KOREADER_STORE.loadFromFile();
UITheme::getInstance().reload(); UITheme::getInstance().reload();
ButtonNavigator::setMappedInputManager(mappedInputManager);
switch (gpio.getWakeupReason()) { switch (gpio.getWakeupReason()) {
case HalGPIO::WakeupReason::PowerButton: case HalGPIO::WakeupReason::PowerButton:
@@ -408,6 +410,13 @@ void loop() {
if (currentActivity && currentActivity->skipLoopDelay()) { if (currentActivity && currentActivity->skipLoopDelay()) {
yield(); // Give FreeRTOS a chance to run tasks, but return immediately yield(); // Give FreeRTOS a chance to run tasks, but return immediately
} else { } else {
delay(10); // Normal delay when no activity requires fast response static constexpr unsigned long IDLE_POWER_SAVING_MS = 3000; // 3 seconds
if (millis() - lastActivityTime >= IDLE_POWER_SAVING_MS) {
// If we've been inactive for a while, increase the delay to save power
delay(50);
} else {
// Short delay to prevent tight loop while still being responsive
delay(10);
}
} }
} }

View File

@@ -3,14 +3,17 @@
#include <ArduinoJson.h> #include <ArduinoJson.h>
#include <Epub.h> #include <Epub.h>
#include <FsHelpers.h> #include <FsHelpers.h>
#include <SDCardManager.h> #include <HalStorage.h>
#include <WiFi.h> #include <WiFi.h>
#include <esp_task_wdt.h> #include <esp_task_wdt.h>
#include <algorithm> #include <algorithm>
#include "CrossPointSettings.h"
#include "SettingsList.h"
#include "html/FilesPageHtml.generated.h" #include "html/FilesPageHtml.generated.h"
#include "html/HomePageHtml.generated.h" #include "html/HomePageHtml.generated.h"
#include "html/SettingsPageHtml.generated.h"
#include "util/StringUtils.h" #include "util/StringUtils.h"
namespace { namespace {
@@ -148,6 +151,11 @@ void CrossPointWebServer::begin() {
// Delete file/folder endpoint // Delete file/folder endpoint
server->on("/delete", HTTP_POST, [this] { handleDelete(); }); server->on("/delete", HTTP_POST, [this] { handleDelete(); });
// Settings endpoints
server->on("/settings", HTTP_GET, [this] { handleSettingsPage(); });
server->on("/api/settings", HTTP_GET, [this] { handleGetSettings(); });
server->on("/api/settings", HTTP_POST, [this] { handlePostSettings(); });
server->onNotFound([this] { handleNotFound(); }); server->onNotFound([this] { handleNotFound(); });
Serial.printf("[%lu] [WEB] [MEM] Free heap after route setup: %d bytes\n", millis(), ESP.getFreeHeap()); Serial.printf("[%lu] [WEB] [MEM] Free heap after route setup: %d bytes\n", millis(), ESP.getFreeHeap());
@@ -316,7 +324,7 @@ void CrossPointWebServer::handleStatus() const {
} }
void CrossPointWebServer::scanFiles(const char* path, const std::function<void(FileInfo)>& callback) const { void CrossPointWebServer::scanFiles(const char* path, const std::function<void(FileInfo)>& callback) const {
FsFile root = SdMan.open(path); FsFile root = Storage.open(path);
if (!root) { if (!root) {
Serial.printf("[%lu] [WEB] Failed to open directory: %s\n", millis(), path); Serial.printf("[%lu] [WEB] Failed to open directory: %s\n", millis(), path);
return; return;
@@ -458,12 +466,12 @@ void CrossPointWebServer::handleDownload() const {
} }
} }
if (!SdMan.exists(itemPath.c_str())) { if (!Storage.exists(itemPath.c_str())) {
server->send(404, "text/plain", "Item not found"); server->send(404, "text/plain", "Item not found");
return; return;
} }
FsFile file = SdMan.open(itemPath.c_str()); FsFile file = Storage.open(itemPath.c_str());
if (!file) { if (!file) {
server->send(500, "text/plain", "Failed to open file"); server->send(500, "text/plain", "Failed to open file");
return; return;
@@ -574,15 +582,15 @@ void CrossPointWebServer::handleUpload(UploadState& state) const {
// Check if file already exists - SD operations can be slow // Check if file already exists - SD operations can be slow
esp_task_wdt_reset(); esp_task_wdt_reset();
if (SdMan.exists(filePath.c_str())) { if (Storage.exists(filePath.c_str())) {
Serial.printf("[%lu] [WEB] [UPLOAD] Overwriting existing file: %s\n", millis(), filePath.c_str()); Serial.printf("[%lu] [WEB] [UPLOAD] Overwriting existing file: %s\n", millis(), filePath.c_str());
esp_task_wdt_reset(); esp_task_wdt_reset();
SdMan.remove(filePath.c_str()); Storage.remove(filePath.c_str());
} }
// Open file for writing - this can be slow due to FAT cluster allocation // Open file for writing - this can be slow due to FAT cluster allocation
esp_task_wdt_reset(); esp_task_wdt_reset();
if (!SdMan.openFileForWrite("WEB", filePath, state.file)) { if (!Storage.openFileForWrite("WEB", filePath, state.file)) {
state.error = "Failed to create file on SD card"; state.error = "Failed to create file on SD card";
Serial.printf("[%lu] [WEB] [UPLOAD] FAILED to create file: %s\n", millis(), filePath.c_str()); Serial.printf("[%lu] [WEB] [UPLOAD] FAILED to create file: %s\n", millis(), filePath.c_str());
return; return;
@@ -660,7 +668,7 @@ void CrossPointWebServer::handleUpload(UploadState& state) const {
String filePath = state.path; String filePath = state.path;
if (!filePath.endsWith("/")) filePath += "/"; if (!filePath.endsWith("/")) filePath += "/";
filePath += state.fileName; filePath += state.fileName;
SdMan.remove(filePath.c_str()); Storage.remove(filePath.c_str());
} }
state.error = "Upload aborted"; state.error = "Upload aborted";
Serial.printf("[%lu] [WEB] Upload aborted\n", millis()); Serial.printf("[%lu] [WEB] Upload aborted\n", millis());
@@ -711,13 +719,13 @@ void CrossPointWebServer::handleCreateFolder() const {
Serial.printf("[%lu] [WEB] Creating folder: %s\n", millis(), folderPath.c_str()); Serial.printf("[%lu] [WEB] Creating folder: %s\n", millis(), folderPath.c_str());
// Check if already exists // Check if already exists
if (SdMan.exists(folderPath.c_str())) { if (Storage.exists(folderPath.c_str())) {
server->send(400, "text/plain", "Folder already exists"); server->send(400, "text/plain", "Folder already exists");
return; return;
} }
// Create the folder // Create the folder
if (SdMan.mkdir(folderPath.c_str())) { if (Storage.mkdir(folderPath.c_str())) {
Serial.printf("[%lu] [WEB] Folder created successfully: %s\n", millis(), folderPath.c_str()); Serial.printf("[%lu] [WEB] Folder created successfully: %s\n", millis(), folderPath.c_str());
server->send(200, "text/plain", "Folder created: " + folderName); server->send(200, "text/plain", "Folder created: " + folderName);
} else { } else {
@@ -763,12 +771,12 @@ void CrossPointWebServer::handleRename() const {
return; return;
} }
if (!SdMan.exists(itemPath.c_str())) { if (!Storage.exists(itemPath.c_str())) {
server->send(404, "text/plain", "Item not found"); server->send(404, "text/plain", "Item not found");
return; return;
} }
FsFile file = SdMan.open(itemPath.c_str()); FsFile file = Storage.open(itemPath.c_str());
if (!file) { if (!file) {
server->send(500, "text/plain", "Failed to open file"); server->send(500, "text/plain", "Failed to open file");
return; return;
@@ -789,7 +797,7 @@ void CrossPointWebServer::handleRename() const {
} }
newPath += newName; newPath += newName;
if (SdMan.exists(newPath.c_str())) { if (Storage.exists(newPath.c_str())) {
file.close(); file.close();
server->send(409, "text/plain", "Target already exists"); server->send(409, "text/plain", "Target already exists");
return; return;
@@ -839,12 +847,12 @@ void CrossPointWebServer::handleMove() const {
} }
} }
if (!SdMan.exists(itemPath.c_str())) { if (!Storage.exists(itemPath.c_str())) {
server->send(404, "text/plain", "Item not found"); server->send(404, "text/plain", "Item not found");
return; return;
} }
FsFile file = SdMan.open(itemPath.c_str()); FsFile file = Storage.open(itemPath.c_str());
if (!file) { if (!file) {
server->send(500, "text/plain", "Failed to open file"); server->send(500, "text/plain", "Failed to open file");
return; return;
@@ -855,12 +863,12 @@ void CrossPointWebServer::handleMove() const {
return; return;
} }
if (!SdMan.exists(destPath.c_str())) { if (!Storage.exists(destPath.c_str())) {
file.close(); file.close();
server->send(404, "text/plain", "Destination not found"); server->send(404, "text/plain", "Destination not found");
return; return;
} }
FsFile destDir = SdMan.open(destPath.c_str()); FsFile destDir = Storage.open(destPath.c_str());
if (!destDir || !destDir.isDirectory()) { if (!destDir || !destDir.isDirectory()) {
if (destDir) { if (destDir) {
destDir.close(); destDir.close();
@@ -882,7 +890,7 @@ void CrossPointWebServer::handleMove() const {
server->send(200, "text/plain", "Already in destination"); server->send(200, "text/plain", "Already in destination");
return; return;
} }
if (SdMan.exists(newPath.c_str())) { if (Storage.exists(newPath.c_str())) {
file.close(); file.close();
server->send(409, "text/plain", "Target already exists"); server->send(409, "text/plain", "Target already exists");
return; return;
@@ -942,7 +950,7 @@ void CrossPointWebServer::handleDelete() const {
} }
// Check if item exists // Check if item exists
if (!SdMan.exists(itemPath.c_str())) { if (!Storage.exists(itemPath.c_str())) {
Serial.printf("[%lu] [WEB] Delete failed - item not found: %s\n", millis(), itemPath.c_str()); Serial.printf("[%lu] [WEB] Delete failed - item not found: %s\n", millis(), itemPath.c_str());
server->send(404, "text/plain", "Item not found"); server->send(404, "text/plain", "Item not found");
return; return;
@@ -954,7 +962,7 @@ void CrossPointWebServer::handleDelete() const {
if (itemType == "folder") { if (itemType == "folder") {
// For folders, try to remove (will fail if not empty) // For folders, try to remove (will fail if not empty)
FsFile dir = SdMan.open(itemPath.c_str()); FsFile dir = Storage.open(itemPath.c_str());
if (dir && dir.isDirectory()) { if (dir && dir.isDirectory()) {
// Check if folder is empty // Check if folder is empty
FsFile entry = dir.openNextFile(); FsFile entry = dir.openNextFile();
@@ -968,10 +976,10 @@ void CrossPointWebServer::handleDelete() const {
} }
dir.close(); dir.close();
} }
success = SdMan.rmdir(itemPath.c_str()); success = Storage.rmdir(itemPath.c_str());
} else { } else {
// For files, use remove // For files, use remove
success = SdMan.remove(itemPath.c_str()); success = Storage.remove(itemPath.c_str());
} }
if (success) { if (success) {
@@ -983,6 +991,168 @@ void CrossPointWebServer::handleDelete() const {
} }
} }
void CrossPointWebServer::handleSettingsPage() const {
server->send(200, "text/html", SettingsPageHtml);
Serial.printf("[%lu] [WEB] Served settings page\n", millis());
}
void CrossPointWebServer::handleGetSettings() const {
auto settings = getSettingsList();
server->setContentLength(CONTENT_LENGTH_UNKNOWN);
server->send(200, "application/json", "");
server->sendContent("[");
char output[512];
constexpr size_t outputSize = sizeof(output);
bool seenFirst = false;
JsonDocument doc;
for (const auto& s : settings) {
if (!s.key) continue; // Skip ACTION-only entries
doc.clear();
doc["key"] = s.key;
doc["name"] = s.name;
doc["category"] = s.category;
switch (s.type) {
case SettingType::TOGGLE: {
doc["type"] = "toggle";
if (s.valuePtr) {
doc["value"] = static_cast<int>(SETTINGS.*(s.valuePtr));
}
break;
}
case SettingType::ENUM: {
doc["type"] = "enum";
if (s.valuePtr) {
doc["value"] = static_cast<int>(SETTINGS.*(s.valuePtr));
} else if (s.valueGetter) {
doc["value"] = static_cast<int>(s.valueGetter());
}
JsonArray options = doc["options"].to<JsonArray>();
for (const auto& opt : s.enumValues) {
options.add(opt);
}
break;
}
case SettingType::VALUE: {
doc["type"] = "value";
if (s.valuePtr) {
doc["value"] = static_cast<int>(SETTINGS.*(s.valuePtr));
}
doc["min"] = s.valueRange.min;
doc["max"] = s.valueRange.max;
doc["step"] = s.valueRange.step;
break;
}
case SettingType::STRING: {
doc["type"] = "string";
if (s.stringGetter) {
doc["value"] = s.stringGetter();
} else if (s.stringPtr) {
doc["value"] = s.stringPtr;
}
break;
}
default:
continue;
}
const size_t written = serializeJson(doc, output, outputSize);
if (written >= outputSize) {
Serial.printf("[%lu] [WEB] Skipping oversized setting JSON for: %s\n", millis(), s.key);
continue;
}
if (seenFirst) {
server->sendContent(",");
} else {
seenFirst = true;
}
server->sendContent(output);
}
server->sendContent("]");
server->sendContent("");
Serial.printf("[%lu] [WEB] Served settings API\n", millis());
}
void CrossPointWebServer::handlePostSettings() {
if (!server->hasArg("plain")) {
server->send(400, "text/plain", "Missing JSON body");
return;
}
const String body = server->arg("plain");
JsonDocument doc;
const DeserializationError err = deserializeJson(doc, body);
if (err) {
server->send(400, "text/plain", String("Invalid JSON: ") + err.c_str());
return;
}
auto settings = getSettingsList();
int applied = 0;
for (auto& s : settings) {
if (!s.key) continue;
if (!doc[s.key].is<JsonVariant>()) continue;
switch (s.type) {
case SettingType::TOGGLE: {
const int val = doc[s.key].as<int>() ? 1 : 0;
if (s.valuePtr) {
SETTINGS.*(s.valuePtr) = val;
}
applied++;
break;
}
case SettingType::ENUM: {
const int val = doc[s.key].as<int>();
if (val >= 0 && val < static_cast<int>(s.enumValues.size())) {
if (s.valuePtr) {
SETTINGS.*(s.valuePtr) = static_cast<uint8_t>(val);
} else if (s.valueSetter) {
s.valueSetter(static_cast<uint8_t>(val));
}
applied++;
}
break;
}
case SettingType::VALUE: {
const int val = doc[s.key].as<int>();
if (val >= s.valueRange.min && val <= s.valueRange.max) {
if (s.valuePtr) {
SETTINGS.*(s.valuePtr) = static_cast<uint8_t>(val);
}
applied++;
}
break;
}
case SettingType::STRING: {
const std::string val = doc[s.key].as<std::string>();
if (s.stringSetter) {
s.stringSetter(val);
} else if (s.stringPtr && s.stringMaxLen > 0) {
strncpy(s.stringPtr, val.c_str(), s.stringMaxLen - 1);
s.stringPtr[s.stringMaxLen - 1] = '\0';
}
applied++;
break;
}
default:
break;
}
}
SETTINGS.saveToFile();
Serial.printf("[%lu] [WEB] Applied %d setting(s)\n", millis(), applied);
server->send(200, "text/plain", String("Applied ") + String(applied) + " setting(s)");
}
// WebSocket callback trampoline // WebSocket callback trampoline
void CrossPointWebServer::wsEventCallback(uint8_t num, WStype_t type, uint8_t* payload, size_t length) { void CrossPointWebServer::wsEventCallback(uint8_t num, WStype_t type, uint8_t* payload, size_t length) {
if (wsInstance) { if (wsInstance) {
@@ -1007,7 +1177,7 @@ void CrossPointWebServer::onWebSocketEvent(uint8_t num, WStype_t type, uint8_t*
String filePath = wsUploadPath; String filePath = wsUploadPath;
if (!filePath.endsWith("/")) filePath += "/"; if (!filePath.endsWith("/")) filePath += "/";
filePath += wsUploadFileName; filePath += wsUploadFileName;
SdMan.remove(filePath.c_str()); Storage.remove(filePath.c_str());
Serial.printf("[%lu] [WS] Deleted incomplete upload: %s\n", millis(), filePath.c_str()); Serial.printf("[%lu] [WS] Deleted incomplete upload: %s\n", millis(), filePath.c_str());
} }
wsUploadInProgress = false; wsUploadInProgress = false;
@@ -1051,13 +1221,13 @@ void CrossPointWebServer::onWebSocketEvent(uint8_t num, WStype_t type, uint8_t*
// Check if file exists and remove it // Check if file exists and remove it
esp_task_wdt_reset(); esp_task_wdt_reset();
if (SdMan.exists(filePath.c_str())) { if (Storage.exists(filePath.c_str())) {
SdMan.remove(filePath.c_str()); Storage.remove(filePath.c_str());
} }
// Open file for writing // Open file for writing
esp_task_wdt_reset(); esp_task_wdt_reset();
if (!SdMan.openFileForWrite("WS", filePath, wsUploadFile)) { if (!Storage.openFileForWrite("WS", filePath, wsUploadFile)) {
wsServer->sendTXT(num, "ERROR:Failed to create file"); wsServer->sendTXT(num, "ERROR:Failed to create file");
wsUploadInProgress = false; wsUploadInProgress = false;
return; return;

View File

@@ -1,6 +1,6 @@
#pragma once #pragma once
#include <SDCardManager.h> #include <HalStorage.h>
#include <WebServer.h> #include <WebServer.h>
#include <WebSocketsServer.h> #include <WebSocketsServer.h>
#include <WiFiUdp.h> #include <WiFiUdp.h>
@@ -100,4 +100,9 @@ class CrossPointWebServer {
void handleRename() const; void handleRename() const;
void handleMove() const; void handleMove() const;
void handleDelete() const; void handleDelete() const;
// Settings handlers
void handleSettingsPage() const;
void handleGetSettings() const;
void handlePostSettings();
}; };

View File

@@ -100,13 +100,13 @@ HttpDownloader::DownloadError HttpDownloader::downloadToFile(const std::string&
Serial.printf("[%lu] [HTTP] Content-Length: %zu\n", millis(), contentLength); Serial.printf("[%lu] [HTTP] Content-Length: %zu\n", millis(), contentLength);
// Remove existing file if present // Remove existing file if present
if (SdMan.exists(destPath.c_str())) { if (Storage.exists(destPath.c_str())) {
SdMan.remove(destPath.c_str()); Storage.remove(destPath.c_str());
} }
// Open file for writing // Open file for writing
FsFile file; FsFile file;
if (!SdMan.openFileForWrite("HTTP", destPath.c_str(), file)) { if (!Storage.openFileForWrite("HTTP", destPath.c_str(), file)) {
Serial.printf("[%lu] [HTTP] Failed to open file for writing\n", millis()); Serial.printf("[%lu] [HTTP] Failed to open file for writing\n", millis());
http.end(); http.end();
return FILE_ERROR; return FILE_ERROR;
@@ -117,7 +117,7 @@ HttpDownloader::DownloadError HttpDownloader::downloadToFile(const std::string&
if (!stream) { if (!stream) {
Serial.printf("[%lu] [HTTP] Failed to get stream\n", millis()); Serial.printf("[%lu] [HTTP] Failed to get stream\n", millis());
file.close(); file.close();
SdMan.remove(destPath.c_str()); Storage.remove(destPath.c_str());
http.end(); http.end();
return HTTP_ERROR; return HTTP_ERROR;
} }
@@ -145,7 +145,7 @@ HttpDownloader::DownloadError HttpDownloader::downloadToFile(const std::string&
if (written != bytesRead) { if (written != bytesRead) {
Serial.printf("[%lu] [HTTP] Write failed: wrote %zu of %zu bytes\n", millis(), written, bytesRead); Serial.printf("[%lu] [HTTP] Write failed: wrote %zu of %zu bytes\n", millis(), written, bytesRead);
file.close(); file.close();
SdMan.remove(destPath.c_str()); Storage.remove(destPath.c_str());
http.end(); http.end();
return FILE_ERROR; return FILE_ERROR;
} }
@@ -165,7 +165,7 @@ HttpDownloader::DownloadError HttpDownloader::downloadToFile(const std::string&
// Verify download size if known // Verify download size if known
if (contentLength > 0 && downloaded != contentLength) { if (contentLength > 0 && downloaded != contentLength) {
Serial.printf("[%lu] [HTTP] Size mismatch: got %zu, expected %zu\n", millis(), downloaded, contentLength); Serial.printf("[%lu] [HTTP] Size mismatch: got %zu, expected %zu\n", millis(), downloaded, contentLength);
SdMan.remove(destPath.c_str()); Storage.remove(destPath.c_str());
return HTTP_ERROR; return HTTP_ERROR;
} }

View File

@@ -1,5 +1,5 @@
#pragma once #pragma once
#include <SDCardManager.h> #include <HalStorage.h>
#include <functional> #include <functional>
#include <string> #include <string>

View File

@@ -628,6 +628,7 @@
<div class="nav-links"> <div class="nav-links">
<a href="/">Home</a> <a href="/">Home</a>
<a href="/files">File Manager</a> <a href="/files">File Manager</a>
<a href="/settings">Settings</a>
</div> </div>
<div class="page-header"> <div class="page-header">

View File

@@ -77,6 +77,7 @@
<div class="nav-links"> <div class="nav-links">
<a href="/">Home</a> <a href="/">Home</a>
<a href="/files">File Manager</a> <a href="/files">File Manager</a>
<a href="/settings">Settings</a>
</div> </div>
<div class="card"> <div class="card">

View File

@@ -0,0 +1,414 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>CrossPoint Reader - Settings</title>
<style>
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,
Oxygen, Ubuntu, sans-serif;
max-width: 800px;
margin: 0 auto;
padding: 20px;
background-color: #f5f5f5;
color: #333;
}
h1 {
color: #2c3e50;
border-bottom: 2px solid #3498db;
padding-bottom: 10px;
}
h2 {
color: #34495e;
margin-top: 0;
}
.card {
background: white;
border-radius: 8px;
padding: 20px;
margin: 15px 0;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
.nav-links {
margin: 20px 0;
}
.nav-links a {
display: inline-block;
padding: 10px 20px;
background-color: #3498db;
color: white;
text-decoration: none;
border-radius: 4px;
margin-right: 10px;
}
.nav-links a:hover {
background-color: #2980b9;
}
.setting-row {
display: flex;
justify-content: space-between;
align-items: center;
padding: 10px 0;
border-bottom: 1px solid #eee;
}
.setting-row:last-child {
border-bottom: none;
}
.setting-name {
font-weight: 500;
color: #2c3e50;
flex: 1;
min-width: 0;
padding-right: 12px;
}
.setting-control {
flex-shrink: 0;
}
.setting-control select,
.setting-control input[type="number"],
.setting-control input[type="text"],
.setting-control input[type="password"] {
padding: 6px 10px;
border: 1px solid #ddd;
border-radius: 4px;
font-size: 0.95em;
background: white;
}
.setting-control select {
min-width: 160px;
}
.setting-control input[type="text"],
.setting-control input[type="password"] {
width: 220px;
}
.setting-control input[type="number"] {
width: 80px;
}
/* Toggle switch */
.toggle-switch {
display: inline-block;
position: relative;
width: 48px;
height: 26px;
}
.toggle-switch input {
opacity: 0;
width: 0;
height: 0;
}
.toggle-slider {
position: absolute;
cursor: pointer;
top: 0; left: 0; right: 0; bottom: 0;
background-color: #ccc;
border-radius: 26px;
transition: 0.3s;
}
.toggle-slider:before {
position: absolute;
content: "";
height: 20px;
width: 20px;
left: 3px;
bottom: 3px;
background-color: white;
border-radius: 50%;
transition: 0.3s;
}
.toggle-switch input:checked + .toggle-slider {
background-color: #27ae60;
}
.toggle-switch input:checked + .toggle-slider:before {
transform: translateX(22px);
}
.save-container {
text-align: center;
margin: 20px 0;
}
.save-btn {
background-color: #27ae60;
color: white;
padding: 12px 40px;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 1.1em;
font-weight: 600;
}
.save-btn:hover {
background-color: #219a52;
}
.save-btn:disabled {
background-color: #95a5a6;
cursor: not-allowed;
}
.message {
padding: 12px;
border-radius: 4px;
margin: 15px 0;
text-align: center;
display: none;
}
.message.success {
background-color: #d4edda;
color: #155724;
border: 1px solid #c3e6cb;
}
.message.error {
background-color: #f8d7da;
color: #721c24;
border: 1px solid #f5c6cb;
}
.loader-container {
display: flex;
justify-content: center;
align-items: center;
margin: 20px 0;
}
.loader {
width: 48px;
height: 48px;
border: 5px solid #AAA;
border-bottom-color: transparent;
border-radius: 50%;
display: inline-block;
box-sizing: border-box;
animation: rotation 1s linear infinite;
}
@keyframes rotation {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}
@media (max-width: 600px) {
body {
padding: 10px;
font-size: 14px;
}
.card {
padding: 12px;
margin: 10px 0;
}
h1 {
font-size: 1.3em;
}
.nav-links a {
padding: 8px 12px;
margin-right: 6px;
font-size: 0.9em;
}
.setting-row {
flex-wrap: wrap;
gap: 6px;
}
.setting-control select,
.setting-control input[type="text"],
.setting-control input[type="password"] {
min-width: 0;
width: 100%;
}
}
</style>
</head>
<body>
<h1>⚙️ Settings</h1>
<div class="nav-links">
<a href="/">Home</a>
<a href="/files">File Manager</a>
<a href="/settings">Settings</a>
</div>
<div id="message" class="message"></div>
<div id="settings-container">
<div class="loader-container">
<span class="loader"></span>
</div>
</div>
<div class="save-container" id="save-container" style="display:none;">
<button class="save-btn" id="saveBtn" onclick="saveSettings()">Save Settings</button>
</div>
<div class="card">
<p style="text-align: center; color: #95a5a6; margin: 0;">
CrossPoint E-Reader • Open Source
</p>
</div>
<script>
let allSettings = [];
let originalValues = {};
function escapeHtml(unsafe) {
return unsafe
.replaceAll("&", "&amp;")
.replaceAll("<", "&lt;")
.replaceAll(">", "&gt;")
.replaceAll('"', "&quot;")
.replaceAll("'", "&#039;");
}
function showMessage(text, isError) {
const msg = document.getElementById('message');
msg.textContent = text;
msg.className = 'message ' + (isError ? 'error' : 'success');
msg.style.display = 'block';
setTimeout(function() { msg.style.display = 'none'; }, 4000);
}
function renderControl(setting) {
const id = 'setting-' + setting.key;
if (setting.type === 'toggle') {
const checked = setting.value ? 'checked' : '';
return '<label class="toggle-switch">' +
'<input type="checkbox" id="' + id + '" ' + checked + ' onchange="markChanged()">' +
'<span class="toggle-slider"></span></label>';
}
if (setting.type === 'enum') {
let html = '<select id="' + id + '" onchange="markChanged()">';
setting.options.forEach(function(opt, idx) {
const selected = idx === setting.value ? ' selected' : '';
html += '<option value="' + idx + '"' + selected + '>' + escapeHtml(opt) + '</option>';
});
html += '</select>';
return html;
}
if (setting.type === 'value') {
return '<input type="number" id="' + id + '" value="' + setting.value + '"' +
' min="' + setting.min + '" max="' + setting.max + '" step="' + setting.step + '"' +
' onchange="markChanged()">';
}
if (setting.type === 'string') {
const inputType = setting.name.toLowerCase().includes('password') ? 'password' : 'text';
const val = setting.value || '';
return '<input type="' + inputType + '" id="' + id + '" value="' + escapeHtml(val) + '"' +
' oninput="markChanged()">';
}
return '';
}
function getValue(setting) {
const el = document.getElementById('setting-' + setting.key);
if (!el) return undefined;
if (setting.type === 'toggle') {
return el.checked ? 1 : 0;
}
if (setting.type === 'enum') {
return parseInt(el.value, 10);
}
if (setting.type === 'value') {
return parseInt(el.value, 10);
}
if (setting.type === 'string') {
return el.value;
}
return undefined;
}
function markChanged() {
document.getElementById('saveBtn').disabled = false;
}
async function loadSettings() {
try {
const response = await fetch('/api/settings');
if (!response.ok) {
throw new Error('Failed to load settings: ' + response.status);
}
allSettings = await response.json();
// Store original values
originalValues = {};
allSettings.forEach(function(s) {
originalValues[s.key] = s.value;
});
// Group by category
const groups = {};
allSettings.forEach(function(s) {
if (!groups[s.category]) groups[s.category] = [];
groups[s.category].push(s);
});
const container = document.getElementById('settings-container');
let html = '';
for (const category in groups) {
html += '<div class="card"><h2>' + escapeHtml(category) + '</h2>';
groups[category].forEach(function(s) {
html += '<div class="setting-row">' +
'<span class="setting-name">' + escapeHtml(s.name) + '</span>' +
'<span class="setting-control">' + renderControl(s) + '</span>' +
'</div>';
});
html += '</div>';
}
container.innerHTML = html;
document.getElementById('save-container').style.display = '';
document.getElementById('saveBtn').disabled = true;
} catch (e) {
console.error(e);
document.getElementById('settings-container').innerHTML =
'<div class="card"><p style="text-align:center;color:#e74c3c;">Failed to load settings</p></div>';
}
}
async function saveSettings() {
const btn = document.getElementById('saveBtn');
btn.disabled = true;
btn.textContent = 'Saving...';
// Collect only changed values
const changes = {};
allSettings.forEach(function(s) {
const current = getValue(s);
if (current !== undefined && current !== originalValues[s.key]) {
changes[s.key] = current;
}
});
if (Object.keys(changes).length === 0) {
showMessage('No changes to save.', false);
btn.textContent = 'Save Settings';
return;
}
try {
const response = await fetch('/api/settings', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(changes)
});
if (!response.ok) {
const text = await response.text();
throw new Error(text || 'Save failed');
}
// Update original values to new values
for (const key in changes) {
originalValues[key] = changes[key];
}
showMessage('Settings saved successfully!', false);
} catch (e) {
console.error(e);
showMessage('Error: ' + e.message, true);
}
btn.textContent = 'Save Settings';
}
loadSettings();
</script>
</body>
</html>

View File

@@ -0,0 +1,124 @@
#include "ButtonNavigator.h"
const MappedInputManager* ButtonNavigator::mappedInput = nullptr;
void ButtonNavigator::onNext(const Callback& callback) {
onNextPress(callback);
onNextContinuous(callback);
}
void ButtonNavigator::onPrevious(const Callback& callback) {
onPreviousPress(callback);
onPreviousContinuous(callback);
}
void ButtonNavigator::onPressAndContinuous(const Buttons& buttons, const Callback& callback) {
onPress(buttons, callback);
onContinuous(buttons, callback);
}
void ButtonNavigator::onNextPress(const Callback& callback) { onPress(getNextButtons(), callback); }
void ButtonNavigator::onPreviousPress(const Callback& callback) { onPress(getPreviousButtons(), callback); }
void ButtonNavigator::onNextRelease(const Callback& callback) { onRelease(getNextButtons(), callback); }
void ButtonNavigator::onPreviousRelease(const Callback& callback) { onRelease(getPreviousButtons(), callback); }
void ButtonNavigator::onNextContinuous(const Callback& callback) { onContinuous(getNextButtons(), callback); }
void ButtonNavigator::onPreviousContinuous(const Callback& callback) { onContinuous(getPreviousButtons(), callback); }
void ButtonNavigator::onPress(const Buttons& buttons, const Callback& callback) {
const bool wasPressed = std::any_of(buttons.begin(), buttons.end(), [](const MappedInputManager::Button button) {
return mappedInput != nullptr && mappedInput->wasPressed(button);
});
if (wasPressed) {
callback();
}
}
void ButtonNavigator::onRelease(const Buttons& buttons, const Callback& callback) {
const bool wasReleased = std::any_of(buttons.begin(), buttons.end(), [](const MappedInputManager::Button button) {
return mappedInput != nullptr && mappedInput->wasReleased(button);
});
if (wasReleased) {
if (lastContinuousNavTime == 0) {
callback();
}
lastContinuousNavTime = 0;
}
}
void ButtonNavigator::onContinuous(const Buttons& buttons, const Callback& callback) {
const bool isPressed = std::any_of(buttons.begin(), buttons.end(), [this](const MappedInputManager::Button button) {
return mappedInput != nullptr && mappedInput->isPressed(button) && shouldNavigateContinuously();
});
if (isPressed) {
callback();
lastContinuousNavTime = millis();
}
}
bool ButtonNavigator::shouldNavigateContinuously() const {
if (!mappedInput) return false;
const bool buttonHeldLongEnough = mappedInput->getHeldTime() > continuousStartMs;
const bool navigationIntervalElapsed = (millis() - lastContinuousNavTime) > continuousIntervalMs;
return buttonHeldLongEnough && navigationIntervalElapsed;
}
int ButtonNavigator::nextIndex(const int currentIndex, const int totalItems) {
if (totalItems <= 0) return 0;
// Calculate the next index with wrap-around
return (currentIndex + 1) % totalItems;
}
int ButtonNavigator::previousIndex(const int currentIndex, const int totalItems) {
if (totalItems <= 0) return 0;
// Calculate the previous index with wrap-around
return (currentIndex + totalItems - 1) % totalItems;
}
int ButtonNavigator::nextPageIndex(const int currentIndex, const int totalItems, const int itemsPerPage) {
if (totalItems <= 0 || itemsPerPage <= 0) return 0;
// When items fit on one page, use index navigation instead
if (totalItems <= itemsPerPage) {
return nextIndex(currentIndex, totalItems);
}
const int lastPageIndex = (totalItems - 1) / itemsPerPage;
const int currentPageIndex = currentIndex / itemsPerPage;
if (currentPageIndex < lastPageIndex) {
return (currentPageIndex + 1) * itemsPerPage;
}
return 0;
}
int ButtonNavigator::previousPageIndex(const int currentIndex, const int totalItems, const int itemsPerPage) {
if (totalItems <= 0 || itemsPerPage <= 0) return 0;
// When items fit on one page, use index navigation instead
if (totalItems <= itemsPerPage) {
return previousIndex(currentIndex, totalItems);
}
const int lastPageIndex = (totalItems - 1) / itemsPerPage;
const int currentPageIndex = currentIndex / itemsPerPage;
if (currentPageIndex > 0) {
return (currentPageIndex - 1) * itemsPerPage;
}
return lastPageIndex * itemsPerPage;
}

View File

@@ -0,0 +1,53 @@
#pragma once
#include <functional>
#include <vector>
#include "MappedInputManager.h"
class ButtonNavigator final {
using Callback = std::function<void()>;
using Buttons = std::vector<MappedInputManager::Button>;
const uint16_t continuousStartMs;
const uint16_t continuousIntervalMs;
uint32_t lastContinuousNavTime = 0;
static const MappedInputManager* mappedInput;
[[nodiscard]] bool shouldNavigateContinuously() const;
public:
explicit ButtonNavigator(const uint16_t continuousIntervalMs = 500, const uint16_t continuousStartMs = 500)
: continuousStartMs(continuousStartMs), continuousIntervalMs(continuousIntervalMs) {}
static void setMappedInputManager(const MappedInputManager& mappedInputManager) { mappedInput = &mappedInputManager; }
void onNext(const Callback& callback);
void onPrevious(const Callback& callback);
void onPressAndContinuous(const Buttons& buttons, const Callback& callback);
void onNextPress(const Callback& callback);
void onPreviousPress(const Callback& callback);
void onPress(const Buttons& buttons, const Callback& callback);
void onNextRelease(const Callback& callback);
void onPreviousRelease(const Callback& callback);
void onRelease(const Buttons& buttons, const Callback& callback);
void onNextContinuous(const Callback& callback);
void onPreviousContinuous(const Callback& callback);
void onContinuous(const Buttons& buttons, const Callback& callback);
[[nodiscard]] static int nextIndex(int currentIndex, int totalItems);
[[nodiscard]] static int previousIndex(int currentIndex, int totalItems);
[[nodiscard]] static int nextPageIndex(int currentIndex, int totalItems, int itemsPerPage);
[[nodiscard]] static int previousPageIndex(int currentIndex, int totalItems, int itemsPerPage);
[[nodiscard]] static Buttons getNextButtons() {
return {MappedInputManager::Button::Down, MappedInputManager::Button::Right};
}
[[nodiscard]] static Buttons getPreviousButtons() {
return {MappedInputManager::Button::Up, MappedInputManager::Button::Left};
}
};

View File

@@ -25,6 +25,10 @@ std::string extractHost(const std::string& url) {
} }
std::string buildUrl(const std::string& serverUrl, const std::string& path) { std::string buildUrl(const std::string& serverUrl, const std::string& path) {
// If path is already an absolute URL (has protocol), use it directly
if (path.find("://") != std::string::npos) {
return path;
}
const std::string urlWithProtocol = ensureProtocol(serverUrl); const std::string urlWithProtocol = ensureProtocol(serverUrl);
if (path.empty()) { if (path.empty()) {
return urlWithProtocol; return urlWithProtocol;

View File

@@ -43,6 +43,7 @@ const std::vector<LanguageConfig> kSupportedLanguages = {
{"german", "test/hyphenation_eval/resources/german_hyphenation_tests.txt", "de"}, {"german", "test/hyphenation_eval/resources/german_hyphenation_tests.txt", "de"},
{"russian", "test/hyphenation_eval/resources/russian_hyphenation_tests.txt", "ru"}, {"russian", "test/hyphenation_eval/resources/russian_hyphenation_tests.txt", "ru"},
{"spanish", "test/hyphenation_eval/resources/spanish_hyphenation_tests.txt", "es"}, {"spanish", "test/hyphenation_eval/resources/spanish_hyphenation_tests.txt", "es"},
{"italian", "test/hyphenation_eval/resources/italian_hyphenation_tests.txt", "it"},
}; };
std::vector<size_t> expectedPositionsFromAnnotatedWord(const std::string& annotated) { std::vector<size_t> expectedPositionsFromAnnotatedWord(const std::string& annotated) {

File diff suppressed because it is too large Load Diff