Compare commits
124 Commits
feature/cr
...
mod/master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b965ce9fb7
|
||
|
|
744d6160e8
|
||
|
|
66f703df69
|
||
|
|
19004eefaa
|
||
|
|
f90aebc891
|
||
|
|
3096d6066b
|
||
|
|
46c2109f1f | ||
|
|
1383d75c84
|
||
|
|
632b76c9ed
|
||
|
|
5dc9d21bdb
|
||
|
|
c1dfe92ea3
|
||
|
|
5816ab2a47 | ||
|
|
2c0a105550 | ||
|
|
82bfbd8fa6
|
||
|
|
6aa0b865c2
|
||
|
|
0c71e0b13f
|
||
|
|
ea11d2f7d3
|
||
|
|
6e51afb977 | ||
|
|
cb24947477 | ||
|
|
31878a77bc
|
||
|
|
21a75c624d
|
||
|
|
8d4bbf284d
|
||
|
|
7a385d78a4 | ||
|
|
905f694576
|
||
|
|
e798065a5c
|
||
|
|
5e269f912f
|
||
|
|
182c236050
|
||
|
|
73cd05827a | ||
|
|
ea32ba0f8d | ||
|
|
f7b1113819 | ||
|
|
228a1cb511 | ||
|
|
0991782fb4 | ||
|
|
3ae1007cbe | ||
|
|
efb9b72e64 | ||
|
|
4a210823a8 | ||
|
|
b72283d304 | ||
|
|
f5b85f5ca1 | ||
|
|
8cf226613b | ||
|
|
7e93411f46 | ||
|
|
44452a42e9 | ||
|
|
0c2df24f5c | ||
|
|
3a12ca2725 | ||
|
|
d4f25c44bf | ||
|
|
98e6789626 | ||
|
|
b5d28a3a9c | ||
|
|
bc12556da1 | ||
|
|
4e7bb8979c | ||
|
|
4edb14bdd9
|
||
|
|
eb79b98f2b | ||
|
|
14ef625679 | ||
|
|
64d161e88b | ||
|
|
a85d5e627b
|
||
|
|
e73bb3213f | ||
|
|
6202bfd651 | ||
|
|
9e04eec072 | ||
|
|
9b04c2ec76 | ||
|
|
def1094411 | ||
|
|
ffddc2472b | ||
|
|
5765bbe821 | ||
|
|
7538e55795 | ||
|
|
21e7d29286 | ||
|
|
b4b028be3a | ||
|
|
f34d7d2aac | ||
|
|
71769490fb | ||
|
|
cda0a3f898 | ||
|
|
7f40c3f477 | ||
|
|
5e52a46837 | ||
|
|
6909f127b4 | ||
|
|
4f0a3aa4dd | ||
|
|
bb983d0ef4 | ||
|
|
b45eaf7ded | ||
|
|
a87eacc6ab | ||
|
|
1caad578fc | ||
|
|
75b0ed7781 | ||
|
|
5b90b68e99 | ||
|
|
67ddd60fce | ||
|
|
76908d38e1 | ||
|
|
e6f5fa43e6 | ||
|
|
e7e31ac487 | ||
|
|
47f3137dee | ||
|
|
d8632eae08 | ||
|
|
9f78fd33e8 | ||
|
|
bd8132a260 | ||
|
|
3223e85ea5 | ||
|
|
f89ce514c8 | ||
|
|
211153fcd5 | ||
|
|
91777a9023 | ||
|
|
d8e813a78d | ||
|
|
c3b9bc38b9 | ||
|
|
fb0af32ec0 | ||
|
|
cb4d86fec6 | ||
|
|
e94f056e8a | ||
|
|
20c5d8ccf8 | ||
|
|
d35bda8023 | ||
|
|
d762325035 | ||
|
|
7f2b1a818e | ||
|
|
ddbe49f536 | ||
|
|
17fedd2a69 | ||
|
|
768c2f8eed | ||
|
|
216dbc8ee3 | ||
|
|
ee987f07ff | ||
|
|
23ecc52261 | ||
|
|
edaf8fff9d | ||
|
|
c8683340ab | ||
|
|
5a9ee19eb8 | ||
|
|
c49a819939 | ||
|
|
bf87a7dc60 | ||
|
|
2cf799f45b | ||
|
|
db659f3ea2 | ||
|
|
78d6e5931c | ||
|
|
dac11c3fdd | ||
|
|
d403044f76 | ||
|
|
f67c544e16 | ||
|
|
e5c0ddc9fa | ||
|
|
b1dcb7733b | ||
|
|
0d82b03981 | ||
|
|
5a97334ace | ||
|
|
4dd73a211a | ||
|
|
634f6279cb | ||
|
|
11b2a59233 | ||
|
|
12c20bb09e | ||
|
|
6b7065b986 | ||
|
|
f4df513bf3 | ||
|
|
f935b59a41 |
106
.github/workflows/ci.yml
vendored
106
.github/workflows/ci.yml
vendored
@@ -1,10 +1,55 @@
|
|||||||
name: CI
|
name: CI (build)
|
||||||
'on':
|
|
||||||
|
on:
|
||||||
push:
|
push:
|
||||||
branches: [master]
|
branches: [master]
|
||||||
pull_request:
|
pull_request:
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
|
clang-format:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v6
|
||||||
|
with:
|
||||||
|
submodules: recursive
|
||||||
|
|
||||||
|
- uses: actions/setup-python@v6
|
||||||
|
with:
|
||||||
|
python-version: '3.14'
|
||||||
|
|
||||||
|
- name: Install clang-format-21
|
||||||
|
run: |
|
||||||
|
wget https://apt.llvm.org/llvm.sh
|
||||||
|
chmod +x llvm.sh
|
||||||
|
sudo ./llvm.sh 21
|
||||||
|
sudo apt-get update
|
||||||
|
sudo apt-get install -y clang-format-21
|
||||||
|
|
||||||
|
- name: Run clang-format
|
||||||
|
run: |
|
||||||
|
PATH="/usr/lib/llvm-21/bin:$PATH" ./bin/clang-format-fix
|
||||||
|
git diff --exit-code || (echo "Please run 'bin/clang-format-fix' to fix formatting issues" && exit 1)
|
||||||
|
|
||||||
|
cppcheck:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v6
|
||||||
|
with:
|
||||||
|
submodules: recursive
|
||||||
|
|
||||||
|
- uses: actions/setup-python@v6
|
||||||
|
with:
|
||||||
|
python-version: '3.14'
|
||||||
|
|
||||||
|
- name: Install PlatformIO Core
|
||||||
|
run: pip install --upgrade platformio
|
||||||
|
|
||||||
|
- name: Run cppcheck
|
||||||
|
run: pio check --fail-on-defect low --fail-on-defect medium --fail-on-defect high
|
||||||
|
|
||||||
build:
|
build:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
@@ -19,19 +64,46 @@ jobs:
|
|||||||
- name: Install PlatformIO Core
|
- name: Install PlatformIO Core
|
||||||
run: pip install --upgrade platformio
|
run: pip install --upgrade platformio
|
||||||
|
|
||||||
- name: Install clang-format-21
|
|
||||||
run: |
|
|
||||||
wget https://apt.llvm.org/llvm.sh
|
|
||||||
chmod +x llvm.sh
|
|
||||||
sudo ./llvm.sh 21
|
|
||||||
sudo apt-get update
|
|
||||||
sudo apt-get install -y clang-format-21
|
|
||||||
|
|
||||||
- name: Run cppcheck
|
|
||||||
run: pio check --fail-on-defect low --fail-on-defect medium --fail-on-defect high
|
|
||||||
|
|
||||||
- name: Run clang-format
|
|
||||||
run: PATH="/usr/lib/llvm-21/bin:$PATH" ./bin/clang-format-fix && git diff --exit-code || (echo "Please run 'bin/clang-format-fix' to fix formatting issues" && exit 1)
|
|
||||||
|
|
||||||
- name: Build CrossPoint
|
- name: Build CrossPoint
|
||||||
run: pio run
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
pio run | tee pio.log
|
||||||
|
|
||||||
|
- name: Extract firmware stats
|
||||||
|
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
ram_line="$(grep -E "RAM:\\s" -m1 pio.log || true)"
|
||||||
|
flash_line="$(grep -E "Flash:\\s" -m1 pio.log || true)"
|
||||||
|
echo "ram_line=${ram_line}" >> "$GITHUB_OUTPUT"
|
||||||
|
echo "flash_line=${flash_line}" >> "$GITHUB_OUTPUT"
|
||||||
|
{
|
||||||
|
echo "## Firmware build stats"
|
||||||
|
if [ -n "$ram_line" ]; then echo "- ${ram_line}"; else echo "- RAM: not found"; fi
|
||||||
|
if [ -n "$flash_line" ]; then echo "- ${flash_line}"; else echo "- Flash: not found"; fi
|
||||||
|
} >> "$GITHUB_STEP_SUMMARY"
|
||||||
|
|
||||||
|
- name: Upload firmware.bin artifact
|
||||||
|
uses: actions/upload-artifact@v6
|
||||||
|
with:
|
||||||
|
name: firmware.bin
|
||||||
|
path: .pio/build/default/firmware.bin
|
||||||
|
if-no-files-found: error
|
||||||
|
|
||||||
|
# This job is used as the PR required actions check, allows for changes to other steps in the future without breaking
|
||||||
|
# PR requirements.
|
||||||
|
test-status:
|
||||||
|
name: Test Status
|
||||||
|
needs:
|
||||||
|
- build
|
||||||
|
- clang-format
|
||||||
|
- cppcheck
|
||||||
|
if: always()
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Fail because needed jobs failed
|
||||||
|
# Fail if any job failed or was cancelled (skipped jobs are ok)
|
||||||
|
if: ${{ contains(needs.*.result, 'failure') || contains(needs.*.result, 'cancelled') }}
|
||||||
|
run: exit 1
|
||||||
|
- name: Success
|
||||||
|
run: exit 0
|
||||||
|
|||||||
1
.github/workflows/pr-formatting-check.yml
vendored
1
.github/workflows/pr-formatting-check.yml
vendored
@@ -1,6 +1,7 @@
|
|||||||
name: "PR Formatting"
|
name: "PR Formatting"
|
||||||
|
|
||||||
on:
|
on:
|
||||||
|
pull_request:
|
||||||
pull_request_target:
|
pull_request_target:
|
||||||
types:
|
types:
|
||||||
- opened
|
- opened
|
||||||
|
|||||||
48
.github/workflows/release_candidate.yml
vendored
Normal file
48
.github/workflows/release_candidate.yml
vendored
Normal file
@@ -0,0 +1,48 @@
|
|||||||
|
name: Compile Release Candidate
|
||||||
|
|
||||||
|
on:
|
||||||
|
workflow_dispatch:
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build-release-candidate:
|
||||||
|
if: startsWith(github.ref_name, 'release/')
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v6
|
||||||
|
with:
|
||||||
|
submodules: recursive
|
||||||
|
|
||||||
|
- uses: actions/cache@v5
|
||||||
|
with:
|
||||||
|
path: |
|
||||||
|
~/.cache/pip
|
||||||
|
~/.platformio/.cache
|
||||||
|
key: ${{ runner.os }}-pio
|
||||||
|
|
||||||
|
- uses: actions/setup-python@v6
|
||||||
|
with:
|
||||||
|
python-version: '3.14'
|
||||||
|
|
||||||
|
- name: Install PlatformIO Core
|
||||||
|
run: pip install --upgrade platformio
|
||||||
|
|
||||||
|
- name: Extract env
|
||||||
|
run: |
|
||||||
|
echo "SHORT_SHA=${GITHUB_SHA::7}" >> $GITHUB_ENV
|
||||||
|
echo "BRANCH_SUFFIX=${GITHUB_REF_NAME#release/}" >> $GITHUB_ENV
|
||||||
|
|
||||||
|
- name: Build CrossPoint Release Candidate
|
||||||
|
env:
|
||||||
|
CROSSPOINT_RC_HASH: ${{ env.SHORT_SHA }}
|
||||||
|
run: pio run -e gh_release_rc
|
||||||
|
|
||||||
|
- name: Upload Artifacts
|
||||||
|
uses: actions/upload-artifact@v4
|
||||||
|
with:
|
||||||
|
name: CrossPoint-RC-${{ env.BRANCH_SUFFIX }}
|
||||||
|
path: |
|
||||||
|
.pio/build/gh_release_rc/bootloader.bin
|
||||||
|
.pio/build/gh_release_rc/firmware.bin
|
||||||
|
.pio/build/gh_release_rc/firmware.elf
|
||||||
|
.pio/build/gh_release_rc/firmware.map
|
||||||
|
.pio/build/gh_release_rc/partitions.bin
|
||||||
5
.gitignore
vendored
5
.gitignore
vendored
@@ -9,3 +9,8 @@ build
|
|||||||
**/__pycache__/
|
**/__pycache__/
|
||||||
/compile_commands.json
|
/compile_commands.json
|
||||||
/.cache
|
/.cache
|
||||||
|
|
||||||
|
# mod
|
||||||
|
mod/*
|
||||||
|
.cursor/*
|
||||||
|
chat-summaries/*
|
||||||
38
GOVERNANCE.md
Normal file
38
GOVERNANCE.md
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
# Project Governance & Community Principles
|
||||||
|
|
||||||
|
CrossPoint Reader is a community-driven, open-source project. Our goal is to provide a high-quality, open-source
|
||||||
|
firmware alternative for the Xteink X4 hardware. To keep this project productive and welcoming as we grow, we ask all
|
||||||
|
contributors to follow these principles.
|
||||||
|
|
||||||
|
### 1. The "Human First" Rule
|
||||||
|
Technical discussions can get heated, but they should never be personal.
|
||||||
|
- **Assume good intent:** We are all volunteers working on this in our free time. If a comment seems abrasive, assume
|
||||||
|
it’s a language barrier or a misunderstanding before taking offense.
|
||||||
|
- **Focus on the code, not the person:** Critique the implementation, the performance, or the UX. Never the intelligence
|
||||||
|
or character of the contributor.
|
||||||
|
- **Inflammatory language:** Personal attacks, trolling, or exclusionary language (based on race, gender, background,
|
||||||
|
etc.) are not welcome here and will be moderated.
|
||||||
|
|
||||||
|
### 2. A "Do-ocracy" with Guidance
|
||||||
|
CrossPoint thrives because people step up to build what they want to see.
|
||||||
|
- If you want a feature, the best way to get it is to start an
|
||||||
|
[Idea Discussion](https://github.com/crosspoint-reader/crosspoint-reader/discussions/categories/ideas) or open a PR.
|
||||||
|
- If you want to report a bug, check for duplicates and create an
|
||||||
|
[Issue](https://github.com/crosspoint-reader/crosspoint-reader/issues).
|
||||||
|
- While we encourage experimentation, the maintainers reserve the right to guide the project’s technical direction to
|
||||||
|
ensure stability on the ESP32-C3’s constrained hardware.
|
||||||
|
- For more guidance on the scope of the project, see the [SCOPE.md](SCOPE.md) document.
|
||||||
|
|
||||||
|
### 3. Transparent Communication
|
||||||
|
To keep the project healthy, we keep our "work" in the open.
|
||||||
|
- **Public by Default:** All technical decisions and project management discussions happen in GitHub Issues, Pull
|
||||||
|
Requests, or the public Discussions tab.
|
||||||
|
- **Clarity in Writing:** Because we have a global community with different levels of English proficiency, please be as
|
||||||
|
explicit and clear as possible in your PR descriptions and bug reports.
|
||||||
|
|
||||||
|
### 4. Moderation & Safety
|
||||||
|
The maintainers are responsible for keeping the community a safe place to contribute.
|
||||||
|
- We reserve the right to hide comments, lock threads, or block users who repeatedly violate these principles or engage
|
||||||
|
in harassment.
|
||||||
|
- **Reporting:** If you feel you are being harassed or see behavior that is damaging the community, please reach out
|
||||||
|
privately to @daveallie.
|
||||||
32
README.md
32
README.md
@@ -45,11 +45,13 @@ Multi-language support: Read EPUBs in various languages, including English, Span
|
|||||||
|
|
||||||
See [the user guide](./USER_GUIDE.md) for instructions on operating CrossPoint.
|
See [the user guide](./USER_GUIDE.md) for instructions on operating CrossPoint.
|
||||||
|
|
||||||
|
For more details about the scope of the project, see the [SCOPE.md](SCOPE.md) document.
|
||||||
|
|
||||||
## Installing
|
## Installing
|
||||||
|
|
||||||
### Web (latest firmware)
|
### Web (latest firmware)
|
||||||
|
|
||||||
1. Connect your Xteink X4 to your computer via USB-C
|
1. Connect your Xteink X4 to your computer via USB-C and wake/unlock the device
|
||||||
2. Go to https://xteink.dve.al/ and click "Flash CrossPoint firmware"
|
2. Go to https://xteink.dve.al/ and click "Flash CrossPoint firmware"
|
||||||
|
|
||||||
To revert back to the official firmware, you can flash the latest official firmware from https://xteink.dve.al/, or swap
|
To revert back to the official firmware, you can flash the latest official firmware from https://xteink.dve.al/, or swap
|
||||||
@@ -58,7 +60,7 @@ back to the other partition using the "Swap boot partition" button here https://
|
|||||||
### Web (specific firmware version)
|
### Web (specific firmware version)
|
||||||
|
|
||||||
1. Connect your Xteink X4 to your computer via USB-C
|
1. Connect your Xteink X4 to your computer via USB-C
|
||||||
2. Download the `firmware.bin` file from the release of your choice via the [releases page](https://github.com/daveallie/crosspoint-reader/releases)
|
2. Download the `firmware.bin` file from the release of your choice via the [releases page](https://github.com/crosspoint-reader/crosspoint-reader/releases)
|
||||||
3. Go to https://xteink.dve.al/ and flash the firmware file using the "OTA fast flash controls" section
|
3. Go to https://xteink.dve.al/ and flash the firmware file using the "OTA fast flash controls" section
|
||||||
|
|
||||||
To revert back to the official firmware, you can flash the latest official firmware from https://xteink.dve.al/, or swap
|
To revert back to the official firmware, you can flash the latest official firmware from https://xteink.dve.al/, or swap
|
||||||
@@ -82,7 +84,7 @@ See [Development](#development) below.
|
|||||||
CrossPoint uses PlatformIO for building and flashing the firmware. To get started, clone the repository:
|
CrossPoint uses PlatformIO for building and flashing the firmware. To get started, clone the repository:
|
||||||
|
|
||||||
```
|
```
|
||||||
git clone --recursive https://github.com/daveallie/crosspoint-reader
|
git clone --recursive https://github.com/crosspoint-reader/crosspoint-reader
|
||||||
|
|
||||||
# Or, if you've already cloned without --recursive:
|
# Or, if you've already cloned without --recursive:
|
||||||
git submodule update --init --recursive
|
git submodule update --init --recursive
|
||||||
@@ -95,6 +97,25 @@ Connect your Xteink X4 to your computer via USB-C and run the following command.
|
|||||||
```sh
|
```sh
|
||||||
pio run --target upload
|
pio run --target upload
|
||||||
```
|
```
|
||||||
|
### Debugging
|
||||||
|
|
||||||
|
After flashing the new features, it’s recommended to capture detailed logs from the serial port.
|
||||||
|
|
||||||
|
First, make sure all required Python packages are installed:
|
||||||
|
|
||||||
|
```python
|
||||||
|
python3 -m pip install pyserial colorama matplotlib
|
||||||
|
```
|
||||||
|
after that run the script:
|
||||||
|
```sh
|
||||||
|
# For Linux
|
||||||
|
# This was tested on Debian and should work on most Linux systems.
|
||||||
|
python3 scripts/debugging_monitor.py
|
||||||
|
|
||||||
|
# For macOS
|
||||||
|
python3 scripts/debugging_monitor.py /dev/cu.usbmodem2101
|
||||||
|
```
|
||||||
|
Minor adjustments may be required for Windows.
|
||||||
|
|
||||||
## Internals
|
## Internals
|
||||||
|
|
||||||
@@ -133,9 +154,12 @@ For more details on the internal file structures, see the [file formats document
|
|||||||
|
|
||||||
Contributions are very welcome!
|
Contributions are very welcome!
|
||||||
|
|
||||||
If you're looking for a way to help out, take a look at the [ideas discussion board](https://github.com/daveallie/crosspoint-reader/discussions/categories/ideas).
|
If you're looking for a way to help out, take a look at the [ideas discussion board](https://github.com/crosspoint-reader/crosspoint-reader/discussions/categories/ideas).
|
||||||
If there's something there you'd like to work on, leave a comment so that we can avoid duplicated effort.
|
If there's something there you'd like to work on, leave a comment so that we can avoid duplicated effort.
|
||||||
|
|
||||||
|
Everyone here is a volunteer, so please be respectful and patient. For more details on our goverance and community
|
||||||
|
principles, please see [GOVERNANCE.md](GOVERNANCE.md).
|
||||||
|
|
||||||
### To submit a contribution:
|
### To submit a contribution:
|
||||||
|
|
||||||
1. Fork the repo
|
1. Fork the repo
|
||||||
|
|||||||
48
SCOPE.md
Normal file
48
SCOPE.md
Normal file
@@ -0,0 +1,48 @@
|
|||||||
|
# Project Vision & Scope: CrossPoint Reader
|
||||||
|
|
||||||
|
The goal of CrossPoint Reader is to create an efficient, open-source reading experience for the Xteink X4. We believe a
|
||||||
|
dedicated e-reader should do one thing exceptionally well: **facilitate focused reading.**
|
||||||
|
|
||||||
|
## 1. Core Mission
|
||||||
|
|
||||||
|
To provide a lightweight, high-performance firmware that maximizes the potential of the X4, prioritizing legibility and
|
||||||
|
usability over "swiss-army-knife" functionality.
|
||||||
|
|
||||||
|
## 2. Scope
|
||||||
|
|
||||||
|
### In-Scope
|
||||||
|
|
||||||
|
*These are features that directly improve the primary purpose of the device.*
|
||||||
|
|
||||||
|
* **User Experience:** E.g. User-friendly interfaces, and interactions, both inside the reader and navigating the
|
||||||
|
firmware. This includes things like button mapping, book loading, and book navigation like bookmarks.
|
||||||
|
* **Document Rendering:** E.g. Support for rendering documents (primarily EPUB) and improvements to the rendering
|
||||||
|
engine.
|
||||||
|
* **Format Optimization:** E.g. Efficiently parsing EPUB (CSS/Images) and other documents within the device's
|
||||||
|
capabilities.
|
||||||
|
* **Typography & Legibility:** E.g. Custom font support, hyphenation engines, and adjustable line spacing.
|
||||||
|
* **E-Ink Driver Refinement:** E.g. Reducing full-screen flashes (ghosting management) and improving general rendering.
|
||||||
|
* **Library Management:** E.g. Simple, intuitive ways to organize and navigate a collection of books.
|
||||||
|
* **Local Transfer:** E.g. Simple, "pull" based book loading via a basic web-server or public and widely-used standards.
|
||||||
|
* **Language Support:** E.g. Support for multiple languages both in the reader and in the interfaces.
|
||||||
|
|
||||||
|
### Out-of-Scope
|
||||||
|
|
||||||
|
*These items are rejected because they compromise the device's stability or mission.*
|
||||||
|
|
||||||
|
* **Interactive Apps:** No Notepads, Calculators, or Games. This is a reader, not a PDA.
|
||||||
|
* **Active Connectivity:** No RSS readers, News aggregators, or Web browsers. Background Wi-Fi tasks drain the battery
|
||||||
|
and complicate the single-core CPU's execution.
|
||||||
|
* **Media Playback:** No Audio players or Audio-books.
|
||||||
|
* **Complex Reader Features:** No highlighting, notes, or dictionary lookup. These features are better suited for
|
||||||
|
devices with better input capabilities and more powerful chips.
|
||||||
|
|
||||||
|
## 3. Idea Evaluation
|
||||||
|
|
||||||
|
While I appreciate the desire to add new and exciting features to CrossPoint Reader, CrossPoint Reader is designed to be
|
||||||
|
a lightweight, reliable, and performant e-reader. Things which distract or compromise the device's core mission will not
|
||||||
|
be accepted. As a guiding question, consider if your idea improve the "core reading experience" for the average user,
|
||||||
|
and, critically, not distract from that reading experience.
|
||||||
|
|
||||||
|
> **Note to Contributors:** If you are unsure if your idea fits the scope, please open a **Discussion** before you start
|
||||||
|
> coding!
|
||||||
@@ -13,14 +13,17 @@ Welcome to the **CrossPoint** firmware. This guide outlines the hardware control
|
|||||||
- [3.2 Book Selection](#32-book-selection)
|
- [3.2 Book Selection](#32-book-selection)
|
||||||
- [3.3 Reading Mode](#33-reading-mode)
|
- [3.3 Reading Mode](#33-reading-mode)
|
||||||
- [3.4 File Upload Screen](#34-file-upload-screen)
|
- [3.4 File Upload Screen](#34-file-upload-screen)
|
||||||
|
- [3.4.1 Calibre Wireless Transfers](#341-calibre-wireless-transfers)
|
||||||
- [3.5 Settings](#35-settings)
|
- [3.5 Settings](#35-settings)
|
||||||
- [3.6 Sleep Screen](#36-sleep-screen)
|
- [3.6 Sleep Screen](#36-sleep-screen)
|
||||||
- [4. Reading Mode](#4-reading-mode)
|
- [4. Reading Mode](#4-reading-mode)
|
||||||
- [Page Turning](#page-turning)
|
- [Page Turning](#page-turning)
|
||||||
- [Chapter Navigation](#chapter-navigation)
|
- [Chapter Navigation](#chapter-navigation)
|
||||||
- [System Navigation](#system-navigation)
|
- [System Navigation](#system-navigation)
|
||||||
|
- [Supported Languages](#supported-languages)
|
||||||
- [5. Chapter Selection Screen](#5-chapter-selection-screen)
|
- [5. Chapter Selection Screen](#5-chapter-selection-screen)
|
||||||
- [6. Current Limitations \& Roadmap](#6-current-limitations--roadmap)
|
- [6. Current Limitations \& Roadmap](#6-current-limitations--roadmap)
|
||||||
|
- [7. Troubleshooting Issues \& Escaping Bootloop](#7-troubleshooting-issues--escaping-bootloop)
|
||||||
|
|
||||||
|
|
||||||
## 1. Hardware Overview
|
## 1. Hardware Overview
|
||||||
@@ -102,6 +105,7 @@ The Settings screen allows you to configure the device's behavior. There are a f
|
|||||||
- "Custom" - Custom images from the SD card; see [Sleep Screen](#36-sleep-screen) below for more information
|
- "Custom" - Custom images from the SD card; see [Sleep Screen](#36-sleep-screen) below for more information
|
||||||
- "Cover" - The book cover image (Note: this is experimental and may not work as expected)
|
- "Cover" - The book cover image (Note: this is experimental and may not work as expected)
|
||||||
- "None" - A blank screen
|
- "None" - A blank screen
|
||||||
|
- "Cover + Custom" - The book cover image, fallbacks to "Custom" behavior
|
||||||
- **Sleep Screen Cover Mode**: How to display the book cover when "Cover" sleep screen is selected:
|
- **Sleep Screen Cover Mode**: How to display the book cover when "Cover" sleep screen is selected:
|
||||||
- "Fit" (default) - Scale the image down to fit centered on the screen, padding with white borders as necessary
|
- "Fit" (default) - Scale the image down to fit centered on the screen, padding with white borders as necessary
|
||||||
- "Crop" - Scale the image down and crop as necessary to try to to fill the screen (Note: this is experimental and may not work as expected)
|
- "Crop" - Scale the image down and crop as necessary to try to to fill the screen (Note: this is experimental and may not work as expected)
|
||||||
@@ -112,7 +116,10 @@ The Settings screen allows you to configure the device's behavior. There are a f
|
|||||||
- **Status Bar**: Configure the status bar displayed while reading:
|
- **Status Bar**: Configure the status bar displayed while reading:
|
||||||
- "None" - No status bar
|
- "None" - No status bar
|
||||||
- "No Progress" - Show status bar without reading progress
|
- "No Progress" - Show status bar without reading progress
|
||||||
- "Full" - Show status bar with reading progress
|
- "Full w/ Percentage" - Show status bar with book progress (as percentage)
|
||||||
|
- "Full w/ Book Bar" - Show status bar with book progress (as bar)
|
||||||
|
- "Book Bar Only" - Show book progress (as bar)
|
||||||
|
- "Full w/ Chapter Bar" - Show status bar with chapter progress (as bar)
|
||||||
- **Hide Battery %**: Configure where to suppress the battery pecentage display in the status bar; the battery icon will still be shown:
|
- **Hide Battery %**: Configure where to suppress the battery pecentage display in the status bar; the battery icon will still be shown:
|
||||||
- "Never" - Always show battery percentage (default)
|
- "Never" - Always show battery percentage (default)
|
||||||
- "In Reader" - Show battery percentage everywhere except in reading mode
|
- "In Reader" - Show battery percentage everywhere except in reading mode
|
||||||
@@ -148,6 +155,9 @@ The Settings screen allows you to configure the device's behavior. There are a f
|
|||||||
- **Reader Paragraph Alignment**: Set the alignment of paragraphs; options are "Justified" (default), "Left", "Center", or "Right".
|
- **Reader Paragraph Alignment**: Set the alignment of paragraphs; options are "Justified" (default), "Left", "Center", or "Right".
|
||||||
- **Time to Sleep**: Set the duration of inactivity before the device automatically goes to sleep.
|
- **Time to Sleep**: Set the duration of inactivity before the device automatically goes to sleep.
|
||||||
- **Refresh Frequency**: Set how often the screen does a full refresh while reading to reduce ghosting.
|
- **Refresh Frequency**: Set how often the screen does a full refresh while reading to reduce ghosting.
|
||||||
|
- **Sunlight Fading Fix**: Configure whether to enable a software-fix for the issue where white X4 models may fade when used in direct sunlight
|
||||||
|
- "OFF" (default) - Disable the fix
|
||||||
|
- "ON" - Enable the fix
|
||||||
- **OPDS Browser**: Configure OPDS server settings for browsing and downloading books. Set the server URL (for Calibre Content Server, add `/opds` to the end), and optionally configure username and password for servers requiring authentication. Note: Only HTTP Basic authentication is supported. If using Calibre Content Server with authentication enabled, you must set it to use Basic authentication instead of the default Digest authentication.
|
- **OPDS Browser**: Configure OPDS server settings for browsing and downloading books. Set the server URL (for Calibre Content Server, add `/opds` to the end), and optionally configure username and password for servers requiring authentication. Note: Only HTTP Basic authentication is supported. If using Calibre Content Server with authentication enabled, you must set it to use Basic authentication instead of the default Digest authentication.
|
||||||
- **Check for updates**: Check for firmware updates over WiFi.
|
- **Check for updates**: Check for firmware updates over WiFi.
|
||||||
|
|
||||||
@@ -201,7 +211,7 @@ CrossPoint renders text using the following Unicode character blocks, enabling s
|
|||||||
* **Latin Script (Basic, Supplement, Extended-A):** Covers English, German, French, Spanish, Portuguese, Italian, Dutch, Swedish, Norwegian, Danish, Finnish, Polish, Czech, Hungarian, Romanian, Slovak, Slovenian, Turkish, and others.
|
* **Latin Script (Basic, Supplement, Extended-A):** Covers English, German, French, Spanish, Portuguese, Italian, Dutch, Swedish, Norwegian, Danish, Finnish, Polish, Czech, Hungarian, Romanian, Slovak, Slovenian, Turkish, and others.
|
||||||
* **Cyrillic Script (Standard and Extended):** Covers Russian, Ukrainian, Belarusian, Bulgarian, Serbian, Macedonian, Kazakh, Kyrgyz, Mongolian, and others.
|
* **Cyrillic Script (Standard and Extended):** Covers Russian, Ukrainian, Belarusian, Bulgarian, Serbian, Macedonian, Kazakh, Kyrgyz, Mongolian, and others.
|
||||||
|
|
||||||
What is not supported: Chinese, Japanese, Korean, Vietnamese, Hebrew, Arabic and Farsi.
|
What is not supported: Chinese, Japanese, Korean, Vietnamese, Hebrew, Arabic, Greek and Farsi.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -220,3 +230,18 @@ 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.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. Troubleshooting Issues & Escaping Bootloop
|
||||||
|
|
||||||
|
If an issue or crash is encountered while using Crosspoint, feel free to raise an issue ticket and attach the serial monitor logs. The logs can be obtained by connecting the device to a computer and starting a serial monitor. Either [Serial Monitor](https://www.serialmonitor.org/) or the following command can be used:
|
||||||
|
|
||||||
|
```
|
||||||
|
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.
|
||||||
|
|
||||||
|
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).
|
||||||
|
|||||||
@@ -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
|
||||||
|
|||||||
@@ -153,7 +153,7 @@ Click **File Manager** to access file management features.
|
|||||||
|
|
||||||
1. Click the **+ Add** button in the top-right corner
|
1. Click the **+ Add** button in the top-right corner
|
||||||
2. Select **New Folder** from the dropdown menu
|
2. Select **New Folder** from the dropdown menu
|
||||||
3. Enter a folder name (letters, numbers, underscores, and hyphens only)
|
3. Enter a folder name (must not contain characters \" * : < > ? / \\ | and must not be . or ..)
|
||||||
4. Click **Create Folder**
|
4. Click **Create Folder**
|
||||||
|
|
||||||
This is useful for organizing your ebooks by genre, author, or series.
|
This is useful for organizing your ebooks by genre, author, or series.
|
||||||
|
|||||||
@@ -1,23 +1,19 @@
|
|||||||
#include "EpdFontFamily.h"
|
#include "EpdFontFamily.h"
|
||||||
|
|
||||||
const EpdFont* EpdFontFamily::getFont(const Style style) const {
|
const EpdFont* EpdFontFamily::getFont(const Style style) const {
|
||||||
if (style == BOLD && bold) {
|
// Extract font style bits (ignore UNDERLINE bit for font selection)
|
||||||
|
const bool hasBold = (style & BOLD) != 0;
|
||||||
|
const bool hasItalic = (style & ITALIC) != 0;
|
||||||
|
|
||||||
|
if (hasBold && hasItalic) {
|
||||||
|
if (boldItalic) return boldItalic;
|
||||||
|
if (bold) return bold;
|
||||||
|
if (italic) return italic;
|
||||||
|
} else if (hasBold && bold) {
|
||||||
return bold;
|
return bold;
|
||||||
}
|
} else if (hasItalic && italic) {
|
||||||
if (style == ITALIC && italic) {
|
|
||||||
return italic;
|
return italic;
|
||||||
}
|
}
|
||||||
if (style == BOLD_ITALIC) {
|
|
||||||
if (boldItalic) {
|
|
||||||
return boldItalic;
|
|
||||||
}
|
|
||||||
if (bold) {
|
|
||||||
return bold;
|
|
||||||
}
|
|
||||||
if (italic) {
|
|
||||||
return italic;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return regular;
|
return regular;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
|
|
||||||
class EpdFontFamily {
|
class EpdFontFamily {
|
||||||
public:
|
public:
|
||||||
enum Style : uint8_t { REGULAR = 0, BOLD = 1, ITALIC = 2, BOLD_ITALIC = 3 };
|
enum Style : uint8_t { REGULAR = 0, BOLD = 1, ITALIC = 2, BOLD_ITALIC = 3, UNDERLINE = 4 };
|
||||||
|
|
||||||
explicit EpdFontFamily(const EpdFont* regular, const EpdFont* bold = nullptr, const EpdFont* italic = nullptr,
|
explicit EpdFontFamily(const EpdFont* regular, const EpdFont* bold = nullptr, const EpdFont* italic = nullptr,
|
||||||
const EpdFont* boldItalic = nullptr)
|
const EpdFont* boldItalic = nullptr)
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
|
#ifndef OMIT_BOOKERLY
|
||||||
#include <builtinFonts/bookerly_12_bold.h>
|
#include <builtinFonts/bookerly_12_bold.h>
|
||||||
#include <builtinFonts/bookerly_12_bolditalic.h>
|
#include <builtinFonts/bookerly_12_bolditalic.h>
|
||||||
#include <builtinFonts/bookerly_12_italic.h>
|
#include <builtinFonts/bookerly_12_italic.h>
|
||||||
@@ -16,7 +17,10 @@
|
|||||||
#include <builtinFonts/bookerly_18_bolditalic.h>
|
#include <builtinFonts/bookerly_18_bolditalic.h>
|
||||||
#include <builtinFonts/bookerly_18_italic.h>
|
#include <builtinFonts/bookerly_18_italic.h>
|
||||||
#include <builtinFonts/bookerly_18_regular.h>
|
#include <builtinFonts/bookerly_18_regular.h>
|
||||||
|
#endif // OMIT_BOOKERLY
|
||||||
|
|
||||||
#include <builtinFonts/notosans_8_regular.h>
|
#include <builtinFonts/notosans_8_regular.h>
|
||||||
|
#ifndef OMIT_NOTOSANS
|
||||||
#include <builtinFonts/notosans_12_bold.h>
|
#include <builtinFonts/notosans_12_bold.h>
|
||||||
#include <builtinFonts/notosans_12_bolditalic.h>
|
#include <builtinFonts/notosans_12_bolditalic.h>
|
||||||
#include <builtinFonts/notosans_12_italic.h>
|
#include <builtinFonts/notosans_12_italic.h>
|
||||||
@@ -33,6 +37,9 @@
|
|||||||
#include <builtinFonts/notosans_18_bolditalic.h>
|
#include <builtinFonts/notosans_18_bolditalic.h>
|
||||||
#include <builtinFonts/notosans_18_italic.h>
|
#include <builtinFonts/notosans_18_italic.h>
|
||||||
#include <builtinFonts/notosans_18_regular.h>
|
#include <builtinFonts/notosans_18_regular.h>
|
||||||
|
#endif // OMIT_NOTOSANS
|
||||||
|
|
||||||
|
#ifndef OMIT_OPENDYSLEXIC
|
||||||
#include <builtinFonts/opendyslexic_10_bold.h>
|
#include <builtinFonts/opendyslexic_10_bold.h>
|
||||||
#include <builtinFonts/opendyslexic_10_bolditalic.h>
|
#include <builtinFonts/opendyslexic_10_bolditalic.h>
|
||||||
#include <builtinFonts/opendyslexic_10_italic.h>
|
#include <builtinFonts/opendyslexic_10_italic.h>
|
||||||
@@ -49,6 +56,8 @@
|
|||||||
#include <builtinFonts/opendyslexic_8_bolditalic.h>
|
#include <builtinFonts/opendyslexic_8_bolditalic.h>
|
||||||
#include <builtinFonts/opendyslexic_8_italic.h>
|
#include <builtinFonts/opendyslexic_8_italic.h>
|
||||||
#include <builtinFonts/opendyslexic_8_regular.h>
|
#include <builtinFonts/opendyslexic_8_regular.h>
|
||||||
|
#endif // OMIT_OPENDYSLEXIC
|
||||||
|
|
||||||
#include <builtinFonts/ubuntu_10_bold.h>
|
#include <builtinFonts/ubuntu_10_bold.h>
|
||||||
#include <builtinFonts/ubuntu_10_regular.h>
|
#include <builtinFonts/ubuntu_10_regular.h>
|
||||||
#include <builtinFonts/ubuntu_12_bold.h>
|
#include <builtinFonts/ubuntu_12_bold.h>
|
||||||
|
|||||||
@@ -1,11 +1,14 @@
|
|||||||
#include "Epub.h"
|
#include "Epub.h"
|
||||||
|
|
||||||
#include <FsHelpers.h>
|
#include <FsHelpers.h>
|
||||||
#include <HardwareSerial.h>
|
#include <HalDisplay.h>
|
||||||
|
#include <HalStorage.h>
|
||||||
#include <JpegToBmpConverter.h>
|
#include <JpegToBmpConverter.h>
|
||||||
#include <SDCardManager.h>
|
#include <Logging.h>
|
||||||
#include <ZipFile.h>
|
#include <ZipFile.h>
|
||||||
|
|
||||||
|
#include <algorithm>
|
||||||
|
|
||||||
#include "Epub/parsers/ContainerParser.h"
|
#include "Epub/parsers/ContainerParser.h"
|
||||||
#include "Epub/parsers/ContentOpfParser.h"
|
#include "Epub/parsers/ContentOpfParser.h"
|
||||||
#include "Epub/parsers/TocNavParser.h"
|
#include "Epub/parsers/TocNavParser.h"
|
||||||
@@ -17,7 +20,7 @@ bool Epub::findContentOpfFile(std::string* contentOpfFile) const {
|
|||||||
|
|
||||||
// Get file size without loading it all into heap
|
// Get file size without loading it all into heap
|
||||||
if (!getItemSize(containerPath, &containerSize)) {
|
if (!getItemSize(containerPath, &containerSize)) {
|
||||||
Serial.printf("[%lu] [EBP] Could not find or size META-INF/container.xml\n", millis());
|
LOG_ERR("EBP", "Could not find or size META-INF/container.xml");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -29,13 +32,13 @@ bool Epub::findContentOpfFile(std::string* contentOpfFile) const {
|
|||||||
|
|
||||||
// Stream read (reusing your existing stream logic)
|
// Stream read (reusing your existing stream logic)
|
||||||
if (!readItemContentsToStream(containerPath, containerParser, 512)) {
|
if (!readItemContentsToStream(containerPath, containerParser, 512)) {
|
||||||
Serial.printf("[%lu] [EBP] Could not read META-INF/container.xml\n", millis());
|
LOG_ERR("EBP", "Could not read META-INF/container.xml");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Extract the result
|
// Extract the result
|
||||||
if (containerParser.fullPath.empty()) {
|
if (containerParser.fullPath.empty()) {
|
||||||
Serial.printf("[%lu] [EBP] Could not find valid rootfile in container.xml\n", millis());
|
LOG_ERR("EBP", "Could not find valid rootfile in container.xml");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -46,28 +49,28 @@ bool Epub::findContentOpfFile(std::string* contentOpfFile) const {
|
|||||||
bool Epub::parseContentOpf(BookMetadataCache::BookMetadata& bookMetadata) {
|
bool Epub::parseContentOpf(BookMetadataCache::BookMetadata& bookMetadata) {
|
||||||
std::string contentOpfFilePath;
|
std::string contentOpfFilePath;
|
||||||
if (!findContentOpfFile(&contentOpfFilePath)) {
|
if (!findContentOpfFile(&contentOpfFilePath)) {
|
||||||
Serial.printf("[%lu] [EBP] Could not find content.opf in zip\n", millis());
|
LOG_ERR("EBP", "Could not find content.opf in zip");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
contentBasePath = contentOpfFilePath.substr(0, contentOpfFilePath.find_last_of('/') + 1);
|
contentBasePath = contentOpfFilePath.substr(0, contentOpfFilePath.find_last_of('/') + 1);
|
||||||
|
|
||||||
Serial.printf("[%lu] [EBP] Parsing content.opf: %s\n", millis(), contentOpfFilePath.c_str());
|
LOG_DBG("EBP", "Parsing content.opf: %s", contentOpfFilePath.c_str());
|
||||||
|
|
||||||
size_t contentOpfSize;
|
size_t contentOpfSize;
|
||||||
if (!getItemSize(contentOpfFilePath, &contentOpfSize)) {
|
if (!getItemSize(contentOpfFilePath, &contentOpfSize)) {
|
||||||
Serial.printf("[%lu] [EBP] Could not get size of content.opf\n", millis());
|
LOG_ERR("EBP", "Could not get size of content.opf");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
ContentOpfParser opfParser(getCachePath(), getBasePath(), contentOpfSize, bookMetadataCache.get());
|
ContentOpfParser opfParser(getCachePath(), getBasePath(), contentOpfSize, bookMetadataCache.get());
|
||||||
if (!opfParser.setup()) {
|
if (!opfParser.setup()) {
|
||||||
Serial.printf("[%lu] [EBP] Could not setup content.opf parser\n", millis());
|
LOG_ERR("EBP", "Could not setup content.opf parser");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!readItemContentsToStream(contentOpfFilePath, opfParser, 1024)) {
|
if (!readItemContentsToStream(contentOpfFilePath, opfParser, 1024)) {
|
||||||
Serial.printf("[%lu] [EBP] Could not read content.opf\n", millis());
|
LOG_ERR("EBP", "Could not read content.opf");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -86,27 +89,31 @@ bool Epub::parseContentOpf(BookMetadataCache::BookMetadata& bookMetadata) {
|
|||||||
tocNavItem = opfParser.tocNavPath;
|
tocNavItem = opfParser.tocNavPath;
|
||||||
}
|
}
|
||||||
|
|
||||||
Serial.printf("[%lu] [EBP] Successfully parsed content.opf\n", millis());
|
if (!opfParser.cssFiles.empty()) {
|
||||||
|
cssFiles = opfParser.cssFiles;
|
||||||
|
}
|
||||||
|
|
||||||
|
LOG_DBG("EBP", "Successfully parsed content.opf");
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
bool Epub::parseTocNcxFile() const {
|
bool Epub::parseTocNcxFile() const {
|
||||||
// the ncx file should have been specified in the content.opf file
|
// the ncx file should have been specified in the content.opf file
|
||||||
if (tocNcxItem.empty()) {
|
if (tocNcxItem.empty()) {
|
||||||
Serial.printf("[%lu] [EBP] No ncx file specified\n", millis());
|
LOG_DBG("EBP", "No ncx file specified");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
Serial.printf("[%lu] [EBP] Parsing toc ncx file: %s\n", millis(), tocNcxItem.c_str());
|
LOG_DBG("EBP", "Parsing toc ncx file: %s", tocNcxItem.c_str());
|
||||||
|
|
||||||
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();
|
||||||
@@ -114,14 +121,14 @@ bool Epub::parseTocNcxFile() const {
|
|||||||
TocNcxParser ncxParser(contentBasePath, ncxSize, bookMetadataCache.get());
|
TocNcxParser ncxParser(contentBasePath, ncxSize, bookMetadataCache.get());
|
||||||
|
|
||||||
if (!ncxParser.setup()) {
|
if (!ncxParser.setup()) {
|
||||||
Serial.printf("[%lu] [EBP] Could not setup toc ncx parser\n", millis());
|
LOG_ERR("EBP", "Could not setup toc ncx parser");
|
||||||
tempNcxFile.close();
|
tempNcxFile.close();
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
const auto ncxBuffer = static_cast<uint8_t*>(malloc(1024));
|
const auto ncxBuffer = static_cast<uint8_t*>(malloc(1024));
|
||||||
if (!ncxBuffer) {
|
if (!ncxBuffer) {
|
||||||
Serial.printf("[%lu] [EBP] Could not allocate memory for toc ncx parser\n", millis());
|
LOG_ERR("EBP", "Could not allocate memory for toc ncx parser");
|
||||||
tempNcxFile.close();
|
tempNcxFile.close();
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@@ -132,7 +139,7 @@ bool Epub::parseTocNcxFile() const {
|
|||||||
const auto processedSize = ncxParser.write(ncxBuffer, readSize);
|
const auto processedSize = ncxParser.write(ncxBuffer, readSize);
|
||||||
|
|
||||||
if (processedSize != readSize) {
|
if (processedSize != readSize) {
|
||||||
Serial.printf("[%lu] [EBP] Could not process all toc ncx data\n", millis());
|
LOG_ERR("EBP", "Could not process all toc ncx data");
|
||||||
free(ncxBuffer);
|
free(ncxBuffer);
|
||||||
tempNcxFile.close();
|
tempNcxFile.close();
|
||||||
return false;
|
return false;
|
||||||
@@ -141,29 +148,29 @@ 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());
|
LOG_DBG("EBP", "Parsed TOC items");
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
bool Epub::parseTocNavFile() const {
|
bool Epub::parseTocNavFile() const {
|
||||||
// the nav file should have been specified in the content.opf file (EPUB 3)
|
// the nav file should have been specified in the content.opf file (EPUB 3)
|
||||||
if (tocNavItem.empty()) {
|
if (tocNavItem.empty()) {
|
||||||
Serial.printf("[%lu] [EBP] No nav file specified\n", millis());
|
LOG_DBG("EBP", "No nav file specified");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
Serial.printf("[%lu] [EBP] Parsing toc nav file: %s\n", millis(), tocNavItem.c_str());
|
LOG_DBG("EBP", "Parsing toc nav file: %s", tocNavItem.c_str());
|
||||||
|
|
||||||
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();
|
||||||
@@ -174,13 +181,13 @@ bool Epub::parseTocNavFile() const {
|
|||||||
TocNavParser navParser(navContentBasePath, navSize, bookMetadataCache.get());
|
TocNavParser navParser(navContentBasePath, navSize, bookMetadataCache.get());
|
||||||
|
|
||||||
if (!navParser.setup()) {
|
if (!navParser.setup()) {
|
||||||
Serial.printf("[%lu] [EBP] Could not setup toc nav parser\n", millis());
|
LOG_ERR("EBP", "Could not setup toc nav parser");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
const auto navBuffer = static_cast<uint8_t*>(malloc(1024));
|
const auto navBuffer = static_cast<uint8_t*>(malloc(1024));
|
||||||
if (!navBuffer) {
|
if (!navBuffer) {
|
||||||
Serial.printf("[%lu] [EBP] Could not allocate memory for toc nav parser\n", millis());
|
LOG_ERR("EBP", "Could not allocate memory for toc nav parser");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -189,7 +196,7 @@ bool Epub::parseTocNavFile() const {
|
|||||||
const auto processedSize = navParser.write(navBuffer, readSize);
|
const auto processedSize = navParser.write(navBuffer, readSize);
|
||||||
|
|
||||||
if (processedSize != readSize) {
|
if (processedSize != readSize) {
|
||||||
Serial.printf("[%lu] [EBP] Could not process all toc nav data\n", millis());
|
LOG_ERR("EBP", "Could not process all toc nav data");
|
||||||
free(navBuffer);
|
free(navBuffer);
|
||||||
tempNavFile.close();
|
tempNavFile.close();
|
||||||
return false;
|
return false;
|
||||||
@@ -198,22 +205,80 @@ 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());
|
LOG_DBG("EBP", "Parsed TOC nav items");
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void Epub::parseCssFiles() const {
|
||||||
|
if (cssFiles.empty()) {
|
||||||
|
LOG_DBG("EBP", "No CSS files to parse, but CssParser created for inline styles");
|
||||||
|
}
|
||||||
|
|
||||||
|
// See if we have a cached version of the CSS rules
|
||||||
|
if (!cssParser->hasCache()) {
|
||||||
|
// No cache yet - parse CSS files
|
||||||
|
for (const auto& cssPath : cssFiles) {
|
||||||
|
LOG_DBG("EBP", "Parsing CSS file: %s", cssPath.c_str());
|
||||||
|
|
||||||
|
// Extract CSS file to temp location
|
||||||
|
const auto tmpCssPath = getCachePath() + "/.tmp.css";
|
||||||
|
FsFile tempCssFile;
|
||||||
|
if (!Storage.openFileForWrite("EBP", tmpCssPath, tempCssFile)) {
|
||||||
|
LOG_ERR("EBP", "Could not create temp CSS file");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (!readItemContentsToStream(cssPath, tempCssFile, 1024)) {
|
||||||
|
LOG_ERR("EBP", "Could not read CSS file: %s", cssPath.c_str());
|
||||||
|
tempCssFile.close();
|
||||||
|
Storage.remove(tmpCssPath.c_str());
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
tempCssFile.close();
|
||||||
|
|
||||||
|
// Parse the CSS file
|
||||||
|
if (!Storage.openFileForRead("EBP", tmpCssPath, tempCssFile)) {
|
||||||
|
LOG_ERR("EBP", "Could not open temp CSS file for reading");
|
||||||
|
Storage.remove(tmpCssPath.c_str());
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
cssParser->loadFromStream(tempCssFile);
|
||||||
|
tempCssFile.close();
|
||||||
|
Storage.remove(tmpCssPath.c_str());
|
||||||
|
}
|
||||||
|
|
||||||
|
// Save to cache for next time
|
||||||
|
if (!cssParser->saveToCache()) {
|
||||||
|
LOG_ERR("EBP", "Failed to save CSS rules to cache");
|
||||||
|
}
|
||||||
|
cssParser->clear();
|
||||||
|
|
||||||
|
LOG_DBG("EBP", "Loaded %zu CSS style rules from %zu files", cssParser->ruleCount(), cssFiles.size());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// load in the meta data for the epub file
|
// load in the meta data for the epub file
|
||||||
bool Epub::load(const bool buildIfMissing) {
|
bool Epub::load(const bool buildIfMissing, const bool skipLoadingCss) {
|
||||||
Serial.printf("[%lu] [EBP] Loading ePub: %s\n", millis(), filepath.c_str());
|
LOG_DBG("EBP", "Loading ePub: %s", filepath.c_str());
|
||||||
|
|
||||||
// Initialize spine/TOC cache
|
// Initialize spine/TOC cache
|
||||||
bookMetadataCache.reset(new BookMetadataCache(cachePath));
|
bookMetadataCache.reset(new BookMetadataCache(cachePath));
|
||||||
|
// Always create CssParser - needed for inline style parsing even without CSS files
|
||||||
|
cssParser.reset(new CssParser(cachePath));
|
||||||
|
|
||||||
// Try to load existing cache first
|
// Try to load existing cache first
|
||||||
if (bookMetadataCache->load()) {
|
if (bookMetadataCache->load()) {
|
||||||
Serial.printf("[%lu] [EBP] Loaded ePub: %s\n", millis(), filepath.c_str());
|
if (!skipLoadingCss && !cssParser->hasCache()) {
|
||||||
|
LOG_DBG("EBP", "Warning: CSS rules cache not found, attempting to parse CSS files");
|
||||||
|
// to get CSS file list
|
||||||
|
if (!parseContentOpf(bookMetadataCache->coreMetadata)) {
|
||||||
|
LOG_ERR("EBP", "Could not parse content.opf from cached bookMetadata for CSS files");
|
||||||
|
// continue anyway - book will work without CSS and we'll still load any inline style CSS
|
||||||
|
}
|
||||||
|
parseCssFiles();
|
||||||
|
}
|
||||||
|
LOG_DBG("EBP", "Loaded ePub: %s", filepath.c_str());
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -223,14 +288,14 @@ bool Epub::load(const bool buildIfMissing) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Cache doesn't exist or is invalid, build it
|
// Cache doesn't exist or is invalid, build it
|
||||||
Serial.printf("[%lu] [EBP] Cache not found, building spine/TOC cache\n", millis());
|
LOG_DBG("EBP", "Cache not found, building spine/TOC cache");
|
||||||
setupCacheDir();
|
setupCacheDir();
|
||||||
|
|
||||||
const uint32_t indexingStart = millis();
|
const uint32_t indexingStart = millis();
|
||||||
|
|
||||||
// Begin building cache - stream entries to disk immediately
|
// Begin building cache - stream entries to disk immediately
|
||||||
if (!bookMetadataCache->beginWrite()) {
|
if (!bookMetadataCache->beginWrite()) {
|
||||||
Serial.printf("[%lu] [EBP] Could not begin writing cache\n", millis());
|
LOG_ERR("EBP", "Could not begin writing cache");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -238,23 +303,23 @@ bool Epub::load(const bool buildIfMissing) {
|
|||||||
const uint32_t opfStart = millis();
|
const uint32_t opfStart = millis();
|
||||||
BookMetadataCache::BookMetadata bookMetadata;
|
BookMetadataCache::BookMetadata bookMetadata;
|
||||||
if (!bookMetadataCache->beginContentOpfPass()) {
|
if (!bookMetadataCache->beginContentOpfPass()) {
|
||||||
Serial.printf("[%lu] [EBP] Could not begin writing content.opf pass\n", millis());
|
LOG_ERR("EBP", "Could not begin writing content.opf pass");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
if (!parseContentOpf(bookMetadata)) {
|
if (!parseContentOpf(bookMetadata)) {
|
||||||
Serial.printf("[%lu] [EBP] Could not parse content.opf\n", millis());
|
LOG_ERR("EBP", "Could not parse content.opf");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
if (!bookMetadataCache->endContentOpfPass()) {
|
if (!bookMetadataCache->endContentOpfPass()) {
|
||||||
Serial.printf("[%lu] [EBP] Could not end writing content.opf pass\n", millis());
|
LOG_ERR("EBP", "Could not end writing content.opf pass");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
Serial.printf("[%lu] [EBP] OPF pass completed in %lu ms\n", millis(), millis() - opfStart);
|
LOG_DBG("EBP", "OPF pass completed in %lu ms", millis() - opfStart);
|
||||||
|
|
||||||
// TOC Pass - try EPUB 3 nav first, fall back to NCX
|
// TOC Pass - try EPUB 3 nav first, fall back to NCX
|
||||||
const uint32_t tocStart = millis();
|
const uint32_t tocStart = millis();
|
||||||
if (!bookMetadataCache->beginTocPass()) {
|
if (!bookMetadataCache->beginTocPass()) {
|
||||||
Serial.printf("[%lu] [EBP] Could not begin writing toc pass\n", millis());
|
LOG_ERR("EBP", "Could not begin writing toc pass");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -262,78 +327,83 @@ bool Epub::load(const bool buildIfMissing) {
|
|||||||
|
|
||||||
// Try EPUB 3 nav document first (preferred)
|
// Try EPUB 3 nav document first (preferred)
|
||||||
if (!tocNavItem.empty()) {
|
if (!tocNavItem.empty()) {
|
||||||
Serial.printf("[%lu] [EBP] Attempting to parse EPUB 3 nav document\n", millis());
|
LOG_DBG("EBP", "Attempting to parse EPUB 3 nav document");
|
||||||
tocParsed = parseTocNavFile();
|
tocParsed = parseTocNavFile();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Fall back to NCX if nav parsing failed or wasn't available
|
// Fall back to NCX if nav parsing failed or wasn't available
|
||||||
if (!tocParsed && !tocNcxItem.empty()) {
|
if (!tocParsed && !tocNcxItem.empty()) {
|
||||||
Serial.printf("[%lu] [EBP] Falling back to NCX TOC\n", millis());
|
LOG_DBG("EBP", "Falling back to NCX TOC");
|
||||||
tocParsed = parseTocNcxFile();
|
tocParsed = parseTocNcxFile();
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!tocParsed) {
|
if (!tocParsed) {
|
||||||
Serial.printf("[%lu] [EBP] Warning: Could not parse any TOC format\n", millis());
|
LOG_ERR("EBP", "Warning: Could not parse any TOC format");
|
||||||
// Continue anyway - book will work without TOC
|
// Continue anyway - book will work without TOC
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!bookMetadataCache->endTocPass()) {
|
if (!bookMetadataCache->endTocPass()) {
|
||||||
Serial.printf("[%lu] [EBP] Could not end writing toc pass\n", millis());
|
LOG_ERR("EBP", "Could not end writing toc pass");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
Serial.printf("[%lu] [EBP] TOC pass completed in %lu ms\n", millis(), millis() - tocStart);
|
LOG_DBG("EBP", "TOC pass completed in %lu ms", millis() - tocStart);
|
||||||
|
|
||||||
// Close the cache files
|
// Close the cache files
|
||||||
if (!bookMetadataCache->endWrite()) {
|
if (!bookMetadataCache->endWrite()) {
|
||||||
Serial.printf("[%lu] [EBP] Could not end writing cache\n", millis());
|
LOG_ERR("EBP", "Could not end writing cache");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Build final book.bin
|
// Build final book.bin
|
||||||
const uint32_t buildStart = millis();
|
const uint32_t buildStart = millis();
|
||||||
if (!bookMetadataCache->buildBookBin(filepath, bookMetadata)) {
|
if (!bookMetadataCache->buildBookBin(filepath, bookMetadata)) {
|
||||||
Serial.printf("[%lu] [EBP] Could not update mappings and sizes\n", millis());
|
LOG_ERR("EBP", "Could not update mappings and sizes");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
Serial.printf("[%lu] [EBP] buildBookBin completed in %lu ms\n", millis(), millis() - buildStart);
|
LOG_DBG("EBP", "buildBookBin completed in %lu ms", millis() - buildStart);
|
||||||
Serial.printf("[%lu] [EBP] Total indexing completed in %lu ms\n", millis(), millis() - indexingStart);
|
LOG_DBG("EBP", "Total indexing completed in %lu ms", millis() - indexingStart);
|
||||||
|
|
||||||
if (!bookMetadataCache->cleanupTmpFiles()) {
|
if (!bookMetadataCache->cleanupTmpFiles()) {
|
||||||
Serial.printf("[%lu] [EBP] Could not cleanup tmp files - ignoring\n", millis());
|
LOG_DBG("EBP", "Could not cleanup tmp files - ignoring");
|
||||||
}
|
}
|
||||||
|
|
||||||
// Reload the cache from disk so it's in the correct state
|
// Reload the cache from disk so it's in the correct state
|
||||||
bookMetadataCache.reset(new BookMetadataCache(cachePath));
|
bookMetadataCache.reset(new BookMetadataCache(cachePath));
|
||||||
if (!bookMetadataCache->load()) {
|
if (!bookMetadataCache->load()) {
|
||||||
Serial.printf("[%lu] [EBP] Failed to reload cache after writing\n", millis());
|
LOG_ERR("EBP", "Failed to reload cache after writing");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
Serial.printf("[%lu] [EBP] Loaded ePub: %s\n", millis(), filepath.c_str());
|
if (!skipLoadingCss) {
|
||||||
|
// Parse CSS files after cache reload
|
||||||
|
parseCssFiles();
|
||||||
|
}
|
||||||
|
|
||||||
|
LOG_DBG("EBP", "Loaded ePub: %s", filepath.c_str());
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
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());
|
LOG_DBG("EPB", "Cache does not exist, no action needed");
|
||||||
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());
|
LOG_ERR("EPB", "Failed to clear cache");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
Serial.printf("[%lu] [EPB] Cache cleared successfully\n", millis());
|
LOG_DBG("EPB", "Cache cleared successfully");
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
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; }
|
||||||
@@ -373,128 +443,357 @@ std::string Epub::getCoverBmpPath(bool cropped) const {
|
|||||||
}
|
}
|
||||||
|
|
||||||
bool Epub::generateCoverBmp(bool cropped) const {
|
bool Epub::generateCoverBmp(bool cropped) const {
|
||||||
|
bool invalid = false;
|
||||||
// Already generated, return true
|
// Already generated, return true
|
||||||
if (SdMan.exists(getCoverBmpPath(cropped).c_str())) {
|
if (Storage.exists(getCoverBmpPath(cropped).c_str())) {
|
||||||
|
// is this a valid cover or just an empty file we created to mark generation attempts?
|
||||||
|
invalid = !isValidThumbnailBmp(getCoverBmpPath(cropped));
|
||||||
|
if (invalid) {
|
||||||
|
// Remove the old invalid cover so we can attempt to generate a new one
|
||||||
|
Storage.remove(getCoverBmpPath(cropped).c_str());
|
||||||
|
LOG_DBG("EBP", "Previous cover generation attempt failed for %s mode, retrying", cropped ? "cropped" : "fit");
|
||||||
|
} else {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if (!bookMetadataCache || !bookMetadataCache->isLoaded()) {
|
if (!bookMetadataCache || !bookMetadataCache->isLoaded()) {
|
||||||
Serial.printf("[%lu] [EBP] Cannot generate cover BMP, cache not loaded\n", millis());
|
LOG_ERR("EBP", "Cannot generate cover BMP, cache not loaded");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
const auto coverImageHref = bookMetadataCache->coreMetadata.coverItemHref;
|
const auto coverImageHref = bookMetadataCache->coreMetadata.coverItemHref;
|
||||||
|
std::string effectiveCoverImageHref = coverImageHref;
|
||||||
if (coverImageHref.empty()) {
|
if (coverImageHref.empty()) {
|
||||||
Serial.printf("[%lu] [EBP] No known cover image\n", millis());
|
// Fallback: try common cover filenames
|
||||||
|
std::vector<std::string> coverCandidates = getCoverCandidates();
|
||||||
|
for (const auto& candidate : coverCandidates) {
|
||||||
|
effectiveCoverImageHref = candidate;
|
||||||
|
// Try to read a small amount to check if exists
|
||||||
|
uint8_t* test = readItemContentsToBytes(candidate, nullptr, false);
|
||||||
|
if (test) {
|
||||||
|
free(test);
|
||||||
|
break;
|
||||||
|
} else {
|
||||||
|
effectiveCoverImageHref.clear();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (effectiveCoverImageHref.empty()) {
|
||||||
|
LOG_ERR("EBP", "No known cover image");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (coverImageHref.substr(coverImageHref.length() - 4) == ".jpg" ||
|
// Check for JPG/JPEG extensions (case insensitive)
|
||||||
coverImageHref.substr(coverImageHref.length() - 5) == ".jpeg") {
|
std::string lowerHref = effectiveCoverImageHref;
|
||||||
Serial.printf("[%lu] [EBP] Generating BMP from JPG cover image (%s mode)\n", millis(), cropped ? "cropped" : "fit");
|
std::transform(lowerHref.begin(), lowerHref.end(), lowerHref.begin(), ::tolower);
|
||||||
|
bool isJpg =
|
||||||
|
lowerHref.substr(lowerHref.length() - 4) == ".jpg" || lowerHref.substr(lowerHref.length() - 5) == ".jpeg";
|
||||||
|
if (isJpg) {
|
||||||
|
LOG_DBG("EBP", "Generating BMP from JPG cover image (%s mode)", cropped ? "cropped" : "fit");
|
||||||
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(effectiveCoverImageHref, 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());
|
LOG_ERR("EBP", "Failed to generate BMP from cover image");
|
||||||
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");
|
LOG_DBG("EBP", "Generated BMP from cover image, success: %s", success ? "yes" : "no");
|
||||||
return success;
|
return success;
|
||||||
} else {
|
} else {
|
||||||
Serial.printf("[%lu] [EBP] Cover image is not a JPG, skipping\n", millis());
|
LOG_ERR("EBP", "Cover image is not a supported format, skipping");
|
||||||
}
|
}
|
||||||
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
std::string Epub::getThumbBmpPath() const { return cachePath + "/thumb.bmp"; }
|
std::string Epub::getThumbBmpPath() const { return cachePath + "/thumb_[HEIGHT].bmp"; }
|
||||||
|
std::string Epub::getThumbBmpPath(int height) const { return cachePath + "/thumb_" + std::to_string(height) + ".bmp"; }
|
||||||
|
|
||||||
bool Epub::generateThumbBmp() const {
|
bool Epub::generateThumbBmp(int height) const {
|
||||||
|
bool invalid = false;
|
||||||
// Already generated, return true
|
// Already generated, return true
|
||||||
if (SdMan.exists(getThumbBmpPath().c_str())) {
|
if (Storage.exists(getThumbBmpPath(height).c_str())) {
|
||||||
|
// is this a valid thumbnail or just an empty file we created to mark generation attempts?
|
||||||
|
invalid = !isValidThumbnailBmp(getThumbBmpPath(height));
|
||||||
|
if (invalid) {
|
||||||
|
// Remove the old invalid thumbnail so we can attempt to generate a new one
|
||||||
|
Storage.remove(getThumbBmpPath(height).c_str());
|
||||||
|
LOG_DBG("EBP", "Previous thumbnail generation attempt failed for height %d, retrying", height);
|
||||||
|
} else {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if (!bookMetadataCache || !bookMetadataCache->isLoaded()) {
|
if (!bookMetadataCache || !bookMetadataCache->isLoaded()) {
|
||||||
Serial.printf("[%lu] [EBP] Cannot generate thumb BMP, cache not loaded\n", millis());
|
LOG_ERR("EBP", "Cannot generate thumb BMP, cache not loaded");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
const auto coverImageHref = bookMetadataCache->coreMetadata.coverItemHref;
|
const auto coverImageHref = bookMetadataCache->coreMetadata.coverItemHref;
|
||||||
|
std::string effectiveCoverImageHref = coverImageHref;
|
||||||
if (coverImageHref.empty()) {
|
if (coverImageHref.empty()) {
|
||||||
Serial.printf("[%lu] [EBP] No known cover image for thumbnail\n", millis());
|
// Fallback: try common cover filenames
|
||||||
return false;
|
std::vector<std::string> coverCandidates = getCoverCandidates();
|
||||||
|
for (const auto& candidate : coverCandidates) {
|
||||||
|
effectiveCoverImageHref = candidate;
|
||||||
|
// Try to read a small amount to check if exists
|
||||||
|
uint8_t* test = readItemContentsToBytes(candidate, nullptr, false);
|
||||||
|
if (test) {
|
||||||
|
free(test);
|
||||||
|
break;
|
||||||
|
} else {
|
||||||
|
effectiveCoverImageHref.clear();
|
||||||
}
|
}
|
||||||
|
}
|
||||||
if (coverImageHref.substr(coverImageHref.length() - 4) == ".jpg" ||
|
}
|
||||||
coverImageHref.substr(coverImageHref.length() - 5) == ".jpeg") {
|
if (effectiveCoverImageHref.empty()) {
|
||||||
Serial.printf("[%lu] [EBP] Generating thumb BMP from JPG cover image\n", millis());
|
LOG_DBG("EBP", "No known cover image for thumbnail");
|
||||||
|
} else {
|
||||||
|
// Check for JPG/JPEG extensions (case insensitive)
|
||||||
|
std::string lowerHref = effectiveCoverImageHref;
|
||||||
|
std::transform(lowerHref.begin(), lowerHref.end(), lowerHref.begin(), ::tolower);
|
||||||
|
bool isJpg =
|
||||||
|
lowerHref.substr(lowerHref.length() - 4) == ".jpg" || lowerHref.substr(lowerHref.length() - 5) == ".jpeg";
|
||||||
|
if (isJpg) {
|
||||||
|
LOG_DBG("EBP", "Generating thumb BMP from JPG cover image");
|
||||||
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(effectiveCoverImageHref, 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(), thumbBmp)) {
|
if (!Storage.openFileForWrite("EBP", getThumbBmpPath(height), thumbBmp)) {
|
||||||
coverJpg.close();
|
coverJpg.close();
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
// Use smaller target size for Continue Reading card (half of screen: 240x400)
|
// Use smaller target size for Continue Reading card (half of screen: 240x400)
|
||||||
// Generate 1-bit BMP for fast home screen rendering (no gray passes needed)
|
// Generate 1-bit BMP for fast home screen rendering (no gray passes needed)
|
||||||
constexpr int THUMB_TARGET_WIDTH = 240;
|
int THUMB_TARGET_WIDTH = height * 0.6;
|
||||||
constexpr int THUMB_TARGET_HEIGHT = 400;
|
int THUMB_TARGET_HEIGHT = height;
|
||||||
const bool success = JpegToBmpConverter::jpegFileTo1BitBmpStreamWithSize(coverJpg, thumbBmp, THUMB_TARGET_WIDTH,
|
const bool success = JpegToBmpConverter::jpegFileTo1BitBmpStreamWithSize(coverJpg, thumbBmp, THUMB_TARGET_WIDTH,
|
||||||
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());
|
LOG_ERR("EBP", "Failed to generate thumb BMP from JPG cover image");
|
||||||
SdMan.remove(getThumbBmpPath().c_str());
|
Storage.remove(getThumbBmpPath(height).c_str());
|
||||||
}
|
}
|
||||||
Serial.printf("[%lu] [EBP] Generated thumb BMP from JPG cover image, success: %s\n", millis(),
|
LOG_DBG("EBP", "Generated thumb BMP from JPG cover image, success: %s", success ? "yes" : "no");
|
||||||
success ? "yes" : "no");
|
|
||||||
return success;
|
return success;
|
||||||
} else {
|
} else {
|
||||||
Serial.printf("[%lu] [EBP] Cover image is not a JPG, skipping thumbnail\n", millis());
|
LOG_ERR("EBP", "Cover image is not a supported format, skipping thumbnail");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
bool Epub::generateInvalidFormatThumbBmp(int height) const {
|
||||||
|
// Create a simple 1-bit BMP with an X pattern to indicate invalid format.
|
||||||
|
// This BMP is a valid 1-bit file used as a marker to prevent repeated
|
||||||
|
// generation attempts when conversion fails (e.g., progressive JPG).
|
||||||
|
const int width = height * 0.6; // Same aspect ratio as normal thumbnails
|
||||||
|
const int rowBytes = ((width + 31) / 32) * 4; // 1-bit rows padded to 4-byte boundary
|
||||||
|
const int imageSize = rowBytes * height;
|
||||||
|
const int fileSize = 14 + 40 + 8 + imageSize; // Header + DIB + palette + data
|
||||||
|
const int dataOffset = 14 + 40 + 8;
|
||||||
|
|
||||||
|
FsFile thumbBmp;
|
||||||
|
if (!Storage.openFileForWrite("EBP", getThumbBmpPath(height), thumbBmp)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// BMP file header (14 bytes)
|
||||||
|
thumbBmp.write('B');
|
||||||
|
thumbBmp.write('M');
|
||||||
|
thumbBmp.write(reinterpret_cast<const uint8_t*>(&fileSize), 4);
|
||||||
|
uint32_t reserved = 0;
|
||||||
|
thumbBmp.write(reinterpret_cast<const uint8_t*>(&reserved), 4);
|
||||||
|
thumbBmp.write(reinterpret_cast<const uint8_t*>(&dataOffset), 4);
|
||||||
|
|
||||||
|
// DIB header (BITMAPINFOHEADER - 40 bytes)
|
||||||
|
uint32_t dibHeaderSize = 40;
|
||||||
|
thumbBmp.write(reinterpret_cast<const uint8_t*>(&dibHeaderSize), 4);
|
||||||
|
int32_t bmpWidth = width;
|
||||||
|
thumbBmp.write(reinterpret_cast<const uint8_t*>(&bmpWidth), 4);
|
||||||
|
int32_t bmpHeight = -height; // Negative for top-down
|
||||||
|
thumbBmp.write(reinterpret_cast<const uint8_t*>(&bmpHeight), 4);
|
||||||
|
uint16_t planes = 1;
|
||||||
|
thumbBmp.write(reinterpret_cast<const uint8_t*>(&planes), 2);
|
||||||
|
uint16_t bitsPerPixel = 1;
|
||||||
|
thumbBmp.write(reinterpret_cast<const uint8_t*>(&bitsPerPixel), 2);
|
||||||
|
uint32_t compression = 0;
|
||||||
|
thumbBmp.write(reinterpret_cast<const uint8_t*>(&compression), 4);
|
||||||
|
thumbBmp.write(reinterpret_cast<const uint8_t*>(&imageSize), 4);
|
||||||
|
int32_t ppmX = 2835; // 72 DPI
|
||||||
|
thumbBmp.write(reinterpret_cast<const uint8_t*>(&ppmX), 4);
|
||||||
|
int32_t ppmY = 2835;
|
||||||
|
thumbBmp.write(reinterpret_cast<const uint8_t*>(&ppmY), 4);
|
||||||
|
uint32_t colorsUsed = 2;
|
||||||
|
thumbBmp.write(reinterpret_cast<const uint8_t*>(&colorsUsed), 4);
|
||||||
|
uint32_t colorsImportant = 2;
|
||||||
|
thumbBmp.write(reinterpret_cast<const uint8_t*>(&colorsImportant), 4);
|
||||||
|
|
||||||
|
// Color palette (2 colors for 1-bit)
|
||||||
|
uint8_t black[4] = {0x00, 0x00, 0x00, 0x00}; // Color 0: Black
|
||||||
|
thumbBmp.write(black, 4);
|
||||||
|
uint8_t white[4] = {0xFF, 0xFF, 0xFF, 0x00}; // Color 1: White
|
||||||
|
thumbBmp.write(white, 4);
|
||||||
|
|
||||||
|
// Generate X pattern bitmap data
|
||||||
|
// In BMP, 0 = black (first color in palette), 1 = white
|
||||||
|
// We'll draw black pixels on white background
|
||||||
|
for (int y = 0; y < height; y++) {
|
||||||
|
std::vector<uint8_t> rowData(rowBytes, 0xFF); // Initialize to all white (1s)
|
||||||
|
|
||||||
|
// Map this row to a horizontal position for diagonals
|
||||||
|
const int scaledY = (y * width) / height;
|
||||||
|
const int thickness = 2; // thickness of diagonal lines in pixels
|
||||||
|
|
||||||
|
for (int x = 0; x < width; x++) {
|
||||||
|
bool drawPixel = false;
|
||||||
|
// Main diagonal (top-left to bottom-right)
|
||||||
|
if (std::abs(x - scaledY) <= thickness) drawPixel = true;
|
||||||
|
// Other diagonal (top-right to bottom-left)
|
||||||
|
if (std::abs(x - (width - 1 - scaledY)) <= thickness) drawPixel = true;
|
||||||
|
|
||||||
|
if (drawPixel) {
|
||||||
|
const int byteIndex = x / 8;
|
||||||
|
const int bitIndex = 7 - (x % 8); // MSB first
|
||||||
|
rowData[byteIndex] &= static_cast<uint8_t>(~(1 << bitIndex));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Write the row data
|
||||||
|
thumbBmp.write(rowData.data(), rowBytes);
|
||||||
|
}
|
||||||
|
|
||||||
|
thumbBmp.close();
|
||||||
|
LOG_DBG("EBP", "Generated invalid format thumbnail BMP");
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool Epub::generateInvalidFormatCoverBmp(bool cropped) const {
|
||||||
|
// Create a simple 1-bit BMP with an X pattern to indicate invalid format.
|
||||||
|
// This BMP is intentionally a valid image that visually indicates a
|
||||||
|
// malformed/unsupported cover image instead of leaving an empty marker
|
||||||
|
// file that would cause repeated generation attempts.
|
||||||
|
// Derive logical portrait dimensions from the display hardware constants
|
||||||
|
// EInkDisplay reports native panel orientation as 800x480; use min/max
|
||||||
|
const int hwW = HalDisplay::DISPLAY_WIDTH;
|
||||||
|
const int hwH = HalDisplay::DISPLAY_HEIGHT;
|
||||||
|
const int width = std::min(hwW, hwH); // logical portrait width (480)
|
||||||
|
const int height = std::max(hwW, hwH); // logical portrait height (800)
|
||||||
|
const int rowBytes = ((width + 31) / 32) * 4; // 1-bit rows padded to 4-byte boundary
|
||||||
|
const int imageSize = rowBytes * height;
|
||||||
|
const int fileSize = 14 + 40 + 8 + imageSize; // Header + DIB + palette + data
|
||||||
|
const int dataOffset = 14 + 40 + 8;
|
||||||
|
|
||||||
|
FsFile coverBmp;
|
||||||
|
if (!Storage.openFileForWrite("EBP", getCoverBmpPath(cropped), coverBmp)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// BMP file header (14 bytes)
|
||||||
|
coverBmp.write('B');
|
||||||
|
coverBmp.write('M');
|
||||||
|
coverBmp.write(reinterpret_cast<const uint8_t*>(&fileSize), 4);
|
||||||
|
uint32_t reserved = 0;
|
||||||
|
coverBmp.write(reinterpret_cast<const uint8_t*>(&reserved), 4);
|
||||||
|
coverBmp.write(reinterpret_cast<const uint8_t*>(&dataOffset), 4);
|
||||||
|
|
||||||
|
// DIB header (BITMAPINFOHEADER - 40 bytes)
|
||||||
|
uint32_t dibHeaderSize = 40;
|
||||||
|
coverBmp.write(reinterpret_cast<const uint8_t*>(&dibHeaderSize), 4);
|
||||||
|
int32_t bmpWidth = width;
|
||||||
|
coverBmp.write(reinterpret_cast<const uint8_t*>(&bmpWidth), 4);
|
||||||
|
int32_t bmpHeight = -height; // Negative for top-down
|
||||||
|
coverBmp.write(reinterpret_cast<const uint8_t*>(&bmpHeight), 4);
|
||||||
|
uint16_t planes = 1;
|
||||||
|
coverBmp.write(reinterpret_cast<const uint8_t*>(&planes), 2);
|
||||||
|
uint16_t bitsPerPixel = 1;
|
||||||
|
coverBmp.write(reinterpret_cast<const uint8_t*>(&bitsPerPixel), 2);
|
||||||
|
uint32_t compression = 0;
|
||||||
|
coverBmp.write(reinterpret_cast<const uint8_t*>(&compression), 4);
|
||||||
|
coverBmp.write(reinterpret_cast<const uint8_t*>(&imageSize), 4);
|
||||||
|
int32_t ppmX = 2835; // 72 DPI
|
||||||
|
coverBmp.write(reinterpret_cast<const uint8_t*>(&ppmX), 4);
|
||||||
|
int32_t ppmY = 2835;
|
||||||
|
coverBmp.write(reinterpret_cast<const uint8_t*>(&ppmY), 4);
|
||||||
|
uint32_t colorsUsed = 2;
|
||||||
|
coverBmp.write(reinterpret_cast<const uint8_t*>(&colorsUsed), 4);
|
||||||
|
uint32_t colorsImportant = 2;
|
||||||
|
coverBmp.write(reinterpret_cast<const uint8_t*>(&colorsImportant), 4);
|
||||||
|
|
||||||
|
// Color palette (2 colors for 1-bit)
|
||||||
|
uint8_t black[4] = {0x00, 0x00, 0x00, 0x00}; // Color 0: Black
|
||||||
|
coverBmp.write(black, 4);
|
||||||
|
uint8_t white[4] = {0xFF, 0xFF, 0xFF, 0x00}; // Color 1: White
|
||||||
|
coverBmp.write(white, 4);
|
||||||
|
|
||||||
|
// Generate X pattern bitmap data
|
||||||
|
// In BMP, 0 = black (first color in palette), 1 = white
|
||||||
|
// We'll draw black pixels on white background
|
||||||
|
for (int y = 0; y < height; y++) {
|
||||||
|
std::vector<uint8_t> rowData(rowBytes, 0xFF); // Initialize to all white (1s)
|
||||||
|
|
||||||
|
const int scaledY = (y * width) / height;
|
||||||
|
const int thickness = 6; // thicker lines for full-cover visibility
|
||||||
|
|
||||||
|
for (int x = 0; x < width; x++) {
|
||||||
|
bool drawPixel = false;
|
||||||
|
if (std::abs(x - scaledY) <= thickness) drawPixel = true;
|
||||||
|
if (std::abs(x - (width - 1 - scaledY)) <= thickness) drawPixel = true;
|
||||||
|
|
||||||
|
if (drawPixel) {
|
||||||
|
const int byteIndex = x / 8;
|
||||||
|
const int bitIndex = 7 - (x % 8);
|
||||||
|
rowData[byteIndex] &= static_cast<uint8_t>(~(1 << bitIndex));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
coverBmp.write(rowData.data(), rowBytes);
|
||||||
|
}
|
||||||
|
|
||||||
|
coverBmp.close();
|
||||||
|
LOG_DBG("EBP", "Generated invalid format cover BMP");
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
uint8_t* Epub::readItemContentsToBytes(const std::string& itemHref, size_t* size, const bool trailingNullByte) const {
|
uint8_t* Epub::readItemContentsToBytes(const std::string& itemHref, size_t* size, const bool trailingNullByte) const {
|
||||||
if (itemHref.empty()) {
|
if (itemHref.empty()) {
|
||||||
Serial.printf("[%lu] [EBP] Failed to read item, empty href\n", millis());
|
LOG_DBG("EBP", "Failed to read item, empty href");
|
||||||
return nullptr;
|
return nullptr;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -502,7 +801,7 @@ uint8_t* Epub::readItemContentsToBytes(const std::string& itemHref, size_t* size
|
|||||||
|
|
||||||
const auto content = ZipFile(filepath).readFileToMemory(path.c_str(), size, trailingNullByte);
|
const auto content = ZipFile(filepath).readFileToMemory(path.c_str(), size, trailingNullByte);
|
||||||
if (!content) {
|
if (!content) {
|
||||||
Serial.printf("[%lu] [EBP] Failed to read item %s\n", millis(), path.c_str());
|
LOG_DBG("EBP", "Failed to read item %s", path.c_str());
|
||||||
return nullptr;
|
return nullptr;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -511,7 +810,7 @@ uint8_t* Epub::readItemContentsToBytes(const std::string& itemHref, size_t* size
|
|||||||
|
|
||||||
bool Epub::readItemContentsToStream(const std::string& itemHref, Print& out, const size_t chunkSize) const {
|
bool Epub::readItemContentsToStream(const std::string& itemHref, Print& out, const size_t chunkSize) const {
|
||||||
if (itemHref.empty()) {
|
if (itemHref.empty()) {
|
||||||
Serial.printf("[%lu] [EBP] Failed to read item, empty href\n", millis());
|
LOG_DBG("EBP", "Failed to read item, empty href");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -535,12 +834,12 @@ size_t Epub::getCumulativeSpineItemSize(const int spineIndex) const { return get
|
|||||||
|
|
||||||
BookMetadataCache::SpineEntry Epub::getSpineItem(const int spineIndex) const {
|
BookMetadataCache::SpineEntry Epub::getSpineItem(const int spineIndex) const {
|
||||||
if (!bookMetadataCache || !bookMetadataCache->isLoaded()) {
|
if (!bookMetadataCache || !bookMetadataCache->isLoaded()) {
|
||||||
Serial.printf("[%lu] [EBP] getSpineItem called but cache not loaded\n", millis());
|
LOG_ERR("EBP", "getSpineItem called but cache not loaded");
|
||||||
return {};
|
return {};
|
||||||
}
|
}
|
||||||
|
|
||||||
if (spineIndex < 0 || spineIndex >= bookMetadataCache->getSpineCount()) {
|
if (spineIndex < 0 || spineIndex >= bookMetadataCache->getSpineCount()) {
|
||||||
Serial.printf("[%lu] [EBP] getSpineItem index:%d is out of range\n", millis(), spineIndex);
|
LOG_ERR("EBP", "getSpineItem index:%d is out of range", spineIndex);
|
||||||
return bookMetadataCache->getSpineEntry(0);
|
return bookMetadataCache->getSpineEntry(0);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -549,12 +848,12 @@ BookMetadataCache::SpineEntry Epub::getSpineItem(const int spineIndex) const {
|
|||||||
|
|
||||||
BookMetadataCache::TocEntry Epub::getTocItem(const int tocIndex) const {
|
BookMetadataCache::TocEntry Epub::getTocItem(const int tocIndex) const {
|
||||||
if (!bookMetadataCache || !bookMetadataCache->isLoaded()) {
|
if (!bookMetadataCache || !bookMetadataCache->isLoaded()) {
|
||||||
Serial.printf("[%lu] [EBP] getTocItem called but cache not loaded\n", millis());
|
LOG_DBG("EBP", "getTocItem called but cache not loaded");
|
||||||
return {};
|
return {};
|
||||||
}
|
}
|
||||||
|
|
||||||
if (tocIndex < 0 || tocIndex >= bookMetadataCache->getTocCount()) {
|
if (tocIndex < 0 || tocIndex >= bookMetadataCache->getTocCount()) {
|
||||||
Serial.printf("[%lu] [EBP] getTocItem index:%d is out of range\n", millis(), tocIndex);
|
LOG_DBG("EBP", "getTocItem index:%d is out of range", tocIndex);
|
||||||
return {};
|
return {};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -572,18 +871,18 @@ int Epub::getTocItemsCount() const {
|
|||||||
// work out the section index for a toc index
|
// work out the section index for a toc index
|
||||||
int Epub::getSpineIndexForTocIndex(const int tocIndex) const {
|
int Epub::getSpineIndexForTocIndex(const int tocIndex) const {
|
||||||
if (!bookMetadataCache || !bookMetadataCache->isLoaded()) {
|
if (!bookMetadataCache || !bookMetadataCache->isLoaded()) {
|
||||||
Serial.printf("[%lu] [EBP] getSpineIndexForTocIndex called but cache not loaded\n", millis());
|
LOG_ERR("EBP", "getSpineIndexForTocIndex called but cache not loaded");
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (tocIndex < 0 || tocIndex >= bookMetadataCache->getTocCount()) {
|
if (tocIndex < 0 || tocIndex >= bookMetadataCache->getTocCount()) {
|
||||||
Serial.printf("[%lu] [EBP] getSpineIndexForTocIndex: tocIndex %d out of range\n", millis(), tocIndex);
|
LOG_ERR("EBP", "getSpineIndexForTocIndex: tocIndex %d out of range", tocIndex);
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
const int spineIndex = bookMetadataCache->getTocEntry(tocIndex).spineIndex;
|
const int spineIndex = bookMetadataCache->getTocEntry(tocIndex).spineIndex;
|
||||||
if (spineIndex < 0) {
|
if (spineIndex < 0) {
|
||||||
Serial.printf("[%lu] [EBP] Section not found for TOC index %d\n", millis(), tocIndex);
|
LOG_DBG("EBP", "Section not found for TOC index %d", tocIndex);
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -601,12 +900,11 @@ size_t Epub::getBookSize() const {
|
|||||||
|
|
||||||
int Epub::getSpineIndexForTextReference() const {
|
int Epub::getSpineIndexForTextReference() const {
|
||||||
if (!bookMetadataCache || !bookMetadataCache->isLoaded()) {
|
if (!bookMetadataCache || !bookMetadataCache->isLoaded()) {
|
||||||
Serial.printf("[%lu] [EBP] getSpineIndexForTextReference called but cache not loaded\n", millis());
|
LOG_ERR("EBP", "getSpineIndexForTextReference called but cache not loaded");
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
Serial.printf("[%lu] [ERS] Core Metadata: cover(%d)=%s, textReference(%d)=%s\n", millis(),
|
LOG_DBG("EBP", "Core Metadata: cover(%d)=%s, textReference(%d)=%s",
|
||||||
bookMetadataCache->coreMetadata.coverItemHref.size(),
|
bookMetadataCache->coreMetadata.coverItemHref.size(), bookMetadataCache->coreMetadata.coverItemHref.c_str(),
|
||||||
bookMetadataCache->coreMetadata.coverItemHref.c_str(),
|
|
||||||
bookMetadataCache->coreMetadata.textReferenceHref.size(),
|
bookMetadataCache->coreMetadata.textReferenceHref.size(),
|
||||||
bookMetadataCache->coreMetadata.textReferenceHref.c_str());
|
bookMetadataCache->coreMetadata.textReferenceHref.c_str());
|
||||||
|
|
||||||
@@ -618,13 +916,13 @@ int Epub::getSpineIndexForTextReference() const {
|
|||||||
// loop through spine items to get the correct index matching the text href
|
// loop through spine items to get the correct index matching the text href
|
||||||
for (size_t i = 0; i < getSpineItemsCount(); i++) {
|
for (size_t i = 0; i < getSpineItemsCount(); i++) {
|
||||||
if (getSpineItem(i).href == bookMetadataCache->coreMetadata.textReferenceHref) {
|
if (getSpineItem(i).href == bookMetadataCache->coreMetadata.textReferenceHref) {
|
||||||
Serial.printf("[%lu] [ERS] Text reference %s found at index %d\n", millis(),
|
LOG_DBG("EBP", "Text reference %s found at index %d", bookMetadataCache->coreMetadata.textReferenceHref.c_str(),
|
||||||
bookMetadataCache->coreMetadata.textReferenceHref.c_str(), i);
|
i);
|
||||||
return i;
|
return i;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// This should not happen, as we checked for empty textReferenceHref earlier
|
// This should not happen, as we checked for empty textReferenceHref earlier
|
||||||
Serial.printf("[%lu] [EBP] Section not found for text reference\n", millis());
|
LOG_DBG("EBP", "Section not found for text reference");
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -640,3 +938,45 @@ float Epub::calculateProgress(const int currentSpineIndex, const float currentSp
|
|||||||
const float totalProgress = static_cast<float>(prevChapterSize) + sectionProgSize;
|
const float totalProgress = static_cast<float>(prevChapterSize) + sectionProgSize;
|
||||||
return totalProgress / static_cast<float>(bookSize);
|
return totalProgress / static_cast<float>(bookSize);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
bool Epub::isValidThumbnailBmp(const std::string& bmpPath) {
|
||||||
|
if (!Storage.exists(bmpPath.c_str())) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
FsFile file = Storage.open(bmpPath.c_str());
|
||||||
|
if (!file) {
|
||||||
|
LOG_ERR("EBP", "Failed to open thumbnail BMP at path: %s", bmpPath.c_str());
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
size_t fileSize = file.size();
|
||||||
|
if (fileSize == 0) {
|
||||||
|
// Empty file is a marker for "no cover available"
|
||||||
|
LOG_DBG("EBP", "Thumbnail BMP is empty (no cover marker) at path: %s", bmpPath.c_str());
|
||||||
|
file.close();
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
// BMP header starts with 'B' 'M'
|
||||||
|
uint8_t header[2];
|
||||||
|
size_t bytesRead = file.read(header, 2);
|
||||||
|
if (bytesRead != 2) {
|
||||||
|
LOG_ERR("EBP", "Failed to read thumbnail BMP header at path: %s", bmpPath.c_str());
|
||||||
|
file.close();
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
LOG_DBG("EBP", "Thumbnail BMP header: %c%c", header[0], header[1]);
|
||||||
|
file.close();
|
||||||
|
return header[0] == 'B' && header[1] == 'M';
|
||||||
|
}
|
||||||
|
|
||||||
|
std::vector<std::string> Epub::getCoverCandidates() const {
|
||||||
|
std::vector<std::string> coverDirectories = {".", "images", "Images", "OEBPS", "OEBPS/images", "OEBPS/Images"};
|
||||||
|
std::vector<std::string> coverExtensions = {".jpg", ".jpeg"}; // add ".png" when PNG cover support is implemented
|
||||||
|
std::vector<std::string> coverCandidates;
|
||||||
|
for (const auto& ext : coverExtensions) {
|
||||||
|
for (const auto& dir : coverDirectories) {
|
||||||
|
std::string candidate = (dir == ".") ? "cover" + ext : dir + "/cover" + ext;
|
||||||
|
coverCandidates.push_back(candidate);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return coverCandidates;
|
||||||
|
}
|
||||||
|
|||||||
@@ -8,6 +8,7 @@
|
|||||||
#include <vector>
|
#include <vector>
|
||||||
|
|
||||||
#include "Epub/BookMetadataCache.h"
|
#include "Epub/BookMetadataCache.h"
|
||||||
|
#include "Epub/css/CssParser.h"
|
||||||
|
|
||||||
class ZipFile;
|
class ZipFile;
|
||||||
|
|
||||||
@@ -24,11 +25,16 @@ class Epub {
|
|||||||
std::string cachePath;
|
std::string cachePath;
|
||||||
// Spine and TOC cache
|
// Spine and TOC cache
|
||||||
std::unique_ptr<BookMetadataCache> bookMetadataCache;
|
std::unique_ptr<BookMetadataCache> bookMetadataCache;
|
||||||
|
// CSS parser for styling
|
||||||
|
std::unique_ptr<CssParser> cssParser;
|
||||||
|
// CSS files
|
||||||
|
std::vector<std::string> cssFiles;
|
||||||
|
|
||||||
bool findContentOpfFile(std::string* contentOpfFile) const;
|
bool findContentOpfFile(std::string* contentOpfFile) const;
|
||||||
bool parseContentOpf(BookMetadataCache::BookMetadata& bookMetadata);
|
bool parseContentOpf(BookMetadataCache::BookMetadata& bookMetadata);
|
||||||
bool parseTocNcxFile() const;
|
bool parseTocNcxFile() const;
|
||||||
bool parseTocNavFile() const;
|
bool parseTocNavFile() const;
|
||||||
|
void parseCssFiles() const;
|
||||||
|
|
||||||
public:
|
public:
|
||||||
explicit Epub(std::string filepath, const std::string& cacheDir) : filepath(std::move(filepath)) {
|
explicit Epub(std::string filepath, const std::string& cacheDir) : filepath(std::move(filepath)) {
|
||||||
@@ -37,7 +43,7 @@ class Epub {
|
|||||||
}
|
}
|
||||||
~Epub() = default;
|
~Epub() = default;
|
||||||
std::string& getBasePath() { return contentBasePath; }
|
std::string& getBasePath() { return contentBasePath; }
|
||||||
bool load(bool buildIfMissing = true);
|
bool load(bool buildIfMissing = true, bool skipLoadingCss = false);
|
||||||
bool clearCache() const;
|
bool clearCache() const;
|
||||||
void setupCacheDir() const;
|
void setupCacheDir() const;
|
||||||
const std::string& getCachePath() const;
|
const std::string& getCachePath() const;
|
||||||
@@ -46,9 +52,23 @@ class Epub {
|
|||||||
const std::string& getAuthor() const;
|
const std::string& getAuthor() const;
|
||||||
const std::string& getLanguage() const;
|
const std::string& getLanguage() const;
|
||||||
std::string getCoverBmpPath(bool cropped = false) const;
|
std::string getCoverBmpPath(bool cropped = false) const;
|
||||||
|
// Generate a 1-bit BMP cover image from the EPUB cover image.
|
||||||
|
// Returns true on success. On conversion failure, callers may use
|
||||||
|
// `generateInvalidFormatCoverBmp` to create a valid marker BMP.
|
||||||
bool generateCoverBmp(bool cropped = false) const;
|
bool generateCoverBmp(bool cropped = false) const;
|
||||||
|
// Create a valid 1-bit BMP that visually indicates an invalid/unsupported
|
||||||
|
// cover format (an X pattern). This prevents repeated generation attempts
|
||||||
|
// by providing a valid BMP file that `isValidThumbnailBmp` accepts.
|
||||||
|
bool generateInvalidFormatCoverBmp(bool cropped = false) const;
|
||||||
std::string getThumbBmpPath() const;
|
std::string getThumbBmpPath() const;
|
||||||
bool generateThumbBmp() const;
|
std::string getThumbBmpPath(int height) const;
|
||||||
|
// Generate a thumbnail BMP at the requested `height`. Returns true on
|
||||||
|
// successful conversion. If conversion fails, `generateInvalidFormatThumbBmp`
|
||||||
|
// can be used to write a valid marker image that prevents retries.
|
||||||
|
bool generateThumbBmp(int height) const;
|
||||||
|
// Create a valid 1-bit thumbnail BMP with an X marker indicating an
|
||||||
|
// invalid/unsupported cover image instead of leaving an empty marker file.
|
||||||
|
bool generateInvalidFormatThumbBmp(int height) const;
|
||||||
uint8_t* readItemContentsToBytes(const std::string& itemHref, size_t* size = nullptr,
|
uint8_t* readItemContentsToBytes(const std::string& itemHref, size_t* size = nullptr,
|
||||||
bool trailingNullByte = false) const;
|
bool trailingNullByte = false) const;
|
||||||
bool readItemContentsToStream(const std::string& itemHref, Print& out, size_t chunkSize) const;
|
bool readItemContentsToStream(const std::string& itemHref, Print& out, size_t chunkSize) const;
|
||||||
@@ -64,4 +84,10 @@ class Epub {
|
|||||||
|
|
||||||
size_t getBookSize() const;
|
size_t getBookSize() const;
|
||||||
float calculateProgress(int currentSpineIndex, float currentSpineRead) const;
|
float calculateProgress(int currentSpineIndex, float currentSpineRead) const;
|
||||||
|
CssParser* getCssParser() const { return cssParser.get(); }
|
||||||
|
|
||||||
|
static bool isValidThumbnailBmp(const std::string& bmpPath);
|
||||||
|
|
||||||
|
private:
|
||||||
|
std::vector<std::string> getCoverCandidates() const;
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
#include "BookMetadataCache.h"
|
#include "BookMetadataCache.h"
|
||||||
|
|
||||||
#include <HardwareSerial.h>
|
#include <Logging.h>
|
||||||
#include <Serialization.h>
|
#include <Serialization.h>
|
||||||
#include <ZipFile.h>
|
#include <ZipFile.h>
|
||||||
|
|
||||||
@@ -21,15 +21,15 @@ bool BookMetadataCache::beginWrite() {
|
|||||||
buildMode = true;
|
buildMode = true;
|
||||||
spineCount = 0;
|
spineCount = 0;
|
||||||
tocCount = 0;
|
tocCount = 0;
|
||||||
Serial.printf("[%lu] [BMC] Entering write mode\n", millis());
|
LOG_DBG("BMC", "Entering write mode");
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
bool BookMetadataCache::beginContentOpfPass() {
|
bool BookMetadataCache::beginContentOpfPass() {
|
||||||
Serial.printf("[%lu] [BMC] Beginning content opf pass\n", millis());
|
LOG_DBG("BMC", "Beginning content opf pass");
|
||||||
|
|
||||||
// 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() {
|
||||||
@@ -38,12 +38,12 @@ bool BookMetadataCache::endContentOpfPass() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
bool BookMetadataCache::beginTocPass() {
|
bool BookMetadataCache::beginTocPass() {
|
||||||
Serial.printf("[%lu] [BMC] Beginning toc pass\n", millis());
|
LOG_DBG("BMC", "Beginning toc pass");
|
||||||
|
|
||||||
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;
|
||||||
}
|
}
|
||||||
@@ -66,7 +66,7 @@ bool BookMetadataCache::beginTocPass() {
|
|||||||
});
|
});
|
||||||
spineFile.seek(0);
|
spineFile.seek(0);
|
||||||
useSpineHrefIndex = true;
|
useSpineHrefIndex = true;
|
||||||
Serial.printf("[%lu] [BMC] Using fast index for %d spine items\n", millis(), spineCount);
|
LOG_DBG("BMC", "Using fast index for %d spine items", spineCount);
|
||||||
} else {
|
} else {
|
||||||
useSpineHrefIndex = false;
|
useSpineHrefIndex = false;
|
||||||
}
|
}
|
||||||
@@ -87,27 +87,27 @@ bool BookMetadataCache::endTocPass() {
|
|||||||
|
|
||||||
bool BookMetadataCache::endWrite() {
|
bool BookMetadataCache::endWrite() {
|
||||||
if (!buildMode) {
|
if (!buildMode) {
|
||||||
Serial.printf("[%lu] [BMC] endWrite called but not in build mode\n", millis());
|
LOG_DBG("BMC", "endWrite called but not in build mode");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
buildMode = false;
|
buildMode = false;
|
||||||
Serial.printf("[%lu] [BMC] Wrote %d spine, %d TOC entries\n", millis(), spineCount, tocCount);
|
LOG_DBG("BMC", "Wrote %d spine, %d TOC entries", spineCount, tocCount);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
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;
|
||||||
@@ -167,7 +167,7 @@ bool BookMetadataCache::buildBookBin(const std::string& epubPath, const BookMeta
|
|||||||
ZipFile zip(epubPath);
|
ZipFile zip(epubPath);
|
||||||
// Pre-open zip file to speed up size calculations
|
// Pre-open zip file to speed up size calculations
|
||||||
if (!zip.open()) {
|
if (!zip.open()) {
|
||||||
Serial.printf("[%lu] [BMC] Could not open EPUB zip for size calculations\n", millis());
|
LOG_ERR("BMC", "Could not open EPUB zip for size calculations");
|
||||||
bookFile.close();
|
bookFile.close();
|
||||||
spineFile.close();
|
spineFile.close();
|
||||||
tocFile.close();
|
tocFile.close();
|
||||||
@@ -185,7 +185,7 @@ bool BookMetadataCache::buildBookBin(const std::string& epubPath, const BookMeta
|
|||||||
bool useBatchSizes = false;
|
bool useBatchSizes = false;
|
||||||
|
|
||||||
if (spineCount >= LARGE_SPINE_THRESHOLD) {
|
if (spineCount >= LARGE_SPINE_THRESHOLD) {
|
||||||
Serial.printf("[%lu] [BMC] Using batch size lookup for %d spine items\n", millis(), spineCount);
|
LOG_DBG("BMC", "Using batch size lookup for %d spine items", spineCount);
|
||||||
|
|
||||||
std::vector<ZipFile::SizeTarget> targets;
|
std::vector<ZipFile::SizeTarget> targets;
|
||||||
targets.reserve(spineCount);
|
targets.reserve(spineCount);
|
||||||
@@ -208,7 +208,7 @@ bool BookMetadataCache::buildBookBin(const std::string& epubPath, const BookMeta
|
|||||||
|
|
||||||
spineSizes.resize(spineCount, 0);
|
spineSizes.resize(spineCount, 0);
|
||||||
int matched = zip.fillUncompressedSizes(targets, spineSizes);
|
int matched = zip.fillUncompressedSizes(targets, spineSizes);
|
||||||
Serial.printf("[%lu] [BMC] Batch lookup matched %d/%d spine items\n", millis(), matched, spineCount);
|
LOG_DBG("BMC", "Batch lookup matched %d/%d spine items", matched, spineCount);
|
||||||
|
|
||||||
targets.clear();
|
targets.clear();
|
||||||
targets.shrink_to_fit();
|
targets.shrink_to_fit();
|
||||||
@@ -227,9 +227,8 @@ bool BookMetadataCache::buildBookBin(const std::string& epubPath, const BookMeta
|
|||||||
// Not a huge deal if we don't fine a TOC entry for the spine entry, this is expected behaviour for EPUBs
|
// Not a huge deal if we don't fine a TOC entry for the spine entry, this is expected behaviour for EPUBs
|
||||||
// Logging here is for debugging
|
// Logging here is for debugging
|
||||||
if (spineEntry.tocIndex == -1) {
|
if (spineEntry.tocIndex == -1) {
|
||||||
Serial.printf(
|
LOG_DBG("BMC", "Warning: Could not find TOC entry for spine item %d: %s, using title from last section", i,
|
||||||
"[%lu] [BMC] Warning: Could not find TOC entry for spine item %d: %s, using title from last section\n",
|
spineEntry.href.c_str());
|
||||||
millis(), i, spineEntry.href.c_str());
|
|
||||||
spineEntry.tocIndex = lastSpineTocIndex;
|
spineEntry.tocIndex = lastSpineTocIndex;
|
||||||
}
|
}
|
||||||
lastSpineTocIndex = spineEntry.tocIndex;
|
lastSpineTocIndex = spineEntry.tocIndex;
|
||||||
@@ -240,13 +239,13 @@ bool BookMetadataCache::buildBookBin(const std::string& epubPath, const BookMeta
|
|||||||
if (itemSize == 0) {
|
if (itemSize == 0) {
|
||||||
const std::string path = FsHelpers::normalisePath(spineEntry.href);
|
const std::string path = FsHelpers::normalisePath(spineEntry.href);
|
||||||
if (!zip.getInflatedFileSize(path.c_str(), &itemSize)) {
|
if (!zip.getInflatedFileSize(path.c_str(), &itemSize)) {
|
||||||
Serial.printf("[%lu] [BMC] Warning: Could not get size for spine item: %s\n", millis(), path.c_str());
|
LOG_ERR("BMC", "Warning: Could not get size for spine item: %s", path.c_str());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
const std::string path = FsHelpers::normalisePath(spineEntry.href);
|
const std::string path = FsHelpers::normalisePath(spineEntry.href);
|
||||||
if (!zip.getInflatedFileSize(path.c_str(), &itemSize)) {
|
if (!zip.getInflatedFileSize(path.c_str(), &itemSize)) {
|
||||||
Serial.printf("[%lu] [BMC] Warning: Could not get size for spine item: %s\n", millis(), path.c_str());
|
LOG_ERR("BMC", "Warning: Could not get size for spine item: %s", path.c_str());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -270,16 +269,16 @@ bool BookMetadataCache::buildBookBin(const std::string& epubPath, const BookMeta
|
|||||||
spineFile.close();
|
spineFile.close();
|
||||||
tocFile.close();
|
tocFile.close();
|
||||||
|
|
||||||
Serial.printf("[%lu] [BMC] Successfully built book.bin\n", millis());
|
LOG_DBG("BMC", "Successfully built book.bin");
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
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;
|
||||||
}
|
}
|
||||||
@@ -306,7 +305,7 @@ uint32_t BookMetadataCache::writeTocEntry(FsFile& file, const TocEntry& entry) c
|
|||||||
// this is because in this function we're marking positions of the items
|
// this is because in this function we're marking positions of the items
|
||||||
void BookMetadataCache::createSpineEntry(const std::string& href) {
|
void BookMetadataCache::createSpineEntry(const std::string& href) {
|
||||||
if (!buildMode || !spineFile) {
|
if (!buildMode || !spineFile) {
|
||||||
Serial.printf("[%lu] [BMC] createSpineEntry called but not in build mode\n", millis());
|
LOG_DBG("BMC", "createSpineEntry called but not in build mode");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -318,7 +317,7 @@ void BookMetadataCache::createSpineEntry(const std::string& href) {
|
|||||||
void BookMetadataCache::createTocEntry(const std::string& title, const std::string& href, const std::string& anchor,
|
void BookMetadataCache::createTocEntry(const std::string& title, const std::string& href, const std::string& anchor,
|
||||||
const uint8_t level) {
|
const uint8_t level) {
|
||||||
if (!buildMode || !tocFile || !spineFile) {
|
if (!buildMode || !tocFile || !spineFile) {
|
||||||
Serial.printf("[%lu] [BMC] createTocEntry called but not in build mode\n", millis());
|
LOG_DBG("BMC", "createTocEntry called but not in build mode");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -340,7 +339,7 @@ void BookMetadataCache::createTocEntry(const std::string& title, const std::stri
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (spineIndex == -1) {
|
if (spineIndex == -1) {
|
||||||
Serial.printf("[%lu] [BMC] createTocEntry: Could not find spine item for TOC href %s\n", millis(), href.c_str());
|
LOG_DBG("BMC", "createTocEntry: Could not find spine item for TOC href %s", href.c_str());
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
spineFile.seek(0);
|
spineFile.seek(0);
|
||||||
@@ -352,7 +351,7 @@ void BookMetadataCache::createTocEntry(const std::string& title, const std::stri
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (spineIndex == -1) {
|
if (spineIndex == -1) {
|
||||||
Serial.printf("[%lu] [BMC] createTocEntry: Could not find spine item for TOC href %s\n", millis(), href.c_str());
|
LOG_DBG("BMC", "createTocEntry: Could not find spine item for TOC href %s", href.c_str());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -364,14 +363,14 @@ 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;
|
||||||
}
|
}
|
||||||
|
|
||||||
uint8_t version;
|
uint8_t version;
|
||||||
serialization::readPod(bookFile, version);
|
serialization::readPod(bookFile, version);
|
||||||
if (version != BOOK_CACHE_VERSION) {
|
if (version != BOOK_CACHE_VERSION) {
|
||||||
Serial.printf("[%lu] [BMC] Cache version mismatch: expected %d, got %d\n", millis(), BOOK_CACHE_VERSION, version);
|
LOG_DBG("BMC", "Cache version mismatch: expected %d, got %d", BOOK_CACHE_VERSION, version);
|
||||||
bookFile.close();
|
bookFile.close();
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@@ -387,18 +386,18 @@ bool BookMetadataCache::load() {
|
|||||||
serialization::readString(bookFile, coreMetadata.textReferenceHref);
|
serialization::readString(bookFile, coreMetadata.textReferenceHref);
|
||||||
|
|
||||||
loaded = true;
|
loaded = true;
|
||||||
Serial.printf("[%lu] [BMC] Loaded cache data: %d spine, %d TOC entries\n", millis(), spineCount, tocCount);
|
LOG_DBG("BMC", "Loaded cache data: %d spine, %d TOC entries", spineCount, tocCount);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
BookMetadataCache::SpineEntry BookMetadataCache::getSpineEntry(const int index) {
|
BookMetadataCache::SpineEntry BookMetadataCache::getSpineEntry(const int index) {
|
||||||
if (!loaded) {
|
if (!loaded) {
|
||||||
Serial.printf("[%lu] [BMC] getSpineEntry called but cache not loaded\n", millis());
|
LOG_ERR("BMC", "getSpineEntry called but cache not loaded");
|
||||||
return {};
|
return {};
|
||||||
}
|
}
|
||||||
|
|
||||||
if (index < 0 || index >= static_cast<int>(spineCount)) {
|
if (index < 0 || index >= static_cast<int>(spineCount)) {
|
||||||
Serial.printf("[%lu] [BMC] getSpineEntry index %d out of range\n", millis(), index);
|
LOG_ERR("BMC", "getSpineEntry index %d out of range", index);
|
||||||
return {};
|
return {};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -412,12 +411,12 @@ BookMetadataCache::SpineEntry BookMetadataCache::getSpineEntry(const int index)
|
|||||||
|
|
||||||
BookMetadataCache::TocEntry BookMetadataCache::getTocEntry(const int index) {
|
BookMetadataCache::TocEntry BookMetadataCache::getTocEntry(const int index) {
|
||||||
if (!loaded) {
|
if (!loaded) {
|
||||||
Serial.printf("[%lu] [BMC] getTocEntry called but cache not loaded\n", millis());
|
LOG_ERR("BMC", "getTocEntry called but cache not loaded");
|
||||||
return {};
|
return {};
|
||||||
}
|
}
|
||||||
|
|
||||||
if (index < 0 || index >= static_cast<int>(tocCount)) {
|
if (index < 0 || index >= static_cast<int>(tocCount)) {
|
||||||
Serial.printf("[%lu] [BMC] getTocEntry index %d out of range\n", millis(), index);
|
LOG_ERR("BMC", "getTocEntry index %d out of range", index);
|
||||||
return {};
|
return {};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include <SDCardManager.h>
|
#include <HalStorage.h>
|
||||||
|
|
||||||
#include <algorithm>
|
#include <algorithm>
|
||||||
#include <string>
|
#include <string>
|
||||||
|
|||||||
@@ -1,8 +1,17 @@
|
|||||||
#include "Page.h"
|
#include "Page.h"
|
||||||
|
|
||||||
#include <HardwareSerial.h>
|
#include <GfxRenderer.h>
|
||||||
|
#include <Logging.h>
|
||||||
#include <Serialization.h>
|
#include <Serialization.h>
|
||||||
|
|
||||||
|
// Cell padding in pixels (must match TABLE_CELL_PAD_* in ChapterHtmlSlimParser.cpp)
|
||||||
|
static constexpr int TABLE_CELL_PADDING_X = 4;
|
||||||
|
static constexpr int TABLE_CELL_PADDING_TOP = 1;
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// PageLine
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
void PageLine::render(GfxRenderer& renderer, const int fontId, const int xOffset, const int yOffset) {
|
void PageLine::render(GfxRenderer& renderer, const int fontId, const int xOffset, const int yOffset) {
|
||||||
block->render(renderer, fontId, xPos + xOffset, yPos + yOffset);
|
block->render(renderer, fontId, xPos + xOffset, yPos + yOffset);
|
||||||
}
|
}
|
||||||
@@ -25,6 +34,142 @@ std::unique_ptr<PageLine> PageLine::deserialize(FsFile& file) {
|
|||||||
return std::unique_ptr<PageLine>(new PageLine(std::move(tb), xPos, yPos));
|
return std::unique_ptr<PageLine>(new PageLine(std::move(tb), xPos, yPos));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// PageImage
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
void PageImage::render(GfxRenderer& renderer, const int fontId, const int xOffset, const int yOffset) {
|
||||||
|
// Images don't use fontId or text rendering
|
||||||
|
imageBlock->render(renderer, xPos + xOffset, yPos + yOffset);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool PageImage::serialize(FsFile& file) {
|
||||||
|
serialization::writePod(file, xPos);
|
||||||
|
serialization::writePod(file, yPos);
|
||||||
|
|
||||||
|
// serialize ImageBlock
|
||||||
|
return imageBlock->serialize(file);
|
||||||
|
}
|
||||||
|
|
||||||
|
std::unique_ptr<PageImage> PageImage::deserialize(FsFile& file) {
|
||||||
|
int16_t xPos;
|
||||||
|
int16_t yPos;
|
||||||
|
serialization::readPod(file, xPos);
|
||||||
|
serialization::readPod(file, yPos);
|
||||||
|
|
||||||
|
auto ib = ImageBlock::deserialize(file);
|
||||||
|
return std::unique_ptr<PageImage>(new PageImage(std::move(ib), xPos, yPos));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// PageTableRow
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
void PageTableRow::render(GfxRenderer& renderer, const int fontId, const int xOffset, const int yOffset) {
|
||||||
|
const int baseX = xPos + xOffset;
|
||||||
|
const int baseY = yPos + yOffset;
|
||||||
|
|
||||||
|
// Draw horizontal borders (top and bottom of this row)
|
||||||
|
renderer.drawLine(baseX, baseY, baseX + totalWidth, baseY);
|
||||||
|
renderer.drawLine(baseX, baseY + rowHeight, baseX + totalWidth, baseY + rowHeight);
|
||||||
|
|
||||||
|
// Draw vertical borders and render cell contents
|
||||||
|
// Left edge
|
||||||
|
renderer.drawLine(baseX, baseY, baseX, baseY + rowHeight);
|
||||||
|
|
||||||
|
for (const auto& cell : cells) {
|
||||||
|
// Right vertical border for this cell
|
||||||
|
const int cellRightX = baseX + cell.xOffset + cell.columnWidth;
|
||||||
|
renderer.drawLine(cellRightX, baseY, cellRightX, baseY + rowHeight);
|
||||||
|
|
||||||
|
// Render each text line within the cell
|
||||||
|
const int cellTextX = baseX + cell.xOffset + TABLE_CELL_PADDING_X;
|
||||||
|
int cellLineY = baseY + 1 + TABLE_CELL_PADDING_TOP; // 1px border + top padding
|
||||||
|
|
||||||
|
for (const auto& line : cell.lines) {
|
||||||
|
line->render(renderer, fontId, cellTextX, cellLineY);
|
||||||
|
cellLineY += lineHeight;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
bool PageTableRow::serialize(FsFile& file) {
|
||||||
|
serialization::writePod(file, xPos);
|
||||||
|
serialization::writePod(file, yPos);
|
||||||
|
serialization::writePod(file, rowHeight);
|
||||||
|
serialization::writePod(file, totalWidth);
|
||||||
|
serialization::writePod(file, lineHeight);
|
||||||
|
|
||||||
|
const uint16_t cellCount = static_cast<uint16_t>(cells.size());
|
||||||
|
serialization::writePod(file, cellCount);
|
||||||
|
|
||||||
|
for (const auto& cell : cells) {
|
||||||
|
serialization::writePod(file, cell.xOffset);
|
||||||
|
serialization::writePod(file, cell.columnWidth);
|
||||||
|
|
||||||
|
const uint16_t lineCount = static_cast<uint16_t>(cell.lines.size());
|
||||||
|
serialization::writePod(file, lineCount);
|
||||||
|
|
||||||
|
for (const auto& line : cell.lines) {
|
||||||
|
if (!line->serialize(file)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::unique_ptr<PageTableRow> PageTableRow::deserialize(FsFile& file) {
|
||||||
|
int16_t xPos, yPos, rowHeight, totalWidth, lineHeight;
|
||||||
|
serialization::readPod(file, xPos);
|
||||||
|
serialization::readPod(file, yPos);
|
||||||
|
serialization::readPod(file, rowHeight);
|
||||||
|
serialization::readPod(file, totalWidth);
|
||||||
|
serialization::readPod(file, lineHeight);
|
||||||
|
|
||||||
|
uint16_t cellCount;
|
||||||
|
serialization::readPod(file, cellCount);
|
||||||
|
|
||||||
|
// Sanity check
|
||||||
|
if (cellCount > 100) {
|
||||||
|
LOG_ERR("PTR", "Deserialization failed: cell count %u exceeds maximum", cellCount);
|
||||||
|
return nullptr;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::vector<PageTableCellData> cells;
|
||||||
|
cells.resize(cellCount);
|
||||||
|
|
||||||
|
for (uint16_t c = 0; c < cellCount; ++c) {
|
||||||
|
serialization::readPod(file, cells[c].xOffset);
|
||||||
|
serialization::readPod(file, cells[c].columnWidth);
|
||||||
|
|
||||||
|
uint16_t lineCount;
|
||||||
|
serialization::readPod(file, lineCount);
|
||||||
|
|
||||||
|
if (lineCount > 1000) {
|
||||||
|
LOG_ERR("PTR", "Deserialization failed: line count %u in cell %u exceeds maximum", lineCount, c);
|
||||||
|
return nullptr;
|
||||||
|
}
|
||||||
|
|
||||||
|
cells[c].lines.reserve(lineCount);
|
||||||
|
for (uint16_t l = 0; l < lineCount; ++l) {
|
||||||
|
auto tb = TextBlock::deserialize(file);
|
||||||
|
if (!tb) {
|
||||||
|
return nullptr;
|
||||||
|
}
|
||||||
|
cells[c].lines.push_back(std::move(tb));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return std::unique_ptr<PageTableRow>(
|
||||||
|
new PageTableRow(std::move(cells), rowHeight, totalWidth, lineHeight, xPos, yPos));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Page
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
void Page::render(GfxRenderer& renderer, const int fontId, const int xOffset, const int yOffset) const {
|
void Page::render(GfxRenderer& renderer, const int fontId, const int xOffset, const int yOffset) const {
|
||||||
for (auto& element : elements) {
|
for (auto& element : elements) {
|
||||||
element->render(renderer, fontId, xOffset, yOffset);
|
element->render(renderer, fontId, xOffset, yOffset);
|
||||||
@@ -36,8 +181,7 @@ bool Page::serialize(FsFile& file) const {
|
|||||||
serialization::writePod(file, count);
|
serialization::writePod(file, count);
|
||||||
|
|
||||||
for (const auto& el : elements) {
|
for (const auto& el : elements) {
|
||||||
// Only PageLine exists currently
|
serialization::writePod(file, static_cast<uint8_t>(el->getTag()));
|
||||||
serialization::writePod(file, static_cast<uint8_t>(TAG_PageLine));
|
|
||||||
if (!el->serialize(file)) {
|
if (!el->serialize(file)) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@@ -59,11 +203,68 @@ std::unique_ptr<Page> Page::deserialize(FsFile& file) {
|
|||||||
if (tag == TAG_PageLine) {
|
if (tag == TAG_PageLine) {
|
||||||
auto pl = PageLine::deserialize(file);
|
auto pl = PageLine::deserialize(file);
|
||||||
page->elements.push_back(std::move(pl));
|
page->elements.push_back(std::move(pl));
|
||||||
|
} else if (tag == TAG_PageTableRow) {
|
||||||
|
auto tr = PageTableRow::deserialize(file);
|
||||||
|
if (!tr) {
|
||||||
|
LOG_ERR("PGE", "Deserialization failed for PageTableRow at element %u", i);
|
||||||
|
return nullptr;
|
||||||
|
}
|
||||||
|
page->elements.push_back(std::move(tr));
|
||||||
|
} else if (tag == TAG_PageImage) {
|
||||||
|
auto pi = PageImage::deserialize(file);
|
||||||
|
page->elements.push_back(std::move(pi));
|
||||||
} else {
|
} else {
|
||||||
Serial.printf("[%lu] [PGE] Deserialization failed: Unknown tag %u\n", millis(), tag);
|
LOG_ERR("PGE", "Deserialization failed: Unknown tag %u", tag);
|
||||||
return nullptr;
|
return nullptr;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return page;
|
return page;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
bool Page::getImageBoundingBox(int& outX, int& outY, int& outWidth, int& outHeight) const {
|
||||||
|
bool firstImage = true;
|
||||||
|
for (const auto& el : elements) {
|
||||||
|
if (el->getTag() == TAG_PageImage) {
|
||||||
|
PageImage* pi = static_cast<PageImage*>(el.get());
|
||||||
|
ImageBlock* ib = pi->getImageBlock();
|
||||||
|
|
||||||
|
if (firstImage) {
|
||||||
|
// Initialize with first image bounds
|
||||||
|
outX = pi->xPos;
|
||||||
|
outY = pi->yPos;
|
||||||
|
outWidth = ib->getWidth();
|
||||||
|
outHeight = ib->getHeight();
|
||||||
|
firstImage = false;
|
||||||
|
} else {
|
||||||
|
// Expand bounding box to include this image
|
||||||
|
int imgX = pi->xPos;
|
||||||
|
int imgY = pi->yPos;
|
||||||
|
int imgW = ib->getWidth();
|
||||||
|
int imgH = ib->getHeight();
|
||||||
|
|
||||||
|
// Expand right boundary
|
||||||
|
if (imgX + imgW > outX + outWidth) {
|
||||||
|
outWidth = (imgX + imgW) - outX;
|
||||||
|
}
|
||||||
|
// Expand left boundary
|
||||||
|
if (imgX < outX) {
|
||||||
|
int oldRight = outX + outWidth;
|
||||||
|
outX = imgX;
|
||||||
|
outWidth = oldRight - outX;
|
||||||
|
}
|
||||||
|
// Expand bottom boundary
|
||||||
|
if (imgY + imgH > outY + outHeight) {
|
||||||
|
outHeight = (imgY + imgH) - outY;
|
||||||
|
}
|
||||||
|
// Expand top boundary
|
||||||
|
if (imgY < outY) {
|
||||||
|
int oldBottom = outY + outHeight;
|
||||||
|
outY = imgY;
|
||||||
|
outHeight = oldBottom - outY;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return !firstImage; // Return true if at least one image was found
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,13 +1,17 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
#include <SdFat.h>
|
#include <HalStorage.h>
|
||||||
|
|
||||||
|
#include <algorithm>
|
||||||
#include <utility>
|
#include <utility>
|
||||||
#include <vector>
|
#include <vector>
|
||||||
|
|
||||||
|
#include "blocks/ImageBlock.h"
|
||||||
#include "blocks/TextBlock.h"
|
#include "blocks/TextBlock.h"
|
||||||
|
|
||||||
enum PageElementTag : uint8_t {
|
enum PageElementTag : uint8_t {
|
||||||
TAG_PageLine = 1,
|
TAG_PageLine = 1,
|
||||||
|
TAG_PageTableRow = 2,
|
||||||
|
TAG_PageImage = 3,
|
||||||
};
|
};
|
||||||
|
|
||||||
// represents something that has been added to a page
|
// represents something that has been added to a page
|
||||||
@@ -17,6 +21,7 @@ class PageElement {
|
|||||||
int16_t yPos;
|
int16_t yPos;
|
||||||
explicit PageElement(const int16_t xPos, const int16_t yPos) : xPos(xPos), yPos(yPos) {}
|
explicit PageElement(const int16_t xPos, const int16_t yPos) : xPos(xPos), yPos(yPos) {}
|
||||||
virtual ~PageElement() = default;
|
virtual ~PageElement() = default;
|
||||||
|
virtual PageElementTag getTag() const = 0;
|
||||||
virtual void render(GfxRenderer& renderer, int fontId, int xOffset, int yOffset) = 0;
|
virtual void render(GfxRenderer& renderer, int fontId, int xOffset, int yOffset) = 0;
|
||||||
virtual bool serialize(FsFile& file) = 0;
|
virtual bool serialize(FsFile& file) = 0;
|
||||||
};
|
};
|
||||||
@@ -28,11 +33,59 @@ class PageLine final : public PageElement {
|
|||||||
public:
|
public:
|
||||||
PageLine(std::shared_ptr<TextBlock> block, const int16_t xPos, const int16_t yPos)
|
PageLine(std::shared_ptr<TextBlock> block, const int16_t xPos, const int16_t yPos)
|
||||||
: PageElement(xPos, yPos), block(std::move(block)) {}
|
: PageElement(xPos, yPos), block(std::move(block)) {}
|
||||||
|
const std::shared_ptr<TextBlock>& getBlock() const { return block; }
|
||||||
|
PageElementTag getTag() const override { return TAG_PageLine; }
|
||||||
void render(GfxRenderer& renderer, int fontId, int xOffset, int yOffset) override;
|
void render(GfxRenderer& renderer, int fontId, int xOffset, int yOffset) override;
|
||||||
bool serialize(FsFile& file) override;
|
bool serialize(FsFile& file) override;
|
||||||
static std::unique_ptr<PageLine> deserialize(FsFile& file);
|
static std::unique_ptr<PageLine> deserialize(FsFile& file);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/// Data for a single cell within a PageTableRow.
|
||||||
|
struct PageTableCellData {
|
||||||
|
std::vector<std::shared_ptr<TextBlock>> lines; // Laid-out text lines for this cell
|
||||||
|
uint16_t columnWidth = 0; // Width of this column in pixels
|
||||||
|
uint16_t xOffset = 0; // X offset of this cell within the row
|
||||||
|
};
|
||||||
|
|
||||||
|
/// A table row element that renders cells in a column-aligned grid with borders.
|
||||||
|
class PageTableRow final : public PageElement {
|
||||||
|
std::vector<PageTableCellData> cells;
|
||||||
|
int16_t rowHeight; // Total row height in pixels
|
||||||
|
int16_t totalWidth; // Total table width in pixels
|
||||||
|
int16_t lineHeight; // Height of one text line (for vertical positioning of cell lines)
|
||||||
|
|
||||||
|
public:
|
||||||
|
PageTableRow(std::vector<PageTableCellData> cells, int16_t rowHeight, int16_t totalWidth, int16_t lineHeight,
|
||||||
|
int16_t xPos, int16_t yPos)
|
||||||
|
: PageElement(xPos, yPos),
|
||||||
|
cells(std::move(cells)),
|
||||||
|
rowHeight(rowHeight),
|
||||||
|
totalWidth(totalWidth),
|
||||||
|
lineHeight(lineHeight) {}
|
||||||
|
|
||||||
|
int16_t getHeight() const { return rowHeight; }
|
||||||
|
PageElementTag getTag() const override { return TAG_PageTableRow; }
|
||||||
|
void render(GfxRenderer& renderer, int fontId, int xOffset, int yOffset) override;
|
||||||
|
bool serialize(FsFile& file) override;
|
||||||
|
static std::unique_ptr<PageTableRow> deserialize(FsFile& file);
|
||||||
|
};
|
||||||
|
|
||||||
|
// An image element on a page
|
||||||
|
class PageImage final : public PageElement {
|
||||||
|
std::shared_ptr<ImageBlock> imageBlock;
|
||||||
|
|
||||||
|
public:
|
||||||
|
PageImage(std::shared_ptr<ImageBlock> block, const int16_t xPos, const int16_t yPos)
|
||||||
|
: PageElement(xPos, yPos), imageBlock(std::move(block)) {}
|
||||||
|
void render(GfxRenderer& renderer, int fontId, int xOffset, int yOffset) override;
|
||||||
|
bool serialize(FsFile& file) override;
|
||||||
|
PageElementTag getTag() const override { return TAG_PageImage; }
|
||||||
|
static std::unique_ptr<PageImage> deserialize(FsFile& file);
|
||||||
|
|
||||||
|
// Helper to get image block dimensions (needed for bounding box calculation)
|
||||||
|
ImageBlock* getImageBlock() const { return imageBlock.get(); }
|
||||||
|
};
|
||||||
|
|
||||||
class Page {
|
class Page {
|
||||||
public:
|
public:
|
||||||
// the list of block index and line numbers on this page
|
// the list of block index and line numbers on this page
|
||||||
@@ -40,4 +93,15 @@ class Page {
|
|||||||
void render(GfxRenderer& renderer, int fontId, int xOffset, int yOffset) const;
|
void render(GfxRenderer& renderer, int fontId, int xOffset, int yOffset) const;
|
||||||
bool serialize(FsFile& file) const;
|
bool serialize(FsFile& file) const;
|
||||||
static std::unique_ptr<Page> deserialize(FsFile& file);
|
static std::unique_ptr<Page> deserialize(FsFile& file);
|
||||||
|
|
||||||
|
// Check if page contains any images (used to force full refresh)
|
||||||
|
bool hasImages() const {
|
||||||
|
return std::any_of(elements.begin(), elements.end(),
|
||||||
|
[](const std::shared_ptr<PageElement>& el) { return el->getTag() == TAG_PageImage; });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get the bounding box of all images on this page.
|
||||||
|
// Returns true if page has images and fills out the bounding box coordinates.
|
||||||
|
// If no images, returns false.
|
||||||
|
bool getImageBoundingBox(int& outX, int& outY, int& outWidth, int& outHeight) const;
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -5,7 +5,6 @@
|
|||||||
#include <algorithm>
|
#include <algorithm>
|
||||||
#include <cmath>
|
#include <cmath>
|
||||||
#include <functional>
|
#include <functional>
|
||||||
#include <iterator>
|
|
||||||
#include <limits>
|
#include <limits>
|
||||||
#include <vector>
|
#include <vector>
|
||||||
|
|
||||||
@@ -32,6 +31,9 @@ void stripSoftHyphensInPlace(std::string& word) {
|
|||||||
// Returns the rendered width for a word while ignoring soft hyphen glyphs and optionally appending a visible hyphen.
|
// Returns the rendered width for a word while ignoring soft hyphen glyphs and optionally appending a visible hyphen.
|
||||||
uint16_t measureWordWidth(const GfxRenderer& renderer, const int fontId, const std::string& word,
|
uint16_t measureWordWidth(const GfxRenderer& renderer, const int fontId, const std::string& word,
|
||||||
const EpdFontFamily::Style style, const bool appendHyphen = false) {
|
const EpdFontFamily::Style style, const bool appendHyphen = false) {
|
||||||
|
if (word.size() == 1 && word[0] == ' ' && !appendHyphen) {
|
||||||
|
return renderer.getSpaceWidth(fontId);
|
||||||
|
}
|
||||||
const bool hasSoftHyphen = containsSoftHyphen(word);
|
const bool hasSoftHyphen = containsSoftHyphen(word);
|
||||||
if (!hasSoftHyphen && !appendHyphen) {
|
if (!hasSoftHyphen && !appendHyphen) {
|
||||||
return renderer.getTextWidth(fontId, word.c_str(), style);
|
return renderer.getTextWidth(fontId, word.c_str(), style);
|
||||||
@@ -49,11 +51,24 @@ uint16_t measureWordWidth(const GfxRenderer& renderer, const int fontId, const s
|
|||||||
|
|
||||||
} // namespace
|
} // namespace
|
||||||
|
|
||||||
void ParsedText::addWord(std::string word, const EpdFontFamily::Style fontStyle) {
|
void ParsedText::addWord(std::string word, const EpdFontFamily::Style fontStyle, const bool underline,
|
||||||
|
const bool attachToPrevious) {
|
||||||
if (word.empty()) return;
|
if (word.empty()) return;
|
||||||
|
|
||||||
words.push_back(std::move(word));
|
words.push_back(std::move(word));
|
||||||
wordStyles.push_back(fontStyle);
|
EpdFontFamily::Style combinedStyle = fontStyle;
|
||||||
|
if (underline) {
|
||||||
|
combinedStyle = static_cast<EpdFontFamily::Style>(combinedStyle | EpdFontFamily::UNDERLINE);
|
||||||
|
}
|
||||||
|
wordStyles.push_back(combinedStyle);
|
||||||
|
wordContinues.push_back(attachToPrevious);
|
||||||
|
forceBreakAfter.push_back(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
void ParsedText::addLineBreak() {
|
||||||
|
if (!words.empty()) {
|
||||||
|
forceBreakAfter.back() = true;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Consumes data to minimize memory usage
|
// Consumes data to minimize memory usage
|
||||||
@@ -70,49 +85,52 @@ void ParsedText::layoutAndExtractLines(const GfxRenderer& renderer, const int fo
|
|||||||
const int pageWidth = viewportWidth;
|
const int pageWidth = viewportWidth;
|
||||||
const int spaceWidth = renderer.getSpaceWidth(fontId);
|
const int spaceWidth = renderer.getSpaceWidth(fontId);
|
||||||
auto wordWidths = calculateWordWidths(renderer, fontId);
|
auto wordWidths = calculateWordWidths(renderer, fontId);
|
||||||
|
|
||||||
std::vector<size_t> lineBreakIndices;
|
std::vector<size_t> lineBreakIndices;
|
||||||
if (hyphenationEnabled) {
|
if (hyphenationEnabled) {
|
||||||
// Use greedy layout that can split words mid-loop when a hyphenated prefix fits.
|
// Use greedy layout that can split words mid-loop when a hyphenated prefix fits.
|
||||||
lineBreakIndices = computeHyphenatedLineBreaks(renderer, fontId, pageWidth, spaceWidth, wordWidths);
|
lineBreakIndices = computeHyphenatedLineBreaks(renderer, fontId, pageWidth, spaceWidth, wordWidths, wordContinues);
|
||||||
} else {
|
} else {
|
||||||
lineBreakIndices = computeLineBreaks(renderer, fontId, pageWidth, spaceWidth, wordWidths);
|
lineBreakIndices = computeLineBreaks(renderer, fontId, pageWidth, spaceWidth, wordWidths, wordContinues);
|
||||||
}
|
}
|
||||||
const size_t lineCount = includeLastLine ? lineBreakIndices.size() : lineBreakIndices.size() - 1;
|
const size_t lineCount = includeLastLine ? lineBreakIndices.size() : lineBreakIndices.size() - 1;
|
||||||
|
|
||||||
for (size_t i = 0; i < lineCount; ++i) {
|
for (size_t i = 0; i < lineCount; ++i) {
|
||||||
extractLine(i, pageWidth, spaceWidth, wordWidths, lineBreakIndices, processLine);
|
extractLine(i, pageWidth, spaceWidth, wordWidths, wordContinues, lineBreakIndices, processLine);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
std::vector<uint16_t> ParsedText::calculateWordWidths(const GfxRenderer& renderer, const int fontId) {
|
std::vector<uint16_t> ParsedText::calculateWordWidths(const GfxRenderer& renderer, const int fontId) {
|
||||||
const size_t totalWordCount = words.size();
|
|
||||||
|
|
||||||
std::vector<uint16_t> wordWidths;
|
std::vector<uint16_t> wordWidths;
|
||||||
wordWidths.reserve(totalWordCount);
|
wordWidths.reserve(words.size());
|
||||||
|
|
||||||
auto wordsIt = words.begin();
|
for (size_t i = 0; i < words.size(); ++i) {
|
||||||
auto wordStylesIt = wordStyles.begin();
|
wordWidths.push_back(measureWordWidth(renderer, fontId, words[i], wordStyles[i]));
|
||||||
|
|
||||||
while (wordsIt != words.end()) {
|
|
||||||
wordWidths.push_back(measureWordWidth(renderer, fontId, *wordsIt, *wordStylesIt));
|
|
||||||
|
|
||||||
std::advance(wordsIt, 1);
|
|
||||||
std::advance(wordStylesIt, 1);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return wordWidths;
|
return wordWidths;
|
||||||
}
|
}
|
||||||
|
|
||||||
std::vector<size_t> ParsedText::computeLineBreaks(const GfxRenderer& renderer, const int fontId, const int pageWidth,
|
std::vector<size_t> ParsedText::computeLineBreaks(const GfxRenderer& renderer, const int fontId, const int pageWidth,
|
||||||
const int spaceWidth, std::vector<uint16_t>& wordWidths) {
|
const int spaceWidth, std::vector<uint16_t>& wordWidths,
|
||||||
|
std::vector<bool>& continuesVec) {
|
||||||
if (words.empty()) {
|
if (words.empty()) {
|
||||||
return {};
|
return {};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Calculate first line indent (only for left/justified text without extra paragraph spacing)
|
||||||
|
const int firstLineIndent =
|
||||||
|
blockStyle.textIndent > 0 && !extraParagraphSpacing &&
|
||||||
|
(blockStyle.alignment == CssTextAlign::Justify || blockStyle.alignment == CssTextAlign::Left)
|
||||||
|
? blockStyle.textIndent
|
||||||
|
: 0;
|
||||||
|
|
||||||
// Ensure any word that would overflow even as the first entry on a line is split using fallback hyphenation.
|
// Ensure any word that would overflow even as the first entry on a line is split using fallback hyphenation.
|
||||||
for (size_t i = 0; i < wordWidths.size(); ++i) {
|
for (size_t i = 0; i < wordWidths.size(); ++i) {
|
||||||
while (wordWidths[i] > pageWidth) {
|
// First word needs to fit in reduced width if there's an indent
|
||||||
if (!hyphenateWordAtIndex(i, pageWidth, renderer, fontId, wordWidths, /*allowFallbackBreaks=*/true)) {
|
const int effectiveWidth = i == 0 ? pageWidth - firstLineIndent : pageWidth;
|
||||||
|
while (wordWidths[i] > effectiveWidth) {
|
||||||
|
if (!hyphenateWordAtIndex(i, effectiveWidth, renderer, fontId, wordWidths, /*allowFallbackBreaks=*/true)) {
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -130,22 +148,39 @@ std::vector<size_t> ParsedText::computeLineBreaks(const GfxRenderer& renderer, c
|
|||||||
ans[totalWordCount - 1] = totalWordCount - 1;
|
ans[totalWordCount - 1] = totalWordCount - 1;
|
||||||
|
|
||||||
for (int i = totalWordCount - 2; i >= 0; --i) {
|
for (int i = totalWordCount - 2; i >= 0; --i) {
|
||||||
int currlen = -spaceWidth;
|
int currlen = 0;
|
||||||
dp[i] = MAX_COST;
|
dp[i] = MAX_COST;
|
||||||
|
|
||||||
for (size_t j = i; j < totalWordCount; ++j) {
|
// First line has reduced width due to text-indent
|
||||||
// Current line length: previous width + space + current word width
|
const int effectivePageWidth = i == 0 ? pageWidth - firstLineIndent : pageWidth;
|
||||||
currlen += wordWidths[j] + spaceWidth;
|
|
||||||
|
|
||||||
if (currlen > pageWidth) {
|
for (size_t j = i; j < totalWordCount; ++j) {
|
||||||
|
// If the previous word has a forced line break, this line cannot include word j
|
||||||
|
if (j > static_cast<size_t>(i) && !forceBreakAfter.empty() && forceBreakAfter[j - 1]) {
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Add space before word j, unless it's the first word on the line or a continuation
|
||||||
|
const int gap = j > static_cast<size_t>(i) && !continuesVec[j] ? spaceWidth : 0;
|
||||||
|
currlen += wordWidths[j] + gap;
|
||||||
|
|
||||||
|
if (currlen > effectivePageWidth) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Forced line break after word j overrides continuation (must end line here)
|
||||||
|
const bool mustBreakHere = !forceBreakAfter.empty() && forceBreakAfter[j];
|
||||||
|
|
||||||
|
// Cannot break after word j if the next word attaches to it (unless forced)
|
||||||
|
if (!mustBreakHere && j + 1 < totalWordCount && continuesVec[j + 1]) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
int cost;
|
int cost;
|
||||||
if (j == totalWordCount - 1) {
|
if (j == totalWordCount - 1) {
|
||||||
cost = 0; // Last line
|
cost = 0; // Last line
|
||||||
} else {
|
} else {
|
||||||
const int remainingSpace = pageWidth - currlen;
|
const int remainingSpace = effectivePageWidth - currlen;
|
||||||
// Use long long for the square to prevent overflow
|
// Use long long for the square to prevent overflow
|
||||||
const long long cost_ll = static_cast<long long>(remainingSpace) * remainingSpace + dp[j + 1];
|
const long long cost_ll = static_cast<long long>(remainingSpace) * remainingSpace + dp[j + 1];
|
||||||
|
|
||||||
@@ -160,6 +195,11 @@ std::vector<size_t> ParsedText::computeLineBreaks(const GfxRenderer& renderer, c
|
|||||||
dp[i] = cost;
|
dp[i] = cost;
|
||||||
ans[i] = j; // j is the index of the last word in this optimal line
|
ans[i] = j; // j is the index of the last word in this optimal line
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// After evaluating cost, enforce forced break - no more words on this line
|
||||||
|
if (mustBreakHere) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Handle oversized word: if no valid configuration found, force single-word line
|
// Handle oversized word: if no valid configuration found, force single-word line
|
||||||
@@ -200,7 +240,11 @@ void ParsedText::applyParagraphIndent() {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (style == TextBlock::JUSTIFIED || style == TextBlock::LEFT_ALIGN) {
|
if (blockStyle.textIndentDefined) {
|
||||||
|
// CSS text-indent is explicitly set (even if 0) - don't use fallback EmSpace
|
||||||
|
// The actual indent positioning is handled in extractLine()
|
||||||
|
} else if (blockStyle.alignment == CssTextAlign::Justify || blockStyle.alignment == CssTextAlign::Left) {
|
||||||
|
// No CSS text-indent defined - use EmSpace fallback for visual indent
|
||||||
words.front().insert(0, "\xe2\x80\x83");
|
words.front().insert(0, "\xe2\x80\x83");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -208,29 +252,51 @@ void ParsedText::applyParagraphIndent() {
|
|||||||
// Builds break indices while opportunistically splitting the word that would overflow the current line.
|
// Builds break indices while opportunistically splitting the word that would overflow the current line.
|
||||||
std::vector<size_t> ParsedText::computeHyphenatedLineBreaks(const GfxRenderer& renderer, const int fontId,
|
std::vector<size_t> ParsedText::computeHyphenatedLineBreaks(const GfxRenderer& renderer, const int fontId,
|
||||||
const int pageWidth, const int spaceWidth,
|
const int pageWidth, const int spaceWidth,
|
||||||
std::vector<uint16_t>& wordWidths) {
|
std::vector<uint16_t>& wordWidths,
|
||||||
|
std::vector<bool>& continuesVec) {
|
||||||
|
// Calculate first line indent (only for left/justified text without extra paragraph spacing)
|
||||||
|
const int firstLineIndent =
|
||||||
|
blockStyle.textIndent > 0 && !extraParagraphSpacing &&
|
||||||
|
(blockStyle.alignment == CssTextAlign::Justify || blockStyle.alignment == CssTextAlign::Left)
|
||||||
|
? blockStyle.textIndent
|
||||||
|
: 0;
|
||||||
|
|
||||||
std::vector<size_t> lineBreakIndices;
|
std::vector<size_t> lineBreakIndices;
|
||||||
size_t currentIndex = 0;
|
size_t currentIndex = 0;
|
||||||
|
bool isFirstLine = true;
|
||||||
|
|
||||||
while (currentIndex < wordWidths.size()) {
|
while (currentIndex < wordWidths.size()) {
|
||||||
const size_t lineStart = currentIndex;
|
const size_t lineStart = currentIndex;
|
||||||
int lineWidth = 0;
|
int lineWidth = 0;
|
||||||
|
|
||||||
|
// First line has reduced width due to text-indent
|
||||||
|
const int effectivePageWidth = isFirstLine ? pageWidth - firstLineIndent : pageWidth;
|
||||||
|
|
||||||
// Consume as many words as possible for current line, splitting when prefixes fit
|
// Consume as many words as possible for current line, splitting when prefixes fit
|
||||||
while (currentIndex < wordWidths.size()) {
|
while (currentIndex < wordWidths.size()) {
|
||||||
|
// If the previous word has a forced line break, stop - this word starts a new line
|
||||||
|
if (currentIndex > lineStart && !forceBreakAfter.empty() && forceBreakAfter[currentIndex - 1]) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
const bool isFirstWord = currentIndex == lineStart;
|
const bool isFirstWord = currentIndex == lineStart;
|
||||||
const int spacing = isFirstWord ? 0 : spaceWidth;
|
const int spacing = isFirstWord || continuesVec[currentIndex] ? 0 : spaceWidth;
|
||||||
const int candidateWidth = spacing + wordWidths[currentIndex];
|
const int candidateWidth = spacing + wordWidths[currentIndex];
|
||||||
|
|
||||||
// Word fits on current line
|
// Word fits on current line
|
||||||
if (lineWidth + candidateWidth <= pageWidth) {
|
if (lineWidth + candidateWidth <= effectivePageWidth) {
|
||||||
lineWidth += candidateWidth;
|
lineWidth += candidateWidth;
|
||||||
++currentIndex;
|
++currentIndex;
|
||||||
|
|
||||||
|
// If the word we just added has a forced break, end this line now
|
||||||
|
if (!forceBreakAfter.empty() && forceBreakAfter[currentIndex - 1]) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Word would overflow — try to split based on hyphenation points
|
// Word would overflow — try to split based on hyphenation points
|
||||||
const int availableWidth = pageWidth - lineWidth - spacing;
|
const int availableWidth = effectivePageWidth - lineWidth - spacing;
|
||||||
const bool allowFallbackBreaks = isFirstWord; // Only for first word on line
|
const bool allowFallbackBreaks = isFirstWord; // Only for first word on line
|
||||||
|
|
||||||
if (availableWidth > 0 &&
|
if (availableWidth > 0 &&
|
||||||
@@ -249,7 +315,19 @@ std::vector<size_t> ParsedText::computeHyphenatedLineBreaks(const GfxRenderer& r
|
|||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Don't break before a continuation word (e.g., orphaned "?" after "question").
|
||||||
|
// Backtrack to the start of the continuation group so the whole group moves to the next line.
|
||||||
|
// But don't backtrack past a forced break point.
|
||||||
|
while (currentIndex > lineStart + 1 && currentIndex < wordWidths.size() && continuesVec[currentIndex]) {
|
||||||
|
// Don't backtrack past a forced break
|
||||||
|
if (!forceBreakAfter.empty() && forceBreakAfter[currentIndex - 1]) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
--currentIndex;
|
||||||
|
}
|
||||||
|
|
||||||
lineBreakIndices.push_back(currentIndex);
|
lineBreakIndices.push_back(currentIndex);
|
||||||
|
isFirstLine = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
return lineBreakIndices;
|
return lineBreakIndices;
|
||||||
@@ -265,14 +343,8 @@ bool ParsedText::hyphenateWordAtIndex(const size_t wordIndex, const int availabl
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get iterators to target word and style.
|
const std::string& word = words[wordIndex];
|
||||||
auto wordIt = words.begin();
|
const auto style = wordStyles[wordIndex];
|
||||||
auto styleIt = wordStyles.begin();
|
|
||||||
std::advance(wordIt, wordIndex);
|
|
||||||
std::advance(styleIt, wordIndex);
|
|
||||||
|
|
||||||
const std::string& word = *wordIt;
|
|
||||||
const auto style = *styleIt;
|
|
||||||
|
|
||||||
// Collect candidate breakpoints (byte offsets and hyphen requirements).
|
// Collect candidate breakpoints (byte offsets and hyphen requirements).
|
||||||
auto breakInfos = Hyphenator::breakOffsets(word, allowFallbackBreaks);
|
auto breakInfos = Hyphenator::breakOffsets(word, allowFallbackBreaks);
|
||||||
@@ -309,16 +381,27 @@ bool ParsedText::hyphenateWordAtIndex(const size_t wordIndex, const int availabl
|
|||||||
|
|
||||||
// Split the word at the selected breakpoint and append a hyphen if required.
|
// Split the word at the selected breakpoint and append a hyphen if required.
|
||||||
std::string remainder = word.substr(chosenOffset);
|
std::string remainder = word.substr(chosenOffset);
|
||||||
wordIt->resize(chosenOffset);
|
words[wordIndex].resize(chosenOffset);
|
||||||
if (chosenNeedsHyphen) {
|
if (chosenNeedsHyphen) {
|
||||||
wordIt->push_back('-');
|
words[wordIndex].push_back('-');
|
||||||
}
|
}
|
||||||
|
|
||||||
// Insert the remainder word (with matching style) directly after the prefix.
|
// Insert the remainder word (with matching style and continuation flag) directly after the prefix.
|
||||||
auto insertWordIt = std::next(wordIt);
|
words.insert(words.begin() + wordIndex + 1, remainder);
|
||||||
auto insertStyleIt = std::next(styleIt);
|
wordStyles.insert(wordStyles.begin() + wordIndex + 1, style);
|
||||||
words.insert(insertWordIt, remainder);
|
|
||||||
wordStyles.insert(insertStyleIt, style);
|
// The remainder inherits whatever continuation status the original word had with the word after it.
|
||||||
|
const bool originalContinuedToNext = wordContinues[wordIndex];
|
||||||
|
// The original word (now prefix) does NOT continue to remainder (hyphen separates them)
|
||||||
|
wordContinues[wordIndex] = false;
|
||||||
|
wordContinues.insert(wordContinues.begin() + wordIndex + 1, originalContinuedToNext);
|
||||||
|
|
||||||
|
// Forced break belongs to the original whole word; transfer it to the remainder (last part).
|
||||||
|
if (!forceBreakAfter.empty()) {
|
||||||
|
const bool originalForceBreak = forceBreakAfter[wordIndex];
|
||||||
|
forceBreakAfter[wordIndex] = false; // prefix doesn't force break
|
||||||
|
forceBreakAfter.insert(forceBreakAfter.begin() + wordIndex + 1, originalForceBreak);
|
||||||
|
}
|
||||||
|
|
||||||
// Update cached widths to reflect the new prefix/remainder pairing.
|
// Update cached widths to reflect the new prefix/remainder pairing.
|
||||||
wordWidths[wordIndex] = static_cast<uint16_t>(chosenWidth);
|
wordWidths[wordIndex] = static_cast<uint16_t>(chosenWidth);
|
||||||
@@ -328,55 +411,74 @@ bool ParsedText::hyphenateWordAtIndex(const size_t wordIndex, const int availabl
|
|||||||
}
|
}
|
||||||
|
|
||||||
void ParsedText::extractLine(const size_t breakIndex, const int pageWidth, const int spaceWidth,
|
void ParsedText::extractLine(const size_t breakIndex, const int pageWidth, const int spaceWidth,
|
||||||
const std::vector<uint16_t>& wordWidths, const std::vector<size_t>& lineBreakIndices,
|
const std::vector<uint16_t>& wordWidths, const std::vector<bool>& continuesVec,
|
||||||
|
const std::vector<size_t>& lineBreakIndices,
|
||||||
const std::function<void(std::shared_ptr<TextBlock>)>& processLine) {
|
const std::function<void(std::shared_ptr<TextBlock>)>& processLine) {
|
||||||
const size_t lineBreak = lineBreakIndices[breakIndex];
|
const size_t lineBreak = lineBreakIndices[breakIndex];
|
||||||
const size_t lastBreakAt = breakIndex > 0 ? lineBreakIndices[breakIndex - 1] : 0;
|
const size_t lastBreakAt = breakIndex > 0 ? lineBreakIndices[breakIndex - 1] : 0;
|
||||||
const size_t lineWordCount = lineBreak - lastBreakAt;
|
const size_t lineWordCount = lineBreak - lastBreakAt;
|
||||||
|
|
||||||
// Calculate total word width for this line
|
// Calculate first line indent (only for left/justified text without extra paragraph spacing)
|
||||||
|
const bool isFirstLine = breakIndex == 0;
|
||||||
|
const int firstLineIndent =
|
||||||
|
isFirstLine && blockStyle.textIndent > 0 && !extraParagraphSpacing &&
|
||||||
|
(blockStyle.alignment == CssTextAlign::Justify || blockStyle.alignment == CssTextAlign::Left)
|
||||||
|
? blockStyle.textIndent
|
||||||
|
: 0;
|
||||||
|
|
||||||
|
// Calculate total word width for this line and count actual word gaps
|
||||||
|
// (continuation words attach to previous word with no gap)
|
||||||
int lineWordWidthSum = 0;
|
int lineWordWidthSum = 0;
|
||||||
for (size_t i = lastBreakAt; i < lineBreak; i++) {
|
size_t actualGapCount = 0;
|
||||||
lineWordWidthSum += wordWidths[i];
|
|
||||||
|
for (size_t wordIdx = 0; wordIdx < lineWordCount; wordIdx++) {
|
||||||
|
lineWordWidthSum += wordWidths[lastBreakAt + wordIdx];
|
||||||
|
// Count gaps: each word after the first creates a gap, unless it's a continuation
|
||||||
|
if (wordIdx > 0 && !continuesVec[lastBreakAt + wordIdx]) {
|
||||||
|
actualGapCount++;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Calculate spacing
|
// Calculate spacing (account for indent reducing effective page width on first line)
|
||||||
const int spareSpace = pageWidth - lineWordWidthSum;
|
const int effectivePageWidth = pageWidth - firstLineIndent;
|
||||||
|
const int spareSpace = effectivePageWidth - lineWordWidthSum;
|
||||||
|
|
||||||
int spacing = spaceWidth;
|
int spacing = spaceWidth;
|
||||||
const bool isLastLine = breakIndex == lineBreakIndices.size() - 1;
|
const bool isLastLine = breakIndex == lineBreakIndices.size() - 1;
|
||||||
|
|
||||||
if (style == TextBlock::JUSTIFIED && !isLastLine && lineWordCount >= 2) {
|
// For justified text, calculate spacing based on actual gap count
|
||||||
spacing = spareSpace / (lineWordCount - 1);
|
if (blockStyle.alignment == CssTextAlign::Justify && !isLastLine && actualGapCount >= 1) {
|
||||||
|
spacing = spareSpace / static_cast<int>(actualGapCount);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Calculate initial x position
|
// Calculate initial x position (first line starts at indent for left/justified text)
|
||||||
uint16_t xpos = 0;
|
auto xpos = static_cast<uint16_t>(firstLineIndent);
|
||||||
if (style == TextBlock::RIGHT_ALIGN) {
|
if (blockStyle.alignment == CssTextAlign::Right) {
|
||||||
xpos = spareSpace - (lineWordCount - 1) * spaceWidth;
|
xpos = spareSpace - static_cast<int>(actualGapCount) * spaceWidth;
|
||||||
} else if (style == TextBlock::CENTER_ALIGN) {
|
} else if (blockStyle.alignment == CssTextAlign::Center) {
|
||||||
xpos = (spareSpace - (lineWordCount - 1) * spaceWidth) / 2;
|
xpos = (spareSpace - static_cast<int>(actualGapCount) * spaceWidth) / 2;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Pre-calculate X positions for words
|
// Pre-calculate X positions for words
|
||||||
std::list<uint16_t> lineXPos;
|
// Continuation words attach to the previous word with no space before them
|
||||||
for (size_t i = lastBreakAt; i < lineBreak; i++) {
|
std::vector<uint16_t> lineXPos;
|
||||||
const uint16_t currentWordWidth = wordWidths[i];
|
lineXPos.reserve(lineWordCount);
|
||||||
|
|
||||||
|
for (size_t wordIdx = 0; wordIdx < lineWordCount; wordIdx++) {
|
||||||
|
const uint16_t currentWordWidth = wordWidths[lastBreakAt + wordIdx];
|
||||||
|
|
||||||
lineXPos.push_back(xpos);
|
lineXPos.push_back(xpos);
|
||||||
xpos += currentWordWidth + spacing;
|
|
||||||
|
// Add spacing after this word, unless the next word is a continuation
|
||||||
|
const bool nextIsContinuation = wordIdx + 1 < lineWordCount && continuesVec[lastBreakAt + wordIdx + 1];
|
||||||
|
|
||||||
|
xpos += currentWordWidth + (nextIsContinuation ? 0 : spacing);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Iterators always start at the beginning as we are moving content with splice below
|
// Build line data by moving from the original vectors using index range
|
||||||
auto wordEndIt = words.begin();
|
std::vector<std::string> lineWords(std::make_move_iterator(words.begin() + lastBreakAt),
|
||||||
auto wordStyleEndIt = wordStyles.begin();
|
std::make_move_iterator(words.begin() + lineBreak));
|
||||||
std::advance(wordEndIt, lineWordCount);
|
std::vector<EpdFontFamily::Style> lineWordStyles(wordStyles.begin() + lastBreakAt, wordStyles.begin() + lineBreak);
|
||||||
std::advance(wordStyleEndIt, lineWordCount);
|
|
||||||
|
|
||||||
// *** CRITICAL STEP: CONSUME DATA USING SPLICE ***
|
|
||||||
std::list<std::string> lineWords;
|
|
||||||
lineWords.splice(lineWords.begin(), words, words.begin(), wordEndIt);
|
|
||||||
std::list<EpdFontFamily::Style> lineWordStyles;
|
|
||||||
lineWordStyles.splice(lineWordStyles.begin(), wordStyles, wordStyles.begin(), wordStyleEndIt);
|
|
||||||
|
|
||||||
for (auto& word : lineWords) {
|
for (auto& word : lineWords) {
|
||||||
if (containsSoftHyphen(word)) {
|
if (containsSoftHyphen(word)) {
|
||||||
@@ -384,5 +486,25 @@ void ParsedText::extractLine(const size_t breakIndex, const int pageWidth, const
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
processLine(std::make_shared<TextBlock>(std::move(lineWords), std::move(lineXPos), std::move(lineWordStyles), style));
|
processLine(
|
||||||
|
std::make_shared<TextBlock>(std::move(lineWords), std::move(lineXPos), std::move(lineWordStyles), blockStyle));
|
||||||
|
}
|
||||||
|
|
||||||
|
uint16_t ParsedText::getNaturalWidth(const GfxRenderer& renderer, const int fontId) const {
|
||||||
|
if (words.empty()) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
const int spaceWidth = renderer.getSpaceWidth(fontId);
|
||||||
|
int totalWidth = 0;
|
||||||
|
|
||||||
|
for (size_t i = 0; i < words.size(); ++i) {
|
||||||
|
totalWidth += measureWordWidth(renderer, fontId, words[i], wordStyles[i]);
|
||||||
|
// Add a space before this word unless it's the first word or a continuation
|
||||||
|
if (i > 0 && !wordContinues[i]) {
|
||||||
|
totalWidth += spaceWidth;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return static_cast<uint16_t>(std::min(totalWidth, static_cast<int>(UINT16_MAX)));
|
||||||
}
|
}
|
||||||
@@ -3,46 +3,58 @@
|
|||||||
#include <EpdFontFamily.h>
|
#include <EpdFontFamily.h>
|
||||||
|
|
||||||
#include <functional>
|
#include <functional>
|
||||||
#include <list>
|
|
||||||
#include <memory>
|
#include <memory>
|
||||||
#include <string>
|
#include <string>
|
||||||
#include <vector>
|
#include <vector>
|
||||||
|
|
||||||
|
#include "blocks/BlockStyle.h"
|
||||||
#include "blocks/TextBlock.h"
|
#include "blocks/TextBlock.h"
|
||||||
|
|
||||||
class GfxRenderer;
|
class GfxRenderer;
|
||||||
|
|
||||||
class ParsedText {
|
class ParsedText {
|
||||||
std::list<std::string> words;
|
std::vector<std::string> words;
|
||||||
std::list<EpdFontFamily::Style> wordStyles;
|
std::vector<EpdFontFamily::Style> wordStyles;
|
||||||
TextBlock::Style style;
|
std::vector<bool> wordContinues; // true = word attaches to previous (no space before it)
|
||||||
|
std::vector<bool> forceBreakAfter; // true = mandatory line break after this word (e.g. <br> in table cells)
|
||||||
|
BlockStyle blockStyle;
|
||||||
bool extraParagraphSpacing;
|
bool extraParagraphSpacing;
|
||||||
bool hyphenationEnabled;
|
bool hyphenationEnabled;
|
||||||
|
|
||||||
void applyParagraphIndent();
|
void applyParagraphIndent();
|
||||||
std::vector<size_t> computeLineBreaks(const GfxRenderer& renderer, int fontId, int pageWidth, int spaceWidth,
|
std::vector<size_t> computeLineBreaks(const GfxRenderer& renderer, int fontId, int pageWidth, int spaceWidth,
|
||||||
std::vector<uint16_t>& wordWidths);
|
std::vector<uint16_t>& wordWidths, std::vector<bool>& continuesVec);
|
||||||
std::vector<size_t> computeHyphenatedLineBreaks(const GfxRenderer& renderer, int fontId, int pageWidth,
|
std::vector<size_t> computeHyphenatedLineBreaks(const GfxRenderer& renderer, int fontId, int pageWidth,
|
||||||
int spaceWidth, std::vector<uint16_t>& wordWidths);
|
int spaceWidth, std::vector<uint16_t>& wordWidths,
|
||||||
|
std::vector<bool>& continuesVec);
|
||||||
bool hyphenateWordAtIndex(size_t wordIndex, int availableWidth, const GfxRenderer& renderer, int fontId,
|
bool hyphenateWordAtIndex(size_t wordIndex, int availableWidth, const GfxRenderer& renderer, int fontId,
|
||||||
std::vector<uint16_t>& wordWidths, bool allowFallbackBreaks);
|
std::vector<uint16_t>& wordWidths, bool allowFallbackBreaks);
|
||||||
void extractLine(size_t breakIndex, int pageWidth, int spaceWidth, const std::vector<uint16_t>& wordWidths,
|
void extractLine(size_t breakIndex, int pageWidth, int spaceWidth, const std::vector<uint16_t>& wordWidths,
|
||||||
const std::vector<size_t>& lineBreakIndices,
|
const std::vector<bool>& continuesVec, const std::vector<size_t>& lineBreakIndices,
|
||||||
const std::function<void(std::shared_ptr<TextBlock>)>& processLine);
|
const std::function<void(std::shared_ptr<TextBlock>)>& processLine);
|
||||||
std::vector<uint16_t> calculateWordWidths(const GfxRenderer& renderer, int fontId);
|
std::vector<uint16_t> calculateWordWidths(const GfxRenderer& renderer, int fontId);
|
||||||
|
|
||||||
public:
|
public:
|
||||||
explicit ParsedText(const TextBlock::Style style, const bool extraParagraphSpacing,
|
explicit ParsedText(const bool extraParagraphSpacing, const bool hyphenationEnabled = false,
|
||||||
const bool hyphenationEnabled = false)
|
const BlockStyle& blockStyle = BlockStyle())
|
||||||
: style(style), extraParagraphSpacing(extraParagraphSpacing), hyphenationEnabled(hyphenationEnabled) {}
|
: blockStyle(blockStyle), extraParagraphSpacing(extraParagraphSpacing), hyphenationEnabled(hyphenationEnabled) {}
|
||||||
~ParsedText() = default;
|
~ParsedText() = default;
|
||||||
|
|
||||||
void addWord(std::string word, EpdFontFamily::Style fontStyle);
|
void addWord(std::string word, EpdFontFamily::Style fontStyle, bool underline = false, bool attachToPrevious = false);
|
||||||
void setStyle(const TextBlock::Style style) { this->style = style; }
|
|
||||||
TextBlock::Style getStyle() const { return style; }
|
/// Mark a forced line break after the last word (e.g. for <br> within table cells).
|
||||||
|
/// If no words have been added yet, this is a no-op.
|
||||||
|
void addLineBreak();
|
||||||
|
void setBlockStyle(const BlockStyle& blockStyle) { this->blockStyle = blockStyle; }
|
||||||
|
BlockStyle& getBlockStyle() { return blockStyle; }
|
||||||
size_t size() const { return words.size(); }
|
size_t size() const { return words.size(); }
|
||||||
bool isEmpty() const { return words.empty(); }
|
bool isEmpty() const { return words.empty(); }
|
||||||
void layoutAndExtractLines(const GfxRenderer& renderer, int fontId, uint16_t viewportWidth,
|
void layoutAndExtractLines(const GfxRenderer& renderer, int fontId, uint16_t viewportWidth,
|
||||||
const std::function<void(std::shared_ptr<TextBlock>)>& processLine,
|
const std::function<void(std::shared_ptr<TextBlock>)>& processLine,
|
||||||
bool includeLastLine = true);
|
bool includeLastLine = true);
|
||||||
|
|
||||||
|
/// Returns the "natural" width of the content if it were laid out on a single line
|
||||||
|
/// (sum of word widths + space widths between non-continuation words).
|
||||||
|
/// Used by table layout to determine column widths before line-breaking.
|
||||||
|
uint16_t getNaturalWidth(const GfxRenderer& renderer, int fontId) const;
|
||||||
};
|
};
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
#include "Section.h"
|
#include "Section.h"
|
||||||
|
|
||||||
#include <SDCardManager.h>
|
#include <HalStorage.h>
|
||||||
|
#include <Logging.h>
|
||||||
#include <Serialization.h>
|
#include <Serialization.h>
|
||||||
|
|
||||||
#include "Page.h"
|
#include "Page.h"
|
||||||
@@ -8,24 +9,24 @@
|
|||||||
#include "parsers/ChapterHtmlSlimParser.h"
|
#include "parsers/ChapterHtmlSlimParser.h"
|
||||||
|
|
||||||
namespace {
|
namespace {
|
||||||
constexpr uint8_t SECTION_FILE_VERSION = 10;
|
constexpr uint8_t SECTION_FILE_VERSION = 13;
|
||||||
constexpr uint32_t HEADER_SIZE = sizeof(uint8_t) + sizeof(int) + sizeof(float) + sizeof(bool) + sizeof(uint8_t) +
|
constexpr uint32_t HEADER_SIZE = sizeof(uint8_t) + sizeof(int) + sizeof(float) + sizeof(bool) + sizeof(uint8_t) +
|
||||||
sizeof(uint16_t) + sizeof(uint16_t) + sizeof(uint16_t) + sizeof(bool) +
|
sizeof(uint16_t) + sizeof(uint16_t) + sizeof(uint16_t) + sizeof(bool) + sizeof(bool) +
|
||||||
sizeof(uint32_t);
|
sizeof(uint32_t);
|
||||||
} // namespace
|
} // namespace
|
||||||
|
|
||||||
uint32_t Section::onPageComplete(std::unique_ptr<Page> page) {
|
uint32_t Section::onPageComplete(std::unique_ptr<Page> page) {
|
||||||
if (!file) {
|
if (!file) {
|
||||||
Serial.printf("[%lu] [SCT] File not open for writing page %d\n", millis(), pageCount);
|
LOG_ERR("SCT", "File not open for writing page %d", pageCount);
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
const uint32_t position = file.position();
|
const uint32_t position = file.position();
|
||||||
if (!page->serialize(file)) {
|
if (!page->serialize(file)) {
|
||||||
Serial.printf("[%lu] [SCT] Failed to serialize page %d\n", millis(), pageCount);
|
LOG_ERR("SCT", "Failed to serialize page %d", pageCount);
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
Serial.printf("[%lu] [SCT] Page %d processed\n", millis(), pageCount);
|
LOG_DBG("SCT", "Page %d processed", pageCount);
|
||||||
|
|
||||||
pageCount++;
|
pageCount++;
|
||||||
return position;
|
return position;
|
||||||
@@ -33,15 +34,16 @@ uint32_t Section::onPageComplete(std::unique_ptr<Page> page) {
|
|||||||
|
|
||||||
void Section::writeSectionFileHeader(const int fontId, const float lineCompression, const bool extraParagraphSpacing,
|
void Section::writeSectionFileHeader(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 uint16_t viewportHeight, const bool hyphenationEnabled,
|
||||||
|
const bool embeddedStyle) {
|
||||||
if (!file) {
|
if (!file) {
|
||||||
Serial.printf("[%lu] [SCT] File not open for writing header\n", millis());
|
LOG_DBG("SCT", "File not open for writing header");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
static_assert(HEADER_SIZE == sizeof(SECTION_FILE_VERSION) + sizeof(fontId) + sizeof(lineCompression) +
|
static_assert(HEADER_SIZE == sizeof(SECTION_FILE_VERSION) + sizeof(fontId) + sizeof(lineCompression) +
|
||||||
sizeof(extraParagraphSpacing) + sizeof(paragraphAlignment) + sizeof(viewportWidth) +
|
sizeof(extraParagraphSpacing) + sizeof(paragraphAlignment) + sizeof(viewportWidth) +
|
||||||
sizeof(viewportHeight) + sizeof(pageCount) + sizeof(hyphenationEnabled) +
|
sizeof(viewportHeight) + sizeof(pageCount) + sizeof(hyphenationEnabled) +
|
||||||
sizeof(uint32_t),
|
sizeof(embeddedStyle) + sizeof(uint32_t),
|
||||||
"Header size mismatch");
|
"Header size mismatch");
|
||||||
serialization::writePod(file, SECTION_FILE_VERSION);
|
serialization::writePod(file, SECTION_FILE_VERSION);
|
||||||
serialization::writePod(file, fontId);
|
serialization::writePod(file, fontId);
|
||||||
@@ -51,14 +53,15 @@ void Section::writeSectionFileHeader(const int fontId, const float lineCompressi
|
|||||||
serialization::writePod(file, viewportWidth);
|
serialization::writePod(file, viewportWidth);
|
||||||
serialization::writePod(file, viewportHeight);
|
serialization::writePod(file, viewportHeight);
|
||||||
serialization::writePod(file, hyphenationEnabled);
|
serialization::writePod(file, hyphenationEnabled);
|
||||||
|
serialization::writePod(file, embeddedStyle);
|
||||||
serialization::writePod(file, pageCount); // Placeholder for page count (will be initially 0 when written)
|
serialization::writePod(file, pageCount); // Placeholder for page count (will be initially 0 when written)
|
||||||
serialization::writePod(file, static_cast<uint32_t>(0)); // Placeholder for LUT offset
|
serialization::writePod(file, static_cast<uint32_t>(0)); // Placeholder for LUT offset
|
||||||
}
|
}
|
||||||
|
|
||||||
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 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;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -68,7 +71,7 @@ bool Section::loadSectionFile(const int fontId, const float lineCompression, con
|
|||||||
serialization::readPod(file, version);
|
serialization::readPod(file, version);
|
||||||
if (version != SECTION_FILE_VERSION) {
|
if (version != SECTION_FILE_VERSION) {
|
||||||
file.close();
|
file.close();
|
||||||
Serial.printf("[%lu] [SCT] Deserialization failed: Unknown version %u\n", millis(), version);
|
LOG_ERR("SCT", "Deserialization failed: Unknown version %u", version);
|
||||||
clearCache();
|
clearCache();
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@@ -79,6 +82,7 @@ bool Section::loadSectionFile(const int fontId, const float lineCompression, con
|
|||||||
bool fileExtraParagraphSpacing;
|
bool fileExtraParagraphSpacing;
|
||||||
uint8_t fileParagraphAlignment;
|
uint8_t fileParagraphAlignment;
|
||||||
bool fileHyphenationEnabled;
|
bool fileHyphenationEnabled;
|
||||||
|
bool fileEmbeddedStyle;
|
||||||
serialization::readPod(file, fileFontId);
|
serialization::readPod(file, fileFontId);
|
||||||
serialization::readPod(file, fileLineCompression);
|
serialization::readPod(file, fileLineCompression);
|
||||||
serialization::readPod(file, fileExtraParagraphSpacing);
|
serialization::readPod(file, fileExtraParagraphSpacing);
|
||||||
@@ -86,13 +90,14 @@ bool Section::loadSectionFile(const int fontId, const float lineCompression, con
|
|||||||
serialization::readPod(file, fileViewportWidth);
|
serialization::readPod(file, fileViewportWidth);
|
||||||
serialization::readPod(file, fileViewportHeight);
|
serialization::readPod(file, fileViewportHeight);
|
||||||
serialization::readPod(file, fileHyphenationEnabled);
|
serialization::readPod(file, fileHyphenationEnabled);
|
||||||
|
serialization::readPod(file, fileEmbeddedStyle);
|
||||||
|
|
||||||
if (fontId != fileFontId || lineCompression != fileLineCompression ||
|
if (fontId != fileFontId || lineCompression != fileLineCompression ||
|
||||||
extraParagraphSpacing != fileExtraParagraphSpacing || paragraphAlignment != fileParagraphAlignment ||
|
extraParagraphSpacing != fileExtraParagraphSpacing || paragraphAlignment != fileParagraphAlignment ||
|
||||||
viewportWidth != fileViewportWidth || viewportHeight != fileViewportHeight ||
|
viewportWidth != fileViewportWidth || viewportHeight != fileViewportHeight ||
|
||||||
hyphenationEnabled != fileHyphenationEnabled) {
|
hyphenationEnabled != fileHyphenationEnabled || embeddedStyle != fileEmbeddedStyle) {
|
||||||
file.close();
|
file.close();
|
||||||
Serial.printf("[%lu] [SCT] Deserialization failed: Parameters do not match\n", millis());
|
LOG_ERR("SCT", "Deserialization failed: Parameters do not match");
|
||||||
clearCache();
|
clearCache();
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@@ -100,39 +105,37 @@ bool Section::loadSectionFile(const int fontId, const float lineCompression, con
|
|||||||
|
|
||||||
serialization::readPod(file, pageCount);
|
serialization::readPod(file, pageCount);
|
||||||
file.close();
|
file.close();
|
||||||
Serial.printf("[%lu] [SCT] Deserialization succeeded: %d pages\n", millis(), pageCount);
|
LOG_DBG("SCT", "Deserialization succeeded: %d pages", pageCount);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 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());
|
LOG_DBG("SCT", "Cache does not exist, no action needed");
|
||||||
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());
|
LOG_ERR("SCT", "Failed to clear cache");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
Serial.printf("[%lu] [SCT] Cache cleared successfully\n", millis());
|
LOG_DBG("SCT", "Cache cleared successfully");
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
bool Section::createSectionFile(const int fontId, const float lineCompression, const bool extraParagraphSpacing,
|
bool Section::createSectionFile(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 uint16_t viewportHeight, const bool hyphenationEnabled, const bool embeddedStyle,
|
||||||
const std::function<void()>& progressSetupFn,
|
const std::function<void()>& popupFn) {
|
||||||
const std::function<void(int)>& progressFn) {
|
|
||||||
constexpr uint32_t MIN_SIZE_FOR_PROGRESS = 50 * 1024; // 50KB
|
|
||||||
const auto localPath = epub->getSpineItem(spineIndex).href;
|
const auto localPath = epub->getSpineItem(spineIndex).href;
|
||||||
const auto tmpHtmlPath = epub->getCachePath() + "/.tmp_" + std::to_string(spineIndex) + ".html";
|
const auto tmpHtmlPath = epub->getCachePath() + "/.tmp_" + std::to_string(spineIndex) + ".html";
|
||||||
|
|
||||||
// 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
|
||||||
@@ -140,17 +143,17 @@ bool Section::createSectionFile(const int fontId, const float lineCompression, c
|
|||||||
uint32_t fileSize = 0;
|
uint32_t fileSize = 0;
|
||||||
for (int attempt = 0; attempt < 3 && !success; attempt++) {
|
for (int attempt = 0; attempt < 3 && !success; attempt++) {
|
||||||
if (attempt > 0) {
|
if (attempt > 0) {
|
||||||
Serial.printf("[%lu] [SCT] Retrying stream (attempt %d)...\n", millis(), attempt + 1);
|
LOG_DBG("SCT", "Retrying stream (attempt %d)...", attempt + 1);
|
||||||
delay(50); // Brief delay before retry
|
delay(50); // Brief delay before retry
|
||||||
}
|
}
|
||||||
|
|
||||||
// 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);
|
||||||
@@ -158,44 +161,56 @@ 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());
|
LOG_DBG("SCT", "Removed incomplete temp file after failed attempt");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!success) {
|
if (!success) {
|
||||||
Serial.printf("[%lu] [SCT] Failed to stream item contents to temp file after retries\n", millis());
|
LOG_ERR("SCT", "Failed to stream item contents to temp file after retries");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
Serial.printf("[%lu] [SCT] Streamed temp HTML to %s (%d bytes)\n", millis(), tmpHtmlPath.c_str(), fileSize);
|
LOG_DBG("SCT", "Streamed temp HTML to %s (%d bytes)", tmpHtmlPath.c_str(), fileSize);
|
||||||
|
|
||||||
// Only show progress bar for larger chapters where rendering overhead is worth it
|
if (!Storage.openFileForWrite("SCT", filePath, file)) {
|
||||||
if (progressSetupFn && fileSize >= MIN_SIZE_FOR_PROGRESS) {
|
|
||||||
progressSetupFn();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!SdMan.openFileForWrite("SCT", filePath, file)) {
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
writeSectionFileHeader(fontId, lineCompression, extraParagraphSpacing, paragraphAlignment, viewportWidth,
|
writeSectionFileHeader(fontId, lineCompression, extraParagraphSpacing, paragraphAlignment, viewportWidth,
|
||||||
viewportHeight, hyphenationEnabled);
|
viewportHeight, hyphenationEnabled, embeddedStyle);
|
||||||
std::vector<uint32_t> lut = {};
|
std::vector<uint32_t> lut = {};
|
||||||
|
|
||||||
|
// Derive the content base directory and image cache path prefix for the parser
|
||||||
|
size_t lastSlash = localPath.find_last_of('/');
|
||||||
|
std::string contentBase = (lastSlash != std::string::npos) ? localPath.substr(0, lastSlash + 1) : "";
|
||||||
|
std::string imageBasePath = epub->getCachePath() + "/img_" + std::to_string(spineIndex) + "_";
|
||||||
|
|
||||||
|
CssParser* cssParser = nullptr;
|
||||||
|
if (embeddedStyle) {
|
||||||
|
cssParser = epub->getCssParser();
|
||||||
|
if (cssParser) {
|
||||||
|
if (!cssParser->loadFromCache()) {
|
||||||
|
LOG_ERR("SCT", "Failed to load CSS from cache");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
ChapterHtmlSlimParser visitor(
|
ChapterHtmlSlimParser visitor(
|
||||||
tmpHtmlPath, renderer, fontId, lineCompression, extraParagraphSpacing, paragraphAlignment, viewportWidth,
|
epub, tmpHtmlPath, renderer, fontId, lineCompression, extraParagraphSpacing, paragraphAlignment, viewportWidth,
|
||||||
viewportHeight, hyphenationEnabled,
|
viewportHeight, hyphenationEnabled,
|
||||||
[this, &lut](std::unique_ptr<Page> page) { lut.emplace_back(this->onPageComplete(std::move(page))); },
|
[this, &lut](std::unique_ptr<Page> page) { lut.emplace_back(this->onPageComplete(std::move(page))); },
|
||||||
progressFn);
|
embeddedStyle, contentBase, imageBasePath, popupFn, cssParser);
|
||||||
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());
|
LOG_ERR("SCT", "Failed to parse XML and build pages");
|
||||||
file.close();
|
file.close();
|
||||||
SdMan.remove(filePath.c_str());
|
Storage.remove(filePath.c_str());
|
||||||
|
if (cssParser) {
|
||||||
|
cssParser->clear();
|
||||||
|
}
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -211,9 +226,9 @@ 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());
|
LOG_ERR("SCT", "Failed to write LUT due to invalid page positions");
|
||||||
file.close();
|
file.close();
|
||||||
SdMan.remove(filePath.c_str());
|
Storage.remove(filePath.c_str());
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -222,11 +237,14 @@ bool Section::createSectionFile(const int fontId, const float lineCompression, c
|
|||||||
serialization::writePod(file, pageCount);
|
serialization::writePod(file, pageCount);
|
||||||
serialization::writePod(file, lutOffset);
|
serialization::writePod(file, lutOffset);
|
||||||
file.close();
|
file.close();
|
||||||
|
if (cssParser) {
|
||||||
|
cssParser->clear();
|
||||||
|
}
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
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;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -15,7 +15,8 @@ class Section {
|
|||||||
FsFile file;
|
FsFile file;
|
||||||
|
|
||||||
void writeSectionFileHeader(int fontId, float lineCompression, bool extraParagraphSpacing, uint8_t paragraphAlignment,
|
void writeSectionFileHeader(int fontId, float lineCompression, bool extraParagraphSpacing, uint8_t paragraphAlignment,
|
||||||
uint16_t viewportWidth, uint16_t viewportHeight, bool hyphenationEnabled);
|
uint16_t viewportWidth, uint16_t viewportHeight, bool hyphenationEnabled,
|
||||||
|
bool embeddedStyle);
|
||||||
uint32_t onPageComplete(std::unique_ptr<Page> page);
|
uint32_t onPageComplete(std::unique_ptr<Page> page);
|
||||||
|
|
||||||
public:
|
public:
|
||||||
@@ -29,11 +30,10 @@ class Section {
|
|||||||
filePath(epub->getCachePath() + "/sections/" + std::to_string(spineIndex) + ".bin") {}
|
filePath(epub->getCachePath() + "/sections/" + std::to_string(spineIndex) + ".bin") {}
|
||||||
~Section() = default;
|
~Section() = default;
|
||||||
bool loadSectionFile(int fontId, float lineCompression, bool extraParagraphSpacing, uint8_t paragraphAlignment,
|
bool loadSectionFile(int fontId, float lineCompression, bool extraParagraphSpacing, uint8_t paragraphAlignment,
|
||||||
uint16_t viewportWidth, uint16_t viewportHeight, bool hyphenationEnabled);
|
uint16_t viewportWidth, uint16_t viewportHeight, bool hyphenationEnabled, bool embeddedStyle);
|
||||||
bool clearCache() const;
|
bool clearCache() const;
|
||||||
bool createSectionFile(int fontId, float lineCompression, bool extraParagraphSpacing, uint8_t paragraphAlignment,
|
bool createSectionFile(int fontId, float lineCompression, bool extraParagraphSpacing, uint8_t paragraphAlignment,
|
||||||
uint16_t viewportWidth, uint16_t viewportHeight, bool hyphenationEnabled,
|
uint16_t viewportWidth, uint16_t viewportHeight, bool hyphenationEnabled, bool embeddedStyle,
|
||||||
const std::function<void()>& progressSetupFn = nullptr,
|
const std::function<void()>& popupFn = nullptr);
|
||||||
const std::function<void(int)>& progressFn = nullptr);
|
|
||||||
std::unique_ptr<Page> loadPageFromSectionFile();
|
std::unique_ptr<Page> loadPageFromSectionFile();
|
||||||
};
|
};
|
||||||
|
|||||||
29
lib/Epub/Epub/TableData.h
Normal file
29
lib/Epub/Epub/TableData.h
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <memory>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
#include "ParsedText.h"
|
||||||
|
#include "css/CssStyle.h"
|
||||||
|
|
||||||
|
/// A single cell in a table row.
|
||||||
|
struct TableCell {
|
||||||
|
std::unique_ptr<ParsedText> content;
|
||||||
|
bool isHeader = false; // true for <th>, false for <td>
|
||||||
|
int colspan = 1; // number of logical columns this cell spans
|
||||||
|
CssLength widthHint; // width hint from HTML attribute or CSS (if hasWidthHint)
|
||||||
|
bool hasWidthHint = false;
|
||||||
|
};
|
||||||
|
|
||||||
|
/// A single row in a table.
|
||||||
|
struct TableRow {
|
||||||
|
std::vector<TableCell> cells;
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Buffered table data collected during SAX parsing.
|
||||||
|
/// The entire table must be buffered before layout because column widths
|
||||||
|
/// depend on content across all rows.
|
||||||
|
struct TableData {
|
||||||
|
std::vector<TableRow> rows;
|
||||||
|
std::vector<CssLength> colWidthHints; // width hints from <col> tags, indexed by logical column
|
||||||
|
};
|
||||||
@@ -8,7 +8,7 @@ typedef enum { TEXT_BLOCK, IMAGE_BLOCK } BlockType;
|
|||||||
class Block {
|
class Block {
|
||||||
public:
|
public:
|
||||||
virtual ~Block() = default;
|
virtual ~Block() = default;
|
||||||
virtual void layout(GfxRenderer& renderer) = 0;
|
|
||||||
virtual BlockType getType() = 0;
|
virtual BlockType getType() = 0;
|
||||||
virtual bool isEmpty() = 0;
|
virtual bool isEmpty() = 0;
|
||||||
virtual void finish() {}
|
virtual void finish() {}
|
||||||
|
|||||||
97
lib/Epub/Epub/blocks/BlockStyle.h
Normal file
97
lib/Epub/Epub/blocks/BlockStyle.h
Normal file
@@ -0,0 +1,97 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <cstdint>
|
||||||
|
|
||||||
|
#include "Epub/css/CssStyle.h"
|
||||||
|
|
||||||
|
/**
|
||||||
|
* BlockStyle - Block-level styling properties
|
||||||
|
*/
|
||||||
|
struct BlockStyle {
|
||||||
|
CssTextAlign alignment = CssTextAlign::Justify;
|
||||||
|
|
||||||
|
// Spacing (in pixels)
|
||||||
|
int16_t marginTop = 0;
|
||||||
|
int16_t marginBottom = 0;
|
||||||
|
int16_t marginLeft = 0;
|
||||||
|
int16_t marginRight = 0;
|
||||||
|
int16_t paddingTop = 0; // treated same as margin for rendering
|
||||||
|
int16_t paddingBottom = 0; // treated same as margin for rendering
|
||||||
|
int16_t paddingLeft = 0; // treated same as margin for rendering
|
||||||
|
int16_t paddingRight = 0; // treated same as margin for rendering
|
||||||
|
int16_t textIndent = 0;
|
||||||
|
bool textIndentDefined = false; // true if text-indent was explicitly set in CSS
|
||||||
|
bool textAlignDefined = false; // true if text-align was explicitly set in CSS
|
||||||
|
|
||||||
|
// Combined horizontal insets (margin + padding)
|
||||||
|
[[nodiscard]] int16_t leftInset() const { return marginLeft + paddingLeft; }
|
||||||
|
[[nodiscard]] int16_t rightInset() const { return marginRight + paddingRight; }
|
||||||
|
[[nodiscard]] int16_t totalHorizontalInset() const { return leftInset() + rightInset(); }
|
||||||
|
|
||||||
|
// Combine with another block style. Useful for parent -> child styles, where the child style should be
|
||||||
|
// applied on top of the parent's style to get the combined style.
|
||||||
|
BlockStyle getCombinedBlockStyle(const BlockStyle& child) const {
|
||||||
|
BlockStyle combinedBlockStyle;
|
||||||
|
|
||||||
|
combinedBlockStyle.marginTop = static_cast<int16_t>(child.marginTop + marginTop);
|
||||||
|
combinedBlockStyle.marginBottom = static_cast<int16_t>(child.marginBottom + marginBottom);
|
||||||
|
combinedBlockStyle.marginLeft = static_cast<int16_t>(child.marginLeft + marginLeft);
|
||||||
|
combinedBlockStyle.marginRight = static_cast<int16_t>(child.marginRight + marginRight);
|
||||||
|
|
||||||
|
combinedBlockStyle.paddingTop = static_cast<int16_t>(child.paddingTop + paddingTop);
|
||||||
|
combinedBlockStyle.paddingBottom = static_cast<int16_t>(child.paddingBottom + paddingBottom);
|
||||||
|
combinedBlockStyle.paddingLeft = static_cast<int16_t>(child.paddingLeft + paddingLeft);
|
||||||
|
combinedBlockStyle.paddingRight = static_cast<int16_t>(child.paddingRight + paddingRight);
|
||||||
|
// Text indent: use child's if defined
|
||||||
|
if (child.textIndentDefined) {
|
||||||
|
combinedBlockStyle.textIndent = child.textIndent;
|
||||||
|
combinedBlockStyle.textIndentDefined = true;
|
||||||
|
} else {
|
||||||
|
combinedBlockStyle.textIndent = textIndent;
|
||||||
|
combinedBlockStyle.textIndentDefined = textIndentDefined;
|
||||||
|
}
|
||||||
|
// Text align: use child's if defined
|
||||||
|
if (child.textAlignDefined) {
|
||||||
|
combinedBlockStyle.alignment = child.alignment;
|
||||||
|
combinedBlockStyle.textAlignDefined = true;
|
||||||
|
} else {
|
||||||
|
combinedBlockStyle.alignment = alignment;
|
||||||
|
combinedBlockStyle.textAlignDefined = textAlignDefined;
|
||||||
|
}
|
||||||
|
return combinedBlockStyle;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create a BlockStyle from CSS style properties, resolving CssLength values to pixels
|
||||||
|
// emSize is the current font line height, used for em/rem unit conversion
|
||||||
|
// paragraphAlignment is the user's paragraphAlignment setting preference
|
||||||
|
static BlockStyle fromCssStyle(const CssStyle& cssStyle, const float emSize, const CssTextAlign paragraphAlignment,
|
||||||
|
const uint16_t viewportWidth = 0) {
|
||||||
|
BlockStyle blockStyle;
|
||||||
|
const float vw = viewportWidth;
|
||||||
|
// Resolve all CssLength values to pixels using the current font's em size and viewport width
|
||||||
|
blockStyle.marginTop = cssStyle.marginTop.toPixelsInt16(emSize, vw);
|
||||||
|
blockStyle.marginBottom = cssStyle.marginBottom.toPixelsInt16(emSize, vw);
|
||||||
|
blockStyle.marginLeft = cssStyle.marginLeft.toPixelsInt16(emSize, vw);
|
||||||
|
blockStyle.marginRight = cssStyle.marginRight.toPixelsInt16(emSize, vw);
|
||||||
|
|
||||||
|
blockStyle.paddingTop = cssStyle.paddingTop.toPixelsInt16(emSize, vw);
|
||||||
|
blockStyle.paddingBottom = cssStyle.paddingBottom.toPixelsInt16(emSize, vw);
|
||||||
|
blockStyle.paddingLeft = cssStyle.paddingLeft.toPixelsInt16(emSize, vw);
|
||||||
|
blockStyle.paddingRight = cssStyle.paddingRight.toPixelsInt16(emSize, vw);
|
||||||
|
|
||||||
|
// For textIndent: if it's a percentage we can't resolve (no viewport width),
|
||||||
|
// leave textIndentDefined=false so the EmSpace fallback in applyParagraphIndent() is used
|
||||||
|
if (cssStyle.hasTextIndent() && cssStyle.textIndent.isResolvable(vw)) {
|
||||||
|
blockStyle.textIndent = cssStyle.textIndent.toPixelsInt16(emSize, vw);
|
||||||
|
blockStyle.textIndentDefined = true;
|
||||||
|
}
|
||||||
|
blockStyle.textAlignDefined = cssStyle.hasTextAlign();
|
||||||
|
// User setting overrides CSS, unless "Book's Style" alignment setting is selected
|
||||||
|
if (paragraphAlignment == CssTextAlign::None) {
|
||||||
|
blockStyle.alignment = blockStyle.textAlignDefined ? cssStyle.textAlign : CssTextAlign::Justify;
|
||||||
|
} else {
|
||||||
|
blockStyle.alignment = paragraphAlignment;
|
||||||
|
}
|
||||||
|
return blockStyle;
|
||||||
|
}
|
||||||
|
};
|
||||||
175
lib/Epub/Epub/blocks/ImageBlock.cpp
Normal file
175
lib/Epub/Epub/blocks/ImageBlock.cpp
Normal file
@@ -0,0 +1,175 @@
|
|||||||
|
#include "ImageBlock.h"
|
||||||
|
|
||||||
|
#include <FsHelpers.h>
|
||||||
|
#include <GfxRenderer.h>
|
||||||
|
#include <HardwareSerial.h>
|
||||||
|
#include <SDCardManager.h>
|
||||||
|
#include <Serialization.h>
|
||||||
|
|
||||||
|
#include "../converters/DitherUtils.h"
|
||||||
|
#include "../converters/ImageDecoderFactory.h"
|
||||||
|
|
||||||
|
// Cache file format:
|
||||||
|
// - uint16_t width
|
||||||
|
// - uint16_t height
|
||||||
|
// - uint8_t pixels[...] - 2 bits per pixel, packed (4 pixels per byte), row-major order
|
||||||
|
|
||||||
|
ImageBlock::ImageBlock(const std::string& imagePath, int16_t width, int16_t height)
|
||||||
|
: imagePath(imagePath), width(width), height(height) {}
|
||||||
|
|
||||||
|
bool ImageBlock::imageExists() const { return Storage.exists(imagePath.c_str()); }
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
|
||||||
|
std::string getCachePath(const std::string& imagePath) {
|
||||||
|
// Replace extension with .pxc (pixel cache)
|
||||||
|
size_t dotPos = imagePath.rfind('.');
|
||||||
|
if (dotPos != std::string::npos) {
|
||||||
|
return imagePath.substr(0, dotPos) + ".pxc";
|
||||||
|
}
|
||||||
|
return imagePath + ".pxc";
|
||||||
|
}
|
||||||
|
|
||||||
|
bool renderFromCache(GfxRenderer& renderer, const std::string& cachePath, int x, int y, int expectedWidth,
|
||||||
|
int expectedHeight) {
|
||||||
|
FsFile cacheFile;
|
||||||
|
if (!Storage.openFileForRead("IMG", cachePath, cacheFile)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
uint16_t cachedWidth, cachedHeight;
|
||||||
|
if (cacheFile.read(&cachedWidth, 2) != 2 || cacheFile.read(&cachedHeight, 2) != 2) {
|
||||||
|
cacheFile.close();
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verify dimensions are close (allow 1 pixel tolerance for rounding differences)
|
||||||
|
int widthDiff = abs(cachedWidth - expectedWidth);
|
||||||
|
int heightDiff = abs(cachedHeight - expectedHeight);
|
||||||
|
if (widthDiff > 1 || heightDiff > 1) {
|
||||||
|
Serial.printf("[%lu] [IMG] Cache dimension mismatch: %dx%d vs %dx%d\n", millis(), cachedWidth, cachedHeight,
|
||||||
|
expectedWidth, expectedHeight);
|
||||||
|
cacheFile.close();
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Use cached dimensions for rendering (they're the actual decoded size)
|
||||||
|
expectedWidth = cachedWidth;
|
||||||
|
expectedHeight = cachedHeight;
|
||||||
|
|
||||||
|
Serial.printf("[%lu] [IMG] Loading from cache: %s (%dx%d)\n", millis(), cachePath.c_str(), cachedWidth, cachedHeight);
|
||||||
|
|
||||||
|
// Read and render row by row to minimize memory usage
|
||||||
|
const int bytesPerRow = (cachedWidth + 3) / 4; // 2 bits per pixel, 4 pixels per byte
|
||||||
|
uint8_t* rowBuffer = (uint8_t*)malloc(bytesPerRow);
|
||||||
|
if (!rowBuffer) {
|
||||||
|
Serial.printf("[%lu] [IMG] Failed to allocate row buffer\n", millis());
|
||||||
|
cacheFile.close();
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (int row = 0; row < cachedHeight; row++) {
|
||||||
|
if (cacheFile.read(rowBuffer, bytesPerRow) != bytesPerRow) {
|
||||||
|
Serial.printf("[%lu] [IMG] Cache read error at row %d\n", millis(), row);
|
||||||
|
free(rowBuffer);
|
||||||
|
cacheFile.close();
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
int destY = y + row;
|
||||||
|
for (int col = 0; col < cachedWidth; col++) {
|
||||||
|
int byteIdx = col / 4;
|
||||||
|
int bitShift = 6 - (col % 4) * 2; // MSB first within byte
|
||||||
|
uint8_t pixelValue = (rowBuffer[byteIdx] >> bitShift) & 0x03;
|
||||||
|
|
||||||
|
drawPixelWithRenderMode(renderer, x + col, destY, pixelValue);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
free(rowBuffer);
|
||||||
|
cacheFile.close();
|
||||||
|
Serial.printf("[%lu] [IMG] Cache render complete\n", millis());
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
void ImageBlock::render(GfxRenderer& renderer, const int x, const int y) {
|
||||||
|
Serial.printf("[%lu] [IMG] Rendering image at %d,%d: %s (%dx%d)\n", millis(), x, y, imagePath.c_str(), width, height);
|
||||||
|
|
||||||
|
const int screenWidth = renderer.getScreenWidth();
|
||||||
|
const int screenHeight = renderer.getScreenHeight();
|
||||||
|
|
||||||
|
// Bounds check render position using logical screen dimensions
|
||||||
|
if (x < 0 || y < 0 || x + width > screenWidth || y + height > screenHeight) {
|
||||||
|
Serial.printf("[%lu] [IMG] Invalid render position: (%d,%d) size (%dx%d) screen (%dx%d)\n", millis(), x, y, width,
|
||||||
|
height, screenWidth, screenHeight);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Try to render from cache first
|
||||||
|
std::string cachePath = getCachePath(imagePath);
|
||||||
|
if (renderFromCache(renderer, cachePath, x, y, width, height)) {
|
||||||
|
return; // Successfully rendered from cache
|
||||||
|
}
|
||||||
|
|
||||||
|
// No cache - need to decode the image
|
||||||
|
// Check if image file exists
|
||||||
|
FsFile file;
|
||||||
|
if (!Storage.openFileForRead("IMG", imagePath, file)) {
|
||||||
|
Serial.printf("[%lu] [IMG] Image file not found: %s\n", millis(), imagePath.c_str());
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
size_t fileSize = file.size();
|
||||||
|
file.close();
|
||||||
|
|
||||||
|
if (fileSize == 0) {
|
||||||
|
Serial.printf("[%lu] [IMG] Image file is empty: %s\n", millis(), imagePath.c_str());
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
Serial.printf("[%lu] [IMG] Decoding and caching: %s\n", millis(), imagePath.c_str());
|
||||||
|
|
||||||
|
RenderConfig config;
|
||||||
|
config.x = x;
|
||||||
|
config.y = y;
|
||||||
|
config.maxWidth = width;
|
||||||
|
config.maxHeight = height;
|
||||||
|
config.useGrayscale = true;
|
||||||
|
config.useDithering = true;
|
||||||
|
config.performanceMode = false;
|
||||||
|
config.useExactDimensions = true; // Use pre-calculated dimensions to avoid rounding mismatches
|
||||||
|
config.cachePath = cachePath; // Enable caching during decode
|
||||||
|
|
||||||
|
ImageToFramebufferDecoder* decoder = ImageDecoderFactory::getDecoder(imagePath);
|
||||||
|
if (!decoder) {
|
||||||
|
Serial.printf("[%lu] [IMG] No decoder found for image: %s\n", millis(), imagePath.c_str());
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
Serial.printf("[%lu] [IMG] Using %s decoder\n", millis(), decoder->getFormatName());
|
||||||
|
|
||||||
|
bool success = decoder->decodeToFramebuffer(imagePath, renderer, config);
|
||||||
|
if (!success) {
|
||||||
|
Serial.printf("[%lu] [IMG] Failed to decode image: %s\n", millis(), imagePath.c_str());
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
Serial.printf("[%lu] [IMG] Decode successful\n", millis());
|
||||||
|
}
|
||||||
|
|
||||||
|
bool ImageBlock::serialize(FsFile& file) {
|
||||||
|
serialization::writeString(file, imagePath);
|
||||||
|
serialization::writePod(file, width);
|
||||||
|
serialization::writePod(file, height);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::unique_ptr<ImageBlock> ImageBlock::deserialize(FsFile& file) {
|
||||||
|
std::string path;
|
||||||
|
serialization::readString(file, path);
|
||||||
|
int16_t w, h;
|
||||||
|
serialization::readPod(file, w);
|
||||||
|
serialization::readPod(file, h);
|
||||||
|
return std::unique_ptr<ImageBlock>(new ImageBlock(path, w, h));
|
||||||
|
}
|
||||||
31
lib/Epub/Epub/blocks/ImageBlock.h
Normal file
31
lib/Epub/Epub/blocks/ImageBlock.h
Normal file
@@ -0,0 +1,31 @@
|
|||||||
|
#pragma once
|
||||||
|
#include <SdFat.h>
|
||||||
|
|
||||||
|
#include <memory>
|
||||||
|
#include <string>
|
||||||
|
|
||||||
|
#include "Block.h"
|
||||||
|
|
||||||
|
class ImageBlock final : public Block {
|
||||||
|
public:
|
||||||
|
ImageBlock(const std::string& imagePath, int16_t width, int16_t height);
|
||||||
|
~ImageBlock() override = default;
|
||||||
|
|
||||||
|
const std::string& getImagePath() const { return imagePath; }
|
||||||
|
int16_t getWidth() const { return width; }
|
||||||
|
int16_t getHeight() const { return height; }
|
||||||
|
|
||||||
|
bool imageExists() const;
|
||||||
|
|
||||||
|
BlockType getType() override { return IMAGE_BLOCK; }
|
||||||
|
bool isEmpty() override { return false; }
|
||||||
|
|
||||||
|
void render(GfxRenderer& renderer, const int x, const int y);
|
||||||
|
bool serialize(FsFile& file);
|
||||||
|
static std::unique_ptr<ImageBlock> deserialize(FsFile& file);
|
||||||
|
|
||||||
|
private:
|
||||||
|
std::string imagePath;
|
||||||
|
int16_t width;
|
||||||
|
int16_t height;
|
||||||
|
};
|
||||||
@@ -1,33 +1,50 @@
|
|||||||
#include "TextBlock.h"
|
#include "TextBlock.h"
|
||||||
|
|
||||||
#include <GfxRenderer.h>
|
#include <GfxRenderer.h>
|
||||||
|
#include <Logging.h>
|
||||||
#include <Serialization.h>
|
#include <Serialization.h>
|
||||||
|
|
||||||
void TextBlock::render(const GfxRenderer& renderer, const int fontId, const int x, const int y) const {
|
void TextBlock::render(const GfxRenderer& renderer, const int fontId, const int x, const int y) const {
|
||||||
// Validate iterator bounds before rendering
|
// Validate iterator bounds before rendering
|
||||||
if (words.size() != wordXpos.size() || words.size() != wordStyles.size()) {
|
if (words.size() != wordXpos.size() || words.size() != wordStyles.size()) {
|
||||||
Serial.printf("[%lu] [TXB] Render skipped: size mismatch (words=%u, xpos=%u, styles=%u)\n", millis(),
|
LOG_ERR("TXB", "Render skipped: size mismatch (words=%u, xpos=%u, styles=%u)\n", (uint32_t)words.size(),
|
||||||
(uint32_t)words.size(), (uint32_t)wordXpos.size(), (uint32_t)wordStyles.size());
|
(uint32_t)wordXpos.size(), (uint32_t)wordStyles.size());
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
auto wordIt = words.begin();
|
|
||||||
auto wordStylesIt = wordStyles.begin();
|
|
||||||
auto wordXposIt = wordXpos.begin();
|
|
||||||
|
|
||||||
for (size_t i = 0; i < words.size(); i++) {
|
for (size_t i = 0; i < words.size(); i++) {
|
||||||
renderer.drawText(fontId, *wordXposIt + x, y, wordIt->c_str(), true, *wordStylesIt);
|
const int wordX = wordXpos[i] + x;
|
||||||
|
const EpdFontFamily::Style currentStyle = wordStyles[i];
|
||||||
|
renderer.drawText(fontId, wordX, y, words[i].c_str(), true, currentStyle);
|
||||||
|
|
||||||
std::advance(wordIt, 1);
|
if ((currentStyle & EpdFontFamily::UNDERLINE) != 0) {
|
||||||
std::advance(wordStylesIt, 1);
|
const std::string& w = words[i];
|
||||||
std::advance(wordXposIt, 1);
|
const int fullWordWidth = renderer.getTextWidth(fontId, w.c_str(), currentStyle);
|
||||||
|
// y is the top of the text line; add ascender to reach baseline, then offset 2px below
|
||||||
|
const int underlineY = y + renderer.getFontAscenderSize(fontId) + 2;
|
||||||
|
|
||||||
|
int startX = wordX;
|
||||||
|
int underlineWidth = fullWordWidth;
|
||||||
|
|
||||||
|
// if word starts with em-space ("\xe2\x80\x83"), account for the additional indent before drawing the line
|
||||||
|
if (w.size() >= 3 && static_cast<uint8_t>(w[0]) == 0xE2 && static_cast<uint8_t>(w[1]) == 0x80 &&
|
||||||
|
static_cast<uint8_t>(w[2]) == 0x83) {
|
||||||
|
const char* visiblePtr = w.c_str() + 3;
|
||||||
|
const int prefixWidth = renderer.getTextAdvanceX(fontId, std::string("\xe2\x80\x83").c_str());
|
||||||
|
const int visibleWidth = renderer.getTextWidth(fontId, visiblePtr, currentStyle);
|
||||||
|
startX = wordX + prefixWidth;
|
||||||
|
underlineWidth = visibleWidth;
|
||||||
|
}
|
||||||
|
|
||||||
|
renderer.drawLine(startX, underlineY, startX + underlineWidth, underlineY, true);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
bool TextBlock::serialize(FsFile& file) const {
|
bool TextBlock::serialize(FsFile& file) const {
|
||||||
if (words.size() != wordXpos.size() || words.size() != wordStyles.size()) {
|
if (words.size() != wordXpos.size() || words.size() != wordStyles.size()) {
|
||||||
Serial.printf("[%lu] [TXB] Serialization failed: size mismatch (words=%u, xpos=%u, styles=%u)\n", millis(),
|
LOG_ERR("TXB", "Serialization failed: size mismatch (words=%u, xpos=%u, styles=%u)\n", words.size(),
|
||||||
words.size(), wordXpos.size(), wordStyles.size());
|
wordXpos.size(), wordStyles.size());
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -37,25 +54,36 @@ bool TextBlock::serialize(FsFile& file) const {
|
|||||||
for (auto x : wordXpos) serialization::writePod(file, x);
|
for (auto x : wordXpos) serialization::writePod(file, x);
|
||||||
for (auto s : wordStyles) serialization::writePod(file, s);
|
for (auto s : wordStyles) serialization::writePod(file, s);
|
||||||
|
|
||||||
// Block style
|
// Style (alignment + margins/padding/indent)
|
||||||
serialization::writePod(file, style);
|
serialization::writePod(file, blockStyle.alignment);
|
||||||
|
serialization::writePod(file, blockStyle.textAlignDefined);
|
||||||
|
serialization::writePod(file, blockStyle.marginTop);
|
||||||
|
serialization::writePod(file, blockStyle.marginBottom);
|
||||||
|
serialization::writePod(file, blockStyle.marginLeft);
|
||||||
|
serialization::writePod(file, blockStyle.marginRight);
|
||||||
|
serialization::writePod(file, blockStyle.paddingTop);
|
||||||
|
serialization::writePod(file, blockStyle.paddingBottom);
|
||||||
|
serialization::writePod(file, blockStyle.paddingLeft);
|
||||||
|
serialization::writePod(file, blockStyle.paddingRight);
|
||||||
|
serialization::writePod(file, blockStyle.textIndent);
|
||||||
|
serialization::writePod(file, blockStyle.textIndentDefined);
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
std::unique_ptr<TextBlock> TextBlock::deserialize(FsFile& file) {
|
std::unique_ptr<TextBlock> TextBlock::deserialize(FsFile& file) {
|
||||||
uint16_t wc;
|
uint16_t wc;
|
||||||
std::list<std::string> words;
|
std::vector<std::string> words;
|
||||||
std::list<uint16_t> wordXpos;
|
std::vector<uint16_t> wordXpos;
|
||||||
std::list<EpdFontFamily::Style> wordStyles;
|
std::vector<EpdFontFamily::Style> wordStyles;
|
||||||
Style style;
|
BlockStyle blockStyle;
|
||||||
|
|
||||||
// Word count
|
// Word count
|
||||||
serialization::readPod(file, wc);
|
serialization::readPod(file, wc);
|
||||||
|
|
||||||
// Sanity check: prevent allocation of unreasonably large lists (max 10000 words per block)
|
// Sanity check: prevent allocation of unreasonably large vectors (max 10000 words per block)
|
||||||
if (wc > 10000) {
|
if (wc > 10000) {
|
||||||
Serial.printf("[%lu] [TXB] Deserialization failed: word count %u exceeds maximum\n", millis(), wc);
|
LOG_ERR("TXB", "Deserialization failed: word count %u exceeds maximum", wc);
|
||||||
return nullptr;
|
return nullptr;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -67,8 +95,20 @@ std::unique_ptr<TextBlock> TextBlock::deserialize(FsFile& file) {
|
|||||||
for (auto& x : wordXpos) serialization::readPod(file, x);
|
for (auto& x : wordXpos) serialization::readPod(file, x);
|
||||||
for (auto& s : wordStyles) serialization::readPod(file, s);
|
for (auto& s : wordStyles) serialization::readPod(file, s);
|
||||||
|
|
||||||
// Block style
|
// Style (alignment + margins/padding/indent)
|
||||||
serialization::readPod(file, style);
|
serialization::readPod(file, blockStyle.alignment);
|
||||||
|
serialization::readPod(file, blockStyle.textAlignDefined);
|
||||||
|
serialization::readPod(file, blockStyle.marginTop);
|
||||||
|
serialization::readPod(file, blockStyle.marginBottom);
|
||||||
|
serialization::readPod(file, blockStyle.marginLeft);
|
||||||
|
serialization::readPod(file, blockStyle.marginRight);
|
||||||
|
serialization::readPod(file, blockStyle.paddingTop);
|
||||||
|
serialization::readPod(file, blockStyle.paddingBottom);
|
||||||
|
serialization::readPod(file, blockStyle.paddingLeft);
|
||||||
|
serialization::readPod(file, blockStyle.paddingRight);
|
||||||
|
serialization::readPod(file, blockStyle.textIndent);
|
||||||
|
serialization::readPod(file, blockStyle.textIndentDefined);
|
||||||
|
|
||||||
return std::unique_ptr<TextBlock>(new TextBlock(std::move(words), std::move(wordXpos), std::move(wordStyles), style));
|
return std::unique_ptr<TextBlock>(
|
||||||
|
new TextBlock(std::move(words), std::move(wordXpos), std::move(wordStyles), blockStyle));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,38 +1,36 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
#include <EpdFontFamily.h>
|
#include <EpdFontFamily.h>
|
||||||
#include <SdFat.h>
|
#include <HalStorage.h>
|
||||||
|
|
||||||
#include <list>
|
|
||||||
#include <memory>
|
#include <memory>
|
||||||
#include <string>
|
#include <string>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
#include "Block.h"
|
#include "Block.h"
|
||||||
|
#include "BlockStyle.h"
|
||||||
|
|
||||||
// Represents a line of text on a page
|
// Represents a line of text on a page
|
||||||
class TextBlock final : public Block {
|
class TextBlock final : public Block {
|
||||||
public:
|
|
||||||
enum Style : uint8_t {
|
|
||||||
JUSTIFIED = 0,
|
|
||||||
LEFT_ALIGN = 1,
|
|
||||||
CENTER_ALIGN = 2,
|
|
||||||
RIGHT_ALIGN = 3,
|
|
||||||
};
|
|
||||||
|
|
||||||
private:
|
private:
|
||||||
std::list<std::string> words;
|
std::vector<std::string> words;
|
||||||
std::list<uint16_t> wordXpos;
|
std::vector<uint16_t> wordXpos;
|
||||||
std::list<EpdFontFamily::Style> wordStyles;
|
std::vector<EpdFontFamily::Style> wordStyles;
|
||||||
Style style;
|
BlockStyle blockStyle;
|
||||||
|
|
||||||
public:
|
public:
|
||||||
explicit TextBlock(std::list<std::string> words, std::list<uint16_t> word_xpos,
|
explicit TextBlock(std::vector<std::string> words, std::vector<uint16_t> word_xpos,
|
||||||
std::list<EpdFontFamily::Style> word_styles, const Style style)
|
std::vector<EpdFontFamily::Style> word_styles, const BlockStyle& blockStyle = BlockStyle())
|
||||||
: words(std::move(words)), wordXpos(std::move(word_xpos)), wordStyles(std::move(word_styles)), style(style) {}
|
: words(std::move(words)),
|
||||||
|
wordXpos(std::move(word_xpos)),
|
||||||
|
wordStyles(std::move(word_styles)),
|
||||||
|
blockStyle(blockStyle) {}
|
||||||
~TextBlock() override = default;
|
~TextBlock() override = default;
|
||||||
void setStyle(const Style style) { this->style = style; }
|
void setBlockStyle(const BlockStyle& blockStyle) { this->blockStyle = blockStyle; }
|
||||||
Style getStyle() const { return style; }
|
const BlockStyle& getBlockStyle() const { return blockStyle; }
|
||||||
|
const std::vector<std::string>& getWords() const { return words; }
|
||||||
|
const std::vector<uint16_t>& getWordXpos() const { return wordXpos; }
|
||||||
|
const std::vector<EpdFontFamily::Style>& getWordStyles() const { return wordStyles; }
|
||||||
bool isEmpty() override { return words.empty(); }
|
bool isEmpty() override { return words.empty(); }
|
||||||
void layout(GfxRenderer& renderer) override {};
|
|
||||||
// given a renderer works out where to break the words into lines
|
// given a renderer works out where to break the words into lines
|
||||||
void render(const GfxRenderer& renderer, int fontId, int x, int y) const;
|
void render(const GfxRenderer& renderer, int fontId, int x, int y) const;
|
||||||
BlockType getType() override { return TEXT_BLOCK; }
|
BlockType getType() override { return TEXT_BLOCK; }
|
||||||
|
|||||||
40
lib/Epub/Epub/converters/DitherUtils.h
Normal file
40
lib/Epub/Epub/converters/DitherUtils.h
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <GfxRenderer.h>
|
||||||
|
#include <stdint.h>
|
||||||
|
|
||||||
|
// 4x4 Bayer matrix for ordered dithering
|
||||||
|
inline const uint8_t bayer4x4[4][4] = {
|
||||||
|
{0, 8, 2, 10},
|
||||||
|
{12, 4, 14, 6},
|
||||||
|
{3, 11, 1, 9},
|
||||||
|
{15, 7, 13, 5},
|
||||||
|
};
|
||||||
|
|
||||||
|
// Apply Bayer dithering and quantize to 4 levels (0-3)
|
||||||
|
// Stateless - works correctly with any pixel processing order
|
||||||
|
inline uint8_t applyBayerDither4Level(uint8_t gray, int x, int y) {
|
||||||
|
int bayer = bayer4x4[y & 3][x & 3];
|
||||||
|
int dither = (bayer - 8) * 5; // Scale to +/-40 (half of quantization step 85)
|
||||||
|
|
||||||
|
int adjusted = gray + dither;
|
||||||
|
if (adjusted < 0) adjusted = 0;
|
||||||
|
if (adjusted > 255) adjusted = 255;
|
||||||
|
|
||||||
|
if (adjusted < 64) return 0;
|
||||||
|
if (adjusted < 128) return 1;
|
||||||
|
if (adjusted < 192) return 2;
|
||||||
|
return 3;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Draw a pixel respecting the current render mode for grayscale support
|
||||||
|
inline void drawPixelWithRenderMode(GfxRenderer& renderer, int x, int y, uint8_t pixelValue) {
|
||||||
|
GfxRenderer::RenderMode renderMode = renderer.getRenderMode();
|
||||||
|
if (renderMode == GfxRenderer::BW && pixelValue < 3) {
|
||||||
|
renderer.drawPixel(x, y, true);
|
||||||
|
} else if (renderMode == GfxRenderer::GRAYSCALE_MSB && (pixelValue == 1 || pixelValue == 2)) {
|
||||||
|
renderer.drawPixel(x, y, false);
|
||||||
|
} else if (renderMode == GfxRenderer::GRAYSCALE_LSB && pixelValue == 1) {
|
||||||
|
renderer.drawPixel(x, y, false);
|
||||||
|
}
|
||||||
|
}
|
||||||
42
lib/Epub/Epub/converters/ImageDecoderFactory.cpp
Normal file
42
lib/Epub/Epub/converters/ImageDecoderFactory.cpp
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
#include "ImageDecoderFactory.h"
|
||||||
|
|
||||||
|
#include <HardwareSerial.h>
|
||||||
|
|
||||||
|
#include <memory>
|
||||||
|
#include <string>
|
||||||
|
|
||||||
|
#include "JpegToFramebufferConverter.h"
|
||||||
|
#include "PngToFramebufferConverter.h"
|
||||||
|
|
||||||
|
std::unique_ptr<JpegToFramebufferConverter> ImageDecoderFactory::jpegDecoder = nullptr;
|
||||||
|
std::unique_ptr<PngToFramebufferConverter> ImageDecoderFactory::pngDecoder = nullptr;
|
||||||
|
|
||||||
|
ImageToFramebufferDecoder* ImageDecoderFactory::getDecoder(const std::string& imagePath) {
|
||||||
|
std::string ext = imagePath;
|
||||||
|
size_t dotPos = ext.rfind('.');
|
||||||
|
if (dotPos != std::string::npos) {
|
||||||
|
ext = ext.substr(dotPos);
|
||||||
|
for (auto& c : ext) {
|
||||||
|
c = tolower(c);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
ext = "";
|
||||||
|
}
|
||||||
|
|
||||||
|
if (JpegToFramebufferConverter::supportsFormat(ext)) {
|
||||||
|
if (!jpegDecoder) {
|
||||||
|
jpegDecoder.reset(new JpegToFramebufferConverter());
|
||||||
|
}
|
||||||
|
return jpegDecoder.get();
|
||||||
|
} else if (PngToFramebufferConverter::supportsFormat(ext)) {
|
||||||
|
if (!pngDecoder) {
|
||||||
|
pngDecoder.reset(new PngToFramebufferConverter());
|
||||||
|
}
|
||||||
|
return pngDecoder.get();
|
||||||
|
}
|
||||||
|
|
||||||
|
Serial.printf("[%lu] [DEC] No decoder found for image: %s\n", millis(), imagePath.c_str());
|
||||||
|
return nullptr;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool ImageDecoderFactory::isFormatSupported(const std::string& imagePath) { return getDecoder(imagePath) != nullptr; }
|
||||||
20
lib/Epub/Epub/converters/ImageDecoderFactory.h
Normal file
20
lib/Epub/Epub/converters/ImageDecoderFactory.h
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
#pragma once
|
||||||
|
#include <cstdint>
|
||||||
|
#include <memory>
|
||||||
|
#include <string>
|
||||||
|
|
||||||
|
#include "ImageToFramebufferDecoder.h"
|
||||||
|
|
||||||
|
class JpegToFramebufferConverter;
|
||||||
|
class PngToFramebufferConverter;
|
||||||
|
|
||||||
|
class ImageDecoderFactory {
|
||||||
|
public:
|
||||||
|
// Returns non-owning pointer - factory owns the decoder lifetime
|
||||||
|
static ImageToFramebufferDecoder* getDecoder(const std::string& imagePath);
|
||||||
|
static bool isFormatSupported(const std::string& imagePath);
|
||||||
|
|
||||||
|
private:
|
||||||
|
static std::unique_ptr<JpegToFramebufferConverter> jpegDecoder;
|
||||||
|
static std::unique_ptr<PngToFramebufferConverter> pngDecoder;
|
||||||
|
};
|
||||||
18
lib/Epub/Epub/converters/ImageToFramebufferDecoder.cpp
Normal file
18
lib/Epub/Epub/converters/ImageToFramebufferDecoder.cpp
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
#include "ImageToFramebufferDecoder.h"
|
||||||
|
|
||||||
|
#include <Arduino.h>
|
||||||
|
#include <HardwareSerial.h>
|
||||||
|
|
||||||
|
bool ImageToFramebufferDecoder::validateImageDimensions(int width, int height, const std::string& format) {
|
||||||
|
if (width * height > MAX_SOURCE_PIXELS) {
|
||||||
|
Serial.printf("[%lu] [IMG] Image too large (%dx%d = %d pixels %s), max supported: %d pixels\n", millis(), width,
|
||||||
|
height, width * height, format.c_str(), MAX_SOURCE_PIXELS);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
void ImageToFramebufferDecoder::warnUnsupportedFeature(const std::string& feature, const std::string& imagePath) {
|
||||||
|
Serial.printf("[%lu] [IMG] Warning: Unsupported feature '%s' in image '%s'. Image may not display correctly.\n",
|
||||||
|
millis(), feature.c_str(), imagePath.c_str());
|
||||||
|
}
|
||||||
40
lib/Epub/Epub/converters/ImageToFramebufferDecoder.h
Normal file
40
lib/Epub/Epub/converters/ImageToFramebufferDecoder.h
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
#pragma once
|
||||||
|
#include <SdFat.h>
|
||||||
|
|
||||||
|
#include <memory>
|
||||||
|
#include <string>
|
||||||
|
|
||||||
|
class GfxRenderer;
|
||||||
|
|
||||||
|
struct ImageDimensions {
|
||||||
|
int16_t width;
|
||||||
|
int16_t height;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct RenderConfig {
|
||||||
|
int x, y;
|
||||||
|
int maxWidth, maxHeight;
|
||||||
|
bool useGrayscale = true;
|
||||||
|
bool useDithering = true;
|
||||||
|
bool performanceMode = false;
|
||||||
|
bool useExactDimensions = false; // If true, use maxWidth/maxHeight as exact output size (no recalculation)
|
||||||
|
std::string cachePath; // If non-empty, decoder will write pixel cache to this path
|
||||||
|
};
|
||||||
|
|
||||||
|
class ImageToFramebufferDecoder {
|
||||||
|
public:
|
||||||
|
virtual ~ImageToFramebufferDecoder() = default;
|
||||||
|
|
||||||
|
virtual bool decodeToFramebuffer(const std::string& imagePath, GfxRenderer& renderer, const RenderConfig& config) = 0;
|
||||||
|
|
||||||
|
virtual bool getDimensions(const std::string& imagePath, ImageDimensions& dims) const = 0;
|
||||||
|
|
||||||
|
virtual const char* getFormatName() const = 0;
|
||||||
|
|
||||||
|
protected:
|
||||||
|
// Size validation helpers
|
||||||
|
static constexpr int MAX_SOURCE_PIXELS = 3145728; // 2048 * 1536
|
||||||
|
|
||||||
|
bool validateImageDimensions(int width, int height, const std::string& format);
|
||||||
|
void warnUnsupportedFeature(const std::string& feature, const std::string& imagePath);
|
||||||
|
};
|
||||||
298
lib/Epub/Epub/converters/JpegToFramebufferConverter.cpp
Normal file
298
lib/Epub/Epub/converters/JpegToFramebufferConverter.cpp
Normal file
@@ -0,0 +1,298 @@
|
|||||||
|
#include "JpegToFramebufferConverter.h"
|
||||||
|
|
||||||
|
#include <GfxRenderer.h>
|
||||||
|
#include <HardwareSerial.h>
|
||||||
|
#include <SDCardManager.h>
|
||||||
|
#include <SdFat.h>
|
||||||
|
#include <picojpeg.h>
|
||||||
|
|
||||||
|
#include <cstdio>
|
||||||
|
#include <cstring>
|
||||||
|
|
||||||
|
#include "DitherUtils.h"
|
||||||
|
#include "PixelCache.h"
|
||||||
|
|
||||||
|
struct JpegContext {
|
||||||
|
FsFile& file;
|
||||||
|
uint8_t buffer[512];
|
||||||
|
size_t bufferPos;
|
||||||
|
size_t bufferFilled;
|
||||||
|
JpegContext(FsFile& f) : file(f), bufferPos(0), bufferFilled(0) {}
|
||||||
|
};
|
||||||
|
|
||||||
|
bool JpegToFramebufferConverter::getDimensionsStatic(const std::string& imagePath, ImageDimensions& out) {
|
||||||
|
FsFile file;
|
||||||
|
if (!Storage.openFileForRead("JPG", imagePath, file)) {
|
||||||
|
Serial.printf("[%lu] [JPG] Failed to open file for dimensions: %s\n", millis(), imagePath.c_str());
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
JpegContext context(file);
|
||||||
|
pjpeg_image_info_t imageInfo;
|
||||||
|
|
||||||
|
int status = pjpeg_decode_init(&imageInfo, jpegReadCallback, &context, 0);
|
||||||
|
file.close();
|
||||||
|
|
||||||
|
if (status != 0) {
|
||||||
|
Serial.printf("[%lu] [JPG] Failed to init JPEG for dimensions: %d\n", millis(), status);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
out.width = imageInfo.m_width;
|
||||||
|
out.height = imageInfo.m_height;
|
||||||
|
Serial.printf("[%lu] [JPG] Image dimensions: %dx%d\n", millis(), out.width, out.height);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool JpegToFramebufferConverter::decodeToFramebuffer(const std::string& imagePath, GfxRenderer& renderer,
|
||||||
|
const RenderConfig& config) {
|
||||||
|
Serial.printf("[%lu] [JPG] Decoding JPEG: %s\n", millis(), imagePath.c_str());
|
||||||
|
|
||||||
|
FsFile file;
|
||||||
|
if (!Storage.openFileForRead("JPG", imagePath, file)) {
|
||||||
|
Serial.printf("[%lu] [JPG] Failed to open file: %s\n", millis(), imagePath.c_str());
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
JpegContext context(file);
|
||||||
|
pjpeg_image_info_t imageInfo;
|
||||||
|
|
||||||
|
int status = pjpeg_decode_init(&imageInfo, jpegReadCallback, &context, 0);
|
||||||
|
if (status != 0) {
|
||||||
|
Serial.printf("[%lu] [JPG] picojpeg init failed: %d\n", millis(), status);
|
||||||
|
file.close();
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!validateImageDimensions(imageInfo.m_width, imageInfo.m_height, "JPEG")) {
|
||||||
|
file.close();
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Calculate output dimensions
|
||||||
|
int destWidth, destHeight;
|
||||||
|
float scale;
|
||||||
|
|
||||||
|
if (config.useExactDimensions && config.maxWidth > 0 && config.maxHeight > 0) {
|
||||||
|
// Use exact dimensions as specified (avoids rounding mismatches with pre-calculated sizes)
|
||||||
|
destWidth = config.maxWidth;
|
||||||
|
destHeight = config.maxHeight;
|
||||||
|
scale = (float)destWidth / imageInfo.m_width;
|
||||||
|
} else {
|
||||||
|
// Calculate scale factor to fit within maxWidth/maxHeight
|
||||||
|
float scaleX = (config.maxWidth > 0 && imageInfo.m_width > config.maxWidth)
|
||||||
|
? (float)config.maxWidth / imageInfo.m_width
|
||||||
|
: 1.0f;
|
||||||
|
float scaleY = (config.maxHeight > 0 && imageInfo.m_height > config.maxHeight)
|
||||||
|
? (float)config.maxHeight / imageInfo.m_height
|
||||||
|
: 1.0f;
|
||||||
|
scale = (scaleX < scaleY) ? scaleX : scaleY;
|
||||||
|
if (scale > 1.0f) scale = 1.0f;
|
||||||
|
|
||||||
|
destWidth = (int)(imageInfo.m_width * scale);
|
||||||
|
destHeight = (int)(imageInfo.m_height * scale);
|
||||||
|
}
|
||||||
|
|
||||||
|
Serial.printf("[%lu] [JPG] JPEG %dx%d -> %dx%d (scale %.2f), scan type: %d, MCU: %dx%d\n", millis(),
|
||||||
|
imageInfo.m_width, imageInfo.m_height, destWidth, destHeight, scale, imageInfo.m_scanType,
|
||||||
|
imageInfo.m_MCUWidth, imageInfo.m_MCUHeight);
|
||||||
|
|
||||||
|
if (!imageInfo.m_pMCUBufR || !imageInfo.m_pMCUBufG || !imageInfo.m_pMCUBufB) {
|
||||||
|
Serial.printf("[%lu] [JPG] Null buffer pointers in imageInfo\n", millis());
|
||||||
|
file.close();
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
const int screenWidth = renderer.getScreenWidth();
|
||||||
|
const int screenHeight = renderer.getScreenHeight();
|
||||||
|
|
||||||
|
// Allocate pixel cache if cachePath is provided
|
||||||
|
PixelCache cache;
|
||||||
|
bool caching = !config.cachePath.empty();
|
||||||
|
if (caching) {
|
||||||
|
if (!cache.allocate(destWidth, destHeight, config.x, config.y)) {
|
||||||
|
Serial.printf("[%lu] [JPG] Failed to allocate cache buffer, continuing without caching\n", millis());
|
||||||
|
caching = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
int mcuX = 0;
|
||||||
|
int mcuY = 0;
|
||||||
|
|
||||||
|
while (mcuY < imageInfo.m_MCUSPerCol) {
|
||||||
|
status = pjpeg_decode_mcu();
|
||||||
|
if (status == PJPG_NO_MORE_BLOCKS) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if (status != 0) {
|
||||||
|
Serial.printf("[%lu] [JPG] MCU decode failed: %d\n", millis(), status);
|
||||||
|
file.close();
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Source position in image coordinates
|
||||||
|
int srcStartX = mcuX * imageInfo.m_MCUWidth;
|
||||||
|
int srcStartY = mcuY * imageInfo.m_MCUHeight;
|
||||||
|
|
||||||
|
switch (imageInfo.m_scanType) {
|
||||||
|
case PJPG_GRAYSCALE:
|
||||||
|
for (int row = 0; row < 8; row++) {
|
||||||
|
int srcY = srcStartY + row;
|
||||||
|
int destY = config.y + (int)(srcY * scale);
|
||||||
|
if (destY >= screenHeight || destY >= config.y + destHeight) continue;
|
||||||
|
for (int col = 0; col < 8; col++) {
|
||||||
|
int srcX = srcStartX + col;
|
||||||
|
int destX = config.x + (int)(srcX * scale);
|
||||||
|
if (destX >= screenWidth || destX >= config.x + destWidth) continue;
|
||||||
|
uint8_t gray = imageInfo.m_pMCUBufR[row * 8 + col];
|
||||||
|
uint8_t dithered = config.useDithering ? applyBayerDither4Level(gray, destX, destY) : gray / 85;
|
||||||
|
if (dithered > 3) dithered = 3;
|
||||||
|
drawPixelWithRenderMode(renderer, destX, destY, dithered);
|
||||||
|
if (caching) cache.setPixel(destX, destY, dithered);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
|
||||||
|
case PJPG_YH1V1:
|
||||||
|
for (int row = 0; row < 8; row++) {
|
||||||
|
int srcY = srcStartY + row;
|
||||||
|
int destY = config.y + (int)(srcY * scale);
|
||||||
|
if (destY >= screenHeight || destY >= config.y + destHeight) continue;
|
||||||
|
for (int col = 0; col < 8; col++) {
|
||||||
|
int srcX = srcStartX + col;
|
||||||
|
int destX = config.x + (int)(srcX * scale);
|
||||||
|
if (destX >= screenWidth || destX >= config.x + destWidth) continue;
|
||||||
|
uint8_t r = imageInfo.m_pMCUBufR[row * 8 + col];
|
||||||
|
uint8_t g = imageInfo.m_pMCUBufG[row * 8 + col];
|
||||||
|
uint8_t b = imageInfo.m_pMCUBufB[row * 8 + col];
|
||||||
|
uint8_t gray = (uint8_t)((r * 77 + g * 150 + b * 29) >> 8);
|
||||||
|
uint8_t dithered = config.useDithering ? applyBayerDither4Level(gray, destX, destY) : gray / 85;
|
||||||
|
if (dithered > 3) dithered = 3;
|
||||||
|
drawPixelWithRenderMode(renderer, destX, destY, dithered);
|
||||||
|
if (caching) cache.setPixel(destX, destY, dithered);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
|
||||||
|
case PJPG_YH2V1:
|
||||||
|
for (int row = 0; row < 8; row++) {
|
||||||
|
int srcY = srcStartY + row;
|
||||||
|
int destY = config.y + (int)(srcY * scale);
|
||||||
|
if (destY >= screenHeight || destY >= config.y + destHeight) continue;
|
||||||
|
for (int col = 0; col < 16; col++) {
|
||||||
|
int srcX = srcStartX + col;
|
||||||
|
int destX = config.x + (int)(srcX * scale);
|
||||||
|
if (destX >= screenWidth || destX >= config.x + destWidth) continue;
|
||||||
|
int blockIndex = (col < 8) ? 0 : 1;
|
||||||
|
int pixelIndex = row * 8 + (col % 8);
|
||||||
|
uint8_t r = imageInfo.m_pMCUBufR[blockIndex * 64 + pixelIndex];
|
||||||
|
uint8_t g = imageInfo.m_pMCUBufG[blockIndex * 64 + pixelIndex];
|
||||||
|
uint8_t b = imageInfo.m_pMCUBufB[blockIndex * 64 + pixelIndex];
|
||||||
|
uint8_t gray = (uint8_t)((r * 77 + g * 150 + b * 29) >> 8);
|
||||||
|
uint8_t dithered = config.useDithering ? applyBayerDither4Level(gray, destX, destY) : gray / 85;
|
||||||
|
if (dithered > 3) dithered = 3;
|
||||||
|
drawPixelWithRenderMode(renderer, destX, destY, dithered);
|
||||||
|
if (caching) cache.setPixel(destX, destY, dithered);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
|
||||||
|
case PJPG_YH1V2:
|
||||||
|
for (int row = 0; row < 16; row++) {
|
||||||
|
int srcY = srcStartY + row;
|
||||||
|
int destY = config.y + (int)(srcY * scale);
|
||||||
|
if (destY >= screenHeight || destY >= config.y + destHeight) continue;
|
||||||
|
for (int col = 0; col < 8; col++) {
|
||||||
|
int srcX = srcStartX + col;
|
||||||
|
int destX = config.x + (int)(srcX * scale);
|
||||||
|
if (destX >= screenWidth || destX >= config.x + destWidth) continue;
|
||||||
|
int blockIndex = (row < 8) ? 0 : 1;
|
||||||
|
int pixelIndex = (row % 8) * 8 + col;
|
||||||
|
uint8_t r = imageInfo.m_pMCUBufR[blockIndex * 128 + pixelIndex];
|
||||||
|
uint8_t g = imageInfo.m_pMCUBufG[blockIndex * 128 + pixelIndex];
|
||||||
|
uint8_t b = imageInfo.m_pMCUBufB[blockIndex * 128 + pixelIndex];
|
||||||
|
uint8_t gray = (uint8_t)((r * 77 + g * 150 + b * 29) >> 8);
|
||||||
|
uint8_t dithered = config.useDithering ? applyBayerDither4Level(gray, destX, destY) : gray / 85;
|
||||||
|
if (dithered > 3) dithered = 3;
|
||||||
|
drawPixelWithRenderMode(renderer, destX, destY, dithered);
|
||||||
|
if (caching) cache.setPixel(destX, destY, dithered);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
|
||||||
|
case PJPG_YH2V2:
|
||||||
|
for (int row = 0; row < 16; row++) {
|
||||||
|
int srcY = srcStartY + row;
|
||||||
|
int destY = config.y + (int)(srcY * scale);
|
||||||
|
if (destY >= screenHeight || destY >= config.y + destHeight) continue;
|
||||||
|
for (int col = 0; col < 16; col++) {
|
||||||
|
int srcX = srcStartX + col;
|
||||||
|
int destX = config.x + (int)(srcX * scale);
|
||||||
|
if (destX >= screenWidth || destX >= config.x + destWidth) continue;
|
||||||
|
int blockX = (col < 8) ? 0 : 1;
|
||||||
|
int blockY = (row < 8) ? 0 : 1;
|
||||||
|
int blockIndex = blockY * 2 + blockX;
|
||||||
|
int pixelIndex = (row % 8) * 8 + (col % 8);
|
||||||
|
int blockOffset = blockIndex * 64;
|
||||||
|
uint8_t r = imageInfo.m_pMCUBufR[blockOffset + pixelIndex];
|
||||||
|
uint8_t g = imageInfo.m_pMCUBufG[blockOffset + pixelIndex];
|
||||||
|
uint8_t b = imageInfo.m_pMCUBufB[blockOffset + pixelIndex];
|
||||||
|
uint8_t gray = (uint8_t)((r * 77 + g * 150 + b * 29) >> 8);
|
||||||
|
uint8_t dithered = config.useDithering ? applyBayerDither4Level(gray, destX, destY) : gray / 85;
|
||||||
|
if (dithered > 3) dithered = 3;
|
||||||
|
drawPixelWithRenderMode(renderer, destX, destY, dithered);
|
||||||
|
if (caching) cache.setPixel(destX, destY, dithered);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
mcuX++;
|
||||||
|
if (mcuX >= imageInfo.m_MCUSPerRow) {
|
||||||
|
mcuX = 0;
|
||||||
|
mcuY++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Serial.printf("[%lu] [JPG] Decoding complete\n", millis());
|
||||||
|
file.close();
|
||||||
|
|
||||||
|
// Write cache file if caching was enabled
|
||||||
|
if (caching) {
|
||||||
|
cache.writeToFile(config.cachePath);
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
unsigned char JpegToFramebufferConverter::jpegReadCallback(unsigned char* pBuf, unsigned char buf_size,
|
||||||
|
unsigned char* pBytes_actually_read, void* pCallback_data) {
|
||||||
|
JpegContext* context = reinterpret_cast<JpegContext*>(pCallback_data);
|
||||||
|
|
||||||
|
if (context->bufferPos >= context->bufferFilled) {
|
||||||
|
int readCount = context->file.read(context->buffer, sizeof(context->buffer));
|
||||||
|
if (readCount <= 0) {
|
||||||
|
*pBytes_actually_read = 0;
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
context->bufferFilled = readCount;
|
||||||
|
context->bufferPos = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
unsigned int bytesAvailable = context->bufferFilled - context->bufferPos;
|
||||||
|
unsigned int bytesToCopy = (bytesAvailable < buf_size) ? bytesAvailable : buf_size;
|
||||||
|
|
||||||
|
memcpy(pBuf, &context->buffer[context->bufferPos], bytesToCopy);
|
||||||
|
context->bufferPos += bytesToCopy;
|
||||||
|
*pBytes_actually_read = bytesToCopy;
|
||||||
|
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool JpegToFramebufferConverter::supportsFormat(const std::string& extension) {
|
||||||
|
std::string ext = extension;
|
||||||
|
for (auto& c : ext) {
|
||||||
|
c = tolower(c);
|
||||||
|
}
|
||||||
|
return (ext == ".jpg" || ext == ".jpeg");
|
||||||
|
}
|
||||||
24
lib/Epub/Epub/converters/JpegToFramebufferConverter.h
Normal file
24
lib/Epub/Epub/converters/JpegToFramebufferConverter.h
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
#pragma once
|
||||||
|
#include <stdint.h>
|
||||||
|
|
||||||
|
#include <string>
|
||||||
|
|
||||||
|
#include "ImageToFramebufferDecoder.h"
|
||||||
|
|
||||||
|
class JpegToFramebufferConverter final : public ImageToFramebufferDecoder {
|
||||||
|
public:
|
||||||
|
static bool getDimensionsStatic(const std::string& imagePath, ImageDimensions& out);
|
||||||
|
|
||||||
|
bool decodeToFramebuffer(const std::string& imagePath, GfxRenderer& renderer, const RenderConfig& config) override;
|
||||||
|
|
||||||
|
bool getDimensions(const std::string& imagePath, ImageDimensions& dims) const override {
|
||||||
|
return getDimensionsStatic(imagePath, dims);
|
||||||
|
}
|
||||||
|
|
||||||
|
static bool supportsFormat(const std::string& extension);
|
||||||
|
const char* getFormatName() const override { return "JPEG"; }
|
||||||
|
|
||||||
|
private:
|
||||||
|
static unsigned char jpegReadCallback(unsigned char* pBuf, unsigned char buf_size,
|
||||||
|
unsigned char* pBytes_actually_read, void* pCallback_data);
|
||||||
|
};
|
||||||
85
lib/Epub/Epub/converters/PixelCache.h
Normal file
85
lib/Epub/Epub/converters/PixelCache.h
Normal file
@@ -0,0 +1,85 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <HardwareSerial.h>
|
||||||
|
#include <SDCardManager.h>
|
||||||
|
#include <SdFat.h>
|
||||||
|
#include <stdint.h>
|
||||||
|
|
||||||
|
#include <cstring>
|
||||||
|
#include <string>
|
||||||
|
|
||||||
|
// Cache buffer for storing 2-bit pixels (4 levels) during decode.
|
||||||
|
// Packs 4 pixels per byte, MSB first.
|
||||||
|
struct PixelCache {
|
||||||
|
uint8_t* buffer;
|
||||||
|
int width;
|
||||||
|
int height;
|
||||||
|
int bytesPerRow;
|
||||||
|
int originX; // config.x - to convert screen coords to cache coords
|
||||||
|
int originY; // config.y
|
||||||
|
|
||||||
|
PixelCache() : buffer(nullptr), width(0), height(0), bytesPerRow(0), originX(0), originY(0) {}
|
||||||
|
PixelCache(const PixelCache&) = delete;
|
||||||
|
PixelCache& operator=(const PixelCache&) = delete;
|
||||||
|
|
||||||
|
static constexpr size_t MAX_CACHE_BYTES = 256 * 1024; // 256KB limit for embedded targets
|
||||||
|
|
||||||
|
bool allocate(int w, int h, int ox, int oy) {
|
||||||
|
width = w;
|
||||||
|
height = h;
|
||||||
|
originX = ox;
|
||||||
|
originY = oy;
|
||||||
|
bytesPerRow = (w + 3) / 4; // 2 bits per pixel, 4 pixels per byte
|
||||||
|
size_t bufferSize = (size_t)bytesPerRow * h;
|
||||||
|
if (bufferSize > MAX_CACHE_BYTES) {
|
||||||
|
Serial.printf("[%lu] [IMG] Cache buffer too large: %d bytes for %dx%d (limit %d)\n", millis(), bufferSize, w, h,
|
||||||
|
MAX_CACHE_BYTES);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
buffer = (uint8_t*)malloc(bufferSize);
|
||||||
|
if (buffer) {
|
||||||
|
memset(buffer, 0, bufferSize);
|
||||||
|
Serial.printf("[%lu] [IMG] Allocated cache buffer: %d bytes for %dx%d\n", millis(), bufferSize, w, h);
|
||||||
|
}
|
||||||
|
return buffer != nullptr;
|
||||||
|
}
|
||||||
|
|
||||||
|
void setPixel(int screenX, int screenY, uint8_t value) {
|
||||||
|
if (!buffer) return;
|
||||||
|
int localX = screenX - originX;
|
||||||
|
int localY = screenY - originY;
|
||||||
|
if (localX < 0 || localX >= width || localY < 0 || localY >= height) return;
|
||||||
|
|
||||||
|
int byteIdx = localY * bytesPerRow + localX / 4;
|
||||||
|
int bitShift = 6 - (localX % 4) * 2; // MSB first: pixel 0 at bits 6-7
|
||||||
|
buffer[byteIdx] = (buffer[byteIdx] & ~(0x03 << bitShift)) | ((value & 0x03) << bitShift);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool writeToFile(const std::string& cachePath) {
|
||||||
|
if (!buffer) return false;
|
||||||
|
|
||||||
|
FsFile cacheFile;
|
||||||
|
if (!Storage.openFileForWrite("IMG", cachePath, cacheFile)) {
|
||||||
|
Serial.printf("[%lu] [IMG] Failed to open cache file for writing: %s\n", millis(), cachePath.c_str());
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
uint16_t w = width;
|
||||||
|
uint16_t h = height;
|
||||||
|
cacheFile.write(&w, 2);
|
||||||
|
cacheFile.write(&h, 2);
|
||||||
|
cacheFile.write(buffer, bytesPerRow * height);
|
||||||
|
cacheFile.close();
|
||||||
|
|
||||||
|
Serial.printf("[%lu] [IMG] Cache written: %s (%dx%d, %d bytes)\n", millis(), cachePath.c_str(), width, height,
|
||||||
|
4 + bytesPerRow * height);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
~PixelCache() {
|
||||||
|
if (buffer) {
|
||||||
|
free(buffer);
|
||||||
|
buffer = nullptr;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
364
lib/Epub/Epub/converters/PngToFramebufferConverter.cpp
Normal file
364
lib/Epub/Epub/converters/PngToFramebufferConverter.cpp
Normal file
@@ -0,0 +1,364 @@
|
|||||||
|
#include "PngToFramebufferConverter.h"
|
||||||
|
|
||||||
|
#include <GfxRenderer.h>
|
||||||
|
#include <HardwareSerial.h>
|
||||||
|
#include <PNGdec.h>
|
||||||
|
#include <SDCardManager.h>
|
||||||
|
#include <SdFat.h>
|
||||||
|
|
||||||
|
#include <cstdlib>
|
||||||
|
#include <new>
|
||||||
|
|
||||||
|
#include "DitherUtils.h"
|
||||||
|
#include "PixelCache.h"
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
|
||||||
|
// Context struct passed through PNGdec callbacks to avoid global mutable state.
|
||||||
|
// The draw callback receives this via pDraw->pUser (set by png.decode()).
|
||||||
|
// The file I/O callbacks receive the FsFile* via pFile->fHandle (set by pngOpen()).
|
||||||
|
struct PngContext {
|
||||||
|
GfxRenderer* renderer;
|
||||||
|
const RenderConfig* config;
|
||||||
|
int screenWidth;
|
||||||
|
int screenHeight;
|
||||||
|
|
||||||
|
// Scaling state
|
||||||
|
float scale;
|
||||||
|
int srcWidth;
|
||||||
|
int srcHeight;
|
||||||
|
int dstWidth;
|
||||||
|
int dstHeight;
|
||||||
|
int lastDstY; // Track last rendered destination Y to avoid duplicates
|
||||||
|
|
||||||
|
PixelCache cache;
|
||||||
|
bool caching;
|
||||||
|
|
||||||
|
uint8_t* grayLineBuffer;
|
||||||
|
|
||||||
|
PngContext()
|
||||||
|
: renderer(nullptr),
|
||||||
|
config(nullptr),
|
||||||
|
screenWidth(0),
|
||||||
|
screenHeight(0),
|
||||||
|
scale(1.0f),
|
||||||
|
srcWidth(0),
|
||||||
|
srcHeight(0),
|
||||||
|
dstWidth(0),
|
||||||
|
dstHeight(0),
|
||||||
|
lastDstY(-1),
|
||||||
|
caching(false),
|
||||||
|
grayLineBuffer(nullptr) {}
|
||||||
|
};
|
||||||
|
|
||||||
|
// File I/O callbacks use pFile->fHandle to access the FsFile*,
|
||||||
|
// avoiding the need for global file state.
|
||||||
|
void* pngOpenWithHandle(const char* filename, int32_t* size) {
|
||||||
|
FsFile* f = new FsFile();
|
||||||
|
if (!Storage.openFileForRead("PNG", std::string(filename), *f)) {
|
||||||
|
delete f;
|
||||||
|
return nullptr;
|
||||||
|
}
|
||||||
|
*size = f->size();
|
||||||
|
return f;
|
||||||
|
}
|
||||||
|
|
||||||
|
void pngCloseWithHandle(void* handle) {
|
||||||
|
FsFile* f = reinterpret_cast<FsFile*>(handle);
|
||||||
|
if (f) {
|
||||||
|
f->close();
|
||||||
|
delete f;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
int32_t pngReadWithHandle(PNGFILE* pFile, uint8_t* pBuf, int32_t len) {
|
||||||
|
FsFile* f = reinterpret_cast<FsFile*>(pFile->fHandle);
|
||||||
|
if (!f) return 0;
|
||||||
|
return f->read(pBuf, len);
|
||||||
|
}
|
||||||
|
|
||||||
|
int32_t pngSeekWithHandle(PNGFILE* pFile, int32_t pos) {
|
||||||
|
FsFile* f = reinterpret_cast<FsFile*>(pFile->fHandle);
|
||||||
|
if (!f) return -1;
|
||||||
|
return f->seek(pos);
|
||||||
|
}
|
||||||
|
|
||||||
|
// The PNG decoder (PNGdec) is ~42 KB due to internal zlib decompression buffers.
|
||||||
|
// We heap-allocate it on demand rather than using a static instance, so this memory
|
||||||
|
// is only consumed while actually decoding/querying PNG images. This is critical on
|
||||||
|
// the ESP32-C3 where total RAM is ~320 KB.
|
||||||
|
constexpr size_t PNG_DECODER_APPROX_SIZE = 44 * 1024; // ~42 KB + overhead
|
||||||
|
constexpr size_t MIN_FREE_HEAP_FOR_PNG = PNG_DECODER_APPROX_SIZE + 16 * 1024; // decoder + 16 KB headroom
|
||||||
|
|
||||||
|
// Convert entire source line to grayscale with alpha blending to white background.
|
||||||
|
// For indexed PNGs with tRNS chunk, alpha values are stored at palette[768] onwards.
|
||||||
|
// Processing the whole line at once improves cache locality and reduces per-pixel overhead.
|
||||||
|
void convertLineToGray(uint8_t* pPixels, uint8_t* grayLine, int width, int pixelType, uint8_t* palette, int hasAlpha) {
|
||||||
|
switch (pixelType) {
|
||||||
|
case PNG_PIXEL_GRAYSCALE:
|
||||||
|
memcpy(grayLine, pPixels, width);
|
||||||
|
break;
|
||||||
|
|
||||||
|
case PNG_PIXEL_TRUECOLOR:
|
||||||
|
for (int x = 0; x < width; x++) {
|
||||||
|
uint8_t* p = &pPixels[x * 3];
|
||||||
|
grayLine[x] = (uint8_t)((p[0] * 77 + p[1] * 150 + p[2] * 29) >> 8);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
|
||||||
|
case PNG_PIXEL_INDEXED:
|
||||||
|
if (palette) {
|
||||||
|
if (hasAlpha) {
|
||||||
|
for (int x = 0; x < width; x++) {
|
||||||
|
uint8_t idx = pPixels[x];
|
||||||
|
uint8_t* p = &palette[idx * 3];
|
||||||
|
uint8_t gray = (uint8_t)((p[0] * 77 + p[1] * 150 + p[2] * 29) >> 8);
|
||||||
|
uint8_t alpha = palette[768 + idx];
|
||||||
|
grayLine[x] = (uint8_t)((gray * alpha + 255 * (255 - alpha)) / 255);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
for (int x = 0; x < width; x++) {
|
||||||
|
uint8_t* p = &palette[pPixels[x] * 3];
|
||||||
|
grayLine[x] = (uint8_t)((p[0] * 77 + p[1] * 150 + p[2] * 29) >> 8);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
memcpy(grayLine, pPixels, width);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
|
||||||
|
case PNG_PIXEL_GRAY_ALPHA:
|
||||||
|
for (int x = 0; x < width; x++) {
|
||||||
|
uint8_t gray = pPixels[x * 2];
|
||||||
|
uint8_t alpha = pPixels[x * 2 + 1];
|
||||||
|
grayLine[x] = (uint8_t)((gray * alpha + 255 * (255 - alpha)) / 255);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
|
||||||
|
case PNG_PIXEL_TRUECOLOR_ALPHA:
|
||||||
|
for (int x = 0; x < width; x++) {
|
||||||
|
uint8_t* p = &pPixels[x * 4];
|
||||||
|
uint8_t gray = (uint8_t)((p[0] * 77 + p[1] * 150 + p[2] * 29) >> 8);
|
||||||
|
uint8_t alpha = p[3];
|
||||||
|
grayLine[x] = (uint8_t)((gray * alpha + 255 * (255 - alpha)) / 255);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
|
||||||
|
default:
|
||||||
|
memset(grayLine, 128, width);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
int pngDrawCallback(PNGDRAW* pDraw) {
|
||||||
|
PngContext* ctx = reinterpret_cast<PngContext*>(pDraw->pUser);
|
||||||
|
if (!ctx || !ctx->config || !ctx->renderer || !ctx->grayLineBuffer) return 0;
|
||||||
|
|
||||||
|
int srcY = pDraw->y;
|
||||||
|
int srcWidth = ctx->srcWidth;
|
||||||
|
|
||||||
|
// Calculate destination Y with scaling
|
||||||
|
int dstY = (int)(srcY * ctx->scale);
|
||||||
|
|
||||||
|
// Skip if we already rendered this destination row (multiple source rows map to same dest)
|
||||||
|
if (dstY == ctx->lastDstY) return 1;
|
||||||
|
ctx->lastDstY = dstY;
|
||||||
|
|
||||||
|
// Check bounds
|
||||||
|
if (dstY >= ctx->dstHeight) return 1;
|
||||||
|
|
||||||
|
int outY = ctx->config->y + dstY;
|
||||||
|
if (outY >= ctx->screenHeight) return 1;
|
||||||
|
|
||||||
|
// Convert entire source line to grayscale (improves cache locality)
|
||||||
|
convertLineToGray(pDraw->pPixels, ctx->grayLineBuffer, srcWidth, pDraw->iPixelType, pDraw->pPalette,
|
||||||
|
pDraw->iHasAlpha);
|
||||||
|
|
||||||
|
// Render scaled row using Bresenham-style integer stepping (no floating-point division)
|
||||||
|
int dstWidth = ctx->dstWidth;
|
||||||
|
int outXBase = ctx->config->x;
|
||||||
|
int screenWidth = ctx->screenWidth;
|
||||||
|
bool useDithering = ctx->config->useDithering;
|
||||||
|
bool caching = ctx->caching;
|
||||||
|
|
||||||
|
int srcX = 0;
|
||||||
|
int error = 0;
|
||||||
|
|
||||||
|
for (int dstX = 0; dstX < dstWidth; dstX++) {
|
||||||
|
int outX = outXBase + dstX;
|
||||||
|
if (outX < screenWidth) {
|
||||||
|
uint8_t gray = ctx->grayLineBuffer[srcX];
|
||||||
|
|
||||||
|
uint8_t ditheredGray;
|
||||||
|
if (useDithering) {
|
||||||
|
ditheredGray = applyBayerDither4Level(gray, outX, outY);
|
||||||
|
} else {
|
||||||
|
ditheredGray = gray / 85;
|
||||||
|
if (ditheredGray > 3) ditheredGray = 3;
|
||||||
|
}
|
||||||
|
drawPixelWithRenderMode(*ctx->renderer, outX, outY, ditheredGray);
|
||||||
|
if (caching) ctx->cache.setPixel(outX, outY, ditheredGray);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Bresenham-style stepping: advance srcX based on ratio srcWidth/dstWidth
|
||||||
|
error += srcWidth;
|
||||||
|
while (error >= dstWidth) {
|
||||||
|
error -= dstWidth;
|
||||||
|
srcX++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
bool PngToFramebufferConverter::getDimensionsStatic(const std::string& imagePath, ImageDimensions& out) {
|
||||||
|
size_t freeHeap = ESP.getFreeHeap();
|
||||||
|
if (freeHeap < MIN_FREE_HEAP_FOR_PNG) {
|
||||||
|
Serial.printf("[%lu] [PNG] Not enough heap for PNG decoder (%u free, need %u)\n", millis(), freeHeap,
|
||||||
|
MIN_FREE_HEAP_FOR_PNG);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
PNG* png = new (std::nothrow) PNG();
|
||||||
|
if (!png) {
|
||||||
|
Serial.printf("[%lu] [PNG] Failed to allocate PNG decoder for dimensions\n", millis());
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
int rc = png->open(imagePath.c_str(), pngOpenWithHandle, pngCloseWithHandle, pngReadWithHandle, pngSeekWithHandle,
|
||||||
|
nullptr);
|
||||||
|
|
||||||
|
if (rc != 0) {
|
||||||
|
Serial.printf("[%lu] [PNG] Failed to open PNG for dimensions: %d\n", millis(), rc);
|
||||||
|
delete png;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
out.width = png->getWidth();
|
||||||
|
out.height = png->getHeight();
|
||||||
|
|
||||||
|
png->close();
|
||||||
|
delete png;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool PngToFramebufferConverter::decodeToFramebuffer(const std::string& imagePath, GfxRenderer& renderer,
|
||||||
|
const RenderConfig& config) {
|
||||||
|
Serial.printf("[%lu] [PNG] Decoding PNG: %s\n", millis(), imagePath.c_str());
|
||||||
|
|
||||||
|
size_t freeHeap = ESP.getFreeHeap();
|
||||||
|
if (freeHeap < MIN_FREE_HEAP_FOR_PNG) {
|
||||||
|
Serial.printf("[%lu] [PNG] Not enough heap for PNG decoder (%u free, need %u)\n", millis(), freeHeap,
|
||||||
|
MIN_FREE_HEAP_FOR_PNG);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Heap-allocate PNG decoder (~42 KB) - freed at end of function
|
||||||
|
PNG* png = new (std::nothrow) PNG();
|
||||||
|
if (!png) {
|
||||||
|
Serial.printf("[%lu] [PNG] Failed to allocate PNG decoder\n", millis());
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
PngContext ctx;
|
||||||
|
ctx.renderer = &renderer;
|
||||||
|
ctx.config = &config;
|
||||||
|
ctx.screenWidth = renderer.getScreenWidth();
|
||||||
|
ctx.screenHeight = renderer.getScreenHeight();
|
||||||
|
|
||||||
|
int rc = png->open(imagePath.c_str(), pngOpenWithHandle, pngCloseWithHandle, pngReadWithHandle, pngSeekWithHandle,
|
||||||
|
pngDrawCallback);
|
||||||
|
if (rc != PNG_SUCCESS) {
|
||||||
|
Serial.printf("[%lu] [PNG] Failed to open PNG: %d\n", millis(), rc);
|
||||||
|
delete png;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!validateImageDimensions(png->getWidth(), png->getHeight(), "PNG")) {
|
||||||
|
png->close();
|
||||||
|
delete png;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Calculate output dimensions
|
||||||
|
ctx.srcWidth = png->getWidth();
|
||||||
|
ctx.srcHeight = png->getHeight();
|
||||||
|
|
||||||
|
if (config.useExactDimensions && config.maxWidth > 0 && config.maxHeight > 0) {
|
||||||
|
// Use exact dimensions as specified (avoids rounding mismatches with pre-calculated sizes)
|
||||||
|
ctx.dstWidth = config.maxWidth;
|
||||||
|
ctx.dstHeight = config.maxHeight;
|
||||||
|
ctx.scale = (float)ctx.dstWidth / ctx.srcWidth;
|
||||||
|
} else {
|
||||||
|
// Calculate scale factor to fit within maxWidth/maxHeight
|
||||||
|
float scaleX = (float)config.maxWidth / ctx.srcWidth;
|
||||||
|
float scaleY = (float)config.maxHeight / ctx.srcHeight;
|
||||||
|
ctx.scale = (scaleX < scaleY) ? scaleX : scaleY;
|
||||||
|
if (ctx.scale > 1.0f) ctx.scale = 1.0f; // Don't upscale
|
||||||
|
|
||||||
|
ctx.dstWidth = (int)(ctx.srcWidth * ctx.scale);
|
||||||
|
ctx.dstHeight = (int)(ctx.srcHeight * ctx.scale);
|
||||||
|
}
|
||||||
|
ctx.lastDstY = -1; // Reset row tracking
|
||||||
|
|
||||||
|
Serial.printf("[%lu] [PNG] PNG %dx%d -> %dx%d (scale %.2f), bpp: %d\n", millis(), ctx.srcWidth, ctx.srcHeight,
|
||||||
|
ctx.dstWidth, ctx.dstHeight, ctx.scale, png->getBpp());
|
||||||
|
|
||||||
|
if (png->getBpp() != 8) {
|
||||||
|
warnUnsupportedFeature("bit depth (" + std::to_string(png->getBpp()) + "bpp)", imagePath);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Allocate grayscale line buffer on demand (~3.2 KB) - freed after decode
|
||||||
|
const size_t grayBufSize = PNG_MAX_BUFFERED_PIXELS / 2;
|
||||||
|
ctx.grayLineBuffer = static_cast<uint8_t*>(malloc(grayBufSize));
|
||||||
|
if (!ctx.grayLineBuffer) {
|
||||||
|
Serial.printf("[%lu] [PNG] Failed to allocate gray line buffer\n", millis());
|
||||||
|
png->close();
|
||||||
|
delete png;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Allocate cache buffer using SCALED dimensions
|
||||||
|
ctx.caching = !config.cachePath.empty();
|
||||||
|
if (ctx.caching) {
|
||||||
|
if (!ctx.cache.allocate(ctx.dstWidth, ctx.dstHeight, config.x, config.y)) {
|
||||||
|
Serial.printf("[%lu] [PNG] Failed to allocate cache buffer, continuing without caching\n", millis());
|
||||||
|
ctx.caching = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
unsigned long decodeStart = millis();
|
||||||
|
rc = png->decode(&ctx, 0);
|
||||||
|
unsigned long decodeTime = millis() - decodeStart;
|
||||||
|
|
||||||
|
free(ctx.grayLineBuffer);
|
||||||
|
ctx.grayLineBuffer = nullptr;
|
||||||
|
|
||||||
|
if (rc != PNG_SUCCESS) {
|
||||||
|
Serial.printf("[%lu] [PNG] Decode failed: %d\n", millis(), rc);
|
||||||
|
png->close();
|
||||||
|
delete png;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
png->close();
|
||||||
|
delete png;
|
||||||
|
Serial.printf("[%lu] [PNG] PNG decoding complete - render time: %lu ms\n", millis(), decodeTime);
|
||||||
|
|
||||||
|
// Write cache file if caching was enabled and buffer was allocated
|
||||||
|
if (ctx.caching) {
|
||||||
|
ctx.cache.writeToFile(config.cachePath);
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool PngToFramebufferConverter::supportsFormat(const std::string& extension) {
|
||||||
|
std::string ext = extension;
|
||||||
|
for (auto& c : ext) {
|
||||||
|
c = tolower(c);
|
||||||
|
}
|
||||||
|
return (ext == ".png");
|
||||||
|
}
|
||||||
17
lib/Epub/Epub/converters/PngToFramebufferConverter.h
Normal file
17
lib/Epub/Epub/converters/PngToFramebufferConverter.h
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include "ImageToFramebufferDecoder.h"
|
||||||
|
|
||||||
|
class PngToFramebufferConverter final : public ImageToFramebufferDecoder {
|
||||||
|
public:
|
||||||
|
static bool getDimensionsStatic(const std::string& imagePath, ImageDimensions& out);
|
||||||
|
|
||||||
|
bool decodeToFramebuffer(const std::string& imagePath, GfxRenderer& renderer, const RenderConfig& config) override;
|
||||||
|
|
||||||
|
bool getDimensions(const std::string& imagePath, ImageDimensions& dims) const override {
|
||||||
|
return getDimensionsStatic(imagePath, dims);
|
||||||
|
}
|
||||||
|
|
||||||
|
static bool supportsFormat(const std::string& extension);
|
||||||
|
const char* getFormatName() const override { return "PNG"; }
|
||||||
|
};
|
||||||
769
lib/Epub/Epub/css/CssParser.cpp
Normal file
769
lib/Epub/Epub/css/CssParser.cpp
Normal file
@@ -0,0 +1,769 @@
|
|||||||
|
#include "CssParser.h"
|
||||||
|
|
||||||
|
#include <Arduino.h>
|
||||||
|
#include <Logging.h>
|
||||||
|
|
||||||
|
#include <algorithm>
|
||||||
|
#include <array>
|
||||||
|
#include <cctype>
|
||||||
|
#include <string_view>
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
|
||||||
|
// Stack-allocated string buffer to avoid heap reallocations during parsing
|
||||||
|
// Provides string-like interface with fixed capacity
|
||||||
|
struct StackBuffer {
|
||||||
|
static constexpr size_t CAPACITY = 1024;
|
||||||
|
char data[CAPACITY];
|
||||||
|
size_t len = 0;
|
||||||
|
|
||||||
|
void push_back(char c) {
|
||||||
|
if (len < CAPACITY - 1) {
|
||||||
|
data[len++] = c;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void clear() { len = 0; }
|
||||||
|
bool empty() const { return len == 0; }
|
||||||
|
size_t size() const { return len; }
|
||||||
|
|
||||||
|
// Get string view of current content (zero-copy)
|
||||||
|
std::string_view view() const { return std::string_view(data, len); }
|
||||||
|
|
||||||
|
// Convert to string for passing to functions (single allocation)
|
||||||
|
std::string str() const { return std::string(data, len); }
|
||||||
|
};
|
||||||
|
|
||||||
|
// Buffer size for reading CSS files
|
||||||
|
constexpr size_t READ_BUFFER_SIZE = 512;
|
||||||
|
|
||||||
|
// Maximum number of CSS rules to store in the selector map
|
||||||
|
// Prevents unbounded memory growth from pathological CSS files
|
||||||
|
constexpr size_t MAX_RULES = 1500;
|
||||||
|
|
||||||
|
// Minimum free heap required to apply CSS during rendering
|
||||||
|
// If below this threshold, we skip CSS to avoid display artifacts.
|
||||||
|
constexpr size_t MIN_FREE_HEAP_FOR_CSS = 48 * 1024;
|
||||||
|
|
||||||
|
// Maximum length for a single selector string
|
||||||
|
// Prevents parsing of extremely long or malformed selectors
|
||||||
|
constexpr size_t MAX_SELECTOR_LENGTH = 256;
|
||||||
|
|
||||||
|
// Check if character is CSS whitespace
|
||||||
|
bool isCssWhitespace(const char c) { return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f'; }
|
||||||
|
|
||||||
|
} // anonymous namespace
|
||||||
|
|
||||||
|
// String utilities implementation
|
||||||
|
|
||||||
|
std::string CssParser::normalized(const std::string& s) {
|
||||||
|
std::string result;
|
||||||
|
result.reserve(s.size());
|
||||||
|
|
||||||
|
bool inSpace = true; // Start true to skip leading space
|
||||||
|
for (const char c : s) {
|
||||||
|
if (isCssWhitespace(c)) {
|
||||||
|
if (!inSpace) {
|
||||||
|
result.push_back(' ');
|
||||||
|
inSpace = true;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
result.push_back(static_cast<char>(std::tolower(static_cast<unsigned char>(c))));
|
||||||
|
inSpace = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Remove trailing space
|
||||||
|
if (!result.empty() && result.back() == ' ') {
|
||||||
|
result.pop_back();
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
void CssParser::normalizedInto(const std::string& s, std::string& out) {
|
||||||
|
out.clear();
|
||||||
|
out.reserve(s.size());
|
||||||
|
|
||||||
|
bool inSpace = true; // Start true to skip leading space
|
||||||
|
for (const char c : s) {
|
||||||
|
if (isCssWhitespace(c)) {
|
||||||
|
if (!inSpace) {
|
||||||
|
out.push_back(' ');
|
||||||
|
inSpace = true;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
out.push_back(static_cast<char>(std::tolower(static_cast<unsigned char>(c))));
|
||||||
|
inSpace = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!out.empty() && out.back() == ' ') {
|
||||||
|
out.pop_back();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
std::vector<std::string> CssParser::splitOnChar(const std::string& s, const char delimiter) {
|
||||||
|
std::vector<std::string> parts;
|
||||||
|
size_t start = 0;
|
||||||
|
|
||||||
|
for (size_t i = 0; i <= s.size(); ++i) {
|
||||||
|
if (i == s.size() || s[i] == delimiter) {
|
||||||
|
std::string part = s.substr(start, i - start);
|
||||||
|
std::string trimmed = normalized(part);
|
||||||
|
if (!trimmed.empty()) {
|
||||||
|
parts.push_back(trimmed);
|
||||||
|
}
|
||||||
|
start = i + 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return parts;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::vector<std::string> CssParser::splitWhitespace(const std::string& s) {
|
||||||
|
std::vector<std::string> parts;
|
||||||
|
size_t start = 0;
|
||||||
|
bool inWord = false;
|
||||||
|
|
||||||
|
for (size_t i = 0; i <= s.size(); ++i) {
|
||||||
|
const bool isSpace = i == s.size() || isCssWhitespace(s[i]);
|
||||||
|
if (isSpace && inWord) {
|
||||||
|
parts.push_back(s.substr(start, i - start));
|
||||||
|
inWord = false;
|
||||||
|
} else if (!isSpace && !inWord) {
|
||||||
|
start = i;
|
||||||
|
inWord = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return parts;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Property value interpreters
|
||||||
|
|
||||||
|
CssTextAlign CssParser::interpretAlignment(const std::string& val) {
|
||||||
|
const std::string v = normalized(val);
|
||||||
|
|
||||||
|
if (v == "left" || v == "start") return CssTextAlign::Left;
|
||||||
|
if (v == "right" || v == "end") return CssTextAlign::Right;
|
||||||
|
if (v == "center") return CssTextAlign::Center;
|
||||||
|
if (v == "justify") return CssTextAlign::Justify;
|
||||||
|
|
||||||
|
return CssTextAlign::Left;
|
||||||
|
}
|
||||||
|
|
||||||
|
CssFontStyle CssParser::interpretFontStyle(const std::string& val) {
|
||||||
|
const std::string v = normalized(val);
|
||||||
|
|
||||||
|
if (v == "italic" || v == "oblique") return CssFontStyle::Italic;
|
||||||
|
return CssFontStyle::Normal;
|
||||||
|
}
|
||||||
|
|
||||||
|
CssFontWeight CssParser::interpretFontWeight(const std::string& val) {
|
||||||
|
const std::string v = normalized(val);
|
||||||
|
|
||||||
|
// Named values
|
||||||
|
if (v == "bold" || v == "bolder") return CssFontWeight::Bold;
|
||||||
|
if (v == "normal" || v == "lighter") return CssFontWeight::Normal;
|
||||||
|
|
||||||
|
// Numeric values: 100-900
|
||||||
|
// CSS spec: 400 = normal, 700 = bold
|
||||||
|
// We use: 0-400 = normal, 700+ = bold, 500-600 = normal (conservative)
|
||||||
|
char* endPtr = nullptr;
|
||||||
|
const long numericWeight = std::strtol(v.c_str(), &endPtr, 10);
|
||||||
|
|
||||||
|
// If we parsed a number and consumed the whole string
|
||||||
|
if (endPtr != v.c_str() && *endPtr == '\0') {
|
||||||
|
return numericWeight >= 700 ? CssFontWeight::Bold : CssFontWeight::Normal;
|
||||||
|
}
|
||||||
|
|
||||||
|
return CssFontWeight::Normal;
|
||||||
|
}
|
||||||
|
|
||||||
|
CssTextDecoration CssParser::interpretDecoration(const std::string& val) {
|
||||||
|
const std::string v = normalized(val);
|
||||||
|
|
||||||
|
// text-decoration can have multiple space-separated values
|
||||||
|
if (v.find("underline") != std::string::npos) {
|
||||||
|
return CssTextDecoration::Underline;
|
||||||
|
}
|
||||||
|
return CssTextDecoration::None;
|
||||||
|
}
|
||||||
|
|
||||||
|
CssLength CssParser::interpretLength(const std::string& val) {
|
||||||
|
const std::string v = normalized(val);
|
||||||
|
if (v.empty()) return CssLength{};
|
||||||
|
|
||||||
|
// Find where the number ends
|
||||||
|
size_t unitStart = v.size();
|
||||||
|
for (size_t i = 0; i < v.size(); ++i) {
|
||||||
|
const char c = v[i];
|
||||||
|
if (!std::isdigit(c) && c != '.' && c != '-' && c != '+') {
|
||||||
|
unitStart = i;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const std::string numPart = v.substr(0, unitStart);
|
||||||
|
const std::string unitPart = v.substr(unitStart);
|
||||||
|
|
||||||
|
// Parse numeric value
|
||||||
|
char* endPtr = nullptr;
|
||||||
|
const float numericValue = std::strtof(numPart.c_str(), &endPtr);
|
||||||
|
if (endPtr == numPart.c_str()) return CssLength{}; // No number parsed
|
||||||
|
|
||||||
|
// Determine unit type (preserve for deferred resolution)
|
||||||
|
auto unit = CssUnit::Pixels;
|
||||||
|
if (unitPart == "em") {
|
||||||
|
unit = CssUnit::Em;
|
||||||
|
} else if (unitPart == "rem") {
|
||||||
|
unit = CssUnit::Rem;
|
||||||
|
} else if (unitPart == "pt") {
|
||||||
|
unit = CssUnit::Points;
|
||||||
|
} else if (unitPart == "%") {
|
||||||
|
unit = CssUnit::Percent;
|
||||||
|
}
|
||||||
|
// px and unitless default to Pixels
|
||||||
|
|
||||||
|
return CssLength{numericValue, unit};
|
||||||
|
}
|
||||||
|
// Declaration parsing
|
||||||
|
|
||||||
|
void CssParser::parseDeclarationIntoStyle(const std::string& decl, CssStyle& style, std::string& propNameBuf,
|
||||||
|
std::string& propValueBuf) {
|
||||||
|
const size_t colonPos = decl.find(':');
|
||||||
|
if (colonPos == std::string::npos || colonPos == 0) return;
|
||||||
|
|
||||||
|
normalizedInto(decl.substr(0, colonPos), propNameBuf);
|
||||||
|
normalizedInto(decl.substr(colonPos + 1), propValueBuf);
|
||||||
|
|
||||||
|
if (propNameBuf.empty() || propValueBuf.empty()) return;
|
||||||
|
|
||||||
|
if (propNameBuf == "text-align") {
|
||||||
|
style.textAlign = interpretAlignment(propValueBuf);
|
||||||
|
style.defined.textAlign = 1;
|
||||||
|
} else if (propNameBuf == "font-style") {
|
||||||
|
style.fontStyle = interpretFontStyle(propValueBuf);
|
||||||
|
style.defined.fontStyle = 1;
|
||||||
|
} else if (propNameBuf == "font-weight") {
|
||||||
|
style.fontWeight = interpretFontWeight(propValueBuf);
|
||||||
|
style.defined.fontWeight = 1;
|
||||||
|
} else if (propNameBuf == "text-decoration" || propNameBuf == "text-decoration-line") {
|
||||||
|
style.textDecoration = interpretDecoration(propValueBuf);
|
||||||
|
style.defined.textDecoration = 1;
|
||||||
|
} else if (propNameBuf == "text-indent") {
|
||||||
|
style.textIndent = interpretLength(propValueBuf);
|
||||||
|
style.defined.textIndent = 1;
|
||||||
|
} else if (propNameBuf == "margin-top") {
|
||||||
|
style.marginTop = interpretLength(propValueBuf);
|
||||||
|
style.defined.marginTop = 1;
|
||||||
|
} else if (propNameBuf == "margin-bottom") {
|
||||||
|
style.marginBottom = interpretLength(propValueBuf);
|
||||||
|
style.defined.marginBottom = 1;
|
||||||
|
} else if (propNameBuf == "margin-left") {
|
||||||
|
style.marginLeft = interpretLength(propValueBuf);
|
||||||
|
style.defined.marginLeft = 1;
|
||||||
|
} else if (propNameBuf == "margin-right") {
|
||||||
|
style.marginRight = interpretLength(propValueBuf);
|
||||||
|
style.defined.marginRight = 1;
|
||||||
|
} else if (propNameBuf == "margin") {
|
||||||
|
const auto values = splitWhitespace(propValueBuf);
|
||||||
|
if (!values.empty()) {
|
||||||
|
style.marginTop = interpretLength(values[0]);
|
||||||
|
style.marginRight = values.size() >= 2 ? interpretLength(values[1]) : style.marginTop;
|
||||||
|
style.marginBottom = values.size() >= 3 ? interpretLength(values[2]) : style.marginTop;
|
||||||
|
style.marginLeft = values.size() >= 4 ? interpretLength(values[3]) : style.marginRight;
|
||||||
|
style.defined.marginTop = style.defined.marginRight = style.defined.marginBottom = style.defined.marginLeft = 1;
|
||||||
|
}
|
||||||
|
} else if (propNameBuf == "padding-top") {
|
||||||
|
style.paddingTop = interpretLength(propValueBuf);
|
||||||
|
style.defined.paddingTop = 1;
|
||||||
|
} else if (propNameBuf == "padding-bottom") {
|
||||||
|
style.paddingBottom = interpretLength(propValueBuf);
|
||||||
|
style.defined.paddingBottom = 1;
|
||||||
|
} else if (propNameBuf == "padding-left") {
|
||||||
|
style.paddingLeft = interpretLength(propValueBuf);
|
||||||
|
style.defined.paddingLeft = 1;
|
||||||
|
} else if (propNameBuf == "padding-right") {
|
||||||
|
style.paddingRight = interpretLength(propValueBuf);
|
||||||
|
style.defined.paddingRight = 1;
|
||||||
|
} else if (propNameBuf == "padding") {
|
||||||
|
const auto values = splitWhitespace(propValueBuf);
|
||||||
|
if (!values.empty()) {
|
||||||
|
style.paddingTop = interpretLength(values[0]);
|
||||||
|
style.paddingRight = values.size() >= 2 ? interpretLength(values[1]) : style.paddingTop;
|
||||||
|
style.paddingBottom = values.size() >= 3 ? interpretLength(values[2]) : style.paddingTop;
|
||||||
|
style.paddingLeft = values.size() >= 4 ? interpretLength(values[3]) : style.paddingRight;
|
||||||
|
style.defined.paddingTop = style.defined.paddingRight = style.defined.paddingBottom = style.defined.paddingLeft =
|
||||||
|
1;
|
||||||
|
}
|
||||||
|
} else if (propNameBuf == "width") {
|
||||||
|
style.width = interpretLength(propValueBuf);
|
||||||
|
style.defined.width = 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
CssStyle CssParser::parseDeclarations(const std::string& declBlock) {
|
||||||
|
CssStyle style;
|
||||||
|
std::string propNameBuf;
|
||||||
|
std::string propValueBuf;
|
||||||
|
|
||||||
|
size_t start = 0;
|
||||||
|
for (size_t i = 0; i <= declBlock.size(); ++i) {
|
||||||
|
if (i == declBlock.size() || declBlock[i] == ';') {
|
||||||
|
if (i > start) {
|
||||||
|
const size_t len = i - start;
|
||||||
|
std::string decl = declBlock.substr(start, len);
|
||||||
|
if (!decl.empty()) {
|
||||||
|
parseDeclarationIntoStyle(decl, style, propNameBuf, propValueBuf);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
start = i + 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return style;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Rule processing
|
||||||
|
|
||||||
|
void CssParser::processRuleBlockWithStyle(const std::string& selectorGroup, const CssStyle& style) {
|
||||||
|
// Check if we've reached the rule limit before processing
|
||||||
|
if (rulesBySelector_.size() >= MAX_RULES) {
|
||||||
|
LOG_DBG("CSS", "Reached max rules limit (%zu), stopping CSS parsing", MAX_RULES);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Handle comma-separated selectors
|
||||||
|
const auto selectors = splitOnChar(selectorGroup, ',');
|
||||||
|
|
||||||
|
for (const auto& sel : selectors) {
|
||||||
|
// Validate selector length before processing
|
||||||
|
if (sel.size() > MAX_SELECTOR_LENGTH) {
|
||||||
|
LOG_DBG("CSS", "Selector too long (%zu > %zu), skipping", sel.size(), MAX_SELECTOR_LENGTH);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Normalize the selector
|
||||||
|
std::string key = normalized(sel);
|
||||||
|
if (key.empty()) continue;
|
||||||
|
|
||||||
|
// Skip if this would exceed the rule limit
|
||||||
|
if (rulesBySelector_.size() >= MAX_RULES) {
|
||||||
|
LOG_DBG("CSS", "Reached max rules limit, stopping selector processing");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Store or merge with existing
|
||||||
|
auto it = rulesBySelector_.find(key);
|
||||||
|
if (it != rulesBySelector_.end()) {
|
||||||
|
it->second.applyOver(style);
|
||||||
|
} else {
|
||||||
|
rulesBySelector_[key] = style;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Main parsing entry point
|
||||||
|
|
||||||
|
bool CssParser::loadFromStream(FsFile& source) {
|
||||||
|
if (!source) {
|
||||||
|
LOG_ERR("CSS", "Cannot read from invalid file");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
size_t totalRead = 0;
|
||||||
|
|
||||||
|
// Use stack-allocated buffers for parsing to avoid heap reallocations
|
||||||
|
StackBuffer selector;
|
||||||
|
StackBuffer declBuffer;
|
||||||
|
// Keep these as std::string since they're passed by reference to parseDeclarationIntoStyle
|
||||||
|
std::string propNameBuf;
|
||||||
|
std::string propValueBuf;
|
||||||
|
|
||||||
|
bool inComment = false;
|
||||||
|
bool maybeSlash = false;
|
||||||
|
bool prevStar = false;
|
||||||
|
|
||||||
|
bool inAtRule = false;
|
||||||
|
int atDepth = 0;
|
||||||
|
|
||||||
|
int bodyDepth = 0;
|
||||||
|
bool skippingRule = false;
|
||||||
|
CssStyle currentStyle;
|
||||||
|
|
||||||
|
auto handleChar = [&](const char c) {
|
||||||
|
if (inAtRule) {
|
||||||
|
if (c == '{') {
|
||||||
|
++atDepth;
|
||||||
|
} else if (c == '}') {
|
||||||
|
if (atDepth > 0) --atDepth;
|
||||||
|
if (atDepth == 0) inAtRule = false;
|
||||||
|
} else if (c == ';' && atDepth == 0) {
|
||||||
|
inAtRule = false;
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (bodyDepth == 0) {
|
||||||
|
if (selector.empty() && isCssWhitespace(c)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (c == '@' && selector.empty()) {
|
||||||
|
inAtRule = true;
|
||||||
|
atDepth = 0;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (c == '{') {
|
||||||
|
bodyDepth = 1;
|
||||||
|
currentStyle = CssStyle{};
|
||||||
|
declBuffer.clear();
|
||||||
|
if (selector.size() > MAX_SELECTOR_LENGTH * 4) {
|
||||||
|
skippingRule = true;
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
selector.push_back(c);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// bodyDepth > 0
|
||||||
|
if (c == '{') {
|
||||||
|
++bodyDepth;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (c == '}') {
|
||||||
|
--bodyDepth;
|
||||||
|
if (bodyDepth == 0) {
|
||||||
|
if (!skippingRule && !declBuffer.empty()) {
|
||||||
|
parseDeclarationIntoStyle(declBuffer.str(), currentStyle, propNameBuf, propValueBuf);
|
||||||
|
}
|
||||||
|
if (!skippingRule) {
|
||||||
|
processRuleBlockWithStyle(selector.str(), currentStyle);
|
||||||
|
}
|
||||||
|
selector.clear();
|
||||||
|
declBuffer.clear();
|
||||||
|
skippingRule = false;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (bodyDepth > 1) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!skippingRule) {
|
||||||
|
if (c == ';') {
|
||||||
|
if (!declBuffer.empty()) {
|
||||||
|
parseDeclarationIntoStyle(declBuffer.str(), currentStyle, propNameBuf, propValueBuf);
|
||||||
|
declBuffer.clear();
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
declBuffer.push_back(c);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
char buffer[READ_BUFFER_SIZE];
|
||||||
|
while (source.available()) {
|
||||||
|
int bytesRead = source.read(buffer, sizeof(buffer));
|
||||||
|
if (bytesRead <= 0) break;
|
||||||
|
|
||||||
|
totalRead += static_cast<size_t>(bytesRead);
|
||||||
|
|
||||||
|
for (int i = 0; i < bytesRead; ++i) {
|
||||||
|
const char c = buffer[i];
|
||||||
|
|
||||||
|
if (inComment) {
|
||||||
|
if (prevStar && c == '/') {
|
||||||
|
inComment = false;
|
||||||
|
prevStar = false;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
prevStar = c == '*';
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (maybeSlash) {
|
||||||
|
if (c == '*') {
|
||||||
|
inComment = true;
|
||||||
|
maybeSlash = false;
|
||||||
|
prevStar = false;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
handleChar('/');
|
||||||
|
maybeSlash = false;
|
||||||
|
// fall through to process current char
|
||||||
|
}
|
||||||
|
|
||||||
|
if (c == '/') {
|
||||||
|
maybeSlash = true;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
handleChar(c);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (maybeSlash) {
|
||||||
|
handleChar('/');
|
||||||
|
}
|
||||||
|
|
||||||
|
LOG_DBG("CSS", "Parsed %zu rules from %zu bytes", rulesBySelector_.size(), totalRead);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Style resolution
|
||||||
|
|
||||||
|
CssStyle CssParser::resolveStyle(const std::string& tagName, const std::string& classAttr) const {
|
||||||
|
static bool lowHeapWarningLogged = false;
|
||||||
|
if (ESP.getFreeHeap() < MIN_FREE_HEAP_FOR_CSS) {
|
||||||
|
if (!lowHeapWarningLogged) {
|
||||||
|
lowHeapWarningLogged = true;
|
||||||
|
LOG_DBG("CSS", "Warning: low heap (%u bytes) below MIN_FREE_HEAP_FOR_CSS (%u), returning empty style",
|
||||||
|
ESP.getFreeHeap(), static_cast<unsigned>(MIN_FREE_HEAP_FOR_CSS));
|
||||||
|
}
|
||||||
|
return CssStyle{};
|
||||||
|
}
|
||||||
|
CssStyle result;
|
||||||
|
const std::string tag = normalized(tagName);
|
||||||
|
|
||||||
|
// 1. Apply element-level style (lowest priority)
|
||||||
|
const auto tagIt = rulesBySelector_.find(tag);
|
||||||
|
if (tagIt != rulesBySelector_.end()) {
|
||||||
|
result.applyOver(tagIt->second);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. Apply class styles (medium priority)
|
||||||
|
if (!classAttr.empty()) {
|
||||||
|
const auto classes = splitWhitespace(classAttr);
|
||||||
|
|
||||||
|
for (const auto& cls : classes) {
|
||||||
|
std::string classKey = "." + normalized(cls);
|
||||||
|
|
||||||
|
auto classIt = rulesBySelector_.find(classKey);
|
||||||
|
if (classIt != rulesBySelector_.end()) {
|
||||||
|
result.applyOver(classIt->second);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. Apply element.class styles (higher priority)
|
||||||
|
for (const auto& cls : classes) {
|
||||||
|
std::string combinedKey = tag + "." + normalized(cls);
|
||||||
|
|
||||||
|
auto combinedIt = rulesBySelector_.find(combinedKey);
|
||||||
|
if (combinedIt != rulesBySelector_.end()) {
|
||||||
|
result.applyOver(combinedIt->second);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Inline style parsing (static - doesn't need rule database)
|
||||||
|
|
||||||
|
CssStyle CssParser::parseInlineStyle(const std::string& styleValue) { return parseDeclarations(styleValue); }
|
||||||
|
|
||||||
|
// Cache serialization
|
||||||
|
|
||||||
|
// Cache format version - increment when format changes
|
||||||
|
constexpr uint8_t CSS_CACHE_VERSION = 2;
|
||||||
|
constexpr char rulesCache[] = "/css_rules.cache";
|
||||||
|
|
||||||
|
bool CssParser::hasCache() const { return Storage.exists((cachePath + rulesCache).c_str()); }
|
||||||
|
|
||||||
|
bool CssParser::saveToCache() const {
|
||||||
|
if (cachePath.empty()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
FsFile file;
|
||||||
|
if (!Storage.openFileForWrite("CSS", cachePath + rulesCache, file)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Write version
|
||||||
|
file.write(CSS_CACHE_VERSION);
|
||||||
|
|
||||||
|
// Write rule count
|
||||||
|
const auto ruleCount = static_cast<uint16_t>(rulesBySelector_.size());
|
||||||
|
file.write(reinterpret_cast<const uint8_t*>(&ruleCount), sizeof(ruleCount));
|
||||||
|
|
||||||
|
// Write each rule: selector string + CssStyle fields
|
||||||
|
for (const auto& pair : rulesBySelector_) {
|
||||||
|
// Write selector string (length-prefixed)
|
||||||
|
const auto selectorLen = static_cast<uint16_t>(pair.first.size());
|
||||||
|
file.write(reinterpret_cast<const uint8_t*>(&selectorLen), sizeof(selectorLen));
|
||||||
|
file.write(reinterpret_cast<const uint8_t*>(pair.first.data()), selectorLen);
|
||||||
|
|
||||||
|
// Write CssStyle fields (all are POD types)
|
||||||
|
const CssStyle& style = pair.second;
|
||||||
|
file.write(static_cast<uint8_t>(style.textAlign));
|
||||||
|
file.write(static_cast<uint8_t>(style.fontStyle));
|
||||||
|
file.write(static_cast<uint8_t>(style.fontWeight));
|
||||||
|
file.write(static_cast<uint8_t>(style.textDecoration));
|
||||||
|
|
||||||
|
// Write CssLength fields (value + unit)
|
||||||
|
auto writeLength = [&file](const CssLength& len) {
|
||||||
|
file.write(reinterpret_cast<const uint8_t*>(&len.value), sizeof(len.value));
|
||||||
|
file.write(static_cast<uint8_t>(len.unit));
|
||||||
|
};
|
||||||
|
|
||||||
|
writeLength(style.textIndent);
|
||||||
|
writeLength(style.marginTop);
|
||||||
|
writeLength(style.marginBottom);
|
||||||
|
writeLength(style.marginLeft);
|
||||||
|
writeLength(style.marginRight);
|
||||||
|
writeLength(style.paddingTop);
|
||||||
|
writeLength(style.paddingBottom);
|
||||||
|
writeLength(style.paddingLeft);
|
||||||
|
writeLength(style.paddingRight);
|
||||||
|
|
||||||
|
// Write defined flags as uint16_t
|
||||||
|
uint16_t definedBits = 0;
|
||||||
|
if (style.defined.textAlign) definedBits |= 1 << 0;
|
||||||
|
if (style.defined.fontStyle) definedBits |= 1 << 1;
|
||||||
|
if (style.defined.fontWeight) definedBits |= 1 << 2;
|
||||||
|
if (style.defined.textDecoration) definedBits |= 1 << 3;
|
||||||
|
if (style.defined.textIndent) definedBits |= 1 << 4;
|
||||||
|
if (style.defined.marginTop) definedBits |= 1 << 5;
|
||||||
|
if (style.defined.marginBottom) definedBits |= 1 << 6;
|
||||||
|
if (style.defined.marginLeft) definedBits |= 1 << 7;
|
||||||
|
if (style.defined.marginRight) definedBits |= 1 << 8;
|
||||||
|
if (style.defined.paddingTop) definedBits |= 1 << 9;
|
||||||
|
if (style.defined.paddingBottom) definedBits |= 1 << 10;
|
||||||
|
if (style.defined.paddingLeft) definedBits |= 1 << 11;
|
||||||
|
if (style.defined.paddingRight) definedBits |= 1 << 12;
|
||||||
|
file.write(reinterpret_cast<const uint8_t*>(&definedBits), sizeof(definedBits));
|
||||||
|
}
|
||||||
|
|
||||||
|
LOG_DBG("CSS", "Saved %u rules to cache", ruleCount);
|
||||||
|
file.close();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool CssParser::loadFromCache() {
|
||||||
|
if (cachePath.empty()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
FsFile file;
|
||||||
|
if (!Storage.openFileForRead("CSS", cachePath + rulesCache, file)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Clear existing rules
|
||||||
|
clear();
|
||||||
|
|
||||||
|
// Read and verify version
|
||||||
|
uint8_t version = 0;
|
||||||
|
if (file.read(&version, 1) != 1 || version != CSS_CACHE_VERSION) {
|
||||||
|
LOG_DBG("CSS", "Cache version mismatch (got %u, expected %u)", version, CSS_CACHE_VERSION);
|
||||||
|
file.close();
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Read rule count
|
||||||
|
uint16_t ruleCount = 0;
|
||||||
|
if (file.read(&ruleCount, sizeof(ruleCount)) != sizeof(ruleCount)) {
|
||||||
|
file.close();
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Read each rule
|
||||||
|
for (uint16_t i = 0; i < ruleCount; ++i) {
|
||||||
|
// Read selector string
|
||||||
|
uint16_t selectorLen = 0;
|
||||||
|
if (file.read(&selectorLen, sizeof(selectorLen)) != sizeof(selectorLen)) {
|
||||||
|
rulesBySelector_.clear();
|
||||||
|
file.close();
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string selector;
|
||||||
|
selector.resize(selectorLen);
|
||||||
|
if (file.read(&selector[0], selectorLen) != selectorLen) {
|
||||||
|
rulesBySelector_.clear();
|
||||||
|
file.close();
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Read CssStyle fields
|
||||||
|
CssStyle style;
|
||||||
|
uint8_t enumVal;
|
||||||
|
|
||||||
|
if (file.read(&enumVal, 1) != 1) {
|
||||||
|
rulesBySelector_.clear();
|
||||||
|
file.close();
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
style.textAlign = static_cast<CssTextAlign>(enumVal);
|
||||||
|
|
||||||
|
if (file.read(&enumVal, 1) != 1) {
|
||||||
|
rulesBySelector_.clear();
|
||||||
|
file.close();
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
style.fontStyle = static_cast<CssFontStyle>(enumVal);
|
||||||
|
|
||||||
|
if (file.read(&enumVal, 1) != 1) {
|
||||||
|
rulesBySelector_.clear();
|
||||||
|
file.close();
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
style.fontWeight = static_cast<CssFontWeight>(enumVal);
|
||||||
|
|
||||||
|
if (file.read(&enumVal, 1) != 1) {
|
||||||
|
rulesBySelector_.clear();
|
||||||
|
file.close();
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
style.textDecoration = static_cast<CssTextDecoration>(enumVal);
|
||||||
|
|
||||||
|
// Read CssLength fields
|
||||||
|
auto readLength = [&file](CssLength& len) -> bool {
|
||||||
|
if (file.read(&len.value, sizeof(len.value)) != sizeof(len.value)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
uint8_t unitVal;
|
||||||
|
if (file.read(&unitVal, 1) != 1) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
len.unit = static_cast<CssUnit>(unitVal);
|
||||||
|
return true;
|
||||||
|
};
|
||||||
|
|
||||||
|
if (!readLength(style.textIndent) || !readLength(style.marginTop) || !readLength(style.marginBottom) ||
|
||||||
|
!readLength(style.marginLeft) || !readLength(style.marginRight) || !readLength(style.paddingTop) ||
|
||||||
|
!readLength(style.paddingBottom) || !readLength(style.paddingLeft) || !readLength(style.paddingRight)) {
|
||||||
|
rulesBySelector_.clear();
|
||||||
|
file.close();
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Read defined flags
|
||||||
|
uint16_t definedBits = 0;
|
||||||
|
if (file.read(&definedBits, sizeof(definedBits)) != sizeof(definedBits)) {
|
||||||
|
rulesBySelector_.clear();
|
||||||
|
file.close();
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
style.defined.textAlign = (definedBits & 1 << 0) != 0;
|
||||||
|
style.defined.fontStyle = (definedBits & 1 << 1) != 0;
|
||||||
|
style.defined.fontWeight = (definedBits & 1 << 2) != 0;
|
||||||
|
style.defined.textDecoration = (definedBits & 1 << 3) != 0;
|
||||||
|
style.defined.textIndent = (definedBits & 1 << 4) != 0;
|
||||||
|
style.defined.marginTop = (definedBits & 1 << 5) != 0;
|
||||||
|
style.defined.marginBottom = (definedBits & 1 << 6) != 0;
|
||||||
|
style.defined.marginLeft = (definedBits & 1 << 7) != 0;
|
||||||
|
style.defined.marginRight = (definedBits & 1 << 8) != 0;
|
||||||
|
style.defined.paddingTop = (definedBits & 1 << 9) != 0;
|
||||||
|
style.defined.paddingBottom = (definedBits & 1 << 10) != 0;
|
||||||
|
style.defined.paddingLeft = (definedBits & 1 << 11) != 0;
|
||||||
|
style.defined.paddingRight = (definedBits & 1 << 12) != 0;
|
||||||
|
|
||||||
|
rulesBySelector_[selector] = style;
|
||||||
|
}
|
||||||
|
|
||||||
|
LOG_DBG("CSS", "Loaded %u rules from cache", ruleCount);
|
||||||
|
file.close();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
122
lib/Epub/Epub/css/CssParser.h
Normal file
122
lib/Epub/Epub/css/CssParser.h
Normal file
@@ -0,0 +1,122 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <HalStorage.h>
|
||||||
|
|
||||||
|
#include <string>
|
||||||
|
#include <unordered_map>
|
||||||
|
#include <utility>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
#include "CssStyle.h"
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Lightweight CSS parser for EPUB stylesheets
|
||||||
|
*
|
||||||
|
* Parses CSS files and extracts styling information relevant for e-ink display.
|
||||||
|
* Uses a two-phase approach: first tokenizes the CSS content, then builds
|
||||||
|
* a rule database that can be queried during HTML parsing.
|
||||||
|
*
|
||||||
|
* Supported selectors:
|
||||||
|
* - Element selectors: p, div, h1, etc.
|
||||||
|
* - Class selectors: .classname
|
||||||
|
* - Combined: element.classname
|
||||||
|
* - Grouped: selector1, selector2 { }
|
||||||
|
*
|
||||||
|
* Not supported (silently ignored):
|
||||||
|
* - Descendant/child selectors
|
||||||
|
* - Pseudo-classes and pseudo-elements
|
||||||
|
* - Media queries (content is skipped)
|
||||||
|
* - @import, @font-face, etc.
|
||||||
|
*/
|
||||||
|
class CssParser {
|
||||||
|
public:
|
||||||
|
explicit CssParser(std::string cachePath) : cachePath(std::move(cachePath)) {}
|
||||||
|
~CssParser() = default;
|
||||||
|
|
||||||
|
// Non-copyable
|
||||||
|
CssParser(const CssParser&) = delete;
|
||||||
|
CssParser& operator=(const CssParser&) = delete;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Load and parse CSS from a file stream.
|
||||||
|
* Can be called multiple times to accumulate rules from multiple stylesheets.
|
||||||
|
* @param source Open file handle to read from
|
||||||
|
* @return true if parsing completed (even if no rules found)
|
||||||
|
*/
|
||||||
|
bool loadFromStream(FsFile& source);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Look up the style for an HTML element, considering tag name and class attributes.
|
||||||
|
* Applies CSS cascade: element style < class style < element.class style
|
||||||
|
*
|
||||||
|
* @param tagName The HTML element name (e.g., "p", "div")
|
||||||
|
* @param classAttr The class attribute value (may contain multiple space-separated classes)
|
||||||
|
* @return Combined style with all applicable rules merged
|
||||||
|
*/
|
||||||
|
[[nodiscard]] CssStyle resolveStyle(const std::string& tagName, const std::string& classAttr) const;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parse an inline style attribute string.
|
||||||
|
* @param styleValue The value of a style="" attribute
|
||||||
|
* @return Parsed style properties
|
||||||
|
*/
|
||||||
|
[[nodiscard]] static CssStyle parseInlineStyle(const std::string& styleValue);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check if any rules have been loaded
|
||||||
|
*/
|
||||||
|
[[nodiscard]] bool empty() const { return rulesBySelector_.empty(); }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get count of loaded rule sets
|
||||||
|
*/
|
||||||
|
[[nodiscard]] size_t ruleCount() const { return rulesBySelector_.size(); }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Clear all loaded rules
|
||||||
|
*/
|
||||||
|
void clear() { rulesBySelector_.clear(); }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check if CSS rules cache file exists
|
||||||
|
*/
|
||||||
|
bool hasCache() const;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Save parsed CSS rules to a cache file.
|
||||||
|
* @return true if cache was written successfully
|
||||||
|
*/
|
||||||
|
bool saveToCache() const;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Load CSS rules from a cache file.
|
||||||
|
* Clears any existing rules before loading.
|
||||||
|
* @return true if cache was loaded successfully
|
||||||
|
*/
|
||||||
|
bool loadFromCache();
|
||||||
|
|
||||||
|
private:
|
||||||
|
// Storage: maps normalized selector -> style properties
|
||||||
|
std::unordered_map<std::string, CssStyle> rulesBySelector_;
|
||||||
|
|
||||||
|
std::string cachePath;
|
||||||
|
|
||||||
|
// Internal parsing helpers
|
||||||
|
void processRuleBlockWithStyle(const std::string& selectorGroup, const CssStyle& style);
|
||||||
|
static CssStyle parseDeclarations(const std::string& declBlock);
|
||||||
|
static void parseDeclarationIntoStyle(const std::string& decl, CssStyle& style, std::string& propNameBuf,
|
||||||
|
std::string& propValueBuf);
|
||||||
|
|
||||||
|
// Individual property value parsers
|
||||||
|
static CssTextAlign interpretAlignment(const std::string& val);
|
||||||
|
static CssFontStyle interpretFontStyle(const std::string& val);
|
||||||
|
static CssFontWeight interpretFontWeight(const std::string& val);
|
||||||
|
static CssTextDecoration interpretDecoration(const std::string& val);
|
||||||
|
static CssLength interpretLength(const std::string& val);
|
||||||
|
|
||||||
|
// String utilities
|
||||||
|
static std::string normalized(const std::string& s);
|
||||||
|
static void normalizedInto(const std::string& s, std::string& out);
|
||||||
|
static std::vector<std::string> splitOnChar(const std::string& s, char delimiter);
|
||||||
|
static std::vector<std::string> splitWhitespace(const std::string& s);
|
||||||
|
};
|
||||||
212
lib/Epub/Epub/css/CssStyle.h
Normal file
212
lib/Epub/Epub/css/CssStyle.h
Normal file
@@ -0,0 +1,212 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <cstdint>
|
||||||
|
|
||||||
|
// Matches order of PARAGRAPH_ALIGNMENT in CrossPointSettings
|
||||||
|
enum class CssTextAlign : uint8_t { Justify = 0, Left = 1, Center = 2, Right = 3, None = 4 };
|
||||||
|
enum class CssUnit : uint8_t { Pixels = 0, Em = 1, Rem = 2, Points = 3, Percent = 4 };
|
||||||
|
|
||||||
|
// Represents a CSS length value with its unit, allowing deferred resolution to pixels
|
||||||
|
struct CssLength {
|
||||||
|
float value = 0.0f;
|
||||||
|
CssUnit unit = CssUnit::Pixels;
|
||||||
|
|
||||||
|
CssLength() = default;
|
||||||
|
CssLength(const float v, const CssUnit u) : value(v), unit(u) {}
|
||||||
|
|
||||||
|
// Convenience constructor for pixel values (most common case)
|
||||||
|
explicit CssLength(const float pixels) : value(pixels) {}
|
||||||
|
|
||||||
|
// Returns true if this length can be resolved to pixels with the given context.
|
||||||
|
// Percentage units require a non-zero containerWidth to resolve.
|
||||||
|
[[nodiscard]] bool isResolvable(const float containerWidth = 0) const {
|
||||||
|
return unit != CssUnit::Percent || containerWidth > 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Resolve to pixels given the current em size (font line height)
|
||||||
|
// containerWidth is needed for percentage units (e.g. viewport width)
|
||||||
|
[[nodiscard]] float toPixels(const float emSize, const float containerWidth = 0) const {
|
||||||
|
switch (unit) {
|
||||||
|
case CssUnit::Em:
|
||||||
|
case CssUnit::Rem:
|
||||||
|
return value * emSize;
|
||||||
|
case CssUnit::Points:
|
||||||
|
return value * 1.33f; // Approximate pt to px conversion
|
||||||
|
case CssUnit::Percent:
|
||||||
|
return value * containerWidth / 100.0f;
|
||||||
|
default:
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Resolve to int16_t pixels (for BlockStyle fields)
|
||||||
|
[[nodiscard]] int16_t toPixelsInt16(const float emSize, const float containerWidth = 0) const {
|
||||||
|
return static_cast<int16_t>(toPixels(emSize, containerWidth));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Font style options matching CSS font-style property
|
||||||
|
enum class CssFontStyle : uint8_t { Normal = 0, Italic = 1 };
|
||||||
|
|
||||||
|
// Font weight options - CSS supports 100-900, we simplify to normal/bold
|
||||||
|
enum class CssFontWeight : uint8_t { Normal = 0, Bold = 1 };
|
||||||
|
|
||||||
|
// Text decoration options
|
||||||
|
enum class CssTextDecoration : uint8_t { None = 0, Underline = 1 };
|
||||||
|
|
||||||
|
// Bitmask for tracking which properties have been explicitly set
|
||||||
|
struct CssPropertyFlags {
|
||||||
|
uint16_t textAlign : 1;
|
||||||
|
uint16_t fontStyle : 1;
|
||||||
|
uint16_t fontWeight : 1;
|
||||||
|
uint16_t textDecoration : 1;
|
||||||
|
uint16_t textIndent : 1;
|
||||||
|
uint16_t marginTop : 1;
|
||||||
|
uint16_t marginBottom : 1;
|
||||||
|
uint16_t marginLeft : 1;
|
||||||
|
uint16_t marginRight : 1;
|
||||||
|
uint16_t paddingTop : 1;
|
||||||
|
uint16_t paddingBottom : 1;
|
||||||
|
uint16_t paddingLeft : 1;
|
||||||
|
uint16_t paddingRight : 1;
|
||||||
|
uint16_t width : 1;
|
||||||
|
|
||||||
|
CssPropertyFlags()
|
||||||
|
: textAlign(0),
|
||||||
|
fontStyle(0),
|
||||||
|
fontWeight(0),
|
||||||
|
textDecoration(0),
|
||||||
|
textIndent(0),
|
||||||
|
marginTop(0),
|
||||||
|
marginBottom(0),
|
||||||
|
marginLeft(0),
|
||||||
|
marginRight(0),
|
||||||
|
paddingTop(0),
|
||||||
|
paddingBottom(0),
|
||||||
|
paddingLeft(0),
|
||||||
|
paddingRight(0),
|
||||||
|
width(0) {}
|
||||||
|
|
||||||
|
[[nodiscard]] bool anySet() const {
|
||||||
|
return textAlign || fontStyle || fontWeight || textDecoration || textIndent || marginTop || marginBottom ||
|
||||||
|
marginLeft || marginRight || paddingTop || paddingBottom || paddingLeft || paddingRight || width;
|
||||||
|
}
|
||||||
|
|
||||||
|
void clearAll() {
|
||||||
|
textAlign = fontStyle = fontWeight = textDecoration = textIndent = 0;
|
||||||
|
marginTop = marginBottom = marginLeft = marginRight = 0;
|
||||||
|
paddingTop = paddingBottom = paddingLeft = paddingRight = 0;
|
||||||
|
width = 0;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Represents a collection of CSS style properties
|
||||||
|
// Only stores properties relevant to e-ink text rendering
|
||||||
|
// Length values are stored as CssLength (value + unit) for deferred resolution
|
||||||
|
struct CssStyle {
|
||||||
|
CssTextAlign textAlign = CssTextAlign::Left;
|
||||||
|
CssFontStyle fontStyle = CssFontStyle::Normal;
|
||||||
|
CssFontWeight fontWeight = CssFontWeight::Normal;
|
||||||
|
CssTextDecoration textDecoration = CssTextDecoration::None;
|
||||||
|
|
||||||
|
CssLength textIndent; // First-line indent (deferred resolution)
|
||||||
|
CssLength marginTop; // Vertical spacing before block
|
||||||
|
CssLength marginBottom; // Vertical spacing after block
|
||||||
|
CssLength marginLeft; // Horizontal spacing left of block
|
||||||
|
CssLength marginRight; // Horizontal spacing right of block
|
||||||
|
CssLength paddingTop; // Padding before
|
||||||
|
CssLength paddingBottom; // Padding after
|
||||||
|
CssLength paddingLeft; // Padding left
|
||||||
|
CssLength paddingRight; // Padding right
|
||||||
|
CssLength width; // Element width (used for table columns/cells)
|
||||||
|
|
||||||
|
CssPropertyFlags defined; // Tracks which properties were explicitly set
|
||||||
|
|
||||||
|
// Apply properties from another style, only overwriting if the other style
|
||||||
|
// has that property explicitly defined
|
||||||
|
void applyOver(const CssStyle& base) {
|
||||||
|
if (base.hasTextAlign()) {
|
||||||
|
textAlign = base.textAlign;
|
||||||
|
defined.textAlign = 1;
|
||||||
|
}
|
||||||
|
if (base.hasFontStyle()) {
|
||||||
|
fontStyle = base.fontStyle;
|
||||||
|
defined.fontStyle = 1;
|
||||||
|
}
|
||||||
|
if (base.hasFontWeight()) {
|
||||||
|
fontWeight = base.fontWeight;
|
||||||
|
defined.fontWeight = 1;
|
||||||
|
}
|
||||||
|
if (base.hasTextDecoration()) {
|
||||||
|
textDecoration = base.textDecoration;
|
||||||
|
defined.textDecoration = 1;
|
||||||
|
}
|
||||||
|
if (base.hasTextIndent()) {
|
||||||
|
textIndent = base.textIndent;
|
||||||
|
defined.textIndent = 1;
|
||||||
|
}
|
||||||
|
if (base.hasMarginTop()) {
|
||||||
|
marginTop = base.marginTop;
|
||||||
|
defined.marginTop = 1;
|
||||||
|
}
|
||||||
|
if (base.hasMarginBottom()) {
|
||||||
|
marginBottom = base.marginBottom;
|
||||||
|
defined.marginBottom = 1;
|
||||||
|
}
|
||||||
|
if (base.hasMarginLeft()) {
|
||||||
|
marginLeft = base.marginLeft;
|
||||||
|
defined.marginLeft = 1;
|
||||||
|
}
|
||||||
|
if (base.hasMarginRight()) {
|
||||||
|
marginRight = base.marginRight;
|
||||||
|
defined.marginRight = 1;
|
||||||
|
}
|
||||||
|
if (base.hasPaddingTop()) {
|
||||||
|
paddingTop = base.paddingTop;
|
||||||
|
defined.paddingTop = 1;
|
||||||
|
}
|
||||||
|
if (base.hasPaddingBottom()) {
|
||||||
|
paddingBottom = base.paddingBottom;
|
||||||
|
defined.paddingBottom = 1;
|
||||||
|
}
|
||||||
|
if (base.hasPaddingLeft()) {
|
||||||
|
paddingLeft = base.paddingLeft;
|
||||||
|
defined.paddingLeft = 1;
|
||||||
|
}
|
||||||
|
if (base.hasPaddingRight()) {
|
||||||
|
paddingRight = base.paddingRight;
|
||||||
|
defined.paddingRight = 1;
|
||||||
|
}
|
||||||
|
if (base.hasWidth()) {
|
||||||
|
width = base.width;
|
||||||
|
defined.width = 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] bool hasTextAlign() const { return defined.textAlign; }
|
||||||
|
[[nodiscard]] bool hasFontStyle() const { return defined.fontStyle; }
|
||||||
|
[[nodiscard]] bool hasFontWeight() const { return defined.fontWeight; }
|
||||||
|
[[nodiscard]] bool hasTextDecoration() const { return defined.textDecoration; }
|
||||||
|
[[nodiscard]] bool hasTextIndent() const { return defined.textIndent; }
|
||||||
|
[[nodiscard]] bool hasMarginTop() const { return defined.marginTop; }
|
||||||
|
[[nodiscard]] bool hasMarginBottom() const { return defined.marginBottom; }
|
||||||
|
[[nodiscard]] bool hasMarginLeft() const { return defined.marginLeft; }
|
||||||
|
[[nodiscard]] bool hasMarginRight() const { return defined.marginRight; }
|
||||||
|
[[nodiscard]] bool hasPaddingTop() const { return defined.paddingTop; }
|
||||||
|
[[nodiscard]] bool hasPaddingBottom() const { return defined.paddingBottom; }
|
||||||
|
[[nodiscard]] bool hasPaddingLeft() const { return defined.paddingLeft; }
|
||||||
|
[[nodiscard]] bool hasPaddingRight() const { return defined.paddingRight; }
|
||||||
|
[[nodiscard]] bool hasWidth() const { return defined.width; }
|
||||||
|
|
||||||
|
void reset() {
|
||||||
|
textAlign = CssTextAlign::Left;
|
||||||
|
fontStyle = CssFontStyle::Normal;
|
||||||
|
fontWeight = CssFontWeight::Normal;
|
||||||
|
textDecoration = CssTextDecoration::None;
|
||||||
|
textIndent = CssLength{};
|
||||||
|
marginTop = marginBottom = marginLeft = marginRight = CssLength{};
|
||||||
|
paddingTop = paddingBottom = paddingLeft = paddingRight = CssLength{};
|
||||||
|
width = CssLength{};
|
||||||
|
defined.clearAll();
|
||||||
|
}
|
||||||
|
};
|
||||||
76
lib/Epub/Epub/htmlEntities.cpp
Normal file
76
lib/Epub/Epub/htmlEntities.cpp
Normal file
@@ -0,0 +1,76 @@
|
|||||||
|
// from
|
||||||
|
// https://github.com/atomic14/diy-esp32-epub-reader/blob/2c2f57fdd7e2a788d14a0bcb26b9e845a47aac42/lib/Epub/RubbishHtmlParser/htmlEntities.cpp
|
||||||
|
|
||||||
|
#include "htmlEntities.h"
|
||||||
|
|
||||||
|
#include <cstring>
|
||||||
|
|
||||||
|
struct EntityPair {
|
||||||
|
const char* key;
|
||||||
|
const char* value;
|
||||||
|
};
|
||||||
|
|
||||||
|
static const EntityPair ENTITY_LOOKUP[] = {
|
||||||
|
{""", "\""}, {"⁄", "⁄"}, {"&", "&"}, {"<", "<"}, {">", ">"},
|
||||||
|
{"À", "À"}, {"Á", "Á"}, {"Â", "Â"}, {"Ã", "Ã"}, {"Ä", "Ä"},
|
||||||
|
{"Å", "Å"}, {"Æ", "Æ"}, {"Ç", "Ç"}, {"È", "È"}, {"É", "É"},
|
||||||
|
{"Ê", "Ê"}, {"Ë", "Ë"}, {"Ì", "Ì"}, {"Í", "Í"}, {"Î", "Î"},
|
||||||
|
{"Ï", "Ï"}, {"Ð", "Ð"}, {"Ñ", "Ñ"}, {"Ò", "Ò"}, {"Ó", "Ó"},
|
||||||
|
{"Ô", "Ô"}, {"Õ", "Õ"}, {"Ö", "Ö"}, {"Ø", "Ø"}, {"Ù", "Ù"},
|
||||||
|
{"Ú", "Ú"}, {"Û", "Û"}, {"Ü", "Ü"}, {"Ý", "Ý"}, {"Þ", "Þ"},
|
||||||
|
{"ß", "ß"}, {"à", "à"}, {"á", "á"}, {"â", "â"}, {"ã", "ã"},
|
||||||
|
{"ä", "ä"}, {"å", "å"}, {"æ", "æ"}, {"ç", "ç"}, {"è", "è"},
|
||||||
|
{"é", "é"}, {"ê", "ê"}, {"ë", "ë"}, {"ì", "ì"}, {"í", "í"},
|
||||||
|
{"î", "î"}, {"ï", "ï"}, {"ð", "ð"}, {"ñ", "ñ"}, {"ò", "ò"},
|
||||||
|
{"ó", "ó"}, {"ô", "ô"}, {"õ", "õ"}, {"ö", "ö"}, {"ø", "ø"},
|
||||||
|
{"ù", "ù"}, {"ú", "ú"}, {"û", "û"}, {"ü", "ü"}, {"ý", "ý"},
|
||||||
|
{"þ", "þ"}, {"ÿ", "ÿ"}, {" ", "\xC2\xA0"}, {"¡", "¡"}, {"¢", "¢"},
|
||||||
|
{"£", "£"}, {"¤", "¤"}, {"¥", "¥"}, {"¦", "¦"}, {"§", "§"},
|
||||||
|
{"¨", "¨"}, {"©", "©"}, {"ª", "ª"}, {"«", "«"}, {"¬", "¬"},
|
||||||
|
{"­", ""}, {"®", "®"}, {"¯", "¯"}, {"°", "°"}, {"±", "±"},
|
||||||
|
{"²", "²"}, {"³", "³"}, {"´", "´"}, {"µ", "µ"}, {"¶", "¶"},
|
||||||
|
{"¸", "¸"}, {"¹", "¹"}, {"º", "º"}, {"»", "»"}, {"¼", "¼"},
|
||||||
|
{"½", "½"}, {"¾", "¾"}, {"¿", "¿"}, {"×", "×"}, {"÷", "÷"},
|
||||||
|
{"∀", "∀"}, {"∂", "∂"}, {"∃", "∃"}, {"∅", "∅"}, {"∇", "∇"},
|
||||||
|
{"∈", "∈"}, {"∉", "∉"}, {"∋", "∋"}, {"∏", "∏"}, {"∑", "∑"},
|
||||||
|
{"−", "−"}, {"∗", "∗"}, {"√", "√"}, {"∝", "∝"}, {"∞", "∞"},
|
||||||
|
{"∠", "∠"}, {"∧", "∧"}, {"∨", "∨"}, {"∩", "∩"}, {"∪", "∪"},
|
||||||
|
{"∫", "∫"}, {"∴", "∴"}, {"∼", "∼"}, {"≅", "≅"}, {"≈", "≈"},
|
||||||
|
{"≠", "≠"}, {"≡", "≡"}, {"≤", "≤"}, {"≥", "≥"}, {"⊂", "⊂"},
|
||||||
|
{"⊃", "⊃"}, {"⊄", "⊄"}, {"⊆", "⊆"}, {"⊇", "⊇"}, {"⊕", "⊕"},
|
||||||
|
{"⊗", "⊗"}, {"⊥", "⊥"}, {"⋅", "⋅"}, {"Α", "Α"}, {"Β", "Β"},
|
||||||
|
{"Γ", "Γ"}, {"Δ", "Δ"}, {"Ε", "Ε"}, {"Ζ", "Ζ"}, {"Η", "Η"},
|
||||||
|
{"Θ", "Θ"}, {"Ι", "Ι"}, {"Κ", "Κ"}, {"Λ", "Λ"}, {"Μ", "Μ"},
|
||||||
|
{"Ν", "Ν"}, {"Ξ", "Ξ"}, {"Ο", "Ο"}, {"Π", "Π"}, {"Ρ", "Ρ"},
|
||||||
|
{"Σ", "Σ"}, {"Τ", "Τ"}, {"Υ", "Υ"}, {"Φ", "Φ"}, {"Χ", "Χ"},
|
||||||
|
{"Ψ", "Ψ"}, {"Ω", "Ω"}, {"α", "α"}, {"β", "β"}, {"γ", "γ"},
|
||||||
|
{"δ", "δ"}, {"ε", "ε"}, {"ζ", "ζ"}, {"η", "η"}, {"θ", "θ"},
|
||||||
|
{"ι", "ι"}, {"κ", "κ"}, {"λ", "λ"}, {"μ", "μ"}, {"ν", "ν"},
|
||||||
|
{"ξ", "ξ"}, {"ο", "ο"}, {"π", "π"}, {"ρ", "ρ"}, {"ς", "ς"},
|
||||||
|
{"σ", "σ"}, {"τ", "τ"}, {"υ", "υ"}, {"φ", "φ"}, {"χ", "χ"},
|
||||||
|
{"ψ", "ψ"}, {"ω", "ω"}, {"ϑ", "ϑ"}, {"ϒ", "ϒ"}, {"ϖ", "ϖ"},
|
||||||
|
{"Œ", "Œ"}, {"œ", "œ"}, {"Š", "Š"}, {"š", "š"}, {"Ÿ", "Ÿ"},
|
||||||
|
{"ƒ", "ƒ"}, {"ˆ", "ˆ"}, {"˜", "˜"}, {" ", " "}, {" ", " "},
|
||||||
|
{" ", " "}, {"‌", ""}, {"‍", ""}, {"‎", ""}, {"‏", ""},
|
||||||
|
{"–", "–"}, {"—", "—"}, {"‘", "‘"}, {"’", "’"}, {"‚", "‚"},
|
||||||
|
{"“", "“"}, {"”", "”"}, {"„", "„"}, {"†", "†"}, {"‡", "‡"},
|
||||||
|
{"•", "•"}, {"…", "…"}, {"‰", "‰"}, {"′", "′"}, {"″", "″"},
|
||||||
|
{"‹", "‹"}, {"›", "›"}, {"‾", "‾"}, {"€", "€"}, {"™", "™"},
|
||||||
|
{"←", "←"}, {"↑", "↑"}, {"→", "→"}, {"↓", "↓"}, {"↔", "↔"},
|
||||||
|
{"↵", "↵"}, {"⌈", "⌈"}, {"⌉", "⌉"}, {"⌊", "⌊"}, {"⌋", "⌋"},
|
||||||
|
{"◊", "◊"}, {"♠", "♠"}, {"♣", "♣"}, {"♥", "♥"}, {"♦", "♦"}};
|
||||||
|
|
||||||
|
static const size_t ENTITY_LOOKUP_COUNT = sizeof(ENTITY_LOOKUP) / sizeof(ENTITY_LOOKUP[0]);
|
||||||
|
|
||||||
|
// Lookup a single HTML entity and return its UTF-8 value
|
||||||
|
const char* lookupHtmlEntity(const char* entity, int len) {
|
||||||
|
for (size_t i = 0; i < ENTITY_LOOKUP_COUNT; i++) {
|
||||||
|
const char* key = ENTITY_LOOKUP[i].key;
|
||||||
|
const size_t keyLen = strlen(key);
|
||||||
|
if (static_cast<size_t>(len) == keyLen && memcmp(entity, key, keyLen) == 0) {
|
||||||
|
return ENTITY_LOOKUP[i].value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nullptr; // Entity not found
|
||||||
|
}
|
||||||
9
lib/Epub/Epub/htmlEntities.h
Normal file
9
lib/Epub/Epub/htmlEntities.h
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
// from
|
||||||
|
// https://github.com/atomic14/diy-esp32-epub-reader/blob/2c2f57fdd7e2a788d14a0bcb26b9e845a47aac42/lib/Epub/RubbishHtmlParser/htmlEntities.cpp
|
||||||
|
|
||||||
|
#pragma once
|
||||||
|
#include <string>
|
||||||
|
|
||||||
|
// Lookup a single HTML entity (including & and ;) and return its UTF-8 value
|
||||||
|
// Returns nullptr if entity is not found
|
||||||
|
const char* lookupHtmlEntity(const char* entity, int len);
|
||||||
@@ -1,45 +1,84 @@
|
|||||||
#include "LanguageRegistry.h"
|
#include "LanguageRegistry.h"
|
||||||
|
|
||||||
#include <algorithm>
|
#include <algorithm>
|
||||||
#include <array>
|
#include <vector>
|
||||||
|
|
||||||
#include "HyphenationCommon.h"
|
#include "HyphenationCommon.h"
|
||||||
|
#ifndef OMIT_HYPH_DE
|
||||||
#include "generated/hyph-de.trie.h"
|
#include "generated/hyph-de.trie.h"
|
||||||
|
#endif
|
||||||
|
#ifndef OMIT_HYPH_EN
|
||||||
#include "generated/hyph-en.trie.h"
|
#include "generated/hyph-en.trie.h"
|
||||||
|
#endif
|
||||||
|
#ifndef OMIT_HYPH_ES
|
||||||
#include "generated/hyph-es.trie.h"
|
#include "generated/hyph-es.trie.h"
|
||||||
|
#endif
|
||||||
|
#ifndef OMIT_HYPH_FR
|
||||||
#include "generated/hyph-fr.trie.h"
|
#include "generated/hyph-fr.trie.h"
|
||||||
|
#endif
|
||||||
|
#ifndef OMIT_HYPH_IT
|
||||||
|
#include "generated/hyph-it.trie.h"
|
||||||
|
#endif
|
||||||
|
#ifndef OMIT_HYPH_RU
|
||||||
#include "generated/hyph-ru.trie.h"
|
#include "generated/hyph-ru.trie.h"
|
||||||
|
#endif
|
||||||
|
|
||||||
namespace {
|
namespace {
|
||||||
|
|
||||||
|
#ifndef OMIT_HYPH_EN
|
||||||
// English hyphenation patterns (3/3 minimum prefix/suffix length)
|
// English hyphenation patterns (3/3 minimum prefix/suffix length)
|
||||||
LanguageHyphenator englishHyphenator(en_us_patterns, isLatinLetter, toLowerLatin, 3, 3);
|
LanguageHyphenator englishHyphenator(en_us_patterns, isLatinLetter, toLowerLatin, 3, 3);
|
||||||
|
#endif
|
||||||
|
#ifndef OMIT_HYPH_FR
|
||||||
LanguageHyphenator frenchHyphenator(fr_patterns, isLatinLetter, toLowerLatin);
|
LanguageHyphenator frenchHyphenator(fr_patterns, isLatinLetter, toLowerLatin);
|
||||||
|
#endif
|
||||||
|
#ifndef OMIT_HYPH_DE
|
||||||
LanguageHyphenator germanHyphenator(de_patterns, isLatinLetter, toLowerLatin);
|
LanguageHyphenator germanHyphenator(de_patterns, isLatinLetter, toLowerLatin);
|
||||||
|
#endif
|
||||||
|
#ifndef OMIT_HYPH_RU
|
||||||
LanguageHyphenator russianHyphenator(ru_ru_patterns, isCyrillicLetter, toLowerCyrillic);
|
LanguageHyphenator russianHyphenator(ru_ru_patterns, isCyrillicLetter, toLowerCyrillic);
|
||||||
|
#endif
|
||||||
|
#ifndef OMIT_HYPH_ES
|
||||||
LanguageHyphenator spanishHyphenator(es_patterns, isLatinLetter, toLowerLatin);
|
LanguageHyphenator spanishHyphenator(es_patterns, isLatinLetter, toLowerLatin);
|
||||||
|
#endif
|
||||||
|
#ifndef OMIT_HYPH_IT
|
||||||
|
LanguageHyphenator italianHyphenator(it_patterns, isLatinLetter, toLowerLatin);
|
||||||
|
#endif
|
||||||
|
|
||||||
using EntryArray = std::array<LanguageEntry, 5>;
|
const LanguageEntryView entries() {
|
||||||
|
static const std::vector<LanguageEntry> kEntries = {
|
||||||
const EntryArray& entries() {
|
#ifndef OMIT_HYPH_EN
|
||||||
static const EntryArray kEntries = {{{"english", "en", &englishHyphenator},
|
{"english", "en", &englishHyphenator},
|
||||||
|
#endif
|
||||||
|
#ifndef OMIT_HYPH_FR
|
||||||
{"french", "fr", &frenchHyphenator},
|
{"french", "fr", &frenchHyphenator},
|
||||||
|
#endif
|
||||||
|
#ifndef OMIT_HYPH_DE
|
||||||
{"german", "de", &germanHyphenator},
|
{"german", "de", &germanHyphenator},
|
||||||
|
#endif
|
||||||
|
#ifndef OMIT_HYPH_RU
|
||||||
{"russian", "ru", &russianHyphenator},
|
{"russian", "ru", &russianHyphenator},
|
||||||
{"spanish", "es", &spanishHyphenator}}};
|
#endif
|
||||||
return kEntries;
|
#ifndef OMIT_HYPH_ES
|
||||||
|
{"spanish", "es", &spanishHyphenator},
|
||||||
|
#endif
|
||||||
|
#ifndef OMIT_HYPH_IT
|
||||||
|
{"italian", "it", &italianHyphenator},
|
||||||
|
#endif
|
||||||
|
};
|
||||||
|
static const LanguageEntryView view{kEntries.data(), kEntries.size()};
|
||||||
|
return view;
|
||||||
}
|
}
|
||||||
|
|
||||||
} // namespace
|
} // namespace
|
||||||
|
|
||||||
const LanguageHyphenator* getLanguageHyphenatorForPrimaryTag(const std::string& primaryTag) {
|
const LanguageHyphenator* getLanguageHyphenatorForPrimaryTag(const std::string& primaryTag) {
|
||||||
const auto& allEntries = entries();
|
const auto allEntries = entries();
|
||||||
const auto it = std::find_if(allEntries.begin(), allEntries.end(),
|
const auto it = std::find_if(allEntries.begin(), allEntries.end(),
|
||||||
[&primaryTag](const LanguageEntry& entry) { return primaryTag == entry.primaryTag; });
|
[&primaryTag](const LanguageEntry& entry) { return primaryTag == entry.primaryTag; });
|
||||||
return (it != allEntries.end()) ? it->hyphenator : nullptr;
|
return (it != allEntries.end()) ? it->hyphenator : nullptr;
|
||||||
}
|
}
|
||||||
|
|
||||||
LanguageEntryView getLanguageEntries() {
|
LanguageEntryView getLanguageEntries() {
|
||||||
const auto& allEntries = entries();
|
return entries();
|
||||||
return LanguageEntryView{allEntries.data(), allEntries.size()};
|
|
||||||
}
|
}
|
||||||
|
|||||||
113
lib/Epub/Epub/hyphenation/generated/hyph-it.trie.h
Normal file
113
lib/Epub/Epub/hyphenation/generated/hyph-it.trie.h
Normal 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),
|
||||||
|
};
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -7,26 +7,35 @@
|
|||||||
#include <memory>
|
#include <memory>
|
||||||
|
|
||||||
#include "../ParsedText.h"
|
#include "../ParsedText.h"
|
||||||
|
#include "../TableData.h"
|
||||||
|
#include "../blocks/ImageBlock.h"
|
||||||
#include "../blocks/TextBlock.h"
|
#include "../blocks/TextBlock.h"
|
||||||
|
#include "../css/CssParser.h"
|
||||||
|
#include "../css/CssStyle.h"
|
||||||
|
|
||||||
class Page;
|
class Page;
|
||||||
|
class PageTableRow;
|
||||||
class GfxRenderer;
|
class GfxRenderer;
|
||||||
|
class Epub;
|
||||||
|
|
||||||
#define MAX_WORD_SIZE 200
|
#define MAX_WORD_SIZE 200
|
||||||
|
|
||||||
class ChapterHtmlSlimParser {
|
class ChapterHtmlSlimParser {
|
||||||
|
std::shared_ptr<Epub> epub;
|
||||||
const std::string& filepath;
|
const std::string& filepath;
|
||||||
GfxRenderer& renderer;
|
GfxRenderer& renderer;
|
||||||
std::function<void(std::unique_ptr<Page>)> completePageFn;
|
std::function<void(std::unique_ptr<Page>)> completePageFn;
|
||||||
std::function<void(int)> progressFn; // Progress callback (0-100)
|
std::function<void()> popupFn; // Popup callback
|
||||||
int depth = 0;
|
int depth = 0;
|
||||||
int skipUntilDepth = INT_MAX;
|
int skipUntilDepth = INT_MAX;
|
||||||
int boldUntilDepth = INT_MAX;
|
int boldUntilDepth = INT_MAX;
|
||||||
int italicUntilDepth = INT_MAX;
|
int italicUntilDepth = INT_MAX;
|
||||||
|
int underlineUntilDepth = INT_MAX;
|
||||||
// buffer for building up words from characters, will auto break if longer than this
|
// buffer for building up words from characters, will auto break if longer than this
|
||||||
// leave one char at end for null pointer
|
// leave one char at end for null pointer
|
||||||
char partWordBuffer[MAX_WORD_SIZE + 1] = {};
|
char partWordBuffer[MAX_WORD_SIZE + 1] = {};
|
||||||
int partWordBufferIndex = 0;
|
int partWordBufferIndex = 0;
|
||||||
|
bool nextWordContinues = false; // true when next flushed word attaches to previous (inline element boundary)
|
||||||
std::unique_ptr<ParsedText> currentTextBlock = nullptr;
|
std::unique_ptr<ParsedText> currentTextBlock = nullptr;
|
||||||
std::unique_ptr<Page> currentPage = nullptr;
|
std::unique_ptr<Page> currentPage = nullptr;
|
||||||
int16_t currentPageNextY = 0;
|
int16_t currentPageNextY = 0;
|
||||||
@@ -37,23 +46,53 @@ class ChapterHtmlSlimParser {
|
|||||||
uint16_t viewportWidth;
|
uint16_t viewportWidth;
|
||||||
uint16_t viewportHeight;
|
uint16_t viewportHeight;
|
||||||
bool hyphenationEnabled;
|
bool hyphenationEnabled;
|
||||||
|
const CssParser* cssParser;
|
||||||
|
bool embeddedStyle;
|
||||||
|
std::string contentBase;
|
||||||
|
std::string imageBasePath;
|
||||||
|
int imageCounter = 0;
|
||||||
|
|
||||||
void startNewTextBlock(TextBlock::Style style);
|
// Style tracking (replaces depth-based approach)
|
||||||
|
struct StyleStackEntry {
|
||||||
|
int depth = 0;
|
||||||
|
bool hasBold = false, bold = false;
|
||||||
|
bool hasItalic = false, italic = false;
|
||||||
|
bool hasUnderline = false, underline = false;
|
||||||
|
};
|
||||||
|
std::vector<StyleStackEntry> inlineStyleStack;
|
||||||
|
CssStyle currentCssStyle;
|
||||||
|
bool effectiveBold = false;
|
||||||
|
bool effectiveItalic = false;
|
||||||
|
bool effectiveUnderline = false;
|
||||||
|
|
||||||
|
// Table buffering state
|
||||||
|
bool inTable = false;
|
||||||
|
std::unique_ptr<TableData> tableData;
|
||||||
|
|
||||||
|
void updateEffectiveInlineStyle();
|
||||||
|
void startNewTextBlock(const BlockStyle& blockStyle);
|
||||||
void flushPartWordBuffer();
|
void flushPartWordBuffer();
|
||||||
void makePages();
|
void makePages();
|
||||||
|
void processTable();
|
||||||
|
void addTableRowToPage(std::shared_ptr<PageTableRow> row);
|
||||||
// XML callbacks
|
// XML callbacks
|
||||||
static void XMLCALL startElement(void* userData, const XML_Char* name, const XML_Char** atts);
|
static void XMLCALL startElement(void* userData, const XML_Char* name, const XML_Char** atts);
|
||||||
static void XMLCALL characterData(void* userData, const XML_Char* s, int len);
|
static void XMLCALL characterData(void* userData, const XML_Char* s, int len);
|
||||||
|
static void XMLCALL defaultHandlerExpand(void* userData, const XML_Char* s, int len);
|
||||||
static void XMLCALL endElement(void* userData, const XML_Char* name);
|
static void XMLCALL endElement(void* userData, const XML_Char* name);
|
||||||
|
|
||||||
public:
|
public:
|
||||||
explicit ChapterHtmlSlimParser(const std::string& filepath, GfxRenderer& renderer, const int fontId,
|
explicit ChapterHtmlSlimParser(std::shared_ptr<Epub> epub, const std::string& filepath, GfxRenderer& renderer,
|
||||||
const float lineCompression, const bool extraParagraphSpacing,
|
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 uint16_t viewportHeight, const bool hyphenationEnabled,
|
||||||
const std::function<void(std::unique_ptr<Page>)>& completePageFn,
|
const std::function<void(std::unique_ptr<Page>)>& completePageFn,
|
||||||
const std::function<void(int)>& progressFn = nullptr)
|
const bool embeddedStyle, const std::string& contentBase,
|
||||||
: filepath(filepath),
|
const std::string& imageBasePath, const std::function<void()>& popupFn = nullptr,
|
||||||
|
const CssParser* cssParser = nullptr)
|
||||||
|
|
||||||
|
: epub(epub),
|
||||||
|
filepath(filepath),
|
||||||
renderer(renderer),
|
renderer(renderer),
|
||||||
fontId(fontId),
|
fontId(fontId),
|
||||||
lineCompression(lineCompression),
|
lineCompression(lineCompression),
|
||||||
@@ -63,7 +102,12 @@ class ChapterHtmlSlimParser {
|
|||||||
viewportHeight(viewportHeight),
|
viewportHeight(viewportHeight),
|
||||||
hyphenationEnabled(hyphenationEnabled),
|
hyphenationEnabled(hyphenationEnabled),
|
||||||
completePageFn(completePageFn),
|
completePageFn(completePageFn),
|
||||||
progressFn(progressFn) {}
|
popupFn(popupFn),
|
||||||
|
cssParser(cssParser),
|
||||||
|
embeddedStyle(embeddedStyle),
|
||||||
|
contentBase(contentBase),
|
||||||
|
imageBasePath(imageBasePath) {}
|
||||||
|
|
||||||
~ChapterHtmlSlimParser() = default;
|
~ChapterHtmlSlimParser() = default;
|
||||||
bool parseAndBuildPages();
|
bool parseAndBuildPages();
|
||||||
void addLineToPage(std::shared_ptr<TextBlock> line);
|
void addLineToPage(std::shared_ptr<TextBlock> line);
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
#include "ContainerParser.h"
|
#include "ContainerParser.h"
|
||||||
|
|
||||||
#include <HardwareSerial.h>
|
#include <Logging.h>
|
||||||
|
|
||||||
bool ContainerParser::setup() {
|
bool ContainerParser::setup() {
|
||||||
parser = XML_ParserCreate(nullptr);
|
parser = XML_ParserCreate(nullptr);
|
||||||
if (!parser) {
|
if (!parser) {
|
||||||
Serial.printf("[%lu] [CTR] Couldn't allocate memory for parser\n", millis());
|
LOG_ERR("CTR", "Couldn't allocate memory for parser");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -34,7 +34,7 @@ size_t ContainerParser::write(const uint8_t* buffer, const size_t size) {
|
|||||||
while (remainingInBuffer > 0) {
|
while (remainingInBuffer > 0) {
|
||||||
void* const buf = XML_GetBuffer(parser, 1024);
|
void* const buf = XML_GetBuffer(parser, 1024);
|
||||||
if (!buf) {
|
if (!buf) {
|
||||||
Serial.printf("[%lu] [CTR] Couldn't allocate buffer\n", millis());
|
LOG_DBG("CTR", "Couldn't allocate buffer");
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -42,7 +42,7 @@ size_t ContainerParser::write(const uint8_t* buffer, const size_t size) {
|
|||||||
memcpy(buf, currentBufferPos, toRead);
|
memcpy(buf, currentBufferPos, toRead);
|
||||||
|
|
||||||
if (XML_ParseBuffer(parser, static_cast<int>(toRead), remainingSize == toRead) == XML_STATUS_ERROR) {
|
if (XML_ParseBuffer(parser, static_cast<int>(toRead), remainingSize == toRead) == XML_STATUS_ERROR) {
|
||||||
Serial.printf("[%lu] [CTR] Parse error: %s\n", millis(), XML_ErrorString(XML_GetErrorCode(parser)));
|
LOG_ERR("CTR", "Parse error: %s", XML_ErrorString(XML_GetErrorCode(parser)));
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,20 +1,21 @@
|
|||||||
#include "ContentOpfParser.h"
|
#include "ContentOpfParser.h"
|
||||||
|
|
||||||
#include <FsHelpers.h>
|
#include <FsHelpers.h>
|
||||||
#include <HardwareSerial.h>
|
#include <Logging.h>
|
||||||
#include <Serialization.h>
|
#include <Serialization.h>
|
||||||
|
|
||||||
#include "../BookMetadataCache.h"
|
#include "../BookMetadataCache.h"
|
||||||
|
|
||||||
namespace {
|
namespace {
|
||||||
constexpr char MEDIA_TYPE_NCX[] = "application/x-dtbncx+xml";
|
constexpr char MEDIA_TYPE_NCX[] = "application/x-dtbncx+xml";
|
||||||
|
constexpr char MEDIA_TYPE_CSS[] = "text/css";
|
||||||
constexpr char itemCacheFile[] = "/.items.bin";
|
constexpr char itemCacheFile[] = "/.items.bin";
|
||||||
} // namespace
|
} // namespace
|
||||||
|
|
||||||
bool ContentOpfParser::setup() {
|
bool ContentOpfParser::setup() {
|
||||||
parser = XML_ParserCreate(nullptr);
|
parser = XML_ParserCreate(nullptr);
|
||||||
if (!parser) {
|
if (!parser) {
|
||||||
Serial.printf("[%lu] [COF] Couldn't allocate memory for parser\n", millis());
|
LOG_DBG("COF", "Couldn't allocate memory for parser");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -35,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();
|
||||||
@@ -55,7 +56,7 @@ size_t ContentOpfParser::write(const uint8_t* buffer, const size_t size) {
|
|||||||
void* const buf = XML_GetBuffer(parser, 1024);
|
void* const buf = XML_GetBuffer(parser, 1024);
|
||||||
|
|
||||||
if (!buf) {
|
if (!buf) {
|
||||||
Serial.printf("[%lu] [COF] Couldn't allocate memory for buffer\n", millis());
|
LOG_ERR("COF", "Couldn't allocate memory for buffer");
|
||||||
XML_StopParser(parser, XML_FALSE); // Stop any pending processing
|
XML_StopParser(parser, XML_FALSE); // Stop any pending processing
|
||||||
XML_SetElementHandler(parser, nullptr, nullptr); // Clear callbacks
|
XML_SetElementHandler(parser, nullptr, nullptr); // Clear callbacks
|
||||||
XML_SetCharacterDataHandler(parser, nullptr);
|
XML_SetCharacterDataHandler(parser, nullptr);
|
||||||
@@ -68,7 +69,7 @@ size_t ContentOpfParser::write(const uint8_t* buffer, const size_t size) {
|
|||||||
memcpy(buf, currentBufferPos, toRead);
|
memcpy(buf, currentBufferPos, toRead);
|
||||||
|
|
||||||
if (XML_ParseBuffer(parser, static_cast<int>(toRead), remainingSize == toRead) == XML_STATUS_ERROR) {
|
if (XML_ParseBuffer(parser, static_cast<int>(toRead), remainingSize == toRead) == XML_STATUS_ERROR) {
|
||||||
Serial.printf("[%lu] [COF] Parse error at line %lu: %s\n", millis(), XML_GetCurrentLineNumber(parser),
|
LOG_DBG("COF", "Parse error at line %lu: %s", XML_GetCurrentLineNumber(parser),
|
||||||
XML_ErrorString(XML_GetErrorCode(parser)));
|
XML_ErrorString(XML_GetErrorCode(parser)));
|
||||||
XML_StopParser(parser, XML_FALSE); // Stop any pending processing
|
XML_StopParser(parser, XML_FALSE); // Stop any pending processing
|
||||||
XML_SetElementHandler(parser, nullptr, nullptr); // Clear callbacks
|
XML_SetElementHandler(parser, nullptr, nullptr); // Clear callbacks
|
||||||
@@ -117,20 +118,16 @@ 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(
|
LOG_ERR("COF", "Couldn't open temp items file for writing. This is probably going to be a fatal error.");
|
||||||
"[%lu] [COF] Couldn't open temp items file for writing. This is probably going to be a fatal error.\n",
|
|
||||||
millis());
|
|
||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
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(
|
LOG_ERR("COF", "Couldn't open temp items file for reading. This is probably going to be a fatal error.");
|
||||||
"[%lu] [COF] Couldn't open temp items file for reading. This is probably going to be a fatal error.\n",
|
|
||||||
millis());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Sort item index for binary search if we have enough items
|
// Sort item index for binary search if we have enough items
|
||||||
@@ -139,7 +136,7 @@ void XMLCALL ContentOpfParser::startElement(void* userData, const XML_Char* name
|
|||||||
return a.idHash < b.idHash || (a.idHash == b.idHash && a.idLen < b.idLen);
|
return a.idHash < b.idHash || (a.idHash == b.idHash && a.idLen < b.idLen);
|
||||||
});
|
});
|
||||||
self->useItemIndex = true;
|
self->useItemIndex = true;
|
||||||
Serial.printf("[%lu] [COF] Using fast index for %zu manifest items\n", millis(), self->itemIndex.size());
|
LOG_DBG("COF", "Using fast index for %zu manifest items", self->itemIndex.size());
|
||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -147,11 +144,9 @@ void XMLCALL ContentOpfParser::startElement(void* userData, const XML_Char* name
|
|||||||
if (self->state == IN_PACKAGE && (strcmp(name, "guide") == 0 || strcmp(name, "opf:guide") == 0)) {
|
if (self->state == IN_PACKAGE && (strcmp(name, "guide") == 0 || strcmp(name, "opf:guide") == 0)) {
|
||||||
self->state = IN_GUIDE;
|
self->state = IN_GUIDE;
|
||||||
// TODO Remove print
|
// TODO Remove print
|
||||||
Serial.printf("[%lu] [COF] Entering guide state.\n", millis());
|
LOG_DBG("COF", "Entering guide state.");
|
||||||
if (!SdMan.openFileForRead("COF", self->cachePath + itemCacheFile, self->tempItemStore)) {
|
if (!Storage.openFileForRead("COF", self->cachePath + itemCacheFile, self->tempItemStore)) {
|
||||||
Serial.printf(
|
LOG_ERR("COF", "Couldn't open temp items file for reading. This is probably going to be a fatal error.");
|
||||||
"[%lu] [COF] Couldn't open temp items file for reading. This is probably going to be a fatal error.\n",
|
|
||||||
millis());
|
|
||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -213,17 +208,29 @@ void XMLCALL ContentOpfParser::startElement(void* userData, const XML_Char* name
|
|||||||
if (self->tocNcxPath.empty()) {
|
if (self->tocNcxPath.empty()) {
|
||||||
self->tocNcxPath = href;
|
self->tocNcxPath = href;
|
||||||
} else {
|
} else {
|
||||||
Serial.printf("[%lu] [COF] Warning: Multiple NCX files found in manifest. Ignoring duplicate: %s\n", millis(),
|
LOG_DBG("COF", "Warning: Multiple NCX files found in manifest. Ignoring duplicate: %s", href.c_str());
|
||||||
href.c_str());
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Collect CSS files
|
||||||
|
if (mediaType == MEDIA_TYPE_CSS) {
|
||||||
|
self->cssFiles.push_back(href);
|
||||||
|
}
|
||||||
|
|
||||||
// EPUB 3: Check for nav document (properties contains "nav")
|
// EPUB 3: Check for nav document (properties contains "nav")
|
||||||
if (!properties.empty() && self->tocNavPath.empty()) {
|
if (!properties.empty() && self->tocNavPath.empty()) {
|
||||||
// Properties is space-separated, check if "nav" is present as a word
|
// Properties is space-separated, check if "nav" is present as a word
|
||||||
if (properties == "nav" || properties.find("nav ") == 0 || properties.find(" nav") != std::string::npos) {
|
if (properties == "nav" || properties.find("nav ") == 0 || properties.find(" nav") != std::string::npos) {
|
||||||
self->tocNavPath = href;
|
self->tocNavPath = href;
|
||||||
Serial.printf("[%lu] [COF] Found EPUB 3 nav document: %s\n", millis(), href.c_str());
|
LOG_DBG("COF", "Found EPUB 3 nav document: %s", 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;
|
||||||
@@ -296,7 +303,7 @@ void XMLCALL ContentOpfParser::startElement(void* userData, const XML_Char* name
|
|||||||
if (type == "text" || type == "start") {
|
if (type == "text" || type == "start") {
|
||||||
continue;
|
continue;
|
||||||
} else {
|
} else {
|
||||||
Serial.printf("[%lu] [COF] Skipping non-text reference in guide: %s\n", millis(), type.c_str());
|
LOG_DBG("COF", "Skipping non-text reference in guide: %s", type.c_str());
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
} else if (strcmp(atts[i], "href") == 0) {
|
} else if (strcmp(atts[i], "href") == 0) {
|
||||||
@@ -304,7 +311,7 @@ void XMLCALL ContentOpfParser::startElement(void* userData, const XML_Char* name
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if ((type == "text" || (type == "start" && !self->textReferenceHref.empty())) && (textHref.length() > 0)) {
|
if ((type == "text" || (type == "start" && !self->textReferenceHref.empty())) && (textHref.length() > 0)) {
|
||||||
Serial.printf("[%lu] [COF] Found %s reference in guide: %s.\n", millis(), type.c_str(), textHref.c_str());
|
LOG_DBG("COF", "Found %s reference in guide: %s.", type.c_str(), textHref.c_str());
|
||||||
self->textReferenceHref = textHref;
|
self->textReferenceHref = textHref;
|
||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
|
|||||||
@@ -64,6 +64,7 @@ class ContentOpfParser final : public Print {
|
|||||||
std::string tocNavPath; // EPUB 3 nav document path
|
std::string tocNavPath; // EPUB 3 nav document path
|
||||||
std::string coverItemHref;
|
std::string coverItemHref;
|
||||||
std::string textReferenceHref;
|
std::string textReferenceHref;
|
||||||
|
std::vector<std::string> cssFiles; // CSS stylesheet paths
|
||||||
|
|
||||||
explicit ContentOpfParser(const std::string& cachePath, const std::string& baseContentPath, const size_t xmlSize,
|
explicit ContentOpfParser(const std::string& cachePath, const std::string& baseContentPath, const size_t xmlSize,
|
||||||
BookMetadataCache* cache)
|
BookMetadataCache* cache)
|
||||||
|
|||||||
@@ -1,14 +1,14 @@
|
|||||||
#include "TocNavParser.h"
|
#include "TocNavParser.h"
|
||||||
|
|
||||||
#include <FsHelpers.h>
|
#include <FsHelpers.h>
|
||||||
#include <HardwareSerial.h>
|
#include <Logging.h>
|
||||||
|
|
||||||
#include "../BookMetadataCache.h"
|
#include "../BookMetadataCache.h"
|
||||||
|
|
||||||
bool TocNavParser::setup() {
|
bool TocNavParser::setup() {
|
||||||
parser = XML_ParserCreate(nullptr);
|
parser = XML_ParserCreate(nullptr);
|
||||||
if (!parser) {
|
if (!parser) {
|
||||||
Serial.printf("[%lu] [NAV] Couldn't allocate memory for parser\n", millis());
|
LOG_DBG("NAV", "Couldn't allocate memory for parser");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -39,7 +39,7 @@ size_t TocNavParser::write(const uint8_t* buffer, const size_t size) {
|
|||||||
while (remainingInBuffer > 0) {
|
while (remainingInBuffer > 0) {
|
||||||
void* const buf = XML_GetBuffer(parser, 1024);
|
void* const buf = XML_GetBuffer(parser, 1024);
|
||||||
if (!buf) {
|
if (!buf) {
|
||||||
Serial.printf("[%lu] [NAV] Couldn't allocate memory for buffer\n", millis());
|
LOG_DBG("NAV", "Couldn't allocate memory for buffer");
|
||||||
XML_StopParser(parser, XML_FALSE);
|
XML_StopParser(parser, XML_FALSE);
|
||||||
XML_SetElementHandler(parser, nullptr, nullptr);
|
XML_SetElementHandler(parser, nullptr, nullptr);
|
||||||
XML_SetCharacterDataHandler(parser, nullptr);
|
XML_SetCharacterDataHandler(parser, nullptr);
|
||||||
@@ -52,7 +52,7 @@ size_t TocNavParser::write(const uint8_t* buffer, const size_t size) {
|
|||||||
memcpy(buf, currentBufferPos, toRead);
|
memcpy(buf, currentBufferPos, toRead);
|
||||||
|
|
||||||
if (XML_ParseBuffer(parser, static_cast<int>(toRead), remainingSize == toRead) == XML_STATUS_ERROR) {
|
if (XML_ParseBuffer(parser, static_cast<int>(toRead), remainingSize == toRead) == XML_STATUS_ERROR) {
|
||||||
Serial.printf("[%lu] [NAV] Parse error at line %lu: %s\n", millis(), XML_GetCurrentLineNumber(parser),
|
LOG_DBG("NAV", "Parse error at line %lu: %s", XML_GetCurrentLineNumber(parser),
|
||||||
XML_ErrorString(XML_GetErrorCode(parser)));
|
XML_ErrorString(XML_GetErrorCode(parser)));
|
||||||
XML_StopParser(parser, XML_FALSE);
|
XML_StopParser(parser, XML_FALSE);
|
||||||
XML_SetElementHandler(parser, nullptr, nullptr);
|
XML_SetElementHandler(parser, nullptr, nullptr);
|
||||||
@@ -88,7 +88,7 @@ void XMLCALL TocNavParser::startElement(void* userData, const XML_Char* name, co
|
|||||||
for (int i = 0; atts[i]; i += 2) {
|
for (int i = 0; atts[i]; i += 2) {
|
||||||
if ((strcmp(atts[i], "epub:type") == 0 || strcmp(atts[i], "type") == 0) && strcmp(atts[i + 1], "toc") == 0) {
|
if ((strcmp(atts[i], "epub:type") == 0 || strcmp(atts[i], "type") == 0) && strcmp(atts[i + 1], "toc") == 0) {
|
||||||
self->state = IN_NAV_TOC;
|
self->state = IN_NAV_TOC;
|
||||||
Serial.printf("[%lu] [NAV] Found nav toc element\n", millis());
|
LOG_DBG("NAV", "Found nav toc element");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -179,7 +179,7 @@ void XMLCALL TocNavParser::endElement(void* userData, const XML_Char* name) {
|
|||||||
|
|
||||||
if (strcmp(name, "nav") == 0 && self->state >= IN_NAV_TOC) {
|
if (strcmp(name, "nav") == 0 && self->state >= IN_NAV_TOC) {
|
||||||
self->state = IN_BODY;
|
self->state = IN_BODY;
|
||||||
Serial.printf("[%lu] [NAV] Finished parsing nav toc\n", millis());
|
LOG_DBG("NAV", "Finished parsing nav toc");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,14 +1,14 @@
|
|||||||
#include "TocNcxParser.h"
|
#include "TocNcxParser.h"
|
||||||
|
|
||||||
#include <FsHelpers.h>
|
#include <FsHelpers.h>
|
||||||
#include <HardwareSerial.h>
|
#include <Logging.h>
|
||||||
|
|
||||||
#include "../BookMetadataCache.h"
|
#include "../BookMetadataCache.h"
|
||||||
|
|
||||||
bool TocNcxParser::setup() {
|
bool TocNcxParser::setup() {
|
||||||
parser = XML_ParserCreate(nullptr);
|
parser = XML_ParserCreate(nullptr);
|
||||||
if (!parser) {
|
if (!parser) {
|
||||||
Serial.printf("[%lu] [TOC] Couldn't allocate memory for parser\n", millis());
|
LOG_DBG("TOC", "Couldn't allocate memory for parser");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -39,7 +39,7 @@ size_t TocNcxParser::write(const uint8_t* buffer, const size_t size) {
|
|||||||
while (remainingInBuffer > 0) {
|
while (remainingInBuffer > 0) {
|
||||||
void* const buf = XML_GetBuffer(parser, 1024);
|
void* const buf = XML_GetBuffer(parser, 1024);
|
||||||
if (!buf) {
|
if (!buf) {
|
||||||
Serial.printf("[%lu] [TOC] Couldn't allocate memory for buffer\n", millis());
|
LOG_DBG("TOC", "Couldn't allocate memory for buffer");
|
||||||
XML_StopParser(parser, XML_FALSE); // Stop any pending processing
|
XML_StopParser(parser, XML_FALSE); // Stop any pending processing
|
||||||
XML_SetElementHandler(parser, nullptr, nullptr); // Clear callbacks
|
XML_SetElementHandler(parser, nullptr, nullptr); // Clear callbacks
|
||||||
XML_SetCharacterDataHandler(parser, nullptr);
|
XML_SetCharacterDataHandler(parser, nullptr);
|
||||||
@@ -52,7 +52,7 @@ size_t TocNcxParser::write(const uint8_t* buffer, const size_t size) {
|
|||||||
memcpy(buf, currentBufferPos, toRead);
|
memcpy(buf, currentBufferPos, toRead);
|
||||||
|
|
||||||
if (XML_ParseBuffer(parser, static_cast<int>(toRead), remainingSize == toRead) == XML_STATUS_ERROR) {
|
if (XML_ParseBuffer(parser, static_cast<int>(toRead), remainingSize == toRead) == XML_STATUS_ERROR) {
|
||||||
Serial.printf("[%lu] [TOC] Parse error at line %lu: %s\n", millis(), XML_GetCurrentLineNumber(parser),
|
LOG_DBG("TOC", "Parse error at line %lu: %s", XML_GetCurrentLineNumber(parser),
|
||||||
XML_ErrorString(XML_GetErrorCode(parser)));
|
XML_ErrorString(XML_GetErrorCode(parser)));
|
||||||
XML_StopParser(parser, XML_FALSE); // Stop any pending processing
|
XML_StopParser(parser, XML_FALSE); // Stop any pending processing
|
||||||
XML_SetElementHandler(parser, nullptr, nullptr); // Clear callbacks
|
XML_SetElementHandler(parser, nullptr, nullptr); // Clear callbacks
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include <SdFat.h>
|
#include <HalStorage.h>
|
||||||
|
|
||||||
#include <cstdint>
|
#include <cstdint>
|
||||||
|
|
||||||
|
|||||||
@@ -104,3 +104,20 @@ uint8_t quantize1bit(int gray, int x, int y) {
|
|||||||
const int adjustedThreshold = 128 + ((threshold - 128) / 2); // Range: 64-192
|
const int adjustedThreshold = 128 + ((threshold - 128) / 2); // Range: 64-192
|
||||||
return (gray >= adjustedThreshold) ? 1 : 0;
|
return (gray >= adjustedThreshold) ? 1 : 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Noise dithering for gradient fills - always uses hash-based noise regardless of global dithering config.
|
||||||
|
// Produces smooth-looking gradients on the 4-level e-ink display.
|
||||||
|
uint8_t quantizeNoiseDither(int gray, int x, int y) {
|
||||||
|
uint32_t hash = static_cast<uint32_t>(x) * 374761393u + static_cast<uint32_t>(y) * 668265263u;
|
||||||
|
hash = (hash ^ (hash >> 13)) * 1274126177u;
|
||||||
|
const int threshold = static_cast<int>(hash >> 24);
|
||||||
|
|
||||||
|
const int scaled = gray * 3;
|
||||||
|
if (scaled < 255) {
|
||||||
|
return (scaled + threshold >= 255) ? 1 : 0;
|
||||||
|
} else if (scaled < 510) {
|
||||||
|
return ((scaled - 255) + threshold >= 255) ? 2 : 1;
|
||||||
|
} else {
|
||||||
|
return ((scaled - 510) + threshold >= 255) ? 3 : 2;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ uint8_t quantize(int gray, int x, int y);
|
|||||||
uint8_t quantizeSimple(int gray);
|
uint8_t quantizeSimple(int gray);
|
||||||
uint8_t quantize1bit(int gray, int x, int y);
|
uint8_t quantize1bit(int gray, int x, int y);
|
||||||
int adjustPixel(int gray);
|
int adjustPixel(int gray);
|
||||||
|
uint8_t quantizeNoiseDither(int gray, int x, int y);
|
||||||
|
|
||||||
// 1-bit Atkinson dithering - better quality than noise dithering for thumbnails
|
// 1-bit Atkinson dithering - better quality than noise dithering for thumbnails
|
||||||
// Error distribution pattern (same as 2-bit but quantizes to 2 levels):
|
// Error distribution pattern (same as 2-bit but quantizes to 2 levels):
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -7,6 +7,10 @@
|
|||||||
|
|
||||||
#include "Bitmap.h"
|
#include "Bitmap.h"
|
||||||
|
|
||||||
|
// Color representation: uint8_t mapped to 4x4 Bayer matrix dithering levels
|
||||||
|
// 0 = transparent, 1-16 = gray levels (white to black)
|
||||||
|
enum Color : uint8_t { Clear = 0x00, White = 0x01, LightGray = 0x05, DarkGray = 0x0A, Black = 0x10 };
|
||||||
|
|
||||||
class GfxRenderer {
|
class GfxRenderer {
|
||||||
public:
|
public:
|
||||||
enum RenderMode { BW, GRAYSCALE_LSB, GRAYSCALE_MSB };
|
enum RenderMode { BW, GRAYSCALE_LSB, GRAYSCALE_MSB };
|
||||||
@@ -28,15 +32,21 @@ class GfxRenderer {
|
|||||||
HalDisplay& display;
|
HalDisplay& display;
|
||||||
RenderMode renderMode;
|
RenderMode renderMode;
|
||||||
Orientation orientation;
|
Orientation orientation;
|
||||||
|
bool fadingFix;
|
||||||
|
uint8_t* frameBuffer = nullptr;
|
||||||
uint8_t* bwBufferChunks[BW_BUFFER_NUM_CHUNKS] = {nullptr};
|
uint8_t* bwBufferChunks[BW_BUFFER_NUM_CHUNKS] = {nullptr};
|
||||||
std::map<int, EpdFontFamily> fontMap;
|
std::map<int, EpdFontFamily> fontMap;
|
||||||
void renderChar(const EpdFontFamily& fontFamily, uint32_t cp, int* x, const int* y, bool pixelState,
|
void renderChar(const EpdFontFamily& fontFamily, uint32_t cp, int* x, const int* y, bool pixelState,
|
||||||
EpdFontFamily::Style style) const;
|
EpdFontFamily::Style style) const;
|
||||||
void freeBwBufferChunks();
|
void freeBwBufferChunks();
|
||||||
void rotateCoordinates(int x, int y, int* rotatedX, int* rotatedY) const;
|
template <Color color>
|
||||||
|
void drawPixelDither(int x, int y) const;
|
||||||
|
template <Color color>
|
||||||
|
void fillArc(int maxRadius, int cx, int cy, int xDir, int yDir) const;
|
||||||
|
|
||||||
public:
|
public:
|
||||||
explicit GfxRenderer(HalDisplay& halDisplay) : display(halDisplay), renderMode(BW), orientation(Portrait) {}
|
explicit GfxRenderer(HalDisplay& halDisplay)
|
||||||
|
: display(halDisplay), renderMode(BW), orientation(Portrait), fadingFix(false) {}
|
||||||
~GfxRenderer() { freeBwBufferChunks(); }
|
~GfxRenderer() { freeBwBufferChunks(); }
|
||||||
|
|
||||||
static constexpr int VIEWABLE_MARGIN_TOP = 9;
|
static constexpr int VIEWABLE_MARGIN_TOP = 9;
|
||||||
@@ -45,27 +55,45 @@ class GfxRenderer {
|
|||||||
static constexpr int VIEWABLE_MARGIN_LEFT = 3;
|
static constexpr int VIEWABLE_MARGIN_LEFT = 3;
|
||||||
|
|
||||||
// Setup
|
// Setup
|
||||||
|
void begin(); // must be called right after display.begin()
|
||||||
void insertFont(int fontId, EpdFontFamily font);
|
void insertFont(int fontId, EpdFontFamily font);
|
||||||
|
|
||||||
// Orientation control (affects logical width/height and coordinate transforms)
|
// Orientation control (affects logical width/height and coordinate transforms)
|
||||||
void setOrientation(const Orientation o) { orientation = o; }
|
void setOrientation(const Orientation o) { orientation = o; }
|
||||||
Orientation getOrientation() const { return orientation; }
|
Orientation getOrientation() const { return orientation; }
|
||||||
|
|
||||||
|
// Fading fix control
|
||||||
|
void setFadingFix(const bool enabled) { fadingFix = enabled; }
|
||||||
|
|
||||||
// Screen ops
|
// Screen ops
|
||||||
int getScreenWidth() const;
|
int getScreenWidth() const;
|
||||||
int getScreenHeight() const;
|
int getScreenHeight() const;
|
||||||
void displayBuffer(HalDisplay::RefreshMode refreshMode = HalDisplay::FAST_REFRESH) const;
|
void displayBuffer(HalDisplay::RefreshMode refreshMode = HalDisplay::FAST_REFRESH) const;
|
||||||
// EXPERIMENTAL: Windowed update - display only a rectangular region
|
// EXPERIMENTAL: Windowed update - display only a rectangular region
|
||||||
void displayWindow(int x, int y, int width, int height) const;
|
void displayWindow(int x, int y, int width, int height,
|
||||||
|
HalDisplay::RefreshMode mode = HalDisplay::FAST_REFRESH) const;
|
||||||
void invertScreen() const;
|
void invertScreen() const;
|
||||||
void clearScreen(uint8_t color = 0xFF) const;
|
void clearScreen(uint8_t color = 0xFF) const;
|
||||||
|
void getOrientedViewableTRBL(int* outTop, int* outRight, int* outBottom, int* outLeft) const;
|
||||||
|
|
||||||
// Drawing
|
// Drawing
|
||||||
void drawPixel(int x, int y, bool state = true) const;
|
void drawPixel(int x, int y, bool state = true) const;
|
||||||
|
void drawPixelGray(int x, int y, uint8_t val2bit) const;
|
||||||
void drawLine(int x1, int y1, int x2, int y2, bool state = true) const;
|
void drawLine(int x1, int y1, int x2, int y2, bool state = true) const;
|
||||||
|
void drawLine(int x1, int y1, int x2, int y2, int lineWidth, bool state) const;
|
||||||
|
void drawArc(int maxRadius, int cx, int cy, int xDir, int yDir, int lineWidth, bool state) const;
|
||||||
void drawRect(int x, int y, int width, int height, bool state = true) const;
|
void drawRect(int x, int y, int width, int height, bool state = true) const;
|
||||||
|
void drawRect(int x, int y, int width, int height, int lineWidth, bool state) const;
|
||||||
|
void drawRoundedRect(int x, int y, int width, int height, int lineWidth, int cornerRadius, bool state) const;
|
||||||
|
void drawRoundedRect(int x, int y, int width, int height, int lineWidth, int cornerRadius, bool roundTopLeft,
|
||||||
|
bool roundTopRight, bool roundBottomLeft, bool roundBottomRight, bool state) const;
|
||||||
void fillRect(int x, int y, int width, int height, bool state = true) const;
|
void fillRect(int x, int y, int width, int height, bool state = true) const;
|
||||||
|
void fillRectDither(int x, int y, int width, int height, Color color) const;
|
||||||
|
void fillRoundedRect(int x, int y, int width, int height, int cornerRadius, Color color) const;
|
||||||
|
void fillRoundedRect(int x, int y, int width, int height, int cornerRadius, bool roundTopLeft, bool roundTopRight,
|
||||||
|
bool roundBottomLeft, bool roundBottomRight, Color color) const;
|
||||||
void drawImage(const uint8_t bitmap[], int x, int y, int width, int height) const;
|
void drawImage(const uint8_t bitmap[], int x, int y, int width, int height) const;
|
||||||
|
void drawIcon(const uint8_t bitmap[], int x, int y, int width, int height) const;
|
||||||
void drawBitmap(const Bitmap& bitmap, int x, int y, int maxWidth, int maxHeight, float cropX = 0,
|
void drawBitmap(const Bitmap& bitmap, int x, int y, int maxWidth, int maxHeight, float cropX = 0,
|
||||||
float cropY = 0) const;
|
float cropY = 0) const;
|
||||||
void drawBitmap1Bit(const Bitmap& bitmap, int x, int y, int maxWidth, int maxHeight) const;
|
void drawBitmap1Bit(const Bitmap& bitmap, int x, int y, int maxWidth, int maxHeight) const;
|
||||||
@@ -78,24 +106,22 @@ class GfxRenderer {
|
|||||||
void drawText(int fontId, int x, int y, const char* text, bool black = true,
|
void drawText(int fontId, int x, int y, const char* text, bool black = true,
|
||||||
EpdFontFamily::Style style = EpdFontFamily::REGULAR) const;
|
EpdFontFamily::Style style = EpdFontFamily::REGULAR) const;
|
||||||
int getSpaceWidth(int fontId) const;
|
int getSpaceWidth(int fontId) const;
|
||||||
|
int getTextAdvanceX(int fontId, const char* text) const;
|
||||||
int getFontAscenderSize(int fontId) const;
|
int getFontAscenderSize(int fontId) const;
|
||||||
int getLineHeight(int fontId) const;
|
int getLineHeight(int fontId) const;
|
||||||
std::string truncatedText(int fontId, const char* text, int maxWidth,
|
std::string truncatedText(int fontId, const char* text, int maxWidth,
|
||||||
EpdFontFamily::Style style = EpdFontFamily::REGULAR) const;
|
EpdFontFamily::Style style = EpdFontFamily::REGULAR) const;
|
||||||
|
|
||||||
// UI Components
|
// Helpers for drawing rotated text (for side buttons)
|
||||||
void drawButtonHints(int fontId, const char* btn1, const char* btn2, const char* btn3, const char* btn4);
|
|
||||||
void drawSideButtonHints(int fontId, const char* topBtn, const char* bottomBtn) const;
|
|
||||||
|
|
||||||
private:
|
|
||||||
// Helper for drawing rotated text (90 degrees clockwise, for side buttons)
|
|
||||||
void drawTextRotated90CW(int fontId, int x, int y, const char* text, bool black = true,
|
void drawTextRotated90CW(int fontId, int x, int y, const char* text, bool black = true,
|
||||||
EpdFontFamily::Style style = EpdFontFamily::REGULAR) const;
|
EpdFontFamily::Style style = EpdFontFamily::REGULAR) const;
|
||||||
|
void drawTextRotated90CCW(int fontId, int x, int y, const char* text, bool black = true,
|
||||||
|
EpdFontFamily::Style style = EpdFontFamily::REGULAR) const;
|
||||||
int getTextHeight(int fontId) const;
|
int getTextHeight(int fontId) const;
|
||||||
|
|
||||||
public:
|
|
||||||
// Grayscale functions
|
// Grayscale functions
|
||||||
void setRenderMode(const RenderMode mode) { this->renderMode = mode; }
|
void setRenderMode(const RenderMode mode) { this->renderMode = mode; }
|
||||||
|
RenderMode getRenderMode() const { return renderMode; }
|
||||||
void copyGrayscaleLsbBuffers() const;
|
void copyGrayscaleLsbBuffers() const;
|
||||||
void copyGrayscaleMsbBuffers() const;
|
void copyGrayscaleMsbBuffers() const;
|
||||||
void displayGrayBuffer() const;
|
void displayGrayBuffer() const;
|
||||||
@@ -106,6 +132,4 @@ class GfxRenderer {
|
|||||||
// Low level functions
|
// Low level functions
|
||||||
uint8_t* getFrameBuffer() const;
|
uint8_t* getFrameBuffer() const;
|
||||||
static size_t getBufferSize();
|
static size_t getBufferSize();
|
||||||
void grayscaleRevert() const;
|
|
||||||
void getOrientedViewableTRBL(int* outTop, int* outRight, int* outBottom, int* outLeft) const;
|
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
#include "JpegToBmpConverter.h"
|
#include "JpegToBmpConverter.h"
|
||||||
|
|
||||||
#include <HardwareSerial.h>
|
#include <HalStorage.h>
|
||||||
#include <SdFat.h>
|
#include <Logging.h>
|
||||||
#include <picojpeg.h>
|
#include <picojpeg.h>
|
||||||
|
|
||||||
#include <cstdio>
|
#include <cstdio>
|
||||||
@@ -201,8 +201,7 @@ unsigned char JpegToBmpConverter::jpegReadCallback(unsigned char* pBuf, const un
|
|||||||
// Internal implementation with configurable target size and bit depth
|
// Internal implementation with configurable target size and bit depth
|
||||||
bool JpegToBmpConverter::jpegFileToBmpStreamInternal(FsFile& jpegFile, Print& bmpOut, int targetWidth, int targetHeight,
|
bool JpegToBmpConverter::jpegFileToBmpStreamInternal(FsFile& jpegFile, Print& bmpOut, int targetWidth, int targetHeight,
|
||||||
bool oneBit, bool crop) {
|
bool oneBit, bool crop) {
|
||||||
Serial.printf("[%lu] [JPG] Converting JPEG to %s BMP (target: %dx%d)\n", millis(), oneBit ? "1-bit" : "2-bit",
|
LOG_DBG("JPG", "Converting JPEG to %s BMP (target: %dx%d)", oneBit ? "1-bit" : "2-bit", targetWidth, targetHeight);
|
||||||
targetWidth, targetHeight);
|
|
||||||
|
|
||||||
// Setup context for picojpeg callback
|
// Setup context for picojpeg callback
|
||||||
JpegReadContext context = {.file = jpegFile, .bufferPos = 0, .bufferFilled = 0};
|
JpegReadContext context = {.file = jpegFile, .bufferPos = 0, .bufferFilled = 0};
|
||||||
@@ -211,12 +210,12 @@ bool JpegToBmpConverter::jpegFileToBmpStreamInternal(FsFile& jpegFile, Print& bm
|
|||||||
pjpeg_image_info_t imageInfo;
|
pjpeg_image_info_t imageInfo;
|
||||||
const unsigned char status = pjpeg_decode_init(&imageInfo, jpegReadCallback, &context, 0);
|
const unsigned char status = pjpeg_decode_init(&imageInfo, jpegReadCallback, &context, 0);
|
||||||
if (status != 0) {
|
if (status != 0) {
|
||||||
Serial.printf("[%lu] [JPG] JPEG decode init failed with error code: %d\n", millis(), status);
|
LOG_ERR("JPG", "JPEG decode init failed with error code: %d", status);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
Serial.printf("[%lu] [JPG] JPEG dimensions: %dx%d, components: %d, MCUs: %dx%d\n", millis(), imageInfo.m_width,
|
LOG_DBG("JPG", "JPEG dimensions: %dx%d, components: %d, MCUs: %dx%d", imageInfo.m_width, imageInfo.m_height,
|
||||||
imageInfo.m_height, imageInfo.m_comps, imageInfo.m_MCUSPerRow, imageInfo.m_MCUSPerCol);
|
imageInfo.m_comps, imageInfo.m_MCUSPerRow, imageInfo.m_MCUSPerCol);
|
||||||
|
|
||||||
// Safety limits to prevent memory issues on ESP32
|
// Safety limits to prevent memory issues on ESP32
|
||||||
constexpr int MAX_IMAGE_WIDTH = 2048;
|
constexpr int MAX_IMAGE_WIDTH = 2048;
|
||||||
@@ -224,8 +223,8 @@ bool JpegToBmpConverter::jpegFileToBmpStreamInternal(FsFile& jpegFile, Print& bm
|
|||||||
constexpr int MAX_MCU_ROW_BYTES = 65536;
|
constexpr int MAX_MCU_ROW_BYTES = 65536;
|
||||||
|
|
||||||
if (imageInfo.m_width > MAX_IMAGE_WIDTH || imageInfo.m_height > MAX_IMAGE_HEIGHT) {
|
if (imageInfo.m_width > MAX_IMAGE_WIDTH || imageInfo.m_height > MAX_IMAGE_HEIGHT) {
|
||||||
Serial.printf("[%lu] [JPG] Image too large (%dx%d), max supported: %dx%d\n", millis(), imageInfo.m_width,
|
LOG_DBG("JPG", "Image too large (%dx%d), max supported: %dx%d", imageInfo.m_width, imageInfo.m_height,
|
||||||
imageInfo.m_height, MAX_IMAGE_WIDTH, MAX_IMAGE_HEIGHT);
|
MAX_IMAGE_WIDTH, MAX_IMAGE_HEIGHT);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -262,8 +261,8 @@ bool JpegToBmpConverter::jpegFileToBmpStreamInternal(FsFile& jpegFile, Print& bm
|
|||||||
scaleY_fp = (static_cast<uint32_t>(imageInfo.m_height) << 16) / outHeight;
|
scaleY_fp = (static_cast<uint32_t>(imageInfo.m_height) << 16) / outHeight;
|
||||||
needsScaling = true;
|
needsScaling = true;
|
||||||
|
|
||||||
Serial.printf("[%lu] [JPG] Pre-scaling %dx%d -> %dx%d (fit to %dx%d)\n", millis(), imageInfo.m_width,
|
LOG_DBG("JPG", "Pre-scaling %dx%d -> %dx%d (fit to %dx%d)", imageInfo.m_width, imageInfo.m_height, outWidth,
|
||||||
imageInfo.m_height, outWidth, outHeight, targetWidth, targetHeight);
|
outHeight, targetWidth, targetHeight);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Write BMP header with output dimensions
|
// Write BMP header with output dimensions
|
||||||
@@ -282,7 +281,7 @@ bool JpegToBmpConverter::jpegFileToBmpStreamInternal(FsFile& jpegFile, Print& bm
|
|||||||
// Allocate row buffer
|
// Allocate row buffer
|
||||||
auto* rowBuffer = static_cast<uint8_t*>(malloc(bytesPerRow));
|
auto* rowBuffer = static_cast<uint8_t*>(malloc(bytesPerRow));
|
||||||
if (!rowBuffer) {
|
if (!rowBuffer) {
|
||||||
Serial.printf("[%lu] [JPG] Failed to allocate row buffer\n", millis());
|
LOG_ERR("JPG", "Failed to allocate row buffer");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -293,15 +292,14 @@ bool JpegToBmpConverter::jpegFileToBmpStreamInternal(FsFile& jpegFile, Print& bm
|
|||||||
|
|
||||||
// Validate MCU row buffer size before allocation
|
// Validate MCU row buffer size before allocation
|
||||||
if (mcuRowPixels > MAX_MCU_ROW_BYTES) {
|
if (mcuRowPixels > MAX_MCU_ROW_BYTES) {
|
||||||
Serial.printf("[%lu] [JPG] MCU row buffer too large (%d bytes), max: %d\n", millis(), mcuRowPixels,
|
LOG_DBG("JPG", "MCU row buffer too large (%d bytes), max: %d", mcuRowPixels, MAX_MCU_ROW_BYTES);
|
||||||
MAX_MCU_ROW_BYTES);
|
|
||||||
free(rowBuffer);
|
free(rowBuffer);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
auto* mcuRowBuffer = static_cast<uint8_t*>(malloc(mcuRowPixels));
|
auto* mcuRowBuffer = static_cast<uint8_t*>(malloc(mcuRowPixels));
|
||||||
if (!mcuRowBuffer) {
|
if (!mcuRowBuffer) {
|
||||||
Serial.printf("[%lu] [JPG] Failed to allocate MCU row buffer (%d bytes)\n", millis(), mcuRowPixels);
|
LOG_ERR("JPG", "Failed to allocate MCU row buffer (%d bytes)", mcuRowPixels);
|
||||||
free(rowBuffer);
|
free(rowBuffer);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@@ -349,10 +347,9 @@ bool JpegToBmpConverter::jpegFileToBmpStreamInternal(FsFile& jpegFile, Print& bm
|
|||||||
const unsigned char mcuStatus = pjpeg_decode_mcu();
|
const unsigned char mcuStatus = pjpeg_decode_mcu();
|
||||||
if (mcuStatus != 0) {
|
if (mcuStatus != 0) {
|
||||||
if (mcuStatus == PJPG_NO_MORE_BLOCKS) {
|
if (mcuStatus == PJPG_NO_MORE_BLOCKS) {
|
||||||
Serial.printf("[%lu] [JPG] Unexpected end of blocks at MCU (%d, %d)\n", millis(), mcuX, mcuY);
|
LOG_ERR("JPG", "Unexpected end of blocks at MCU (%d, %d)", mcuX, mcuY);
|
||||||
} else {
|
} else {
|
||||||
Serial.printf("[%lu] [JPG] JPEG decode MCU failed at (%d, %d) with error code: %d\n", millis(), mcuX, mcuY,
|
LOG_ERR("JPG", "JPEG decode MCU failed at (%d, %d) with error code: %d", mcuX, mcuY, mcuStatus);
|
||||||
mcuStatus);
|
|
||||||
}
|
}
|
||||||
free(mcuRowBuffer);
|
free(mcuRowBuffer);
|
||||||
free(rowBuffer);
|
free(rowBuffer);
|
||||||
@@ -549,7 +546,7 @@ bool JpegToBmpConverter::jpegFileToBmpStreamInternal(FsFile& jpegFile, Print& bm
|
|||||||
free(mcuRowBuffer);
|
free(mcuRowBuffer);
|
||||||
free(rowBuffer);
|
free(rowBuffer);
|
||||||
|
|
||||||
Serial.printf("[%lu] [JPG] Successfully converted JPEG to BMP\n", millis());
|
LOG_DBG("JPG", "Successfully converted JPEG to BMP");
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -567,5 +564,5 @@ bool JpegToBmpConverter::jpegFileToBmpStreamWithSize(FsFile& jpegFile, Print& bm
|
|||||||
// Convert to 1-bit BMP (black and white only, no grays) for fast home screen rendering
|
// Convert to 1-bit BMP (black and white only, no grays) for fast home screen rendering
|
||||||
bool JpegToBmpConverter::jpegFileTo1BitBmpStreamWithSize(FsFile& jpegFile, Print& bmpOut, int targetMaxWidth,
|
bool JpegToBmpConverter::jpegFileTo1BitBmpStreamWithSize(FsFile& jpegFile, Print& bmpOut, int targetMaxWidth,
|
||||||
int targetMaxHeight) {
|
int targetMaxHeight) {
|
||||||
return jpegFileToBmpStreamInternal(jpegFile, bmpOut, targetMaxWidth, targetMaxHeight, true);
|
return jpegFileToBmpStreamInternal(jpegFile, bmpOut, targetMaxWidth, targetMaxHeight, true, true);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
#include "KOReaderCredentialStore.h"
|
#include "KOReaderCredentialStore.h"
|
||||||
|
|
||||||
#include <HardwareSerial.h>
|
#include <HalStorage.h>
|
||||||
|
#include <Logging.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;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -44,7 +44,7 @@ bool KOReaderCredentialStore::saveToFile() const {
|
|||||||
|
|
||||||
// Write username (plaintext - not particularly sensitive)
|
// Write username (plaintext - not particularly sensitive)
|
||||||
serialization::writeString(file, username);
|
serialization::writeString(file, username);
|
||||||
Serial.printf("[%lu] [KRS] Saving username: %s\n", millis(), username.c_str());
|
LOG_DBG("KRS", "Saving username: %s", username.c_str());
|
||||||
|
|
||||||
// Write password (obfuscated)
|
// Write password (obfuscated)
|
||||||
std::string obfuscatedPwd = password;
|
std::string obfuscatedPwd = password;
|
||||||
@@ -58,14 +58,14 @@ bool KOReaderCredentialStore::saveToFile() const {
|
|||||||
serialization::writePod(file, static_cast<uint8_t>(matchMethod));
|
serialization::writePod(file, static_cast<uint8_t>(matchMethod));
|
||||||
|
|
||||||
file.close();
|
file.close();
|
||||||
Serial.printf("[%lu] [KRS] Saved KOReader credentials to file\n", millis());
|
LOG_DBG("KRS", "Saved KOReader credentials to file");
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
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());
|
LOG_DBG("KRS", "No credentials file found");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -73,7 +73,7 @@ bool KOReaderCredentialStore::loadFromFile() {
|
|||||||
uint8_t version;
|
uint8_t version;
|
||||||
serialization::readPod(file, version);
|
serialization::readPod(file, version);
|
||||||
if (version != KOREADER_FILE_VERSION) {
|
if (version != KOREADER_FILE_VERSION) {
|
||||||
Serial.printf("[%lu] [KRS] Unknown file version: %u\n", millis(), version);
|
LOG_DBG("KRS", "Unknown file version: %u", version);
|
||||||
file.close();
|
file.close();
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@@ -110,14 +110,14 @@ bool KOReaderCredentialStore::loadFromFile() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
file.close();
|
file.close();
|
||||||
Serial.printf("[%lu] [KRS] Loaded KOReader credentials for user: %s\n", millis(), username.c_str());
|
LOG_DBG("KRS", "Loaded KOReader credentials for user: %s", username.c_str());
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
void KOReaderCredentialStore::setCredentials(const std::string& user, const std::string& pass) {
|
void KOReaderCredentialStore::setCredentials(const std::string& user, const std::string& pass) {
|
||||||
username = user;
|
username = user;
|
||||||
password = pass;
|
password = pass;
|
||||||
Serial.printf("[%lu] [KRS] Set credentials for user: %s\n", millis(), user.c_str());
|
LOG_DBG("KRS", "Set credentials for user: %s", user.c_str());
|
||||||
}
|
}
|
||||||
|
|
||||||
std::string KOReaderCredentialStore::getMd5Password() const {
|
std::string KOReaderCredentialStore::getMd5Password() const {
|
||||||
@@ -140,12 +140,12 @@ void KOReaderCredentialStore::clearCredentials() {
|
|||||||
username.clear();
|
username.clear();
|
||||||
password.clear();
|
password.clear();
|
||||||
saveToFile();
|
saveToFile();
|
||||||
Serial.printf("[%lu] [KRS] Cleared KOReader credentials\n", millis());
|
LOG_DBG("KRS", "Cleared KOReader credentials");
|
||||||
}
|
}
|
||||||
|
|
||||||
void KOReaderCredentialStore::setServerUrl(const std::string& url) {
|
void KOReaderCredentialStore::setServerUrl(const std::string& url) {
|
||||||
serverUrl = url;
|
serverUrl = url;
|
||||||
Serial.printf("[%lu] [KRS] Set server URL: %s\n", millis(), url.empty() ? "(default)" : url.c_str());
|
LOG_DBG("KRS", "Set server URL: %s", url.empty() ? "(default)" : url.c_str());
|
||||||
}
|
}
|
||||||
|
|
||||||
std::string KOReaderCredentialStore::getBaseUrl() const {
|
std::string KOReaderCredentialStore::getBaseUrl() const {
|
||||||
@@ -163,6 +163,5 @@ std::string KOReaderCredentialStore::getBaseUrl() const {
|
|||||||
|
|
||||||
void KOReaderCredentialStore::setMatchMethod(DocumentMatchMethod method) {
|
void KOReaderCredentialStore::setMatchMethod(DocumentMatchMethod method) {
|
||||||
matchMethod = method;
|
matchMethod = method;
|
||||||
Serial.printf("[%lu] [KRS] Set match method: %s\n", millis(),
|
LOG_DBG("KRS", "Set match method: %s", method == DocumentMatchMethod::FILENAME ? "Filename" : "Binary");
|
||||||
method == DocumentMatchMethod::FILENAME ? "Filename" : "Binary");
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
#include "KOReaderDocumentId.h"
|
#include "KOReaderDocumentId.h"
|
||||||
|
|
||||||
#include <HardwareSerial.h>
|
#include <HalStorage.h>
|
||||||
|
#include <Logging.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 '/')
|
||||||
@@ -27,7 +27,7 @@ std::string KOReaderDocumentId::calculateFromFilename(const std::string& filePat
|
|||||||
md5.calculate();
|
md5.calculate();
|
||||||
|
|
||||||
std::string result = md5.toString().c_str();
|
std::string result = md5.toString().c_str();
|
||||||
Serial.printf("[%lu] [KODoc] Filename hash: %s (from '%s')\n", millis(), result.c_str(), filename.c_str());
|
LOG_DBG("KODoc", "Filename hash: %s (from '%s')", result.c_str(), filename.c_str());
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -43,13 +43,13 @@ 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());
|
LOG_DBG("KODoc", "Failed to open file: %s", filePath.c_str());
|
||||||
return "";
|
return "";
|
||||||
}
|
}
|
||||||
|
|
||||||
const size_t fileSize = file.fileSize();
|
const size_t fileSize = file.fileSize();
|
||||||
Serial.printf("[%lu] [KODoc] Calculating hash for file: %s (size: %zu)\n", millis(), filePath.c_str(), fileSize);
|
LOG_DBG("KODoc", "Calculating hash for file: %s (size: %zu)", filePath.c_str(), fileSize);
|
||||||
|
|
||||||
// Initialize MD5 builder
|
// Initialize MD5 builder
|
||||||
MD5Builder md5;
|
MD5Builder md5;
|
||||||
@@ -70,7 +70,7 @@ std::string KOReaderDocumentId::calculate(const std::string& filePath) {
|
|||||||
|
|
||||||
// Seek to offset
|
// Seek to offset
|
||||||
if (!file.seekSet(offset)) {
|
if (!file.seekSet(offset)) {
|
||||||
Serial.printf("[%lu] [KODoc] Failed to seek to offset %zu\n", millis(), offset);
|
LOG_DBG("KODoc", "Failed to seek to offset %zu", offset);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -90,7 +90,7 @@ std::string KOReaderDocumentId::calculate(const std::string& filePath) {
|
|||||||
md5.calculate();
|
md5.calculate();
|
||||||
std::string result = md5.toString().c_str();
|
std::string result = md5.toString().c_str();
|
||||||
|
|
||||||
Serial.printf("[%lu] [KODoc] Hash calculated: %s (from %zu bytes)\n", millis(), result.c_str(), totalBytesRead);
|
LOG_DBG("KODoc", "Hash calculated: %s (from %zu bytes)", result.c_str(), totalBytesRead);
|
||||||
|
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
#include <ArduinoJson.h>
|
#include <ArduinoJson.h>
|
||||||
#include <HTTPClient.h>
|
#include <HTTPClient.h>
|
||||||
#include <HardwareSerial.h>
|
#include <Logging.h>
|
||||||
#include <WiFi.h>
|
#include <WiFi.h>
|
||||||
#include <WiFiClientSecure.h>
|
#include <WiFiClientSecure.h>
|
||||||
|
|
||||||
@@ -19,6 +19,10 @@ void addAuthHeaders(HTTPClient& http) {
|
|||||||
http.addHeader("Accept", "application/vnd.koreader.v1+json");
|
http.addHeader("Accept", "application/vnd.koreader.v1+json");
|
||||||
http.addHeader("x-auth-user", KOREADER_STORE.getUsername().c_str());
|
http.addHeader("x-auth-user", KOREADER_STORE.getUsername().c_str());
|
||||||
http.addHeader("x-auth-key", KOREADER_STORE.getMd5Password().c_str());
|
http.addHeader("x-auth-key", KOREADER_STORE.getMd5Password().c_str());
|
||||||
|
|
||||||
|
// HTTP Basic Auth (RFC 7617) header. This is needed to support koreader sync server embedded in Calibre Web Automated
|
||||||
|
// (https://github.com/crocodilestick/Calibre-Web-Automated/blob/main/cps/progress_syncing/protocols/kosync.py)
|
||||||
|
http.setAuthorization(KOREADER_STORE.getUsername().c_str(), KOREADER_STORE.getPassword().c_str());
|
||||||
}
|
}
|
||||||
|
|
||||||
bool isHttpsUrl(const std::string& url) { return url.rfind("https://", 0) == 0; }
|
bool isHttpsUrl(const std::string& url) { return url.rfind("https://", 0) == 0; }
|
||||||
@@ -26,12 +30,12 @@ bool isHttpsUrl(const std::string& url) { return url.rfind("https://", 0) == 0;
|
|||||||
|
|
||||||
KOReaderSyncClient::Error KOReaderSyncClient::authenticate() {
|
KOReaderSyncClient::Error KOReaderSyncClient::authenticate() {
|
||||||
if (!KOREADER_STORE.hasCredentials()) {
|
if (!KOREADER_STORE.hasCredentials()) {
|
||||||
Serial.printf("[%lu] [KOSync] No credentials configured\n", millis());
|
LOG_DBG("KOSync", "No credentials configured");
|
||||||
return NO_CREDENTIALS;
|
return NO_CREDENTIALS;
|
||||||
}
|
}
|
||||||
|
|
||||||
std::string url = KOREADER_STORE.getBaseUrl() + "/users/auth";
|
std::string url = KOREADER_STORE.getBaseUrl() + "/users/auth";
|
||||||
Serial.printf("[%lu] [KOSync] Authenticating: %s\n", millis(), url.c_str());
|
LOG_DBG("KOSync", "Authenticating: %s", url.c_str());
|
||||||
|
|
||||||
HTTPClient http;
|
HTTPClient http;
|
||||||
std::unique_ptr<WiFiClientSecure> secureClient;
|
std::unique_ptr<WiFiClientSecure> secureClient;
|
||||||
@@ -49,7 +53,7 @@ KOReaderSyncClient::Error KOReaderSyncClient::authenticate() {
|
|||||||
const int httpCode = http.GET();
|
const int httpCode = http.GET();
|
||||||
http.end();
|
http.end();
|
||||||
|
|
||||||
Serial.printf("[%lu] [KOSync] Auth response: %d\n", millis(), httpCode);
|
LOG_DBG("KOSync", "Auth response: %d", httpCode);
|
||||||
|
|
||||||
if (httpCode == 200) {
|
if (httpCode == 200) {
|
||||||
return OK;
|
return OK;
|
||||||
@@ -64,12 +68,12 @@ KOReaderSyncClient::Error KOReaderSyncClient::authenticate() {
|
|||||||
KOReaderSyncClient::Error KOReaderSyncClient::getProgress(const std::string& documentHash,
|
KOReaderSyncClient::Error KOReaderSyncClient::getProgress(const std::string& documentHash,
|
||||||
KOReaderProgress& outProgress) {
|
KOReaderProgress& outProgress) {
|
||||||
if (!KOREADER_STORE.hasCredentials()) {
|
if (!KOREADER_STORE.hasCredentials()) {
|
||||||
Serial.printf("[%lu] [KOSync] No credentials configured\n", millis());
|
LOG_DBG("KOSync", "No credentials configured");
|
||||||
return NO_CREDENTIALS;
|
return NO_CREDENTIALS;
|
||||||
}
|
}
|
||||||
|
|
||||||
std::string url = KOREADER_STORE.getBaseUrl() + "/syncs/progress/" + documentHash;
|
std::string url = KOREADER_STORE.getBaseUrl() + "/syncs/progress/" + documentHash;
|
||||||
Serial.printf("[%lu] [KOSync] Getting progress: %s\n", millis(), url.c_str());
|
LOG_DBG("KOSync", "Getting progress: %s", url.c_str());
|
||||||
|
|
||||||
HTTPClient http;
|
HTTPClient http;
|
||||||
std::unique_ptr<WiFiClientSecure> secureClient;
|
std::unique_ptr<WiFiClientSecure> secureClient;
|
||||||
@@ -95,7 +99,7 @@ KOReaderSyncClient::Error KOReaderSyncClient::getProgress(const std::string& doc
|
|||||||
const DeserializationError error = deserializeJson(doc, responseBody);
|
const DeserializationError error = deserializeJson(doc, responseBody);
|
||||||
|
|
||||||
if (error) {
|
if (error) {
|
||||||
Serial.printf("[%lu] [KOSync] JSON parse failed: %s\n", millis(), error.c_str());
|
LOG_ERR("KOSync", "JSON parse failed: %s", error.c_str());
|
||||||
return JSON_ERROR;
|
return JSON_ERROR;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -106,14 +110,13 @@ KOReaderSyncClient::Error KOReaderSyncClient::getProgress(const std::string& doc
|
|||||||
outProgress.deviceId = doc["device_id"].as<std::string>();
|
outProgress.deviceId = doc["device_id"].as<std::string>();
|
||||||
outProgress.timestamp = doc["timestamp"].as<int64_t>();
|
outProgress.timestamp = doc["timestamp"].as<int64_t>();
|
||||||
|
|
||||||
Serial.printf("[%lu] [KOSync] Got progress: %.2f%% at %s\n", millis(), outProgress.percentage * 100,
|
LOG_DBG("KOSync", "Got progress: %.2f%% at %s", outProgress.percentage * 100, outProgress.progress.c_str());
|
||||||
outProgress.progress.c_str());
|
|
||||||
return OK;
|
return OK;
|
||||||
}
|
}
|
||||||
|
|
||||||
http.end();
|
http.end();
|
||||||
|
|
||||||
Serial.printf("[%lu] [KOSync] Get progress response: %d\n", millis(), httpCode);
|
LOG_DBG("KOSync", "Get progress response: %d", httpCode);
|
||||||
|
|
||||||
if (httpCode == 401) {
|
if (httpCode == 401) {
|
||||||
return AUTH_FAILED;
|
return AUTH_FAILED;
|
||||||
@@ -127,12 +130,12 @@ KOReaderSyncClient::Error KOReaderSyncClient::getProgress(const std::string& doc
|
|||||||
|
|
||||||
KOReaderSyncClient::Error KOReaderSyncClient::updateProgress(const KOReaderProgress& progress) {
|
KOReaderSyncClient::Error KOReaderSyncClient::updateProgress(const KOReaderProgress& progress) {
|
||||||
if (!KOREADER_STORE.hasCredentials()) {
|
if (!KOREADER_STORE.hasCredentials()) {
|
||||||
Serial.printf("[%lu] [KOSync] No credentials configured\n", millis());
|
LOG_DBG("KOSync", "No credentials configured");
|
||||||
return NO_CREDENTIALS;
|
return NO_CREDENTIALS;
|
||||||
}
|
}
|
||||||
|
|
||||||
std::string url = KOREADER_STORE.getBaseUrl() + "/syncs/progress";
|
std::string url = KOREADER_STORE.getBaseUrl() + "/syncs/progress";
|
||||||
Serial.printf("[%lu] [KOSync] Updating progress: %s\n", millis(), url.c_str());
|
LOG_DBG("KOSync", "Updating progress: %s", url.c_str());
|
||||||
|
|
||||||
HTTPClient http;
|
HTTPClient http;
|
||||||
std::unique_ptr<WiFiClientSecure> secureClient;
|
std::unique_ptr<WiFiClientSecure> secureClient;
|
||||||
@@ -159,12 +162,12 @@ KOReaderSyncClient::Error KOReaderSyncClient::updateProgress(const KOReaderProgr
|
|||||||
std::string body;
|
std::string body;
|
||||||
serializeJson(doc, body);
|
serializeJson(doc, body);
|
||||||
|
|
||||||
Serial.printf("[%lu] [KOSync] Request body: %s\n", millis(), body.c_str());
|
LOG_DBG("KOSync", "Request body: %s", body.c_str());
|
||||||
|
|
||||||
const int httpCode = http.PUT(body.c_str());
|
const int httpCode = http.PUT(body.c_str());
|
||||||
http.end();
|
http.end();
|
||||||
|
|
||||||
Serial.printf("[%lu] [KOSync] Update progress response: %d\n", millis(), httpCode);
|
LOG_DBG("KOSync", "Update progress response: %d", httpCode);
|
||||||
|
|
||||||
if (httpCode == 200 || httpCode == 202) {
|
if (httpCode == 200 || httpCode == 202) {
|
||||||
return OK;
|
return OK;
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
#include "ProgressMapper.h"
|
#include "ProgressMapper.h"
|
||||||
|
|
||||||
#include <HardwareSerial.h>
|
#include <Logging.h>
|
||||||
|
|
||||||
#include <cmath>
|
#include <cmath>
|
||||||
|
|
||||||
@@ -23,8 +23,8 @@ KOReaderPosition ProgressMapper::toKOReader(const std::shared_ptr<Epub>& epub, c
|
|||||||
const int tocIndex = epub->getTocIndexForSpineIndex(pos.spineIndex);
|
const int tocIndex = epub->getTocIndexForSpineIndex(pos.spineIndex);
|
||||||
const std::string chapterName = (tocIndex >= 0) ? epub->getTocItem(tocIndex).title : "unknown";
|
const std::string chapterName = (tocIndex >= 0) ? epub->getTocItem(tocIndex).title : "unknown";
|
||||||
|
|
||||||
Serial.printf("[%lu] [ProgressMapper] CrossPoint -> KOReader: chapter='%s', page=%d/%d -> %.2f%% at %s\n", millis(),
|
LOG_DBG("ProgressMapper", "CrossPoint -> KOReader: chapter='%s', page=%d/%d -> %.2f%% at %s", chapterName.c_str(),
|
||||||
chapterName.c_str(), pos.pageNumber, pos.totalPages, result.percentage * 100, result.xpath.c_str());
|
pos.pageNumber, pos.totalPages, result.percentage * 100, result.xpath.c_str());
|
||||||
|
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
@@ -76,8 +76,8 @@ CrossPointPosition ProgressMapper::toCrossPoint(const std::shared_ptr<Epub>& epu
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Serial.printf("[%lu] [ProgressMapper] KOReader -> CrossPoint: %.2f%% at %s -> spine=%d, page=%d\n", millis(),
|
LOG_DBG("ProgressMapper", "KOReader -> CrossPoint: %.2f%% at %s -> spine=%d, page=%d", koPos.percentage * 100,
|
||||||
koPos.percentage * 100, koPos.xpath.c_str(), result.spineIndex, result.pageNumber);
|
koPos.xpath.c_str(), result.spineIndex, result.pageNumber);
|
||||||
|
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|||||||
47
lib/Logging/Logging.cpp
Normal file
47
lib/Logging/Logging.cpp
Normal file
@@ -0,0 +1,47 @@
|
|||||||
|
#include "Logging.h"
|
||||||
|
|
||||||
|
// Since logging can take a large amount of flash, we want to make the format string as short as possible.
|
||||||
|
// This logPrintf prepend the timestamp, level and origin to the user-provided message, so that the user only needs to
|
||||||
|
// provide the format string for the message itself.
|
||||||
|
void logPrintf(const char* level, const char* origin, const char* format, ...) {
|
||||||
|
if (!logSerial) {
|
||||||
|
return; // Serial not initialized, skip logging
|
||||||
|
}
|
||||||
|
va_list args;
|
||||||
|
va_start(args, format);
|
||||||
|
char buf[256];
|
||||||
|
char* c = buf;
|
||||||
|
// add the timestamp
|
||||||
|
{
|
||||||
|
unsigned long ms = millis();
|
||||||
|
int len = snprintf(c, sizeof(buf), "[%lu] ", ms);
|
||||||
|
if (len < 0) {
|
||||||
|
return; // encoding error, skip logging
|
||||||
|
}
|
||||||
|
c += len;
|
||||||
|
}
|
||||||
|
// add the level
|
||||||
|
{
|
||||||
|
const char* p = level;
|
||||||
|
size_t remaining = sizeof(buf) - (c - buf);
|
||||||
|
while (*p && remaining > 1) {
|
||||||
|
*c++ = *p++;
|
||||||
|
remaining--;
|
||||||
|
}
|
||||||
|
if (remaining > 1) {
|
||||||
|
*c++ = ' ';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// add the origin
|
||||||
|
{
|
||||||
|
int len = snprintf(c, sizeof(buf) - (c - buf), "[%s] ", origin);
|
||||||
|
if (len < 0) {
|
||||||
|
return; // encoding error, skip logging
|
||||||
|
}
|
||||||
|
c += len;
|
||||||
|
}
|
||||||
|
// add the user message
|
||||||
|
vsnprintf(c, sizeof(buf) - (c - buf), format, args);
|
||||||
|
va_end(args);
|
||||||
|
logSerial.print(buf);
|
||||||
|
}
|
||||||
71
lib/Logging/Logging.h
Normal file
71
lib/Logging/Logging.h
Normal file
@@ -0,0 +1,71 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <HardwareSerial.h>
|
||||||
|
|
||||||
|
/*
|
||||||
|
Define ENABLE_SERIAL_LOG to enable logging
|
||||||
|
Can be set in platformio.ini build_flags or as a compile definition
|
||||||
|
|
||||||
|
Define LOG_LEVEL to control log verbosity:
|
||||||
|
0 = ERR only
|
||||||
|
1 = ERR + INF
|
||||||
|
2 = ERR + INF + DBG
|
||||||
|
If not defined, defaults to 0
|
||||||
|
|
||||||
|
If you have a legitimate need for raw Serial access (e.g., binary data,
|
||||||
|
special formatting), use the underlying logSerial object directly:
|
||||||
|
logSerial.printf("Special case: %d\n", value);
|
||||||
|
logSerial.write(binaryData, length);
|
||||||
|
|
||||||
|
The logSerial reference (defined below) points to the real Serial object and
|
||||||
|
won't trigger deprecation warnings.
|
||||||
|
*/
|
||||||
|
|
||||||
|
#ifndef LOG_LEVEL
|
||||||
|
#define LOG_LEVEL 0
|
||||||
|
#endif
|
||||||
|
|
||||||
|
static HWCDC& logSerial = Serial;
|
||||||
|
|
||||||
|
void logPrintf(const char* level, const char* origin, const char* format, ...);
|
||||||
|
|
||||||
|
#ifdef ENABLE_SERIAL_LOG
|
||||||
|
#if LOG_LEVEL >= 0
|
||||||
|
#define LOG_ERR(origin, format, ...) logPrintf("[ERR]", origin, format "\n", ##__VA_ARGS__)
|
||||||
|
#else
|
||||||
|
#define LOG_ERR(origin, format, ...)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if LOG_LEVEL >= 1
|
||||||
|
#define LOG_INF(origin, format, ...) logPrintf("[INF]", origin, format "\n", ##__VA_ARGS__)
|
||||||
|
#else
|
||||||
|
#define LOG_INF(origin, format, ...)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if LOG_LEVEL >= 2
|
||||||
|
#define LOG_DBG(origin, format, ...) logPrintf("[DBG]", origin, format "\n", ##__VA_ARGS__)
|
||||||
|
#else
|
||||||
|
#define LOG_DBG(origin, format, ...)
|
||||||
|
#endif
|
||||||
|
#else
|
||||||
|
#define LOG_DBG(origin, format, ...)
|
||||||
|
#define LOG_ERR(origin, format, ...)
|
||||||
|
#define LOG_INF(origin, format, ...)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
class MySerialImpl : public Print {
|
||||||
|
public:
|
||||||
|
void begin(unsigned long baud) { logSerial.begin(baud); }
|
||||||
|
|
||||||
|
// Support boolean conversion for compatibility with code like:
|
||||||
|
// if (Serial) or while (!Serial)
|
||||||
|
operator bool() const { return logSerial; }
|
||||||
|
|
||||||
|
__attribute__((deprecated("Use LOG_* macro instead"))) size_t printf(const char* format, ...);
|
||||||
|
size_t write(uint8_t b) override;
|
||||||
|
size_t write(const uint8_t* buffer, size_t size) override;
|
||||||
|
void flush() override;
|
||||||
|
static MySerialImpl instance;
|
||||||
|
};
|
||||||
|
|
||||||
|
#define Serial MySerialImpl::instance
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
#include "OpdsParser.h"
|
#include "OpdsParser.h"
|
||||||
|
|
||||||
#include <HardwareSerial.h>
|
#include <Logging.h>
|
||||||
|
|
||||||
#include <cstring>
|
#include <cstring>
|
||||||
|
|
||||||
@@ -8,7 +8,7 @@ OpdsParser::OpdsParser() {
|
|||||||
parser = XML_ParserCreate(nullptr);
|
parser = XML_ParserCreate(nullptr);
|
||||||
if (!parser) {
|
if (!parser) {
|
||||||
errorOccured = true;
|
errorOccured = true;
|
||||||
Serial.printf("[%lu] [OPDS] Couldn't allocate memory for parser\n", millis());
|
LOG_DBG("OPDS", "Couldn't allocate memory for parser");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -42,7 +42,7 @@ size_t OpdsParser::write(const uint8_t* xmlData, const size_t length) {
|
|||||||
void* const buf = XML_GetBuffer(parser, chunkSize);
|
void* const buf = XML_GetBuffer(parser, chunkSize);
|
||||||
if (!buf) {
|
if (!buf) {
|
||||||
errorOccured = true;
|
errorOccured = true;
|
||||||
Serial.printf("[%lu] [OPDS] Couldn't allocate memory for buffer\n", millis());
|
LOG_DBG("OPDS", "Couldn't allocate memory for buffer");
|
||||||
XML_ParserFree(parser);
|
XML_ParserFree(parser);
|
||||||
parser = nullptr;
|
parser = nullptr;
|
||||||
return length;
|
return length;
|
||||||
@@ -53,7 +53,7 @@ size_t OpdsParser::write(const uint8_t* xmlData, const size_t length) {
|
|||||||
|
|
||||||
if (XML_ParseBuffer(parser, static_cast<int>(toRead), 0) == XML_STATUS_ERROR) {
|
if (XML_ParseBuffer(parser, static_cast<int>(toRead), 0) == XML_STATUS_ERROR) {
|
||||||
errorOccured = true;
|
errorOccured = true;
|
||||||
Serial.printf("[%lu] [OPDS] Parse error at line %lu: %s\n", millis(), XML_GetCurrentLineNumber(parser),
|
LOG_DBG("OPDS", "Parse error at line %lu: %s", XML_GetCurrentLineNumber(parser),
|
||||||
XML_ErrorString(XML_GetErrorCode(parser)));
|
XML_ErrorString(XML_GetErrorCode(parser)));
|
||||||
XML_ParserFree(parser);
|
XML_ParserFree(parser);
|
||||||
parser = nullptr;
|
parser = nullptr;
|
||||||
|
|||||||
27
lib/PlaceholderCover/BookIcon.h
Normal file
27
lib/PlaceholderCover/BookIcon.h
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
#pragma once
|
||||||
|
#include <cstdint>
|
||||||
|
|
||||||
|
// Book icon: 48x48, 1-bit packed (MSB first)
|
||||||
|
// 0 = black, 1 = white (same format as Logo120.h)
|
||||||
|
static constexpr int BOOK_ICON_WIDTH = 48;
|
||||||
|
static constexpr int BOOK_ICON_HEIGHT = 48;
|
||||||
|
static const uint8_t BookIcon[] = {
|
||||||
|
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfc, 0x00, 0x00, 0x00,
|
||||||
|
0x00, 0x1f, 0xfc, 0x00, 0x00, 0x00, 0x00, 0x1f, 0xfc, 0x1f, 0xff, 0xff, 0xff, 0x9f, 0xfc, 0x1f,
|
||||||
|
0xff, 0xff, 0xff, 0x9f, 0xfc, 0x1f, 0xff, 0xff, 0xff, 0x9f, 0xfc, 0x1f, 0xff, 0xff, 0xff, 0x9f,
|
||||||
|
0xfc, 0x1f, 0xff, 0xff, 0xff, 0x9f, 0xfc, 0x1f, 0xff, 0xff, 0xff, 0x9f, 0xfc, 0x1f, 0xff, 0xff,
|
||||||
|
0xff, 0x9f, 0xfc, 0x1f, 0xff, 0xff, 0xff, 0x9f, 0xfc, 0x1c, 0x00, 0x00, 0x01, 0x9f, 0xfc, 0x1f,
|
||||||
|
0xff, 0xff, 0xff, 0x9f, 0xfc, 0x1f, 0xff, 0xff, 0xff, 0x9f, 0xfc, 0x1f, 0xff, 0xff, 0xff, 0x9f,
|
||||||
|
0xfc, 0x1f, 0xff, 0xff, 0xff, 0x9f, 0xfc, 0x1f, 0xff, 0xff, 0xff, 0x9f, 0xfc, 0x1c, 0x00, 0x01,
|
||||||
|
0xff, 0x9f, 0xfc, 0x1f, 0xff, 0xff, 0xff, 0x9f, 0xfc, 0x1f, 0xff, 0xff, 0xff, 0x9f, 0xfc, 0x1f,
|
||||||
|
0xff, 0xff, 0xff, 0x9f, 0xfc, 0x1f, 0xff, 0xff, 0xff, 0x9f, 0xfc, 0x1f, 0xff, 0xff, 0xff, 0x9f,
|
||||||
|
0xfc, 0x1c, 0x00, 0x00, 0x1f, 0x9f, 0xfc, 0x1f, 0xff, 0xff, 0xff, 0x9f, 0xfc, 0x1f, 0xff, 0xff,
|
||||||
|
0xff, 0x9f, 0xfc, 0x1f, 0xff, 0xff, 0xff, 0x9f, 0xfc, 0x1f, 0xff, 0xff, 0xff, 0x9f, 0xfc, 0x1f,
|
||||||
|
0xff, 0xff, 0xff, 0x9f, 0xfc, 0x1f, 0xff, 0xff, 0xff, 0x9f, 0xfc, 0x1f, 0xff, 0xff, 0xff, 0x9f,
|
||||||
|
0xfc, 0x1f, 0xff, 0xff, 0xff, 0x9f, 0xfc, 0x1f, 0xff, 0xff, 0xff, 0x9f, 0xfc, 0x1f, 0xff, 0xff,
|
||||||
|
0xff, 0x9f, 0xfc, 0x1f, 0xff, 0xff, 0xff, 0x9f, 0xfc, 0x1f, 0xff, 0xff, 0xff, 0x9f, 0xfc, 0x1f,
|
||||||
|
0xff, 0xff, 0xff, 0x9f, 0xfc, 0x1f, 0xff, 0xff, 0xff, 0x9f, 0xfc, 0x00, 0x00, 0x00, 0x00, 0x1f,
|
||||||
|
0xfc, 0x00, 0x00, 0x00, 0x00, 0x1f, 0xff, 0x00, 0x00, 0x00, 0x00, 0x3f, 0xff, 0x00, 0x00, 0x00,
|
||||||
|
0x00, 0x3f, 0xff, 0x00, 0x00, 0x00, 0x00, 0x3f, 0xff, 0x00, 0x00, 0x00, 0x00, 0x3f, 0xff, 0xff,
|
||||||
|
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||||
|
};
|
||||||
480
lib/PlaceholderCover/PlaceholderCoverGenerator.cpp
Normal file
480
lib/PlaceholderCover/PlaceholderCoverGenerator.cpp
Normal file
@@ -0,0 +1,480 @@
|
|||||||
|
#include "PlaceholderCoverGenerator.h"
|
||||||
|
|
||||||
|
#include <EpdFont.h>
|
||||||
|
#include <HalStorage.h>
|
||||||
|
#include <Logging.h>
|
||||||
|
#include <Utf8.h>
|
||||||
|
|
||||||
|
#include <algorithm>
|
||||||
|
#include <cstring>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
// Include the UI fonts directly for self-contained placeholder rendering.
|
||||||
|
// These are 1-bit bitmap fonts compiled from Ubuntu TTF.
|
||||||
|
#include "builtinFonts/ubuntu_10_regular.h"
|
||||||
|
#include "builtinFonts/ubuntu_12_bold.h"
|
||||||
|
|
||||||
|
// Book icon bitmap (48x48 1-bit, generated by scripts/generate_book_icon.py)
|
||||||
|
#include "BookIcon.h"
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
|
||||||
|
// BMP writing helpers (same format as JpegToBmpConverter)
|
||||||
|
inline void write16(Print& out, const uint16_t value) {
|
||||||
|
out.write(value & 0xFF);
|
||||||
|
out.write((value >> 8) & 0xFF);
|
||||||
|
}
|
||||||
|
|
||||||
|
inline void write32(Print& out, const uint32_t value) {
|
||||||
|
out.write(value & 0xFF);
|
||||||
|
out.write((value >> 8) & 0xFF);
|
||||||
|
out.write((value >> 16) & 0xFF);
|
||||||
|
out.write((value >> 24) & 0xFF);
|
||||||
|
}
|
||||||
|
|
||||||
|
inline void write32Signed(Print& out, const int32_t value) {
|
||||||
|
out.write(value & 0xFF);
|
||||||
|
out.write((value >> 8) & 0xFF);
|
||||||
|
out.write((value >> 16) & 0xFF);
|
||||||
|
out.write((value >> 24) & 0xFF);
|
||||||
|
}
|
||||||
|
|
||||||
|
void writeBmpHeader1bit(Print& bmpOut, const int width, const int height) {
|
||||||
|
const int bytesPerRow = (width + 31) / 32 * 4;
|
||||||
|
const int imageSize = bytesPerRow * height;
|
||||||
|
const uint32_t fileSize = 62 + imageSize;
|
||||||
|
|
||||||
|
// BMP File Header (14 bytes)
|
||||||
|
bmpOut.write('B');
|
||||||
|
bmpOut.write('M');
|
||||||
|
write32(bmpOut, fileSize);
|
||||||
|
write32(bmpOut, 0); // Reserved
|
||||||
|
write32(bmpOut, 62); // Offset to pixel data
|
||||||
|
|
||||||
|
// DIB Header (BITMAPINFOHEADER - 40 bytes)
|
||||||
|
write32(bmpOut, 40);
|
||||||
|
write32Signed(bmpOut, width);
|
||||||
|
write32Signed(bmpOut, -height); // Negative = top-down
|
||||||
|
write16(bmpOut, 1); // Color planes
|
||||||
|
write16(bmpOut, 1); // Bits per pixel
|
||||||
|
write32(bmpOut, 0); // BI_RGB
|
||||||
|
write32(bmpOut, imageSize);
|
||||||
|
write32(bmpOut, 2835); // xPixelsPerMeter
|
||||||
|
write32(bmpOut, 2835); // yPixelsPerMeter
|
||||||
|
write32(bmpOut, 2); // colorsUsed
|
||||||
|
write32(bmpOut, 2); // colorsImportant
|
||||||
|
|
||||||
|
// Palette: index 0 = black, index 1 = white
|
||||||
|
const uint8_t palette[8] = {
|
||||||
|
0x00, 0x00, 0x00, 0x00, // Black
|
||||||
|
0xFF, 0xFF, 0xFF, 0x00 // White
|
||||||
|
};
|
||||||
|
for (const uint8_t b : palette) {
|
||||||
|
bmpOut.write(b);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 1-bit pixel buffer that can render text, icons, and shapes, then write as BMP.
|
||||||
|
class PixelBuffer {
|
||||||
|
public:
|
||||||
|
PixelBuffer(int width, int height) : width(width), height(height) {
|
||||||
|
bytesPerRow = (width + 31) / 32 * 4;
|
||||||
|
bufferSize = bytesPerRow * height;
|
||||||
|
buffer = static_cast<uint8_t*>(malloc(bufferSize));
|
||||||
|
if (buffer) {
|
||||||
|
memset(buffer, 0xFF, bufferSize); // White background
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
~PixelBuffer() {
|
||||||
|
if (buffer) {
|
||||||
|
free(buffer);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
bool isValid() const { return buffer != nullptr; }
|
||||||
|
|
||||||
|
/// Set a pixel to black.
|
||||||
|
void setBlack(int x, int y) {
|
||||||
|
if (x < 0 || x >= width || y < 0 || y >= height) return;
|
||||||
|
const int byteIndex = y * bytesPerRow + x / 8;
|
||||||
|
const uint8_t bitMask = 0x80 >> (x % 8);
|
||||||
|
buffer[byteIndex] &= ~bitMask;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Set a scaled "pixel" (scale x scale block) to black.
|
||||||
|
void setBlackScaled(int x, int y, int scale) {
|
||||||
|
for (int dy = 0; dy < scale; dy++) {
|
||||||
|
for (int dx = 0; dx < scale; dx++) {
|
||||||
|
setBlack(x + dx, y + dy);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Draw a filled rectangle in black.
|
||||||
|
void fillRect(int x, int y, int w, int h) {
|
||||||
|
for (int row = y; row < y + h && row < height; row++) {
|
||||||
|
for (int col = x; col < x + w && col < width; col++) {
|
||||||
|
setBlack(col, row);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Draw a rectangular border in black.
|
||||||
|
void drawBorder(int x, int y, int w, int h, int thickness) {
|
||||||
|
fillRect(x, y, w, thickness); // Top
|
||||||
|
fillRect(x, y + h - thickness, w, thickness); // Bottom
|
||||||
|
fillRect(x, y, thickness, h); // Left
|
||||||
|
fillRect(x + w - thickness, y, thickness, h); // Right
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Draw a horizontal line in black with configurable thickness.
|
||||||
|
void drawHLine(int x, int y, int length, int thickness = 1) {
|
||||||
|
fillRect(x, y, length, thickness);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Render a single glyph at (cursorX, baselineY) with integer scaling. Returns advance in X (scaled).
|
||||||
|
int renderGlyph(const EpdFontData* font, uint32_t codepoint, int cursorX, int baselineY, int scale = 1) {
|
||||||
|
const EpdFont fontObj(font);
|
||||||
|
const EpdGlyph* glyph = fontObj.getGlyph(codepoint);
|
||||||
|
if (!glyph) {
|
||||||
|
glyph = fontObj.getGlyph(REPLACEMENT_GLYPH);
|
||||||
|
}
|
||||||
|
if (!glyph) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
const uint8_t* bitmap = &font->bitmap[glyph->dataOffset];
|
||||||
|
const int glyphW = glyph->width;
|
||||||
|
const int glyphH = glyph->height;
|
||||||
|
|
||||||
|
for (int gy = 0; gy < glyphH; gy++) {
|
||||||
|
const int screenY = baselineY - glyph->top * scale + gy * scale;
|
||||||
|
for (int gx = 0; gx < glyphW; gx++) {
|
||||||
|
const int pixelPos = gy * glyphW + gx;
|
||||||
|
const int screenX = cursorX + glyph->left * scale + gx * scale;
|
||||||
|
|
||||||
|
bool isSet = false;
|
||||||
|
if (font->is2Bit) {
|
||||||
|
const uint8_t byte = bitmap[pixelPos / 4];
|
||||||
|
const uint8_t bitIndex = (3 - pixelPos % 4) * 2;
|
||||||
|
const uint8_t val = 3 - ((byte >> bitIndex) & 0x3);
|
||||||
|
isSet = (val < 3);
|
||||||
|
} else {
|
||||||
|
const uint8_t byte = bitmap[pixelPos / 8];
|
||||||
|
const uint8_t bitIndex = 7 - (pixelPos % 8);
|
||||||
|
isSet = ((byte >> bitIndex) & 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isSet) {
|
||||||
|
setBlackScaled(screenX, screenY, scale);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return glyph->advanceX * scale;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Render a UTF-8 string at (x, y) where y is the top of the text line, with integer scaling.
|
||||||
|
void drawText(const EpdFontData* font, int x, int y, const char* text, int scale = 1) {
|
||||||
|
const int baselineY = y + font->ascender * scale;
|
||||||
|
int cursorX = x;
|
||||||
|
uint32_t cp;
|
||||||
|
while ((cp = utf8NextCodepoint(reinterpret_cast<const uint8_t**>(&text)))) {
|
||||||
|
cursorX += renderGlyph(font, cp, cursorX, baselineY, scale);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Draw a 1-bit icon bitmap (MSB first, 0=black, 1=white) with integer scaling.
|
||||||
|
void drawIcon(const uint8_t* icon, int iconW, int iconH, int x, int y, int scale = 1) {
|
||||||
|
const int bytesPerIconRow = iconW / 8;
|
||||||
|
for (int iy = 0; iy < iconH; iy++) {
|
||||||
|
for (int ix = 0; ix < iconW; ix++) {
|
||||||
|
const int byteIdx = iy * bytesPerIconRow + ix / 8;
|
||||||
|
const uint8_t bitMask = 0x80 >> (ix % 8);
|
||||||
|
// In the icon data: 0 = black (drawn), 1 = white (skip)
|
||||||
|
if (!(icon[byteIdx] & bitMask)) {
|
||||||
|
const int sx = x + ix * scale;
|
||||||
|
const int sy = y + iy * scale;
|
||||||
|
setBlackScaled(sx, sy, scale);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Write the pixel buffer to a file as a 1-bit BMP.
|
||||||
|
bool writeBmp(Print& out) const {
|
||||||
|
if (!buffer) return false;
|
||||||
|
writeBmpHeader1bit(out, width, height);
|
||||||
|
out.write(buffer, bufferSize);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
int getWidth() const { return width; }
|
||||||
|
int getHeight() const { return height; }
|
||||||
|
|
||||||
|
private:
|
||||||
|
int width;
|
||||||
|
int height;
|
||||||
|
int bytesPerRow;
|
||||||
|
size_t bufferSize;
|
||||||
|
uint8_t* buffer;
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Measure the width of a UTF-8 string in pixels (at 1x scale).
|
||||||
|
int measureTextWidth(const EpdFontData* font, const char* text) {
|
||||||
|
const EpdFont fontObj(font);
|
||||||
|
int w = 0, h = 0;
|
||||||
|
fontObj.getTextDimensions(text, &w, &h);
|
||||||
|
return w;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get the advance width of a single character.
|
||||||
|
int getCharAdvance(const EpdFontData* font, uint32_t cp) {
|
||||||
|
const EpdFont fontObj(font);
|
||||||
|
const EpdGlyph* glyph = fontObj.getGlyph(cp);
|
||||||
|
if (!glyph) return 0;
|
||||||
|
return glyph->advanceX;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Split a string into words (splitting on spaces).
|
||||||
|
std::vector<std::string> splitWords(const std::string& text) {
|
||||||
|
std::vector<std::string> words;
|
||||||
|
std::string current;
|
||||||
|
for (size_t i = 0; i < text.size(); i++) {
|
||||||
|
if (text[i] == ' ') {
|
||||||
|
if (!current.empty()) {
|
||||||
|
words.push_back(current);
|
||||||
|
current.clear();
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
current += text[i];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!current.empty()) {
|
||||||
|
words.push_back(current);
|
||||||
|
}
|
||||||
|
return words;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Word-wrap text into lines that fit within maxWidth pixels at the given scale.
|
||||||
|
std::vector<std::string> wrapText(const EpdFontData* font, const std::string& text, int maxWidth, int scale = 1) {
|
||||||
|
std::vector<std::string> lines;
|
||||||
|
const auto words = splitWords(text);
|
||||||
|
if (words.empty()) return lines;
|
||||||
|
|
||||||
|
const int spaceWidth = getCharAdvance(font, ' ') * scale;
|
||||||
|
std::string currentLine;
|
||||||
|
int currentWidth = 0;
|
||||||
|
|
||||||
|
for (const auto& word : words) {
|
||||||
|
const int wordWidth = measureTextWidth(font, word.c_str()) * scale;
|
||||||
|
|
||||||
|
if (currentLine.empty()) {
|
||||||
|
currentLine = word;
|
||||||
|
currentWidth = wordWidth;
|
||||||
|
} else if (currentWidth + spaceWidth + wordWidth <= maxWidth) {
|
||||||
|
currentLine += " " + word;
|
||||||
|
currentWidth += spaceWidth + wordWidth;
|
||||||
|
} else {
|
||||||
|
lines.push_back(currentLine);
|
||||||
|
currentLine = word;
|
||||||
|
currentWidth = wordWidth;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!currentLine.empty()) {
|
||||||
|
lines.push_back(currentLine);
|
||||||
|
}
|
||||||
|
|
||||||
|
return lines;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Truncate a string with "..." if it exceeds maxWidth pixels at the given scale.
|
||||||
|
std::string truncateText(const EpdFontData* font, const std::string& text, int maxWidth, int scale = 1) {
|
||||||
|
if (measureTextWidth(font, text.c_str()) * scale <= maxWidth) {
|
||||||
|
return text;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string truncated = text;
|
||||||
|
const char* ellipsis = "...";
|
||||||
|
const int ellipsisWidth = measureTextWidth(font, ellipsis) * scale;
|
||||||
|
|
||||||
|
while (!truncated.empty()) {
|
||||||
|
utf8RemoveLastChar(truncated);
|
||||||
|
if (measureTextWidth(font, truncated.c_str()) * scale + ellipsisWidth <= maxWidth) {
|
||||||
|
return truncated + ellipsis;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return ellipsis;
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
bool PlaceholderCoverGenerator::generate(const std::string& outputPath, const std::string& title,
|
||||||
|
const std::string& author, int width, int height) {
|
||||||
|
LOG_DBG("PHC", "Generating placeholder cover %dx%d: \"%s\" by \"%s\"", width, height, title.c_str(), author.c_str());
|
||||||
|
|
||||||
|
const EpdFontData* titleFont = &ubuntu_12_bold;
|
||||||
|
const EpdFontData* authorFont = &ubuntu_10_regular;
|
||||||
|
|
||||||
|
PixelBuffer buf(width, height);
|
||||||
|
if (!buf.isValid()) {
|
||||||
|
LOG_ERR("PHC", "Failed to allocate %dx%d pixel buffer (%d bytes)", width, height,
|
||||||
|
(width + 31) / 32 * 4 * height);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Proportional layout constants based on cover dimensions.
|
||||||
|
// The device bezel covers ~2-3px on each edge, so we pad inward from the edge.
|
||||||
|
const int edgePadding = std::max(3, width / 48); // ~10px at 480w, ~3px at 136w
|
||||||
|
const int borderWidth = std::max(2, width / 96); // ~5px at 480w, ~2px at 136w
|
||||||
|
const int innerPadding = std::max(4, width / 32); // ~15px at 480w, ~4px at 136w
|
||||||
|
|
||||||
|
// Text scaling: 2x for full-size covers, 1x for thumbnails
|
||||||
|
const int titleScale = (height >= 600) ? 2 : 1;
|
||||||
|
const int authorScale = (height >= 600) ? 2 : 1; // Author also larger on full covers
|
||||||
|
// Icon: 2x for full cover, 1x for medium thumb, skip for small
|
||||||
|
const int iconScale = (height >= 600) ? 2 : (height >= 350 ? 1 : 0);
|
||||||
|
|
||||||
|
// Draw border inset from edge
|
||||||
|
buf.drawBorder(edgePadding, edgePadding, width - 2 * edgePadding, height - 2 * edgePadding, borderWidth);
|
||||||
|
|
||||||
|
// Content area (inside border + inner padding)
|
||||||
|
const int contentX = edgePadding + borderWidth + innerPadding;
|
||||||
|
const int contentY = edgePadding + borderWidth + innerPadding;
|
||||||
|
const int contentW = width - 2 * contentX;
|
||||||
|
const int contentH = height - 2 * contentY;
|
||||||
|
|
||||||
|
if (contentW <= 0 || contentH <= 0) {
|
||||||
|
LOG_ERR("PHC", "Cover too small for content (%dx%d)", width, height);
|
||||||
|
FsFile file;
|
||||||
|
if (!Storage.openFileForWrite("PHC", outputPath, file)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
buf.writeBmp(file);
|
||||||
|
file.close();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Layout zones ---
|
||||||
|
// Title zone: top 2/3 of content area (icon + title)
|
||||||
|
// Author zone: bottom 1/3 of content area
|
||||||
|
const int titleZoneH = contentH * 2 / 3;
|
||||||
|
const int authorZoneH = contentH - titleZoneH;
|
||||||
|
const int authorZoneY = contentY + titleZoneH;
|
||||||
|
|
||||||
|
// --- Separator line at the zone boundary ---
|
||||||
|
const int separatorWidth = contentW / 3;
|
||||||
|
const int separatorX = contentX + (contentW - separatorWidth) / 2;
|
||||||
|
buf.drawHLine(separatorX, authorZoneY, separatorWidth);
|
||||||
|
|
||||||
|
// --- Icon dimensions (needed for title text wrapping) ---
|
||||||
|
const int iconW = (iconScale > 0) ? BOOK_ICON_WIDTH * iconScale : 0;
|
||||||
|
const int iconGap = (iconScale > 0) ? std::max(8, width / 40) : 0; // Gap between icon and title text
|
||||||
|
const int titleTextW = contentW - iconW - iconGap; // Title wraps in narrower area beside icon
|
||||||
|
|
||||||
|
// --- Prepare title text (wraps within the area to the right of the icon) ---
|
||||||
|
const std::string displayTitle = title.empty() ? "Untitled" : title;
|
||||||
|
auto titleLines = wrapText(titleFont, displayTitle, titleTextW, titleScale);
|
||||||
|
|
||||||
|
constexpr int MAX_TITLE_LINES = 5;
|
||||||
|
if (static_cast<int>(titleLines.size()) > MAX_TITLE_LINES) {
|
||||||
|
titleLines.resize(MAX_TITLE_LINES);
|
||||||
|
titleLines.back() = truncateText(titleFont, titleLines.back(), titleTextW, titleScale);
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Prepare author text (multi-line, max 3 lines) ---
|
||||||
|
std::vector<std::string> authorLines;
|
||||||
|
if (!author.empty()) {
|
||||||
|
authorLines = wrapText(authorFont, author, contentW, authorScale);
|
||||||
|
constexpr int MAX_AUTHOR_LINES = 3;
|
||||||
|
if (static_cast<int>(authorLines.size()) > MAX_AUTHOR_LINES) {
|
||||||
|
authorLines.resize(MAX_AUTHOR_LINES);
|
||||||
|
authorLines.back() = truncateText(authorFont, authorLines.back(), contentW, authorScale);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Calculate title zone layout (icon LEFT of title) ---
|
||||||
|
// Tighter line spacing so 2-3 title lines fit within the icon height
|
||||||
|
const int titleLineH = titleFont->advanceY * titleScale * 3 / 4;
|
||||||
|
const int iconH = (iconScale > 0) ? BOOK_ICON_HEIGHT * iconScale : 0;
|
||||||
|
const int numTitleLines = static_cast<int>(titleLines.size());
|
||||||
|
// Visual height: distance from top of first line to bottom of last line's glyphs.
|
||||||
|
// Use ascender (not full advanceY) for the last line since trailing line-gap isn't visible.
|
||||||
|
const int titleVisualH = (numTitleLines > 0)
|
||||||
|
? (numTitleLines - 1) * titleLineH + titleFont->ascender * titleScale
|
||||||
|
: 0;
|
||||||
|
const int titleBlockH = std::max(iconH, titleVisualH); // Taller of icon or text
|
||||||
|
|
||||||
|
int titleStartY = contentY + (titleZoneH - titleBlockH) / 2;
|
||||||
|
if (titleStartY < contentY) {
|
||||||
|
titleStartY = contentY;
|
||||||
|
}
|
||||||
|
|
||||||
|
// If title fits within icon height, center it vertically against the icon.
|
||||||
|
// Otherwise top-align so extra lines overflow below.
|
||||||
|
const int iconY = titleStartY;
|
||||||
|
const int titleTextY = (iconH > 0 && titleVisualH <= iconH)
|
||||||
|
? titleStartY + (iconH - titleVisualH) / 2
|
||||||
|
: titleStartY;
|
||||||
|
|
||||||
|
// --- Horizontal centering: measure the widest title line, then center icon+gap+text block ---
|
||||||
|
int maxTitleLineW = 0;
|
||||||
|
for (const auto& line : titleLines) {
|
||||||
|
const int w = measureTextWidth(titleFont, line.c_str()) * titleScale;
|
||||||
|
if (w > maxTitleLineW) maxTitleLineW = w;
|
||||||
|
}
|
||||||
|
const int titleBlockW = iconW + iconGap + maxTitleLineW;
|
||||||
|
const int titleBlockX = contentX + (contentW - titleBlockW) / 2;
|
||||||
|
|
||||||
|
// --- Draw icon ---
|
||||||
|
if (iconScale > 0) {
|
||||||
|
buf.drawIcon(BookIcon, BOOK_ICON_WIDTH, BOOK_ICON_HEIGHT, titleBlockX, iconY, iconScale);
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Draw title lines (to the right of the icon) ---
|
||||||
|
const int titleTextX = titleBlockX + iconW + iconGap;
|
||||||
|
int currentY = titleTextY;
|
||||||
|
for (const auto& line : titleLines) {
|
||||||
|
buf.drawText(titleFont, titleTextX, currentY, line.c_str(), titleScale);
|
||||||
|
currentY += titleLineH;
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Draw author lines (centered vertically in bottom 1/3, centered horizontally) ---
|
||||||
|
if (!authorLines.empty()) {
|
||||||
|
const int authorLineH = authorFont->advanceY * authorScale;
|
||||||
|
const int authorBlockH = static_cast<int>(authorLines.size()) * authorLineH;
|
||||||
|
int authorStartY = authorZoneY + (authorZoneH - authorBlockH) / 2;
|
||||||
|
if (authorStartY < authorZoneY + 4) {
|
||||||
|
authorStartY = authorZoneY + 4; // Small gap below separator
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const auto& line : authorLines) {
|
||||||
|
const int lineWidth = measureTextWidth(authorFont, line.c_str()) * authorScale;
|
||||||
|
const int lineX = contentX + (contentW - lineWidth) / 2;
|
||||||
|
buf.drawText(authorFont, lineX, authorStartY, line.c_str(), authorScale);
|
||||||
|
authorStartY += authorLineH;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Write to file ---
|
||||||
|
FsFile file;
|
||||||
|
if (!Storage.openFileForWrite("PHC", outputPath, file)) {
|
||||||
|
LOG_ERR("PHC", "Failed to open output file: %s", outputPath.c_str());
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
const bool success = buf.writeBmp(file);
|
||||||
|
file.close();
|
||||||
|
|
||||||
|
if (success) {
|
||||||
|
LOG_DBG("PHC", "Placeholder cover written to %s", outputPath.c_str());
|
||||||
|
} else {
|
||||||
|
LOG_ERR("PHC", "Failed to write placeholder BMP");
|
||||||
|
Storage.remove(outputPath.c_str());
|
||||||
|
}
|
||||||
|
|
||||||
|
return success;
|
||||||
|
}
|
||||||
14
lib/PlaceholderCover/PlaceholderCoverGenerator.h
Normal file
14
lib/PlaceholderCover/PlaceholderCoverGenerator.h
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <string>
|
||||||
|
|
||||||
|
/// Generates simple 1-bit BMP placeholder covers with title/author text
|
||||||
|
/// for books that have no embedded cover image.
|
||||||
|
class PlaceholderCoverGenerator {
|
||||||
|
public:
|
||||||
|
/// Generate a placeholder cover BMP with title and author text.
|
||||||
|
/// The BMP is written to outputPath as a 1-bit black-and-white image.
|
||||||
|
/// Returns true if the file was written successfully.
|
||||||
|
static bool generate(const std::string& outputPath, const std::string& title, const std::string& author, int width,
|
||||||
|
int height);
|
||||||
|
};
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
#include <SdFat.h>
|
#include <HalStorage.h>
|
||||||
|
|
||||||
#include <iostream>
|
#include <iostream>
|
||||||
|
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
#include <FsHelpers.h>
|
#include <FsHelpers.h>
|
||||||
#include <JpegToBmpConverter.h>
|
#include <JpegToBmpConverter.h>
|
||||||
|
#include <Logging.h>
|
||||||
|
|
||||||
Txt::Txt(std::string path, std::string cacheBasePath)
|
Txt::Txt(std::string path, std::string cacheBasePath)
|
||||||
: filepath(std::move(path)), cacheBasePath(std::move(cacheBasePath)) {
|
: filepath(std::move(path)), cacheBasePath(std::move(cacheBasePath)) {
|
||||||
@@ -15,14 +16,14 @@ 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());
|
LOG_ERR("TXT", "File does not exist: %s", 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());
|
LOG_ERR("TXT", "Failed to open file: %s", filepath.c_str());
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -30,7 +31,7 @@ bool Txt::load() {
|
|||||||
file.close();
|
file.close();
|
||||||
|
|
||||||
loaded = true;
|
loaded = true;
|
||||||
Serial.printf("[%lu] [TXT] Loaded TXT file: %s (%zu bytes)\n", millis(), filepath.c_str(), fileSize);
|
LOG_DBG("TXT", "Loaded TXT file: %s (%zu bytes)", filepath.c_str(), fileSize);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -48,11 +49,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,8 +74,8 @@ 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());
|
LOG_DBG("TXT", "Found matching cover image: %s", coverPath.c_str());
|
||||||
return coverPath;
|
return coverPath;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -84,8 +85,8 @@ 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());
|
LOG_DBG("TXT", "Found fallback cover image: %s", coverPath.c_str());
|
||||||
return coverPath;
|
return coverPath;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -96,15 +97,18 @@ std::string Txt::findCoverImage() const {
|
|||||||
|
|
||||||
std::string Txt::getCoverBmpPath() const { return cachePath + "/cover.bmp"; }
|
std::string Txt::getCoverBmpPath() const { return cachePath + "/cover.bmp"; }
|
||||||
|
|
||||||
|
std::string Txt::getThumbBmpPath() const { return cachePath + "/thumb_[HEIGHT].bmp"; }
|
||||||
|
std::string Txt::getThumbBmpPath(int height) const { return cachePath + "/thumb_" + std::to_string(height) + ".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;
|
||||||
}
|
}
|
||||||
|
|
||||||
std::string coverImagePath = findCoverImage();
|
std::string coverImagePath = findCoverImage();
|
||||||
if (coverImagePath.empty()) {
|
if (coverImagePath.empty()) {
|
||||||
Serial.printf("[%lu] [TXT] No cover image found for TXT file\n", millis());
|
LOG_DBG("TXT", "No cover image found for TXT file");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -120,12 +124,12 @@ bool Txt::generateCoverBmp() const {
|
|||||||
|
|
||||||
if (isBmp) {
|
if (isBmp) {
|
||||||
// Copy BMP file to cache
|
// Copy BMP file to cache
|
||||||
Serial.printf("[%lu] [TXT] Copying BMP cover image to cache\n", millis());
|
LOG_DBG("TXT", "Copying BMP cover image to cache");
|
||||||
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;
|
||||||
}
|
}
|
||||||
@@ -136,18 +140,18 @@ bool Txt::generateCoverBmp() const {
|
|||||||
}
|
}
|
||||||
src.close();
|
src.close();
|
||||||
dst.close();
|
dst.close();
|
||||||
Serial.printf("[%lu] [TXT] Copied BMP cover to cache\n", millis());
|
LOG_DBG("TXT", "Copied BMP cover to cache");
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (isJpg) {
|
if (isJpg) {
|
||||||
// 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());
|
LOG_DBG("TXT", "Generating BMP from JPG cover image");
|
||||||
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;
|
||||||
}
|
}
|
||||||
@@ -156,16 +160,16 @@ bool Txt::generateCoverBmp() const {
|
|||||||
coverBmp.close();
|
coverBmp.close();
|
||||||
|
|
||||||
if (!success) {
|
if (!success) {
|
||||||
Serial.printf("[%lu] [TXT] Failed to generate BMP from JPG cover image\n", millis());
|
LOG_ERR("TXT", "Failed to generate BMP from JPG cover image");
|
||||||
SdMan.remove(getCoverBmpPath().c_str());
|
Storage.remove(getCoverBmpPath().c_str());
|
||||||
} else {
|
} else {
|
||||||
Serial.printf("[%lu] [TXT] Generated BMP from JPG cover image\n", millis());
|
LOG_DBG("TXT", "Generated BMP from JPG cover image");
|
||||||
}
|
}
|
||||||
return success;
|
return success;
|
||||||
}
|
}
|
||||||
|
|
||||||
// PNG files are not supported (would need a PNG decoder)
|
// PNG files are not supported (would need a PNG decoder)
|
||||||
Serial.printf("[%lu] [TXT] Cover image format not supported (only BMP/JPG/JPEG)\n", millis());
|
LOG_ERR("TXT", "Cover image format not supported (only BMP/JPG/JPEG)");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -175,7 +179,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;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include <SDCardManager.h>
|
#include <HalStorage.h>
|
||||||
|
|
||||||
#include <memory>
|
#include <memory>
|
||||||
#include <string>
|
#include <string>
|
||||||
@@ -28,6 +28,10 @@ class Txt {
|
|||||||
[[nodiscard]] bool generateCoverBmp() const;
|
[[nodiscard]] bool generateCoverBmp() const;
|
||||||
[[nodiscard]] std::string findCoverImage() const;
|
[[nodiscard]] std::string findCoverImage() const;
|
||||||
|
|
||||||
|
// Thumbnail paths (matching Epub/Xtc pattern for home screen covers)
|
||||||
|
[[nodiscard]] std::string getThumbBmpPath() const;
|
||||||
|
[[nodiscard]] std::string getThumbBmpPath(int height) const;
|
||||||
|
|
||||||
// Read content from file
|
// Read content from file
|
||||||
[[nodiscard]] bool readContent(uint8_t* buffer, size_t offset, size_t length) const;
|
[[nodiscard]] bool readContent(uint8_t* buffer, size_t offset, size_t length) const;
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -29,3 +29,20 @@ uint32_t utf8NextCodepoint(const unsigned char** string) {
|
|||||||
|
|
||||||
return cp;
|
return cp;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
size_t utf8RemoveLastChar(std::string& str) {
|
||||||
|
if (str.empty()) return 0;
|
||||||
|
size_t pos = str.size() - 1;
|
||||||
|
while (pos > 0 && (static_cast<unsigned char>(str[pos]) & 0xC0) == 0x80) {
|
||||||
|
--pos;
|
||||||
|
}
|
||||||
|
str.resize(pos);
|
||||||
|
return pos;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Truncate string by removing N UTF-8 characters from the end
|
||||||
|
void utf8TruncateChars(std::string& str, const size_t numChars) {
|
||||||
|
for (size_t i = 0; i < numChars && !str.empty(); ++i) {
|
||||||
|
utf8RemoveLastChar(str);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,7 +1,11 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include <cstdint>
|
#include <cstdint>
|
||||||
|
#include <string>
|
||||||
#define REPLACEMENT_GLYPH 0xFFFD
|
#define REPLACEMENT_GLYPH 0xFFFD
|
||||||
|
|
||||||
uint32_t utf8NextCodepoint(const unsigned char** string);
|
uint32_t utf8NextCodepoint(const unsigned char** string);
|
||||||
|
// Remove the last UTF-8 codepoint from a std::string and return the new size.
|
||||||
|
size_t utf8RemoveLastChar(std::string& str);
|
||||||
|
// Truncate string by removing N UTF-8 codepoints from the end.
|
||||||
|
void utf8TruncateChars(std::string& str, size_t numChars);
|
||||||
|
|||||||
@@ -7,11 +7,11 @@
|
|||||||
|
|
||||||
#include "Xtc.h"
|
#include "Xtc.h"
|
||||||
|
|
||||||
#include <HardwareSerial.h>
|
#include <HalStorage.h>
|
||||||
#include <SDCardManager.h>
|
#include <Logging.h>
|
||||||
|
|
||||||
bool Xtc::load() {
|
bool Xtc::load() {
|
||||||
Serial.printf("[%lu] [XTC] Loading XTC: %s\n", millis(), filepath.c_str());
|
LOG_DBG("XTC", "Loading XTC: %s", filepath.c_str());
|
||||||
|
|
||||||
// Initialize parser
|
// Initialize parser
|
||||||
parser.reset(new xtc::XtcParser());
|
parser.reset(new xtc::XtcParser());
|
||||||
@@ -19,43 +19,43 @@ bool Xtc::load() {
|
|||||||
// Open XTC file
|
// Open XTC file
|
||||||
xtc::XtcError err = parser->open(filepath.c_str());
|
xtc::XtcError err = parser->open(filepath.c_str());
|
||||||
if (err != xtc::XtcError::OK) {
|
if (err != xtc::XtcError::OK) {
|
||||||
Serial.printf("[%lu] [XTC] Failed to load: %s\n", millis(), xtc::errorToString(err));
|
LOG_ERR("XTC", "Failed to load: %s", xtc::errorToString(err));
|
||||||
parser.reset();
|
parser.reset();
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
loaded = true;
|
loaded = true;
|
||||||
Serial.printf("[%lu] [XTC] Loaded XTC: %s (%lu pages)\n", millis(), filepath.c_str(), parser->getPageCount());
|
LOG_DBG("XTC", "Loaded XTC: %s (%lu pages)", filepath.c_str(), parser->getPageCount());
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
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());
|
LOG_DBG("XTC", "Cache does not exist, no action needed");
|
||||||
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());
|
LOG_ERR("XTC", "Failed to clear cache");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
Serial.printf("[%lu] [XTC] Cache cleared successfully\n", millis());
|
LOG_DBG("XTC", "Cache cleared successfully");
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
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,17 +114,17 @@ 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;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!loaded || !parser) {
|
if (!loaded || !parser) {
|
||||||
Serial.printf("[%lu] [XTC] Cannot generate cover BMP, file not loaded\n", millis());
|
LOG_ERR("XTC", "Cannot generate cover BMP, file not loaded");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (parser->getPageCount() == 0) {
|
if (parser->getPageCount() == 0) {
|
||||||
Serial.printf("[%lu] [XTC] No pages in XTC file\n", millis());
|
LOG_ERR("XTC", "No pages in XTC file");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -134,7 +134,7 @@ bool Xtc::generateCoverBmp() const {
|
|||||||
// Get first page info for cover
|
// Get first page info for cover
|
||||||
xtc::PageInfo pageInfo;
|
xtc::PageInfo pageInfo;
|
||||||
if (!parser->getPageInfo(0, pageInfo)) {
|
if (!parser->getPageInfo(0, pageInfo)) {
|
||||||
Serial.printf("[%lu] [XTC] Failed to get first page info\n", millis());
|
LOG_DBG("XTC", "Failed to get first page info");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -152,22 +152,22 @@ bool Xtc::generateCoverBmp() const {
|
|||||||
}
|
}
|
||||||
uint8_t* pageBuffer = static_cast<uint8_t*>(malloc(bitmapSize));
|
uint8_t* pageBuffer = static_cast<uint8_t*>(malloc(bitmapSize));
|
||||||
if (!pageBuffer) {
|
if (!pageBuffer) {
|
||||||
Serial.printf("[%lu] [XTC] Failed to allocate page buffer (%lu bytes)\n", millis(), bitmapSize);
|
LOG_ERR("XTC", "Failed to allocate page buffer (%lu bytes)", bitmapSize);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Load first page (cover)
|
// Load first page (cover)
|
||||||
size_t bytesRead = const_cast<xtc::XtcParser*>(parser.get())->loadPage(0, pageBuffer, bitmapSize);
|
size_t bytesRead = const_cast<xtc::XtcParser*>(parser.get())->loadPage(0, pageBuffer, bitmapSize);
|
||||||
if (bytesRead == 0) {
|
if (bytesRead == 0) {
|
||||||
Serial.printf("[%lu] [XTC] Failed to load cover page\n", millis());
|
LOG_ERR("XTC", "Failed to load cover page");
|
||||||
free(pageBuffer);
|
free(pageBuffer);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 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());
|
LOG_DBG("XTC", "Failed to create cover BMP file");
|
||||||
free(pageBuffer);
|
free(pageBuffer);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@@ -297,25 +297,26 @@ bool Xtc::generateCoverBmp() const {
|
|||||||
coverBmp.close();
|
coverBmp.close();
|
||||||
free(pageBuffer);
|
free(pageBuffer);
|
||||||
|
|
||||||
Serial.printf("[%lu] [XTC] Generated cover BMP: %s\n", millis(), getCoverBmpPath().c_str());
|
LOG_DBG("XTC", "Generated cover BMP: %s", getCoverBmpPath().c_str());
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
std::string Xtc::getThumbBmpPath() const { return cachePath + "/thumb.bmp"; }
|
std::string Xtc::getThumbBmpPath() const { return cachePath + "/thumb_[HEIGHT].bmp"; }
|
||||||
|
std::string Xtc::getThumbBmpPath(int height) const { return cachePath + "/thumb_" + std::to_string(height) + ".bmp"; }
|
||||||
|
|
||||||
bool Xtc::generateThumbBmp() const {
|
bool Xtc::generateThumbBmp(int height) const {
|
||||||
// Already generated
|
// Already generated
|
||||||
if (SdMan.exists(getThumbBmpPath().c_str())) {
|
if (Storage.exists(getThumbBmpPath(height).c_str())) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!loaded || !parser) {
|
if (!loaded || !parser) {
|
||||||
Serial.printf("[%lu] [XTC] Cannot generate thumb BMP, file not loaded\n", millis());
|
LOG_ERR("XTC", "Cannot generate thumb BMP, file not loaded");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (parser->getPageCount() == 0) {
|
if (parser->getPageCount() == 0) {
|
||||||
Serial.printf("[%lu] [XTC] No pages in XTC file\n", millis());
|
LOG_ERR("XTC", "No pages in XTC file");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -325,7 +326,7 @@ bool Xtc::generateThumbBmp() const {
|
|||||||
// Get first page info for cover
|
// Get first page info for cover
|
||||||
xtc::PageInfo pageInfo;
|
xtc::PageInfo pageInfo;
|
||||||
if (!parser->getPageInfo(0, pageInfo)) {
|
if (!parser->getPageInfo(0, pageInfo)) {
|
||||||
Serial.printf("[%lu] [XTC] Failed to get first page info\n", millis());
|
LOG_DBG("XTC", "Failed to get first page info");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -333,13 +334,13 @@ bool Xtc::generateThumbBmp() const {
|
|||||||
const uint8_t bitDepth = parser->getBitDepth();
|
const uint8_t bitDepth = parser->getBitDepth();
|
||||||
|
|
||||||
// Calculate target dimensions for thumbnail (fit within 240x400 Continue Reading card)
|
// Calculate target dimensions for thumbnail (fit within 240x400 Continue Reading card)
|
||||||
constexpr int THUMB_TARGET_WIDTH = 240;
|
int THUMB_TARGET_WIDTH = height * 0.6;
|
||||||
constexpr int THUMB_TARGET_HEIGHT = 400;
|
int THUMB_TARGET_HEIGHT = height;
|
||||||
|
|
||||||
// Calculate scale factor
|
// Calculate scale factor
|
||||||
float scaleX = static_cast<float>(THUMB_TARGET_WIDTH) / pageInfo.width;
|
float scaleX = static_cast<float>(THUMB_TARGET_WIDTH) / pageInfo.width;
|
||||||
float scaleY = static_cast<float>(THUMB_TARGET_HEIGHT) / pageInfo.height;
|
float scaleY = static_cast<float>(THUMB_TARGET_HEIGHT) / pageInfo.height;
|
||||||
float scale = (scaleX < scaleY) ? scaleX : scaleY;
|
float scale = (scaleX > scaleY) ? scaleX : scaleY; // for cropping
|
||||||
|
|
||||||
// Only scale down, never up
|
// Only scale down, never up
|
||||||
if (scale >= 1.0f) {
|
if (scale >= 1.0f) {
|
||||||
@@ -347,8 +348,8 @@ bool Xtc::generateThumbBmp() 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(), 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));
|
||||||
@@ -358,8 +359,8 @@ bool Xtc::generateThumbBmp() const {
|
|||||||
}
|
}
|
||||||
src.close();
|
src.close();
|
||||||
}
|
}
|
||||||
Serial.printf("[%lu] [XTC] Copied cover to thumb (no scaling needed)\n", millis());
|
LOG_DBG("XTC", "Copied cover to thumb (no scaling needed)");
|
||||||
return SdMan.exists(getThumbBmpPath().c_str());
|
return Storage.exists(getThumbBmpPath(height).c_str());
|
||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@@ -367,8 +368,8 @@ bool Xtc::generateThumbBmp() const {
|
|||||||
uint16_t thumbWidth = static_cast<uint16_t>(pageInfo.width * scale);
|
uint16_t thumbWidth = static_cast<uint16_t>(pageInfo.width * scale);
|
||||||
uint16_t thumbHeight = static_cast<uint16_t>(pageInfo.height * scale);
|
uint16_t thumbHeight = static_cast<uint16_t>(pageInfo.height * scale);
|
||||||
|
|
||||||
Serial.printf("[%lu] [XTC] Generating thumb BMP: %dx%d -> %dx%d (scale: %.3f)\n", millis(), pageInfo.width,
|
LOG_DBG("XTC", "Generating thumb BMP: %dx%d -> %dx%d (scale: %.3f)", pageInfo.width, pageInfo.height, thumbWidth,
|
||||||
pageInfo.height, thumbWidth, thumbHeight, scale);
|
thumbHeight, scale);
|
||||||
|
|
||||||
// Allocate buffer for page data
|
// Allocate buffer for page data
|
||||||
size_t bitmapSize;
|
size_t bitmapSize;
|
||||||
@@ -379,22 +380,22 @@ bool Xtc::generateThumbBmp() const {
|
|||||||
}
|
}
|
||||||
uint8_t* pageBuffer = static_cast<uint8_t*>(malloc(bitmapSize));
|
uint8_t* pageBuffer = static_cast<uint8_t*>(malloc(bitmapSize));
|
||||||
if (!pageBuffer) {
|
if (!pageBuffer) {
|
||||||
Serial.printf("[%lu] [XTC] Failed to allocate page buffer (%lu bytes)\n", millis(), bitmapSize);
|
LOG_ERR("XTC", "Failed to allocate page buffer (%lu bytes)", bitmapSize);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Load first page (cover)
|
// Load first page (cover)
|
||||||
size_t bytesRead = const_cast<xtc::XtcParser*>(parser.get())->loadPage(0, pageBuffer, bitmapSize);
|
size_t bytesRead = const_cast<xtc::XtcParser*>(parser.get())->loadPage(0, pageBuffer, bitmapSize);
|
||||||
if (bytesRead == 0) {
|
if (bytesRead == 0) {
|
||||||
Serial.printf("[%lu] [XTC] Failed to load cover page for thumb\n", millis());
|
LOG_ERR("XTC", "Failed to load cover page for thumb");
|
||||||
free(pageBuffer);
|
free(pageBuffer);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 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(), thumbBmp)) {
|
if (!Storage.openFileForWrite("XTC", getThumbBmpPath(height), thumbBmp)) {
|
||||||
Serial.printf("[%lu] [XTC] Failed to create thumb BMP file\n", millis());
|
LOG_DBG("XTC", "Failed to create thumb BMP file");
|
||||||
free(pageBuffer);
|
free(pageBuffer);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@@ -557,8 +558,7 @@ bool Xtc::generateThumbBmp() const {
|
|||||||
thumbBmp.close();
|
thumbBmp.close();
|
||||||
free(pageBuffer);
|
free(pageBuffer);
|
||||||
|
|
||||||
Serial.printf("[%lu] [XTC] Generated thumb BMP (%dx%d): %s\n", millis(), thumbWidth, thumbHeight,
|
LOG_DBG("XTC", "Generated thumb BMP (%dx%d): %s", thumbWidth, thumbHeight, getThumbBmpPath(height).c_str());
|
||||||
getThumbBmpPath().c_str());
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -65,7 +65,8 @@ class Xtc {
|
|||||||
bool generateCoverBmp() const;
|
bool generateCoverBmp() const;
|
||||||
// Thumbnail support (for Continue Reading card)
|
// Thumbnail support (for Continue Reading card)
|
||||||
std::string getThumbBmpPath() const;
|
std::string getThumbBmpPath() const;
|
||||||
bool generateThumbBmp() const;
|
std::string getThumbBmpPath(int height) const;
|
||||||
|
bool generateThumbBmp(int height) const;
|
||||||
|
|
||||||
// Page access
|
// Page access
|
||||||
uint32_t getPageCount() const;
|
uint32_t getPageCount() const;
|
||||||
|
|||||||
@@ -8,8 +8,8 @@
|
|||||||
#include "XtcParser.h"
|
#include "XtcParser.h"
|
||||||
|
|
||||||
#include <FsHelpers.h>
|
#include <FsHelpers.h>
|
||||||
#include <HardwareSerial.h>
|
#include <HalStorage.h>
|
||||||
#include <SDCardManager.h>
|
#include <Logging.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;
|
||||||
}
|
}
|
||||||
@@ -42,7 +42,7 @@ XtcError XtcParser::open(const char* filepath) {
|
|||||||
// Read header
|
// Read header
|
||||||
m_lastError = readHeader();
|
m_lastError = readHeader();
|
||||||
if (m_lastError != XtcError::OK) {
|
if (m_lastError != XtcError::OK) {
|
||||||
Serial.printf("[%lu] [XTC] Failed to read header: %s\n", millis(), errorToString(m_lastError));
|
LOG_DBG("XTC", "Failed to read header: %s", errorToString(m_lastError));
|
||||||
m_file.close();
|
m_file.close();
|
||||||
return m_lastError;
|
return m_lastError;
|
||||||
}
|
}
|
||||||
@@ -51,13 +51,13 @@ XtcError XtcParser::open(const char* filepath) {
|
|||||||
if (m_header.hasMetadata) {
|
if (m_header.hasMetadata) {
|
||||||
m_lastError = readTitle();
|
m_lastError = readTitle();
|
||||||
if (m_lastError != XtcError::OK) {
|
if (m_lastError != XtcError::OK) {
|
||||||
Serial.printf("[%lu] [XTC] Failed to read title: %s\n", millis(), errorToString(m_lastError));
|
LOG_DBG("XTC", "Failed to read title: %s", errorToString(m_lastError));
|
||||||
m_file.close();
|
m_file.close();
|
||||||
return m_lastError;
|
return m_lastError;
|
||||||
}
|
}
|
||||||
m_lastError = readAuthor();
|
m_lastError = readAuthor();
|
||||||
if (m_lastError != XtcError::OK) {
|
if (m_lastError != XtcError::OK) {
|
||||||
Serial.printf("[%lu] [XTC] Failed to read author: %s\n", millis(), errorToString(m_lastError));
|
LOG_DBG("XTC", "Failed to read author: %s", errorToString(m_lastError));
|
||||||
m_file.close();
|
m_file.close();
|
||||||
return m_lastError;
|
return m_lastError;
|
||||||
}
|
}
|
||||||
@@ -66,7 +66,7 @@ XtcError XtcParser::open(const char* filepath) {
|
|||||||
// Read page table
|
// Read page table
|
||||||
m_lastError = readPageTable();
|
m_lastError = readPageTable();
|
||||||
if (m_lastError != XtcError::OK) {
|
if (m_lastError != XtcError::OK) {
|
||||||
Serial.printf("[%lu] [XTC] Failed to read page table: %s\n", millis(), errorToString(m_lastError));
|
LOG_DBG("XTC", "Failed to read page table: %s", errorToString(m_lastError));
|
||||||
m_file.close();
|
m_file.close();
|
||||||
return m_lastError;
|
return m_lastError;
|
||||||
}
|
}
|
||||||
@@ -74,14 +74,13 @@ XtcError XtcParser::open(const char* filepath) {
|
|||||||
// Read chapters if present
|
// Read chapters if present
|
||||||
m_lastError = readChapters();
|
m_lastError = readChapters();
|
||||||
if (m_lastError != XtcError::OK) {
|
if (m_lastError != XtcError::OK) {
|
||||||
Serial.printf("[%lu] [XTC] Failed to read chapters: %s\n", millis(), errorToString(m_lastError));
|
LOG_DBG("XTC", "Failed to read chapters: %s", errorToString(m_lastError));
|
||||||
m_file.close();
|
m_file.close();
|
||||||
return m_lastError;
|
return m_lastError;
|
||||||
}
|
}
|
||||||
|
|
||||||
m_isOpen = true;
|
m_isOpen = true;
|
||||||
Serial.printf("[%lu] [XTC] Opened file: %s (%u pages, %dx%d)\n", millis(), filepath, m_header.pageCount,
|
LOG_DBG("XTC", "Opened file: %s (%u pages, %dx%d)", filepath, m_header.pageCount, m_defaultWidth, m_defaultHeight);
|
||||||
m_defaultWidth, m_defaultHeight);
|
|
||||||
return XtcError::OK;
|
return XtcError::OK;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -106,8 +105,7 @@ XtcError XtcParser::readHeader() {
|
|||||||
|
|
||||||
// Verify magic number (accept both XTC and XTCH)
|
// Verify magic number (accept both XTC and XTCH)
|
||||||
if (m_header.magic != XTC_MAGIC && m_header.magic != XTCH_MAGIC) {
|
if (m_header.magic != XTC_MAGIC && m_header.magic != XTCH_MAGIC) {
|
||||||
Serial.printf("[%lu] [XTC] Invalid magic: 0x%08X (expected 0x%08X or 0x%08X)\n", millis(), m_header.magic,
|
LOG_DBG("XTC", "Invalid magic: 0x%08X (expected 0x%08X or 0x%08X)", m_header.magic, XTC_MAGIC, XTCH_MAGIC);
|
||||||
XTC_MAGIC, XTCH_MAGIC);
|
|
||||||
return XtcError::INVALID_MAGIC;
|
return XtcError::INVALID_MAGIC;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -120,7 +118,7 @@ XtcError XtcParser::readHeader() {
|
|||||||
const bool validVersion = m_header.versionMajor == 1 && m_header.versionMinor == 0 ||
|
const bool validVersion = m_header.versionMajor == 1 && m_header.versionMinor == 0 ||
|
||||||
m_header.versionMajor == 0 && m_header.versionMinor == 1;
|
m_header.versionMajor == 0 && m_header.versionMinor == 1;
|
||||||
if (!validVersion) {
|
if (!validVersion) {
|
||||||
Serial.printf("[%lu] [XTC] Unsupported version: %u.%u\n", millis(), m_header.versionMajor, m_header.versionMinor);
|
LOG_DBG("XTC", "Unsupported version: %u.%u", m_header.versionMajor, m_header.versionMinor);
|
||||||
return XtcError::INVALID_VERSION;
|
return XtcError::INVALID_VERSION;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -129,7 +127,7 @@ XtcError XtcParser::readHeader() {
|
|||||||
return XtcError::CORRUPTED_HEADER;
|
return XtcError::CORRUPTED_HEADER;
|
||||||
}
|
}
|
||||||
|
|
||||||
Serial.printf("[%lu] [XTC] Header: magic=0x%08X (%s), ver=%u.%u, pages=%u, bitDepth=%u\n", millis(), m_header.magic,
|
LOG_DBG("XTC", "Header: magic=0x%08X (%s), ver=%u.%u, pages=%u, bitDepth=%u", m_header.magic,
|
||||||
(m_header.magic == XTCH_MAGIC) ? "XTCH" : "XTC", m_header.versionMajor, m_header.versionMinor,
|
(m_header.magic == XTCH_MAGIC) ? "XTCH" : "XTC", m_header.versionMajor, m_header.versionMinor,
|
||||||
m_header.pageCount, m_bitDepth);
|
m_header.pageCount, m_bitDepth);
|
||||||
|
|
||||||
@@ -146,7 +144,7 @@ XtcError XtcParser::readTitle() {
|
|||||||
m_file.read(titleBuf, sizeof(titleBuf) - 1);
|
m_file.read(titleBuf, sizeof(titleBuf) - 1);
|
||||||
m_title = titleBuf;
|
m_title = titleBuf;
|
||||||
|
|
||||||
Serial.printf("[%lu] [XTC] Title: %s\n", millis(), m_title.c_str());
|
LOG_DBG("XTC", "Title: %s", m_title.c_str());
|
||||||
return XtcError::OK;
|
return XtcError::OK;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -161,19 +159,19 @@ XtcError XtcParser::readAuthor() {
|
|||||||
m_file.read(authorBuf, sizeof(authorBuf) - 1);
|
m_file.read(authorBuf, sizeof(authorBuf) - 1);
|
||||||
m_author = authorBuf;
|
m_author = authorBuf;
|
||||||
|
|
||||||
Serial.printf("[%lu] [XTC] Author: %s\n", millis(), m_author.c_str());
|
LOG_DBG("XTC", "Author: %s", m_author.c_str());
|
||||||
return XtcError::OK;
|
return XtcError::OK;
|
||||||
}
|
}
|
||||||
|
|
||||||
XtcError XtcParser::readPageTable() {
|
XtcError XtcParser::readPageTable() {
|
||||||
if (m_header.pageTableOffset == 0) {
|
if (m_header.pageTableOffset == 0) {
|
||||||
Serial.printf("[%lu] [XTC] Page table offset is 0, cannot read\n", millis());
|
LOG_DBG("XTC", "Page table offset is 0, cannot read");
|
||||||
return XtcError::CORRUPTED_HEADER;
|
return XtcError::CORRUPTED_HEADER;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Seek to page table
|
// Seek to page table
|
||||||
if (!m_file.seek(m_header.pageTableOffset)) {
|
if (!m_file.seek(m_header.pageTableOffset)) {
|
||||||
Serial.printf("[%lu] [XTC] Failed to seek to page table at %llu\n", millis(), m_header.pageTableOffset);
|
LOG_DBG("XTC", "Failed to seek to page table at %llu", m_header.pageTableOffset);
|
||||||
return XtcError::READ_ERROR;
|
return XtcError::READ_ERROR;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -184,7 +182,7 @@ XtcError XtcParser::readPageTable() {
|
|||||||
PageTableEntry entry;
|
PageTableEntry entry;
|
||||||
size_t bytesRead = m_file.read(reinterpret_cast<uint8_t*>(&entry), sizeof(PageTableEntry));
|
size_t bytesRead = m_file.read(reinterpret_cast<uint8_t*>(&entry), sizeof(PageTableEntry));
|
||||||
if (bytesRead != sizeof(PageTableEntry)) {
|
if (bytesRead != sizeof(PageTableEntry)) {
|
||||||
Serial.printf("[%lu] [XTC] Failed to read page table entry %u\n", millis(), i);
|
LOG_DBG("XTC", "Failed to read page table entry %u", i);
|
||||||
return XtcError::READ_ERROR;
|
return XtcError::READ_ERROR;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -201,7 +199,7 @@ XtcError XtcParser::readPageTable() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Serial.printf("[%lu] [XTC] Read %u page table entries\n", millis(), m_header.pageCount);
|
LOG_DBG("XTC", "Read %u page table entries", m_header.pageCount);
|
||||||
return XtcError::OK;
|
return XtcError::OK;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -307,7 +305,7 @@ XtcError XtcParser::readChapters() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
m_hasChapters = !m_chapters.empty();
|
m_hasChapters = !m_chapters.empty();
|
||||||
Serial.printf("[%lu] [XTC] Chapters: %u\n", millis(), static_cast<unsigned int>(m_chapters.size()));
|
LOG_DBG("XTC", "Chapters: %u", static_cast<unsigned int>(m_chapters.size()));
|
||||||
return XtcError::OK;
|
return XtcError::OK;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -334,7 +332,7 @@ size_t XtcParser::loadPage(uint32_t pageIndex, uint8_t* buffer, size_t bufferSiz
|
|||||||
|
|
||||||
// Seek to page data
|
// Seek to page data
|
||||||
if (!m_file.seek(page.offset)) {
|
if (!m_file.seek(page.offset)) {
|
||||||
Serial.printf("[%lu] [XTC] Failed to seek to page %u at offset %lu\n", millis(), pageIndex, page.offset);
|
LOG_DBG("XTC", "Failed to seek to page %u at offset %lu", pageIndex, page.offset);
|
||||||
m_lastError = XtcError::READ_ERROR;
|
m_lastError = XtcError::READ_ERROR;
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
@@ -343,7 +341,7 @@ size_t XtcParser::loadPage(uint32_t pageIndex, uint8_t* buffer, size_t bufferSiz
|
|||||||
XtgPageHeader pageHeader;
|
XtgPageHeader pageHeader;
|
||||||
size_t headerRead = m_file.read(reinterpret_cast<uint8_t*>(&pageHeader), sizeof(XtgPageHeader));
|
size_t headerRead = m_file.read(reinterpret_cast<uint8_t*>(&pageHeader), sizeof(XtgPageHeader));
|
||||||
if (headerRead != sizeof(XtgPageHeader)) {
|
if (headerRead != sizeof(XtgPageHeader)) {
|
||||||
Serial.printf("[%lu] [XTC] Failed to read page header for page %u\n", millis(), pageIndex);
|
LOG_DBG("XTC", "Failed to read page header for page %u", pageIndex);
|
||||||
m_lastError = XtcError::READ_ERROR;
|
m_lastError = XtcError::READ_ERROR;
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
@@ -351,8 +349,8 @@ size_t XtcParser::loadPage(uint32_t pageIndex, uint8_t* buffer, size_t bufferSiz
|
|||||||
// Verify page magic (XTG for 1-bit, XTH for 2-bit)
|
// Verify page magic (XTG for 1-bit, XTH for 2-bit)
|
||||||
const uint32_t expectedMagic = (m_bitDepth == 2) ? XTH_MAGIC : XTG_MAGIC;
|
const uint32_t expectedMagic = (m_bitDepth == 2) ? XTH_MAGIC : XTG_MAGIC;
|
||||||
if (pageHeader.magic != expectedMagic) {
|
if (pageHeader.magic != expectedMagic) {
|
||||||
Serial.printf("[%lu] [XTC] Invalid page magic for page %u: 0x%08X (expected 0x%08X)\n", millis(), pageIndex,
|
LOG_DBG("XTC", "Invalid page magic for page %u: 0x%08X (expected 0x%08X)", pageIndex, pageHeader.magic,
|
||||||
pageHeader.magic, expectedMagic);
|
expectedMagic);
|
||||||
m_lastError = XtcError::INVALID_MAGIC;
|
m_lastError = XtcError::INVALID_MAGIC;
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
@@ -370,7 +368,7 @@ size_t XtcParser::loadPage(uint32_t pageIndex, uint8_t* buffer, size_t bufferSiz
|
|||||||
|
|
||||||
// Check buffer size
|
// Check buffer size
|
||||||
if (bufferSize < bitmapSize) {
|
if (bufferSize < bitmapSize) {
|
||||||
Serial.printf("[%lu] [XTC] Buffer too small: need %u, have %u\n", millis(), bitmapSize, bufferSize);
|
LOG_DBG("XTC", "Buffer too small: need %u, have %u", bitmapSize, bufferSize);
|
||||||
m_lastError = XtcError::MEMORY_ERROR;
|
m_lastError = XtcError::MEMORY_ERROR;
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
@@ -378,7 +376,7 @@ size_t XtcParser::loadPage(uint32_t pageIndex, uint8_t* buffer, size_t bufferSiz
|
|||||||
// Read bitmap data
|
// Read bitmap data
|
||||||
size_t bytesRead = m_file.read(buffer, bitmapSize);
|
size_t bytesRead = m_file.read(buffer, bitmapSize);
|
||||||
if (bytesRead != bitmapSize) {
|
if (bytesRead != bitmapSize) {
|
||||||
Serial.printf("[%lu] [XTC] Page read error: expected %u, got %u\n", millis(), bitmapSize, bytesRead);
|
LOG_DBG("XTC", "Page read error: expected %u, got %u", bitmapSize, bytesRead);
|
||||||
m_lastError = XtcError::READ_ERROR;
|
m_lastError = XtcError::READ_ERROR;
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
@@ -444,7 +442,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;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -7,7 +7,7 @@
|
|||||||
|
|
||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include <SdFat.h>
|
#include <HalStorage.h>
|
||||||
|
|
||||||
#include <functional>
|
#include <functional>
|
||||||
#include <memory>
|
#include <memory>
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
#include "ZipFile.h"
|
#include "ZipFile.h"
|
||||||
|
|
||||||
#include <HardwareSerial.h>
|
#include <HalStorage.h>
|
||||||
#include <SDCardManager.h>
|
#include <Logging.h>
|
||||||
#include <miniz.h>
|
#include <miniz.h>
|
||||||
|
|
||||||
#include <algorithm>
|
#include <algorithm>
|
||||||
@@ -10,7 +10,7 @@ bool inflateOneShot(const uint8_t* inputBuf, const size_t deflatedSize, uint8_t*
|
|||||||
// Setup inflator
|
// Setup inflator
|
||||||
const auto inflator = static_cast<tinfl_decompressor*>(malloc(sizeof(tinfl_decompressor)));
|
const auto inflator = static_cast<tinfl_decompressor*>(malloc(sizeof(tinfl_decompressor)));
|
||||||
if (!inflator) {
|
if (!inflator) {
|
||||||
Serial.printf("[%lu] [ZIP] Failed to allocate memory for inflator\n", millis());
|
LOG_ERR("ZIP", "Failed to allocate memory for inflator");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
memset(inflator, 0, sizeof(tinfl_decompressor));
|
memset(inflator, 0, sizeof(tinfl_decompressor));
|
||||||
@@ -23,7 +23,7 @@ bool inflateOneShot(const uint8_t* inputBuf, const size_t deflatedSize, uint8_t*
|
|||||||
free(inflator);
|
free(inflator);
|
||||||
|
|
||||||
if (status != TINFL_STATUS_DONE) {
|
if (status != TINFL_STATUS_DONE) {
|
||||||
Serial.printf("[%lu] [ZIP] tinfl_decompress() failed with status %d\n", millis(), status);
|
LOG_ERR("ZIP", "tinfl_decompress() failed with status %d", status);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -195,13 +195,13 @@ long ZipFile::getDataOffset(const FileStatSlim& fileStat) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (read != localHeaderSize) {
|
if (read != localHeaderSize) {
|
||||||
Serial.printf("[%lu] [ZIP] Something went wrong reading the local header\n", millis());
|
LOG_ERR("ZIP", "Something went wrong reading the local header");
|
||||||
return -1;
|
return -1;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (pLocalHeader[0] + (pLocalHeader[1] << 8) + (pLocalHeader[2] << 16) + (pLocalHeader[3] << 24) !=
|
if (pLocalHeader[0] + (pLocalHeader[1] << 8) + (pLocalHeader[2] << 16) + (pLocalHeader[3] << 24) !=
|
||||||
0x04034b50 /* MZ_ZIP_LOCAL_DIR_HEADER_SIG */) {
|
0x04034b50 /* MZ_ZIP_LOCAL_DIR_HEADER_SIG */) {
|
||||||
Serial.printf("[%lu] [ZIP] Not a valid zip file header\n", millis());
|
LOG_ERR("ZIP", "Not a valid zip file header");
|
||||||
return -1;
|
return -1;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -222,7 +222,7 @@ bool ZipFile::loadZipDetails() {
|
|||||||
|
|
||||||
const size_t fileSize = file.size();
|
const size_t fileSize = file.size();
|
||||||
if (fileSize < 22) {
|
if (fileSize < 22) {
|
||||||
Serial.printf("[%lu] [ZIP] File too small to be a valid zip\n", millis());
|
LOG_ERR("ZIP", "File too small to be a valid zip");
|
||||||
if (!wasOpen) {
|
if (!wasOpen) {
|
||||||
close();
|
close();
|
||||||
}
|
}
|
||||||
@@ -234,7 +234,7 @@ bool ZipFile::loadZipDetails() {
|
|||||||
const int scanRange = fileSize > 1024 ? 1024 : fileSize;
|
const int scanRange = fileSize > 1024 ? 1024 : fileSize;
|
||||||
const auto buffer = static_cast<uint8_t*>(malloc(scanRange));
|
const auto buffer = static_cast<uint8_t*>(malloc(scanRange));
|
||||||
if (!buffer) {
|
if (!buffer) {
|
||||||
Serial.printf("[%lu] [ZIP] Failed to allocate memory for EOCD scan buffer\n", millis());
|
LOG_ERR("ZIP", "Failed to allocate memory for EOCD scan buffer");
|
||||||
if (!wasOpen) {
|
if (!wasOpen) {
|
||||||
close();
|
close();
|
||||||
}
|
}
|
||||||
@@ -255,7 +255,7 @@ bool ZipFile::loadZipDetails() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (foundOffset == -1) {
|
if (foundOffset == -1) {
|
||||||
Serial.printf("[%lu] [ZIP] EOCD signature not found in zip file\n", millis());
|
LOG_ERR("ZIP", "EOCD signature not found in zip file");
|
||||||
free(buffer);
|
free(buffer);
|
||||||
if (!wasOpen) {
|
if (!wasOpen) {
|
||||||
close();
|
close();
|
||||||
@@ -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;
|
||||||
@@ -407,7 +407,7 @@ uint8_t* ZipFile::readFileToMemory(const char* filename, size_t* size, const boo
|
|||||||
const auto dataSize = trailingNullByte ? inflatedDataSize + 1 : inflatedDataSize;
|
const auto dataSize = trailingNullByte ? inflatedDataSize + 1 : inflatedDataSize;
|
||||||
const auto data = static_cast<uint8_t*>(malloc(dataSize));
|
const auto data = static_cast<uint8_t*>(malloc(dataSize));
|
||||||
if (data == nullptr) {
|
if (data == nullptr) {
|
||||||
Serial.printf("[%lu] [ZIP] Failed to allocate memory for output buffer (%zu bytes)\n", millis(), dataSize);
|
LOG_ERR("ZIP", "Failed to allocate memory for output buffer (%zu bytes)", dataSize);
|
||||||
if (!wasOpen) {
|
if (!wasOpen) {
|
||||||
close();
|
close();
|
||||||
}
|
}
|
||||||
@@ -422,7 +422,7 @@ uint8_t* ZipFile::readFileToMemory(const char* filename, size_t* size, const boo
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (dataRead != inflatedDataSize) {
|
if (dataRead != inflatedDataSize) {
|
||||||
Serial.printf("[%lu] [ZIP] Failed to read data\n", millis());
|
LOG_ERR("ZIP", "Failed to read data");
|
||||||
free(data);
|
free(data);
|
||||||
return nullptr;
|
return nullptr;
|
||||||
}
|
}
|
||||||
@@ -432,7 +432,7 @@ uint8_t* ZipFile::readFileToMemory(const char* filename, size_t* size, const boo
|
|||||||
// Read out deflated content from file
|
// Read out deflated content from file
|
||||||
const auto deflatedData = static_cast<uint8_t*>(malloc(deflatedDataSize));
|
const auto deflatedData = static_cast<uint8_t*>(malloc(deflatedDataSize));
|
||||||
if (deflatedData == nullptr) {
|
if (deflatedData == nullptr) {
|
||||||
Serial.printf("[%lu] [ZIP] Failed to allocate memory for decompression buffer\n", millis());
|
LOG_ERR("ZIP", "Failed to allocate memory for decompression buffer");
|
||||||
if (!wasOpen) {
|
if (!wasOpen) {
|
||||||
close();
|
close();
|
||||||
}
|
}
|
||||||
@@ -445,7 +445,7 @@ uint8_t* ZipFile::readFileToMemory(const char* filename, size_t* size, const boo
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (dataRead != deflatedDataSize) {
|
if (dataRead != deflatedDataSize) {
|
||||||
Serial.printf("[%lu] [ZIP] Failed to read data, expected %d got %d\n", millis(), deflatedDataSize, dataRead);
|
LOG_ERR("ZIP", "Failed to read data, expected %d got %d", deflatedDataSize, dataRead);
|
||||||
free(deflatedData);
|
free(deflatedData);
|
||||||
free(data);
|
free(data);
|
||||||
return nullptr;
|
return nullptr;
|
||||||
@@ -455,14 +455,14 @@ uint8_t* ZipFile::readFileToMemory(const char* filename, size_t* size, const boo
|
|||||||
free(deflatedData);
|
free(deflatedData);
|
||||||
|
|
||||||
if (!success) {
|
if (!success) {
|
||||||
Serial.printf("[%lu] [ZIP] Failed to inflate file\n", millis());
|
LOG_ERR("ZIP", "Failed to inflate file");
|
||||||
free(data);
|
free(data);
|
||||||
return nullptr;
|
return nullptr;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Continue out of block with data set
|
// Continue out of block with data set
|
||||||
} else {
|
} else {
|
||||||
Serial.printf("[%lu] [ZIP] Unsupported compression method\n", millis());
|
LOG_ERR("ZIP", "Unsupported compression method");
|
||||||
if (!wasOpen) {
|
if (!wasOpen) {
|
||||||
close();
|
close();
|
||||||
}
|
}
|
||||||
@@ -498,7 +498,7 @@ bool ZipFile::readFileToStream(const char* filename, Print& out, const size_t ch
|
|||||||
// no deflation, just read content
|
// no deflation, just read content
|
||||||
const auto buffer = static_cast<uint8_t*>(malloc(chunkSize));
|
const auto buffer = static_cast<uint8_t*>(malloc(chunkSize));
|
||||||
if (!buffer) {
|
if (!buffer) {
|
||||||
Serial.printf("[%lu] [ZIP] Failed to allocate memory for buffer\n", millis());
|
LOG_ERR("ZIP", "Failed to allocate memory for buffer");
|
||||||
if (!wasOpen) {
|
if (!wasOpen) {
|
||||||
close();
|
close();
|
||||||
}
|
}
|
||||||
@@ -509,7 +509,7 @@ bool ZipFile::readFileToStream(const char* filename, Print& out, const size_t ch
|
|||||||
while (remaining > 0) {
|
while (remaining > 0) {
|
||||||
const size_t dataRead = file.read(buffer, remaining < chunkSize ? remaining : chunkSize);
|
const size_t dataRead = file.read(buffer, remaining < chunkSize ? remaining : chunkSize);
|
||||||
if (dataRead == 0) {
|
if (dataRead == 0) {
|
||||||
Serial.printf("[%lu] [ZIP] Could not read more bytes\n", millis());
|
LOG_ERR("ZIP", "Could not read more bytes");
|
||||||
free(buffer);
|
free(buffer);
|
||||||
if (!wasOpen) {
|
if (!wasOpen) {
|
||||||
close();
|
close();
|
||||||
@@ -532,7 +532,7 @@ bool ZipFile::readFileToStream(const char* filename, Print& out, const size_t ch
|
|||||||
// Setup inflator
|
// Setup inflator
|
||||||
const auto inflator = static_cast<tinfl_decompressor*>(malloc(sizeof(tinfl_decompressor)));
|
const auto inflator = static_cast<tinfl_decompressor*>(malloc(sizeof(tinfl_decompressor)));
|
||||||
if (!inflator) {
|
if (!inflator) {
|
||||||
Serial.printf("[%lu] [ZIP] Failed to allocate memory for inflator\n", millis());
|
LOG_ERR("ZIP", "Failed to allocate memory for inflator");
|
||||||
if (!wasOpen) {
|
if (!wasOpen) {
|
||||||
close();
|
close();
|
||||||
}
|
}
|
||||||
@@ -544,7 +544,7 @@ bool ZipFile::readFileToStream(const char* filename, Print& out, const size_t ch
|
|||||||
// Setup file read buffer
|
// Setup file read buffer
|
||||||
const auto fileReadBuffer = static_cast<uint8_t*>(malloc(chunkSize));
|
const auto fileReadBuffer = static_cast<uint8_t*>(malloc(chunkSize));
|
||||||
if (!fileReadBuffer) {
|
if (!fileReadBuffer) {
|
||||||
Serial.printf("[%lu] [ZIP] Failed to allocate memory for zip file read buffer\n", millis());
|
LOG_ERR("ZIP", "Failed to allocate memory for zip file read buffer");
|
||||||
free(inflator);
|
free(inflator);
|
||||||
if (!wasOpen) {
|
if (!wasOpen) {
|
||||||
close();
|
close();
|
||||||
@@ -554,7 +554,7 @@ bool ZipFile::readFileToStream(const char* filename, Print& out, const size_t ch
|
|||||||
|
|
||||||
const auto outputBuffer = static_cast<uint8_t*>(malloc(TINFL_LZ_DICT_SIZE));
|
const auto outputBuffer = static_cast<uint8_t*>(malloc(TINFL_LZ_DICT_SIZE));
|
||||||
if (!outputBuffer) {
|
if (!outputBuffer) {
|
||||||
Serial.printf("[%lu] [ZIP] Failed to allocate memory for dictionary\n", millis());
|
LOG_ERR("ZIP", "Failed to allocate memory for dictionary");
|
||||||
free(inflator);
|
free(inflator);
|
||||||
free(fileReadBuffer);
|
free(fileReadBuffer);
|
||||||
if (!wasOpen) {
|
if (!wasOpen) {
|
||||||
@@ -605,7 +605,7 @@ bool ZipFile::readFileToStream(const char* filename, Print& out, const size_t ch
|
|||||||
if (outBytes > 0) {
|
if (outBytes > 0) {
|
||||||
processedOutputBytes += outBytes;
|
processedOutputBytes += outBytes;
|
||||||
if (out.write(outputBuffer + outputCursor, outBytes) != outBytes) {
|
if (out.write(outputBuffer + outputCursor, outBytes) != outBytes) {
|
||||||
Serial.printf("[%lu] [ZIP] Failed to write all output bytes to stream\n", millis());
|
LOG_ERR("ZIP", "Failed to write all output bytes to stream");
|
||||||
if (!wasOpen) {
|
if (!wasOpen) {
|
||||||
close();
|
close();
|
||||||
}
|
}
|
||||||
@@ -619,7 +619,7 @@ bool ZipFile::readFileToStream(const char* filename, Print& out, const size_t ch
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (status < 0) {
|
if (status < 0) {
|
||||||
Serial.printf("[%lu] [ZIP] tinfl_decompress() failed with status %d\n", millis(), status);
|
LOG_ERR("ZIP", "tinfl_decompress() failed with status %d", status);
|
||||||
if (!wasOpen) {
|
if (!wasOpen) {
|
||||||
close();
|
close();
|
||||||
}
|
}
|
||||||
@@ -630,8 +630,7 @@ bool ZipFile::readFileToStream(const char* filename, Print& out, const size_t ch
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (status == TINFL_STATUS_DONE) {
|
if (status == TINFL_STATUS_DONE) {
|
||||||
Serial.printf("[%lu] [ZIP] Decompressed %d bytes into %d bytes\n", millis(), deflatedDataSize,
|
LOG_ERR("ZIP", "Decompressed %d bytes into %d bytes", deflatedDataSize, inflatedDataSize);
|
||||||
inflatedDataSize);
|
|
||||||
if (!wasOpen) {
|
if (!wasOpen) {
|
||||||
close();
|
close();
|
||||||
}
|
}
|
||||||
@@ -643,7 +642,7 @@ bool ZipFile::readFileToStream(const char* filename, Print& out, const size_t ch
|
|||||||
}
|
}
|
||||||
|
|
||||||
// If we get here, EOF reached without TINFL_STATUS_DONE
|
// If we get here, EOF reached without TINFL_STATUS_DONE
|
||||||
Serial.printf("[%lu] [ZIP] Unexpected EOF\n", millis());
|
LOG_ERR("ZIP", "Unexpected EOF");
|
||||||
if (!wasOpen) {
|
if (!wasOpen) {
|
||||||
close();
|
close();
|
||||||
}
|
}
|
||||||
@@ -657,6 +656,6 @@ bool ZipFile::readFileToStream(const char* filename, Print& out, const size_t ch
|
|||||||
close();
|
close();
|
||||||
}
|
}
|
||||||
|
|
||||||
Serial.printf("[%lu] [ZIP] Unsupported compression method\n", millis());
|
LOG_ERR("ZIP", "Unsupported compression method");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
#include <SdFat.h>
|
#include <HalStorage.h>
|
||||||
|
|
||||||
#include <string>
|
#include <string>
|
||||||
#include <unordered_map>
|
#include <unordered_map>
|
||||||
|
|||||||
@@ -28,7 +28,16 @@ EInkDisplay::RefreshMode convertRefreshMode(HalDisplay::RefreshMode mode) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void HalDisplay::displayBuffer(HalDisplay::RefreshMode mode) { einkDisplay.displayBuffer(convertRefreshMode(mode)); }
|
void HalDisplay::displayBuffer(HalDisplay::RefreshMode mode, bool turnOffScreen) {
|
||||||
|
einkDisplay.displayBuffer(convertRefreshMode(mode), turnOffScreen);
|
||||||
|
}
|
||||||
|
|
||||||
|
// EXPERIMENTAL: Display only a rectangular region
|
||||||
|
void HalDisplay::displayWindow(uint16_t x, uint16_t y, uint16_t w, uint16_t h,
|
||||||
|
HalDisplay::RefreshMode mode, bool turnOffScreen) {
|
||||||
|
(void)mode; // EInkDisplay::displayWindow does not take mode yet
|
||||||
|
einkDisplay.displayWindow(x, y, w, h, turnOffScreen);
|
||||||
|
}
|
||||||
|
|
||||||
void HalDisplay::refreshDisplay(HalDisplay::RefreshMode mode, bool turnOffScreen) {
|
void HalDisplay::refreshDisplay(HalDisplay::RefreshMode mode, bool turnOffScreen) {
|
||||||
einkDisplay.refreshDisplay(convertRefreshMode(mode), turnOffScreen);
|
einkDisplay.refreshDisplay(convertRefreshMode(mode), turnOffScreen);
|
||||||
@@ -48,4 +57,4 @@ void HalDisplay::copyGrayscaleMsbBuffers(const uint8_t* msbBuffer) { einkDisplay
|
|||||||
|
|
||||||
void HalDisplay::cleanupGrayscaleBuffers(const uint8_t* bwBuffer) { einkDisplay.cleanupGrayscaleBuffers(bwBuffer); }
|
void HalDisplay::cleanupGrayscaleBuffers(const uint8_t* bwBuffer) { einkDisplay.cleanupGrayscaleBuffers(bwBuffer); }
|
||||||
|
|
||||||
void HalDisplay::displayGrayBuffer() { einkDisplay.displayGrayBuffer(); }
|
void HalDisplay::displayGrayBuffer(bool turnOffScreen) { einkDisplay.displayGrayBuffer(turnOffScreen); }
|
||||||
|
|||||||
@@ -31,9 +31,13 @@ class HalDisplay {
|
|||||||
void drawImage(const uint8_t* imageData, uint16_t x, uint16_t y, uint16_t w, uint16_t h,
|
void drawImage(const uint8_t* imageData, uint16_t x, uint16_t y, uint16_t w, uint16_t h,
|
||||||
bool fromProgmem = false) const;
|
bool fromProgmem = false) const;
|
||||||
|
|
||||||
void displayBuffer(RefreshMode mode = RefreshMode::FAST_REFRESH);
|
void displayBuffer(RefreshMode mode = RefreshMode::FAST_REFRESH, bool turnOffScreen = false);
|
||||||
void refreshDisplay(RefreshMode mode = RefreshMode::FAST_REFRESH, bool turnOffScreen = false);
|
void refreshDisplay(RefreshMode mode = RefreshMode::FAST_REFRESH, bool turnOffScreen = false);
|
||||||
|
|
||||||
|
// EXPERIMENTAL: Display only a rectangular region
|
||||||
|
void displayWindow(uint16_t x, uint16_t y, uint16_t w, uint16_t h,
|
||||||
|
RefreshMode mode = RefreshMode::FAST_REFRESH, bool turnOffScreen = false);
|
||||||
|
|
||||||
// Power management
|
// Power management
|
||||||
void deepSleep();
|
void deepSleep();
|
||||||
|
|
||||||
@@ -45,7 +49,7 @@ class HalDisplay {
|
|||||||
void copyGrayscaleMsbBuffers(const uint8_t* msbBuffer);
|
void copyGrayscaleMsbBuffers(const uint8_t* msbBuffer);
|
||||||
void cleanupGrayscaleBuffers(const uint8_t* bwBuffer);
|
void cleanupGrayscaleBuffers(const uint8_t* bwBuffer);
|
||||||
|
|
||||||
void displayGrayBuffer();
|
void displayGrayBuffer(bool turnOffScreen = false);
|
||||||
|
|
||||||
private:
|
private:
|
||||||
EInkDisplay einkDisplay;
|
EInkDisplay einkDisplay;
|
||||||
|
|||||||
@@ -1,11 +1,9 @@
|
|||||||
#include <HalGPIO.h>
|
#include <HalGPIO.h>
|
||||||
#include <SPI.h>
|
#include <SPI.h>
|
||||||
#include <esp_sleep.h>
|
|
||||||
|
|
||||||
void HalGPIO::begin() {
|
void HalGPIO::begin() {
|
||||||
inputMgr.begin();
|
inputMgr.begin();
|
||||||
SPI.begin(EPD_SCLK, SPI_MISO, EPD_MOSI, EPD_CS);
|
SPI.begin(EPD_SCLK, SPI_MISO, EPD_MOSI, EPD_CS);
|
||||||
pinMode(BAT_GPIO0, INPUT);
|
|
||||||
pinMode(UART0_RXD, INPUT);
|
pinMode(UART0_RXD, INPUT);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -23,33 +21,25 @@ bool HalGPIO::wasAnyReleased() const { return inputMgr.wasAnyReleased(); }
|
|||||||
|
|
||||||
unsigned long HalGPIO::getHeldTime() const { return inputMgr.getHeldTime(); }
|
unsigned long HalGPIO::getHeldTime() const { return inputMgr.getHeldTime(); }
|
||||||
|
|
||||||
void HalGPIO::startDeepSleep() {
|
|
||||||
esp_deep_sleep_enable_gpio_wakeup(1ULL << InputManager::POWER_BUTTON_PIN, ESP_GPIO_WAKEUP_GPIO_LOW);
|
|
||||||
// Ensure that the power button has been released to avoid immediately turning back on if you're holding it
|
|
||||||
while (inputMgr.isPressed(BTN_POWER)) {
|
|
||||||
delay(50);
|
|
||||||
inputMgr.update();
|
|
||||||
}
|
|
||||||
// Enter Deep Sleep
|
|
||||||
esp_deep_sleep_start();
|
|
||||||
}
|
|
||||||
|
|
||||||
int HalGPIO::getBatteryPercentage() const {
|
|
||||||
static const BatteryMonitor battery = BatteryMonitor(BAT_GPIO0);
|
|
||||||
return battery.readPercentage();
|
|
||||||
}
|
|
||||||
|
|
||||||
bool HalGPIO::isUsbConnected() const {
|
bool HalGPIO::isUsbConnected() const {
|
||||||
// U0RXD/GPIO20 reads HIGH when USB is connected
|
// U0RXD/GPIO20 reads HIGH when USB is connected
|
||||||
return digitalRead(UART0_RXD) == HIGH;
|
return digitalRead(UART0_RXD) == HIGH;
|
||||||
}
|
}
|
||||||
|
|
||||||
bool HalGPIO::isWakeupByPowerButton() const {
|
HalGPIO::WakeupReason HalGPIO::getWakeupReason() const {
|
||||||
|
const bool usbConnected = isUsbConnected();
|
||||||
const auto wakeupCause = esp_sleep_get_wakeup_cause();
|
const auto wakeupCause = esp_sleep_get_wakeup_cause();
|
||||||
const auto resetReason = esp_reset_reason();
|
const auto resetReason = esp_reset_reason();
|
||||||
if (isUsbConnected()) {
|
|
||||||
return wakeupCause == ESP_SLEEP_WAKEUP_GPIO;
|
if ((wakeupCause == ESP_SLEEP_WAKEUP_UNDEFINED && resetReason == ESP_RST_POWERON && !usbConnected) ||
|
||||||
} else {
|
(wakeupCause == ESP_SLEEP_WAKEUP_GPIO && resetReason == ESP_RST_DEEPSLEEP && usbConnected)) {
|
||||||
return (wakeupCause == ESP_SLEEP_WAKEUP_UNDEFINED) && (resetReason == ESP_RST_POWERON);
|
return WakeupReason::PowerButton;
|
||||||
}
|
}
|
||||||
|
if (wakeupCause == ESP_SLEEP_WAKEUP_UNDEFINED && resetReason == ESP_RST_UNKNOWN && usbConnected) {
|
||||||
|
return WakeupReason::AfterFlash;
|
||||||
|
}
|
||||||
|
if (wakeupCause == ESP_SLEEP_WAKEUP_UNDEFINED && resetReason == ESP_RST_POWERON && usbConnected) {
|
||||||
|
return WakeupReason::AfterUSBPower;
|
||||||
|
}
|
||||||
|
return WakeupReason::Other;
|
||||||
}
|
}
|
||||||
@@ -38,17 +38,12 @@ class HalGPIO {
|
|||||||
bool wasAnyReleased() const;
|
bool wasAnyReleased() const;
|
||||||
unsigned long getHeldTime() const;
|
unsigned long getHeldTime() const;
|
||||||
|
|
||||||
// Setup wake up GPIO and enter deep sleep
|
|
||||||
void startDeepSleep();
|
|
||||||
|
|
||||||
// Get battery percentage (range 0-100)
|
|
||||||
int getBatteryPercentage() const;
|
|
||||||
|
|
||||||
// Check if USB is connected
|
// Check if USB is connected
|
||||||
bool isUsbConnected() const;
|
bool isUsbConnected() const;
|
||||||
|
|
||||||
// Check if wakeup was caused by power button press
|
enum class WakeupReason { PowerButton, AfterFlash, AfterUSBPower, Other };
|
||||||
bool isWakeupByPowerButton() const;
|
|
||||||
|
WakeupReason getWakeupReason() const;
|
||||||
|
|
||||||
// Button indices
|
// Button indices
|
||||||
static constexpr uint8_t BTN_BACK = 0;
|
static constexpr uint8_t BTN_BACK = 0;
|
||||||
|
|||||||
49
lib/hal/HalPowerManager.cpp
Normal file
49
lib/hal/HalPowerManager.cpp
Normal file
@@ -0,0 +1,49 @@
|
|||||||
|
#include "HalPowerManager.h"
|
||||||
|
|
||||||
|
#include <Logging.h>
|
||||||
|
#include <esp_sleep.h>
|
||||||
|
|
||||||
|
#include "HalGPIO.h"
|
||||||
|
|
||||||
|
void HalPowerManager::begin() {
|
||||||
|
pinMode(BAT_GPIO0, INPUT);
|
||||||
|
normalFreq = getCpuFrequencyMhz();
|
||||||
|
}
|
||||||
|
|
||||||
|
void HalPowerManager::setPowerSaving(bool enabled) {
|
||||||
|
if (normalFreq <= 0) {
|
||||||
|
return; // invalid state
|
||||||
|
}
|
||||||
|
if (enabled && !isLowPower) {
|
||||||
|
LOG_DBG("PWR", "Going to low-power mode");
|
||||||
|
if (!setCpuFrequencyMhz(LOW_POWER_FREQ)) {
|
||||||
|
LOG_DBG("PWR", "Failed to set CPU frequency = %d MHz", LOW_POWER_FREQ);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!enabled && isLowPower) {
|
||||||
|
LOG_DBG("PWR", "Restoring normal CPU frequency");
|
||||||
|
if (!setCpuFrequencyMhz(normalFreq)) {
|
||||||
|
LOG_DBG("PWR", "Failed to set CPU frequency = %d MHz", normalFreq);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
isLowPower = enabled;
|
||||||
|
}
|
||||||
|
|
||||||
|
void HalPowerManager::startDeepSleep(HalGPIO& gpio) const {
|
||||||
|
// Ensure that the power button has been released to avoid immediately turning back on if you're holding it
|
||||||
|
while (gpio.isPressed(HalGPIO::BTN_POWER)) {
|
||||||
|
delay(50);
|
||||||
|
gpio.update();
|
||||||
|
}
|
||||||
|
// Arm the wakeup trigger *after* the button is released
|
||||||
|
esp_deep_sleep_enable_gpio_wakeup(1ULL << InputManager::POWER_BUTTON_PIN, ESP_GPIO_WAKEUP_GPIO_LOW);
|
||||||
|
// Enter Deep Sleep
|
||||||
|
esp_deep_sleep_start();
|
||||||
|
}
|
||||||
|
|
||||||
|
int HalPowerManager::getBatteryPercentage() const {
|
||||||
|
static const BatteryMonitor battery = BatteryMonitor(BAT_GPIO0);
|
||||||
|
return battery.readPercentage();
|
||||||
|
}
|
||||||
27
lib/hal/HalPowerManager.h
Normal file
27
lib/hal/HalPowerManager.h
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <Arduino.h>
|
||||||
|
#include <BatteryMonitor.h>
|
||||||
|
#include <InputManager.h>
|
||||||
|
|
||||||
|
#include "HalGPIO.h"
|
||||||
|
|
||||||
|
class HalPowerManager {
|
||||||
|
int normalFreq = 0; // MHz
|
||||||
|
bool isLowPower = false;
|
||||||
|
|
||||||
|
public:
|
||||||
|
static constexpr int LOW_POWER_FREQ = 10; // MHz
|
||||||
|
static constexpr unsigned long IDLE_POWER_SAVING_MS = 3000; // ms
|
||||||
|
|
||||||
|
void begin();
|
||||||
|
|
||||||
|
// Control CPU frequency for power saving
|
||||||
|
void setPowerSaving(bool enabled);
|
||||||
|
|
||||||
|
// Setup wake up GPIO and enter deep sleep
|
||||||
|
void startDeepSleep(HalGPIO& gpio) const;
|
||||||
|
|
||||||
|
// Get battery percentage (range 0-100)
|
||||||
|
int getBatteryPercentage() const;
|
||||||
|
};
|
||||||
65
lib/hal/HalStorage.cpp
Normal file
65
lib/hal/HalStorage.cpp
Normal 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
54
lib/hal/HalStorage.h
Normal 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
|
||||||
Submodule open-x4-sdk updated: bd4e670750...c8ce3949b3
@@ -2,7 +2,7 @@
|
|||||||
default_envs = default
|
default_envs = default
|
||||||
|
|
||||||
[crosspoint]
|
[crosspoint]
|
||||||
version = 0.16.0
|
version = 1.0.0
|
||||||
|
|
||||||
[base]
|
[base]
|
||||||
platform = espressif32 @ 6.12.0
|
platform = espressif32 @ 6.12.0
|
||||||
@@ -27,9 +27,15 @@ build_flags =
|
|||||||
# https://libexpat.github.io/doc/api/latest/#XML_GE
|
# https://libexpat.github.io/doc/api/latest/#XML_GE
|
||||||
-DXML_GE=0
|
-DXML_GE=0
|
||||||
-DXML_CONTEXT_BYTES=1024
|
-DXML_CONTEXT_BYTES=1024
|
||||||
-std=c++2a
|
-std=gnu++2a
|
||||||
# Enable UTF-8 long file names in SdFat
|
# Enable UTF-8 long file names in SdFat
|
||||||
-DUSE_UTF8_LONG_NAMES=1
|
-DUSE_UTF8_LONG_NAMES=1
|
||||||
|
# Increase PNG scanline buffer to support up to 800px wide images
|
||||||
|
# Default is (320*4+1)*2=2562, we need more for larger images
|
||||||
|
-DPNG_MAX_BUFFERED_PIXELS=6402
|
||||||
|
|
||||||
|
build_unflags =
|
||||||
|
-std=gnu++11
|
||||||
|
|
||||||
; Board configuration
|
; Board configuration
|
||||||
board_build.flash_mode = dio
|
board_build.flash_mode = dio
|
||||||
@@ -47,6 +53,7 @@ lib_deps =
|
|||||||
SDCardManager=symlink://open-x4-sdk/libs/hardware/SDCardManager
|
SDCardManager=symlink://open-x4-sdk/libs/hardware/SDCardManager
|
||||||
bblanchon/ArduinoJson @ 7.4.2
|
bblanchon/ArduinoJson @ 7.4.2
|
||||||
ricmoo/QRCode @ 0.0.1
|
ricmoo/QRCode @ 0.0.1
|
||||||
|
bitbank2/PNGdec @ ^1.0.0
|
||||||
links2004/WebSockets @ 2.7.3
|
links2004/WebSockets @ 2.7.3
|
||||||
|
|
||||||
[env:default]
|
[env:default]
|
||||||
@@ -54,9 +61,47 @@ extends = base
|
|||||||
build_flags =
|
build_flags =
|
||||||
${base.build_flags}
|
${base.build_flags}
|
||||||
-DCROSSPOINT_VERSION=\"${crosspoint.version}-dev\"
|
-DCROSSPOINT_VERSION=\"${crosspoint.version}-dev\"
|
||||||
|
-DENABLE_SERIAL_LOG
|
||||||
|
-DLOG_LEVEL=2 ; Set log level to debug for development builds
|
||||||
|
|
||||||
|
|
||||||
|
[env:mod]
|
||||||
|
extends = base
|
||||||
|
extra_scripts =
|
||||||
|
${base.extra_scripts}
|
||||||
|
pre:scripts/inject_mod_version.py
|
||||||
|
build_flags =
|
||||||
|
${base.build_flags}
|
||||||
|
-DOMIT_OPENDYSLEXIC
|
||||||
|
-DOMIT_HYPH_DE
|
||||||
|
-DOMIT_HYPH_ES
|
||||||
|
-DOMIT_HYPH_FR
|
||||||
|
-DOMIT_HYPH_IT
|
||||||
|
-DOMIT_HYPH_RU
|
||||||
|
-DENABLE_SERIAL_LOG
|
||||||
|
-DLOG_LEVEL=2 ; Set log level to debug for mod builds
|
||||||
|
|
||||||
[env:gh_release]
|
[env:gh_release]
|
||||||
extends = base
|
extends = base
|
||||||
build_flags =
|
build_flags =
|
||||||
${base.build_flags}
|
${base.build_flags}
|
||||||
-DCROSSPOINT_VERSION=\"${crosspoint.version}\"
|
-DCROSSPOINT_VERSION=\"${crosspoint.version}\"
|
||||||
|
-DENABLE_SERIAL_LOG
|
||||||
|
-DLOG_LEVEL=0 ; Set log level to error for release builds
|
||||||
|
|
||||||
|
[env:gh_release_rc]
|
||||||
|
extends = base
|
||||||
|
build_flags =
|
||||||
|
${base.build_flags}
|
||||||
|
-DCROSSPOINT_VERSION=\"${crosspoint.version}-rc+${sysenv.CROSSPOINT_RC_HASH}\"
|
||||||
|
-DENABLE_SERIAL_LOG
|
||||||
|
-DLOG_LEVEL=1 ; Set log level to info for release candidate builds
|
||||||
|
|
||||||
|
[env:slim]
|
||||||
|
extends = base
|
||||||
|
build_flags =
|
||||||
|
${base.build_flags}
|
||||||
|
-DCROSSPOINT_VERSION=\"${crosspoint.version}-slim\"
|
||||||
|
; serial output is disabled in slim builds to save space
|
||||||
|
-UENABLE_SERIAL_LOG
|
||||||
|
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
import os
|
import os
|
||||||
import re
|
import re
|
||||||
|
import gzip
|
||||||
|
|
||||||
SRC_DIR = "src"
|
SRC_DIR = "src"
|
||||||
|
|
||||||
@@ -40,12 +41,34 @@ for root, _, files in os.walk(SRC_DIR):
|
|||||||
|
|
||||||
# minified = regex.sub("\g<1>", html_content)
|
# minified = regex.sub("\g<1>", html_content)
|
||||||
minified = minify_html(html_content)
|
minified = minify_html(html_content)
|
||||||
|
|
||||||
|
# Compress with gzip (compresslevel 9 is maximum compression)
|
||||||
|
# IMPORTANT: we don't use brotli because Firefox doesn't support brotli with insecured context (only supported on HTTPS)
|
||||||
|
compressed = gzip.compress(minified.encode('utf-8'), compresslevel=9)
|
||||||
|
|
||||||
base_name = f"{os.path.splitext(file)[0]}Html"
|
base_name = f"{os.path.splitext(file)[0]}Html"
|
||||||
header_path = os.path.join(root, f"{base_name}.generated.h")
|
header_path = os.path.join(root, f"{base_name}.generated.h")
|
||||||
|
|
||||||
with open(header_path, "w", encoding="utf-8") as h:
|
with open(header_path, "w", encoding="utf-8") as h:
|
||||||
h.write(f"// THIS FILE IS AUTOGENERATED, DO NOT EDIT MANUALLY\n\n")
|
h.write(f"// THIS FILE IS AUTOGENERATED, DO NOT EDIT MANUALLY\n\n")
|
||||||
h.write(f"#pragma once\n")
|
h.write(f"#pragma once\n")
|
||||||
h.write(f'constexpr char {base_name}[] PROGMEM = R"rawliteral({minified})rawliteral";\n')
|
h.write(f"#include <cstddef>\n\n")
|
||||||
|
|
||||||
|
# Write the compressed data as a byte array
|
||||||
|
h.write(f"constexpr char {base_name}[] PROGMEM = {{\n")
|
||||||
|
|
||||||
|
# Write bytes in rows of 16
|
||||||
|
for i in range(0, len(compressed), 16):
|
||||||
|
chunk = compressed[i:i+16]
|
||||||
|
hex_values = ', '.join(f'0x{b:02x}' for b in chunk)
|
||||||
|
h.write(f" {hex_values},\n")
|
||||||
|
|
||||||
|
h.write(f"}};\n\n")
|
||||||
|
h.write(f"constexpr size_t {base_name}CompressedSize = {len(compressed)};\n")
|
||||||
|
h.write(f"constexpr size_t {base_name}OriginalSize = {len(minified)};\n")
|
||||||
|
|
||||||
print(f"Generated: {header_path}")
|
print(f"Generated: {header_path}")
|
||||||
|
print(f" Original: {len(html_content)} bytes")
|
||||||
|
print(f" Minified: {len(minified)} bytes ({100*len(minified)/len(html_content):.1f}%)")
|
||||||
|
print(f" Compressed: {len(compressed)} bytes ({100*len(compressed)/len(html_content):.1f}%)")
|
||||||
|
|
||||||
|
|||||||
508
scripts/debugging_monitor.py
Executable file
508
scripts/debugging_monitor.py
Executable file
@@ -0,0 +1,508 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""
|
||||||
|
ESP32 Serial Monitor with Memory Graph
|
||||||
|
|
||||||
|
This script provides a comprehensive 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.
|
||||||
|
|
||||||
|
Features:
|
||||||
|
- Real-time serial output monitoring with color-coded log levels
|
||||||
|
- Interactive memory usage graphing with matplotlib
|
||||||
|
- Command input interface for sending commands to the ESP32 device
|
||||||
|
- Screenshot capture and processing (1-bit black/white format)
|
||||||
|
- Graceful shutdown handling with Ctrl-C signal processing
|
||||||
|
- Configurable filtering and suppression of log messages
|
||||||
|
- Thread-safe operation with coordinated shutdown events
|
||||||
|
|
||||||
|
Usage:
|
||||||
|
python debugging_monitor.py [port] [options]
|
||||||
|
|
||||||
|
The script will open a matplotlib window showing memory usage over time and provide
|
||||||
|
an interactive command prompt for sending commands to the device. Press Ctrl-C or
|
||||||
|
close the graph window to exit gracefully.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import glob
|
||||||
|
import platform
|
||||||
|
import re
|
||||||
|
import signal
|
||||||
|
import sys
|
||||||
|
import threading
|
||||||
|
from collections import deque
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
# Try to import potentially missing packages
|
||||||
|
PACKAGE_MAPPING: dict[str, str] = {
|
||||||
|
"serial": "pyserial",
|
||||||
|
"colorama": "colorama",
|
||||||
|
"matplotlib": "matplotlib",
|
||||||
|
"PIL": "Pillow",
|
||||||
|
}
|
||||||
|
|
||||||
|
try:
|
||||||
|
import matplotlib.pyplot as plt
|
||||||
|
import serial
|
||||||
|
from colorama import Fore, Style, init
|
||||||
|
from matplotlib import animation
|
||||||
|
|
||||||
|
try:
|
||||||
|
from PIL import Image
|
||||||
|
except ImportError:
|
||||||
|
Image = None
|
||||||
|
except ImportError as e:
|
||||||
|
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(f" Error: Required package(s) not installed: {', '.join(missing_packages)}")
|
||||||
|
print("!" * 50)
|
||||||
|
|
||||||
|
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 "
|
||||||
|
print(f" {INSTALL_CMD}{' '.join(missing_packages)}")
|
||||||
|
|
||||||
|
print("\nExiting...")
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
# --- Global Variables for Data Sharing ---
|
||||||
|
# Store last 50 data points
|
||||||
|
MAX_POINTS = 50
|
||||||
|
time_data: deque[str] = deque(maxlen=MAX_POINTS)
|
||||||
|
free_mem_data: deque[float] = deque(maxlen=MAX_POINTS)
|
||||||
|
total_mem_data: deque[float] = deque(maxlen=MAX_POINTS)
|
||||||
|
data_lock: threading.Lock = threading.Lock() # Prevent reading while writing
|
||||||
|
|
||||||
|
# Global shutdown flag
|
||||||
|
shutdown_event = threading.Event()
|
||||||
|
|
||||||
|
# Initialize colors
|
||||||
|
init(autoreset=True)
|
||||||
|
|
||||||
|
# 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"],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def signal_handler(signum, frame):
|
||||||
|
"""Handle SIGINT (Ctrl-C) by setting the shutdown event."""
|
||||||
|
# frame parameter is required by signal handler signature but not used
|
||||||
|
del frame # Explicitly mark as unused to satisfy linters
|
||||||
|
print(f"\n{Fore.YELLOW}Received signal {signum}. Shutting down...{Style.RESET_ALL}")
|
||||||
|
shutdown_event.set()
|
||||||
|
plt.close("all")
|
||||||
|
|
||||||
|
|
||||||
|
# pylint: disable=R0912
|
||||||
|
def get_color_for_line(line: str) -> str:
|
||||||
|
"""
|
||||||
|
Classify log lines by type and assign appropriate colors.
|
||||||
|
"""
|
||||||
|
line_upper = line.upper()
|
||||||
|
for color, keywords in COLOR_KEYWORDS.items():
|
||||||
|
if any(keyword in line_upper for keyword in keywords):
|
||||||
|
return color
|
||||||
|
return Fore.WHITE
|
||||||
|
|
||||||
|
|
||||||
|
def parse_memory_line(line: str) -> tuple[int | None, int | None]:
|
||||||
|
"""
|
||||||
|
Extracts Free and Total bytes from the specific log line.
|
||||||
|
Format: [MEM] Free: 196344 bytes, Total: 226412 bytes, Min Free: 112620 bytes
|
||||||
|
"""
|
||||||
|
# Regex to find 'Free: <digits>' and 'Total: <digits>'
|
||||||
|
match = re.search(r"Free:\s*(\d+).*Total:\s*(\d+)", line)
|
||||||
|
if match:
|
||||||
|
try:
|
||||||
|
free_bytes = int(match.group(1))
|
||||||
|
total_bytes = int(match.group(2))
|
||||||
|
return free_bytes, total_bytes
|
||||||
|
except ValueError:
|
||||||
|
return None, None
|
||||||
|
return None, None
|
||||||
|
|
||||||
|
|
||||||
|
def serial_worker(ser, kwargs: dict[str, str]) -> None:
|
||||||
|
"""
|
||||||
|
Runs in a background thread. Handles reading serial data, printing to console,
|
||||||
|
updating memory usage data for graphing, and processing screenshot data.
|
||||||
|
Monitors the global shutdown event for graceful termination.
|
||||||
|
"""
|
||||||
|
print(f"{Fore.CYAN}--- Opening serial port ---{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}"
|
||||||
|
)
|
||||||
|
|
||||||
|
expecting_screenshot = False
|
||||||
|
screenshot_size = 0
|
||||||
|
screenshot_data = b""
|
||||||
|
|
||||||
|
try:
|
||||||
|
while not shutdown_event.is_set():
|
||||||
|
if expecting_screenshot:
|
||||||
|
data = ser.read(screenshot_size - len(screenshot_data))
|
||||||
|
if not data:
|
||||||
|
continue
|
||||||
|
screenshot_data += data
|
||||||
|
if len(screenshot_data) == screenshot_size:
|
||||||
|
if Image:
|
||||||
|
img = Image.frombytes("1", (800, 480), screenshot_data)
|
||||||
|
# We need to rotate the image because the raw data is in landscape mode
|
||||||
|
img = img.transpose(Image.ROTATE_270)
|
||||||
|
img.save("screenshot.bmp")
|
||||||
|
print(
|
||||||
|
f"{Fore.GREEN}Screenshot saved to screenshot.bmp{Style.RESET_ALL}"
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
with open("screenshot.raw", "wb") as f:
|
||||||
|
f.write(screenshot_data)
|
||||||
|
print(
|
||||||
|
f"{Fore.GREEN}Screenshot saved to screenshot.raw (PIL not available){Style.RESET_ALL}"
|
||||||
|
)
|
||||||
|
expecting_screenshot = False
|
||||||
|
screenshot_data = b""
|
||||||
|
else:
|
||||||
|
try:
|
||||||
|
raw_data = ser.readline().decode("utf-8", errors="replace")
|
||||||
|
|
||||||
|
if not raw_data:
|
||||||
|
continue
|
||||||
|
|
||||||
|
clean_line = raw_data.strip()
|
||||||
|
if not clean_line:
|
||||||
|
continue
|
||||||
|
|
||||||
|
if clean_line.startswith("SCREENSHOT_START:"):
|
||||||
|
screenshot_size = int(clean_line.split(":")[1])
|
||||||
|
expecting_screenshot = True
|
||||||
|
continue
|
||||||
|
elif clean_line == "SCREENSHOT_END":
|
||||||
|
continue # ignore
|
||||||
|
|
||||||
|
# Add PC timestamp
|
||||||
|
pc_time = datetime.now().strftime("%H:%M:%S")
|
||||||
|
formatted_line = re.sub(r"^\[\d+\]", f"[{pc_time}]", clean_line)
|
||||||
|
|
||||||
|
# Check for Memory Line
|
||||||
|
if "[MEM]" in formatted_line:
|
||||||
|
free_val, total_val = parse_memory_line(formatted_line)
|
||||||
|
if free_val is not None and total_val is not None:
|
||||||
|
with data_lock:
|
||||||
|
time_data.append(pc_time)
|
||||||
|
free_mem_data.append(free_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
|
||||||
|
line_color = get_color_for_line(formatted_line)
|
||||||
|
print(f"{line_color}{formatted_line}")
|
||||||
|
|
||||||
|
except (OSError, UnicodeDecodeError):
|
||||||
|
print(
|
||||||
|
f"{Fore.RED}Device disconnected or data error.{Style.RESET_ALL}"
|
||||||
|
)
|
||||||
|
break
|
||||||
|
except KeyboardInterrupt:
|
||||||
|
# If thread is killed violently (e.g. main exit), silence errors
|
||||||
|
pass
|
||||||
|
finally:
|
||||||
|
pass # ser closed in main
|
||||||
|
|
||||||
|
|
||||||
|
def input_worker(ser) -> None:
|
||||||
|
"""
|
||||||
|
Runs in a background thread. Handles user input to send commands to the ESP32 device.
|
||||||
|
Monitors the global shutdown event for graceful termination on Ctrl-C.
|
||||||
|
"""
|
||||||
|
while not shutdown_event.is_set():
|
||||||
|
try:
|
||||||
|
cmd = input("Command: ")
|
||||||
|
ser.write(f"CMD:{cmd}\n".encode())
|
||||||
|
except (EOFError, KeyboardInterrupt):
|
||||||
|
break
|
||||||
|
|
||||||
|
|
||||||
|
def update_graph(frame) -> list: # pylint: disable=unused-argument
|
||||||
|
"""
|
||||||
|
Called by Matplotlib animation to redraw the memory usage chart.
|
||||||
|
Monitors the global shutdown event and closes the plot when shutdown is requested.
|
||||||
|
"""
|
||||||
|
if shutdown_event.is_set():
|
||||||
|
plt.close("all")
|
||||||
|
return []
|
||||||
|
|
||||||
|
with data_lock:
|
||||||
|
if not time_data:
|
||||||
|
return []
|
||||||
|
|
||||||
|
# Convert deques to lists for plotting
|
||||||
|
x = list(time_data)
|
||||||
|
y_free = list(free_mem_data)
|
||||||
|
y_total = list(total_mem_data)
|
||||||
|
|
||||||
|
plt.cla() # Clear axis
|
||||||
|
|
||||||
|
# Plot Total RAM
|
||||||
|
plt.plot(x, y_total, label="Total RAM (KB)", color="red", linestyle="--")
|
||||||
|
|
||||||
|
# Plot Free RAM
|
||||||
|
plt.plot(x, y_free, label="Free RAM (KB)", color="green", marker="o")
|
||||||
|
|
||||||
|
# Fill area under Free RAM
|
||||||
|
plt.fill_between(x, y_free, color="green", alpha=0.1)
|
||||||
|
|
||||||
|
plt.title("ESP32 Memory Monitor")
|
||||||
|
plt.ylabel("Memory (KB)")
|
||||||
|
plt.xlabel("Time")
|
||||||
|
plt.legend(loc="upper left")
|
||||||
|
plt.grid(True, linestyle=":", alpha=0.6)
|
||||||
|
|
||||||
|
# Rotate date labels
|
||||||
|
plt.xticks(rotation=45, ha="right")
|
||||||
|
plt.tight_layout()
|
||||||
|
|
||||||
|
return []
|
||||||
|
|
||||||
|
|
||||||
|
def get_auto_detected_port() -> list[str]:
|
||||||
|
"""
|
||||||
|
Attempts to auto-detect the serial port for the ESP32 device.
|
||||||
|
Returns a list of all detected ports.
|
||||||
|
If no suitable port is found, the list will be empty.
|
||||||
|
Darwin/Linux logic by jonasdiemer
|
||||||
|
"""
|
||||||
|
port_list = []
|
||||||
|
system = platform.system()
|
||||||
|
# Code for darwin (macOS), linux, and windows
|
||||||
|
if system in ("Darwin", "Linux"):
|
||||||
|
pattern = "/dev/tty.usbmodem*" if system == "Darwin" else "/dev/ttyACM*"
|
||||||
|
port_list = sorted(glob.glob(pattern))
|
||||||
|
elif system == "Windows":
|
||||||
|
from serial.tools import list_ports
|
||||||
|
|
||||||
|
# Be careful with this pattern list - it should be specific
|
||||||
|
# enough to avoid picking up unrelated devices, but broad enough
|
||||||
|
# to catch all common USB-serial adapters used with ESP32
|
||||||
|
# Caveat: localized versions of Windows may have different descriptions,
|
||||||
|
# so we also check for specific VID:PID (but that may not cover all clones)
|
||||||
|
pattern_list = ["CP210x", "CH340", "USB Serial"]
|
||||||
|
found_ports = list_ports.comports()
|
||||||
|
port_list = [
|
||||||
|
port.device
|
||||||
|
for port in found_ports
|
||||||
|
if any(pat in port.description for pat in pattern_list)
|
||||||
|
or port.hwid.startswith(
|
||||||
|
"USB VID:PID=303A:1001"
|
||||||
|
) # Add specific VID:PID for XTEINK X4
|
||||||
|
]
|
||||||
|
|
||||||
|
return port_list
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> None:
|
||||||
|
"""
|
||||||
|
Main entry point for the ESP32 monitor application.
|
||||||
|
|
||||||
|
Sets up argument parsing, initializes serial communication, starts background threads
|
||||||
|
for serial monitoring and command input, and launches the memory usage graph.
|
||||||
|
Implements graceful shutdown handling with signal processing for clean termination.
|
||||||
|
|
||||||
|
Features:
|
||||||
|
- Serial port monitoring with color-coded output
|
||||||
|
- Real-time memory usage graphing
|
||||||
|
- Interactive command interface
|
||||||
|
- Screenshot capture capability
|
||||||
|
- Graceful shutdown on Ctrl-C or window close
|
||||||
|
"""
|
||||||
|
parser = argparse.ArgumentParser(
|
||||||
|
description="ESP32 Serial Monitor with Memory Graph - Real-time monitoring, graphing, and command interface"
|
||||||
|
)
|
||||||
|
default_baudrate = 115200
|
||||||
|
parser.add_argument(
|
||||||
|
"port",
|
||||||
|
nargs="?",
|
||||||
|
default=None,
|
||||||
|
help="Serial port (leave empty for autodetection)",
|
||||||
|
)
|
||||||
|
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()
|
||||||
|
port = args.port
|
||||||
|
if port is None:
|
||||||
|
port_list = get_auto_detected_port()
|
||||||
|
if len(port_list) == 1:
|
||||||
|
port = port_list[0]
|
||||||
|
print(f"{Fore.CYAN}Auto-detected serial port: {port}{Style.RESET_ALL}")
|
||||||
|
elif len(port_list) > 1:
|
||||||
|
print(f"{Fore.YELLOW}Multiple serial ports found:{Style.RESET_ALL}")
|
||||||
|
for p in port_list:
|
||||||
|
print(f" - {p}")
|
||||||
|
print(
|
||||||
|
f"{Fore.YELLOW}Please specify the desired port as a command-line argument.{Style.RESET_ALL}"
|
||||||
|
)
|
||||||
|
if port is None:
|
||||||
|
print(f"{Fore.RED}Error: No suitable serial port found.{Style.RESET_ALL}")
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
try:
|
||||||
|
ser = serial.Serial(port, args.baud, timeout=0.1)
|
||||||
|
ser.dtr = False
|
||||||
|
ser.rts = False
|
||||||
|
except serial.SerialException as e:
|
||||||
|
print(f"{Fore.RED}Error opening port: {e}{Style.RESET_ALL}")
|
||||||
|
return
|
||||||
|
|
||||||
|
# Set up signal handler for graceful shutdown
|
||||||
|
signal.signal(signal.SIGINT, signal_handler)
|
||||||
|
|
||||||
|
# 1. Start the Serial Reader in a separate thread
|
||||||
|
# Daemon=True means this thread dies when the main program closes
|
||||||
|
myargs = vars(args) # Convert Namespace to dict for easier passing
|
||||||
|
t = threading.Thread(target=serial_worker, args=(ser, myargs), daemon=True)
|
||||||
|
t.start()
|
||||||
|
|
||||||
|
# Start input thread
|
||||||
|
input_thread = threading.Thread(target=input_worker, args=(ser,), daemon=True)
|
||||||
|
input_thread.start()
|
||||||
|
|
||||||
|
# 2. Set up the Graph (Main Thread)
|
||||||
|
try:
|
||||||
|
import matplotlib.style as mplstyle # pylint: disable=import-outside-toplevel
|
||||||
|
|
||||||
|
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
|
||||||
|
|
||||||
|
fig = plt.figure(figsize=(10, 6))
|
||||||
|
|
||||||
|
# Update graph every 1000ms
|
||||||
|
_ = animation.FuncAnimation(
|
||||||
|
fig, update_graph, interval=1000, cache_frame_data=False
|
||||||
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
print(
|
||||||
|
f"{Fore.YELLOW}Starting Graph Window... (Close window or press Ctrl-C to exit){Style.RESET_ALL}"
|
||||||
|
)
|
||||||
|
plt.show()
|
||||||
|
except KeyboardInterrupt:
|
||||||
|
print(f"\n{Fore.YELLOW}Exiting...{Style.RESET_ALL}")
|
||||||
|
finally:
|
||||||
|
shutdown_event.set() # Ensure all threads know to stop
|
||||||
|
plt.close("all") # Force close any lingering plot windows
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
123
scripts/generate_book_icon.py
Normal file
123
scripts/generate_book_icon.py
Normal file
@@ -0,0 +1,123 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Generate a 1-bit book icon bitmap as a C header for PlaceholderCoverGenerator.
|
||||||
|
|
||||||
|
The icon is a simplified closed book with a spine on the left and 3 text lines.
|
||||||
|
Output format matches Logo120.h: MSB-first packed 1-bit, 0=black, 1=white.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from PIL import Image, ImageDraw
|
||||||
|
import sys
|
||||||
|
|
||||||
|
|
||||||
|
def generate_book_icon(size=48):
|
||||||
|
"""Create a book icon at the given size."""
|
||||||
|
img = Image.new("1", (size, size), 1) # White background
|
||||||
|
draw = ImageDraw.Draw(img)
|
||||||
|
|
||||||
|
# Scale helper
|
||||||
|
s = size / 48.0
|
||||||
|
|
||||||
|
# Book body (main rectangle, leaving room for spine and pages)
|
||||||
|
body_left = int(6 * s)
|
||||||
|
body_top = int(2 * s)
|
||||||
|
body_right = int(42 * s)
|
||||||
|
body_bottom = int(40 * s)
|
||||||
|
|
||||||
|
# Draw book body outline (2px thick)
|
||||||
|
for i in range(int(2 * s)):
|
||||||
|
draw.rectangle(
|
||||||
|
[body_left + i, body_top + i, body_right - i, body_bottom - i], outline=0
|
||||||
|
)
|
||||||
|
|
||||||
|
# Spine (thicker left edge)
|
||||||
|
spine_width = int(4 * s)
|
||||||
|
draw.rectangle([body_left, body_top, body_left + spine_width, body_bottom], fill=0)
|
||||||
|
|
||||||
|
# Pages at the bottom (slight offset from body)
|
||||||
|
pages_top = body_bottom
|
||||||
|
pages_bottom = int(44 * s)
|
||||||
|
draw.rectangle(
|
||||||
|
[body_left + int(2 * s), pages_top, body_right - int(1 * s), pages_bottom],
|
||||||
|
outline=0,
|
||||||
|
)
|
||||||
|
# Page edges (a few lines)
|
||||||
|
for i in range(3):
|
||||||
|
y = pages_top + int((i + 1) * 1 * s)
|
||||||
|
if y < pages_bottom:
|
||||||
|
draw.line(
|
||||||
|
[body_left + int(3 * s), y, body_right - int(2 * s), y], fill=0
|
||||||
|
)
|
||||||
|
|
||||||
|
# Text lines on the book cover
|
||||||
|
text_left = body_left + spine_width + int(4 * s)
|
||||||
|
text_right = body_right - int(4 * s)
|
||||||
|
line_thickness = max(1, int(1.5 * s))
|
||||||
|
|
||||||
|
text_lines_y = [int(12 * s), int(18 * s), int(24 * s)]
|
||||||
|
text_widths = [1.0, 0.7, 0.85] # Relative widths for visual interest
|
||||||
|
|
||||||
|
for y, w_ratio in zip(text_lines_y, text_widths):
|
||||||
|
line_right = text_left + int((text_right - text_left) * w_ratio)
|
||||||
|
for t in range(line_thickness):
|
||||||
|
draw.line([text_left, y + t, line_right, y + t], fill=0)
|
||||||
|
|
||||||
|
return img
|
||||||
|
|
||||||
|
|
||||||
|
def image_to_c_array(img, name="BookIcon"):
|
||||||
|
"""Convert a 1-bit PIL image to a C header array."""
|
||||||
|
width, height = img.size
|
||||||
|
pixels = img.load()
|
||||||
|
|
||||||
|
bytes_per_row = width // 8
|
||||||
|
data = []
|
||||||
|
|
||||||
|
for y in range(height):
|
||||||
|
for bx in range(bytes_per_row):
|
||||||
|
byte = 0
|
||||||
|
for bit in range(8):
|
||||||
|
x = bx * 8 + bit
|
||||||
|
if x < width:
|
||||||
|
# 1 = white, 0 = black (matching Logo120.h convention)
|
||||||
|
if pixels[x, y]:
|
||||||
|
byte |= 1 << (7 - bit)
|
||||||
|
data.append(byte)
|
||||||
|
|
||||||
|
# Format as C header
|
||||||
|
lines = []
|
||||||
|
lines.append("#pragma once")
|
||||||
|
lines.append("#include <cstdint>")
|
||||||
|
lines.append("")
|
||||||
|
lines.append(f"// Book icon: {width}x{height}, 1-bit packed (MSB first)")
|
||||||
|
lines.append(f"// 0 = black, 1 = white (same format as Logo120.h)")
|
||||||
|
lines.append(f"static constexpr int BOOK_ICON_WIDTH = {width};")
|
||||||
|
lines.append(f"static constexpr int BOOK_ICON_HEIGHT = {height};")
|
||||||
|
lines.append(f"static const uint8_t {name}[] = {{")
|
||||||
|
|
||||||
|
# Format data in rows of 16 bytes
|
||||||
|
for i in range(0, len(data), 16):
|
||||||
|
chunk = data[i : i + 16]
|
||||||
|
hex_str = ", ".join(f"0x{b:02x}" for b in chunk)
|
||||||
|
lines.append(f" {hex_str},")
|
||||||
|
|
||||||
|
lines.append("};")
|
||||||
|
lines.append("")
|
||||||
|
|
||||||
|
return "\n".join(lines)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
size = int(sys.argv[1]) if len(sys.argv) > 1 else 48
|
||||||
|
img = generate_book_icon(size)
|
||||||
|
|
||||||
|
# Save preview PNG
|
||||||
|
preview_path = f"mod/book_icon_{size}x{size}.png"
|
||||||
|
img.resize((size * 4, size * 4), Image.NEAREST).save(preview_path)
|
||||||
|
print(f"Preview saved to {preview_path}", file=sys.stderr)
|
||||||
|
|
||||||
|
# Generate C header
|
||||||
|
header = image_to_c_array(img, "BookIcon")
|
||||||
|
output_path = "lib/PlaceholderCover/BookIcon.h"
|
||||||
|
with open(output_path, "w") as f:
|
||||||
|
f.write(header)
|
||||||
|
print(f"C header saved to {output_path}", file=sys.stderr)
|
||||||
501
scripts/generate_test_epub.py
Normal file
501
scripts/generate_test_epub.py
Normal file
@@ -0,0 +1,501 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""
|
||||||
|
Generate test EPUBs for image rendering verification.
|
||||||
|
|
||||||
|
Creates EPUBs with annotated JPEG and PNG images to verify:
|
||||||
|
- Grayscale rendering (4 levels)
|
||||||
|
- Image scaling
|
||||||
|
- Image centering
|
||||||
|
- Cache performance
|
||||||
|
- Page serialization
|
||||||
|
"""
|
||||||
|
|
||||||
|
import os
|
||||||
|
import zipfile
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
try:
|
||||||
|
from PIL import Image, ImageDraw, ImageFont
|
||||||
|
except ImportError:
|
||||||
|
print("Please install Pillow: pip install Pillow")
|
||||||
|
exit(1)
|
||||||
|
|
||||||
|
OUTPUT_DIR = Path(__file__).parent.parent / "test" / "epubs"
|
||||||
|
SCREEN_WIDTH = 480
|
||||||
|
SCREEN_HEIGHT = 800
|
||||||
|
|
||||||
|
def get_font(size=20):
|
||||||
|
"""Get a font, falling back to default if needed."""
|
||||||
|
try:
|
||||||
|
return ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", size)
|
||||||
|
except:
|
||||||
|
try:
|
||||||
|
return ImageFont.truetype("/usr/share/fonts/TTF/DejaVuSans.ttf", size)
|
||||||
|
except:
|
||||||
|
return ImageFont.load_default()
|
||||||
|
|
||||||
|
def draw_text_centered(draw, y, text, font, fill=0):
|
||||||
|
"""Draw centered text at given y position."""
|
||||||
|
bbox = draw.textbbox((0, 0), text, font=font)
|
||||||
|
text_width = bbox[2] - bbox[0]
|
||||||
|
x = (draw.im.size[0] - text_width) // 2
|
||||||
|
draw.text((x, y), text, font=font, fill=fill)
|
||||||
|
|
||||||
|
def draw_text_wrapped(draw, x, y, text, font, max_width, fill=0):
|
||||||
|
"""Draw text with word wrapping."""
|
||||||
|
words = text.split()
|
||||||
|
lines = []
|
||||||
|
current_line = []
|
||||||
|
|
||||||
|
for word in words:
|
||||||
|
test_line = ' '.join(current_line + [word])
|
||||||
|
bbox = draw.textbbox((0, 0), test_line, font=font)
|
||||||
|
if bbox[2] - bbox[0] <= max_width:
|
||||||
|
current_line.append(word)
|
||||||
|
else:
|
||||||
|
if current_line:
|
||||||
|
lines.append(' '.join(current_line))
|
||||||
|
current_line = [word]
|
||||||
|
if current_line:
|
||||||
|
lines.append(' '.join(current_line))
|
||||||
|
|
||||||
|
line_height = font.size + 4 if hasattr(font, 'size') else 20
|
||||||
|
for i, line in enumerate(lines):
|
||||||
|
draw.text((x, y + i * line_height), line, font=font, fill=fill)
|
||||||
|
|
||||||
|
return len(lines) * line_height
|
||||||
|
|
||||||
|
def create_grayscale_test_image(filename, is_png=True):
|
||||||
|
"""
|
||||||
|
Create image with 4 grayscale squares to verify 4-level rendering.
|
||||||
|
"""
|
||||||
|
width, height = 400, 600
|
||||||
|
img = Image.new('L', (width, height), 255)
|
||||||
|
draw = ImageDraw.Draw(img)
|
||||||
|
font = get_font(16)
|
||||||
|
font_small = get_font(14)
|
||||||
|
|
||||||
|
# Title
|
||||||
|
draw_text_centered(draw, 10, "GRAYSCALE TEST", font, fill=0)
|
||||||
|
draw_text_centered(draw, 35, "Verify 4 distinct gray levels", font_small, fill=64)
|
||||||
|
|
||||||
|
# Draw 4 grayscale squares
|
||||||
|
square_size = 70
|
||||||
|
start_y = 65
|
||||||
|
gap = 10
|
||||||
|
|
||||||
|
levels = [
|
||||||
|
(0, "Level 0: BLACK"),
|
||||||
|
(96, "Level 1: DARK GRAY"),
|
||||||
|
(160, "Level 2: LIGHT GRAY"),
|
||||||
|
(255, "Level 3: WHITE"),
|
||||||
|
]
|
||||||
|
|
||||||
|
for i, (gray_value, label) in enumerate(levels):
|
||||||
|
y = start_y + i * (square_size + gap + 22)
|
||||||
|
x = (width - square_size) // 2
|
||||||
|
|
||||||
|
# Draw square with border
|
||||||
|
draw.rectangle([x-2, y-2, x + square_size + 2, y + square_size + 2], fill=0)
|
||||||
|
draw.rectangle([x, y, x + square_size, y + square_size], fill=gray_value)
|
||||||
|
|
||||||
|
# Label below square
|
||||||
|
bbox = draw.textbbox((0, 0), label, font=font_small)
|
||||||
|
label_width = bbox[2] - bbox[0]
|
||||||
|
draw.text(((width - label_width) // 2, y + square_size + 5), label, font=font_small, fill=0)
|
||||||
|
|
||||||
|
# Instructions at bottom
|
||||||
|
y = height - 70
|
||||||
|
draw_text_centered(draw, y, "PASS: 4 distinct shades visible", font_small, fill=0)
|
||||||
|
draw_text_centered(draw, y + 20, "FAIL: Only black/white or", font_small, fill=64)
|
||||||
|
draw_text_centered(draw, y + 38, "muddy/indistinct grays", font_small, fill=64)
|
||||||
|
|
||||||
|
if is_png:
|
||||||
|
img.save(filename, 'PNG')
|
||||||
|
else:
|
||||||
|
img.save(filename, 'JPEG', quality=95)
|
||||||
|
|
||||||
|
def create_centering_test_image(filename, is_png=True):
|
||||||
|
"""
|
||||||
|
Create image with border markers to verify centering.
|
||||||
|
"""
|
||||||
|
width, height = 350, 400
|
||||||
|
img = Image.new('L', (width, height), 255)
|
||||||
|
draw = ImageDraw.Draw(img)
|
||||||
|
font = get_font(16)
|
||||||
|
font_small = get_font(14)
|
||||||
|
|
||||||
|
# Draw border
|
||||||
|
draw.rectangle([0, 0, width-1, height-1], outline=0, width=3)
|
||||||
|
|
||||||
|
# Corner markers
|
||||||
|
marker_size = 20
|
||||||
|
for x, y in [(0, 0), (width-marker_size, 0), (0, height-marker_size), (width-marker_size, height-marker_size)]:
|
||||||
|
draw.rectangle([x, y, x+marker_size, y+marker_size], fill=0)
|
||||||
|
|
||||||
|
# Center cross
|
||||||
|
cx, cy = width // 2, height // 2
|
||||||
|
draw.line([cx - 30, cy, cx + 30, cy], fill=0, width=2)
|
||||||
|
draw.line([cx, cy - 30, cx, cy + 30], fill=0, width=2)
|
||||||
|
|
||||||
|
# Title
|
||||||
|
draw_text_centered(draw, 40, "CENTERING TEST", font, fill=0)
|
||||||
|
|
||||||
|
# Instructions
|
||||||
|
y = 80
|
||||||
|
draw_text_centered(draw, y, "Image should be centered", font_small, fill=0)
|
||||||
|
draw_text_centered(draw, y + 20, "horizontally on screen", font_small, fill=0)
|
||||||
|
|
||||||
|
y = 150
|
||||||
|
draw_text_centered(draw, y, "Check:", font_small, fill=0)
|
||||||
|
draw_text_centered(draw, y + 25, "- Equal margins left & right", font_small, fill=64)
|
||||||
|
draw_text_centered(draw, y + 45, "- All 4 corners visible", font_small, fill=64)
|
||||||
|
draw_text_centered(draw, y + 65, "- Border is complete rectangle", font_small, fill=64)
|
||||||
|
|
||||||
|
# Pass/fail
|
||||||
|
y = height - 80
|
||||||
|
draw_text_centered(draw, y, "PASS: Centered, all corners visible", font_small, fill=0)
|
||||||
|
draw_text_centered(draw, y + 20, "FAIL: Off-center or cropped", font_small, fill=64)
|
||||||
|
|
||||||
|
if is_png:
|
||||||
|
img.save(filename, 'PNG')
|
||||||
|
else:
|
||||||
|
img.save(filename, 'JPEG', quality=95)
|
||||||
|
|
||||||
|
def create_scaling_test_image(filename, is_png=True):
|
||||||
|
"""
|
||||||
|
Create large image to verify scaling works.
|
||||||
|
"""
|
||||||
|
width, height = 1200, 1500
|
||||||
|
img = Image.new('L', (width, height), 240)
|
||||||
|
draw = ImageDraw.Draw(img)
|
||||||
|
font = get_font(48)
|
||||||
|
font_medium = get_font(32)
|
||||||
|
font_small = get_font(24)
|
||||||
|
|
||||||
|
# Border
|
||||||
|
draw.rectangle([0, 0, width-1, height-1], outline=0, width=8)
|
||||||
|
draw.rectangle([20, 20, width-21, height-21], outline=128, width=4)
|
||||||
|
|
||||||
|
# Title
|
||||||
|
draw_text_centered(draw, 60, "SCALING TEST", font, fill=0)
|
||||||
|
draw_text_centered(draw, 130, f"Original: {width}x{height} (larger than screen)", font_medium, fill=64)
|
||||||
|
|
||||||
|
# Grid pattern
|
||||||
|
grid_start_y = 220
|
||||||
|
grid_size = 400
|
||||||
|
cell_size = 50
|
||||||
|
|
||||||
|
draw_text_centered(draw, grid_start_y - 40, "Grid pattern (check for artifacts):", font_small, fill=0)
|
||||||
|
|
||||||
|
grid_x = (width - grid_size) // 2
|
||||||
|
for row in range(grid_size // cell_size):
|
||||||
|
for col in range(grid_size // cell_size):
|
||||||
|
x = grid_x + col * cell_size
|
||||||
|
y = grid_start_y + row * cell_size
|
||||||
|
if (row + col) % 2 == 0:
|
||||||
|
draw.rectangle([x, y, x + cell_size, y + cell_size], fill=0)
|
||||||
|
else:
|
||||||
|
draw.rectangle([x, y, x + cell_size, y + cell_size], fill=200)
|
||||||
|
|
||||||
|
# Pass/fail
|
||||||
|
y = height - 100
|
||||||
|
draw_text_centered(draw, y, "PASS: Scaled down, readable, complete", font_small, fill=0)
|
||||||
|
draw_text_centered(draw, y + 30, "FAIL: Cropped, distorted, or unreadable", font_small, fill=64)
|
||||||
|
|
||||||
|
if is_png:
|
||||||
|
img.save(filename, 'PNG')
|
||||||
|
else:
|
||||||
|
img.save(filename, 'JPEG', quality=95)
|
||||||
|
|
||||||
|
def create_cache_test_image(filename, page_num, is_png=True):
|
||||||
|
"""
|
||||||
|
Create image for cache performance testing.
|
||||||
|
"""
|
||||||
|
width, height = 400, 300
|
||||||
|
img = Image.new('L', (width, height), 255)
|
||||||
|
draw = ImageDraw.Draw(img)
|
||||||
|
font = get_font(18)
|
||||||
|
font_small = get_font(14)
|
||||||
|
font_large = get_font(36)
|
||||||
|
|
||||||
|
# Border
|
||||||
|
draw.rectangle([0, 0, width-1, height-1], outline=0, width=2)
|
||||||
|
|
||||||
|
# Page number prominent
|
||||||
|
draw_text_centered(draw, 30, f"CACHE TEST PAGE {page_num}", font, fill=0)
|
||||||
|
draw_text_centered(draw, 80, f"#{page_num}", font_large, fill=0)
|
||||||
|
|
||||||
|
# Instructions
|
||||||
|
y = 140
|
||||||
|
draw_text_centered(draw, y, "Navigate away then return", font_small, fill=64)
|
||||||
|
draw_text_centered(draw, y + 25, "Second load should be faster", font_small, fill=64)
|
||||||
|
|
||||||
|
y = 220
|
||||||
|
draw_text_centered(draw, y, "PASS: Faster reload from cache", font_small, fill=0)
|
||||||
|
draw_text_centered(draw, y + 20, "FAIL: Same slow decode each time", font_small, fill=64)
|
||||||
|
|
||||||
|
if is_png:
|
||||||
|
img.save(filename, 'PNG')
|
||||||
|
else:
|
||||||
|
img.save(filename, 'JPEG', quality=95)
|
||||||
|
|
||||||
|
def create_format_test_image(filename, format_name, is_png=True):
|
||||||
|
"""
|
||||||
|
Create simple image to verify format support.
|
||||||
|
"""
|
||||||
|
width, height = 350, 250
|
||||||
|
img = Image.new('L', (width, height), 255)
|
||||||
|
draw = ImageDraw.Draw(img)
|
||||||
|
font = get_font(20)
|
||||||
|
font_large = get_font(36)
|
||||||
|
font_small = get_font(14)
|
||||||
|
|
||||||
|
# Border
|
||||||
|
draw.rectangle([0, 0, width-1, height-1], outline=0, width=3)
|
||||||
|
|
||||||
|
# Format name
|
||||||
|
draw_text_centered(draw, 30, f"{format_name} FORMAT TEST", font, fill=0)
|
||||||
|
draw_text_centered(draw, 80, format_name, font_large, fill=0)
|
||||||
|
|
||||||
|
# Checkmark area
|
||||||
|
y = 140
|
||||||
|
draw_text_centered(draw, y, "If you can read this,", font_small, fill=64)
|
||||||
|
draw_text_centered(draw, y + 20, f"{format_name} decoding works!", font_small, fill=64)
|
||||||
|
|
||||||
|
y = height - 40
|
||||||
|
draw_text_centered(draw, y, f"PASS: {format_name} image visible", font_small, fill=0)
|
||||||
|
|
||||||
|
if is_png:
|
||||||
|
img.save(filename, 'PNG')
|
||||||
|
else:
|
||||||
|
img.save(filename, 'JPEG', quality=95)
|
||||||
|
|
||||||
|
def create_epub(epub_path, title, chapters):
|
||||||
|
"""
|
||||||
|
Create an EPUB file with the given chapters.
|
||||||
|
|
||||||
|
chapters: list of (chapter_title, html_content, images)
|
||||||
|
images: list of (image_filename, image_data)
|
||||||
|
"""
|
||||||
|
with zipfile.ZipFile(epub_path, 'w', zipfile.ZIP_DEFLATED) as epub:
|
||||||
|
# mimetype (must be first, uncompressed)
|
||||||
|
epub.writestr('mimetype', 'application/epub+zip', compress_type=zipfile.ZIP_STORED)
|
||||||
|
|
||||||
|
# Container
|
||||||
|
container_xml = '''<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<container version="1.0" xmlns="urn:oasis:names:tc:opendocument:xmlns:container">
|
||||||
|
<rootfiles>
|
||||||
|
<rootfile full-path="OEBPS/content.opf" media-type="application/oebps-package+xml"/>
|
||||||
|
</rootfiles>
|
||||||
|
</container>'''
|
||||||
|
epub.writestr('META-INF/container.xml', container_xml)
|
||||||
|
|
||||||
|
# Collect all images and chapters
|
||||||
|
manifest_items = []
|
||||||
|
spine_items = []
|
||||||
|
|
||||||
|
# Add chapters and images
|
||||||
|
for i, (chapter_title, html_content, images) in enumerate(chapters):
|
||||||
|
chapter_id = f'chapter{i+1}'
|
||||||
|
chapter_file = f'chapter{i+1}.xhtml'
|
||||||
|
|
||||||
|
# Add images for this chapter
|
||||||
|
for img_filename, img_data in images:
|
||||||
|
media_type = 'image/png' if img_filename.endswith('.png') else 'image/jpeg'
|
||||||
|
manifest_items.append(f' <item id="{img_filename.replace(".", "_")}" href="images/{img_filename}" media-type="{media_type}"/>')
|
||||||
|
epub.writestr(f'OEBPS/images/{img_filename}', img_data)
|
||||||
|
|
||||||
|
# Add chapter
|
||||||
|
manifest_items.append(f' <item id="{chapter_id}" href="{chapter_file}" media-type="application/xhtml+xml"/>')
|
||||||
|
spine_items.append(f' <itemref idref="{chapter_id}"/>')
|
||||||
|
epub.writestr(f'OEBPS/{chapter_file}', html_content)
|
||||||
|
|
||||||
|
# content.opf
|
||||||
|
content_opf = f'''<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<package xmlns="http://www.idpf.org/2007/opf" version="3.0" unique-identifier="uid">
|
||||||
|
<metadata xmlns:dc="http://purl.org/dc/elements/1.1/">
|
||||||
|
<dc:identifier id="uid">test-epub-{title.lower().replace(" ", "-")}</dc:identifier>
|
||||||
|
<dc:title>{title}</dc:title>
|
||||||
|
<dc:language>en</dc:language>
|
||||||
|
</metadata>
|
||||||
|
<manifest>
|
||||||
|
<item id="nav" href="nav.xhtml" media-type="application/xhtml+xml" properties="nav"/>
|
||||||
|
{chr(10).join(manifest_items)}
|
||||||
|
</manifest>
|
||||||
|
<spine>
|
||||||
|
{chr(10).join(spine_items)}
|
||||||
|
</spine>
|
||||||
|
</package>'''
|
||||||
|
epub.writestr('OEBPS/content.opf', content_opf)
|
||||||
|
|
||||||
|
# Navigation document
|
||||||
|
nav_items = '\n'.join([f' <li><a href="chapter{i+1}.xhtml">{chapters[i][0]}</a></li>'
|
||||||
|
for i in range(len(chapters))])
|
||||||
|
nav_xhtml = f'''<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:epub="http://www.idpf.org/2007/ops">
|
||||||
|
<head><title>Navigation</title></head>
|
||||||
|
<body>
|
||||||
|
<nav epub:type="toc">
|
||||||
|
<h1>Contents</h1>
|
||||||
|
<ol>
|
||||||
|
{nav_items}
|
||||||
|
</ol>
|
||||||
|
</nav>
|
||||||
|
</body>
|
||||||
|
</html>'''
|
||||||
|
epub.writestr('OEBPS/nav.xhtml', nav_xhtml)
|
||||||
|
|
||||||
|
def make_chapter(title, body_content):
|
||||||
|
"""Create XHTML chapter content."""
|
||||||
|
return f'''<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html xmlns="http://www.w3.org/1999/xhtml">
|
||||||
|
<head><title>{title}</title></head>
|
||||||
|
<body>
|
||||||
|
<h1>{title}</h1>
|
||||||
|
{body_content}
|
||||||
|
</body>
|
||||||
|
</html>'''
|
||||||
|
|
||||||
|
def main():
|
||||||
|
OUTPUT_DIR.mkdir(exist_ok=True)
|
||||||
|
|
||||||
|
import tempfile
|
||||||
|
with tempfile.TemporaryDirectory() as tmpdir:
|
||||||
|
tmpdir = Path(tmpdir)
|
||||||
|
|
||||||
|
print("Generating test images...")
|
||||||
|
|
||||||
|
images = {}
|
||||||
|
|
||||||
|
# JPEG tests
|
||||||
|
create_grayscale_test_image(tmpdir / 'grayscale_test.jpg', is_png=False)
|
||||||
|
create_centering_test_image(tmpdir / 'centering_test.jpg', is_png=False)
|
||||||
|
create_scaling_test_image(tmpdir / 'scaling_test.jpg', is_png=False)
|
||||||
|
create_format_test_image(tmpdir / 'jpeg_format.jpg', 'JPEG', is_png=False)
|
||||||
|
create_cache_test_image(tmpdir / 'cache_test_1.jpg', 1, is_png=False)
|
||||||
|
create_cache_test_image(tmpdir / 'cache_test_2.jpg', 2, is_png=False)
|
||||||
|
|
||||||
|
# PNG tests
|
||||||
|
create_grayscale_test_image(tmpdir / 'grayscale_test.png', is_png=True)
|
||||||
|
create_centering_test_image(tmpdir / 'centering_test.png', is_png=True)
|
||||||
|
create_scaling_test_image(tmpdir / 'scaling_test.png', is_png=True)
|
||||||
|
create_format_test_image(tmpdir / 'png_format.png', 'PNG', is_png=True)
|
||||||
|
create_cache_test_image(tmpdir / 'cache_test_1.png', 1, is_png=True)
|
||||||
|
create_cache_test_image(tmpdir / 'cache_test_2.png', 2, is_png=True)
|
||||||
|
|
||||||
|
# Read all images
|
||||||
|
for img_file in tmpdir.glob('*.*'):
|
||||||
|
images[img_file.name] = img_file.read_bytes()
|
||||||
|
|
||||||
|
print("Creating JPEG test EPUB...")
|
||||||
|
jpeg_chapters = [
|
||||||
|
("Introduction", make_chapter("JPEG Image Tests", """
|
||||||
|
<p>This EPUB tests JPEG image rendering.</p>
|
||||||
|
<p>Navigate through chapters to verify each test case.</p>
|
||||||
|
"""), []),
|
||||||
|
("1. JPEG Format", make_chapter("JPEG Format Test", """
|
||||||
|
<p>Basic JPEG decoding test.</p>
|
||||||
|
<img src="images/jpeg_format.jpg" alt="JPEG format test"/>
|
||||||
|
<p>If the image above is visible, JPEG decoding works.</p>
|
||||||
|
"""), [('jpeg_format.jpg', images['jpeg_format.jpg'])]),
|
||||||
|
("2. Grayscale", make_chapter("Grayscale Test", """
|
||||||
|
<p>Verify 4 distinct gray levels are visible.</p>
|
||||||
|
<img src="images/grayscale_test.jpg" alt="Grayscale test"/>
|
||||||
|
"""), [('grayscale_test.jpg', images['grayscale_test.jpg'])]),
|
||||||
|
("3. Centering", make_chapter("Centering Test", """
|
||||||
|
<p>Verify image is centered horizontally.</p>
|
||||||
|
<img src="images/centering_test.jpg" alt="Centering test"/>
|
||||||
|
"""), [('centering_test.jpg', images['centering_test.jpg'])]),
|
||||||
|
("4. Scaling", make_chapter("Scaling Test", """
|
||||||
|
<p>This image is 1200x1500 pixels - larger than the screen.</p>
|
||||||
|
<p>It should be scaled down to fit.</p>
|
||||||
|
<img src="images/scaling_test.jpg" alt="Scaling test"/>
|
||||||
|
"""), [('scaling_test.jpg', images['scaling_test.jpg'])]),
|
||||||
|
("5. Cache Test A", make_chapter("Cache Test - Page A", """
|
||||||
|
<p>First cache test page. Note the load time.</p>
|
||||||
|
<img src="images/cache_test_1.jpg" alt="Cache test 1"/>
|
||||||
|
<p>Navigate to next page, then come back.</p>
|
||||||
|
"""), [('cache_test_1.jpg', images['cache_test_1.jpg'])]),
|
||||||
|
("6. Cache Test B", make_chapter("Cache Test - Page B", """
|
||||||
|
<p>Second cache test page.</p>
|
||||||
|
<img src="images/cache_test_2.jpg" alt="Cache test 2"/>
|
||||||
|
<p>Navigate back to Page A - it should load faster from cache.</p>
|
||||||
|
"""), [('cache_test_2.jpg', images['cache_test_2.jpg'])]),
|
||||||
|
]
|
||||||
|
|
||||||
|
create_epub(OUTPUT_DIR / 'test_jpeg_images.epub', 'JPEG Image Tests', jpeg_chapters)
|
||||||
|
|
||||||
|
print("Creating PNG test EPUB...")
|
||||||
|
png_chapters = [
|
||||||
|
("Introduction", make_chapter("PNG Image Tests", """
|
||||||
|
<p>This EPUB tests PNG image rendering.</p>
|
||||||
|
<p>Navigate through chapters to verify each test case.</p>
|
||||||
|
"""), []),
|
||||||
|
("1. PNG Format", make_chapter("PNG Format Test", """
|
||||||
|
<p>Basic PNG decoding test.</p>
|
||||||
|
<img src="images/png_format.png" alt="PNG format test"/>
|
||||||
|
<p>If the image above is visible and no crash occurred, PNG decoding works.</p>
|
||||||
|
"""), [('png_format.png', images['png_format.png'])]),
|
||||||
|
("2. Grayscale", make_chapter("Grayscale Test", """
|
||||||
|
<p>Verify 4 distinct gray levels are visible.</p>
|
||||||
|
<img src="images/grayscale_test.png" alt="Grayscale test"/>
|
||||||
|
"""), [('grayscale_test.png', images['grayscale_test.png'])]),
|
||||||
|
("3. Centering", make_chapter("Centering Test", """
|
||||||
|
<p>Verify image is centered horizontally.</p>
|
||||||
|
<img src="images/centering_test.png" alt="Centering test"/>
|
||||||
|
"""), [('centering_test.png', images['centering_test.png'])]),
|
||||||
|
("4. Scaling", make_chapter("Scaling Test", """
|
||||||
|
<p>This image is 1200x1500 pixels - larger than the screen.</p>
|
||||||
|
<p>It should be scaled down to fit.</p>
|
||||||
|
<img src="images/scaling_test.png" alt="Scaling test"/>
|
||||||
|
"""), [('scaling_test.png', images['scaling_test.png'])]),
|
||||||
|
("5. Cache Test A", make_chapter("Cache Test - Page A", """
|
||||||
|
<p>First cache test page. Note the load time.</p>
|
||||||
|
<img src="images/cache_test_1.png" alt="Cache test 1"/>
|
||||||
|
<p>Navigate to next page, then come back.</p>
|
||||||
|
"""), [('cache_test_1.png', images['cache_test_1.png'])]),
|
||||||
|
("6. Cache Test B", make_chapter("Cache Test - Page B", """
|
||||||
|
<p>Second cache test page.</p>
|
||||||
|
<img src="images/cache_test_2.png" alt="Cache test 2"/>
|
||||||
|
<p>Navigate back to Page A - it should load faster from cache.</p>
|
||||||
|
"""), [('cache_test_2.png', images['cache_test_2.png'])]),
|
||||||
|
]
|
||||||
|
|
||||||
|
create_epub(OUTPUT_DIR / 'test_png_images.epub', 'PNG Image Tests', png_chapters)
|
||||||
|
|
||||||
|
print("Creating mixed format test EPUB...")
|
||||||
|
mixed_chapters = [
|
||||||
|
("Introduction", make_chapter("Mixed Image Format Tests", """
|
||||||
|
<p>This EPUB contains both JPEG and PNG images.</p>
|
||||||
|
<p>Tests format detection and mixed rendering.</p>
|
||||||
|
"""), []),
|
||||||
|
("1. JPEG Image", make_chapter("JPEG in Mixed EPUB", """
|
||||||
|
<p>This is a JPEG image:</p>
|
||||||
|
<img src="images/jpeg_format.jpg" alt="JPEG"/>
|
||||||
|
"""), [('jpeg_format.jpg', images['jpeg_format.jpg'])]),
|
||||||
|
("2. PNG Image", make_chapter("PNG in Mixed EPUB", """
|
||||||
|
<p>This is a PNG image:</p>
|
||||||
|
<img src="images/png_format.png" alt="PNG"/>
|
||||||
|
"""), [('png_format.png', images['png_format.png'])]),
|
||||||
|
("3. Both Formats", make_chapter("Both Formats on One Page", """
|
||||||
|
<p>JPEG image:</p>
|
||||||
|
<img src="images/grayscale_test.jpg" alt="JPEG grayscale"/>
|
||||||
|
<p>PNG image:</p>
|
||||||
|
<img src="images/grayscale_test.png" alt="PNG grayscale"/>
|
||||||
|
<p>Both should render with proper grayscale.</p>
|
||||||
|
"""), [('grayscale_test.jpg', images['grayscale_test.jpg']),
|
||||||
|
('grayscale_test.png', images['grayscale_test.png'])]),
|
||||||
|
]
|
||||||
|
|
||||||
|
create_epub(OUTPUT_DIR / 'test_mixed_images.epub', 'Mixed Format Tests', mixed_chapters)
|
||||||
|
|
||||||
|
print(f"\nTest EPUBs created in: {OUTPUT_DIR}")
|
||||||
|
print("Files:")
|
||||||
|
for f in OUTPUT_DIR.glob('*.epub'):
|
||||||
|
print(f" - {f.name}")
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
main()
|
||||||
15
scripts/inject_mod_version.py
Normal file
15
scripts/inject_mod_version.py
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
Import("env")
|
||||||
|
import subprocess
|
||||||
|
|
||||||
|
config = env.GetProjectConfig()
|
||||||
|
version = config.get("crosspoint", "version")
|
||||||
|
|
||||||
|
result = subprocess.run(
|
||||||
|
["git", "rev-parse", "--short", "HEAD"],
|
||||||
|
capture_output=True, text=True
|
||||||
|
)
|
||||||
|
git_hash = result.stdout.strip()
|
||||||
|
|
||||||
|
env.Append(
|
||||||
|
BUILD_FLAGS=[f'-DCROSSPOINT_VERSION=\\"{version}-mod+{git_hash}\\"']
|
||||||
|
)
|
||||||
179
scripts/preview_placeholder_cover.py
Normal file
179
scripts/preview_placeholder_cover.py
Normal file
@@ -0,0 +1,179 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Generate a preview of the placeholder cover layout at full cover size (480x800).
|
||||||
|
This mirrors the C++ PlaceholderCoverGenerator layout logic for visual verification.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from PIL import Image, ImageDraw, ImageFont
|
||||||
|
import sys
|
||||||
|
import os
|
||||||
|
|
||||||
|
# Reuse the book icon generator
|
||||||
|
sys.path.insert(0, os.path.dirname(__file__))
|
||||||
|
from generate_book_icon import generate_book_icon
|
||||||
|
|
||||||
|
|
||||||
|
def create_preview(width=480, height=800, title="The Great Gatsby", author="F. Scott Fitzgerald"):
|
||||||
|
img = Image.new("1", (width, height), 1) # White
|
||||||
|
draw = ImageDraw.Draw(img)
|
||||||
|
|
||||||
|
# Proportional layout constants
|
||||||
|
edge_padding = max(3, width // 48) # ~10px at 480w
|
||||||
|
border_width = max(2, width // 96) # ~5px at 480w
|
||||||
|
inner_padding = max(4, width // 32) # ~15px at 480w
|
||||||
|
|
||||||
|
title_scale = 2 if height >= 600 else 1
|
||||||
|
author_scale = 2 if height >= 600 else 1 # Author also larger on full covers
|
||||||
|
icon_scale = 2 if height >= 600 else (1 if height >= 350 else 0)
|
||||||
|
|
||||||
|
# Draw border inset from edge
|
||||||
|
bx = edge_padding
|
||||||
|
by = edge_padding
|
||||||
|
bw = width - 2 * edge_padding
|
||||||
|
bh = height - 2 * edge_padding
|
||||||
|
for i in range(border_width):
|
||||||
|
draw.rectangle([bx + i, by + i, bx + bw - 1 - i, by + bh - 1 - i], outline=0)
|
||||||
|
|
||||||
|
# Content area
|
||||||
|
content_x = edge_padding + border_width + inner_padding
|
||||||
|
content_y = edge_padding + border_width + inner_padding
|
||||||
|
content_w = width - 2 * content_x
|
||||||
|
content_h = height - 2 * content_y
|
||||||
|
|
||||||
|
# Zones
|
||||||
|
title_zone_h = content_h * 2 // 3
|
||||||
|
author_zone_h = content_h - title_zone_h
|
||||||
|
author_zone_y = content_y + title_zone_h
|
||||||
|
|
||||||
|
# Separator
|
||||||
|
sep_w = content_w // 3
|
||||||
|
sep_x = content_x + (content_w - sep_w) // 2
|
||||||
|
draw.line([sep_x, author_zone_y, sep_x + sep_w, author_zone_y], fill=0)
|
||||||
|
|
||||||
|
# Use a basic font for the preview (won't match exact Ubuntu metrics, but shows layout)
|
||||||
|
try:
|
||||||
|
title_font = ImageFont.truetype("/System/Library/Fonts/Helvetica.ttc", 12 * title_scale)
|
||||||
|
author_font = ImageFont.truetype("/System/Library/Fonts/Helvetica.ttc", 10 * author_scale)
|
||||||
|
except (OSError, IOError):
|
||||||
|
title_font = ImageFont.load_default()
|
||||||
|
author_font = ImageFont.load_default()
|
||||||
|
|
||||||
|
# Icon dimensions (needed for title text wrapping)
|
||||||
|
icon_w_px = 48 * icon_scale if icon_scale > 0 else 0
|
||||||
|
icon_h_px = 48 * icon_scale if icon_scale > 0 else 0
|
||||||
|
icon_gap = max(8, width // 40) if icon_scale > 0 else 0
|
||||||
|
title_text_w = content_w - icon_w_px - icon_gap # Title wraps in narrower area beside icon
|
||||||
|
|
||||||
|
# Wrap title (within the narrower area to the right of the icon)
|
||||||
|
title_lines = []
|
||||||
|
words = title.split()
|
||||||
|
current_line = ""
|
||||||
|
for word in words:
|
||||||
|
test = f"{current_line} {word}".strip()
|
||||||
|
bbox = draw.textbbox((0, 0), test, font=title_font)
|
||||||
|
if bbox[2] - bbox[0] <= title_text_w:
|
||||||
|
current_line = test
|
||||||
|
else:
|
||||||
|
if current_line:
|
||||||
|
title_lines.append(current_line)
|
||||||
|
current_line = word
|
||||||
|
if current_line:
|
||||||
|
title_lines.append(current_line)
|
||||||
|
title_lines = title_lines[:5]
|
||||||
|
|
||||||
|
# Line spacing: 75% of advanceY (tighter so 2-3 lines fit within icon height)
|
||||||
|
title_line_h = 29 * title_scale * 3 // 4 # Based on C++ ubuntu_12_bold advanceY
|
||||||
|
|
||||||
|
# Measure actual single-line height from the PIL font for accurate centering
|
||||||
|
sample_bbox = draw.textbbox((0, 0), "Ag", font=title_font) # Tall + descender chars
|
||||||
|
single_line_visual_h = sample_bbox[3] - sample_bbox[1]
|
||||||
|
|
||||||
|
# Visual height: line spacing between lines + actual height of last line's glyphs
|
||||||
|
num_title_lines = len(title_lines)
|
||||||
|
title_visual_h = (num_title_lines - 1) * title_line_h + single_line_visual_h if num_title_lines > 0 else 0
|
||||||
|
title_block_h = max(icon_h_px, title_visual_h)
|
||||||
|
|
||||||
|
title_start_y = content_y + (title_zone_h - title_block_h) // 2
|
||||||
|
if title_start_y < content_y:
|
||||||
|
title_start_y = content_y
|
||||||
|
|
||||||
|
# If title fits within icon height, center it vertically against the icon.
|
||||||
|
# Otherwise top-align so extra lines overflow below.
|
||||||
|
icon_y = title_start_y
|
||||||
|
if icon_h_px > 0 and title_visual_h <= icon_h_px:
|
||||||
|
title_text_y = title_start_y + (icon_h_px - title_visual_h) // 2
|
||||||
|
else:
|
||||||
|
title_text_y = title_start_y
|
||||||
|
|
||||||
|
# Horizontal centering: measure widest title line, center icon+gap+text block
|
||||||
|
max_title_line_w = 0
|
||||||
|
for line in title_lines:
|
||||||
|
bbox = draw.textbbox((0, 0), line, font=title_font)
|
||||||
|
w = bbox[2] - bbox[0]
|
||||||
|
if w > max_title_line_w:
|
||||||
|
max_title_line_w = w
|
||||||
|
title_block_w = icon_w_px + icon_gap + max_title_line_w
|
||||||
|
title_block_x = content_x + (content_w - title_block_w) // 2
|
||||||
|
|
||||||
|
# Draw icon
|
||||||
|
if icon_scale > 0:
|
||||||
|
icon_img = generate_book_icon(48)
|
||||||
|
scaled_icon = icon_img.resize((icon_w_px, icon_h_px), Image.NEAREST)
|
||||||
|
for iy in range(scaled_icon.height):
|
||||||
|
for ix in range(scaled_icon.width):
|
||||||
|
if not scaled_icon.getpixel((ix, iy)):
|
||||||
|
img.putpixel((title_block_x + ix, icon_y + iy), 0)
|
||||||
|
|
||||||
|
# Draw title (to the right of the icon)
|
||||||
|
title_text_x = title_block_x + icon_w_px + icon_gap
|
||||||
|
current_y = title_text_y
|
||||||
|
for line in title_lines:
|
||||||
|
draw.text((title_text_x, current_y), line, fill=0, font=title_font)
|
||||||
|
current_y += title_line_h
|
||||||
|
|
||||||
|
# Wrap author
|
||||||
|
author_lines = []
|
||||||
|
words = author.split()
|
||||||
|
current_line = ""
|
||||||
|
for word in words:
|
||||||
|
test = f"{current_line} {word}".strip()
|
||||||
|
bbox = draw.textbbox((0, 0), test, font=author_font)
|
||||||
|
if bbox[2] - bbox[0] <= content_w:
|
||||||
|
current_line = test
|
||||||
|
else:
|
||||||
|
if current_line:
|
||||||
|
author_lines.append(current_line)
|
||||||
|
current_line = word
|
||||||
|
if current_line:
|
||||||
|
author_lines.append(current_line)
|
||||||
|
author_lines = author_lines[:3]
|
||||||
|
|
||||||
|
# Draw author centered in bottom 1/3
|
||||||
|
author_line_h = 24 * author_scale # Ubuntu 10 regular advanceY ~24
|
||||||
|
author_block_h = len(author_lines) * author_line_h
|
||||||
|
author_start_y = author_zone_y + (author_zone_h - author_block_h) // 2
|
||||||
|
|
||||||
|
for line in author_lines:
|
||||||
|
bbox = draw.textbbox((0, 0), line, font=author_font)
|
||||||
|
line_w = bbox[2] - bbox[0]
|
||||||
|
line_x = content_x + (content_w - line_w) // 2
|
||||||
|
draw.text((line_x, author_start_y), line, fill=0, font=author_font)
|
||||||
|
author_start_y += author_line_h
|
||||||
|
|
||||||
|
return img
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
# Full cover
|
||||||
|
img = create_preview(480, 800, "A Really Long Book Title That Should Wrap", "Jane Doe")
|
||||||
|
img.save("mod/preview_cover_480x800.png")
|
||||||
|
print("Saved mod/preview_cover_480x800.png", file=sys.stderr)
|
||||||
|
|
||||||
|
# Medium thumbnail
|
||||||
|
img2 = create_preview(240, 400, "A Really Long Book Title That Should Wrap", "Jane Doe")
|
||||||
|
img2.save("mod/preview_thumb_240x400.png")
|
||||||
|
print("Saved mod/preview_thumb_240x400.png", file=sys.stderr)
|
||||||
|
|
||||||
|
# Small thumbnail
|
||||||
|
img3 = create_preview(136, 226, "A Really Long Book Title", "Jane Doe")
|
||||||
|
img3.save("mod/preview_thumb_136x226.png")
|
||||||
|
print("Saved mod/preview_thumb_136x226.png", file=sys.stderr)
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
#include "CrossPointSettings.h"
|
#include "CrossPointSettings.h"
|
||||||
|
|
||||||
#include <HardwareSerial.h>
|
#include <HalStorage.h>
|
||||||
#include <SDCardManager.h>
|
#include <Logging.h>
|
||||||
#include <Serialization.h>
|
#include <Serialization.h>
|
||||||
|
|
||||||
#include <cstring>
|
#include <cstring>
|
||||||
@@ -22,16 +22,67 @@ void readAndValidate(FsFile& file, uint8_t& member, const uint8_t maxValue) {
|
|||||||
namespace {
|
namespace {
|
||||||
constexpr uint8_t SETTINGS_FILE_VERSION = 1;
|
constexpr uint8_t SETTINGS_FILE_VERSION = 1;
|
||||||
// Increment this when adding new persisted settings fields
|
// Increment this when adding new persisted settings fields
|
||||||
constexpr uint8_t SETTINGS_COUNT = 23;
|
constexpr uint8_t SETTINGS_COUNT = 31;
|
||||||
constexpr char SETTINGS_FILE[] = "/.crosspoint/settings.bin";
|
constexpr char SETTINGS_FILE[] = "/.crosspoint/settings.bin";
|
||||||
|
|
||||||
|
// Validate front button mapping to ensure each hardware button is unique.
|
||||||
|
// If duplicates are detected, reset to the default physical order to prevent invalid mappings.
|
||||||
|
void validateFrontButtonMapping(CrossPointSettings& settings) {
|
||||||
|
// Snapshot the logical->hardware mapping so we can compare for duplicates.
|
||||||
|
const uint8_t mapping[] = {settings.frontButtonBack, settings.frontButtonConfirm, settings.frontButtonLeft,
|
||||||
|
settings.frontButtonRight};
|
||||||
|
for (size_t i = 0; i < 4; i++) {
|
||||||
|
for (size_t j = i + 1; j < 4; j++) {
|
||||||
|
if (mapping[i] == mapping[j]) {
|
||||||
|
// Duplicate detected: restore the default physical order (Back, Confirm, Left, Right).
|
||||||
|
settings.frontButtonBack = CrossPointSettings::FRONT_HW_BACK;
|
||||||
|
settings.frontButtonConfirm = CrossPointSettings::FRONT_HW_CONFIRM;
|
||||||
|
settings.frontButtonLeft = CrossPointSettings::FRONT_HW_LEFT;
|
||||||
|
settings.frontButtonRight = CrossPointSettings::FRONT_HW_RIGHT;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Convert legacy front button layout into explicit logical->hardware mapping.
|
||||||
|
void applyLegacyFrontButtonLayout(CrossPointSettings& settings) {
|
||||||
|
switch (static_cast<CrossPointSettings::FRONT_BUTTON_LAYOUT>(settings.frontButtonLayout)) {
|
||||||
|
case CrossPointSettings::LEFT_RIGHT_BACK_CONFIRM:
|
||||||
|
settings.frontButtonBack = CrossPointSettings::FRONT_HW_LEFT;
|
||||||
|
settings.frontButtonConfirm = CrossPointSettings::FRONT_HW_RIGHT;
|
||||||
|
settings.frontButtonLeft = CrossPointSettings::FRONT_HW_BACK;
|
||||||
|
settings.frontButtonRight = CrossPointSettings::FRONT_HW_CONFIRM;
|
||||||
|
break;
|
||||||
|
case CrossPointSettings::LEFT_BACK_CONFIRM_RIGHT:
|
||||||
|
settings.frontButtonBack = CrossPointSettings::FRONT_HW_CONFIRM;
|
||||||
|
settings.frontButtonConfirm = CrossPointSettings::FRONT_HW_LEFT;
|
||||||
|
settings.frontButtonLeft = CrossPointSettings::FRONT_HW_BACK;
|
||||||
|
settings.frontButtonRight = CrossPointSettings::FRONT_HW_RIGHT;
|
||||||
|
break;
|
||||||
|
case CrossPointSettings::BACK_CONFIRM_RIGHT_LEFT:
|
||||||
|
settings.frontButtonBack = CrossPointSettings::FRONT_HW_BACK;
|
||||||
|
settings.frontButtonConfirm = CrossPointSettings::FRONT_HW_CONFIRM;
|
||||||
|
settings.frontButtonLeft = CrossPointSettings::FRONT_HW_RIGHT;
|
||||||
|
settings.frontButtonRight = CrossPointSettings::FRONT_HW_LEFT;
|
||||||
|
break;
|
||||||
|
case CrossPointSettings::BACK_CONFIRM_LEFT_RIGHT:
|
||||||
|
default:
|
||||||
|
settings.frontButtonBack = CrossPointSettings::FRONT_HW_BACK;
|
||||||
|
settings.frontButtonConfirm = CrossPointSettings::FRONT_HW_CONFIRM;
|
||||||
|
settings.frontButtonLeft = CrossPointSettings::FRONT_HW_LEFT;
|
||||||
|
settings.frontButtonRight = CrossPointSettings::FRONT_HW_RIGHT;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
} // namespace
|
} // namespace
|
||||||
|
|
||||||
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;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -42,7 +93,7 @@ bool CrossPointSettings::saveToFile() const {
|
|||||||
serialization::writePod(outputFile, shortPwrBtn);
|
serialization::writePod(outputFile, shortPwrBtn);
|
||||||
serialization::writePod(outputFile, statusBar);
|
serialization::writePod(outputFile, statusBar);
|
||||||
serialization::writePod(outputFile, orientation);
|
serialization::writePod(outputFile, orientation);
|
||||||
serialization::writePod(outputFile, frontButtonLayout);
|
serialization::writePod(outputFile, frontButtonLayout); // legacy
|
||||||
serialization::writePod(outputFile, sideButtonLayout);
|
serialization::writePod(outputFile, sideButtonLayout);
|
||||||
serialization::writePod(outputFile, fontFamily);
|
serialization::writePod(outputFile, fontFamily);
|
||||||
serialization::writePod(outputFile, fontSize);
|
serialization::writePod(outputFile, fontSize);
|
||||||
@@ -60,23 +111,31 @@ bool CrossPointSettings::saveToFile() const {
|
|||||||
serialization::writeString(outputFile, std::string(opdsUsername));
|
serialization::writeString(outputFile, std::string(opdsUsername));
|
||||||
serialization::writeString(outputFile, std::string(opdsPassword));
|
serialization::writeString(outputFile, std::string(opdsPassword));
|
||||||
serialization::writePod(outputFile, sleepScreenCoverFilter);
|
serialization::writePod(outputFile, sleepScreenCoverFilter);
|
||||||
|
serialization::writePod(outputFile, uiTheme);
|
||||||
|
serialization::writePod(outputFile, frontButtonBack);
|
||||||
|
serialization::writePod(outputFile, frontButtonConfirm);
|
||||||
|
serialization::writePod(outputFile, frontButtonLeft);
|
||||||
|
serialization::writePod(outputFile, frontButtonRight);
|
||||||
|
serialization::writePod(outputFile, fadingFix);
|
||||||
|
serialization::writePod(outputFile, embeddedStyle);
|
||||||
|
serialization::writePod(outputFile, sleepScreenLetterboxFill);
|
||||||
// New fields added at end for backward compatibility
|
// New fields added at end for backward compatibility
|
||||||
outputFile.close();
|
outputFile.close();
|
||||||
|
|
||||||
Serial.printf("[%lu] [CPS] Settings saved to file\n", millis());
|
LOG_DBG("CPS", "Settings saved to file");
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
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;
|
||||||
}
|
}
|
||||||
|
|
||||||
uint8_t version;
|
uint8_t version;
|
||||||
serialization::readPod(inputFile, version);
|
serialization::readPod(inputFile, version);
|
||||||
if (version != SETTINGS_FILE_VERSION) {
|
if (version != SETTINGS_FILE_VERSION) {
|
||||||
Serial.printf("[%lu] [CPS] Deserialization failed: Unknown version %u\n", millis(), version);
|
LOG_ERR("CPS", "Deserialization failed: Unknown version %u", version);
|
||||||
inputFile.close();
|
inputFile.close();
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@@ -86,6 +145,8 @@ bool CrossPointSettings::loadFromFile() {
|
|||||||
|
|
||||||
// load settings that exist (support older files with fewer fields)
|
// load settings that exist (support older files with fewer fields)
|
||||||
uint8_t settingsRead = 0;
|
uint8_t settingsRead = 0;
|
||||||
|
// Track whether remap fields were present in the settings file.
|
||||||
|
bool frontButtonMappingRead = false;
|
||||||
do {
|
do {
|
||||||
readAndValidate(inputFile, sleepScreen, SLEEP_SCREEN_MODE_COUNT);
|
readAndValidate(inputFile, sleepScreen, SLEEP_SCREEN_MODE_COUNT);
|
||||||
if (++settingsRead >= fileSettingsCount) break;
|
if (++settingsRead >= fileSettingsCount) break;
|
||||||
@@ -97,7 +158,7 @@ bool CrossPointSettings::loadFromFile() {
|
|||||||
if (++settingsRead >= fileSettingsCount) break;
|
if (++settingsRead >= fileSettingsCount) break;
|
||||||
readAndValidate(inputFile, orientation, ORIENTATION_COUNT);
|
readAndValidate(inputFile, orientation, ORIENTATION_COUNT);
|
||||||
if (++settingsRead >= fileSettingsCount) break;
|
if (++settingsRead >= fileSettingsCount) break;
|
||||||
readAndValidate(inputFile, frontButtonLayout, FRONT_BUTTON_LAYOUT_COUNT);
|
readAndValidate(inputFile, frontButtonLayout, FRONT_BUTTON_LAYOUT_COUNT); // legacy
|
||||||
if (++settingsRead >= fileSettingsCount) break;
|
if (++settingsRead >= fileSettingsCount) break;
|
||||||
readAndValidate(inputFile, sideButtonLayout, SIDE_BUTTON_LAYOUT_COUNT);
|
readAndValidate(inputFile, sideButtonLayout, SIDE_BUTTON_LAYOUT_COUNT);
|
||||||
if (++settingsRead >= fileSettingsCount) break;
|
if (++settingsRead >= fileSettingsCount) break;
|
||||||
@@ -148,18 +209,43 @@ bool CrossPointSettings::loadFromFile() {
|
|||||||
if (++settingsRead >= fileSettingsCount) break;
|
if (++settingsRead >= fileSettingsCount) break;
|
||||||
readAndValidate(inputFile, sleepScreenCoverFilter, SLEEP_SCREEN_COVER_FILTER_COUNT);
|
readAndValidate(inputFile, sleepScreenCoverFilter, SLEEP_SCREEN_COVER_FILTER_COUNT);
|
||||||
if (++settingsRead >= fileSettingsCount) break;
|
if (++settingsRead >= fileSettingsCount) break;
|
||||||
|
serialization::readPod(inputFile, uiTheme);
|
||||||
|
if (++settingsRead >= fileSettingsCount) break;
|
||||||
|
readAndValidate(inputFile, frontButtonBack, FRONT_BUTTON_HARDWARE_COUNT);
|
||||||
|
if (++settingsRead >= fileSettingsCount) break;
|
||||||
|
readAndValidate(inputFile, frontButtonConfirm, FRONT_BUTTON_HARDWARE_COUNT);
|
||||||
|
if (++settingsRead >= fileSettingsCount) break;
|
||||||
|
readAndValidate(inputFile, frontButtonLeft, FRONT_BUTTON_HARDWARE_COUNT);
|
||||||
|
if (++settingsRead >= fileSettingsCount) break;
|
||||||
|
readAndValidate(inputFile, frontButtonRight, FRONT_BUTTON_HARDWARE_COUNT);
|
||||||
|
frontButtonMappingRead = true;
|
||||||
|
if (++settingsRead >= fileSettingsCount) break;
|
||||||
|
serialization::readPod(inputFile, fadingFix);
|
||||||
|
if (++settingsRead >= fileSettingsCount) break;
|
||||||
|
serialization::readPod(inputFile, embeddedStyle);
|
||||||
|
if (++settingsRead >= fileSettingsCount) break;
|
||||||
|
readAndValidate(inputFile, sleepScreenLetterboxFill, SLEEP_SCREEN_LETTERBOX_FILL_COUNT);
|
||||||
|
if (++settingsRead >= fileSettingsCount) break;
|
||||||
|
{ uint8_t _ignore; serialization::readPod(inputFile, _ignore); } // legacy: sleepScreenGradientDir
|
||||||
|
if (++settingsRead >= fileSettingsCount) break;
|
||||||
// New fields added at end for backward compatibility
|
// New fields added at end for backward compatibility
|
||||||
} while (false);
|
} while (false);
|
||||||
|
|
||||||
|
if (frontButtonMappingRead) {
|
||||||
|
validateFrontButtonMapping(*this);
|
||||||
|
} else {
|
||||||
|
applyLegacyFrontButtonLayout(*this);
|
||||||
|
}
|
||||||
|
|
||||||
inputFile.close();
|
inputFile.close();
|
||||||
Serial.printf("[%lu] [CPS] Settings loaded from file\n", millis());
|
LOG_DBG("CPS", "Settings loaded from file");
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
float CrossPointSettings::getReaderLineCompression() const {
|
float CrossPointSettings::getReaderLineCompression() const {
|
||||||
switch (fontFamily) {
|
switch (fontFamily) {
|
||||||
|
#ifndef OMIT_BOOKERLY
|
||||||
case BOOKERLY:
|
case BOOKERLY:
|
||||||
default:
|
|
||||||
switch (lineSpacing) {
|
switch (lineSpacing) {
|
||||||
case TIGHT:
|
case TIGHT:
|
||||||
return 0.95f;
|
return 0.95f;
|
||||||
@@ -169,6 +255,8 @@ float CrossPointSettings::getReaderLineCompression() const {
|
|||||||
case WIDE:
|
case WIDE:
|
||||||
return 1.1f;
|
return 1.1f;
|
||||||
}
|
}
|
||||||
|
#endif // OMIT_BOOKERLY
|
||||||
|
#ifndef OMIT_NOTOSANS
|
||||||
case NOTOSANS:
|
case NOTOSANS:
|
||||||
switch (lineSpacing) {
|
switch (lineSpacing) {
|
||||||
case TIGHT:
|
case TIGHT:
|
||||||
@@ -179,6 +267,8 @@ float CrossPointSettings::getReaderLineCompression() const {
|
|||||||
case WIDE:
|
case WIDE:
|
||||||
return 1.0f;
|
return 1.0f;
|
||||||
}
|
}
|
||||||
|
#endif // OMIT_NOTOSANS
|
||||||
|
#ifndef OMIT_OPENDYSLEXIC
|
||||||
case OPENDYSLEXIC:
|
case OPENDYSLEXIC:
|
||||||
switch (lineSpacing) {
|
switch (lineSpacing) {
|
||||||
case TIGHT:
|
case TIGHT:
|
||||||
@@ -189,6 +279,30 @@ float CrossPointSettings::getReaderLineCompression() const {
|
|||||||
case WIDE:
|
case WIDE:
|
||||||
return 1.0f;
|
return 1.0f;
|
||||||
}
|
}
|
||||||
|
#endif // OMIT_OPENDYSLEXIC
|
||||||
|
default:
|
||||||
|
// Fallback: use Bookerly-style compression, or Noto Sans if Bookerly is omitted
|
||||||
|
#if !defined(OMIT_BOOKERLY)
|
||||||
|
switch (lineSpacing) {
|
||||||
|
case TIGHT:
|
||||||
|
return 0.95f;
|
||||||
|
case NORMAL:
|
||||||
|
default:
|
||||||
|
return 1.0f;
|
||||||
|
case WIDE:
|
||||||
|
return 1.1f;
|
||||||
|
}
|
||||||
|
#else
|
||||||
|
switch (lineSpacing) {
|
||||||
|
case TIGHT:
|
||||||
|
return 0.90f;
|
||||||
|
case NORMAL:
|
||||||
|
default:
|
||||||
|
return 0.95f;
|
||||||
|
case WIDE:
|
||||||
|
return 1.0f;
|
||||||
|
}
|
||||||
|
#endif
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -226,8 +340,8 @@ int CrossPointSettings::getRefreshFrequency() const {
|
|||||||
|
|
||||||
int CrossPointSettings::getReaderFontId() const {
|
int CrossPointSettings::getReaderFontId() const {
|
||||||
switch (fontFamily) {
|
switch (fontFamily) {
|
||||||
|
#ifndef OMIT_BOOKERLY
|
||||||
case BOOKERLY:
|
case BOOKERLY:
|
||||||
default:
|
|
||||||
switch (fontSize) {
|
switch (fontSize) {
|
||||||
case SMALL:
|
case SMALL:
|
||||||
return BOOKERLY_12_FONT_ID;
|
return BOOKERLY_12_FONT_ID;
|
||||||
@@ -239,6 +353,8 @@ int CrossPointSettings::getReaderFontId() const {
|
|||||||
case EXTRA_LARGE:
|
case EXTRA_LARGE:
|
||||||
return BOOKERLY_18_FONT_ID;
|
return BOOKERLY_18_FONT_ID;
|
||||||
}
|
}
|
||||||
|
#endif // OMIT_BOOKERLY
|
||||||
|
#ifndef OMIT_NOTOSANS
|
||||||
case NOTOSANS:
|
case NOTOSANS:
|
||||||
switch (fontSize) {
|
switch (fontSize) {
|
||||||
case SMALL:
|
case SMALL:
|
||||||
@@ -251,6 +367,8 @@ int CrossPointSettings::getReaderFontId() const {
|
|||||||
case EXTRA_LARGE:
|
case EXTRA_LARGE:
|
||||||
return NOTOSANS_18_FONT_ID;
|
return NOTOSANS_18_FONT_ID;
|
||||||
}
|
}
|
||||||
|
#endif // OMIT_NOTOSANS
|
||||||
|
#ifndef OMIT_OPENDYSLEXIC
|
||||||
case OPENDYSLEXIC:
|
case OPENDYSLEXIC:
|
||||||
switch (fontSize) {
|
switch (fontSize) {
|
||||||
case SMALL:
|
case SMALL:
|
||||||
@@ -263,5 +381,17 @@ int CrossPointSettings::getReaderFontId() const {
|
|||||||
case EXTRA_LARGE:
|
case EXTRA_LARGE:
|
||||||
return OPENDYSLEXIC_14_FONT_ID;
|
return OPENDYSLEXIC_14_FONT_ID;
|
||||||
}
|
}
|
||||||
|
#endif // OMIT_OPENDYSLEXIC
|
||||||
|
default:
|
||||||
|
// Fallback to first available font family at medium size
|
||||||
|
#if !defined(OMIT_BOOKERLY)
|
||||||
|
return BOOKERLY_14_FONT_ID;
|
||||||
|
#elif !defined(OMIT_NOTOSANS)
|
||||||
|
return NOTOSANS_14_FONT_ID;
|
||||||
|
#elif !defined(OMIT_OPENDYSLEXIC)
|
||||||
|
return OPENDYSLEXIC_10_FONT_ID;
|
||||||
|
#else
|
||||||
|
#error "At least one font family must be available"
|
||||||
|
#endif
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -15,7 +15,15 @@ class CrossPointSettings {
|
|||||||
CrossPointSettings(const CrossPointSettings&) = delete;
|
CrossPointSettings(const CrossPointSettings&) = delete;
|
||||||
CrossPointSettings& operator=(const CrossPointSettings&) = delete;
|
CrossPointSettings& operator=(const CrossPointSettings&) = delete;
|
||||||
|
|
||||||
enum SLEEP_SCREEN_MODE { DARK = 0, LIGHT = 1, CUSTOM = 2, COVER = 3, BLANK = 4, SLEEP_SCREEN_MODE_COUNT };
|
enum SLEEP_SCREEN_MODE {
|
||||||
|
DARK = 0,
|
||||||
|
LIGHT = 1,
|
||||||
|
CUSTOM = 2,
|
||||||
|
COVER = 3,
|
||||||
|
BLANK = 4,
|
||||||
|
COVER_CUSTOM = 5,
|
||||||
|
SLEEP_SCREEN_MODE_COUNT
|
||||||
|
};
|
||||||
enum SLEEP_SCREEN_COVER_MODE { FIT = 0, CROP = 1, SLEEP_SCREEN_COVER_MODE_COUNT };
|
enum SLEEP_SCREEN_COVER_MODE { FIT = 0, CROP = 1, SLEEP_SCREEN_COVER_MODE_COUNT };
|
||||||
enum SLEEP_SCREEN_COVER_FILTER {
|
enum SLEEP_SCREEN_COVER_FILTER {
|
||||||
NO_FILTER = 0,
|
NO_FILTER = 0,
|
||||||
@@ -23,14 +31,21 @@ class CrossPointSettings {
|
|||||||
INVERTED_BLACK_AND_WHITE = 2,
|
INVERTED_BLACK_AND_WHITE = 2,
|
||||||
SLEEP_SCREEN_COVER_FILTER_COUNT
|
SLEEP_SCREEN_COVER_FILTER_COUNT
|
||||||
};
|
};
|
||||||
|
enum SLEEP_SCREEN_LETTERBOX_FILL {
|
||||||
|
LETTERBOX_DITHERED = 0,
|
||||||
|
LETTERBOX_SOLID = 1,
|
||||||
|
LETTERBOX_NONE = 2,
|
||||||
|
SLEEP_SCREEN_LETTERBOX_FILL_COUNT
|
||||||
|
};
|
||||||
|
|
||||||
// Status bar display type enum
|
// Status bar display type enum
|
||||||
enum STATUS_BAR_MODE {
|
enum STATUS_BAR_MODE {
|
||||||
NONE = 0,
|
NONE = 0,
|
||||||
NO_PROGRESS = 1,
|
NO_PROGRESS = 1,
|
||||||
FULL = 2,
|
FULL = 2,
|
||||||
FULL_WITH_PROGRESS_BAR = 3,
|
BOOK_PROGRESS_BAR = 3,
|
||||||
ONLY_PROGRESS_BAR = 4,
|
ONLY_BOOK_PROGRESS_BAR = 4,
|
||||||
|
CHAPTER_PROGRESS_BAR = 5,
|
||||||
STATUS_BAR_MODE_COUNT
|
STATUS_BAR_MODE_COUNT
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -42,7 +57,7 @@ class CrossPointSettings {
|
|||||||
ORIENTATION_COUNT
|
ORIENTATION_COUNT
|
||||||
};
|
};
|
||||||
|
|
||||||
// Front button layout options
|
// Front button layout options (legacy)
|
||||||
// Default: Back, Confirm, Left, Right
|
// Default: Back, Confirm, Left, Right
|
||||||
// Swapped: Left, Right, Back, Confirm
|
// Swapped: Left, Right, Back, Confirm
|
||||||
enum FRONT_BUTTON_LAYOUT {
|
enum FRONT_BUTTON_LAYOUT {
|
||||||
@@ -53,6 +68,15 @@ class CrossPointSettings {
|
|||||||
FRONT_BUTTON_LAYOUT_COUNT
|
FRONT_BUTTON_LAYOUT_COUNT
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Front button hardware identifiers (for remapping)
|
||||||
|
enum FRONT_BUTTON_HARDWARE {
|
||||||
|
FRONT_HW_BACK = 0,
|
||||||
|
FRONT_HW_CONFIRM = 1,
|
||||||
|
FRONT_HW_LEFT = 2,
|
||||||
|
FRONT_HW_RIGHT = 3,
|
||||||
|
FRONT_BUTTON_HARDWARE_COUNT
|
||||||
|
};
|
||||||
|
|
||||||
// Side button layout options
|
// Side button layout options
|
||||||
// Default: Previous, Next
|
// Default: Previous, Next
|
||||||
// Swapped: Next, Previous
|
// Swapped: Next, Previous
|
||||||
@@ -68,6 +92,7 @@ class CrossPointSettings {
|
|||||||
LEFT_ALIGN = 1,
|
LEFT_ALIGN = 1,
|
||||||
CENTER_ALIGN = 2,
|
CENTER_ALIGN = 2,
|
||||||
RIGHT_ALIGN = 3,
|
RIGHT_ALIGN = 3,
|
||||||
|
BOOK_STYLE = 4,
|
||||||
PARAGRAPH_ALIGNMENT_COUNT
|
PARAGRAPH_ALIGNMENT_COUNT
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -97,12 +122,17 @@ class CrossPointSettings {
|
|||||||
// Hide battery percentage
|
// Hide battery percentage
|
||||||
enum HIDE_BATTERY_PERCENTAGE { HIDE_NEVER = 0, HIDE_READER = 1, HIDE_ALWAYS = 2, HIDE_BATTERY_PERCENTAGE_COUNT };
|
enum HIDE_BATTERY_PERCENTAGE { HIDE_NEVER = 0, HIDE_READER = 1, HIDE_ALWAYS = 2, HIDE_BATTERY_PERCENTAGE_COUNT };
|
||||||
|
|
||||||
|
// UI Theme
|
||||||
|
enum UI_THEME { CLASSIC = 0, LYRA = 1 };
|
||||||
|
|
||||||
// Sleep screen settings
|
// Sleep screen settings
|
||||||
uint8_t sleepScreen = DARK;
|
uint8_t sleepScreen = DARK;
|
||||||
// Sleep screen cover mode settings
|
// Sleep screen cover mode settings
|
||||||
uint8_t sleepScreenCoverMode = FIT;
|
uint8_t sleepScreenCoverMode = FIT;
|
||||||
// Sleep screen cover filter
|
// Sleep screen cover filter
|
||||||
uint8_t sleepScreenCoverFilter = NO_FILTER;
|
uint8_t sleepScreenCoverFilter = NO_FILTER;
|
||||||
|
// Sleep screen letterbox fill mode (Dithered / Solid / None)
|
||||||
|
uint8_t sleepScreenLetterboxFill = LETTERBOX_DITHERED;
|
||||||
// Status bar settings
|
// Status bar settings
|
||||||
uint8_t statusBar = FULL;
|
uint8_t statusBar = FULL;
|
||||||
// Text rendering settings
|
// Text rendering settings
|
||||||
@@ -113,9 +143,15 @@ class CrossPointSettings {
|
|||||||
// EPUB reading orientation settings
|
// EPUB reading orientation settings
|
||||||
// 0 = portrait (default), 1 = landscape clockwise, 2 = inverted, 3 = landscape counter-clockwise
|
// 0 = portrait (default), 1 = landscape clockwise, 2 = inverted, 3 = landscape counter-clockwise
|
||||||
uint8_t orientation = PORTRAIT;
|
uint8_t orientation = PORTRAIT;
|
||||||
// Button layouts
|
// Button layouts (front layout retained for migration only)
|
||||||
uint8_t frontButtonLayout = BACK_CONFIRM_LEFT_RIGHT;
|
uint8_t frontButtonLayout = BACK_CONFIRM_LEFT_RIGHT;
|
||||||
uint8_t sideButtonLayout = PREV_NEXT;
|
uint8_t sideButtonLayout = PREV_NEXT;
|
||||||
|
// Front button remap (logical -> hardware)
|
||||||
|
// Used by MappedInputManager to translate logical buttons into physical front buttons.
|
||||||
|
uint8_t frontButtonBack = FRONT_HW_BACK;
|
||||||
|
uint8_t frontButtonConfirm = FRONT_HW_CONFIRM;
|
||||||
|
uint8_t frontButtonLeft = FRONT_HW_LEFT;
|
||||||
|
uint8_t frontButtonRight = FRONT_HW_RIGHT;
|
||||||
// Reader font settings
|
// Reader font settings
|
||||||
uint8_t fontFamily = BOOKERLY;
|
uint8_t fontFamily = BOOKERLY;
|
||||||
uint8_t fontSize = MEDIUM;
|
uint8_t fontSize = MEDIUM;
|
||||||
@@ -137,6 +173,12 @@ class CrossPointSettings {
|
|||||||
uint8_t hideBatteryPercentage = HIDE_NEVER;
|
uint8_t hideBatteryPercentage = HIDE_NEVER;
|
||||||
// Long-press chapter skip on side buttons
|
// Long-press chapter skip on side buttons
|
||||||
uint8_t longPressChapterSkip = 1;
|
uint8_t longPressChapterSkip = 1;
|
||||||
|
// UI Theme
|
||||||
|
uint8_t uiTheme = LYRA;
|
||||||
|
// Sunlight fading compensation
|
||||||
|
uint8_t fadingFix = 0;
|
||||||
|
// Use book's embedded CSS styles for EPUB rendering (1 = enabled, 0 = disabled)
|
||||||
|
uint8_t embeddedStyle = 1;
|
||||||
|
|
||||||
~CrossPointSettings() = default;
|
~CrossPointSettings() = default;
|
||||||
|
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
#include "CrossPointState.h"
|
#include "CrossPointState.h"
|
||||||
|
|
||||||
#include <HardwareSerial.h>
|
#include <HalStorage.h>
|
||||||
#include <SDCardManager.h>
|
#include <Logging.h>
|
||||||
#include <Serialization.h>
|
#include <Serialization.h>
|
||||||
|
|
||||||
namespace {
|
namespace {
|
||||||
constexpr uint8_t STATE_FILE_VERSION = 2;
|
constexpr uint8_t STATE_FILE_VERSION = 4;
|
||||||
constexpr char STATE_FILE[] = "/.crosspoint/state.bin";
|
constexpr char STATE_FILE[] = "/.crosspoint/state.bin";
|
||||||
} // namespace
|
} // namespace
|
||||||
|
|
||||||
@@ -13,27 +13,29 @@ 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;
|
||||||
}
|
}
|
||||||
|
|
||||||
serialization::writePod(outputFile, STATE_FILE_VERSION);
|
serialization::writePod(outputFile, STATE_FILE_VERSION);
|
||||||
serialization::writeString(outputFile, openEpubPath);
|
serialization::writeString(outputFile, openEpubPath);
|
||||||
serialization::writePod(outputFile, lastSleepImage);
|
serialization::writePod(outputFile, lastSleepImage);
|
||||||
|
serialization::writePod(outputFile, readerActivityLoadCount);
|
||||||
|
serialization::writePod(outputFile, lastSleepFromReader);
|
||||||
outputFile.close();
|
outputFile.close();
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
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;
|
||||||
}
|
}
|
||||||
|
|
||||||
uint8_t version;
|
uint8_t version;
|
||||||
serialization::readPod(inputFile, version);
|
serialization::readPod(inputFile, version);
|
||||||
if (version > STATE_FILE_VERSION) {
|
if (version > STATE_FILE_VERSION) {
|
||||||
Serial.printf("[%lu] [CPS] Deserialization failed: Unknown version %u\n", millis(), version);
|
LOG_ERR("CPS", "Deserialization failed: Unknown version %u", version);
|
||||||
inputFile.close();
|
inputFile.close();
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@@ -45,6 +47,16 @@ bool CrossPointState::loadFromFile() {
|
|||||||
lastSleepImage = 0;
|
lastSleepImage = 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (version >= 3) {
|
||||||
|
serialization::readPod(inputFile, readerActivityLoadCount);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (version >= 4) {
|
||||||
|
serialization::readPod(inputFile, lastSleepFromReader);
|
||||||
|
} else {
|
||||||
|
lastSleepFromReader = false;
|
||||||
|
}
|
||||||
|
|
||||||
inputFile.close();
|
inputFile.close();
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user