Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b1763821b5 | ||
|
|
c0b83b626e | ||
|
|
f8c0b1acea | ||
|
|
f9b604f04e | ||
|
|
3dc5f6fec4 | ||
|
|
41c93e4eba | ||
|
|
1c33162368 | ||
|
|
27d42fbef3 | ||
|
|
dd280bdc97 | ||
|
|
bf031fd999 | ||
|
|
02350c6a9f | ||
|
|
9023b262a1 | ||
|
|
eabd149371 | ||
|
|
838246d147 | ||
|
|
f96b6ab29c | ||
|
|
e3d0201365 | ||
|
|
286b47f489 | ||
|
|
aff4dc6628 | ||
|
|
98a39374e8 | ||
|
|
e8c0fb42d4 | ||
|
|
b77af16caa | ||
|
|
e3c1e28b8f | ||
|
|
dc7544d944 | ||
|
|
504c7b307d | ||
|
|
b6bc1f7ed3 | ||
|
|
ea0abaf351 | ||
|
|
2771579007 | ||
|
|
27035b2b91 | ||
|
|
1107590b56 | ||
|
|
66ddb52103 | ||
|
|
9f4f71fabe | ||
|
|
d23020e268 | ||
|
|
f4491875ab | ||
|
|
6fe28da41b | ||
|
|
689b539c6b | ||
|
|
ce37c80c2d | ||
|
|
b39ce22e54 | ||
|
|
77c655fcf5 | ||
|
|
246afae6ef | ||
|
|
fcfa10bb1f | ||
|
|
febf79a98a | ||
|
|
424104f8ff | ||
|
|
955c78de64 | ||
|
|
958508eb6b | ||
|
|
6aa5d41a42 | ||
|
|
2a27c6d068 | ||
|
|
b73ae7fe74 | ||
|
|
f264efdb12 | ||
|
|
0d32d21d75 | ||
|
|
9b4dfbd180 | ||
|
|
926c786705 | ||
|
|
299623927e | ||
|
|
9a3bb81337 | ||
|
|
73d1839ddd | ||
|
|
cc86533e86 | ||
|
|
bf3f270067 | ||
|
|
cfe838e03b | ||
|
|
7484fe478c | ||
|
|
d41d539435 | ||
|
|
cf6fec78dc | ||
|
|
10d76dde12 | ||
|
|
7b5a63d220 | ||
|
|
c1d5f5d562 | ||
|
|
adfeee063f | ||
|
|
2d3928ed81 | ||
|
|
48249fbd1e | ||
|
|
1a53dccebd | ||
|
|
3e28724b62 | ||
|
|
d86b3fe134 | ||
|
|
1a3d6b125d | ||
|
|
b2020f5512 | ||
|
|
70dc0f018e | ||
|
|
424594488f | ||
|
|
57fdb1c0fb | ||
|
|
5e1694748c | ||
|
|
063a1df851 | ||
|
|
d429966dd4 | ||
|
|
c78f2a9840 | ||
|
|
11f01d3a41 | ||
|
|
973d372521 | ||
|
|
67da8139b3 | ||
|
|
c287aa03a4 | ||
|
|
5d68c8b305 | ||
|
|
def7abbd60 | ||
|
|
9ad8111ce7 | ||
|
|
57d1939be7 | ||
|
|
012992f904 | ||
|
|
c262f222de | ||
|
|
449b3ca161 | ||
|
|
6989035ef8 | ||
|
|
108cf57202 | ||
|
|
a640fbecf8 | ||
|
|
7a5719b46d | ||
|
|
8c3576e397 | ||
|
|
fdb5634ea6 | ||
|
|
5cabba7712 | ||
|
|
a86d405fb0 | ||
|
|
e4b5dc0e6a | ||
|
|
dfc74f94c2 | ||
|
|
3518cbb56d | ||
|
|
8994953254 | ||
|
|
ead39fd04b | ||
|
|
5a7381a0eb | ||
|
|
f69fc90b5c | ||
|
|
5bae283838 | ||
|
|
c7a32fe41f | ||
|
|
d450f362d1 | ||
|
|
6ddcf9b592 | ||
|
|
492c6fd23e | ||
|
|
7c852cf7d1 | ||
|
|
69f357998e | ||
|
|
09f68a3d03 | ||
|
|
7ec7efcb47 | ||
|
|
45af2d0e81 | ||
|
|
0926e9e6e4 | ||
|
|
02b157c02b | ||
|
|
07cc589e59 | ||
|
|
b743a1ca8e | ||
|
|
2ed8017aa2 |
@@ -0,0 +1,2 @@
|
|||||||
|
github: [daveallie]
|
||||||
|
ko_fi: daveallie
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
name: Bug Report
|
||||||
|
description: Report an issue or unexpected behavior
|
||||||
|
title: "Short, descriptive title of the issue"
|
||||||
|
labels: ["bug", "triage"]
|
||||||
|
body:
|
||||||
|
- type: markdown
|
||||||
|
attributes:
|
||||||
|
value: |
|
||||||
|
Thanks for taking the time to report this bug! Please fill out the details below.
|
||||||
|
|
||||||
|
- type: input
|
||||||
|
id: version
|
||||||
|
attributes:
|
||||||
|
label: Affected Version
|
||||||
|
description: What version of the project/library are you using? (e.g., v1.2.3, master branch commit SHA)
|
||||||
|
placeholder: Ex. v1.2.3
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
|
||||||
|
- type: textarea
|
||||||
|
id: bug-description
|
||||||
|
attributes:
|
||||||
|
label: Describe the Bug
|
||||||
|
description: A clear and concise description of what the bug is.
|
||||||
|
placeholder:
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
|
||||||
|
- type: textarea
|
||||||
|
id: steps-to-reproduce
|
||||||
|
attributes:
|
||||||
|
label: Steps to Reproduce
|
||||||
|
description: Clearly list the steps necessary to reproduce the unexpected behavior.
|
||||||
|
placeholder: |
|
||||||
|
1. Go to '...'
|
||||||
|
2. Select '...'
|
||||||
|
3. Crash
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
|
||||||
|
- type: textarea
|
||||||
|
id: expected-behavior
|
||||||
|
attributes:
|
||||||
|
label: Expected Behavior
|
||||||
|
description: A clear and concise description of what you expected to happen.
|
||||||
|
validations:
|
||||||
|
required: true
|
||||||
|
|
||||||
|
- type: textarea
|
||||||
|
id: logs
|
||||||
|
attributes:
|
||||||
|
label: Relevant Log Output/Screenshots
|
||||||
|
description: If applicable, error messages, or log output to help explain your problem. You can drag and drop images here.
|
||||||
|
render: shell
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
## Summary
|
||||||
|
|
||||||
|
* **What is the goal of this PR?** (e.g., Fixes a bug in the user authentication module, Implements the new feature for
|
||||||
|
file uploading.)
|
||||||
|
* **What changes are included?**
|
||||||
|
|
||||||
|
## Additional Context
|
||||||
|
|
||||||
|
* Add any other information that might be helpful for the reviewer (e.g., performance implications, potential risks, specific areas to focus on).
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
name: CI
|
||||||
|
'on':
|
||||||
|
push:
|
||||||
|
branches: [master]
|
||||||
|
pull_request:
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build:
|
||||||
|
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: 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
|
||||||
|
run: pio run
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
name: Compile Release
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
tags:
|
||||||
|
- '*'
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build-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: Build CrossPoint
|
||||||
|
run: pio run -e gh_release
|
||||||
|
|
||||||
|
- name: Upload Artifacts
|
||||||
|
uses: actions/upload-artifact@v4
|
||||||
|
with:
|
||||||
|
name: CrossPoint-${{ github.ref_name }}
|
||||||
|
path: |
|
||||||
|
.pio/build/gh_release/bootloader.bin
|
||||||
|
.pio/build/gh_release/firmware.bin
|
||||||
|
.pio/build/gh_release/firmware.elf
|
||||||
|
.pio/build/gh_release/firmware.map
|
||||||
|
.pio/build/gh_release/partitions.bin
|
||||||
@@ -1,3 +1,6 @@
|
|||||||
.pio
|
.pio
|
||||||
.idea
|
.idea
|
||||||
.DS_Store
|
.DS_Store
|
||||||
|
.vscode
|
||||||
|
lib/EpdFont/fontsrc
|
||||||
|
*.generated.h
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ Built using **PlatformIO** and targeting the **ESP32-C3** microcontroller.
|
|||||||
CrossPoint Reader is a purpose-built firmware designed to be a drop-in, fully open-source replacement for the official
|
CrossPoint Reader is a purpose-built firmware designed to be a drop-in, fully open-source replacement for the official
|
||||||
Xteink firmware. It aims to match or improve upon the standard EPUB reading experience.
|
Xteink firmware. It aims to match or improve upon the standard EPUB reading experience.
|
||||||
|
|
||||||

|

|
||||||
|
|
||||||
## Motivation
|
## Motivation
|
||||||
|
|
||||||
@@ -23,20 +23,48 @@ CrossPoint Reader aims to:
|
|||||||
|
|
||||||
This project is **not affiliated with Xteink**; it's built as a community project.
|
This project is **not affiliated with Xteink**; it's built as a community project.
|
||||||
|
|
||||||
## Features
|
## Features & Usage
|
||||||
|
|
||||||
- [x] EPUB parsing and rendering
|
- [x] EPUB parsing and rendering
|
||||||
|
- [ ] Image support within EPUB
|
||||||
- [x] Saved reading position
|
- [x] Saved reading position
|
||||||
- [ ] File explorer with file picker
|
- [x] File explorer with file picker
|
||||||
- [x] Basic EPUB picker from root directory
|
- [x] Basic EPUB picker from root directory
|
||||||
- [x] Support nested folders
|
- [x] Support nested folders
|
||||||
- [ ] EPUB picker with cover art
|
- [ ] EPUB picker with cover art
|
||||||
- [ ] Image support within EPUB
|
- [x] Custom sleep screen
|
||||||
|
- [ ] Cover sleep screen
|
||||||
|
- [x] Wifi book upload
|
||||||
|
- [ ] Wifi OTA updates
|
||||||
- [ ] Configurable font, layout, and display options
|
- [ ] Configurable font, layout, and display options
|
||||||
- [ ] WiFi connectivity
|
- [ ] Screen rotation
|
||||||
- [ ] BLE connectivity
|
|
||||||
|
|
||||||
## Getting Started
|
See [the user guide](./USER_GUIDE.md) for instructions on operating CrossPoint.
|
||||||
|
|
||||||
|
## Installing
|
||||||
|
|
||||||
|
### Web (latest firmware)
|
||||||
|
|
||||||
|
1. Connect your Xteink X4 to your computer via USB-C
|
||||||
|
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
|
||||||
|
back to the other partition using the "Swap boot partition" button here https://xteink.dve.al/debug.
|
||||||
|
|
||||||
|
### Web (specific firmware version)
|
||||||
|
|
||||||
|
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)
|
||||||
|
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
|
||||||
|
back to the other partition using the "Swap boot partition" button here https://xteink.dve.al/debug.
|
||||||
|
|
||||||
|
### Manual
|
||||||
|
|
||||||
|
See [Development](#development) below.
|
||||||
|
|
||||||
|
## Development
|
||||||
|
|
||||||
### Prerequisites
|
### Prerequisites
|
||||||
|
|
||||||
@@ -58,24 +86,12 @@ git submodule update --init --recursive
|
|||||||
|
|
||||||
### Flashing your device
|
### Flashing your device
|
||||||
|
|
||||||
#### Command line
|
|
||||||
|
|
||||||
Connect your Xteink X4 to your computer via USB-C and run the following command.
|
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
|
||||||
```
|
```
|
||||||
|
|
||||||
#### Web
|
|
||||||
|
|
||||||
1. Connect your Xteink X4 to your computer via USB-C
|
|
||||||
2. Download the `firmware.bin` file from the latest release via the [releases page](https://github.com/daveallie/crosspoint-reader/releases)
|
|
||||||
3. Go to https://xteink.dve.al/ and flash the firmware file using the "OTA fast flash controls" section
|
|
||||||
4. Press the reset button on the Xteink X4 to restart the device
|
|
||||||
|
|
||||||
To revert back to the official firmware, you can flash the latest official firmware from https://xteink.dve.al/, or swap
|
|
||||||
back to the other partition using the "Swap boot partition" button here https://xteink.dve.al/debug.
|
|
||||||
|
|
||||||
## Internals
|
## Internals
|
||||||
|
|
||||||
CrossPoint Reader is pretty aggressive about caching data down to the SD card to minimise RAM usage. The ESP32-C3 only
|
CrossPoint Reader is pretty aggressive about caching data down to the SD card to minimise RAM usage. The ESP32-C3 only
|
||||||
@@ -116,6 +132,9 @@ EPUB file will reset the reading progress.
|
|||||||
|
|
||||||
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 there's something there you'd like to work on, leave a comment so that we can avoid duplicated effort.
|
||||||
|
|
||||||
### To submit a contribution:
|
### To submit a contribution:
|
||||||
|
|
||||||
1. Fork the repo
|
1. Fork the repo
|
||||||
|
|||||||
@@ -0,0 +1,127 @@
|
|||||||
|
# CrossPoint User Guide
|
||||||
|
|
||||||
|
Welcome to the **CrossPoint** firmware. This guide outlines the hardware controls, navigation, and reading features of
|
||||||
|
the device.
|
||||||
|
|
||||||
|
## 1. Hardware Overview
|
||||||
|
|
||||||
|
The device utilises the standard buttons on the Xtink X4 in the same layout:
|
||||||
|
|
||||||
|
### Button Layout
|
||||||
|
| Location | Buttons |
|
||||||
|
|-----------------|--------------------------------------------|
|
||||||
|
| **Bottom Edge** | **Back**, **Confirm**, **Left**, **Right** |
|
||||||
|
| **Right Side** | **Power**, **Volume Up**, **Volume Down** |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Power & Startup
|
||||||
|
|
||||||
|
### Power On / Off
|
||||||
|
|
||||||
|
To turn the device on or off, **press and hold the Power button for half a second**. In **Settings** you can configure
|
||||||
|
the power button to trigger on a short press instead of a long one.
|
||||||
|
|
||||||
|
### First Launch
|
||||||
|
|
||||||
|
Upon turning the device on for the first time, you will be placed on the **Home** screen.
|
||||||
|
|
||||||
|
> **Note:** On subsequent restarts, the firmware will automatically reopen the last book you were reading.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Screens
|
||||||
|
|
||||||
|
### 3.1 Home Screen
|
||||||
|
|
||||||
|
The Home Screen is the main entry point to the firmware. From here you can navigate to the **Book Selection** screen,
|
||||||
|
**Settings** screen, or **File Upload** screen.
|
||||||
|
|
||||||
|
### 3.2 Book Selection (Read)
|
||||||
|
|
||||||
|
The Book Selection acts as a folder and file browser.
|
||||||
|
|
||||||
|
* **Navigate List:** Use **Left** (or **Volume Up**), or **Right** (or **Volume Down**) to move the selection cursor up
|
||||||
|
and down through folders and books.
|
||||||
|
* **Open Selection:** Press **Confirm** to open a folder or read a selected book.
|
||||||
|
|
||||||
|
### 3.3 Reading Screen
|
||||||
|
|
||||||
|
See [4. Reading Mode](#4-reading-mode) below for more information.
|
||||||
|
|
||||||
|
### 3.4 File Upload Screen
|
||||||
|
|
||||||
|
The File Upload screen allows you to upload new e-books to the device. When you enter the screen you'll be prompted with
|
||||||
|
a WiFi selection dialog and then your X4 will start hosting a web server.
|
||||||
|
|
||||||
|
See the [webserver docs](./docs/webserver.md) for more information on how to connect to the web server and upload files.
|
||||||
|
|
||||||
|
### 3.5 Settings
|
||||||
|
|
||||||
|
The Settings screen allows you to configure the device's behavior. There are a few settings you can adjust:
|
||||||
|
- **Sleep Screen**: Which sleep screen to display when the device sleeps, options are:
|
||||||
|
- "Dark" (default) - The default dark sleep screen
|
||||||
|
- "Light" - The same default sleep screen, on a white background
|
||||||
|
- "Custom" - Custom images from the SD card, see [3.6 Sleep Screen](#36-sleep-screen) below for more information
|
||||||
|
- "Cover" - The book cover image (Note: this is experimental and may not work as expected)
|
||||||
|
- **Extra Paragraph Spacing**: If enabled, vertical space will be added between paragraphs in the book, if disabled,
|
||||||
|
paragraphs will not have vertical space between them, but will have first word indentation.
|
||||||
|
- **Short Power Button Click**: Whether to trigger the power button on a short press or a long press.
|
||||||
|
|
||||||
|
### 3.6 Sleep Screen
|
||||||
|
|
||||||
|
You can customize the sleep screen by placing custom images in specific locations on the SD card:
|
||||||
|
|
||||||
|
- **Single Image:** Place a file named `sleep.bmp` in the root directory.
|
||||||
|
- **Multiple Images:** Create a `sleep` directory in the root of the SD card and place any number of `.bmp` images
|
||||||
|
inside. If images are found in this directory, they will take priority over the `sleep.png` file, and one will be
|
||||||
|
randomly selected each time the device sleeps.
|
||||||
|
|
||||||
|
> [!NOTE]
|
||||||
|
> You'll need to set the **Sleep Screen** setting to **Custom** in order to use these images.
|
||||||
|
|
||||||
|
> [!TIP]
|
||||||
|
> For best results:
|
||||||
|
> - Use uncompressed BMP files with 24-bit color depth
|
||||||
|
> - Use a resolution of 480x800 pixels to match the device's screen resolution.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Reading Mode
|
||||||
|
|
||||||
|
Once you have opened a book, the button layout changes to facilitate reading.
|
||||||
|
|
||||||
|
### Page Turning
|
||||||
|
| Action | Buttons |
|
||||||
|
|-------------------|--------------------------------------|
|
||||||
|
| **Previous Page** | Press **Left** _or_ **Volume Up** |
|
||||||
|
| **Next Page** | Press **Right** _or_ **Volume Down** |
|
||||||
|
|
||||||
|
### Chapter Navigation
|
||||||
|
* **Next Chapter:** Press and **hold** the **Right** (or **Volume Down**) button briefly, then release.
|
||||||
|
* **Previous Chapter:** Press and **hold** the **Left** (or **Volume Up**) button briefly, then release.
|
||||||
|
|
||||||
|
### System Navigation
|
||||||
|
* **Return to Home:** Press **Back** to close the book and return to the Book Selection screen.
|
||||||
|
* **Chapter Menu:** Press **Confirm** to open the Table of Contents/Chapter Selection screen.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Chapter Selection Screen
|
||||||
|
|
||||||
|
Accessible by pressing **Confirm** while inside a book.
|
||||||
|
|
||||||
|
1. Use **Left** (or **Volume Up**), or **Right** (or **Volume Down**) to highlight the desired chapter.
|
||||||
|
2. Press **Confirm** to jump to that chapter.
|
||||||
|
3. *Alternatively, press **Back** to cancel and return to your current page.*
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Current Limitations & Roadmap
|
||||||
|
|
||||||
|
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.
|
||||||
|
* **Text Formatting:** There are currently no settings to adjust font type, size, line spacing, or margins.
|
||||||
|
* **Rotation**: Different rotation options are not supported.
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
# CrossPoint vs XTOS
|
||||||
|
|
||||||
|
Below is like for like comparison of CrossPoint (version 0.5.1) and XTOS (version 3.1.1). CrossPoint is on the left,
|
||||||
|
XTOS is on the right. CrossPoint does not currently support all features of XTOS, so this comparison is just of key
|
||||||
|
features which both firmwares support.
|
||||||
|
|
||||||
|
## EPUB reading
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
## Menus
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|

|
||||||
|
Before Width: | Height: | Size: 2.2 MiB |
|
After Width: | Height: | Size: 1.3 MiB |
|
After Width: | Height: | Size: 1.3 MiB |
|
After Width: | Height: | Size: 1.8 MiB |
|
After Width: | Height: | Size: 1.7 MiB |
|
After Width: | Height: | Size: 1.6 MiB |
|
After Width: | Height: | Size: 899 KiB |
|
After Width: | Height: | Size: 193 KiB |
|
After Width: | Height: | Size: 144 KiB |
|
After Width: | Height: | Size: 135 KiB |
|
After Width: | Height: | Size: 2.0 MiB |
|
After Width: | Height: | Size: 1.7 MiB |
|
After Width: | Height: | Size: 2.1 MiB |
@@ -0,0 +1,272 @@
|
|||||||
|
# Web Server Guide
|
||||||
|
|
||||||
|
This guide explains how to connect your CrossPoint Reader to WiFi and use the built-in web server to upload EPUB files from your computer or phone.
|
||||||
|
|
||||||
|
## Overview
|
||||||
|
|
||||||
|
CrossPoint Reader includes a built-in web server that allows you to:
|
||||||
|
|
||||||
|
- Upload EPUB files wirelessly from any device on the same WiFi network
|
||||||
|
- Browse and manage files on your device's SD card
|
||||||
|
- Create folders to organize your ebooks
|
||||||
|
- Delete files and folders
|
||||||
|
|
||||||
|
## Prerequisites
|
||||||
|
|
||||||
|
- Your CrossPoint Reader device
|
||||||
|
- A WiFi network
|
||||||
|
- A computer, phone, or tablet connected to the **same WiFi network**
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step 1: Accessing the WiFi Screen
|
||||||
|
|
||||||
|
1. From the main menu or file browser, navigate to the **Settings** screen
|
||||||
|
2. Select the **WiFi** option
|
||||||
|
3. The device will automatically start scanning for available networks
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step 2: Connecting to WiFi
|
||||||
|
|
||||||
|
### Viewing Available Networks
|
||||||
|
|
||||||
|
Once the scan completes, you'll see a list of available WiFi networks with the following indicators:
|
||||||
|
|
||||||
|
- **Signal strength bars** (`||||`, `|||`, `||`, `|`) - Shows connection quality
|
||||||
|
- **`*` symbol** - Indicates the network is password-protected (encrypted)
|
||||||
|
- **`+` symbol** - Indicates you have previously saved credentials for this network
|
||||||
|
|
||||||
|
<img src="./images/wifi/wifi_networks.jpeg" height="500">
|
||||||
|
|
||||||
|
### Selecting a Network
|
||||||
|
|
||||||
|
1. Use the **Left/Right** (or **Volume Up/Down**) buttons to navigate through the network list
|
||||||
|
2. Press **Confirm** to select the highlighted network
|
||||||
|
|
||||||
|
### Entering Password (for encrypted networks)
|
||||||
|
|
||||||
|
If the network requires a password:
|
||||||
|
|
||||||
|
1. An on-screen keyboard will appear
|
||||||
|
2. Use the navigation buttons to select characters
|
||||||
|
3. Press **Confirm** to enter each character
|
||||||
|
4. When complete, select the **Done** option on the keyboard
|
||||||
|
|
||||||
|
<img src="./images/wifi/wifi_password.jpeg" height="500">
|
||||||
|
|
||||||
|
**Note:** If you've previously connected to this network, the saved password will be used automatically.
|
||||||
|
|
||||||
|
### Connection Process
|
||||||
|
|
||||||
|
The device will display "Connecting..." while establishing the connection. This typically takes 5-10 seconds.
|
||||||
|
|
||||||
|
### Saving Credentials
|
||||||
|
|
||||||
|
If this is a new network, you'll be prompted to save the password:
|
||||||
|
|
||||||
|
- Select **Yes** to save credentials for automatic connection next time (NOTE: These are stored in plaintext on the device's SD card. Do not use this for sensitive networks.)
|
||||||
|
- Select **No** to connect without saving
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step 3: Connection Success
|
||||||
|
|
||||||
|
Once connected, the screen will display:
|
||||||
|
|
||||||
|
- **Network name** (SSID)
|
||||||
|
- **IP Address** (e.g., `192.168.1.102`)
|
||||||
|
- **Web server URL** (e.g., `http://192.168.1.102/`)
|
||||||
|
|
||||||
|
<img src="./images/wifi/wifi_connected.jpeg" height="500">
|
||||||
|
|
||||||
|
**Important:** Make note of the IP address - you'll need this to access the web interface from your computer or phone.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step 4: Accessing the Web Interface
|
||||||
|
|
||||||
|
### From a Computer
|
||||||
|
|
||||||
|
1. Ensure your computer is connected to the **same WiFi network** as your CrossPoint Reader
|
||||||
|
2. Open any web browser (Chrome is recommended)
|
||||||
|
3. Type the IP address shown on your device into the browser's address bar
|
||||||
|
- Example: `http://192.168.1.102/`
|
||||||
|
4. Press Enter
|
||||||
|
|
||||||
|
### From a Phone or Tablet
|
||||||
|
|
||||||
|
1. Ensure your phone/tablet is connected to the **same WiFi network** as your CrossPoint Reader
|
||||||
|
2. Open your mobile browser (Safari, Chrome, etc.)
|
||||||
|
3. Type the IP address into the address bar
|
||||||
|
- Example: `http://192.168.1.102/`
|
||||||
|
4. Tap Go
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Step 5: Using the Web Interface
|
||||||
|
|
||||||
|
### Home Page
|
||||||
|
|
||||||
|
The home page displays:
|
||||||
|
|
||||||
|
- Device status and version information
|
||||||
|
- WiFi connection status
|
||||||
|
- Current IP address
|
||||||
|
- Available memory
|
||||||
|
|
||||||
|
Navigation links:
|
||||||
|
|
||||||
|
- **Home** - Returns to the status page
|
||||||
|
- **File Manager** - Access file management features
|
||||||
|
|
||||||
|
<img src="./images/wifi/webserver_homepage.png" width="600">
|
||||||
|
|
||||||
|
### File Manager
|
||||||
|
|
||||||
|
Click **File Manager** to access file management features.
|
||||||
|
|
||||||
|
#### Browsing Files
|
||||||
|
|
||||||
|
- The file manager displays all files and folders on your SD card
|
||||||
|
- **Folders** are highlighted in yellow with a 📁 icon
|
||||||
|
- **EPUB files** are highlighted in green with a 📗 icon
|
||||||
|
- Click on a folder name to navigate into it
|
||||||
|
- Use the breadcrumb navigation at the top to go back to parent folders
|
||||||
|
|
||||||
|
<img src="./images/wifi/webserver_files.png" width="600">
|
||||||
|
|
||||||
|
#### Uploading EPUB Files
|
||||||
|
|
||||||
|
1. Click the **+ Add** button in the top-right corner
|
||||||
|
2. Select **Upload eBook** from the dropdown menu
|
||||||
|
3. Click **Choose File** and select an `.epub` file from your device
|
||||||
|
4. Click **Upload**
|
||||||
|
5. A progress bar will show the upload status
|
||||||
|
6. The page will automatically refresh when the upload is complete
|
||||||
|
|
||||||
|
**Note:** Only `.epub` files are accepted. Other file types will be rejected.
|
||||||
|
|
||||||
|
<img src="./images/wifi/webserver_upload.png" width="600">
|
||||||
|
|
||||||
|
#### Creating Folders
|
||||||
|
|
||||||
|
1. Click the **+ Add** button in the top-right corner
|
||||||
|
2. Select **New Folder** from the dropdown menu
|
||||||
|
3. Enter a folder name (letters, numbers, underscores, and hyphens only)
|
||||||
|
4. Click **Create Folder**
|
||||||
|
|
||||||
|
This is useful for organizing your ebooks by genre, author, or series.
|
||||||
|
|
||||||
|
#### Deleting Files and Folders
|
||||||
|
|
||||||
|
1. Click the **🗑️** (trash) icon next to any file or folder
|
||||||
|
2. Confirm the deletion in the popup dialog
|
||||||
|
3. Click **Delete** to permanently remove the item
|
||||||
|
|
||||||
|
**Warning:** Deletion is permanent and cannot be undone!
|
||||||
|
|
||||||
|
**Note:** Folders must be empty before they can be deleted.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Troubleshooting
|
||||||
|
|
||||||
|
### Cannot See the Device on the Network
|
||||||
|
|
||||||
|
**Problem:** Browser shows "Cannot connect" or "Site can't be reached"
|
||||||
|
|
||||||
|
**Solutions:**
|
||||||
|
|
||||||
|
1. Verify both devices are on the **same WiFi network**
|
||||||
|
- Check your computer/phone WiFi settings
|
||||||
|
- Confirm the CrossPoint Reader shows "Connected" status
|
||||||
|
2. Double-check the IP address
|
||||||
|
- Make sure you typed it correctly
|
||||||
|
- Include `http://` at the beginning
|
||||||
|
3. Try disabling VPN if you're using one
|
||||||
|
4. Some networks have "client isolation" enabled - check with your network administrator
|
||||||
|
|
||||||
|
### Connection Drops or Times Out
|
||||||
|
|
||||||
|
**Problem:** WiFi connection is unstable
|
||||||
|
|
||||||
|
**Solutions:**
|
||||||
|
|
||||||
|
1. Move closer to the WiFi router
|
||||||
|
2. Check signal strength on the device (should be at least `||` or better)
|
||||||
|
3. Avoid interference from other devices
|
||||||
|
4. Try a different WiFi network if available
|
||||||
|
|
||||||
|
### Upload Fails
|
||||||
|
|
||||||
|
**Problem:** File upload doesn't complete or shows an error
|
||||||
|
|
||||||
|
**Solutions:**
|
||||||
|
|
||||||
|
1. Ensure the file is a valid `.epub` file
|
||||||
|
2. Check that the SD card has enough free space
|
||||||
|
3. Try uploading a smaller file first to test
|
||||||
|
4. Refresh the browser page and try again
|
||||||
|
|
||||||
|
### Saved Password Not Working
|
||||||
|
|
||||||
|
**Problem:** Device fails to connect with saved credentials
|
||||||
|
|
||||||
|
**Solutions:**
|
||||||
|
|
||||||
|
1. When connection fails, you'll be prompted to "Forget Network"
|
||||||
|
2. Select **Yes** to remove the saved password
|
||||||
|
3. Reconnect and enter the password again
|
||||||
|
4. Choose to save the new password
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Security Notes
|
||||||
|
|
||||||
|
- The web server runs on port 80 (standard HTTP)
|
||||||
|
- **No authentication is required** - anyone on the same network can access the interface
|
||||||
|
- The web server is only accessible while the WiFi screen shows "Connected"
|
||||||
|
- The web server automatically stops when you exit the WiFi screen
|
||||||
|
- For security, only use on trusted private networks
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Technical Details
|
||||||
|
|
||||||
|
- **Supported WiFi:** 2.4GHz networks (802.11 b/g/n)
|
||||||
|
- **Web Server Port:** 80 (HTTP)
|
||||||
|
- **Maximum Upload Size:** Limited by available SD card space
|
||||||
|
- **Supported File Format:** `.epub` only
|
||||||
|
- **Browser Compatibility:** All modern browsers (Chrome, Firefox, Safari, Edge)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Tips and Best Practices
|
||||||
|
|
||||||
|
1. **Organize with folders** - Create folders before uploading to keep your library organized
|
||||||
|
2. **Check signal strength** - Stronger signals (`|||` or `||||`) provide faster, more reliable uploads
|
||||||
|
3. **Upload multiple files** - You can upload files one at a time; the page refreshes after each upload
|
||||||
|
4. **Use descriptive names** - Name your folders clearly (e.g., "SciFi", "Mystery", "Non-Fiction")
|
||||||
|
5. **Keep credentials saved** - Save your WiFi password for quick reconnection in the future
|
||||||
|
6. **Exit when done** - Press **Back** to exit the WiFi screen and save battery
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Exiting WiFi Mode
|
||||||
|
|
||||||
|
When you're finished uploading files:
|
||||||
|
|
||||||
|
1. Press the **Back** button on your CrossPoint Reader
|
||||||
|
2. The web server will automatically stop
|
||||||
|
3. WiFi will disconnect to conserve battery
|
||||||
|
4. You'll return to the previous screen
|
||||||
|
|
||||||
|
Your uploaded files will be immediately available in the file browser!
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Related Documentation
|
||||||
|
|
||||||
|
- [User Guide](../USER_GUIDE.md) - General device operation
|
||||||
|
- [README](../README.md) - Project overview and features
|
||||||
@@ -59,14 +59,28 @@ bool EpdFont::hasPrintableChars(const char* string) const {
|
|||||||
|
|
||||||
const EpdGlyph* EpdFont::getGlyph(const uint32_t cp) const {
|
const EpdGlyph* EpdFont::getGlyph(const uint32_t cp) const {
|
||||||
const EpdUnicodeInterval* intervals = data->intervals;
|
const EpdUnicodeInterval* intervals = data->intervals;
|
||||||
for (int i = 0; i < data->intervalCount; i++) {
|
const int count = data->intervalCount;
|
||||||
const EpdUnicodeInterval* interval = &intervals[i];
|
|
||||||
if (cp >= interval->first && cp <= interval->last) {
|
if (count == 0) return nullptr;
|
||||||
|
|
||||||
|
// Binary search for O(log n) lookup instead of O(n)
|
||||||
|
// Critical for Korean fonts with many unicode intervals
|
||||||
|
int left = 0;
|
||||||
|
int right = count - 1;
|
||||||
|
|
||||||
|
while (left <= right) {
|
||||||
|
const int mid = left + (right - left) / 2;
|
||||||
|
const EpdUnicodeInterval* interval = &intervals[mid];
|
||||||
|
|
||||||
|
if (cp < interval->first) {
|
||||||
|
right = mid - 1;
|
||||||
|
} else if (cp > interval->last) {
|
||||||
|
left = mid + 1;
|
||||||
|
} else {
|
||||||
|
// Found: cp >= interval->first && cp <= interval->last
|
||||||
return &data->glyph[interval->offset + (cp - interval->first)];
|
return &data->glyph[interval->offset + (cp - interval->first)];
|
||||||
}
|
}
|
||||||
if (cp < interval->first) {
|
|
||||||
return nullptr;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return nullptr;
|
return nullptr;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -31,4 +31,5 @@ typedef struct {
|
|||||||
uint8_t advanceY; ///< Newline distance (y axis)
|
uint8_t advanceY; ///< Newline distance (y axis)
|
||||||
int ascender; ///< Maximal height of a glyph above the base line
|
int ascender; ///< Maximal height of a glyph above the base line
|
||||||
int descender; ///< Maximal height of a glyph below the base line
|
int descender; ///< Maximal height of a glyph below the base line
|
||||||
|
bool is2Bit;
|
||||||
} EpdFontData;
|
} EpdFontData;
|
||||||
|
|||||||
@@ -1,504 +0,0 @@
|
|||||||
/**
|
|
||||||
* generated by fontconvert.py
|
|
||||||
* name: babyblue
|
|
||||||
* size: 8
|
|
||||||
*/
|
|
||||||
#pragma once
|
|
||||||
#include "EpdFontData.h"
|
|
||||||
|
|
||||||
static const uint8_t babyblueBitmaps[3140] = {
|
|
||||||
0xFF, 0xFF, 0x30, 0xFF, 0xFF, 0xF0, 0x36, 0x1B, 0x0D, 0x9F, 0xFF, 0xF9, 0xB3, 0xFF, 0xFF, 0x36, 0x1B, 0x0D, 0x80,
|
|
||||||
0x18, 0x18, 0x7E, 0xFF, 0xDB, 0xD8, 0xFE, 0x7F, 0x9B, 0xDB, 0xFF, 0x7E, 0x18, 0x00, 0x71, 0x9F, 0x73, 0x6C, 0x6F,
|
|
||||||
0x8F, 0xE0, 0xFF, 0x83, 0xF8, 0xFB, 0x1B, 0x63, 0x7C, 0xC7, 0x00, 0x38, 0x3E, 0x1B, 0x0D, 0x87, 0xC3, 0xEF, 0xBF,
|
|
||||||
0x8E, 0xCF, 0x7F, 0x1E, 0xC0, 0xFF, 0x37, 0xEC, 0xCC, 0xCC, 0xCC, 0xCC, 0x67, 0x20, 0xCE, 0x73, 0x33, 0x33, 0x33,
|
|
||||||
0x33, 0x6C, 0x80, 0x32, 0xFF, 0xDE, 0xFE, 0x30, 0x18, 0x18, 0x18, 0xFF, 0xFF, 0x18, 0x18, 0x18, 0xBF, 0x00, 0xFF,
|
|
||||||
0xC0, 0x30, 0x0C, 0x31, 0xC6, 0x18, 0xE3, 0x1C, 0x63, 0x8C, 0x00, 0x3C, 0x7E, 0xE7, 0xC3, 0xC3, 0xC3, 0xC3, 0xC3,
|
|
||||||
0xC7, 0x7E, 0x3C, 0x19, 0xDF, 0xFD, 0x8C, 0x63, 0x18, 0xC6, 0x3C, 0x7E, 0xE7, 0x83, 0x07, 0x0E, 0x1C, 0x38, 0x70,
|
|
||||||
0xFE, 0xFF, 0x7E, 0xFF, 0xC3, 0x07, 0x3E, 0x3E, 0x07, 0x03, 0x83, 0xFF, 0x7E, 0x0E, 0x1E, 0x3E, 0x76, 0xE6, 0xFF,
|
|
||||||
0xFF, 0x06, 0x06, 0x06, 0x06, 0x7F, 0xFF, 0x06, 0x0F, 0xDF, 0xC1, 0x83, 0x87, 0xFD, 0xF0, 0x3E, 0x7F, 0xE3, 0xC0,
|
|
||||||
0xFC, 0xFE, 0xE7, 0xC3, 0xC7, 0x7E, 0x3C, 0xFF, 0xFF, 0xC0, 0xE0, 0xE0, 0x60, 0x70, 0x30, 0x18, 0x1C, 0x0C, 0x06,
|
|
||||||
0x00, 0x3C, 0x7E, 0x66, 0x66, 0x7E, 0x7E, 0xE7, 0xC3, 0xC7, 0x7E, 0x3C, 0x3C, 0x7E, 0xE7, 0xC3, 0xC3, 0xC7, 0x7F,
|
|
||||||
0x3F, 0x07, 0x3E, 0x7C, 0xB0, 0x03, 0xB0, 0x03, 0xF8, 0x06, 0x3D, 0xF7, 0x8F, 0x0F, 0x87, 0x03, 0xFF, 0xFF, 0x00,
|
|
||||||
0xFF, 0xFF, 0x81, 0xE1, 0xF0, 0xF1, 0xEF, 0xBC, 0x40, 0x38, 0xFB, 0xBE, 0x30, 0xE3, 0x8E, 0x18, 0x30, 0x00, 0xC0,
|
|
||||||
0x0F, 0xE0, 0x7F, 0xC3, 0x83, 0x9D, 0xE7, 0xEF, 0xCF, 0x73, 0x3D, 0x8C, 0xF6, 0x33, 0xD8, 0xDB, 0x3F, 0xC6, 0x7E,
|
|
||||||
0x0C, 0x03, 0x18, 0x18, 0x7F, 0xE0, 0xFF, 0x00, 0x38, 0xFB, 0xBE, 0x3C, 0x7F, 0xFF, 0xE3, 0xC7, 0x8C, 0xFC, 0xFE,
|
|
||||||
0xC7, 0xC7, 0xFE, 0xFE, 0xC7, 0xC7, 0xFE, 0xFC, 0x3F, 0x3F, 0xF8, 0x78, 0x0C, 0x06, 0x03, 0x01, 0x83, 0x7F, 0x9F,
|
|
||||||
0x80, 0xFC, 0xFE, 0xC7, 0xC3, 0xC3, 0xC3, 0xC3, 0xC7, 0xFE, 0xFC, 0xFF, 0xFF, 0x06, 0x0F, 0xDF, 0xB0, 0x60, 0xFD,
|
|
||||||
0xFC, 0xFF, 0xFF, 0x06, 0x0F, 0xDF, 0xB0, 0x60, 0xC1, 0x80, 0x3F, 0x3F, 0xF8, 0x78, 0x0C, 0x7E, 0x3F, 0x07, 0x83,
|
|
||||||
0x7F, 0x9F, 0x80, 0xC3, 0xC3, 0xC3, 0xC3, 0xFF, 0xFF, 0xC3, 0xC3, 0xC3, 0xC3, 0xFF, 0xFF, 0xF0, 0x0C, 0x30, 0xC3,
|
|
||||||
0x0C, 0x38, 0xF3, 0xFD, 0xE0, 0xC3, 0xC7, 0xCE, 0xDC, 0xF8, 0xF8, 0xDC, 0xCC, 0xC6, 0xC3, 0xC1, 0x83, 0x06, 0x0C,
|
|
||||||
0x18, 0x30, 0x60, 0xFD, 0xFC, 0xE1, 0xF8, 0x7F, 0x3F, 0xCF, 0xFF, 0xF7, 0xBD, 0xEF, 0x7B, 0xCC, 0xF3, 0x30, 0xC3,
|
|
||||||
0xE3, 0xF3, 0xF3, 0xFB, 0xDF, 0xCF, 0xCF, 0xC7, 0xC3, 0x3E, 0x3F, 0xB8, 0xF8, 0x3C, 0x1E, 0x0F, 0x07, 0x87, 0x7F,
|
|
||||||
0x1F, 0x00, 0xFE, 0xFF, 0xC3, 0xC3, 0xFF, 0xFE, 0xC0, 0xC0, 0xC0, 0xC0, 0x3E, 0x3F, 0xB8, 0xF8, 0x3C, 0x1E, 0x0F,
|
|
||||||
0x37, 0x9F, 0x7F, 0x1F, 0xC0, 0xFE, 0xFF, 0xC3, 0xC7, 0xFE, 0xFE, 0xC7, 0xC3, 0xC3, 0xC3, 0x7D, 0xFF, 0x1F, 0x87,
|
|
||||||
0xC3, 0xC1, 0xC3, 0xFE, 0xF8, 0xFF, 0xFF, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0xC3, 0xC3, 0xC3, 0xC3,
|
|
||||||
0xC3, 0xC3, 0xC3, 0xC7, 0x7E, 0x3C, 0xC3, 0xC3, 0xC3, 0xE7, 0x66, 0x7E, 0x3C, 0x3C, 0x3C, 0x18, 0x83, 0x0F, 0x0C,
|
|
||||||
0x3C, 0x30, 0xF1, 0xE7, 0x67, 0x99, 0xBF, 0xE3, 0xCF, 0x0F, 0x3C, 0x3C, 0xF0, 0x61, 0x80, 0x80, 0xF8, 0x77, 0x38,
|
|
||||||
0xFC, 0x1E, 0x07, 0x83, 0xF1, 0xCE, 0xE1, 0xB0, 0x30, 0xC3, 0xC3, 0xE7, 0x7E, 0x3C, 0x18, 0x18, 0x18, 0x18, 0x18,
|
|
||||||
0xFF, 0xFF, 0x07, 0x0E, 0x1C, 0x38, 0x70, 0xE0, 0xFE, 0xFF, 0xFF, 0xCC, 0xCC, 0xCC, 0xCC, 0xCC, 0xFE, 0x81, 0xC1,
|
|
||||||
0x83, 0x83, 0x83, 0x06, 0x06, 0x0C, 0x0C, 0xFF, 0x33, 0x33, 0x33, 0x33, 0x33, 0xFE, 0x18, 0x3C, 0x7E, 0x66, 0xE7,
|
|
||||||
0xC3, 0x83, 0xFF, 0xFF, 0x9D, 0x80, 0x7D, 0xFE, 0x1B, 0xFF, 0xF8, 0xFF, 0xBF, 0xC1, 0x83, 0xE7, 0xEC, 0xF8, 0xF1,
|
|
||||||
0xE7, 0xFD, 0xF0, 0x3C, 0xFF, 0x9E, 0x0C, 0x18, 0x9F, 0x9E, 0x06, 0x0C, 0xFB, 0xFE, 0x78, 0xF1, 0xE3, 0x7E, 0x7C,
|
|
||||||
0x3C, 0x7E, 0xE7, 0xFF, 0xFF, 0xC0, 0x7E, 0x3F, 0x3B, 0xD9, 0xFF, 0xB1, 0x8C, 0x63, 0x18, 0x3E, 0xFF, 0x9E, 0x3C,
|
|
||||||
0x78, 0xDF, 0x9F, 0x06, 0x0D, 0xF3, 0xC0, 0xC3, 0x0F, 0xBF, 0xEF, 0x3C, 0xF3, 0xCF, 0x30, 0xFB, 0xFF, 0xF0, 0x6D,
|
|
||||||
0x36, 0xDB, 0x6D, 0xBD, 0x00, 0xC3, 0x0C, 0xF7, 0xFB, 0xCE, 0x3C, 0xDB, 0x30, 0xFF, 0xFF, 0xF0, 0x7F, 0xBF, 0xFC,
|
|
||||||
0xCF, 0x33, 0xCC, 0xF3, 0x3C, 0xCF, 0x33, 0x7B, 0xFC, 0xF3, 0xCF, 0x3C, 0xF3, 0x3C, 0x7E, 0xE7, 0xC3, 0xC3, 0xC7,
|
|
||||||
0x7E, 0x3C, 0x79, 0xFB, 0x3E, 0x3C, 0x79, 0xFF, 0x7C, 0xC1, 0x82, 0x00, 0x3C, 0xFF, 0x9E, 0x3C, 0x78, 0xDF, 0x9F,
|
|
||||||
0x06, 0x0C, 0x10, 0x77, 0xF7, 0x8C, 0x63, 0x18, 0x7D, 0xFF, 0x1F, 0xE7, 0xF0, 0xFF, 0xBE, 0x63, 0x3D, 0xE6, 0x31,
|
|
||||||
0x8C, 0x71, 0xC0, 0x8F, 0x3C, 0xF3, 0xCF, 0x3F, 0xDE, 0x83, 0xC3, 0xC7, 0x66, 0x66, 0x6E, 0x3C, 0x18, 0x80, 0xF3,
|
|
||||||
0x3D, 0xFD, 0xFE, 0x7F, 0x9F, 0xE3, 0x30, 0xCC, 0x83, 0xC7, 0x6E, 0x3C, 0x38, 0x7C, 0xE6, 0xC3, 0x83, 0xC7, 0x66,
|
|
||||||
0x6E, 0x3C, 0x3C, 0x18, 0x18, 0x18, 0x70, 0x60, 0xFF, 0xFC, 0x71, 0xC7, 0x1C, 0x3F, 0x7F, 0x19, 0xCC, 0x63, 0x3B,
|
|
||||||
0x98, 0x61, 0x8C, 0x63, 0x1C, 0x40, 0xFF, 0xFF, 0xFF, 0xF8, 0x83, 0x87, 0x0C, 0x30, 0xE1, 0xC7, 0x38, 0xC3, 0x0C,
|
|
||||||
0x63, 0x08, 0x00, 0x79, 0xFF, 0xE3, 0xC0, 0xF2, 0xFF, 0xFE, 0x18, 0x30, 0xF3, 0xFF, 0xFB, 0x36, 0x6E, 0x7E, 0x78,
|
|
||||||
0x60, 0xC1, 0x00, 0x3C, 0x7E, 0x66, 0x60, 0xFC, 0xFC, 0x30, 0x72, 0xFF, 0xFE, 0x83, 0xFF, 0x7E, 0x66, 0x66, 0x7E,
|
|
||||||
0xFE, 0x83, 0x83, 0xE7, 0x7E, 0x3C, 0xFF, 0xFF, 0xFF, 0xFF, 0x18, 0x18, 0xFF, 0xFC, 0xBF, 0xF8, 0x3C, 0x7E, 0x66,
|
|
||||||
0x7E, 0x7C, 0xEE, 0xC7, 0xC3, 0x77, 0x3E, 0x0C, 0x66, 0x66, 0x7C, 0x38, 0x9E, 0xE6, 0x3F, 0x1F, 0xEF, 0xFF, 0xFF,
|
|
||||||
0xF3, 0xFC, 0x3F, 0x3F, 0xFF, 0xDF, 0xDF, 0xE3, 0xF0, 0x77, 0xFF, 0xFF, 0xBC, 0x36, 0xFF, 0xF6, 0xCD, 0xCD, 0x8D,
|
|
||||||
0x80, 0xFF, 0xFF, 0x03, 0x03, 0x03, 0x3F, 0x1F, 0xEF, 0xFF, 0xFB, 0xF6, 0xFF, 0xBF, 0xEF, 0xDB, 0xF7, 0xDF, 0xE3,
|
|
||||||
0xF0, 0xFF, 0xFF, 0x6F, 0xFF, 0x60, 0x18, 0x18, 0x18, 0xFF, 0xFF, 0x18, 0x18, 0xFE, 0xFF, 0x77, 0xE6, 0x77, 0x73,
|
|
||||||
0xFF, 0x77, 0xEF, 0x7F, 0xB8, 0x7F, 0x00, 0xCF, 0x3C, 0xF3, 0xCF, 0x3F, 0xFE, 0xC3, 0x0C, 0x20, 0x7F, 0xFF, 0xFE,
|
|
||||||
0xFE, 0xFE, 0x7E, 0x1E, 0x1E, 0x1E, 0x1E, 0x1E, 0x1E, 0x1E, 0x16, 0xB0, 0x63, 0xEC, 0x37, 0xFB, 0x33, 0x30, 0x7B,
|
|
||||||
0xFC, 0xF3, 0xFD, 0xE0, 0x99, 0xF9, 0xF9, 0xB7, 0xFF, 0xB6, 0x00, 0x30, 0x07, 0x03, 0xF0, 0x7B, 0x0E, 0x31, 0xC3,
|
|
||||||
0x38, 0x37, 0x60, 0xEE, 0x1D, 0xE3, 0xBF, 0x33, 0xF6, 0x06, 0x30, 0x67, 0x0E, 0xF1, 0xCB, 0x38, 0x37, 0x03, 0xEF,
|
|
||||||
0x1D, 0xF3, 0x9F, 0x70, 0xEE, 0x0E, 0xC1, 0xF0, 0x70, 0x6F, 0x8E, 0xB9, 0xCB, 0xB8, 0xFF, 0x07, 0xE6, 0x1C, 0xE3,
|
|
||||||
0x9E, 0x73, 0xFE, 0x3F, 0xC0, 0x60, 0x30, 0x60, 0xC1, 0x87, 0x1C, 0x30, 0x60, 0xC6, 0xD9, 0xE1, 0x80, 0x30, 0x70,
|
|
||||||
0x61, 0xC7, 0xDD, 0xF1, 0xE3, 0xFF, 0xFF, 0x1E, 0x3C, 0x60, 0x18, 0x70, 0xC1, 0xC7, 0xDD, 0xF1, 0xE3, 0xFF, 0xFF,
|
|
||||||
0x1E, 0x3C, 0x60, 0x38, 0xF9, 0xB1, 0xC7, 0xDD, 0xF1, 0xE3, 0xFF, 0xFF, 0x1E, 0x3C, 0x60, 0x3C, 0xF9, 0xE1, 0xC7,
|
|
||||||
0xDD, 0xF1, 0xE3, 0xFF, 0xFF, 0x1E, 0x3C, 0x60, 0x6C, 0xD8, 0xE3, 0xEE, 0xF8, 0xF1, 0xFF, 0xFF, 0x8F, 0x1E, 0x30,
|
|
||||||
0x38, 0xF9, 0xF1, 0xC7, 0xDD, 0xF1, 0xE3, 0xFF, 0xFF, 0x1E, 0x3C, 0x60, 0x0F, 0xF8, 0x7F, 0xC7, 0xC0, 0x36, 0x03,
|
|
||||||
0xB0, 0x19, 0xF9, 0xFF, 0xCF, 0xE0, 0xE3, 0x06, 0x1F, 0xB0, 0xFE, 0x3F, 0x3F, 0xF8, 0x78, 0x0C, 0x06, 0x03, 0x01,
|
|
||||||
0x83, 0x7F, 0x9F, 0x86, 0x01, 0x83, 0x81, 0x80, 0x30, 0x70, 0x67, 0xFF, 0xF8, 0x30, 0x7E, 0xFD, 0x83, 0x07, 0xEF,
|
|
||||||
0xE0, 0x0C, 0x38, 0x67, 0xFF, 0xF8, 0x30, 0x7E, 0xFD, 0x83, 0x07, 0xEF, 0xE0, 0x18, 0x78, 0xF7, 0xFF, 0xF8, 0x30,
|
|
||||||
0x7E, 0xFD, 0x83, 0x07, 0xEF, 0xE0, 0x3C, 0x7B, 0xFF, 0xFC, 0x18, 0x3F, 0x7E, 0xC1, 0x83, 0xF7, 0xF0, 0x9D, 0x36,
|
|
||||||
0xDB, 0x6D, 0xB6, 0x7A, 0x6D, 0xB6, 0xDB, 0x6C, 0x6F, 0xB6, 0x66, 0x66, 0x66, 0x66, 0x60, 0xBB, 0x66, 0x66, 0x66,
|
|
||||||
0x66, 0x66, 0x7E, 0x3F, 0x98, 0xEC, 0x3F, 0xDF, 0xED, 0x86, 0xC7, 0x7F, 0x3F, 0x00, 0x1E, 0x3E, 0x3C, 0xC3, 0xE3,
|
|
||||||
0xF3, 0xF3, 0xFB, 0xDF, 0xCF, 0xCF, 0xC7, 0xC3, 0x18, 0x0E, 0x03, 0x07, 0xC7, 0xF7, 0x1F, 0x07, 0x83, 0xC1, 0xE0,
|
|
||||||
0xF0, 0xEF, 0xE3, 0xE0, 0x0C, 0x0E, 0x06, 0x07, 0xC7, 0xF7, 0x1F, 0x07, 0x83, 0xC1, 0xE0, 0xF0, 0xEF, 0xE3, 0xE0,
|
|
||||||
0x1C, 0x1F, 0x0D, 0x87, 0xC7, 0xF7, 0x1F, 0x07, 0x83, 0xC1, 0xE0, 0xF0, 0xEF, 0xE3, 0xE0, 0x1E, 0x1F, 0x0F, 0x07,
|
|
||||||
0xC7, 0xF7, 0x1F, 0x07, 0x83, 0xC1, 0xE0, 0xF0, 0xEF, 0xE3, 0xE0, 0x36, 0x1B, 0x0F, 0x8F, 0xEE, 0x3E, 0x0F, 0x07,
|
|
||||||
0x83, 0xC1, 0xE1, 0xDF, 0xC7, 0xC0, 0x8F, 0xF7, 0x9E, 0xFF, 0x30, 0x1F, 0xCF, 0xF7, 0x3D, 0x9F, 0x6E, 0xDF, 0x37,
|
|
||||||
0x8D, 0xC7, 0xFF, 0xB7, 0xC0, 0x30, 0x38, 0x18, 0xC3, 0xC3, 0xC3, 0xC3, 0xC3, 0xC3, 0xC3, 0xC7, 0x7E, 0x3C, 0x0C,
|
|
||||||
0x1C, 0x18, 0xC3, 0xC3, 0xC3, 0xC3, 0xC3, 0xC3, 0xC3, 0xC7, 0x7E, 0x3C, 0x18, 0x3C, 0x3C, 0xC3, 0xC3, 0xC3, 0xC3,
|
|
||||||
0xC3, 0xC3, 0xC3, 0xC7, 0x7E, 0x3C, 0x3C, 0x3C, 0xC3, 0xC3, 0xC3, 0xC3, 0xC3, 0xC3, 0xC3, 0xC7, 0x7E, 0x3C, 0x0C,
|
|
||||||
0x1C, 0x18, 0xC3, 0xC3, 0xE7, 0x7E, 0x3C, 0x18, 0x18, 0x18, 0x18, 0x18, 0xC0, 0xFC, 0xFE, 0xC7, 0xC3, 0xC7, 0xFE,
|
|
||||||
0xFC, 0xC0, 0xC0, 0x38, 0xFB, 0xB6, 0x6D, 0xDB, 0x37, 0x67, 0xE7, 0xFF, 0x70, 0x30, 0x70, 0x63, 0xEF, 0xF0, 0xDF,
|
|
||||||
0xFF, 0xC7, 0xFD, 0xF8, 0x0C, 0x38, 0x63, 0xEF, 0xF0, 0xDF, 0xFF, 0xC7, 0xFD, 0xF8, 0x18, 0x78, 0xF3, 0xEF, 0xF0,
|
|
||||||
0xDF, 0xFF, 0xC7, 0xFD, 0xF8, 0x3C, 0xF9, 0xE3, 0xEF, 0xF0, 0xDF, 0xFF, 0xC7, 0xFD, 0xF8, 0x3C, 0x79, 0xF7, 0xF8,
|
|
||||||
0x6F, 0xFF, 0xE3, 0xFE, 0xFC, 0x18, 0x78, 0xF0, 0xC7, 0xDF, 0xE1, 0xBF, 0xFF, 0x8F, 0xFB, 0xF0, 0x7F, 0xEF, 0xFF,
|
|
||||||
0x86, 0x37, 0xFF, 0xFF, 0xFC, 0x61, 0xFF, 0xF7, 0xFE, 0x3C, 0xFF, 0x9E, 0x0C, 0x18, 0x9F, 0x9E, 0x18, 0x18, 0xE1,
|
|
||||||
0x80, 0x30, 0x38, 0x18, 0x3C, 0x7E, 0xE7, 0xFF, 0xFF, 0xC0, 0x7E, 0x3F, 0x0C, 0x1C, 0x18, 0x3C, 0x7E, 0xE7, 0xFF,
|
|
||||||
0xFF, 0xC0, 0x7E, 0x3F, 0x18, 0x3C, 0x3C, 0x3C, 0x7E, 0xE7, 0xFF, 0xFF, 0xC0, 0x7E, 0x3F, 0x3C, 0x3C, 0x3C, 0x7E,
|
|
||||||
0xE7, 0xFF, 0xFF, 0xC0, 0x7E, 0x3F, 0x9D, 0xA6, 0xDB, 0x6D, 0x80, 0x7F, 0x4D, 0xB6, 0xDB, 0x00, 0x6F, 0xB4, 0x66,
|
|
||||||
0x66, 0x66, 0x60, 0xBB, 0x46, 0x66, 0x66, 0x66, 0x3E, 0x3E, 0x3C, 0x7E, 0xE7, 0xC3, 0xC3, 0xC3, 0xC7, 0x7E, 0x3C,
|
|
||||||
0x3D, 0xF7, 0x9E, 0xFF, 0x3C, 0xF3, 0xCF, 0x3C, 0xC0, 0x30, 0x38, 0x18, 0x3C, 0x7E, 0xE7, 0xC3, 0xC3, 0xC7, 0x7E,
|
|
||||||
0x3C, 0x0C, 0x1C, 0x18, 0x3C, 0x7E, 0xE7, 0xC3, 0xC3, 0xC7, 0x7E, 0x3C, 0x18, 0x3C, 0x3C, 0x3C, 0x7E, 0xE7, 0xC3,
|
|
||||||
0xC3, 0xC7, 0x7E, 0x3C, 0x1E, 0x3E, 0x3C, 0x3C, 0x7E, 0xE7, 0xC3, 0xC3, 0xC7, 0x7E, 0x3C, 0x3C, 0x3C, 0x3C, 0x7E,
|
|
||||||
0xE7, 0xC3, 0xC3, 0xC7, 0x7E, 0x3C, 0x18, 0x18, 0xFF, 0xFF, 0x10, 0x18, 0x3F, 0x7F, 0xEF, 0xDF, 0xFB, 0xF7, 0xFE,
|
|
||||||
0xFC, 0x61, 0xC3, 0x23, 0xCF, 0x3C, 0xF3, 0xCF, 0xF7, 0x80, 0x18, 0xE3, 0x23, 0xCF, 0x3C, 0xF3, 0xCF, 0xF7, 0x80,
|
|
||||||
0x31, 0xE7, 0xA3, 0xCF, 0x3C, 0xF3, 0xCF, 0xF7, 0x80, 0x79, 0xE8, 0xF3, 0xCF, 0x3C, 0xF3, 0xFD, 0xE0, 0x0C, 0x1C,
|
|
||||||
0x18, 0x83, 0xC7, 0x66, 0x6E, 0x3C, 0x3C, 0x18, 0x18, 0x18, 0x70, 0x60, 0xC1, 0x83, 0xE7, 0xEE, 0xF8, 0xF1, 0xE7,
|
|
||||||
0xFD, 0xF3, 0x06, 0x08, 0x00, 0x3C, 0x3C, 0x83, 0xC7, 0x66, 0x6E, 0x3C, 0x3C, 0x18, 0x18, 0x18, 0x70, 0x60, 0x7C,
|
|
||||||
0xF8, 0xE3, 0xEE, 0xF8, 0xF1, 0xFF, 0xFF, 0x8F, 0x1E, 0x30, 0x7C, 0xF9, 0xF7, 0xF8, 0x6F, 0xFF, 0xE3, 0xFE, 0xFC,
|
|
||||||
0x6C, 0xF8, 0xE1, 0xC7, 0xDD, 0xF1, 0xE3, 0xFF, 0xFF, 0x1E, 0x3C, 0x60, 0x6C, 0xF8, 0xE3, 0xEF, 0xF0, 0xDF, 0xFF,
|
|
||||||
0xC7, 0xFD, 0xF8, 0x38, 0x7C, 0xEE, 0xC6, 0xC6, 0xFE, 0xFE, 0xC6, 0xC6, 0xC6, 0x0C, 0x0C, 0x0F, 0x07, 0x7C, 0xFE,
|
|
||||||
0x86, 0x7E, 0xFE, 0xC6, 0xFE, 0x7E, 0x06, 0x0C, 0x0F, 0x0F, 0x0C, 0x0E, 0x06, 0x07, 0xE7, 0xFF, 0x0F, 0x01, 0x80,
|
|
||||||
0xC0, 0x60, 0x30, 0x6F, 0xF3, 0xF0, 0x0C, 0x38, 0x61, 0xE7, 0xFC, 0xF0, 0x60, 0xC4, 0xFC, 0xF0, 0x0C, 0x0F, 0x07,
|
|
||||||
0x87, 0xE7, 0xFF, 0x0F, 0x01, 0x80, 0xC0, 0x60, 0x30, 0x6F, 0xF3, 0xF0, 0x18, 0x78, 0xF1, 0xE7, 0xFC, 0xF0, 0x60,
|
|
||||||
0xC4, 0xFC, 0xF0, 0x0C, 0x06, 0x0F, 0xCF, 0xFE, 0x1E, 0x03, 0x01, 0x80, 0xC0, 0x60, 0xDF, 0xE7, 0xE0, 0x18, 0x30,
|
|
||||||
0xF3, 0xFE, 0x78, 0x30, 0x62, 0x7E, 0x78, 0x1E, 0x0F, 0x03, 0x07, 0xE7, 0xFF, 0x0F, 0x01, 0x80, 0xC0, 0x60, 0x30,
|
|
||||||
0x6F, 0xF3, 0xF0, 0x3C, 0x78, 0x61, 0xE7, 0xFC, 0xF0, 0x60, 0xC4, 0xFC, 0xF0, 0x78, 0x78, 0x30, 0xFC, 0xFE, 0xC7,
|
|
||||||
0xC3, 0xC3, 0xC3, 0xC3, 0xC7, 0xFE, 0xFC, 0x01, 0x83, 0xC1, 0xE7, 0xC7, 0xE7, 0x33, 0x19, 0x8C, 0xC6, 0x3F, 0x0F,
|
|
||||||
0x80, 0x7E, 0x3F, 0x98, 0xEC, 0x3F, 0xDF, 0xED, 0x86, 0xC7, 0x7F, 0x3F, 0x00, 0x06, 0x1F, 0x1F, 0x3E, 0x7E, 0xE6,
|
|
||||||
0xC6, 0xC6, 0xC6, 0x7E, 0x3E, 0x3C, 0x7B, 0xFF, 0xFC, 0x18, 0x3F, 0x7E, 0xC1, 0x83, 0xF7, 0xF0, 0x3C, 0x3C, 0x3C,
|
|
||||||
0x7E, 0xE7, 0xFF, 0xFF, 0xC0, 0x7E, 0x3F, 0x66, 0xFC, 0xF7, 0xFF, 0xF8, 0x30, 0x7E, 0xFD, 0x83, 0x07, 0xEF, 0xE0,
|
|
||||||
0x66, 0x7E, 0x3C, 0x3C, 0x7E, 0xE7, 0xFF, 0xFF, 0xC0, 0x7E, 0x3F, 0x18, 0x33, 0xFF, 0xFC, 0x18, 0x3F, 0x7E, 0xC1,
|
|
||||||
0x83, 0xF7, 0xF0, 0x18, 0x18, 0x3C, 0x7E, 0xE7, 0xFF, 0xFF, 0xC0, 0x7E, 0x3F, 0xFE, 0xFE, 0xC0, 0xC0, 0xFC, 0xFC,
|
|
||||||
0xC0, 0xC0, 0xFC, 0xFE, 0x06, 0x0C, 0x0F, 0x0F, 0x3C, 0x7E, 0xE7, 0xFF, 0xFF, 0xC0, 0x7E, 0x3F, 0x06, 0x0C, 0x0F,
|
|
||||||
0x07, 0x3C, 0x78, 0x67, 0xFF, 0xF8, 0x30, 0x7E, 0xFD, 0x83, 0x07, 0xEF, 0xE0, 0x3C, 0x3C, 0x18, 0x3C, 0x7E, 0xE7,
|
|
||||||
0xFF, 0xFF, 0xC0, 0x7E, 0x3F, 0x0C, 0x0F, 0x07, 0x87, 0xE7, 0xFF, 0x0F, 0x01, 0x8F, 0xC7, 0xE0, 0xF0, 0x6F, 0xF3,
|
|
||||||
0xF0, 0x18, 0x78, 0xF1, 0xF7, 0xFC, 0xF1, 0xE3, 0xC6, 0xFC, 0xF8, 0x30, 0x6F, 0x9E, 0x00, 0x36, 0x1F, 0x07, 0x07,
|
|
||||||
0xE7, 0xFF, 0x0F, 0x01, 0x8F, 0xC7, 0xE0, 0xF0, 0x6F, 0xF3, 0xF0, 0x36, 0x7C, 0x71, 0xF7, 0xFC, 0xF1, 0xE3, 0xC6,
|
|
||||||
0xFC, 0xF8, 0x30, 0x6F, 0x9E, 0x00, 0x0C, 0x06, 0x0F, 0xCF, 0xFE, 0x1E, 0x03, 0x1F, 0x8F, 0xC1, 0xE0, 0xDF, 0xE7,
|
|
||||||
0xE0, 0x18, 0x30, 0xFB, 0xFE, 0x78, 0xF1, 0xE3, 0x7E, 0x7C, 0x18, 0x37, 0xCF, 0x00, 0x3F, 0x3F, 0xF8, 0x78, 0x0C,
|
|
||||||
0x7E, 0x3F, 0x07, 0x83, 0x7F, 0x9F, 0x83, 0x00, 0xC1, 0xC0, 0xE0, 0x18, 0x30, 0x61, 0xF7, 0xFC, 0xF1, 0xE3, 0xC6,
|
|
||||||
0xFC, 0xF8, 0x30, 0x6F, 0x9E, 0x00, 0x18, 0x3C, 0x3C, 0xC3, 0xC3, 0xC3, 0xC3, 0xFF, 0xFF, 0xC3, 0xC3, 0xC3, 0xC3,
|
|
||||||
0x31, 0xE7, 0xB0, 0xC3, 0xEF, 0xFB, 0xCF, 0x3C, 0xF3, 0xCC, 0x61, 0xBF, 0xFF, 0xFD, 0x86, 0x7F, 0x9F, 0xE6, 0x19,
|
|
||||||
0x86, 0x61, 0x98, 0x60, 0x61, 0xF3, 0xE3, 0xE7, 0xEE, 0xD9, 0xB3, 0x66, 0xCD, 0x98, 0x7F, 0xEC, 0xC6, 0x31, 0x8C,
|
|
||||||
0x63, 0x18, 0xC6, 0x00, 0x7F, 0xEC, 0x86, 0x31, 0x8C, 0x63, 0x18, 0xFF, 0x66, 0x66, 0x66, 0x66, 0x66, 0xFF, 0x46,
|
|
||||||
0x66, 0x66, 0x66, 0x9F, 0xDC, 0xC6, 0x31, 0x8C, 0x63, 0x18, 0xC6, 0x00, 0x9F, 0xDC, 0x86, 0x31, 0x8C, 0x63, 0x18,
|
|
||||||
0x66, 0x66, 0x66, 0x66, 0x66, 0x6C, 0xF6, 0x66, 0x46, 0x66, 0x66, 0x66, 0x6C, 0xF6, 0xEF, 0xFF, 0xFF, 0xBF, 0xFF,
|
|
||||||
0xC3, 0xC3, 0xC3, 0xC3, 0xC3, 0xC3, 0xE3, 0xF3, 0xFF, 0xDE, 0xDE, 0xE7, 0xBD, 0xEF, 0x7B, 0xDE, 0xC6, 0x33, 0x10,
|
|
||||||
0x0C, 0x3C, 0x78, 0x60, 0xC1, 0x83, 0x06, 0x0D, 0x1B, 0x37, 0xE7, 0x80, 0x6F, 0xB4, 0x66, 0x66, 0x66, 0x66, 0x6C,
|
|
||||||
0x80, 0xC3, 0xC7, 0xCE, 0xDC, 0xF8, 0xF8, 0xDC, 0xCC, 0xC6, 0xC3, 0x38, 0x1C, 0x38, 0x30, 0xC3, 0x0C, 0xF7, 0xFB,
|
|
||||||
0xCE, 0x3C, 0xDB, 0x37, 0x0E, 0x71, 0x80, 0x8F, 0x7F, 0xBC, 0xE3, 0xCD, 0xB3, 0x30, 0xE1, 0x86, 0x0C, 0x18, 0x30,
|
|
||||||
0x60, 0xC1, 0x83, 0x07, 0xEF, 0xE0, 0x7A, 0x6D, 0xB6, 0xDB, 0x6C, 0xC1, 0x83, 0x06, 0x0C, 0x18, 0x30, 0x60, 0xFD,
|
|
||||||
0xFD, 0xC1, 0xC7, 0x0C, 0x00, 0x66, 0x66, 0x66, 0x66, 0x66, 0xEF, 0xEC, 0x0D, 0x9B, 0x36, 0x6C, 0x18, 0x30, 0x60,
|
|
||||||
0xC1, 0xFB, 0xF8, 0x3F, 0xFF, 0xCC, 0xCC, 0xCC, 0xC0, 0xC1, 0x83, 0x06, 0x0C, 0xD9, 0xB0, 0x60, 0xFD, 0xFC, 0xCC,
|
|
||||||
0xCC, 0xFF, 0xCC, 0xCC, 0x60, 0x60, 0x78, 0x78, 0xF0, 0xE0, 0x60, 0x60, 0x7E, 0x7F, 0x66, 0x67, 0xFE, 0x66, 0x66,
|
|
||||||
0x0C, 0x1C, 0x18, 0xC3, 0xE3, 0xF3, 0xF3, 0xFB, 0xDF, 0xCF, 0xCF, 0xC7, 0xC3, 0x18, 0x63, 0x8C, 0x7B, 0xFC, 0xF3,
|
|
||||||
0xCF, 0x3C, 0xF3, 0xC3, 0xE3, 0xF3, 0xF3, 0xFB, 0xDF, 0xCF, 0xCF, 0xC7, 0xC3, 0x38, 0x1C, 0x38, 0x30, 0x7B, 0xFC,
|
|
||||||
0xF3, 0xCF, 0x3C, 0xF3, 0x70, 0xE7, 0x18, 0x3C, 0x3C, 0x18, 0xC3, 0xE3, 0xF3, 0xF3, 0xFB, 0xDF, 0xCF, 0xCF, 0xC7,
|
|
||||||
0xC3, 0x79, 0xE3, 0x1E, 0xFF, 0x3C, 0xF3, 0xCF, 0x3C, 0xC0, 0x81, 0x83, 0x05, 0xE7, 0xEC, 0xD9, 0xB3, 0x66, 0xCD,
|
|
||||||
0x98, 0xC3, 0xE3, 0xF3, 0xF3, 0xFB, 0xDF, 0xCF, 0xCF, 0xC7, 0xC3, 0x03, 0x03, 0x03, 0x7B, 0xFC, 0xF3, 0xCF, 0x3C,
|
|
||||||
0xF3, 0x0C, 0x31, 0x84, 0x3E, 0x1F, 0x0F, 0x8F, 0xEE, 0x3E, 0x0F, 0x07, 0x83, 0xC1, 0xE1, 0xDF, 0xC7, 0xC0, 0x3C,
|
|
||||||
0x3C, 0x3C, 0x7E, 0xE7, 0xC3, 0xC3, 0xC7, 0x7E, 0x3C, 0x36, 0x1F, 0x07, 0x07, 0xC7, 0xF7, 0x1F, 0x07, 0x83, 0xC1,
|
|
||||||
0xE0, 0xF0, 0xEF, 0xE3, 0xE0, 0x36, 0x3E, 0x1C, 0x3C, 0x7E, 0xE7, 0xC3, 0xC3, 0xC7, 0x7E, 0x3C, 0x1B, 0x1F, 0x8D,
|
|
||||||
0x87, 0xC7, 0xF7, 0x1F, 0x07, 0x83, 0xC1, 0xE0, 0xF0, 0xEF, 0xE3, 0xE0, 0x1E, 0x3E, 0x3C, 0x3C, 0x7E, 0xE7, 0xC3,
|
|
||||||
0xC3, 0xC7, 0x7E, 0x3C, 0x3F, 0xFB, 0xFF, 0xF9, 0xC1, 0x86, 0x0C, 0x3F, 0x61, 0xFB, 0x0C, 0x18, 0x60, 0xC7, 0x03,
|
|
||||||
0xFF, 0x0F, 0xFC, 0x3D, 0xE3, 0xFF, 0xB9, 0xCF, 0x87, 0xFC, 0x3F, 0xE3, 0x85, 0xFF, 0xE7, 0xBE, 0x18, 0x38, 0x30,
|
|
||||||
0xFE, 0xFF, 0xC3, 0xC7, 0xFE, 0xFE, 0xC7, 0xC3, 0xC3, 0xC3, 0x33, 0x98, 0xEF, 0xEF, 0x18, 0xC6, 0x30, 0xFE, 0xFF,
|
|
||||||
0xC3, 0xC7, 0xFE, 0xFE, 0xC7, 0xC3, 0xC3, 0xC3, 0x38, 0x1C, 0x38, 0x30, 0x77, 0xF7, 0x8C, 0x63, 0x18, 0xE3, 0xB9,
|
|
||||||
0x80, 0x3C, 0x3C, 0x18, 0xFE, 0xFF, 0xC3, 0xC7, 0xFE, 0xFE, 0xC7, 0xC3, 0xC3, 0xC3, 0xF7, 0x98, 0xEF, 0xEF, 0x18,
|
|
||||||
0xC6, 0x30, 0x18, 0x70, 0xC3, 0xEF, 0xF8, 0xFC, 0x3E, 0x1E, 0x0E, 0x1F, 0xF7, 0xC0, 0x18, 0x70, 0xC3, 0xEF, 0xF8,
|
|
||||||
0xFF, 0x3F, 0x87, 0xFD, 0xF0, 0x18, 0x78, 0xF3, 0xEF, 0xF8, 0xFC, 0x3E, 0x1E, 0x0E, 0x1F, 0xF7, 0xC0, 0x18, 0x78,
|
|
||||||
0xF3, 0xEF, 0xF8, 0xFF, 0x3F, 0x87, 0xFD, 0xF0, 0x7D, 0xFF, 0x1F, 0x87, 0xC3, 0xC1, 0xC3, 0xFE, 0xF8, 0xC0, 0xC7,
|
|
||||||
0x0C, 0x00, 0x7D, 0xFF, 0x1F, 0xE7, 0xF0, 0xFF, 0xBE, 0x18, 0x18, 0xE1, 0x80, 0x3C, 0x78, 0x63, 0xEF, 0xF8, 0xFC,
|
|
||||||
0x3E, 0x1E, 0x0E, 0x1F, 0xF7, 0xC0, 0x3C, 0x78, 0x63, 0xEF, 0xF8, 0xFF, 0x3F, 0x87, 0xFD, 0xF0, 0xFF, 0xFF, 0xC6,
|
|
||||||
0x03, 0x01, 0x80, 0xC0, 0x60, 0x30, 0x18, 0x0C, 0x06, 0x01, 0x83, 0x81, 0x80, 0x63, 0x3D, 0xE6, 0x31, 0x8C, 0x71,
|
|
||||||
0xCC, 0x37, 0x30, 0x3C, 0x3C, 0x18, 0xFF, 0xFF, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x0D, 0xB6, 0xFF,
|
|
||||||
0xF1, 0x86, 0x18, 0x61, 0xC3, 0x80, 0xFF, 0xFF, 0x18, 0x18, 0x7E, 0x7E, 0x18, 0x18, 0x18, 0x18, 0x63, 0x3D, 0xE6,
|
|
||||||
0x73, 0xCC, 0x71, 0xC0, 0x1E, 0x3E, 0x3C, 0xC3, 0xC3, 0xC3, 0xC3, 0xC3, 0xC3, 0xC3, 0xC7, 0x7E, 0x3C, 0x3D, 0xF7,
|
|
||||||
0xA3, 0xCF, 0x3C, 0xF3, 0xCF, 0xF7, 0x80, 0x3C, 0x3C, 0xC3, 0xC3, 0xC3, 0xC3, 0xC3, 0xC3, 0xC3, 0xC7, 0x7E, 0x3C,
|
|
||||||
0x79, 0xE8, 0xF3, 0xCF, 0x3C, 0xF3, 0xFD, 0xE0, 0x36, 0x3E, 0x1C, 0xC3, 0xC3, 0xC3, 0xC3, 0xC3, 0xC3, 0xC3, 0xC7,
|
|
||||||
0x7E, 0x3C, 0x6D, 0xF3, 0xA3, 0xCF, 0x3C, 0xF3, 0xCF, 0xF7, 0x80, 0x18, 0x3C, 0x3C, 0xDB, 0xC3, 0xC3, 0xC3, 0xC3,
|
|
||||||
0xC3, 0xC3, 0xC7, 0x7E, 0x3C, 0x31, 0xE7, 0xAF, 0xCF, 0x3C, 0xF3, 0xCF, 0xF7, 0x80, 0x1E, 0x3E, 0x3C, 0xC3, 0xC3,
|
|
||||||
0xC3, 0xC3, 0xC3, 0xC3, 0xC3, 0xC7, 0x7E, 0x3C, 0x3D, 0xF7, 0xA3, 0xCF, 0x3C, 0xF3, 0xCF, 0xF7, 0x80, 0xC3, 0xC3,
|
|
||||||
0xC3, 0xC3, 0xC3, 0xC3, 0xC3, 0xC7, 0x7E, 0x3C, 0x18, 0x30, 0x3C, 0x1C, 0x8D, 0x9B, 0x36, 0x6C, 0xD9, 0xBF, 0x3E,
|
|
||||||
0x0C, 0x30, 0x78, 0x70, 0x03, 0x00, 0x1E, 0x00, 0x78, 0x20, 0xC3, 0xC3, 0x0F, 0x0C, 0x3C, 0x79, 0xD9, 0xE6, 0x6F,
|
|
||||||
0xF8, 0xF3, 0xC3, 0xCF, 0x0F, 0x3C, 0x18, 0x60, 0x0C, 0x07, 0x81, 0xE2, 0x03, 0xCC, 0xF7, 0xF7, 0xF9, 0xFE, 0x7F,
|
|
||||||
0x8C, 0xC3, 0x30, 0x18, 0x3C, 0x3C, 0xC3, 0xC3, 0xE7, 0x7E, 0x3C, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x3C, 0x3C,
|
|
||||||
0x83, 0xC7, 0x66, 0x6E, 0x3C, 0x3C, 0x18, 0x18, 0x18, 0x70, 0x60, 0x3C, 0x3C, 0xC3, 0xC3, 0xE7, 0x7E, 0x3C, 0x18,
|
|
||||||
0x18, 0x18, 0x18, 0x18, 0x0C, 0x1C, 0x18, 0xFF, 0xFF, 0x07, 0x0E, 0x1C, 0x38, 0x70, 0xE0, 0xFE, 0xFF, 0x0C, 0x38,
|
|
||||||
0x67, 0xFF, 0xE3, 0x8E, 0x38, 0xE1, 0xFB, 0xF8, 0x0C, 0x0C, 0xFF, 0xFF, 0x07, 0x0E, 0x1C, 0x38, 0x70, 0xE0, 0xFE,
|
|
||||||
0xFF, 0x18, 0x33, 0xFF, 0xF1, 0xC7, 0x1C, 0x70, 0xFD, 0xFC, 0x3C, 0x3C, 0x18, 0xFF, 0xFF, 0x07, 0x0E, 0x1C, 0x38,
|
|
||||||
0x70, 0xE0, 0xFE, 0xFF, 0x3C, 0x78, 0x67, 0xFF, 0xE3, 0x8E, 0x38, 0xE1, 0xFB, 0xF8, 0x1E, 0x3F, 0x73, 0xFE, 0xFE,
|
|
||||||
0xFE, 0xFE, 0x62, 0x3F, 0x1E,
|
|
||||||
};
|
|
||||||
|
|
||||||
static const EpdGlyph babyblueGlyphs[] = {
|
|
||||||
{0, 0, 5, 0, 0, 0, 0}, //
|
|
||||||
{2, 10, 3, 1, 10, 3, 0}, // !
|
|
||||||
{4, 5, 5, 1, 11, 3, 3}, // "
|
|
||||||
{9, 11, 10, 0, 11, 13, 6}, // #
|
|
||||||
{8, 14, 9, 0, 12, 14, 19}, // $
|
|
||||||
{11, 11, 13, 1, 11, 16, 33}, // %
|
|
||||||
{9, 11, 11, 1, 11, 13, 49}, // &
|
|
||||||
{2, 4, 3, 1, 11, 1, 62}, // '
|
|
||||||
{4, 15, 5, 1, 11, 8, 63}, // (
|
|
||||||
{4, 15, 5, 1, 11, 8, 71}, // )
|
|
||||||
{6, 6, 6, 0, 11, 5, 79}, // *
|
|
||||||
{8, 8, 9, 0, 9, 8, 84}, // +
|
|
||||||
{2, 5, 3, 1, 3, 2, 92}, // ,
|
|
||||||
{5, 2, 5, 0, 5, 2, 94}, // -
|
|
||||||
{2, 2, 3, 1, 2, 1, 96}, // .
|
|
||||||
{6, 11, 6, 0, 11, 9, 97}, // /
|
|
||||||
{8, 11, 9, 0, 11, 11, 106}, // 0
|
|
||||||
{5, 11, 6, 1, 11, 7, 117}, // 1
|
|
||||||
{8, 11, 9, 0, 11, 11, 124}, // 2
|
|
||||||
{8, 11, 10, 1, 11, 11, 135}, // 3
|
|
||||||
{8, 11, 9, 0, 11, 11, 146}, // 4
|
|
||||||
{7, 11, 9, 1, 11, 10, 157}, // 5
|
|
||||||
{8, 11, 9, 0, 11, 11, 167}, // 6
|
|
||||||
{9, 11, 10, 0, 11, 13, 178}, // 7
|
|
||||||
{8, 11, 9, 0, 11, 11, 191}, // 8
|
|
||||||
{8, 11, 9, 0, 11, 11, 202}, // 9
|
|
||||||
{2, 8, 3, 1, 8, 2, 213}, // :
|
|
||||||
{2, 11, 3, 1, 8, 3, 215}, // ;
|
|
||||||
{7, 8, 9, 1, 9, 7, 218}, // <
|
|
||||||
{8, 5, 9, 0, 8, 5, 225}, // =
|
|
||||||
{7, 8, 7, 0, 9, 7, 230}, // >
|
|
||||||
{7, 11, 9, 1, 11, 10, 237}, // ?
|
|
||||||
{14, 15, 15, 0, 11, 27, 247}, // @
|
|
||||||
{7, 10, 9, 1, 10, 9, 274}, // A
|
|
||||||
{8, 10, 10, 1, 10, 10, 283}, // B
|
|
||||||
{9, 10, 11, 1, 10, 12, 293}, // C
|
|
||||||
{8, 10, 10, 1, 10, 10, 305}, // D
|
|
||||||
{7, 10, 9, 1, 10, 9, 315}, // E
|
|
||||||
{7, 10, 9, 1, 10, 9, 324}, // F
|
|
||||||
{9, 10, 11, 1, 10, 12, 333}, // G
|
|
||||||
{8, 10, 10, 1, 10, 10, 345}, // H
|
|
||||||
{2, 10, 3, 1, 10, 3, 355}, // I
|
|
||||||
{6, 10, 6, 0, 10, 8, 358}, // J
|
|
||||||
{8, 10, 10, 1, 10, 10, 366}, // K
|
|
||||||
{7, 10, 9, 1, 10, 9, 376}, // L
|
|
||||||
{10, 10, 12, 1, 10, 13, 385}, // M
|
|
||||||
{8, 10, 10, 1, 10, 10, 398}, // N
|
|
||||||
{9, 10, 11, 1, 10, 12, 408}, // O
|
|
||||||
{8, 10, 10, 1, 10, 10, 420}, // P
|
|
||||||
{9, 10, 11, 1, 10, 12, 430}, // Q
|
|
||||||
{8, 10, 10, 1, 10, 10, 442}, // R
|
|
||||||
{7, 10, 9, 1, 10, 9, 452}, // S
|
|
||||||
{8, 10, 9, 0, 10, 10, 461}, // T
|
|
||||||
{8, 10, 10, 1, 10, 10, 471}, // U
|
|
||||||
{8, 10, 10, 1, 10, 10, 481}, // V
|
|
||||||
{14, 10, 15, 0, 10, 18, 491}, // W
|
|
||||||
{10, 10, 11, 0, 10, 13, 509}, // X
|
|
||||||
{8, 10, 10, 1, 10, 10, 522}, // Y
|
|
||||||
{8, 10, 9, 0, 10, 10, 532}, // Z
|
|
||||||
{4, 14, 5, 1, 10, 7, 542}, // [
|
|
||||||
{7, 10, 7, 0, 10, 9, 549}, // <backslash>
|
|
||||||
{4, 14, 4, 0, 10, 7, 558}, // ]
|
|
||||||
{8, 7, 9, 0, 11, 7, 565}, // ^
|
|
||||||
{8, 2, 9, 0, -2, 2, 572}, // _
|
|
||||||
{3, 3, 3, 0, 11, 2, 574}, // `
|
|
||||||
{7, 8, 7, 0, 8, 7, 576}, // a
|
|
||||||
{7, 10, 9, 1, 10, 9, 583}, // b
|
|
||||||
{7, 8, 7, 0, 8, 7, 592}, // c
|
|
||||||
{7, 10, 7, 0, 10, 9, 599}, // d
|
|
||||||
{8, 8, 9, 0, 8, 8, 608}, // e
|
|
||||||
{5, 11, 5, 0, 11, 7, 616}, // f
|
|
||||||
{7, 12, 7, 0, 8, 11, 623}, // g
|
|
||||||
{6, 10, 7, 1, 10, 8, 634}, // h
|
|
||||||
{2, 10, 3, 1, 10, 3, 642}, // i
|
|
||||||
{3, 14, 3, 0, 10, 6, 645}, // j
|
|
||||||
{6, 10, 7, 1, 10, 8, 651}, // k
|
|
||||||
{2, 10, 3, 1, 10, 3, 659}, // l
|
|
||||||
{10, 8, 12, 1, 8, 10, 662}, // m
|
|
||||||
{6, 8, 7, 1, 8, 6, 672}, // n
|
|
||||||
{8, 8, 9, 0, 8, 8, 678}, // o
|
|
||||||
{7, 11, 9, 1, 8, 10, 686}, // p
|
|
||||||
{7, 11, 7, 0, 8, 10, 696}, // q
|
|
||||||
{5, 8, 6, 1, 8, 5, 706}, // r
|
|
||||||
{7, 8, 7, 0, 8, 7, 711}, // s
|
|
||||||
{5, 10, 5, 0, 10, 7, 718}, // t
|
|
||||||
{6, 8, 7, 1, 8, 6, 725}, // u
|
|
||||||
{8, 8, 9, 0, 8, 8, 731}, // v
|
|
||||||
{10, 8, 11, 0, 8, 10, 739}, // w
|
|
||||||
{8, 8, 9, 0, 8, 8, 749}, // x
|
|
||||||
{8, 11, 9, 0, 8, 11, 757}, // y
|
|
||||||
{7, 8, 7, 0, 8, 7, 768}, // z
|
|
||||||
{5, 15, 5, 0, 11, 10, 775}, // {
|
|
||||||
{2, 15, 3, 1, 11, 4, 785}, // |
|
|
||||||
{6, 15, 6, 0, 11, 12, 789}, // }
|
|
||||||
{9, 3, 10, 0, 7, 4, 801}, // ~
|
|
||||||
{2, 12, 4, 2, 8, 3, 805}, // ¡
|
|
||||||
{7, 13, 7, 0, 10, 12, 808}, // ¢
|
|
||||||
{8, 10, 9, 0, 10, 10, 820}, // £
|
|
||||||
{8, 8, 9, 0, 9, 8, 830}, // ¤
|
|
||||||
{8, 10, 9, 0, 10, 10, 838}, // ¥
|
|
||||||
{2, 15, 3, 1, 11, 4, 848}, // ¦
|
|
||||||
{8, 15, 9, 0, 11, 15, 852}, // §
|
|
||||||
{5, 3, 5, 0, 11, 2, 867}, // ¨
|
|
||||||
{10, 11, 11, 0, 11, 14, 869}, // ©
|
|
||||||
{5, 6, 5, 0, 11, 4, 883}, // ª
|
|
||||||
{7, 7, 9, 1, 8, 7, 887}, // «
|
|
||||||
{8, 5, 9, 0, 8, 5, 894}, // ¬
|
|
||||||
{10, 11, 11, 0, 11, 14, 899}, // ®
|
|
||||||
{8, 2, 9, 0, 12, 2, 913}, // ¯
|
|
||||||
{4, 5, 5, 1, 11, 3, 915}, // °
|
|
||||||
{8, 9, 9, 0, 9, 9, 918}, // ±
|
|
||||||
{5, 8, 5, 0, 11, 5, 927}, // ²
|
|
||||||
{5, 6, 5, 0, 11, 4, 932}, // ³
|
|
||||||
{3, 3, 4, 1, 11, 2, 936}, // ´
|
|
||||||
{6, 12, 9, 2, 8, 9, 938}, // µ
|
|
||||||
{8, 14, 9, 0, 10, 14, 947}, // ¶
|
|
||||||
{2, 2, 3, 1, 6, 1, 961}, // ·
|
|
||||||
{4, 4, 4, 0, 0, 2, 962}, // ¸
|
|
||||||
{4, 7, 4, 0, 12, 4, 964}, // ¹
|
|
||||||
{6, 6, 6, 0, 11, 5, 968}, // º
|
|
||||||
{7, 7, 9, 1, 8, 7, 973}, // »
|
|
||||||
{12, 12, 13, 0, 12, 18, 980}, // ¼
|
|
||||||
{12, 11, 13, 0, 11, 17, 998}, // ½
|
|
||||||
{12, 11, 13, 0, 11, 17, 1015}, // ¾
|
|
||||||
{7, 12, 9, 1, 8, 11, 1032}, // ¿
|
|
||||||
{7, 13, 9, 1, 13, 12, 1043}, // À
|
|
||||||
{7, 13, 9, 1, 13, 12, 1055}, // Á
|
|
||||||
{7, 13, 9, 1, 13, 12, 1067}, // Â
|
|
||||||
{7, 13, 9, 1, 13, 12, 1079}, // Ã
|
|
||||||
{7, 12, 9, 1, 12, 11, 1091}, // Ä
|
|
||||||
{7, 13, 9, 1, 13, 12, 1102}, // Å
|
|
||||||
{13, 11, 14, 0, 11, 18, 1114}, // Æ
|
|
||||||
{9, 14, 11, 1, 10, 16, 1132}, // Ç
|
|
||||||
{7, 13, 9, 1, 13, 12, 1148}, // È
|
|
||||||
{7, 13, 9, 1, 13, 12, 1160}, // É
|
|
||||||
{7, 13, 9, 1, 13, 12, 1172}, // Ê
|
|
||||||
{7, 12, 9, 1, 12, 11, 1184}, // Ë
|
|
||||||
{3, 13, 3, 0, 13, 5, 1195}, // Ì
|
|
||||||
{3, 13, 4, 1, 13, 5, 1200}, // Í
|
|
||||||
{4, 13, 4, 0, 13, 7, 1205}, // Î
|
|
||||||
{4, 12, 4, 0, 12, 6, 1212}, // Ï
|
|
||||||
{9, 10, 10, 0, 10, 12, 1218}, // Ð
|
|
||||||
{8, 13, 10, 1, 13, 13, 1230}, // Ñ
|
|
||||||
{9, 13, 11, 1, 13, 15, 1243}, // Ò
|
|
||||||
{9, 13, 11, 1, 13, 15, 1258}, // Ó
|
|
||||||
{9, 13, 11, 1, 13, 15, 1273}, // Ô
|
|
||||||
{9, 13, 11, 1, 13, 15, 1288}, // Õ
|
|
||||||
{9, 12, 11, 1, 12, 14, 1303}, // Ö
|
|
||||||
{6, 6, 7, 1, 8, 5, 1317}, // ×
|
|
||||||
{10, 10, 11, 0, 10, 13, 1322}, // Ø
|
|
||||||
{8, 13, 10, 1, 13, 13, 1335}, // Ù
|
|
||||||
{8, 13, 10, 1, 13, 13, 1348}, // Ú
|
|
||||||
{8, 13, 10, 1, 13, 13, 1361}, // Û
|
|
||||||
{8, 12, 10, 1, 12, 12, 1374}, // Ü
|
|
||||||
{8, 13, 10, 1, 13, 13, 1386}, // Ý
|
|
||||||
{8, 10, 10, 1, 10, 10, 1399}, // Þ
|
|
||||||
{7, 11, 9, 1, 11, 10, 1409}, // ß
|
|
||||||
{7, 11, 7, 0, 11, 10, 1419}, // à
|
|
||||||
{7, 11, 7, 0, 11, 10, 1429}, // á
|
|
||||||
{7, 11, 7, 0, 11, 10, 1439}, // â
|
|
||||||
{7, 11, 7, 0, 11, 10, 1449}, // ã
|
|
||||||
{7, 10, 7, 0, 10, 9, 1459}, // ä
|
|
||||||
{7, 12, 7, 0, 12, 11, 1468}, // å
|
|
||||||
{12, 8, 13, 0, 8, 12, 1479}, // æ
|
|
||||||
{7, 12, 7, 0, 8, 11, 1491}, // ç
|
|
||||||
{8, 11, 9, 0, 11, 11, 1502}, // è
|
|
||||||
{8, 11, 9, 0, 11, 11, 1513}, // é
|
|
||||||
{8, 11, 9, 0, 11, 11, 1524}, // ê
|
|
||||||
{8, 10, 9, 0, 10, 10, 1535}, // ë
|
|
||||||
{3, 11, 3, 0, 11, 5, 1545}, // ì
|
|
||||||
{3, 11, 4, 1, 11, 5, 1550}, // í
|
|
||||||
{4, 11, 4, 0, 11, 6, 1555}, // î
|
|
||||||
{4, 10, 4, 0, 10, 5, 1561}, // ï
|
|
||||||
{8, 11, 9, 0, 11, 11, 1566}, // ð
|
|
||||||
{6, 11, 7, 1, 11, 9, 1577}, // ñ
|
|
||||||
{8, 11, 9, 0, 11, 11, 1586}, // ò
|
|
||||||
{8, 11, 9, 0, 11, 11, 1597}, // ó
|
|
||||||
{8, 11, 9, 0, 11, 11, 1608}, // ô
|
|
||||||
{8, 11, 9, 0, 11, 11, 1619}, // õ
|
|
||||||
{8, 10, 9, 0, 10, 10, 1630}, // ö
|
|
||||||
{8, 6, 9, 0, 8, 6, 1640}, // ÷
|
|
||||||
{8, 8, 9, 0, 8, 8, 1646}, // ø
|
|
||||||
{6, 11, 7, 1, 11, 9, 1654}, // ù
|
|
||||||
{6, 11, 7, 1, 11, 9, 1663}, // ú
|
|
||||||
{6, 11, 7, 1, 11, 9, 1672}, // û
|
|
||||||
{6, 10, 7, 1, 10, 8, 1681}, // ü
|
|
||||||
{8, 14, 9, 0, 11, 14, 1689}, // ý
|
|
||||||
{7, 13, 9, 1, 10, 12, 1703}, // þ
|
|
||||||
{8, 13, 9, 0, 10, 13, 1715}, // ÿ
|
|
||||||
{7, 12, 9, 1, 12, 11, 1728}, // Ā
|
|
||||||
{7, 10, 7, 0, 10, 9, 1739}, // ā
|
|
||||||
{7, 13, 9, 1, 13, 12, 1748}, // Ă
|
|
||||||
{7, 11, 7, 0, 11, 10, 1760}, // ă
|
|
||||||
{8, 14, 10, 1, 10, 14, 1770}, // Ą
|
|
||||||
{8, 12, 9, 0, 8, 12, 1784}, // ą
|
|
||||||
{9, 13, 11, 1, 13, 15, 1796}, // Ć
|
|
||||||
{7, 11, 7, 0, 11, 10, 1811}, // ć
|
|
||||||
{9, 13, 11, 1, 13, 15, 1821}, // Ĉ
|
|
||||||
{7, 11, 7, 0, 11, 10, 1836}, // ĉ
|
|
||||||
{9, 12, 11, 1, 12, 14, 1846}, // Ċ
|
|
||||||
{7, 10, 7, 0, 10, 9, 1860}, // ċ
|
|
||||||
{9, 13, 11, 1, 13, 15, 1869}, // Č
|
|
||||||
{7, 11, 7, 0, 11, 10, 1884}, // č
|
|
||||||
{8, 13, 10, 1, 13, 13, 1894}, // Ď
|
|
||||||
{9, 11, 10, 0, 11, 13, 1907}, // ď
|
|
||||||
{9, 10, 10, 0, 10, 12, 1920}, // Đ
|
|
||||||
{8, 11, 9, 0, 11, 11, 1932}, // đ
|
|
||||||
{7, 12, 9, 1, 12, 11, 1943}, // Ē
|
|
||||||
{8, 10, 9, 0, 10, 10, 1954}, // ē
|
|
||||||
{7, 13, 9, 1, 13, 12, 1964}, // Ĕ
|
|
||||||
{8, 11, 9, 0, 11, 11, 1976}, // ĕ
|
|
||||||
{7, 12, 9, 1, 12, 11, 1987}, // Ė
|
|
||||||
{8, 10, 9, 0, 10, 10, 1998}, // ė
|
|
||||||
{8, 14, 10, 1, 10, 14, 2008}, // Ę
|
|
||||||
{8, 12, 9, 0, 8, 12, 2022}, // ę
|
|
||||||
{7, 13, 9, 1, 13, 12, 2034}, // Ě
|
|
||||||
{8, 11, 9, 0, 11, 11, 2046}, // ě
|
|
||||||
{9, 13, 11, 1, 13, 15, 2057}, // Ĝ
|
|
||||||
{7, 15, 7, 0, 11, 14, 2072}, // ĝ
|
|
||||||
{9, 13, 11, 1, 13, 15, 2086}, // Ğ
|
|
||||||
{7, 15, 7, 0, 11, 14, 2101}, // ğ
|
|
||||||
{9, 12, 11, 1, 12, 14, 2115}, // Ġ
|
|
||||||
{7, 14, 7, 0, 10, 13, 2129}, // ġ
|
|
||||||
{9, 14, 11, 1, 10, 16, 2142}, // Ģ
|
|
||||||
{7, 15, 7, 0, 11, 14, 2158}, // ģ
|
|
||||||
{8, 13, 10, 1, 13, 13, 2172}, // Ĥ
|
|
||||||
{6, 13, 7, 1, 13, 10, 2185}, // ĥ
|
|
||||||
{10, 10, 11, 0, 10, 13, 2195}, // Ħ
|
|
||||||
{7, 11, 7, 0, 11, 10, 2208}, // ħ
|
|
||||||
{5, 13, 5, 0, 13, 9, 2218}, // Ĩ
|
|
||||||
{5, 11, 5, 0, 11, 7, 2227}, // ĩ
|
|
||||||
{4, 12, 4, 0, 12, 6, 2234}, // Ī
|
|
||||||
{4, 10, 4, 0, 10, 5, 2240}, // ī
|
|
||||||
{5, 13, 5, 0, 13, 9, 2245}, // Ĭ
|
|
||||||
{5, 11, 5, 0, 11, 7, 2254}, // ĭ
|
|
||||||
{4, 14, 4, 0, 10, 7, 2261}, // Į
|
|
||||||
{4, 14, 4, 0, 10, 7, 2268}, // į
|
|
||||||
{2, 12, 3, 1, 12, 3, 2275}, // İ
|
|
||||||
{2, 8, 3, 1, 8, 2, 2278}, // ı
|
|
||||||
{8, 10, 10, 1, 10, 10, 2280}, // IJ
|
|
||||||
{5, 14, 6, 1, 10, 9, 2290}, // ij
|
|
||||||
{7, 13, 7, 0, 13, 12, 2299}, // Ĵ
|
|
||||||
{4, 15, 4, 0, 11, 8, 2311}, // ĵ
|
|
||||||
{8, 14, 10, 1, 10, 14, 2319}, // Ķ
|
|
||||||
{6, 14, 7, 1, 10, 11, 2333}, // ķ
|
|
||||||
{6, 8, 7, 1, 8, 6, 2344}, // ĸ
|
|
||||||
{7, 13, 9, 1, 13, 12, 2350}, // Ĺ
|
|
||||||
{3, 13, 4, 1, 13, 5, 2362}, // ĺ
|
|
||||||
{7, 14, 9, 1, 10, 13, 2367}, // Ļ
|
|
||||||
{4, 14, 4, 0, 10, 7, 2380}, // ļ
|
|
||||||
{7, 11, 9, 1, 11, 10, 2387}, // Ľ
|
|
||||||
{4, 11, 5, 1, 11, 6, 2397}, // ľ
|
|
||||||
{7, 10, 9, 1, 10, 9, 2403}, // Ŀ
|
|
||||||
{4, 10, 5, 1, 10, 5, 2412}, // ŀ
|
|
||||||
{8, 10, 9, 0, 10, 10, 2417}, // Ł
|
|
||||||
{4, 10, 4, 0, 10, 5, 2427}, // ł
|
|
||||||
{8, 13, 10, 1, 13, 13, 2432}, // Ń
|
|
||||||
{6, 12, 7, 1, 12, 9, 2445}, // ń
|
|
||||||
{8, 14, 10, 1, 10, 14, 2454}, // Ņ
|
|
||||||
{6, 12, 7, 1, 8, 9, 2468}, // ņ
|
|
||||||
{8, 13, 10, 1, 13, 13, 2477}, // Ň
|
|
||||||
{6, 11, 7, 1, 11, 9, 2490}, // ň
|
|
||||||
{7, 11, 7, 0, 11, 10, 2499}, // ʼn
|
|
||||||
{8, 13, 10, 1, 10, 13, 2509}, // Ŋ
|
|
||||||
{6, 12, 7, 1, 8, 9, 2522}, // ŋ
|
|
||||||
{9, 12, 11, 1, 12, 14, 2531}, // Ō
|
|
||||||
{8, 10, 9, 0, 10, 10, 2545}, // ō
|
|
||||||
{9, 13, 11, 1, 13, 15, 2555}, // Ŏ
|
|
||||||
{8, 11, 9, 0, 11, 11, 2570}, // ŏ
|
|
||||||
{9, 13, 11, 1, 13, 15, 2581}, // Ő
|
|
||||||
{8, 11, 9, 0, 11, 11, 2596}, // ő
|
|
||||||
{13, 11, 15, 1, 11, 18, 2607}, // Œ
|
|
||||||
{13, 8, 14, 0, 8, 13, 2625}, // œ
|
|
||||||
{8, 13, 10, 1, 13, 13, 2638}, // Ŕ
|
|
||||||
{5, 11, 6, 1, 11, 7, 2651}, // ŕ
|
|
||||||
{8, 14, 10, 1, 10, 14, 2658}, // Ŗ
|
|
||||||
{5, 12, 6, 1, 8, 8, 2672}, // ŗ
|
|
||||||
{8, 13, 10, 1, 13, 13, 2680}, // Ř
|
|
||||||
{5, 11, 6, 1, 11, 7, 2693}, // ř
|
|
||||||
{7, 13, 9, 1, 13, 12, 2700}, // Ś
|
|
||||||
{7, 11, 7, 0, 11, 10, 2712}, // ś
|
|
||||||
{7, 13, 9, 1, 13, 12, 2722}, // Ŝ
|
|
||||||
{7, 11, 7, 0, 11, 10, 2734}, // ŝ
|
|
||||||
{7, 14, 9, 1, 10, 13, 2744}, // Ş
|
|
||||||
{7, 12, 7, 0, 8, 11, 2757}, // ş
|
|
||||||
{7, 13, 9, 1, 13, 12, 2768}, // Š
|
|
||||||
{7, 11, 7, 0, 11, 10, 2780}, // š
|
|
||||||
{9, 14, 10, 0, 10, 16, 2790}, // Ţ
|
|
||||||
{5, 14, 5, 0, 10, 9, 2806}, // ţ
|
|
||||||
{8, 13, 9, 0, 13, 13, 2815}, // Ť
|
|
||||||
{6, 11, 6, 0, 11, 9, 2828}, // ť
|
|
||||||
{8, 10, 9, 0, 10, 10, 2837}, // Ŧ
|
|
||||||
{5, 10, 5, 0, 10, 7, 2847}, // ŧ
|
|
||||||
{8, 13, 10, 1, 13, 13, 2854}, // Ũ
|
|
||||||
{6, 11, 7, 1, 11, 9, 2867}, // ũ
|
|
||||||
{8, 12, 10, 1, 12, 12, 2876}, // Ū
|
|
||||||
{6, 10, 7, 1, 10, 8, 2888}, // ū
|
|
||||||
{8, 13, 10, 1, 13, 13, 2896}, // Ŭ
|
|
||||||
{6, 11, 7, 1, 11, 9, 2909}, // ŭ
|
|
||||||
{8, 13, 10, 1, 13, 13, 2918}, // Ů
|
|
||||||
{6, 11, 7, 1, 11, 9, 2931}, // ů
|
|
||||||
{8, 13, 10, 1, 13, 13, 2940}, // Ű
|
|
||||||
{6, 11, 7, 1, 11, 9, 2953}, // ű
|
|
||||||
{8, 14, 10, 1, 10, 14, 2962}, // Ų
|
|
||||||
{7, 12, 9, 1, 8, 11, 2976}, // ų
|
|
||||||
{14, 13, 15, 0, 13, 23, 2987}, // Ŵ
|
|
||||||
{10, 11, 11, 0, 11, 14, 3010}, // ŵ
|
|
||||||
{8, 13, 10, 1, 13, 13, 3024}, // Ŷ
|
|
||||||
{8, 14, 9, 0, 11, 14, 3037}, // ŷ
|
|
||||||
{8, 12, 10, 1, 12, 12, 3051}, // Ÿ
|
|
||||||
{8, 13, 9, 0, 13, 13, 3063}, // Ź
|
|
||||||
{7, 11, 7, 0, 11, 10, 3076}, // ź
|
|
||||||
{8, 12, 9, 0, 12, 12, 3086}, // Ż
|
|
||||||
{7, 10, 7, 0, 10, 9, 3098}, // ż
|
|
||||||
{8, 13, 9, 0, 13, 13, 3107}, // Ž
|
|
||||||
{7, 11, 7, 0, 11, 10, 3120}, // ž
|
|
||||||
{8, 10, 9, 0, 10, 10, 3130}, // €
|
|
||||||
};
|
|
||||||
|
|
||||||
static const EpdUnicodeInterval babyblueIntervals[] = {
|
|
||||||
{0x20, 0x7E, 0x0}, {0xA1, 0xAC, 0x5F}, {0xAE, 0xFF, 0x6B}, {0x100, 0x17E, 0xBD}, {0x20AC, 0x20AC, 0x13C},
|
|
||||||
};
|
|
||||||
|
|
||||||
static const EpdFontData babyblue = {
|
|
||||||
babyblueBitmaps, babyblueGlyphs, babyblueIntervals, 5, 17, 13, -4,
|
|
||||||
};
|
|
||||||
@@ -13,12 +13,14 @@ parser = argparse.ArgumentParser(description="Generate a header file from a font
|
|||||||
parser.add_argument("name", action="store", help="name of the font.")
|
parser.add_argument("name", action="store", help="name of the font.")
|
||||||
parser.add_argument("size", type=int, help="font size to use.")
|
parser.add_argument("size", type=int, help="font size to use.")
|
||||||
parser.add_argument("fontstack", action="store", nargs='+', help="list of font files, ordered by descending priority.")
|
parser.add_argument("fontstack", action="store", nargs='+', help="list of font files, ordered by descending priority.")
|
||||||
|
parser.add_argument("--2bit", dest="is2Bit", action="store_true", help="generate 2-bit greyscale bitmap instead of 1-bit black and white.")
|
||||||
parser.add_argument("--additional-intervals", dest="additional_intervals", action="append", help="Additional code point intervals to export as min,max. This argument can be repeated.")
|
parser.add_argument("--additional-intervals", dest="additional_intervals", action="append", help="Additional code point intervals to export as min,max. This argument can be repeated.")
|
||||||
args = parser.parse_args()
|
args = parser.parse_args()
|
||||||
|
|
||||||
GlyphProps = namedtuple("GlyphProps", ["width", "height", "advance_x", "left", "top", "data_length", "data_offset", "code_point"])
|
GlyphProps = namedtuple("GlyphProps", ["width", "height", "advance_x", "left", "top", "data_length", "data_offset", "code_point"])
|
||||||
|
|
||||||
font_stack = [freetype.Face(f) for f in args.fontstack]
|
font_stack = [freetype.Face(f) for f in args.fontstack]
|
||||||
|
is2Bit = args.is2Bit
|
||||||
size = args.size
|
size = args.size
|
||||||
font_name = args.name
|
font_name = args.name
|
||||||
|
|
||||||
@@ -52,7 +54,7 @@ intervals = [
|
|||||||
# (0x0370, 0x03FF),
|
# (0x0370, 0x03FF),
|
||||||
### Cyrillic ###
|
### Cyrillic ###
|
||||||
# Russian, Ukrainian, Bulgarian, etc.
|
# Russian, Ukrainian, Bulgarian, etc.
|
||||||
# (0x0400, 0x04FF),
|
(0x0400, 0x04FF),
|
||||||
### Math Symbols (common subset) ###
|
### Math Symbols (common subset) ###
|
||||||
# General math operators
|
# General math operators
|
||||||
(0x2200, 0x22FF),
|
(0x2200, 0x22FF),
|
||||||
@@ -173,26 +175,73 @@ for i_start, i_end in intervals:
|
|||||||
pixels4g.append(px)
|
pixels4g.append(px)
|
||||||
px = 0
|
px = 0
|
||||||
|
|
||||||
# Downsample to 1-bit bitmap - treat any non-zero as black
|
if is2Bit:
|
||||||
pixelsbw = []
|
# 0-3 white, 4-7 light grey, 8-11 dark grey, 12-15 black
|
||||||
px = 0
|
# Downsample to 2-bit bitmap
|
||||||
pitch = (bitmap.width // 2) + (bitmap.width % 2)
|
pixels2b = []
|
||||||
for y in range(bitmap.rows):
|
px = 0
|
||||||
for x in range(bitmap.width):
|
pitch = (bitmap.width // 2) + (bitmap.width % 2)
|
||||||
px = px << 1
|
for y in range(bitmap.rows):
|
||||||
bm = pixels4g[y * pitch + (x // 2)]
|
for x in range(bitmap.width):
|
||||||
px += 1 if ((x & 1) == 0 and bm & 0xF > 0) or ((x & 1) == 1 and bm & 0xF0 > 0) else 0
|
px = px << 2
|
||||||
|
bm = pixels4g[y * pitch + (x // 2)]
|
||||||
|
bm = (bm >> ((x % 2) * 4)) & 0xF
|
||||||
|
|
||||||
if (y * bitmap.width + x) % 8 == 7:
|
if bm >= 12:
|
||||||
pixelsbw.append(px)
|
px += 3
|
||||||
px = 0
|
elif bm >= 8:
|
||||||
if (bitmap.width * bitmap.rows) % 8 != 0:
|
px += 2
|
||||||
px = px << (8 - (bitmap.width * bitmap.rows) % 8)
|
elif bm >= 4:
|
||||||
pixelsbw.append(px)
|
px += 1
|
||||||
|
|
||||||
|
if (y * bitmap.width + x) % 4 == 3:
|
||||||
|
pixels2b.append(px)
|
||||||
|
px = 0
|
||||||
|
if (bitmap.width * bitmap.rows) % 4 != 0:
|
||||||
|
px = px << (4 - (bitmap.width * bitmap.rows) % 4) * 2
|
||||||
|
pixels2b.append(px)
|
||||||
|
|
||||||
|
# for y in range(bitmap.rows):
|
||||||
|
# line = ''
|
||||||
|
# for x in range(bitmap.width):
|
||||||
|
# pixelPosition = y * bitmap.width + x
|
||||||
|
# byte = pixels2b[pixelPosition // 4]
|
||||||
|
# bit_index = (3 - (pixelPosition % 4)) * 2
|
||||||
|
# line += '#' if ((byte >> bit_index) & 3) > 0 else '.'
|
||||||
|
# print(line)
|
||||||
|
# print('')
|
||||||
|
else:
|
||||||
|
# Downsample to 1-bit bitmap - treat any 2+ as black
|
||||||
|
pixelsbw = []
|
||||||
|
px = 0
|
||||||
|
pitch = (bitmap.width // 2) + (bitmap.width % 2)
|
||||||
|
for y in range(bitmap.rows):
|
||||||
|
for x in range(bitmap.width):
|
||||||
|
px = px << 1
|
||||||
|
bm = pixels4g[y * pitch + (x // 2)]
|
||||||
|
px += 1 if ((x & 1) == 0 and bm & 0xE > 0) or ((x & 1) == 1 and bm & 0xE0 > 0) else 0
|
||||||
|
|
||||||
|
if (y * bitmap.width + x) % 8 == 7:
|
||||||
|
pixelsbw.append(px)
|
||||||
|
px = 0
|
||||||
|
if (bitmap.width * bitmap.rows) % 8 != 0:
|
||||||
|
px = px << (8 - (bitmap.width * bitmap.rows) % 8)
|
||||||
|
pixelsbw.append(px)
|
||||||
|
|
||||||
|
# for y in range(bitmap.rows):
|
||||||
|
# line = ''
|
||||||
|
# for x in range(bitmap.width):
|
||||||
|
# pixelPosition = y * bitmap.width + x
|
||||||
|
# byte = pixelsbw[pixelPosition // 8]
|
||||||
|
# bit_index = 7 - (pixelPosition % 8)
|
||||||
|
# line += '#' if (byte >> bit_index) & 1 else '.'
|
||||||
|
# print(line)
|
||||||
|
# print('')
|
||||||
|
|
||||||
|
pixels = pixels2b if is2Bit else pixelsbw
|
||||||
|
|
||||||
# Build output data
|
# Build output data
|
||||||
packed = bytes(pixelsbw)
|
packed = bytes(pixels)
|
||||||
glyph = GlyphProps(
|
glyph = GlyphProps(
|
||||||
width = bitmap.width,
|
width = bitmap.width,
|
||||||
height = bitmap.rows,
|
height = bitmap.rows,
|
||||||
@@ -216,7 +265,7 @@ for index, glyph in enumerate(all_glyphs):
|
|||||||
glyph_data.extend([b for b in packed])
|
glyph_data.extend([b for b in packed])
|
||||||
glyph_props.append(props)
|
glyph_props.append(props)
|
||||||
|
|
||||||
print(f"/**\n * generated by fontconvert.py\n * name: {font_name}\n * size: {size}\n */")
|
print(f"/**\n * generated by fontconvert.py\n * name: {font_name}\n * size: {size}\n * mode: {'2-bit' if is2Bit else '1-bit'}\n */")
|
||||||
print("#pragma once")
|
print("#pragma once")
|
||||||
print("#include \"EpdFontData.h\"\n")
|
print("#include \"EpdFontData.h\"\n")
|
||||||
print(f"static const uint8_t {font_name}Bitmaps[{len(glyph_data)}] = {{")
|
print(f"static const uint8_t {font_name}Bitmaps[{len(glyph_data)}] = {{")
|
||||||
@@ -244,4 +293,5 @@ print(f" {len(intervals)},")
|
|||||||
print(f" {norm_ceil(face.size.height)},")
|
print(f" {norm_ceil(face.size.height)},")
|
||||||
print(f" {norm_ceil(face.size.ascender)},")
|
print(f" {norm_ceil(face.size.ascender)},")
|
||||||
print(f" {norm_floor(face.size.descender)},")
|
print(f" {norm_floor(face.size.descender)},")
|
||||||
|
print(f" {'true' if is2Bit else 'false'},")
|
||||||
print("};")
|
print("};")
|
||||||
|
|||||||
@@ -1,84 +0,0 @@
|
|||||||
#pragma once
|
|
||||||
#include <EpdFontFamily.h>
|
|
||||||
#include <HardwareSerial.h>
|
|
||||||
#include <Utf8.h>
|
|
||||||
|
|
||||||
inline int min(const int a, const int b) { return a < b ? a : b; }
|
|
||||||
inline int max(const int a, const int b) { return a > b ? a : b; }
|
|
||||||
|
|
||||||
template <typename Renderable>
|
|
||||||
class EpdFontRenderer {
|
|
||||||
Renderable& renderer;
|
|
||||||
void renderChar(uint32_t cp, int* x, const int* y, uint16_t color, EpdFontStyle style = REGULAR);
|
|
||||||
|
|
||||||
public:
|
|
||||||
const EpdFontFamily* fontFamily;
|
|
||||||
explicit EpdFontRenderer(const EpdFontFamily* fontFamily, Renderable& renderer)
|
|
||||||
: fontFamily(fontFamily), renderer(renderer) {}
|
|
||||||
~EpdFontRenderer() = default;
|
|
||||||
void renderString(const char* string, int* x, int* y, uint16_t color, EpdFontStyle style = REGULAR);
|
|
||||||
};
|
|
||||||
|
|
||||||
template <typename Renderable>
|
|
||||||
void EpdFontRenderer<Renderable>::renderString(const char* string, int* x, int* y, const uint16_t color,
|
|
||||||
const EpdFontStyle style) {
|
|
||||||
// cannot draw a NULL / empty string
|
|
||||||
if (string == nullptr || *string == '\0') {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// no printable characters
|
|
||||||
if (!fontFamily->hasPrintableChars(string, style)) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
uint32_t cp;
|
|
||||||
while ((cp = utf8NextCodepoint(reinterpret_cast<const uint8_t**>(&string)))) {
|
|
||||||
renderChar(cp, x, y, color, style);
|
|
||||||
}
|
|
||||||
|
|
||||||
*y += fontFamily->getData(style)->advanceY;
|
|
||||||
}
|
|
||||||
|
|
||||||
template <typename Renderable>
|
|
||||||
void EpdFontRenderer<Renderable>::renderChar(const uint32_t cp, int* x, const int* y, uint16_t color,
|
|
||||||
const EpdFontStyle style) {
|
|
||||||
const EpdGlyph* glyph = fontFamily->getGlyph(cp, style);
|
|
||||||
if (!glyph) {
|
|
||||||
// TODO: Replace with fallback glyph property?
|
|
||||||
glyph = fontFamily->getGlyph('?', style);
|
|
||||||
}
|
|
||||||
|
|
||||||
// no glyph?
|
|
||||||
if (!glyph) {
|
|
||||||
Serial.printf("No glyph for codepoint %d\n", cp);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const uint32_t offset = glyph->dataOffset;
|
|
||||||
const uint8_t width = glyph->width;
|
|
||||||
const uint8_t height = glyph->height;
|
|
||||||
const int left = glyph->left;
|
|
||||||
|
|
||||||
const uint8_t* bitmap = nullptr;
|
|
||||||
bitmap = &fontFamily->getData(style)->bitmap[offset];
|
|
||||||
|
|
||||||
if (bitmap != nullptr) {
|
|
||||||
for (int glyphY = 0; glyphY < height; glyphY++) {
|
|
||||||
int screenY = *y - glyph->top + glyphY;
|
|
||||||
for (int glyphX = 0; glyphX < width; glyphX++) {
|
|
||||||
const int pixelPosition = glyphY * width + glyphX;
|
|
||||||
int screenX = *x + left + glyphX;
|
|
||||||
|
|
||||||
const uint8_t byte = bitmap[pixelPosition / 8];
|
|
||||||
const uint8_t bit_index = 7 - (pixelPosition % 8);
|
|
||||||
|
|
||||||
if ((byte >> bit_index) & 1) {
|
|
||||||
renderer.drawPixel(screenX, screenY, color);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
*x += glyph->advanceX;
|
|
||||||
}
|
|
||||||
@@ -1,168 +0,0 @@
|
|||||||
#include "EpdRenderer.h"
|
|
||||||
|
|
||||||
#include "builtinFonts/babyblue.h"
|
|
||||||
#include "builtinFonts/bookerly.h"
|
|
||||||
#include "builtinFonts/bookerly_bold.h"
|
|
||||||
#include "builtinFonts/bookerly_bold_italic.h"
|
|
||||||
#include "builtinFonts/bookerly_italic.h"
|
|
||||||
#include "builtinFonts/ubuntu_10.h"
|
|
||||||
#include "builtinFonts/ubuntu_bold_10.h"
|
|
||||||
|
|
||||||
EpdFont bookerlyFont(&bookerly);
|
|
||||||
EpdFont bookerlyBoldFont(&bookerly_bold);
|
|
||||||
EpdFont bookerlyItalicFont(&bookerly_italic);
|
|
||||||
EpdFont bookerlyBoldItalicFont(&bookerly_bold_italic);
|
|
||||||
EpdFontFamily bookerlyFontFamily(&bookerlyFont, &bookerlyBoldFont, &bookerlyItalicFont, &bookerlyBoldItalicFont);
|
|
||||||
|
|
||||||
EpdFont smallFont(&babyblue);
|
|
||||||
EpdFontFamily smallFontFamily(&smallFont);
|
|
||||||
|
|
||||||
EpdFont ubuntu10Font(&ubuntu_10);
|
|
||||||
EpdFont ununtuBold10Font(&ubuntu_bold_10);
|
|
||||||
EpdFontFamily ubuntuFontFamily(&ubuntu10Font, &ununtuBold10Font);
|
|
||||||
|
|
||||||
EpdRenderer::EpdRenderer(XteinkDisplay& display)
|
|
||||||
: display(display), marginTop(11), marginBottom(30), marginLeft(10), marginRight(10), lineCompression(0.95f) {
|
|
||||||
this->regularFontRenderer = new EpdFontRenderer<XteinkDisplay>(&bookerlyFontFamily, display);
|
|
||||||
this->smallFontRenderer = new EpdFontRenderer<XteinkDisplay>(&smallFontFamily, display);
|
|
||||||
this->uiFontRenderer = new EpdFontRenderer<XteinkDisplay>(&ubuntuFontFamily, display);
|
|
||||||
}
|
|
||||||
|
|
||||||
EpdRenderer::~EpdRenderer() {
|
|
||||||
delete regularFontRenderer;
|
|
||||||
delete smallFontRenderer;
|
|
||||||
delete uiFontRenderer;
|
|
||||||
}
|
|
||||||
|
|
||||||
int EpdRenderer::getTextWidth(const char* text, const EpdFontStyle style) const {
|
|
||||||
int w = 0, h = 0;
|
|
||||||
|
|
||||||
regularFontRenderer->fontFamily->getTextDimensions(text, &w, &h, style);
|
|
||||||
|
|
||||||
return w;
|
|
||||||
}
|
|
||||||
|
|
||||||
int EpdRenderer::getUiTextWidth(const char* text, const EpdFontStyle style) const {
|
|
||||||
int w = 0, h = 0;
|
|
||||||
|
|
||||||
uiFontRenderer->fontFamily->getTextDimensions(text, &w, &h, style);
|
|
||||||
|
|
||||||
return w;
|
|
||||||
}
|
|
||||||
|
|
||||||
int EpdRenderer::getSmallTextWidth(const char* text, const EpdFontStyle style) const {
|
|
||||||
int w = 0, h = 0;
|
|
||||||
|
|
||||||
smallFontRenderer->fontFamily->getTextDimensions(text, &w, &h, style);
|
|
||||||
|
|
||||||
return w;
|
|
||||||
}
|
|
||||||
|
|
||||||
void EpdRenderer::drawText(const int x, const int y, const char* text, const uint16_t color,
|
|
||||||
const EpdFontStyle style) const {
|
|
||||||
int ypos = y + getLineHeight() + marginTop;
|
|
||||||
int xpos = x + marginLeft;
|
|
||||||
regularFontRenderer->renderString(text, &xpos, &ypos, color > 0 ? GxEPD_BLACK : GxEPD_WHITE, style);
|
|
||||||
}
|
|
||||||
|
|
||||||
void EpdRenderer::drawUiText(const int x, const int y, const char* text, const uint16_t color,
|
|
||||||
const EpdFontStyle style) const {
|
|
||||||
int ypos = y + uiFontRenderer->fontFamily->getData(style)->advanceY + marginTop;
|
|
||||||
int xpos = x + marginLeft;
|
|
||||||
uiFontRenderer->renderString(text, &xpos, &ypos, color > 0 ? GxEPD_BLACK : GxEPD_WHITE, style);
|
|
||||||
}
|
|
||||||
|
|
||||||
void EpdRenderer::drawSmallText(const int x, const int y, const char* text, const uint16_t color,
|
|
||||||
const EpdFontStyle style) const {
|
|
||||||
int ypos = y + smallFontRenderer->fontFamily->getData(style)->advanceY + marginTop;
|
|
||||||
int xpos = x + marginLeft;
|
|
||||||
smallFontRenderer->renderString(text, &xpos, &ypos, color > 0 ? GxEPD_BLACK : GxEPD_WHITE, style);
|
|
||||||
}
|
|
||||||
|
|
||||||
void EpdRenderer::drawTextBox(const int x, const int y, const std::string& text, const int width, const int height,
|
|
||||||
const EpdFontStyle style) const {
|
|
||||||
const size_t length = text.length();
|
|
||||||
// fit the text into the box
|
|
||||||
int start = 0;
|
|
||||||
int end = 1;
|
|
||||||
int ypos = 0;
|
|
||||||
while (true) {
|
|
||||||
if (end >= length) {
|
|
||||||
drawText(x, y + ypos, text.substr(start, length - start).c_str(), 1, style);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (ypos + getLineHeight() >= height) {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (text[end - 1] == '\n') {
|
|
||||||
drawText(x, y + ypos, text.substr(start, end - start).c_str(), 1, style);
|
|
||||||
ypos += getLineHeight();
|
|
||||||
start = end;
|
|
||||||
end = start + 1;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (getTextWidth(text.substr(start, end - start).c_str(), style) > width) {
|
|
||||||
drawText(x, y + ypos, text.substr(start, end - start - 1).c_str(), 1, style);
|
|
||||||
ypos += getLineHeight();
|
|
||||||
start = end - 1;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
end++;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void EpdRenderer::drawLine(int x1, int y1, int x2, int y2, uint16_t color) const {
|
|
||||||
display.drawLine(x1 + marginLeft, y1 + marginTop, x2 + marginLeft, y2 + marginTop,
|
|
||||||
color > 0 ? GxEPD_BLACK : GxEPD_WHITE);
|
|
||||||
}
|
|
||||||
|
|
||||||
void EpdRenderer::drawRect(const int x, const int y, const int width, const int height, const uint16_t color) const {
|
|
||||||
display.drawRect(x + marginLeft, y + marginTop, width, height, color > 0 ? GxEPD_BLACK : GxEPD_WHITE);
|
|
||||||
}
|
|
||||||
|
|
||||||
void EpdRenderer::fillRect(const int x, const int y, const int width, const int height, const uint16_t color) const {
|
|
||||||
display.fillRect(x + marginLeft, y + marginTop, width, height, color > 0 ? GxEPD_BLACK : GxEPD_WHITE);
|
|
||||||
}
|
|
||||||
|
|
||||||
void EpdRenderer::drawCircle(const int x, const int y, const int radius, const uint16_t color) const {
|
|
||||||
display.drawCircle(x + marginLeft, y + marginTop, radius, color > 0 ? GxEPD_BLACK : GxEPD_WHITE);
|
|
||||||
}
|
|
||||||
|
|
||||||
void EpdRenderer::fillCircle(const int x, const int y, const int radius, const uint16_t color) const {
|
|
||||||
display.fillCircle(x + marginLeft, y + marginTop, radius, color > 0 ? GxEPD_BLACK : GxEPD_WHITE);
|
|
||||||
}
|
|
||||||
|
|
||||||
void EpdRenderer::drawImage(const uint8_t bitmap[], const int x, const int y, const int width, const int height,
|
|
||||||
const bool invert, const bool mirrorY) const {
|
|
||||||
drawImageNoMargin(bitmap, x + marginLeft, y + marginTop, width, height, invert, mirrorY);
|
|
||||||
}
|
|
||||||
|
|
||||||
void EpdRenderer::drawImageNoMargin(const uint8_t bitmap[], const int x, const int y, const int width, const int height,
|
|
||||||
const bool invert, const bool mirrorY) const {
|
|
||||||
display.drawImage(bitmap, x, y, width, height, invert, mirrorY);
|
|
||||||
}
|
|
||||||
|
|
||||||
void EpdRenderer::clearScreen(const bool black) const {
|
|
||||||
Serial.println("Clearing screen");
|
|
||||||
display.fillScreen(black ? GxEPD_BLACK : GxEPD_WHITE);
|
|
||||||
}
|
|
||||||
|
|
||||||
void EpdRenderer::flushDisplay(const bool partialUpdate) const { display.display(partialUpdate); }
|
|
||||||
|
|
||||||
void EpdRenderer::flushArea(const int x, const int y, const int width, const int height) const {
|
|
||||||
display.displayWindow(x + marginLeft, y + marginTop, width, height);
|
|
||||||
}
|
|
||||||
|
|
||||||
int EpdRenderer::getPageWidth() const { return display.width() - marginLeft - marginRight; }
|
|
||||||
|
|
||||||
int EpdRenderer::getPageHeight() const { return display.height() - marginTop - marginBottom; }
|
|
||||||
|
|
||||||
int EpdRenderer::getSpaceWidth() const { return regularFontRenderer->fontFamily->getGlyph(' ', REGULAR)->advanceX; }
|
|
||||||
|
|
||||||
int EpdRenderer::getLineHeight() const {
|
|
||||||
return regularFontRenderer->fontFamily->getData(REGULAR)->advanceY * lineCompression;
|
|
||||||
}
|
|
||||||
@@ -1,52 +0,0 @@
|
|||||||
#pragma once
|
|
||||||
|
|
||||||
#include <GxEPD2_BW.h>
|
|
||||||
|
|
||||||
#include <EpdFontRenderer.hpp>
|
|
||||||
|
|
||||||
#define XteinkDisplay GxEPD2_BW<GxEPD2_426_GDEQ0426T82, GxEPD2_426_GDEQ0426T82::HEIGHT>
|
|
||||||
|
|
||||||
class EpdRenderer {
|
|
||||||
XteinkDisplay& display;
|
|
||||||
EpdFontRenderer<XteinkDisplay>* regularFontRenderer;
|
|
||||||
EpdFontRenderer<XteinkDisplay>* smallFontRenderer;
|
|
||||||
EpdFontRenderer<XteinkDisplay>* uiFontRenderer;
|
|
||||||
int marginTop;
|
|
||||||
int marginBottom;
|
|
||||||
int marginLeft;
|
|
||||||
int marginRight;
|
|
||||||
float lineCompression;
|
|
||||||
|
|
||||||
public:
|
|
||||||
explicit EpdRenderer(XteinkDisplay& display);
|
|
||||||
~EpdRenderer();
|
|
||||||
int getTextWidth(const char* text, EpdFontStyle style = REGULAR) const;
|
|
||||||
int getUiTextWidth(const char* text, EpdFontStyle style = REGULAR) const;
|
|
||||||
int getSmallTextWidth(const char* text, EpdFontStyle style = REGULAR) const;
|
|
||||||
void drawText(int x, int y, const char* text, uint16_t color = 1, EpdFontStyle style = REGULAR) const;
|
|
||||||
void drawUiText(int x, int y, const char* text, uint16_t color = 1, EpdFontStyle style = REGULAR) const;
|
|
||||||
void drawSmallText(int x, int y, const char* text, uint16_t color = 1, EpdFontStyle style = REGULAR) const;
|
|
||||||
void drawTextBox(int x, int y, const std::string& text, int width, int height, EpdFontStyle style = REGULAR) const;
|
|
||||||
void drawLine(int x1, int y1, int x2, int y2, uint16_t color = 1) const;
|
|
||||||
void drawRect(int x, int y, int width, int height, uint16_t color = 1) const;
|
|
||||||
void fillRect(int x, int y, int width, int height, uint16_t color = 1) const;
|
|
||||||
void drawCircle(int x, int y, int radius, uint16_t color = 1) const;
|
|
||||||
void fillCircle(int x, int y, int radius, uint16_t color = 1) const;
|
|
||||||
void drawImage(const uint8_t bitmap[], int x, int y, int width, int height, bool invert = false,
|
|
||||||
bool mirrorY = false) const;
|
|
||||||
void drawImageNoMargin(const uint8_t bitmap[], int x, int y, int width, int height, bool invert = false,
|
|
||||||
bool mirrorY = false) const;
|
|
||||||
void clearScreen(bool black = false) const;
|
|
||||||
void flushDisplay(bool partialUpdate = true) const;
|
|
||||||
void flushArea(int x, int y, int width, int height) const;
|
|
||||||
|
|
||||||
int getPageWidth() const;
|
|
||||||
int getPageHeight() const;
|
|
||||||
int getSpaceWidth() const;
|
|
||||||
int getLineHeight() const;
|
|
||||||
// set margins
|
|
||||||
void setMarginTop(const int newMarginTop) { this->marginTop = newMarginTop; }
|
|
||||||
void setMarginBottom(const int newMarginBottom) { this->marginBottom = newMarginBottom; }
|
|
||||||
void setMarginLeft(const int newMarginLeft) { this->marginLeft = newMarginLeft; }
|
|
||||||
void setMarginRight(const int newMarginRight) { this->marginRight = newMarginRight; }
|
|
||||||
};
|
|
||||||
@@ -1,254 +1,239 @@
|
|||||||
#include "Epub.h"
|
#include "Epub.h"
|
||||||
|
|
||||||
|
#include <FsHelpers.h>
|
||||||
#include <HardwareSerial.h>
|
#include <HardwareSerial.h>
|
||||||
|
#include <JpegToBmpConverter.h>
|
||||||
#include <SD.h>
|
#include <SD.h>
|
||||||
#include <ZipFile.h>
|
#include <ZipFile.h>
|
||||||
|
|
||||||
#include <map>
|
#include "Epub/parsers/ContainerParser.h"
|
||||||
|
#include "Epub/parsers/ContentOpfParser.h"
|
||||||
|
#include "Epub/parsers/TocNcxParser.h"
|
||||||
|
|
||||||
bool Epub::findContentOpfFile(const ZipFile& zip, std::string& contentOpfFile) {
|
bool Epub::findContentOpfFile(std::string* contentOpfFile) const {
|
||||||
// open up the meta data to find where the content.opf file lives
|
const auto containerPath = "META-INF/container.xml";
|
||||||
size_t s;
|
size_t containerSize;
|
||||||
const auto metaInfo = reinterpret_cast<char*>(zip.readFileToMemory("META-INF/container.xml", &s, true));
|
|
||||||
if (!metaInfo) {
|
// Get file size without loading it all into heap
|
||||||
Serial.println("Could not find META-INF/container.xml");
|
if (!getItemSize(containerPath, &containerSize)) {
|
||||||
|
Serial.printf("[%lu] [EBP] Could not find or size META-INF/container.xml\n", millis());
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
// parse the meta data
|
ContainerParser containerParser(containerSize);
|
||||||
tinyxml2::XMLDocument metaDataDoc;
|
|
||||||
const auto result = metaDataDoc.Parse(metaInfo);
|
|
||||||
free(metaInfo);
|
|
||||||
|
|
||||||
if (result != tinyxml2::XML_SUCCESS) {
|
if (!containerParser.setup()) {
|
||||||
Serial.printf("Could not parse META-INF/container.xml. Error: %d\n", result);
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
const auto container = metaDataDoc.FirstChildElement("container");
|
// Stream read (reusing your existing stream logic)
|
||||||
if (!container) {
|
if (!readItemContentsToStream(containerPath, containerParser, 512)) {
|
||||||
Serial.println("Could not find container element in META-INF/container.xml");
|
Serial.printf("[%lu] [EBP] Could not read META-INF/container.xml\n", millis());
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
const auto rootfiles = container->FirstChildElement("rootfiles");
|
// Extract the result
|
||||||
if (!rootfiles) {
|
if (containerParser.fullPath.empty()) {
|
||||||
Serial.println("Could not find rootfiles element in META-INF/container.xml");
|
Serial.printf("[%lu] [EBP] Could not find valid rootfile in container.xml\n", millis());
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
// find the root file that has the media-type="application/oebps-package+xml"
|
*contentOpfFile = std::move(containerParser.fullPath);
|
||||||
auto rootfile = rootfiles->FirstChildElement("rootfile");
|
|
||||||
while (rootfile) {
|
|
||||||
const char* mediaType = rootfile->Attribute("media-type");
|
|
||||||
if (mediaType && strcmp(mediaType, "application/oebps-package+xml") == 0) {
|
|
||||||
const char* full_path = rootfile->Attribute("full-path");
|
|
||||||
if (full_path) {
|
|
||||||
contentOpfFile = full_path;
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
rootfile = rootfile->NextSiblingElement("rootfile");
|
|
||||||
}
|
|
||||||
|
|
||||||
Serial.println("Could not get path to content.opf file");
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool Epub::parseContentOpf(ZipFile& zip, std::string& content_opf_file) {
|
|
||||||
// read in the content.opf file and parse it
|
|
||||||
auto contents = reinterpret_cast<char*>(zip.readFileToMemory(content_opf_file.c_str(), nullptr, true));
|
|
||||||
|
|
||||||
// parse the contents
|
|
||||||
tinyxml2::XMLDocument doc;
|
|
||||||
auto result = doc.Parse(contents);
|
|
||||||
free(contents);
|
|
||||||
|
|
||||||
if (result != tinyxml2::XML_SUCCESS) {
|
|
||||||
Serial.printf("Error parsing content.opf - %s\n", tinyxml2::XMLDocument::ErrorIDToName(result));
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
auto package = doc.FirstChildElement("package");
|
|
||||||
if (!package) package = doc.FirstChildElement("opf:package");
|
|
||||||
|
|
||||||
if (!package) {
|
|
||||||
Serial.println("Could not find package element in content.opf");
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
// get the metadata - title and cover image
|
|
||||||
auto metadata = package->FirstChildElement("metadata");
|
|
||||||
if (!metadata) metadata = package->FirstChildElement("opf:metadata");
|
|
||||||
if (!metadata) {
|
|
||||||
Serial.println("Missing metadata");
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
auto titleEl = metadata->FirstChildElement("dc:title");
|
|
||||||
if (!titleEl) {
|
|
||||||
Serial.println("Missing title");
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
this->title = titleEl->GetText();
|
|
||||||
|
|
||||||
auto cover = metadata->FirstChildElement("meta");
|
|
||||||
if (!cover) cover = metadata->FirstChildElement("opf:meta");
|
|
||||||
while (cover && cover->Attribute("name") && strcmp(cover->Attribute("name"), "cover") != 0) {
|
|
||||||
cover = cover->NextSiblingElement("meta");
|
|
||||||
}
|
|
||||||
if (!cover) {
|
|
||||||
Serial.println("Missing cover");
|
|
||||||
}
|
|
||||||
auto coverItem = cover ? cover->Attribute("content") : nullptr;
|
|
||||||
|
|
||||||
// read the manifest and spine
|
|
||||||
// the manifest gives us the names of the files
|
|
||||||
// the spine gives us the order of the files
|
|
||||||
// we can then read the files in the order they are in the spine
|
|
||||||
auto manifest = package->FirstChildElement("manifest");
|
|
||||||
if (!manifest) manifest = package->FirstChildElement("opf:manifest");
|
|
||||||
if (!manifest) {
|
|
||||||
Serial.println("Missing manifest");
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
// create a mapping from id to file name
|
|
||||||
auto item = manifest->FirstChildElement("item");
|
|
||||||
if (!item) item = manifest->FirstChildElement("opf:item");
|
|
||||||
std::map<std::string, std::string> items;
|
|
||||||
|
|
||||||
while (item) {
|
|
||||||
std::string itemId = item->Attribute("id");
|
|
||||||
std::string href = contentBasePath + item->Attribute("href");
|
|
||||||
|
|
||||||
// grab the cover image
|
|
||||||
if (coverItem && itemId == coverItem) {
|
|
||||||
coverImageItem = href;
|
|
||||||
}
|
|
||||||
|
|
||||||
// grab the ncx file
|
|
||||||
if (itemId == "ncx" || itemId == "ncxtoc") {
|
|
||||||
tocNcxItem = href;
|
|
||||||
}
|
|
||||||
|
|
||||||
items[itemId] = href;
|
|
||||||
auto nextItem = item->NextSiblingElement("item");
|
|
||||||
if (!nextItem) nextItem = item->NextSiblingElement("opf:item");
|
|
||||||
item = nextItem;
|
|
||||||
}
|
|
||||||
|
|
||||||
// find the spine
|
|
||||||
auto spineEl = package->FirstChildElement("spine");
|
|
||||||
if (!spineEl) spineEl = package->FirstChildElement("opf:spine");
|
|
||||||
if (!spineEl) {
|
|
||||||
Serial.println("Missing spine");
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
// read the spine
|
|
||||||
auto itemref = spineEl->FirstChildElement("itemref");
|
|
||||||
if (!itemref) itemref = spineEl->FirstChildElement("opf:itemref");
|
|
||||||
while (itemref) {
|
|
||||||
auto id = itemref->Attribute("idref");
|
|
||||||
if (items.find(id) != items.end()) {
|
|
||||||
spine.emplace_back(id, items[id]);
|
|
||||||
}
|
|
||||||
auto nextItemRef = itemref->NextSiblingElement("itemref");
|
|
||||||
if (!nextItemRef) nextItemRef = itemref->NextSiblingElement("opf:itemref");
|
|
||||||
itemref = nextItemRef;
|
|
||||||
}
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
bool Epub::parseTocNcxFile(const ZipFile& zip) {
|
bool Epub::parseContentOpf(BookMetadataCache::BookMetadata& bookMetadata) {
|
||||||
|
std::string contentOpfFilePath;
|
||||||
|
if (!findContentOpfFile(&contentOpfFilePath)) {
|
||||||
|
Serial.printf("[%lu] [EBP] Could not find content.opf in zip\n", millis());
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
contentBasePath = contentOpfFilePath.substr(0, contentOpfFilePath.find_last_of('/') + 1);
|
||||||
|
|
||||||
|
Serial.printf("[%lu] [EBP] Parsing content.opf: %s\n", millis(), contentOpfFilePath.c_str());
|
||||||
|
|
||||||
|
size_t contentOpfSize;
|
||||||
|
if (!getItemSize(contentOpfFilePath, &contentOpfSize)) {
|
||||||
|
Serial.printf("[%lu] [EBP] Could not get size of content.opf\n", millis());
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
ContentOpfParser opfParser(getCachePath(), getBasePath(), contentOpfSize, bookMetadataCache.get());
|
||||||
|
Serial.printf("[%lu] [MEM] Free: %d bytes, Total: %d bytes, Min Free: %d bytes\n", millis(), ESP.getFreeHeap(),
|
||||||
|
ESP.getHeapSize(), ESP.getMinFreeHeap());
|
||||||
|
|
||||||
|
if (!opfParser.setup()) {
|
||||||
|
Serial.printf("[%lu] [EBP] Could not setup content.opf parser\n", millis());
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!readItemContentsToStream(contentOpfFilePath, opfParser, 1024)) {
|
||||||
|
Serial.printf("[%lu] [EBP] Could not read content.opf\n", millis());
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Grab data from opfParser into epub
|
||||||
|
bookMetadata.title = opfParser.title;
|
||||||
|
// TODO: Parse author
|
||||||
|
bookMetadata.author = "";
|
||||||
|
bookMetadata.coverItemHref = opfParser.coverItemHref;
|
||||||
|
|
||||||
|
if (!opfParser.tocNcxPath.empty()) {
|
||||||
|
tocNcxItem = opfParser.tocNcxPath;
|
||||||
|
}
|
||||||
|
|
||||||
|
Serial.printf("[%lu] [EBP] Successfully parsed content.opf\n", millis());
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
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.println("No ncx file specified");
|
Serial.printf("[%lu] [EBP] No ncx file specified\n", millis());
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
const auto ncxData = reinterpret_cast<char*>(zip.readFileToMemory(tocNcxItem.c_str(), nullptr, true));
|
Serial.printf("[%lu] [EBP] Parsing toc ncx file: %s\n", millis(), tocNcxItem.c_str());
|
||||||
if (!ncxData) {
|
|
||||||
Serial.printf("Could not find %s\n", tocNcxItem.c_str());
|
const auto tmpNcxPath = getCachePath() + "/toc.ncx";
|
||||||
|
File tempNcxFile;
|
||||||
|
if (!FsHelpers::openFileForWrite("EBP", tmpNcxPath, tempNcxFile)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
readItemContentsToStream(tocNcxItem, tempNcxFile, 1024);
|
||||||
|
tempNcxFile.close();
|
||||||
|
if (!FsHelpers::openFileForRead("EBP", tmpNcxPath, tempNcxFile)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
const auto ncxSize = tempNcxFile.size();
|
||||||
|
|
||||||
|
TocNcxParser ncxParser(contentBasePath, ncxSize, bookMetadataCache.get());
|
||||||
|
|
||||||
|
if (!ncxParser.setup()) {
|
||||||
|
Serial.printf("[%lu] [EBP] Could not setup toc ncx parser\n", millis());
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Parse the Toc contents
|
const auto ncxBuffer = static_cast<uint8_t*>(malloc(1024));
|
||||||
tinyxml2::XMLDocument doc;
|
if (!ncxBuffer) {
|
||||||
const auto result = doc.Parse(ncxData);
|
Serial.printf("[%lu] [EBP] Could not allocate memory for toc ncx parser\n", millis());
|
||||||
free(ncxData);
|
|
||||||
|
|
||||||
if (result != tinyxml2::XML_SUCCESS) {
|
|
||||||
Serial.printf("Error parsing toc %s\n", tinyxml2::XMLDocument::ErrorIDToName(result));
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
const auto ncx = doc.FirstChildElement("ncx");
|
while (tempNcxFile.available()) {
|
||||||
if (!ncx) {
|
const auto readSize = tempNcxFile.read(ncxBuffer, 1024);
|
||||||
Serial.println("Could not find first child ncx in toc");
|
const auto processedSize = ncxParser.write(ncxBuffer, readSize);
|
||||||
return false;
|
|
||||||
|
if (processedSize != readSize) {
|
||||||
|
Serial.printf("[%lu] [EBP] Could not process all toc ncx data\n", millis());
|
||||||
|
free(ncxBuffer);
|
||||||
|
tempNcxFile.close();
|
||||||
|
return false;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const auto navMap = ncx->FirstChildElement("navMap");
|
free(ncxBuffer);
|
||||||
if (!navMap) {
|
tempNcxFile.close();
|
||||||
Serial.println("Could not find navMap child in ncx");
|
SD.remove(tmpNcxPath.c_str());
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
recursivelyParseNavMap(navMap->FirstChildElement("navPoint"));
|
Serial.printf("[%lu] [EBP] Parsed TOC items\n", millis());
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
void Epub::recursivelyParseNavMap(tinyxml2::XMLElement* element) {
|
|
||||||
// Fills toc map
|
|
||||||
while (element) {
|
|
||||||
std::string navTitle = element->FirstChildElement("navLabel")->FirstChildElement("text")->FirstChild()->Value();
|
|
||||||
const auto content = element->FirstChildElement("content");
|
|
||||||
std::string href = contentBasePath + content->Attribute("src");
|
|
||||||
// split the href on the # to get the href and the anchor
|
|
||||||
const size_t pos = href.find('#');
|
|
||||||
std::string anchor;
|
|
||||||
|
|
||||||
if (pos != std::string::npos) {
|
|
||||||
anchor = href.substr(pos + 1);
|
|
||||||
href = href.substr(0, pos);
|
|
||||||
}
|
|
||||||
|
|
||||||
toc.emplace_back(navTitle, href, anchor, 0);
|
|
||||||
|
|
||||||
tinyxml2::XMLElement* nestedNavPoint = element->FirstChildElement("navPoint");
|
|
||||||
if (nestedNavPoint) {
|
|
||||||
recursivelyParseNavMap(nestedNavPoint);
|
|
||||||
}
|
|
||||||
element = element->NextSiblingElement("navPoint");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// load in the meta data for the epub file
|
// load in the meta data for the epub file
|
||||||
bool Epub::load() {
|
bool Epub::load() {
|
||||||
ZipFile zip("/sd" + filepath);
|
Serial.printf("[%lu] [EBP] Loading ePub: %s\n", millis(), filepath.c_str());
|
||||||
|
|
||||||
std::string contentOpfFile;
|
// Initialize spine/TOC cache
|
||||||
if (!findContentOpfFile(zip, contentOpfFile)) {
|
bookMetadataCache.reset(new BookMetadataCache(cachePath));
|
||||||
Serial.println("Could not open ePub");
|
|
||||||
|
// Try to load existing cache first
|
||||||
|
if (bookMetadataCache->load()) {
|
||||||
|
Serial.printf("[%lu] [EBP] Loaded ePub: %s\n", millis(), filepath.c_str());
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Cache doesn't exist or is invalid, build it
|
||||||
|
Serial.printf("[%lu] [EBP] Cache not found, building spine/TOC cache\n", millis());
|
||||||
|
setupCacheDir();
|
||||||
|
|
||||||
|
// Begin building cache - stream entries to disk immediately
|
||||||
|
if (!bookMetadataCache->beginWrite()) {
|
||||||
|
Serial.printf("[%lu] [EBP] Could not begin writing cache\n", millis());
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
contentBasePath = contentOpfFile.substr(0, contentOpfFile.find_last_of('/') + 1);
|
// OPF Pass
|
||||||
|
BookMetadataCache::BookMetadata bookMetadata;
|
||||||
if (!parseContentOpf(zip, contentOpfFile)) {
|
if (!bookMetadataCache->beginContentOpfPass()) {
|
||||||
|
Serial.printf("[%lu] [EBP] Could not begin writing content.opf pass\n", millis());
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (!parseContentOpf(bookMetadata)) {
|
||||||
|
Serial.printf("[%lu] [EBP] Could not parse content.opf\n", millis());
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (!bookMetadataCache->endContentOpfPass()) {
|
||||||
|
Serial.printf("[%lu] [EBP] Could not end writing content.opf pass\n", millis());
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!parseTocNcxFile(zip)) {
|
// TOC Pass
|
||||||
|
if (!bookMetadataCache->beginTocPass()) {
|
||||||
|
Serial.printf("[%lu] [EBP] Could not begin writing toc pass\n", millis());
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (!parseTocNcxFile()) {
|
||||||
|
Serial.printf("[%lu] [EBP] Could not parse toc\n", millis());
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (!bookMetadataCache->endTocPass()) {
|
||||||
|
Serial.printf("[%lu] [EBP] Could not end writing toc pass\n", millis());
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Close the cache files
|
||||||
|
if (!bookMetadataCache->endWrite()) {
|
||||||
|
Serial.printf("[%lu] [EBP] Could not end writing cache\n", millis());
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Build final book.bin
|
||||||
|
if (!bookMetadataCache->buildBookBin(filepath, bookMetadata)) {
|
||||||
|
Serial.printf("[%lu] [EBP] Could not update mappings and sizes\n", millis());
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!bookMetadataCache->cleanupTmpFiles()) {
|
||||||
|
Serial.printf("[%lu] [EBP] Could not cleanup tmp files - ignoring\n", millis());
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reload the cache from disk so it's in the correct state
|
||||||
|
bookMetadataCache.reset(new BookMetadataCache(cachePath));
|
||||||
|
if (!bookMetadataCache->load()) {
|
||||||
|
Serial.printf("[%lu] [EBP] Failed to reload cache after writing\n", millis());
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
Serial.printf("[%lu] [EBP] Loaded ePub: %s\n", millis(), filepath.c_str());
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
void Epub::clearCache() const { SD.rmdir(cachePath.c_str()); }
|
bool Epub::clearCache() const {
|
||||||
|
if (!SD.exists(cachePath.c_str())) {
|
||||||
|
Serial.printf("[%lu] [EPB] Cache does not exist, no action needed\n", millis());
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!FsHelpers::removeDir(cachePath.c_str())) {
|
||||||
|
Serial.printf("[%lu] [EPB] Failed to clear cache\n", millis());
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
Serial.printf("[%lu] [EPB] Cache cleared successfully\n", millis());
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
void Epub::setupCacheDir() const {
|
void Epub::setupCacheDir() const {
|
||||||
if (SD.exists(cachePath.c_str())) {
|
if (SD.exists(cachePath.c_str())) {
|
||||||
@@ -268,53 +253,80 @@ const std::string& Epub::getCachePath() const { return cachePath; }
|
|||||||
|
|
||||||
const std::string& Epub::getPath() const { return filepath; }
|
const std::string& Epub::getPath() const { return filepath; }
|
||||||
|
|
||||||
const std::string& Epub::getTitle() const { return title; }
|
const std::string& Epub::getTitle() const {
|
||||||
|
static std::string blank;
|
||||||
const std::string& Epub::getCoverImageItem() const { return coverImageItem; }
|
if (!bookMetadataCache || !bookMetadataCache->isLoaded()) {
|
||||||
|
return blank;
|
||||||
std::string normalisePath(const std::string& path) {
|
|
||||||
std::vector<std::string> components;
|
|
||||||
std::string component;
|
|
||||||
|
|
||||||
for (const auto c : path) {
|
|
||||||
if (c == '/') {
|
|
||||||
if (!component.empty()) {
|
|
||||||
if (component == "..") {
|
|
||||||
if (!components.empty()) {
|
|
||||||
components.pop_back();
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
components.push_back(component);
|
|
||||||
}
|
|
||||||
component.clear();
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
component += c;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!component.empty()) {
|
return bookMetadataCache->coreMetadata.title;
|
||||||
components.push_back(component);
|
|
||||||
}
|
|
||||||
|
|
||||||
std::string result;
|
|
||||||
for (const auto& c : components) {
|
|
||||||
if (!result.empty()) {
|
|
||||||
result += "/";
|
|
||||||
}
|
|
||||||
result += c;
|
|
||||||
}
|
|
||||||
|
|
||||||
return result;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
uint8_t* Epub::readItemContentsToBytes(const std::string& itemHref, size_t* size, bool trailingNullByte) const {
|
std::string Epub::getCoverBmpPath() const { return cachePath + "/cover.bmp"; }
|
||||||
|
|
||||||
|
bool Epub::generateCoverBmp() const {
|
||||||
|
// Already generated, return true
|
||||||
|
if (SD.exists(getCoverBmpPath().c_str())) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!bookMetadataCache || !bookMetadataCache->isLoaded()) {
|
||||||
|
Serial.printf("[%lu] [EBP] Cannot generate cover BMP, cache not loaded\n", millis());
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
const auto coverImageHref = bookMetadataCache->coreMetadata.coverItemHref;
|
||||||
|
if (coverImageHref.empty()) {
|
||||||
|
Serial.printf("[%lu] [EBP] No known cover image\n", millis());
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (coverImageHref.substr(coverImageHref.length() - 4) == ".jpg" ||
|
||||||
|
coverImageHref.substr(coverImageHref.length() - 5) == ".jpeg") {
|
||||||
|
Serial.printf("[%lu] [EBP] Generating BMP from JPG cover image\n", millis());
|
||||||
|
const auto coverJpgTempPath = getCachePath() + "/.cover.jpg";
|
||||||
|
|
||||||
|
File coverJpg;
|
||||||
|
if (!FsHelpers::openFileForWrite("EBP", coverJpgTempPath, coverJpg)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
readItemContentsToStream(coverImageHref, coverJpg, 1024);
|
||||||
|
coverJpg.close();
|
||||||
|
|
||||||
|
if (!FsHelpers::openFileForRead("EBP", coverJpgTempPath, coverJpg)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
File coverBmp;
|
||||||
|
if (!FsHelpers::openFileForWrite("EBP", getCoverBmpPath(), coverBmp)) {
|
||||||
|
coverJpg.close();
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
const bool success = JpegToBmpConverter::jpegFileToBmpStream(coverJpg, coverBmp);
|
||||||
|
coverJpg.close();
|
||||||
|
coverBmp.close();
|
||||||
|
SD.remove(coverJpgTempPath.c_str());
|
||||||
|
|
||||||
|
if (!success) {
|
||||||
|
Serial.printf("[%lu] [EBP] Failed to generate BMP from JPG cover image\n", millis());
|
||||||
|
SD.remove(getCoverBmpPath().c_str());
|
||||||
|
}
|
||||||
|
Serial.printf("[%lu] [EBP] Generated BMP from JPG cover image, success: %s\n", millis(), success ? "yes" : "no");
|
||||||
|
return success;
|
||||||
|
} else {
|
||||||
|
Serial.printf("[%lu] [EBP] Cover image is not a JPG, skipping\n", millis());
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
uint8_t* Epub::readItemContentsToBytes(const std::string& itemHref, size_t* size, const bool trailingNullByte) const {
|
||||||
const ZipFile zip("/sd" + filepath);
|
const ZipFile zip("/sd" + filepath);
|
||||||
const std::string path = normalisePath(itemHref);
|
const std::string path = FsHelpers::normalisePath(itemHref);
|
||||||
|
|
||||||
const auto content = zip.readFileToMemory(path.c_str(), size, trailingNullByte);
|
const auto content = zip.readFileToMemory(path.c_str(), size, trailingNullByte);
|
||||||
if (!content) {
|
if (!content) {
|
||||||
Serial.printf("Failed to read item %s\n", path.c_str());
|
Serial.printf("[%lu] [EBP] Failed to read item %s\n", millis(), path.c_str());
|
||||||
return nullptr;
|
return nullptr;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -323,58 +335,104 @@ 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 {
|
||||||
const ZipFile zip("/sd" + filepath);
|
const ZipFile zip("/sd" + filepath);
|
||||||
const std::string path = normalisePath(itemHref);
|
const std::string path = FsHelpers::normalisePath(itemHref);
|
||||||
|
|
||||||
return zip.readFileToStream(path.c_str(), out, chunkSize);
|
return zip.readFileToStream(path.c_str(), out, chunkSize);
|
||||||
}
|
}
|
||||||
|
|
||||||
int Epub::getSpineItemsCount() const { return spine.size(); }
|
bool Epub::getItemSize(const std::string& itemHref, size_t* size) const {
|
||||||
|
const ZipFile zip("/sd" + filepath);
|
||||||
std::string& Epub::getSpineItem(const int spineIndex) {
|
return getItemSize(zip, itemHref, size);
|
||||||
if (spineIndex < 0 || spineIndex >= spine.size()) {
|
|
||||||
Serial.printf("getSpineItem index:%d is out of range\n", spineIndex);
|
|
||||||
return spine.at(0).second;
|
|
||||||
}
|
|
||||||
|
|
||||||
return spine.at(spineIndex).second;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
EpubTocEntry& Epub::getTocItem(const int tocTndex) {
|
bool Epub::getItemSize(const ZipFile& zip, const std::string& itemHref, size_t* size) {
|
||||||
if (tocTndex < 0 || tocTndex >= toc.size()) {
|
const std::string path = FsHelpers::normalisePath(itemHref);
|
||||||
Serial.printf("getTocItem index:%d is out of range\n", tocTndex);
|
return zip.getInflatedFileSize(path.c_str(), size);
|
||||||
return toc.at(0);
|
|
||||||
}
|
|
||||||
|
|
||||||
return toc.at(tocTndex);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
int Epub::getTocItemsCount() const { return toc.size(); }
|
int Epub::getSpineItemsCount() const {
|
||||||
|
if (!bookMetadataCache || !bookMetadataCache->isLoaded()) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
return bookMetadataCache->getSpineCount();
|
||||||
|
}
|
||||||
|
|
||||||
|
size_t Epub::getCumulativeSpineItemSize(const int spineIndex) const { return getSpineItem(spineIndex).cumulativeSize; }
|
||||||
|
|
||||||
|
BookMetadataCache::SpineEntry Epub::getSpineItem(const int spineIndex) const {
|
||||||
|
if (!bookMetadataCache || !bookMetadataCache->isLoaded()) {
|
||||||
|
Serial.printf("[%lu] [EBP] getSpineItem called but cache not loaded\n", millis());
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (spineIndex < 0 || spineIndex >= bookMetadataCache->getSpineCount()) {
|
||||||
|
Serial.printf("[%lu] [EBP] getSpineItem index:%d is out of range\n", millis(), spineIndex);
|
||||||
|
return bookMetadataCache->getSpineEntry(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
return bookMetadataCache->getSpineEntry(spineIndex);
|
||||||
|
}
|
||||||
|
|
||||||
|
BookMetadataCache::TocEntry Epub::getTocItem(const int tocIndex) const {
|
||||||
|
if (!bookMetadataCache || !bookMetadataCache->isLoaded()) {
|
||||||
|
Serial.printf("[%lu] [EBP] getTocItem called but cache not loaded\n", millis());
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (tocIndex < 0 || tocIndex >= bookMetadataCache->getTocCount()) {
|
||||||
|
Serial.printf("[%lu] [EBP] getTocItem index:%d is out of range\n", millis(), tocIndex);
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
|
return bookMetadataCache->getTocEntry(tocIndex);
|
||||||
|
}
|
||||||
|
|
||||||
|
int Epub::getTocItemsCount() const {
|
||||||
|
if (!bookMetadataCache || !bookMetadataCache->isLoaded()) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
return bookMetadataCache->getTocCount();
|
||||||
|
}
|
||||||
|
|
||||||
// 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 {
|
||||||
// the toc entry should have an href that matches the spine item
|
if (!bookMetadataCache || !bookMetadataCache->isLoaded()) {
|
||||||
// so we can find the spine index by looking for the href
|
Serial.printf("[%lu] [EBP] getSpineIndexForTocIndex called but cache not loaded\n", millis());
|
||||||
for (int i = 0; i < spine.size(); i++) {
|
return 0;
|
||||||
if (spine[i].second == toc[tocIndex].href) {
|
|
||||||
return i;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
Serial.println("Section not found");
|
if (tocIndex < 0 || tocIndex >= bookMetadataCache->getTocCount()) {
|
||||||
// not found - default to the start of the book
|
Serial.printf("[%lu] [EBP] getSpineIndexForTocIndex: tocIndex %d out of range\n", millis(), tocIndex);
|
||||||
return 0;
|
return 0;
|
||||||
}
|
|
||||||
|
|
||||||
int Epub::getTocIndexForSpineIndex(const int spineIndex) const {
|
|
||||||
// the toc entry should have an href that matches the spine item
|
|
||||||
// so we can find the toc index by looking for the href
|
|
||||||
for (int i = 0; i < toc.size(); i++) {
|
|
||||||
if (toc[i].href == spine[spineIndex].second) {
|
|
||||||
return i;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
Serial.println("TOC item not found");
|
const int spineIndex = bookMetadataCache->getTocEntry(tocIndex).spineIndex;
|
||||||
// not found - default to first item
|
if (spineIndex < 0) {
|
||||||
return 0;
|
Serial.printf("[%lu] [EBP] Section not found for TOC index %d\n", millis(), tocIndex);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
return spineIndex;
|
||||||
|
}
|
||||||
|
|
||||||
|
int Epub::getTocIndexForSpineIndex(const int spineIndex) const { return getSpineItem(spineIndex).tocIndex; }
|
||||||
|
|
||||||
|
size_t Epub::getBookSize() const {
|
||||||
|
if (!bookMetadataCache || !bookMetadataCache->isLoaded() || bookMetadataCache->getSpineCount() == 0) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
return getCumulativeSpineItemSize(getSpineItemsCount() - 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Calculate progress in book
|
||||||
|
uint8_t Epub::calculateProgress(const int currentSpineIndex, const float currentSpineRead) const {
|
||||||
|
const size_t bookSize = getBookSize();
|
||||||
|
if (bookSize == 0) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
const size_t prevChapterSize = (currentSpineIndex >= 1) ? getCumulativeSpineItemSize(currentSpineIndex - 1) : 0;
|
||||||
|
const size_t curChapterSize = getCumulativeSpineItemSize(currentSpineIndex) - prevChapterSize;
|
||||||
|
const size_t sectionProgSize = currentSpineRead * curChapterSize;
|
||||||
|
return round(static_cast<float>(prevChapterSize + sectionProgSize) / bookSize * 100.0);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,46 +1,30 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
#include <HardwareSerial.h>
|
|
||||||
#include <tinyxml2.h>
|
|
||||||
|
|
||||||
|
#include <memory>
|
||||||
#include <string>
|
#include <string>
|
||||||
#include <unordered_map>
|
#include <unordered_map>
|
||||||
#include <vector>
|
#include <vector>
|
||||||
|
|
||||||
|
#include "Epub/BookMetadataCache.h"
|
||||||
|
|
||||||
class ZipFile;
|
class ZipFile;
|
||||||
|
|
||||||
class EpubTocEntry {
|
|
||||||
public:
|
|
||||||
std::string title;
|
|
||||||
std::string href;
|
|
||||||
std::string anchor;
|
|
||||||
int level;
|
|
||||||
EpubTocEntry(std::string title, std::string href, std::string anchor, const int level)
|
|
||||||
: title(std::move(title)), href(std::move(href)), anchor(std::move(anchor)), level(level) {}
|
|
||||||
};
|
|
||||||
|
|
||||||
class Epub {
|
class Epub {
|
||||||
// the title read from the EPUB meta data
|
|
||||||
std::string title;
|
|
||||||
// the cover image
|
|
||||||
std::string coverImageItem;
|
|
||||||
// the ncx file
|
// the ncx file
|
||||||
std::string tocNcxItem;
|
std::string tocNcxItem;
|
||||||
// where is the EPUBfile?
|
// where is the EPUBfile?
|
||||||
std::string filepath;
|
std::string filepath;
|
||||||
// the spine of the EPUB file
|
|
||||||
std::vector<std::pair<std::string, std::string>> spine;
|
|
||||||
// the toc of the EPUB file
|
|
||||||
std::vector<EpubTocEntry> toc;
|
|
||||||
// the base path for items in the EPUB file
|
// the base path for items in the EPUB file
|
||||||
std::string contentBasePath;
|
std::string contentBasePath;
|
||||||
// Uniq cache key based on filepath
|
// Uniq cache key based on filepath
|
||||||
std::string cachePath;
|
std::string cachePath;
|
||||||
|
// Spine and TOC cache
|
||||||
|
std::unique_ptr<BookMetadataCache> bookMetadataCache;
|
||||||
|
|
||||||
// find the path for the content.opf file
|
bool findContentOpfFile(std::string* contentOpfFile) const;
|
||||||
static bool findContentOpfFile(const ZipFile& zip, std::string& contentOpfFile);
|
bool parseContentOpf(BookMetadataCache::BookMetadata& bookMetadata);
|
||||||
bool parseContentOpf(ZipFile& zip, std::string& content_opf_file);
|
bool parseTocNcxFile() const;
|
||||||
bool parseTocNcxFile(const ZipFile& zip);
|
static bool getItemSize(const ZipFile& zip, const std::string& itemHref, size_t* size);
|
||||||
void recursivelyParseNavMap(tinyxml2::XMLElement* element);
|
|
||||||
|
|
||||||
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)) {
|
||||||
@@ -50,19 +34,25 @@ class Epub {
|
|||||||
~Epub() = default;
|
~Epub() = default;
|
||||||
std::string& getBasePath() { return contentBasePath; }
|
std::string& getBasePath() { return contentBasePath; }
|
||||||
bool load();
|
bool load();
|
||||||
void clearCache() const;
|
bool clearCache() const;
|
||||||
void setupCacheDir() const;
|
void setupCacheDir() const;
|
||||||
const std::string& getCachePath() const;
|
const std::string& getCachePath() const;
|
||||||
const std::string& getPath() const;
|
const std::string& getPath() const;
|
||||||
const std::string& getTitle() const;
|
const std::string& getTitle() const;
|
||||||
const std::string& getCoverImageItem() const;
|
std::string getCoverBmpPath() const;
|
||||||
|
bool generateCoverBmp() 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;
|
||||||
std::string& getSpineItem(int spineIndex);
|
bool getItemSize(const std::string& itemHref, size_t* size) const;
|
||||||
|
BookMetadataCache::SpineEntry getSpineItem(int spineIndex) const;
|
||||||
|
BookMetadataCache::TocEntry getTocItem(int tocIndex) const;
|
||||||
int getSpineItemsCount() const;
|
int getSpineItemsCount() const;
|
||||||
EpubTocEntry& getTocItem(int tocTndex);
|
|
||||||
int getTocItemsCount() const;
|
int getTocItemsCount() const;
|
||||||
int getSpineIndexForTocIndex(int tocIndex) const;
|
int getSpineIndexForTocIndex(int tocIndex) const;
|
||||||
int getTocIndexForSpineIndex(int spineIndex) const;
|
int getTocIndexForSpineIndex(int spineIndex) const;
|
||||||
|
size_t getCumulativeSpineItemSize(int spineIndex) const;
|
||||||
|
|
||||||
|
size_t getBookSize() const;
|
||||||
|
uint8_t calculateProgress(const int currentSpineIndex, const float currentSpineRead) const;
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -0,0 +1,326 @@
|
|||||||
|
#include "BookMetadataCache.h"
|
||||||
|
|
||||||
|
#include <HardwareSerial.h>
|
||||||
|
#include <SD.h>
|
||||||
|
#include <Serialization.h>
|
||||||
|
#include <ZipFile.h>
|
||||||
|
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
#include "FsHelpers.h"
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
constexpr uint8_t BOOK_CACHE_VERSION = 1;
|
||||||
|
constexpr char bookBinFile[] = "/book.bin";
|
||||||
|
constexpr char tmpSpineBinFile[] = "/spine.bin.tmp";
|
||||||
|
constexpr char tmpTocBinFile[] = "/toc.bin.tmp";
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
/* ============= WRITING / BUILDING FUNCTIONS ================ */
|
||||||
|
|
||||||
|
bool BookMetadataCache::beginWrite() {
|
||||||
|
buildMode = true;
|
||||||
|
spineCount = 0;
|
||||||
|
tocCount = 0;
|
||||||
|
Serial.printf("[%lu] [BMC] Entering write mode\n", millis());
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool BookMetadataCache::beginContentOpfPass() {
|
||||||
|
Serial.printf("[%lu] [BMC] Beginning content opf pass\n", millis());
|
||||||
|
|
||||||
|
// Open spine file for writing
|
||||||
|
return FsHelpers::openFileForWrite("BMC", cachePath + tmpSpineBinFile, spineFile);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool BookMetadataCache::endContentOpfPass() {
|
||||||
|
spineFile.close();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool BookMetadataCache::beginTocPass() {
|
||||||
|
Serial.printf("[%lu] [BMC] Beginning toc pass\n", millis());
|
||||||
|
|
||||||
|
// Open spine file for reading
|
||||||
|
if (!FsHelpers::openFileForRead("BMC", cachePath + tmpSpineBinFile, spineFile)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (!FsHelpers::openFileForWrite("BMC", cachePath + tmpTocBinFile, tocFile)) {
|
||||||
|
spineFile.close();
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool BookMetadataCache::endTocPass() {
|
||||||
|
tocFile.close();
|
||||||
|
spineFile.close();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool BookMetadataCache::endWrite() {
|
||||||
|
if (!buildMode) {
|
||||||
|
Serial.printf("[%lu] [BMC] endWrite called but not in build mode\n", millis());
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
buildMode = false;
|
||||||
|
Serial.printf("[%lu] [BMC] Wrote %d spine, %d TOC entries\n", millis(), spineCount, tocCount);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool BookMetadataCache::buildBookBin(const std::string& epubPath, const BookMetadata& metadata) {
|
||||||
|
// Open all three files, writing to meta, reading from spine and toc
|
||||||
|
if (!FsHelpers::openFileForWrite("BMC", cachePath + bookBinFile, bookFile)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!FsHelpers::openFileForRead("BMC", cachePath + tmpSpineBinFile, spineFile)) {
|
||||||
|
bookFile.close();
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!FsHelpers::openFileForRead("BMC", cachePath + tmpTocBinFile, tocFile)) {
|
||||||
|
bookFile.close();
|
||||||
|
spineFile.close();
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
constexpr size_t headerASize =
|
||||||
|
sizeof(BOOK_CACHE_VERSION) + /* LUT Offset */ sizeof(size_t) + sizeof(spineCount) + sizeof(tocCount);
|
||||||
|
const size_t metadataSize =
|
||||||
|
metadata.title.size() + metadata.author.size() + metadata.coverItemHref.size() + sizeof(uint32_t) * 3;
|
||||||
|
const size_t lutSize = sizeof(size_t) * spineCount + sizeof(size_t) * tocCount;
|
||||||
|
const size_t lutOffset = headerASize + metadataSize;
|
||||||
|
|
||||||
|
// Header A
|
||||||
|
serialization::writePod(bookFile, BOOK_CACHE_VERSION);
|
||||||
|
serialization::writePod(bookFile, lutOffset);
|
||||||
|
serialization::writePod(bookFile, spineCount);
|
||||||
|
serialization::writePod(bookFile, tocCount);
|
||||||
|
// Metadata
|
||||||
|
serialization::writeString(bookFile, metadata.title);
|
||||||
|
serialization::writeString(bookFile, metadata.author);
|
||||||
|
serialization::writeString(bookFile, metadata.coverItemHref);
|
||||||
|
|
||||||
|
// Loop through spine entries, writing LUT positions
|
||||||
|
spineFile.seek(0);
|
||||||
|
for (int i = 0; i < spineCount; i++) {
|
||||||
|
auto pos = spineFile.position();
|
||||||
|
auto spineEntry = readSpineEntry(spineFile);
|
||||||
|
serialization::writePod(bookFile, pos + lutOffset + lutSize);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Loop through toc entries, writing LUT positions
|
||||||
|
tocFile.seek(0);
|
||||||
|
for (int i = 0; i < tocCount; i++) {
|
||||||
|
auto pos = tocFile.position();
|
||||||
|
auto tocEntry = readTocEntry(tocFile);
|
||||||
|
serialization::writePod(bookFile, pos + lutOffset + lutSize + spineFile.position());
|
||||||
|
}
|
||||||
|
|
||||||
|
// LUTs complete
|
||||||
|
// Loop through spines from spine file matching up TOC indexes, calculating cumulative size and writing to book.bin
|
||||||
|
|
||||||
|
const ZipFile zip("/sd" + epubPath);
|
||||||
|
size_t cumSize = 0;
|
||||||
|
spineFile.seek(0);
|
||||||
|
for (int i = 0; i < spineCount; i++) {
|
||||||
|
auto spineEntry = readSpineEntry(spineFile);
|
||||||
|
|
||||||
|
tocFile.seek(0);
|
||||||
|
for (int j = 0; j < tocCount; j++) {
|
||||||
|
auto tocEntry = readTocEntry(tocFile);
|
||||||
|
if (tocEntry.spineIndex == i) {
|
||||||
|
spineEntry.tocIndex = j;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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
|
||||||
|
if (spineEntry.tocIndex == -1) {
|
||||||
|
Serial.printf("[%lu] [BMC] Warning: Could not find TOC entry for spine item %d: %s\n", millis(), i,
|
||||||
|
spineEntry.href.c_str());
|
||||||
|
}
|
||||||
|
|
||||||
|
// Calculate size for cumulative size
|
||||||
|
size_t itemSize = 0;
|
||||||
|
const std::string path = FsHelpers::normalisePath(spineEntry.href);
|
||||||
|
if (zip.getInflatedFileSize(path.c_str(), &itemSize)) {
|
||||||
|
cumSize += itemSize;
|
||||||
|
spineEntry.cumulativeSize = cumSize;
|
||||||
|
} else {
|
||||||
|
Serial.printf("[%lu] [BMC] Warning: Could not get size for spine item: %s\n", millis(), path.c_str());
|
||||||
|
}
|
||||||
|
|
||||||
|
// Write out spine data to book.bin
|
||||||
|
writeSpineEntry(bookFile, spineEntry);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Loop through toc entries from toc file writing to book.bin
|
||||||
|
tocFile.seek(0);
|
||||||
|
for (int i = 0; i < tocCount; i++) {
|
||||||
|
auto tocEntry = readTocEntry(tocFile);
|
||||||
|
writeTocEntry(bookFile, tocEntry);
|
||||||
|
}
|
||||||
|
|
||||||
|
bookFile.close();
|
||||||
|
spineFile.close();
|
||||||
|
tocFile.close();
|
||||||
|
|
||||||
|
Serial.printf("[%lu] [BMC] Successfully built book.bin\n", millis());
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool BookMetadataCache::cleanupTmpFiles() const {
|
||||||
|
if (SD.exists((cachePath + tmpSpineBinFile).c_str())) {
|
||||||
|
SD.remove((cachePath + tmpSpineBinFile).c_str());
|
||||||
|
}
|
||||||
|
if (SD.exists((cachePath + tmpTocBinFile).c_str())) {
|
||||||
|
SD.remove((cachePath + tmpTocBinFile).c_str());
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
size_t BookMetadataCache::writeSpineEntry(File& file, const SpineEntry& entry) const {
|
||||||
|
const auto pos = file.position();
|
||||||
|
serialization::writeString(file, entry.href);
|
||||||
|
serialization::writePod(file, entry.cumulativeSize);
|
||||||
|
serialization::writePod(file, entry.tocIndex);
|
||||||
|
return pos;
|
||||||
|
}
|
||||||
|
|
||||||
|
size_t BookMetadataCache::writeTocEntry(File& file, const TocEntry& entry) const {
|
||||||
|
const auto pos = file.position();
|
||||||
|
serialization::writeString(file, entry.title);
|
||||||
|
serialization::writeString(file, entry.href);
|
||||||
|
serialization::writeString(file, entry.anchor);
|
||||||
|
serialization::writePod(file, entry.level);
|
||||||
|
serialization::writePod(file, entry.spineIndex);
|
||||||
|
return pos;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Note: for the LUT to be accurate, this **MUST** be called for all spine items before `addTocEntry` is ever called
|
||||||
|
// this is because in this function we're marking positions of the items
|
||||||
|
void BookMetadataCache::createSpineEntry(const std::string& href) {
|
||||||
|
if (!buildMode || !spineFile) {
|
||||||
|
Serial.printf("[%lu] [BMC] createSpineEntry called but not in build mode\n", millis());
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const SpineEntry entry(href, 0, -1);
|
||||||
|
writeSpineEntry(spineFile, entry);
|
||||||
|
spineCount++;
|
||||||
|
}
|
||||||
|
|
||||||
|
void BookMetadataCache::createTocEntry(const std::string& title, const std::string& href, const std::string& anchor,
|
||||||
|
const uint8_t level) {
|
||||||
|
if (!buildMode || !tocFile || !spineFile) {
|
||||||
|
Serial.printf("[%lu] [BMC] createTocEntry called but not in build mode\n", millis());
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
int spineIndex = -1;
|
||||||
|
// find spine index
|
||||||
|
spineFile.seek(0);
|
||||||
|
for (int i = 0; i < spineCount; i++) {
|
||||||
|
auto spineEntry = readSpineEntry(spineFile);
|
||||||
|
if (spineEntry.href == href) {
|
||||||
|
spineIndex = i;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (spineIndex == -1) {
|
||||||
|
Serial.printf("[%lu] [BMC] addTocEntry: Could not find spine item for TOC href %s\n", millis(), href.c_str());
|
||||||
|
}
|
||||||
|
|
||||||
|
const TocEntry entry(title, href, anchor, level, spineIndex);
|
||||||
|
writeTocEntry(tocFile, entry);
|
||||||
|
tocCount++;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ============= READING / LOADING FUNCTIONS ================ */
|
||||||
|
|
||||||
|
bool BookMetadataCache::load() {
|
||||||
|
if (!FsHelpers::openFileForRead("BMC", cachePath + bookBinFile, bookFile)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
uint8_t version;
|
||||||
|
serialization::readPod(bookFile, version);
|
||||||
|
if (version != BOOK_CACHE_VERSION) {
|
||||||
|
Serial.printf("[%lu] [BMC] Cache version mismatch: expected %d, got %d\n", millis(), BOOK_CACHE_VERSION, version);
|
||||||
|
bookFile.close();
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
serialization::readPod(bookFile, lutOffset);
|
||||||
|
serialization::readPod(bookFile, spineCount);
|
||||||
|
serialization::readPod(bookFile, tocCount);
|
||||||
|
|
||||||
|
serialization::readString(bookFile, coreMetadata.title);
|
||||||
|
serialization::readString(bookFile, coreMetadata.author);
|
||||||
|
serialization::readString(bookFile, coreMetadata.coverItemHref);
|
||||||
|
|
||||||
|
loaded = true;
|
||||||
|
Serial.printf("[%lu] [BMC] Loaded cache data: %d spine, %d TOC entries\n", millis(), spineCount, tocCount);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
BookMetadataCache::SpineEntry BookMetadataCache::getSpineEntry(const int index) {
|
||||||
|
if (!loaded) {
|
||||||
|
Serial.printf("[%lu] [BMC] getSpineEntry called but cache not loaded\n", millis());
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (index < 0 || index >= static_cast<int>(spineCount)) {
|
||||||
|
Serial.printf("[%lu] [BMC] getSpineEntry index %d out of range\n", millis(), index);
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Seek to spine LUT item, read from LUT and get out data
|
||||||
|
bookFile.seek(lutOffset + sizeof(size_t) * index);
|
||||||
|
size_t spineEntryPos;
|
||||||
|
serialization::readPod(bookFile, spineEntryPos);
|
||||||
|
bookFile.seek(spineEntryPos);
|
||||||
|
return readSpineEntry(bookFile);
|
||||||
|
}
|
||||||
|
|
||||||
|
BookMetadataCache::TocEntry BookMetadataCache::getTocEntry(const int index) {
|
||||||
|
if (!loaded) {
|
||||||
|
Serial.printf("[%lu] [BMC] getTocEntry called but cache not loaded\n", millis());
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (index < 0 || index >= static_cast<int>(tocCount)) {
|
||||||
|
Serial.printf("[%lu] [BMC] getTocEntry index %d out of range\n", millis(), index);
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Seek to TOC LUT item, read from LUT and get out data
|
||||||
|
bookFile.seek(lutOffset + sizeof(size_t) * spineCount + sizeof(size_t) * index);
|
||||||
|
size_t tocEntryPos;
|
||||||
|
serialization::readPod(bookFile, tocEntryPos);
|
||||||
|
bookFile.seek(tocEntryPos);
|
||||||
|
return readTocEntry(bookFile);
|
||||||
|
}
|
||||||
|
|
||||||
|
BookMetadataCache::SpineEntry BookMetadataCache::readSpineEntry(File& file) const {
|
||||||
|
SpineEntry entry;
|
||||||
|
serialization::readString(file, entry.href);
|
||||||
|
serialization::readPod(file, entry.cumulativeSize);
|
||||||
|
serialization::readPod(file, entry.tocIndex);
|
||||||
|
return entry;
|
||||||
|
}
|
||||||
|
|
||||||
|
BookMetadataCache::TocEntry BookMetadataCache::readTocEntry(File& file) const {
|
||||||
|
TocEntry entry;
|
||||||
|
serialization::readString(file, entry.title);
|
||||||
|
serialization::readString(file, entry.href);
|
||||||
|
serialization::readString(file, entry.anchor);
|
||||||
|
serialization::readPod(file, entry.level);
|
||||||
|
serialization::readPod(file, entry.spineIndex);
|
||||||
|
return entry;
|
||||||
|
}
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <SD.h>
|
||||||
|
|
||||||
|
#include <string>
|
||||||
|
|
||||||
|
class BookMetadataCache {
|
||||||
|
public:
|
||||||
|
struct BookMetadata {
|
||||||
|
std::string title;
|
||||||
|
std::string author;
|
||||||
|
std::string coverItemHref;
|
||||||
|
};
|
||||||
|
|
||||||
|
struct SpineEntry {
|
||||||
|
std::string href;
|
||||||
|
size_t cumulativeSize;
|
||||||
|
int16_t tocIndex;
|
||||||
|
|
||||||
|
SpineEntry() : cumulativeSize(0), tocIndex(-1) {}
|
||||||
|
SpineEntry(std::string href, const size_t cumulativeSize, const int16_t tocIndex)
|
||||||
|
: href(std::move(href)), cumulativeSize(cumulativeSize), tocIndex(tocIndex) {}
|
||||||
|
};
|
||||||
|
|
||||||
|
struct TocEntry {
|
||||||
|
std::string title;
|
||||||
|
std::string href;
|
||||||
|
std::string anchor;
|
||||||
|
uint8_t level;
|
||||||
|
int16_t spineIndex;
|
||||||
|
|
||||||
|
TocEntry() : level(0), spineIndex(-1) {}
|
||||||
|
TocEntry(std::string title, std::string href, std::string anchor, const uint8_t level, const int16_t spineIndex)
|
||||||
|
: title(std::move(title)),
|
||||||
|
href(std::move(href)),
|
||||||
|
anchor(std::move(anchor)),
|
||||||
|
level(level),
|
||||||
|
spineIndex(spineIndex) {}
|
||||||
|
};
|
||||||
|
|
||||||
|
private:
|
||||||
|
std::string cachePath;
|
||||||
|
size_t lutOffset;
|
||||||
|
uint16_t spineCount;
|
||||||
|
uint16_t tocCount;
|
||||||
|
bool loaded;
|
||||||
|
bool buildMode;
|
||||||
|
|
||||||
|
File bookFile;
|
||||||
|
// Temp file handles during build
|
||||||
|
File spineFile;
|
||||||
|
File tocFile;
|
||||||
|
|
||||||
|
size_t writeSpineEntry(File& file, const SpineEntry& entry) const;
|
||||||
|
size_t writeTocEntry(File& file, const TocEntry& entry) const;
|
||||||
|
SpineEntry readSpineEntry(File& file) const;
|
||||||
|
TocEntry readTocEntry(File& file) const;
|
||||||
|
|
||||||
|
public:
|
||||||
|
BookMetadata coreMetadata;
|
||||||
|
|
||||||
|
explicit BookMetadataCache(std::string cachePath)
|
||||||
|
: cachePath(std::move(cachePath)), lutOffset(0), spineCount(0), tocCount(0), loaded(false), buildMode(false) {}
|
||||||
|
~BookMetadataCache() = default;
|
||||||
|
|
||||||
|
// Building phase (stream to disk immediately)
|
||||||
|
bool beginWrite();
|
||||||
|
bool beginContentOpfPass();
|
||||||
|
void createSpineEntry(const std::string& href);
|
||||||
|
bool endContentOpfPass();
|
||||||
|
bool beginTocPass();
|
||||||
|
void createTocEntry(const std::string& title, const std::string& href, const std::string& anchor, uint8_t level);
|
||||||
|
bool endTocPass();
|
||||||
|
bool endWrite();
|
||||||
|
bool cleanupTmpFiles() const;
|
||||||
|
|
||||||
|
// Post-processing to update mappings and sizes
|
||||||
|
bool buildBookBin(const std::string& epubPath, const BookMetadata& metadata);
|
||||||
|
|
||||||
|
// Reading phase (read mode)
|
||||||
|
bool load();
|
||||||
|
SpineEntry getSpineEntry(int index);
|
||||||
|
TocEntry getTocEntry(int index);
|
||||||
|
int getSpineCount() const { return spineCount; }
|
||||||
|
int getTocCount() const { return tocCount; }
|
||||||
|
bool isLoaded() const { return loaded; }
|
||||||
|
};
|
||||||
@@ -1,293 +0,0 @@
|
|||||||
#include "EpubHtmlParserSlim.h"
|
|
||||||
|
|
||||||
#include <EpdRenderer.h>
|
|
||||||
#include <HardwareSerial.h>
|
|
||||||
#include <expat.h>
|
|
||||||
|
|
||||||
#include "Page.h"
|
|
||||||
#include "htmlEntities.h"
|
|
||||||
|
|
||||||
const char* HEADER_TAGS[] = {"h1", "h2", "h3", "h4", "h5", "h6"};
|
|
||||||
constexpr int NUM_HEADER_TAGS = sizeof(HEADER_TAGS) / sizeof(HEADER_TAGS[0]);
|
|
||||||
|
|
||||||
const char* BLOCK_TAGS[] = {"p", "li", "div", "br"};
|
|
||||||
constexpr int NUM_BLOCK_TAGS = sizeof(BLOCK_TAGS) / sizeof(BLOCK_TAGS[0]);
|
|
||||||
|
|
||||||
const char* BOLD_TAGS[] = {"b"};
|
|
||||||
constexpr int NUM_BOLD_TAGS = sizeof(BOLD_TAGS) / sizeof(BOLD_TAGS[0]);
|
|
||||||
|
|
||||||
const char* ITALIC_TAGS[] = {"i"};
|
|
||||||
constexpr int NUM_ITALIC_TAGS = sizeof(ITALIC_TAGS) / sizeof(ITALIC_TAGS[0]);
|
|
||||||
|
|
||||||
const char* IMAGE_TAGS[] = {"img"};
|
|
||||||
constexpr int NUM_IMAGE_TAGS = sizeof(IMAGE_TAGS) / sizeof(IMAGE_TAGS[0]);
|
|
||||||
|
|
||||||
const char* SKIP_TAGS[] = {"head", "table"};
|
|
||||||
constexpr int NUM_SKIP_TAGS = sizeof(SKIP_TAGS) / sizeof(SKIP_TAGS[0]);
|
|
||||||
|
|
||||||
bool isWhitespace(const char c) { return c == ' ' || c == '\r' || c == '\n'; }
|
|
||||||
|
|
||||||
// given the start and end of a tag, check to see if it matches a known tag
|
|
||||||
bool matches(const char* tag_name, const char* possible_tags[], const int possible_tag_count) {
|
|
||||||
for (int i = 0; i < possible_tag_count; i++) {
|
|
||||||
if (strcmp(tag_name, possible_tags[i]) == 0) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
// start a new text block if needed
|
|
||||||
void EpubHtmlParserSlim::startNewTextBlock(const BLOCK_STYLE style) {
|
|
||||||
if (currentTextBlock) {
|
|
||||||
// already have a text block running and it is empty - just reuse it
|
|
||||||
if (currentTextBlock->isEmpty()) {
|
|
||||||
currentTextBlock->setStyle(style);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
currentTextBlock->finish();
|
|
||||||
makePages();
|
|
||||||
delete currentTextBlock;
|
|
||||||
}
|
|
||||||
currentTextBlock = new TextBlock(style);
|
|
||||||
}
|
|
||||||
|
|
||||||
void XMLCALL EpubHtmlParserSlim::startElement(void* userData, const XML_Char* name, const XML_Char** atts) {
|
|
||||||
auto* self = static_cast<EpubHtmlParserSlim*>(userData);
|
|
||||||
(void)atts;
|
|
||||||
|
|
||||||
// Middle of skip
|
|
||||||
if (self->skipUntilDepth < self->depth) {
|
|
||||||
self->depth += 1;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (matches(name, IMAGE_TAGS, NUM_IMAGE_TAGS)) {
|
|
||||||
// const char* src = element.Attribute("src");
|
|
||||||
// if (src) {
|
|
||||||
// // don't leave an empty text block in the list
|
|
||||||
// // const BLOCK_STYLE style = currentTextBlock->get_style();
|
|
||||||
// if (currentTextBlock->isEmpty()) {
|
|
||||||
// delete currentTextBlock;
|
|
||||||
// currentTextBlock = nullptr;
|
|
||||||
// }
|
|
||||||
// // TODO: Fix this
|
|
||||||
// // blocks.push_back(new ImageBlock(m_base_path + src));
|
|
||||||
// // start a new text block - with the same style as before
|
|
||||||
// // startNewTextBlock(style);
|
|
||||||
// } else {
|
|
||||||
// // ESP_LOGE(TAG, "Could not find src attribute");
|
|
||||||
// }
|
|
||||||
|
|
||||||
// start skip
|
|
||||||
self->skipUntilDepth = self->depth;
|
|
||||||
self->depth += 1;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (matches(name, SKIP_TAGS, NUM_SKIP_TAGS)) {
|
|
||||||
// start skip
|
|
||||||
self->skipUntilDepth = self->depth;
|
|
||||||
self->depth += 1;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (matches(name, HEADER_TAGS, NUM_HEADER_TAGS)) {
|
|
||||||
self->startNewTextBlock(CENTER_ALIGN);
|
|
||||||
self->boldUntilDepth = min(self->boldUntilDepth, self->depth);
|
|
||||||
} else if (matches(name, BLOCK_TAGS, NUM_BLOCK_TAGS)) {
|
|
||||||
if (strcmp(name, "br") == 0) {
|
|
||||||
self->startNewTextBlock(self->currentTextBlock->getStyle());
|
|
||||||
} else {
|
|
||||||
self->startNewTextBlock(JUSTIFIED);
|
|
||||||
}
|
|
||||||
} else if (matches(name, BOLD_TAGS, NUM_BOLD_TAGS)) {
|
|
||||||
self->boldUntilDepth = min(self->boldUntilDepth, self->depth);
|
|
||||||
} else if (matches(name, ITALIC_TAGS, NUM_ITALIC_TAGS)) {
|
|
||||||
self->italicUntilDepth = min(self->italicUntilDepth, self->depth);
|
|
||||||
}
|
|
||||||
|
|
||||||
self->depth += 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
void XMLCALL EpubHtmlParserSlim::characterData(void* userData, const XML_Char* s, const int len) {
|
|
||||||
auto* self = static_cast<EpubHtmlParserSlim*>(userData);
|
|
||||||
|
|
||||||
// Middle of skip
|
|
||||||
if (self->skipUntilDepth < self->depth) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
for (int i = 0; i < len; i++) {
|
|
||||||
if (isWhitespace(s[i])) {
|
|
||||||
// Currently looking at whitespace, if there's anything in the partWordBuffer, flush it
|
|
||||||
if (self->partWordBufferIndex > 0) {
|
|
||||||
self->partWordBuffer[self->partWordBufferIndex] = '\0';
|
|
||||||
self->currentTextBlock->addWord(replaceHtmlEntities(self->partWordBuffer), self->boldUntilDepth < self->depth,
|
|
||||||
self->italicUntilDepth < self->depth);
|
|
||||||
self->partWordBufferIndex = 0;
|
|
||||||
}
|
|
||||||
// Skip the whitespace char
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
// If we're about to run out of space, then cut the word off and start a new one
|
|
||||||
if (self->partWordBufferIndex >= PART_WORD_BUFFER_SIZE - 2) {
|
|
||||||
self->partWordBuffer[self->partWordBufferIndex] = '\0';
|
|
||||||
self->currentTextBlock->addWord(replaceHtmlEntities(self->partWordBuffer), self->boldUntilDepth < self->depth,
|
|
||||||
self->italicUntilDepth < self->depth);
|
|
||||||
self->partWordBufferIndex = 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
self->partWordBuffer[self->partWordBufferIndex++] = s[i];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void XMLCALL EpubHtmlParserSlim::endElement(void* userData, const XML_Char* name) {
|
|
||||||
auto* self = static_cast<EpubHtmlParserSlim*>(userData);
|
|
||||||
(void)name;
|
|
||||||
|
|
||||||
if (self->partWordBufferIndex > 0) {
|
|
||||||
// Only flush out part word buffer if we're closing a block tag or are at the top of the HTML file.
|
|
||||||
// We don't want to flush out content when closing inline tags like <span>.
|
|
||||||
// Currently this also flushes out on closing <b> and <i> tags, but they are line tags so that shouldn't happen,
|
|
||||||
// text styling needs to be overhauled to fix it.
|
|
||||||
const bool shouldBreakText =
|
|
||||||
matches(name, BLOCK_TAGS, NUM_BLOCK_TAGS) || matches(name, HEADER_TAGS, NUM_HEADER_TAGS) ||
|
|
||||||
matches(name, BOLD_TAGS, NUM_BOLD_TAGS) || matches(name, ITALIC_TAGS, NUM_ITALIC_TAGS) || self->depth == 1;
|
|
||||||
|
|
||||||
if (shouldBreakText) {
|
|
||||||
self->partWordBuffer[self->partWordBufferIndex] = '\0';
|
|
||||||
self->currentTextBlock->addWord(replaceHtmlEntities(self->partWordBuffer), self->boldUntilDepth < self->depth,
|
|
||||||
self->italicUntilDepth < self->depth);
|
|
||||||
self->partWordBufferIndex = 0;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
self->depth -= 1;
|
|
||||||
|
|
||||||
// Leaving skip
|
|
||||||
if (self->skipUntilDepth == self->depth) {
|
|
||||||
self->skipUntilDepth = INT_MAX;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Leaving bold
|
|
||||||
if (self->boldUntilDepth == self->depth) {
|
|
||||||
self->boldUntilDepth = INT_MAX;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Leaving italic
|
|
||||||
if (self->italicUntilDepth == self->depth) {
|
|
||||||
self->italicUntilDepth = INT_MAX;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
bool EpubHtmlParserSlim::parseAndBuildPages() {
|
|
||||||
startNewTextBlock(JUSTIFIED);
|
|
||||||
|
|
||||||
const XML_Parser parser = XML_ParserCreate(nullptr);
|
|
||||||
int done;
|
|
||||||
|
|
||||||
if (!parser) {
|
|
||||||
Serial.println("Couldn't allocate memory for parser");
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
XML_SetUserData(parser, this);
|
|
||||||
XML_SetElementHandler(parser, startElement, endElement);
|
|
||||||
XML_SetCharacterDataHandler(parser, characterData);
|
|
||||||
|
|
||||||
FILE* file = fopen(filepath, "r");
|
|
||||||
if (!file) {
|
|
||||||
Serial.printf("Couldn't open file %s\n", filepath);
|
|
||||||
XML_ParserFree(parser);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
do {
|
|
||||||
void* const buf = XML_GetBuffer(parser, 1024);
|
|
||||||
if (!buf) {
|
|
||||||
Serial.println("Couldn't allocate memory for buffer");
|
|
||||||
XML_ParserFree(parser);
|
|
||||||
fclose(file);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
const size_t len = fread(buf, 1, 1024, file);
|
|
||||||
|
|
||||||
if (ferror(file)) {
|
|
||||||
Serial.println("Read error");
|
|
||||||
XML_ParserFree(parser);
|
|
||||||
fclose(file);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
done = feof(file);
|
|
||||||
|
|
||||||
if (XML_ParseBuffer(parser, static_cast<int>(len), done) == XML_STATUS_ERROR) {
|
|
||||||
Serial.printf("Parse error at line %lu:\n%s\n", XML_GetCurrentLineNumber(parser),
|
|
||||||
XML_ErrorString(XML_GetErrorCode(parser)));
|
|
||||||
XML_ParserFree(parser);
|
|
||||||
fclose(file);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
} while (!done);
|
|
||||||
|
|
||||||
XML_ParserFree(parser);
|
|
||||||
fclose(file);
|
|
||||||
|
|
||||||
// Process last page if there is still text
|
|
||||||
if (currentTextBlock) {
|
|
||||||
makePages();
|
|
||||||
completePageFn(currentPage);
|
|
||||||
currentPage = nullptr;
|
|
||||||
delete currentTextBlock;
|
|
||||||
currentTextBlock = nullptr;
|
|
||||||
}
|
|
||||||
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
void EpubHtmlParserSlim::makePages() {
|
|
||||||
if (!currentTextBlock) {
|
|
||||||
Serial.println("!! No text block to make pages for !!");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!currentPage) {
|
|
||||||
currentPage = new Page();
|
|
||||||
}
|
|
||||||
|
|
||||||
const int lineHeight = renderer.getLineHeight();
|
|
||||||
const int pageHeight = renderer.getPageHeight();
|
|
||||||
|
|
||||||
// Long running task, make sure to let other things happen
|
|
||||||
vTaskDelay(1);
|
|
||||||
|
|
||||||
if (currentTextBlock->getType() == TEXT_BLOCK) {
|
|
||||||
const auto lines = currentTextBlock->splitIntoLines(renderer);
|
|
||||||
|
|
||||||
for (const auto line : lines) {
|
|
||||||
if (currentPage->nextY + lineHeight > pageHeight) {
|
|
||||||
completePageFn(currentPage);
|
|
||||||
currentPage = new Page();
|
|
||||||
}
|
|
||||||
|
|
||||||
currentPage->elements.push_back(new PageLine(line, currentPage->nextY));
|
|
||||||
currentPage->nextY += lineHeight;
|
|
||||||
}
|
|
||||||
// add some extra line between blocks
|
|
||||||
currentPage->nextY += lineHeight / 2;
|
|
||||||
}
|
|
||||||
// TODO: Image block support
|
|
||||||
// if (block->getType() == BlockType::IMAGE_BLOCK) {
|
|
||||||
// ImageBlock *imageBlock = (ImageBlock *)block;
|
|
||||||
// if (y + imageBlock->height > page_height) {
|
|
||||||
// pages.push_back(new Page());
|
|
||||||
// y = 0;
|
|
||||||
// }
|
|
||||||
// pages.back()->elements.push_back(new PageImage(imageBlock, y));
|
|
||||||
// y += imageBlock->height;
|
|
||||||
// }
|
|
||||||
}
|
|
||||||
@@ -1,42 +0,0 @@
|
|||||||
#pragma once
|
|
||||||
|
|
||||||
#include <expat.h>
|
|
||||||
#include <limits.h>
|
|
||||||
|
|
||||||
#include <functional>
|
|
||||||
|
|
||||||
#include "blocks/TextBlock.h"
|
|
||||||
|
|
||||||
class Page;
|
|
||||||
class EpdRenderer;
|
|
||||||
|
|
||||||
#define PART_WORD_BUFFER_SIZE 200
|
|
||||||
|
|
||||||
class EpubHtmlParserSlim {
|
|
||||||
const char* filepath;
|
|
||||||
EpdRenderer& renderer;
|
|
||||||
std::function<void(Page*)> completePageFn;
|
|
||||||
int depth = 0;
|
|
||||||
int skipUntilDepth = INT_MAX;
|
|
||||||
int boldUntilDepth = INT_MAX;
|
|
||||||
int italicUntilDepth = INT_MAX;
|
|
||||||
// If we encounter words longer than this, but this is pretty large
|
|
||||||
char partWordBuffer[PART_WORD_BUFFER_SIZE] = {};
|
|
||||||
int partWordBufferIndex = 0;
|
|
||||||
TextBlock* currentTextBlock = nullptr;
|
|
||||||
Page* currentPage = nullptr;
|
|
||||||
|
|
||||||
void startNewTextBlock(BLOCK_STYLE style);
|
|
||||||
void makePages();
|
|
||||||
// XML callbacks
|
|
||||||
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 endElement(void* userData, const XML_Char* name);
|
|
||||||
|
|
||||||
public:
|
|
||||||
explicit EpubHtmlParserSlim(const char* filepath, EpdRenderer& renderer,
|
|
||||||
const std::function<void(Page*)>& completePageFn)
|
|
||||||
: filepath(filepath), renderer(renderer), completePageFn(completePageFn) {}
|
|
||||||
~EpubHtmlParserSlim() = default;
|
|
||||||
bool parseAndBuildPages();
|
|
||||||
};
|
|
||||||
@@ -0,0 +1,92 @@
|
|||||||
|
#include "FsHelpers.h"
|
||||||
|
|
||||||
|
#include <SD.h>
|
||||||
|
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
bool FsHelpers::openFileForRead(const char* moduleName, const std::string& path, File& file) {
|
||||||
|
file = SD.open(path.c_str(), FILE_READ);
|
||||||
|
if (!file) {
|
||||||
|
Serial.printf("[%lu] [%s] Failed to open file for reading: %s\n", millis(), moduleName, path.c_str());
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool FsHelpers::openFileForWrite(const char* moduleName, const std::string& path, File& file) {
|
||||||
|
file = SD.open(path.c_str(), FILE_WRITE, true);
|
||||||
|
if (!file) {
|
||||||
|
Serial.printf("[%lu] [%s] Failed to open file for writing: %s\n", millis(), moduleName, path.c_str());
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool FsHelpers::removeDir(const char* path) {
|
||||||
|
// 1. Open the directory
|
||||||
|
File dir = SD.open(path);
|
||||||
|
if (!dir) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (!dir.isDirectory()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
File file = dir.openNextFile();
|
||||||
|
while (file) {
|
||||||
|
String filePath = path;
|
||||||
|
if (!filePath.endsWith("/")) {
|
||||||
|
filePath += "/";
|
||||||
|
}
|
||||||
|
filePath += file.name();
|
||||||
|
|
||||||
|
if (file.isDirectory()) {
|
||||||
|
if (!removeDir(filePath.c_str())) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if (!SD.remove(filePath.c_str())) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
file = dir.openNextFile();
|
||||||
|
}
|
||||||
|
|
||||||
|
return SD.rmdir(path);
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string FsHelpers::normalisePath(const std::string& path) {
|
||||||
|
std::vector<std::string> components;
|
||||||
|
std::string component;
|
||||||
|
|
||||||
|
for (const auto c : path) {
|
||||||
|
if (c == '/') {
|
||||||
|
if (!component.empty()) {
|
||||||
|
if (component == "..") {
|
||||||
|
if (!components.empty()) {
|
||||||
|
components.pop_back();
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
components.push_back(component);
|
||||||
|
}
|
||||||
|
component.clear();
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
component += c;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!component.empty()) {
|
||||||
|
components.push_back(component);
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string result;
|
||||||
|
for (const auto& c : components) {
|
||||||
|
if (!result.empty()) {
|
||||||
|
result += "/";
|
||||||
|
}
|
||||||
|
result += c;
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
#pragma once
|
||||||
|
#include <FS.h>
|
||||||
|
|
||||||
|
#include <string>
|
||||||
|
|
||||||
|
class FsHelpers {
|
||||||
|
public:
|
||||||
|
static bool openFileForRead(const char* moduleName, const std::string& path, File& file);
|
||||||
|
static bool openFileForWrite(const char* moduleName, const std::string& path, File& file);
|
||||||
|
static bool removeDir(const char* path);
|
||||||
|
static std::string normalisePath(const std::string& path);
|
||||||
|
};
|
||||||
@@ -3,61 +3,74 @@
|
|||||||
#include <HardwareSerial.h>
|
#include <HardwareSerial.h>
|
||||||
#include <Serialization.h>
|
#include <Serialization.h>
|
||||||
|
|
||||||
void PageLine::render(EpdRenderer& renderer) { block->render(renderer, 0, yPos); }
|
namespace {
|
||||||
|
constexpr uint8_t PAGE_FILE_VERSION = 3;
|
||||||
|
}
|
||||||
|
|
||||||
void PageLine::serialize(std::ostream& os) {
|
void PageLine::render(GfxRenderer& renderer, const int fontId, const int xOffset, const int yOffset) {
|
||||||
serialization::writePod(os, yPos);
|
block->render(renderer, fontId, xPos + xOffset, yPos + yOffset);
|
||||||
|
}
|
||||||
|
|
||||||
|
void PageLine::serialize(File& file) {
|
||||||
|
serialization::writePod(file, xPos);
|
||||||
|
serialization::writePod(file, yPos);
|
||||||
|
|
||||||
// serialize TextBlock pointed to by PageLine
|
// serialize TextBlock pointed to by PageLine
|
||||||
block->serialize(os);
|
block->serialize(file);
|
||||||
}
|
}
|
||||||
|
|
||||||
PageLine* PageLine::deserialize(std::istream& is) {
|
std::unique_ptr<PageLine> PageLine::deserialize(File& file) {
|
||||||
int32_t yPos;
|
int16_t xPos;
|
||||||
serialization::readPod(is, yPos);
|
int16_t yPos;
|
||||||
|
serialization::readPod(file, xPos);
|
||||||
|
serialization::readPod(file, yPos);
|
||||||
|
|
||||||
const auto tb = TextBlock::deserialize(is);
|
auto tb = TextBlock::deserialize(file);
|
||||||
return new PageLine(tb, yPos);
|
return std::unique_ptr<PageLine>(new PageLine(std::move(tb), xPos, yPos));
|
||||||
}
|
}
|
||||||
|
|
||||||
void Page::render(EpdRenderer& renderer) const {
|
void Page::render(GfxRenderer& renderer, const int fontId, const int xOffset, const int yOffset) const {
|
||||||
const auto start = millis();
|
for (auto& element : elements) {
|
||||||
for (const auto element : elements) {
|
element->render(renderer, fontId, xOffset, yOffset);
|
||||||
element->render(renderer);
|
|
||||||
}
|
}
|
||||||
Serial.printf("Rendered page elements (%u) in %dms\n", elements.size(), millis() - start);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void Page::serialize(std::ostream& os) const {
|
void Page::serialize(File& file) const {
|
||||||
serialization::writePod(os, nextY);
|
serialization::writePod(file, PAGE_FILE_VERSION);
|
||||||
|
|
||||||
const uint32_t count = elements.size();
|
const uint32_t count = elements.size();
|
||||||
serialization::writePod(os, count);
|
serialization::writePod(file, count);
|
||||||
|
|
||||||
for (auto* el : elements) {
|
for (const auto& el : elements) {
|
||||||
// Only PageLine exists currently
|
// Only PageLine exists currently
|
||||||
serialization::writePod(os, static_cast<uint8_t>(TAG_PageLine));
|
serialization::writePod(file, static_cast<uint8_t>(TAG_PageLine));
|
||||||
static_cast<PageLine*>(el)->serialize(os);
|
el->serialize(file);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Page* Page::deserialize(std::istream& is) {
|
std::unique_ptr<Page> Page::deserialize(File& file) {
|
||||||
auto* page = new Page();
|
uint8_t version;
|
||||||
|
serialization::readPod(file, version);
|
||||||
|
if (version != PAGE_FILE_VERSION) {
|
||||||
|
Serial.printf("[%lu] [PGE] Deserialization failed: Unknown version %u\n", millis(), version);
|
||||||
|
return nullptr;
|
||||||
|
}
|
||||||
|
|
||||||
serialization::readPod(is, page->nextY);
|
auto page = std::unique_ptr<Page>(new Page());
|
||||||
|
|
||||||
uint32_t count;
|
uint32_t count;
|
||||||
serialization::readPod(is, count);
|
serialization::readPod(file, count);
|
||||||
|
|
||||||
for (uint32_t i = 0; i < count; i++) {
|
for (uint32_t i = 0; i < count; i++) {
|
||||||
uint8_t tag;
|
uint8_t tag;
|
||||||
serialization::readPod(is, tag);
|
serialization::readPod(file, tag);
|
||||||
|
|
||||||
if (tag == TAG_PageLine) {
|
if (tag == TAG_PageLine) {
|
||||||
auto* pl = PageLine::deserialize(is);
|
auto pl = PageLine::deserialize(file);
|
||||||
page->elements.push_back(pl);
|
page->elements.push_back(std::move(pl));
|
||||||
} else {
|
} else {
|
||||||
throw std::runtime_error("Unknown PageElement tag");
|
Serial.printf("[%lu] [PGE] Deserialization failed: Unknown tag %u\n", millis(), tag);
|
||||||
|
return nullptr;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,9 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
#include <FS.h>
|
||||||
|
|
||||||
|
#include <utility>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
#include "blocks/TextBlock.h"
|
#include "blocks/TextBlock.h"
|
||||||
|
|
||||||
enum PageElementTag : uint8_t {
|
enum PageElementTag : uint8_t {
|
||||||
@@ -8,36 +13,31 @@ enum PageElementTag : uint8_t {
|
|||||||
// represents something that has been added to a page
|
// represents something that has been added to a page
|
||||||
class PageElement {
|
class PageElement {
|
||||||
public:
|
public:
|
||||||
int yPos;
|
int16_t xPos;
|
||||||
explicit PageElement(const int yPos) : yPos(yPos) {}
|
int16_t yPos;
|
||||||
|
explicit PageElement(const int16_t xPos, const int16_t yPos) : xPos(xPos), yPos(yPos) {}
|
||||||
virtual ~PageElement() = default;
|
virtual ~PageElement() = default;
|
||||||
virtual void render(EpdRenderer& renderer) = 0;
|
virtual void render(GfxRenderer& renderer, int fontId, int xOffset, int yOffset) = 0;
|
||||||
virtual void serialize(std::ostream& os) = 0;
|
virtual void serialize(File& file) = 0;
|
||||||
};
|
};
|
||||||
|
|
||||||
// a line from a block element
|
// a line from a block element
|
||||||
class PageLine final : public PageElement {
|
class PageLine final : public PageElement {
|
||||||
const TextBlock* block;
|
std::shared_ptr<TextBlock> block;
|
||||||
|
|
||||||
public:
|
public:
|
||||||
PageLine(const TextBlock* block, const int yPos) : PageElement(yPos), block(block) {}
|
PageLine(std::shared_ptr<TextBlock> block, const int16_t xPos, const int16_t yPos)
|
||||||
~PageLine() override { delete block; }
|
: PageElement(xPos, yPos), block(std::move(block)) {}
|
||||||
void render(EpdRenderer& renderer) override;
|
void render(GfxRenderer& renderer, int fontId, int xOffset, int yOffset) override;
|
||||||
void serialize(std::ostream& os) override;
|
void serialize(File& file) override;
|
||||||
static PageLine* deserialize(std::istream& is);
|
static std::unique_ptr<PageLine> deserialize(File& file);
|
||||||
};
|
};
|
||||||
|
|
||||||
class Page {
|
class Page {
|
||||||
public:
|
public:
|
||||||
int nextY = 0;
|
|
||||||
// the list of block index and line numbers on this page
|
// the list of block index and line numbers on this page
|
||||||
std::vector<PageElement*> elements;
|
std::vector<std::shared_ptr<PageElement>> elements;
|
||||||
void render(EpdRenderer& renderer) const;
|
void render(GfxRenderer& renderer, int fontId, int xOffset, int yOffset) const;
|
||||||
~Page() {
|
void serialize(File& file) const;
|
||||||
for (const auto element : elements) {
|
static std::unique_ptr<Page> deserialize(File& file);
|
||||||
delete element;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
void serialize(std::ostream& os) const;
|
|
||||||
static Page* deserialize(std::istream& is);
|
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -0,0 +1,195 @@
|
|||||||
|
#include "ParsedText.h"
|
||||||
|
|
||||||
|
#include <GfxRenderer.h>
|
||||||
|
|
||||||
|
#include <algorithm>
|
||||||
|
#include <cmath>
|
||||||
|
#include <functional>
|
||||||
|
#include <limits>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
constexpr int MAX_COST = std::numeric_limits<int>::max();
|
||||||
|
|
||||||
|
void ParsedText::addWord(std::string word, const EpdFontStyle fontStyle) {
|
||||||
|
if (word.empty()) return;
|
||||||
|
|
||||||
|
words.push_back(std::move(word));
|
||||||
|
wordStyles.push_back(fontStyle);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Consumes data to minimize memory usage
|
||||||
|
void ParsedText::layoutAndExtractLines(const GfxRenderer& renderer, const int fontId, const int viewportWidth,
|
||||||
|
const std::function<void(std::shared_ptr<TextBlock>)>& processLine,
|
||||||
|
const bool includeLastLine) {
|
||||||
|
if (words.empty()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const int pageWidth = viewportWidth;
|
||||||
|
const int spaceWidth = renderer.getSpaceWidth(fontId);
|
||||||
|
const auto wordWidths = calculateWordWidths(renderer, fontId);
|
||||||
|
const auto lineBreakIndices = computeLineBreaks(pageWidth, spaceWidth, wordWidths);
|
||||||
|
const size_t lineCount = includeLastLine ? lineBreakIndices.size() : lineBreakIndices.size() - 1;
|
||||||
|
|
||||||
|
for (size_t i = 0; i < lineCount; ++i) {
|
||||||
|
extractLine(i, pageWidth, spaceWidth, wordWidths, lineBreakIndices, processLine);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
std::vector<uint16_t> ParsedText::calculateWordWidths(const GfxRenderer& renderer, const int fontId) {
|
||||||
|
const size_t totalWordCount = words.size();
|
||||||
|
|
||||||
|
std::vector<uint16_t> wordWidths;
|
||||||
|
wordWidths.reserve(totalWordCount);
|
||||||
|
|
||||||
|
// add em-space at the beginning of first word in paragraph to indent
|
||||||
|
if (!extraParagraphSpacing) {
|
||||||
|
std::string& first_word = words.front();
|
||||||
|
first_word.insert(0, "\xe2\x80\x83");
|
||||||
|
}
|
||||||
|
|
||||||
|
auto wordsIt = words.begin();
|
||||||
|
auto wordStylesIt = wordStyles.begin();
|
||||||
|
|
||||||
|
while (wordsIt != words.end()) {
|
||||||
|
wordWidths.push_back(renderer.getTextWidth(fontId, wordsIt->c_str(), *wordStylesIt));
|
||||||
|
|
||||||
|
std::advance(wordsIt, 1);
|
||||||
|
std::advance(wordStylesIt, 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
return wordWidths;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::vector<size_t> ParsedText::computeLineBreaks(const int pageWidth, const int spaceWidth,
|
||||||
|
const std::vector<uint16_t>& wordWidths) const {
|
||||||
|
const size_t totalWordCount = words.size();
|
||||||
|
|
||||||
|
// DP table to store the minimum badness (cost) of lines starting at index i
|
||||||
|
std::vector<int> dp(totalWordCount);
|
||||||
|
// 'ans[i]' stores the index 'j' of the *last word* in the optimal line starting at 'i'
|
||||||
|
std::vector<size_t> ans(totalWordCount);
|
||||||
|
|
||||||
|
// Base Case
|
||||||
|
dp[totalWordCount - 1] = 0;
|
||||||
|
ans[totalWordCount - 1] = totalWordCount - 1;
|
||||||
|
|
||||||
|
for (int i = totalWordCount - 2; i >= 0; --i) {
|
||||||
|
int currlen = -spaceWidth;
|
||||||
|
dp[i] = MAX_COST;
|
||||||
|
|
||||||
|
for (size_t j = i; j < totalWordCount; ++j) {
|
||||||
|
// Current line length: previous width + space + current word width
|
||||||
|
currlen += wordWidths[j] + spaceWidth;
|
||||||
|
|
||||||
|
if (currlen > pageWidth) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
int cost;
|
||||||
|
if (j == totalWordCount - 1) {
|
||||||
|
cost = 0; // Last line
|
||||||
|
} else {
|
||||||
|
const int remainingSpace = pageWidth - currlen;
|
||||||
|
// Use long long for the square to prevent overflow
|
||||||
|
const long long cost_ll = static_cast<long long>(remainingSpace) * remainingSpace + dp[j + 1];
|
||||||
|
|
||||||
|
if (cost_ll > MAX_COST) {
|
||||||
|
cost = MAX_COST;
|
||||||
|
} else {
|
||||||
|
cost = static_cast<int>(cost_ll);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (cost < dp[i]) {
|
||||||
|
dp[i] = cost;
|
||||||
|
ans[i] = j; // j is the index of the last word in this optimal line
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Handle oversized word: if no valid configuration found, force single-word line
|
||||||
|
// This prevents cascade failure where one oversized word breaks all preceding words
|
||||||
|
if (dp[i] == MAX_COST) {
|
||||||
|
ans[i] = i; // Just this word on its own line
|
||||||
|
// Inherit cost from next word to allow subsequent words to find valid configurations
|
||||||
|
if (i + 1 < static_cast<int>(totalWordCount)) {
|
||||||
|
dp[i] = dp[i + 1];
|
||||||
|
} else {
|
||||||
|
dp[i] = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Stores the index of the word that starts the next line (last_word_index + 1)
|
||||||
|
std::vector<size_t> lineBreakIndices;
|
||||||
|
size_t currentWordIndex = 0;
|
||||||
|
|
||||||
|
while (currentWordIndex < totalWordCount) {
|
||||||
|
size_t nextBreakIndex = ans[currentWordIndex] + 1;
|
||||||
|
|
||||||
|
// Safety check: prevent infinite loop if nextBreakIndex doesn't advance
|
||||||
|
if (nextBreakIndex <= currentWordIndex) {
|
||||||
|
// Force advance by at least one word to avoid infinite loop
|
||||||
|
nextBreakIndex = currentWordIndex + 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
lineBreakIndices.push_back(nextBreakIndex);
|
||||||
|
currentWordIndex = nextBreakIndex;
|
||||||
|
}
|
||||||
|
|
||||||
|
return lineBreakIndices;
|
||||||
|
}
|
||||||
|
|
||||||
|
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::function<void(std::shared_ptr<TextBlock>)>& processLine) {
|
||||||
|
const size_t lineBreak = lineBreakIndices[breakIndex];
|
||||||
|
const size_t lastBreakAt = breakIndex > 0 ? lineBreakIndices[breakIndex - 1] : 0;
|
||||||
|
const size_t lineWordCount = lineBreak - lastBreakAt;
|
||||||
|
|
||||||
|
// Calculate total word width for this line
|
||||||
|
int lineWordWidthSum = 0;
|
||||||
|
for (size_t i = lastBreakAt; i < lineBreak; i++) {
|
||||||
|
lineWordWidthSum += wordWidths[i];
|
||||||
|
}
|
||||||
|
|
||||||
|
// Calculate spacing
|
||||||
|
const int spareSpace = pageWidth - lineWordWidthSum;
|
||||||
|
|
||||||
|
int spacing = spaceWidth;
|
||||||
|
const bool isLastLine = breakIndex == lineBreakIndices.size() - 1;
|
||||||
|
|
||||||
|
if (style == TextBlock::JUSTIFIED && !isLastLine && lineWordCount >= 2) {
|
||||||
|
spacing = spareSpace / (lineWordCount - 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Calculate initial x position
|
||||||
|
uint16_t xpos = 0;
|
||||||
|
if (style == TextBlock::RIGHT_ALIGN) {
|
||||||
|
xpos = spareSpace - (lineWordCount - 1) * spaceWidth;
|
||||||
|
} else if (style == TextBlock::CENTER_ALIGN) {
|
||||||
|
xpos = (spareSpace - (lineWordCount - 1) * spaceWidth) / 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Pre-calculate X positions for words
|
||||||
|
std::list<uint16_t> lineXPos;
|
||||||
|
for (size_t i = lastBreakAt; i < lineBreak; i++) {
|
||||||
|
const uint16_t currentWordWidth = wordWidths[i];
|
||||||
|
lineXPos.push_back(xpos);
|
||||||
|
xpos += currentWordWidth + spacing;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Iterators always start at the beginning as we are moving content with splice below
|
||||||
|
auto wordEndIt = words.begin();
|
||||||
|
auto wordStyleEndIt = wordStyles.begin();
|
||||||
|
std::advance(wordEndIt, lineWordCount);
|
||||||
|
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<EpdFontStyle> lineWordStyles;
|
||||||
|
lineWordStyles.splice(lineWordStyles.begin(), wordStyles, wordStyles.begin(), wordStyleEndIt);
|
||||||
|
|
||||||
|
processLine(std::make_shared<TextBlock>(std::move(lineWords), std::move(lineXPos), std::move(lineWordStyles), style));
|
||||||
|
}
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <EpdFontFamily.h>
|
||||||
|
|
||||||
|
#include <functional>
|
||||||
|
#include <list>
|
||||||
|
#include <memory>
|
||||||
|
#include <string>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
#include "blocks/TextBlock.h"
|
||||||
|
|
||||||
|
class GfxRenderer;
|
||||||
|
|
||||||
|
class ParsedText {
|
||||||
|
std::list<std::string> words;
|
||||||
|
std::list<EpdFontStyle> wordStyles;
|
||||||
|
TextBlock::BLOCK_STYLE style;
|
||||||
|
bool extraParagraphSpacing;
|
||||||
|
|
||||||
|
std::vector<size_t> computeLineBreaks(int pageWidth, int spaceWidth, const std::vector<uint16_t>& wordWidths) const;
|
||||||
|
void extractLine(size_t breakIndex, int pageWidth, int spaceWidth, const std::vector<uint16_t>& wordWidths,
|
||||||
|
const std::vector<size_t>& lineBreakIndices,
|
||||||
|
const std::function<void(std::shared_ptr<TextBlock>)>& processLine);
|
||||||
|
std::vector<uint16_t> calculateWordWidths(const GfxRenderer& renderer, int fontId);
|
||||||
|
|
||||||
|
public:
|
||||||
|
explicit ParsedText(const TextBlock::BLOCK_STYLE style, const bool extraParagraphSpacing)
|
||||||
|
: style(style), extraParagraphSpacing(extraParagraphSpacing) {}
|
||||||
|
~ParsedText() = default;
|
||||||
|
|
||||||
|
void addWord(std::string word, EpdFontStyle fontStyle);
|
||||||
|
void setStyle(const TextBlock::BLOCK_STYLE style) { this->style = style; }
|
||||||
|
TextBlock::BLOCK_STYLE getStyle() const { return style; }
|
||||||
|
size_t size() const { return words.size(); }
|
||||||
|
bool isEmpty() const { return words.empty(); }
|
||||||
|
void layoutAndExtractLines(const GfxRenderer& renderer, int fontId, int viewportWidth,
|
||||||
|
const std::function<void(std::shared_ptr<TextBlock>)>& processLine,
|
||||||
|
bool includeLastLine = true);
|
||||||
|
};
|
||||||
@@ -1,58 +1,88 @@
|
|||||||
#include "Section.h"
|
#include "Section.h"
|
||||||
|
|
||||||
#include <EpdRenderer.h>
|
#include <FsHelpers.h>
|
||||||
#include <SD.h>
|
#include <SD.h>
|
||||||
|
#include <Serialization.h>
|
||||||
|
|
||||||
#include <fstream>
|
|
||||||
|
|
||||||
#include "EpubHtmlParserSlim.h"
|
|
||||||
#include "Page.h"
|
#include "Page.h"
|
||||||
#include "Serialization.h"
|
#include "parsers/ChapterHtmlSlimParser.h"
|
||||||
|
|
||||||
constexpr uint8_t SECTION_FILE_VERSION = 2;
|
namespace {
|
||||||
|
constexpr uint8_t SECTION_FILE_VERSION = 6;
|
||||||
void Section::onPageComplete(const Page* page) {
|
} // namespace
|
||||||
Serial.printf("Page %d complete - free mem: %lu\n", pageCount, ESP.getFreeHeap());
|
|
||||||
|
|
||||||
|
void Section::onPageComplete(std::unique_ptr<Page> page) {
|
||||||
const auto filePath = cachePath + "/page_" + std::to_string(pageCount) + ".bin";
|
const auto filePath = cachePath + "/page_" + std::to_string(pageCount) + ".bin";
|
||||||
|
|
||||||
std::ofstream outputFile("/sd" + filePath);
|
File outputFile;
|
||||||
|
if (!FsHelpers::openFileForWrite("SCT", filePath, outputFile)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
page->serialize(outputFile);
|
page->serialize(outputFile);
|
||||||
outputFile.close();
|
outputFile.close();
|
||||||
|
|
||||||
|
Serial.printf("[%lu] [SCT] Page %d processed\n", millis(), pageCount);
|
||||||
|
|
||||||
pageCount++;
|
pageCount++;
|
||||||
delete page;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void Section::writeCacheMetadata() const {
|
void Section::writeCacheMetadata(const int fontId, const float lineCompression, const bool extraParagraphSpacing,
|
||||||
std::ofstream outputFile(("/sd" + cachePath + "/section.bin").c_str());
|
const int viewportWidth, const int viewportHeight) const {
|
||||||
|
File outputFile;
|
||||||
|
if (!FsHelpers::openFileForWrite("SCT", cachePath + "/section.bin", outputFile)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
serialization::writePod(outputFile, SECTION_FILE_VERSION);
|
serialization::writePod(outputFile, SECTION_FILE_VERSION);
|
||||||
|
serialization::writePod(outputFile, fontId);
|
||||||
|
serialization::writePod(outputFile, lineCompression);
|
||||||
|
serialization::writePod(outputFile, extraParagraphSpacing);
|
||||||
|
serialization::writePod(outputFile, viewportWidth);
|
||||||
|
serialization::writePod(outputFile, viewportHeight);
|
||||||
serialization::writePod(outputFile, pageCount);
|
serialization::writePod(outputFile, pageCount);
|
||||||
outputFile.close();
|
outputFile.close();
|
||||||
}
|
}
|
||||||
|
|
||||||
bool Section::loadCacheMetadata() {
|
bool Section::loadCacheMetadata(const int fontId, const float lineCompression, const bool extraParagraphSpacing,
|
||||||
if (!SD.exists(cachePath.c_str())) {
|
const int viewportWidth, const int viewportHeight) {
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
const auto sectionFilePath = cachePath + "/section.bin";
|
const auto sectionFilePath = cachePath + "/section.bin";
|
||||||
if (!SD.exists(sectionFilePath.c_str())) {
|
File inputFile;
|
||||||
|
if (!FsHelpers::openFileForRead("SCT", sectionFilePath, inputFile)) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
std::ifstream inputFile(("/sd" + sectionFilePath).c_str());
|
// Match parameters
|
||||||
uint8_t version;
|
{
|
||||||
serialization::readPod(inputFile, version);
|
uint8_t version;
|
||||||
if (version != SECTION_FILE_VERSION) {
|
serialization::readPod(inputFile, version);
|
||||||
inputFile.close();
|
if (version != SECTION_FILE_VERSION) {
|
||||||
SD.remove(sectionFilePath.c_str());
|
inputFile.close();
|
||||||
Serial.printf("Section state file: Unknown version %u\n", version);
|
Serial.printf("[%lu] [SCT] Deserialization failed: Unknown version %u\n", millis(), version);
|
||||||
return false;
|
clearCache();
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
int fileFontId, fileViewportWidth, fileViewportHeight;
|
||||||
|
float fileLineCompression;
|
||||||
|
bool fileExtraParagraphSpacing;
|
||||||
|
serialization::readPod(inputFile, fileFontId);
|
||||||
|
serialization::readPod(inputFile, fileLineCompression);
|
||||||
|
serialization::readPod(inputFile, fileExtraParagraphSpacing);
|
||||||
|
serialization::readPod(inputFile, fileViewportWidth);
|
||||||
|
serialization::readPod(inputFile, fileViewportHeight);
|
||||||
|
|
||||||
|
if (fontId != fileFontId || lineCompression != fileLineCompression ||
|
||||||
|
extraParagraphSpacing != fileExtraParagraphSpacing || viewportWidth != fileViewportWidth ||
|
||||||
|
viewportHeight != fileViewportHeight) {
|
||||||
|
inputFile.close();
|
||||||
|
Serial.printf("[%lu] [SCT] Deserialization failed: Parameters do not match\n", millis());
|
||||||
|
clearCache();
|
||||||
|
return false;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
serialization::readPod(inputFile, pageCount);
|
serialization::readPod(inputFile, pageCount);
|
||||||
inputFile.close();
|
inputFile.close();
|
||||||
Serial.printf("Loaded cache: %d pages\n", pageCount);
|
Serial.printf("[%lu] [SCT] Deserialization succeeded: %d pages\n", millis(), pageCount);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -61,58 +91,95 @@ void Section::setupCacheDir() const {
|
|||||||
SD.mkdir(cachePath.c_str());
|
SD.mkdir(cachePath.c_str());
|
||||||
}
|
}
|
||||||
|
|
||||||
void Section::clearCache() const { SD.rmdir(cachePath.c_str()); }
|
// Your updated class method (assuming you are using the 'SD' object, which is a wrapper for a specific filesystem)
|
||||||
|
bool Section::clearCache() const {
|
||||||
|
if (!SD.exists(cachePath.c_str())) {
|
||||||
|
Serial.printf("[%lu] [SCT] Cache does not exist, no action needed\n", millis());
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
bool Section::persistPageDataToSD() {
|
if (!FsHelpers::removeDir(cachePath.c_str())) {
|
||||||
const auto localPath = epub->getSpineItem(spineIndex);
|
Serial.printf("[%lu] [SCT] Failed to clear cache\n", millis());
|
||||||
|
|
||||||
// TODO: Should we get rid of this file all together?
|
|
||||||
// It currently saves us a bit of memory by allowing for all the inflation bits to be released
|
|
||||||
// before loading the XML parser
|
|
||||||
const auto tmpHtmlPath = epub->getCachePath() + "/.tmp_" + std::to_string(spineIndex) + ".html";
|
|
||||||
File f = SD.open(tmpHtmlPath.c_str(), FILE_WRITE, true);
|
|
||||||
bool success = epub->readItemContentsToStream(localPath, f, 1024);
|
|
||||||
f.close();
|
|
||||||
|
|
||||||
if (!success) {
|
|
||||||
Serial.println("Failed to stream item contents");
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
Serial.printf("Streamed HTML to %s\n", tmpHtmlPath.c_str());
|
Serial.printf("[%lu] [SCT] Cache cleared successfully\n", millis());
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
const auto sdTmpHtmlPath = "/sd" + tmpHtmlPath;
|
bool Section::persistPageDataToSD(const int fontId, const float lineCompression, const bool extraParagraphSpacing,
|
||||||
|
const int viewportWidth, const int viewportHeight,
|
||||||
|
const std::function<void()>& progressSetupFn,
|
||||||
|
const std::function<void(int)>& progressFn) {
|
||||||
|
constexpr size_t MIN_SIZE_FOR_PROGRESS = 50 * 1024; // 50KB
|
||||||
|
const auto localPath = epub->getSpineItem(spineIndex).href;
|
||||||
|
const auto tmpHtmlPath = epub->getCachePath() + "/.tmp_" + std::to_string(spineIndex) + ".html";
|
||||||
|
|
||||||
auto visitor =
|
// Retry logic for SD card timing issues
|
||||||
EpubHtmlParserSlim(sdTmpHtmlPath.c_str(), renderer, [this](const Page* page) { this->onPageComplete(page); });
|
bool success = false;
|
||||||
|
size_t fileSize = 0;
|
||||||
|
for (int attempt = 0; attempt < 3 && !success; attempt++) {
|
||||||
|
if (attempt > 0) {
|
||||||
|
Serial.printf("[%lu] [SCT] Retrying stream (attempt %d)...\n", millis(), attempt + 1);
|
||||||
|
delay(50); // Brief delay before retry
|
||||||
|
}
|
||||||
|
|
||||||
|
// Remove any incomplete file from previous attempt before retrying
|
||||||
|
if (SD.exists(tmpHtmlPath.c_str())) {
|
||||||
|
SD.remove(tmpHtmlPath.c_str());
|
||||||
|
}
|
||||||
|
|
||||||
|
File tmpHtml;
|
||||||
|
if (!FsHelpers::openFileForWrite("SCT", tmpHtmlPath, tmpHtml)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
success = epub->readItemContentsToStream(localPath, tmpHtml, 1024);
|
||||||
|
fileSize = tmpHtml.size();
|
||||||
|
tmpHtml.close();
|
||||||
|
|
||||||
|
// If streaming failed, remove the incomplete file immediately
|
||||||
|
if (!success && SD.exists(tmpHtmlPath.c_str())) {
|
||||||
|
SD.remove(tmpHtmlPath.c_str());
|
||||||
|
Serial.printf("[%lu] [SCT] Removed incomplete temp file after failed attempt\n", millis());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!success) {
|
||||||
|
Serial.printf("[%lu] [SCT] Failed to stream item contents to temp file after retries\n", millis());
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
Serial.printf("[%lu] [SCT] Streamed temp HTML to %s (%d bytes)\n", millis(), tmpHtmlPath.c_str(), fileSize);
|
||||||
|
|
||||||
|
// Only show progress bar for larger chapters where rendering overhead is worth it
|
||||||
|
if (progressSetupFn && fileSize >= MIN_SIZE_FOR_PROGRESS) {
|
||||||
|
progressSetupFn();
|
||||||
|
}
|
||||||
|
|
||||||
|
ChapterHtmlSlimParser visitor(
|
||||||
|
tmpHtmlPath, renderer, fontId, lineCompression, extraParagraphSpacing, viewportWidth, viewportHeight,
|
||||||
|
[this](std::unique_ptr<Page> page) { this->onPageComplete(std::move(page)); }, progressFn);
|
||||||
success = visitor.parseAndBuildPages();
|
success = visitor.parseAndBuildPages();
|
||||||
|
|
||||||
SD.remove(tmpHtmlPath.c_str());
|
SD.remove(tmpHtmlPath.c_str());
|
||||||
if (!success) {
|
if (!success) {
|
||||||
Serial.println("Failed to parse and build pages");
|
Serial.printf("[%lu] [SCT] Failed to parse XML and build pages\n", millis());
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
writeCacheMetadata();
|
writeCacheMetadata(fontId, lineCompression, extraParagraphSpacing, viewportWidth, viewportHeight);
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
void Section::renderPage() const {
|
std::unique_ptr<Page> Section::loadPageFromSD() const {
|
||||||
if (0 <= currentPage && currentPage < pageCount) {
|
const auto filePath = cachePath + "/page_" + std::to_string(currentPage) + ".bin";
|
||||||
const auto filePath = "/sd" + cachePath + "/page_" + std::to_string(currentPage) + ".bin";
|
|
||||||
std::ifstream inputFile(filePath);
|
File inputFile;
|
||||||
const Page* p = Page::deserialize(inputFile);
|
if (!FsHelpers::openFileForRead("SCT", filePath, inputFile)) {
|
||||||
inputFile.close();
|
return nullptr;
|
||||||
p->render(renderer);
|
|
||||||
delete p;
|
|
||||||
} else if (pageCount == 0) {
|
|
||||||
Serial.println("No pages to render");
|
|
||||||
const int width = renderer.getTextWidth("Empty chapter", BOLD);
|
|
||||||
renderer.drawText((renderer.getPageWidth() - width) / 2, 300, "Empty chapter", 1, BOLD);
|
|
||||||
} else {
|
|
||||||
Serial.printf("Page out of bounds: %d (max %d)\n", currentPage, pageCount);
|
|
||||||
const int width = renderer.getTextWidth("Out of bounds", BOLD);
|
|
||||||
renderer.drawText((renderer.getPageWidth() - width) / 2, 300, "Out of bounds", 1, BOLD);
|
|
||||||
}
|
}
|
||||||
|
auto page = Page::deserialize(inputFile);
|
||||||
|
inputFile.close();
|
||||||
|
return page;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,30 +1,38 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
#include <functional>
|
||||||
|
#include <memory>
|
||||||
|
|
||||||
#include "Epub.h"
|
#include "Epub.h"
|
||||||
|
|
||||||
class Page;
|
class Page;
|
||||||
class EpdRenderer;
|
class GfxRenderer;
|
||||||
|
|
||||||
class Section {
|
class Section {
|
||||||
Epub* epub;
|
std::shared_ptr<Epub> epub;
|
||||||
const int spineIndex;
|
const int spineIndex;
|
||||||
EpdRenderer& renderer;
|
GfxRenderer& renderer;
|
||||||
std::string cachePath;
|
std::string cachePath;
|
||||||
|
|
||||||
void onPageComplete(const Page* page);
|
void writeCacheMetadata(int fontId, float lineCompression, bool extraParagraphSpacing, int viewportWidth,
|
||||||
|
int viewportHeight) const;
|
||||||
|
void onPageComplete(std::unique_ptr<Page> page);
|
||||||
|
|
||||||
public:
|
public:
|
||||||
int pageCount = 0;
|
int pageCount = 0;
|
||||||
int currentPage = 0;
|
int currentPage = 0;
|
||||||
|
|
||||||
explicit Section(Epub* epub, const int spineIndex, EpdRenderer& renderer)
|
explicit Section(const std::shared_ptr<Epub>& epub, const int spineIndex, GfxRenderer& renderer)
|
||||||
: epub(epub), spineIndex(spineIndex), renderer(renderer) {
|
: epub(epub),
|
||||||
cachePath = epub->getCachePath() + "/" + std::to_string(spineIndex);
|
spineIndex(spineIndex),
|
||||||
}
|
renderer(renderer),
|
||||||
|
cachePath(epub->getCachePath() + "/" + std::to_string(spineIndex)) {}
|
||||||
~Section() = default;
|
~Section() = default;
|
||||||
void writeCacheMetadata() const;
|
bool loadCacheMetadata(int fontId, float lineCompression, bool extraParagraphSpacing, int viewportWidth,
|
||||||
bool loadCacheMetadata();
|
int viewportHeight);
|
||||||
void setupCacheDir() const;
|
void setupCacheDir() const;
|
||||||
void clearCache() const;
|
bool clearCache() const;
|
||||||
bool persistPageDataToSD();
|
bool persistPageDataToSD(int fontId, float lineCompression, bool extraParagraphSpacing, int viewportWidth,
|
||||||
void renderPage() const;
|
int viewportHeight, const std::function<void()>& progressSetupFn = nullptr,
|
||||||
|
const std::function<void(int)>& progressFn = nullptr);
|
||||||
|
std::unique_ptr<Page> loadPageFromSD() const;
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
class EpdRenderer;
|
class GfxRenderer;
|
||||||
|
|
||||||
typedef enum { TEXT_BLOCK, IMAGE_BLOCK } BlockType;
|
typedef enum { TEXT_BLOCK, IMAGE_BLOCK } BlockType;
|
||||||
|
|
||||||
@@ -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(EpdRenderer& renderer) = 0;
|
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() {}
|
||||||
|
|||||||
@@ -1,218 +1,87 @@
|
|||||||
#include "TextBlock.h"
|
#include "TextBlock.h"
|
||||||
|
|
||||||
#include <EpdRenderer.h>
|
#include <GfxRenderer.h>
|
||||||
#include <Serialization.h>
|
#include <Serialization.h>
|
||||||
|
|
||||||
void TextBlock::addWord(const std::string& word, const bool is_bold, const bool is_italic) {
|
void TextBlock::render(const GfxRenderer& renderer, const int fontId, const int x, const int y) const {
|
||||||
if (word.length() == 0) return;
|
// Validate iterator bounds before rendering
|
||||||
|
if (words.size() != wordXpos.size() || words.size() != wordStyles.size()) {
|
||||||
words.push_back(word);
|
Serial.printf("[%lu] [TXB] Render skipped: size mismatch (words=%u, xpos=%u, styles=%u)\n", millis(),
|
||||||
wordStyles.push_back((is_bold ? BOLD_SPAN : 0) | (is_italic ? ITALIC_SPAN : 0));
|
(uint32_t)words.size(), (uint32_t)wordXpos.size(), (uint32_t)wordStyles.size());
|
||||||
}
|
return;
|
||||||
|
|
||||||
std::list<TextBlock*> TextBlock::splitIntoLines(const EpdRenderer& renderer) {
|
|
||||||
const int totalWordCount = words.size();
|
|
||||||
const int pageWidth = renderer.getPageWidth();
|
|
||||||
const int spaceWidth = renderer.getSpaceWidth();
|
|
||||||
|
|
||||||
words.shrink_to_fit();
|
|
||||||
wordStyles.shrink_to_fit();
|
|
||||||
wordXpos.reserve(totalWordCount);
|
|
||||||
|
|
||||||
// measure each word
|
|
||||||
uint16_t wordWidths[totalWordCount];
|
|
||||||
for (int i = 0; i < words.size(); i++) {
|
|
||||||
// measure the word
|
|
||||||
EpdFontStyle fontStyle = REGULAR;
|
|
||||||
if (wordStyles[i] & BOLD_SPAN) {
|
|
||||||
if (wordStyles[i] & ITALIC_SPAN) {
|
|
||||||
fontStyle = BOLD_ITALIC;
|
|
||||||
} else {
|
|
||||||
fontStyle = BOLD;
|
|
||||||
}
|
|
||||||
} else if (wordStyles[i] & ITALIC_SPAN) {
|
|
||||||
fontStyle = ITALIC;
|
|
||||||
}
|
|
||||||
const int width = renderer.getTextWidth(words[i].c_str(), fontStyle);
|
|
||||||
wordWidths[i] = width;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// now apply the dynamic programming algorithm to find the best line breaks
|
auto wordIt = words.begin();
|
||||||
// DP table in which dp[i] represents cost of line starting with word words[i]
|
auto wordStylesIt = wordStyles.begin();
|
||||||
int dp[totalWordCount];
|
auto wordXposIt = wordXpos.begin();
|
||||||
|
|
||||||
// Array in which ans[i] store index of last word in line starting with word
|
for (size_t i = 0; i < words.size(); i++) {
|
||||||
// word[i]
|
renderer.drawText(fontId, *wordXposIt + x, y, wordIt->c_str(), true, *wordStylesIt);
|
||||||
size_t ans[totalWordCount];
|
|
||||||
|
|
||||||
// If only one word is present then only one line is required. Cost of last
|
std::advance(wordIt, 1);
|
||||||
// line is zero. Hence cost of this line is zero. Ending point is also n-1 as
|
std::advance(wordStylesIt, 1);
|
||||||
// single word is present
|
std::advance(wordXposIt, 1);
|
||||||
dp[totalWordCount - 1] = 0;
|
|
||||||
ans[totalWordCount - 1] = totalWordCount - 1;
|
|
||||||
|
|
||||||
// Make each word first word of line by iterating over each index in arr.
|
|
||||||
for (int i = totalWordCount - 2; i >= 0; i--) {
|
|
||||||
int currlen = -1;
|
|
||||||
dp[i] = INT_MAX;
|
|
||||||
|
|
||||||
// Variable to store possible minimum cost of line.
|
|
||||||
int cost;
|
|
||||||
|
|
||||||
// Keep on adding words in current line by iterating from starting word upto
|
|
||||||
// last word in arr.
|
|
||||||
for (int j = i; j < totalWordCount; j++) {
|
|
||||||
// Update the width of the words in current line + the space between two
|
|
||||||
// words.
|
|
||||||
currlen += wordWidths[j] + spaceWidth;
|
|
||||||
|
|
||||||
// If we're bigger than the current pagewidth then we can't add more words
|
|
||||||
if (currlen > pageWidth) break;
|
|
||||||
|
|
||||||
// if we've run out of words then this is last line and the cost should be
|
|
||||||
// 0 Otherwise the cost is the sqaure of the left over space + the costs
|
|
||||||
// of all the previous lines
|
|
||||||
if (j == totalWordCount - 1)
|
|
||||||
cost = 0;
|
|
||||||
else
|
|
||||||
cost = (pageWidth - currlen) * (pageWidth - currlen) + dp[j + 1];
|
|
||||||
|
|
||||||
// Check if this arrangement gives minimum cost for line starting with
|
|
||||||
// word words[i].
|
|
||||||
if (cost < dp[i]) {
|
|
||||||
dp[i] = cost;
|
|
||||||
ans[i] = j;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// We can now iterate through the answer to find the line break positions
|
|
||||||
std::list<uint16_t> lineBreaks;
|
|
||||||
for (size_t i = 0; i < totalWordCount;) {
|
|
||||||
i = ans[i] + 1;
|
|
||||||
if (i > totalWordCount) {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
lineBreaks.push_back(i);
|
|
||||||
// Text too big, just exit
|
|
||||||
if (lineBreaks.size() > 1000) {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
std::list<TextBlock*> lines;
|
|
||||||
|
|
||||||
// With the line breaks calculated we can now position the words along the
|
|
||||||
// line
|
|
||||||
int startWord = 0;
|
|
||||||
for (const auto lineBreak : lineBreaks) {
|
|
||||||
const int lineWordCount = lineBreak - startWord;
|
|
||||||
|
|
||||||
int lineWordWidthSum = 0;
|
|
||||||
for (int i = startWord; i < lineBreak; i++) {
|
|
||||||
lineWordWidthSum += wordWidths[i];
|
|
||||||
}
|
|
||||||
|
|
||||||
// Calculate spacing between words
|
|
||||||
const uint16_t spareSpace = pageWidth - lineWordWidthSum;
|
|
||||||
uint16_t spacing = spaceWidth;
|
|
||||||
// evenly space words if using justified style, not the last line, and at
|
|
||||||
// least 2 words
|
|
||||||
if (style == JUSTIFIED && lineBreak != lineBreaks.back() && lineWordCount >= 2) {
|
|
||||||
spacing = spareSpace / (lineWordCount - 1);
|
|
||||||
}
|
|
||||||
|
|
||||||
uint16_t xpos = 0;
|
|
||||||
if (style == RIGHT_ALIGN) {
|
|
||||||
xpos = spareSpace - (lineWordCount - 1) * spaceWidth;
|
|
||||||
} else if (style == CENTER_ALIGN) {
|
|
||||||
xpos = (spareSpace - (lineWordCount - 1) * spaceWidth) / 2;
|
|
||||||
}
|
|
||||||
|
|
||||||
for (int i = startWord; i < lineBreak; i++) {
|
|
||||||
wordXpos[i] = xpos;
|
|
||||||
xpos += wordWidths[i] + spacing;
|
|
||||||
}
|
|
||||||
|
|
||||||
std::vector<std::string> lineWords;
|
|
||||||
std::vector<uint16_t> lineXPos;
|
|
||||||
std::vector<uint8_t> lineWordStyles;
|
|
||||||
lineWords.reserve(lineWordCount);
|
|
||||||
lineXPos.reserve(lineWordCount);
|
|
||||||
lineWordStyles.reserve(lineWordCount);
|
|
||||||
|
|
||||||
for (int i = startWord; i < lineBreak; i++) {
|
|
||||||
lineWords.push_back(words[i]);
|
|
||||||
lineXPos.push_back(wordXpos[i]);
|
|
||||||
lineWordStyles.push_back(wordStyles[i]);
|
|
||||||
}
|
|
||||||
const auto textLine = new TextBlock(lineWords, lineXPos, lineWordStyles, style);
|
|
||||||
lines.push_back(textLine);
|
|
||||||
startWord = lineBreak;
|
|
||||||
}
|
|
||||||
|
|
||||||
return lines;
|
|
||||||
}
|
|
||||||
|
|
||||||
void TextBlock::render(const EpdRenderer& renderer, const int x, const int y) const {
|
|
||||||
for (int i = 0; i < words.size(); i++) {
|
|
||||||
// render the word
|
|
||||||
EpdFontStyle fontStyle = REGULAR;
|
|
||||||
if (wordStyles[i] & BOLD_SPAN && wordStyles[i] & ITALIC_SPAN) {
|
|
||||||
fontStyle = BOLD_ITALIC;
|
|
||||||
} else if (wordStyles[i] & BOLD_SPAN) {
|
|
||||||
fontStyle = BOLD;
|
|
||||||
} else if (wordStyles[i] & ITALIC_SPAN) {
|
|
||||||
fontStyle = ITALIC;
|
|
||||||
}
|
|
||||||
renderer.drawText(x + wordXpos[i], y, words[i].c_str(), 1, fontStyle);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void TextBlock::serialize(std::ostream& os) const {
|
void TextBlock::serialize(File& file) const {
|
||||||
// words
|
// words
|
||||||
const uint32_t wc = words.size();
|
const uint32_t wc = words.size();
|
||||||
serialization::writePod(os, wc);
|
serialization::writePod(file, wc);
|
||||||
for (const auto& w : words) serialization::writeString(os, w);
|
for (const auto& w : words) serialization::writeString(file, w);
|
||||||
|
|
||||||
// wordXpos
|
// wordXpos
|
||||||
const uint32_t xc = wordXpos.size();
|
const uint32_t xc = wordXpos.size();
|
||||||
serialization::writePod(os, xc);
|
serialization::writePod(file, xc);
|
||||||
for (auto x : wordXpos) serialization::writePod(os, x);
|
for (auto x : wordXpos) serialization::writePod(file, x);
|
||||||
|
|
||||||
// wordStyles
|
// wordStyles
|
||||||
const uint32_t sc = wordStyles.size();
|
const uint32_t sc = wordStyles.size();
|
||||||
serialization::writePod(os, sc);
|
serialization::writePod(file, sc);
|
||||||
for (auto s : wordStyles) serialization::writePod(os, s);
|
for (auto s : wordStyles) serialization::writePod(file, s);
|
||||||
|
|
||||||
// style
|
// style
|
||||||
serialization::writePod(os, style);
|
serialization::writePod(file, style);
|
||||||
}
|
}
|
||||||
|
|
||||||
TextBlock* TextBlock::deserialize(std::istream& is) {
|
std::unique_ptr<TextBlock> TextBlock::deserialize(File& file) {
|
||||||
uint32_t wc, xc, sc;
|
uint32_t wc, xc, sc;
|
||||||
std::vector<std::string> words;
|
std::list<std::string> words;
|
||||||
std::vector<uint16_t> wordXpos;
|
std::list<uint16_t> wordXpos;
|
||||||
std::vector<uint8_t> wordStyles;
|
std::list<EpdFontStyle> wordStyles;
|
||||||
BLOCK_STYLE style;
|
BLOCK_STYLE style;
|
||||||
|
|
||||||
// words
|
// words
|
||||||
serialization::readPod(is, wc);
|
serialization::readPod(file, wc);
|
||||||
|
|
||||||
|
// Sanity check: prevent allocation of unreasonably large lists (max 10000 words per block)
|
||||||
|
if (wc > 10000) {
|
||||||
|
Serial.printf("[%lu] [TXB] Deserialization failed: word count %u exceeds maximum\n", millis(), wc);
|
||||||
|
return nullptr;
|
||||||
|
}
|
||||||
|
|
||||||
words.resize(wc);
|
words.resize(wc);
|
||||||
for (auto& w : words) serialization::readString(is, w);
|
for (auto& w : words) serialization::readString(file, w);
|
||||||
|
|
||||||
// wordXpos
|
// wordXpos
|
||||||
serialization::readPod(is, xc);
|
serialization::readPod(file, xc);
|
||||||
wordXpos.resize(xc);
|
wordXpos.resize(xc);
|
||||||
for (auto& x : wordXpos) serialization::readPod(is, x);
|
for (auto& x : wordXpos) serialization::readPod(file, x);
|
||||||
|
|
||||||
// wordStyles
|
// wordStyles
|
||||||
serialization::readPod(is, sc);
|
serialization::readPod(file, sc);
|
||||||
wordStyles.resize(sc);
|
wordStyles.resize(sc);
|
||||||
for (auto& s : wordStyles) serialization::readPod(is, s);
|
for (auto& s : wordStyles) serialization::readPod(file, s);
|
||||||
|
|
||||||
|
// Validate data consistency: all three lists must have the same size
|
||||||
|
if (wc != xc || wc != sc) {
|
||||||
|
Serial.printf("[%lu] [TXB] Deserialization failed: size mismatch (words=%u, xpos=%u, styles=%u)\n", millis(), wc,
|
||||||
|
xc, sc);
|
||||||
|
return nullptr;
|
||||||
|
}
|
||||||
|
|
||||||
// style
|
// style
|
||||||
serialization::readPod(is, style);
|
serialization::readPod(file, style);
|
||||||
|
|
||||||
return new TextBlock(words, wordXpos, wordStyles, style);
|
return std::unique_ptr<TextBlock>(new TextBlock(std::move(words), std::move(wordXpos), std::move(wordStyles), style));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,50 +1,41 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
#include <EpdFontFamily.h>
|
||||||
|
#include <FS.h>
|
||||||
|
|
||||||
#include <list>
|
#include <list>
|
||||||
|
#include <memory>
|
||||||
#include <string>
|
#include <string>
|
||||||
#include <vector>
|
|
||||||
|
|
||||||
#include "Block.h"
|
#include "Block.h"
|
||||||
|
|
||||||
enum SPAN_STYLE : uint8_t {
|
|
||||||
BOLD_SPAN = 1,
|
|
||||||
ITALIC_SPAN = 2,
|
|
||||||
};
|
|
||||||
|
|
||||||
enum BLOCK_STYLE : uint8_t {
|
|
||||||
JUSTIFIED = 0,
|
|
||||||
LEFT_ALIGN = 1,
|
|
||||||
CENTER_ALIGN = 2,
|
|
||||||
RIGHT_ALIGN = 3,
|
|
||||||
};
|
|
||||||
|
|
||||||
// represents a block of words in the html document
|
// represents a block of words in the html document
|
||||||
class TextBlock final : public Block {
|
class TextBlock final : public Block {
|
||||||
// pointer to each word
|
public:
|
||||||
std::vector<std::string> words;
|
enum BLOCK_STYLE : uint8_t {
|
||||||
// x position of each word
|
JUSTIFIED = 0,
|
||||||
std::vector<uint16_t> wordXpos;
|
LEFT_ALIGN = 1,
|
||||||
// the styles of each word
|
CENTER_ALIGN = 2,
|
||||||
std::vector<uint8_t> wordStyles;
|
RIGHT_ALIGN = 3,
|
||||||
|
};
|
||||||
|
|
||||||
// the style of the block - left, center, right aligned
|
private:
|
||||||
|
std::list<std::string> words;
|
||||||
|
std::list<uint16_t> wordXpos;
|
||||||
|
std::list<EpdFontStyle> wordStyles;
|
||||||
BLOCK_STYLE style;
|
BLOCK_STYLE style;
|
||||||
|
|
||||||
public:
|
public:
|
||||||
explicit TextBlock(const BLOCK_STYLE style) : style(style) {}
|
explicit TextBlock(std::list<std::string> words, std::list<uint16_t> word_xpos, std::list<EpdFontStyle> word_styles,
|
||||||
explicit TextBlock(const std::vector<std::string>& words, const std::vector<uint16_t>& word_xpos,
|
const BLOCK_STYLE style)
|
||||||
// the styles of each word
|
: words(std::move(words)), wordXpos(std::move(word_xpos)), wordStyles(std::move(word_styles)), style(style) {}
|
||||||
const std::vector<uint8_t>& word_styles, const BLOCK_STYLE style)
|
|
||||||
: words(words), wordXpos(word_xpos), wordStyles(word_styles), style(style) {}
|
|
||||||
~TextBlock() override = default;
|
~TextBlock() override = default;
|
||||||
void addWord(const std::string& word, bool is_bold, bool is_italic);
|
|
||||||
void setStyle(const BLOCK_STYLE style) { this->style = style; }
|
void setStyle(const BLOCK_STYLE style) { this->style = style; }
|
||||||
BLOCK_STYLE getStyle() const { return style; }
|
BLOCK_STYLE getStyle() const { return style; }
|
||||||
bool isEmpty() override { return words.empty(); }
|
bool isEmpty() override { return words.empty(); }
|
||||||
void layout(EpdRenderer& renderer) override {};
|
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
|
||||||
std::list<TextBlock*> splitIntoLines(const EpdRenderer& renderer);
|
void render(const GfxRenderer& renderer, int fontId, int x, int y) const;
|
||||||
void render(const EpdRenderer& renderer, int x, int y) const;
|
|
||||||
BlockType getType() override { return TEXT_BLOCK; }
|
BlockType getType() override { return TEXT_BLOCK; }
|
||||||
void serialize(std::ostream& os) const;
|
void serialize(File& file) const;
|
||||||
static TextBlock* deserialize(std::istream& is);
|
static std::unique_ptr<TextBlock> deserialize(File& file);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -0,0 +1,334 @@
|
|||||||
|
#include "ChapterHtmlSlimParser.h"
|
||||||
|
|
||||||
|
#include <FsHelpers.h>
|
||||||
|
#include <GfxRenderer.h>
|
||||||
|
#include <HardwareSerial.h>
|
||||||
|
#include <expat.h>
|
||||||
|
|
||||||
|
#include "../Page.h"
|
||||||
|
#include "../htmlEntities.h"
|
||||||
|
|
||||||
|
const char* HEADER_TAGS[] = {"h1", "h2", "h3", "h4", "h5", "h6"};
|
||||||
|
constexpr int NUM_HEADER_TAGS = sizeof(HEADER_TAGS) / sizeof(HEADER_TAGS[0]);
|
||||||
|
|
||||||
|
// Minimum file size (in bytes) to show progress bar - smaller chapters don't benefit from it
|
||||||
|
constexpr size_t MIN_SIZE_FOR_PROGRESS = 50 * 1024; // 50KB
|
||||||
|
|
||||||
|
const char* BLOCK_TAGS[] = {"p", "li", "div", "br", "blockquote"};
|
||||||
|
constexpr int NUM_BLOCK_TAGS = sizeof(BLOCK_TAGS) / sizeof(BLOCK_TAGS[0]);
|
||||||
|
|
||||||
|
const char* BOLD_TAGS[] = {"b", "strong"};
|
||||||
|
constexpr int NUM_BOLD_TAGS = sizeof(BOLD_TAGS) / sizeof(BOLD_TAGS[0]);
|
||||||
|
|
||||||
|
const char* ITALIC_TAGS[] = {"i", "em"};
|
||||||
|
constexpr int NUM_ITALIC_TAGS = sizeof(ITALIC_TAGS) / sizeof(ITALIC_TAGS[0]);
|
||||||
|
|
||||||
|
const char* IMAGE_TAGS[] = {"img"};
|
||||||
|
constexpr int NUM_IMAGE_TAGS = sizeof(IMAGE_TAGS) / sizeof(IMAGE_TAGS[0]);
|
||||||
|
|
||||||
|
const char* SKIP_TAGS[] = {"head", "table"};
|
||||||
|
constexpr int NUM_SKIP_TAGS = sizeof(SKIP_TAGS) / sizeof(SKIP_TAGS[0]);
|
||||||
|
|
||||||
|
bool isWhitespace(const char c) { return c == ' ' || c == '\r' || c == '\n' || c == '\t'; }
|
||||||
|
|
||||||
|
// given the start and end of a tag, check to see if it matches a known tag
|
||||||
|
bool matches(const char* tag_name, const char* possible_tags[], const int possible_tag_count) {
|
||||||
|
for (int i = 0; i < possible_tag_count; i++) {
|
||||||
|
if (strcmp(tag_name, possible_tags[i]) == 0) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// start a new text block if needed
|
||||||
|
void ChapterHtmlSlimParser::startNewTextBlock(const TextBlock::BLOCK_STYLE style) {
|
||||||
|
if (currentTextBlock) {
|
||||||
|
// already have a text block running and it is empty - just reuse it
|
||||||
|
if (currentTextBlock->isEmpty()) {
|
||||||
|
currentTextBlock->setStyle(style);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
makePages();
|
||||||
|
}
|
||||||
|
currentTextBlock.reset(new ParsedText(style, extraParagraphSpacing));
|
||||||
|
}
|
||||||
|
|
||||||
|
void XMLCALL ChapterHtmlSlimParser::startElement(void* userData, const XML_Char* name, const XML_Char** atts) {
|
||||||
|
auto* self = static_cast<ChapterHtmlSlimParser*>(userData);
|
||||||
|
(void)atts;
|
||||||
|
|
||||||
|
// Middle of skip
|
||||||
|
if (self->skipUntilDepth < self->depth) {
|
||||||
|
self->depth += 1;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (matches(name, IMAGE_TAGS, NUM_IMAGE_TAGS)) {
|
||||||
|
// TODO: Start processing image tags
|
||||||
|
self->skipUntilDepth = self->depth;
|
||||||
|
self->depth += 1;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (matches(name, SKIP_TAGS, NUM_SKIP_TAGS)) {
|
||||||
|
// start skip
|
||||||
|
self->skipUntilDepth = self->depth;
|
||||||
|
self->depth += 1;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Skip blocks with role="doc-pagebreak" and epub:type="pagebreak"
|
||||||
|
if (atts != nullptr) {
|
||||||
|
for (int i = 0; atts[i]; i += 2) {
|
||||||
|
if (strcmp(atts[i], "role") == 0 && strcmp(atts[i + 1], "doc-pagebreak") == 0 ||
|
||||||
|
strcmp(atts[i], "epub:type") == 0 && strcmp(atts[i + 1], "pagebreak") == 0) {
|
||||||
|
self->skipUntilDepth = self->depth;
|
||||||
|
self->depth += 1;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (matches(name, HEADER_TAGS, NUM_HEADER_TAGS)) {
|
||||||
|
self->startNewTextBlock(TextBlock::CENTER_ALIGN);
|
||||||
|
self->boldUntilDepth = min(self->boldUntilDepth, self->depth);
|
||||||
|
} else if (matches(name, BLOCK_TAGS, NUM_BLOCK_TAGS)) {
|
||||||
|
if (strcmp(name, "br") == 0) {
|
||||||
|
self->startNewTextBlock(self->currentTextBlock->getStyle());
|
||||||
|
} else {
|
||||||
|
self->startNewTextBlock(TextBlock::JUSTIFIED);
|
||||||
|
}
|
||||||
|
} else if (matches(name, BOLD_TAGS, NUM_BOLD_TAGS)) {
|
||||||
|
self->boldUntilDepth = min(self->boldUntilDepth, self->depth);
|
||||||
|
} else if (matches(name, ITALIC_TAGS, NUM_ITALIC_TAGS)) {
|
||||||
|
self->italicUntilDepth = min(self->italicUntilDepth, self->depth);
|
||||||
|
}
|
||||||
|
|
||||||
|
self->depth += 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
void XMLCALL ChapterHtmlSlimParser::characterData(void* userData, const XML_Char* s, const int len) {
|
||||||
|
auto* self = static_cast<ChapterHtmlSlimParser*>(userData);
|
||||||
|
|
||||||
|
// Middle of skip
|
||||||
|
if (self->skipUntilDepth < self->depth) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
EpdFontStyle fontStyle = REGULAR;
|
||||||
|
if (self->boldUntilDepth < self->depth && self->italicUntilDepth < self->depth) {
|
||||||
|
fontStyle = BOLD_ITALIC;
|
||||||
|
} else if (self->boldUntilDepth < self->depth) {
|
||||||
|
fontStyle = BOLD;
|
||||||
|
} else if (self->italicUntilDepth < self->depth) {
|
||||||
|
fontStyle = ITALIC;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (int i = 0; i < len; i++) {
|
||||||
|
if (isWhitespace(s[i])) {
|
||||||
|
// Currently looking at whitespace, if there's anything in the partWordBuffer, flush it
|
||||||
|
if (self->partWordBufferIndex > 0) {
|
||||||
|
self->partWordBuffer[self->partWordBufferIndex] = '\0';
|
||||||
|
self->currentTextBlock->addWord(std::move(replaceHtmlEntities(self->partWordBuffer)), fontStyle);
|
||||||
|
self->partWordBufferIndex = 0;
|
||||||
|
}
|
||||||
|
// Skip the whitespace char
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// If we're about to run out of space, then cut the word off and start a new one
|
||||||
|
if (self->partWordBufferIndex >= MAX_WORD_SIZE) {
|
||||||
|
self->partWordBuffer[self->partWordBufferIndex] = '\0';
|
||||||
|
self->currentTextBlock->addWord(std::move(replaceHtmlEntities(self->partWordBuffer)), fontStyle);
|
||||||
|
self->partWordBufferIndex = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
self->partWordBuffer[self->partWordBufferIndex++] = s[i];
|
||||||
|
}
|
||||||
|
|
||||||
|
// If we have > 750 words buffered up, perform the layout and consume out all but the last line
|
||||||
|
// There should be enough here to build out 1-2 full pages and doing this will free up a lot of
|
||||||
|
// memory.
|
||||||
|
// Spotted when reading Intermezzo, there are some really long text blocks in there.
|
||||||
|
if (self->currentTextBlock->size() > 750) {
|
||||||
|
Serial.printf("[%lu] [EHP] Text block too long, splitting into multiple pages\n", millis());
|
||||||
|
self->currentTextBlock->layoutAndExtractLines(
|
||||||
|
self->renderer, self->fontId, self->viewportWidth,
|
||||||
|
[self](const std::shared_ptr<TextBlock>& textBlock) { self->addLineToPage(textBlock); }, false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void XMLCALL ChapterHtmlSlimParser::endElement(void* userData, const XML_Char* name) {
|
||||||
|
auto* self = static_cast<ChapterHtmlSlimParser*>(userData);
|
||||||
|
(void)name;
|
||||||
|
|
||||||
|
if (self->partWordBufferIndex > 0) {
|
||||||
|
// Only flush out part word buffer if we're closing a block tag or are at the top of the HTML file.
|
||||||
|
// We don't want to flush out content when closing inline tags like <span>.
|
||||||
|
// Currently this also flushes out on closing <b> and <i> tags, but they are line tags so that shouldn't happen,
|
||||||
|
// text styling needs to be overhauled to fix it.
|
||||||
|
const bool shouldBreakText =
|
||||||
|
matches(name, BLOCK_TAGS, NUM_BLOCK_TAGS) || matches(name, HEADER_TAGS, NUM_HEADER_TAGS) ||
|
||||||
|
matches(name, BOLD_TAGS, NUM_BOLD_TAGS) || matches(name, ITALIC_TAGS, NUM_ITALIC_TAGS) || self->depth == 1;
|
||||||
|
|
||||||
|
if (shouldBreakText) {
|
||||||
|
EpdFontStyle fontStyle = REGULAR;
|
||||||
|
if (self->boldUntilDepth < self->depth && self->italicUntilDepth < self->depth) {
|
||||||
|
fontStyle = BOLD_ITALIC;
|
||||||
|
} else if (self->boldUntilDepth < self->depth) {
|
||||||
|
fontStyle = BOLD;
|
||||||
|
} else if (self->italicUntilDepth < self->depth) {
|
||||||
|
fontStyle = ITALIC;
|
||||||
|
}
|
||||||
|
|
||||||
|
self->partWordBuffer[self->partWordBufferIndex] = '\0';
|
||||||
|
self->currentTextBlock->addWord(std::move(replaceHtmlEntities(self->partWordBuffer)), fontStyle);
|
||||||
|
self->partWordBufferIndex = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
self->depth -= 1;
|
||||||
|
|
||||||
|
// Leaving skip
|
||||||
|
if (self->skipUntilDepth == self->depth) {
|
||||||
|
self->skipUntilDepth = INT_MAX;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Leaving bold
|
||||||
|
if (self->boldUntilDepth == self->depth) {
|
||||||
|
self->boldUntilDepth = INT_MAX;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Leaving italic
|
||||||
|
if (self->italicUntilDepth == self->depth) {
|
||||||
|
self->italicUntilDepth = INT_MAX;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
bool ChapterHtmlSlimParser::parseAndBuildPages() {
|
||||||
|
startNewTextBlock(TextBlock::JUSTIFIED);
|
||||||
|
|
||||||
|
const XML_Parser parser = XML_ParserCreate(nullptr);
|
||||||
|
int done;
|
||||||
|
|
||||||
|
if (!parser) {
|
||||||
|
Serial.printf("[%lu] [EHP] Couldn't allocate memory for parser\n", millis());
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
File file;
|
||||||
|
if (!FsHelpers::openFileForRead("EHP", filepath, file)) {
|
||||||
|
XML_ParserFree(parser);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get file size for progress calculation
|
||||||
|
const size_t totalSize = file.size();
|
||||||
|
size_t bytesRead = 0;
|
||||||
|
int lastProgress = -1;
|
||||||
|
|
||||||
|
XML_SetUserData(parser, this);
|
||||||
|
XML_SetElementHandler(parser, startElement, endElement);
|
||||||
|
XML_SetCharacterDataHandler(parser, characterData);
|
||||||
|
|
||||||
|
do {
|
||||||
|
void* const buf = XML_GetBuffer(parser, 1024);
|
||||||
|
if (!buf) {
|
||||||
|
Serial.printf("[%lu] [EHP] Couldn't allocate memory for buffer\n", millis());
|
||||||
|
XML_StopParser(parser, XML_FALSE); // Stop any pending processing
|
||||||
|
XML_SetElementHandler(parser, nullptr, nullptr); // Clear callbacks
|
||||||
|
XML_SetCharacterDataHandler(parser, nullptr);
|
||||||
|
XML_ParserFree(parser);
|
||||||
|
file.close();
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
const size_t len = file.read(static_cast<uint8_t*>(buf), 1024);
|
||||||
|
|
||||||
|
if (len == 0) {
|
||||||
|
Serial.printf("[%lu] [EHP] File read error\n", millis());
|
||||||
|
XML_StopParser(parser, XML_FALSE); // Stop any pending processing
|
||||||
|
XML_SetElementHandler(parser, nullptr, nullptr); // Clear callbacks
|
||||||
|
XML_SetCharacterDataHandler(parser, nullptr);
|
||||||
|
XML_ParserFree(parser);
|
||||||
|
file.close();
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update progress (call every 10% change to avoid too frequent updates)
|
||||||
|
// Only show progress for larger chapters where rendering overhead is worth it
|
||||||
|
bytesRead += len;
|
||||||
|
if (progressFn && totalSize >= MIN_SIZE_FOR_PROGRESS) {
|
||||||
|
const int progress = static_cast<int>((bytesRead * 100) / totalSize);
|
||||||
|
if (lastProgress / 10 != progress / 10) {
|
||||||
|
lastProgress = progress;
|
||||||
|
progressFn(progress);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
done = file.available() == 0;
|
||||||
|
|
||||||
|
if (XML_ParseBuffer(parser, static_cast<int>(len), done) == XML_STATUS_ERROR) {
|
||||||
|
Serial.printf("[%lu] [EHP] Parse error at line %lu:\n%s\n", millis(), XML_GetCurrentLineNumber(parser),
|
||||||
|
XML_ErrorString(XML_GetErrorCode(parser)));
|
||||||
|
XML_StopParser(parser, XML_FALSE); // Stop any pending processing
|
||||||
|
XML_SetElementHandler(parser, nullptr, nullptr); // Clear callbacks
|
||||||
|
XML_SetCharacterDataHandler(parser, nullptr);
|
||||||
|
XML_ParserFree(parser);
|
||||||
|
file.close();
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
} while (!done);
|
||||||
|
|
||||||
|
XML_StopParser(parser, XML_FALSE); // Stop any pending processing
|
||||||
|
XML_SetElementHandler(parser, nullptr, nullptr); // Clear callbacks
|
||||||
|
XML_SetCharacterDataHandler(parser, nullptr);
|
||||||
|
XML_ParserFree(parser);
|
||||||
|
file.close();
|
||||||
|
|
||||||
|
// Process last page if there is still text
|
||||||
|
if (currentTextBlock) {
|
||||||
|
makePages();
|
||||||
|
completePageFn(std::move(currentPage));
|
||||||
|
currentPage.reset();
|
||||||
|
currentTextBlock.reset();
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
void ChapterHtmlSlimParser::addLineToPage(std::shared_ptr<TextBlock> line) {
|
||||||
|
const int lineHeight = renderer.getLineHeight(fontId) * lineCompression;
|
||||||
|
|
||||||
|
if (currentPageNextY + lineHeight > viewportHeight) {
|
||||||
|
completePageFn(std::move(currentPage));
|
||||||
|
currentPage.reset(new Page());
|
||||||
|
currentPageNextY = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
currentPage->elements.push_back(std::make_shared<PageLine>(line, 0, currentPageNextY));
|
||||||
|
currentPageNextY += lineHeight;
|
||||||
|
}
|
||||||
|
|
||||||
|
void ChapterHtmlSlimParser::makePages() {
|
||||||
|
if (!currentTextBlock) {
|
||||||
|
Serial.printf("[%lu] [EHP] !! No text block to make pages for !!\n", millis());
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!currentPage) {
|
||||||
|
currentPage.reset(new Page());
|
||||||
|
currentPageNextY = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
const int lineHeight = renderer.getLineHeight(fontId) * lineCompression;
|
||||||
|
currentTextBlock->layoutAndExtractLines(
|
||||||
|
renderer, fontId, viewportWidth,
|
||||||
|
[this](const std::shared_ptr<TextBlock>& textBlock) { addLineToPage(textBlock); });
|
||||||
|
// Extra paragraph spacing if enabled
|
||||||
|
if (extraParagraphSpacing) {
|
||||||
|
currentPageNextY += lineHeight / 2;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <expat.h>
|
||||||
|
|
||||||
|
#include <climits>
|
||||||
|
#include <functional>
|
||||||
|
#include <memory>
|
||||||
|
|
||||||
|
#include "../ParsedText.h"
|
||||||
|
#include "../blocks/TextBlock.h"
|
||||||
|
|
||||||
|
class Page;
|
||||||
|
class GfxRenderer;
|
||||||
|
|
||||||
|
#define MAX_WORD_SIZE 200
|
||||||
|
|
||||||
|
class ChapterHtmlSlimParser {
|
||||||
|
const std::string& filepath;
|
||||||
|
GfxRenderer& renderer;
|
||||||
|
std::function<void(std::unique_ptr<Page>)> completePageFn;
|
||||||
|
std::function<void(int)> progressFn; // Progress callback (0-100)
|
||||||
|
int depth = 0;
|
||||||
|
int skipUntilDepth = INT_MAX;
|
||||||
|
int boldUntilDepth = INT_MAX;
|
||||||
|
int italicUntilDepth = INT_MAX;
|
||||||
|
// buffer for building up words from characters, will auto break if longer than this
|
||||||
|
// leave one char at end for null pointer
|
||||||
|
char partWordBuffer[MAX_WORD_SIZE + 1] = {};
|
||||||
|
int partWordBufferIndex = 0;
|
||||||
|
std::unique_ptr<ParsedText> currentTextBlock = nullptr;
|
||||||
|
std::unique_ptr<Page> currentPage = nullptr;
|
||||||
|
int16_t currentPageNextY = 0;
|
||||||
|
int fontId;
|
||||||
|
float lineCompression;
|
||||||
|
bool extraParagraphSpacing;
|
||||||
|
int viewportWidth;
|
||||||
|
int viewportHeight;
|
||||||
|
|
||||||
|
void startNewTextBlock(TextBlock::BLOCK_STYLE style);
|
||||||
|
void makePages();
|
||||||
|
// XML callbacks
|
||||||
|
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 endElement(void* userData, const XML_Char* name);
|
||||||
|
|
||||||
|
public:
|
||||||
|
explicit ChapterHtmlSlimParser(const std::string& filepath, GfxRenderer& renderer, const int fontId,
|
||||||
|
const float lineCompression, const bool extraParagraphSpacing, const int viewportWidth,
|
||||||
|
const int viewportHeight,
|
||||||
|
const std::function<void(std::unique_ptr<Page>)>& completePageFn,
|
||||||
|
const std::function<void(int)>& progressFn = nullptr)
|
||||||
|
: filepath(filepath),
|
||||||
|
renderer(renderer),
|
||||||
|
fontId(fontId),
|
||||||
|
lineCompression(lineCompression),
|
||||||
|
extraParagraphSpacing(extraParagraphSpacing),
|
||||||
|
viewportWidth(viewportWidth),
|
||||||
|
viewportHeight(viewportHeight),
|
||||||
|
completePageFn(completePageFn),
|
||||||
|
progressFn(progressFn) {}
|
||||||
|
~ChapterHtmlSlimParser() = default;
|
||||||
|
bool parseAndBuildPages();
|
||||||
|
void addLineToPage(std::shared_ptr<TextBlock> line);
|
||||||
|
};
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
#include "ContainerParser.h"
|
||||||
|
|
||||||
|
#include <HardwareSerial.h>
|
||||||
|
|
||||||
|
bool ContainerParser::setup() {
|
||||||
|
parser = XML_ParserCreate(nullptr);
|
||||||
|
if (!parser) {
|
||||||
|
Serial.printf("[%lu] [CTR] Couldn't allocate memory for parser\n", millis());
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
XML_SetUserData(parser, this);
|
||||||
|
XML_SetElementHandler(parser, startElement, endElement);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
ContainerParser::~ContainerParser() {
|
||||||
|
if (parser) {
|
||||||
|
XML_StopParser(parser, XML_FALSE); // Stop any pending processing
|
||||||
|
XML_SetElementHandler(parser, nullptr, nullptr); // Clear callbacks
|
||||||
|
XML_ParserFree(parser);
|
||||||
|
parser = nullptr;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
size_t ContainerParser::write(const uint8_t data) { return write(&data, 1); }
|
||||||
|
|
||||||
|
size_t ContainerParser::write(const uint8_t* buffer, const size_t size) {
|
||||||
|
if (!parser) return 0;
|
||||||
|
|
||||||
|
const uint8_t* currentBufferPos = buffer;
|
||||||
|
auto remainingInBuffer = size;
|
||||||
|
|
||||||
|
while (remainingInBuffer > 0) {
|
||||||
|
void* const buf = XML_GetBuffer(parser, 1024);
|
||||||
|
if (!buf) {
|
||||||
|
Serial.printf("[%lu] [CTR] Couldn't allocate buffer\n", millis());
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
const auto toRead = remainingInBuffer < 1024 ? remainingInBuffer : 1024;
|
||||||
|
memcpy(buf, currentBufferPos, toRead);
|
||||||
|
|
||||||
|
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)));
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
currentBufferPos += toRead;
|
||||||
|
remainingInBuffer -= toRead;
|
||||||
|
remainingSize -= toRead;
|
||||||
|
}
|
||||||
|
return size;
|
||||||
|
}
|
||||||
|
|
||||||
|
void XMLCALL ContainerParser::startElement(void* userData, const XML_Char* name, const XML_Char** atts) {
|
||||||
|
auto* self = static_cast<ContainerParser*>(userData);
|
||||||
|
|
||||||
|
// Simple state tracking to ensure we are looking at the valid schema structure
|
||||||
|
if (self->state == START && strcmp(name, "container") == 0) {
|
||||||
|
self->state = IN_CONTAINER;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (self->state == IN_CONTAINER && strcmp(name, "rootfiles") == 0) {
|
||||||
|
self->state = IN_ROOTFILES;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (self->state == IN_ROOTFILES && strcmp(name, "rootfile") == 0) {
|
||||||
|
const char* mediaType = nullptr;
|
||||||
|
const char* path = nullptr;
|
||||||
|
|
||||||
|
for (int i = 0; atts[i]; i += 2) {
|
||||||
|
if (strcmp(atts[i], "media-type") == 0) {
|
||||||
|
mediaType = atts[i + 1];
|
||||||
|
} else if (strcmp(atts[i], "full-path") == 0) {
|
||||||
|
path = atts[i + 1];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if this is the standard OEBPS package
|
||||||
|
if (mediaType && path && strcmp(mediaType, "application/oebps-package+xml") == 0) {
|
||||||
|
self->fullPath = path;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void XMLCALL ContainerParser::endElement(void* userData, const XML_Char* name) {
|
||||||
|
auto* self = static_cast<ContainerParser*>(userData);
|
||||||
|
|
||||||
|
if (self->state == IN_ROOTFILES && strcmp(name, "rootfiles") == 0) {
|
||||||
|
self->state = IN_CONTAINER;
|
||||||
|
} else if (self->state == IN_CONTAINER && strcmp(name, "container") == 0) {
|
||||||
|
self->state = START;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
#pragma once
|
||||||
|
#include <Print.h>
|
||||||
|
|
||||||
|
#include <string>
|
||||||
|
|
||||||
|
#include "expat.h"
|
||||||
|
|
||||||
|
class ContainerParser final : public Print {
|
||||||
|
enum ParserState {
|
||||||
|
START,
|
||||||
|
IN_CONTAINER,
|
||||||
|
IN_ROOTFILES,
|
||||||
|
};
|
||||||
|
|
||||||
|
size_t remainingSize;
|
||||||
|
XML_Parser parser = nullptr;
|
||||||
|
ParserState state = START;
|
||||||
|
|
||||||
|
static void startElement(void* userData, const XML_Char* name, const XML_Char** atts);
|
||||||
|
static void endElement(void* userData, const XML_Char* name);
|
||||||
|
|
||||||
|
public:
|
||||||
|
std::string fullPath;
|
||||||
|
|
||||||
|
explicit ContainerParser(const size_t xmlSize) : remainingSize(xmlSize) {}
|
||||||
|
~ContainerParser() override;
|
||||||
|
|
||||||
|
bool setup();
|
||||||
|
|
||||||
|
size_t write(uint8_t) override;
|
||||||
|
size_t write(const uint8_t* buffer, size_t size) override;
|
||||||
|
};
|
||||||
@@ -0,0 +1,243 @@
|
|||||||
|
#include "ContentOpfParser.h"
|
||||||
|
|
||||||
|
#include <FsHelpers.h>
|
||||||
|
#include <HardwareSerial.h>
|
||||||
|
#include <Serialization.h>
|
||||||
|
#include <ZipFile.h>
|
||||||
|
|
||||||
|
#include "../BookMetadataCache.h"
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
constexpr char MEDIA_TYPE_NCX[] = "application/x-dtbncx+xml";
|
||||||
|
constexpr char itemCacheFile[] = "/.items.bin";
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
bool ContentOpfParser::setup() {
|
||||||
|
parser = XML_ParserCreate(nullptr);
|
||||||
|
if (!parser) {
|
||||||
|
Serial.printf("[%lu] [COF] Couldn't allocate memory for parser\n", millis());
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
XML_SetUserData(parser, this);
|
||||||
|
XML_SetElementHandler(parser, startElement, endElement);
|
||||||
|
XML_SetCharacterDataHandler(parser, characterData);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
ContentOpfParser::~ContentOpfParser() {
|
||||||
|
if (parser) {
|
||||||
|
XML_StopParser(parser, XML_FALSE); // Stop any pending processing
|
||||||
|
XML_SetElementHandler(parser, nullptr, nullptr); // Clear callbacks
|
||||||
|
XML_SetCharacterDataHandler(parser, nullptr);
|
||||||
|
XML_ParserFree(parser);
|
||||||
|
parser = nullptr;
|
||||||
|
}
|
||||||
|
if (tempItemStore) {
|
||||||
|
tempItemStore.close();
|
||||||
|
}
|
||||||
|
if (SD.exists((cachePath + itemCacheFile).c_str())) {
|
||||||
|
SD.remove((cachePath + itemCacheFile).c_str());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
size_t ContentOpfParser::write(const uint8_t data) { return write(&data, 1); }
|
||||||
|
|
||||||
|
size_t ContentOpfParser::write(const uint8_t* buffer, const size_t size) {
|
||||||
|
if (!parser) return 0;
|
||||||
|
|
||||||
|
const uint8_t* currentBufferPos = buffer;
|
||||||
|
auto remainingInBuffer = size;
|
||||||
|
|
||||||
|
while (remainingInBuffer > 0) {
|
||||||
|
void* const buf = XML_GetBuffer(parser, 1024);
|
||||||
|
|
||||||
|
if (!buf) {
|
||||||
|
Serial.printf("[%lu] [COF] Couldn't allocate memory for buffer\n", millis());
|
||||||
|
XML_StopParser(parser, XML_FALSE); // Stop any pending processing
|
||||||
|
XML_SetElementHandler(parser, nullptr, nullptr); // Clear callbacks
|
||||||
|
XML_SetCharacterDataHandler(parser, nullptr);
|
||||||
|
XML_ParserFree(parser);
|
||||||
|
parser = nullptr;
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
const auto toRead = remainingInBuffer < 1024 ? remainingInBuffer : 1024;
|
||||||
|
memcpy(buf, currentBufferPos, toRead);
|
||||||
|
|
||||||
|
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),
|
||||||
|
XML_ErrorString(XML_GetErrorCode(parser)));
|
||||||
|
XML_StopParser(parser, XML_FALSE); // Stop any pending processing
|
||||||
|
XML_SetElementHandler(parser, nullptr, nullptr); // Clear callbacks
|
||||||
|
XML_SetCharacterDataHandler(parser, nullptr);
|
||||||
|
XML_ParserFree(parser);
|
||||||
|
parser = nullptr;
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
currentBufferPos += toRead;
|
||||||
|
remainingInBuffer -= toRead;
|
||||||
|
remainingSize -= toRead;
|
||||||
|
}
|
||||||
|
|
||||||
|
return size;
|
||||||
|
}
|
||||||
|
|
||||||
|
void XMLCALL ContentOpfParser::startElement(void* userData, const XML_Char* name, const XML_Char** atts) {
|
||||||
|
auto* self = static_cast<ContentOpfParser*>(userData);
|
||||||
|
(void)atts;
|
||||||
|
|
||||||
|
if (self->state == START && (strcmp(name, "package") == 0 || strcmp(name, "opf:package") == 0)) {
|
||||||
|
self->state = IN_PACKAGE;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (self->state == IN_PACKAGE && (strcmp(name, "metadata") == 0 || strcmp(name, "opf:metadata") == 0)) {
|
||||||
|
self->state = IN_METADATA;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (self->state == IN_METADATA && strcmp(name, "dc:title") == 0) {
|
||||||
|
self->state = IN_BOOK_TITLE;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (self->state == IN_PACKAGE && (strcmp(name, "manifest") == 0 || strcmp(name, "opf:manifest") == 0)) {
|
||||||
|
self->state = IN_MANIFEST;
|
||||||
|
if (!FsHelpers::openFileForWrite("COF", self->cachePath + itemCacheFile, self->tempItemStore)) {
|
||||||
|
Serial.printf(
|
||||||
|
"[%lu] [COF] Couldn't open temp items file for writing. This is probably going to be a fatal error.\n",
|
||||||
|
millis());
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (self->state == IN_PACKAGE && (strcmp(name, "spine") == 0 || strcmp(name, "opf:spine") == 0)) {
|
||||||
|
self->state = IN_SPINE;
|
||||||
|
if (!FsHelpers::openFileForRead("COF", self->cachePath + itemCacheFile, self->tempItemStore)) {
|
||||||
|
Serial.printf(
|
||||||
|
"[%lu] [COF] Couldn't open temp items file for reading. This is probably going to be a fatal error.\n",
|
||||||
|
millis());
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (self->state == IN_METADATA && (strcmp(name, "meta") == 0 || strcmp(name, "opf:meta") == 0)) {
|
||||||
|
bool isCover = false;
|
||||||
|
std::string coverItemId;
|
||||||
|
|
||||||
|
for (int i = 0; atts[i]; i += 2) {
|
||||||
|
if (strcmp(atts[i], "name") == 0 && strcmp(atts[i + 1], "cover") == 0) {
|
||||||
|
isCover = true;
|
||||||
|
} else if (strcmp(atts[i], "content") == 0) {
|
||||||
|
coverItemId = atts[i + 1];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isCover) {
|
||||||
|
self->coverItemId = coverItemId;
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (self->state == IN_MANIFEST && (strcmp(name, "item") == 0 || strcmp(name, "opf:item") == 0)) {
|
||||||
|
std::string itemId;
|
||||||
|
std::string href;
|
||||||
|
std::string mediaType;
|
||||||
|
|
||||||
|
for (int i = 0; atts[i]; i += 2) {
|
||||||
|
if (strcmp(atts[i], "id") == 0) {
|
||||||
|
itemId = atts[i + 1];
|
||||||
|
} else if (strcmp(atts[i], "href") == 0) {
|
||||||
|
href = self->baseContentPath + atts[i + 1];
|
||||||
|
} else if (strcmp(atts[i], "media-type") == 0) {
|
||||||
|
mediaType = atts[i + 1];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Write items down to SD card
|
||||||
|
serialization::writeString(self->tempItemStore, itemId);
|
||||||
|
serialization::writeString(self->tempItemStore, href);
|
||||||
|
|
||||||
|
if (itemId == self->coverItemId) {
|
||||||
|
self->coverItemHref = href;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (mediaType == MEDIA_TYPE_NCX) {
|
||||||
|
if (self->tocNcxPath.empty()) {
|
||||||
|
self->tocNcxPath = href;
|
||||||
|
} else {
|
||||||
|
Serial.printf("[%lu] [COF] Warning: Multiple NCX files found in manifest. Ignoring duplicate: %s\n", millis(),
|
||||||
|
href.c_str());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// NOTE: This relies on spine appearing after item manifest (which is pretty safe as it's part of the EPUB spec)
|
||||||
|
// Only run the spine parsing if there's a cache to add it to
|
||||||
|
if (self->cache) {
|
||||||
|
if (self->state == IN_SPINE && (strcmp(name, "itemref") == 0 || strcmp(name, "opf:itemref") == 0)) {
|
||||||
|
for (int i = 0; atts[i]; i += 2) {
|
||||||
|
if (strcmp(atts[i], "idref") == 0) {
|
||||||
|
const std::string idref = atts[i + 1];
|
||||||
|
// Resolve the idref to href using items map
|
||||||
|
self->tempItemStore.seek(0);
|
||||||
|
std::string itemId;
|
||||||
|
std::string href;
|
||||||
|
while (self->tempItemStore.available()) {
|
||||||
|
serialization::readString(self->tempItemStore, itemId);
|
||||||
|
serialization::readString(self->tempItemStore, href);
|
||||||
|
if (itemId == idref) {
|
||||||
|
self->cache->createSpineEntry(href);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void XMLCALL ContentOpfParser::characterData(void* userData, const XML_Char* s, const int len) {
|
||||||
|
auto* self = static_cast<ContentOpfParser*>(userData);
|
||||||
|
|
||||||
|
if (self->state == IN_BOOK_TITLE) {
|
||||||
|
self->title.append(s, len);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void XMLCALL ContentOpfParser::endElement(void* userData, const XML_Char* name) {
|
||||||
|
auto* self = static_cast<ContentOpfParser*>(userData);
|
||||||
|
(void)name;
|
||||||
|
|
||||||
|
if (self->state == IN_SPINE && (strcmp(name, "spine") == 0 || strcmp(name, "opf:spine") == 0)) {
|
||||||
|
self->state = IN_PACKAGE;
|
||||||
|
self->tempItemStore.close();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (self->state == IN_MANIFEST && (strcmp(name, "manifest") == 0 || strcmp(name, "opf:manifest") == 0)) {
|
||||||
|
self->state = IN_PACKAGE;
|
||||||
|
self->tempItemStore.close();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (self->state == IN_BOOK_TITLE && strcmp(name, "dc:title") == 0) {
|
||||||
|
self->state = IN_METADATA;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (self->state == IN_METADATA && (strcmp(name, "metadata") == 0 || strcmp(name, "opf:metadata") == 0)) {
|
||||||
|
self->state = IN_PACKAGE;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (self->state == IN_PACKAGE && (strcmp(name, "package") == 0 || strcmp(name, "opf:package") == 0)) {
|
||||||
|
self->state = START;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
#pragma once
|
||||||
|
#include <Print.h>
|
||||||
|
|
||||||
|
#include "Epub.h"
|
||||||
|
#include "expat.h"
|
||||||
|
|
||||||
|
class BookMetadataCache;
|
||||||
|
|
||||||
|
class ContentOpfParser final : public Print {
|
||||||
|
enum ParserState {
|
||||||
|
START,
|
||||||
|
IN_PACKAGE,
|
||||||
|
IN_METADATA,
|
||||||
|
IN_BOOK_TITLE,
|
||||||
|
IN_MANIFEST,
|
||||||
|
IN_SPINE,
|
||||||
|
};
|
||||||
|
|
||||||
|
const std::string& cachePath;
|
||||||
|
const std::string& baseContentPath;
|
||||||
|
size_t remainingSize;
|
||||||
|
XML_Parser parser = nullptr;
|
||||||
|
ParserState state = START;
|
||||||
|
BookMetadataCache* cache;
|
||||||
|
File tempItemStore;
|
||||||
|
std::string coverItemId;
|
||||||
|
|
||||||
|
static void startElement(void* userData, const XML_Char* name, const XML_Char** atts);
|
||||||
|
static void characterData(void* userData, const XML_Char* s, int len);
|
||||||
|
static void endElement(void* userData, const XML_Char* name);
|
||||||
|
|
||||||
|
public:
|
||||||
|
std::string title;
|
||||||
|
std::string tocNcxPath;
|
||||||
|
std::string coverItemHref;
|
||||||
|
|
||||||
|
explicit ContentOpfParser(const std::string& cachePath, const std::string& baseContentPath, const size_t xmlSize,
|
||||||
|
BookMetadataCache* cache)
|
||||||
|
: cachePath(cachePath), baseContentPath(baseContentPath), remainingSize(xmlSize), cache(cache) {}
|
||||||
|
~ContentOpfParser() override;
|
||||||
|
|
||||||
|
bool setup();
|
||||||
|
|
||||||
|
size_t write(uint8_t) override;
|
||||||
|
size_t write(const uint8_t* buffer, size_t size) override;
|
||||||
|
};
|
||||||
@@ -0,0 +1,180 @@
|
|||||||
|
#include "TocNcxParser.h"
|
||||||
|
|
||||||
|
#include <HardwareSerial.h>
|
||||||
|
|
||||||
|
#include "../BookMetadataCache.h"
|
||||||
|
|
||||||
|
bool TocNcxParser::setup() {
|
||||||
|
parser = XML_ParserCreate(nullptr);
|
||||||
|
if (!parser) {
|
||||||
|
Serial.printf("[%lu] [TOC] Couldn't allocate memory for parser\n", millis());
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
XML_SetUserData(parser, this);
|
||||||
|
XML_SetElementHandler(parser, startElement, endElement);
|
||||||
|
XML_SetCharacterDataHandler(parser, characterData);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
TocNcxParser::~TocNcxParser() {
|
||||||
|
if (parser) {
|
||||||
|
XML_StopParser(parser, XML_FALSE); // Stop any pending processing
|
||||||
|
XML_SetElementHandler(parser, nullptr, nullptr); // Clear callbacks
|
||||||
|
XML_SetCharacterDataHandler(parser, nullptr);
|
||||||
|
XML_ParserFree(parser);
|
||||||
|
parser = nullptr;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
size_t TocNcxParser::write(const uint8_t data) { return write(&data, 1); }
|
||||||
|
|
||||||
|
size_t TocNcxParser::write(const uint8_t* buffer, const size_t size) {
|
||||||
|
if (!parser) return 0;
|
||||||
|
|
||||||
|
const uint8_t* currentBufferPos = buffer;
|
||||||
|
auto remainingInBuffer = size;
|
||||||
|
|
||||||
|
while (remainingInBuffer > 0) {
|
||||||
|
void* const buf = XML_GetBuffer(parser, 1024);
|
||||||
|
if (!buf) {
|
||||||
|
Serial.printf("[%lu] [TOC] Couldn't allocate memory for buffer\n", millis());
|
||||||
|
XML_StopParser(parser, XML_FALSE); // Stop any pending processing
|
||||||
|
XML_SetElementHandler(parser, nullptr, nullptr); // Clear callbacks
|
||||||
|
XML_SetCharacterDataHandler(parser, nullptr);
|
||||||
|
XML_ParserFree(parser);
|
||||||
|
parser = nullptr;
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
const auto toRead = remainingInBuffer < 1024 ? remainingInBuffer : 1024;
|
||||||
|
memcpy(buf, currentBufferPos, toRead);
|
||||||
|
|
||||||
|
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),
|
||||||
|
XML_ErrorString(XML_GetErrorCode(parser)));
|
||||||
|
XML_StopParser(parser, XML_FALSE); // Stop any pending processing
|
||||||
|
XML_SetElementHandler(parser, nullptr, nullptr); // Clear callbacks
|
||||||
|
XML_SetCharacterDataHandler(parser, nullptr);
|
||||||
|
XML_ParserFree(parser);
|
||||||
|
parser = nullptr;
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
currentBufferPos += toRead;
|
||||||
|
remainingInBuffer -= toRead;
|
||||||
|
remainingSize -= toRead;
|
||||||
|
}
|
||||||
|
return size;
|
||||||
|
}
|
||||||
|
|
||||||
|
void XMLCALL TocNcxParser::startElement(void* userData, const XML_Char* name, const XML_Char** atts) {
|
||||||
|
// NOTE: We rely on navPoint label and content coming before any nested navPoints, this will be fine:
|
||||||
|
// <navPoint>
|
||||||
|
// <navLabel><text>Chapter 1</text></navLabel>
|
||||||
|
// <content src="ch1.html"/>
|
||||||
|
// <navPoint> ...nested... </navPoint>
|
||||||
|
// </navPoint>
|
||||||
|
//
|
||||||
|
// This will NOT:
|
||||||
|
// <navPoint>
|
||||||
|
// <navPoint> ...nested... </navPoint>
|
||||||
|
// <navLabel><text>Chapter 1</text></navLabel>
|
||||||
|
// <content src="ch1.html"/>
|
||||||
|
// </navPoint>
|
||||||
|
|
||||||
|
auto* self = static_cast<TocNcxParser*>(userData);
|
||||||
|
|
||||||
|
if (self->state == START && strcmp(name, "ncx") == 0) {
|
||||||
|
self->state = IN_NCX;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (self->state == IN_NCX && strcmp(name, "navMap") == 0) {
|
||||||
|
self->state = IN_NAV_MAP;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Handles both top-level and nested navPoints
|
||||||
|
if ((self->state == IN_NAV_MAP || self->state == IN_NAV_POINT) && strcmp(name, "navPoint") == 0) {
|
||||||
|
self->state = IN_NAV_POINT;
|
||||||
|
self->currentDepth++;
|
||||||
|
|
||||||
|
self->currentLabel.clear();
|
||||||
|
self->currentSrc.clear();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (self->state == IN_NAV_POINT && strcmp(name, "navLabel") == 0) {
|
||||||
|
self->state = IN_NAV_LABEL;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (self->state == IN_NAV_LABEL && strcmp(name, "text") == 0) {
|
||||||
|
self->state = IN_NAV_LABEL_TEXT;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (self->state == IN_NAV_POINT && strcmp(name, "content") == 0) {
|
||||||
|
for (int i = 0; atts[i]; i += 2) {
|
||||||
|
if (strcmp(atts[i], "src") == 0) {
|
||||||
|
self->currentSrc = atts[i + 1];
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void XMLCALL TocNcxParser::characterData(void* userData, const XML_Char* s, const int len) {
|
||||||
|
auto* self = static_cast<TocNcxParser*>(userData);
|
||||||
|
if (self->state == IN_NAV_LABEL_TEXT) {
|
||||||
|
self->currentLabel.append(s, len);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void XMLCALL TocNcxParser::endElement(void* userData, const XML_Char* name) {
|
||||||
|
auto* self = static_cast<TocNcxParser*>(userData);
|
||||||
|
|
||||||
|
if (self->state == IN_NAV_LABEL_TEXT && strcmp(name, "text") == 0) {
|
||||||
|
self->state = IN_NAV_LABEL;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (self->state == IN_NAV_LABEL && strcmp(name, "navLabel") == 0) {
|
||||||
|
self->state = IN_NAV_POINT;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (self->state == IN_NAV_POINT && strcmp(name, "navPoint") == 0) {
|
||||||
|
self->currentDepth--;
|
||||||
|
if (self->currentDepth == 0) {
|
||||||
|
self->state = IN_NAV_MAP;
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (self->state == IN_NAV_POINT && strcmp(name, "content") == 0) {
|
||||||
|
// At this point (end of content tag), we likely have both Label (from previous tags) and Src.
|
||||||
|
// This is the safest place to push the data, assuming <navLabel> always comes before <content>.
|
||||||
|
// NCX spec says navLabel comes before content.
|
||||||
|
if (!self->currentLabel.empty() && !self->currentSrc.empty()) {
|
||||||
|
std::string href = self->baseContentPath + self->currentSrc;
|
||||||
|
std::string anchor;
|
||||||
|
|
||||||
|
const size_t pos = href.find('#');
|
||||||
|
if (pos != std::string::npos) {
|
||||||
|
anchor = href.substr(pos + 1);
|
||||||
|
href = href.substr(0, pos);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (self->cache) {
|
||||||
|
self->cache->createTocEntry(self->currentLabel, href, anchor, self->currentDepth);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Clear them so we don't re-add them if there are weird XML structures
|
||||||
|
self->currentLabel.clear();
|
||||||
|
self->currentSrc.clear();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
#pragma once
|
||||||
|
#include <Print.h>
|
||||||
|
#include <expat.h>
|
||||||
|
|
||||||
|
#include <string>
|
||||||
|
|
||||||
|
class BookMetadataCache;
|
||||||
|
|
||||||
|
class TocNcxParser final : public Print {
|
||||||
|
enum ParserState { START, IN_NCX, IN_NAV_MAP, IN_NAV_POINT, IN_NAV_LABEL, IN_NAV_LABEL_TEXT, IN_CONTENT };
|
||||||
|
|
||||||
|
const std::string& baseContentPath;
|
||||||
|
size_t remainingSize;
|
||||||
|
XML_Parser parser = nullptr;
|
||||||
|
ParserState state = START;
|
||||||
|
BookMetadataCache* cache;
|
||||||
|
|
||||||
|
std::string currentLabel;
|
||||||
|
std::string currentSrc;
|
||||||
|
uint8_t currentDepth = 0;
|
||||||
|
|
||||||
|
static void startElement(void* userData, const XML_Char* name, const XML_Char** atts);
|
||||||
|
static void characterData(void* userData, const XML_Char* s, int len);
|
||||||
|
static void endElement(void* userData, const XML_Char* name);
|
||||||
|
|
||||||
|
public:
|
||||||
|
explicit TocNcxParser(const std::string& baseContentPath, const size_t xmlSize, BookMetadataCache* cache)
|
||||||
|
: baseContentPath(baseContentPath), remainingSize(xmlSize), cache(cache) {}
|
||||||
|
~TocNcxParser() override;
|
||||||
|
|
||||||
|
bool setup();
|
||||||
|
|
||||||
|
size_t write(uint8_t) override;
|
||||||
|
size_t write(const uint8_t* buffer, size_t size) override;
|
||||||
|
};
|
||||||
@@ -0,0 +1,112 @@
|
|||||||
|
#include "FsHelpers.h"
|
||||||
|
|
||||||
|
#include <SD.h>
|
||||||
|
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
bool FsHelpers::openFileForRead(const char* moduleName, const char* path, File& file) {
|
||||||
|
if (!SD.exists(path)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
file = SD.open(path, FILE_READ);
|
||||||
|
if (!file) {
|
||||||
|
Serial.printf("[%lu] [%s] Failed to open file for reading: %s\n", millis(), moduleName, path);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool FsHelpers::openFileForRead(const char* moduleName, const std::string& path, File& file) {
|
||||||
|
return openFileForRead(moduleName, path.c_str(), file);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool FsHelpers::openFileForRead(const char* moduleName, const String& path, File& file) {
|
||||||
|
return openFileForRead(moduleName, path.c_str(), file);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool FsHelpers::openFileForWrite(const char* moduleName, const char* path, File& file) {
|
||||||
|
file = SD.open(path, FILE_WRITE, true);
|
||||||
|
if (!file) {
|
||||||
|
Serial.printf("[%lu] [%s] Failed to open file for writing: %s\n", millis(), moduleName, path);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool FsHelpers::openFileForWrite(const char* moduleName, const std::string& path, File& file) {
|
||||||
|
return openFileForWrite(moduleName, path.c_str(), file);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool FsHelpers::openFileForWrite(const char* moduleName, const String& path, File& file) {
|
||||||
|
return openFileForWrite(moduleName, path.c_str(), file);
|
||||||
|
}
|
||||||
|
|
||||||
|
bool FsHelpers::removeDir(const char* path) {
|
||||||
|
// 1. Open the directory
|
||||||
|
File dir = SD.open(path);
|
||||||
|
if (!dir) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (!dir.isDirectory()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
File file = dir.openNextFile();
|
||||||
|
while (file) {
|
||||||
|
String filePath = path;
|
||||||
|
if (!filePath.endsWith("/")) {
|
||||||
|
filePath += "/";
|
||||||
|
}
|
||||||
|
filePath += file.name();
|
||||||
|
|
||||||
|
if (file.isDirectory()) {
|
||||||
|
if (!removeDir(filePath.c_str())) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if (!SD.remove(filePath.c_str())) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
file = dir.openNextFile();
|
||||||
|
}
|
||||||
|
|
||||||
|
return SD.rmdir(path);
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string FsHelpers::normalisePath(const std::string& path) {
|
||||||
|
std::vector<std::string> components;
|
||||||
|
std::string component;
|
||||||
|
|
||||||
|
for (const auto c : path) {
|
||||||
|
if (c == '/') {
|
||||||
|
if (!component.empty()) {
|
||||||
|
if (component == "..") {
|
||||||
|
if (!components.empty()) {
|
||||||
|
components.pop_back();
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
components.push_back(component);
|
||||||
|
}
|
||||||
|
component.clear();
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
component += c;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!component.empty()) {
|
||||||
|
components.push_back(component);
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string result;
|
||||||
|
for (const auto& c : components) {
|
||||||
|
if (!result.empty()) {
|
||||||
|
result += "/";
|
||||||
|
}
|
||||||
|
result += c;
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
#pragma once
|
||||||
|
#include <FS.h>
|
||||||
|
|
||||||
|
class FsHelpers {
|
||||||
|
public:
|
||||||
|
static bool openFileForRead(const char* moduleName, const char* path, File& file);
|
||||||
|
static bool openFileForRead(const char* moduleName, const std::string& path, File& file);
|
||||||
|
static bool openFileForRead(const char* moduleName, const String& path, File& file);
|
||||||
|
static bool openFileForWrite(const char* moduleName, const char* path, File& file);
|
||||||
|
static bool openFileForWrite(const char* moduleName, const std::string& path, File& file);
|
||||||
|
static bool openFileForWrite(const char* moduleName, const String& path, File& file);
|
||||||
|
static bool removeDir(const char* path);
|
||||||
|
static std::string normalisePath(const std::string& path);
|
||||||
|
};
|
||||||
@@ -0,0 +1,372 @@
|
|||||||
|
#include "Bitmap.h"
|
||||||
|
|
||||||
|
#include <cstdlib>
|
||||||
|
#include <cstring>
|
||||||
|
|
||||||
|
// ============================================================================
|
||||||
|
// IMAGE PROCESSING OPTIONS - Toggle these to test different configurations
|
||||||
|
// ============================================================================
|
||||||
|
// Note: For cover images, dithering is done in JpegToBmpConverter.cpp
|
||||||
|
// This file handles BMP reading - use simple quantization to avoid double-dithering
|
||||||
|
constexpr bool USE_FLOYD_STEINBERG = false; // Disabled - dithering done at JPEG conversion
|
||||||
|
constexpr bool USE_NOISE_DITHERING = false; // Hash-based noise dithering
|
||||||
|
// Brightness adjustments:
|
||||||
|
constexpr bool USE_BRIGHTNESS = false; // true: apply brightness/gamma adjustments
|
||||||
|
constexpr int BRIGHTNESS_BOOST = 20; // Brightness offset (0-50), only if USE_BRIGHTNESS=true
|
||||||
|
constexpr bool GAMMA_CORRECTION = false; // Gamma curve, only if USE_BRIGHTNESS=true
|
||||||
|
// ============================================================================
|
||||||
|
|
||||||
|
// Integer approximation of gamma correction (brightens midtones)
|
||||||
|
static inline int applyGamma(int gray) {
|
||||||
|
if (!GAMMA_CORRECTION) return gray;
|
||||||
|
const int product = gray * 255;
|
||||||
|
int x = gray;
|
||||||
|
if (x > 0) {
|
||||||
|
x = (x + product / x) >> 1;
|
||||||
|
x = (x + product / x) >> 1;
|
||||||
|
}
|
||||||
|
return x > 255 ? 255 : x;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Simple quantization without dithering - just divide into 4 levels
|
||||||
|
static inline uint8_t quantizeSimple(int gray) {
|
||||||
|
if (USE_BRIGHTNESS) {
|
||||||
|
gray += BRIGHTNESS_BOOST;
|
||||||
|
if (gray > 255) gray = 255;
|
||||||
|
gray = applyGamma(gray);
|
||||||
|
}
|
||||||
|
return static_cast<uint8_t>(gray >> 6);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Hash-based noise dithering - survives downsampling without moiré artifacts
|
||||||
|
static inline uint8_t quantizeNoise(int gray, int x, int y) {
|
||||||
|
if (USE_BRIGHTNESS) {
|
||||||
|
gray += BRIGHTNESS_BOOST;
|
||||||
|
if (gray > 255) gray = 255;
|
||||||
|
gray = applyGamma(gray);
|
||||||
|
}
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Main quantization function
|
||||||
|
static inline uint8_t quantize(int gray, int x, int y) {
|
||||||
|
if (USE_NOISE_DITHERING) {
|
||||||
|
return quantizeNoise(gray, x, y);
|
||||||
|
} else {
|
||||||
|
return quantizeSimple(gray);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Floyd-Steinberg quantization with error diffusion and serpentine scanning
|
||||||
|
// Returns 2-bit value (0-3) and updates error buffers
|
||||||
|
static inline uint8_t quantizeFloydSteinberg(int gray, int x, int width, int16_t* errorCurRow, int16_t* errorNextRow,
|
||||||
|
bool reverseDir) {
|
||||||
|
// Add accumulated error to this pixel
|
||||||
|
int adjusted = gray + errorCurRow[x + 1];
|
||||||
|
|
||||||
|
// Clamp to valid range
|
||||||
|
if (adjusted < 0) adjusted = 0;
|
||||||
|
if (adjusted > 255) adjusted = 255;
|
||||||
|
|
||||||
|
// Quantize to 4 levels (0, 85, 170, 255)
|
||||||
|
uint8_t quantized;
|
||||||
|
int quantizedValue;
|
||||||
|
if (adjusted < 43) {
|
||||||
|
quantized = 0;
|
||||||
|
quantizedValue = 0;
|
||||||
|
} else if (adjusted < 128) {
|
||||||
|
quantized = 1;
|
||||||
|
quantizedValue = 85;
|
||||||
|
} else if (adjusted < 213) {
|
||||||
|
quantized = 2;
|
||||||
|
quantizedValue = 170;
|
||||||
|
} else {
|
||||||
|
quantized = 3;
|
||||||
|
quantizedValue = 255;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Calculate error
|
||||||
|
int error = adjusted - quantizedValue;
|
||||||
|
|
||||||
|
// Distribute error to neighbors (serpentine: direction-aware)
|
||||||
|
if (!reverseDir) {
|
||||||
|
// Left to right
|
||||||
|
errorCurRow[x + 2] += (error * 7) >> 4; // Right: 7/16
|
||||||
|
errorNextRow[x] += (error * 3) >> 4; // Bottom-left: 3/16
|
||||||
|
errorNextRow[x + 1] += (error * 5) >> 4; // Bottom: 5/16
|
||||||
|
errorNextRow[x + 2] += (error) >> 4; // Bottom-right: 1/16
|
||||||
|
} else {
|
||||||
|
// Right to left (mirrored)
|
||||||
|
errorCurRow[x] += (error * 7) >> 4; // Left: 7/16
|
||||||
|
errorNextRow[x + 2] += (error * 3) >> 4; // Bottom-right: 3/16
|
||||||
|
errorNextRow[x + 1] += (error * 5) >> 4; // Bottom: 5/16
|
||||||
|
errorNextRow[x] += (error) >> 4; // Bottom-left: 1/16
|
||||||
|
}
|
||||||
|
|
||||||
|
return quantized;
|
||||||
|
}
|
||||||
|
|
||||||
|
Bitmap::~Bitmap() {
|
||||||
|
delete[] errorCurRow;
|
||||||
|
delete[] errorNextRow;
|
||||||
|
}
|
||||||
|
|
||||||
|
uint16_t Bitmap::readLE16(File& f) {
|
||||||
|
const int c0 = f.read();
|
||||||
|
const int c1 = f.read();
|
||||||
|
const auto b0 = static_cast<uint8_t>(c0 < 0 ? 0 : c0);
|
||||||
|
const auto b1 = static_cast<uint8_t>(c1 < 0 ? 0 : c1);
|
||||||
|
return static_cast<uint16_t>(b0) | (static_cast<uint16_t>(b1) << 8);
|
||||||
|
}
|
||||||
|
|
||||||
|
uint32_t Bitmap::readLE32(File& f) {
|
||||||
|
const int c0 = f.read();
|
||||||
|
const int c1 = f.read();
|
||||||
|
const int c2 = f.read();
|
||||||
|
const int c3 = f.read();
|
||||||
|
|
||||||
|
const auto b0 = static_cast<uint8_t>(c0 < 0 ? 0 : c0);
|
||||||
|
const auto b1 = static_cast<uint8_t>(c1 < 0 ? 0 : c1);
|
||||||
|
const auto b2 = static_cast<uint8_t>(c2 < 0 ? 0 : c2);
|
||||||
|
const auto b3 = static_cast<uint8_t>(c3 < 0 ? 0 : c3);
|
||||||
|
|
||||||
|
return static_cast<uint32_t>(b0) | (static_cast<uint32_t>(b1) << 8) | (static_cast<uint32_t>(b2) << 16) |
|
||||||
|
(static_cast<uint32_t>(b3) << 24);
|
||||||
|
}
|
||||||
|
|
||||||
|
const char* Bitmap::errorToString(BmpReaderError err) {
|
||||||
|
switch (err) {
|
||||||
|
case BmpReaderError::Ok:
|
||||||
|
return "Ok";
|
||||||
|
case BmpReaderError::FileInvalid:
|
||||||
|
return "FileInvalid";
|
||||||
|
case BmpReaderError::SeekStartFailed:
|
||||||
|
return "SeekStartFailed";
|
||||||
|
case BmpReaderError::NotBMP:
|
||||||
|
return "NotBMP (missing 'BM')";
|
||||||
|
case BmpReaderError::DIBTooSmall:
|
||||||
|
return "DIBTooSmall (<40 bytes)";
|
||||||
|
case BmpReaderError::BadPlanes:
|
||||||
|
return "BadPlanes (!= 1)";
|
||||||
|
case BmpReaderError::UnsupportedBpp:
|
||||||
|
return "UnsupportedBpp (expected 1, 2, 8, 24, or 32)";
|
||||||
|
case BmpReaderError::UnsupportedCompression:
|
||||||
|
return "UnsupportedCompression (expected BI_RGB or BI_BITFIELDS for 32bpp)";
|
||||||
|
case BmpReaderError::BadDimensions:
|
||||||
|
return "BadDimensions";
|
||||||
|
case BmpReaderError::ImageTooLarge:
|
||||||
|
return "ImageTooLarge (max 2048x3072)";
|
||||||
|
case BmpReaderError::PaletteTooLarge:
|
||||||
|
return "PaletteTooLarge";
|
||||||
|
|
||||||
|
case BmpReaderError::SeekPixelDataFailed:
|
||||||
|
return "SeekPixelDataFailed";
|
||||||
|
case BmpReaderError::BufferTooSmall:
|
||||||
|
return "BufferTooSmall";
|
||||||
|
|
||||||
|
case BmpReaderError::OomRowBuffer:
|
||||||
|
return "OomRowBuffer";
|
||||||
|
case BmpReaderError::ShortReadRow:
|
||||||
|
return "ShortReadRow";
|
||||||
|
}
|
||||||
|
return "Unknown";
|
||||||
|
}
|
||||||
|
|
||||||
|
BmpReaderError Bitmap::parseHeaders() {
|
||||||
|
if (!file) return BmpReaderError::FileInvalid;
|
||||||
|
if (!file.seek(0)) return BmpReaderError::SeekStartFailed;
|
||||||
|
|
||||||
|
// --- BMP FILE HEADER ---
|
||||||
|
const uint16_t bfType = readLE16(file);
|
||||||
|
if (bfType != 0x4D42) return BmpReaderError::NotBMP;
|
||||||
|
|
||||||
|
file.seek(8, SeekCur);
|
||||||
|
bfOffBits = readLE32(file);
|
||||||
|
|
||||||
|
// --- DIB HEADER ---
|
||||||
|
const uint32_t biSize = readLE32(file);
|
||||||
|
if (biSize < 40) return BmpReaderError::DIBTooSmall;
|
||||||
|
|
||||||
|
width = static_cast<int32_t>(readLE32(file));
|
||||||
|
const auto rawHeight = static_cast<int32_t>(readLE32(file));
|
||||||
|
topDown = rawHeight < 0;
|
||||||
|
height = topDown ? -rawHeight : rawHeight;
|
||||||
|
|
||||||
|
const uint16_t planes = readLE16(file);
|
||||||
|
bpp = readLE16(file);
|
||||||
|
const uint32_t comp = readLE32(file);
|
||||||
|
const bool validBpp = bpp == 1 || bpp == 2 || bpp == 8 || bpp == 24 || bpp == 32;
|
||||||
|
|
||||||
|
if (planes != 1) return BmpReaderError::BadPlanes;
|
||||||
|
if (!validBpp) return BmpReaderError::UnsupportedBpp;
|
||||||
|
// Allow BI_RGB (0) for all, and BI_BITFIELDS (3) for 32bpp which is common for BGRA masks.
|
||||||
|
if (!(comp == 0 || (bpp == 32 && comp == 3))) return BmpReaderError::UnsupportedCompression;
|
||||||
|
|
||||||
|
file.seek(12, SeekCur); // biSizeImage, biXPelsPerMeter, biYPelsPerMeter
|
||||||
|
const uint32_t colorsUsed = readLE32(file);
|
||||||
|
if (colorsUsed > 256u) return BmpReaderError::PaletteTooLarge;
|
||||||
|
file.seek(4, SeekCur); // biClrImportant
|
||||||
|
|
||||||
|
if (width <= 0 || height <= 0) return BmpReaderError::BadDimensions;
|
||||||
|
|
||||||
|
// Safety limits to prevent memory issues on ESP32
|
||||||
|
constexpr int MAX_IMAGE_WIDTH = 2048;
|
||||||
|
constexpr int MAX_IMAGE_HEIGHT = 3072;
|
||||||
|
if (width > MAX_IMAGE_WIDTH || height > MAX_IMAGE_HEIGHT) {
|
||||||
|
return BmpReaderError::ImageTooLarge;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Pre-calculate Row Bytes to avoid doing this every row
|
||||||
|
rowBytes = (width * bpp + 31) / 32 * 4;
|
||||||
|
|
||||||
|
for (int i = 0; i < 256; i++) paletteLum[i] = static_cast<uint8_t>(i);
|
||||||
|
if (colorsUsed > 0) {
|
||||||
|
for (uint32_t i = 0; i < colorsUsed; i++) {
|
||||||
|
uint8_t rgb[4];
|
||||||
|
file.read(rgb, 4); // Read B, G, R, Reserved in one go
|
||||||
|
paletteLum[i] = (77u * rgb[2] + 150u * rgb[1] + 29u * rgb[0]) >> 8;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!file.seek(bfOffBits)) {
|
||||||
|
return BmpReaderError::SeekPixelDataFailed;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Allocate Floyd-Steinberg error buffers if enabled
|
||||||
|
if (USE_FLOYD_STEINBERG) {
|
||||||
|
delete[] errorCurRow;
|
||||||
|
delete[] errorNextRow;
|
||||||
|
errorCurRow = new int16_t[width + 2](); // +2 for boundary handling
|
||||||
|
errorNextRow = new int16_t[width + 2]();
|
||||||
|
lastRowY = -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
return BmpReaderError::Ok;
|
||||||
|
}
|
||||||
|
|
||||||
|
// packed 2bpp output, 0 = black, 1 = dark gray, 2 = light gray, 3 = white
|
||||||
|
BmpReaderError Bitmap::readRow(uint8_t* data, uint8_t* rowBuffer, int rowY) const {
|
||||||
|
// Note: rowBuffer should be pre-allocated by the caller to size 'rowBytes'
|
||||||
|
if (file.read(rowBuffer, rowBytes) != rowBytes) return BmpReaderError::ShortReadRow;
|
||||||
|
|
||||||
|
// Handle Floyd-Steinberg error buffer progression
|
||||||
|
const bool useFS = USE_FLOYD_STEINBERG && errorCurRow && errorNextRow;
|
||||||
|
if (useFS) {
|
||||||
|
// Check if we need to advance to next row (or reset if jumping)
|
||||||
|
if (rowY != lastRowY + 1 && rowY != 0) {
|
||||||
|
// Non-sequential row access - reset error buffers
|
||||||
|
memset(errorCurRow, 0, (width + 2) * sizeof(int16_t));
|
||||||
|
memset(errorNextRow, 0, (width + 2) * sizeof(int16_t));
|
||||||
|
} else if (rowY > 0) {
|
||||||
|
// Sequential access - swap buffers
|
||||||
|
int16_t* temp = errorCurRow;
|
||||||
|
errorCurRow = errorNextRow;
|
||||||
|
errorNextRow = temp;
|
||||||
|
memset(errorNextRow, 0, (width + 2) * sizeof(int16_t));
|
||||||
|
}
|
||||||
|
lastRowY = rowY;
|
||||||
|
}
|
||||||
|
|
||||||
|
uint8_t* outPtr = data;
|
||||||
|
uint8_t currentOutByte = 0;
|
||||||
|
int bitShift = 6;
|
||||||
|
int currentX = 0;
|
||||||
|
|
||||||
|
// Helper lambda to pack 2bpp color into the output stream
|
||||||
|
auto packPixel = [&](const uint8_t lum) {
|
||||||
|
uint8_t color;
|
||||||
|
if (useFS) {
|
||||||
|
// Floyd-Steinberg error diffusion
|
||||||
|
color = quantizeFloydSteinberg(lum, currentX, width, errorCurRow, errorNextRow, false);
|
||||||
|
} else {
|
||||||
|
// Simple quantization or noise dithering
|
||||||
|
color = quantize(lum, currentX, rowY);
|
||||||
|
}
|
||||||
|
currentOutByte |= (color << bitShift);
|
||||||
|
if (bitShift == 0) {
|
||||||
|
*outPtr++ = currentOutByte;
|
||||||
|
currentOutByte = 0;
|
||||||
|
bitShift = 6;
|
||||||
|
} else {
|
||||||
|
bitShift -= 2;
|
||||||
|
}
|
||||||
|
currentX++;
|
||||||
|
};
|
||||||
|
|
||||||
|
uint8_t lum;
|
||||||
|
|
||||||
|
switch (bpp) {
|
||||||
|
case 32: {
|
||||||
|
const uint8_t* p = rowBuffer;
|
||||||
|
for (int x = 0; x < width; x++) {
|
||||||
|
lum = (77u * p[2] + 150u * p[1] + 29u * p[0]) >> 8;
|
||||||
|
packPixel(lum);
|
||||||
|
p += 4;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case 24: {
|
||||||
|
const uint8_t* p = rowBuffer;
|
||||||
|
for (int x = 0; x < width; x++) {
|
||||||
|
lum = (77u * p[2] + 150u * p[1] + 29u * p[0]) >> 8;
|
||||||
|
packPixel(lum);
|
||||||
|
p += 3;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case 8: {
|
||||||
|
for (int x = 0; x < width; x++) {
|
||||||
|
packPixel(paletteLum[rowBuffer[x]]);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case 2: {
|
||||||
|
for (int x = 0; x < width; x++) {
|
||||||
|
lum = paletteLum[(rowBuffer[x >> 2] >> (6 - ((x & 3) * 2))) & 0x03];
|
||||||
|
packPixel(lum);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case 1: {
|
||||||
|
for (int x = 0; x < width; x++) {
|
||||||
|
lum = (rowBuffer[x >> 3] & (0x80 >> (x & 7))) ? 0xFF : 0x00;
|
||||||
|
packPixel(lum);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
return BmpReaderError::UnsupportedBpp;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Flush remaining bits if width is not a multiple of 4
|
||||||
|
if (bitShift != 6) *outPtr = currentOutByte;
|
||||||
|
|
||||||
|
return BmpReaderError::Ok;
|
||||||
|
}
|
||||||
|
|
||||||
|
BmpReaderError Bitmap::rewindToData() const {
|
||||||
|
if (!file.seek(bfOffBits)) {
|
||||||
|
return BmpReaderError::SeekPixelDataFailed;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reset Floyd-Steinberg error buffers when rewinding
|
||||||
|
if (USE_FLOYD_STEINBERG && errorCurRow && errorNextRow) {
|
||||||
|
memset(errorCurRow, 0, (width + 2) * sizeof(int16_t));
|
||||||
|
memset(errorNextRow, 0, (width + 2) * sizeof(int16_t));
|
||||||
|
lastRowY = -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
return BmpReaderError::Ok;
|
||||||
|
}
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <FS.h>
|
||||||
|
|
||||||
|
enum class BmpReaderError : uint8_t {
|
||||||
|
Ok = 0,
|
||||||
|
FileInvalid,
|
||||||
|
SeekStartFailed,
|
||||||
|
|
||||||
|
NotBMP,
|
||||||
|
DIBTooSmall,
|
||||||
|
|
||||||
|
BadPlanes,
|
||||||
|
UnsupportedBpp,
|
||||||
|
UnsupportedCompression,
|
||||||
|
|
||||||
|
BadDimensions,
|
||||||
|
ImageTooLarge,
|
||||||
|
PaletteTooLarge,
|
||||||
|
|
||||||
|
SeekPixelDataFailed,
|
||||||
|
BufferTooSmall,
|
||||||
|
OomRowBuffer,
|
||||||
|
ShortReadRow,
|
||||||
|
};
|
||||||
|
|
||||||
|
class Bitmap {
|
||||||
|
public:
|
||||||
|
static const char* errorToString(BmpReaderError err);
|
||||||
|
|
||||||
|
explicit Bitmap(File& file) : file(file) {}
|
||||||
|
~Bitmap();
|
||||||
|
BmpReaderError parseHeaders();
|
||||||
|
BmpReaderError readRow(uint8_t* data, uint8_t* rowBuffer, int rowY) const;
|
||||||
|
BmpReaderError rewindToData() const;
|
||||||
|
int getWidth() const { return width; }
|
||||||
|
int getHeight() const { return height; }
|
||||||
|
bool isTopDown() const { return topDown; }
|
||||||
|
bool hasGreyscale() const { return bpp > 1; }
|
||||||
|
int getRowBytes() const { return rowBytes; }
|
||||||
|
|
||||||
|
private:
|
||||||
|
static uint16_t readLE16(File& f);
|
||||||
|
static uint32_t readLE32(File& f);
|
||||||
|
|
||||||
|
File& file;
|
||||||
|
int width = 0;
|
||||||
|
int height = 0;
|
||||||
|
bool topDown = false;
|
||||||
|
uint32_t bfOffBits = 0;
|
||||||
|
uint16_t bpp = 0;
|
||||||
|
int rowBytes = 0;
|
||||||
|
uint8_t paletteLum[256] = {};
|
||||||
|
|
||||||
|
// Floyd-Steinberg dithering state (mutable for const methods)
|
||||||
|
mutable int16_t* errorCurRow = nullptr;
|
||||||
|
mutable int16_t* errorNextRow = nullptr;
|
||||||
|
mutable int lastRowY = -1; // Track row progression for error propagation
|
||||||
|
};
|
||||||
@@ -0,0 +1,529 @@
|
|||||||
|
#include "GfxRenderer.h"
|
||||||
|
|
||||||
|
#include <Utf8.h>
|
||||||
|
|
||||||
|
void GfxRenderer::insertFont(const int fontId, EpdFontFamily font) { fontMap.insert({fontId, font}); }
|
||||||
|
|
||||||
|
void GfxRenderer::rotateCoordinates(const int x, const int y, int* rotatedX, int* rotatedY) const {
|
||||||
|
switch (orientation) {
|
||||||
|
case Portrait: {
|
||||||
|
// Logical portrait (480x800) → panel (800x480)
|
||||||
|
// Rotation: 90 degrees clockwise
|
||||||
|
*rotatedX = y;
|
||||||
|
*rotatedY = EInkDisplay::DISPLAY_HEIGHT - 1 - x;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case LandscapeClockwise: {
|
||||||
|
// Logical landscape (800x480) rotated 180 degrees (swap top/bottom and left/right)
|
||||||
|
*rotatedX = EInkDisplay::DISPLAY_WIDTH - 1 - x;
|
||||||
|
*rotatedY = EInkDisplay::DISPLAY_HEIGHT - 1 - y;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case PortraitInverted: {
|
||||||
|
// Logical portrait (480x800) → panel (800x480)
|
||||||
|
// Rotation: 90 degrees counter-clockwise
|
||||||
|
*rotatedX = EInkDisplay::DISPLAY_WIDTH - 1 - y;
|
||||||
|
*rotatedY = x;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case LandscapeCounterClockwise: {
|
||||||
|
// Logical landscape (800x480) aligned with panel orientation
|
||||||
|
*rotatedX = x;
|
||||||
|
*rotatedY = y;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void GfxRenderer::drawPixel(const int x, const int y, const bool state) const {
|
||||||
|
uint8_t* frameBuffer = einkDisplay.getFrameBuffer();
|
||||||
|
|
||||||
|
// Early return if no framebuffer is set
|
||||||
|
if (!frameBuffer) {
|
||||||
|
Serial.printf("[%lu] [GFX] !! No framebuffer\n", millis());
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
int rotatedX = 0;
|
||||||
|
int rotatedY = 0;
|
||||||
|
rotateCoordinates(x, y, &rotatedX, &rotatedY);
|
||||||
|
|
||||||
|
// Bounds checking against physical panel dimensions
|
||||||
|
if (rotatedX < 0 || rotatedX >= EInkDisplay::DISPLAY_WIDTH || rotatedY < 0 ||
|
||||||
|
rotatedY >= EInkDisplay::DISPLAY_HEIGHT) {
|
||||||
|
Serial.printf("[%lu] [GFX] !! Outside range (%d, %d) -> (%d, %d)\n", millis(), x, y, rotatedX, rotatedY);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Calculate byte position and bit position
|
||||||
|
const uint16_t byteIndex = rotatedY * EInkDisplay::DISPLAY_WIDTH_BYTES + (rotatedX / 8);
|
||||||
|
const uint8_t bitPosition = 7 - (rotatedX % 8); // MSB first
|
||||||
|
|
||||||
|
if (state) {
|
||||||
|
frameBuffer[byteIndex] &= ~(1 << bitPosition); // Clear bit
|
||||||
|
} else {
|
||||||
|
frameBuffer[byteIndex] |= 1 << bitPosition; // Set bit
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
int GfxRenderer::getTextWidth(const int fontId, const char* text, const EpdFontStyle style) const {
|
||||||
|
if (fontMap.count(fontId) == 0) {
|
||||||
|
Serial.printf("[%lu] [GFX] Font %d not found\n", millis(), fontId);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
int w = 0, h = 0;
|
||||||
|
fontMap.at(fontId).getTextDimensions(text, &w, &h, style);
|
||||||
|
return w;
|
||||||
|
}
|
||||||
|
|
||||||
|
void GfxRenderer::drawCenteredText(const int fontId, const int y, const char* text, const bool black,
|
||||||
|
const EpdFontStyle style) const {
|
||||||
|
const int x = (getScreenWidth() - getTextWidth(fontId, text, style)) / 2;
|
||||||
|
drawText(fontId, x, y, text, black, style);
|
||||||
|
}
|
||||||
|
|
||||||
|
void GfxRenderer::drawText(const int fontId, const int x, const int y, const char* text, const bool black,
|
||||||
|
const EpdFontStyle style) const {
|
||||||
|
const int yPos = y + getFontAscenderSize(fontId);
|
||||||
|
int xpos = x;
|
||||||
|
|
||||||
|
// cannot draw a NULL / empty string
|
||||||
|
if (text == nullptr || *text == '\0') {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (fontMap.count(fontId) == 0) {
|
||||||
|
Serial.printf("[%lu] [GFX] Font %d not found\n", millis(), fontId);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const auto font = fontMap.at(fontId);
|
||||||
|
|
||||||
|
// no printable characters
|
||||||
|
if (!font.hasPrintableChars(text, style)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
uint32_t cp;
|
||||||
|
while ((cp = utf8NextCodepoint(reinterpret_cast<const uint8_t**>(&text)))) {
|
||||||
|
renderChar(font, cp, &xpos, &yPos, black, style);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void GfxRenderer::drawLine(int x1, int y1, int x2, int y2, const bool state) const {
|
||||||
|
if (x1 == x2) {
|
||||||
|
if (y2 < y1) {
|
||||||
|
std::swap(y1, y2);
|
||||||
|
}
|
||||||
|
for (int y = y1; y <= y2; y++) {
|
||||||
|
drawPixel(x1, y, state);
|
||||||
|
}
|
||||||
|
} else if (y1 == y2) {
|
||||||
|
if (x2 < x1) {
|
||||||
|
std::swap(x1, x2);
|
||||||
|
}
|
||||||
|
for (int x = x1; x <= x2; x++) {
|
||||||
|
drawPixel(x, y1, state);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// TODO: Implement
|
||||||
|
Serial.printf("[%lu] [GFX] Line drawing not supported\n", millis());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void GfxRenderer::drawRect(const int x, const int y, const int width, const int height, const bool state) const {
|
||||||
|
drawLine(x, y, x + width - 1, y, state);
|
||||||
|
drawLine(x + width - 1, y, x + width - 1, y + height - 1, state);
|
||||||
|
drawLine(x + width - 1, y + height - 1, x, y + height - 1, state);
|
||||||
|
drawLine(x, y, x, y + height - 1, state);
|
||||||
|
}
|
||||||
|
|
||||||
|
void GfxRenderer::fillRect(const int x, const int y, const int width, const int height, const bool state) const {
|
||||||
|
for (int fillY = y; fillY < y + height; fillY++) {
|
||||||
|
drawLine(x, fillY, x + width - 1, fillY, state);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void GfxRenderer::drawImage(const uint8_t bitmap[], const int x, const int y, const int width, const int height) const {
|
||||||
|
// TODO: Rotate bits
|
||||||
|
int rotatedX = 0;
|
||||||
|
int rotatedY = 0;
|
||||||
|
rotateCoordinates(x, y, &rotatedX, &rotatedY);
|
||||||
|
einkDisplay.drawImage(bitmap, rotatedX, rotatedY, width, height);
|
||||||
|
}
|
||||||
|
|
||||||
|
void GfxRenderer::drawBitmap(const Bitmap& bitmap, const int x, const int y, const int maxWidth,
|
||||||
|
const int maxHeight) const {
|
||||||
|
float scale = 1.0f;
|
||||||
|
bool isScaled = false;
|
||||||
|
if (maxWidth > 0 && bitmap.getWidth() > maxWidth) {
|
||||||
|
scale = static_cast<float>(maxWidth) / static_cast<float>(bitmap.getWidth());
|
||||||
|
isScaled = true;
|
||||||
|
}
|
||||||
|
if (maxHeight > 0 && bitmap.getHeight() > maxHeight) {
|
||||||
|
scale = std::min(scale, static_cast<float>(maxHeight) / static_cast<float>(bitmap.getHeight()));
|
||||||
|
isScaled = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Calculate output row size (2 bits per pixel, packed into bytes)
|
||||||
|
// IMPORTANT: Use int, not uint8_t, to avoid overflow for images > 1020 pixels wide
|
||||||
|
const int outputRowSize = (bitmap.getWidth() + 3) / 4;
|
||||||
|
auto* outputRow = static_cast<uint8_t*>(malloc(outputRowSize));
|
||||||
|
auto* rowBytes = static_cast<uint8_t*>(malloc(bitmap.getRowBytes()));
|
||||||
|
|
||||||
|
if (!outputRow || !rowBytes) {
|
||||||
|
Serial.printf("[%lu] [GFX] !! Failed to allocate BMP row buffers\n", millis());
|
||||||
|
free(outputRow);
|
||||||
|
free(rowBytes);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (int bmpY = 0; bmpY < bitmap.getHeight(); bmpY++) {
|
||||||
|
// The BMP's (0, 0) is the bottom-left corner (if the height is positive, top-left if negative).
|
||||||
|
// Screen's (0, 0) is the top-left corner.
|
||||||
|
int screenY = y + (bitmap.isTopDown() ? bmpY : bitmap.getHeight() - 1 - bmpY);
|
||||||
|
if (isScaled) {
|
||||||
|
screenY = std::floor(screenY * scale);
|
||||||
|
}
|
||||||
|
if (screenY >= getScreenHeight()) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (bitmap.readRow(outputRow, rowBytes, bmpY) != BmpReaderError::Ok) {
|
||||||
|
Serial.printf("[%lu] [GFX] Failed to read row %d from bitmap\n", millis(), bmpY);
|
||||||
|
free(outputRow);
|
||||||
|
free(rowBytes);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (int bmpX = 0; bmpX < bitmap.getWidth(); bmpX++) {
|
||||||
|
int screenX = x + bmpX;
|
||||||
|
if (isScaled) {
|
||||||
|
screenX = std::floor(screenX * scale);
|
||||||
|
}
|
||||||
|
if (screenX >= getScreenWidth()) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
const uint8_t val = outputRow[bmpX / 4] >> (6 - ((bmpX * 2) % 8)) & 0x3;
|
||||||
|
|
||||||
|
if (renderMode == BW && val < 3) {
|
||||||
|
drawPixel(screenX, screenY);
|
||||||
|
} else if (renderMode == GRAYSCALE_MSB && (val == 1 || val == 2)) {
|
||||||
|
drawPixel(screenX, screenY, false);
|
||||||
|
} else if (renderMode == GRAYSCALE_LSB && val == 1) {
|
||||||
|
drawPixel(screenX, screenY, false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
free(outputRow);
|
||||||
|
free(rowBytes);
|
||||||
|
}
|
||||||
|
|
||||||
|
void GfxRenderer::clearScreen(const uint8_t color) const { einkDisplay.clearScreen(color); }
|
||||||
|
|
||||||
|
void GfxRenderer::invertScreen() const {
|
||||||
|
uint8_t* buffer = einkDisplay.getFrameBuffer();
|
||||||
|
if (!buffer) {
|
||||||
|
Serial.printf("[%lu] [GFX] !! No framebuffer in invertScreen\n", millis());
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
for (int i = 0; i < EInkDisplay::BUFFER_SIZE; i++) {
|
||||||
|
buffer[i] = ~buffer[i];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void GfxRenderer::displayBuffer(const EInkDisplay::RefreshMode refreshMode) const {
|
||||||
|
einkDisplay.displayBuffer(refreshMode);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Note: Internal driver treats screen in command orientation; this library exposes a logical orientation
|
||||||
|
int GfxRenderer::getScreenWidth() const {
|
||||||
|
switch (orientation) {
|
||||||
|
case Portrait:
|
||||||
|
case PortraitInverted:
|
||||||
|
// 480px wide in portrait logical coordinates
|
||||||
|
return EInkDisplay::DISPLAY_HEIGHT;
|
||||||
|
case LandscapeClockwise:
|
||||||
|
case LandscapeCounterClockwise:
|
||||||
|
// 800px wide in landscape logical coordinates
|
||||||
|
return EInkDisplay::DISPLAY_WIDTH;
|
||||||
|
}
|
||||||
|
return EInkDisplay::DISPLAY_HEIGHT;
|
||||||
|
}
|
||||||
|
|
||||||
|
int GfxRenderer::getScreenHeight() const {
|
||||||
|
switch (orientation) {
|
||||||
|
case Portrait:
|
||||||
|
case PortraitInverted:
|
||||||
|
// 800px tall in portrait logical coordinates
|
||||||
|
return EInkDisplay::DISPLAY_WIDTH;
|
||||||
|
case LandscapeClockwise:
|
||||||
|
case LandscapeCounterClockwise:
|
||||||
|
// 480px tall in landscape logical coordinates
|
||||||
|
return EInkDisplay::DISPLAY_HEIGHT;
|
||||||
|
}
|
||||||
|
return EInkDisplay::DISPLAY_WIDTH;
|
||||||
|
}
|
||||||
|
|
||||||
|
int GfxRenderer::getSpaceWidth(const int fontId) const {
|
||||||
|
if (fontMap.count(fontId) == 0) {
|
||||||
|
Serial.printf("[%lu] [GFX] Font %d not found\n", millis(), fontId);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
return fontMap.at(fontId).getGlyph(' ', REGULAR)->advanceX;
|
||||||
|
}
|
||||||
|
|
||||||
|
int GfxRenderer::getFontAscenderSize(const int fontId) const {
|
||||||
|
if (fontMap.count(fontId) == 0) {
|
||||||
|
Serial.printf("[%lu] [GFX] Font %d not found\n", millis(), fontId);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
return fontMap.at(fontId).getData(REGULAR)->ascender;
|
||||||
|
}
|
||||||
|
|
||||||
|
int GfxRenderer::getLineHeight(const int fontId) const {
|
||||||
|
if (fontMap.count(fontId) == 0) {
|
||||||
|
Serial.printf("[%lu] [GFX] Font %d not found\n", millis(), fontId);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
return fontMap.at(fontId).getData(REGULAR)->advanceY;
|
||||||
|
}
|
||||||
|
|
||||||
|
void GfxRenderer::drawButtonHints(const int fontId, const char* btn1, const char* btn2, const char* btn3,
|
||||||
|
const char* btn4) const {
|
||||||
|
const int pageHeight = getScreenHeight();
|
||||||
|
constexpr int buttonWidth = 106;
|
||||||
|
constexpr int buttonHeight = 40;
|
||||||
|
constexpr int buttonY = 40; // Distance from bottom
|
||||||
|
constexpr int textYOffset = 7; // Distance from top of button to text baseline
|
||||||
|
constexpr int buttonPositions[] = {25, 130, 245, 350};
|
||||||
|
const char* labels[] = {btn1, btn2, btn3, btn4};
|
||||||
|
|
||||||
|
for (int i = 0; i < 4; i++) {
|
||||||
|
// Only draw if the label is non-empty
|
||||||
|
if (labels[i] != nullptr && labels[i][0] != '\0') {
|
||||||
|
const int x = buttonPositions[i];
|
||||||
|
drawRect(x, pageHeight - buttonY, buttonWidth, buttonHeight);
|
||||||
|
const int textWidth = getTextWidth(fontId, labels[i]);
|
||||||
|
const int textX = x + (buttonWidth - 1 - textWidth) / 2;
|
||||||
|
drawText(fontId, textX, pageHeight - buttonY + textYOffset, labels[i]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
uint8_t* GfxRenderer::getFrameBuffer() const { return einkDisplay.getFrameBuffer(); }
|
||||||
|
|
||||||
|
size_t GfxRenderer::getBufferSize() { return EInkDisplay::BUFFER_SIZE; }
|
||||||
|
|
||||||
|
void GfxRenderer::grayscaleRevert() const { einkDisplay.grayscaleRevert(); }
|
||||||
|
|
||||||
|
void GfxRenderer::copyGrayscaleLsbBuffers() const { einkDisplay.copyGrayscaleLsbBuffers(einkDisplay.getFrameBuffer()); }
|
||||||
|
|
||||||
|
void GfxRenderer::copyGrayscaleMsbBuffers() const { einkDisplay.copyGrayscaleMsbBuffers(einkDisplay.getFrameBuffer()); }
|
||||||
|
|
||||||
|
void GfxRenderer::displayGrayBuffer() const { einkDisplay.displayGrayBuffer(); }
|
||||||
|
|
||||||
|
void GfxRenderer::freeBwBufferChunks() {
|
||||||
|
for (auto& bwBufferChunk : bwBufferChunks) {
|
||||||
|
if (bwBufferChunk) {
|
||||||
|
free(bwBufferChunk);
|
||||||
|
bwBufferChunk = nullptr;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This should be called before grayscale buffers are populated.
|
||||||
|
* A `restoreBwBuffer` call should always follow the grayscale render if this method was called.
|
||||||
|
* Uses chunked allocation to avoid needing 48KB of contiguous memory.
|
||||||
|
* Returns true if buffer was stored successfully, false if allocation failed.
|
||||||
|
*/
|
||||||
|
bool GfxRenderer::storeBwBuffer() {
|
||||||
|
const uint8_t* frameBuffer = einkDisplay.getFrameBuffer();
|
||||||
|
if (!frameBuffer) {
|
||||||
|
Serial.printf("[%lu] [GFX] !! No framebuffer in storeBwBuffer\n", millis());
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Allocate and copy each chunk
|
||||||
|
for (size_t i = 0; i < BW_BUFFER_NUM_CHUNKS; i++) {
|
||||||
|
// Check if any chunks are already allocated
|
||||||
|
if (bwBufferChunks[i]) {
|
||||||
|
Serial.printf("[%lu] [GFX] !! BW buffer chunk %zu already stored - this is likely a bug, freeing chunk\n",
|
||||||
|
millis(), i);
|
||||||
|
free(bwBufferChunks[i]);
|
||||||
|
bwBufferChunks[i] = nullptr;
|
||||||
|
}
|
||||||
|
|
||||||
|
const size_t offset = i * BW_BUFFER_CHUNK_SIZE;
|
||||||
|
bwBufferChunks[i] = static_cast<uint8_t*>(malloc(BW_BUFFER_CHUNK_SIZE));
|
||||||
|
|
||||||
|
if (!bwBufferChunks[i]) {
|
||||||
|
Serial.printf("[%lu] [GFX] !! Failed to allocate BW buffer chunk %zu (%zu bytes)\n", millis(), i,
|
||||||
|
BW_BUFFER_CHUNK_SIZE);
|
||||||
|
// Free previously allocated chunks
|
||||||
|
freeBwBufferChunks();
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
memcpy(bwBufferChunks[i], frameBuffer + offset, BW_BUFFER_CHUNK_SIZE);
|
||||||
|
}
|
||||||
|
|
||||||
|
Serial.printf("[%lu] [GFX] Stored BW buffer in %zu chunks (%zu bytes each)\n", millis(), BW_BUFFER_NUM_CHUNKS,
|
||||||
|
BW_BUFFER_CHUNK_SIZE);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This can only be called if `storeBwBuffer` was called prior to the grayscale render.
|
||||||
|
* It should be called to restore the BW buffer state after grayscale rendering is complete.
|
||||||
|
* Uses chunked restoration to match chunked storage.
|
||||||
|
*/
|
||||||
|
void GfxRenderer::restoreBwBuffer() {
|
||||||
|
// Check if any all chunks are allocated
|
||||||
|
bool missingChunks = false;
|
||||||
|
for (const auto& bwBufferChunk : bwBufferChunks) {
|
||||||
|
if (!bwBufferChunk) {
|
||||||
|
missingChunks = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (missingChunks) {
|
||||||
|
freeBwBufferChunks();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
uint8_t* frameBuffer = einkDisplay.getFrameBuffer();
|
||||||
|
if (!frameBuffer) {
|
||||||
|
Serial.printf("[%lu] [GFX] !! No framebuffer in restoreBwBuffer\n", millis());
|
||||||
|
freeBwBufferChunks();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (size_t i = 0; i < BW_BUFFER_NUM_CHUNKS; i++) {
|
||||||
|
// Check if chunk is missing
|
||||||
|
if (!bwBufferChunks[i]) {
|
||||||
|
Serial.printf("[%lu] [GFX] !! BW buffer chunks not stored - this is likely a bug\n", millis());
|
||||||
|
freeBwBufferChunks();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const size_t offset = i * BW_BUFFER_CHUNK_SIZE;
|
||||||
|
memcpy(frameBuffer + offset, bwBufferChunks[i], BW_BUFFER_CHUNK_SIZE);
|
||||||
|
}
|
||||||
|
|
||||||
|
einkDisplay.cleanupGrayscaleBuffers(frameBuffer);
|
||||||
|
|
||||||
|
freeBwBufferChunks();
|
||||||
|
Serial.printf("[%lu] [GFX] Restored and freed BW buffer chunks\n", millis());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Cleanup grayscale buffers using the current frame buffer.
|
||||||
|
* Use this when BW buffer was re-rendered instead of stored/restored.
|
||||||
|
*/
|
||||||
|
void GfxRenderer::cleanupGrayscaleWithFrameBuffer() const {
|
||||||
|
uint8_t* frameBuffer = einkDisplay.getFrameBuffer();
|
||||||
|
if (frameBuffer) {
|
||||||
|
einkDisplay.cleanupGrayscaleBuffers(frameBuffer);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void GfxRenderer::renderChar(const EpdFontFamily& fontFamily, const uint32_t cp, int* x, const int* y,
|
||||||
|
const bool pixelState, const EpdFontStyle style) const {
|
||||||
|
const EpdGlyph* glyph = fontFamily.getGlyph(cp, style);
|
||||||
|
if (!glyph) {
|
||||||
|
// TODO: Replace with fallback glyph property?
|
||||||
|
glyph = fontFamily.getGlyph('?', style);
|
||||||
|
}
|
||||||
|
|
||||||
|
// no glyph?
|
||||||
|
if (!glyph) {
|
||||||
|
Serial.printf("[%lu] [GFX] No glyph for codepoint %d\n", millis(), cp);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const int is2Bit = fontFamily.getData(style)->is2Bit;
|
||||||
|
const uint32_t offset = glyph->dataOffset;
|
||||||
|
const uint8_t width = glyph->width;
|
||||||
|
const uint8_t height = glyph->height;
|
||||||
|
const int left = glyph->left;
|
||||||
|
|
||||||
|
const uint8_t* bitmap = nullptr;
|
||||||
|
bitmap = &fontFamily.getData(style)->bitmap[offset];
|
||||||
|
|
||||||
|
if (bitmap != nullptr) {
|
||||||
|
for (int glyphY = 0; glyphY < height; glyphY++) {
|
||||||
|
const int screenY = *y - glyph->top + glyphY;
|
||||||
|
for (int glyphX = 0; glyphX < width; glyphX++) {
|
||||||
|
const int pixelPosition = glyphY * width + glyphX;
|
||||||
|
const int screenX = *x + left + glyphX;
|
||||||
|
|
||||||
|
if (is2Bit) {
|
||||||
|
const uint8_t byte = bitmap[pixelPosition / 4];
|
||||||
|
const uint8_t bit_index = (3 - pixelPosition % 4) * 2;
|
||||||
|
// the direct bit from the font is 0 -> white, 1 -> light gray, 2 -> dark gray, 3 -> black
|
||||||
|
// we swap this to better match the way images and screen think about colors:
|
||||||
|
// 0 -> black, 1 -> dark grey, 2 -> light grey, 3 -> white
|
||||||
|
const uint8_t bmpVal = 3 - (byte >> bit_index) & 0x3;
|
||||||
|
|
||||||
|
if (renderMode == BW && bmpVal < 3) {
|
||||||
|
// Black (also paints over the grays in BW mode)
|
||||||
|
drawPixel(screenX, screenY, pixelState);
|
||||||
|
} else if (renderMode == GRAYSCALE_MSB && (bmpVal == 1 || bmpVal == 2)) {
|
||||||
|
// Light gray (also mark the MSB if it's going to be a dark gray too)
|
||||||
|
// We have to flag pixels in reverse for the gray buffers, as 0 leave alone, 1 update
|
||||||
|
drawPixel(screenX, screenY, false);
|
||||||
|
} else if (renderMode == GRAYSCALE_LSB && bmpVal == 1) {
|
||||||
|
// Dark gray
|
||||||
|
drawPixel(screenX, screenY, false);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
const uint8_t byte = bitmap[pixelPosition / 8];
|
||||||
|
const uint8_t bit_index = 7 - (pixelPosition % 8);
|
||||||
|
|
||||||
|
if ((byte >> bit_index) & 1) {
|
||||||
|
drawPixel(screenX, screenY, pixelState);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
*x += glyph->advanceX;
|
||||||
|
}
|
||||||
|
|
||||||
|
void GfxRenderer::getOrientedViewableTRBL(int* outTop, int* outRight, int* outBottom, int* outLeft) const {
|
||||||
|
switch (orientation) {
|
||||||
|
case Portrait:
|
||||||
|
*outTop = VIEWABLE_MARGIN_TOP;
|
||||||
|
*outRight = VIEWABLE_MARGIN_RIGHT;
|
||||||
|
*outBottom = VIEWABLE_MARGIN_BOTTOM;
|
||||||
|
*outLeft = VIEWABLE_MARGIN_LEFT;
|
||||||
|
break;
|
||||||
|
case LandscapeClockwise:
|
||||||
|
*outTop = VIEWABLE_MARGIN_LEFT;
|
||||||
|
*outRight = VIEWABLE_MARGIN_TOP;
|
||||||
|
*outBottom = VIEWABLE_MARGIN_RIGHT;
|
||||||
|
*outLeft = VIEWABLE_MARGIN_BOTTOM;
|
||||||
|
break;
|
||||||
|
case PortraitInverted:
|
||||||
|
*outTop = VIEWABLE_MARGIN_BOTTOM;
|
||||||
|
*outRight = VIEWABLE_MARGIN_LEFT;
|
||||||
|
*outBottom = VIEWABLE_MARGIN_TOP;
|
||||||
|
*outLeft = VIEWABLE_MARGIN_RIGHT;
|
||||||
|
break;
|
||||||
|
case LandscapeCounterClockwise:
|
||||||
|
*outTop = VIEWABLE_MARGIN_RIGHT;
|
||||||
|
*outRight = VIEWABLE_MARGIN_BOTTOM;
|
||||||
|
*outBottom = VIEWABLE_MARGIN_LEFT;
|
||||||
|
*outLeft = VIEWABLE_MARGIN_TOP;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <EInkDisplay.h>
|
||||||
|
#include <EpdFontFamily.h>
|
||||||
|
#include <FS.h>
|
||||||
|
|
||||||
|
#include <map>
|
||||||
|
|
||||||
|
#include "Bitmap.h"
|
||||||
|
|
||||||
|
class GfxRenderer {
|
||||||
|
public:
|
||||||
|
enum RenderMode { BW, GRAYSCALE_LSB, GRAYSCALE_MSB };
|
||||||
|
|
||||||
|
// Logical screen orientation from the perspective of callers
|
||||||
|
enum Orientation {
|
||||||
|
Portrait, // 480x800 logical coordinates (current default)
|
||||||
|
LandscapeClockwise, // 800x480 logical coordinates, rotated 180° (swap top/bottom)
|
||||||
|
PortraitInverted, // 480x800 logical coordinates, inverted
|
||||||
|
LandscapeCounterClockwise // 800x480 logical coordinates, native panel orientation
|
||||||
|
};
|
||||||
|
|
||||||
|
private:
|
||||||
|
static constexpr size_t BW_BUFFER_CHUNK_SIZE = 8000; // 8KB chunks to allow for non-contiguous memory
|
||||||
|
static constexpr size_t BW_BUFFER_NUM_CHUNKS = EInkDisplay::BUFFER_SIZE / BW_BUFFER_CHUNK_SIZE;
|
||||||
|
static_assert(BW_BUFFER_CHUNK_SIZE * BW_BUFFER_NUM_CHUNKS == EInkDisplay::BUFFER_SIZE,
|
||||||
|
"BW buffer chunking does not line up with display buffer size");
|
||||||
|
|
||||||
|
EInkDisplay& einkDisplay;
|
||||||
|
RenderMode renderMode;
|
||||||
|
Orientation orientation;
|
||||||
|
uint8_t* bwBufferChunks[BW_BUFFER_NUM_CHUNKS] = {nullptr};
|
||||||
|
std::map<int, EpdFontFamily> fontMap;
|
||||||
|
void renderChar(const EpdFontFamily& fontFamily, uint32_t cp, int* x, const int* y, bool pixelState,
|
||||||
|
EpdFontStyle style) const;
|
||||||
|
void freeBwBufferChunks();
|
||||||
|
void rotateCoordinates(int x, int y, int* rotatedX, int* rotatedY) const;
|
||||||
|
|
||||||
|
public:
|
||||||
|
explicit GfxRenderer(EInkDisplay& einkDisplay) : einkDisplay(einkDisplay), renderMode(BW), orientation(Portrait) {}
|
||||||
|
~GfxRenderer() = default;
|
||||||
|
|
||||||
|
static constexpr int VIEWABLE_MARGIN_TOP = 9;
|
||||||
|
static constexpr int VIEWABLE_MARGIN_RIGHT = 3;
|
||||||
|
static constexpr int VIEWABLE_MARGIN_BOTTOM = 3;
|
||||||
|
static constexpr int VIEWABLE_MARGIN_LEFT = 3;
|
||||||
|
|
||||||
|
// Setup
|
||||||
|
void insertFont(int fontId, EpdFontFamily font);
|
||||||
|
|
||||||
|
// Orientation control (affects logical width/height and coordinate transforms)
|
||||||
|
void setOrientation(const Orientation o) { orientation = o; }
|
||||||
|
Orientation getOrientation() const { return orientation; }
|
||||||
|
|
||||||
|
// Screen ops
|
||||||
|
int getScreenWidth() const;
|
||||||
|
int getScreenHeight() const;
|
||||||
|
void displayBuffer(EInkDisplay::RefreshMode refreshMode = EInkDisplay::FAST_REFRESH) const;
|
||||||
|
// EXPERIMENTAL: Windowed update - display only a rectangular region
|
||||||
|
void displayWindow(int x, int y, int width, int height) const;
|
||||||
|
void invertScreen() const;
|
||||||
|
void clearScreen(uint8_t color = 0xFF) const;
|
||||||
|
|
||||||
|
// Drawing
|
||||||
|
void drawPixel(int x, int y, bool state = true) const;
|
||||||
|
void drawLine(int x1, int y1, int x2, int y2, bool state = true) const;
|
||||||
|
void drawRect(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 drawImage(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) const;
|
||||||
|
|
||||||
|
// Text
|
||||||
|
int getTextWidth(int fontId, const char* text, EpdFontStyle style = REGULAR) const;
|
||||||
|
void drawCenteredText(int fontId, int y, const char* text, bool black = true, EpdFontStyle style = REGULAR) const;
|
||||||
|
void drawText(int fontId, int x, int y, const char* text, bool black = true, EpdFontStyle style = REGULAR) const;
|
||||||
|
int getSpaceWidth(int fontId) const;
|
||||||
|
int getFontAscenderSize(int fontId) const;
|
||||||
|
int getLineHeight(int fontId) const;
|
||||||
|
|
||||||
|
// UI Components
|
||||||
|
void drawButtonHints(int fontId, const char* btn1, const char* btn2, const char* btn3, const char* btn4) const;
|
||||||
|
|
||||||
|
// Grayscale functions
|
||||||
|
void setRenderMode(const RenderMode mode) { this->renderMode = mode; }
|
||||||
|
void copyGrayscaleLsbBuffers() const;
|
||||||
|
void copyGrayscaleMsbBuffers() const;
|
||||||
|
void displayGrayBuffer() const;
|
||||||
|
bool storeBwBuffer(); // Returns true if buffer was stored successfully
|
||||||
|
void restoreBwBuffer();
|
||||||
|
void cleanupGrayscaleWithFrameBuffer() const;
|
||||||
|
|
||||||
|
// Low level functions
|
||||||
|
uint8_t* getFrameBuffer() const;
|
||||||
|
static size_t getBufferSize();
|
||||||
|
void grayscaleRevert() const;
|
||||||
|
void getOrientedViewableTRBL(int* outTop, int* outRight, int* outBottom, int* outLeft) const;
|
||||||
|
};
|
||||||
@@ -0,0 +1,736 @@
|
|||||||
|
#include "JpegToBmpConverter.h"
|
||||||
|
|
||||||
|
#include <picojpeg.h>
|
||||||
|
|
||||||
|
#include <cstdio>
|
||||||
|
#include <cstring>
|
||||||
|
|
||||||
|
// Context structure for picojpeg callback
|
||||||
|
struct JpegReadContext {
|
||||||
|
File& file;
|
||||||
|
uint8_t buffer[512];
|
||||||
|
size_t bufferPos;
|
||||||
|
size_t bufferFilled;
|
||||||
|
};
|
||||||
|
|
||||||
|
// ============================================================================
|
||||||
|
// IMAGE PROCESSING OPTIONS - Toggle these to test different configurations
|
||||||
|
// ============================================================================
|
||||||
|
constexpr bool USE_8BIT_OUTPUT = false; // true: 8-bit grayscale (no quantization), false: 2-bit (4 levels)
|
||||||
|
// Dithering method selection (only one should be true, or all false for simple quantization):
|
||||||
|
constexpr bool USE_ATKINSON = true; // Atkinson dithering (cleaner than F-S, less error diffusion)
|
||||||
|
constexpr bool USE_FLOYD_STEINBERG = false; // Floyd-Steinberg error diffusion (can cause "worm" artifacts)
|
||||||
|
constexpr bool USE_NOISE_DITHERING = false; // Hash-based noise dithering (good for downsampling)
|
||||||
|
// Brightness/Contrast adjustments:
|
||||||
|
constexpr bool USE_BRIGHTNESS = true; // true: apply brightness/gamma adjustments
|
||||||
|
constexpr int BRIGHTNESS_BOOST = 10; // Brightness offset (0-50)
|
||||||
|
constexpr bool GAMMA_CORRECTION = true; // Gamma curve (brightens midtones)
|
||||||
|
constexpr float CONTRAST_FACTOR = 1.15f; // Contrast multiplier (1.0 = no change, >1 = more contrast)
|
||||||
|
// Pre-resize to target display size (CRITICAL: avoids dithering artifacts from post-downsampling)
|
||||||
|
constexpr bool USE_PRESCALE = true; // true: scale image to target size before dithering
|
||||||
|
constexpr int TARGET_MAX_WIDTH = 480; // Max width for cover images (portrait display width)
|
||||||
|
constexpr int TARGET_MAX_HEIGHT = 800; // Max height for cover images (portrait display height)
|
||||||
|
// ============================================================================
|
||||||
|
|
||||||
|
// Integer approximation of gamma correction (brightens midtones)
|
||||||
|
// Uses a simple curve: out = 255 * sqrt(in/255) ≈ sqrt(in * 255)
|
||||||
|
static inline int applyGamma(int gray) {
|
||||||
|
if (!GAMMA_CORRECTION) return gray;
|
||||||
|
// Fast integer square root approximation for gamma ~0.5 (brightening)
|
||||||
|
// This brightens dark/mid tones while preserving highlights
|
||||||
|
const int product = gray * 255;
|
||||||
|
// Newton-Raphson integer sqrt (2 iterations for good accuracy)
|
||||||
|
int x = gray;
|
||||||
|
if (x > 0) {
|
||||||
|
x = (x + product / x) >> 1;
|
||||||
|
x = (x + product / x) >> 1;
|
||||||
|
}
|
||||||
|
return x > 255 ? 255 : x;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Apply contrast adjustment around midpoint (128)
|
||||||
|
// factor > 1.0 increases contrast, < 1.0 decreases
|
||||||
|
static inline int applyContrast(int gray) {
|
||||||
|
// Integer-based contrast: (gray - 128) * factor + 128
|
||||||
|
// Using fixed-point: factor 1.15 ≈ 115/100
|
||||||
|
constexpr int factorNum = static_cast<int>(CONTRAST_FACTOR * 100);
|
||||||
|
int adjusted = ((gray - 128) * factorNum) / 100 + 128;
|
||||||
|
if (adjusted < 0) adjusted = 0;
|
||||||
|
if (adjusted > 255) adjusted = 255;
|
||||||
|
return adjusted;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Combined brightness/contrast/gamma adjustment
|
||||||
|
static inline int adjustPixel(int gray) {
|
||||||
|
if (!USE_BRIGHTNESS) return gray;
|
||||||
|
|
||||||
|
// Order: contrast first, then brightness, then gamma
|
||||||
|
gray = applyContrast(gray);
|
||||||
|
gray += BRIGHTNESS_BOOST;
|
||||||
|
if (gray > 255) gray = 255;
|
||||||
|
if (gray < 0) gray = 0;
|
||||||
|
gray = applyGamma(gray);
|
||||||
|
|
||||||
|
return gray;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Simple quantization without dithering - just divide into 4 levels
|
||||||
|
static inline uint8_t quantizeSimple(int gray) {
|
||||||
|
gray = adjustPixel(gray);
|
||||||
|
// Simple 2-bit quantization: 0-63=0, 64-127=1, 128-191=2, 192-255=3
|
||||||
|
return static_cast<uint8_t>(gray >> 6);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Hash-based noise dithering - survives downsampling without moiré artifacts
|
||||||
|
// Uses integer hash to generate pseudo-random threshold per pixel
|
||||||
|
static inline uint8_t quantizeNoise(int gray, int x, int y) {
|
||||||
|
gray = adjustPixel(gray);
|
||||||
|
|
||||||
|
// Generate noise threshold using integer hash (no regular pattern to alias)
|
||||||
|
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); // 0-255
|
||||||
|
|
||||||
|
// Map gray (0-255) to 4 levels with dithering
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Main quantization function - selects between methods based on config
|
||||||
|
static inline uint8_t quantize(int gray, int x, int y) {
|
||||||
|
if (USE_NOISE_DITHERING) {
|
||||||
|
return quantizeNoise(gray, x, y);
|
||||||
|
} else {
|
||||||
|
return quantizeSimple(gray);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Atkinson dithering - distributes only 6/8 (75%) of error for cleaner results
|
||||||
|
// Error distribution pattern:
|
||||||
|
// X 1/8 1/8
|
||||||
|
// 1/8 1/8 1/8
|
||||||
|
// 1/8
|
||||||
|
// Less error buildup = fewer artifacts than Floyd-Steinberg
|
||||||
|
class AtkinsonDitherer {
|
||||||
|
public:
|
||||||
|
AtkinsonDitherer(int width) : width(width) {
|
||||||
|
errorRow0 = new int16_t[width + 4](); // Current row
|
||||||
|
errorRow1 = new int16_t[width + 4](); // Next row
|
||||||
|
errorRow2 = new int16_t[width + 4](); // Row after next
|
||||||
|
}
|
||||||
|
|
||||||
|
~AtkinsonDitherer() {
|
||||||
|
delete[] errorRow0;
|
||||||
|
delete[] errorRow1;
|
||||||
|
delete[] errorRow2;
|
||||||
|
}
|
||||||
|
|
||||||
|
uint8_t processPixel(int gray, int x) {
|
||||||
|
// Apply brightness/contrast/gamma adjustments
|
||||||
|
gray = adjustPixel(gray);
|
||||||
|
|
||||||
|
// Add accumulated error
|
||||||
|
int adjusted = gray + errorRow0[x + 2];
|
||||||
|
if (adjusted < 0) adjusted = 0;
|
||||||
|
if (adjusted > 255) adjusted = 255;
|
||||||
|
|
||||||
|
// Quantize to 4 levels
|
||||||
|
uint8_t quantized;
|
||||||
|
int quantizedValue;
|
||||||
|
if (adjusted < 43) {
|
||||||
|
quantized = 0;
|
||||||
|
quantizedValue = 0;
|
||||||
|
} else if (adjusted < 128) {
|
||||||
|
quantized = 1;
|
||||||
|
quantizedValue = 85;
|
||||||
|
} else if (adjusted < 213) {
|
||||||
|
quantized = 2;
|
||||||
|
quantizedValue = 170;
|
||||||
|
} else {
|
||||||
|
quantized = 3;
|
||||||
|
quantizedValue = 255;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Calculate error (only distribute 6/8 = 75%)
|
||||||
|
int error = (adjusted - quantizedValue) >> 3; // error/8
|
||||||
|
|
||||||
|
// Distribute 1/8 to each of 6 neighbors
|
||||||
|
errorRow0[x + 3] += error; // Right
|
||||||
|
errorRow0[x + 4] += error; // Right+1
|
||||||
|
errorRow1[x + 1] += error; // Bottom-left
|
||||||
|
errorRow1[x + 2] += error; // Bottom
|
||||||
|
errorRow1[x + 3] += error; // Bottom-right
|
||||||
|
errorRow2[x + 2] += error; // Two rows down
|
||||||
|
|
||||||
|
return quantized;
|
||||||
|
}
|
||||||
|
|
||||||
|
void nextRow() {
|
||||||
|
int16_t* temp = errorRow0;
|
||||||
|
errorRow0 = errorRow1;
|
||||||
|
errorRow1 = errorRow2;
|
||||||
|
errorRow2 = temp;
|
||||||
|
memset(errorRow2, 0, (width + 4) * sizeof(int16_t));
|
||||||
|
}
|
||||||
|
|
||||||
|
void reset() {
|
||||||
|
memset(errorRow0, 0, (width + 4) * sizeof(int16_t));
|
||||||
|
memset(errorRow1, 0, (width + 4) * sizeof(int16_t));
|
||||||
|
memset(errorRow2, 0, (width + 4) * sizeof(int16_t));
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
int width;
|
||||||
|
int16_t* errorRow0;
|
||||||
|
int16_t* errorRow1;
|
||||||
|
int16_t* errorRow2;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Floyd-Steinberg error diffusion dithering with serpentine scanning
|
||||||
|
// Serpentine scanning alternates direction each row to reduce "worm" artifacts
|
||||||
|
// Error distribution pattern (left-to-right):
|
||||||
|
// X 7/16
|
||||||
|
// 3/16 5/16 1/16
|
||||||
|
// Error distribution pattern (right-to-left, mirrored):
|
||||||
|
// 1/16 5/16 3/16
|
||||||
|
// 7/16 X
|
||||||
|
class FloydSteinbergDitherer {
|
||||||
|
public:
|
||||||
|
FloydSteinbergDitherer(int width) : width(width), rowCount(0) {
|
||||||
|
errorCurRow = new int16_t[width + 2](); // +2 for boundary handling
|
||||||
|
errorNextRow = new int16_t[width + 2]();
|
||||||
|
}
|
||||||
|
|
||||||
|
~FloydSteinbergDitherer() {
|
||||||
|
delete[] errorCurRow;
|
||||||
|
delete[] errorNextRow;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Process a single pixel and return quantized 2-bit value
|
||||||
|
// x is the logical x position (0 to width-1), direction handled internally
|
||||||
|
uint8_t processPixel(int gray, int x, bool reverseDirection) {
|
||||||
|
// Add accumulated error to this pixel
|
||||||
|
int adjusted = gray + errorCurRow[x + 1];
|
||||||
|
|
||||||
|
// Clamp to valid range
|
||||||
|
if (adjusted < 0) adjusted = 0;
|
||||||
|
if (adjusted > 255) adjusted = 255;
|
||||||
|
|
||||||
|
// Quantize to 4 levels (0, 85, 170, 255)
|
||||||
|
uint8_t quantized;
|
||||||
|
int quantizedValue;
|
||||||
|
if (adjusted < 43) {
|
||||||
|
quantized = 0;
|
||||||
|
quantizedValue = 0;
|
||||||
|
} else if (adjusted < 128) {
|
||||||
|
quantized = 1;
|
||||||
|
quantizedValue = 85;
|
||||||
|
} else if (adjusted < 213) {
|
||||||
|
quantized = 2;
|
||||||
|
quantizedValue = 170;
|
||||||
|
} else {
|
||||||
|
quantized = 3;
|
||||||
|
quantizedValue = 255;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Calculate error
|
||||||
|
int error = adjusted - quantizedValue;
|
||||||
|
|
||||||
|
// Distribute error to neighbors (serpentine: direction-aware)
|
||||||
|
if (!reverseDirection) {
|
||||||
|
// Left to right: standard distribution
|
||||||
|
// Right: 7/16
|
||||||
|
errorCurRow[x + 2] += (error * 7) >> 4;
|
||||||
|
// Bottom-left: 3/16
|
||||||
|
errorNextRow[x] += (error * 3) >> 4;
|
||||||
|
// Bottom: 5/16
|
||||||
|
errorNextRow[x + 1] += (error * 5) >> 4;
|
||||||
|
// Bottom-right: 1/16
|
||||||
|
errorNextRow[x + 2] += (error) >> 4;
|
||||||
|
} else {
|
||||||
|
// Right to left: mirrored distribution
|
||||||
|
// Left: 7/16
|
||||||
|
errorCurRow[x] += (error * 7) >> 4;
|
||||||
|
// Bottom-right: 3/16
|
||||||
|
errorNextRow[x + 2] += (error * 3) >> 4;
|
||||||
|
// Bottom: 5/16
|
||||||
|
errorNextRow[x + 1] += (error * 5) >> 4;
|
||||||
|
// Bottom-left: 1/16
|
||||||
|
errorNextRow[x] += (error) >> 4;
|
||||||
|
}
|
||||||
|
|
||||||
|
return quantized;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Call at the end of each row to swap buffers
|
||||||
|
void nextRow() {
|
||||||
|
// Swap buffers
|
||||||
|
int16_t* temp = errorCurRow;
|
||||||
|
errorCurRow = errorNextRow;
|
||||||
|
errorNextRow = temp;
|
||||||
|
// Clear the next row buffer
|
||||||
|
memset(errorNextRow, 0, (width + 2) * sizeof(int16_t));
|
||||||
|
rowCount++;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if current row should be processed in reverse
|
||||||
|
bool isReverseRow() const { return (rowCount & 1) != 0; }
|
||||||
|
|
||||||
|
// Reset for a new image or MCU block
|
||||||
|
void reset() {
|
||||||
|
memset(errorCurRow, 0, (width + 2) * sizeof(int16_t));
|
||||||
|
memset(errorNextRow, 0, (width + 2) * sizeof(int16_t));
|
||||||
|
rowCount = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
int width;
|
||||||
|
int rowCount;
|
||||||
|
int16_t* errorCurRow;
|
||||||
|
int16_t* errorNextRow;
|
||||||
|
};
|
||||||
|
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Helper function: Write BMP header with 8-bit grayscale (256 levels)
|
||||||
|
void writeBmpHeader8bit(Print& bmpOut, const int width, const int height) {
|
||||||
|
// Calculate row padding (each row must be multiple of 4 bytes)
|
||||||
|
const int bytesPerRow = (width + 3) / 4 * 4; // 8 bits per pixel, padded
|
||||||
|
const int imageSize = bytesPerRow * height;
|
||||||
|
const uint32_t paletteSize = 256 * 4; // 256 colors * 4 bytes (BGRA)
|
||||||
|
const uint32_t fileSize = 14 + 40 + paletteSize + imageSize;
|
||||||
|
|
||||||
|
// BMP File Header (14 bytes)
|
||||||
|
bmpOut.write('B');
|
||||||
|
bmpOut.write('M');
|
||||||
|
write32(bmpOut, fileSize);
|
||||||
|
write32(bmpOut, 0); // Reserved
|
||||||
|
write32(bmpOut, 14 + 40 + paletteSize); // Offset to pixel data
|
||||||
|
|
||||||
|
// DIB Header (BITMAPINFOHEADER - 40 bytes)
|
||||||
|
write32(bmpOut, 40);
|
||||||
|
write32Signed(bmpOut, width);
|
||||||
|
write32Signed(bmpOut, -height); // Negative height = top-down bitmap
|
||||||
|
write16(bmpOut, 1); // Color planes
|
||||||
|
write16(bmpOut, 8); // Bits per pixel (8 bits)
|
||||||
|
write32(bmpOut, 0); // BI_RGB (no compression)
|
||||||
|
write32(bmpOut, imageSize);
|
||||||
|
write32(bmpOut, 2835); // xPixelsPerMeter (72 DPI)
|
||||||
|
write32(bmpOut, 2835); // yPixelsPerMeter (72 DPI)
|
||||||
|
write32(bmpOut, 256); // colorsUsed
|
||||||
|
write32(bmpOut, 256); // colorsImportant
|
||||||
|
|
||||||
|
// Color Palette (256 grayscale entries x 4 bytes = 1024 bytes)
|
||||||
|
for (int i = 0; i < 256; i++) {
|
||||||
|
bmpOut.write(static_cast<uint8_t>(i)); // Blue
|
||||||
|
bmpOut.write(static_cast<uint8_t>(i)); // Green
|
||||||
|
bmpOut.write(static_cast<uint8_t>(i)); // Red
|
||||||
|
bmpOut.write(static_cast<uint8_t>(0)); // Reserved
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Helper function: Write BMP header with 2-bit color depth
|
||||||
|
void JpegToBmpConverter::writeBmpHeader(Print& bmpOut, const int width, const int height) {
|
||||||
|
// Calculate row padding (each row must be multiple of 4 bytes)
|
||||||
|
const int bytesPerRow = (width * 2 + 31) / 32 * 4; // 2 bits per pixel, round up
|
||||||
|
const int imageSize = bytesPerRow * height;
|
||||||
|
const uint32_t fileSize = 70 + imageSize; // 14 (file header) + 40 (DIB header) + 16 (palette) + image
|
||||||
|
|
||||||
|
// BMP File Header (14 bytes)
|
||||||
|
bmpOut.write('B');
|
||||||
|
bmpOut.write('M');
|
||||||
|
write32(bmpOut, fileSize); // File size
|
||||||
|
write32(bmpOut, 0); // Reserved
|
||||||
|
write32(bmpOut, 70); // Offset to pixel data
|
||||||
|
|
||||||
|
// DIB Header (BITMAPINFOHEADER - 40 bytes)
|
||||||
|
write32(bmpOut, 40);
|
||||||
|
write32Signed(bmpOut, width);
|
||||||
|
write32Signed(bmpOut, -height); // Negative height = top-down bitmap
|
||||||
|
write16(bmpOut, 1); // Color planes
|
||||||
|
write16(bmpOut, 2); // Bits per pixel (2 bits)
|
||||||
|
write32(bmpOut, 0); // BI_RGB (no compression)
|
||||||
|
write32(bmpOut, imageSize);
|
||||||
|
write32(bmpOut, 2835); // xPixelsPerMeter (72 DPI)
|
||||||
|
write32(bmpOut, 2835); // yPixelsPerMeter (72 DPI)
|
||||||
|
write32(bmpOut, 4); // colorsUsed
|
||||||
|
write32(bmpOut, 4); // colorsImportant
|
||||||
|
|
||||||
|
// Color Palette (4 colors x 4 bytes = 16 bytes)
|
||||||
|
// Format: Blue, Green, Red, Reserved (BGRA)
|
||||||
|
uint8_t palette[16] = {
|
||||||
|
0x00, 0x00, 0x00, 0x00, // Color 0: Black
|
||||||
|
0x55, 0x55, 0x55, 0x00, // Color 1: Dark gray (85)
|
||||||
|
0xAA, 0xAA, 0xAA, 0x00, // Color 2: Light gray (170)
|
||||||
|
0xFF, 0xFF, 0xFF, 0x00 // Color 3: White
|
||||||
|
};
|
||||||
|
for (const uint8_t i : palette) {
|
||||||
|
bmpOut.write(i);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Callback function for picojpeg to read JPEG data
|
||||||
|
unsigned char JpegToBmpConverter::jpegReadCallback(unsigned char* pBuf, const unsigned char buf_size,
|
||||||
|
unsigned char* pBytes_actually_read, void* pCallback_data) {
|
||||||
|
auto* context = static_cast<JpegReadContext*>(pCallback_data);
|
||||||
|
|
||||||
|
if (!context || !context->file) {
|
||||||
|
return PJPG_STREAM_READ_ERROR;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if we need to refill our context buffer
|
||||||
|
if (context->bufferPos >= context->bufferFilled) {
|
||||||
|
context->bufferFilled = context->file.read(context->buffer, sizeof(context->buffer));
|
||||||
|
context->bufferPos = 0;
|
||||||
|
|
||||||
|
if (context->bufferFilled == 0) {
|
||||||
|
// EOF or error
|
||||||
|
*pBytes_actually_read = 0;
|
||||||
|
return 0; // Success (EOF is normal)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Copy available bytes to picojpeg's buffer
|
||||||
|
const size_t available = context->bufferFilled - context->bufferPos;
|
||||||
|
const size_t toRead = available < buf_size ? available : buf_size;
|
||||||
|
|
||||||
|
memcpy(pBuf, context->buffer + context->bufferPos, toRead);
|
||||||
|
context->bufferPos += toRead;
|
||||||
|
*pBytes_actually_read = static_cast<unsigned char>(toRead);
|
||||||
|
|
||||||
|
return 0; // Success
|
||||||
|
}
|
||||||
|
|
||||||
|
// Core function: Convert JPEG file to 2-bit BMP
|
||||||
|
bool JpegToBmpConverter::jpegFileToBmpStream(File& jpegFile, Print& bmpOut) {
|
||||||
|
Serial.printf("[%lu] [JPG] Converting JPEG to BMP\n", millis());
|
||||||
|
|
||||||
|
// Setup context for picojpeg callback
|
||||||
|
JpegReadContext context = {.file = jpegFile, .bufferPos = 0, .bufferFilled = 0};
|
||||||
|
|
||||||
|
// Initialize picojpeg decoder
|
||||||
|
pjpeg_image_info_t imageInfo;
|
||||||
|
const unsigned char status = pjpeg_decode_init(&imageInfo, jpegReadCallback, &context, 0);
|
||||||
|
if (status != 0) {
|
||||||
|
Serial.printf("[%lu] [JPG] JPEG decode init failed with error code: %d\n", millis(), status);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
Serial.printf("[%lu] [JPG] JPEG dimensions: %dx%d, components: %d, MCUs: %dx%d\n", millis(), imageInfo.m_width,
|
||||||
|
imageInfo.m_height, imageInfo.m_comps, imageInfo.m_MCUSPerRow, imageInfo.m_MCUSPerCol);
|
||||||
|
|
||||||
|
// Safety limits to prevent memory issues on ESP32
|
||||||
|
constexpr int MAX_IMAGE_WIDTH = 2048;
|
||||||
|
constexpr int MAX_IMAGE_HEIGHT = 3072;
|
||||||
|
constexpr int MAX_MCU_ROW_BYTES = 65536;
|
||||||
|
|
||||||
|
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,
|
||||||
|
imageInfo.m_height, MAX_IMAGE_WIDTH, MAX_IMAGE_HEIGHT);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Calculate output dimensions (pre-scale to fit display exactly)
|
||||||
|
int outWidth = imageInfo.m_width;
|
||||||
|
int outHeight = imageInfo.m_height;
|
||||||
|
// Use fixed-point scaling (16.16) for sub-pixel accuracy
|
||||||
|
uint32_t scaleX_fp = 65536; // 1.0 in 16.16 fixed point
|
||||||
|
uint32_t scaleY_fp = 65536;
|
||||||
|
bool needsScaling = false;
|
||||||
|
|
||||||
|
if (USE_PRESCALE && (imageInfo.m_width > TARGET_MAX_WIDTH || imageInfo.m_height > TARGET_MAX_HEIGHT)) {
|
||||||
|
// Calculate scale to fit within target dimensions while maintaining aspect ratio
|
||||||
|
const float scaleToFitWidth = static_cast<float>(TARGET_MAX_WIDTH) / imageInfo.m_width;
|
||||||
|
const float scaleToFitHeight = static_cast<float>(TARGET_MAX_HEIGHT) / imageInfo.m_height;
|
||||||
|
const float scale = (scaleToFitWidth < scaleToFitHeight) ? scaleToFitWidth : scaleToFitHeight;
|
||||||
|
|
||||||
|
outWidth = static_cast<int>(imageInfo.m_width * scale);
|
||||||
|
outHeight = static_cast<int>(imageInfo.m_height * scale);
|
||||||
|
|
||||||
|
// Ensure at least 1 pixel
|
||||||
|
if (outWidth < 1) outWidth = 1;
|
||||||
|
if (outHeight < 1) outHeight = 1;
|
||||||
|
|
||||||
|
// Calculate fixed-point scale factors (source pixels per output pixel)
|
||||||
|
// scaleX_fp = (srcWidth << 16) / outWidth
|
||||||
|
scaleX_fp = (static_cast<uint32_t>(imageInfo.m_width) << 16) / outWidth;
|
||||||
|
scaleY_fp = (static_cast<uint32_t>(imageInfo.m_height) << 16) / outHeight;
|
||||||
|
needsScaling = true;
|
||||||
|
|
||||||
|
Serial.printf("[%lu] [JPG] Pre-scaling %dx%d -> %dx%d (fit to %dx%d)\n", millis(), imageInfo.m_width,
|
||||||
|
imageInfo.m_height, outWidth, outHeight, TARGET_MAX_WIDTH, TARGET_MAX_HEIGHT);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Write BMP header with output dimensions
|
||||||
|
int bytesPerRow;
|
||||||
|
if (USE_8BIT_OUTPUT) {
|
||||||
|
writeBmpHeader8bit(bmpOut, outWidth, outHeight);
|
||||||
|
bytesPerRow = (outWidth + 3) / 4 * 4;
|
||||||
|
} else {
|
||||||
|
writeBmpHeader(bmpOut, outWidth, outHeight);
|
||||||
|
bytesPerRow = (outWidth * 2 + 31) / 32 * 4;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Allocate row buffer
|
||||||
|
auto* rowBuffer = static_cast<uint8_t*>(malloc(bytesPerRow));
|
||||||
|
if (!rowBuffer) {
|
||||||
|
Serial.printf("[%lu] [JPG] Failed to allocate row buffer\n", millis());
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Allocate a buffer for one MCU row worth of grayscale pixels
|
||||||
|
// This is the minimal memory needed for streaming conversion
|
||||||
|
const int mcuPixelHeight = imageInfo.m_MCUHeight;
|
||||||
|
const int mcuRowPixels = imageInfo.m_width * mcuPixelHeight;
|
||||||
|
|
||||||
|
// Validate MCU row buffer size before allocation
|
||||||
|
if (mcuRowPixels > MAX_MCU_ROW_BYTES) {
|
||||||
|
Serial.printf("[%lu] [JPG] MCU row buffer too large (%d bytes), max: %d\n", millis(), mcuRowPixels,
|
||||||
|
MAX_MCU_ROW_BYTES);
|
||||||
|
free(rowBuffer);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
auto* mcuRowBuffer = static_cast<uint8_t*>(malloc(mcuRowPixels));
|
||||||
|
if (!mcuRowBuffer) {
|
||||||
|
Serial.printf("[%lu] [JPG] Failed to allocate MCU row buffer (%d bytes)\n", millis(), mcuRowPixels);
|
||||||
|
free(rowBuffer);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create ditherer if enabled (only for 2-bit output)
|
||||||
|
// Use OUTPUT dimensions for dithering (after prescaling)
|
||||||
|
AtkinsonDitherer* atkinsonDitherer = nullptr;
|
||||||
|
FloydSteinbergDitherer* fsDitherer = nullptr;
|
||||||
|
if (!USE_8BIT_OUTPUT) {
|
||||||
|
if (USE_ATKINSON) {
|
||||||
|
atkinsonDitherer = new AtkinsonDitherer(outWidth);
|
||||||
|
} else if (USE_FLOYD_STEINBERG) {
|
||||||
|
fsDitherer = new FloydSteinbergDitherer(outWidth);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// For scaling: accumulate source rows into scaled output rows
|
||||||
|
// We need to track which source Y maps to which output Y
|
||||||
|
// Using fixed-point: srcY_fp = outY * scaleY_fp (gives source Y in 16.16 format)
|
||||||
|
uint32_t* rowAccum = nullptr; // Accumulator for each output X (32-bit for larger sums)
|
||||||
|
uint16_t* rowCount = nullptr; // Count of source pixels accumulated per output X
|
||||||
|
int currentOutY = 0; // Current output row being accumulated
|
||||||
|
uint32_t nextOutY_srcStart = 0; // Source Y where next output row starts (16.16 fixed point)
|
||||||
|
|
||||||
|
if (needsScaling) {
|
||||||
|
rowAccum = new uint32_t[outWidth]();
|
||||||
|
rowCount = new uint16_t[outWidth]();
|
||||||
|
nextOutY_srcStart = scaleY_fp; // First boundary is at scaleY_fp (source Y for outY=1)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Process MCUs row-by-row and write to BMP as we go (top-down)
|
||||||
|
const int mcuPixelWidth = imageInfo.m_MCUWidth;
|
||||||
|
|
||||||
|
for (int mcuY = 0; mcuY < imageInfo.m_MCUSPerCol; mcuY++) {
|
||||||
|
// Clear the MCU row buffer
|
||||||
|
memset(mcuRowBuffer, 0, mcuRowPixels);
|
||||||
|
|
||||||
|
// Decode one row of MCUs
|
||||||
|
for (int mcuX = 0; mcuX < imageInfo.m_MCUSPerRow; mcuX++) {
|
||||||
|
const unsigned char mcuStatus = pjpeg_decode_mcu();
|
||||||
|
if (mcuStatus != 0) {
|
||||||
|
if (mcuStatus == PJPG_NO_MORE_BLOCKS) {
|
||||||
|
Serial.printf("[%lu] [JPG] Unexpected end of blocks at MCU (%d, %d)\n", millis(), mcuX, mcuY);
|
||||||
|
} else {
|
||||||
|
Serial.printf("[%lu] [JPG] JPEG decode MCU failed at (%d, %d) with error code: %d\n", millis(), mcuX, mcuY,
|
||||||
|
mcuStatus);
|
||||||
|
}
|
||||||
|
free(mcuRowBuffer);
|
||||||
|
free(rowBuffer);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// picojpeg stores MCU data in 8x8 blocks
|
||||||
|
// Block layout: H2V2(16x16)=0,64,128,192 H2V1(16x8)=0,64 H1V2(8x16)=0,128
|
||||||
|
for (int blockY = 0; blockY < mcuPixelHeight; blockY++) {
|
||||||
|
for (int blockX = 0; blockX < mcuPixelWidth; blockX++) {
|
||||||
|
const int pixelX = mcuX * mcuPixelWidth + blockX;
|
||||||
|
if (pixelX >= imageInfo.m_width) continue;
|
||||||
|
|
||||||
|
// Calculate proper block offset for picojpeg buffer
|
||||||
|
const int blockCol = blockX / 8;
|
||||||
|
const int blockRow = blockY / 8;
|
||||||
|
const int localX = blockX % 8;
|
||||||
|
const int localY = blockY % 8;
|
||||||
|
const int blocksPerRow = mcuPixelWidth / 8;
|
||||||
|
const int blockIndex = blockRow * blocksPerRow + blockCol;
|
||||||
|
const int pixelOffset = blockIndex * 64 + localY * 8 + localX;
|
||||||
|
|
||||||
|
uint8_t gray;
|
||||||
|
if (imageInfo.m_comps == 1) {
|
||||||
|
gray = imageInfo.m_pMCUBufR[pixelOffset];
|
||||||
|
} else {
|
||||||
|
const uint8_t r = imageInfo.m_pMCUBufR[pixelOffset];
|
||||||
|
const uint8_t g = imageInfo.m_pMCUBufG[pixelOffset];
|
||||||
|
const uint8_t b = imageInfo.m_pMCUBufB[pixelOffset];
|
||||||
|
gray = (r * 25 + g * 50 + b * 25) / 100;
|
||||||
|
}
|
||||||
|
|
||||||
|
mcuRowBuffer[blockY * imageInfo.m_width + pixelX] = gray;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Process source rows from this MCU row
|
||||||
|
const int startRow = mcuY * mcuPixelHeight;
|
||||||
|
const int endRow = (mcuY + 1) * mcuPixelHeight;
|
||||||
|
|
||||||
|
for (int y = startRow; y < endRow && y < imageInfo.m_height; y++) {
|
||||||
|
const int bufferY = y - startRow;
|
||||||
|
|
||||||
|
if (!needsScaling) {
|
||||||
|
// No scaling - direct output (1:1 mapping)
|
||||||
|
memset(rowBuffer, 0, bytesPerRow);
|
||||||
|
|
||||||
|
if (USE_8BIT_OUTPUT) {
|
||||||
|
for (int x = 0; x < outWidth; x++) {
|
||||||
|
const uint8_t gray = mcuRowBuffer[bufferY * imageInfo.m_width + x];
|
||||||
|
rowBuffer[x] = adjustPixel(gray);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
for (int x = 0; x < outWidth; x++) {
|
||||||
|
const uint8_t gray = mcuRowBuffer[bufferY * imageInfo.m_width + x];
|
||||||
|
uint8_t twoBit;
|
||||||
|
if (atkinsonDitherer) {
|
||||||
|
twoBit = atkinsonDitherer->processPixel(gray, x);
|
||||||
|
} else if (fsDitherer) {
|
||||||
|
twoBit = fsDitherer->processPixel(gray, x, fsDitherer->isReverseRow());
|
||||||
|
} else {
|
||||||
|
twoBit = quantize(gray, x, y);
|
||||||
|
}
|
||||||
|
const int byteIndex = (x * 2) / 8;
|
||||||
|
const int bitOffset = 6 - ((x * 2) % 8);
|
||||||
|
rowBuffer[byteIndex] |= (twoBit << bitOffset);
|
||||||
|
}
|
||||||
|
if (atkinsonDitherer)
|
||||||
|
atkinsonDitherer->nextRow();
|
||||||
|
else if (fsDitherer)
|
||||||
|
fsDitherer->nextRow();
|
||||||
|
}
|
||||||
|
bmpOut.write(rowBuffer, bytesPerRow);
|
||||||
|
} else {
|
||||||
|
// Fixed-point area averaging for exact fit scaling
|
||||||
|
// For each output pixel X, accumulate source pixels that map to it
|
||||||
|
// srcX range for outX: [outX * scaleX_fp >> 16, (outX+1) * scaleX_fp >> 16)
|
||||||
|
const uint8_t* srcRow = mcuRowBuffer + bufferY * imageInfo.m_width;
|
||||||
|
|
||||||
|
for (int outX = 0; outX < outWidth; outX++) {
|
||||||
|
// Calculate source X range for this output pixel
|
||||||
|
const int srcXStart = (static_cast<uint32_t>(outX) * scaleX_fp) >> 16;
|
||||||
|
const int srcXEnd = (static_cast<uint32_t>(outX + 1) * scaleX_fp) >> 16;
|
||||||
|
|
||||||
|
// Accumulate all source pixels in this range
|
||||||
|
int sum = 0;
|
||||||
|
int count = 0;
|
||||||
|
for (int srcX = srcXStart; srcX < srcXEnd && srcX < imageInfo.m_width; srcX++) {
|
||||||
|
sum += srcRow[srcX];
|
||||||
|
count++;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Handle edge case: if no pixels in range, use nearest
|
||||||
|
if (count == 0 && srcXStart < imageInfo.m_width) {
|
||||||
|
sum = srcRow[srcXStart];
|
||||||
|
count = 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
rowAccum[outX] += sum;
|
||||||
|
rowCount[outX] += count;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if we've crossed into the next output row
|
||||||
|
// Current source Y in fixed point: y << 16
|
||||||
|
const uint32_t srcY_fp = static_cast<uint32_t>(y + 1) << 16;
|
||||||
|
|
||||||
|
// Output row when source Y crosses the boundary
|
||||||
|
if (srcY_fp >= nextOutY_srcStart && currentOutY < outHeight) {
|
||||||
|
memset(rowBuffer, 0, bytesPerRow);
|
||||||
|
|
||||||
|
if (USE_8BIT_OUTPUT) {
|
||||||
|
for (int x = 0; x < outWidth; x++) {
|
||||||
|
const uint8_t gray = (rowCount[x] > 0) ? (rowAccum[x] / rowCount[x]) : 0;
|
||||||
|
rowBuffer[x] = adjustPixel(gray);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
for (int x = 0; x < outWidth; x++) {
|
||||||
|
const uint8_t gray = (rowCount[x] > 0) ? (rowAccum[x] / rowCount[x]) : 0;
|
||||||
|
uint8_t twoBit;
|
||||||
|
if (atkinsonDitherer) {
|
||||||
|
twoBit = atkinsonDitherer->processPixel(gray, x);
|
||||||
|
} else if (fsDitherer) {
|
||||||
|
twoBit = fsDitherer->processPixel(gray, x, fsDitherer->isReverseRow());
|
||||||
|
} else {
|
||||||
|
twoBit = quantize(gray, x, currentOutY);
|
||||||
|
}
|
||||||
|
const int byteIndex = (x * 2) / 8;
|
||||||
|
const int bitOffset = 6 - ((x * 2) % 8);
|
||||||
|
rowBuffer[byteIndex] |= (twoBit << bitOffset);
|
||||||
|
}
|
||||||
|
if (atkinsonDitherer)
|
||||||
|
atkinsonDitherer->nextRow();
|
||||||
|
else if (fsDitherer)
|
||||||
|
fsDitherer->nextRow();
|
||||||
|
}
|
||||||
|
|
||||||
|
bmpOut.write(rowBuffer, bytesPerRow);
|
||||||
|
currentOutY++;
|
||||||
|
|
||||||
|
// Reset accumulators for next output row
|
||||||
|
memset(rowAccum, 0, outWidth * sizeof(uint32_t));
|
||||||
|
memset(rowCount, 0, outWidth * sizeof(uint16_t));
|
||||||
|
|
||||||
|
// Update boundary for next output row
|
||||||
|
nextOutY_srcStart = static_cast<uint32_t>(currentOutY + 1) * scaleY_fp;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Clean up
|
||||||
|
if (rowAccum) {
|
||||||
|
delete[] rowAccum;
|
||||||
|
}
|
||||||
|
if (rowCount) {
|
||||||
|
delete[] rowCount;
|
||||||
|
}
|
||||||
|
if (atkinsonDitherer) {
|
||||||
|
delete atkinsonDitherer;
|
||||||
|
}
|
||||||
|
if (fsDitherer) {
|
||||||
|
delete fsDitherer;
|
||||||
|
}
|
||||||
|
free(mcuRowBuffer);
|
||||||
|
free(rowBuffer);
|
||||||
|
|
||||||
|
Serial.printf("[%lu] [JPG] Successfully converted JPEG to BMP\n", millis());
|
||||||
|
return true;
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <FS.h>
|
||||||
|
|
||||||
|
class ZipFile;
|
||||||
|
|
||||||
|
class JpegToBmpConverter {
|
||||||
|
static void writeBmpHeader(Print& bmpOut, int width, int height);
|
||||||
|
// [COMMENTED OUT] static uint8_t grayscaleTo2Bit(uint8_t grayscale, int x, int y);
|
||||||
|
static unsigned char jpegReadCallback(unsigned char* pBuf, unsigned char buf_size,
|
||||||
|
unsigned char* pBytes_actually_read, void* pCallback_data);
|
||||||
|
|
||||||
|
public:
|
||||||
|
static bool jpegFileToBmpStream(File& jpegFile, Print& bmpOut);
|
||||||
|
};
|
||||||
@@ -1,4 +1,6 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
#include <FS.h>
|
||||||
|
|
||||||
#include <iostream>
|
#include <iostream>
|
||||||
|
|
||||||
namespace serialization {
|
namespace serialization {
|
||||||
@@ -7,21 +9,44 @@ static void writePod(std::ostream& os, const T& value) {
|
|||||||
os.write(reinterpret_cast<const char*>(&value), sizeof(T));
|
os.write(reinterpret_cast<const char*>(&value), sizeof(T));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
template <typename T>
|
||||||
|
static void writePod(File& file, const T& value) {
|
||||||
|
file.write(reinterpret_cast<const uint8_t*>(&value), sizeof(T));
|
||||||
|
}
|
||||||
|
|
||||||
template <typename T>
|
template <typename T>
|
||||||
static void readPod(std::istream& is, T& value) {
|
static void readPod(std::istream& is, T& value) {
|
||||||
is.read(reinterpret_cast<char*>(&value), sizeof(T));
|
is.read(reinterpret_cast<char*>(&value), sizeof(T));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
template <typename T>
|
||||||
|
static void readPod(File& file, T& value) {
|
||||||
|
file.read(reinterpret_cast<uint8_t*>(&value), sizeof(T));
|
||||||
|
}
|
||||||
|
|
||||||
static void writeString(std::ostream& os, const std::string& s) {
|
static void writeString(std::ostream& os, const std::string& s) {
|
||||||
const uint32_t len = s.size();
|
const uint32_t len = s.size();
|
||||||
writePod(os, len);
|
writePod(os, len);
|
||||||
os.write(s.data(), len);
|
os.write(s.data(), len);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
static void writeString(File& file, const std::string& s) {
|
||||||
|
const uint32_t len = s.size();
|
||||||
|
writePod(file, len);
|
||||||
|
file.write(reinterpret_cast<const uint8_t*>(s.data()), len);
|
||||||
|
}
|
||||||
|
|
||||||
static void readString(std::istream& is, std::string& s) {
|
static void readString(std::istream& is, std::string& s) {
|
||||||
uint32_t len;
|
uint32_t len;
|
||||||
readPod(is, len);
|
readPod(is, len);
|
||||||
s.resize(len);
|
s.resize(len);
|
||||||
is.read(&s[0], len);
|
is.read(&s[0], len);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
static void readString(File& file, std::string& s) {
|
||||||
|
uint32_t len;
|
||||||
|
readPod(file, len);
|
||||||
|
s.resize(len);
|
||||||
|
file.read(reinterpret_cast<uint8_t*>(&s[0]), len);
|
||||||
|
}
|
||||||
} // namespace serialization
|
} // namespace serialization
|
||||||
|
|||||||
@@ -0,0 +1,40 @@
|
|||||||
|
# XTC/XTCH Library
|
||||||
|
|
||||||
|
XTC ebook format support for CrossPoint Reader.
|
||||||
|
|
||||||
|
## Supported Formats
|
||||||
|
|
||||||
|
| Format | Extension | Description |
|
||||||
|
|--------|-----------|----------------------------------------------|
|
||||||
|
| XTC | `.xtc` | Container with XTG pages (1-bit monochrome) |
|
||||||
|
| XTCH | `.xtch` | Container with XTH pages (2-bit grayscale) |
|
||||||
|
|
||||||
|
## Format Overview
|
||||||
|
|
||||||
|
XTC/XTCH are container formats designed for ESP32 e-paper displays. They store pre-rendered bitmap pages optimized for the XTeink X4 e-reader (480x800 resolution).
|
||||||
|
|
||||||
|
### Container Structure (XTC/XTCH)
|
||||||
|
|
||||||
|
- 56-byte header with metadata offsets
|
||||||
|
- Optional metadata (title, author, etc.)
|
||||||
|
- Page index table (16 bytes per page)
|
||||||
|
- Page data (XTG or XTH format)
|
||||||
|
|
||||||
|
### Page Formats
|
||||||
|
|
||||||
|
#### XTG (1-bit monochrome)
|
||||||
|
|
||||||
|
- Row-major storage, 8 pixels per byte
|
||||||
|
- MSB first (bit 7 = leftmost pixel)
|
||||||
|
- 0 = Black, 1 = White
|
||||||
|
|
||||||
|
#### XTH (2-bit grayscale)
|
||||||
|
|
||||||
|
- Two bit planes stored sequentially
|
||||||
|
- Column-major order (right to left)
|
||||||
|
- 8 vertical pixels per byte
|
||||||
|
- Grayscale: 0=White, 1=Dark Grey, 2=Light Grey, 3=Black
|
||||||
|
|
||||||
|
## Reference
|
||||||
|
|
||||||
|
Original format info: <https://gist.github.com/CrazyCoder/b125f26d6987c0620058249f59f1327d>
|
||||||
@@ -0,0 +1,337 @@
|
|||||||
|
/**
|
||||||
|
* Xtc.cpp
|
||||||
|
*
|
||||||
|
* Main XTC ebook class implementation
|
||||||
|
* XTC ebook support for CrossPoint Reader
|
||||||
|
*/
|
||||||
|
|
||||||
|
#include "Xtc.h"
|
||||||
|
|
||||||
|
#include <FsHelpers.h>
|
||||||
|
#include <HardwareSerial.h>
|
||||||
|
#include <SD.h>
|
||||||
|
|
||||||
|
bool Xtc::load() {
|
||||||
|
Serial.printf("[%lu] [XTC] Loading XTC: %s\n", millis(), filepath.c_str());
|
||||||
|
|
||||||
|
// Initialize parser
|
||||||
|
parser.reset(new xtc::XtcParser());
|
||||||
|
|
||||||
|
// Open XTC file
|
||||||
|
xtc::XtcError err = parser->open(filepath.c_str());
|
||||||
|
if (err != xtc::XtcError::OK) {
|
||||||
|
Serial.printf("[%lu] [XTC] Failed to load: %s\n", millis(), xtc::errorToString(err));
|
||||||
|
parser.reset();
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
loaded = true;
|
||||||
|
Serial.printf("[%lu] [XTC] Loaded XTC: %s (%lu pages)\n", millis(), filepath.c_str(), parser->getPageCount());
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool Xtc::clearCache() const {
|
||||||
|
if (!SD.exists(cachePath.c_str())) {
|
||||||
|
Serial.printf("[%lu] [XTC] Cache does not exist, no action needed\n", millis());
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!FsHelpers::removeDir(cachePath.c_str())) {
|
||||||
|
Serial.printf("[%lu] [XTC] Failed to clear cache\n", millis());
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
Serial.printf("[%lu] [XTC] Cache cleared successfully\n", millis());
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
void Xtc::setupCacheDir() const {
|
||||||
|
if (SD.exists(cachePath.c_str())) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create directories recursively
|
||||||
|
for (size_t i = 1; i < cachePath.length(); i++) {
|
||||||
|
if (cachePath[i] == '/') {
|
||||||
|
SD.mkdir(cachePath.substr(0, i).c_str());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
SD.mkdir(cachePath.c_str());
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string Xtc::getTitle() const {
|
||||||
|
if (!loaded || !parser) {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
|
||||||
|
// Try to get title from XTC metadata first
|
||||||
|
std::string title = parser->getTitle();
|
||||||
|
if (!title.empty()) {
|
||||||
|
return title;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fallback: extract filename from path as title
|
||||||
|
size_t lastSlash = filepath.find_last_of('/');
|
||||||
|
size_t lastDot = filepath.find_last_of('.');
|
||||||
|
|
||||||
|
if (lastSlash == std::string::npos) {
|
||||||
|
lastSlash = 0;
|
||||||
|
} else {
|
||||||
|
lastSlash++;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (lastDot == std::string::npos || lastDot <= lastSlash) {
|
||||||
|
return filepath.substr(lastSlash);
|
||||||
|
}
|
||||||
|
|
||||||
|
return filepath.substr(lastSlash, lastDot - lastSlash);
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string Xtc::getCoverBmpPath() const { return cachePath + "/cover.bmp"; }
|
||||||
|
|
||||||
|
bool Xtc::generateCoverBmp() const {
|
||||||
|
// Already generated
|
||||||
|
if (SD.exists(getCoverBmpPath().c_str())) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!loaded || !parser) {
|
||||||
|
Serial.printf("[%lu] [XTC] Cannot generate cover BMP, file not loaded\n", millis());
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (parser->getPageCount() == 0) {
|
||||||
|
Serial.printf("[%lu] [XTC] No pages in XTC file\n", millis());
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Setup cache directory
|
||||||
|
setupCacheDir();
|
||||||
|
|
||||||
|
// Get first page info for cover
|
||||||
|
xtc::PageInfo pageInfo;
|
||||||
|
if (!parser->getPageInfo(0, pageInfo)) {
|
||||||
|
Serial.printf("[%lu] [XTC] Failed to get first page info\n", millis());
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get bit depth
|
||||||
|
const uint8_t bitDepth = parser->getBitDepth();
|
||||||
|
|
||||||
|
// Allocate buffer for page data
|
||||||
|
// XTG (1-bit): Row-major, ((width+7)/8) * height bytes
|
||||||
|
// XTH (2-bit): Two bit planes, column-major, ((width * height + 7) / 8) * 2 bytes
|
||||||
|
size_t bitmapSize;
|
||||||
|
if (bitDepth == 2) {
|
||||||
|
bitmapSize = ((static_cast<size_t>(pageInfo.width) * pageInfo.height + 7) / 8) * 2;
|
||||||
|
} else {
|
||||||
|
bitmapSize = ((pageInfo.width + 7) / 8) * pageInfo.height;
|
||||||
|
}
|
||||||
|
uint8_t* pageBuffer = static_cast<uint8_t*>(malloc(bitmapSize));
|
||||||
|
if (!pageBuffer) {
|
||||||
|
Serial.printf("[%lu] [XTC] Failed to allocate page buffer (%lu bytes)\n", millis(), bitmapSize);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Load first page (cover)
|
||||||
|
size_t bytesRead = const_cast<xtc::XtcParser*>(parser.get())->loadPage(0, pageBuffer, bitmapSize);
|
||||||
|
if (bytesRead == 0) {
|
||||||
|
Serial.printf("[%lu] [XTC] Failed to load cover page\n", millis());
|
||||||
|
free(pageBuffer);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create BMP file
|
||||||
|
File coverBmp;
|
||||||
|
if (!FsHelpers::openFileForWrite("XTC", getCoverBmpPath(), coverBmp)) {
|
||||||
|
Serial.printf("[%lu] [XTC] Failed to create cover BMP file\n", millis());
|
||||||
|
free(pageBuffer);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Write BMP header
|
||||||
|
// BMP file header (14 bytes)
|
||||||
|
const uint32_t rowSize = ((pageInfo.width + 31) / 32) * 4; // Row size aligned to 4 bytes
|
||||||
|
const uint32_t imageSize = rowSize * pageInfo.height;
|
||||||
|
const uint32_t fileSize = 14 + 40 + 8 + imageSize; // Header + DIB + palette + data
|
||||||
|
|
||||||
|
// File header
|
||||||
|
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);
|
||||||
|
uint32_t dataOffset = 14 + 40 + 8; // 1-bit palette has 2 colors (8 bytes)
|
||||||
|
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 width = pageInfo.width;
|
||||||
|
coverBmp.write(reinterpret_cast<const uint8_t*>(&width), 4);
|
||||||
|
int32_t height = -static_cast<int32_t>(pageInfo.height); // Negative for top-down
|
||||||
|
coverBmp.write(reinterpret_cast<const uint8_t*>(&height), 4);
|
||||||
|
uint16_t planes = 1;
|
||||||
|
coverBmp.write(reinterpret_cast<const uint8_t*>(&planes), 2);
|
||||||
|
uint16_t bitsPerPixel = 1; // 1-bit monochrome
|
||||||
|
coverBmp.write(reinterpret_cast<const uint8_t*>(&bitsPerPixel), 2);
|
||||||
|
uint32_t compression = 0; // BI_RGB (no compression)
|
||||||
|
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)
|
||||||
|
// XTC uses inverted polarity: 0 = black, 1 = white
|
||||||
|
// Color 0: Black (text/foreground in XTC)
|
||||||
|
uint8_t black[4] = {0x00, 0x00, 0x00, 0x00};
|
||||||
|
coverBmp.write(black, 4);
|
||||||
|
// Color 1: White (background in XTC)
|
||||||
|
uint8_t white[4] = {0xFF, 0xFF, 0xFF, 0x00};
|
||||||
|
coverBmp.write(white, 4);
|
||||||
|
|
||||||
|
// Write bitmap data
|
||||||
|
// BMP requires 4-byte row alignment
|
||||||
|
const size_t dstRowSize = (pageInfo.width + 7) / 8; // 1-bit destination row size
|
||||||
|
|
||||||
|
if (bitDepth == 2) {
|
||||||
|
// XTH 2-bit mode: Two bit planes, column-major order
|
||||||
|
// - Columns scanned right to left (x = width-1 down to 0)
|
||||||
|
// - 8 vertical pixels per byte (MSB = topmost pixel in group)
|
||||||
|
// - First plane: Bit1, Second plane: Bit2
|
||||||
|
// - Pixel value = (bit1 << 1) | bit2
|
||||||
|
const size_t planeSize = (static_cast<size_t>(pageInfo.width) * pageInfo.height + 7) / 8;
|
||||||
|
const uint8_t* plane1 = pageBuffer; // Bit1 plane
|
||||||
|
const uint8_t* plane2 = pageBuffer + planeSize; // Bit2 plane
|
||||||
|
const size_t colBytes = (pageInfo.height + 7) / 8; // Bytes per column
|
||||||
|
|
||||||
|
// Allocate a row buffer for 1-bit output
|
||||||
|
uint8_t* rowBuffer = static_cast<uint8_t*>(malloc(dstRowSize));
|
||||||
|
if (!rowBuffer) {
|
||||||
|
free(pageBuffer);
|
||||||
|
coverBmp.close();
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (uint16_t y = 0; y < pageInfo.height; y++) {
|
||||||
|
memset(rowBuffer, 0xFF, dstRowSize); // Start with all white
|
||||||
|
|
||||||
|
for (uint16_t x = 0; x < pageInfo.width; x++) {
|
||||||
|
// Column-major, right to left: column index = (width - 1 - x)
|
||||||
|
const size_t colIndex = pageInfo.width - 1 - x;
|
||||||
|
const size_t byteInCol = y / 8;
|
||||||
|
const size_t bitInByte = 7 - (y % 8); // MSB = topmost pixel
|
||||||
|
|
||||||
|
const size_t byteOffset = colIndex * colBytes + byteInCol;
|
||||||
|
const uint8_t bit1 = (plane1[byteOffset] >> bitInByte) & 1;
|
||||||
|
const uint8_t bit2 = (plane2[byteOffset] >> bitInByte) & 1;
|
||||||
|
const uint8_t pixelValue = (bit1 << 1) | bit2;
|
||||||
|
|
||||||
|
// Threshold: 0=white (1); 1,2,3=black (0)
|
||||||
|
if (pixelValue >= 1) {
|
||||||
|
// Set bit to 0 (black) in BMP format
|
||||||
|
const size_t dstByte = x / 8;
|
||||||
|
const size_t dstBit = 7 - (x % 8);
|
||||||
|
rowBuffer[dstByte] &= ~(1 << dstBit);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Write converted row
|
||||||
|
coverBmp.write(rowBuffer, dstRowSize);
|
||||||
|
|
||||||
|
// Pad to 4-byte boundary
|
||||||
|
uint8_t padding[4] = {0, 0, 0, 0};
|
||||||
|
size_t paddingSize = rowSize - dstRowSize;
|
||||||
|
if (paddingSize > 0) {
|
||||||
|
coverBmp.write(padding, paddingSize);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
free(rowBuffer);
|
||||||
|
} else {
|
||||||
|
// 1-bit source: write directly with proper padding
|
||||||
|
const size_t srcRowSize = (pageInfo.width + 7) / 8;
|
||||||
|
|
||||||
|
for (uint16_t y = 0; y < pageInfo.height; y++) {
|
||||||
|
// Write source row
|
||||||
|
coverBmp.write(pageBuffer + y * srcRowSize, srcRowSize);
|
||||||
|
|
||||||
|
// Pad to 4-byte boundary
|
||||||
|
uint8_t padding[4] = {0, 0, 0, 0};
|
||||||
|
size_t paddingSize = rowSize - srcRowSize;
|
||||||
|
if (paddingSize > 0) {
|
||||||
|
coverBmp.write(padding, paddingSize);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
coverBmp.close();
|
||||||
|
free(pageBuffer);
|
||||||
|
|
||||||
|
Serial.printf("[%lu] [XTC] Generated cover BMP: %s\n", millis(), getCoverBmpPath().c_str());
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
uint32_t Xtc::getPageCount() const {
|
||||||
|
if (!loaded || !parser) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
return parser->getPageCount();
|
||||||
|
}
|
||||||
|
|
||||||
|
uint16_t Xtc::getPageWidth() const {
|
||||||
|
if (!loaded || !parser) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
return parser->getWidth();
|
||||||
|
}
|
||||||
|
|
||||||
|
uint16_t Xtc::getPageHeight() const {
|
||||||
|
if (!loaded || !parser) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
return parser->getHeight();
|
||||||
|
}
|
||||||
|
|
||||||
|
uint8_t Xtc::getBitDepth() const {
|
||||||
|
if (!loaded || !parser) {
|
||||||
|
return 1; // Default to 1-bit
|
||||||
|
}
|
||||||
|
return parser->getBitDepth();
|
||||||
|
}
|
||||||
|
|
||||||
|
size_t Xtc::loadPage(uint32_t pageIndex, uint8_t* buffer, size_t bufferSize) const {
|
||||||
|
if (!loaded || !parser) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
return const_cast<xtc::XtcParser*>(parser.get())->loadPage(pageIndex, buffer, bufferSize);
|
||||||
|
}
|
||||||
|
|
||||||
|
xtc::XtcError Xtc::loadPageStreaming(uint32_t pageIndex,
|
||||||
|
std::function<void(const uint8_t* data, size_t size, size_t offset)> callback,
|
||||||
|
size_t chunkSize) const {
|
||||||
|
if (!loaded || !parser) {
|
||||||
|
return xtc::XtcError::FILE_NOT_FOUND;
|
||||||
|
}
|
||||||
|
return const_cast<xtc::XtcParser*>(parser.get())->loadPageStreaming(pageIndex, callback, chunkSize);
|
||||||
|
}
|
||||||
|
|
||||||
|
uint8_t Xtc::calculateProgress(uint32_t currentPage) const {
|
||||||
|
if (!loaded || !parser || parser->getPageCount() == 0) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
return static_cast<uint8_t>((currentPage + 1) * 100 / parser->getPageCount());
|
||||||
|
}
|
||||||
|
|
||||||
|
xtc::XtcError Xtc::getLastError() const {
|
||||||
|
if (!parser) {
|
||||||
|
return xtc::XtcError::FILE_NOT_FOUND;
|
||||||
|
}
|
||||||
|
return parser->getLastError();
|
||||||
|
}
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
/**
|
||||||
|
* Xtc.h
|
||||||
|
*
|
||||||
|
* Main XTC ebook class for CrossPoint Reader
|
||||||
|
* Provides EPUB-like interface for XTC file handling
|
||||||
|
*/
|
||||||
|
|
||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <memory>
|
||||||
|
#include <string>
|
||||||
|
|
||||||
|
#include "Xtc/XtcParser.h"
|
||||||
|
#include "Xtc/XtcTypes.h"
|
||||||
|
|
||||||
|
/**
|
||||||
|
* XTC Ebook Handler
|
||||||
|
*
|
||||||
|
* Handles XTC file loading, page access, and cover image generation.
|
||||||
|
* Interface is designed to be similar to Epub class for easy integration.
|
||||||
|
*/
|
||||||
|
class Xtc {
|
||||||
|
std::string filepath;
|
||||||
|
std::string cachePath;
|
||||||
|
std::unique_ptr<xtc::XtcParser> parser;
|
||||||
|
bool loaded;
|
||||||
|
|
||||||
|
public:
|
||||||
|
explicit Xtc(std::string filepath, const std::string& cacheDir) : filepath(std::move(filepath)), loaded(false) {
|
||||||
|
// Create cache key based on filepath (same as Epub)
|
||||||
|
cachePath = cacheDir + "/xtc_" + std::to_string(std::hash<std::string>{}(this->filepath));
|
||||||
|
}
|
||||||
|
~Xtc() = default;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Load XTC file
|
||||||
|
* @return true on success
|
||||||
|
*/
|
||||||
|
bool load();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Clear cached data
|
||||||
|
* @return true on success
|
||||||
|
*/
|
||||||
|
bool clearCache() const;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Setup cache directory
|
||||||
|
*/
|
||||||
|
void setupCacheDir() const;
|
||||||
|
|
||||||
|
// Path accessors
|
||||||
|
const std::string& getCachePath() const { return cachePath; }
|
||||||
|
const std::string& getPath() const { return filepath; }
|
||||||
|
|
||||||
|
// Metadata
|
||||||
|
std::string getTitle() const;
|
||||||
|
|
||||||
|
// Cover image support (for sleep screen)
|
||||||
|
std::string getCoverBmpPath() const;
|
||||||
|
bool generateCoverBmp() const;
|
||||||
|
|
||||||
|
// Page access
|
||||||
|
uint32_t getPageCount() const;
|
||||||
|
uint16_t getPageWidth() const;
|
||||||
|
uint16_t getPageHeight() const;
|
||||||
|
uint8_t getBitDepth() const; // 1 = XTC (1-bit), 2 = XTCH (2-bit)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Load page bitmap data
|
||||||
|
* @param pageIndex Page index (0-based)
|
||||||
|
* @param buffer Output buffer
|
||||||
|
* @param bufferSize Buffer size
|
||||||
|
* @return Number of bytes read
|
||||||
|
*/
|
||||||
|
size_t loadPage(uint32_t pageIndex, uint8_t* buffer, size_t bufferSize) const;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Load page with streaming callback
|
||||||
|
* @param pageIndex Page index
|
||||||
|
* @param callback Callback for each chunk
|
||||||
|
* @param chunkSize Chunk size
|
||||||
|
* @return Error code
|
||||||
|
*/
|
||||||
|
xtc::XtcError loadPageStreaming(uint32_t pageIndex,
|
||||||
|
std::function<void(const uint8_t* data, size_t size, size_t offset)> callback,
|
||||||
|
size_t chunkSize = 1024) const;
|
||||||
|
|
||||||
|
// Progress calculation
|
||||||
|
uint8_t calculateProgress(uint32_t currentPage) const;
|
||||||
|
|
||||||
|
// Check if file is loaded
|
||||||
|
bool isLoaded() const { return loaded; }
|
||||||
|
|
||||||
|
// Error information
|
||||||
|
xtc::XtcError getLastError() const;
|
||||||
|
};
|
||||||
@@ -0,0 +1,316 @@
|
|||||||
|
/**
|
||||||
|
* XtcParser.cpp
|
||||||
|
*
|
||||||
|
* XTC file parsing implementation
|
||||||
|
* XTC ebook support for CrossPoint Reader
|
||||||
|
*/
|
||||||
|
|
||||||
|
#include "XtcParser.h"
|
||||||
|
|
||||||
|
#include <FsHelpers.h>
|
||||||
|
#include <HardwareSerial.h>
|
||||||
|
|
||||||
|
#include <cstring>
|
||||||
|
|
||||||
|
namespace xtc {
|
||||||
|
|
||||||
|
XtcParser::XtcParser()
|
||||||
|
: m_isOpen(false),
|
||||||
|
m_defaultWidth(DISPLAY_WIDTH),
|
||||||
|
m_defaultHeight(DISPLAY_HEIGHT),
|
||||||
|
m_bitDepth(1),
|
||||||
|
m_lastError(XtcError::OK) {
|
||||||
|
memset(&m_header, 0, sizeof(m_header));
|
||||||
|
}
|
||||||
|
|
||||||
|
XtcParser::~XtcParser() { close(); }
|
||||||
|
|
||||||
|
XtcError XtcParser::open(const char* filepath) {
|
||||||
|
// Close if already open
|
||||||
|
if (m_isOpen) {
|
||||||
|
close();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Open file
|
||||||
|
if (!FsHelpers::openFileForRead("XTC", filepath, m_file)) {
|
||||||
|
m_lastError = XtcError::FILE_NOT_FOUND;
|
||||||
|
return m_lastError;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Read header
|
||||||
|
m_lastError = readHeader();
|
||||||
|
if (m_lastError != XtcError::OK) {
|
||||||
|
Serial.printf("[%lu] [XTC] Failed to read header: %s\n", millis(), errorToString(m_lastError));
|
||||||
|
m_file.close();
|
||||||
|
return m_lastError;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Read title if available
|
||||||
|
readTitle();
|
||||||
|
|
||||||
|
// Read page table
|
||||||
|
m_lastError = readPageTable();
|
||||||
|
if (m_lastError != XtcError::OK) {
|
||||||
|
Serial.printf("[%lu] [XTC] Failed to read page table: %s\n", millis(), errorToString(m_lastError));
|
||||||
|
m_file.close();
|
||||||
|
return m_lastError;
|
||||||
|
}
|
||||||
|
|
||||||
|
m_isOpen = true;
|
||||||
|
Serial.printf("[%lu] [XTC] Opened file: %s (%u pages, %dx%d)\n", millis(), filepath, m_header.pageCount,
|
||||||
|
m_defaultWidth, m_defaultHeight);
|
||||||
|
return XtcError::OK;
|
||||||
|
}
|
||||||
|
|
||||||
|
void XtcParser::close() {
|
||||||
|
if (m_isOpen) {
|
||||||
|
m_file.close();
|
||||||
|
m_isOpen = false;
|
||||||
|
}
|
||||||
|
m_pageTable.clear();
|
||||||
|
m_title.clear();
|
||||||
|
memset(&m_header, 0, sizeof(m_header));
|
||||||
|
}
|
||||||
|
|
||||||
|
XtcError XtcParser::readHeader() {
|
||||||
|
// Read first 56 bytes of header
|
||||||
|
size_t bytesRead = m_file.read(reinterpret_cast<uint8_t*>(&m_header), sizeof(XtcHeader));
|
||||||
|
if (bytesRead != sizeof(XtcHeader)) {
|
||||||
|
return XtcError::READ_ERROR;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verify magic number (accept both XTC and XTCH)
|
||||||
|
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,
|
||||||
|
XTC_MAGIC, XTCH_MAGIC);
|
||||||
|
return XtcError::INVALID_MAGIC;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Determine bit depth from file magic
|
||||||
|
m_bitDepth = (m_header.magic == XTCH_MAGIC) ? 2 : 1;
|
||||||
|
|
||||||
|
// Check version
|
||||||
|
if (m_header.version > 1) {
|
||||||
|
Serial.printf("[%lu] [XTC] Unsupported version: %d\n", millis(), m_header.version);
|
||||||
|
return XtcError::INVALID_VERSION;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Basic validation
|
||||||
|
if (m_header.pageCount == 0) {
|
||||||
|
return XtcError::CORRUPTED_HEADER;
|
||||||
|
}
|
||||||
|
|
||||||
|
Serial.printf("[%lu] [XTC] Header: magic=0x%08X (%s), ver=%u, pages=%u, bitDepth=%u\n", millis(), m_header.magic,
|
||||||
|
(m_header.magic == XTCH_MAGIC) ? "XTCH" : "XTC", m_header.version, m_header.pageCount, m_bitDepth);
|
||||||
|
|
||||||
|
return XtcError::OK;
|
||||||
|
}
|
||||||
|
|
||||||
|
XtcError XtcParser::readTitle() {
|
||||||
|
// Title is usually at offset 0x38 (56) for 88-byte headers
|
||||||
|
// Read title as null-terminated UTF-8 string
|
||||||
|
if (m_header.titleOffset == 0) {
|
||||||
|
m_header.titleOffset = 0x38; // Default offset
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!m_file.seek(m_header.titleOffset)) {
|
||||||
|
return XtcError::READ_ERROR;
|
||||||
|
}
|
||||||
|
|
||||||
|
char titleBuf[128] = {0};
|
||||||
|
m_file.read(reinterpret_cast<uint8_t*>(titleBuf), sizeof(titleBuf) - 1);
|
||||||
|
m_title = titleBuf;
|
||||||
|
|
||||||
|
Serial.printf("[%lu] [XTC] Title: %s\n", millis(), m_title.c_str());
|
||||||
|
return XtcError::OK;
|
||||||
|
}
|
||||||
|
|
||||||
|
XtcError XtcParser::readPageTable() {
|
||||||
|
if (m_header.pageTableOffset == 0) {
|
||||||
|
Serial.printf("[%lu] [XTC] Page table offset is 0, cannot read\n", millis());
|
||||||
|
return XtcError::CORRUPTED_HEADER;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Seek to page table
|
||||||
|
if (!m_file.seek(m_header.pageTableOffset)) {
|
||||||
|
Serial.printf("[%lu] [XTC] Failed to seek to page table at %llu\n", millis(), m_header.pageTableOffset);
|
||||||
|
return XtcError::READ_ERROR;
|
||||||
|
}
|
||||||
|
|
||||||
|
m_pageTable.resize(m_header.pageCount);
|
||||||
|
|
||||||
|
// Read page table entries
|
||||||
|
for (uint16_t i = 0; i < m_header.pageCount; i++) {
|
||||||
|
PageTableEntry entry;
|
||||||
|
size_t bytesRead = m_file.read(reinterpret_cast<uint8_t*>(&entry), sizeof(PageTableEntry));
|
||||||
|
if (bytesRead != sizeof(PageTableEntry)) {
|
||||||
|
Serial.printf("[%lu] [XTC] Failed to read page table entry %u\n", millis(), i);
|
||||||
|
return XtcError::READ_ERROR;
|
||||||
|
}
|
||||||
|
|
||||||
|
m_pageTable[i].offset = static_cast<uint32_t>(entry.dataOffset);
|
||||||
|
m_pageTable[i].size = entry.dataSize;
|
||||||
|
m_pageTable[i].width = entry.width;
|
||||||
|
m_pageTable[i].height = entry.height;
|
||||||
|
m_pageTable[i].bitDepth = m_bitDepth;
|
||||||
|
|
||||||
|
// Update default dimensions from first page
|
||||||
|
if (i == 0) {
|
||||||
|
m_defaultWidth = entry.width;
|
||||||
|
m_defaultHeight = entry.height;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Serial.printf("[%lu] [XTC] Read %u page table entries\n", millis(), m_header.pageCount);
|
||||||
|
return XtcError::OK;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool XtcParser::getPageInfo(uint32_t pageIndex, PageInfo& info) const {
|
||||||
|
if (pageIndex >= m_pageTable.size()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
info = m_pageTable[pageIndex];
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
size_t XtcParser::loadPage(uint32_t pageIndex, uint8_t* buffer, size_t bufferSize) {
|
||||||
|
if (!m_isOpen) {
|
||||||
|
m_lastError = XtcError::FILE_NOT_FOUND;
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (pageIndex >= m_header.pageCount) {
|
||||||
|
m_lastError = XtcError::PAGE_OUT_OF_RANGE;
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
const PageInfo& page = m_pageTable[pageIndex];
|
||||||
|
|
||||||
|
// Seek to page data
|
||||||
|
if (!m_file.seek(page.offset)) {
|
||||||
|
Serial.printf("[%lu] [XTC] Failed to seek to page %u at offset %lu\n", millis(), pageIndex, page.offset);
|
||||||
|
m_lastError = XtcError::READ_ERROR;
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Read page header (XTG for 1-bit, XTH for 2-bit - same structure)
|
||||||
|
XtgPageHeader pageHeader;
|
||||||
|
size_t headerRead = m_file.read(reinterpret_cast<uint8_t*>(&pageHeader), sizeof(XtgPageHeader));
|
||||||
|
if (headerRead != sizeof(XtgPageHeader)) {
|
||||||
|
Serial.printf("[%lu] [XTC] Failed to read page header for page %u\n", millis(), pageIndex);
|
||||||
|
m_lastError = XtcError::READ_ERROR;
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verify page magic (XTG for 1-bit, XTH for 2-bit)
|
||||||
|
const uint32_t expectedMagic = (m_bitDepth == 2) ? XTH_MAGIC : XTG_MAGIC;
|
||||||
|
if (pageHeader.magic != expectedMagic) {
|
||||||
|
Serial.printf("[%lu] [XTC] Invalid page magic for page %u: 0x%08X (expected 0x%08X)\n", millis(), pageIndex,
|
||||||
|
pageHeader.magic, expectedMagic);
|
||||||
|
m_lastError = XtcError::INVALID_MAGIC;
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Calculate bitmap size based on bit depth
|
||||||
|
// XTG (1-bit): Row-major, ((width+7)/8) * height bytes
|
||||||
|
// XTH (2-bit): Two bit planes, column-major, ((width * height + 7) / 8) * 2 bytes
|
||||||
|
size_t bitmapSize;
|
||||||
|
if (m_bitDepth == 2) {
|
||||||
|
// XTH: two bit planes, each containing (width * height) bits rounded up to bytes
|
||||||
|
bitmapSize = ((static_cast<size_t>(pageHeader.width) * pageHeader.height + 7) / 8) * 2;
|
||||||
|
} else {
|
||||||
|
bitmapSize = ((pageHeader.width + 7) / 8) * pageHeader.height;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check buffer size
|
||||||
|
if (bufferSize < bitmapSize) {
|
||||||
|
Serial.printf("[%lu] [XTC] Buffer too small: need %u, have %u\n", millis(), bitmapSize, bufferSize);
|
||||||
|
m_lastError = XtcError::MEMORY_ERROR;
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Read bitmap data
|
||||||
|
size_t bytesRead = m_file.read(buffer, bitmapSize);
|
||||||
|
if (bytesRead != bitmapSize) {
|
||||||
|
Serial.printf("[%lu] [XTC] Page read error: expected %u, got %u\n", millis(), bitmapSize, bytesRead);
|
||||||
|
m_lastError = XtcError::READ_ERROR;
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
m_lastError = XtcError::OK;
|
||||||
|
return bytesRead;
|
||||||
|
}
|
||||||
|
|
||||||
|
XtcError XtcParser::loadPageStreaming(uint32_t pageIndex,
|
||||||
|
std::function<void(const uint8_t* data, size_t size, size_t offset)> callback,
|
||||||
|
size_t chunkSize) {
|
||||||
|
if (!m_isOpen) {
|
||||||
|
return XtcError::FILE_NOT_FOUND;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (pageIndex >= m_header.pageCount) {
|
||||||
|
return XtcError::PAGE_OUT_OF_RANGE;
|
||||||
|
}
|
||||||
|
|
||||||
|
const PageInfo& page = m_pageTable[pageIndex];
|
||||||
|
|
||||||
|
// Seek to page data
|
||||||
|
if (!m_file.seek(page.offset)) {
|
||||||
|
return XtcError::READ_ERROR;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Read and skip page header (XTG for 1-bit, XTH for 2-bit)
|
||||||
|
XtgPageHeader pageHeader;
|
||||||
|
size_t headerRead = m_file.read(reinterpret_cast<uint8_t*>(&pageHeader), sizeof(XtgPageHeader));
|
||||||
|
const uint32_t expectedMagic = (m_bitDepth == 2) ? XTH_MAGIC : XTG_MAGIC;
|
||||||
|
if (headerRead != sizeof(XtgPageHeader) || pageHeader.magic != expectedMagic) {
|
||||||
|
return XtcError::READ_ERROR;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Calculate bitmap size based on bit depth
|
||||||
|
// XTG (1-bit): Row-major, ((width+7)/8) * height bytes
|
||||||
|
// XTH (2-bit): Two bit planes, ((width * height + 7) / 8) * 2 bytes
|
||||||
|
size_t bitmapSize;
|
||||||
|
if (m_bitDepth == 2) {
|
||||||
|
bitmapSize = ((static_cast<size_t>(pageHeader.width) * pageHeader.height + 7) / 8) * 2;
|
||||||
|
} else {
|
||||||
|
bitmapSize = ((pageHeader.width + 7) / 8) * pageHeader.height;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Read in chunks
|
||||||
|
std::vector<uint8_t> chunk(chunkSize);
|
||||||
|
size_t totalRead = 0;
|
||||||
|
|
||||||
|
while (totalRead < bitmapSize) {
|
||||||
|
size_t toRead = std::min(chunkSize, bitmapSize - totalRead);
|
||||||
|
size_t bytesRead = m_file.read(chunk.data(), toRead);
|
||||||
|
|
||||||
|
if (bytesRead == 0) {
|
||||||
|
return XtcError::READ_ERROR;
|
||||||
|
}
|
||||||
|
|
||||||
|
callback(chunk.data(), bytesRead, totalRead);
|
||||||
|
totalRead += bytesRead;
|
||||||
|
}
|
||||||
|
|
||||||
|
return XtcError::OK;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool XtcParser::isValidXtcFile(const char* filepath) {
|
||||||
|
File file = SD.open(filepath, FILE_READ);
|
||||||
|
if (!file) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
uint32_t magic = 0;
|
||||||
|
size_t bytesRead = file.read(reinterpret_cast<uint8_t*>(&magic), sizeof(magic));
|
||||||
|
file.close();
|
||||||
|
|
||||||
|
if (bytesRead != sizeof(magic)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (magic == XTC_MAGIC || magic == XTCH_MAGIC);
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace xtc
|
||||||
@@ -0,0 +1,96 @@
|
|||||||
|
/**
|
||||||
|
* XtcParser.h
|
||||||
|
*
|
||||||
|
* XTC file parsing and page data extraction
|
||||||
|
* XTC ebook support for CrossPoint Reader
|
||||||
|
*/
|
||||||
|
|
||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <SD.h>
|
||||||
|
|
||||||
|
#include <functional>
|
||||||
|
#include <memory>
|
||||||
|
#include <string>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
#include "XtcTypes.h"
|
||||||
|
|
||||||
|
namespace xtc {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* XTC File Parser
|
||||||
|
*
|
||||||
|
* Reads XTC files from SD card and extracts page data.
|
||||||
|
* Designed for ESP32-C3's limited RAM (~380KB) using streaming.
|
||||||
|
*/
|
||||||
|
class XtcParser {
|
||||||
|
public:
|
||||||
|
XtcParser();
|
||||||
|
~XtcParser();
|
||||||
|
|
||||||
|
// File open/close
|
||||||
|
XtcError open(const char* filepath);
|
||||||
|
void close();
|
||||||
|
bool isOpen() const { return m_isOpen; }
|
||||||
|
|
||||||
|
// Header information access
|
||||||
|
const XtcHeader& getHeader() const { return m_header; }
|
||||||
|
uint16_t getPageCount() const { return m_header.pageCount; }
|
||||||
|
uint16_t getWidth() const { return m_defaultWidth; }
|
||||||
|
uint16_t getHeight() const { return m_defaultHeight; }
|
||||||
|
uint8_t getBitDepth() const { return m_bitDepth; } // 1 = XTC/XTG, 2 = XTCH/XTH
|
||||||
|
|
||||||
|
// Page information
|
||||||
|
bool getPageInfo(uint32_t pageIndex, PageInfo& info) const;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Load page bitmap (raw 1-bit data, skipping XTG header)
|
||||||
|
*
|
||||||
|
* @param pageIndex Page index (0-based)
|
||||||
|
* @param buffer Output buffer (caller allocated)
|
||||||
|
* @param bufferSize Buffer size
|
||||||
|
* @return Number of bytes read on success, 0 on failure
|
||||||
|
*/
|
||||||
|
size_t loadPage(uint32_t pageIndex, uint8_t* buffer, size_t bufferSize);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Streaming page load
|
||||||
|
* Memory-efficient method that reads page data in chunks.
|
||||||
|
*
|
||||||
|
* @param pageIndex Page index
|
||||||
|
* @param callback Callback function to receive data chunks
|
||||||
|
* @param chunkSize Chunk size (default: 1024 bytes)
|
||||||
|
* @return Error code
|
||||||
|
*/
|
||||||
|
XtcError loadPageStreaming(uint32_t pageIndex,
|
||||||
|
std::function<void(const uint8_t* data, size_t size, size_t offset)> callback,
|
||||||
|
size_t chunkSize = 1024);
|
||||||
|
|
||||||
|
// Get title from metadata
|
||||||
|
std::string getTitle() const { return m_title; }
|
||||||
|
|
||||||
|
// Validation
|
||||||
|
static bool isValidXtcFile(const char* filepath);
|
||||||
|
|
||||||
|
// Error information
|
||||||
|
XtcError getLastError() const { return m_lastError; }
|
||||||
|
|
||||||
|
private:
|
||||||
|
File m_file;
|
||||||
|
bool m_isOpen;
|
||||||
|
XtcHeader m_header;
|
||||||
|
std::vector<PageInfo> m_pageTable;
|
||||||
|
std::string m_title;
|
||||||
|
uint16_t m_defaultWidth;
|
||||||
|
uint16_t m_defaultHeight;
|
||||||
|
uint8_t m_bitDepth; // 1 = XTC/XTG (1-bit), 2 = XTCH/XTH (2-bit)
|
||||||
|
XtcError m_lastError;
|
||||||
|
|
||||||
|
// Internal helper functions
|
||||||
|
XtcError readHeader();
|
||||||
|
XtcError readPageTable();
|
||||||
|
XtcError readTitle();
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace xtc
|
||||||
@@ -0,0 +1,147 @@
|
|||||||
|
/**
|
||||||
|
* XtcTypes.h
|
||||||
|
*
|
||||||
|
* XTC file format type definitions
|
||||||
|
* XTC ebook support for CrossPoint Reader
|
||||||
|
*
|
||||||
|
* XTC is the native binary ebook format for XTeink X4 e-reader.
|
||||||
|
* It stores pre-rendered bitmap images per page.
|
||||||
|
*
|
||||||
|
* Format based on EPUB2XTC converter by Rafal-P-Mazur
|
||||||
|
*/
|
||||||
|
|
||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <cstdint>
|
||||||
|
|
||||||
|
namespace xtc {
|
||||||
|
|
||||||
|
// XTC file magic numbers (little-endian)
|
||||||
|
// "XTC\0" = 0x58, 0x54, 0x43, 0x00
|
||||||
|
constexpr uint32_t XTC_MAGIC = 0x00435458; // "XTC\0" in little-endian (1-bit fast mode)
|
||||||
|
// "XTCH" = 0x58, 0x54, 0x43, 0x48
|
||||||
|
constexpr uint32_t XTCH_MAGIC = 0x48435458; // "XTCH" in little-endian (2-bit high quality mode)
|
||||||
|
// "XTG\0" = 0x58, 0x54, 0x47, 0x00
|
||||||
|
constexpr uint32_t XTG_MAGIC = 0x00475458; // "XTG\0" for 1-bit page data
|
||||||
|
// "XTH\0" = 0x58, 0x54, 0x48, 0x00
|
||||||
|
constexpr uint32_t XTH_MAGIC = 0x00485458; // "XTH\0" for 2-bit page data
|
||||||
|
|
||||||
|
// XTeink X4 display resolution
|
||||||
|
constexpr uint16_t DISPLAY_WIDTH = 480;
|
||||||
|
constexpr uint16_t DISPLAY_HEIGHT = 800;
|
||||||
|
|
||||||
|
// XTC file header (56 bytes)
|
||||||
|
#pragma pack(push, 1)
|
||||||
|
struct XtcHeader {
|
||||||
|
uint32_t magic; // 0x00: Magic number "XTC\0" (0x00435458)
|
||||||
|
uint16_t version; // 0x04: Format version (typically 1)
|
||||||
|
uint16_t pageCount; // 0x06: Total page count
|
||||||
|
uint32_t flags; // 0x08: Flags/reserved
|
||||||
|
uint32_t headerSize; // 0x0C: Size of header section (typically 88)
|
||||||
|
uint32_t reserved1; // 0x10: Reserved
|
||||||
|
uint32_t tocOffset; // 0x14: TOC offset (0 if unused) - 4 bytes, not 8!
|
||||||
|
uint64_t pageTableOffset; // 0x18: Page table offset
|
||||||
|
uint64_t dataOffset; // 0x20: First page data offset
|
||||||
|
uint64_t reserved2; // 0x28: Reserved
|
||||||
|
uint32_t titleOffset; // 0x30: Title string offset
|
||||||
|
uint32_t padding; // 0x34: Padding to 56 bytes
|
||||||
|
};
|
||||||
|
#pragma pack(pop)
|
||||||
|
|
||||||
|
// Page table entry (16 bytes per page)
|
||||||
|
#pragma pack(push, 1)
|
||||||
|
struct PageTableEntry {
|
||||||
|
uint64_t dataOffset; // 0x00: Absolute offset to page data
|
||||||
|
uint32_t dataSize; // 0x08: Page data size in bytes
|
||||||
|
uint16_t width; // 0x0C: Page width (480)
|
||||||
|
uint16_t height; // 0x0E: Page height (800)
|
||||||
|
};
|
||||||
|
#pragma pack(pop)
|
||||||
|
|
||||||
|
// XTG/XTH page data header (22 bytes)
|
||||||
|
// Used for both 1-bit (XTG) and 2-bit (XTH) formats
|
||||||
|
#pragma pack(push, 1)
|
||||||
|
struct XtgPageHeader {
|
||||||
|
uint32_t magic; // 0x00: File identifier (XTG: 0x00475458, XTH: 0x00485458)
|
||||||
|
uint16_t width; // 0x04: Image width (pixels)
|
||||||
|
uint16_t height; // 0x06: Image height (pixels)
|
||||||
|
uint8_t colorMode; // 0x08: Color mode (0=monochrome)
|
||||||
|
uint8_t compression; // 0x09: Compression (0=uncompressed)
|
||||||
|
uint32_t dataSize; // 0x0A: Image data size (bytes)
|
||||||
|
uint64_t md5; // 0x0E: MD5 checksum (first 8 bytes, optional)
|
||||||
|
// Followed by bitmap data at offset 0x16 (22)
|
||||||
|
//
|
||||||
|
// XTG (1-bit): Row-major, 8 pixels/byte, MSB first
|
||||||
|
// dataSize = ((width + 7) / 8) * height
|
||||||
|
//
|
||||||
|
// XTH (2-bit): Two bit planes, column-major (right-to-left), 8 vertical pixels/byte
|
||||||
|
// dataSize = ((width * height + 7) / 8) * 2
|
||||||
|
// First plane: Bit1 for all pixels
|
||||||
|
// Second plane: Bit2 for all pixels
|
||||||
|
// pixelValue = (bit1 << 1) | bit2
|
||||||
|
};
|
||||||
|
#pragma pack(pop)
|
||||||
|
|
||||||
|
// Page information (internal use, optimized for memory)
|
||||||
|
struct PageInfo {
|
||||||
|
uint32_t offset; // File offset to page data (max 4GB file size)
|
||||||
|
uint32_t size; // Data size (bytes)
|
||||||
|
uint16_t width; // Page width
|
||||||
|
uint16_t height; // Page height
|
||||||
|
uint8_t bitDepth; // 1 = XTG (1-bit), 2 = XTH (2-bit grayscale)
|
||||||
|
uint8_t padding; // Alignment padding
|
||||||
|
}; // 16 bytes total
|
||||||
|
|
||||||
|
// Error codes
|
||||||
|
enum class XtcError {
|
||||||
|
OK = 0,
|
||||||
|
FILE_NOT_FOUND,
|
||||||
|
INVALID_MAGIC,
|
||||||
|
INVALID_VERSION,
|
||||||
|
CORRUPTED_HEADER,
|
||||||
|
PAGE_OUT_OF_RANGE,
|
||||||
|
READ_ERROR,
|
||||||
|
WRITE_ERROR,
|
||||||
|
MEMORY_ERROR,
|
||||||
|
DECOMPRESSION_ERROR,
|
||||||
|
};
|
||||||
|
|
||||||
|
// Convert error code to string
|
||||||
|
inline const char* errorToString(XtcError err) {
|
||||||
|
switch (err) {
|
||||||
|
case XtcError::OK:
|
||||||
|
return "OK";
|
||||||
|
case XtcError::FILE_NOT_FOUND:
|
||||||
|
return "File not found";
|
||||||
|
case XtcError::INVALID_MAGIC:
|
||||||
|
return "Invalid magic number";
|
||||||
|
case XtcError::INVALID_VERSION:
|
||||||
|
return "Unsupported version";
|
||||||
|
case XtcError::CORRUPTED_HEADER:
|
||||||
|
return "Corrupted header";
|
||||||
|
case XtcError::PAGE_OUT_OF_RANGE:
|
||||||
|
return "Page out of range";
|
||||||
|
case XtcError::READ_ERROR:
|
||||||
|
return "Read error";
|
||||||
|
case XtcError::WRITE_ERROR:
|
||||||
|
return "Write error";
|
||||||
|
case XtcError::MEMORY_ERROR:
|
||||||
|
return "Memory allocation error";
|
||||||
|
case XtcError::DECOMPRESSION_ERROR:
|
||||||
|
return "Decompression error";
|
||||||
|
default:
|
||||||
|
return "Unknown error";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check if filename has XTC/XTCH extension
|
||||||
|
*/
|
||||||
|
inline bool isXtcExtension(const char* filename) {
|
||||||
|
if (!filename) return false;
|
||||||
|
const char* ext = strrchr(filename, '.');
|
||||||
|
if (!ext) return false;
|
||||||
|
return (strcasecmp(ext, ".xtc") == 0 || strcasecmp(ext, ".xtch") == 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace xtc
|
||||||
@@ -7,7 +7,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.println("Failed to allocate memory for inflator");
|
Serial.printf("[%lu] [ZIP] Failed to allocate memory for inflator\n", millis());
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
memset(inflator, 0, sizeof(tinfl_decompressor));
|
memset(inflator, 0, sizeof(tinfl_decompressor));
|
||||||
@@ -20,36 +20,35 @@ 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("tinfl_decompress() failed with status %d\n", status);
|
Serial.printf("[%lu] [ZIP] tinfl_decompress() failed with status %d\n", millis(), status);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
bool ZipFile::loadFileStat(const char* filename, mz_zip_archive_file_stat* fileStat) const {
|
ZipFile::ZipFile(std::string filePath) : filePath(std::move(filePath)) {
|
||||||
mz_zip_archive zipArchive = {};
|
const bool status = mz_zip_reader_init_file(&zipArchive, this->filePath.c_str(), 0);
|
||||||
const bool status = mz_zip_reader_init_file(&zipArchive, filePath.c_str(), 0);
|
|
||||||
|
|
||||||
if (!status) {
|
if (!status) {
|
||||||
Serial.printf("mz_zip_reader_init_file() failed!\nError %s\n", mz_zip_get_error_string(zipArchive.m_last_error));
|
Serial.printf("[%lu] [ZIP] mz_zip_reader_init_file() failed for %s! Error: %s\n", millis(), this->filePath.c_str(),
|
||||||
return false;
|
mz_zip_get_error_string(zipArchive.m_last_error));
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
bool ZipFile::loadFileStat(const char* filename, mz_zip_archive_file_stat* fileStat) const {
|
||||||
// find the file
|
// find the file
|
||||||
mz_uint32 fileIndex = 0;
|
mz_uint32 fileIndex = 0;
|
||||||
if (!mz_zip_reader_locate_file_v2(&zipArchive, filename, nullptr, 0, &fileIndex)) {
|
if (!mz_zip_reader_locate_file_v2(&zipArchive, filename, nullptr, 0, &fileIndex)) {
|
||||||
Serial.printf("Could not find file %s\n", filename);
|
Serial.printf("[%lu] [ZIP] Could not find file %s\n", millis(), filename);
|
||||||
mz_zip_reader_end(&zipArchive);
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!mz_zip_reader_file_stat(&zipArchive, fileIndex, fileStat)) {
|
if (!mz_zip_reader_file_stat(&zipArchive, fileIndex, fileStat)) {
|
||||||
Serial.printf("mz_zip_reader_file_stat() failed!\nError %s\n", mz_zip_get_error_string(zipArchive.m_last_error));
|
Serial.printf("[%lu] [ZIP] mz_zip_reader_file_stat() failed! Error: %s\n", millis(),
|
||||||
mz_zip_reader_end(&zipArchive);
|
mz_zip_get_error_string(zipArchive.m_last_error));
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
mz_zip_reader_end(&zipArchive);
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -60,18 +59,22 @@ long ZipFile::getDataOffset(const mz_zip_archive_file_stat& fileStat) const {
|
|||||||
const uint64_t fileOffset = fileStat.m_local_header_ofs;
|
const uint64_t fileOffset = fileStat.m_local_header_ofs;
|
||||||
|
|
||||||
FILE* file = fopen(filePath.c_str(), "r");
|
FILE* file = fopen(filePath.c_str(), "r");
|
||||||
|
if (!file) {
|
||||||
|
Serial.printf("[%lu] [ZIP] Failed to open file for reading local header\n", millis());
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
fseek(file, fileOffset, SEEK_SET);
|
fseek(file, fileOffset, SEEK_SET);
|
||||||
const size_t read = fread(pLocalHeader, 1, localHeaderSize, file);
|
const size_t read = fread(pLocalHeader, 1, localHeaderSize, file);
|
||||||
fclose(file);
|
fclose(file);
|
||||||
|
|
||||||
if (read != localHeaderSize) {
|
if (read != localHeaderSize) {
|
||||||
Serial.println("Something went wrong reading the local header");
|
Serial.printf("[%lu] [ZIP] Something went wrong reading the local header\n", millis());
|
||||||
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.println("Not a valid zip file header");
|
Serial.printf("[%lu] [ZIP] Not a valid zip file header\n", millis());
|
||||||
return -1;
|
return -1;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -80,6 +83,16 @@ long ZipFile::getDataOffset(const mz_zip_archive_file_stat& fileStat) const {
|
|||||||
return fileOffset + localHeaderSize + filenameLength + extraOffset;
|
return fileOffset + localHeaderSize + filenameLength + extraOffset;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
bool ZipFile::getInflatedFileSize(const char* filename, size_t* size) const {
|
||||||
|
mz_zip_archive_file_stat fileStat;
|
||||||
|
if (!loadFileStat(filename, &fileStat)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
*size = static_cast<size_t>(fileStat.m_uncomp_size);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
uint8_t* ZipFile::readFileToMemory(const char* filename, size_t* size, const bool trailingNullByte) const {
|
uint8_t* ZipFile::readFileToMemory(const char* filename, size_t* size, const bool trailingNullByte) const {
|
||||||
mz_zip_archive_file_stat fileStat;
|
mz_zip_archive_file_stat fileStat;
|
||||||
if (!loadFileStat(filename, &fileStat)) {
|
if (!loadFileStat(filename, &fileStat)) {
|
||||||
@@ -92,12 +105,21 @@ uint8_t* ZipFile::readFileToMemory(const char* filename, size_t* size, const boo
|
|||||||
}
|
}
|
||||||
|
|
||||||
FILE* file = fopen(filePath.c_str(), "rb");
|
FILE* file = fopen(filePath.c_str(), "rb");
|
||||||
|
if (!file) {
|
||||||
|
Serial.printf("[%lu] [ZIP] Failed to open file for reading\n", millis());
|
||||||
|
return nullptr;
|
||||||
|
}
|
||||||
fseek(file, fileOffset, SEEK_SET);
|
fseek(file, fileOffset, SEEK_SET);
|
||||||
|
|
||||||
const auto deflatedDataSize = static_cast<size_t>(fileStat.m_comp_size);
|
const auto deflatedDataSize = static_cast<size_t>(fileStat.m_comp_size);
|
||||||
const auto inflatedDataSize = static_cast<size_t>(fileStat.m_uncomp_size);
|
const auto inflatedDataSize = static_cast<size_t>(fileStat.m_uncomp_size);
|
||||||
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) {
|
||||||
|
Serial.printf("[%lu] [ZIP] Failed to allocate memory for output buffer (%zu bytes)\n", millis(), dataSize);
|
||||||
|
fclose(file);
|
||||||
|
return nullptr;
|
||||||
|
}
|
||||||
|
|
||||||
if (fileStat.m_method == MZ_NO_COMPRESSION) {
|
if (fileStat.m_method == MZ_NO_COMPRESSION) {
|
||||||
// no deflation, just read content
|
// no deflation, just read content
|
||||||
@@ -105,7 +127,7 @@ uint8_t* ZipFile::readFileToMemory(const char* filename, size_t* size, const boo
|
|||||||
fclose(file);
|
fclose(file);
|
||||||
|
|
||||||
if (dataRead != inflatedDataSize) {
|
if (dataRead != inflatedDataSize) {
|
||||||
Serial.println("Failed to read data");
|
Serial.printf("[%lu] [ZIP] Failed to read data\n", millis());
|
||||||
free(data);
|
free(data);
|
||||||
return nullptr;
|
return nullptr;
|
||||||
}
|
}
|
||||||
@@ -115,7 +137,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.println("Failed to allocate memory for decompression buffer");
|
Serial.printf("[%lu] [ZIP] Failed to allocate memory for decompression buffer\n", millis());
|
||||||
fclose(file);
|
fclose(file);
|
||||||
return nullptr;
|
return nullptr;
|
||||||
}
|
}
|
||||||
@@ -124,7 +146,7 @@ uint8_t* ZipFile::readFileToMemory(const char* filename, size_t* size, const boo
|
|||||||
fclose(file);
|
fclose(file);
|
||||||
|
|
||||||
if (dataRead != deflatedDataSize) {
|
if (dataRead != deflatedDataSize) {
|
||||||
Serial.printf("Failed to read data, expected %d got %d\n", deflatedDataSize, dataRead);
|
Serial.printf("[%lu] [ZIP] Failed to read data, expected %d got %d\n", millis(), deflatedDataSize, dataRead);
|
||||||
free(deflatedData);
|
free(deflatedData);
|
||||||
free(data);
|
free(data);
|
||||||
return nullptr;
|
return nullptr;
|
||||||
@@ -134,14 +156,14 @@ uint8_t* ZipFile::readFileToMemory(const char* filename, size_t* size, const boo
|
|||||||
free(deflatedData);
|
free(deflatedData);
|
||||||
|
|
||||||
if (!success) {
|
if (!success) {
|
||||||
Serial.println("Failed to inflate file");
|
Serial.printf("[%lu] [ZIP] Failed to inflate file\n", millis());
|
||||||
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.println("Unsupported compression method");
|
Serial.printf("[%lu] [ZIP] Unsupported compression method\n", millis());
|
||||||
fclose(file);
|
fclose(file);
|
||||||
return nullptr;
|
return nullptr;
|
||||||
}
|
}
|
||||||
@@ -163,6 +185,10 @@ bool ZipFile::readFileToStream(const char* filename, Print& out, const size_t ch
|
|||||||
}
|
}
|
||||||
|
|
||||||
FILE* file = fopen(filePath.c_str(), "rb");
|
FILE* file = fopen(filePath.c_str(), "rb");
|
||||||
|
if (!file) {
|
||||||
|
Serial.printf("[%lu] [ZIP] Failed to open file for streaming\n", millis());
|
||||||
|
return false;
|
||||||
|
}
|
||||||
fseek(file, fileOffset, SEEK_SET);
|
fseek(file, fileOffset, SEEK_SET);
|
||||||
|
|
||||||
const auto deflatedDataSize = static_cast<size_t>(fileStat.m_comp_size);
|
const auto deflatedDataSize = static_cast<size_t>(fileStat.m_comp_size);
|
||||||
@@ -172,7 +198,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.println("Failed to allocate memory for buffer");
|
Serial.printf("[%lu] [ZIP] Failed to allocate memory for buffer\n", millis());
|
||||||
fclose(file);
|
fclose(file);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@@ -181,7 +207,7 @@ bool ZipFile::readFileToStream(const char* filename, Print& out, const size_t ch
|
|||||||
while (remaining > 0) {
|
while (remaining > 0) {
|
||||||
const size_t dataRead = fread(buffer, 1, remaining < chunkSize ? remaining : chunkSize, file);
|
const size_t dataRead = fread(buffer, 1, remaining < chunkSize ? remaining : chunkSize, file);
|
||||||
if (dataRead == 0) {
|
if (dataRead == 0) {
|
||||||
Serial.println("Could not read more bytes");
|
Serial.printf("[%lu] [ZIP] Could not read more bytes\n", millis());
|
||||||
free(buffer);
|
free(buffer);
|
||||||
fclose(file);
|
fclose(file);
|
||||||
return false;
|
return false;
|
||||||
@@ -200,7 +226,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.println("Failed to allocate memory for inflator");
|
Serial.printf("[%lu] [ZIP] Failed to allocate memory for inflator\n", millis());
|
||||||
fclose(file);
|
fclose(file);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@@ -210,7 +236,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.println("Failed to allocate memory for zip file read buffer");
|
Serial.printf("[%lu] [ZIP] Failed to allocate memory for zip file read buffer\n", millis());
|
||||||
free(inflator);
|
free(inflator);
|
||||||
fclose(file);
|
fclose(file);
|
||||||
return false;
|
return false;
|
||||||
@@ -218,7 +244,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.println("Failed to allocate memory for dictionary");
|
Serial.printf("[%lu] [ZIP] Failed to allocate memory for dictionary\n", millis());
|
||||||
free(inflator);
|
free(inflator);
|
||||||
free(fileReadBuffer);
|
free(fileReadBuffer);
|
||||||
fclose(file);
|
fclose(file);
|
||||||
@@ -266,16 +292,20 @@ bool ZipFile::readFileToStream(const char* filename, Print& out, const size_t ch
|
|||||||
// Write output chunk
|
// Write output chunk
|
||||||
if (outBytes > 0) {
|
if (outBytes > 0) {
|
||||||
processedOutputBytes += outBytes;
|
processedOutputBytes += outBytes;
|
||||||
out.write(outputBuffer + outputCursor, outBytes);
|
if (out.write(outputBuffer + outputCursor, outBytes) != outBytes) {
|
||||||
|
Serial.printf("[%lu] [ZIP] Failed to write all output bytes to stream\n", millis());
|
||||||
|
fclose(file);
|
||||||
|
free(outputBuffer);
|
||||||
|
free(fileReadBuffer);
|
||||||
|
free(inflator);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
// Update output position in buffer (with wraparound)
|
// Update output position in buffer (with wraparound)
|
||||||
outputCursor = (outputCursor + outBytes) & (TINFL_LZ_DICT_SIZE - 1);
|
outputCursor = (outputCursor + outBytes) & (TINFL_LZ_DICT_SIZE - 1);
|
||||||
}
|
}
|
||||||
|
|
||||||
Serial.printf("Decompressing - %d/%d deflated into %d/%d inflated\n", deflatedDataSize - fileRemainingBytes,
|
|
||||||
deflatedDataSize, processedOutputBytes, inflatedDataSize);
|
|
||||||
|
|
||||||
if (status < 0) {
|
if (status < 0) {
|
||||||
Serial.printf("tinfl_decompress() failed with status %d\n", status);
|
Serial.printf("[%lu] [ZIP] tinfl_decompress() failed with status %d\n", millis(), status);
|
||||||
fclose(file);
|
fclose(file);
|
||||||
free(outputBuffer);
|
free(outputBuffer);
|
||||||
free(fileReadBuffer);
|
free(fileReadBuffer);
|
||||||
@@ -284,7 +314,8 @@ bool ZipFile::readFileToStream(const char* filename, Print& out, const size_t ch
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (status == TINFL_STATUS_DONE) {
|
if (status == TINFL_STATUS_DONE) {
|
||||||
Serial.println("Decompression finished");
|
Serial.printf("[%lu] [ZIP] Decompressed %d bytes into %d bytes\n", millis(), deflatedDataSize,
|
||||||
|
inflatedDataSize);
|
||||||
fclose(file);
|
fclose(file);
|
||||||
free(inflator);
|
free(inflator);
|
||||||
free(fileReadBuffer);
|
free(fileReadBuffer);
|
||||||
@@ -294,7 +325,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.println("Unexpected EOF");
|
Serial.printf("[%lu] [ZIP] Unexpected EOF\n", millis());
|
||||||
fclose(file);
|
fclose(file);
|
||||||
free(outputBuffer);
|
free(outputBuffer);
|
||||||
free(fileReadBuffer);
|
free(fileReadBuffer);
|
||||||
@@ -302,6 +333,6 @@ bool ZipFile::readFileToStream(const char* filename, Print& out, const size_t ch
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
Serial.println("Unsupported compression method");
|
Serial.printf("[%lu] [ZIP] Unsupported compression method\n", millis());
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,19 +1,20 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
#include <Print.h>
|
#include <Print.h>
|
||||||
|
|
||||||
#include <functional>
|
|
||||||
#include <string>
|
#include <string>
|
||||||
|
|
||||||
#include "miniz.h"
|
#include "miniz.h"
|
||||||
|
|
||||||
class ZipFile {
|
class ZipFile {
|
||||||
std::string filePath;
|
std::string filePath;
|
||||||
|
mutable mz_zip_archive zipArchive = {};
|
||||||
bool loadFileStat(const char* filename, mz_zip_archive_file_stat* fileStat) const;
|
bool loadFileStat(const char* filename, mz_zip_archive_file_stat* fileStat) const;
|
||||||
long getDataOffset(const mz_zip_archive_file_stat& fileStat) const;
|
long getDataOffset(const mz_zip_archive_file_stat& fileStat) const;
|
||||||
|
|
||||||
public:
|
public:
|
||||||
explicit ZipFile(std::string filePath) : filePath(std::move(filePath)) {}
|
explicit ZipFile(std::string filePath);
|
||||||
~ZipFile() = default;
|
~ZipFile() { mz_zip_reader_end(&zipArchive); }
|
||||||
|
bool getInflatedFileSize(const char* filename, size_t* size) const;
|
||||||
uint8_t* readFileToMemory(const char* filename, size_t* size = nullptr, bool trailingNullByte = false) const;
|
uint8_t* readFileToMemory(const char* filename, size_t* size = nullptr, bool trailingNullByte = false) const;
|
||||||
bool readFileToStream(const char* filename, Print& out, size_t chunkSize) const;
|
bool readFileToStream(const char* filename, Print& out, size_t chunkSize) const;
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -0,0 +1,124 @@
|
|||||||
|
//------------------------------------------------------------------------------
|
||||||
|
// picojpeg - Public domain, Rich Geldreich <richgel99@gmail.com>
|
||||||
|
//------------------------------------------------------------------------------
|
||||||
|
#ifndef PICOJPEG_H
|
||||||
|
#define PICOJPEG_H
|
||||||
|
|
||||||
|
#ifdef __cplusplus
|
||||||
|
extern "C" {
|
||||||
|
#endif
|
||||||
|
|
||||||
|
// Error codes
|
||||||
|
enum {
|
||||||
|
PJPG_NO_MORE_BLOCKS = 1,
|
||||||
|
PJPG_BAD_DHT_COUNTS,
|
||||||
|
PJPG_BAD_DHT_INDEX,
|
||||||
|
PJPG_BAD_DHT_MARKER,
|
||||||
|
PJPG_BAD_DQT_MARKER,
|
||||||
|
PJPG_BAD_DQT_TABLE,
|
||||||
|
PJPG_BAD_PRECISION,
|
||||||
|
PJPG_BAD_HEIGHT,
|
||||||
|
PJPG_BAD_WIDTH,
|
||||||
|
PJPG_TOO_MANY_COMPONENTS,
|
||||||
|
PJPG_BAD_SOF_LENGTH,
|
||||||
|
PJPG_BAD_VARIABLE_MARKER,
|
||||||
|
PJPG_BAD_DRI_LENGTH,
|
||||||
|
PJPG_BAD_SOS_LENGTH,
|
||||||
|
PJPG_BAD_SOS_COMP_ID,
|
||||||
|
PJPG_W_EXTRA_BYTES_BEFORE_MARKER,
|
||||||
|
PJPG_NO_ARITHMITIC_SUPPORT,
|
||||||
|
PJPG_UNEXPECTED_MARKER,
|
||||||
|
PJPG_NOT_JPEG,
|
||||||
|
PJPG_UNSUPPORTED_MARKER,
|
||||||
|
PJPG_BAD_DQT_LENGTH,
|
||||||
|
PJPG_TOO_MANY_BLOCKS,
|
||||||
|
PJPG_UNDEFINED_QUANT_TABLE,
|
||||||
|
PJPG_UNDEFINED_HUFF_TABLE,
|
||||||
|
PJPG_NOT_SINGLE_SCAN,
|
||||||
|
PJPG_UNSUPPORTED_COLORSPACE,
|
||||||
|
PJPG_UNSUPPORTED_SAMP_FACTORS,
|
||||||
|
PJPG_DECODE_ERROR,
|
||||||
|
PJPG_BAD_RESTART_MARKER,
|
||||||
|
PJPG_ASSERTION_ERROR,
|
||||||
|
PJPG_BAD_SOS_SPECTRAL,
|
||||||
|
PJPG_BAD_SOS_SUCCESSIVE,
|
||||||
|
PJPG_STREAM_READ_ERROR,
|
||||||
|
PJPG_NOTENOUGHMEM,
|
||||||
|
PJPG_UNSUPPORTED_COMP_IDENT,
|
||||||
|
PJPG_UNSUPPORTED_QUANT_TABLE,
|
||||||
|
PJPG_UNSUPPORTED_MODE, // picojpeg doesn't support progressive JPEG's
|
||||||
|
};
|
||||||
|
|
||||||
|
// Scan types
|
||||||
|
typedef enum { PJPG_GRAYSCALE, PJPG_YH1V1, PJPG_YH2V1, PJPG_YH1V2, PJPG_YH2V2 } pjpeg_scan_type_t;
|
||||||
|
|
||||||
|
typedef struct {
|
||||||
|
// Image resolution
|
||||||
|
int m_width;
|
||||||
|
int m_height;
|
||||||
|
|
||||||
|
// Number of components (1 or 3)
|
||||||
|
int m_comps;
|
||||||
|
|
||||||
|
// Total number of minimum coded units (MCU's) per row/col.
|
||||||
|
int m_MCUSPerRow;
|
||||||
|
int m_MCUSPerCol;
|
||||||
|
|
||||||
|
// Scan type
|
||||||
|
pjpeg_scan_type_t m_scanType;
|
||||||
|
|
||||||
|
// MCU width/height in pixels (each is either 8 or 16 depending on the scan type)
|
||||||
|
int m_MCUWidth;
|
||||||
|
int m_MCUHeight;
|
||||||
|
|
||||||
|
// m_pMCUBufR, m_pMCUBufG, and m_pMCUBufB are pointers to internal MCU Y or RGB pixel component buffers.
|
||||||
|
// Each time pjpegDecodeMCU() is called successfully these buffers will be filled with 8x8 pixel blocks of Y or RGB
|
||||||
|
// pixels. Each MCU consists of (m_MCUWidth/8)*(m_MCUHeight/8) Y/RGB blocks: 1 for greyscale/no subsampling, 2 for
|
||||||
|
// H1V2/H2V1, or 4 blocks for H2V2 sampling factors. Each block is a contiguous array of 64 (8x8) bytes of a single
|
||||||
|
// component: either Y for grayscale images, or R, G or B components for color images.
|
||||||
|
//
|
||||||
|
// The 8x8 pixel blocks are organized in these byte arrays like this:
|
||||||
|
//
|
||||||
|
// PJPG_GRAYSCALE: Each MCU is decoded to a single block of 8x8 grayscale pixels.
|
||||||
|
// Only the values in m_pMCUBufR are valid. Each 8 bytes is a row of pixels (raster order: left to right, top to
|
||||||
|
// bottom) from the 8x8 block.
|
||||||
|
//
|
||||||
|
// PJPG_H1V1: Each MCU contains is decoded to a single block of 8x8 RGB pixels.
|
||||||
|
//
|
||||||
|
// PJPG_YH2V1: Each MCU is decoded to 2 blocks, or 16x8 pixels.
|
||||||
|
// The 2 RGB blocks are at byte offsets: 0, 64
|
||||||
|
//
|
||||||
|
// PJPG_YH1V2: Each MCU is decoded to 2 blocks, or 8x16 pixels.
|
||||||
|
// The 2 RGB blocks are at byte offsets: 0,
|
||||||
|
// 128
|
||||||
|
//
|
||||||
|
// PJPG_YH2V2: Each MCU is decoded to 4 blocks, or 16x16 pixels.
|
||||||
|
// The 2x2 block array is organized at byte offsets: 0, 64,
|
||||||
|
// 128, 192
|
||||||
|
//
|
||||||
|
// It is up to the caller to copy or blit these pixels from these buffers into the destination bitmap.
|
||||||
|
unsigned char* m_pMCUBufR;
|
||||||
|
unsigned char* m_pMCUBufG;
|
||||||
|
unsigned char* m_pMCUBufB;
|
||||||
|
} pjpeg_image_info_t;
|
||||||
|
|
||||||
|
typedef unsigned char (*pjpeg_need_bytes_callback_t)(unsigned char* pBuf, unsigned char buf_size,
|
||||||
|
unsigned char* pBytes_actually_read, void* pCallback_data);
|
||||||
|
|
||||||
|
// Initializes the decompressor. Returns 0 on success, or one of the above error codes on failure.
|
||||||
|
// pNeed_bytes_callback will be called to fill the decompressor's internal input buffer.
|
||||||
|
// If reduce is 1, only the first pixel of each block will be decoded. This mode is much faster because it skips the AC
|
||||||
|
// dequantization, IDCT and chroma upsampling of every image pixel. Not thread safe.
|
||||||
|
unsigned char pjpeg_decode_init(pjpeg_image_info_t* pInfo, pjpeg_need_bytes_callback_t pNeed_bytes_callback,
|
||||||
|
void* pCallback_data, unsigned char reduce);
|
||||||
|
|
||||||
|
// Decompresses the file's next MCU. Returns 0 on success, PJPG_NO_MORE_BLOCKS if no more blocks are available, or an
|
||||||
|
// error code. Must be called a total of m_MCUSPerRow*m_MCUSPerCol times to completely decompress the image. Not thread
|
||||||
|
// safe.
|
||||||
|
unsigned char pjpeg_decode_mcu(void);
|
||||||
|
|
||||||
|
#ifdef __cplusplus
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#endif // PICOJPEG_H
|
||||||
@@ -1,40 +1,55 @@
|
|||||||
; PlatformIO Project Configuration File
|
[platformio]
|
||||||
;
|
crosspoint_version = 0.10.0
|
||||||
; Build options: build flags, source filter
|
default_envs = default
|
||||||
; Upload options: custom upload port, speed and extra flags
|
|
||||||
; Library options: dependencies, extra library storages
|
|
||||||
; Advanced options: extra scripting
|
|
||||||
;
|
|
||||||
; Please visit documentation for the other options and examples
|
|
||||||
; https://docs.platformio.org/page/projectconf.html
|
|
||||||
|
|
||||||
[env:esp32-c3-devkitm-1]
|
[base]
|
||||||
platform = espressif32
|
platform = espressif32 @ 6.12.0
|
||||||
board = esp32-c3-devkitm-1
|
board = esp32-c3-devkitm-1
|
||||||
framework = arduino
|
framework = arduino
|
||||||
monitor_speed = 115200
|
monitor_speed = 115200
|
||||||
upload_speed = 921600
|
upload_speed = 921600
|
||||||
|
check_tool = cppcheck
|
||||||
|
check_flags = --enable=all --suppress=missingIncludeSystem --suppress=unusedFunction --suppress=unmatchedSuppression --suppress=*:*/.pio/* --inline-suppr
|
||||||
|
check_skip_packages = yes
|
||||||
|
|
||||||
board_upload.flash_size = 16MB
|
board_upload.flash_size = 16MB
|
||||||
board_upload.maximum_size = 16777216
|
board_upload.maximum_size = 16777216
|
||||||
board_upload.offset_address = 0x10000
|
board_upload.offset_address = 0x10000
|
||||||
|
|
||||||
|
build_flags =
|
||||||
|
-DARDUINO_USB_MODE=1
|
||||||
|
-DARDUINO_USB_CDC_ON_BOOT=1
|
||||||
|
-DMINIZ_NO_ZLIB_COMPATIBLE_NAMES=1
|
||||||
|
-DEINK_DISPLAY_SINGLE_BUFFER_MODE=1
|
||||||
|
# https://libexpat.github.io/doc/api/latest/#XML_GE
|
||||||
|
-DXML_GE=0
|
||||||
|
-DXML_CONTEXT_BYTES=1024
|
||||||
|
-std=c++2a
|
||||||
|
|
||||||
; Board configuration
|
; Board configuration
|
||||||
board_build.flash_mode = dio
|
board_build.flash_mode = dio
|
||||||
board_build.flash_size = 16MB
|
board_build.flash_size = 16MB
|
||||||
board_build.partitions = partitions.csv
|
board_build.partitions = partitions.csv
|
||||||
|
|
||||||
build_flags =
|
extra_scripts =
|
||||||
-DARDUINO_USB_MODE=1
|
pre:scripts/build_html.py
|
||||||
-DARDUINO_USB_CDC_ON_BOOT=1
|
|
||||||
-DMINIZ_NO_ZLIB_COMPATIBLE_NAMES=1
|
|
||||||
# https://libexpat.github.io/doc/api/latest/#XML_GE
|
|
||||||
-DXML_GE=0
|
|
||||||
-DXML_CONTEXT_BYTES=1024
|
|
||||||
|
|
||||||
; Libraries
|
; Libraries
|
||||||
lib_deps =
|
lib_deps =
|
||||||
zinggjm/GxEPD2@^1.6.5
|
|
||||||
https://github.com/leethomason/tinyxml2.git#11.0.0
|
|
||||||
BatteryMonitor=symlink://open-x4-sdk/libs/hardware/BatteryMonitor
|
BatteryMonitor=symlink://open-x4-sdk/libs/hardware/BatteryMonitor
|
||||||
InputManager=symlink://open-x4-sdk/libs/hardware/InputManager
|
InputManager=symlink://open-x4-sdk/libs/hardware/InputManager
|
||||||
|
EInkDisplay=symlink://open-x4-sdk/libs/display/EInkDisplay
|
||||||
|
ArduinoJson @ 7.4.2
|
||||||
|
QRCode @ 0.0.1
|
||||||
|
|
||||||
|
[env:default]
|
||||||
|
extends = base
|
||||||
|
build_flags =
|
||||||
|
${base.build_flags}
|
||||||
|
-DCROSSPOINT_VERSION=\"${platformio.crosspoint_version}-dev\"
|
||||||
|
|
||||||
|
[env:gh_release]
|
||||||
|
extends = base
|
||||||
|
build_flags =
|
||||||
|
${base.build_flags}
|
||||||
|
-DCROSSPOINT_VERSION=\"${platformio.crosspoint_version}\"
|
||||||
|
|||||||
@@ -0,0 +1,51 @@
|
|||||||
|
import os
|
||||||
|
import re
|
||||||
|
|
||||||
|
SRC_DIR = "src"
|
||||||
|
|
||||||
|
def minify_html(html: str) -> str:
|
||||||
|
# Tags where whitespace should be preserved
|
||||||
|
preserve_tags = ['pre', 'code', 'textarea', 'script', 'style']
|
||||||
|
preserve_regex = '|'.join(preserve_tags)
|
||||||
|
|
||||||
|
# Protect preserve blocks with placeholders
|
||||||
|
preserve_blocks = []
|
||||||
|
def preserve(match):
|
||||||
|
preserve_blocks.append(match.group(0))
|
||||||
|
return f"__PRESERVE_BLOCK_{len(preserve_blocks)-1}__"
|
||||||
|
|
||||||
|
html = re.sub(rf'<({preserve_regex})[\s\S]*?</\1>', preserve, html, flags=re.IGNORECASE)
|
||||||
|
|
||||||
|
# Remove HTML comments
|
||||||
|
html = re.sub(r'<!--.*?-->', '', html, flags=re.DOTALL)
|
||||||
|
|
||||||
|
# Collapse all whitespace between tags
|
||||||
|
html = re.sub(r'>\s+<', '><', html)
|
||||||
|
|
||||||
|
# Collapse multiple spaces inside tags
|
||||||
|
html = re.sub(r'\s+', ' ', html)
|
||||||
|
|
||||||
|
# Restore preserved blocks
|
||||||
|
for i, block in enumerate(preserve_blocks):
|
||||||
|
html = html.replace(f"__PRESERVE_BLOCK_{i}__", block)
|
||||||
|
|
||||||
|
return html.strip()
|
||||||
|
|
||||||
|
for root, _, files in os.walk(SRC_DIR):
|
||||||
|
for file in files:
|
||||||
|
if file.endswith(".html"):
|
||||||
|
html_path = os.path.join(root, file)
|
||||||
|
with open(html_path, "r", encoding="utf-8") as f:
|
||||||
|
html_content = f.read()
|
||||||
|
|
||||||
|
# minified = regex.sub("\g<1>", html_content)
|
||||||
|
minified = minify_html(html_content)
|
||||||
|
base_name = f"{os.path.splitext(file)[0]}Html"
|
||||||
|
header_path = os.path.join(root, f"{base_name}.generated.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"#pragma once\n")
|
||||||
|
h.write(f'constexpr char {base_name}[] PROGMEM = R"rawliteral({minified})rawliteral";\n')
|
||||||
|
|
||||||
|
print(f"Generated: {header_path}")
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
#include "CrossPointSettings.h"
|
||||||
|
|
||||||
|
#include <FsHelpers.h>
|
||||||
|
#include <HardwareSerial.h>
|
||||||
|
#include <SD.h>
|
||||||
|
#include <Serialization.h>
|
||||||
|
|
||||||
|
// Initialize the static instance
|
||||||
|
CrossPointSettings CrossPointSettings::instance;
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
constexpr uint8_t SETTINGS_FILE_VERSION = 1;
|
||||||
|
// Increment this when adding new persisted settings fields
|
||||||
|
constexpr uint8_t SETTINGS_COUNT = 5;
|
||||||
|
constexpr char SETTINGS_FILE[] = "/.crosspoint/settings.bin";
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
bool CrossPointSettings::saveToFile() const {
|
||||||
|
// Make sure the directory exists
|
||||||
|
SD.mkdir("/.crosspoint");
|
||||||
|
|
||||||
|
File outputFile;
|
||||||
|
if (!FsHelpers::openFileForWrite("CPS", SETTINGS_FILE, outputFile)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
serialization::writePod(outputFile, SETTINGS_FILE_VERSION);
|
||||||
|
serialization::writePod(outputFile, SETTINGS_COUNT);
|
||||||
|
serialization::writePod(outputFile, sleepScreen);
|
||||||
|
serialization::writePod(outputFile, extraParagraphSpacing);
|
||||||
|
serialization::writePod(outputFile, shortPwrBtn);
|
||||||
|
serialization::writePod(outputFile, statusBar);
|
||||||
|
serialization::writePod(outputFile, orientation);
|
||||||
|
outputFile.close();
|
||||||
|
|
||||||
|
Serial.printf("[%lu] [CPS] Settings saved to file\n", millis());
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool CrossPointSettings::loadFromFile() {
|
||||||
|
File inputFile;
|
||||||
|
if (!FsHelpers::openFileForRead("CPS", SETTINGS_FILE, inputFile)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
uint8_t version;
|
||||||
|
serialization::readPod(inputFile, version);
|
||||||
|
if (version != SETTINGS_FILE_VERSION) {
|
||||||
|
Serial.printf("[%lu] [CPS] Deserialization failed: Unknown version %u\n", millis(), version);
|
||||||
|
inputFile.close();
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
uint8_t fileSettingsCount = 0;
|
||||||
|
serialization::readPod(inputFile, fileSettingsCount);
|
||||||
|
|
||||||
|
// load settings that exist (support older files with fewer fields)
|
||||||
|
uint8_t settingsRead = 0;
|
||||||
|
do {
|
||||||
|
serialization::readPod(inputFile, sleepScreen);
|
||||||
|
if (++settingsRead >= fileSettingsCount) break;
|
||||||
|
serialization::readPod(inputFile, extraParagraphSpacing);
|
||||||
|
if (++settingsRead >= fileSettingsCount) break;
|
||||||
|
serialization::readPod(inputFile, shortPwrBtn);
|
||||||
|
if (++settingsRead >= fileSettingsCount) break;
|
||||||
|
serialization::readPod(inputFile, statusBar);
|
||||||
|
if (++settingsRead >= fileSettingsCount) break;
|
||||||
|
serialization::readPod(inputFile, orientation);
|
||||||
|
if (++settingsRead >= fileSettingsCount) break;
|
||||||
|
} while (false);
|
||||||
|
|
||||||
|
inputFile.close();
|
||||||
|
Serial.printf("[%lu] [CPS] Settings loaded from file\n", millis());
|
||||||
|
return true;
|
||||||
|
}
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
#pragma once
|
||||||
|
#include <cstdint>
|
||||||
|
#include <iosfwd>
|
||||||
|
|
||||||
|
class CrossPointSettings {
|
||||||
|
private:
|
||||||
|
// Private constructor for singleton
|
||||||
|
CrossPointSettings() = default;
|
||||||
|
|
||||||
|
// Static instance
|
||||||
|
static CrossPointSettings instance;
|
||||||
|
|
||||||
|
public:
|
||||||
|
// Delete copy constructor and assignment
|
||||||
|
CrossPointSettings(const CrossPointSettings&) = delete;
|
||||||
|
CrossPointSettings& operator=(const CrossPointSettings&) = delete;
|
||||||
|
|
||||||
|
// Should match with SettingsActivity text
|
||||||
|
enum SLEEP_SCREEN_MODE { DARK = 0, LIGHT = 1, CUSTOM = 2, COVER = 3 };
|
||||||
|
|
||||||
|
// Status bar display type enum
|
||||||
|
enum STATUS_BAR_MODE { NONE = 0, NO_PROGRESS = 1, FULL = 2 };
|
||||||
|
|
||||||
|
enum ORIENTATION {
|
||||||
|
PORTRAIT = 0, // 480x800 logical coordinates (current default)
|
||||||
|
LANDSCAPE_CW = 1, // 800x480 logical coordinates, rotated 180° (swap top/bottom)
|
||||||
|
INVERTED = 2, // 480x800 logical coordinates, inverted
|
||||||
|
LANDSCAPE_CCW = 3 // 800x480 logical coordinates, native panel orientation
|
||||||
|
};
|
||||||
|
|
||||||
|
// Sleep screen settings
|
||||||
|
uint8_t sleepScreen = DARK;
|
||||||
|
// Status bar settings
|
||||||
|
uint8_t statusBar = FULL;
|
||||||
|
// Text rendering settings
|
||||||
|
uint8_t extraParagraphSpacing = 1;
|
||||||
|
// Duration of the power button press
|
||||||
|
uint8_t shortPwrBtn = 0;
|
||||||
|
// EPUB reading orientation settings
|
||||||
|
// 0 = portrait (default), 1 = landscape clockwise, 2 = inverted, 3 = landscape counter-clockwise
|
||||||
|
uint8_t orientation = PORTRAIT;
|
||||||
|
|
||||||
|
~CrossPointSettings() = default;
|
||||||
|
|
||||||
|
// Get singleton instance
|
||||||
|
static CrossPointSettings& getInstance() { return instance; }
|
||||||
|
|
||||||
|
uint16_t getPowerButtonDuration() const { return shortPwrBtn ? 10 : 500; }
|
||||||
|
|
||||||
|
bool saveToFile() const;
|
||||||
|
bool loadFromFile();
|
||||||
|
};
|
||||||
|
|
||||||
|
// Helper macro to access settings
|
||||||
|
#define SETTINGS CrossPointSettings::getInstance()
|
||||||
@@ -1,16 +1,22 @@
|
|||||||
#include "CrossPointState.h"
|
#include "CrossPointState.h"
|
||||||
|
|
||||||
|
#include <FsHelpers.h>
|
||||||
#include <HardwareSerial.h>
|
#include <HardwareSerial.h>
|
||||||
#include <SD.h>
|
|
||||||
#include <Serialization.h>
|
#include <Serialization.h>
|
||||||
|
|
||||||
#include <fstream>
|
namespace {
|
||||||
|
|
||||||
constexpr uint8_t STATE_FILE_VERSION = 1;
|
constexpr uint8_t STATE_FILE_VERSION = 1;
|
||||||
constexpr char STATE_FILE[] = "/sd/.crosspoint/state.bin";
|
constexpr char STATE_FILE[] = "/.crosspoint/state.bin";
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
CrossPointState CrossPointState::instance;
|
||||||
|
|
||||||
bool CrossPointState::saveToFile() const {
|
bool CrossPointState::saveToFile() const {
|
||||||
std::ofstream outputFile(STATE_FILE);
|
File outputFile;
|
||||||
|
if (!FsHelpers::openFileForWrite("CPS", STATE_FILE, outputFile)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
serialization::writePod(outputFile, STATE_FILE_VERSION);
|
serialization::writePod(outputFile, STATE_FILE_VERSION);
|
||||||
serialization::writeString(outputFile, openEpubPath);
|
serialization::writeString(outputFile, openEpubPath);
|
||||||
outputFile.close();
|
outputFile.close();
|
||||||
@@ -18,12 +24,15 @@ bool CrossPointState::saveToFile() const {
|
|||||||
}
|
}
|
||||||
|
|
||||||
bool CrossPointState::loadFromFile() {
|
bool CrossPointState::loadFromFile() {
|
||||||
std::ifstream inputFile(STATE_FILE);
|
File inputFile;
|
||||||
|
if (!FsHelpers::openFileForRead("CPS", STATE_FILE, inputFile)) {
|
||||||
|
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("CrossPointState: Unknown version %u\n", version);
|
Serial.printf("[%lu] [CPS] Deserialization failed: Unknown version %u\n", millis(), version);
|
||||||
inputFile.close();
|
inputFile.close();
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,11 +3,20 @@
|
|||||||
#include <string>
|
#include <string>
|
||||||
|
|
||||||
class CrossPointState {
|
class CrossPointState {
|
||||||
|
// Static instance
|
||||||
|
static CrossPointState instance;
|
||||||
|
|
||||||
public:
|
public:
|
||||||
std::string openEpubPath;
|
std::string openEpubPath;
|
||||||
~CrossPointState() = default;
|
~CrossPointState() = default;
|
||||||
|
|
||||||
|
// Get singleton instance
|
||||||
|
static CrossPointState& getInstance() { return instance; }
|
||||||
|
|
||||||
bool saveToFile() const;
|
bool saveToFile() const;
|
||||||
|
|
||||||
bool loadFromFile();
|
bool loadFromFile();
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Helper macro to access settings
|
||||||
|
#define APP_STATE CrossPointState::getInstance()
|
||||||
|
|||||||
@@ -0,0 +1,154 @@
|
|||||||
|
#include "WifiCredentialStore.h"
|
||||||
|
|
||||||
|
#include <FsHelpers.h>
|
||||||
|
#include <HardwareSerial.h>
|
||||||
|
#include <SD.h>
|
||||||
|
#include <Serialization.h>
|
||||||
|
|
||||||
|
// Initialize the static instance
|
||||||
|
WifiCredentialStore WifiCredentialStore::instance;
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
// File format version
|
||||||
|
constexpr uint8_t WIFI_FILE_VERSION = 1;
|
||||||
|
|
||||||
|
// WiFi credentials file path
|
||||||
|
constexpr char WIFI_FILE[] = "/.crosspoint/wifi.bin";
|
||||||
|
|
||||||
|
// Obfuscation key - "CrossPoint" in ASCII
|
||||||
|
// This is NOT cryptographic security, just prevents casual file reading
|
||||||
|
constexpr uint8_t OBFUSCATION_KEY[] = {0x43, 0x72, 0x6F, 0x73, 0x73, 0x50, 0x6F, 0x69, 0x6E, 0x74};
|
||||||
|
constexpr size_t KEY_LENGTH = sizeof(OBFUSCATION_KEY);
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
void WifiCredentialStore::obfuscate(std::string& data) const {
|
||||||
|
Serial.printf("[%lu] [WCS] Obfuscating/deobfuscating %zu bytes\n", millis(), data.size());
|
||||||
|
for (size_t i = 0; i < data.size(); i++) {
|
||||||
|
data[i] ^= OBFUSCATION_KEY[i % KEY_LENGTH];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
bool WifiCredentialStore::saveToFile() const {
|
||||||
|
// Make sure the directory exists
|
||||||
|
SD.mkdir("/.crosspoint");
|
||||||
|
|
||||||
|
File file;
|
||||||
|
if (!FsHelpers::openFileForWrite("WCS", WIFI_FILE, file)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Write header
|
||||||
|
serialization::writePod(file, WIFI_FILE_VERSION);
|
||||||
|
serialization::writePod(file, static_cast<uint8_t>(credentials.size()));
|
||||||
|
|
||||||
|
// Write each credential
|
||||||
|
for (const auto& cred : credentials) {
|
||||||
|
// Write SSID (plaintext - not sensitive)
|
||||||
|
serialization::writeString(file, cred.ssid);
|
||||||
|
Serial.printf("[%lu] [WCS] Saving SSID: %s, password length: %zu\n", millis(), cred.ssid.c_str(),
|
||||||
|
cred.password.size());
|
||||||
|
|
||||||
|
// Write password (obfuscated)
|
||||||
|
std::string obfuscatedPwd = cred.password;
|
||||||
|
obfuscate(obfuscatedPwd);
|
||||||
|
serialization::writeString(file, obfuscatedPwd);
|
||||||
|
}
|
||||||
|
|
||||||
|
file.close();
|
||||||
|
Serial.printf("[%lu] [WCS] Saved %zu WiFi credentials to file\n", millis(), credentials.size());
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool WifiCredentialStore::loadFromFile() {
|
||||||
|
File file;
|
||||||
|
if (!FsHelpers::openFileForRead("WCS", WIFI_FILE, file)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Read and verify version
|
||||||
|
uint8_t version;
|
||||||
|
serialization::readPod(file, version);
|
||||||
|
if (version != WIFI_FILE_VERSION) {
|
||||||
|
Serial.printf("[%lu] [WCS] Unknown file version: %u\n", millis(), version);
|
||||||
|
file.close();
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Read credential count
|
||||||
|
uint8_t count;
|
||||||
|
serialization::readPod(file, count);
|
||||||
|
|
||||||
|
// Read credentials
|
||||||
|
credentials.clear();
|
||||||
|
for (uint8_t i = 0; i < count && i < MAX_NETWORKS; i++) {
|
||||||
|
WifiCredential cred;
|
||||||
|
|
||||||
|
// Read SSID
|
||||||
|
serialization::readString(file, cred.ssid);
|
||||||
|
|
||||||
|
// Read and deobfuscate password
|
||||||
|
serialization::readString(file, cred.password);
|
||||||
|
Serial.printf("[%lu] [WCS] Loaded SSID: %s, obfuscated password length: %zu\n", millis(), cred.ssid.c_str(),
|
||||||
|
cred.password.size());
|
||||||
|
obfuscate(cred.password); // XOR is symmetric, so same function deobfuscates
|
||||||
|
Serial.printf("[%lu] [WCS] After deobfuscation, password length: %zu\n", millis(), cred.password.size());
|
||||||
|
|
||||||
|
credentials.push_back(cred);
|
||||||
|
}
|
||||||
|
|
||||||
|
file.close();
|
||||||
|
Serial.printf("[%lu] [WCS] Loaded %zu WiFi credentials from file\n", millis(), credentials.size());
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool WifiCredentialStore::addCredential(const std::string& ssid, const std::string& password) {
|
||||||
|
// Check if this SSID already exists and update it
|
||||||
|
const auto cred = find_if(credentials.begin(), credentials.end(),
|
||||||
|
[&ssid](const WifiCredential& cred) { return cred.ssid == ssid; });
|
||||||
|
if (cred != credentials.end()) {
|
||||||
|
cred->password = password;
|
||||||
|
Serial.printf("[%lu] [WCS] Updated credentials for: %s\n", millis(), ssid.c_str());
|
||||||
|
return saveToFile();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if we've reached the limit
|
||||||
|
if (credentials.size() >= MAX_NETWORKS) {
|
||||||
|
Serial.printf("[%lu] [WCS] Cannot add more networks, limit of %zu reached\n", millis(), MAX_NETWORKS);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add new credential
|
||||||
|
credentials.push_back({ssid, password});
|
||||||
|
Serial.printf("[%lu] [WCS] Added credentials for: %s\n", millis(), ssid.c_str());
|
||||||
|
return saveToFile();
|
||||||
|
}
|
||||||
|
|
||||||
|
bool WifiCredentialStore::removeCredential(const std::string& ssid) {
|
||||||
|
const auto cred = find_if(credentials.begin(), credentials.end(),
|
||||||
|
[&ssid](const WifiCredential& cred) { return cred.ssid == ssid; });
|
||||||
|
if (cred != credentials.end()) {
|
||||||
|
credentials.erase(cred);
|
||||||
|
Serial.printf("[%lu] [WCS] Removed credentials for: %s\n", millis(), ssid.c_str());
|
||||||
|
return saveToFile();
|
||||||
|
}
|
||||||
|
return false; // Not found
|
||||||
|
}
|
||||||
|
|
||||||
|
const WifiCredential* WifiCredentialStore::findCredential(const std::string& ssid) const {
|
||||||
|
const auto cred = find_if(credentials.begin(), credentials.end(),
|
||||||
|
[&ssid](const WifiCredential& cred) { return cred.ssid == ssid; });
|
||||||
|
|
||||||
|
if (cred != credentials.end()) {
|
||||||
|
return &*cred;
|
||||||
|
}
|
||||||
|
|
||||||
|
return nullptr;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool WifiCredentialStore::hasSavedCredential(const std::string& ssid) const { return findCredential(ssid) != nullptr; }
|
||||||
|
|
||||||
|
void WifiCredentialStore::clearAll() {
|
||||||
|
credentials.clear();
|
||||||
|
saveToFile();
|
||||||
|
Serial.printf("[%lu] [WCS] Cleared all WiFi credentials\n", millis());
|
||||||
|
}
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
#pragma once
|
||||||
|
#include <string>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
struct WifiCredential {
|
||||||
|
std::string ssid;
|
||||||
|
std::string password; // Stored obfuscated in file
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Singleton class for storing WiFi credentials on the SD card.
|
||||||
|
* Credentials are stored in /sd/.crosspoint/wifi.bin with basic
|
||||||
|
* XOR obfuscation to prevent casual reading (not cryptographically secure).
|
||||||
|
*/
|
||||||
|
class WifiCredentialStore {
|
||||||
|
private:
|
||||||
|
static WifiCredentialStore instance;
|
||||||
|
std::vector<WifiCredential> credentials;
|
||||||
|
|
||||||
|
static constexpr size_t MAX_NETWORKS = 8;
|
||||||
|
|
||||||
|
// Private constructor for singleton
|
||||||
|
WifiCredentialStore() = default;
|
||||||
|
|
||||||
|
// XOR obfuscation (symmetric - same for encode/decode)
|
||||||
|
void obfuscate(std::string& data) const;
|
||||||
|
|
||||||
|
public:
|
||||||
|
// Delete copy constructor and assignment
|
||||||
|
WifiCredentialStore(const WifiCredentialStore&) = delete;
|
||||||
|
WifiCredentialStore& operator=(const WifiCredentialStore&) = delete;
|
||||||
|
|
||||||
|
// Get singleton instance
|
||||||
|
static WifiCredentialStore& getInstance() { return instance; }
|
||||||
|
|
||||||
|
// Save/load from SD card
|
||||||
|
bool saveToFile() const;
|
||||||
|
bool loadFromFile();
|
||||||
|
|
||||||
|
// Credential management
|
||||||
|
bool addCredential(const std::string& ssid, const std::string& password);
|
||||||
|
bool removeCredential(const std::string& ssid);
|
||||||
|
const WifiCredential* findCredential(const std::string& ssid) const;
|
||||||
|
|
||||||
|
// Get all stored credentials (for UI display)
|
||||||
|
const std::vector<WifiCredential>& getCredentials() const { return credentials; }
|
||||||
|
|
||||||
|
// Check if a network is saved
|
||||||
|
bool hasSavedCredential(const std::string& ssid) const;
|
||||||
|
|
||||||
|
// Clear all credentials
|
||||||
|
void clearAll();
|
||||||
|
};
|
||||||
|
|
||||||
|
// Helper macro to access credentials store
|
||||||
|
#define WIFI_STORE WifiCredentialStore::getInstance()
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <HardwareSerial.h>
|
||||||
|
|
||||||
|
#include <string>
|
||||||
|
#include <utility>
|
||||||
|
|
||||||
|
class InputManager;
|
||||||
|
class GfxRenderer;
|
||||||
|
|
||||||
|
class Activity {
|
||||||
|
protected:
|
||||||
|
std::string name;
|
||||||
|
GfxRenderer& renderer;
|
||||||
|
InputManager& inputManager;
|
||||||
|
|
||||||
|
public:
|
||||||
|
explicit Activity(std::string name, GfxRenderer& renderer, InputManager& inputManager)
|
||||||
|
: name(std::move(name)), renderer(renderer), inputManager(inputManager) {}
|
||||||
|
virtual ~Activity() = default;
|
||||||
|
virtual void onEnter() { Serial.printf("[%lu] [ACT] Entering activity: %s\n", millis(), name.c_str()); }
|
||||||
|
virtual void onExit() { Serial.printf("[%lu] [ACT] Exiting activity: %s\n", millis(), name.c_str()); }
|
||||||
|
virtual void loop() {}
|
||||||
|
virtual bool skipLoopDelay() { return false; }
|
||||||
|
};
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
#include "ActivityWithSubactivity.h"
|
||||||
|
|
||||||
|
void ActivityWithSubactivity::exitActivity() {
|
||||||
|
if (subActivity) {
|
||||||
|
subActivity->onExit();
|
||||||
|
subActivity.reset();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void ActivityWithSubactivity::enterNewActivity(Activity* activity) {
|
||||||
|
subActivity.reset(activity);
|
||||||
|
subActivity->onEnter();
|
||||||
|
}
|
||||||
|
|
||||||
|
void ActivityWithSubactivity::loop() {
|
||||||
|
if (subActivity) {
|
||||||
|
subActivity->loop();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void ActivityWithSubactivity::onExit() {
|
||||||
|
Activity::onExit();
|
||||||
|
exitActivity();
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
#pragma once
|
||||||
|
#include <memory>
|
||||||
|
|
||||||
|
#include "Activity.h"
|
||||||
|
|
||||||
|
class ActivityWithSubactivity : public Activity {
|
||||||
|
protected:
|
||||||
|
std::unique_ptr<Activity> subActivity = nullptr;
|
||||||
|
void exitActivity();
|
||||||
|
void enterNewActivity(Activity* activity);
|
||||||
|
|
||||||
|
public:
|
||||||
|
explicit ActivityWithSubactivity(std::string name, GfxRenderer& renderer, InputManager& inputManager)
|
||||||
|
: Activity(std::move(name), renderer, inputManager) {}
|
||||||
|
void loop() override;
|
||||||
|
void onExit() override;
|
||||||
|
};
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
#include "BootActivity.h"
|
||||||
|
|
||||||
|
#include <GfxRenderer.h>
|
||||||
|
|
||||||
|
#include "config.h"
|
||||||
|
#include "images/CrossLarge.h"
|
||||||
|
|
||||||
|
void BootActivity::onEnter() {
|
||||||
|
Activity::onEnter();
|
||||||
|
|
||||||
|
const auto pageWidth = renderer.getScreenWidth();
|
||||||
|
const auto pageHeight = renderer.getScreenHeight();
|
||||||
|
|
||||||
|
renderer.clearScreen();
|
||||||
|
renderer.drawImage(CrossLarge, (pageWidth + 128) / 2, (pageHeight - 128) / 2, 128, 128);
|
||||||
|
renderer.drawCenteredText(UI_FONT_ID, pageHeight / 2 + 70, "CrossPoint", true, BOLD);
|
||||||
|
renderer.drawCenteredText(SMALL_FONT_ID, pageHeight / 2 + 95, "BOOTING");
|
||||||
|
renderer.drawCenteredText(SMALL_FONT_ID, pageHeight - 30, CROSSPOINT_VERSION);
|
||||||
|
renderer.displayBuffer();
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
#pragma once
|
||||||
|
#include "../Activity.h"
|
||||||
|
|
||||||
|
class BootActivity final : public Activity {
|
||||||
|
public:
|
||||||
|
explicit BootActivity(GfxRenderer& renderer, InputManager& inputManager) : Activity("Boot", renderer, inputManager) {}
|
||||||
|
void onEnter() override;
|
||||||
|
};
|
||||||