Compare commits
336
Commits
release/1.1.1
...
1.3.0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8959836e46 | ||
|
|
fd79074d43 | ||
|
|
b971f7bda4 | ||
|
|
c26e410c58 | ||
|
|
16e5e5f00b | ||
|
|
74e75746df | ||
|
|
a7586f20a1 | ||
|
|
b145e4437c | ||
|
|
3c34a8310e | ||
|
|
bc6e090aa8 | ||
|
|
8d1b86a893 | ||
|
|
63d5094f2e | ||
|
|
24977048c3 | ||
|
|
63e92ec74e | ||
|
|
accd50b593 | ||
|
|
26250c0b80 | ||
|
|
99ac1c5c89 | ||
|
|
90874dae9f | ||
|
|
a0037ced2b | ||
|
|
20fee843c7 | ||
|
|
181ed6c488 | ||
|
|
3ac1ab13a0 | ||
|
|
dd06e71b66 | ||
|
|
4e5e2fe40a | ||
|
|
2ff63884d6 | ||
|
|
74b8cac928 | ||
|
|
fcb8793640 | ||
|
|
aba393f900 | ||
|
|
45441e0789 | ||
|
|
cff54d776c | ||
|
|
5917c561b3 | ||
|
|
5d5533b3d2 | ||
|
|
c5d2dc2e00 | ||
|
|
91de6ac278 | ||
|
|
c7ad14eb36 | ||
|
|
d3e0aeb62b | ||
|
|
3efc863038 | ||
|
|
6c97061629 | ||
|
|
bf30964982 | ||
|
|
ceb3fed392 | ||
|
|
f03d3a8056 | ||
|
|
bf894fd343 | ||
|
|
628794f8b8 | ||
|
|
9b2d8388ef | ||
|
|
e64155ed63 | ||
|
|
bb3a44f584 | ||
|
|
7993b2bb97 | ||
|
|
29fd29f537 | ||
|
|
b463966045 | ||
|
|
a48ad3cd61 | ||
|
|
e3fb3bba37 | ||
|
|
e8d7153d7f | ||
|
|
1e2f6e2d67 | ||
|
|
e841c84194 | ||
|
|
83f0cee565 | ||
|
|
c15b5b9bc5 | ||
|
|
dadce519c4 | ||
|
|
11bc36ebb5 | ||
|
|
395e68ea2b | ||
|
|
cfe3a948a0 | ||
|
|
4ea938b709 | ||
|
|
939014d996 | ||
|
|
3e7d63dab9 | ||
|
|
efa4f71a68 | ||
|
|
f44722a0f2 | ||
|
|
40af42683e | ||
|
|
78625afe76 | ||
|
|
bd546093cb | ||
|
|
adcd7961c9 | ||
|
|
5717374e4b | ||
|
|
b8a6b58b5e | ||
|
|
333286acfc | ||
|
|
e026bcb9dc | ||
|
|
a1007a4660 | ||
|
|
6c4ae7c41a | ||
|
|
a5fac320ab | ||
|
|
2e2ea6a9e8 | ||
|
|
b692bad10d | ||
|
|
aa7a31b3db | ||
|
|
22701ccf18 | ||
|
|
64ecfe2ef3 | ||
|
|
ba4a361d64 | ||
|
|
15ea7027df | ||
|
|
b25389b43e | ||
|
|
ae865f6d08 | ||
|
|
d53c8b0e0e | ||
|
|
2f969a93b4 | ||
|
|
14e1ce2d04 | ||
|
|
5d2e5596b4 | ||
|
|
bc9651b664 | ||
|
|
741dd89ac1 | ||
|
|
ef98d44ef3 | ||
|
|
b8a51522ca | ||
|
|
33386953d9 | ||
|
|
02822e01b3 | ||
|
|
198b9d7786 | ||
|
|
15e0d39d2c | ||
|
|
6c4e946e27 | ||
|
|
907e14da28 | ||
|
|
b9b795bf45 | ||
|
|
b21b10f4b9 | ||
|
|
1cf2239742 | ||
|
|
c5f82709c0 | ||
|
|
867fb7cbe2 | ||
|
|
5e26baef63 | ||
|
|
8154f88dbe | ||
|
|
56d3ab929c | ||
|
|
9dab5f471b | ||
|
|
ce22deab7c | ||
|
|
e28918b24d | ||
|
|
c0ee096841 | ||
|
|
1a145fe085 | ||
|
|
302dea1eea | ||
|
|
e8645ed92e | ||
|
|
64f5ef018a | ||
|
|
3cdfc6c781 | ||
|
|
77b2c31635 | ||
|
|
fedcb2f53d | ||
|
|
a888978f95 | ||
|
|
23f60a3407 | ||
|
|
2c5a47f9d7 | ||
|
|
ce1756e36f | ||
|
|
3b12c083bc | ||
|
|
c4f5c8e931 | ||
|
|
0c5dee3c62 | ||
|
|
81ae9dd779 | ||
|
|
40e4c96906 | ||
|
|
80772ff6b8 | ||
|
|
57fc6555f2 | ||
|
|
ed54f97909 | ||
|
|
45cd00889e | ||
|
|
cced77783f | ||
|
|
1bd7a1de67 | ||
|
|
23aad213fc | ||
|
|
075ad7d021 | ||
|
|
243ae8b408 | ||
|
|
4e9c7a787f | ||
|
|
cc23aaa9c2 | ||
|
|
05f8e6e12d | ||
|
|
405ce0c3c8 | ||
|
|
9bc5111c77 | ||
|
|
9c11f3e4a2 | ||
|
|
fa2a3d2539 | ||
|
|
5c12f2f01e | ||
|
|
8d6b35b8e7 | ||
|
|
83cd96bc2f | ||
|
|
14ec53a335 | ||
|
|
5ba85290ab | ||
|
|
104f391a29 | ||
|
|
b3b43bb373 | ||
|
|
5349e81723 | ||
|
|
825ef56ad8 | ||
|
|
ed0811c898 | ||
|
|
d29b8ee2f9 | ||
|
|
b898d53f7b | ||
|
|
c656673b9a | ||
|
|
1398aeb1ed | ||
|
|
6cd19f5619 | ||
|
|
cff3e12a0a | ||
|
|
fa3c7d96a0 | ||
|
|
f429f9035c | ||
|
|
11984f8fef | ||
|
|
1c13331189 | ||
|
|
9b3885135f | ||
|
+7 |
e6c6e72a24 | ||
|
|
1d219ae27e | ||
|
|
c4f11015f1 | ||
|
|
abd2266048 | ||
|
|
1df543d48d | ||
|
|
63961625a2 | ||
|
|
34484300e4 | ||
|
|
831144e737 | ||
|
|
42c33528f9 | ||
|
|
6969950cd7 | ||
|
|
bc6f6daeb5 | ||
|
|
8352e1f08f | ||
|
|
dfc38cca4c | ||
|
|
3856348ee6 | ||
|
|
0e228324e6 | ||
|
|
8e091609f7 | ||
|
|
710055f02c | ||
|
|
0245972132 | ||
|
|
0cbfaa007d | ||
|
|
ceb6acc8d7 | ||
|
|
7d56810ee6 | ||
|
|
526c8a5e7a | ||
|
|
0c9e8b3ece | ||
|
|
53beeeed2b | ||
|
|
8dd365b4da | ||
|
|
9665dd7473 | ||
|
|
71719e1d94 | ||
|
|
d6951f81b7 | ||
|
|
99721c081b | ||
|
|
f9286709d1 | ||
|
|
dc39480349 | ||
|
|
b5df6cb2b5 | ||
|
|
16b73744c5 | ||
|
|
79b54b3a75 | ||
|
|
11ca208ec2 | ||
|
|
7a28f90dad | ||
|
|
3dabd30287 | ||
|
|
f1e9dc7f30 | ||
|
|
b467ea7973 | ||
|
|
32a5c1c358 | ||
|
|
a95a63b753 | ||
|
|
4104fa8102 | ||
|
|
e60ba7620d | ||
|
|
cd508d27d5 | ||
|
|
170cc25774 | ||
|
|
c40e92e4d1 | ||
|
|
4d22256745 | ||
|
|
18b36efbae | ||
|
|
a35f372e1b | ||
|
|
4ef433e373 | ||
|
|
a5d7e03f54 | ||
|
|
047b0029c9 | ||
|
|
c3f1dbfa09 | ||
|
|
ea88797c8e | ||
|
|
218201bd1f | ||
|
|
6ee05b08a1 | ||
|
|
a826569a0f | ||
|
|
88594077aa | ||
|
|
ce0b439aa3 | ||
|
|
019587bb77 | ||
|
|
4388bf8cc7 | ||
|
|
6de8b7a666 | ||
|
|
307a6608f0 | ||
|
|
a350492571 | ||
|
|
ef02737c89 | ||
|
|
aff93f1dc0 | ||
|
|
f0a549b680 | ||
|
|
7dc518624c | ||
|
|
620835a6a1 | ||
|
|
3cc8e272ca | ||
|
|
80d1856330 | ||
|
|
76681201bf | ||
|
|
04242fa221 | ||
|
|
2b25f4d168 | ||
|
|
a57c62f0b4 | ||
|
|
3da2cd3cf8 | ||
|
|
88c49b8bed | ||
|
|
f67e6c2831 | ||
|
|
5e95d9a36f | ||
|
|
45a228a645 | ||
|
|
6ff5fcd9a7 | ||
|
|
42b122b8fd | ||
|
|
0e168aa22c | ||
|
|
050a3bd1b6 | ||
|
|
3b4f2a1129 | ||
|
|
09cef70709 | ||
|
|
4fb785af82 | ||
|
|
74c7205967 | ||
|
|
93d4a34c37 | ||
|
|
c4fc4effbd | ||
|
|
5b11e45a36 | ||
|
|
d05cb220bb | ||
|
|
125e091d13 | ||
|
|
6b64a0a2d8 | ||
|
|
1abe307f20 | ||
|
|
f7814cd139 | ||
|
|
3f98a87709 | ||
|
|
30d8a8d011 | ||
|
|
451774ddf8 | ||
|
|
8c27938979 | ||
|
|
4a0ef05899 | ||
|
|
c99a673e5b | ||
|
|
cae8517235 | ||
|
|
7e214ea760 | ||
|
|
b695a48af6 | ||
|
|
a6c5d9aa7c | ||
|
|
2d49c7b7b4 | ||
|
|
cb72916397 | ||
|
|
35988ada55 | ||
|
|
f2fbdccd53 | ||
|
|
128eb614a6 | ||
|
|
31396da064 | ||
|
|
8ab2f22730 | ||
|
|
c0cd7c13a3 | ||
|
|
000289e429 | ||
|
|
ff577540a3 | ||
|
|
43efd80e14 | ||
|
|
5050992bd6 | ||
|
|
7d97687a5b | ||
|
|
d6d0cc869e | ||
|
|
233deacfe1 | ||
|
|
0eb8a9346b | ||
|
|
13592db50f | ||
|
|
f8a9f1f07a | ||
|
|
052f497b9e | ||
|
|
bfdf0a4f78 | ||
|
|
ae94e97fb8 | ||
|
|
04e72a9ede | ||
|
|
52ca658634 | ||
|
|
75bb1d8582 | ||
|
|
7761ced0ed | ||
|
|
2b52bc658c | ||
|
|
57250b97e4 | ||
|
|
13fc8b94b0 | ||
|
|
410c70ab89 | ||
|
|
a6aead660a | ||
|
|
9e4ef008cc | ||
|
|
6dc993852b | ||
|
|
63002d464b | ||
|
|
75ff7b25ab | ||
|
|
4ccafe5cfa | ||
|
|
ecb5b1b4e5 | ||
|
|
f28623dacd | ||
|
|
a610568f8c | ||
|
|
d9f114b652 | ||
|
|
3cb60aa231 | ||
|
|
786b438ea2 | ||
|
|
6e4d0e534d | ||
|
|
f62529ad91 | ||
|
|
88537769f6 | ||
|
|
3696794591 | ||
|
|
c1fad16e10 | ||
|
|
5f5561b684 | ||
|
|
10a2678584 | ||
|
|
e32d41a37e | ||
|
|
7717ae2683 | ||
|
|
f02c9784ec | ||
|
|
693dba4c94 | ||
|
|
9c55c15a72 | ||
|
|
6ba9658f15 | ||
|
|
22b96ec22a | ||
|
|
c9faf2a8c0 | ||
|
|
356fe9a31e | ||
|
|
5da23eed82 | ||
|
|
388fbf206a | ||
|
|
2a38bfd8af | ||
|
|
d7f89e6c0d | ||
|
|
07d715e32d | ||
|
|
63b2643534 | ||
|
|
cabbfcfd7e | ||
|
|
d461d93e76 | ||
|
|
ca89e41636 |
Executable
+26
@@ -0,0 +1,26 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
# Run formatter from repository root regardless of current directory.
|
||||
REPO_ROOT="$(git rev-parse --show-toplevel)"
|
||||
cd "${REPO_ROOT}"
|
||||
|
||||
# Capture the files already staged for commit so we only re-stage those
|
||||
# paths after formatting.
|
||||
staged_files=()
|
||||
while IFS= read -r -d '' file; do
|
||||
staged_files+=("${file}")
|
||||
done < <(git diff --cached --name-only -z --diff-filter=ACMR)
|
||||
|
||||
# Intentionally format all currently modified tracked C/C++ files.
|
||||
# The helper handles no-op cases and exits 0 when nothing matches.
|
||||
echo "Running clang-format fix before commit..."
|
||||
./bin/clang-format-fix
|
||||
|
||||
# Ensure formatting changes are included in the pending commit without
|
||||
# staging unrelated tracked modifications from other files in the
|
||||
# working tree.
|
||||
if ((${#staged_files[@]})); then
|
||||
git add -- "${staged_files[@]}"
|
||||
fi
|
||||
+1
@@ -0,0 +1 @@
|
||||
../../.skills/SKILL.md
|
||||
@@ -44,8 +44,14 @@ jobs:
|
||||
with:
|
||||
python-version: '3.14'
|
||||
|
||||
- name: Install uv
|
||||
uses: astral-sh/setup-uv@v7
|
||||
with:
|
||||
version: "latest"
|
||||
enable-cache: false
|
||||
|
||||
- name: Install PlatformIO Core
|
||||
run: pip install --upgrade platformio
|
||||
run: uv pip install --system -U https://github.com/pioarduino/platformio-core/archive/refs/tags/v6.1.19.zip
|
||||
|
||||
- name: Run cppcheck
|
||||
run: pio check --fail-on-defect low --fail-on-defect medium --fail-on-defect high
|
||||
@@ -61,8 +67,14 @@ jobs:
|
||||
with:
|
||||
python-version: '3.14'
|
||||
|
||||
- name: Install uv
|
||||
uses: astral-sh/setup-uv@v7
|
||||
with:
|
||||
version: "latest"
|
||||
enable-cache: false
|
||||
|
||||
- name: Install PlatformIO Core
|
||||
run: pip install --upgrade platformio
|
||||
run: uv pip install --system -U https://github.com/pioarduino/platformio-core/archive/refs/tags/v6.1.19.zip
|
||||
|
||||
- name: Build CrossPoint
|
||||
run: |
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
name: Build & Publish SD Card Fonts
|
||||
|
||||
# Fonts change rarely — run manually when font sources or the conversion
|
||||
# pipeline are updated. Publishes .cpfont files + fonts.json manifest as
|
||||
# GitHub Release assets on the crosspoint-fonts repo so font releases don't
|
||||
# clutter the firmware releases page.
|
||||
#
|
||||
# Requires a repository secret FONTS_REPO_TOKEN — a fine-grained PAT (or
|
||||
# classic PAT) with contents:write permission on the target fonts repo.
|
||||
on:
|
||||
workflow_dispatch:
|
||||
|
||||
env:
|
||||
FONTS_REPO: crosspoint-reader/crosspoint-fonts
|
||||
|
||||
jobs:
|
||||
build-fonts:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
with:
|
||||
submodules: recursive
|
||||
|
||||
- uses: actions/setup-python@v6
|
||||
with:
|
||||
python-version: '3.14'
|
||||
|
||||
- name: Install font tools
|
||||
run: pip install freetype-py fonttools pyyaml
|
||||
|
||||
- name: Install system dependencies
|
||||
run: sudo apt-get update && sudo apt-get install -y libfreetype6-dev
|
||||
|
||||
- name: Read version constants
|
||||
id: versions
|
||||
run: |
|
||||
cd lib/EpdFont/scripts
|
||||
echo "binary=$(python3 -c 'from cpfont_version import CPFONT_VERSION; print(CPFONT_VERSION)')" >> "$GITHUB_OUTPUT"
|
||||
echo "metadata=$(python3 -c 'from cpfont_version import FONTS_MANIFEST_VERSION; print(FONTS_MANIFEST_VERSION)')" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Build SD card fonts
|
||||
run: python3 lib/EpdFont/scripts/build-sd-fonts.py --clean --verbose -j 1
|
||||
|
||||
- name: Flatten output for release assets
|
||||
run: |
|
||||
mkdir -p dist
|
||||
find lib/EpdFont/scripts/output -name '*.cpfont' -exec cp {} dist/ \;
|
||||
|
||||
- name: Compute release tags
|
||||
id: tags
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.FONTS_REPO_TOKEN }}
|
||||
run: |
|
||||
BASE="sd-fonts-m${{ steps.versions.outputs.metadata }}-b${{ steps.versions.outputs.binary }}"
|
||||
echo "base=$BASE" >> "$GITHUB_OUTPUT"
|
||||
|
||||
# Find the highest existing revision for this m/b pair
|
||||
LAST=$(gh release list --repo "${{ env.FONTS_REPO }}" \
|
||||
--json tagName --jq \
|
||||
'[.[] | select(.tagName | startswith("'"${BASE}-r"'")) | .tagName | split("-r")[1] | tonumber] | max // 0')
|
||||
NEXT=$((LAST + 1))
|
||||
echo "revision=$NEXT" >> "$GITHUB_OUTPUT"
|
||||
echo "versioned=${BASE}-r${NEXT}" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Generate manifest
|
||||
run: |
|
||||
python3 scripts/generate-font-manifest.py \
|
||||
--input dist \
|
||||
--base-url "https://github.com/${{ env.FONTS_REPO }}/releases/download/${{ steps.tags.outputs.base }}/" \
|
||||
--output dist/fonts.json \
|
||||
--descriptions-from lib/EpdFont/scripts/sd-fonts.yaml
|
||||
|
||||
- name: Publish versioned release to fonts repo
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.FONTS_REPO_TOKEN }}
|
||||
run: |
|
||||
VERSIONED="${{ steps.tags.outputs.versioned }}"
|
||||
TITLE="SD Card Fonts (${VERSIONED#sd-fonts-})"
|
||||
|
||||
gh release create "$VERSIONED" dist/* \
|
||||
--repo "${{ env.FONTS_REPO }}" \
|
||||
--title "$TITLE" \
|
||||
--notes "Pre-built \`.cpfont\` font files for CrossPoint Reader.
|
||||
|
||||
Download individual files or use **Settings > System > Manage Fonts** on the device.
|
||||
|
||||
See [SD Card Fonts documentation](https://github.com/${{ github.repository }}/blob/main/docs/sd-card-fonts.md) for details."
|
||||
|
||||
- name: Update stable tag for device downloads
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.FONTS_REPO_TOKEN }}
|
||||
run: |
|
||||
BASE="${{ steps.tags.outputs.base }}"
|
||||
|
||||
# Delete the old stable release for this m/b pair (the versioned releases are kept)
|
||||
gh release delete "$BASE" --repo "${{ env.FONTS_REPO }}" --yes 2>/dev/null || true
|
||||
|
||||
gh release create "$BASE" dist/* \
|
||||
--repo "${{ env.FONTS_REPO }}" \
|
||||
--title "SD Card Fonts (${BASE#sd-fonts-})" \
|
||||
--notes "Current font build for manifest v${{ steps.versions.outputs.metadata }}, binary format v${{ steps.versions.outputs.binary }}. Devices with this firmware version download from this release.
|
||||
|
||||
This is revision **${{ steps.tags.outputs.revision }}** — see [\`${{ steps.tags.outputs.versioned }}\`](https://github.com/${{ env.FONTS_REPO }}/releases/tag/${{ steps.tags.outputs.versioned }}) for the immutable copy.
|
||||
|
||||
Download individual files or use **Settings > System > Manage fonts** on the device."
|
||||
@@ -12,19 +12,18 @@ jobs:
|
||||
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 uv
|
||||
uses: astral-sh/setup-uv@v7
|
||||
with:
|
||||
version: "latest"
|
||||
enable-cache: false
|
||||
|
||||
- name: Install PlatformIO Core
|
||||
run: pip install --upgrade platformio
|
||||
run: uv pip install --system -U https://github.com/pioarduino/platformio-core/archive/refs/tags/v6.1.19.zip
|
||||
|
||||
- name: Build CrossPoint
|
||||
run: pio run -e gh_release
|
||||
|
||||
@@ -12,19 +12,18 @@ jobs:
|
||||
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 uv
|
||||
uses: astral-sh/setup-uv@v7
|
||||
with:
|
||||
version: "latest"
|
||||
enable-cache: false
|
||||
|
||||
- name: Install PlatformIO Core
|
||||
run: pip install --upgrade platformio
|
||||
run: uv pip install --system -U https://github.com/pioarduino/platformio-core/archive/refs/tags/v6.1.19.zip
|
||||
|
||||
- name: Extract env
|
||||
run: |
|
||||
|
||||
@@ -3,6 +3,8 @@
|
||||
.DS_Store
|
||||
.vscode
|
||||
lib/EpdFont/fontsrc
|
||||
lib/I18n/I18nKeys.h
|
||||
lib/I18n/I18nStrings.h
|
||||
lib/I18n/I18nStrings.cpp
|
||||
*.generated.h
|
||||
.vs
|
||||
@@ -10,3 +12,10 @@ build
|
||||
**/__pycache__/
|
||||
/compile_commands.json
|
||||
/.cache
|
||||
.history/
|
||||
/.venv
|
||||
*.local*
|
||||
*.cpfont
|
||||
lib/EpdFont/scripts/downloaded_fonts/
|
||||
lib/EpdFont/scripts/instanced_fonts/
|
||||
lib/EpdFont/scripts/output/
|
||||
|
||||
+1
-1
@@ -1,3 +1,3 @@
|
||||
[submodule "open-x4-sdk"]
|
||||
path = open-x4-sdk
|
||||
url = https://github.com/open-x4-epaper/community-sdk.git
|
||||
url = https://github.com/crosspoint-reader/community-sdk.git
|
||||
|
||||
@@ -0,0 +1,881 @@
|
||||
# CrossPoint Reader Development Guide
|
||||
|
||||
Project: Open-source e-reader firmware for Xteink X4 (ESP32-C3)
|
||||
Mission: Provide a lightweight, high-performance reading experience focused on EPUB rendering on constrained hardware.
|
||||
|
||||
## AI Agent Identity and Cognitive Rules
|
||||
* Role: Senior Embedded Systems Engineer (ESP-IDF/Arduino-ESP32 specialized).
|
||||
* Primary Constraint: 380KB RAM is the hard ceiling. Stability is non-negotiable.
|
||||
* Evidence-Based Reasoning: Before proposing a change, you MUST cite the specific file path and line numbers that justify the modification.
|
||||
* Anti-Hallucination: Do not assume the existence of libraries or ESP-IDF functions. If you are unsure of an API's availability for the ESP32-C3 RISC-V target, check the open-x4-sdk or official docs first.
|
||||
* No Unfounded Claims: Do not claim performance gains or memory savings without explaining the technical mechanism (e.g., DRAM vs IRAM usage).
|
||||
* Resource Justification: You must justify any new heap allocation (new, malloc, std::vector) or explain why a stack/static alternative was rejected.
|
||||
* Verification: After suggesting a fix, instruct the user on how to verify it (e.g., monitoring heap via Serial or checking a specific cache file).
|
||||
---
|
||||
|
||||
## Development Environment Awareness
|
||||
|
||||
**CRITICAL**: Detect the host platform at session start to choose appropriate tools and commands.
|
||||
|
||||
### Platform Detection
|
||||
```bash
|
||||
# Detect platform (run once per session)
|
||||
uname -s
|
||||
# Returns: MINGW64_NT-* (Windows Git Bash), Linux, Darwin (macOS)
|
||||
```
|
||||
|
||||
**Detection Required**: Run `uname -s` at session start to determine platform
|
||||
|
||||
### Platform-Specific Behaviors
|
||||
- **Windows (Git Bash)**: Unix commands, `C:\` paths in Windows but `/` in bash, limited glob (use `find`+`xargs`)
|
||||
- **Linux/WSL**: Full bash, Unix paths, native glob support
|
||||
|
||||
**Cross-Platform Code Formatting**:
|
||||
```bash
|
||||
find src -name "*.cpp" -o -name "*.h" | xargs clang-format -i
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Platform and Hardware Constraints
|
||||
|
||||
### Hardware Specs
|
||||
* MCU: ESP32-C3 (Single-core RISC-V @ 160MHz)
|
||||
* RAM: ~380KB usable (VERY LIMITED - primary project constraint)
|
||||
* **NO PSRAM**: ESP32-C3 has no PSRAM capability (unlike ESP32-S3)
|
||||
* **Single Buffer Mode**: Only ONE 48KB framebuffer (not double-buffered)
|
||||
* Flash: 16MB (Instruction storage and static data)
|
||||
* Display: 800x480 E-Ink (Slow refresh, monochrome, 1-2s full update)
|
||||
* Framebuffer: 48,000 bytes (800 × 480 ÷ 8)
|
||||
* Storage: SD Card (Used for books and aggressive caching)
|
||||
|
||||
### The Resource Protocol
|
||||
1. Stack Safety: Limit local function variables to < 256 bytes. The ESP32-C3 default stack is small; use std::unique_ptr or static pools for larger buffers.
|
||||
2. Heap Fragmentation: Avoid repeated new/delete in loops. Allocate buffers once during onEnter() and reuse them.
|
||||
3. Flash Persistence: Large constant data (UI strings, lookup tables) MUST be marked static const to stay in Flash (Instruction Bus), freeing DRAM.
|
||||
4. String Policy: Prohibit std::string and Arduino String in hot paths. Use std::string_view for read-only access and snprintf with fixed char[] buffers for construction.
|
||||
5. UI Strings: All user-facing text must use the `tr()` macro (e.g., `tr(STR_LOADING)`) for i18n support. Never hardcode UI strings directly. For the avoidance of doubt, logging messages (LOG_DBG/LOG_ERR) can be hardcoded, but user-facing text must use `tr()`.
|
||||
6. `constexpr` First: Compile-time constants and lookup tables must be `constexpr`, not just `static const`. This moves computation to compile time, enables dead-branch elimination, and guarantees flash placement. Use `static constexpr` for class-level constants.
|
||||
7. `std::vector` Pre-allocation: Always call `.reserve(N)` before any `push_back()` loop. Each growth event allocates a new block (2×), copies all elements, then frees the old one — three heap operations that fragment DRAM. When the final size is unknown, estimate conservatively.
|
||||
8. SPIFFS Write Throttling: Never write a settings file on every user interaction. Guard all writes with a value-change check (`if (newVal == _current) return;`). Progress saves during reading must be debounced — write on activity exit or every N page turns, not on every turn. SPIFFS sectors have a finite erase cycle limit.
|
||||
|
||||
---
|
||||
|
||||
## Project Architecture
|
||||
|
||||
### Build System: PlatformIO
|
||||
|
||||
**PlatformIO is BOTH a VS Code extension AND a CLI tool**:
|
||||
|
||||
1. **VS Code Extension** (Recommended):
|
||||
* Extension ID: `platformio.platformio-ide` (see `.vscode/extensions.json`)
|
||||
* Provides: Toolbar buttons, IntelliSense, integrated build/upload/monitor
|
||||
* Configuration: `.vscode/c_cpp_properties.json`, `.vscode/tasks.json`
|
||||
* Usage: Click Build (✓), Upload (→), or Monitor (🔌) buttons
|
||||
|
||||
2. **CLI Tool** (`pio` command):
|
||||
* **Installation**: Python package (typically `pip install platformio`)
|
||||
* **Windows Location**: `C:\Users\<user>\AppData\Local\Programs\Python\Python3xx\Scripts\pio.exe`
|
||||
* **Verify**: `which pio` (Git Bash) or `where.exe pio` (cmd)
|
||||
* **Usage**: `pio run`, `pio run -t upload`, etc.
|
||||
|
||||
**Configuration Files**:
|
||||
* `platformio.ini`: Main build configuration (committed to git)
|
||||
* `platformio.local.ini`: Local overrides (gitignored, create if needed)
|
||||
* `partitions.csv`: ESP32 flash partition layout
|
||||
|
||||
### Build Environment
|
||||
* **Standard**: C++20 (`-std=c++2a`). No Exceptions, No RTTI.
|
||||
* **Logging**: ALWAYS use `LOG_INF`, `LOG_DBG`, or `LOG_ERR` from `Logging.h`. Raw Serial output is deprecated.
|
||||
* **Environments** (in `platformio.ini`):
|
||||
* `default`: Development (LOG_LEVEL=2, serial enabled)
|
||||
* `gh_release`: Production (LOG_LEVEL=0)
|
||||
* `gh_release_rc`: Release candidate (LOG_LEVEL=1)
|
||||
* `slim`: Minimal build (no serial logging)
|
||||
|
||||
### Critical Build Flags
|
||||
These flags in `platformio.ini` fundamentally affect firmware behavior:
|
||||
|
||||
```cpp
|
||||
-DEINK_DISPLAY_SINGLE_BUFFER_MODE=1 // Single framebuffer (saves 48KB RAM!)
|
||||
-DARDUINO_USB_MODE=1 // Enable USB CDC
|
||||
-DARDUINO_USB_CDC_ON_BOOT=1 // Serial available immediately at boot
|
||||
-DXML_CONTEXT_BYTES=1024 // XML parser memory limit (EPUB parsing)
|
||||
-DUSE_UTF8_LONG_NAMES=1 // SD card long filename support
|
||||
-DMINIZ_NO_ZLIB_COMPATIBLE_NAMES=1 // Avoid zlib name conflicts
|
||||
-DXML_GE=0 // Disable XML general entities (security)
|
||||
-DDESTRUCTOR_CLOSES_FILE=1 // FsFile destructor auto-closes (SdFat)
|
||||
```
|
||||
|
||||
**DESTRUCTOR_CLOSES_FILE implications**:
|
||||
- SdFat's `FsBaseFile` destructor calls `close()` automatically when the object goes out of scope
|
||||
- **Do NOT add explicit `file.close()` calls** for local `FsFile` variables — the destructor handles it
|
||||
- Explicit `close()` is still required in these cases:
|
||||
1. **Close before delete**: Must close before `Storage.remove()` on the same path
|
||||
2. **Close before reopen**: Must close before reopening the same `FsFile` variable (e.g., write then reopen for read, or rewrite the same path)
|
||||
3. **Member variables**: `FsFile` members persist beyond any single function scope, so close at the intended release point (e.g., in `onExit()`)
|
||||
|
||||
**SINGLE_BUFFER_MODE implications**:
|
||||
- Only ONE framebuffer exists (not double-buffered)
|
||||
- Grayscale rendering requires temporary buffer allocation (`renderer.storeBwBuffer()`)
|
||||
- Must call `renderer.restoreBwBuffer()` to free temporary buffers
|
||||
- See [lib/GfxRenderer/GfxRenderer.cpp:439-440](../lib/GfxRenderer/GfxRenderer.cpp) for malloc usage
|
||||
|
||||
### Directory Structure
|
||||
* lib/: Internal libraries (Epub engine, GfxRenderer, UITheme, I18n)
|
||||
* lib/hal/: Hardware Abstraction Layer (HalDisplay, HalGPIO, HalStorage)
|
||||
* lib/I18n/: Internationalization (translations in `translations/*.yaml`, generated string tables)
|
||||
* src/activities/: UI logic using the Activity Lifecycle (onEnter, loop, onExit)
|
||||
* open-x4-sdk/: Low-level SDK (EInkDisplay, InputManager, BatteryMonitor, SDCardManager)
|
||||
* .crosspoint/: SD-based binary cache for EPUB metadata and pre-rendered layout sections
|
||||
|
||||
### Hardware Abstraction Layer (HAL)
|
||||
|
||||
**CRITICAL**: Always use HAL classes, NOT SDK classes directly.
|
||||
|
||||
| HAL Class | Wraps SDK Class | Purpose | Singleton Macro |
|
||||
|-----------|----------------|---------|-----------------|
|
||||
| `HalDisplay` | `EInkDisplay` | E-ink display control | *(none)* |
|
||||
| `HalGPIO` | `InputManager` | Button input handling | *(none)* |
|
||||
| `HalStorage` | `SDCardManager` | SD card file I/O | `Storage` |
|
||||
|
||||
**Location**: [lib/hal/](../lib/hal/)
|
||||
|
||||
**Why HAL?**
|
||||
- Provides consistent error logging per module
|
||||
- Abstracts SDK implementation details
|
||||
- Centralizes resource management
|
||||
|
||||
**Example - HalStorage**:
|
||||
```cpp
|
||||
#include <HalStorage.h>
|
||||
|
||||
// Use Storage singleton (defined via macro)
|
||||
FsFile file;
|
||||
if (Storage.openFileForRead("MODULE", "/path/to/file.bin", file)) {
|
||||
// Read from file
|
||||
// No file.close() needed — DESTRUCTOR_CLOSES_FILE=1 handles it at scope exit
|
||||
}
|
||||
```
|
||||
|
||||
**Usage**: See example above. Uses `FsFile` (SdFat), NOT Arduino `File`. Do NOT add `file.close()` for local variables (see DESTRUCTOR_CLOSES_FILE above).
|
||||
|
||||
---
|
||||
|
||||
## Coding Standards
|
||||
|
||||
### Naming Conventions
|
||||
* Classes: PascalCase (e.g., EpubReaderActivity)
|
||||
* Methods/Variables: camelCase (e.g., renderPage())
|
||||
* Constants: UPPER_SNAKE_CASE (e.g., MAX_BUFFER_SIZE)
|
||||
* Private Members: memberVariable (no prefix)
|
||||
* File Names: Match Class names (e.g., EpubReaderActivity.cpp)
|
||||
|
||||
### Header Guards
|
||||
* Use #pragma once for all header files.
|
||||
|
||||
### Memory Safety and RAII
|
||||
* Smart Pointers: Prefer std::unique_ptr. Avoid std::shared_ptr (unnecessary atomic overhead for a single-core RISC-V).
|
||||
* RAII: Use destructors for cleanup. Call `vTaskDelete()` explicitly for deterministic task release. Do NOT call `file.close()` on local `FsFile` variables — `DESTRUCTOR_CLOSES_FILE=1` handles it at scope exit (see Critical Build Flags).
|
||||
|
||||
### ESP32-C3 Platform Pitfalls
|
||||
|
||||
#### `std::string_view` and Null Termination
|
||||
`string_view` is *not* null-terminated. Passing `.data()` to any C-style API (`drawText`, `snprintf`, `strcmp`, SdFat file paths) is undefined behaviour when the view is a substring or a view of a non-null-terminated buffer.
|
||||
|
||||
**Rule**: `string_view` is safe only when passing to C++ APIs that accept `string_view`. For any C API boundary, convert explicitly:
|
||||
```cpp
|
||||
// WRONG - undefined behaviour if view is a substring:
|
||||
renderer.drawText(font, x, y, myView.data(), true);
|
||||
|
||||
// CORRECT - guaranteed null-terminated:
|
||||
renderer.drawText(font, x, y, std::string(myView).c_str(), true);
|
||||
|
||||
// CORRECT - for short strings, use a stack buffer:
|
||||
char buf[64];
|
||||
snprintf(buf, sizeof(buf), "%.*s", (int)myView.size(), myView.data());
|
||||
```
|
||||
|
||||
#### `IRAM_ATTR` and Flash Cache Safety
|
||||
All code runs from flash via the instruction cache. During SPI flash operations (OTA write, SPIFFS commit, NVS update) the cache is briefly suspended. Any code that can execute during this window — ISRs in particular — must reside in IRAM or it will crash silently.
|
||||
|
||||
```cpp
|
||||
// ISR handler: must be in IRAM
|
||||
void IRAM_ATTR gpioISR() { ... }
|
||||
|
||||
// Data accessed from IRAM_ATTR code: must be in DRAM, never a flash const
|
||||
static DRAM_ATTR uint32_t isrEventFlags = 0;
|
||||
```
|
||||
|
||||
**Rules**:
|
||||
- All ISR handlers: `IRAM_ATTR`
|
||||
- Data read by `IRAM_ATTR` code: `DRAM_ATTR` (a flash-resident `static const` will fault)
|
||||
- Normal task code does **not** need `IRAM_ATTR`
|
||||
|
||||
#### ISR vs Task Shared State
|
||||
`xSemaphoreTake()` (mutex) **cannot** be called from ISR context — it will crash. Use the correct primitive for each communication direction:
|
||||
|
||||
| Direction | Correct primitive |
|
||||
|---|---|
|
||||
| ISR → task (data) | `xQueueSendFromISR()` + `portYIELD_FROM_ISR()` |
|
||||
| ISR → task (signal) | `xSemaphoreGiveFromISR()` + `portYIELD_FROM_ISR()` |
|
||||
| Task → task | `xSemaphoreTake()` / mutex |
|
||||
| Simple flag (single writer ISR) | `volatile bool` + `portENTER_CRITICAL_ISR()` |
|
||||
|
||||
#### RISC-V Alignment
|
||||
ESP32-C3 faults on unaligned multi-byte loads. Never cast a `uint8_t*` buffer to a wider pointer type and dereference it directly. Use `memcpy` for any unaligned read:
|
||||
|
||||
```cpp
|
||||
// WRONG — faults if buf is not 4-byte aligned:
|
||||
uint32_t val = *reinterpret_cast<const uint32_t*>(buf);
|
||||
|
||||
// CORRECT:
|
||||
uint32_t val;
|
||||
memcpy(&val, buf, sizeof(val));
|
||||
```
|
||||
|
||||
This applies to all cache deserialization code and any raw buffer-to-struct casting. `__attribute__((packed))` structs have the same hazard when accessed via member reference.
|
||||
|
||||
#### Template and `std::function` Bloat
|
||||
Each template instantiation generates a separate binary copy. `std::function<void()>` adds ~2–4 KB per unique signature and heap-allocates its closure. Avoid both in library code and any path called from the render loop:
|
||||
|
||||
```cpp
|
||||
// Avoid — heap-allocating, large binary footprint:
|
||||
std::function<void()> callback;
|
||||
|
||||
// Prefer — zero overhead:
|
||||
void (*callback)() = nullptr;
|
||||
|
||||
// For member function + context (common activity callback pattern):
|
||||
struct Callback { void* ctx; void (*fn)(void*); };
|
||||
```
|
||||
|
||||
When a template is necessary, limit instantiations: use explicit template instantiation in a `.cpp` file to prevent the compiler from generating duplicates across translation units.
|
||||
|
||||
---
|
||||
|
||||
### Error Handling Philosophy
|
||||
|
||||
**Source**: [src/main.cpp:132-143](../src/main.cpp), [lib/GfxRenderer/GfxRenderer.cpp:10](../lib/GfxRenderer/GfxRenderer.cpp)
|
||||
|
||||
**Pattern Hierarchy**:
|
||||
1. **LOG_ERR + return false** (90%): `LOG_ERR("MOD", "Failed: %s", reason); return false;`
|
||||
2. **LOG_ERR + fallback**: `LOG_ERR("MOD", "Unavailable"); useDefault();`
|
||||
3. **assert(false)**: Only for fatal "impossible" states (framebuffer missing)
|
||||
4. **ESP.restart()**: Only for recovery (OTA complete)
|
||||
|
||||
**Rules**: NO exceptions, NO abort(), ALWAYS log before error return
|
||||
|
||||
### Acceptable malloc/free Patterns
|
||||
|
||||
**Source**: [src/activities/home/HomeActivity.cpp:166](../src/activities/home/HomeActivity.cpp), [lib/GfxRenderer/GfxRenderer.cpp:439-440](../lib/GfxRenderer/GfxRenderer.cpp)
|
||||
|
||||
Despite "prefer stack allocation," malloc is acceptable for:
|
||||
1. **Large temporary buffers** (> 256 bytes, won't fit on stack)
|
||||
2. **One-time allocations** during activity initialization
|
||||
3. **Bitmap rendering buffers** (variable size, used briefly)
|
||||
|
||||
**Pattern**:
|
||||
```cpp
|
||||
// Allocate
|
||||
auto* buffer = static_cast<uint8_t*>(malloc(bufferSize));
|
||||
if (!buffer) {
|
||||
LOG_ERR("MODULE", "malloc failed: %d bytes", bufferSize);
|
||||
return false; // Handle allocation failure
|
||||
}
|
||||
|
||||
// Use buffer
|
||||
processData(buffer, bufferSize);
|
||||
|
||||
// Free immediately after use
|
||||
free(buffer);
|
||||
buffer = nullptr;
|
||||
```
|
||||
|
||||
**Rules**:
|
||||
- **ALWAYS check for nullptr** after malloc
|
||||
- **Free immediately** after use (don't hold across multiple operations)
|
||||
- **Set to nullptr** after free (avoid use-after-free)
|
||||
- **Document size**: Comment why stack allocation was rejected
|
||||
|
||||
**Examples in codebase**:
|
||||
- Cover image buffers: [HomeActivity.cpp:166](../src/activities/home/HomeActivity.cpp)
|
||||
- Text chunk buffers: [TxtReaderActivity.cpp:259](../src/activities/reader/TxtReaderActivity.cpp)
|
||||
- Bitmap rendering: [GfxRenderer.cpp:439-440](../lib/GfxRenderer/GfxRenderer.cpp)
|
||||
- OTA update buffer: [OtaUpdater.cpp:40](../src/network/OtaUpdater.cpp)
|
||||
|
||||
---
|
||||
|
||||
## UI and Orientation Guidelines
|
||||
|
||||
### Orientation-Aware Logic
|
||||
* No Hardcoding: Never assume 800 or 480. Use renderer.getScreenWidth() and renderer.getScreenHeight().
|
||||
* Viewable Area: Use renderer.getOrientedViewableTRBL() to stay within physical bezel margins.
|
||||
|
||||
### Logical Button Mapping
|
||||
|
||||
**Source**: [src/MappedInputManager.cpp:20-55](../src/MappedInputManager.cpp)
|
||||
|
||||
Constraint: Physical button positions are fixed on hardware, but their logical functions change based on user settings and screen orientation.
|
||||
|
||||
**Button Categories**:
|
||||
1. **Physical Fixed** (Up/Down side buttons):
|
||||
- `Button::Up` → Always `HalGPIO::BTN_UP`
|
||||
- `Button::Down` → Always `HalGPIO::BTN_DOWN`
|
||||
|
||||
2. **User Remappable** (Front buttons):
|
||||
- `Button::Back` → Maps to `SETTINGS.frontButtonBack` (hardware index)
|
||||
- `Button::Confirm` → Maps to `SETTINGS.frontButtonConfirm`
|
||||
- `Button::Left` → Maps to `SETTINGS.frontButtonLeft`
|
||||
- `Button::Right` → Maps to `SETTINGS.frontButtonRight`
|
||||
|
||||
3. **Reader-Specific** (Page navigation with optional swap):
|
||||
- `Button::PageBack` → Uses side button (swappable via `SETTINGS.sideButtonLayout`)
|
||||
- `Button::PageForward` → Uses side button (swappable)
|
||||
|
||||
**Implementation**:
|
||||
- Activities use **logical buttons** (e.g., `Button::Confirm`)
|
||||
- `MappedInputManager` translates to **physical hardware buttons**
|
||||
- User can remap front buttons in settings
|
||||
- Orientation changes handled separately by renderer coordinate transforms
|
||||
|
||||
**Rule**: Always use `MappedInputManager::Button::*` enums, never raw `HalGPIO::BTN_*` indices (except in ButtonRemapActivity).
|
||||
|
||||
### UITheme (The GUI Macro)
|
||||
* Rule: All UI rendering must go through the GUI macro (UITheme).
|
||||
* Do not hardcode fonts, colors, or positioning. This ensures orientation-aware layout consistency.
|
||||
|
||||
---
|
||||
|
||||
## Common Patterns
|
||||
|
||||
### Singleton Access
|
||||
**Available Singletons**:
|
||||
```cpp
|
||||
#define SETTINGS CrossPointSettings::getInstance() // User settings
|
||||
#define APP_STATE CrossPointState::getInstance() // Runtime state
|
||||
#define GUI UITheme::getInstance() // Current theme
|
||||
#define Storage HalStorage::getInstance() // SD card I/O
|
||||
#define I18N I18n::getInstance() // Internationalization
|
||||
```
|
||||
|
||||
### Activity Lifecycle and Memory Management
|
||||
|
||||
**Source**: [src/main.cpp:132-143](../src/main.cpp)
|
||||
|
||||
**CRITICAL**: Activities are **heap-allocated** and **deleted on exit**.
|
||||
|
||||
```cpp
|
||||
// main.cpp navigation pattern
|
||||
void exitActivity() {
|
||||
if (currentActivity) {
|
||||
currentActivity->onExit();
|
||||
delete currentActivity; // Activity deleted here!
|
||||
currentActivity = nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
void enterNewActivity(Activity* activity) {
|
||||
currentActivity = activity; // Heap-allocated activity
|
||||
currentActivity->onEnter();
|
||||
}
|
||||
```
|
||||
|
||||
**Memory Implications**:
|
||||
- Activity navigation = `delete` old activity + `new` create next activity
|
||||
- Any memory allocated in `onEnter()` MUST be freed in `onExit()`
|
||||
- FreeRTOS tasks MUST be deleted in `onExit()` before activity destruction
|
||||
- Member `FsFile` handles MUST be closed in `onExit()` (local `FsFile` variables auto-close via destructor)
|
||||
|
||||
**Activity Pattern**:
|
||||
```cpp
|
||||
void onEnter() { Activity::onEnter(); /* alloc: buffer, tasks */ render(); }
|
||||
void loop() { mappedInput.update(); /* handle input */ }
|
||||
void onExit() { /* free: vTaskDelete, free buffer, close member FsFiles */ Activity::onExit(); }
|
||||
```
|
||||
|
||||
**Critical**: Free resources in reverse order. Delete tasks BEFORE activity destruction.
|
||||
|
||||
### FreeRTOS Task Guidelines
|
||||
|
||||
**Source**: [src/activities/util/KeyboardEntryActivity.cpp:45-50](../src/activities/util/KeyboardEntryActivity.cpp)
|
||||
|
||||
**Pattern**: See Activity Lifecycle above. `xTaskCreate(&taskTrampoline, "Name", stackSize, this, 1, &handle)`
|
||||
|
||||
**Stack Sizing** (in BYTES, not words):
|
||||
- **2048**: Simple rendering (most activities)
|
||||
- **4096**: Network, EPUB parsing
|
||||
- Monitor: `uxTaskGetStackHighWaterMark()` if crashes
|
||||
|
||||
**Rules**: Always `vTaskDelete()` in `onExit()` before destruction. Use mutex if shared state.
|
||||
|
||||
### Global Font Loading
|
||||
|
||||
**Source**: [src/main.cpp:40-115](../src/main.cpp)
|
||||
|
||||
**All fonts are loaded as global static objects** at firmware startup:
|
||||
- Noto Serif: 12, 14, 16, 18pt (4 styles each: regular, bold, italic, bold-italic)
|
||||
- Noto Sans: 12, 14, 16, 18pt (4 styles each)
|
||||
- OpenDyslexic: 8, 10, 12, 14pt (4 styles each)
|
||||
- Ubuntu UI fonts: 10, 12pt (2 styles)
|
||||
|
||||
**Total**: ~80+ global `EpdFont` and `EpdFontFamily` objects
|
||||
|
||||
**Compilation Flag**:
|
||||
```cpp
|
||||
#ifndef OMIT_FONTS
|
||||
// Most fonts loaded here
|
||||
#endif
|
||||
```
|
||||
|
||||
**Implications**:
|
||||
- Fonts stored in **Flash** (marked as `static const` in `lib/EpdFont/builtinFonts/`)
|
||||
- Font rendering data cached in **DRAM** when first used
|
||||
- `OMIT_FONTS` can reduce binary size for minimal builds
|
||||
- Font IDs defined in [src/fontIds.h](../src/fontIds.h)
|
||||
|
||||
**Usage**:
|
||||
```cpp
|
||||
#include "fontIds.h"
|
||||
|
||||
renderer.insertFont(FONT_UI_MEDIUM, ui12FontFamily);
|
||||
renderer.drawText(FONT_UI_MEDIUM, x, y, "Hello", true);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Testing and Debugging
|
||||
|
||||
### Build Commands
|
||||
|
||||
**Via CLI**:
|
||||
```bash
|
||||
# Build firmware (default environment)
|
||||
pio run
|
||||
|
||||
# Build and upload to device
|
||||
pio run -t upload
|
||||
|
||||
# Build specific environment
|
||||
pio run -e gh_release
|
||||
|
||||
# Clean build artifacts
|
||||
pio run -t clean
|
||||
|
||||
# Upload filesystem data (if using SPIFFS/LittleFS)
|
||||
pio run -t uploadfs
|
||||
```
|
||||
|
||||
**Via VS Code**:
|
||||
* Use PlatformIO toolbar: Build (✓), Upload (→), Clean (🗑️)
|
||||
* Or Command Palette: `PlatformIO: Build`, `PlatformIO: Upload`, etc.
|
||||
|
||||
### Monitoring and Debugging
|
||||
|
||||
```bash
|
||||
# Enhanced monitor with color/logging (recommended)
|
||||
python3 scripts/debugging_monitor.py
|
||||
|
||||
# Standard PlatformIO monitor
|
||||
pio device monitor
|
||||
|
||||
# Combined upload + monitor
|
||||
pio run -t upload && pio device monitor
|
||||
```
|
||||
|
||||
**Via VS Code**: Click Monitor (🔌) button in PlatformIO toolbar
|
||||
|
||||
### Code Quality
|
||||
|
||||
```bash
|
||||
# Static analysis (cppcheck)
|
||||
pio check
|
||||
|
||||
# Format code (clang-format) - Windows Git Bash
|
||||
find src -name "*.cpp" -o -name "*.h" | xargs clang-format -i
|
||||
|
||||
# Format code (clang-format) - Linux
|
||||
clang-format -i src/**/*.cpp src/**/*.h
|
||||
```
|
||||
|
||||
### Debugging Crashes
|
||||
|
||||
**Common Crash Causes**:
|
||||
|
||||
1. **Out of Memory** (Most common):
|
||||
```cpp
|
||||
LOG_DBG("MEM", "Free heap: %d bytes", ESP.getFreeHeap());
|
||||
```
|
||||
- Monitor heap usage throughout activity lifecycle
|
||||
- Check if large allocations (>10KB) occur before crash
|
||||
- Verify buffers are freed in `onExit()`
|
||||
|
||||
2. **Stack Overflow**:
|
||||
```cpp
|
||||
LOG_DBG("TASK", "Stack high water: %d", uxTaskGetStackHighWaterMark(taskHandle));
|
||||
```
|
||||
- Occurs during deep recursion or large local variables
|
||||
- Increase task stack size in `xTaskCreate()` (2048 → 4096)
|
||||
- Move large buffers to heap with malloc
|
||||
|
||||
3. **Use-After-Free**:
|
||||
- Activity deleted but task still running
|
||||
- Always `vTaskDelete()` in `onExit()` BEFORE activity destruction
|
||||
- Set pointers to `nullptr` after `free()`
|
||||
|
||||
4. **Corrupt Cache Files**:
|
||||
- Delete `.crosspoint/` directory on SD card
|
||||
- Forces clean re-parse of all EPUBs
|
||||
- Check file format versions in [docs/file-formats.md](../docs/file-formats.md)
|
||||
|
||||
5. **Watchdog Timeout**:
|
||||
- Loop/task blocked for >5 seconds
|
||||
- Add `vTaskDelay(1)` in tight loops
|
||||
- Check for blocking I/O operations
|
||||
|
||||
**Verification Steps**:
|
||||
1. Check serial output for stack traces
|
||||
2. Monitor heap with `ESP.getFreeHeap()` before/after operations
|
||||
3. Verify task deletion with task list (`vTaskList()`)
|
||||
4. Test with `LOG_LEVEL=2` (debug logging enabled)
|
||||
|
||||
---
|
||||
|
||||
## Git Workflow and Repository Awareness
|
||||
|
||||
### Repository Detection Protocol
|
||||
|
||||
**CRITICAL**: ALWAYS verify repository context before git operations. This could be:
|
||||
- A **fork** with `origin` pointing to personal repo, `upstream` to main repo
|
||||
- A **direct clone** with `origin` pointing to main repo
|
||||
- Multiple collaborator remotes
|
||||
|
||||
**Verification Commands** (run at session start):
|
||||
```bash
|
||||
# Check current branch
|
||||
git branch --show-current
|
||||
|
||||
# Check all remotes
|
||||
git remote -v
|
||||
|
||||
# Identify main branch name (could be 'main' or 'master')
|
||||
git symbolic-ref refs/remotes/origin/HEAD 2>/dev/null | sed 's@^refs/remotes/origin/@@'
|
||||
|
||||
# Check working tree status
|
||||
git status --short
|
||||
```
|
||||
|
||||
**Example Output** (forked repository):
|
||||
```text
|
||||
origin https://github.com/<your-username>/crosspoint-reader.git (fetch/push)
|
||||
upstream https://github.com/crosspoint-reader/crosspoint-reader.git (fetch/push)
|
||||
```
|
||||
|
||||
### Git Operation Rules
|
||||
|
||||
1. **Never assume branch names**:
|
||||
```bash
|
||||
# Bad: git push origin main
|
||||
# Good: git push origin $(git branch --show-current)
|
||||
```
|
||||
|
||||
2. **Never assume remote names or write permissions**:
|
||||
- **Forked repos**: Push to `origin` (your fork), submit PR to `upstream`
|
||||
- **Direct contributors**: May push feature branches to `upstream`
|
||||
- **Always ask**: "Should I push to origin or create a PR?"
|
||||
|
||||
3. **Check for upstream changes before starting work**:
|
||||
```bash
|
||||
# Sync fork with upstream (if applicable)
|
||||
git fetch upstream
|
||||
git merge upstream/main # or upstream/master
|
||||
```
|
||||
|
||||
4. **Use explicit remote and branch names**:
|
||||
```bash
|
||||
# Check remotes first
|
||||
git remote -v
|
||||
|
||||
# Use explicit syntax
|
||||
git push <remote> <branch>
|
||||
```
|
||||
|
||||
### Branch Naming Convention
|
||||
|
||||
**For feature/fix branches**:
|
||||
```text
|
||||
feature/<short-description> # New features
|
||||
fix/<issue-number>-<description> # Bug fixes
|
||||
refactor/<component-name> # Code refactoring
|
||||
docs/<topic> # Documentation updates
|
||||
```
|
||||
|
||||
**Examples**:
|
||||
- `feature/sd-download-progress`
|
||||
- `fix/123-orientation-crash`
|
||||
- `refactor/hal-storage`
|
||||
|
||||
### Commit Message Format
|
||||
|
||||
**Pattern**:
|
||||
```text
|
||||
<type>: <short summary (50 chars max)>
|
||||
|
||||
<optional detailed description>
|
||||
|
||||
```
|
||||
|
||||
**Types**: `feat`, `fix`, `refactor`, `docs`, `test`, `chore`, `perf`
|
||||
|
||||
**Example**:
|
||||
```text
|
||||
feat: add real-time SD download progress bar
|
||||
|
||||
Implements progress tracking for book downloads using
|
||||
UITheme progress bar component with heap-safe updates.
|
||||
|
||||
Tested in all 4 orientations with 5MB+ files.
|
||||
```
|
||||
|
||||
### When to Commit
|
||||
|
||||
**DO commit when**:
|
||||
- User explicitly requests: "commit these changes"
|
||||
- Feature is complete and tested on device
|
||||
- Bug fix is verified working
|
||||
- Refactoring preserves all functionality
|
||||
- All tests pass (`pio run` succeeds)
|
||||
|
||||
**DO NOT commit when**:
|
||||
- Changes are untested on actual hardware
|
||||
- Build fails or has warnings
|
||||
- Experimenting or debugging in progress
|
||||
- User hasn't explicitly requested commit
|
||||
- Files excluded by `.gitignore` would be included — always run `git status` and cross-check against `.gitignore` before staging (e.g., `*.generated.h`, `.pio/`, `compile_commands.json`, `platformio.local.ini`)
|
||||
|
||||
**Rule**: **If uncertain, ASK before committing.**
|
||||
|
||||
---
|
||||
|
||||
## Generated Files and Build Artifacts
|
||||
|
||||
### Files Generated by Build Scripts
|
||||
|
||||
**NEVER manually edit these files** - they are regenerated automatically:
|
||||
|
||||
1. **HTML Headers** (generated by `scripts/build_html.py`):
|
||||
- `src/network/html/*.generated.h`
|
||||
- **Source**: HTML templates in `data/html/` directory
|
||||
- **Triggered**: During PlatformIO `pre:` build step
|
||||
- **To modify**: Edit source HTML in `data/html/`, not generated headers
|
||||
|
||||
2. **I18n Headers** (generated by `scripts/gen_i18n.py`):
|
||||
- `lib/I18n/I18nKeys.h`, `lib/I18n/I18nStrings.h`, `lib/I18n/I18nStrings.cpp`
|
||||
- **Source**: YAML translation files in `lib/I18n/translations/` (one per language)
|
||||
- **To modify**: Edit source YAML files, then run `python scripts/gen_i18n.py lib/I18n/translations lib/I18n/`
|
||||
- **Commit**: Source YAML files only. All three generated files (`I18nKeys.h`, `I18nStrings.h`, `I18nStrings.cpp`) are in `.gitignore` and regenerated at build time.
|
||||
|
||||
3. **Build Artifacts** (in `.gitignore`):
|
||||
- `.pio/` - PlatformIO build output
|
||||
- `build/` - Compiled binaries
|
||||
- `*.generated.h` - Any auto-generated headers
|
||||
- `compile_commands.json` - LSP/IDE metadata
|
||||
|
||||
### Modifying Generated Content Workflow
|
||||
|
||||
**To change HTML pages**:
|
||||
1. Edit source: `data/html/<pagename>.html`
|
||||
2. Build: `pio run` (auto-triggers `scripts/build_html.py`)
|
||||
3. Generated headers update: `src/network/html/<pagename>Html.generated.h`
|
||||
4. **Commit ONLY** source HTML, NOT generated `.generated.h` files
|
||||
|
||||
**To add/modify translations (i18n)**:
|
||||
1. Edit or add YAML file: `lib/I18n/translations/<language>.yaml`
|
||||
- Each file must contain: `_language_name`, `_language_code`, `_order`, and `STR_*` keys
|
||||
- English (`english.yaml`) is the reference; missing keys in other languages fall back to English
|
||||
2. Run generator: `python scripts/gen_i18n.py lib/I18n/translations lib/I18n/`
|
||||
3. Generated files update: `I18nKeys.h`, `I18nStrings.h`, `I18nStrings.cpp`
|
||||
4. **Commit** source YAML files only. All three generated files are in `.gitignore` and regenerated at build time.
|
||||
|
||||
**To use translated strings in code**:
|
||||
```cpp
|
||||
#include <I18n.h>
|
||||
// Use tr() macro with StrId enum (defined in generated I18nKeys.h)
|
||||
renderer.drawText(FONT_UI, x, y, tr(STR_LOADING), true);
|
||||
```
|
||||
|
||||
**To add custom fonts**:
|
||||
1. Place source fonts in `lib/EpdFont/fontsrc/` (gitignored)
|
||||
2. Run conversion script (see `lib/EpdFont/README`)
|
||||
3. Update global font objects in `src/main.cpp:40-115`
|
||||
4. Add font ID constant to `src/fontIds.h`
|
||||
|
||||
---
|
||||
|
||||
## Local Development Configuration
|
||||
|
||||
### platformio.local.ini (Personal Overrides)
|
||||
|
||||
**Purpose**: Personal development settings that should NEVER be committed.
|
||||
|
||||
**Use Cases**:
|
||||
- Serial port configuration (varies by machine)
|
||||
- Debug flags for specific testing
|
||||
- Local build optimizations
|
||||
- Developer-specific paths
|
||||
|
||||
**Example** `platformio.local.ini`:
|
||||
```ini
|
||||
# platformio.local.ini (gitignored)
|
||||
[env:default]
|
||||
upload_port = COM7 # Windows: COMx, Linux: /dev/ttyUSBx
|
||||
monitor_port = COM7
|
||||
|
||||
build_flags =
|
||||
${base.build_flags}
|
||||
-DMY_DEBUG_FLAG=1 # Personal debug flags
|
||||
-DTEST_FEATURE_ENABLED=1
|
||||
```
|
||||
|
||||
**Configuration Hierarchy**:
|
||||
1. `platformio.ini` - **Committed**, shared project settings
|
||||
2. `platformio.local.ini` - **Gitignored**, personal overrides
|
||||
3. Local file extends/overrides base config
|
||||
|
||||
**Rules**:
|
||||
- **NEVER commit** `platformio.local.ini`
|
||||
- **NEVER put** personal info (serial ports, credentials) in main `platformio.ini`
|
||||
- Use `${base.build_flags}` to extend (not replace) base flags
|
||||
|
||||
---
|
||||
|
||||
## Testing and Verification Workflow
|
||||
|
||||
### Testing Checklist
|
||||
|
||||
**AI agent scope** (what you CAN verify):
|
||||
1. ✅ **Build**: `pio run -t clean && pio run` (0 errors/warnings)
|
||||
2. ✅ **Quality**: `pio check` + `find src -name "*.cpp" -o -name "*.h" | xargs clang-format -i`
|
||||
3. ✅ **Format**: Commit messages (`feat:`/`fix:`), no `.gitignore`-excluded files staged (e.g., `*.generated.h`, `.pio/`, `platformio.local.ini`)
|
||||
4. ✅ **CI**: Fix GitHub Actions failures before review
|
||||
5. ✅ **Code review**: Ensure orientation-aware logic is correct in all 4 modes by inspecting switch/case coverage
|
||||
|
||||
**Human tester scope** (flag these for the user):
|
||||
6. 🔲 **Device**: Test on hardware
|
||||
7. 🔲 **Orientations**: Verify all 4 modes (Portrait/Inverted/Landscape CW/CCW)
|
||||
8. 🔲 **Heap**: `ESP.getFreeHeap()` > 50KB, no leaks
|
||||
9. 🔲 **Cache**: If EPUB modified, delete `.crosspoint/` and verify re-parse
|
||||
|
||||
### CI/CD Pipeline Awareness
|
||||
|
||||
**GitHub Actions** run automatically on pull requests:
|
||||
|
||||
| Workflow | File | Purpose |
|
||||
|----------|------|---------|
|
||||
| Build Check | `.github/workflows/ci.yml` | Verifies code compiles |
|
||||
| Format Check | `.github/workflows/pr-formatting-check.yml` | Validates clang-format |
|
||||
| Release Build | `.github/workflows/release.yml` | Production releases |
|
||||
| RC Build | `.github/workflows/release_candidate.yml` | Release candidates |
|
||||
|
||||
**Rules**:
|
||||
- **Fix CI failures BEFORE** requesting review
|
||||
- CI runs on: Push to PR, PR updates
|
||||
- Format check fails → Run clang-format locally
|
||||
- Build check fails → Fix compile errors
|
||||
|
||||
---
|
||||
|
||||
## Serial Monitoring and Live Debugging
|
||||
|
||||
### Serial Monitor Options
|
||||
|
||||
1. **Enhanced**: `python3 scripts/debugging_monitor.py` (color-coded, recommended)
|
||||
2. **Standard**: `pio device monitor` (basic, no colors)
|
||||
3. **VS Code**: Monitor (🔌) button (IDE-integrated)
|
||||
|
||||
### Live Debugging Patterns
|
||||
|
||||
**Heap**: `LOG_DBG("MEM", "Free: %d", ESP.getFreeHeap());` (every 5s in loop)
|
||||
**Stack**: `uxTaskGetStackHighWaterMark(nullptr)` (< 512 bytes → increase stack)
|
||||
**Flush**: `logSerial.flush();` (force output before crash)
|
||||
|
||||
**Port Detection**: Windows: `mode` | Linux: `ls /dev/ttyUSB* /dev/ttyACM*` or `dmesg | grep tty`
|
||||
|
||||
---
|
||||
|
||||
## Cache Management and Invalidation
|
||||
|
||||
### Cache Structure on SD Card
|
||||
|
||||
**Location**: `.crosspoint/` directory on SD card root
|
||||
|
||||
**Structure**: `.crosspoint/epub_<hash>/{book.bin, progress.bin, cover.bmp, sections/*.bin}`
|
||||
|
||||
**Hash**: `std::hash<std::string>{}(filepath)` → Moving/renaming file = new hash = lost progress
|
||||
|
||||
### Cache Invalidation Rules
|
||||
|
||||
**Cache is automatically invalidated when**:
|
||||
1. **File format version changes** (see `docs/file-formats.md`)
|
||||
- `book.bin` version number incremented
|
||||
- `section.bin` version number incremented
|
||||
2. **Render settings change**:
|
||||
- Font family or size (`SETTINGS.fontFamily`, `SETTINGS.fontSize`)
|
||||
- Line spacing (`SETTINGS.lineSpacing`)
|
||||
- Paragraph spacing (`SETTINGS.extraParagraphSpacing`)
|
||||
- Screen margins (`SETTINGS.screenMargin`)
|
||||
3. **Viewport dimensions change**:
|
||||
- Screen orientation change
|
||||
- Display resolution change
|
||||
4. **Book file modified**:
|
||||
- Moved, renamed, or content changed (new hash)
|
||||
|
||||
**Manual Cache Clear** (safe operations):
|
||||
```bash
|
||||
# Delete ALL caches (forces full regeneration)
|
||||
rm -rf /path/to/sd/.crosspoint/
|
||||
|
||||
# Delete specific book cache
|
||||
rm -rf /path/to/sd/.crosspoint/epub_<hash>/
|
||||
|
||||
# Keep progress, delete only rendered sections
|
||||
rm -rf /path/to/sd/.crosspoint/epub_<hash>/sections/
|
||||
```
|
||||
|
||||
**When to Clear Cache**:
|
||||
- EPUB parsing errors after code changes to `lib/Epub/`
|
||||
- Corrupt rendering (missing text, wrong layout)
|
||||
- Testing cache generation logic
|
||||
- After modifying:
|
||||
- `lib/Epub/Epub/Section.cpp`
|
||||
- `lib/Epub/Epub/BookMetadataCache.cpp`
|
||||
- Render settings in `CrossPointSettings`
|
||||
|
||||
### Cache File Format Versioning
|
||||
|
||||
**Source**: `lib/Epub/Epub/Section.cpp`, `lib/Epub/Epub/BookMetadataCache.cpp`
|
||||
|
||||
**Current Versions** (as of docs/file-formats.md):
|
||||
- `book.bin`: **Version 5** (metadata structure)
|
||||
- `section.bin`: **Version 12** (layout structure)
|
||||
|
||||
**Version Increment Rules**:
|
||||
1. **ALWAYS increment version** BEFORE changing binary structure
|
||||
2. Version mismatch → Cache auto-invalidated and regenerated
|
||||
3. Document format changes in `docs/file-formats.md`
|
||||
|
||||
**Example** (incrementing section format version):
|
||||
```cpp
|
||||
// lib/Epub/Epub/Section.cpp
|
||||
static constexpr uint8_t SECTION_FILE_VERSION = 13; // Was 12, now 13
|
||||
|
||||
// Add new field to structure
|
||||
struct PageLine {
|
||||
// ... existing fields ...
|
||||
uint16_t newField; // New field added
|
||||
};
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
Philosophy: We are building a dedicated e-reader, not a Swiss Army knife. If a feature adds RAM pressure without significantly improving the reading experience, it is Out of Scope.
|
||||
@@ -1,102 +1,169 @@
|
||||
# CrossPoint Reader
|
||||
|
||||
Firmware for the **Xteink X4** e-paper display reader (unaffiliated with Xteink).
|
||||
Built using **PlatformIO** and targeting the **ESP32-C3** microcontroller.
|
||||
CrossPoint is open-source e-reader firmware - community-built, fully hackable, free forever. It's maintained by a growing community of developers and readers who believe your device should do what you want - not what a manufacturer decided for you.
|
||||
|
||||
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.
|
||||
**Now running on:** ESP32C3-based Xteink [X4](https://www.xteink.com/products/xteink-x4) and [X3](https://www.xteink.com/products/xteink-x3).
|
||||
|
||||

|
||||

|
||||
|
||||
## Motivation
|
||||
## What can CrossPoint do?
|
||||
|
||||
E-paper devices are fantastic for reading, but most commercially available readers are closed systems with limited
|
||||
customisation. The **Xteink X4** is an affordable, e-paper device, however the official firmware remains closed.
|
||||
CrossPoint exists partly as a fun side-project and partly to open up the ecosystem and truely unlock the device's
|
||||
potential.
|
||||
- **Reader engine**: EPUB 2/3 rendering with embedded-style option, image handling, hyphenation, kerning, chapter navigation, footnotes, go-to-percent, auto page turn, orientation control, focus reading, KOReader progress sync and more.
|
||||
|
||||
CrossPoint Reader aims to:
|
||||
* Provide a **fully open-source alternative** to the official firmware.
|
||||
* Offer a **document reader** capable of handling EPUB content on constrained hardware.
|
||||
* Support **customisable font, layout, and display** options.
|
||||
* Run purely on the **Xteink X4 hardware**.
|
||||
- **Various formats**: native handling for `.epub`, `.xtc/.xtch`, `.txt`, and `.bmp`.
|
||||
|
||||
This project is **not affiliated with Xteink**; it's built as a community project.
|
||||
- **Screenshots.**
|
||||
|
||||
## Features & Usage
|
||||
- **Custom fonts**: install your favorite fonts on the SD card.
|
||||
|
||||
- [x] EPUB parsing and rendering (EPUB 2 and EPUB 3)
|
||||
- [ ] Image support within EPUB
|
||||
- [x] Saved reading position
|
||||
- [x] File explorer with file picker
|
||||
- [x] Basic EPUB picker from root directory
|
||||
- [x] Support nested folders
|
||||
- [ ] EPUB picker with cover art
|
||||
- [x] Custom sleep screen
|
||||
- [x] Cover sleep screen
|
||||
- [x] Wifi book upload
|
||||
- [x] Wifi OTA updates
|
||||
- [x] Configurable font, layout, and display options
|
||||
- [ ] User provided fonts
|
||||
- [ ] Full UTF support
|
||||
- [x] Screen rotation
|
||||
- **Tilt page turn (X3 only)**.
|
||||
|
||||
Multi-language support: Read EPUBs in various languages, including English, Spanish, French, German, Italian, Portuguese, Russian, Ukrainian, Polish, Swedish, Norwegian, [and more](./USER_GUIDE.md#supported-languages).
|
||||
- **Library workflow**: folder browser, hidden-file toggle, long-press delete, recent books, SD-cache management.
|
||||
|
||||
See [the user guide](./USER_GUIDE.md) for instructions on operating CrossPoint.
|
||||
- **Wireless workflows**:
|
||||
|
||||
- File transfer web UI
|
||||
- EPUB Optimizer
|
||||
- Web settings UI/API (edit many device settings from browser)
|
||||
- WebSocket fast uploads
|
||||
- WebDAV handler
|
||||
- AP mode (hotspot) and STA mode (join existing WiFi), both with QR helpers
|
||||
- Calibre wireless connect flow
|
||||
- OPDS browser with saved servers (up to 8), search, pagination, and direct download
|
||||
- OTA update checks and installs from GitHub releases
|
||||
|
||||
For more details about the scope of the project, see the [SCOPE.md](SCOPE.md) document.
|
||||
- **Customization**: multiple themes (Classic, Lyra, Lyra Extended, RoundedRaff), sleep screen modes, front/side button remapping, status bar controls, power-button behavior, refresh cadence, and more.
|
||||
|
||||
## Installing
|
||||
- **Localization**: 22 UI languages and counting.
|
||||
|
||||
### Web (latest firmware)
|
||||
### Coming soon:
|
||||
|
||||
1. Connect your Xteink X4 to your computer via USB-C and wake/unlock the device
|
||||
2. Go to https://xteink.dve.al/ and click "Flash CrossPoint firmware"
|
||||
- RTL support — Arabic, Hebrew, and Farsi.
|
||||
|
||||
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.
|
||||
- Bookmarks.
|
||||
|
||||
### Web (specific firmware version)
|
||||
- Dictionary lookup — inline word lookup without leaving the reader.
|
||||
|
||||
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/crosspoint-reader/crosspoint-reader/releases)
|
||||
3. Go to https://xteink.dve.al/ and flash the firmware file using the "OTA fast flash controls" section
|
||||
- More themes.
|
||||
|
||||
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.
|
||||
- Much more! stay tuned.
|
||||
|
||||
---
|
||||
|
||||
## USB-locked devices (Xteink Unlocker)
|
||||
|
||||
Some Xteink units purchased from third-party stores (e.g. AliExpress) ship with USB flashing locked from the factory.
|
||||
If your device is locked, you will need to use the **Xteink Unlocker** tool available at
|
||||
https://crosspointreader.com/#unlock-tool before you can flash CrossPoint.
|
||||
|
||||
**You do not need this tool if you bought your device directly from xteink.com.** Those units are not locked.
|
||||
|
||||
**Not sure if your device is locked?** Power it on, connect the USB-C cable, and try flashing via the web flasher first (see
|
||||
[Install firmware](#install-firmware) below). If the browser's serial device picker does not show your device, try a different
|
||||
USB port or browser before assuming the device is locked. Only reach for the unlocker if the device still doesn't appear.
|
||||
|
||||
> ### ⚠️ WARNING: READ THIS BEFORE USING THE UNLOCKER ⚠️
|
||||
>
|
||||
> **The only officially supported firmwares in the unlock tool are CrossPoint and CrossInk.**
|
||||
>
|
||||
> Flashing any other firmware on a USB-locked device may **permanently brick the device** or leave it **permanently
|
||||
> stuck on that firmware with no recovery path**. Once USB flashing is re-locked, your only way back is via OTA, and if
|
||||
> the firmware you flashed doesn't support OTA, **there is no way out**.
|
||||
>
|
||||
> **The Papyrix fork has removed OTA update support from its code.** If you flash Papyrix onto a
|
||||
> USB-locked unit, you will have **zero update or recovery path** and will be stuck on it forever. **Do not flash
|
||||
> Papyrix (or any other unsupported firmware) on a locked device.**
|
||||
|
||||
## Install firmware
|
||||
|
||||
### Web installer (recommended)
|
||||
|
||||
1. Connect your device to your computer via USB-C and wake/unlock the device
|
||||
2. Go to https://crosspointreader.com/#flash-tools, select device (X3 or X4), and choose an official CrossPoint release.
|
||||
|
||||
### Web installer (specific version)
|
||||
|
||||
1. Connect your device to your computer via USB-C and wake/unlock the device
|
||||
2. Download a `firmware.bin` from [Releases](https://github.com/crosspoint-reader/crosspoint-reader/releases), local build, or continuous integration artifact.
|
||||
3. Go to https://crosspointreader.com/#flash-tools, select device (X3 or X4), click "Custom .bin" and upload a `firmware.bin`.
|
||||
|
||||
### Revert to Official Firmware
|
||||
|
||||
To revert to the official firmware, you can also flash the latest official firmware using https://crosspointreader.com/#flash-tools.
|
||||
|
||||
### Command line
|
||||
|
||||
1. Install [`esptool`](https://github.com/espressif/esptool):
|
||||
|
||||
```bash
|
||||
pip install esptool
|
||||
```
|
||||
|
||||
2. Download `firmware.bin` from the [releases page](https://github.com/crosspoint-reader/crosspoint-reader/releases).
|
||||
3. Connect your device via USB-C.
|
||||
4. Find the device port. On Linux, run `dmesg` after connecting. On macOS:
|
||||
|
||||
```bash
|
||||
log stream --predicate 'subsystem == "com.apple.iokit"' --info
|
||||
```
|
||||
|
||||
5. Flash:
|
||||
|
||||
```bash
|
||||
esptool.py --chip esp32c3 --port /dev/ttyACM0 --baud 921600 write_flash 0x10000 /path/to/firmware.bin
|
||||
```
|
||||
|
||||
Adjust `/dev/ttyACM0` to match your system.
|
||||
|
||||
### Manual
|
||||
|
||||
See [Development](#development) below.
|
||||
See [Development quick start](#development-quick-start) below.
|
||||
|
||||
## Development
|
||||
---
|
||||
|
||||
## Documentation
|
||||
|
||||
- [User Guide](./USER_GUIDE.md)
|
||||
- [Web server usage](./docs/webserver.md)
|
||||
- [Web server endpoints](./docs/webserver-endpoints.md)
|
||||
- [Project scope](./SCOPE.md)
|
||||
- [Contributing docs](./docs/contributing/README.md)
|
||||
|
||||
---
|
||||
|
||||
## Development quick start
|
||||
|
||||
### Prerequisites
|
||||
|
||||
* **PlatformIO Core** (`pio`) or **VS Code + PlatformIO IDE**
|
||||
* Python 3.8+
|
||||
* USB-C cable for flashing the ESP32-C3
|
||||
* Xteink X4
|
||||
- [pioarduino](https://github.com/pioarduino/pioarduino) or VS Code + pioarduino plugin
|
||||
- Python 3.8+
|
||||
- `clang-format` 21
|
||||
- USB-C cable supporting data transfer
|
||||
|
||||
### Checking out the code
|
||||
### Setup
|
||||
|
||||
CrossPoint uses PlatformIO for building and flashing the firmware. To get started, clone the repository:
|
||||
|
||||
```
|
||||
```bash
|
||||
git clone --recursive https://github.com/crosspoint-reader/crosspoint-reader
|
||||
cd crosspoint-reader
|
||||
|
||||
# Or, if you've already cloned without --recursive:
|
||||
# if cloned without --recursive:
|
||||
git submodule update --init --recursive
|
||||
```
|
||||
|
||||
### Flashing your device
|
||||
### Build / flash / monitor
|
||||
|
||||
Connect your Xteink X4 to your computer via USB-C and run the following command.
|
||||
|
||||
```sh
|
||||
```bash
|
||||
pio run --target upload
|
||||
```
|
||||
|
||||
### Contributor pre-PR checks
|
||||
|
||||
```bash
|
||||
./bin/clang-format-fix
|
||||
pio check -e default
|
||||
pio run -e default
|
||||
```
|
||||
|
||||
### Debugging
|
||||
|
||||
After flashing the new features, it’s recommended to capture detailed logs from the serial port.
|
||||
@@ -106,7 +173,9 @@ First, make sure all required Python packages are installed:
|
||||
```python
|
||||
python3 -m pip install pyserial colorama matplotlib
|
||||
```
|
||||
after that run the script:
|
||||
|
||||
After that run the script:
|
||||
|
||||
```sh
|
||||
# For Linux
|
||||
# This was tested on Debian and should work on most Linux systems.
|
||||
@@ -115,61 +184,72 @@ python3 scripts/debugging_monitor.py
|
||||
# For macOS
|
||||
python3 scripts/debugging_monitor.py /dev/cu.usbmodem2101
|
||||
```
|
||||
|
||||
Minor adjustments may be required for Windows.
|
||||
|
||||
---
|
||||
|
||||
## Internals
|
||||
|
||||
CrossPoint Reader is pretty aggressive about caching data down to the SD card to minimise RAM usage. The ESP32-C3 only
|
||||
has ~380KB of usable RAM, so we have to be careful. A lot of the decisions made in the design of the firmware were based
|
||||
on this constraint.
|
||||
CrossPoint Reader is pretty aggressive about caching data down to the SD card to minimise RAM usage. The ESP32-C3 only has ~380KB of usable RAM, so we have to be careful. A lot of the decisions made in the design of the firmware were based on this constraint.
|
||||
|
||||
### Data caching
|
||||
|
||||
The first time chapters of a book are loaded, they are cached to the SD card. Subsequent loads are served from the
|
||||
cache. This cache directory exists at `.crosspoint` on the SD card. The structure is as follows:
|
||||
|
||||
|
||||
```
|
||||
```text
|
||||
.crosspoint/
|
||||
├── epub_12471232/ # Each EPUB is cached to a subdirectory named `epub_<hash>`
|
||||
│ ├── progress.bin # Stores reading progress (chapter, page, etc.)
|
||||
│ ├── cover.bmp # Book cover image (once generated)
|
||||
│ ├── book.bin # Book metadata (title, author, spine, table of contents, etc.)
|
||||
│ └── sections/ # All chapter data is stored in the sections subdirectory
|
||||
│ ├── 0.bin # Chapter data (screen count, all text layout info, etc.)
|
||||
│ ├── 1.bin # files are named by their index in the spine
|
||||
├── epub_<hash>/ # one directory per book, named by content hash
|
||||
│ ├── progress.bin # reading position (chapter, page, etc.)
|
||||
│ ├── cover.bmp # generated cover image
|
||||
│ ├── book.bin # metadata: title, author, spine, TOC
|
||||
│ └── sections/ # per-chapter layout cache
|
||||
│ ├── 0.bin
|
||||
│ ├── 1.bin
|
||||
│ └── ...
|
||||
│
|
||||
└── epub_189013891/
|
||||
```
|
||||
|
||||
Deleting the `.crosspoint` directory will clear the entire cache.
|
||||
|
||||
Due the way it's currently implemented, the cache is not automatically cleared when a book is deleted and moving a book
|
||||
file will use a new cache directory, resetting the reading progress.
|
||||
Removing `/.crosspoint` clears all cached metadata and forces a full regeneration on next open. Note: the cache isn't cleared automatically when you delete a book, and moving a file to a new path resets its reading progress.
|
||||
|
||||
For more details on the internal file structures, see the [file formats document](./docs/file-formats.md).
|
||||
|
||||
---
|
||||
|
||||
## Contributing
|
||||
|
||||
Contributions are very welcome!
|
||||
Contributions are welcome. If you're new to the codebase, start with the [contributing docs](./docs/contributing/README.md). For things to work on, check the [ideas discussion board](https://github.com/crosspoint-reader/crosspoint-reader/discussions/categories/ideas) — leave a comment before starting so we don't duplicate effort.
|
||||
|
||||
If you're looking for a way to help out, take a look at the [ideas discussion board](https://github.com/crosspoint-reader/crosspoint-reader/discussions/categories/ideas).
|
||||
If there's something there you'd like to work on, leave a comment so that we can avoid duplicated effort.
|
||||
|
||||
Everyone here is a volunteer, so please be respectful and patient. For more details on our goverance and community
|
||||
principles, please see [GOVERNANCE.md](GOVERNANCE.md).
|
||||
|
||||
### To submit a contribution:
|
||||
|
||||
1. Fork the repo
|
||||
2. Create a branch (`feature/dithering-improvement`)
|
||||
3. Make changes
|
||||
4. Submit a PR
|
||||
Everyone here is a volunteer, so please be respectful and patient. For governance and community expectations, see [GOVERNANCE.md](./GOVERNANCE.md).
|
||||
|
||||
---
|
||||
|
||||
CrossPoint Reader is **not affiliated with Xteink or any manufacturer of the X4 hardware**.
|
||||
## Community forks
|
||||
|
||||
Huge shoutout to [**diy-esp32-epub-reader** by atomic14](https://github.com/atomic14/diy-esp32-epub-reader), which was a project I took a lot of inspiration from as I
|
||||
was making CrossPoint.
|
||||
One of the best things about open source is that anyone can take the code in a different direction. If you need something outside CrossPoint's [scope](./SCOPE.md), check out the community forks:
|
||||
|
||||
- [CrossInk](https://github.com/uxjulia/CrossInk) — Typography and reading tracking: Bionic Reading (bolds word stems to create fixation points), guide dots between words, improved paragraph indents, and replaces the default fonts with ChareInk/Lexend/Bitter.
|
||||
|
||||
- [papyrix-reader](https://github.com/bigbag/papyrix-reader) — Adds FB2 and MD format support. Actively maintained with Arabic script support. Custom themes via SD card.
|
||||
|
||||
- [crosspet](https://github.com/trilwu/crosspet) — A Vietnamese fork that adds a Tamagotchi-style virtual chicken that grows based on your reading milestones (pages read, streaks, care). Also: Flashcards, Weather, Pomodoro timer, and mini-games.
|
||||
|
||||
- [crosspoint-reader (jpirnay)](https://github.com/jpirnay/crosspoint-reader) — Faster integration of functionality. Tracks upstream PRs and integrates the good ones ahead of the official merge.
|
||||
|
||||
- [crosspoint-reader-cjk](https://github.com/aBER0724/crosspoint-reader-cjk) — Purpose-built for Chinese, Japanese, and Korean reading.
|
||||
|
||||
- [inx](https://github.com/obijuankenobiii/inx) — Completely reimagines the user interface with tabbed navigation.
|
||||
|
||||
- ~~[PlusPoint](https://github.com/ngxson/pluspoint-reader) — custom JS apps support.~~ (Unmaintained)
|
||||
|
||||
- [crosspoint-reader-papers3](https://github.com/juicecultus/crosspoint-reader-papers3) — Crosspoint port for M5Stack Paper S3.
|
||||
|
||||
**Note:** Many of these features will make their way into CrossPoint over time. We maintain a slower pace to ensure rock-solid stability and squash bugs before they reach your device.
|
||||
|
||||
Want to build your own device? Be sure to check out the [de-link](https://github.com/iandchasse/de-link) project.
|
||||
|
||||
---
|
||||
|
||||
CrossPoint Reader is **not affiliated with Xteink or any device manufacturer**.
|
||||
|
||||
Huge shoutout to [diy-esp32-epub-reader](https://github.com/atomic14/diy-esp32-epub-reader), which inspired this project.
|
||||
|
||||
@@ -27,6 +27,12 @@ usability over "swiss-army-knife" functionality.
|
||||
* **Language Support:** E.g. Support for multiple languages both in the reader and in the interfaces.
|
||||
* **Reference Tools:** E.g. Local dictionary lookup. Providing quick, offline definitions to enhance comprehension
|
||||
without breaking focus.
|
||||
* **Clock Display (device dependent):**
|
||||
|
||||
| Device | Scope |
|
||||
| -- | -- |
|
||||
| X3 | The X3 uses a dedicated DS3231 RTC, which maintains accurate time across sleep cycles and can be treated as a reliable wall clock. |
|
||||
| X4 | The X4 relies on the ESP32-C3's internal RTC, which drifts significantly during deep sleep. NTP sync could correct this, with an appropriate user experience around connecting to the internet on wake or on demand. This causes some tension with the **Active Connectivity** section below, so please open a discussion about this UX if it's a feature you would find useful. |
|
||||
|
||||
### Out-of-Scope
|
||||
|
||||
@@ -39,6 +45,12 @@ usability over "swiss-army-knife" functionality.
|
||||
* **Complex Annotation:** No typed out notes. These features are better suited for devices with better input
|
||||
capabilities and more powerful chips.
|
||||
|
||||
### In-scope — Technically Unsupported
|
||||
|
||||
*These features align with CrossPoint's goals but are impractical on the current hardware or produce poor UX.*
|
||||
|
||||
* **PDF Rendering:** PDFs are fixed-layout documents, so rendering them requires displaying pages as images rather than reflowable text — resulting in constant panning and zooming that makes for a poor reading experience on e-ink.
|
||||
|
||||
## 3. Idea Evaluation
|
||||
|
||||
While I appreciate the desire to add new and exciting features to CrossPoint Reader, CrossPoint Reader is designed to be
|
||||
|
||||
+275
-70
@@ -10,12 +10,20 @@ Welcome to the **CrossPoint** firmware. This guide outlines the hardware control
|
||||
- [First Launch](#first-launch)
|
||||
- [3. Screens](#3-screens)
|
||||
- [3.1 Home Screen](#31-home-screen)
|
||||
- [3.2 Book Selection](#32-book-selection)
|
||||
- [3.3 Reading Mode](#33-reading-mode)
|
||||
- [3.4 File Upload Screen](#34-file-upload-screen)
|
||||
- [3.4.1 Calibre Wireless Transfers](#341-calibre-wireless-transfers)
|
||||
- [3.5 Settings](#35-settings)
|
||||
- [3.6 Sleep Screen](#36-sleep-screen)
|
||||
- [3.2 Reading Mode](#32-reading-mode)
|
||||
- [3.3 Browse Files Screen](#33-browse-files-screen)
|
||||
- [3.4 Recent Books Screen](#34-recent-books-screen)
|
||||
- [3.5 File Transfer Screen](#35-file-transfer-screen)
|
||||
- [3.5.1 Calibre Wireless Transfers](#351-calibre-wireless-transfers)
|
||||
- [3.6 Settings](#36-settings)
|
||||
- [3.6.1 Display](#361-display)
|
||||
- [3.6.2 Reader](#362-reader)
|
||||
- [3.6.3 Controls](#363-controls)
|
||||
- [3.6.4 System](#364-system)
|
||||
- [3.6.5 OPDS Servers (Multiple Libraries)](#365-opds-servers-multiple-libraries)
|
||||
- [3.6.6 Web Settings (WiFi + OPDS)](#366-web-settings-wifi--opds)
|
||||
- [3.6.7 KOReader Sync Quick Setup](#367-koreader-sync-quick-setup)
|
||||
- [3.7 Sleep Screen](#37-sleep-screen)
|
||||
- [4. Reading Mode](#4-reading-mode)
|
||||
- [Page Turning](#page-turning)
|
||||
- [Chapter Navigation](#chapter-navigation)
|
||||
@@ -28,7 +36,7 @@ Welcome to the **CrossPoint** firmware. This guide outlines the hardware control
|
||||
|
||||
## 1. Hardware Overview
|
||||
|
||||
The device utilises the standard buttons on the Xtink X4 (in the same layout as the manufacturer firmware, by default):
|
||||
The device utilises the standard buttons on the Xteink X4 (in the same layout as the manufacturer firmware, by default):
|
||||
|
||||
### Button Layout
|
||||
| Location | Buttons |
|
||||
@@ -36,7 +44,12 @@ The device utilises the standard buttons on the Xtink X4 (in the same layout as
|
||||
| **Bottom Edge** | **Back**, **Confirm**, **Left**, **Right** |
|
||||
| **Right Side** | **Power**, **Volume Up**, **Volume Down**, **Reset** |
|
||||
|
||||
Button layout can be customized in **[Settings](#35-settings)**.
|
||||
Button layout can be customized in the **[Controls Settings](#363-controls)**.
|
||||
|
||||
### Taking a Screenshot
|
||||
When the Power Button and Volume Down button are pressed at the same time, it will take a screenshot and save it in the folder `screenshots/`.
|
||||
|
||||
Alternatively, while reading a book, press the **Confirm** button to open the reader menu and select **Take screenshot**.
|
||||
|
||||
---
|
||||
|
||||
@@ -45,9 +58,9 @@ Button layout can be customized in **[Settings](#35-settings)**.
|
||||
### Power On / Off
|
||||
|
||||
To turn the device on or off, **press and hold the Power button for approximately half a second**.
|
||||
In **[Settings](#35-settings)** you can configure the power button to turn the device off with a short press instead of a long one.
|
||||
In the **[Controls Settings](#363-controls)** you can configure the power button to turn the device off with a short press instead of a long one.
|
||||
|
||||
To reboot the device (for example if it's frozen, or after a firmware update), press and release the Reset button, and then quickly press and hold the Power button for a few seconds.
|
||||
To reboot the device (for example after a firmware update or if it's frozen), press and release the Reset button, and then quickly press and hold the Power button for a few seconds.
|
||||
|
||||
### First Launch
|
||||
|
||||
@@ -62,29 +75,34 @@ Upon turning the device on for the first time, you will be placed on the **[Home
|
||||
|
||||
### 3.1 Home Screen
|
||||
|
||||
The Home Screen is the main entry point to the firmware. From here you can navigate to **[Reading Mode](#4-reading-mode)** with the most recently read book, **[Book Selection](#32-book-selection)**, **[Settings](#35-settings)**, or the **[File Upload](#34-file-upload-screen)** screen.
|
||||
The Home screen is the main entry point to the firmware. From here you can navigate to **[Reading Mode](#4-reading-mode)** with the most recently read book, the **[Browse Files](#33-browse-files-screen)** screen, the **[Recent Books](#34-recent-books-screen)** screen, the **[File Transfer](#35-file-transfer-screen)** screen, or **[Settings](#36-settings)**.
|
||||
|
||||
### 3.2 Book Selection
|
||||
|
||||
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. You can also long-press these buttons to scroll a full page up or down.
|
||||
* **Open Selection:** Press **Confirm** to open a folder or read a selected book.
|
||||
|
||||
### 3.3 Reading Mode
|
||||
### 3.2 Reading Mode
|
||||
|
||||
See [Reading Mode](#4-reading-mode) below for more information.
|
||||
|
||||
### 3.4 File Upload Screen
|
||||
### 3.3 Browse Files 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.
|
||||
The Browse Files screen acts as a file and folder 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. You can also long-press these buttons to scroll a full page up or down.
|
||||
* **Open Selection:** Press **Confirm** to open a folder or read a selected book.
|
||||
* **Delete Files:** Hold and release **Confirm** to delete the selected file. You will be given an option to either confirm or cancel deletion. Folder deletion is not supported.
|
||||
|
||||
### 3.4 Recent Books Screen
|
||||
|
||||
The Recent Books screen lists the most recently opened books in a chronological view, displaying title and author.
|
||||
|
||||
### 3.5 File Transfer Screen
|
||||
|
||||
The File Transfer 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.
|
||||
|
||||
> [!TIP]
|
||||
> Advanced users can also manage files programmatically or via the command line using `curl`. See the [webserver docs](./docs/webserver.md) for details.
|
||||
|
||||
### 3.4.1 Calibre Wireless Transfers
|
||||
### 3.5.1 Calibre Wireless Transfers
|
||||
|
||||
CrossPoint supports sending books from Calibre using the CrossPoint Reader device plugin.
|
||||
|
||||
@@ -96,23 +114,26 @@ CrossPoint supports sending books from Calibre using the CrossPoint Reader devic
|
||||
3. Make sure your computer is on the same WiFi network.
|
||||
4. In Calibre, click "Send to device" to transfer books.
|
||||
|
||||
### 3.5 Settings
|
||||
### 3.6 Settings
|
||||
|
||||
The Settings screen allows you to configure the device's behavior. There are a few settings you can adjust:
|
||||
|
||||
#### 3.6.1 Display
|
||||
|
||||
- **Sleep Screen**: Which sleep screen to display when the device sleeps:
|
||||
- "Dark" (default) - The default dark Crosspoint logo sleep screen
|
||||
- "Light" - The same default sleep screen, on a white background
|
||||
- "Custom" - Custom images from the SD card; see [Sleep Screen](#36-sleep-screen) below for more information
|
||||
- "Custom" - Custom images from the SD card; see [Sleep Screen](#37-sleep-screen) below for more information
|
||||
- "Cover" - The book cover image (Note: this is experimental and may not work as expected)
|
||||
- "None" - A blank screen
|
||||
- "Cover + Custom" - The book cover image, fallbacks to "Custom" behavior
|
||||
- "Cover + Custom" - The book cover image, falls back to "Custom" behavior
|
||||
- **Sleep Screen Cover Mode**: How to display the book cover when "Cover" sleep screen is selected:
|
||||
- "Fit" (default) - Scale the image down to fit centered on the screen, padding with white borders as necessary
|
||||
- "Crop" - Scale the image down and crop as necessary to try to to fill the screen (Note: this is experimental and may not work as expected)
|
||||
- **Sleep Screen Cover Filter**: What filter will be applied to the book cover when "Cover" sleep screen is selected
|
||||
- "Crop" - Scale the image down and crop as necessary to try to fill the screen (Note: this is experimental and may not work as expected)
|
||||
- **Sleep Screen Cover Filter**: What filter will be applied to the book cover when "Cover" sleep screen is selected:
|
||||
- "None" (default) - The cover image will be converted to a grayscale image and displayed as it is
|
||||
- "Contrast" - The image will be displayed as a black & white image without grayscale conversion
|
||||
- "Inverted" - The image will be inverted as in white&black and will be displayed without grayscale conversion
|
||||
- "Inverted" - The image will be inverted as in white & black and will be displayed without grayscale conversion
|
||||
- **Status Bar**: Configure the status bar displayed while reading:
|
||||
- "None" - No status bar
|
||||
- "No Progress" - Show status bar without reading progress
|
||||
@@ -120,61 +141,245 @@ The Settings screen allows you to configure the device's behavior. There are a f
|
||||
- "Full w/ Book Bar" - Show status bar with book progress (as bar)
|
||||
- "Book Bar Only" - Show book progress (as bar)
|
||||
- "Full w/ Chapter Bar" - Show status bar with chapter progress (as bar)
|
||||
- **Hide Battery %**: Configure where to suppress the battery pecentage display in the status bar; the battery icon will still be shown:
|
||||
- "Never" - Always show battery percentage (default)
|
||||
- **Hide Battery %**: Configure where to suppress the battery percentage display in the status bar; the battery icon will still be shown:
|
||||
- "Never" (default) - Always show battery percentage
|
||||
- "In Reader" - Show battery percentage everywhere except in reading mode
|
||||
- "Always" - Always hide battery percentage
|
||||
- **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-line indentation.
|
||||
- **Text Anti-Aliasing**: Whether to show smooth grey edges (anti-aliasing) on text in reading mode. Note this slows down page turns slightly.
|
||||
- **Short Power Button Click**: Controls the effect of a short click of the power button:
|
||||
- "Ignore" - Require a long press to turn off the device
|
||||
- "Sleep" - A short press powers the device off
|
||||
- "Page Turn" - A short press in reading mode turns to the next page; a long press turns the device off
|
||||
- **Refresh Frequency**: Set how often the screen does a full refresh while reading to reduce ghosting; options are every 1, 5, 10, 15, or 30 pages.
|
||||
|
||||
- **UI Theme**: Set which UI theme to use:
|
||||
- "Classic" - The original Crosspoint theme
|
||||
- "Lyra" - The new theme for Crosspoint featuring rounded elements and menu icons
|
||||
- "Lyra Extended" - Lyra, but displays 3 books instead of 1 on the **[Home Screen](#31-home-screen)**
|
||||
- **Sunlight Fading Fix**: Configure whether to enable a software-fix for the issue where white X4 models may fade when used in direct sunlight:
|
||||
- "OFF" (default) - Disable the fix
|
||||
- "ON" - Enable the fix
|
||||
|
||||
#### 3.6.2 Reader
|
||||
- **Reader Font Family**: Choose the font used for reading:
|
||||
- "Noto Serif" (default) - Google's serif font
|
||||
- "Noto Sans" - Google's sans-serif font
|
||||
- "Open Dyslexic" - Font designed for readers with dyslexia
|
||||
- **Reader Font Size**: Adjust the text size for reading; options are "Small", "Medium" (default), "Large", or "X Large".
|
||||
|
||||
- **Reader Line Spacing**: Adjust the spacing between lines; options are "Tight", "Normal" (default), or "Wide".
|
||||
- **Reader Screen Margin**: Controls the screen margins in Reading Mode between 5 and 40 pixels in 5-pixel increments.
|
||||
- **Reader Paragraph Alignment**: Set the alignment of paragraphs; options are "Justified" (default), "Left", "Center", or "Right".
|
||||
- **Embedded Style**: Whether to use the EPUB file's embedded HTML and CSS stylisation and formatting; options are "ON" or "OFF".
|
||||
- **Hyphenation**: Whether to hyphenate text in Reading Mode; options are "ON" or "OFF".
|
||||
- **Reading Orientation**: Set the screen orientation for reading EPUB files:
|
||||
- "Portrait" (default) - Standard portrait orientation
|
||||
- "Landscape CW" - Landscape, rotated clockwise
|
||||
- "Inverted" - Portrait, upside down
|
||||
- "Landscape CCW" - Landscape, rotated counter-clockwise
|
||||
- **Front Button Layout**: Configure the order of the bottom edge buttons:
|
||||
- Back, Confirm, Left, Right (default)
|
||||
- Left, Right, Back, Confirm
|
||||
- Left, Back, Confirm, Right
|
||||
- Back, Confirm, Right, Left
|
||||
- **Side Button Layout (reader)**: Swap the order of the up and down volume buttons from Previous/Next to Next/Previous. This change is only in effect when reading.
|
||||
- **Long-press Chapter Skip**: Set whether long-pressing page turn buttons skip to the next/previous chapter.
|
||||
- **Extra Paragraph Spacing**: Set how to handle paragraph breaks:
|
||||
- "ON" - Vertical space will be added between paragraphs in Reading Mode
|
||||
- "OFF" - Paragraphs will not have vertical space added, but will have first-line indentation
|
||||
- **Text Anti-Aliasing**: Whether to show smooth grey edges (anti-aliasing) on text in reading mode. Note this slows down page turns slightly.
|
||||
|
||||
#### 3.6.3 Controls
|
||||
|
||||
- **Remap Front Buttons**: A menu for customising the function of each bottom edge button.
|
||||
- **Side Button Layout (reader)**: Swap the order of the up and down volume buttons from "Prev/Next" (default) to "Next/Prev". This change is only in effect when reading.
|
||||
|
||||
- **Long-press Chapter Skip**: Set whether long-pressing page turn buttons skips to the next/previous chapter:
|
||||
- "Chapter Skip" (default) - Long-pressing skips to next/previous chapter
|
||||
- "Page Scroll" - Long-pressing scrolls a page up/down
|
||||
- Swap the order of the up and down volume buttons from Previous/Next to Next/Previous. This change is only in effect when reading.
|
||||
- **Reader Font Family**: Choose the font used for reading:
|
||||
- "Bookerly" (default) - Amazon's reading font
|
||||
- "Noto Sans" - Google's sans-serif font
|
||||
- "Open Dyslexic" - Font designed for readers with dyslexia
|
||||
- **Reader Font Size**: Adjust the text size for reading; options are "Small", "Medium", "Large", or "X Large".
|
||||
- **Reader Line Spacing**: Adjust the spacing between lines; options are "Tight", "Normal", or "Wide".
|
||||
- **Reader Screen Margin**: Controls the screen margins in reader mode between 5 and 40 pixels in 5 pixel increments.
|
||||
- **Reader Paragraph Alignment**: Set the alignment of paragraphs; options are "Justified" (default), "Left", "Center", or "Right".
|
||||
- **Time to Sleep**: Set the duration of inactivity before the device automatically goes to sleep.
|
||||
- **Refresh Frequency**: Set how often the screen does a full refresh while reading to reduce ghosting.
|
||||
- **Sunlight Fading Fix**: Configure whether to enable a software-fix for the issue where white X4 models may fade when used in direct sunlight
|
||||
- "OFF" (default) - Disable the fix
|
||||
- "ON" - Enable the fix
|
||||
- **OPDS Browser**: Configure OPDS server settings for browsing and downloading books. Set the server URL (for Calibre Content Server, add `/opds` to the end), and optionally configure username and password for servers requiring authentication. Note: Only HTTP Basic authentication is supported. If using Calibre Content Server with authentication enabled, you must set it to use Basic authentication instead of the default Digest authentication.
|
||||
- **Check for updates**: Check for firmware updates over WiFi.
|
||||
- **Short Power Button Click**: Controls the effect of a short click of the power button:
|
||||
- "Ignore" (default) - Require a long press to turn off the device
|
||||
- "Sleep" - A short press puts the device into sleep mode
|
||||
- "Page Turn" - A short press in reading mode turns to the next page; a long press turns the device off
|
||||
|
||||
### 3.6 Sleep Screen
|
||||
#### 3.6.4 System
|
||||
|
||||
You can customize the sleep screen by placing custom images in specific locations on the SD card:
|
||||
- **Time to Sleep**: Set the duration of inactivity before the device automatically goes to sleep; options are 1, 5, 10 (default), 15 or 30 minutes.
|
||||
|
||||
- **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.bmp` file, and one will be randomly selected each time the device sleeps.
|
||||
- **WiFi Networks**: Connect to WiFi networks for file transfers and firmware updates.
|
||||
- **KOReader Sync**: Options for setting up KOReader for syncing book progress.
|
||||
- **OPDS Servers**: Manage one or more OPDS [(Open Publication Distribution System)](https://en.wikipedia.org/wiki/Open_Publication_Distribution_System) libraries for browsing and downloading books. See [OPDS Servers (Multiple Libraries)](#365-opds-servers-multiple-libraries) below.
|
||||
- **Clear Reading Cache**: Clear the internal SD card cache.
|
||||
- **Check for updates**: Check for Crosspoint firmware updates over WiFi.
|
||||
- **Language**: Set the system language (see **[Supported Languages](#supported-languages)** for more information).
|
||||
|
||||
#### 3.6.5 OPDS Servers (Multiple Libraries)
|
||||
|
||||
CrossPoint supports saving multiple OPDS servers and switching between them when browsing catalogs.
|
||||
|
||||
1. Open **Settings -> System -> OPDS Servers**.
|
||||
2. Select **Add Server** to create a new entry, or select an existing server to edit it.
|
||||
3. Configure these fields:
|
||||
- **Server Name**: Optional display name (for example, "Home Calibre" or "Public Catalog").
|
||||
- **OPDS Server URL**: Full catalog root URL (for Calibre Content Server, usually ends with `/opds`).
|
||||
- **Username / Password**: Optional credentials for authenticated servers.
|
||||
4. Use **Delete Server** inside a server entry to remove it.
|
||||
|
||||
Behavior notes:
|
||||
|
||||
- You can store up to 8 OPDS servers.
|
||||
- OPDS authentication supports HTTP Basic auth. If you use Calibre Content Server with authentication enabled, set it to Basic (not Digest).
|
||||
|
||||
You can also manage OPDS servers from the web interface while in File Transfer mode:
|
||||
|
||||
1. Connect to the device web UI.
|
||||
2. Open `http://<device-ip>/settings`.
|
||||
3. Use the **OPDS Servers** card to add, edit, or delete entries.
|
||||
|
||||
For web-based WiFi network management, see [Web Settings (WiFi + OPDS)](#366-web-settings-wifi--opds).
|
||||
|
||||
#### 3.6.6 Web Settings (WiFi + OPDS)
|
||||
|
||||
While in **File Transfer** mode, the web settings page includes management cards for both **WiFi Networks** and **OPDS Servers**.
|
||||
|
||||
1. On device: open **File Transfer** and connect to WiFi.
|
||||
1. In a browser, open `http://<device-ip>/settings` or `http://crosspoint.local`.
|
||||
1. In **WiFi Networks**, add, edit, or delete saved network entries (SSID + optional password).
|
||||
1. In **OPDS Servers**, add, edit, or delete OPDS catalogs.
|
||||
|
||||
Behavior notes:
|
||||
|
||||
- Passwords are never shown back in the web UI after saving.
|
||||
- Leaving Password blank while editing keeps the existing saved password unchanged.
|
||||
- The web UI can save hidden-network SSIDs, but connecting to hidden networks still depends on device-side WiFi connection flow.
|
||||
|
||||
#### 3.6.7 KOReader Sync Quick Setup
|
||||
|
||||
CrossPoint can sync reading progress with KOReader-compatible sync servers.
|
||||
It also interoperates with KOReader apps/devices when they use the same server and credentials.
|
||||
|
||||
##### Option A: Free Public Server (`sync.koreader.rocks`)
|
||||
|
||||
1. Register a user once (only if needed):
|
||||
|
||||
```bash
|
||||
USERNAME="user"
|
||||
PASSWORD="pass"
|
||||
PASSWORD_MD5="$(printf '%s' "$PASSWORD" | openssl md5 | awk '{print $2}')"
|
||||
|
||||
curl -i "https://sync.koreader.rocks/users/create" \
|
||||
-H "Accept: application/vnd.koreader.v1+json" \
|
||||
-H "Content-Type: application/json" \
|
||||
--data "{\"username\":\"$USERNAME\",\"password\":\"$PASSWORD_MD5\"}"
|
||||
```
|
||||
|
||||
Already have KOReader Sync credentials? Skip registration; basic sync only requires using the same existing username/password on all devices.
|
||||
|
||||
When this returns `HTTP 402` with `{"code":2002,"message":"Username is already registered."}`, pick a different username or use that existing account.
|
||||
|
||||
2. On each CrossPoint device:
|
||||
- Go to **Settings -> System -> KOReader Sync**.
|
||||
- Set **Username** and **Password** (enter the plain password; CrossPoint computes MD5 internally, and use the same values on all devices).
|
||||
- Set **Sync Server URL** to `https://sync.koreader.rocks`, or leave it empty (both use the same default KOReader sync server).
|
||||
- Run **Authenticate**.
|
||||
|
||||
3. While reading, press **Confirm** to open the reader menu, then select **Sync Progress**.
|
||||
- Choose **Apply Remote** to jump to remote progress.
|
||||
- Choose **Upload Local** to push current progress.
|
||||
|
||||
##### Option B: Self-Hosted Server (Docker Compose)
|
||||
|
||||
1. Start a sync server:
|
||||
|
||||
```bash
|
||||
mkdir -p kosync-quickstart
|
||||
cd kosync-quickstart
|
||||
|
||||
cat > compose.yaml <<'YAML'
|
||||
services:
|
||||
kosync:
|
||||
image: koreader/kosync:latest
|
||||
ports:
|
||||
- "7200:7200"
|
||||
- "17200:17200"
|
||||
volumes:
|
||||
- ./data/redis:/var/lib/redis
|
||||
environment:
|
||||
- ENABLE_USER_REGISTRATION=true
|
||||
restart: unless-stopped
|
||||
YAML
|
||||
|
||||
# Docker
|
||||
docker compose up -d
|
||||
|
||||
# Podman (alternative)
|
||||
podman compose up -d
|
||||
```
|
||||
|
||||
> [!NOTE]
|
||||
> You'll need to set the **Sleep Screen** setting to **Custom** in order to use these images.
|
||||
> `ENABLE_USER_REGISTRATION=true` is convenient for first setup. After creating your users, set it to `false` (or remove it) to avoid unexpected registrations.
|
||||
|
||||
2. Verify the server:
|
||||
|
||||
```bash
|
||||
curl -H "Accept: application/vnd.koreader.v1+json" "http://<server-ip>:17200/healthcheck"
|
||||
# Expected: {"state":"OK"}
|
||||
```
|
||||
|
||||
3. Register a user once.
|
||||
CrossPoint authenticates against KOReader Sync (`koreader/kosync`) using an MD5 key, so register using the MD5 of your password:
|
||||
|
||||
> [!WARNING]
|
||||
> Sending a reusable MD5-derived password over plain HTTP is insecure.
|
||||
> Create unique sync-only credentials and do not reuse main account passwords.
|
||||
> Prefer `https://<server-ip>:7200` whenever traffic leaves a fully trusted LAN or when using untrusted networks.
|
||||
> Use `curl -k` only for self-signed certificate testing.
|
||||
|
||||
```bash
|
||||
USERNAME="user"
|
||||
PASSWORD="pass"
|
||||
PASSWORD_MD5="$(printf '%s' "$PASSWORD" | openssl md5 | awk '{print $2}')"
|
||||
|
||||
curl -i "http://<server-ip>:17200/users/create" \
|
||||
-H "Accept: application/vnd.koreader.v1+json" \
|
||||
-H "Content-Type: application/json" \
|
||||
--data "{\"username\":\"$USERNAME\",\"password\":\"$PASSWORD_MD5\"}"
|
||||
```
|
||||
|
||||
If this returns `HTTP 402` with `{"code":2002,"message":"Username is already registered."}`, the account already exists.
|
||||
|
||||
4. On each CrossPoint device:
|
||||
- Go to **Settings -> System -> KOReader Sync**.
|
||||
- Set **Username** and **Password** (enter the plain password; CrossPoint computes MD5 internally, and use the same values on all devices).
|
||||
- Set **Sync Server URL** to `http://<server-ip>:17200`.
|
||||
- Run **Authenticate**.
|
||||
|
||||
If you use the HTTPS listener, use `https://<server-ip>:7200` (`curl -k` only for self-signed certificate testing).
|
||||
|
||||
5. While reading, press **Confirm** to open the reader menu, then select **Sync Progress**.
|
||||
- Choose **Apply Remote** to jump to remote progress.
|
||||
- Choose **Upload Local** to push current progress.
|
||||
|
||||
### 3.7 Sleep Screen
|
||||
|
||||
The **Sleep Screen** setting controls what is displayed when the device goes to sleep:
|
||||
|
||||
| Mode | Behavior |
|
||||
|------|----------|
|
||||
| **Dark** (default) | The CrossPoint logo on a dark background. |
|
||||
| **Light** | The CrossPoint logo on a white background. |
|
||||
| **Custom** | A custom image from the SD card (see below). Falls back to **Dark** if no custom image is found. |
|
||||
| **Cover** | The cover of the currently open book. Falls back to **Dark** if no book is open. |
|
||||
| **Cover + Custom** | The cover of the currently open book. Falls back to **Custom** behavior if no book is open. |
|
||||
| **None** | A blank screen. |
|
||||
|
||||
#### Cover settings
|
||||
|
||||
When using **Cover** or **Cover + Custom**, two additional settings apply:
|
||||
|
||||
- **Sleep Screen Cover Mode**: **Fit** (scale to fit, white borders) or **Crop** (scale and crop to fill the screen).
|
||||
- **Sleep Screen Cover Filter**: **None** (grayscale), **Contrast** (black & white), or **Inverted** (inverted black & white).
|
||||
|
||||
#### Custom images
|
||||
|
||||
To use custom sleep images, set the sleep screen mode to **Custom** or **Cover + Custom**, then place images on the SD card:
|
||||
|
||||
- **Multiple Images (recommended):** Create a `.sleep` directory in the root of the SD card and place any number of `.bmp` images inside. One will be randomly selected each time the device sleeps. (A directory named `sleep` is also accepted as a fallback.)
|
||||
- **Single Image:** Place a file named `sleep.bmp` in the root directory. This is used as a fallback if no valid images are found in the `.sleep`/`sleep` directory.
|
||||
|
||||
> [!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.
|
||||
> - X4: Use a resolution of 480x800 pixels to match the device's screen resolution.
|
||||
> - X3: Use a resolution of 528x792 pixels to match the device's screen resolution.
|
||||
|
||||
---
|
||||
|
||||
@@ -188,7 +393,7 @@ Once you have opened a book, the button layout changes to facilitate reading.
|
||||
| **Previous Page** | Press **Left** _or_ **Volume Up** |
|
||||
| **Next Page** | Press **Right** _or_ **Volume Down** |
|
||||
|
||||
The role of the volume (side) buttons can be swapped in **[Settings](#35-settings)**.
|
||||
The role of the volume (side) buttons can be swapped in the **[Controls Settings](#363-controls)**.
|
||||
|
||||
If the **Short Power Button Click** setting is set to "Page Turn", you can also turn to the next page by briefly pressing the Power button.
|
||||
|
||||
@@ -196,13 +401,13 @@ If the **Short Power Button Click** setting is set to "Page Turn", you can also
|
||||
* **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.
|
||||
|
||||
This feature can be disabled in **[Settings](#35-settings)** to help avoid changing chapters by mistake.
|
||||
This feature can be disabled in the **[Controls Settings](#363-controls)** to help avoid changing chapters by mistake.
|
||||
|
||||
|
||||
### System Navigation
|
||||
* **Return to Book Selection:** Press **Back** to close the book and return to the **[Book Selection](#32-book-selection)** screen.
|
||||
* **Return to Home:** Press and **hold** the **Back** button to close the book and return to the **[Home](#31-home-screen)** screen.
|
||||
* **Chapter Menu:** Press **Confirm** to open the **[Table of Contents/Chapter Selection](#5-chapter-selection-screen)**.
|
||||
* **Return to Home:** Press the **Back** button to close the book and return to the **[Home](#31-home-screen)** screen.
|
||||
* **Return to Browse Files:** Press and hold the **Back** button to close the book and return to the **[Browse Files](#33-browse-files-screen)** screen.
|
||||
* **Chapter Menu:** Press **Confirm** to open the **[Table of Contents/Chapter Selection](#5-chapter-selection-screen)** screen.
|
||||
|
||||
### Supported Languages
|
||||
|
||||
|
||||
+30
-8
@@ -1,17 +1,34 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
# Check if clang-format is availible
|
||||
command -v clang-format >/dev/null 2>&1 || {
|
||||
printf "'clang-format' not found in current environment\n"
|
||||
printf "install 'clang', 'clang-tools', or 'clang-format' depending on your distro/os and tooling requirements\n"
|
||||
exit 1
|
||||
}
|
||||
# Check if clang-format is available and pick the preferred binary.
|
||||
if command -v clang-format-21 >/dev/null 2>&1; then
|
||||
CLANG_FORMAT_BIN="clang-format-21"
|
||||
elif command -v clang-format >/dev/null 2>&1; then
|
||||
CLANG_FORMAT_BIN="clang-format"
|
||||
else
|
||||
printf "'clang-format' not found in current environment\n"
|
||||
printf "Install clang-format-21 (recommended), clang, clang-tools, or clang-format depending on your distro/os and tooling requirements\n"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
GIT_LS_FILES_FLAGS=""
|
||||
if [[ "$1" == "-g" ]]; then
|
||||
# -g scopes formatting to tracked files currently modified in git status.
|
||||
if [[ "${1:-}" == "-g" ]]; then
|
||||
GIT_LS_FILES_FLAGS="--modified"
|
||||
fi
|
||||
|
||||
CLANG_FORMAT_VERSION_RAW="$(${CLANG_FORMAT_BIN} --version)"
|
||||
CLANG_FORMAT_MAJOR="$(printf '%s\n' "${CLANG_FORMAT_VERSION_RAW}" | grep -oE '[0-9]+' | head -n1)"
|
||||
|
||||
# Guard against local binaries older than the repo formatting config.
|
||||
if [[ -z "${CLANG_FORMAT_MAJOR}" || "${CLANG_FORMAT_MAJOR}" -lt 21 ]]; then
|
||||
echo "Error: ${CLANG_FORMAT_BIN} is too old: ${CLANG_FORMAT_VERSION_RAW}"
|
||||
echo "This repository's .clang-format requires clang-format 21 or newer."
|
||||
echo "Install clang-format-21 and rerun ./bin/clang-format-fix"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# --- Main Logic ---
|
||||
|
||||
@@ -22,9 +39,14 @@ fi
|
||||
# --exclude-standard: ignores files in .gitignore
|
||||
# Additionally exclude files in 'lib/EpdFont/builtinFonts/' as they are script-generated.
|
||||
# Also exclude files in 'lib/Epub/Epub/hyphenation/generated/' as they are script-generated.
|
||||
# Keep the no-match case non-fatal: grep returns 1 when no files match,
|
||||
# which is expected when there are no modified C/C++ files.
|
||||
set +o pipefail
|
||||
git ls-files --exclude-standard ${GIT_LS_FILES_FLAGS} \
|
||||
| grep -E '\.(c|cpp|h|hpp)$' \
|
||||
| grep -v -E '^lib/EpdFont/builtinFonts/' \
|
||||
| grep -v -E '^lib/Epub/Epub/hyphenation/generated/' \
|
||||
| grep -v -E '^lib/uzlib/' \
|
||||
| xargs -r clang-format -style=file -i
|
||||
| xargs -r "${CLANG_FORMAT_BIN}" -style=file -i
|
||||
# Restore strict pipeline failure handling for the rest of the script.
|
||||
set -o pipefail
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Runs clang-format -i on project *.cpp and *.h files.
|
||||
|
||||
.DESCRIPTION
|
||||
Formats all C/C++ source and header files in the repository, excluding
|
||||
generated, vendored, and build directories (open-x4-sdk, builtinFonts,
|
||||
hyphenation tries, uzlib, .pio, *.generated.h).
|
||||
|
||||
The clang-format binary path is resolved once and cached in
|
||||
bin/clang-format-fix.local. On first run it checks a default path,
|
||||
then PATH, then common install locations. Edit the .local file to
|
||||
override manually.
|
||||
|
||||
.PARAMETER g
|
||||
Format only git-modified files (git diff --name-only HEAD) instead of
|
||||
the full tree.
|
||||
|
||||
.PARAMETER h
|
||||
Show this help text.
|
||||
|
||||
.EXAMPLE
|
||||
.\clang-format-fix.ps1
|
||||
Format all files.
|
||||
|
||||
.EXAMPLE
|
||||
.\clang-format-fix.ps1 -g
|
||||
Format only git-modified files.
|
||||
#>
|
||||
|
||||
param(
|
||||
[switch]$g,
|
||||
[switch]$h
|
||||
)
|
||||
|
||||
if ($h) {
|
||||
Get-Help $PSCommandPath -Detailed
|
||||
return
|
||||
}
|
||||
|
||||
$repoRoot = (Resolve-Path "$PSScriptRoot\..").Path
|
||||
$configFile = Join-Path $PSScriptRoot 'clang-format-fix.local'
|
||||
$defaultPath = 'C:\Program Files\LLVM\bin\clang-format.exe'
|
||||
|
||||
$candidatePaths = @(
|
||||
'C:\Program Files\LLVM\bin\clang-format.exe'
|
||||
'C:\Program Files (x86)\LLVM\bin\clang-format.exe'
|
||||
'C:\msys64\ucrt64\bin\clang-format.exe'
|
||||
'C:\msys64\mingw64\bin\clang-format.exe'
|
||||
"$env:LOCALAPPDATA\LLVM\bin\clang-format.exe"
|
||||
)
|
||||
|
||||
function Find-ClangFormat {
|
||||
# Try PATH first
|
||||
$inPath = Get-Command clang-format -ErrorAction SilentlyContinue
|
||||
if ($inPath) { return $inPath.Source }
|
||||
|
||||
# Try candidate paths
|
||||
foreach ($p in $candidatePaths) {
|
||||
if (Test-Path $p) { return $p }
|
||||
}
|
||||
return $null
|
||||
}
|
||||
|
||||
function Resolve-ClangFormat {
|
||||
# 1. Read from config if present
|
||||
if (Test-Path $configFile) {
|
||||
$saved = (Get-Content $configFile -Raw).Trim()
|
||||
if ($saved -and (Test-Path $saved)) { return $saved }
|
||||
Write-Host "Configured path no longer valid: $saved"
|
||||
}
|
||||
|
||||
# 2. Check default
|
||||
if (Test-Path $defaultPath) {
|
||||
$defaultPath | Set-Content $configFile
|
||||
Write-Host "Saved clang-format path to $configFile"
|
||||
return $defaultPath
|
||||
}
|
||||
|
||||
# 3. Search PATH and candidate locations
|
||||
$found = Find-ClangFormat
|
||||
if ($found) {
|
||||
$found | Set-Content $configFile
|
||||
Write-Host "Found clang-format at $found - saved to $configFile"
|
||||
return $found
|
||||
}
|
||||
|
||||
Write-Error "clang-format not found. Install LLVM or add clang-format to PATH."
|
||||
exit 1
|
||||
}
|
||||
|
||||
$clangFormat = Resolve-ClangFormat
|
||||
|
||||
$exclude = @(
|
||||
'open-x4-sdk'
|
||||
'lib\EpdFont\builtinFonts'
|
||||
'lib\Epub\Epub\hyphenation\generated'
|
||||
'lib\uzlib'
|
||||
'.pio'
|
||||
'.venv'
|
||||
)
|
||||
|
||||
function Test-Excluded($fullPath) {
|
||||
foreach ($ex in $exclude) {
|
||||
if ($fullPath -like "*\$ex\*") { return $true }
|
||||
}
|
||||
if ($fullPath -like '*.generated.h') { return $true }
|
||||
return $false
|
||||
}
|
||||
|
||||
if ($g) {
|
||||
# Only git-modified *.cpp / *.h files
|
||||
# Covers both staged and unstaged changes
|
||||
$files = @(git -C $repoRoot diff --name-only HEAD) +
|
||||
@(git -C $repoRoot diff --name-only --cached) |
|
||||
Sort-Object -Unique |
|
||||
Where-Object { $_ -match '\.(cpp|h)$' } |
|
||||
ForEach-Object { Get-Item (Join-Path $repoRoot $_) -ErrorAction SilentlyContinue } |
|
||||
Where-Object { $_ -and -not (Test-Excluded $_.FullName) }
|
||||
} else {
|
||||
$files = Get-ChildItem -Path $repoRoot -Recurse -Include *.cpp, *.h -File |
|
||||
Where-Object { -not (Test-Excluded $_.FullName) }
|
||||
}
|
||||
|
||||
$files = @($files)
|
||||
|
||||
if ($files.Count -eq 0) {
|
||||
Write-Host 'No files to format.'
|
||||
return
|
||||
}
|
||||
|
||||
Write-Host "Formatting $($files.Count) files..."
|
||||
$i = 0
|
||||
$changed = 0
|
||||
$failures = 0
|
||||
foreach ($f in $files) {
|
||||
$i++
|
||||
$rel = $f.FullName.Substring($repoRoot.Length + 1)
|
||||
$hashBefore = (Get-FileHash $f.FullName -Algorithm MD5).Hash
|
||||
& $clangFormat -i $f.FullName
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
$failures++
|
||||
Write-Host " [$i/$($files.Count)] $rel (FAILED, exit code $LASTEXITCODE)"
|
||||
continue
|
||||
}
|
||||
$hashAfter = (Get-FileHash $f.FullName -Algorithm MD5).Hash
|
||||
if ($hashBefore -ne $hashAfter) {
|
||||
$changed++
|
||||
Write-Host " [$i/$($files.Count)] $rel (changed)"
|
||||
} else {
|
||||
Write-Host " [$i/$($files.Count)] $rel"
|
||||
}
|
||||
}
|
||||
Write-Host "Done. $changed/$($files.Count) files changed, $failures failed."
|
||||
if ($failures -gt 0) { exit 1 }
|
||||
@@ -0,0 +1,472 @@
|
||||
# Activity & ActivityManager Migration Guide
|
||||
|
||||
This document explains the refactoring from the original per-activity render task model to the centralized `ActivityManager` introduced in [PR #1016](https://github.com/crosspoint-reader/crosspoint-reader/pull/1016). It covers the architectural differences, what changed for activity authors, and the FreeRTOS task and locking model that underpins the system.
|
||||
|
||||
## Overview of Changes
|
||||
|
||||
| Aspect | Old Model | New Model |
|
||||
|--------|-----------|-----------|
|
||||
| Render task | One per activity (8KB stack each) | Single shared task in `ActivityManager` |
|
||||
| Render mutex | Per-activity `renderingMutex` | Single global mutex in `ActivityManager` |
|
||||
| `RenderLock` | Inner class of `Activity` | Standalone class, acquires global mutex |
|
||||
| Subactivities | `ActivityWithSubactivity` base class | Activity stack managed by `ActivityManager` |
|
||||
| Navigation | Free functions in `main.cpp` | `activityManager.goHome()`, `goToReader()`, etc. |
|
||||
| Subactivity results | Callback lambdas stored in parent | `startActivityForResult()` / `setResult()` / `finish()` |
|
||||
| `requestUpdate()` | Notifies activity's own render task | Delegates to `ActivityManager` (immediate or deferred) |
|
||||
|
||||
## Architecture
|
||||
|
||||
### Old Model: Per-Activity Render Tasks
|
||||
|
||||
Each activity created its own FreeRTOS render task on entry and destroyed it on exit:
|
||||
|
||||
```text
|
||||
┌─────────────────────────────────────────────────────────┐
|
||||
│ Main Task (Arduino loop) │
|
||||
│ ┌───────────────────────────────────────────────────┐ │
|
||||
│ │ currentActivity->loop() │ │
|
||||
│ │ ├── handle input │ │
|
||||
│ │ ├── update state (under RenderLock) │ │
|
||||
│ │ └── requestUpdate() ──notify──► Render Task │ │
|
||||
│ │ (per-activity)│ │
|
||||
│ │ 8KB stack │ │
|
||||
│ │ owns mutex │ │
|
||||
│ └───────────────────────────────────────────────────┘ │
|
||||
│ │
|
||||
│ ActivityWithSubactivity: │
|
||||
│ ┌──────────────┐ ┌──────────────┐ │
|
||||
│ │ Parent │────►│ SubActivity │ │
|
||||
│ │ (has render │ │ (has own │ │
|
||||
│ │ task) │ │ render task) │ │
|
||||
│ └──────────────┘ └──────────────┘ │
|
||||
└─────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
Problems with this approach:
|
||||
|
||||
- **8KB per render task**: Each activity allocated an 8KB FreeRTOS stack for its render task, even though only one renders at a time
|
||||
- **Dangerous deletion patterns**: `exitActivity()` + `enterNewActivity()` in callbacks led to `delete this` situations where the caller was destroyed while its code was still on the stack
|
||||
- **Subactivity coupling**: Parents stored callbacks to child results, creating tight coupling and lifetime hazards
|
||||
|
||||
### New Model: Centralized ActivityManager
|
||||
|
||||
A single `ActivityManager` owns the render task and manages an activity stack:
|
||||
|
||||
```text
|
||||
┌──────────────────────────────────────────────────────────┐
|
||||
│ Main Task (Arduino loop) │
|
||||
│ │
|
||||
│ activityManager.loop() │
|
||||
│ │ │
|
||||
│ ├── currentActivity->loop() │
|
||||
│ │ ├── handle input │
|
||||
│ │ ├── update state (under RenderLock) │
|
||||
│ │ └── requestUpdate() │
|
||||
│ │ │
|
||||
│ ├── process pending actions (Push / Pop / Replace) │
|
||||
│ │ │
|
||||
│ └── if requestedUpdate: ──notify──► Render Task │
|
||||
│ (single, shared) │
|
||||
│ 8KB stack │
|
||||
│ global mutex │
|
||||
│ │
|
||||
│ Activity Stack: │
|
||||
│ ┌──────────┬──────────┬──────────┐ ┌──────────┐ │
|
||||
│ │ Home │ Settings │ Wifi │ │ Keyboard │ │
|
||||
│ │ (stack) │ (stack) │ (stack) │ │ (current)│ │
|
||||
│ └──────────┴──────────┴──────────┘ └──────────┘ │
|
||||
│ stackActivities[] currentActivity │
|
||||
└──────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
## Migration Checklist
|
||||
|
||||
### 1. Change Base Class
|
||||
|
||||
If your activity extended `ActivityWithSubactivity`, change it to extend `Activity`:
|
||||
|
||||
```cpp
|
||||
// BEFORE
|
||||
class MyActivity final : public ActivityWithSubactivity {
|
||||
MyActivity(GfxRenderer& r, MappedInputManager& m, std::function<void()> goBack)
|
||||
: ActivityWithSubactivity("MyActivity", r, m), goBack(goBack) {}
|
||||
};
|
||||
|
||||
// AFTER
|
||||
class MyActivity final : public Activity {
|
||||
MyActivity(GfxRenderer& r, MappedInputManager& m)
|
||||
: Activity("MyActivity", r, m) {}
|
||||
};
|
||||
```
|
||||
|
||||
Note that navigation callbacks like `goBack` are no longer stored — use `finish()` or `activityManager.goHome()` instead.
|
||||
|
||||
### 2. Replace Navigation Functions
|
||||
|
||||
The free functions `exitActivity()` / `enterNewActivity()` in `main.cpp` are gone. Use `ActivityManager` methods:
|
||||
|
||||
```cpp
|
||||
// BEFORE (in main.cpp or via stored callbacks)
|
||||
exitActivity();
|
||||
enterNewActivity(new SettingsActivity(renderer, mappedInput, onGoHome));
|
||||
|
||||
// AFTER (from any Activity method)
|
||||
activityManager.goToSettings();
|
||||
// or for arbitrary navigation:
|
||||
activityManager.replaceActivity(std::make_unique<MyActivity>(renderer, mappedInput));
|
||||
```
|
||||
|
||||
`replaceActivity()` destroys the current activity and clears the stack. Use it for top-level navigation (home, reader, settings, etc.).
|
||||
|
||||
### 3. Replace Subactivity Pattern
|
||||
|
||||
The `enterNewActivity()` / `exitActivity()` subactivity pattern is replaced by a stack with typed results:
|
||||
|
||||
```cpp
|
||||
// BEFORE
|
||||
void MyActivity::launchWifi() {
|
||||
enterNewActivity(new WifiSelectionActivity(renderer, mappedInput,
|
||||
[this](bool connected) { onWifiDone(connected); }));
|
||||
}
|
||||
// Child calls: onComplete(true); // triggers callback, which may call exitActivity()
|
||||
|
||||
// AFTER
|
||||
void MyActivity::launchWifi() {
|
||||
startActivityForResult(
|
||||
std::make_unique<WifiSelectionActivity>(renderer, mappedInput),
|
||||
[this](const ActivityResult& result) {
|
||||
if (result.isCancelled) return;
|
||||
auto& wifi = std::get<WifiResult>(result.data);
|
||||
onWifiDone(wifi.connected);
|
||||
});
|
||||
}
|
||||
// Child calls:
|
||||
// setResult(WifiResult{.connected = true, .ssid = ssid});
|
||||
// finish();
|
||||
```
|
||||
|
||||
Key differences:
|
||||
|
||||
- **`startActivityForResult()`** pushes the current activity onto the stack and launches the child
|
||||
- **`setResult()`** stores a typed result on the child activity
|
||||
- **`finish()`** signals the manager to pop the child, call the result handler, and resume the parent
|
||||
- The parent is never deleted during this process — it's safely stored on the stack
|
||||
|
||||
### 4. Update `render()` Signature
|
||||
|
||||
The `RenderLock` type changed from `Activity::RenderLock` (inner class) to standalone `RenderLock`:
|
||||
|
||||
```cpp
|
||||
// BEFORE
|
||||
void render(Activity::RenderLock&&) override;
|
||||
|
||||
// AFTER
|
||||
void render(RenderLock&&) override;
|
||||
```
|
||||
|
||||
Include `RenderLock.h` if not transitively included via `Activity.h`.
|
||||
|
||||
### 5. Update `onEnter()` / `onExit()`
|
||||
|
||||
Activities no longer create or destroy render tasks:
|
||||
|
||||
```cpp
|
||||
// BEFORE
|
||||
void MyActivity::onEnter() {
|
||||
Activity::onEnter(); // created render task + logged
|
||||
// ... allocate resources
|
||||
requestUpdate();
|
||||
}
|
||||
void MyActivity::onExit() {
|
||||
// ... free resources
|
||||
Activity::onExit(); // acquired RenderLock, deleted render task
|
||||
}
|
||||
|
||||
// AFTER
|
||||
void MyActivity::onEnter() {
|
||||
Activity::onEnter(); // just logs
|
||||
// ... allocate resources
|
||||
requestUpdate();
|
||||
}
|
||||
void MyActivity::onExit() {
|
||||
// ... free resources
|
||||
Activity::onExit(); // just logs
|
||||
}
|
||||
```
|
||||
|
||||
The render task lifecycle is handled entirely by `ActivityManager::begin()`.
|
||||
|
||||
### 6. Update `requestUpdate()` Calls
|
||||
|
||||
The signature changed to accept an `immediate` flag:
|
||||
|
||||
```cpp
|
||||
// BEFORE
|
||||
void requestUpdate(); // always immediate notification to per-activity render task
|
||||
|
||||
// AFTER
|
||||
void requestUpdate(bool immediate = false);
|
||||
// immediate=false (default): deferred until end of current loop iteration
|
||||
// immediate=true: sends notification to render task right away
|
||||
```
|
||||
|
||||
**When to use `immediate`**: Almost never. Deferred updates are batched — if `loop()` triggers multiple state changes that each call `requestUpdate()`, only one render happens. Use `immediate` only when you need the render to start before the current function returns (e.g., before a blocking network call).
|
||||
|
||||
**`requestUpdateAndWait()`**: Blocks the calling task until the render completes. Use sparingly — it's designed for cases where you need the screen to reflect new state before proceeding (e.g., showing "Checking for update..." before calling a network API).
|
||||
|
||||
### 7. Remove Stored Navigation Callbacks
|
||||
|
||||
Old activities often stored `std::function` callbacks for navigation:
|
||||
|
||||
```cpp
|
||||
// BEFORE
|
||||
class SettingsActivity : public ActivityWithSubactivity {
|
||||
const std::function<void()> goBack; // stored callback
|
||||
const std::function<void()> goHome; // stored callback
|
||||
public:
|
||||
SettingsActivity(GfxRenderer& r, MappedInputManager& m,
|
||||
std::function<void()> goBack, std::function<void()> goHome)
|
||||
: ActivityWithSubactivity("Settings", r, m), goBack(goBack), goHome(goHome) {}
|
||||
};
|
||||
|
||||
// AFTER
|
||||
class SettingsActivity : public Activity {
|
||||
public:
|
||||
SettingsActivity(GfxRenderer& r, MappedInputManager& m)
|
||||
: Activity("Settings", r, m) {}
|
||||
// Use finish() to go back, activityManager.goHome() to go home
|
||||
};
|
||||
```
|
||||
|
||||
This removes `std::function` overhead (~2-4KB per unique signature) and eliminates lifetime risks from captured `this` pointers.
|
||||
|
||||
## Technical Details
|
||||
|
||||
### FreeRTOS Task Model
|
||||
|
||||
The firmware runs on an ESP32-C3, a single-core RISC-V microcontroller. FreeRTOS provides cooperative and preemptive multitasking on this single core — only one task executes at any moment, and the scheduler switches between tasks at yield points (blocking calls, `vTaskDelay`, `taskYIELD`) or when a tick interrupt promotes a higher-priority task.
|
||||
|
||||
There are two tasks relevant to the activity system:
|
||||
|
||||
```text
|
||||
┌──────────────────────┐ ┌──────────────────────────┐
|
||||
│ Main Task │ │ Render Task │
|
||||
│ (Arduino loop) │ │ (ActivityManager-owned) │
|
||||
│ Priority: 1 │ │ Priority: 1 │
|
||||
│ │ │ │
|
||||
│ Runs: │ │ Runs: │
|
||||
│ - gpio.update() │ │ - ulTaskNotifyTake() │
|
||||
│ - activity->loop() │ │ (blocks until notified)│
|
||||
│ - pending actions │ │ - RenderLock (mutex) │
|
||||
│ - sleep/power mgmt │ │ - activity->render() │
|
||||
│ - requestUpdate →────┼─────┼─► xTaskNotify() │
|
||||
│ (end of loop) │ │ │
|
||||
└──────────────────────┘ └──────────────────────────┘
|
||||
```
|
||||
|
||||
Both tasks run at priority 1. Since the ESP32-C3 is single-core, they alternate execution: the main task runs `loop()`, then at the end of the loop iteration, notifies the render task if an update was requested. The render task wakes, acquires the mutex, calls `render()`, releases the mutex, and blocks again.
|
||||
|
||||
Do not use `xTaskCreate` inside activities. If you have a use case that seems to require a background task, open a discussion to propose a lifecycle-aware `Worker` abstraction first.
|
||||
|
||||
### The Render Mutex and RenderLock
|
||||
|
||||
A single FreeRTOS mutex (`renderingMutex`) protects shared state between `loop()` and `render()`. Since these run on different tasks, any state read by `render()` and written by `loop()` must be guarded.
|
||||
|
||||
`RenderLock` is an RAII wrapper:
|
||||
|
||||
```cpp
|
||||
// Standalone class (not tied to any specific activity)
|
||||
class RenderLock {
|
||||
bool isLocked = false;
|
||||
public:
|
||||
explicit RenderLock(); // acquires activityManager.renderingMutex
|
||||
explicit RenderLock(Activity&); // same — Activity& param kept for compatibility
|
||||
~RenderLock(); // releases mutex if still held
|
||||
void unlock(); // early release
|
||||
};
|
||||
```
|
||||
|
||||
**Usage patterns:**
|
||||
|
||||
```cpp
|
||||
// In loop(): protect state mutations that render() reads
|
||||
void MyActivity::loop() {
|
||||
if (somethingChanged) {
|
||||
RenderLock lock;
|
||||
state = newState; // safe — render() can't run while lock is held
|
||||
}
|
||||
requestUpdate(); // trigger render after lock is released
|
||||
}
|
||||
|
||||
// In render(): lock is passed in, held for duration of render
|
||||
void MyActivity::render(RenderLock&&) {
|
||||
// Lock is held — safe to read shared state
|
||||
renderer.clearScreen();
|
||||
renderer.drawText(..., stateString, ...);
|
||||
renderer.displayBuffer();
|
||||
// Lock released when RenderLock destructor runs
|
||||
}
|
||||
```
|
||||
|
||||
**Critical rule**: Never call `requestUpdateAndWait()` while holding a `RenderLock`. The render task needs the mutex to call `render()`, so holding it while waiting for the render to complete is a deadlock:
|
||||
|
||||
```text
|
||||
Main Task Render Task
|
||||
────────── ───────────
|
||||
RenderLock lock; (blocked on mutex)
|
||||
requestUpdateAndWait();
|
||||
→ notify render task
|
||||
→ block waiting for
|
||||
render to complete → wakes up
|
||||
→ tries to acquire mutex
|
||||
→ DEADLOCK: main holds mutex,
|
||||
waits for render; render
|
||||
waits for mutex
|
||||
```
|
||||
|
||||
### requestUpdate() vs requestUpdateAndWait()
|
||||
|
||||
```text
|
||||
requestUpdate(false) requestUpdate(true)
|
||||
───────────────── ─────────────────
|
||||
Sets flag only. Notifies render task
|
||||
Render happens after immediately.
|
||||
loop() returns and Render may start
|
||||
ActivityManager checks before the calling
|
||||
the flag. function returns.
|
||||
(Does NOT wait for
|
||||
render to complete.)
|
||||
|
||||
requestUpdateAndWait()
|
||||
──────────────────────
|
||||
Notifies render task AND
|
||||
blocks calling task until
|
||||
render is done. Uses
|
||||
FreeRTOS direct-to-task
|
||||
notification on the
|
||||
caller's task handle.
|
||||
```
|
||||
|
||||
`requestUpdateAndWait()` flow in detail:
|
||||
|
||||
```text
|
||||
Calling Task Render Task
|
||||
──────────── ───────────
|
||||
requestUpdateAndWait()
|
||||
├─ assert: not render task
|
||||
├─ assert: not holding RenderLock
|
||||
├─ store waitingTaskHandle
|
||||
├─ xTaskNotify(renderTask) → wakes render task
|
||||
└─ ulTaskNotifyTake() ─┐
|
||||
(blocked) │ RenderLock lock;
|
||||
│ activity->render();
|
||||
│ // render complete
|
||||
│ taskENTER_CRITICAL
|
||||
│ waiter = waitingTaskHandle
|
||||
│ waitingTaskHandle = nullptr
|
||||
│ taskEXIT_CRITICAL
|
||||
│ xTaskNotify(waiter) ───┐
|
||||
│ │
|
||||
┌──────────────────────┘ │
|
||||
│ (woken by notification) ◄────────────────────────┘
|
||||
└─ return
|
||||
```
|
||||
|
||||
### Activity Lifecycle Under ActivityManager
|
||||
|
||||
```text
|
||||
activityManager.replaceActivity(make_unique<MyActivity>(...))
|
||||
│
|
||||
▼
|
||||
╔═══════════════════════════════════════════════════╗
|
||||
║ pendingAction = Replace ║
|
||||
║ pendingActivity = MyActivity ║
|
||||
╚═══════════════════════════════════════════════════╝
|
||||
│
|
||||
▼ (next loop iteration)
|
||||
ActivityManager::loop()
|
||||
│
|
||||
├── currentActivity->loop() // old activity's last loop
|
||||
│
|
||||
├── process pending action:
|
||||
│ ├── RenderLock lock;
|
||||
│ ├── oldActivity->onExit() // cleanup under lock
|
||||
│ ├── delete oldActivity
|
||||
│ ├── clear stack
|
||||
│ ├── currentActivity = MyActivity
|
||||
│ ├── lock.unlock()
|
||||
│ └── MyActivity->onEnter() // init new activity
|
||||
│
|
||||
└── if requestedUpdate:
|
||||
└── notify render task
|
||||
```
|
||||
|
||||
For push/pop (subactivity) navigation:
|
||||
|
||||
```text
|
||||
Parent calls: startActivityForResult(make_unique<Child>(...), handler)
|
||||
│
|
||||
▼
|
||||
╔══════════════════════════════════════╗
|
||||
║ pendingAction = Push ║
|
||||
║ pendingActivity = Child ║
|
||||
║ parent->resultHandler = handler ║
|
||||
╚══════════════════════════════════════╝
|
||||
│
|
||||
▼ (next loop iteration)
|
||||
├── Parent moved to stackActivities[]
|
||||
├── currentActivity = Child
|
||||
└── Child->onEnter()
|
||||
|
||||
... child runs ...
|
||||
|
||||
Child calls: setResult(MyResult{...}); finish();
|
||||
│
|
||||
▼
|
||||
╔══════════════════════════════════════╗
|
||||
║ pendingAction = Pop ║
|
||||
║ child->result = MyResult{...} ║
|
||||
╚══════════════════════════════════════╝
|
||||
│
|
||||
▼ (next loop iteration)
|
||||
├── result = child->result
|
||||
├── Child->onExit(); delete Child
|
||||
├── currentActivity = Parent (popped from stack)
|
||||
├── Parent->resultHandler(result)
|
||||
└── requestUpdate() // automatic re-render for parent
|
||||
```
|
||||
|
||||
### Common Pitfalls
|
||||
|
||||
**Calling `finish()` and continuing to access `this`**: `finish()` sets `pendingAction = Pop` but does not immediately destroy the activity. The activity is destroyed on the next `ActivityManager::loop()` iteration. It's safe to access member variables after `finish()` within the same function, but don't rely on the activity surviving past the current `loop()` call.
|
||||
|
||||
**Modifying shared state without `RenderLock`**: If `render()` reads a variable and `loop()` writes it, the write must be under a `RenderLock`. Without it, `render()` could see a half-written value (e.g., a partially updated string or struct).
|
||||
|
||||
**Creating background tasks that outlive the activity**: Any FreeRTOS task created in `onEnter()` must be deleted in `onExit()` before the activity is destroyed. The `ActivityManager` does not track or clean up background tasks.
|
||||
|
||||
**Holding `RenderLock` across blocking calls**: The render task is blocked on the mutex while you hold the lock. Keep critical sections short — acquire, mutate state, release, then do blocking work.
|
||||
|
||||
```cpp
|
||||
// WRONG — blocks render for the entire network call
|
||||
void MyActivity::doNetworkStuff() {
|
||||
RenderLock lock;
|
||||
state = LOADING;
|
||||
auto result = http.get(url); // blocks for seconds with lock held
|
||||
state = DONE;
|
||||
}
|
||||
|
||||
// CORRECT — release lock before blocking
|
||||
void MyActivity::doNetworkStuff() {
|
||||
{
|
||||
RenderLock lock;
|
||||
state = LOADING;
|
||||
}
|
||||
requestUpdate(true); // render "Loading..." immediately, before we block
|
||||
auto result = http.get(url); // lock is not held
|
||||
{
|
||||
RenderLock lock;
|
||||
state = DONE;
|
||||
}
|
||||
requestUpdate();
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,11 @@
|
||||
# Contributing Docs
|
||||
|
||||
This section is a lightweight contributor guide for CrossPoint Reader.
|
||||
It is written for software developers who may be new to embedded development.
|
||||
|
||||
- [Getting Started](./getting-started.md)
|
||||
- [Architecture Overview](./architecture.md)
|
||||
- [Development Workflow](./development-workflow.md)
|
||||
- [Testing and Debugging](./testing-debugging.md)
|
||||
|
||||
If you are new, start with [Getting Started](./getting-started.md).
|
||||
@@ -0,0 +1,199 @@
|
||||
# Architecture Overview
|
||||
|
||||
CrossPoint is firmware for the Xteink X4 (unaffiliated with Xteink), built with PlatformIO targeting the ESP32-C3 microcontroller.
|
||||
|
||||
At a high level, it is firmware that uses an activity-driven application architecture loop with persistent settings/state, SD-card-first caching, and a rendering pipeline optimized for e-ink constraints.
|
||||
|
||||
## System at a glance
|
||||
|
||||
```mermaid
|
||||
graph TD
|
||||
A[Hardware: ESP32-C3 + SD + E-ink + Buttons] --> B[open-x4-sdk HAL]
|
||||
B --> C[src/main.cpp runtime loop]
|
||||
C --> D[Activities layer]
|
||||
C --> E[State and settings]
|
||||
D --> F[Reader flows]
|
||||
D --> G[Home/Library/Settings flows]
|
||||
D --> H[Network/Web server flows]
|
||||
F --> I[lib/Epub parsing + layout + hyphenation]
|
||||
I --> J[SD cache in .crosspoint]
|
||||
D --> K[GfxRenderer]
|
||||
K --> L[E-ink display buffer]
|
||||
```
|
||||
|
||||
## Runtime lifecycle
|
||||
|
||||
Primary entry point is `src/main.cpp`.
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
A[Boot] --> B[Init GPIO and optional serial]
|
||||
B --> C[Init SD storage]
|
||||
C --> D[Load settings and app state]
|
||||
D --> E[Init display and fonts]
|
||||
E --> F{Resume reader?}
|
||||
F -->|No| G[Enter Home activity]
|
||||
F -->|Yes| H[Enter Reader activity]
|
||||
G --> I[Main loop]
|
||||
H --> I
|
||||
I --> J[Poll input and run current activity]
|
||||
J --> K{Sleep condition met?}
|
||||
K -->|No| I
|
||||
K -->|Yes| L[Persist state and enter deep sleep]
|
||||
```
|
||||
|
||||
In each loop iteration, the firmware updates input, runs the active activity, handles auto-sleep/power behavior, and applies a short delay policy to balance responsiveness and power.
|
||||
|
||||
## Activity model
|
||||
|
||||
Activities are screen-level controllers deriving from `src/activities/Activity.h`.
|
||||
Some flows use `src/activities/ActivityWithSubactivity.h` to host nested activities.
|
||||
|
||||
- `onEnter()` and `onExit()` manage setup/teardown
|
||||
- `loop()` handles per-frame behavior
|
||||
- `skipLoopDelay()` and `preventAutoSleep()` are used by long-running flows (for example web server mode)
|
||||
|
||||
Top-level activity groups:
|
||||
|
||||
- `src/activities/home/`: home and library navigation
|
||||
- `src/activities/reader/`: EPUB/XTC/TXT reading flows
|
||||
- `src/activities/settings/`: settings menus and configuration
|
||||
- `src/activities/network/`: WiFi selection, AP/STA mode, file transfer server
|
||||
- `src/activities/boot_sleep/`: boot and sleep transitions
|
||||
|
||||
## Reader and content pipeline
|
||||
|
||||
Reader orchestration starts in `src/activities/reader/ReaderActivity.h` and dispatches to format-specific readers.
|
||||
EPUB processing is implemented in `lib/Epub/`.
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
A[Select book] --> B[ReaderActivity]
|
||||
B --> C{Format}
|
||||
C -->|EPUB| D[lib/Epub/Epub]
|
||||
C -->|XTC| E[lib/Xtc reader]
|
||||
C -->|TXT| F[lib/Txt reader]
|
||||
D --> G[Parse OPF/TOC/CSS]
|
||||
G --> H[Layout pages/sections]
|
||||
H --> I[Write section and metadata caches]
|
||||
I --> J[Render current page via GfxRenderer]
|
||||
```
|
||||
|
||||
Why caching matters:
|
||||
|
||||
- RAM is limited on ESP32-C3, so expensive parsed/layout data is persisted to SD
|
||||
- repeat opens/page navigation can reuse cached data instead of full reparsing
|
||||
|
||||
## Reader internals call graph
|
||||
|
||||
This diagram zooms into the EPUB path to show the main control and data flow from activity entry to on-screen draw.
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
A[ReaderActivity onEnter] --> B{File type}
|
||||
B -->|EPUB| C[Create Epub object]
|
||||
B -->|XTC/TXT| Z[Use format-specific reader]
|
||||
|
||||
C --> D[Epub load]
|
||||
D --> E[Locate container and OPF]
|
||||
E --> F[Build or load BookMetadataCache]
|
||||
F --> G[Load TOC and spine]
|
||||
G --> H[Load or parse CSS rules]
|
||||
|
||||
H --> I[EpubReaderActivity]
|
||||
I --> J{Section cache exists for current settings?}
|
||||
J -->|Yes| K[Read section bin from SD cache]
|
||||
J -->|No| L[Parse chapter HTML and layout text]
|
||||
L --> M[Apply typography settings and hyphenation]
|
||||
M --> N[Write section cache bin]
|
||||
|
||||
K --> O[Build page model]
|
||||
N --> O
|
||||
O --> P[GfxRenderer draw calls]
|
||||
P --> Q[HAL display framebuffer update]
|
||||
Q --> R[E-ink refresh policy]
|
||||
|
||||
S[SETTINGS singleton] -. influences .-> J
|
||||
S -. influences .-> M
|
||||
T[APP_STATE singleton] -. persists .-> U[Reading progress and resume context]
|
||||
U -. used by .-> I
|
||||
```
|
||||
|
||||
Notes:
|
||||
|
||||
- "section cache exists" depends on cache-busting parameters such as font and layout-related settings
|
||||
- rendering favors reusing precomputed layout data to keep page turns responsive on constrained hardware
|
||||
- progress/session state is persisted so the reader can reopen at the last position after reboot/sleep
|
||||
|
||||
## State and persistence
|
||||
|
||||
Two singletons are central:
|
||||
|
||||
- `src/CrossPointSettings.h` (`SETTINGS`): user preferences and behavior flags
|
||||
- `src/CrossPointState.h` (`APP_STATE`): runtime/session state such as current book and sleep context
|
||||
|
||||
Typical persisted areas on SD:
|
||||
|
||||
```text
|
||||
/.crosspoint/
|
||||
epub_<hash>/
|
||||
book.bin
|
||||
progress.bin
|
||||
cover.bmp
|
||||
sections/*.bin
|
||||
settings.bin
|
||||
state.bin
|
||||
```
|
||||
|
||||
For binary cache formats, see `docs/file-formats.md`.
|
||||
|
||||
## Networking architecture
|
||||
|
||||
Network file transfer is controlled by `src/activities/network/CrossPointWebServerActivity.h` and served by `src/network/CrossPointWebServer.h`.
|
||||
|
||||
Modes:
|
||||
|
||||
- STA: join existing WiFi network
|
||||
- AP: create hotspot
|
||||
|
||||
Server behavior:
|
||||
|
||||
- HTTP server on port 80
|
||||
- WebSocket upload server on port 81
|
||||
- file operations backed by SD storage
|
||||
- activity requests faster loop responsiveness while server is running
|
||||
|
||||
Endpoint reference: `docs/webserver-endpoints.md`.
|
||||
|
||||
## Build-time generated assets
|
||||
|
||||
Some sources are generated and should not be edited manually.
|
||||
|
||||
- `scripts/build_html.py` generates `src/network/html/*.generated.h` from HTML files
|
||||
- `scripts/generate_hyphenation_trie.py` generates hyphenation headers under `lib/Epub/Epub/hyphenation/generated/`
|
||||
|
||||
When editing related source assets, regenerate via normal build steps/scripts.
|
||||
|
||||
## Key directories
|
||||
|
||||
- `src/`: app orchestration, settings/state, and activity implementations
|
||||
- `src/network/`: web server and OTA/update networking
|
||||
- `src/components/`: theming and shared UI components
|
||||
- `lib/Epub/`: EPUB parser, layout, CSS handling, and hyphenation
|
||||
- `lib/`: supporting libraries (fonts, text, filesystem helpers, etc.)
|
||||
- `open-x4-sdk/`: hardware SDK submodule (display, input, storage, battery)
|
||||
- `docs/`: user and technical documentation
|
||||
|
||||
## Embedded constraints that shape design
|
||||
|
||||
- constrained RAM drives SD-first caching and careful allocations
|
||||
- e-ink refresh cost drives render/update batching choices
|
||||
- main loop responsiveness matters for input, power handling, and watchdog safety
|
||||
- background/network flows must cooperate with sleep and loop timing logic
|
||||
|
||||
## Scope guardrails
|
||||
|
||||
Before implementing larger ideas, check:
|
||||
|
||||
- [SCOPE.md](../../SCOPE.md)
|
||||
- [GOVERNANCE.md](../../GOVERNANCE.md)
|
||||
@@ -0,0 +1,44 @@
|
||||
# Development Workflow
|
||||
|
||||
This page defines the expected local workflow before opening a pull request.
|
||||
|
||||
## 1) Fork and create a focused branch
|
||||
|
||||
- Fork the repository to your own GitHub account
|
||||
- Clone your fork locally and add the upstream repository if needed
|
||||
- Enable repo hooks once per clone: `git config core.hooksPath .githooks && chmod +x .githooks/pre-commit`
|
||||
|
||||
- Branch from `master`
|
||||
- Keep each PR focused on one fix or feature area
|
||||
|
||||
## 2) Implement with scope in mind
|
||||
|
||||
- Confirm your idea is in project scope: [SCOPE.md](../../SCOPE.md)
|
||||
- Prefer incremental changes over broad refactors
|
||||
|
||||
## 3) Run local checks
|
||||
|
||||
```sh
|
||||
./bin/clang-format-fix
|
||||
pio check --fail-on-defect low --fail-on-defect medium --fail-on-defect high
|
||||
pio run
|
||||
```
|
||||
|
||||
CI enforces formatting, static analysis, and build checks.
|
||||
Use clang-format 21+ locally to match CI.
|
||||
If `clang-format` is missing or too old locally, see [Getting Started](./getting-started.md).
|
||||
|
||||
## 4) Open the PR
|
||||
|
||||
- Use a semantic title (example: `fix: avoid crash when opening malformed epub`)
|
||||
- Fill out `.github/PULL_REQUEST_TEMPLATE.md`
|
||||
- Describe the problem, approach, and any tradeoffs
|
||||
- Include reproduction and verification steps for bug fixes
|
||||
|
||||
## 5) Review etiquette
|
||||
|
||||
- Be explicit and concise in responses
|
||||
- Keep discussions technical and respectful
|
||||
- Assume good intent and focus on code-level feedback
|
||||
|
||||
For community expectations, see [GOVERNANCE.md](../../GOVERNANCE.md).
|
||||
@@ -0,0 +1,87 @@
|
||||
# Getting Started
|
||||
|
||||
This guide helps you build and run CrossPoint locally.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- PlatformIO Core (`pio`) or VS Code + PlatformIO IDE
|
||||
- Python 3.8+
|
||||
- `clang-format` 21+ in your `PATH` (CI uses clang-format 21)
|
||||
- USB-C cable
|
||||
- Xteink X4 device for hardware testing
|
||||
|
||||
If `./bin/clang-format-fix` fails with either of these errors, install clang-format 21:
|
||||
|
||||
- `clang-format: No such file or directory`
|
||||
- `.clang-format: error: unknown key 'AlignFunctionDeclarations'`
|
||||
|
||||
Examples:
|
||||
|
||||
```sh
|
||||
# Debian/Ubuntu (try this first)
|
||||
sudo apt-get update && sudo apt-get install -y clang-format-21
|
||||
|
||||
# If the package is unavailable, add LLVM apt repo and retry
|
||||
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
|
||||
|
||||
# macOS (Homebrew)
|
||||
brew install clang-format
|
||||
```
|
||||
|
||||
Then verify:
|
||||
|
||||
```sh
|
||||
clang-format-21 --version
|
||||
```
|
||||
|
||||
The reported major version must be 21 or newer.
|
||||
|
||||
## Clone and initialize
|
||||
|
||||
```sh
|
||||
git clone --recursive https://github.com/crosspoint-reader/crosspoint-reader
|
||||
cd crosspoint-reader
|
||||
```
|
||||
|
||||
If you already cloned without submodules:
|
||||
|
||||
```sh
|
||||
git submodule update --init --recursive
|
||||
```
|
||||
|
||||
Enable the repository-managed Git hooks (required once per clone):
|
||||
|
||||
```sh
|
||||
git config core.hooksPath .githooks
|
||||
chmod +x .githooks/pre-commit
|
||||
```
|
||||
|
||||
## Build
|
||||
|
||||
```sh
|
||||
pio run
|
||||
```
|
||||
|
||||
## Flash
|
||||
|
||||
```sh
|
||||
pio run --target upload
|
||||
```
|
||||
|
||||
## First checks before opening a PR
|
||||
|
||||
```sh
|
||||
./bin/clang-format-fix
|
||||
pio check --fail-on-defect low --fail-on-defect medium --fail-on-defect high
|
||||
pio run
|
||||
```
|
||||
|
||||
## What to read next
|
||||
|
||||
- [Architecture Overview](./architecture.md)
|
||||
- [Development Workflow](./development-workflow.md)
|
||||
- [Testing and Debugging](./testing-debugging.md)
|
||||
@@ -0,0 +1,48 @@
|
||||
# Testing and Debugging
|
||||
|
||||
CrossPoint runs on real hardware, so debugging usually combines local build checks and on-device logs.
|
||||
|
||||
## Local checks
|
||||
|
||||
Make sure `clang-format` 21+ is installed and available in `PATH` before running the formatting step.
|
||||
If needed, see [Getting Started](./getting-started.md).
|
||||
|
||||
```sh
|
||||
./bin/clang-format-fix
|
||||
pio check --fail-on-defect low --fail-on-defect medium --fail-on-defect high
|
||||
pio run
|
||||
```
|
||||
|
||||
## Flash and monitor
|
||||
|
||||
Flash firmware:
|
||||
|
||||
```sh
|
||||
pio run --target upload
|
||||
```
|
||||
|
||||
Open serial monitor:
|
||||
|
||||
```sh
|
||||
pio device monitor
|
||||
```
|
||||
|
||||
Optional enhanced monitor:
|
||||
|
||||
```sh
|
||||
python3 -m pip install pyserial colorama matplotlib
|
||||
python3 scripts/debugging_monitor.py
|
||||
```
|
||||
|
||||
## Useful bug report contents
|
||||
|
||||
- Firmware version and build environment
|
||||
- Exact steps to reproduce
|
||||
- Expected vs actual behavior
|
||||
- Serial logs from boot through failure
|
||||
- Whether issue reproduces after clearing `.crosspoint/` cache on SD card
|
||||
|
||||
## Common troubleshooting references
|
||||
|
||||
- [User Guide troubleshooting section](../../USER_GUIDE.md#7-troubleshooting-issues--escaping-bootloop)
|
||||
- [Webserver troubleshooting](../troubleshooting.md)
|
||||
@@ -0,0 +1,33 @@
|
||||
# Focus Reading
|
||||
|
||||
Focus Reading is a reading aid that bolds the first portion of each word, guiding your eyes to natural fixation points and helping you read faster with less effort. Some readers — particularly those with ADHD — find it helps them stay engaged with the text and reduces mind-wandering. It is inspired by the Bionic Reading technique.
|
||||
|
||||
<img src="./images/focus-reading/focus-reading.jpg" height="500" alt="Comparison of the same page with and without Focus Reading enabled" />
|
||||
|
||||
*Left: Focus Reading off. Right: Focus Reading on. Both using Literata.*
|
||||
|
||||
## Enabling Focus Reading
|
||||
|
||||
1. Open **Settings > Reader**
|
||||
2. Toggle **Focus Reading** on
|
||||
|
||||
Toggling the setting will trigger a re-index of your current book, the same as when changing font settings. Once indexing is complete, page turns proceed as normal. No changes are made to your EPUB files.
|
||||
|
||||
## Examples
|
||||
|
||||
<img src="./images/focus-reading/focus-reading-notoserif.jpg" height="500" alt="Focus Reading with Noto Serif font" />
|
||||
|
||||
*Focus Reading with Noto Serif font*
|
||||
|
||||
<img src="./images/focus-reading/focus-reading-merriweather.jpg" height="500" alt="Focus Reading with Merriweather font" />
|
||||
|
||||
*Focus Reading with Merriweather font*
|
||||
|
||||
<img src="./images/focus-reading/focus-reading-atkinson.jpg" height="500" alt="Focus Reading with Atkinson Hyperlegible Next font" />
|
||||
|
||||
*Focus Reading with Atkinson Hyperlegible Next font*
|
||||
|
||||
## Notes
|
||||
|
||||
- Focus Reading only applies to regular body text. Already-bold text (headings, emphasis) is left unchanged.
|
||||
- The setting is per-device, not per-book — it applies to all books while enabled.
|
||||
@@ -49,5 +49,5 @@ A convenient script `update_hyphenation.sh` is used to update all languages.
|
||||
To use it, run:
|
||||
|
||||
```sh
|
||||
./scripts/update_hypenation.sh
|
||||
./scripts/update_hyphenation.sh
|
||||
```
|
||||
|
||||
+11
-7
@@ -12,6 +12,10 @@ This guide explains the multi-language support system in CrossPoint Reader.
|
||||
- Swedish
|
||||
- Czech
|
||||
- Russian
|
||||
- Ukrainian
|
||||
- Polish
|
||||
- Danish
|
||||
- Turkish
|
||||
|
||||
---
|
||||
|
||||
@@ -51,7 +55,7 @@ A file looks like this:
|
||||
|
||||
```yaml
|
||||
_language_name: "Español"
|
||||
_language_code: "SPANISH"
|
||||
_language_code: "ES"
|
||||
_order: "1"
|
||||
|
||||
STR_CROSSPOINT: "CrossPoint"
|
||||
@@ -61,13 +65,13 @@ STR_BROWSE_FILES: "Buscar archivos"
|
||||
|
||||
**Metadata keys** (prefixed with `_`):
|
||||
- `_language_name` — Native display name shown to the user (e.g. "Français")
|
||||
- `_language_code` — C++ enum name (e.g. "FRENCH"). Must be a valid C++ identifier.
|
||||
- `_language_code` — C++ enum name (e.g. "FR"). Please use the [ISO Code](https://en.wikipedia.org/wiki/List_of_ISO_639_language_codes) of the language. Must be a valid C++ identifier.
|
||||
- `_order` — Controls the position in the Language enum (English is always 0)
|
||||
|
||||
**Rules:**
|
||||
- Use UTF-8 encoding
|
||||
- Every line must follow the format: `KEY: "value"`
|
||||
- Keys must be valid C++ identifiers (uppercase, strats with STR_)
|
||||
- Keys must be valid C++ identifiers (uppercase, starts with STR_)
|
||||
- Keys must be unique within a file
|
||||
- String values must be quoted
|
||||
- Use `\n` for newlines, `\\` for literal backslashes, `\"` for literal quotes inside values
|
||||
@@ -127,7 +131,7 @@ Create `lib/I18n/translations/italian.yaml`:
|
||||
|
||||
```yaml
|
||||
_language_name: "Italiano"
|
||||
_language_code: "ITALIAN"
|
||||
_language_code: "IT"
|
||||
_order: "7"
|
||||
|
||||
STR_CROSSPOINT: "CrossPoint"
|
||||
@@ -174,7 +178,7 @@ renderer.drawText(font, x, y, tr(STR_BROWSE_FILES));
|
||||
Serial.printf("Status: %s\n", tr(STR_CONNECTED));
|
||||
|
||||
// I18N - Shorthand for I18n::getInstance()
|
||||
I18N.setLanguage(Language::SPANISH);
|
||||
I18N.setLanguage(Language::ES);
|
||||
Language lang = I18N.getLanguage();
|
||||
|
||||
// === Full API ===
|
||||
@@ -188,7 +192,7 @@ const char* text = I18N.get(StrId::STR_SETTINGS_TITLE); // Direct call
|
||||
const char* text = I18N[StrId::STR_SETTINGS_TITLE]; // Operator overload
|
||||
|
||||
// Set language
|
||||
I18N.setLanguage(Language::SPANISH);
|
||||
I18N.setLanguage(Language::ES);
|
||||
|
||||
// Get current language
|
||||
Language lang = I18N.getLanguage();
|
||||
@@ -200,7 +204,7 @@ I18N.saveSettings();
|
||||
I18N.loadSettings();
|
||||
|
||||
// Get character set for font subsetting (static method)
|
||||
const char* chars = I18n::getCharacterSet(Language::FRENCH);
|
||||
const char* chars = I18n::getCharacterSet(Language::FR);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 216 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 211 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 207 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 260 KiB |
@@ -0,0 +1,104 @@
|
||||
# SD Card Fonts
|
||||
|
||||
CrossPoint supports loading additional fonts from the SD card, including fonts
|
||||
with extended Unicode coverage (CJK, Cyrillic, Greek, etc.).
|
||||
|
||||
## Installing Fonts
|
||||
|
||||
There are three ways to install fonts:
|
||||
|
||||
### Option 1: Download from device (recommended)
|
||||
|
||||
1. Connect your CrossPoint reader to WiFi
|
||||
2. Go to **Settings > System > Manage Fonts**
|
||||
3. Browse available font families and tap to download
|
||||
4. Downloaded fonts appear immediately in **Settings > Reader > Font Family**
|
||||
|
||||
### Option 2: Upload via web browser
|
||||
|
||||
1. Connect your CrossPoint reader to WiFi
|
||||
2. Open the web interface in your browser (shown on the WiFi screen)
|
||||
3. Navigate to the **Fonts** tab
|
||||
4. Upload `.cpfont` files using the upload form
|
||||
|
||||
### Option 3: Manual SD card copy
|
||||
|
||||
1. Download font files from the
|
||||
[crosspoint-fonts repository](https://github.com/crosspoint-reader/crosspoint-fonts)
|
||||
2. Copy font family folders to one of two locations on your SD card:
|
||||
|
||||
- `/.fonts/` — hidden directory (preferred; keeps the SD root tidy
|
||||
when mounted on a desktop)
|
||||
- `/fonts/` — visible directory (use this if your OS hides dot-files
|
||||
and you'd rather see the folder in your file manager)
|
||||
|
||||
Both roots are always scanned at boot and the results are merged: a
|
||||
family installed in `/fonts/` shows up even when `/.fonts/` also
|
||||
exists, and vice versa. The two roots only collide if the same family
|
||||
name appears in both — in that case the copy in `/.fonts/` wins and
|
||||
the duplicate in `/fonts/` is ignored.
|
||||
|
||||
SD Card Root/
|
||||
├── .fonts/ ← Hidden root (preferred)
|
||||
│ └── Literata/
|
||||
│ ├── Literata_12.cpfont
|
||||
│ ├── Literata_14.cpfont
|
||||
│ ├── Literata_16.cpfont
|
||||
│ └── Literata_18.cpfont
|
||||
└── fonts/ ← Visible root (equally valid)
|
||||
└── Merriweather/
|
||||
├── Merriweather_12.cpfont
|
||||
└── ...
|
||||
|
||||
3. Insert the SD card and power on your CrossPoint reader
|
||||
|
||||
## Available Pre-Built Fonts
|
||||
|
||||
The current list of pre-built fonts is maintained in the
|
||||
[crosspoint-fonts repository](https://github.com/crosspoint-reader/crosspoint-fonts).
|
||||
|
||||
## Converting Custom Fonts
|
||||
|
||||
To convert your own TrueType/OpenType fonts:
|
||||
|
||||
### Prerequisites
|
||||
|
||||
pip install freetype-py fonttools
|
||||
|
||||
### Single font (one style)
|
||||
|
||||
python3 lib/EpdFont/scripts/fontconvert_sdcard.py \
|
||||
MyFont-Regular.ttf \
|
||||
--intervals latin-ext \
|
||||
--sizes 12,14,16,18 \
|
||||
--style regular \
|
||||
--name MyFont \
|
||||
--output-dir ./MyFont/
|
||||
|
||||
### Multi-style font
|
||||
|
||||
python3 lib/EpdFont/scripts/fontconvert_sdcard.py \
|
||||
--regular MyFont-Regular.ttf \
|
||||
--bold MyFont-Bold.ttf \
|
||||
--italic MyFont-Italic.ttf \
|
||||
--bolditalic MyFont-BoldItalic.ttf \
|
||||
--intervals latin-ext \
|
||||
--sizes 12,14,16,18 \
|
||||
--name MyFont \
|
||||
--output-dir ./MyFont/
|
||||
|
||||
### Available Unicode interval presets
|
||||
|
||||
| Preset | Coverage |
|
||||
|--------|----------|
|
||||
| `ascii` | U+0020-U+007E (Basic Latin) |
|
||||
| `latin-ext` | European languages (Latin + Extended-A/B) |
|
||||
| `greek` | Greek + Extended Greek |
|
||||
| `cyrillic` | Cyrillic + Supplement |
|
||||
| `cjk` | CJK Unified Ideographs + Hiragana + Katakana + Fullwidth |
|
||||
| `hangul` | Korean Hangul syllables |
|
||||
| `builtin` | Matches built-in Bookerly coverage exactly |
|
||||
|
||||
Combine presets with commas: `--intervals latin-ext,greek,cyrillic`
|
||||
|
||||
Install custom fonts via WiFi upload or manual SD card copy.
|
||||
+27
-1
@@ -1,6 +1,6 @@
|
||||
# Translators
|
||||
|
||||
Below is a list of users and languages CrossPoint may support in the future.
|
||||
Below is a list of users and languages CrossPoint may support in the future.
|
||||
Note because a language is below does not mean there is official support for the language at this time.
|
||||
|
||||
## Contributing
|
||||
@@ -20,8 +20,13 @@ If you'd like to add your name to this list, please open a PR adding yourself an
|
||||
## Portuguese (Brazil)
|
||||
- [yagofarias](https://github.com/yagofarias)
|
||||
|
||||
## Portuguese (Portugal)
|
||||
- [victordomingos](https://github.com/victordomingos)
|
||||
|
||||
## Italian
|
||||
- [andreaturchet](https://github.com/andreaturchet)
|
||||
- [fragolinux](https://github.com/fragolinux)
|
||||
- [alan0ford](https://github.com/alan0ford)
|
||||
|
||||
## Russian
|
||||
- [madebyKir](https://github.com/madebyKir)
|
||||
@@ -31,6 +36,27 @@ If you'd like to add your name to this list, please open a PR adding yourself an
|
||||
- [yeyeto2788](https://github.com/yeyeto2788)
|
||||
- [Skrzakk](https://github.com/Skrzakk)
|
||||
- [pablohc](https://github.com/pablohc)
|
||||
- [DaniPhii](https://github.com/DaniPhii)
|
||||
|
||||
## Swedish
|
||||
- [dawiik](https://github.com/dawiik)
|
||||
- [steka](https://github.com/steka)
|
||||
|
||||
## Romanian
|
||||
- [ariel-lindemann](https://github.com/ariel-lindemann)
|
||||
|
||||
## Catalan
|
||||
- [angeldenom](https://github.com/angeldenom)
|
||||
|
||||
## Finnish
|
||||
- [plahteenlahti](https://github.com/plahteenlahti)
|
||||
|
||||
## Ukrainian
|
||||
- [mirus-ua](https://github.com/mirus-ua)
|
||||
- [KymAndriy](https://github.com/KymAndriy)
|
||||
|
||||
## Belarusian
|
||||
- [Dexif](https://github.com/dexif)
|
||||
|
||||
## Danish
|
||||
- [hajisan](https://github.com/hajisan)
|
||||
|
||||
@@ -1,37 +0,0 @@
|
||||
|
||||
This directory is intended for project header files.
|
||||
|
||||
A header file is a file containing C declarations and macro definitions
|
||||
to be shared between several project source files. You request the use of a
|
||||
header file in your project source file (C, C++, etc) located in `src` folder
|
||||
by including it, with the C preprocessing directive `#include'.
|
||||
|
||||
```src/main.c
|
||||
|
||||
#include "header.h"
|
||||
|
||||
int main (void)
|
||||
{
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
Including a header file produces the same results as copying the header file
|
||||
into each source file that needs it. Such copying would be time-consuming
|
||||
and error-prone. With a header file, the related declarations appear
|
||||
in only one place. If they need to be changed, they can be changed in one
|
||||
place, and programs that include the header file will automatically use the
|
||||
new version when next recompiled. The header file eliminates the labor of
|
||||
finding and changing all the copies as well as the risk that a failure to
|
||||
find one copy will result in inconsistencies within a program.
|
||||
|
||||
In C, the convention is to give header files names that end with `.h'.
|
||||
|
||||
Read more about using header files in official GCC documentation:
|
||||
|
||||
* Include Syntax
|
||||
* Include Operation
|
||||
* Once-Only Headers
|
||||
* Computed Includes
|
||||
|
||||
https://gcc.gnu.org/onlinedocs/cpp/Header-Files.html
|
||||
+125
-39
@@ -15,37 +15,46 @@ void EpdFont::getTextBounds(const char* string, const int startX, const int star
|
||||
return;
|
||||
}
|
||||
|
||||
int cursorX = startX;
|
||||
const int cursorY = startY;
|
||||
int lastBaseX = startX;
|
||||
int lastBaseAdvance = 0;
|
||||
int lastBaseLeft = 0;
|
||||
int lastBaseWidth = 0;
|
||||
int lastBaseTop = 0;
|
||||
bool hasBaseGlyph = false;
|
||||
constexpr int MIN_COMBINING_GAP_PX = 1;
|
||||
int32_t prevAdvanceFP = 0; // 12.4 fixed-point: prev glyph's advance + next kern for snap
|
||||
uint32_t cp;
|
||||
uint32_t prevCp = 0;
|
||||
while ((cp = utf8NextCodepoint(reinterpret_cast<const uint8_t**>(&string)))) {
|
||||
const EpdGlyph* glyph = getGlyph(cp);
|
||||
const bool isCombining = utf8IsCombiningMark(cp);
|
||||
|
||||
if (!glyph) {
|
||||
glyph = getGlyph(REPLACEMENT_GLYPH);
|
||||
if (!isCombining) {
|
||||
cp = applyLigatures(cp, string);
|
||||
}
|
||||
|
||||
const EpdGlyph* glyph = getGlyph(cp);
|
||||
if (!glyph) {
|
||||
// TODO: Better handle this?
|
||||
// Keep cursor movement stable when a base glyph is missing, but don't attach subsequent
|
||||
// combining marks to stale base metrics.
|
||||
if (!isCombining) {
|
||||
lastBaseX += fp4::toPixel(prevAdvanceFP); // flush pending advance before resetting
|
||||
prevCp = 0;
|
||||
prevAdvanceFP = 0;
|
||||
lastBaseLeft = 0;
|
||||
lastBaseWidth = 0;
|
||||
lastBaseTop = 0;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
const bool isCombining = utf8IsCombiningMark(cp);
|
||||
int raiseBy = 0;
|
||||
if (isCombining && hasBaseGlyph) {
|
||||
const int currentGap = glyph->top - glyph->height - lastBaseTop;
|
||||
if (currentGap < MIN_COMBINING_GAP_PX) {
|
||||
raiseBy = MIN_COMBINING_GAP_PX - currentGap;
|
||||
}
|
||||
const int raiseBy = isCombining ? combiningMark::raiseAboveBase(glyph->top, glyph->height, lastBaseTop) : 0;
|
||||
|
||||
if (!isCombining && prevCp != 0) {
|
||||
const auto kernFP = getKerning(prevCp, cp); // 4.4 fixed-point kern
|
||||
lastBaseX += fp4::toPixel(prevAdvanceFP + kernFP);
|
||||
}
|
||||
|
||||
const int glyphBaseX = (isCombining && hasBaseGlyph) ? (lastBaseX + lastBaseAdvance / 2) : cursorX;
|
||||
const int glyphBaseY = cursorY - raiseBy;
|
||||
const int glyphBaseX =
|
||||
isCombining ? combiningMark::centerOver(lastBaseX, lastBaseLeft, lastBaseWidth, glyph->left, glyph->width)
|
||||
: lastBaseX;
|
||||
const int glyphBaseY = startY - raiseBy;
|
||||
|
||||
*minX = std::min(*minX, glyphBaseX + glyph->left);
|
||||
*maxX = std::max(*maxX, glyphBaseX + glyph->left + glyph->width);
|
||||
@@ -53,11 +62,11 @@ void EpdFont::getTextBounds(const char* string, const int startX, const int star
|
||||
*maxY = std::max(*maxY, glyphBaseY + glyph->top);
|
||||
|
||||
if (!isCombining) {
|
||||
lastBaseX = cursorX;
|
||||
lastBaseAdvance = glyph->advanceX;
|
||||
lastBaseLeft = glyph->left;
|
||||
lastBaseWidth = glyph->width;
|
||||
lastBaseTop = glyph->top;
|
||||
hasBaseGlyph = true;
|
||||
cursorX += glyph->advanceX;
|
||||
prevAdvanceFP = glyph->advanceX; // 12.4 fixed-point
|
||||
prevCp = cp;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -71,30 +80,107 @@ void EpdFont::getTextDimensions(const char* string, int* w, int* h) const {
|
||||
*h = maxY - minY;
|
||||
}
|
||||
|
||||
static uint8_t lookupKernClass(const EpdKernClassEntry* entries, const uint16_t count, const uint32_t cp) {
|
||||
if (!entries || count == 0 || cp > 0xFFFF) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const auto target = static_cast<uint16_t>(cp);
|
||||
const auto* end = entries + count;
|
||||
|
||||
// lower_bound: exact-key lookup. Finds the first entry with codepoint >= target,
|
||||
// then the equality check confirms an exact match exists.
|
||||
const auto it = std::lower_bound(
|
||||
entries, end, target, [](const EpdKernClassEntry& entry, uint16_t value) { return entry.codepoint < value; });
|
||||
|
||||
if (it != end && it->codepoint == target) {
|
||||
return it->classId;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
int8_t EpdFont::getKerning(const uint32_t leftCp, const uint32_t rightCp) const {
|
||||
if (!data->kernMatrix) {
|
||||
return 0;
|
||||
}
|
||||
const uint8_t lc = lookupKernClass(data->kernLeftClasses, data->kernLeftEntryCount, leftCp);
|
||||
if (lc == 0) return 0;
|
||||
const uint8_t rc = lookupKernClass(data->kernRightClasses, data->kernRightEntryCount, rightCp);
|
||||
if (rc == 0) return 0;
|
||||
return data->kernMatrix[(lc - 1) * data->kernRightClassCount + (rc - 1)];
|
||||
}
|
||||
|
||||
uint32_t EpdFont::getLigature(const uint32_t leftCp, const uint32_t rightCp) const {
|
||||
const auto* pairs = data->ligaturePairs;
|
||||
const auto count = data->ligaturePairCount;
|
||||
if (!pairs || count == 0 || leftCp > 0xFFFF || rightCp > 0xFFFF) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const uint32_t key = (leftCp << 16) | rightCp;
|
||||
const auto* end = pairs + count;
|
||||
|
||||
// lower_bound: exact-key lookup. Finds the first entry with pair >= key,
|
||||
// then the equality check confirms an exact match exists.
|
||||
const auto it =
|
||||
std::lower_bound(pairs, end, key, [](const EpdLigaturePair& pair, uint32_t value) { return pair.pair < value; });
|
||||
|
||||
if (it != end && it->pair == key) {
|
||||
return it->ligatureCp;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
uint32_t EpdFont::applyLigatures(uint32_t cp, const char*& text) const {
|
||||
if (!data->ligaturePairs || data->ligaturePairCount == 0) {
|
||||
return cp;
|
||||
}
|
||||
while (true) {
|
||||
const auto saved = reinterpret_cast<const uint8_t*>(text);
|
||||
const uint32_t nextCp = utf8NextCodepoint(reinterpret_cast<const uint8_t**>(&text));
|
||||
if (nextCp == 0) break;
|
||||
const uint32_t lig = getLigature(cp, nextCp);
|
||||
if (lig == 0) {
|
||||
text = reinterpret_cast<const char*>(saved);
|
||||
break;
|
||||
}
|
||||
cp = lig;
|
||||
}
|
||||
return cp;
|
||||
}
|
||||
|
||||
const EpdGlyph* EpdFont::getGlyph(const uint32_t cp) const {
|
||||
const EpdUnicodeInterval* intervals = data->intervals;
|
||||
const int count = data->intervalCount;
|
||||
if (count == 0 && !data->glyphMissHandler) return nullptr;
|
||||
|
||||
if (count == 0) return nullptr;
|
||||
if (count > 0) {
|
||||
const EpdUnicodeInterval* intervals = data->intervals;
|
||||
const auto* end = intervals + count;
|
||||
|
||||
// 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;
|
||||
// upper_bound: range lookup. Finds the first interval with first > cp, so the
|
||||
// interval just before it is the last one with first <= cp. That's the only
|
||||
// candidate that could contain cp. Then we verify cp <= candidate.last.
|
||||
const auto it = std::upper_bound(
|
||||
intervals, end, cp, [](uint32_t value, const EpdUnicodeInterval& interval) { return value < interval.first; });
|
||||
|
||||
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)];
|
||||
if (it != intervals) {
|
||||
const auto& interval = *(it - 1);
|
||||
if (cp <= interval.last) {
|
||||
return &data->glyph[interval.offset + (cp - interval.first)];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Codepoint not in interval table — try on-demand loading (SD card fonts).
|
||||
if (data->glyphMissHandler) {
|
||||
const EpdGlyph* loaded = data->glyphMissHandler(data->glyphMissCtx, cp);
|
||||
if (loaded) return loaded;
|
||||
}
|
||||
|
||||
if (cp != REPLACEMENT_GLYPH) {
|
||||
return getGlyph(REPLACEMENT_GLYPH);
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
@@ -11,4 +11,16 @@ class EpdFont {
|
||||
void getTextDimensions(const char* string, int* w, int* h) const;
|
||||
|
||||
const EpdGlyph* getGlyph(uint32_t cp) const;
|
||||
|
||||
/// Returns the kerning adjustment (4.4 fixed-point in pixels) between two codepoints.
|
||||
/// Returns 0 if no kerning data exists for the pair.
|
||||
int8_t getKerning(uint32_t leftCp, uint32_t rightCp) const;
|
||||
|
||||
/// Returns the ligature codepoint for a pair, or 0 if no ligature exists.
|
||||
uint32_t getLigature(uint32_t leftCp, uint32_t rightCp) const;
|
||||
|
||||
/// Greedily applies ligature substitutions starting from cp, consuming
|
||||
/// as many following codepoints from text as possible. Returns the
|
||||
/// (possibly substituted) codepoint; advances text past consumed chars.
|
||||
uint32_t applyLigatures(uint32_t cp, const char*& text) const;
|
||||
};
|
||||
|
||||
+102
-4
@@ -4,11 +4,73 @@
|
||||
#pragma once
|
||||
#include <cstdint>
|
||||
|
||||
/// Font metrics use "fixed-point 4" (4 fractional bits, i.e. 1/16-pixel
|
||||
/// resolution). Both the 12.4 glyph advances (uint16_t) and the 4.4 kern
|
||||
/// values (int8_t) share the same 4 fractional bits, so they can be freely
|
||||
/// added before snapping to whole pixels.
|
||||
///
|
||||
/// Rendering and measurement use "differential rounding": each glyph step
|
||||
/// (previous advance + current kern) is combined in fixed-point and snapped
|
||||
/// to a pixel as one unit. This guarantees identical character pairs always
|
||||
/// produce the same pixel spacing, regardless of position on the line.
|
||||
///
|
||||
/// The helpers below eliminate the raw bit-shifts that would otherwise be
|
||||
/// scattered across every layout / measurement call site.
|
||||
namespace fp4 {
|
||||
constexpr int FRAC_BITS = 4;
|
||||
constexpr int32_t HALF = 1 << (FRAC_BITS - 1); // 8, added before shift for round-to-nearest
|
||||
|
||||
/// Convert an integer pixel value to 12.4 fixed-point.
|
||||
constexpr int32_t fromPixel(int px) { return static_cast<int32_t>(px) << FRAC_BITS; }
|
||||
|
||||
/// Snap a fixed-point value to the nearest integer pixel.
|
||||
constexpr int toPixel(int32_t fp) { return static_cast<int>((fp + HALF) >> FRAC_BITS); }
|
||||
|
||||
/// Convert a fixed-point value to float (mainly useful for debug logging).
|
||||
constexpr float toFloat(int32_t fp) { return fp / static_cast<float>(1 << FRAC_BITS); }
|
||||
} // namespace fp4
|
||||
|
||||
/// Helpers for positioning Unicode combining marks (U+0300 ff.) over a
|
||||
/// preceding base glyph without GPOS anchor tables.
|
||||
namespace combiningMark {
|
||||
|
||||
constexpr int MIN_GAP_PX = 1;
|
||||
|
||||
/// Compute the cursor-X at which to render a combining mark so its bitmap
|
||||
/// is visually centered over the base glyph's bitmap.
|
||||
constexpr int centerOver(int baseCursorPos, int baseLeft, int baseWidth, int markLeft, int markWidth) {
|
||||
return baseCursorPos + baseLeft + baseWidth / 2 - markWidth / 2 - markLeft;
|
||||
}
|
||||
|
||||
/// Rotated-90CW variant of centerOver. In the rotated coordinate system
|
||||
/// renderCharImpl uses (cursorY - left) instead of (cursorX + left), so
|
||||
/// every left/width term inverts sign.
|
||||
constexpr int centerOverRotated90CW(int baseCursorPos, int baseLeft, int baseWidth, int markLeft, int markWidth) {
|
||||
return baseCursorPos - baseLeft - baseWidth / 2 + markWidth / 2 + markLeft;
|
||||
}
|
||||
|
||||
/// For combining marks that sit entirely above the baseline, compute how many
|
||||
/// pixels to raise the mark so there is at least MIN_GAP_PX between its bottom
|
||||
/// edge and the top of the base glyph. Returns 0 for marks that extend to or
|
||||
/// below the baseline (e.g. cedilla, dot-below, ogonek).
|
||||
constexpr int raiseAboveBase(int markTop, int markHeight, int baseTop) {
|
||||
if (markTop - markHeight <= 0) return 0;
|
||||
const int gap = markTop - markHeight - baseTop;
|
||||
return (gap < MIN_GAP_PX) ? (MIN_GAP_PX - gap) : 0;
|
||||
}
|
||||
|
||||
} // namespace combiningMark
|
||||
|
||||
/// Fixed-point conventions used by EpdGlyph and EpdFontData:
|
||||
/// advanceX: 12.4 unsigned fixed-point in uint16_t (use fp4::toPixel)
|
||||
/// kernMatrix: 4.4 signed fixed-point in int8_t (use fp4::toPixel)
|
||||
/// Both share 4 fractional bits so they combine directly in an accumulator.
|
||||
|
||||
/// Font data stored PER GLYPH
|
||||
typedef struct {
|
||||
uint8_t width; ///< Bitmap dimensions in pixels
|
||||
uint8_t height; ///< Bitmap dimensions in pixels
|
||||
uint8_t advanceX; ///< Distance to advance cursor (x axis)
|
||||
uint16_t advanceX; ///< Distance to advance cursor (x axis), 12.4 fixed-point in pixels
|
||||
int16_t left; ///< X dist from cursor pos to UL corner
|
||||
int16_t top; ///< Y dist from cursor pos to UL corner
|
||||
uint16_t dataLength; ///< Size of the font data.
|
||||
@@ -21,7 +83,7 @@ typedef struct {
|
||||
uint32_t compressedSize; ///< Compressed DEFLATE stream size
|
||||
uint32_t uncompressedSize; ///< Decompressed size
|
||||
uint16_t glyphCount; ///< Number of glyphs in this group
|
||||
uint16_t firstGlyphIndex; ///< First glyph index in the global glyph array
|
||||
uint32_t firstGlyphIndex; ///< First glyph index in the global glyph array
|
||||
} EpdFontGroup;
|
||||
|
||||
/// Glyph interval structure
|
||||
@@ -31,6 +93,20 @@ typedef struct {
|
||||
uint32_t offset; ///< Index of the first code point into the glyph array
|
||||
} EpdUnicodeInterval;
|
||||
|
||||
/// Maps a codepoint to a kerning class ID, sorted by codepoint for binary search.
|
||||
/// Class IDs are 1-based; codepoints not in the table have implicit class 0 (no kerning).
|
||||
typedef struct {
|
||||
uint16_t codepoint; ///< Unicode codepoint
|
||||
uint8_t classId; ///< 1-based kerning class ID
|
||||
} __attribute__((packed)) EpdKernClassEntry;
|
||||
|
||||
/// Ligature substitution for a specific glyph pair, sorted by `pair` for binary search.
|
||||
/// `pair` encodes (leftCodepoint << 16 | rightCodepoint) for single-key lookup.
|
||||
typedef struct {
|
||||
uint32_t pair; ///< Packed codepoint pair (left << 16 | right)
|
||||
uint32_t ligatureCp; ///< Codepoint of the replacement ligature glyph
|
||||
} __attribute__((packed)) EpdLigaturePair;
|
||||
|
||||
/// Data stored for FONT AS A WHOLE
|
||||
typedef struct {
|
||||
const uint8_t* bitmap; ///< Glyph bitmaps, concatenated
|
||||
@@ -41,6 +117,28 @@ typedef struct {
|
||||
int ascender; ///< Maximal height of a glyph above the base line
|
||||
int descender; ///< Maximal height of a glyph below the base line
|
||||
bool is2Bit;
|
||||
const EpdFontGroup* groups; ///< NULL for uncompressed fonts
|
||||
uint16_t groupCount; ///< 0 for uncompressed fonts
|
||||
const EpdFontGroup* groups; ///< NULL for uncompressed fonts
|
||||
uint16_t groupCount; ///< 0 for uncompressed fonts
|
||||
const uint16_t* glyphToGroup; ///< Per-glyph group ID (nullptr for contiguous-group fonts)
|
||||
const EpdKernClassEntry* kernLeftClasses; ///< Sorted left-side class map (nullptr if none)
|
||||
const EpdKernClassEntry* kernRightClasses; ///< Sorted right-side class map (nullptr if none)
|
||||
const int8_t* kernMatrix; ///< Flat leftClassCount x rightClassCount matrix, 4.4 fixed-point in pixels
|
||||
uint16_t kernLeftEntryCount; ///< Entries in kernLeftClasses
|
||||
uint16_t kernRightEntryCount; ///< Entries in kernRightClasses
|
||||
uint8_t kernLeftClassCount; ///< Number of distinct left classes (matrix rows)
|
||||
uint8_t kernRightClassCount; ///< Number of distinct right classes (matrix cols)
|
||||
const EpdLigaturePair* ligaturePairs; ///< Sorted ligature pair table (nullptr if none)
|
||||
uint32_t ligaturePairCount; ///< Number of entries in ligaturePairs
|
||||
|
||||
/// On-demand glyph loading for fonts that don't keep all glyphs in RAM (e.g. SD card fonts).
|
||||
/// Called by getGlyph() when a codepoint is not found in the interval table.
|
||||
/// Returns a valid EpdGlyph* with correct metadata, or nullptr to fall back to the
|
||||
/// replacement glyph. The returned pointer is valid until the next glyphMissHandler
|
||||
/// call that causes a ring-buffer eviction — callers must consume it (measure or draw)
|
||||
/// before requesting another missed glyph.
|
||||
const EpdGlyph* (*glyphMissHandler)(void* ctx, uint32_t codepoint);
|
||||
|
||||
/// Context pointer for glyphMissHandler (typically SdCardFont*). Also used by
|
||||
/// GfxRenderer::getGlyphBitmap() to retrieve overflow bitmaps via SdCardFont.
|
||||
void* glyphMissCtx;
|
||||
} EpdFontData;
|
||||
|
||||
@@ -26,4 +26,12 @@ const EpdFontData* EpdFontFamily::getData(const Style style) const { return getF
|
||||
|
||||
const EpdGlyph* EpdFontFamily::getGlyph(const uint32_t cp, const Style style) const {
|
||||
return getFont(style)->getGlyph(cp);
|
||||
};
|
||||
}
|
||||
|
||||
int8_t EpdFontFamily::getKerning(const uint32_t leftCp, const uint32_t rightCp, const Style style) const {
|
||||
return getFont(style)->getKerning(leftCp, rightCp);
|
||||
}
|
||||
|
||||
uint32_t EpdFontFamily::applyLigatures(const uint32_t cp, const char*& text, const Style style) const {
|
||||
return getFont(style)->applyLigatures(cp, text);
|
||||
}
|
||||
|
||||
@@ -12,6 +12,8 @@ class EpdFontFamily {
|
||||
void getTextDimensions(const char* string, int* w, int* h, Style style = REGULAR) const;
|
||||
const EpdFontData* getData(Style style = REGULAR) const;
|
||||
const EpdGlyph* getGlyph(uint32_t cp, Style style = REGULAR) const;
|
||||
int8_t getKerning(uint32_t leftCp, uint32_t rightCp, Style style = REGULAR) const;
|
||||
uint32_t applyLigatures(uint32_t cp, const char*& text, Style style = REGULAR) const;
|
||||
|
||||
private:
|
||||
const EpdFont* regular;
|
||||
|
||||
@@ -1,37 +1,55 @@
|
||||
#include "FontDecompressor.h"
|
||||
|
||||
#include <Arduino.h>
|
||||
#include <Logging.h>
|
||||
#include <uzlib.h>
|
||||
#include <Utf8.h>
|
||||
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
|
||||
FontDecompressor::~FontDecompressor() { deinit(); }
|
||||
|
||||
bool FontDecompressor::init() {
|
||||
clearCache();
|
||||
memset(&decomp, 0, sizeof(decomp));
|
||||
return true;
|
||||
}
|
||||
|
||||
void FontDecompressor::freeAllEntries() {
|
||||
for (auto& entry : cache) {
|
||||
if (entry.data) {
|
||||
free(entry.data);
|
||||
entry.data = nullptr;
|
||||
}
|
||||
entry.valid = false;
|
||||
}
|
||||
void FontDecompressor::deinit() {
|
||||
freePageBuffer();
|
||||
freeHotGroup();
|
||||
}
|
||||
|
||||
void FontDecompressor::deinit() { freeAllEntries(); }
|
||||
|
||||
void FontDecompressor::clearCache() {
|
||||
freeAllEntries();
|
||||
accessCounter = 0;
|
||||
freePageBuffer();
|
||||
freeHotGroup();
|
||||
}
|
||||
|
||||
uint16_t FontDecompressor::getGroupIndex(const EpdFontData* fontData, uint16_t glyphIndex) {
|
||||
void FontDecompressor::freePageBuffer() {
|
||||
for (uint8_t s = 0; s < pageSlotCount; s++) {
|
||||
free(pageSlots[s].buffer);
|
||||
free(pageSlots[s].glyphs);
|
||||
pageSlots[s] = {};
|
||||
}
|
||||
pageSlotCount = 0;
|
||||
}
|
||||
|
||||
void FontDecompressor::freeHotGroup() {
|
||||
hotGroup.clear();
|
||||
hotGroup.shrink_to_fit();
|
||||
hotGroupFont = nullptr;
|
||||
hotGroupIndex = UINT16_MAX;
|
||||
hotGlyphBuf.clear();
|
||||
hotGlyphBuf.shrink_to_fit();
|
||||
}
|
||||
|
||||
uint16_t FontDecompressor::getGroupIndex(const EpdFontData* fontData, uint32_t glyphIndex) {
|
||||
// O(1) path for frequency-grouped fonts with glyphToGroup mapping
|
||||
if (fontData->glyphToGroup != nullptr) {
|
||||
return fontData->glyphToGroup[glyphIndex];
|
||||
}
|
||||
|
||||
// Contiguous-group fonts: linear scan
|
||||
for (uint16_t i = 0; i < fontData->groupCount; i++) {
|
||||
uint16_t first = fontData->groups[i].firstGlyphIndex;
|
||||
uint32_t first = fontData->groups[i].firstGlyphIndex;
|
||||
if (glyphIndex >= first && glyphIndex < first + fontData->groups[i].glyphCount) {
|
||||
return i;
|
||||
}
|
||||
@@ -39,109 +57,462 @@ uint16_t FontDecompressor::getGroupIndex(const EpdFontData* fontData, uint16_t g
|
||||
return fontData->groupCount; // sentinel = not found
|
||||
}
|
||||
|
||||
FontDecompressor::CacheEntry* FontDecompressor::findInCache(const EpdFontData* fontData, uint16_t groupIndex) {
|
||||
for (auto& entry : cache) {
|
||||
if (entry.valid && entry.font == fontData && entry.groupIndex == groupIndex) {
|
||||
return &entry;
|
||||
}
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
FontDecompressor::CacheEntry* FontDecompressor::findEvictionCandidate() {
|
||||
// Find an invalid slot first
|
||||
for (auto& entry : cache) {
|
||||
if (!entry.valid) {
|
||||
return &entry;
|
||||
}
|
||||
}
|
||||
// Otherwise evict LRU
|
||||
CacheEntry* lru = &cache[0];
|
||||
for (auto& entry : cache) {
|
||||
if (entry.lastUsed < lru->lastUsed) {
|
||||
lru = &entry;
|
||||
}
|
||||
}
|
||||
return lru;
|
||||
}
|
||||
|
||||
bool FontDecompressor::decompressGroup(const EpdFontData* fontData, uint16_t groupIndex, CacheEntry* entry) {
|
||||
bool FontDecompressor::decompressGroup(const EpdFontData* fontData, uint16_t groupIndex, uint8_t* outBuf,
|
||||
uint32_t outSize) {
|
||||
const EpdFontGroup& group = fontData->groups[groupIndex];
|
||||
|
||||
// Free old buffer if reusing a slot
|
||||
if (entry->data) {
|
||||
free(entry->data);
|
||||
entry->data = nullptr;
|
||||
}
|
||||
entry->valid = false;
|
||||
|
||||
// Allocate output buffer
|
||||
auto* outBuf = static_cast<uint8_t*>(malloc(group.uncompressedSize));
|
||||
if (!outBuf) {
|
||||
LOG_ERR("FDC", "Failed to allocate %u bytes for group %u", group.uncompressedSize, groupIndex);
|
||||
const uint32_t tDecomp = millis();
|
||||
inflateReader.init(false);
|
||||
inflateReader.setSource(&fontData->bitmap[group.compressedOffset], group.compressedSize);
|
||||
if (!inflateReader.read(outBuf, outSize)) {
|
||||
stats.decompressTimeMs += millis() - tDecomp;
|
||||
LOG_ERR("FDC", "Decompression failed for group %u", groupIndex);
|
||||
return false;
|
||||
}
|
||||
|
||||
// Decompress using uzlib
|
||||
const uint8_t* inputBuf = &fontData->bitmap[group.compressedOffset];
|
||||
|
||||
uzlib_uncompress_init(&decomp, NULL, 0);
|
||||
decomp.source = inputBuf;
|
||||
decomp.source_limit = inputBuf + group.compressedSize;
|
||||
decomp.dest_start = outBuf;
|
||||
decomp.dest = outBuf;
|
||||
decomp.dest_limit = outBuf + group.uncompressedSize;
|
||||
|
||||
int res = uzlib_uncompress(&decomp);
|
||||
|
||||
if (res < 0 || decomp.dest != decomp.dest_limit) {
|
||||
LOG_ERR("FDC", "Decompression failed for group %u (status %d)", groupIndex, res);
|
||||
free(outBuf);
|
||||
return false;
|
||||
}
|
||||
|
||||
entry->font = fontData;
|
||||
entry->groupIndex = groupIndex;
|
||||
entry->data = outBuf;
|
||||
entry->dataSize = group.uncompressedSize;
|
||||
entry->valid = true;
|
||||
stats.decompressTimeMs += millis() - tDecomp;
|
||||
return true;
|
||||
}
|
||||
|
||||
const uint8_t* FontDecompressor::getBitmap(const EpdFontData* fontData, const EpdGlyph* glyph, uint16_t glyphIndex) {
|
||||
// --- Byte-aligned helpers ---
|
||||
|
||||
uint32_t FontDecompressor::getAlignedOffset(const EpdFontData* fontData, uint16_t groupIndex, uint32_t glyphIndex) {
|
||||
uint32_t offset = 0;
|
||||
|
||||
auto accumGlyph = [&](const EpdGlyph& g) {
|
||||
if (g.width > 0 && g.height > 0) {
|
||||
offset += ((g.width + 3) / 4) * g.height;
|
||||
}
|
||||
};
|
||||
|
||||
if (fontData->glyphToGroup) {
|
||||
// Frequency-grouped: scan glyphs before glyphIndex that belong to this group
|
||||
for (uint32_t i = 0; i < glyphIndex; i++) {
|
||||
if (fontData->glyphToGroup[i] == groupIndex) {
|
||||
accumGlyph(fontData->glyph[i]);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Contiguous-group: sum aligned sizes of preceding glyphs in the group
|
||||
const EpdFontGroup& group = fontData->groups[groupIndex];
|
||||
for (uint32_t i = group.firstGlyphIndex; i < glyphIndex; i++) {
|
||||
accumGlyph(fontData->glyph[i]);
|
||||
}
|
||||
}
|
||||
|
||||
return offset;
|
||||
}
|
||||
|
||||
void FontDecompressor::compactSingleGlyph(const uint8_t* alignedSrc, uint8_t* packedDst, uint8_t width,
|
||||
uint8_t height) {
|
||||
if (width == 0 || height == 0) return;
|
||||
const uint32_t rowStride = (width + 3) / 4;
|
||||
if (width % 4 == 0) {
|
||||
memcpy(packedDst, alignedSrc, rowStride * height);
|
||||
return;
|
||||
}
|
||||
uint8_t outByte = 0, outBits = 0;
|
||||
uint32_t writeIdx = 0;
|
||||
for (uint8_t y = 0; y < height; y++) {
|
||||
for (uint8_t x = 0; x < width; x++) {
|
||||
outByte = (outByte << 2) | ((alignedSrc[y * rowStride + x / 4] >> ((3 - (x % 4)) * 2)) & 0x3);
|
||||
outBits += 2;
|
||||
if (outBits == 8) {
|
||||
packedDst[writeIdx++] = outByte;
|
||||
outByte = 0;
|
||||
outBits = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (outBits > 0) packedDst[writeIdx] = outByte << (8 - outBits);
|
||||
}
|
||||
|
||||
// --- getBitmap: page buffer → hot group → decompress ---
|
||||
|
||||
const uint8_t* FontDecompressor::getBitmap(const EpdFontData* fontData, const EpdGlyph* glyph, uint32_t glyphIndex) {
|
||||
const uint32_t tStart = micros();
|
||||
stats.getBitmapCalls++;
|
||||
|
||||
if (!fontData->groups || fontData->groupCount == 0) {
|
||||
stats.getBitmapTimeUs += micros() - tStart;
|
||||
return &fontData->bitmap[glyph->dataOffset];
|
||||
}
|
||||
|
||||
// Check page buffer slots (populated by prewarmCache — one slot per font style)
|
||||
for (uint8_t s = 0; s < pageSlotCount; s++) {
|
||||
const auto& slot = pageSlots[s];
|
||||
if (slot.fontData != fontData || slot.glyphCount == 0) continue;
|
||||
|
||||
int left = 0, right = slot.glyphCount - 1;
|
||||
while (left <= right) {
|
||||
int mid = left + (right - left) / 2;
|
||||
if (slot.glyphs[mid].glyphIndex == glyphIndex) {
|
||||
if (slot.glyphs[mid].bufferOffset != UINT32_MAX) {
|
||||
stats.cacheHits++;
|
||||
stats.getBitmapTimeUs += micros() - tStart;
|
||||
return &slot.buffer[slot.glyphs[mid].bufferOffset];
|
||||
}
|
||||
break; // Not extracted during prewarm; fall through to hot-group path
|
||||
}
|
||||
if (slot.glyphs[mid].glyphIndex < glyphIndex)
|
||||
left = mid + 1;
|
||||
else
|
||||
right = mid - 1;
|
||||
}
|
||||
break; // Found the right slot but glyph wasn't in it; don't check other slots
|
||||
}
|
||||
|
||||
// Fallback: hot group slot
|
||||
uint16_t groupIndex = getGroupIndex(fontData, glyphIndex);
|
||||
if (groupIndex >= fontData->groupCount) {
|
||||
LOG_ERR("FDC", "Glyph %u not found in any group", glyphIndex);
|
||||
stats.getBitmapTimeUs += micros() - tStart;
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
// Check cache
|
||||
CacheEntry* entry = findInCache(fontData, groupIndex);
|
||||
if (entry) {
|
||||
entry->lastUsed = ++accessCounter;
|
||||
if (glyph->dataOffset + glyph->dataLength > entry->dataSize) {
|
||||
LOG_ERR("FDC", "dataOffset %u + dataLength %u out of bounds for group %u (size %u)", glyph->dataOffset,
|
||||
glyph->dataLength, groupIndex, entry->dataSize);
|
||||
// Check if hot group already has this group decompressed — if not, decompress it
|
||||
if (!(!hotGroup.empty() && hotGroupFont == fontData && hotGroupIndex == groupIndex)) {
|
||||
stats.cacheMisses++;
|
||||
const EpdFontGroup& group = fontData->groups[groupIndex];
|
||||
|
||||
hotGroup.resize(group.uncompressedSize);
|
||||
if (hotGroup.empty()) {
|
||||
LOG_ERR("FDC", "Failed to allocate %u bytes for hot group %u", group.uncompressedSize, groupIndex);
|
||||
hotGroupFont = nullptr;
|
||||
hotGroupIndex = UINT16_MAX;
|
||||
stats.getBitmapTimeUs += micros() - tStart;
|
||||
return nullptr;
|
||||
}
|
||||
return &entry->data[glyph->dataOffset];
|
||||
|
||||
if (!decompressGroup(fontData, groupIndex, hotGroup.data(), group.uncompressedSize)) {
|
||||
hotGroup.clear();
|
||||
hotGroup.shrink_to_fit();
|
||||
hotGroupFont = nullptr;
|
||||
hotGroupIndex = UINT16_MAX;
|
||||
stats.getBitmapTimeUs += micros() - tStart;
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
hotGroupFont = fontData;
|
||||
hotGroupIndex = groupIndex;
|
||||
stats.hotGroupBytes = group.uncompressedSize;
|
||||
} else {
|
||||
stats.cacheHits++;
|
||||
}
|
||||
|
||||
// Cache miss - decompress
|
||||
entry = findEvictionCandidate();
|
||||
if (!decompressGroup(fontData, groupIndex, entry)) {
|
||||
// Compact just the requested glyph from byte-aligned data into scratch buffer
|
||||
if (glyph->dataLength > hotGlyphBuf.size()) {
|
||||
hotGlyphBuf.resize(glyph->dataLength);
|
||||
}
|
||||
if (hotGlyphBuf.empty()) {
|
||||
stats.getBitmapTimeUs += micros() - tStart;
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
entry->lastUsed = ++accessCounter;
|
||||
if (glyph->dataOffset + glyph->dataLength > entry->dataSize) {
|
||||
LOG_ERR("FDC", "dataOffset %u + dataLength %u out of bounds for group %u (size %u)", glyph->dataOffset,
|
||||
glyph->dataLength, groupIndex, entry->dataSize);
|
||||
return nullptr;
|
||||
uint32_t alignedOff = getAlignedOffset(fontData, groupIndex, glyphIndex);
|
||||
compactSingleGlyph(&hotGroup[alignedOff], hotGlyphBuf.data(), glyph->width, glyph->height);
|
||||
stats.getBitmapTimeUs += micros() - tStart;
|
||||
return hotGlyphBuf.data();
|
||||
}
|
||||
|
||||
// --- Prewarm: pre-decompress glyph bitmaps for a page of text ---
|
||||
|
||||
int32_t FontDecompressor::findGlyphIndex(const EpdFontData* fontData, uint32_t codepoint) {
|
||||
const EpdUnicodeInterval* intervals = fontData->intervals;
|
||||
const int count = fontData->intervalCount;
|
||||
|
||||
if (count == 0) return -1;
|
||||
|
||||
// Binary search
|
||||
int left = 0;
|
||||
int right = count - 1;
|
||||
|
||||
while (left <= right) {
|
||||
const int mid = left + (right - left) / 2;
|
||||
const EpdUnicodeInterval* interval = &intervals[mid];
|
||||
|
||||
if (codepoint < interval->first) {
|
||||
right = mid - 1;
|
||||
} else if (codepoint > interval->last) {
|
||||
left = mid + 1;
|
||||
} else {
|
||||
return static_cast<int32_t>(interval->offset + (codepoint - interval->first));
|
||||
}
|
||||
}
|
||||
return &entry->data[glyph->dataOffset];
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
int FontDecompressor::prewarmCache(const EpdFontData* fontData, const char* utf8Text) {
|
||||
if (!fontData || !fontData->groups || !utf8Text) return 0;
|
||||
|
||||
// Allocate the next available slot (caller must call freePageBuffer/clearCache to reset)
|
||||
if (pageSlotCount >= MAX_PAGE_SLOTS) {
|
||||
LOG_ERR("FDC", "All %u page buffer slots full, cannot prewarm fontData=%p", MAX_PAGE_SLOTS, (void*)fontData);
|
||||
return -1;
|
||||
}
|
||||
PageSlot& slot = pageSlots[pageSlotCount];
|
||||
|
||||
// Step 1: Collect unique glyph indices needed for this page
|
||||
uint32_t neededGlyphs[MAX_PAGE_GLYPHS];
|
||||
uint16_t glyphCount = 0;
|
||||
bool glyphCapWarned = false;
|
||||
|
||||
const unsigned char* p = reinterpret_cast<const unsigned char*>(utf8Text);
|
||||
while (*p) {
|
||||
uint32_t cp = utf8NextCodepoint(&p);
|
||||
if (cp == 0) break;
|
||||
|
||||
int32_t glyphIdx = findGlyphIndex(fontData, cp);
|
||||
if (glyphIdx < 0) continue;
|
||||
|
||||
// Deduplicate
|
||||
bool found = false;
|
||||
for (uint16_t i = 0; i < glyphCount; i++) {
|
||||
if (neededGlyphs[i] == static_cast<uint32_t>(glyphIdx)) {
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!found) {
|
||||
if (glyphCount < MAX_PAGE_GLYPHS) {
|
||||
neededGlyphs[glyphCount++] = static_cast<uint32_t>(glyphIdx);
|
||||
} else if (!glyphCapWarned) {
|
||||
LOG_DBG("FDC", "Glyph cap (%u) reached during prewarm; excess glyphs will use hot-group fallback",
|
||||
MAX_PAGE_GLYPHS);
|
||||
glyphCapWarned = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Add ligature output glyphs: if both input codepoints of a ligature pair are
|
||||
// in the needed set, the output glyph will be queried during rendering.
|
||||
if (fontData->ligaturePairs && fontData->ligaturePairCount > 0) {
|
||||
for (uint32_t li = 0; li < fontData->ligaturePairCount && glyphCount < MAX_PAGE_GLYPHS; li++) {
|
||||
uint32_t leftCp = fontData->ligaturePairs[li].pair >> 16;
|
||||
uint32_t rightCp = fontData->ligaturePairs[li].pair & 0xFFFF;
|
||||
|
||||
int32_t leftIdx = findGlyphIndex(fontData, leftCp);
|
||||
int32_t rightIdx = findGlyphIndex(fontData, rightCp);
|
||||
if (leftIdx < 0 || rightIdx < 0) continue;
|
||||
|
||||
// Check if both inputs are in neededGlyphs
|
||||
bool hasLeft = false, hasRight = false;
|
||||
for (uint16_t i = 0; i < glyphCount; i++) {
|
||||
if (neededGlyphs[i] == static_cast<uint32_t>(leftIdx)) hasLeft = true;
|
||||
if (neededGlyphs[i] == static_cast<uint32_t>(rightIdx)) hasRight = true;
|
||||
if (hasLeft && hasRight) break;
|
||||
}
|
||||
if (!hasLeft || !hasRight) continue;
|
||||
|
||||
int32_t outIdx = findGlyphIndex(fontData, fontData->ligaturePairs[li].ligatureCp);
|
||||
if (outIdx < 0) continue;
|
||||
|
||||
// Deduplicate
|
||||
bool found = false;
|
||||
for (uint16_t i = 0; i < glyphCount; i++) {
|
||||
if (neededGlyphs[i] == static_cast<uint32_t>(outIdx)) {
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!found) {
|
||||
neededGlyphs[glyphCount++] = static_cast<uint32_t>(outIdx);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (glyphCount == 0) return 0;
|
||||
|
||||
// Step 2: Compute total buffer size and collect unique groups
|
||||
uint32_t totalBytes = 0;
|
||||
uint16_t neededGroups[128];
|
||||
uint8_t groupCount = 0;
|
||||
bool groupCapWarned = false;
|
||||
|
||||
for (uint16_t i = 0; i < glyphCount; i++) {
|
||||
totalBytes += fontData->glyph[neededGlyphs[i]].dataLength;
|
||||
uint16_t gi = getGroupIndex(fontData, neededGlyphs[i]);
|
||||
bool found = false;
|
||||
for (uint8_t j = 0; j < groupCount; j++) {
|
||||
if (neededGroups[j] == gi) {
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!found) {
|
||||
if (groupCount < 128) {
|
||||
neededGroups[groupCount++] = gi;
|
||||
} else if (!groupCapWarned) {
|
||||
LOG_DBG("FDC", "Group cap (128) reached during prewarm; some groups will use hot-group fallback");
|
||||
groupCapWarned = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
stats.uniqueGroupsAccessed = groupCount;
|
||||
|
||||
// Step 3: Allocate page buffer and lookup table for this slot
|
||||
slot.buffer = static_cast<uint8_t*>(malloc(totalBytes));
|
||||
slot.glyphs = static_cast<PageGlyphEntry*>(malloc(glyphCount * sizeof(PageGlyphEntry)));
|
||||
if (!slot.buffer || !slot.glyphs) {
|
||||
LOG_ERR("FDC", "Failed to allocate page buffer (%u bytes, %u glyphs)", totalBytes, glyphCount);
|
||||
free(slot.buffer);
|
||||
free(slot.glyphs);
|
||||
slot = {};
|
||||
return glyphCount;
|
||||
}
|
||||
stats.pageBufferBytes += totalBytes;
|
||||
stats.pageGlyphsBytes += glyphCount * sizeof(PageGlyphEntry);
|
||||
|
||||
slot.fontData = fontData;
|
||||
slot.glyphCount = glyphCount;
|
||||
pageSlotCount++;
|
||||
|
||||
// Initialize lookup entries (bufferOffset = UINT32_MAX means not yet extracted)
|
||||
for (uint16_t i = 0; i < glyphCount; i++) {
|
||||
slot.glyphs[i] = {neededGlyphs[i], UINT32_MAX, 0};
|
||||
}
|
||||
|
||||
// Sort by glyphIndex for binary search in getBitmap()
|
||||
for (uint16_t i = 1; i < glyphCount; i++) {
|
||||
PageGlyphEntry key = slot.glyphs[i];
|
||||
int j = i - 1;
|
||||
while (j >= 0 && slot.glyphs[j].glyphIndex > key.glyphIndex) {
|
||||
slot.glyphs[j + 1] = slot.glyphs[j];
|
||||
j--;
|
||||
}
|
||||
slot.glyphs[j + 1] = key;
|
||||
}
|
||||
|
||||
// Step 3b: Pre-scan to compute each needed glyph's byte-aligned offset within its group.
|
||||
// This avoids recomputing aligned offsets per group during extraction in step 4.
|
||||
uint32_t groupAlignedTracker[128] = {}; // running byte-aligned offset for each needed group
|
||||
|
||||
if (fontData->glyphToGroup) {
|
||||
// Frequency-grouped: single O(totalGlyphs) pass through glyphToGroup
|
||||
const auto& lastInterval = fontData->intervals[fontData->intervalCount - 1];
|
||||
const uint32_t totalGlyphs = lastInterval.offset + (lastInterval.last - lastInterval.first + 1);
|
||||
|
||||
for (uint32_t i = 0; i < totalGlyphs; i++) {
|
||||
const uint16_t gi = fontData->glyphToGroup[i];
|
||||
// Find this glyph's group position in neededGroups
|
||||
uint8_t gpPos = groupCount;
|
||||
for (uint8_t j = 0; j < groupCount; j++) {
|
||||
if (neededGroups[j] == gi) {
|
||||
gpPos = j;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (gpPos == groupCount) continue; // not a needed group
|
||||
|
||||
const EpdGlyph& glyph = fontData->glyph[i];
|
||||
|
||||
// Binary search in sorted slot.glyphs to find if glyph i is needed
|
||||
int left = 0, right = (int)slot.glyphCount - 1;
|
||||
while (left <= right) {
|
||||
const int mid = left + (right - left) / 2;
|
||||
if (slot.glyphs[mid].glyphIndex == i) {
|
||||
slot.glyphs[mid].alignedOffset = groupAlignedTracker[gpPos];
|
||||
break;
|
||||
}
|
||||
if (slot.glyphs[mid].glyphIndex < i)
|
||||
left = mid + 1;
|
||||
else
|
||||
right = mid - 1;
|
||||
}
|
||||
|
||||
if (glyph.width > 0 && glyph.height > 0) {
|
||||
groupAlignedTracker[gpPos] += ((glyph.width + 3) / 4) * glyph.height;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Contiguous-group: iterate each needed group's glyphs directly
|
||||
for (uint8_t g = 0; g < groupCount; g++) {
|
||||
const EpdFontGroup& group = fontData->groups[neededGroups[g]];
|
||||
uint32_t alignedOff = 0;
|
||||
for (uint16_t j = 0; j < group.glyphCount; j++) {
|
||||
const uint32_t glyphI = group.firstGlyphIndex + j;
|
||||
const EpdGlyph& glyph = fontData->glyph[glyphI];
|
||||
|
||||
int left = 0, right = (int)slot.glyphCount - 1;
|
||||
while (left <= right) {
|
||||
const int mid = left + (right - left) / 2;
|
||||
if (slot.glyphs[mid].glyphIndex == glyphI) {
|
||||
slot.glyphs[mid].alignedOffset = alignedOff;
|
||||
break;
|
||||
}
|
||||
if (slot.glyphs[mid].glyphIndex < glyphI)
|
||||
left = mid + 1;
|
||||
else
|
||||
right = mid - 1;
|
||||
}
|
||||
|
||||
if (glyph.width > 0 && glyph.height > 0) {
|
||||
alignedOff += ((glyph.width + 3) / 4) * glyph.height;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Step 4: For each unique group, decompress to temp buffer and extract needed glyphs
|
||||
uint32_t writeOffset = 0;
|
||||
int missed = 0;
|
||||
|
||||
for (uint8_t g = 0; g < groupCount; g++) {
|
||||
uint16_t groupIdx = neededGroups[g];
|
||||
const EpdFontGroup& group = fontData->groups[groupIdx];
|
||||
|
||||
auto* tempBuf = static_cast<uint8_t*>(malloc(group.uncompressedSize));
|
||||
if (!tempBuf) {
|
||||
LOG_ERR("FDC", "Failed to allocate temp buffer (%u bytes) for group %u", group.uncompressedSize, groupIdx);
|
||||
missed++;
|
||||
continue;
|
||||
}
|
||||
if (group.uncompressedSize > stats.peakTempBytes) {
|
||||
stats.peakTempBytes = group.uncompressedSize;
|
||||
}
|
||||
|
||||
if (!decompressGroup(fontData, groupIdx, tempBuf, group.uncompressedSize)) {
|
||||
free(tempBuf);
|
||||
missed++;
|
||||
continue;
|
||||
}
|
||||
|
||||
// Extract needed glyphs directly from the byte-aligned temp buffer, compacting on the fly.
|
||||
// alignedOffset was pre-computed in step 3b — no full-group compact scan needed.
|
||||
for (uint16_t i = 0; i < slot.glyphCount; i++) {
|
||||
if (slot.glyphs[i].bufferOffset != UINT32_MAX) continue; // already extracted
|
||||
if (getGroupIndex(fontData, slot.glyphs[i].glyphIndex) != groupIdx) continue;
|
||||
|
||||
const EpdGlyph& glyph = fontData->glyph[slot.glyphs[i].glyphIndex];
|
||||
compactSingleGlyph(&tempBuf[slot.glyphs[i].alignedOffset], &slot.buffer[writeOffset], glyph.width, glyph.height);
|
||||
slot.glyphs[i].bufferOffset = writeOffset;
|
||||
writeOffset += glyph.dataLength;
|
||||
}
|
||||
|
||||
free(tempBuf);
|
||||
}
|
||||
|
||||
LOG_DBG("FDC", "Prewarm: %u glyphs in %u bytes from %u groups (%d missed)", glyphCount, writeOffset, groupCount,
|
||||
missed);
|
||||
|
||||
return missed;
|
||||
}
|
||||
|
||||
// --- Stats ---
|
||||
|
||||
void FontDecompressor::resetStats() { stats = Stats{}; }
|
||||
|
||||
void FontDecompressor::logStats(const char* label) {
|
||||
const uint32_t total = stats.cacheHits + stats.cacheMisses;
|
||||
LOG_DBG("FDC", "[%s] hits=%lu misses=%lu (%.1f%% hit rate)", label, stats.cacheHits, stats.cacheMisses,
|
||||
total > 0 ? 100.0f * stats.cacheHits / total : 0.0f);
|
||||
LOG_DBG("FDC", "[%s] decompress=%lums groups_accessed=%u", label, stats.decompressTimeMs, stats.uniqueGroupsAccessed);
|
||||
LOG_DBG("FDC", "[%s] mem: pageBuf=%lu pageGlyphs=%lu hotGroup=%lu peakTemp=%lu", label, stats.pageBufferBytes,
|
||||
stats.pageGlyphsBytes, stats.hotGroupBytes, stats.peakTempBytes);
|
||||
if (stats.getBitmapCalls > 0) {
|
||||
LOG_DBG("FDC", "[%s] getBitmap: %lu calls, %luus total, %luus/call avg", label, stats.getBitmapCalls,
|
||||
stats.getBitmapTimeUs, stats.getBitmapTimeUs / stats.getBitmapCalls);
|
||||
}
|
||||
resetStats();
|
||||
}
|
||||
|
||||
@@ -1,42 +1,85 @@
|
||||
#pragma once
|
||||
|
||||
#include <uzlib.h>
|
||||
#include <InflateReader.h>
|
||||
|
||||
#include <cstdint>
|
||||
#include <vector>
|
||||
|
||||
#include "EpdFontData.h"
|
||||
|
||||
class FontDecompressor {
|
||||
public:
|
||||
static constexpr uint16_t MAX_PAGE_GLYPHS = 512;
|
||||
static constexpr uint8_t MAX_PAGE_SLOTS = 4; // One per font style (R/B/I/BI)
|
||||
|
||||
FontDecompressor() = default;
|
||||
~FontDecompressor();
|
||||
|
||||
bool init();
|
||||
void deinit();
|
||||
|
||||
// Returns pointer to decompressed bitmap data for the given glyph.
|
||||
// Valid until LRU eviction (safe for the duration of one glyph render).
|
||||
const uint8_t* getBitmap(const EpdFontData* fontData, const EpdGlyph* glyph, uint16_t glyphIndex);
|
||||
// Checks the page buffer (from prewarm) first, then falls back to the hot group slot.
|
||||
const uint8_t* getBitmap(const EpdFontData* fontData, const EpdGlyph* glyph, uint32_t glyphIndex);
|
||||
|
||||
// Evict all cached decompressed groups (call between pages for within-page-only caching).
|
||||
// Free all cached data (page buffer + hot group).
|
||||
void clearCache();
|
||||
|
||||
private:
|
||||
static constexpr uint8_t CACHE_SLOTS = 4;
|
||||
// Pre-scan UTF-8 text and extract needed glyph bitmaps into a flat page buffer.
|
||||
// Each group is decompressed once into a temp buffer; only needed glyphs are kept.
|
||||
// Returns the number of glyphs that couldn't be loaded (0 on full success).
|
||||
int prewarmCache(const EpdFontData* fontData, const char* utf8Text);
|
||||
|
||||
struct CacheEntry {
|
||||
const EpdFontData* font = nullptr;
|
||||
uint16_t groupIndex = 0;
|
||||
uint8_t* data = nullptr;
|
||||
uint32_t dataSize = 0;
|
||||
uint32_t lastUsed = 0;
|
||||
bool valid = false;
|
||||
struct Stats {
|
||||
uint32_t cacheHits = 0;
|
||||
uint32_t cacheMisses = 0;
|
||||
uint32_t decompressTimeMs = 0;
|
||||
uint16_t uniqueGroupsAccessed = 0;
|
||||
uint32_t pageBufferBytes = 0; // pageBuffer allocation
|
||||
uint32_t pageGlyphsBytes = 0; // pageGlyphs lookup table allocation
|
||||
uint32_t hotGroupBytes = 0; // current hot group allocation
|
||||
uint32_t peakTempBytes = 0; // largest temp buffer in prewarm
|
||||
uint32_t getBitmapTimeUs = 0; // cumulative getBitmap time (micros)
|
||||
uint32_t getBitmapCalls = 0; // number of getBitmap calls
|
||||
};
|
||||
void logStats(const char* label = "FDC");
|
||||
void resetStats();
|
||||
const Stats& getStats() const { return stats; }
|
||||
|
||||
struct uzlib_uncomp decomp = {};
|
||||
CacheEntry cache[CACHE_SLOTS] = {};
|
||||
uint32_t accessCounter = 0;
|
||||
private:
|
||||
Stats stats;
|
||||
InflateReader inflateReader;
|
||||
|
||||
void freeAllEntries();
|
||||
uint16_t getGroupIndex(const EpdFontData* fontData, uint16_t glyphIndex);
|
||||
CacheEntry* findInCache(const EpdFontData* fontData, uint16_t groupIndex);
|
||||
CacheEntry* findEvictionCandidate();
|
||||
bool decompressGroup(const EpdFontData* fontData, uint16_t groupIndex, CacheEntry* entry);
|
||||
// Page buffer slots: each style gets its own flat glyph buffer with sorted lookup.
|
||||
// Up to MAX_PAGE_SLOTS (4) styles can be prewarmed simultaneously.
|
||||
struct PageGlyphEntry {
|
||||
uint32_t glyphIndex;
|
||||
uint32_t bufferOffset;
|
||||
uint32_t alignedOffset; // byte-aligned offset within its decompressed group (set during prewarm pre-scan)
|
||||
};
|
||||
struct PageSlot {
|
||||
uint8_t* buffer = nullptr;
|
||||
const EpdFontData* fontData = nullptr;
|
||||
PageGlyphEntry* glyphs = nullptr;
|
||||
uint16_t glyphCount = 0;
|
||||
};
|
||||
PageSlot pageSlots[MAX_PAGE_SLOTS] = {};
|
||||
uint8_t pageSlotCount = 0;
|
||||
|
||||
// Hot group: last decompressed group (byte-aligned) for non-prewarmed fallback path.
|
||||
// Kept in byte-aligned format; individual glyphs are compacted on demand into hotGlyphBuf.
|
||||
const EpdFontData* hotGroupFont = nullptr;
|
||||
uint16_t hotGroupIndex = UINT16_MAX;
|
||||
std::vector<uint8_t> hotGroup;
|
||||
|
||||
// Scratch buffer for compacting a single glyph from the hot group.
|
||||
// Valid until the next getBitmap() call.
|
||||
std::vector<uint8_t> hotGlyphBuf;
|
||||
|
||||
void freePageBuffer();
|
||||
void freeHotGroup();
|
||||
uint16_t getGroupIndex(const EpdFontData* fontData, uint32_t glyphIndex);
|
||||
uint32_t getAlignedOffset(const EpdFontData* fontData, uint16_t groupIndex, uint32_t glyphIndex);
|
||||
bool decompressGroup(const EpdFontData* fontData, uint16_t groupIndex, uint8_t* outBuf, uint32_t outSize);
|
||||
static void compactSingleGlyph(const uint8_t* alignedSrc, uint8_t* packedDst, uint8_t width, uint8_t height);
|
||||
static int32_t findGlyphIndex(const EpdFontData* fontData, uint32_t codepoint);
|
||||
};
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,254 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "EpdFont.h"
|
||||
#include "EpdFontData.h"
|
||||
|
||||
// On-disk binary format version for .cpfont files. Defined as a preprocessor
|
||||
// macro (rather than a constexpr) so it can be stringified into the SD-fonts
|
||||
// release URL — see FONT_MANIFEST_URL in FontDownloadActivity.h. No integer
|
||||
// suffix because stringification would include it (e.g. `4U` → `"4U"`).
|
||||
//
|
||||
// The canonical version for the build tooling lives in
|
||||
// lib/EpdFont/scripts/cpfont_version.py. This firmware-side copy must be
|
||||
// bumped manually when the firmware is updated to support a new format.
|
||||
// Reader enforcement: SdCardFont::load().
|
||||
#define CPFONT_VERSION 4
|
||||
|
||||
class SdCardFont {
|
||||
public:
|
||||
static constexpr uint16_t MAX_PAGE_GLYPHS = 512;
|
||||
static constexpr uint8_t MAX_STYLES = 4;
|
||||
|
||||
SdCardFont() = default;
|
||||
~SdCardFont();
|
||||
// Owns raw buffers freed in dtor — no shallow-copy semantics. Make any
|
||||
// accidental pass-by-value or move a compile-time error.
|
||||
SdCardFont(const SdCardFont&) = delete;
|
||||
SdCardFont& operator=(const SdCardFont&) = delete;
|
||||
SdCardFont(SdCardFont&&) = delete;
|
||||
SdCardFont& operator=(SdCardFont&&) = delete;
|
||||
|
||||
// Load .cpfont file: reads header + intervals into RAM, records file layout offsets.
|
||||
// Supports v4 (multi-style) format.
|
||||
// Returns true on success.
|
||||
bool load(const char* path);
|
||||
|
||||
// Pre-read glyphs needed for the given UTF-8 text from SD card.
|
||||
// styleMask: bitmask of styles to prewarm (bit 0=regular, 1=bold, 2=italic, 3=bolditalic).
|
||||
// Default 0x0F = all present styles.
|
||||
// When metadataOnly=true, only glyph metrics are loaded (no bitmap data).
|
||||
// Returns number of glyphs that couldn't be loaded (0 on full success).
|
||||
int prewarm(const char* utf8Text, uint8_t styleMask = 0x0F, bool metadataOnly = false);
|
||||
|
||||
// Build a compact advance-only table for layout measurement.
|
||||
// Extracts ALL unique codepoints from words (no MAX_PAGE_GLYPHS cap),
|
||||
// batch-reads advanceX from SD, stores in a sorted per-style table.
|
||||
// Returns number of codepoints not found in font coverage.
|
||||
int buildAdvanceTable(const char* utf8Text, uint8_t styleMask = 0x0F);
|
||||
int buildAdvanceTable(const std::vector<std::string>& words, bool includeHyphen, uint8_t styleMask = 0x0F);
|
||||
|
||||
// Look up advanceX for a codepoint from the advance table.
|
||||
// Returns the 12.4 fixed-point advance, or 0 if not found.
|
||||
uint16_t getAdvance(uint32_t codepoint, uint8_t style) const;
|
||||
|
||||
// Returns true if advance table is populated for at least one style.
|
||||
bool hasAdvanceTable() const;
|
||||
|
||||
// Free mini data for all styles, restore stub EpdFontData.
|
||||
// Also clears the temporary advance table (built per layout pass) but
|
||||
// preserves the persistent advance cache (reused across passes).
|
||||
void clearCache();
|
||||
|
||||
// Drop the persistent advance cache. Call when unloading the SD font or
|
||||
// when font/size/family/glyph-table state changes.
|
||||
void clearPersistentCache();
|
||||
|
||||
// Returns pointer to the managed EpdFont for a given style.
|
||||
// Returns nullptr if the style is not present.
|
||||
EpdFont* getEpdFont(uint8_t style = 0);
|
||||
|
||||
// Returns true if the given style is present in this font file.
|
||||
bool hasStyle(uint8_t style) const;
|
||||
|
||||
// Resolve requested style bits to the closest present style.
|
||||
uint8_t resolveStyle(uint8_t style) const;
|
||||
|
||||
// Resolve every requested style bit through fallback and return the actual
|
||||
// styles that need cache/advance preparation.
|
||||
uint8_t resolveStyleMask(uint8_t styleMask) const;
|
||||
|
||||
// Number of styles present in this font file.
|
||||
uint8_t styleCount() const { return styleCount_; }
|
||||
|
||||
// Returns true if the glyph pointer points into the overflow buffer.
|
||||
bool isOverflowGlyph(const EpdGlyph* glyph) const;
|
||||
|
||||
// Returns the bitmap for an on-demand-loaded (overflow) glyph.
|
||||
const uint8_t* getOverflowBitmap(const EpdGlyph* glyph) const;
|
||||
|
||||
// Extract SdCardFont* from an opaque glyphMissCtx pointer.
|
||||
// Used by GfxRenderer::getGlyphBitmap() to recover the SdCardFont from EpdFontData::glyphMissCtx.
|
||||
static SdCardFont* fromMissCtx(void* ctx);
|
||||
|
||||
struct Stats {
|
||||
uint32_t prewarmTotalMs = 0;
|
||||
uint32_t sdReadTimeMs = 0;
|
||||
uint32_t seekCount = 0;
|
||||
uint32_t uniqueGlyphs = 0;
|
||||
uint32_t bitmapBytes = 0;
|
||||
};
|
||||
void logStats(const char* label = "SDCF");
|
||||
void resetStats();
|
||||
const Stats& getStats() const { return stats_; }
|
||||
|
||||
// Content hash of the file header + style TOC entries (computed during load).
|
||||
// Used to generate deterministic font IDs for section cache invalidation.
|
||||
uint32_t contentHash() const { return contentHash_; }
|
||||
|
||||
private:
|
||||
// Per-style metadata (parsed from file header/TOC)
|
||||
struct CpFontHeader {
|
||||
uint32_t intervalCount = 0;
|
||||
uint32_t glyphCount = 0;
|
||||
uint8_t advanceY = 0;
|
||||
int16_t ascender = 0;
|
||||
int16_t descender = 0;
|
||||
bool is2Bit = false;
|
||||
uint16_t kernLeftEntryCount = 0;
|
||||
uint16_t kernRightEntryCount = 0;
|
||||
uint8_t kernLeftClassCount = 0;
|
||||
uint8_t kernRightClassCount = 0;
|
||||
uint8_t ligaturePairCount = 0;
|
||||
};
|
||||
|
||||
// All per-style data: file offsets, intervals, kern/lig, prewarm cache, EpdFont
|
||||
struct PerStyle {
|
||||
CpFontHeader header{};
|
||||
|
||||
// File layout offsets for this style's data sections
|
||||
uint32_t intervalsFileOffset = 0;
|
||||
uint32_t glyphsFileOffset = 0;
|
||||
uint32_t kernLeftFileOffset = 0;
|
||||
uint32_t kernRightFileOffset = 0;
|
||||
uint32_t kernMatrixFileOffset = 0;
|
||||
uint32_t ligatureFileOffset = 0;
|
||||
uint32_t bitmapFileOffset = 0;
|
||||
|
||||
// Full intervals loaded from file (kept in RAM for codepoint lookup)
|
||||
EpdUnicodeInterval* fullIntervals = nullptr;
|
||||
|
||||
// Persistent kern-class + ligature tables (lazy-loaded on first prewarm).
|
||||
// The full kern MATRIX is NOT resident — on Literata-class fonts a single
|
||||
// style's matrix is ~36-42KB contiguous, and 4 styles' worth won't fit
|
||||
// alongside bitmaps + framebuffer on a 380KB device. Only kernLeftClasses
|
||||
// and kernRightClasses (small codepoint→classId tables, ~3KB each) stay
|
||||
// resident; the matrix is reconstructed per-page as miniKernMatrix.
|
||||
EpdKernClassEntry* kernLeftClasses = nullptr;
|
||||
EpdKernClassEntry* kernRightClasses = nullptr;
|
||||
EpdLigaturePair* ligaturePairs = nullptr;
|
||||
bool kernLigLoaded = false;
|
||||
|
||||
// Stub EpdFontData returned when not prewarmed
|
||||
EpdFontData stubData{};
|
||||
|
||||
// Mini EpdFontData built during prewarm
|
||||
EpdFontData miniData{};
|
||||
EpdUnicodeInterval* miniIntervals = nullptr;
|
||||
EpdGlyph* miniGlyphs = nullptr;
|
||||
uint8_t* miniBitmap = nullptr;
|
||||
uint32_t miniIntervalCount = 0;
|
||||
uint32_t miniGlyphCount = 0;
|
||||
|
||||
// Per-page mini kern matrix (built by buildMiniKernMatrix on each full
|
||||
// prewarm). miniKernLeftClasses/miniKernRightClasses map ONLY the codepoints
|
||||
// used on the current page to renumbered class IDs (1..miniKern*ClassCount).
|
||||
// miniKernMatrix is a small miniKernLeftClassCount × miniKernRightClassCount
|
||||
// flat matrix. Typical Latin page: ~25×25 matrix = ~625 bytes per style vs
|
||||
// ~36KB for the full Literata matrix — ~50× reduction.
|
||||
EpdKernClassEntry* miniKernLeftClasses = nullptr;
|
||||
EpdKernClassEntry* miniKernRightClasses = nullptr;
|
||||
uint16_t miniKernLeftEntryCount = 0;
|
||||
uint16_t miniKernRightEntryCount = 0;
|
||||
uint8_t miniKernLeftClassCount = 0;
|
||||
uint8_t miniKernRightClassCount = 0;
|
||||
int8_t* miniKernMatrix = nullptr;
|
||||
|
||||
// The EpdFont whose data pointer we manage
|
||||
EpdFont epdFont{&stubData};
|
||||
|
||||
bool present = false;
|
||||
};
|
||||
|
||||
PerStyle styles_[MAX_STYLES] = {};
|
||||
uint8_t styleCount_ = 0;
|
||||
|
||||
char filePath_[128] = {};
|
||||
|
||||
// Overflow context: glyphMissHandler needs to know which style it's serving
|
||||
struct OverflowContext {
|
||||
SdCardFont* self;
|
||||
uint8_t styleIdx;
|
||||
};
|
||||
OverflowContext overflowCtx_[MAX_STYLES] = {};
|
||||
|
||||
// Shared on-demand overflow buffer (ring buffer of glyphs loaded via glyphMissHandler)
|
||||
static constexpr uint32_t OVERFLOW_CAPACITY = 8;
|
||||
struct OverflowEntry {
|
||||
EpdGlyph glyph;
|
||||
uint8_t* bitmap = nullptr;
|
||||
uint32_t codepoint = 0;
|
||||
uint8_t styleIdx = 0;
|
||||
};
|
||||
OverflowEntry overflow_[OVERFLOW_CAPACITY] = {};
|
||||
uint32_t overflowCount_ = 0;
|
||||
uint32_t overflowNext_ = 0;
|
||||
|
||||
// Compact advance-only table for layout measurement (per-style).
|
||||
// Built by buildAdvanceTable(), queried by getAdvance().
|
||||
struct AdvanceEntry {
|
||||
uint32_t codepoint;
|
||||
uint16_t advanceX; // 12.4 fixed-point
|
||||
};
|
||||
// Per-style advance table. Sorted by codepoint for binary lookup.
|
||||
// Bounded to ADVANCE_CACHE_LIMIT entries; persists across layout passes
|
||||
// (across calls to clearCache()) so repeated indexing of the same font
|
||||
// amortizes SD reads. Cleared only on font unload or clearPersistentCache().
|
||||
static constexpr uint32_t ADVANCE_CACHE_LIMIT = 768;
|
||||
AdvanceEntry* advanceTable_[MAX_STYLES] = {};
|
||||
uint32_t advanceTableSize_[MAX_STYLES] = {};
|
||||
bool advanceTableLookup(uint8_t styleIdx, uint32_t codepoint, uint16_t* outAdvance) const;
|
||||
// Merge sortedNew (sorted by codepoint, no overlap with existing) into the
|
||||
// advance table for styleIdx, preserving sort order; cap-truncates the tail.
|
||||
void mergeIntoAdvanceTable(uint8_t styleIdx, const AdvanceEntry* sortedNew, uint32_t newCount);
|
||||
|
||||
Stats stats_;
|
||||
uint32_t contentHash_ = 0;
|
||||
bool loaded_ = false;
|
||||
|
||||
// Per-style helpers
|
||||
void freeStyleMiniData(PerStyle& s);
|
||||
void freeStyleAll(PerStyle& s);
|
||||
void freeStyleKernLigatureData(PerStyle& s);
|
||||
void freeStyleMiniKern(PerStyle& s);
|
||||
bool loadStyleKernLigatureData(PerStyle& s);
|
||||
bool buildMiniKernMatrix(PerStyle& s, const uint32_t* codepoints, uint32_t cpCount);
|
||||
void applyKernLigaturePointers(PerStyle& s, EpdFontData& data) const;
|
||||
void applyGlyphMissCallback(uint8_t styleIdx);
|
||||
int32_t findGlobalGlyphIndex(const PerStyle& s, uint32_t codepoint) const;
|
||||
int fetchAdvancesForCodepoints(uint32_t* codepoints, uint32_t cpCount, uint8_t styleMask);
|
||||
template <typename Iter>
|
||||
int buildAdvanceTableRange(Iter begin, Iter end, bool includeSpace, bool includeHyphen, uint8_t styleMask);
|
||||
int prewarmStyle(uint8_t styleIdx, const uint32_t* codepoints, uint32_t cpCount, bool metadataOnly);
|
||||
|
||||
// Global helpers
|
||||
void freeAll();
|
||||
void clearOverflow();
|
||||
static void computeStyleFileOffsets(PerStyle& s, uint32_t baseOffset);
|
||||
|
||||
// Static callback for EpdFontData::glyphMissHandler (per-style via OverflowContext)
|
||||
static const EpdGlyph* onGlyphMiss(void* ctx, uint32_t codepoint);
|
||||
};
|
||||
@@ -0,0 +1,98 @@
|
||||
#include "SdCardFontManager.h"
|
||||
|
||||
#include <EpdFontFamily.h>
|
||||
#include <GfxRenderer.h>
|
||||
#include <Logging.h>
|
||||
#include <SdCardFont.h>
|
||||
#include <SdCardFontRegistry.h>
|
||||
|
||||
SdCardFontManager::~SdCardFontManager() {
|
||||
for (auto& lf : loaded_) {
|
||||
delete lf.font;
|
||||
}
|
||||
}
|
||||
|
||||
// FNV-1a continuation: seeds with contentHash, then hashes family name + point size.
|
||||
// Produces a deterministic ID that is stable across load/unload cycles and reboots,
|
||||
// and changes when font content changes (different header/TOC = different contentHash).
|
||||
int SdCardFontManager::computeFontId(uint32_t contentHash, const char* familyName, uint8_t pointSize) {
|
||||
static constexpr uint32_t FNV_PRIME = 16777619u;
|
||||
uint32_t hash = contentHash;
|
||||
while (*familyName) {
|
||||
hash ^= static_cast<uint8_t>(*familyName++);
|
||||
hash *= FNV_PRIME;
|
||||
}
|
||||
hash ^= pointSize;
|
||||
hash *= FNV_PRIME;
|
||||
int id = static_cast<int>(hash);
|
||||
return id != 0 ? id : 1; // 0 is reserved as "not found" sentinel
|
||||
}
|
||||
|
||||
bool SdCardFontManager::loadFamily(const SdCardFontFamilyInfo& family, GfxRenderer& renderer, uint8_t fontSizeEnum) {
|
||||
// Unload any previously loaded family first
|
||||
if (!loadedFamilyName_.empty()) {
|
||||
unloadAll(renderer);
|
||||
}
|
||||
|
||||
// Select by ordinal position: sort available sizes, then map the font size
|
||||
// enum (SMALL=0 .. EXTRA_LARGE=3) to the corresponding slot. When the
|
||||
// family has fewer sizes than 4, clamp to the last available size.
|
||||
auto sizes = family.availableSizes();
|
||||
if (sizes.empty()) {
|
||||
LOG_ERR("SDMGR", "Family %s has no files to load", family.name.c_str());
|
||||
return false;
|
||||
}
|
||||
|
||||
uint8_t idx = fontSizeEnum;
|
||||
if (idx >= sizes.size()) idx = sizes.size() - 1;
|
||||
const SdCardFontFileInfo* selected = family.findFile(sizes[idx]);
|
||||
|
||||
auto* font = new (std::nothrow) SdCardFont();
|
||||
if (!font) {
|
||||
LOG_ERR("SDMGR", "Failed to allocate SdCardFont for %s", selected->path.c_str());
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!font->load(selected->path.c_str())) {
|
||||
LOG_ERR("SDMGR", "Failed to load %s", selected->path.c_str());
|
||||
delete font;
|
||||
return false;
|
||||
}
|
||||
|
||||
int fontId = computeFontId(font->contentHash(), family.name.c_str(), selected->pointSize);
|
||||
// Guard against collision with built-in font IDs (astronomically unlikely
|
||||
// with FNV-1a hashes, but provides a safety net)
|
||||
if (renderer.getFontMap().count(fontId) != 0) {
|
||||
LOG_ERR("SDMGR", "Font ID %d collides with existing font, skipping %s", fontId, selected->path.c_str());
|
||||
delete font;
|
||||
return false;
|
||||
}
|
||||
renderer.registerSdCardFont(fontId, font);
|
||||
loaded_.push_back({font, fontId, selected->pointSize});
|
||||
|
||||
LOG_DBG("SDMGR", "Loaded %s size=%u id=%d styles=%u (sizeEnum=%u)", selected->path.c_str(), selected->pointSize,
|
||||
fontId, font->styleCount(), fontSizeEnum);
|
||||
|
||||
EpdFontFamily fontFamily(font->getEpdFont(0), font->getEpdFont(1), font->getEpdFont(2), font->getEpdFont(3));
|
||||
renderer.insertFont(fontId, fontFamily);
|
||||
|
||||
loadedFamilyName_ = family.name;
|
||||
loadedPointSize_ = selected->pointSize;
|
||||
return true;
|
||||
}
|
||||
|
||||
void SdCardFontManager::unloadAll(GfxRenderer& renderer) {
|
||||
renderer.clearSdCardFonts();
|
||||
for (auto& lf : loaded_) {
|
||||
renderer.removeFont(lf.fontId);
|
||||
delete lf.font;
|
||||
}
|
||||
loaded_.clear();
|
||||
loadedFamilyName_.clear();
|
||||
loadedPointSize_ = 0;
|
||||
}
|
||||
|
||||
int SdCardFontManager::getFontId(const std::string& familyName) const {
|
||||
if (familyName != loadedFamilyName_ || loaded_.empty()) return 0;
|
||||
return loaded_.front().fontId;
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
class GfxRenderer;
|
||||
class SdCardFont;
|
||||
struct SdCardFontFamilyInfo;
|
||||
|
||||
class SdCardFontManager {
|
||||
public:
|
||||
SdCardFontManager() = default;
|
||||
~SdCardFontManager();
|
||||
SdCardFontManager(const SdCardFontManager&) = delete;
|
||||
SdCardFontManager& operator=(const SdCardFontManager&) = delete;
|
||||
|
||||
// Load the font file matching fontSizeEnum (SMALL=0 .. EXTRA_LARGE=3) by
|
||||
// ordinal position in the family's sorted size list. Only one .cpfont file
|
||||
// is loaded; other sizes remain on disk. This keeps resident interval +
|
||||
// kern/ligature tables to one size's worth of memory.
|
||||
// Returns true on success.
|
||||
bool loadFamily(const SdCardFontFamilyInfo& family, GfxRenderer& renderer, uint8_t fontSizeEnum);
|
||||
|
||||
// Unload everything, unregister from renderer.
|
||||
void unloadAll(GfxRenderer& renderer);
|
||||
|
||||
// Look up the font ID for the loaded family. Returns 0 if nothing loaded
|
||||
// or familyName doesn't match.
|
||||
int getFontId(const std::string& familyName) const;
|
||||
|
||||
// Get name of currently loaded family (empty if none).
|
||||
const std::string& currentFamilyName() const { return loadedFamilyName_; };
|
||||
|
||||
// Point size that was actually loaded (closest match to targetPtSize).
|
||||
// 0 if nothing loaded.
|
||||
uint8_t currentPointSize() const { return loadedPointSize_; };
|
||||
|
||||
private:
|
||||
struct LoadedFont {
|
||||
SdCardFont* font; // heap-allocated, owned
|
||||
int fontId;
|
||||
uint8_t size;
|
||||
};
|
||||
static int computeFontId(uint32_t contentHash, const char* familyName, uint8_t pointSize);
|
||||
|
||||
std::string loadedFamilyName_;
|
||||
uint8_t loadedPointSize_ = 0;
|
||||
std::vector<LoadedFont> loaded_;
|
||||
};
|
||||
@@ -0,0 +1,230 @@
|
||||
#include "SdCardFontRegistry.h"
|
||||
|
||||
#include <HalStorage.h>
|
||||
#include <Logging.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstring>
|
||||
|
||||
// --- SdCardFontFamilyInfo helpers ---
|
||||
|
||||
const SdCardFontFileInfo* SdCardFontFamilyInfo::findFile(uint8_t size, uint8_t style) const {
|
||||
for (const auto& f : files) {
|
||||
if (f.pointSize == size && f.style == style) return &f;
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
bool SdCardFontFamilyInfo::hasSize(uint8_t size) const {
|
||||
for (const auto& f : files) {
|
||||
if (f.pointSize == size) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
std::vector<uint8_t> SdCardFontFamilyInfo::availableSizes() const {
|
||||
std::vector<uint8_t> sizes;
|
||||
for (const auto& f : files) {
|
||||
bool found = false;
|
||||
for (uint8_t s : sizes) {
|
||||
if (s == f.pointSize) {
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!found) sizes.push_back(f.pointSize);
|
||||
}
|
||||
std::sort(sizes.begin(), sizes.end());
|
||||
return sizes;
|
||||
}
|
||||
|
||||
// --- SdCardFontRegistry ---
|
||||
|
||||
bool SdCardFontRegistry::parseFilename(const char* filename, uint8_t& size, uint8_t& style) {
|
||||
// V4 naming: <name>_<size>.cpfont (e.g. Bookerly-SD_14.cpfont)
|
||||
// Use an ends-with check rather than strstr() so that in-progress downloads
|
||||
// like "Foo_14.cpfont.tmp" or backups like "Foo_14.cpfont~" aren't accepted.
|
||||
static constexpr char kExt[] = ".cpfont";
|
||||
static constexpr size_t kExtLen = sizeof(kExt) - 1;
|
||||
const size_t nameLen = strlen(filename);
|
||||
if (nameLen <= kExtLen) return false;
|
||||
if (strcmp(filename + nameLen - kExtLen, kExt) != 0) return false;
|
||||
const char* ext = filename + nameLen - kExtLen;
|
||||
|
||||
size_t baseLen = ext - filename;
|
||||
if (baseLen == 0 || baseLen > 127) return false;
|
||||
|
||||
char base[128];
|
||||
memcpy(base, filename, baseLen);
|
||||
base[baseLen] = '\0';
|
||||
|
||||
char* lastUnderscore = strrchr(base, '_');
|
||||
if (!lastUnderscore || lastUnderscore == base) return false;
|
||||
|
||||
const char* sizeStr = lastUnderscore + 1;
|
||||
char* endPtr;
|
||||
long sizeVal = strtol(sizeStr, &endPtr, 10);
|
||||
if (endPtr == sizeStr || *endPtr != '\0' || sizeVal < 1 || sizeVal > 255) return false;
|
||||
size = static_cast<uint8_t>(sizeVal);
|
||||
// V4 .cpfont files bundle every style (regular/bold/italic/bold-italic) into
|
||||
// one file, so style is always 0 at the registry level. The per-style
|
||||
// bitstream is selected later by SdCardFont::getEpdFont(style). The `style`
|
||||
// field in SdCardFontFileInfo is reserved for future formats that split
|
||||
// styles across files; scanDirectory() defends against accidental
|
||||
// (pointSize, style) collisions in that scenario.
|
||||
style = 0;
|
||||
return true;
|
||||
}
|
||||
|
||||
void SdCardFontRegistry::scanDirectory(const char* dirPath, SdCardFontFamilyInfo& family) {
|
||||
FsFile dir = Storage.open(dirPath);
|
||||
if (!dir || !dir.isDirectory()) return;
|
||||
|
||||
char nameBuffer[128];
|
||||
while (true) {
|
||||
FsFile entry = dir.openNextFile();
|
||||
if (!entry) break;
|
||||
if (entry.isDirectory()) {
|
||||
entry.close();
|
||||
continue;
|
||||
}
|
||||
|
||||
entry.getName(nameBuffer, sizeof(nameBuffer));
|
||||
entry.close();
|
||||
|
||||
// Skip macOS resource fork files (._*) and other hidden files
|
||||
if (nameBuffer[0] == '.' || nameBuffer[0] == '_') continue;
|
||||
|
||||
uint8_t size, style;
|
||||
if (!parseFilename(nameBuffer, size, style)) continue;
|
||||
|
||||
// Reject duplicate (pointSize, style) entries in the same family. With
|
||||
// v4's bundle-everything design parseFilename always returns style=0, so
|
||||
// two files at the same size in the same family would silently shadow
|
||||
// each other in findFile(). Skip the duplicate and warn.
|
||||
bool duplicate = false;
|
||||
for (const auto& existing : family.files) {
|
||||
if (existing.pointSize == size && existing.style == style) {
|
||||
duplicate = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (duplicate) {
|
||||
LOG_ERR("SDREG", "Duplicate font %s in %s — skipping", nameBuffer, dirPath);
|
||||
continue;
|
||||
}
|
||||
|
||||
SdCardFontFileInfo info;
|
||||
info.path = std::string(dirPath) + "/" + nameBuffer;
|
||||
info.pointSize = size;
|
||||
info.style = style;
|
||||
family.files.push_back(std::move(info));
|
||||
}
|
||||
}
|
||||
|
||||
// Scan a single root (e.g. "/.fonts") and append its families to `out`.
|
||||
// Skips families whose names already exist in `out` (de-duplicates between
|
||||
// the hidden and visible roots — first scan wins).
|
||||
void SdCardFontRegistry::scanRoot(const char* rootPath, std::vector<SdCardFontFamilyInfo>& out) {
|
||||
FsFile root = Storage.open(rootPath);
|
||||
if (!root) {
|
||||
LOG_DBG("SDREG", "Fonts directory not found: %s", rootPath);
|
||||
return;
|
||||
}
|
||||
if (!root.isDirectory()) {
|
||||
LOG_ERR("SDREG", "Fonts path is not a directory: %s", rootPath);
|
||||
return;
|
||||
}
|
||||
|
||||
char nameBuffer[128];
|
||||
while (true) {
|
||||
FsFile entry = root.openNextFile();
|
||||
if (!entry) break;
|
||||
if (entry.isDirectory()) {
|
||||
entry.getName(nameBuffer, sizeof(nameBuffer));
|
||||
entry.close();
|
||||
|
||||
// Skip hidden/system directories inside the root (macOS ._*, .Trashes, etc.)
|
||||
if (nameBuffer[0] == '.' || nameBuffer[0] == '_') continue;
|
||||
|
||||
// De-dup by family name across roots.
|
||||
bool exists = false;
|
||||
for (const auto& fam : out) {
|
||||
if (fam.name == nameBuffer) {
|
||||
exists = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (exists) continue;
|
||||
|
||||
SdCardFontFamilyInfo family;
|
||||
family.name = nameBuffer;
|
||||
std::string subDirPath = std::string(rootPath) + "/" + nameBuffer;
|
||||
SdCardFontRegistry::scanDirectory(subDirPath.c_str(), family);
|
||||
|
||||
if (!family.files.empty()) {
|
||||
out.push_back(std::move(family));
|
||||
LOG_DBG("SDREG", "Found family: %s (%d files) in %s", out.back().name.c_str(),
|
||||
static_cast<int>(out.back().files.size()), rootPath);
|
||||
}
|
||||
} else {
|
||||
entry.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bool SdCardFontRegistry::discover() {
|
||||
families_.clear();
|
||||
families_.reserve(MAX_SD_FAMILIES);
|
||||
|
||||
// Hidden root is scanned first so it wins on name collisions, matching the
|
||||
// sleep-folder pattern (/.sleep preferred over /sleep).
|
||||
scanRoot(FONTS_DIR_HIDDEN, families_);
|
||||
scanRoot(FONTS_DIR_VISIBLE, families_);
|
||||
|
||||
// Sort families alphabetically
|
||||
std::sort(families_.begin(), families_.end(),
|
||||
[](const SdCardFontFamilyInfo& a, const SdCardFontFamilyInfo& b) { return a.name < b.name; });
|
||||
|
||||
// Cap at MAX_SD_FAMILIES
|
||||
if (static_cast<int>(families_.size()) > MAX_SD_FAMILIES) {
|
||||
families_.resize(MAX_SD_FAMILIES);
|
||||
}
|
||||
|
||||
LOG_DBG("SDREG", "Discovery complete: %d families", static_cast<int>(families_.size()));
|
||||
return !families_.empty();
|
||||
}
|
||||
|
||||
const char* SdCardFontRegistry::findFamilyRoot(const char* familyName) {
|
||||
if (!familyName || !*familyName) return nullptr;
|
||||
char path[160];
|
||||
snprintf(path, sizeof(path), "%s/%s", FONTS_DIR_HIDDEN, familyName);
|
||||
if (Storage.exists(path)) return FONTS_DIR_HIDDEN;
|
||||
snprintf(path, sizeof(path), "%s/%s", FONTS_DIR_VISIBLE, familyName);
|
||||
if (Storage.exists(path)) return FONTS_DIR_VISIBLE;
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
const char* SdCardFontRegistry::defaultWriteRoot() {
|
||||
// If exactly one of the roots already exists, keep using it. Otherwise
|
||||
// (neither exists, or both exist) prefer the hidden root for new installs.
|
||||
bool hiddenExists = Storage.exists(FONTS_DIR_HIDDEN);
|
||||
bool visibleExists = Storage.exists(FONTS_DIR_VISIBLE);
|
||||
if (hiddenExists) return FONTS_DIR_HIDDEN;
|
||||
if (visibleExists) return FONTS_DIR_VISIBLE;
|
||||
return FONTS_DIR_HIDDEN;
|
||||
}
|
||||
|
||||
const SdCardFontFamilyInfo* SdCardFontRegistry::findFamily(const std::string& name) const {
|
||||
for (const auto& f : families_) {
|
||||
if (f.name == name) return &f;
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
int SdCardFontRegistry::getFamilyIndex(const std::string& name) const {
|
||||
for (int i = 0; i < static_cast<int>(families_.size()); i++) {
|
||||
if (families_[i].name == name) return i;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
struct SdCardFontFileInfo {
|
||||
std::string path; // v4 on-disk naming: "/<root>/<Family>/<Family>_<size>.cpfont"
|
||||
// where <root> is "/.fonts" (preferred, hidden) or "/fonts" (visible).
|
||||
// e.g. "/.fonts/NotoSansCJK/NotoSansCJK_14.cpfont"
|
||||
uint8_t pointSize; // parsed from filename: 14
|
||||
uint8_t style; // always 0 in v4 (all 4 styles bundled in one file);
|
||||
// kept for potential future formats
|
||||
};
|
||||
|
||||
struct SdCardFontFamilyInfo {
|
||||
std::string name; // directory name, e.g. "NotoSansCJK"
|
||||
std::vector<SdCardFontFileInfo> files;
|
||||
|
||||
const SdCardFontFileInfo* findFile(uint8_t size, uint8_t style = 0) const;
|
||||
bool hasSize(uint8_t size) const;
|
||||
std::vector<uint8_t> availableSizes() const;
|
||||
};
|
||||
|
||||
class SdCardFontRegistry {
|
||||
public:
|
||||
static constexpr int MAX_SD_FAMILIES = 128;
|
||||
// Two top-level roots are scanned at discovery time. Hidden is preferred
|
||||
// when creating new installs; both are read from if present.
|
||||
static constexpr const char* FONTS_DIR_HIDDEN = "/.fonts";
|
||||
static constexpr const char* FONTS_DIR_VISIBLE = "/fonts";
|
||||
|
||||
// Returns the existing root for `familyName` (the one that contains
|
||||
// /<root>/<familyName>/), or nullptr if the family is not installed in
|
||||
// either root. Used by writers to keep re-installs in their existing dir.
|
||||
static const char* findFamilyRoot(const char* familyName);
|
||||
|
||||
// Returns the root path that should be used when creating a brand-new
|
||||
// family on disk (no prior install): the existing root if exactly one of
|
||||
// the two roots exists, otherwise the hidden root.
|
||||
static const char* defaultWriteRoot();
|
||||
|
||||
// Scan SD card, populate families_. Returns true if any families found.
|
||||
bool discover();
|
||||
|
||||
const std::vector<SdCardFontFamilyInfo>& getFamilies() const { return families_; }
|
||||
const SdCardFontFamilyInfo* findFamily(const std::string& name) const;
|
||||
int getFamilyIndex(const std::string& name) const;
|
||||
int getFamilyCount() const { return static_cast<int>(families_.size()); }
|
||||
|
||||
private:
|
||||
std::vector<SdCardFontFamilyInfo> families_; // sorted alphabetically
|
||||
|
||||
static bool parseFilename(const char* filename, uint8_t& size, uint8_t& style);
|
||||
static void scanDirectory(const char* dirPath, SdCardFontFamilyInfo& family);
|
||||
// Scan one root (e.g. "/.fonts"), append families to `out`, dedup by name.
|
||||
static void scanRoot(const char* rootPath, std::vector<SdCardFontFamilyInfo>& out);
|
||||
};
|
||||
@@ -1,21 +1,21 @@
|
||||
#pragma once
|
||||
|
||||
#include <builtinFonts/bookerly_12_bold.h>
|
||||
#include <builtinFonts/bookerly_12_bolditalic.h>
|
||||
#include <builtinFonts/bookerly_12_italic.h>
|
||||
#include <builtinFonts/bookerly_12_regular.h>
|
||||
#include <builtinFonts/bookerly_14_bold.h>
|
||||
#include <builtinFonts/bookerly_14_bolditalic.h>
|
||||
#include <builtinFonts/bookerly_14_italic.h>
|
||||
#include <builtinFonts/bookerly_14_regular.h>
|
||||
#include <builtinFonts/bookerly_16_bold.h>
|
||||
#include <builtinFonts/bookerly_16_bolditalic.h>
|
||||
#include <builtinFonts/bookerly_16_italic.h>
|
||||
#include <builtinFonts/bookerly_16_regular.h>
|
||||
#include <builtinFonts/bookerly_18_bold.h>
|
||||
#include <builtinFonts/bookerly_18_bolditalic.h>
|
||||
#include <builtinFonts/bookerly_18_italic.h>
|
||||
#include <builtinFonts/bookerly_18_regular.h>
|
||||
#include <builtinFonts/notoserif_12_bold.h>
|
||||
#include <builtinFonts/notoserif_12_bolditalic.h>
|
||||
#include <builtinFonts/notoserif_12_italic.h>
|
||||
#include <builtinFonts/notoserif_12_regular.h>
|
||||
#include <builtinFonts/notoserif_14_bold.h>
|
||||
#include <builtinFonts/notoserif_14_bolditalic.h>
|
||||
#include <builtinFonts/notoserif_14_italic.h>
|
||||
#include <builtinFonts/notoserif_14_regular.h>
|
||||
#include <builtinFonts/notoserif_16_bold.h>
|
||||
#include <builtinFonts/notoserif_16_bolditalic.h>
|
||||
#include <builtinFonts/notoserif_16_italic.h>
|
||||
#include <builtinFonts/notoserif_16_regular.h>
|
||||
#include <builtinFonts/notoserif_18_bold.h>
|
||||
#include <builtinFonts/notoserif_18_bolditalic.h>
|
||||
#include <builtinFonts/notoserif_18_italic.h>
|
||||
#include <builtinFonts/notoserif_18_regular.h>
|
||||
#include <builtinFonts/notosans_8_regular.h>
|
||||
#include <builtinFonts/notosans_12_bold.h>
|
||||
#include <builtinFonts/notosans_12_bolditalic.h>
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
+3831
-2406
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
+4196
-2791
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
+4541
-3040
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
+4947
-3384
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user