Upgrade to Qt 6.10.3, refactor AppState for LibraryModel integration, add ChunkMeasurer tests, and update CI/docker configurations.

This commit is contained in:
Agel committed 2026-04-03 13:55:28 +02:00
1 parent 0303107fa2
commit a31b20534a
53 files changed
+2057 -842

No files matched your search

+3 -1
View File
@@ -17,7 +17,9 @@
"Bash(bash scripts/test-ci-linux.sh 2>&1)",
"Bash(pkg-config --modversion Qt6Core)",
"Bash(dpkg -l)",
"Bash(pkg-config:*)"
"Bash(pkg-config:*)",
"Bash(git checkout:*)",
"Bash(git:*)"
]
}
}
+2
View File
@@ -37,3 +37,5 @@ ci-output/
.DS_Store
Thumbs.db
/aqtinstall.log
.claude/worktrees/
+1 -1
View File
@@ -36,7 +36,7 @@ build-docker:
- docker login -u "${CI_REGISTRY_USER}" -p "${CI_REGISTRY_PASSWORD}" "${CI_REGISTRY}"
script:
- docker build
--build-arg QT_VERSION=6.10.1
--build-arg QT_VERSION=6.10.3
-t "${DOCKER_IMAGE}"
-f docker/Dockerfile.build .
- docker push "${DOCKER_IMAGE}"
+19 -33
View File
@@ -7,8 +7,6 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co
Asteria Qt is a cross-platform desktop book/document reader built with Qt6/C++. It is a reimplementation of [asteria-bookreader](../asteria-bookreader) (Electron/React) using a native Qt stack.
**Target platforms:** Windows and Linux (both required from day one); macOS planned
**Current dev environment:** Linux
**Feature tier:** Minimal reader — open, read
### Format Support
@@ -39,7 +37,7 @@ Full target format list (derived from actual library inventory):
### Windows Build Environment
The toolchain is at `C:\msys64\mingw64\bin\`. Call binaries directly with full paths, but prepend `/c/msys64/mingw64/bin` to `PATH` so the compiler and its runtime DLLs are resolvable:
Qt 6.10.3 is installed at `C:\msys64\opt\qt\6.10.3\mingw_64` (by `scripts/install-deps-windows.sh`). The MinGW toolchain is at `C:\msys64\mingw64\bin\`. Call binaries directly with full paths, but prepend `/c/msys64/mingw64/bin` to `PATH` so the compiler and its runtime DLLs are resolvable:
```bash
# Configure
@@ -49,27 +47,27 @@ PATH="/c/msys64/mingw64/bin:$PATH" "C:/msys64/mingw64/bin/cmake.exe" \
-DCMAKE_MAKE_PROGRAM="C:/msys64/mingw64/bin/ninja.exe" \
-DCMAKE_C_COMPILER="C:/msys64/mingw64/bin/gcc.exe" \
-DCMAKE_CXX_COMPILER="C:/msys64/mingw64/bin/g++.exe" \
-DCMAKE_PREFIX_PATH="C:/msys64/mingw64"
-DCMAKE_PREFIX_PATH="c:\msys64\opt\qt\6.10.3\mingw_64"
# Build
PATH="/c/msys64/mingw64/bin:$PATH" "C:/msys64/mingw64/bin/ninja.exe" -C build
# Test
PATH="/c/msys64/mingw64/bin:$PATH" "C:/msys64/mingw64/bin/ctest.exe" --test-dir build --output-on-failure
# Test (Qt DLLs must be on PATH so test executables can load them)
PATH="/c/msys64/opt/qt/6.10.3/mingw_64/bin:/c/msys64/mingw64/bin:$PATH" "C:/msys64/mingw64/bin/ctest.exe" --test-dir build --output-on-failure
```
Use Unix-style paths (`/c/msys64/...`) for `PATH` assignments — Windows-style paths are not recognised by the shell.
### Linux Build Environment
Base: **Ubuntu 24.04**. Ubuntu apt only ships Qt 6.4, which is too old; Qt 6.10.1 is installed via `aqtinstall`.
Base: **Ubuntu 24.04**. Ubuntu apt only ships Qt 6.4, which is too old; Qt 6.10.3 is installed via `aqtinstall`.
Run `scripts/install-deps-ubuntu.sh` to install all system packages and Qt, then:
```bash
cmake -S . -B build -G Ninja \
-DCMAKE_BUILD_TYPE=Debug \
-DCMAKE_PREFIX_PATH=/opt/qt/6.10.1/gcc_64
-DCMAKE_PREFIX_PATH=/opt/qt/6.10.3/gcc_64
ninja -C build
ctest --test-dir build --output-on-failure
@@ -96,8 +94,8 @@ System packages installed by the script:
GitLab CI (`.gitlab-ci.yml`), stages: `build` → `package` → `wiki`.
The CI Docker image is built from `docker/Dockerfile.build` (Ubuntu 24.04 base) and contains:
- Native Linux toolchain + Qt 6.10.1 at `$QT_LINUX_DIR` (`/opt/qt/6.10.1/gcc_64`)
- MinGW-w64 cross-compilation toolchain + Qt 6.10.1 for Windows at `$QT_WINDOWS_DIR` (`/opt/qt/6.10.1/mingw_64`)
- Native Linux toolchain + Qt 6.10.3 at `$QT_LINUX_DIR` (`/opt/qt/6.10.3/gcc_64`)
- MinGW-w64 cross-compilation toolchain + Qt 6.10.3 for Windows at `$QT_WINDOWS_DIR` (`/opt/qt/6.10.3/mingw_64`)
- Cross-compiled Windows sysroot at `$MINGW_SYSROOT` (`/opt/mingw-sysroot`) with libiconv and uchardet
- AppImage packaging tools (linuxdeploy, appimagetool)
@@ -115,41 +113,28 @@ When `CMakeLists.txt` gains a new `find_package` or `pkg_check_modules` dependen
| `scripts/install-deps-windows.sh` | `pacman` package for Windows host builds |
| `docker/Dockerfile.build` | `apt` package for CI Linux build; cross-compiled lib for CI Windows cross-build if needed |
## Architecture
Strictly follow SOLID principles.
## Development
## Test-Driven Development
**All new backend logic must be test-driven.** Follow the red-green-refactor cycle strictly:
1. **Red** — write a failing test that specifies the desired behavior before writing any implementation
2. **Green** — write the minimum implementation to make the test pass
3. **Refactor** — clean up with tests still passing
### Rules
- Never write implementation code without a corresponding failing test first
- Tests live in `tests/` mirroring the `src/backend/` structure (e.g., `tests/formats/TxtReaderTest.cpp`)
- Keep test coverage high (80%+)
- Use `Qt Test` (`QTest`) framework — include `find_package(Qt6 REQUIRED COMPONENTS Test)` in CMakeLists
- Each format reader must have a test that loads a real sample file from `tests/fixtures/`
- `BookController`, `ReadingModel`, and `AppState` must each have unit tests
- QML-only UI code is exempt from TDD; backend logic extracted to C++ is not
- Run `ctest --test-dir build --output-on-failure` before considering any task complete
- Run `ctest --test-dir build --output-on-failure` and check for test coverage before considering any task complete
## Architecture
**Strictly follow SOLID principles.**
**Backend (C++)** handles all file I/O and format parsing. **QML** handles all UI. They communicate via `QObject` models exposed to the QML engine via `setContextProperty()`.
**Position restoration:** Pixel-perfect position restoration is mandatory. On every book open, `ChunkMeasurer` pre-measures chunk heights (in background, parallel, via `IImageLoader` for images) before restoring `contentY`. Never restore using pixel offsets that were calculated before heights were measured.
### QObjects Exposed to QML
| Object | Responsibility |
|---|---|
| `BookController` | Open/close book, owns reader (via `ReaderFactory`), exposes metadata (title, author), TOC |
| `ReadingModel` | QAbstractListModel exposing chapter chunks (ContentRole), position, next/prev navigation, progress % |
| `ReadingModel` | QAbstractListModel exposing chapter chunks (ContentRole), position, next/prev navigation, progress |
| `AppState` | Window geometry, last file, preferences (`QSettings`) |
Sidebar state, header state, etc. stay as pure QML properties — no C++ needed.
### Content Model
All format readers produce normalized HTML content organized into chapters. Each chapter's content is split into chunks (a `QStringList`) at the reader level, where the format structure is known. This enables virtualized rendering via `ListView` in QML. The content model is defined in `FormatReader.h`:
@@ -182,9 +167,11 @@ Chapter mapping by format: TXT = 1 chapter (whole file). FB2 = `<section>` eleme
**ReadingModel** is a `QAbstractListModel` exposing chunks via `ContentRole`. `PageView.qml` renders chunks in a `ListView` with `cacheBuffer` for seamless scrolling — no visible seams between chunks.
**Progress tracking** to track reading position ONLY ListView y offset must be used. Current page / progress percentage must be calculated using this and total height only.
### Reader Factory
`ReaderFactory` is separate from `FormatReader`. It provides a static `create(const QString &filePath)` method with a simple extension-to-reader map. No plugin system — a switch statement is fine for ~11 formats.
`ReaderFactory` is separate from `FormatReader`. It provides a static `create(const QString &filePath)` method backed by a registration map (extension → factory function). Adding a new format requires only a new map entry — no modifications to existing factory logic (OCP). No plugin system needed.
### Async Book Opening
@@ -248,7 +235,6 @@ tests/
- Use only Qt APIs for filesystem, paths, and dialogs — no platform-specific code
- Third-party libs must be available on Windows and Linux; prefer those with CMake `find_package` or vcpkg support
- Avoid `#ifdef Q_OS_WIN` / `#ifdef Q_OS_LINUX` except where genuinely unavoidable
## Design & Color Scheme
+41 -4
View File
@@ -36,13 +36,25 @@ set(SOURCES
src/backend/FormatReader.h
src/backend/AppState.h
src/backend/AppState.cpp
src/backend/LibraryBookModel.h
src/backend/LibraryBookModel.cpp
src/backend/LibraryModel.h
src/backend/LibraryModel.cpp
src/backend/ReadingModel.h
src/backend/ReadingModel.cpp
src/backend/BookController.h
src/backend/BookController.cpp
src/backend/IImageProvider.h
src/backend/EpubImageProvider.h
src/backend/EpubImageProvider.cpp
src/backend/ImageProviderFactory.h
src/backend/ImageProviderFactory.cpp
src/backend/ZipUtils.h
src/backend/IImageLoader.h
src/backend/ImageLoaderFactory.h
src/backend/ImageLoaderFactory.cpp
src/backend/ChunkMeasurer.h
src/backend/ChunkMeasurer.cpp
src/backend/IFileDialogService.h
src/backend/IFileDialogService.cpp
src/backend/NativeFileDialogService.h
@@ -191,25 +203,50 @@ add_asteria_test(ReaderFactoryTest tests/ReaderFactoryTest.cpp
src/backend/formats/EpubReader.cpp)
target_link_libraries(ReaderFactoryTest PRIVATE PkgConfig::MINIZIP Qt6::Xml)
add_asteria_test(ChunkMeasurerTest tests/ChunkMeasurerTest.cpp
src/backend/ChunkMeasurer.cpp
src/backend/EpubImageProvider.cpp)
target_link_libraries(ChunkMeasurerTest PRIVATE Qt6::Gui Qt6::Concurrent Qt6::Quick PkgConfig::MINIZIP)
set_tests_properties(ChunkMeasurerTest PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen")
add_asteria_test(ReadingModelTest tests/ReadingModelTest.cpp
src/backend/ReadingModel.cpp)
target_link_libraries(ReadingModelTest PRIVATE Qt6::Gui)
src/backend/ReadingModel.cpp
src/backend/ChunkMeasurer.cpp
src/backend/EpubImageProvider.cpp
src/backend/AppState.cpp
src/backend/LibraryBookModel.cpp
src/backend/LibraryModel.cpp
src/backend/ReaderFactory.cpp
src/backend/formats/TxtReader.cpp
src/backend/formats/EpubReader.cpp)
target_link_libraries(ReadingModelTest PRIVATE Qt6::Gui Qt6::Concurrent Qt6::Quick PkgConfig::MINIZIP Qt6::Xml)
set_tests_properties(ReadingModelTest PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen")
add_asteria_test(BookControllerTest tests/BookControllerTest.cpp
src/backend/BookController.cpp
src/backend/AppState.cpp
src/backend/LibraryBookModel.cpp
src/backend/LibraryModel.cpp
src/backend/ReaderFactory.cpp
src/backend/ReadingModel.cpp
src/backend/IFileDialogService.cpp
src/backend/NativeFileDialogService.cpp
src/backend/ImageProviderFactory.cpp
src/backend/ImageLoaderFactory.cpp
src/backend/EpubImageProvider.cpp
src/backend/ChunkMeasurer.cpp
src/backend/formats/TxtReader.cpp
src/backend/formats/EpubReader.cpp)
add_asteria_test(AppStateTest tests/AppStateTest.cpp
src/backend/AppState.cpp)
src/backend/AppState.cpp
src/backend/LibraryBookModel.cpp
src/backend/LibraryModel.cpp
src/backend/ReaderFactory.cpp
src/backend/formats/TxtReader.cpp
src/backend/formats/EpubReader.cpp)
target_link_libraries(AppStateTest PRIVATE PkgConfig::MINIZIP Qt6::Xml Qt6::Concurrent)
target_link_libraries(BookControllerTest PRIVATE Qt6::Widgets Qt6::Quick Qt6::Gui PkgConfig::MINIZIP Qt6::Xml)
target_link_libraries(BookControllerTest PRIVATE Qt6::Widgets Qt6::Quick Qt6::Gui PkgConfig::MINIZIP Qt6::Xml Qt6::Concurrent)
set_tests_properties(BookControllerTest PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen")
add_asteria_test(EpubImageProviderTest tests/EpubImageProviderTest.cpp
+3
View File
@@ -0,0 +1,3 @@
Read CLAUDE.md for project details.
ALWAYS try to compile and run tests after making code changes to ensure system integrity.
+25 -29
View File
@@ -18,7 +18,7 @@ A cross-platform desktop book/document reader built with Qt6/C++. Reimplementati
sudo scripts/install-deps-ubuntu.sh
```
The script installs Qt 6.10.1 via `aqtinstall` to `/opt/qt/6.10.1/gcc_64`, plus the following apt packages:
The script installs Qt 6.10.3 via `aqtinstall` to `/opt/qt/6.10.3/gcc_64`, plus the following apt packages:
| Group | Packages | Required? |
|---|---|---|
@@ -64,31 +64,24 @@ cd /c/path/to/asteria-qt
bash scripts/install-deps-windows.sh
```
Or install manually:
The script installs Qt 6.10.3 via `aqtinstall` to `/opt/qt/6.10.3/mingw_64`, plus the following MSYS2 packages:
```bash
pacman -S --needed \
mingw-w64-x86_64-gcc \
mingw-w64-x86_64-zlib \
mingw-w64-x86_64-qt6-base \
mingw-w64-x86_64-qt6-declarative \
mingw-w64-x86_64-qt6-tools \
mingw-w64-x86_64-qt6-shadertools \
mingw-w64-x86_64-qt6-svg \
mingw-w64-x86_64-cmake \
mingw-w64-x86_64-ninja \
mingw-w64-x86_64-uchardet \
mingw-w64-x86_64-quazip \
mingw-w64-x86_64-djvulibre \
mingw-w64-x86_64-libwpd
```
- `mingw-w64-x86_64-gcc` — GCC toolchain
- `mingw-w64-x86_64-zlib` — Compression library
- `mingw-w64-x86_64-cmake` — CMake build system
- `mingw-w64-x86_64-ninja` — Ninja build tool
- `mingw-w64-x86_64-uchardet` — Character encoding detection
- `mingw-w64-x86_64-minizip` — ZIP archive support
- `mingw-w64-x86_64-quazip` — Qt ZIP integration
- `mingw-w64-x86_64-djvulibre` — DjVu document support
- `mingw-w64-x86_64-libwpd` — WordPerfect document support
Verify the installation:
```bash
qmake6 --version
gcc --version
cmake --version
ls /opt/qt/6.10.3/mingw_64/bin # Should show Qt binaries like qmake6
```
**Step 4 — Clone the repository**
@@ -102,21 +95,21 @@ cd asteria-qt
All build commands run in the **MSYS2 MINGW64** shell on Windows, or a regular terminal on Linux.
On Linux, pass `-DCMAKE_PREFIX_PATH=/opt/qt/6.10.1/gcc_64` so CMake finds the aqt-installed Qt. On Windows, MSYS2 installs everything to a standard prefix that CMake finds automatically.
On Linux, pass `-DCMAKE_PREFIX_PATH=/opt/qt/6.10.3/gcc_64` so CMake finds the aqt-installed Qt. On Windows, pass `-DCMAKE_PREFIX_PATH=c:\msys64\opt\qt\6.10.3\mingw_64` for the same reason.
### Command Line
```bash
# Debug build (Linux)
cmake -B build -G Ninja -DCMAKE_BUILD_TYPE=Debug -DCMAKE_PREFIX_PATH=/opt/qt/6.10.1/gcc_64
cmake -B build -G Ninja -DCMAKE_BUILD_TYPE=Debug -DCMAKE_PREFIX_PATH=/opt/qt/6.10.3/gcc_64
cmake --build build --parallel
# Debug build (Windows — no prefix needed)
cmake -B build -G Ninja -DCMAKE_BUILD_TYPE=Debug
# Debug build (Windows)
cmake -B build -G Ninja -DCMAKE_BUILD_TYPE=Debug -DCMAKE_PREFIX_PATH=c:\msys64\opt\qt\6.10.3\mingw_64
cmake --build build --parallel
# Release build (Linux)
cmake -B build-release -G Ninja -DCMAKE_BUILD_TYPE=Release -DCMAKE_PREFIX_PATH=/opt/qt/6.10.1/gcc_64
cmake -B build-release -G Ninja -DCMAKE_BUILD_TYPE=Release -DCMAKE_PREFIX_PATH=/opt/qt/6.10.3/gcc_64
cmake --build build-release --parallel
# Run tests
@@ -136,11 +129,11 @@ ctest --test-dir build --output-on-failure
1. Open the project root folder (File → Open) — CLion detects `CMakeLists.txt` automatically
2. Go to **Settings → Build, Execution, Deployment → CMake**
3. In the **Debug** profile, add to **CMake options**:
3. In the **Debug** and **Release** profiles, add to **CMake options**:
```
-DCMAKE_PREFIX_PATH=/opt/qt/6.10.1/gcc_64
-DCMAKE_PREFIX_PATH=/opt/qt/6.10.3/gcc_64
```
This is where `install-deps-ubuntu.sh` installs Qt 6.10.1 via aqtinstall.
This is where `install-deps-ubuntu.sh` installs Qt 6.10.3 via aqtinstall.
4. CLion auto-detects the system GCC toolchain — no toolchain configuration needed
5. To add a **Release** profile: click `+` to duplicate, change **Build type** to `Release`, same CMake options
6. Build: `Ctrl+F9` | Run: `Shift+F10`
@@ -154,7 +147,10 @@ ctest --test-dir build --output-on-failure
- Leave **Debugger** set to **Bundled** — MSYS2's GDB can be newer than CLion supports
2. **Configure CMake** — Settings → Build, Execution, Deployment → **CMake**:
- In the Debug profile, set **Toolchain** to the MSYS2 MinGW toolchain created above
- No `CMAKE_PREFIX_PATH` needed — MSYS2 installs Qt to a prefix CMake finds automatically
3. In the **Debug** and **Release** profiles, add to **CMake options**:
```
-DCMAKE_PREFIX_PATH=c:\msys64\opt\qt\6.10.3\mingw_64
```
3. Build: `Ctrl+F9` | Run: `Shift+F10`
### VSCode
@@ -169,5 +165,5 @@ ctest --test-dir build --output-on-failure
1. File → Open File or Project → select `CMakeLists.txt`
2. Configure the kit under Edit → Preferences → Kits
3. On Windows: add a kit pointing to MSYS2's Qt (`C:\msys64\mingw64`) and MinGW compiler
3. On Windows: add a kit pointing to MSYS2's Qt (`C:\msys64\mingw64`) and MinGW compiler and `-DCMAKE_PREFIX_PATH=c:\msys64\opt\qt\6.10.3\mingw_64` to the CMake options
4. Build: `Ctrl+B` / `⌘B` | Run: `Ctrl+R` / `⌘R`
+1 -1
View File
@@ -1,6 +1,6 @@
FROM ubuntu:24.04
ARG QT_VERSION=6.10.1
ARG QT_VERSION=6.10.3
ARG QT_INSTALL_DIR=/opt/qt
ARG ZLIB_VERSION=1.3.1
+5 -5
View File
@@ -23,18 +23,18 @@ apt-get install -y \
python3-venv
echo ""
echo "Installing Qt 6.10.1 via aqtinstall → /opt/qt ..."
echo "Installing Qt 6.10.3 via aqtinstall → /opt/qt ..."
python3 -m venv /tmp/aqt-venv
/tmp/aqt-venv/bin/pip install --quiet aqtinstall
/tmp/aqt-venv/bin/aqt install-qt linux desktop 6.10.1 linux_gcc_64 -m qtimageformats qtpdf qtwebview --outputdir /opt/qt
/tmp/aqt-venv/bin/aqt install-tool linux desktop tools_qtdesignstudio_generation2 --outputdir /opt/qt
/tmp/aqt-venv/bin/aqt install-qt linux desktop 6.10.3 linux_gcc_64 -m qtimageformats qtpdf qtwebview --outputdir /opt/qt
/tmp/aqt-venv/bin/aqt install-src linux 6.10.3 --archives qtbase qtimageformats qtwebview --outputdir /opt/qt
rm -rf /tmp/aqt-venv
echo ""
echo "All dependencies installed."
echo ""
echo "Qt 6.10.1 is at /opt/qt/6.10.1/gcc_64"
echo "Qt 6.10.3 is at /opt/qt/6.10.3/gcc_64"
echo ""
echo "Build with:"
echo " cmake -B build -G Ninja -DCMAKE_BUILD_TYPE=Debug -DCMAKE_PREFIX_PATH=/opt/qt/6.10.1/gcc_64"
echo " cmake -B build -G Ninja -DCMAKE_BUILD_TYPE=Debug -DCMAKE_PREFIX_PATH=/opt/qt/6.10.3/gcc_64"
echo " cmake --build build --parallel"
+20 -11
View File
@@ -5,26 +5,35 @@
set -euo pipefail
echo "Installing Qt 6 and dependencies via pacman..."
echo "Installing non-Qt dependencies via pacman..."
pacman -S --needed \
mingw-w64-x86_64-gcc \
mingw-w64-x86_64-zlib \
mingw-w64-x86_64-qt6-base \
mingw-w64-x86_64-qt6-declarative \
mingw-w64-x86_64-qt6-tools \
mingw-w64-x86_64-qt6-shadertools \
mingw-w64-x86_64-qt6-svg \
mingw-w64-x86_64-cmake \
mingw-w64-x86_64-ninja \
mingw-w64-x86_64-uchardet \
mingw-w64-x86_64-minizip \
mingw-w64-x86_64-quazip \
mingw-w64-x86_64-djvulibre \
mingw-w64-x86_64-libwpd
mingw-w64-x86_64-libwpd \
python3 \
python-pip \
python-setuptools \
mingw-w64-x86_64-python-psutil
echo ""
echo "Done. Verify with:"
echo " qmake6 --version"
echo " gcc --version"
echo " cmake --version"
echo "Installing Qt 6.10.3 via aqtinstall → /opt/qt ..."
python3 -m venv --system-site-packages /tmp/aqt-venv
/tmp/aqt-venv/bin/pip install --no-build-isolation aqtinstall
/tmp/aqt-venv/bin/aqt install-qt windows desktop 6.10.3 win64_mingw -m qtimageformats qtpdf qtwebview --outputdir /opt/qt
rm -rf /tmp/aqt-venv
echo ""
echo "All dependencies installed."
echo ""
echo "Qt 6.10.3 is at /opt/qt/6.10.3/mingw_64"
echo ""
echo "Build with:"
echo " cmake -B build -G Ninja -DCMAKE_BUILD_TYPE=Debug -DCMAKE_PREFIX_PATH=c:\msys64\opt\qt\6.10.3\mingw_64"
echo " cmake --build build --parallel"
+1 -1
View File
@@ -24,7 +24,7 @@ echo "Using container runtime: $RUNTIME"
# Build CI image
echo "==> Building CI image from $DOCKERFILE"
"$RUNTIME" build \
--build-arg QT_VERSION=6.10.1 \
--build-arg QT_VERSION=6.10.3 \
-t "$IMAGE_TAG" \
-f "$DOCKERFILE" \
"$PROJECT_DIR"
+1 -1
View File
@@ -32,7 +32,7 @@ echo "Using container runtime: $RUNTIME"
# Build CI image
echo "==> Building CI image from $DOCKERFILE"
"$RUNTIME" build \
--build-arg QT_VERSION=6.10.1 \
--build-arg QT_VERSION=6.10.3 \
-t "$IMAGE_TAG" \
-f "$DOCKERFILE" \
"$PROJECT_DIR"
+64 -112
View File
@@ -1,7 +1,9 @@
#include "AppState.h"
#include <QSettings>
#include <QCryptographicHash>
#include <QDateTime>
#include "LibraryBookModel.h"
#include "LibraryModel.h"
#include <QtConcurrent/QtConcurrent>
static constexpr int SETTINGS_VERSION = 3;
static QString bookSettingsKey(const QString &filePath)
{
@@ -12,6 +14,7 @@ static QString bookSettingsKey(const QString &filePath)
AppState::AppState(QObject *parent)
: QObject(parent)
{
m_libraryModel = new LibraryModel(this);
}
QString AppState::lastFilePath() const { return m_lastFilePath; }
@@ -24,46 +27,6 @@ void AppState::setLastFilePath(const QString &path)
emit lastFilePathChanged();
}
int AppState::lastChapter() const { return m_lastChapter; }
void AppState::setLastChapter(int chapter)
{
if (m_lastChapter == chapter)
return;
m_lastChapter = chapter;
emit lastChapterChanged();
}
qreal AppState::lastScrollPosition() const { return m_lastScrollPosition; }
void AppState::setLastScrollPosition(qreal position)
{
if (qFuzzyCompare(m_lastScrollPosition, position))
return;
m_lastScrollPosition = position;
emit lastScrollPositionChanged();
}
int AppState::lastScrollIndex() const { return m_lastScrollIndex; }
void AppState::setLastScrollIndex(int index)
{
if (m_lastScrollIndex == index)
return;
m_lastScrollIndex = index;
emit lastScrollIndexChanged();
}
qreal AppState::lastScrollOffset() const { return m_lastScrollOffset; }
void AppState::setLastScrollOffset(qreal offset)
{
if (qFuzzyCompare(m_lastScrollOffset, offset))
return;
m_lastScrollOffset = offset;
emit lastScrollOffsetChanged();
}
int AppState::horizontalMargin() const { return m_horizontalMargin; }
void AppState::setHorizontalMargin(int margin)
@@ -149,23 +112,22 @@ QUrl AppState::lastFileUrl() const
return QUrl::fromLocalFile(m_lastFilePath);
}
void AppState::saveBookPosition(const QString &filePath, int chapter, int scrollIndex, qreal scrollOffset)
void AppState::saveBookPosition(const QString &filePath, int chunkIndex, int intraChunkOffset)
{
qInfo() << "Saving book position: chunk" << chunkIndex << "offset" << intraChunkOffset;
QSettings s;
QString key = bookSettingsKey(filePath);
s.setValue(key + QStringLiteral("/chapter"), chapter);
s.setValue(key + QStringLiteral("/scrollIndex"), scrollIndex);
s.setValue(key + QStringLiteral("/scrollOffset"), scrollOffset);
s.setValue(key + QStringLiteral("/chunkIndex"), chunkIndex);
s.setValue(key + QStringLiteral("/intraChunkOffset"), intraChunkOffset);
}
QVariantMap AppState::loadBookPosition(const QString &filePath) const
QVariantMap AppState::loadBookPosition(const QString &filePath)
{
QSettings s;
QString key = bookSettingsKey(filePath);
QVariantMap result;
result[QStringLiteral("chapter")] = s.value(key + QStringLiteral("/chapter"), 0).toInt();
result[QStringLiteral("scrollIndex")] = s.value(key + QStringLiteral("/scrollIndex"), 0).toInt();
result[QStringLiteral("scrollOffset")] = s.value(key + QStringLiteral("/scrollOffset"), 0.0).toDouble();
result[QStringLiteral("chunkIndex")] = s.value(key + QStringLiteral("/chunkIndex"), 0).toInt();
result[QStringLiteral("intraChunkOffset")] = s.value(key + QStringLiteral("/intraChunkOffset"), 0.0).toInt();
return result;
}
@@ -199,67 +161,53 @@ void AppState::setThemeName(const QString &themeName)
emit themeNameChanged();
}
void AppState::addOrUpdateLibraryBook(const QString &filePath, const QString &title, const QString &author, double progress)
void AppState::addOrUpdateLibraryBook(const QString &filePath, double progress)
{
QString lastOpened = QDateTime::currentDateTime().toString(Qt::ISODate);
for (int i = 0; i < m_libraryBooks.size(); i++) {
QVariantMap book = m_libraryBooks[i].toMap();
if (book[QStringLiteral("filePath")].toString() == filePath) {
book[QStringLiteral("title")] = title;
book[QStringLiteral("author")] = author;
book[QStringLiteral("lastOpened")] = lastOpened;
if (progress >= 0.0)
book[QStringLiteral("progress")] = progress;
m_libraryBooks[i] = book;
// Move to front (most recently opened)
m_libraryBooks.move(i, 0);
saveLibraryBooks();
emit libraryBooksChanged();
return;
// Sentinel: progress < 0 means "preserve existing progress"
double resolvedProgress = progress;
if (progress < 0.0) {
LibraryBookModel* existing = m_libraryModel->findBook(filePath);
resolvedProgress = existing ? existing->progress() : 0.0;
}
}
QVariantMap newBook;
newBook[QStringLiteral("filePath")] = filePath;
newBook[QStringLiteral("title")] = title;
newBook[QStringLiteral("author")] = author;
newBook[QStringLiteral("progress")] = qMax(progress, 0.0);
newBook[QStringLiteral("lastOpened")] = lastOpened;
m_libraryBooks.prepend(newBook);
m_libraryModel->addOrUpdateBook(filePath, resolvedProgress, lastOpened);
saveLibraryBooks();
emit libraryBooksChanged();
}
void AppState::removeLibraryBook(const QString &filePath)
{
for (int i = 0; i < m_libraryBooks.size(); i++) {
if (m_libraryBooks[i].toMap()[QStringLiteral("filePath")].toString() == filePath) {
m_libraryBooks.removeAt(i);
m_libraryModel->removeBook(filePath);
saveLibraryBooks();
emit libraryBooksChanged();
return;
}
}
}
QVariantList AppState::libraryBooks() const
QObject* AppState::libraryModel() const
{
return m_libraryBooks;
// Add null check to prevent crashes during initialization
if (!m_libraryModel) {
qWarning() << "LibraryModel accessed before initialization";
return nullptr;
}
return m_libraryModel;
}
void AppState::loadLibraryBooks()
{
QSettings s;
int size = s.beginReadArray(QStringLiteral("library"));
m_libraryBooks.clear();
for (int i = 0; i < size; i++) {
s.setArrayIndex(i);
QVariantMap book;
book[QStringLiteral("filePath")] = s.value(QStringLiteral("filePath")).toString();
book[QStringLiteral("title")] = s.value(QStringLiteral("title")).toString();
book[QStringLiteral("author")] = s.value(QStringLiteral("author")).toString();
book[QStringLiteral("progress")] = s.value(QStringLiteral("progress"), 0.0).toDouble();
book[QStringLiteral("lastOpened")] = s.value(QStringLiteral("lastOpened")).toString();
m_libraryBooks.append(book);
QString filePath = s.value(QStringLiteral("filePath")).toString();
if (filePath.isEmpty())
continue;
bool progressOk;
double progress = s.value(QStringLiteral("progress"), 0.0).toDouble(&progressOk);
if (!progressOk)
progress = 0.0;
progress = qBound(0.0, progress, 1.0);
QString lastOpened = s.value(QStringLiteral("lastOpened")).toString();
m_libraryModel->addOrUpdateBook(filePath, progress, lastOpened);
}
s.endArray();
}
@@ -267,15 +215,14 @@ void AppState::loadLibraryBooks()
void AppState::saveLibraryBooks()
{
QSettings s;
s.beginWriteArray(QStringLiteral("library"), m_libraryBooks.size());
for (int i = 0; i < m_libraryBooks.size(); i++) {
QList<LibraryBookModel*> books = m_libraryModel->books();
s.beginWriteArray(QStringLiteral("library"), books.size());
for (int i = 0; i < books.size(); i++) {
s.setArrayIndex(i);
QVariantMap book = m_libraryBooks[i].toMap();
s.setValue(QStringLiteral("filePath"), book[QStringLiteral("filePath")]);
s.setValue(QStringLiteral("title"), book[QStringLiteral("title")]);
s.setValue(QStringLiteral("author"), book[QStringLiteral("author")]);
s.setValue(QStringLiteral("progress"), book[QStringLiteral("progress")]);
s.setValue(QStringLiteral("lastOpened"), book[QStringLiteral("lastOpened")]);
LibraryBookModel* book = books[i];
s.setValue(QStringLiteral("filePath"), book->filePath());
s.setValue(QStringLiteral("progress"), book->progress());
s.setValue(QStringLiteral("lastOpened"), book->lastOpened());
}
s.endArray();
}
@@ -283,11 +230,8 @@ void AppState::saveLibraryBooks()
void AppState::save()
{
QSettings s;
s.setValue(QStringLiteral("version"), SETTINGS_VERSION);
s.setValue(QStringLiteral("session/lastFilePath"), m_lastFilePath);
s.setValue(QStringLiteral("session/lastChapter"), m_lastChapter);
s.setValue(QStringLiteral("session/lastScrollPosition"), m_lastScrollPosition);
s.setValue(QStringLiteral("session/lastScrollIndex"), m_lastScrollIndex);
s.setValue(QStringLiteral("session/lastScrollOffset"), m_lastScrollOffset);
s.setValue(QStringLiteral("session/lastPage"), m_lastPage);
s.setValue(QStringLiteral("session/sidebarOpen"), m_sidebarOpen);
s.setValue(QStringLiteral("preferences/horizontalMargin"), m_horizontalMargin);
@@ -300,27 +244,35 @@ void AppState::save()
s.setValue(QStringLiteral("window/x"), m_windowX);
s.setValue(QStringLiteral("window/y"), m_windowY);
saveLibraryBooks();
qInfo() << "filename:" << s.fileName();
}
void AppState::restore()
{
QSettings s;
// Wipe and start fresh if settings are from a different/incompatible format version
if (s.value(QStringLiteral("version"), 0).toInt() != SETTINGS_VERSION) {
s.clear();
emit stateRestored();
return;
}
m_lastFilePath = s.value(QStringLiteral("session/lastFilePath"), QString()).toString();
m_lastChapter = s.value(QStringLiteral("session/lastChapter"), 0).toInt();
m_lastScrollPosition = s.value(QStringLiteral("session/lastScrollPosition"), 0.0).toDouble();
m_lastScrollIndex = s.value(QStringLiteral("session/lastScrollIndex"), 0).toInt();
m_lastScrollOffset = s.value(QStringLiteral("session/lastScrollOffset"), 0.0).toDouble();
m_lastPage = s.value(QStringLiteral("session/lastPage"), QStringLiteral("starter")).toString();
m_sidebarOpen = s.value(QStringLiteral("session/sidebarOpen"), false).toBool();
m_horizontalMargin = s.value(QStringLiteral("preferences/horizontalMargin"), 32).toInt();
m_verticalMargin = s.value(QStringLiteral("preferences/verticalMargin"), 8).toInt();
m_fontSize = s.value(QStringLiteral("preferences/fontSize"), 16).toInt();
m_lineSpacing = s.value(QStringLiteral("preferences/lineSpacing"), 1.6).toDouble();
m_horizontalMargin = qMax(0, s.value(QStringLiteral("preferences/horizontalMargin"), 32).toInt());
m_verticalMargin = qMax(0, s.value(QStringLiteral("preferences/verticalMargin"), 8).toInt());
m_fontSize = qBound(8, s.value(QStringLiteral("preferences/fontSize"), 16).toInt(), 72);
m_lineSpacing = qMax(0.1, s.value(QStringLiteral("preferences/lineSpacing"), 1.6).toDouble());
m_themeName = s.value(QStringLiteral("preferences/themeName"), QStringLiteral("dark")).toString();
m_windowWidth = s.value(QStringLiteral("window/width"), 1024).toInt();
m_windowHeight = s.value(QStringLiteral("window/height"), 768).toInt();
m_windowX = s.value(QStringLiteral("window/x"), -1).toInt();
m_windowY = s.value(QStringLiteral("window/y"), -1).toInt();
loadLibraryBooks();
emit stateRestored();
+11 -32
View File
@@ -5,15 +5,13 @@
#include <QString>
#include <QUrl>
#include <QVariantMap>
#include <QVariantList>
class LibraryBookModel;
class LibraryModel;
class AppState : public QObject {
Q_OBJECT
Q_PROPERTY(QString lastFilePath READ lastFilePath WRITE setLastFilePath NOTIFY lastFilePathChanged)
Q_PROPERTY(int lastChapter READ lastChapter WRITE setLastChapter NOTIFY lastChapterChanged)
Q_PROPERTY(qreal lastScrollPosition READ lastScrollPosition WRITE setLastScrollPosition NOTIFY lastScrollPositionChanged)
Q_PROPERTY(int lastScrollIndex READ lastScrollIndex WRITE setLastScrollIndex NOTIFY lastScrollIndexChanged)
Q_PROPERTY(qreal lastScrollOffset READ lastScrollOffset WRITE setLastScrollOffset NOTIFY lastScrollOffsetChanged)
Q_PROPERTY(int horizontalMargin READ horizontalMargin WRITE setHorizontalMargin NOTIFY horizontalMarginChanged)
Q_PROPERTY(int verticalMargin READ verticalMargin WRITE setVerticalMargin NOTIFY verticalMarginChanged)
Q_PROPERTY(int fontSize READ fontSize WRITE setFontSize NOTIFY fontSizeChanged)
@@ -22,10 +20,11 @@ class AppState : public QObject {
Q_PROPERTY(int windowHeight READ windowHeight WRITE setWindowHeight NOTIFY windowHeightChanged)
Q_PROPERTY(int windowX READ windowX WRITE setWindowX NOTIFY windowXChanged)
Q_PROPERTY(int windowY READ windowY WRITE setWindowY NOTIFY windowYChanged)
Q_PROPERTY(QVariantList libraryBooks READ libraryBooks NOTIFY libraryBooksChanged)
Q_PROPERTY(QString lastPage READ lastPage WRITE setLastPage NOTIFY lastPageChanged)
Q_PROPERTY(bool sidebarOpen READ sidebarOpen WRITE setSidebarOpen NOTIFY sidebarOpenChanged)
Q_PROPERTY(QString themeName READ themeName WRITE setThemeName NOTIFY themeNameChanged)
Q_PROPERTY(QObject* libraryModel READ libraryModel CONSTANT)
public:
explicit AppState(QObject *parent = nullptr);
@@ -36,18 +35,6 @@ public:
QString lastFilePath() const;
void setLastFilePath(const QString &path);
int lastChapter() const;
void setLastChapter(int chapter);
qreal lastScrollPosition() const;
void setLastScrollPosition(qreal position);
int lastScrollIndex() const;
void setLastScrollIndex(int index);
qreal lastScrollOffset() const;
void setLastScrollOffset(qreal offset);
int horizontalMargin() const;
void setHorizontalMargin(int margin);
@@ -74,8 +61,8 @@ public:
Q_INVOKABLE QUrl lastFileUrl() const;
Q_INVOKABLE void saveBookPosition(const QString &filePath, int chapter, int scrollIndex, qreal scrollOffset);
Q_INVOKABLE QVariantMap loadBookPosition(const QString &filePath) const;
Q_INVOKABLE static void saveBookPosition(const QString &filePath, int chunkIndex, int intraChunkOffset);
Q_INVOKABLE static QVariantMap loadBookPosition(const QString &filePath);
QString lastPage() const;
void setLastPage(const QString &page);
@@ -83,19 +70,15 @@ public:
bool sidebarOpen() const;
void setSidebarOpen(bool open);
Q_INVOKABLE void addOrUpdateLibraryBook(const QString &filePath, const QString &title, const QString &author, double progress);
Q_INVOKABLE void addOrUpdateLibraryBook(const QString &filePath, double progress);
Q_INVOKABLE void removeLibraryBook(const QString &filePath);
Q_INVOKABLE QVariantList libraryBooks() const;
QObject* libraryModel() const;
Q_INVOKABLE void save();
Q_INVOKABLE void restore();
signals:
void lastFilePathChanged();
void lastChapterChanged();
void lastScrollPositionChanged();
void lastScrollIndexChanged();
void lastScrollOffsetChanged();
void horizontalMarginChanged();
void verticalMarginChanged();
void fontSizeChanged();
@@ -105,7 +88,7 @@ signals:
void windowHeightChanged();
void windowXChanged();
void windowYChanged();
void libraryBooksChanged();
void lastPageChanged();
void sidebarOpenChanged();
void themeNameChanged();
@@ -114,10 +97,6 @@ private:
void loadLibraryBooks();
void saveLibraryBooks();
QString m_lastFilePath;
int m_lastChapter = 0;
qreal m_lastScrollPosition = 0.0;
int m_lastScrollIndex = 0;
qreal m_lastScrollOffset = 0.0;
int m_horizontalMargin = 32;
int m_verticalMargin = 8;
int m_fontSize = 16;
@@ -126,7 +105,7 @@ private:
int m_windowHeight = 768;
int m_windowX = -1;
int m_windowY = -1;
QVariantList m_libraryBooks;
LibraryModel* m_libraryModel;
QString m_lastPage = QStringLiteral("starter");
bool m_sidebarOpen = false;
QString m_themeName = QStringLiteral("dark");
+117 -27
View File
@@ -1,13 +1,24 @@
#include "BookController.h"
#include "AppState.h"
#include "ImageLoaderFactory.h"
#include "ImageProviderFactory.h"
#include "ReaderFactory.h"
#include "ReadingModel.h"
#include <QtConcurrent>
BookController::BookController(QObject *parent)
: QObject(parent)
{
}
BookController::~BookController()
{
if (m_openFuture.isRunning()) {
m_openFuture.cancel();
m_openFuture.waitForFinished();
}
}
QString BookController::bookTitle() const
{
return m_bookTitle;
@@ -38,6 +49,11 @@ QString BookController::currentFilePath() const
return m_currentFilePath;
}
bool BookController::startupRestore() const
{
return m_startupRestore;
}
QList<TocEntry> BookController::toc() const
{
if (m_reader)
@@ -45,9 +61,25 @@ QList<TocEntry> BookController::toc() const
return {};
}
QString BookController::coverImageUrl() const
{
return m_coverImageUrl;
}
void BookController::setReadingModel(ReadingModel *model)
{
m_readingModel = model;
if (m_readingModel) {
connect(m_readingModel, &ReadingModel::restoreReady,
this, [this]() {
if (!m_loading)
return;
m_loading = false;
emit loadingChanged();
emit bookReady();
m_startupRestore = false;
});
}
}
void BookController::setAppState(AppState *state)
@@ -63,6 +95,16 @@ void BookController::setFileDialogService(IFileDialogService *service)
this, &BookController::openBookFromPath);
}
void BookController::uiReady()
{
if (!m_appState || m_appState->lastFilePath().isEmpty()) {
emit noSavedBook();
return;
}
m_startupRestore = true;
openBook(m_appState->lastFileUrl());
}
void BookController::openBookFromPath(const QString &filePath)
{
openBook(QUrl::fromLocalFile(filePath));
@@ -70,15 +112,10 @@ void BookController::openBookFromPath(const QString &filePath)
void BookController::openBook(const QUrl &fileUrl)
{
QString filePath = fileUrl.toLocalFile();
const QString filePath = fileUrl.toLocalFile();
if (m_reader && m_appState && m_readingModel) {
m_appState->saveBookPosition(m_currentFilePath,
m_readingModel->currentChapter(),
m_appState->lastScrollIndex(),
m_appState->lastScrollOffset());
m_appState->addOrUpdateLibraryBook(m_currentFilePath, m_bookTitle, m_bookAuthor,
m_readingModel->progress());
m_appState->addOrUpdateLibraryBook(m_currentFilePath, m_readingModel->progress());
}
if (m_reader)
closeBook();
@@ -89,42 +126,94 @@ void BookController::openBook(const QUrl &fileUrl)
m_errorMessage.clear();
emit errorMessageChanged();
const int generation = ++m_openGeneration;
m_openFuture = QtConcurrent::run([this, filePath, generation]() {
// --- background thread: all file I/O ---
auto reader = ReaderFactory::create(filePath);
if (!reader) {
QMetaObject::invokeMethod(this, [this, generation]() {
if (generation != m_openGeneration) return;
m_loading = false;
emit loadingChanged();
m_errorMessage = QStringLiteral("No format readers available");
emit errorMessageChanged();
emit bookError(m_errorMessage);
}, Qt::QueuedConnection);
return;
}
if (!reader->open(filePath)) {
const QString err = reader->lastError();
QMetaObject::invokeMethod(this, [this, generation, err]() {
if (generation != m_openGeneration) return;
m_loading = false;
emit loadingChanged();
m_errorMessage = reader->lastError();
m_errorMessage = err;
emit errorMessageChanged();
emit bookError(m_errorMessage);
}, Qt::QueuedConnection);
return;
}
m_reader = std::move(reader);
// Cheap metadata reads while still on background thread
const QString title = reader->title();
const QString author = reader->author();
const QString coverPath = reader->coverImagePath();
// Box the unique_ptr in a shared_ptr so the lambda capturing it is copyable
// (QMetaObject::invokeMethod requires a copyable functor for queued delivery).
auto readerBox = std::make_shared<std::unique_ptr<FormatReader>>(std::move(reader));
// --- main thread: model / provider setup ---
QMetaObject::invokeMethod(this, [this, generation, filePath,
readerBox, title, author, coverPath]() {
if (generation != m_openGeneration) return;
m_reader = std::move(*readerBox);
m_currentFilePath = filePath;
if (m_imageProvider)
m_imageProvider->setEpubPath(filePath);
m_bookTitle = m_reader->title();
m_bookAuthor = m_reader->author();
m_bookTitle = title;
m_bookAuthor = author;
if (m_readingModel)
m_readingModel->setReader(m_reader.get());
IImageProvider *rawProvider = ImageProviderFactory::create(filePath);
m_ownedProvider.reset();
if (rawProvider && m_providerRegistrar) {
m_providerRegistrar(rawProvider->scheme(), rawProvider);
} else {
m_ownedProvider.reset(rawProvider);
}
m_imageProvider = rawProvider;
if (m_imageProvider) {
m_imageProvider->setFilePath(filePath);
m_imageProvider->setDisplayWidth(m_contentWidth);
}
if (!coverPath.isEmpty() && m_imageProvider)
m_coverImageUrl = m_imageProvider->coverImageUrl(coverPath);
else
m_coverImageUrl.clear();
if (m_readingModel) {
if (m_appState)
m_appState->addOrUpdateLibraryBook(m_currentFilePath, m_bookTitle, m_bookAuthor, -1.0);
m_readingModel->setFontParams(m_appState->fontSize(), m_appState->lineSpacing());
m_readingModel->setImageLoader(ImageLoaderFactory::create(filePath));
m_readingModel->setCoverImageUrl(m_coverImageUrl);
m_readingModel->setReader(m_reader.get());
}
if (m_readingModel && m_appState) {
m_readingModel->measure(true);
emit bookChanged();
} else {
m_loading = false;
emit loadingChanged();
emit bookChanged();
emit bookReady();
m_startupRestore = false;
}
}, Qt::QueuedConnection);
});
}
void BookController::browseAndOpen()
@@ -136,22 +225,19 @@ void BookController::browseAndOpen()
void BookController::closeBook()
{
if (m_reader && m_appState && m_readingModel && !m_currentFilePath.isEmpty()) {
m_appState->saveBookPosition(m_currentFilePath,
m_readingModel->currentChapter(),
m_appState->lastScrollIndex(),
m_appState->lastScrollOffset());
m_appState->addOrUpdateLibraryBook(m_currentFilePath, m_bookTitle, m_bookAuthor,
m_readingModel->progress());
m_appState->addOrUpdateLibraryBook(m_currentFilePath, m_readingModel->progress());
}
if (m_imageProvider)
m_imageProvider->clear();
m_imageProvider = nullptr;
m_ownedProvider.reset();
if (m_readingModel)
m_readingModel->setReader(nullptr);
m_reader.reset();
m_bookTitle.clear();
m_bookAuthor.clear();
m_currentFilePath.clear();
if (m_readingModel)
m_readingModel->setReader(nullptr);
m_coverImageUrl.clear();
emit bookChanged();
}
@@ -164,13 +250,17 @@ void BookController::clearError()
emit errorMessageChanged();
}
void BookController::setImageProvider(EpubImageProvider *provider)
void BookController::setImageProviderRegistrar(
std::function<void(const QString &scheme, IImageProvider *)> fn)
{
m_imageProvider = provider;
m_providerRegistrar = std::move(fn);
}
void BookController::setContentWidth(int width)
{
m_contentWidth = width;
if (m_imageProvider)
m_imageProvider->setDisplayWidth(width);
if (m_readingModel)
m_readingModel->setContentWidth(width);
}
+25 -5
View File
@@ -1,15 +1,16 @@
#ifndef BOOKCONTROLLER_H
#define BOOKCONTROLLER_H
#include <QObject>
#include <QFuture>
#include <QString>
#include <QUrl>
#include <QList>
#include <functional>
#include <memory>
#include "EpubImageProvider.h"
#include "FormatReader.h"
#include "IFileDialogService.h"
#include "IImageLoader.h"
#include "IImageProvider.h"
class AppState;
class ReadingModel;
@@ -23,9 +24,12 @@ class BookController : public QObject {
Q_PROPERTY(bool hasBook READ hasBook NOTIFY bookChanged)
Q_PROPERTY(QList<TocEntry> toc READ toc NOTIFY bookChanged)
Q_PROPERTY(QString currentFilePath READ currentFilePath NOTIFY bookChanged)
Q_PROPERTY(QString coverImageUrl READ coverImageUrl NOTIFY bookChanged)
Q_PROPERTY(bool startupRestore READ startupRestore NOTIFY bookReady)
public:
explicit BookController(QObject *parent = nullptr);
~BookController();
QString bookTitle() const;
QString bookAuthor() const;
@@ -34,12 +38,19 @@ public:
bool hasBook() const;
QList<TocEntry> toc() const;
QString currentFilePath() const;
QString coverImageUrl() const;
bool startupRestore() const;
void setReadingModel(ReadingModel *model);
void setAppState(AppState *state);
void setFileDialogService(IFileDialogService *service);
void setImageProvider(EpubImageProvider *provider);
// Called each time a new image provider is created for a book.
// The callback must register the provider with the QML engine (which takes ownership).
void setImageProviderRegistrar(std::function<void(const QString &scheme, IImageProvider *)> fn);
// Called by QML once the window is fully laid out. Reads AppState to decide
// whether to open the last book or emit noSavedBook().
Q_INVOKABLE void uiReady();
Q_INVOKABLE void openBook(const QUrl &fileUrl);
Q_INVOKABLE void openBookFromPath(const QString &filePath);
Q_INVOKABLE void browseAndOpen();
@@ -53,18 +64,27 @@ signals:
void bookChanged();
void loadingChanged();
void errorMessageChanged();
void noSavedBook(); // emitted by uiReady() when there is no last file to open
private:
std::unique_ptr<FormatReader> m_reader;
ReadingModel *m_readingModel = nullptr;
AppState *m_appState = nullptr;
IFileDialogService *m_fileDialogService = nullptr;
EpubImageProvider *m_imageProvider = nullptr;
std::function<void(const QString &, IImageProvider *)> m_providerRegistrar;
// Non-owning when the QML engine owns the provider; owning otherwise (e.g., in tests).
std::unique_ptr<IImageProvider> m_ownedProvider;
IImageProvider *m_imageProvider = nullptr;
QString m_bookTitle;
QString m_bookAuthor;
QString m_currentFilePath;
QString m_coverImageUrl;
bool m_loading = false;
QString m_errorMessage;
bool m_startupRestore = false;
int m_contentWidth = 0;
int m_openGeneration = 0; // incremented per openBook call; callbacks check for staleness
QFuture<void> m_openFuture;
};
#endif // BOOKCONTROLLER_H
+91
View File
@@ -0,0 +1,91 @@
#include "ChunkMeasurer.h"
#include <QFont>
#include <QImage>
#include <QTextBlockFormat>
#include <QTextCursor>
#include <QTextDocument>
#include <QTextOption>
#include <QThread>
#include <QtConcurrent>
#include <QAtomicInt>
// Private: one instance per worker thread — owns its IImageLoader clone
class ImageLoadingDocument : public QTextDocument {
IImageLoader *m_loader = nullptr;
int m_maxWidth = 0;
public:
void setLoader(IImageLoader *loader, int maxWidth) {
m_loader = loader;
m_maxWidth = maxWidth;
}
protected:
QVariant loadResource(int type, const QUrl &url) override {
if (type == QTextDocument::ImageResource && m_loader) {
QImage img = m_loader->load(url, m_maxWidth);
if (!img.isNull()) return img;
}
return QTextDocument::loadResource(type, url);
}
};
ChunkMeasurer::ChunkMeasurer(std::unique_ptr<IImageLoader> imageLoader,
int fontSize, qreal lineSpacing)
: m_imageLoader(std::move(imageLoader))
, m_fontSize(fontSize)
, m_lineSpacing(lineSpacing)
{}
QVector<int> ChunkMeasurer::measure(const QStringList &chunks, qreal textWidth)
{
const int n = chunks.size();
if (n == 0) return {};
if (textWidth <= 0) textWidth = 1.0;
QVector<int> heights(n, 0);
QAtomicInt nextIdx(0);
const int threadCount = QThread::idealThreadCount();
// Capture by value what each worker needs (no shared mutable state)
auto worker = [&]() {
std::unique_ptr<IImageLoader> loader =
m_imageLoader ? m_imageLoader->clone() : nullptr;
ImageLoadingDocument doc;
doc.setLoader(loader.get(), qRound(textWidth));
doc.setDocumentMargin(0);
doc.setUndoRedoEnabled(false);
QTextOption textOption = doc.defaultTextOption();
textOption.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere);
doc.setDefaultTextOption(textOption);
QFont font;
font.setPixelSize(m_fontSize);
doc.setDefaultFont(font);
for (;;) {
const int i = nextIdx.fetchAndAddRelaxed(1);
if (i >= n) break;
doc.setHtml(chunks[i]);
doc.setTextWidth(textWidth);
QTextBlockFormat fmt;
fmt.setLineHeight(m_lineSpacing * 100.0, QTextBlockFormat::ProportionalHeight);
QTextCursor cursor(&doc);
cursor.select(QTextCursor::Document);
cursor.mergeBlockFormat(fmt);
heights[i] = qRound(doc.size().height());
}
};
QList<QFuture<void>> futures;
futures.reserve(threadCount);
for (int t = 0; t < threadCount; ++t)
futures.append(QtConcurrent::run(worker));
for (auto &f : futures)
f.waitForFinished();
return heights;
}
+16
View File
@@ -0,0 +1,16 @@
#ifndef CHUNKMEASURER_H
#define CHUNKMEASURER_H
#include "IChunkMeasurer.h"
#include "IImageLoader.h"
#include <memory>
class ChunkMeasurer : public IChunkMeasurer {
public:
explicit ChunkMeasurer(std::unique_ptr<IImageLoader> imageLoader = nullptr,
int fontSize = 16, qreal lineSpacing = 1.6);
QVector<int> measure(const QStringList &chunks, qreal textWidth) override;
private:
std::unique_ptr<IImageLoader> m_imageLoader;
int m_fontSize;
qreal m_lineSpacing;
};
#endif
+40 -1
View File
@@ -115,12 +115,51 @@ QImage EpubImageProvider::loadImageFromEpub(const QString &epubPath, const QStri
return image;
}
void EpubImageProvider::setEpubPath(const QString &filePath)
QImage EpubImageProvider::load(const QUrl &url, int maxWidth) const
{
if (url.scheme() != QLatin1String("image"))
return {};
QString zipPath = url.path();
if (zipPath.startsWith(QLatin1Char('/')))
zipPath = zipPath.mid(1);
if (zipPath.isEmpty())
return {};
QString epubPath;
{
QMutexLocker lock(&m_mutex);
epubPath = m_epubPath;
}
return loadImageFromEpub(epubPath, zipPath, maxWidth, {});
}
std::unique_ptr<IImageLoader> EpubImageProvider::clone() const
{
QString epubPath;
{
QMutexLocker lock(&m_mutex);
epubPath = m_epubPath;
}
auto c = std::make_unique<EpubImageProvider>();
c->setFilePath(epubPath);
return c;
}
void EpubImageProvider::setFilePath(const QString &filePath)
{
QMutexLocker lock(&m_mutex);
m_epubPath = filePath;
}
QString EpubImageProvider::coverImageUrl(const QString &coverPath) const
{
return QStringLiteral("image://epub/") + coverPath;
}
QString EpubImageProvider::scheme() const
{
return QStringLiteral("epub");
}
void EpubImageProvider::setDisplayWidth(int width)
{
QMutexLocker lock(&m_mutex);
+13 -8
View File
@@ -1,12 +1,12 @@
#pragma once
#include <QAtomicInt>
#include <QImage>
#include <QMutex>
#include <QQuickAsyncImageProvider>
#include <QRunnable>
#include <QString>
#include "IImageLoader.h"
#include "IImageProvider.h"
class EpubImageResponse : public QQuickImageResponse, public QRunnable {
// NO Q_OBJECT — already inherited from QQuickImageResponse
public:
@@ -26,20 +26,25 @@ private:
QImage m_image;
};
class EpubImageProvider : public QQuickAsyncImageProvider {
class EpubImageProvider : public IImageProvider, public IImageLoader {
public:
QQuickImageResponse *requestImageResponse(const QString &id,
const QSize &requestedSize) override;
void setEpubPath(const QString &filePath);
void setDisplayWidth(int width);
void clear();
void setFilePath(const QString &filePath) override;
void setDisplayWidth(int width) override;
void clear() override;
QString coverImageUrl(const QString &coverPath) const override;
QString scheme() const override;
QImage load(const QUrl &url, int maxWidth) const override;
std::unique_ptr<IImageLoader> clone() const override;
static QImage loadImageFromEpub(const QString &epubPath, const QString &id,
int displayWidth, const QSize &requestedSize);
private:
QMutex m_mutex;
mutable QMutex m_mutex;
QString m_epubPath;
int m_displayWidth = 0;
};
+4 -1
View File
@@ -2,7 +2,6 @@
#define FORMATREADER_H
#include <QString>
#include <QStringList>
#include <QList>
struct TocEntry {
@@ -22,12 +21,16 @@ public:
virtual ~FormatReader() = default;
virtual bool open(const QString &filePath) = 0;
virtual bool loadMetadata(const QString &filePath) = 0;
virtual QString lastError() = 0;
virtual int chapterCount() = 0;
virtual Chapter loadChapter(int index) = 0;
virtual QList<TocEntry> tableOfContents() = 0;
virtual QString filePath() = 0;
virtual QString title() = 0;
virtual QString author() = 0;
virtual QString coverImagePath() = 0;
};
#endif // FORMATREADER_H
+2 -5
View File
@@ -1,14 +1,11 @@
#ifndef ICHUNKMEASURER_H
#define ICHUNKMEASURER_H
#include <QStringList>
#include <QVector>
#include <QtGlobal>
class IChunkMeasurer {
public:
virtual ~IChunkMeasurer() = default;
virtual QVector<qreal> measure(const QStringList &chunks, qreal textWidth) const = 0;
virtual QVector<int> measure(const QStringList &chunks, qreal textWidth) = 0;
};
#endif // ICHUNKMEASURER_H
#endif
+12
View File
@@ -0,0 +1,12 @@
#ifndef IIMAGELLOADER_H
#define IIMAGELLOADER_H
#include <QImage>
#include <QUrl>
#include <memory>
class IImageLoader {
public:
virtual ~IImageLoader() = default;
virtual QImage load(const QUrl &url, int maxWidth) const = 0;
virtual std::unique_ptr<IImageLoader> clone() const = 0;
};
#endif
+15
View File
@@ -0,0 +1,15 @@
#pragma once
#include <QQuickAsyncImageProvider>
#include <QString>
class IImageProvider : public QQuickAsyncImageProvider {
public:
virtual ~IImageProvider() = default;
virtual void setFilePath(const QString &filePath) = 0;
virtual void setDisplayWidth(int width) = 0;
virtual void clear() = 0;
// Returns the full QML image URL for a given internal path (e.g., "image://epub/OEBPS/cover.jpg")
virtual QString coverImageUrl(const QString &coverPath) const = 0;
// The scheme this provider is registered under with the QML engine (e.g., "epub")
virtual QString scheme() const = 0;
};
+14
View File
@@ -0,0 +1,14 @@
#include "ImageLoaderFactory.h"
#include "EpubImageProvider.h"
#include <QFileInfo>
std::unique_ptr<IImageLoader> ImageLoaderFactory::create(const QString &filePath)
{
const QString ext = QFileInfo(filePath).suffix().toLower();
if (ext == QLatin1String("epub")) {
auto provider = std::make_unique<EpubImageProvider>();
provider->setFilePath(filePath);
return provider;
}
return nullptr;
}
+11
View File
@@ -0,0 +1,11 @@
#pragma once
#include <memory>
#include <QString>
class IImageLoader;
class ImageLoaderFactory {
public:
// Returns a new loader for the given file format, or nullptr for formats without images.
static std::unique_ptr<IImageLoader> create(const QString &filePath);
};
+11
View File
@@ -0,0 +1,11 @@
#include "ImageProviderFactory.h"
#include "EpubImageProvider.h"
#include <QFileInfo>
IImageProvider *ImageProviderFactory::create(const QString &filePath)
{
const QString ext = QFileInfo(filePath).suffix().toLower();
if (ext == QLatin1String("epub"))
return new EpubImageProvider();
return nullptr;
}
+11
View File
@@ -0,0 +1,11 @@
#pragma once
#include <QString>
class IImageProvider;
class ImageProviderFactory {
public:
// Returns a new provider for the given file format, or nullptr for formats without images.
// Caller is responsible for the returned pointer's lifetime.
static IImageProvider *create(const QString &filePath);
};
+119
View File
@@ -0,0 +1,119 @@
#include "LibraryBookModel.h"
#include "FormatReader.h"
#include "ReaderFactory.h"
#include <QtConcurrent/QtConcurrent>
LibraryBookModel::LibraryBookModel(QObject *parent)
: QObject(parent)
{
connect(this, &LibraryBookModel::metadataLoaded, this, &LibraryBookModel::onMetadataLoaded);
}
LibraryBookModel::LibraryBookModel(const QString &filePath, double progress, const QString &lastOpened, QObject *parent)
: QObject(parent), m_filePath(filePath), m_progress(progress), m_lastOpened(lastOpened)
{
connect(this, &LibraryBookModel::metadataLoaded, this, &LibraryBookModel::onMetadataLoaded);
}
LibraryBookModel::~LibraryBookModel()
{
if (m_metadataFuture.isRunning())
m_metadataFuture.waitForFinished();
}
QString LibraryBookModel::filePath() const
{
return m_filePath;
}
double LibraryBookModel::progress() const
{
return m_progress;
}
void LibraryBookModel::setProgress(double progress)
{
if (qFuzzyCompare(m_progress, progress))
return;
m_progress = progress;
emit progressChanged();
}
QString LibraryBookModel::lastOpened() const
{
return m_lastOpened;
}
void LibraryBookModel::setLastOpened(const QString &lastOpened)
{
if (m_lastOpened == lastOpened)
return;
m_lastOpened = lastOpened;
emit lastOpenedChanged();
}
QString LibraryBookModel::title() const
{
return m_title;
}
QString LibraryBookModel::author() const
{
return m_author;
}
QString LibraryBookModel::coverImageUrl() const
{
return m_coverImageUrl;
}
void LibraryBookModel::loadMetadata()
{
if (m_metadataLoaded || m_filePath.isEmpty() || m_metadataFuture.isRunning())
return;
QPointer<LibraryBookModel> self = this;
QString filePath = m_filePath;
m_metadataFuture = QtConcurrent::run([self, filePath]() {
auto reader = ReaderFactory::create(filePath);
QString title;
QString author;
bool success = false;
if (reader && reader->loadMetadata(filePath)) {
title = reader->title();
author = reader->author();
success = true;
}
QMetaObject::invokeMethod(self.data(), [self, title, author, success]() {
if (!self || !success)
return;
self->m_title = title;
self->m_author = author;
self->m_metadataLoaded = true;
emit self->metadataLoaded();
}, Qt::QueuedConnection);
});
}
void LibraryBookModel::onMetadataLoaded()
{
// This slot can be used for any post-processing after metadata is loaded
}
void LibraryBookModel::loadCoverImage(const QString &epubBasePath)
{
if (!m_coverImageUrl.isEmpty() || m_filePath.isEmpty())
return;
auto reader = ReaderFactory::create(m_filePath);
if (reader && reader->loadMetadata(m_filePath)) {
QString coverPath = reader->coverImagePath();
if (!coverPath.isEmpty()) {
m_coverImageUrl = QStringLiteral("image://epub/") + coverPath;
emit coverImageLoaded();
}
}
}
+59
View File
@@ -0,0 +1,59 @@
#ifndef LIBRARYBOOKMODEL_H
#define LIBRARYBOOKMODEL_H
#include <QString>
#include <QObject>
#include <QPointer>
#include <QFuture>
class FormatReader;
class LibraryBookModel : public QObject {
Q_OBJECT
Q_PROPERTY(QString filePath READ filePath CONSTANT)
Q_PROPERTY(double progress READ progress WRITE setProgress NOTIFY progressChanged)
Q_PROPERTY(QString lastOpened READ lastOpened WRITE setLastOpened NOTIFY lastOpenedChanged)
Q_PROPERTY(QString title READ title NOTIFY metadataLoaded)
Q_PROPERTY(QString author READ author NOTIFY metadataLoaded)
Q_PROPERTY(QString coverImageUrl READ coverImageUrl NOTIFY coverImageLoaded)
public:
explicit LibraryBookModel(QObject *parent = nullptr);
explicit LibraryBookModel(const QString &filePath, double progress = 0.0, const QString &lastOpened = QString(), QObject *parent = nullptr);
~LibraryBookModel() override;
QString filePath() const;
double progress() const;
void setProgress(double progress);
QString lastOpened() const;
void setLastOpened(const QString &lastOpened);
QString title() const;
QString author() const;
QString coverImageUrl() const;
void loadMetadata();
void loadCoverImage(const QString &epubBasePath);
public slots:
void onMetadataLoaded();
signals:
void progressChanged();
void lastOpenedChanged();
void metadataLoaded();
void coverImageLoaded();
private:
QString m_filePath;
double m_progress = 0.0;
QString m_lastOpened;
QString m_title;
QString m_author;
QString m_coverImageUrl;
bool m_metadataLoaded = false;
QFuture<void> m_metadataFuture;
};
#endif // LIBRARYBOOKMODEL_H
+177
View File
@@ -0,0 +1,177 @@
#include "LibraryModel.h"
#include "LibraryBookModel.h"
LibraryModel::LibraryModel(QObject *parent)
: QAbstractListModel(parent)
{
// Initialize role names
m_roleNames[FilePathRole] = "filePath";
m_roleNames[TitleRole] = "title";
m_roleNames[AuthorRole] = "author";
m_roleNames[ProgressRole] = "progress";
m_roleNames[LastOpenedRole] = "lastOpened";
m_roleNames[CoverImageUrlRole] = "coverImageUrl";
}
LibraryModel::~LibraryModel()
{
clear();
}
int LibraryModel::rowCount(const QModelIndex &parent) const
{
if (parent.isValid())
return 0;
return m_books.count();
}
QVariant LibraryModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid() || index.row() < 0 || index.row() >= m_books.count())
return QVariant();
LibraryBookModel* book = m_books.at(index.row());
if (!book)
return QVariant();
switch (role) {
case FilePathRole:
return book->filePath();
case TitleRole:
return book->title();
case AuthorRole:
return book->author();
case ProgressRole:
return book->progress();
case LastOpenedRole:
return book->lastOpened();
case CoverImageUrlRole:
return book->coverImageUrl();
default:
return QVariant();
}
}
bool LibraryModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
if (!index.isValid() || index.row() < 0 || index.row() >= m_books.count())
return false;
LibraryBookModel* book = m_books.at(index.row());
switch (role) {
case ProgressRole:
book->setProgress(value.toDouble());
emit dataChanged(index, index, {ProgressRole});
return true;
case LastOpenedRole:
book->setLastOpened(value.toString());
emit dataChanged(index, index, {LastOpenedRole});
return true;
default:
return false;
}
}
QHash<int, QByteArray> LibraryModel::roleNames() const
{
return m_roleNames;
}
void LibraryModel::addOrUpdateBook(const QString &filePath, double progress, const QString &lastOpened)
{
// Check if book already exists
for (int i = 0; i < m_books.size(); i++) {
if (m_books[i]->filePath() == filePath) {
LibraryBookModel* existingBook = m_books[i];
existingBook->setProgress(progress);
existingBook->setLastOpened(lastOpened);
if (i != 0) {
beginMoveRows(QModelIndex(), i, i, QModelIndex(), 0);
m_books.move(i, 0);
endMoveRows();
}
return;
}
}
// New book — LibraryModel takes ownership via parent
auto* book = new LibraryBookModel(filePath, progress, lastOpened, this);
connect(book, &LibraryBookModel::metadataLoaded, this, &LibraryModel::onBookMetadataLoaded);
beginInsertRows(QModelIndex(), 0, 0);
m_books.prepend(book);
endInsertRows();
emit countChanged();
book->loadMetadata();
}
void LibraryModel::removeBook(const QString &filePath)
{
for (int i = 0; i < m_books.size(); i++) {
if (m_books[i]->filePath() == filePath) {
LibraryBookModel* book = m_books[i];
// Disconnect signals
disconnect(book, &LibraryBookModel::metadataLoaded, this, &LibraryModel::onBookMetadataLoaded);
beginRemoveRows(QModelIndex(), i, i);
m_books.removeAt(i);
endRemoveRows();
book->deleteLater();
emit countChanged();
return;
}
}
}
LibraryBookModel* LibraryModel::findBook(const QString &filePath) const
{
for (LibraryBookModel* book : m_books) {
if (book->filePath() == filePath) {
return book;
}
}
return nullptr;
}
void LibraryModel::clear()
{
if (m_books.isEmpty())
return;
beginRemoveRows(QModelIndex(), 0, m_books.size() - 1);
// Disconnect and delete all books
for (LibraryBookModel* book : m_books) {
disconnect(book, &LibraryBookModel::metadataLoaded, this, &LibraryModel::onBookMetadataLoaded);
book->deleteLater();
}
m_books.clear();
endRemoveRows();
emit countChanged();
}
QList<LibraryBookModel*> LibraryModel::books() const
{
return m_books;
}
void LibraryModel::onBookMetadataLoaded()
{
LibraryBookModel* book = qobject_cast<LibraryBookModel*>(sender());
if (!book)
return;
int row = m_books.indexOf(book);
if (row >= 0) {
QModelIndex index = this->index(row);
// Update all metadata-related roles when metadata is loaded
emit dataChanged(index, index, {TitleRole, AuthorRole, CoverImageUrlRole});
}
}
+57
View File
@@ -0,0 +1,57 @@
#ifndef LIBRARYMODEL_H
#define LIBRARYMODEL_H
#include <QAbstractListModel>
#include <QList>
#include <QHash>
class LibraryBookModel;
class LibraryModel : public QAbstractListModel
{
Q_OBJECT
Q_PROPERTY(int count READ rowCount NOTIFY countChanged)
public:
enum LibraryRoles {
FilePathRole = Qt::UserRole + 1,
TitleRole,
AuthorRole,
ProgressRole,
LastOpenedRole,
CoverImageUrlRole
};
Q_ENUM(LibraryRoles)
explicit LibraryModel(QObject *parent = nullptr);
~LibraryModel() override;
// QAbstractItemModel interface
int rowCount(const QModelIndex &parent = QModelIndex()) const override;
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::DisplayRole) override;
// Add QHash<int, QByteArray> for role names
QHash<int, QByteArray> roleNames() const override;
// Methods to manage books
Q_INVOKABLE void addOrUpdateBook(const QString &filePath, double progress, const QString &lastOpened);
Q_INVOKABLE void removeBook(const QString &filePath);
Q_INVOKABLE LibraryBookModel* findBook(const QString &filePath) const;
Q_INVOKABLE void clear();
// Access to books for saving/loading
QList<LibraryBookModel*> books() const;
signals:
void countChanged();
private slots:
void onBookMetadataLoaded();
private:
QList<LibraryBookModel*> m_books;
QHash<int, QByteArray> m_roleNames;
};
#endif // LIBRARYMODEL_H
-1
View File
@@ -3,7 +3,6 @@
#include "PortalFileDialogService.h"
#include <QDBusConnection>
#include <QDBusMessage>
#include <QDBusArgument>
#include <QDBusMetaType>
#include <QRandomGenerator>
#include <QUrl>
-41
View File
@@ -1,41 +0,0 @@
#include "QDocumentChunkMeasurer.h"
#include <QFont>
#include <QTextBlockFormat>
#include <QTextCursor>
#include <QTextDocument>
QDocumentChunkMeasurer::QDocumentChunkMeasurer(int pixelSize, qreal lineHeightPercent)
: m_pixelSize(pixelSize)
, m_lineHeightPercent(lineHeightPercent)
{
}
QVector<qreal> QDocumentChunkMeasurer::measure(const QStringList &chunks, qreal textWidth) const
{
if (textWidth <= 0)
textWidth = 1;
QFont font;
font.setPixelSize(m_pixelSize);
QTextDocument doc;
doc.setDefaultFont(font);
QVector<qreal> heights;
heights.reserve(chunks.size());
for (const QString &chunk : chunks) {
doc.setHtml(chunk);
doc.setTextWidth(textWidth);
QTextBlockFormat fmt;
fmt.setLineHeight(m_lineHeightPercent, QTextBlockFormat::ProportionalHeight);
QTextCursor cursor(&doc);
cursor.select(QTextCursor::Document);
cursor.mergeBlockFormat(fmt);
heights.append(doc.size().height());
}
return heights;
}
-16
View File
@@ -1,16 +0,0 @@
#ifndef QDOCUMENTCHUNKMEASURER_H
#define QDOCUMENTCHUNKMEASURER_H
#include "IChunkMeasurer.h"
class QDocumentChunkMeasurer : public IChunkMeasurer {
public:
explicit QDocumentChunkMeasurer(int pixelSize = 16, qreal lineHeightPercent = 160.0);
QVector<qreal> measure(const QStringList &chunks, qreal textWidth) const override;
private:
int m_pixelSize;
qreal m_lineHeightPercent;
};
#endif // QDOCUMENTCHUNKMEASURER_H
+147 -82
View File
@@ -1,34 +1,47 @@
#include "ReadingModel.h"
#include "FormatReader.h"
#include "IChunkMeasurer.h"
#include "IImageLoader.h"
#include "ChunkMeasurer.h"
#include <algorithm>
#include <cmath>
#include <QtConcurrent>
ReadingModel::ReadingModel(QObject *parent)
: QAbstractListModel(parent)
#include "AppState.h"
ReadingModel::ReadingModel(QObject *parent) : QAbstractListModel(parent) {}
ReadingModel::~ReadingModel()
{
if (m_measureFuture.isRunning()) {
m_measureFuture.cancel();
m_measureFuture.waitForFinished();
}
}
int ReadingModel::rowCount(const QModelIndex &parent) const
{
if (parent.isValid())
return 0;
int ReadingModel::rowCount(const QModelIndex &parent) const {
if (parent.isValid()) return 0;
return m_chunks.size();
}
QVariant ReadingModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid() || index.row() < 0 || index.row() >= m_chunks.size())
return {};
if (role == ContentRole)
return m_chunks.at(index.row());
QVariant ReadingModel::data(const QModelIndex &index, int role) const {
if (!index.isValid() || index.row() < 0 || index.row() >= (int)m_chunks.size())
return {};
const auto &c = m_chunks.at(index.row());
switch (role) {
case ContentRole: return c.html;
case PixelHeightRole: return c.pixelHeight;
case ChapterRole: return c.chapterIndex;
default: return {};
}
}
QHash<int, QByteArray> ReadingModel::roleNames() const
{
return {{ContentRole, "content"}};
QHash<int, QByteArray> ReadingModel::roleNames() const {
return {
{ContentRole, "content"},
{PixelHeightRole, "pixelHeight"},
{ChapterRole, "chapter"},
};
}
QString ReadingModel::chapterTitle() const
@@ -38,52 +51,27 @@ QString ReadingModel::chapterTitle() const
return m_chapterTitles.at(m_currentChapter);
}
int ReadingModel::currentChapter() const
{
return m_currentChapter;
}
int ReadingModel::totalChapters() const
{
return m_totalChapters;
}
bool ReadingModel::hasChapters() const
{
return m_totalChapters > 1;
}
int ReadingModel::currentChapter() const { return m_currentChapter; }
int ReadingModel::totalChapters() const { return m_totalChapters; }
bool ReadingModel::hasChapters() const { return m_totalChapters > 1; }
bool ReadingModel::measuring() const { return m_measuring; }
qreal ReadingModel::totalPixelHeight() const { return m_totalPixelHeight; }
double ReadingModel::progress() const
{
if (m_totalBookBytes == 0)
return 0.0;
return qBound(0.0,
static_cast<double>(m_chunkByteOffsets.value(m_topChunkIndex)) / m_totalBookBytes,
1.0);
return qBound(0, static_cast<int>(m_yOffset * 100), 100);
}
int ReadingModel::currentPage() const
int ReadingModel::currentPage() const { return m_currentPage; }
int ReadingModel::totalPages() const { return m_totalPages; }
void ReadingModel::setScrollInfo(const int topChunkIndex, const qreal proportion)
{
return m_currentPage;
}
m_yOffset = proportion;
int ReadingModel::totalPages() const
{
return m_totalPages;
}
void ReadingModel::setScrollInfo(int topChunkIndex, qreal /*offsetInChunk*/, bool atYEnd)
{
if (topChunkIndex < 0 || topChunkIndex >= m_chunks.size())
return;
m_topChunkIndex = topChunkIndex;
m_atYEnd = atYEnd;
// Derive current chapter from global chunk index
auto it = std::upper_bound(m_chapterStartIndices.begin(), m_chapterStartIndices.end(), topChunkIndex);
int chapter = std::max(0, static_cast<int>(std::distance(m_chapterStartIndices.begin(), it)) - 1);
if (chapter != m_currentChapter) {
// Derive current chapter
const auto it = std::upper_bound(m_chapterStartIndices.begin(), m_chapterStartIndices.end(), topChunkIndex);
if (const int chapter = std::max(0, static_cast<int>(std::distance(m_chapterStartIndices.begin(), it)) - 1); chapter != m_currentChapter) {
m_currentChapter = chapter;
emit chapterChanged();
}
@@ -91,26 +79,87 @@ void ReadingModel::setScrollInfo(int topChunkIndex, qreal /*offsetInChunk*/, boo
recalculateCurrentPage();
}
void ReadingModel::computeChunkBytes()
void ReadingModel::measure(const bool isNew)
{
m_chunkBytes.resize(m_chunks.size());
m_chunkByteOffsets.resize(m_chunks.size());
qsizetype offset = 0;
for (int i = 0; i < m_chunks.size(); ++i) {
m_chunkByteOffsets[i] = offset;
qsizetype sz = m_chunks.at(i).toUtf8().size();
m_chunkBytes[i] = sz;
offset += sz;
if (!m_reader) return;
m_totalPixelHeight = 0;
QStringList htmls;
htmls.reserve(m_chunks.size());
for (const auto &c : m_chunks)
htmls.append(c.html);
runMeasurement(htmls, isNew);
}
void ReadingModel::runMeasurement(const QStringList &htmls, const bool isNew)
{
if (m_measureFuture.isRunning())
m_measureFuture.cancel();
m_measuring = true;
emit measuringChanged();
const int width = m_contentWidth > 0 ? m_contentWidth : 800;
const int fontSize = m_fontSize;
const qreal lineSpacing = m_lineSpacing;
std::unique_ptr<IImageLoader> loaderClone = m_imageLoader ? m_imageLoader->clone() : nullptr;
auto measurer = new ChunkMeasurer(std::move(loaderClone), fontSize, lineSpacing);
m_measureFuture = QtConcurrent::run(
[this, htmls, measurer, width, isNew]() {
QVector<int> heights = measurer->measure(htmls, width);
QMetaObject::invokeMethod(this, [this, heights, isNew] {
for (int i = 0; i < qMin(heights.size(), static_cast<int>(m_chunks.size())); ++i) {
m_chunks[i].pixelHeight = heights[i];
m_totalPixelHeight += heights[i];
}
m_totalBookBytes = offset;
qInfo("Measured %lld chunks, total height: %f", heights.size(), m_totalPixelHeight);
m_measuring = false;
emit measuringChanged();
emit totalPixelHeightChanged();
emit dataChanged(createIndex(0, 0),
createIndex(m_chunks.size() - 1, 0),
{PixelHeightRole});
if (isNew) {
QVariantMap map = AppState::loadBookPosition(m_reader->filePath());
int savedChunk = map.value(QStringLiteral("chunkIndex"), 0).toInt();
qreal savedIntra = map.value(QStringLiteral("intraChunkOffset"), 0).toInt();
restoreReady(savedChunk, savedIntra);
}
}, Qt::QueuedConnection);
});
}
void ReadingModel::setContentWidth(int width)
{
if (width == m_contentWidth) return;
m_contentWidth = width;
if (m_reader) measure(false);
}
void ReadingModel::setFontParams(int fontSize, qreal lineSpacing)
{
if (fontSize == m_fontSize && qFuzzyCompare(lineSpacing, m_lineSpacing)) return;
m_fontSize = fontSize;
m_lineSpacing = lineSpacing;
if (m_reader) measure(false);
}
void ReadingModel::setImageLoader(std::unique_ptr<IImageLoader> loader)
{
m_imageLoader = std::move(loader);
}
void ReadingModel::recalculateCurrentPage()
{
int page = 0;
if (!m_chunks.isEmpty()) {
page = m_atYEnd ? m_totalPages : m_topChunkIndex + 1;
page = std::max(1, std::min(page, m_totalPages));
page = qBound(0.0, m_yOffset / m_totalPixelHeight, 1.0) * m_chunks.size() * page_ratio;
}
if (m_currentPage == page)
return;
@@ -121,37 +170,46 @@ void ReadingModel::recalculateCurrentPage()
void ReadingModel::loadAllChapters()
{
beginResetModel();
m_chunks.clear();
m_chapterStartIndices.clear();
m_chapterTitles.clear();
m_chunkBytes.clear();
m_chunkByteOffsets.clear();
m_totalBookBytes = 0;
m_topChunkIndex = 0;
m_atYEnd = false;
m_totalPixelHeight = 0.0;
emit totalPixelHeightChanged();
m_currentChapter = 0;
if (m_currentPage != 0) { m_currentPage = 0; emit currentPageChanged(); }
if (m_totalPages != 0) { m_totalPages = 0; emit totalPagesChanged(); }
if (m_reader) {
if (!m_coverImageUrl.isEmpty()) {
QString coverHtml = QStringLiteral("<div class=\"cover-image\" style=\"text-align: center; margin: 2em 0;\">")
+ QStringLiteral("<img src=\"") + m_coverImageUrl
+ QStringLiteral("\" style=\"max-width: 100%; max-height: 80vh;\" /></div>");
m_chunks.push_back({coverHtml, 0, -1, -1}); // chunkInChapter=-1 = cover sentinel
m_chapterStartIndices.append(1); // chapter 0 starts after cover
} else {
m_chapterStartIndices.append(0);
}
for (int i = 0; i < m_totalChapters; ++i) {
auto chapter = m_reader->loadChapter(i);
if (i > 0)
m_chapterStartIndices.append(m_chunks.size());
m_chapterTitles.append(chapter.title);
m_chunks.append(chapter.contentChunks);
int j = 0;
for (const auto &html : chapter.contentChunks)
m_chunks.push_back({html, i, j++, -1});
}
}
endResetModel();
computeChunkBytes();
int pages = m_chunks.size();
if (m_totalPages != pages) { m_totalPages = pages; emit totalPagesChanged(); }
int page = m_chunks.isEmpty() ? 0 : 1;
if (m_currentPage != page) { m_currentPage = page; emit currentPageChanged(); }
if (const int pages = m_chunks.size() * page_ratio; m_totalPages != pages) {
m_totalPages = pages;
emit totalPagesChanged();
}
if (const int page = m_chunks.isEmpty() ? 0 : 1; m_currentPage != page) {
m_currentPage = page;
emit currentPageChanged();
}
}
void ReadingModel::setReader(FormatReader *reader)
@@ -166,6 +224,13 @@ void ReadingModel::setReader(FormatReader *reader)
emit chapterChanged();
}
void ReadingModel::setCoverImageUrl(const QString &coverImageUrl)
{
if (m_coverImageUrl != coverImageUrl) {
m_coverImageUrl = coverImageUrl;
}
}
void ReadingModel::nextChapter()
{
if (!m_reader || m_currentChapter >= m_totalChapters - 1)
+51 -16
View File
@@ -2,12 +2,20 @@
#define READINGMODEL_H
#include <QAbstractListModel>
#include <QFuture>
#include <QString>
#include <QStringList>
#include <QVector>
#include <memory>
#include "IImageLoader.h"
class FormatReader;
struct ContentChunk {
QString html; // empty when unloaded (lazy streaming)
int chapterIndex = 0; // which chapter owns this chunk
int chunkInChapter = 0; // 0-based index within chapter (-1 for cover)
int pixelHeight = -1; // -1 = not yet measured
};
class ReadingModel : public QAbstractListModel {
Q_OBJECT
Q_PROPERTY(QString chapterTitle READ chapterTitle NOTIFY chapterChanged)
@@ -17,17 +25,21 @@ class ReadingModel : public QAbstractListModel {
Q_PROPERTY(int currentPage READ currentPage NOTIFY currentPageChanged)
Q_PROPERTY(int totalPages READ totalPages NOTIFY totalPagesChanged)
Q_PROPERTY(bool hasChapters READ hasChapters NOTIFY totalChaptersChanged)
Q_PROPERTY(bool measuring READ measuring NOTIFY measuringChanged)
Q_PROPERTY(qreal totalPixelHeight READ totalPixelHeight NOTIFY totalPixelHeightChanged)
public:
enum Roles {
ContentRole = Qt::UserRole + 1
ContentRole = Qt::UserRole + 1,
PixelHeightRole = Qt::UserRole + 2,
ChapterRole = Qt::UserRole + 3,
};
explicit ReadingModel(QObject *parent = nullptr);
~ReadingModel() override;
// QAbstractListModel overrides
int rowCount(const QModelIndex &parent = QModelIndex()) const override;
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
int rowCount(const QModelIndex &parent) const override;
QVariant data(const QModelIndex &index, int role) const override;
QHash<int, QByteArray> roleNames() const override;
QString chapterTitle() const;
@@ -37,42 +49,65 @@ public:
int currentPage() const;
int totalPages() const;
bool hasChapters() const;
bool measuring() const;
qreal totalPixelHeight() const;
void setReader(FormatReader *reader);
void setCoverImageUrl(const QString &coverImageUrl);
// Called from QML on every scroll (real-time)
Q_INVOKABLE void setScrollInfo(int topChunkIndex, qreal offsetInChunk, bool atYEnd = false);
Q_INVOKABLE void setScrollInfo(int topChunkIndex, qreal proportion);
Q_INVOKABLE void nextChapter();
Q_INVOKABLE void previousChapter();
Q_INVOKABLE void goToChapter(int index);
// Measurement
Q_INVOKABLE void measure(bool isNew);
// Preferences & state
void setContentWidth(int width);
Q_INVOKABLE void setFontParams(int fontSize, qreal lineSpacing);
void setImageLoader(std::unique_ptr<IImageLoader> loader);
signals:
void chapterChanged();
void totalChaptersChanged();
void measuringChanged();
void totalPixelHeightChanged();
void currentPageChanged();
void totalPagesChanged();
void scrollToChunkRequested(int chunkIndex);
void restoreReady(int chunkIndex, int intraChunkOffset);
private:
static constexpr qreal page_ratio = 1.5;
void loadAllChapters();
void computeChunkBytes();
void recalculateCurrentPage();
void runMeasurement(const QStringList &htmls, bool isNew);
FormatReader *m_reader = nullptr;
QString m_coverImageUrl;
int m_currentChapter = 0;
int m_totalChapters = 0;
int m_currentPage = 0;
int m_totalPages = 0;
int m_topChunkIndex = 0;
bool m_atYEnd = false;
bool m_measuring = false;
QStringList m_chunks;
QVector<int> m_chapterStartIndices; // m_chapterStartIndices[i] = first global chunk index of chapter i
QVector<QString> m_chapterTitles; // title of each chapter
QVector<ContentChunk> m_chunks;
QVector<int> m_chapterStartIndices;
QVector<QString> m_chapterTitles;
QVector<qsizetype> m_chunkBytes; // UTF-8 byte size of each chunk (all chapters)
QVector<qsizetype> m_chunkByteOffsets; // prefix sums: offset[i] = sum of bytes[0..i-1]
qsizetype m_totalBookBytes = 0;
qreal m_totalPixelHeight = 0.0;
qreal m_yOffset = 0.0;
int m_contentWidth = 0;
int m_fontSize = 0;
qreal m_lineSpacing = 0;
std::unique_ptr<IImageLoader> m_imageLoader;
QFuture<void> m_measureFuture;
};
#endif // READINGMODEL_H
+82 -3
View File
@@ -31,6 +31,7 @@ bool EpubReader::open(const QString &filePath)
m_author.clear();
m_error.clear();
m_opfDir.clear();
m_coverImagePath.clear();
m_spineHrefs.clear();
m_spineRawContent.clear();
m_toc.clear();
@@ -40,7 +41,6 @@ bool EpubReader::open(const QString &filePath)
m_error = QStringLiteral("Cannot open as ZIP archive: ") + filePath;
return false;
}
// Ensure the handle is closed on all exit paths
auto guard = [&](void *) { unzClose(zf); };
std::unique_ptr<void, decltype(guard)> closeGuard(zf, guard);
@@ -85,7 +85,7 @@ bool EpubReader::open(const QString &filePath)
if (!ncxData.isEmpty())
parseNcx(ncxData);
}
m_filePath = filePath;
return true;
}
@@ -116,6 +116,7 @@ bool EpubReader::parseOpf(const QByteArray &data, QString &ncxHref)
QXmlStreamReader xml(data);
QHash<QString, QString> manifest; // id -> relative href
QString ncxId;
QString coverId; // ID of the cover image item
static const QLatin1String kDcNs("http://purl.org/dc/elements/1.1/");
@@ -133,11 +134,25 @@ bool EpubReader::parseOpf(const QByteArray &data, QString &ncxHref)
} else if (name == QLatin1String("creator") && ns == kDcNs) {
if (m_author.isEmpty())
m_author = xml.readElementText().trimmed();
} else if (name == QLatin1String("meta")) {
// Check for cover image metadata
const QString metaName = xml.attributes().value(QLatin1String("name")).toString();
const QString metaContent = xml.attributes().value(QLatin1String("content")).toString();
if (metaName == QLatin1String("cover") && !metaContent.isEmpty()) {
coverId = metaContent;
}
} else if (name == QLatin1String("item")) {
const QString id = xml.attributes().value(QLatin1String("id")).toString();
const QString href = xml.attributes().value(QLatin1String("href")).toString();
const QString properties = xml.attributes().value(QLatin1String("properties")).toString();
if (!id.isEmpty() && !href.isEmpty())
manifest.insert(id, href);
// Check if this item is the cover image
if (properties.contains(QLatin1String("cover-image"))) {
coverId = id;
}
} else if (name == QLatin1String("spine")) {
ncxId = xml.attributes().value(QLatin1String("toc")).toString();
} else if (name == QLatin1String("itemref")) {
@@ -147,6 +162,11 @@ bool EpubReader::parseOpf(const QByteArray &data, QString &ncxHref)
}
}
// Resolve cover image path if we found a cover ID
if (!coverId.isEmpty() && manifest.contains(coverId)) {
m_coverImagePath = m_opfDir + manifest.value(coverId);
}
if (!ncxId.isEmpty() && manifest.contains(ncxId))
ncxHref = m_opfDir + manifest.value(ncxId);
@@ -256,7 +276,8 @@ QStringList EpubReader::chunkXhtml(const QByteArray &data, const QString &xhtmlH
continue;
src = QUrl::fromPercentEncoding(src.toUtf8());
const QString resolved = QDir::cleanPath(xhtmlDir + src);
img.setAttribute(QStringLiteral("src"), QStringLiteral("image://epub/") + resolved);
img.setAttribute(QStringLiteral("src"),
QStringLiteral("image://epub/") + resolved);
}
// Find <body> element (may have namespace prefix in some EPUBs)
@@ -304,13 +325,71 @@ QStringList EpubReader::chunkXhtml(const QByteArray &data, const QString &xhtmlH
// FormatReader interface
// ---------------------------------------------------------------------------
bool EpubReader::loadMetadata(const QString &filePath)
{
// Reset state
m_title.clear();
m_author.clear();
m_error.clear();
m_opfDir.clear();
m_coverImagePath.clear();
m_spineHrefs.clear();
unzFile zf = unzOpen(filePath.toUtf8().constData());
if (!zf) {
m_error = QStringLiteral("Cannot open as ZIP archive: ") + filePath;
return false;
}
// Ensure the handle is closed on all exit paths
auto guard = [&](void *) { unzClose(zf); };
std::unique_ptr<void, decltype(guard)> closeGuard(zf, guard);
// 1. Parse META-INF/container.xml
QByteArray containerData = readZipEntry(zf, "META-INF/container.xml");
if (containerData.isEmpty()) {
m_error = QStringLiteral("Invalid EPUB: missing META-INF/container.xml");
return false;
}
QString opfPath;
if (!parseContainer(containerData, opfPath)) {
m_error = QStringLiteral("Invalid EPUB: cannot parse container.xml");
return false;
}
// 2. Determine OPF base directory
const int lastSlash = opfPath.lastIndexOf(QLatin1Char('/'));
m_opfDir = (lastSlash >= 0) ? opfPath.left(lastSlash + 1) : QString();
// 3. Parse OPF (only metadata and manifest for cover image)
QByteArray opfData = readZipEntry(zf, opfPath.toUtf8().constData());
if (opfData.isEmpty()) {
m_error = QStringLiteral("Invalid EPUB: cannot read OPF file: ") + opfPath;
return false;
}
QString ncxHref;
if (!parseOpf(opfData, ncxHref)) {
m_error = QStringLiteral("Invalid EPUB: cannot parse OPF file");
return false;
}
return true;
}
QString EpubReader::lastError() { return m_error; }
QString EpubReader::title() { return m_title; }
QString EpubReader::author() { return m_author; }
QString EpubReader::coverImagePath() { return m_coverImagePath; }
int EpubReader::chapterCount() { return m_spineHrefs.size(); }
QList<TocEntry> EpubReader::tableOfContents() { return m_toc; }
QString EpubReader::filePath()
{
return m_filePath;
}
Chapter EpubReader::loadChapter(int index)
{
if (index < 0 || index >= m_spineRawContent.size())
+5 -1
View File
@@ -5,23 +5,27 @@
#include <QByteArray>
#include <QHash>
#include <QList>
#include <QStringList>
class EpubReader : public FormatReader {
public:
bool open(const QString &filePath) override;
bool loadMetadata(const QString &filePath) override;
QString lastError() override;
int chapterCount() override;
Chapter loadChapter(int index) override;
QList<TocEntry> tableOfContents() override;
QString filePath() override;
QString title() override;
QString author() override;
QString coverImagePath() override;
private:
QString m_filePath;
QString m_title;
QString m_author;
QString m_error;
QString m_opfDir;
QString m_coverImagePath;
QStringList m_spineHrefs;
QList<QByteArray> m_spineRawContent;
QList<TocEntry> m_toc;
+26 -1
View File
@@ -1,6 +1,5 @@
#include "TxtReader.h"
#include <QFile>
#include <QFileInfo>
#include <QRegularExpression>
#include <QTextStream>
@@ -127,6 +126,7 @@ bool TxtReader::open(const QString &filePath)
uchardet_delete(ud);
if (!m_content.isEmpty()) {
m_title = QFileInfo(filePath).completeBaseName();
m_filePath = filePath;
return true;
}
}
@@ -136,6 +136,21 @@ bool TxtReader::open(const QString &filePath)
// Default: UTF-8
m_content = QString::fromUtf8(raw);
m_title = QFileInfo(filePath).completeBaseName();
m_filePath = filePath;
return true;
}
bool TxtReader::loadMetadata(const QString &filePath)
{
QFile file(filePath);
if (!file.exists()) {
m_error = QStringLiteral("File not found: ") + filePath;
return false;
}
// For TXT files, we only need the filename for title
m_title = QFileInfo(filePath).completeBaseName();
m_author.clear(); // No author info in plain text files
return true;
}
@@ -172,6 +187,11 @@ QList<TocEntry> TxtReader::tableOfContents()
return {};
}
QString TxtReader::filePath()
{
return m_filePath;
}
QString TxtReader::title()
{
return m_title;
@@ -181,3 +201,8 @@ QString TxtReader::author()
{
return {};
}
QString TxtReader::coverImagePath()
{
return {};
}
+5
View File
@@ -6,16 +6,21 @@
class TxtReader : public FormatReader {
public:
bool open(const QString &filePath) override;
bool loadMetadata(const QString &filePath) override;
QString lastError() override;
int chapterCount() override;
Chapter loadChapter(int index) override;
QList<TocEntry> tableOfContents() override;
QString filePath() override;
QString title() override;
QString author() override;
QString coverImagePath() override;
private:
QString m_content;
QString m_filePath;
QString m_title;
QString m_author;
QString m_error;
};
+16 -13
View File
@@ -1,17 +1,18 @@
#include <QApplication>
#include <QDateTime>
#include <QFileInfo>
#include <QSize>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <QQuickStyle>
#include <QQuickWindow>
#include <QSettings>
#include <QSGRendererInterface>
#include "backend/BookController.h"
#include "backend/EpubImageProvider.h"
#include "backend/IImageProvider.h"
#include "backend/ReadingModel.h"
#include "backend/AppState.h"
#include "backend/LibraryModel.h"
#include "backend/NativeFileDialogService.h"
#ifdef HAS_QT_DBUS
@@ -57,6 +58,7 @@ void myMessageHandler(const QtMsgType type, const QMessageLogContext &context, c
int main(int argc, char *argv[])
{
qInstallMessageHandler(myMessageHandler);
QSettings::setDefaultFormat(QSettings::IniFormat);
// Select graphics API per platform
#if defined(Q_OS_MACOS)
@@ -87,7 +89,7 @@ int main(int argc, char *argv[])
appState.restore();
bookController.setAppState(&appState);
#ifdef HAS_QT_DBUS
#if defined(HAS_QT_DBUS) && defined(Q_OS_LINUX)
IFileDialogService *fileDialogService;
if (QDBusConnection::sessionBus().isConnected()) {
fileDialogService = new PortalFileDialogService(&bookController);
@@ -106,10 +108,18 @@ int main(int argc, char *argv[])
}
QQmlApplicationEngine engine;
engine.rootContext()->setContextProperty("isDebugBuild",
#ifdef QT_DEBUG
true
#else
false
#endif
);
auto *epubImageProvider = new EpubImageProvider;
engine.addImageProvider(QStringLiteral("epub"), epubImageProvider);
bookController.setImageProvider(epubImageProvider);
bookController.setImageProviderRegistrar([&engine](const QString &scheme, IImageProvider *provider) {
engine.removeImageProvider(scheme);
engine.addImageProvider(scheme, provider);
});
engine.rootContext()->setContextProperty(QStringLiteral("bookController"), &bookController);
engine.rootContext()->setContextProperty(QStringLiteral("readingModel"), &readingModel);
@@ -141,14 +151,7 @@ int main(int argc, char *argv[])
QObject::connect(&app, &QCoreApplication::aboutToQuit, [&bookController, &appState, &readingModel]() {
if (bookController.hasBook()) {
appState.setLastFilePath(bookController.currentFilePath());
appState.setLastChapter(readingModel.currentChapter());
appState.saveBookPosition(bookController.currentFilePath(),
readingModel.currentChapter(),
appState.lastScrollIndex(),
appState.lastScrollOffset());
appState.addOrUpdateLibraryBook(bookController.currentFilePath(),
bookController.bookTitle(),
bookController.bookAuthor(),
readingModel.progress());
} else {
appState.setLastFilePath(QString());
+27 -14
View File
@@ -7,6 +7,7 @@ ApplicationWindow {
id: window
width: 1024
height: 768
opacity: 0
visible: true
title: "Asteria"
color: ThemeManager.currentTheme.backgroundDeepest
@@ -19,7 +20,6 @@ ApplicationWindow {
property bool sidebarOpen: appState.sidebarOpen
onSidebarOpenChanged: appState.sidebarOpen = sidebarOpen
property string currentPage: "starter"
property bool _restoringState: false
property bool barsVisible: true
onCurrentPageChanged: appState.lastPage = currentPage
@@ -31,21 +31,10 @@ ApplicationWindow {
x = appState.windowX
y = appState.windowY
}
// Initialize theme from AppState
if (appState.themeName !== "") {
ThemeManager.currentThemeName = appState.themeName
}
if (appState.lastFilePath !== "") {
window._restoringState = true
bookController.openBook(appState.lastFileUrl())
} else {
window.sidebarOpen = true
var savedPage = appState.lastPage
if (savedPage === "library" || savedPage === "settings")
window.currentPage = savedPage
}
}
Connections {
@@ -129,6 +118,13 @@ ApplicationWindow {
anchors.fill: parent
visible: window.currentPage === "library"
}
BusyIndicator {
anchors.centerIn: parent
running: bookController.loading || readingModel.measuring
visible: running
z: 10
}
}
Loader {
@@ -224,8 +220,7 @@ ApplicationWindow {
Connections {
target: bookController
function onBookReady() {
if (window._restoringState) {
window._restoringState = false
if (bookController.startupRestore) {
var savedPage = appState.lastPage
if (savedPage === "library" || savedPage === "settings")
window.currentPage = savedPage
@@ -239,5 +234,23 @@ ApplicationWindow {
if (!bookController.hasBook && window.currentPage === "reader")
window.currentPage = "starter"
}
function onNoSavedBook() {
window.sidebarOpen = true
var savedPage = appState.lastPage
if (savedPage === "library" || savedPage === "settings")
window.currentPage = savedPage
}
}
Timer {
running: true
repeat: false
interval: 1
triggeredOnStart: false
onTriggered: {
window.opacity = 1
readerPage.pageView.updateContentWidth()
bookController.uiReady()
}
}
}
+93 -43
View File
@@ -5,6 +5,12 @@ import Asteria
Rectangle {
focus: true
property bool contentReady: false
property bool resizing: false
property bool restoreReady: false
property int initialIndex: -1
property int initialOffset: -1
// Animation for smooth scrolling
property Animation scrollAnimation: PropertyAnimation {
target: chunkListView
@@ -62,19 +68,46 @@ Rectangle {
}
Component.onCompleted: updateContentWidth()
onWidthChanged: updateContentWidth()
onWidthChanged: {
resizing = true;
remeasureTimer.restart()
}
Timer {
id: remeasureTimer
interval: 150
repeat: false
onTriggered: {
updateContentWidth()
resizing = false;
}
}
ListView {
id: chunkListView
anchors.fill: parent
model: bookController.hasBook ? readingModel : null
model: contentReady ? readingModel : null
header: Item { height: appState.verticalMargin }
footer: Item { height: appState.verticalMargin }
cacheBuffer: 2000
cacheBuffer: 20
clip: true
delegate: Text {
width: ListView.view.width - 18
delegate: Item {
id: chunkDelegate
readonly property int chunkIdx: model.index
width: chunkListView.width
height: resizing || readingModel.measuring ? contentText.implicitHeight : model.pixelHeight
Text {
visible: isDebugBuild
leftPadding: 0
text: model.index
color: "#FFFFFF"
height: 0
}
Text {
id: contentText
width: parent.width - 18 // subtract scrollbar
leftPadding: appState.horizontalMargin
rightPadding: appState.horizontalMargin
wrapMode: Text.WrapAtWordBoundaryOrAnywhere
@@ -83,16 +116,24 @@ Rectangle {
lineHeight: appState.lineSpacing
color: ThemeManager.currentTheme.readingText
text: model.content
visible: model.content !== ""
// TODO: remove when we're good with measurer
onImplicitHeightChanged: {
if (model.pixelHeight > 0 && implicitHeight > 0) {
var diff = model.pixelHeight - implicitHeight
if (Math.abs(diff) > 1) {
console.warn("Chunk", model.index,
"height mismatch: measured=" + model.pixelHeight,
"actual=" + Math.round(implicitHeight),
"diff=" + Math.round(diff))
}
}
}
}
}
onContentYChanged: {
scrollTrackTimer.restart()
var idx = chunkListView.indexAt(0, chunkListView.contentY)
if (idx >= 0) {
var item = chunkListView.itemAtIndex(idx)
var offset = item ? chunkListView.contentY - item.y : 0
readingModel.setScrollInfo(idx, offset, chunkListView.atYEnd)
}
}
ScrollBar.vertical: ScrollBar {
@@ -125,60 +166,69 @@ Rectangle {
interval: 150
onTriggered: {
window.barsVisible = !window.barsVisible
window.sidebarOpen = false
window.sidebarOpen = !window.sidebarOpen
}
}
}
}
Timer {
id: scrollTrackTimer
interval: 300
repeat: false
onTriggered: {
var idx = chunkListView.indexAt(0, chunkListView.contentY)
appState.lastScrollIndex = idx
var item = chunkListView.itemAtIndex(idx)
var offset = item ? chunkListView.contentY - item.y : 0
appState.lastScrollOffset = offset
appState.lastScrollPosition = chunkListView.contentY
if (bookController.hasBook)
appState.saveBookPosition(bookController.currentFilePath,
readingModel.currentChapter, idx, offset)
if (bookController.hasBook && contentReady && restoreReady) {
var topIdx = chunkListView.indexAt(0, chunkListView.contentY)
if (topIdx < 0) topIdx = 0
var topItem = chunkListView.itemAtIndex(topIdx)
var intraOffset = topItem ? (chunkListView.contentY - topItem.y) : 0
readingModel.setScrollInfo(topIdx, chunkListView.visibleArea.yPosition)
appState.saveBookPosition(bookController.currentFilePath, topIdx, intraOffset)
}
}
}
property bool _restoring: false
Connections {
target: bookController
function onBookReady() {
_restoring = true
var pos = appState.loadBookPosition(bookController.currentFilePath)
var savedScrollIndex = pos["scrollIndex"]
var savedScrollOffset = pos["scrollOffset"]
Qt.callLater(function() {
if (savedScrollIndex > 0) {
chunkListView.positionViewAtIndex(savedScrollIndex, ListView.Beginning)
chunkListView.contentY += savedScrollOffset
var idx = chunkListView.indexAt(0, chunkListView.contentY)
if (idx >= 0) {
var item = chunkListView.itemAtIndex(idx)
var offset = item ? chunkListView.contentY - item.y : 0
readingModel.setScrollInfo(idx, offset, chunkListView.atYEnd)
}
}
_restoring = false
})
function onLoadingChanged() {
if (bookController.loading)
contentReady = false
}
}
Connections {
target: readingModel
function onRestoreReady(chunkIndex, intraOffset) {
contentReady = true
initialIndex = chunkIndex
initialOffset = intraOffset
restoreTimer.start()
}
function onScrollToChunkRequested(chunkIndex) {
chunkListView.positionViewAtIndex(chunkIndex, ListView.Beginning)
}
}
Connections {
target: appState
function onFontSizeChanged() {
readingModel.setFontParams(appState.fontSize, appState.lineSpacing)
}
function onLineSpacingChanged() {
readingModel.setFontParams(appState.fontSize, appState.lineSpacing)
}
}
Timer {
id: restoreTimer
interval: 1
repeat: false
onTriggered: {
console.info("Restoring contentHeight:", chunkListView.contentHeight, "originY:", chunkListView.originY, "chunkIndex:", initialIndex, "intraOffset:", initialOffset)
chunkListView.positionViewAtIndex(initialIndex, ListView.Beginning)
chunkListView.contentY += initialOffset
restoreReady = true
}
}
}
+20 -10
View File
@@ -6,7 +6,7 @@ Rectangle {
color: ThemeManager.currentTheme.backgroundDefault
Text {
visible: appState.libraryBooks.length === 0
visible: appState.libraryModel.count === 0
anchors.centerIn: parent
text: "No books read yet.\nOpen a book to start your library."
horizontalAlignment: Text.AlignHCenter
@@ -16,12 +16,12 @@ Rectangle {
}
ListView {
visible: appState.libraryBooks.length > 0
visible: appState.libraryModel.count > 0
anchors.fill: parent
anchors.margins: 16
spacing: 8
clip: true
model: appState.libraryBooks
model: appState.libraryModel
delegate: Rectangle {
id: bookRow
@@ -38,15 +38,25 @@ Rectangle {
anchors.bottomMargin: 12
spacing: 8
Image {
id: coverImage
visible: filePath !== ""
width: 60
height: 80
source: coverImageUrl
fillMode: Image.PreserveAspectFit
anchors.verticalCenter: parent.verticalCenter
}
Column {
id: bookInfoCol
width: parent.width - removeBtn.width - parent.spacing
width: parent.width - removeBtn.width - parent.spacing - (coverImage.visible ? coverImage.width + 8 : 0)
anchors.verticalCenter: parent.verticalCenter
spacing: 3
Text {
width: parent.width
text: modelData.title || "Unknown Title"
text: title || "Unknown Title"
color: ThemeManager.currentTheme.uiText
font.pixelSize: 14
font.bold: true
@@ -54,16 +64,16 @@ Rectangle {
}
Text {
visible: modelData.author !== ""
visible: author !== ""
width: parent.width
text: modelData.author
text: author
color: ThemeManager.currentTheme.dimText
font.pixelSize: 12
elide: Text.ElideRight
}
Text {
text: Math.round(modelData.progress * 100) + "%"
text: Math.round(progress * 100) + "%"
color: ThemeManager.currentTheme.buttonAccent
font.pixelSize: 12
}
@@ -82,14 +92,14 @@ Rectangle {
verticalAlignment: Text.AlignVCenter
}
background: Item {}
onClicked: appState.removeLibraryBook(modelData.filePath)
onClicked: appState.removeLibraryBook(filePath)
}
}
MouseArea {
anchors.fill: parent
z: -1
onClicked: bookController.openBookFromPath(modelData.filePath)
onClicked: bookController.openBookFromPath(filePath)
}
}
}
+48 -8
View File
@@ -44,7 +44,7 @@ Rectangle {
}
Text {
id: valueH
text: appState.horizontalMargin + " px"
text: hmSlider.value + " px"
font.pixelSize: 13
color: ThemeManager.currentTheme.dimText
anchors.right: parent.right
@@ -53,13 +53,23 @@ Rectangle {
}
}
Timer {
id: hmTimer
interval: 250
onTriggered: appState.horizontalMargin = hmSlider.value
}
Slider {
id: hmSlider
width: parent.width
from: 0
to: 120
stepSize: 1
value: appState.horizontalMargin
onValueChanged: appState.horizontalMargin = value
onValueChanged: {
if (value !== appState.horizontalMargin)
hmTimer.restart()
}
}
}
@@ -81,7 +91,7 @@ Rectangle {
}
Text {
id: valueV
text: appState.verticalMargin + " px"
text: vmSlider.value + " px"
font.pixelSize: 13
color: ThemeManager.currentTheme.dimText
anchors.right: parent.right
@@ -90,13 +100,23 @@ Rectangle {
}
}
Timer {
id: vmTimer
interval: 250
onTriggered: appState.verticalMargin = vmSlider.value
}
Slider {
id: vmSlider
width: parent.width
from: 0
to: 80
stepSize: 1
value: appState.verticalMargin
onValueChanged: appState.verticalMargin = value
onValueChanged: {
if (value !== appState.verticalMargin)
vmTimer.restart()
}
}
}
@@ -118,7 +138,7 @@ Rectangle {
}
Text {
id: valueF
text: appState.fontSize + " px"
text: fsSlider.value + " px"
font.pixelSize: 13
color: ThemeManager.currentTheme.dimText
anchors.right: parent.right
@@ -127,13 +147,23 @@ Rectangle {
}
}
Timer {
id: fsTimer
interval: 250
onTriggered: appState.fontSize = fsSlider.value
}
Slider {
id: fsSlider
width: parent.width
from: 10
to: 32
stepSize: 1
value: appState.fontSize
onValueChanged: appState.fontSize = value
onValueChanged: {
if (value !== appState.fontSize)
fsTimer.restart()
}
}
}
@@ -155,7 +185,7 @@ Rectangle {
}
Text {
id: valueL
text: appState.lineSpacing.toFixed(1) + "×"
text: lsSlider.value.toFixed(1) + "×"
font.pixelSize: 13
color: ThemeManager.currentTheme.dimText
anchors.right: parent.right
@@ -164,13 +194,23 @@ Rectangle {
}
}
Timer {
id: lsTimer
interval: 250
onTriggered: appState.lineSpacing = lsSlider.value
}
Slider {
id: lsSlider
width: parent.width
from: 0.5
to: 3.0
stepSize: 0.1
value: appState.lineSpacing
onValueChanged: appState.lineSpacing = value
onValueChanged: {
if (Math.abs(value - appState.lineSpacing) > 0.01)
lsTimer.restart()
}
}
}
}
+107 -186
View File
@@ -2,6 +2,7 @@
#include <QSignalSpy>
#include <QSettings>
#include "backend/AppState.h"
#include "backend/LibraryModel.h"
class AppStateTest : public QObject {
Q_OBJECT
@@ -30,54 +31,6 @@ private slots:
QCOMPARE(state2.lastFilePath(), QStringLiteral("/books/test.epub"));
}
void saveAndRestoreLastChapter()
{
{
AppState state;
state.setLastChapter(5);
state.save();
}
AppState state2;
state2.restore();
QCOMPARE(state2.lastChapter(), 5);
}
void saveAndRestoreLastScrollPosition()
{
{
AppState state;
state.setLastScrollPosition(542.5);
state.save();
}
AppState state2;
state2.restore();
QCOMPARE(state2.lastScrollPosition(), 542.5);
}
void saveAndRestoreLastScrollIndex()
{
{
AppState state;
state.setLastScrollIndex(42);
state.save();
}
AppState state2;
state2.restore();
QCOMPARE(state2.lastScrollIndex(), 42);
}
void saveAndRestoreLastScrollOffset()
{
{
AppState state;
state.setLastScrollOffset(123.75);
state.save();
}
AppState state2;
state2.restore();
QCOMPARE(state2.lastScrollOffset(), 123.75);
}
void saveAndRestoreMargins()
{
{
@@ -139,10 +92,6 @@ private slots:
AppState state;
state.restore();
QVERIFY(state.lastFilePath().isEmpty());
QCOMPARE(state.lastChapter(), 0);
QCOMPARE(state.lastScrollPosition(), 0.0);
QCOMPARE(state.lastScrollIndex(), 0);
QCOMPARE(state.lastScrollOffset(), 0.0);
QCOMPARE(state.horizontalMargin(), 32);
QCOMPARE(state.verticalMargin(), 8);
QCOMPARE(state.fontSize(), 16);
@@ -157,10 +106,6 @@ private slots:
{
AppState state;
QSignalSpy spyFilePath(&state, &AppState::lastFilePathChanged);
QSignalSpy spyChapter(&state, &AppState::lastChapterChanged);
QSignalSpy spyScroll(&state, &AppState::lastScrollPositionChanged);
QSignalSpy spyScrollIndex(&state, &AppState::lastScrollIndexChanged);
QSignalSpy spyScrollOffset(&state, &AppState::lastScrollOffsetChanged);
QSignalSpy spyHMargin(&state, &AppState::horizontalMarginChanged);
QSignalSpy spyVMargin(&state, &AppState::verticalMarginChanged);
QSignalSpy spyFontSize(&state, &AppState::fontSizeChanged);
@@ -171,10 +116,6 @@ private slots:
QSignalSpy spyY(&state, &AppState::windowYChanged);
state.setLastFilePath(QStringLiteral("/foo.txt"));
state.setLastChapter(3);
state.setLastScrollPosition(10.5);
state.setLastScrollIndex(7);
state.setLastScrollOffset(55.25);
state.setHorizontalMargin(64);
state.setVerticalMargin(24);
state.setFontSize(20);
@@ -185,10 +126,6 @@ private slots:
state.setWindowY(150);
QCOMPARE(spyFilePath.count(), 1);
QCOMPARE(spyChapter.count(), 1);
QCOMPARE(spyScroll.count(), 1);
QCOMPARE(spyScrollIndex.count(), 1);
QCOMPARE(spyScrollOffset.count(), 1);
QCOMPARE(spyHMargin.count(), 1);
QCOMPARE(spyVMargin.count(), 1);
QCOMPARE(spyFontSize.count(), 1);
@@ -202,49 +139,41 @@ private slots:
void saveAndLoadBookPosition()
{
AppState state;
state.saveBookPosition(QStringLiteral("/books/a.epub"), 3, 42, 123.5);
state.saveBookPosition(QStringLiteral("/books/a.epub"), 5, 120);
QVariantMap pos = state.loadBookPosition(QStringLiteral("/books/a.epub"));
QCOMPARE(pos["chapter"].toInt(), 3);
QCOMPARE(pos["scrollIndex"].toInt(), 42);
QCOMPARE(pos["scrollOffset"].toDouble(), 123.5);
QCOMPARE(pos[QStringLiteral("chunkIndex")].toInt(), 5);
QCOMPARE(pos[QStringLiteral("intraChunkOffset")].toInt(), 120);
}
void loadBookPositionForUnknownBook()
{
AppState state;
QVariantMap pos = state.loadBookPosition(QStringLiteral("/books/unknown.epub"));
QCOMPARE(pos["chapter"].toInt(), 0);
QCOMPARE(pos["scrollIndex"].toInt(), 0);
QCOMPARE(pos["scrollOffset"].toDouble(), 0.0);
QCOMPARE(pos[QStringLiteral("chunkIndex")].toInt(), 0);
QCOMPARE(pos[QStringLiteral("intraChunkOffset")].toInt(), 0);
}
void saveBookPositionForMultipleBooks()
{
AppState state;
state.saveBookPosition(QStringLiteral("/books/a.epub"), 1, 10, 50.0);
state.saveBookPosition(QStringLiteral("/books/b.epub"), 5, 99, 200.5);
state.saveBookPosition(QStringLiteral("/books/a.epub"), 10, 50);
state.saveBookPosition(QStringLiteral("/books/b.epub"), 20, 200);
QVariantMap posA = state.loadBookPosition(QStringLiteral("/books/a.epub"));
QVariantMap posB = state.loadBookPosition(QStringLiteral("/books/b.epub"));
QCOMPARE(posA["chapter"].toInt(), 1);
QCOMPARE(posA["scrollIndex"].toInt(), 10);
QCOMPARE(posB["chapter"].toInt(), 5);
QCOMPARE(posB["scrollIndex"].toInt(), 99);
QCOMPARE(posB["scrollOffset"].toDouble(), 200.5);
QCOMPARE(posA[QStringLiteral("chunkIndex")].toInt(), 10);
QCOMPARE(posA[QStringLiteral("intraChunkOffset")].toInt(), 50);
QCOMPARE(posB[QStringLiteral("chunkIndex")].toInt(), 20);
QCOMPARE(posB[QStringLiteral("intraChunkOffset")].toInt(), 200);
}
void saveBookPositionOverwritesPrevious()
{
AppState state;
state.saveBookPosition(QStringLiteral("/books/a.epub"), 1, 10, 50.0);
state.saveBookPosition(QStringLiteral("/books/a.epub"), 7, 33, 88.0);
state.saveBookPosition(QStringLiteral("/books/a.epub"), 10, 50);
state.saveBookPosition(QStringLiteral("/books/a.epub"), 15, 88);
QVariantMap pos = state.loadBookPosition(QStringLiteral("/books/a.epub"));
QCOMPARE(pos["chapter"].toInt(), 7);
QCOMPARE(pos["scrollIndex"].toInt(), 33);
QCOMPARE(pos["scrollOffset"].toDouble(), 88.0);
QCOMPARE(pos[QStringLiteral("chunkIndex")].toInt(), 15);
QCOMPARE(pos[QStringLiteral("intraChunkOffset")].toInt(), 88);
}
void restoreEmitsSingleSignal()
@@ -253,10 +182,6 @@ private slots:
QSignalSpy spyRestored(&state, &AppState::stateRestored);
QSignalSpy spyFilePath(&state, &AppState::lastFilePathChanged);
QSignalSpy spyChapter(&state, &AppState::lastChapterChanged);
QSignalSpy spyScroll(&state, &AppState::lastScrollPositionChanged);
QSignalSpy spyScrollIndex(&state, &AppState::lastScrollIndexChanged);
QSignalSpy spyScrollOffset(&state, &AppState::lastScrollOffsetChanged);
QSignalSpy spyHMargin(&state, &AppState::horizontalMarginChanged);
QSignalSpy spyVMargin(&state, &AppState::verticalMarginChanged);
QSignalSpy spyFontSize(&state, &AppState::fontSizeChanged);
@@ -271,10 +196,6 @@ private slots:
QCOMPARE(spyRestored.count(), 1);
QCOMPARE(spyFilePath.count(), 0);
QCOMPARE(spyChapter.count(), 0);
QCOMPARE(spyScroll.count(), 0);
QCOMPARE(spyScrollIndex.count(), 0);
QCOMPARE(spyScrollOffset.count(), 0);
QCOMPARE(spyHMargin.count(), 0);
QCOMPARE(spyVMargin.count(), 0);
QCOMPARE(spyFontSize.count(), 0);
@@ -343,153 +264,155 @@ private slots:
void libraryBooksInitiallyEmpty()
{
AppState state;
QVERIFY(state.libraryBooks().isEmpty());
auto* model = qobject_cast<QAbstractListModel*>(state.libraryModel());
QVERIFY(model->rowCount() == 0);
}
void addLibraryBookAddsEntry()
{
AppState state;
state.addOrUpdateLibraryBook(QStringLiteral("/books/a.epub"),
QStringLiteral("Title A"),
QStringLiteral("Author A"), 0.0);
state.addOrUpdateLibraryBook(QStringLiteral("/books/a.epub"), 0.0);
QVariantList books = state.libraryBooks();
QCOMPARE(books.size(), 1);
QVariantMap book = books.first().toMap();
QCOMPARE(book[QStringLiteral("filePath")].toString(), QStringLiteral("/books/a.epub"));
QCOMPARE(book[QStringLiteral("title")].toString(), QStringLiteral("Title A"));
QCOMPARE(book[QStringLiteral("author")].toString(), QStringLiteral("Author A"));
QCOMPARE(book[QStringLiteral("progress")].toDouble(), 0.0);
auto* model = qobject_cast<QAbstractListModel*>(state.libraryModel());
QCOMPARE(model->rowCount(), 1);
// Get data from the model
QModelIndex index = model->index(0);
QString filePath = model->data(index, LibraryModel::FilePathRole).toString();
double progress = model->data(index, LibraryModel::ProgressRole).toDouble();
QCOMPARE(filePath, QStringLiteral("/books/a.epub"));
QCOMPARE(progress, 0.0);
// Title and author are now loaded asynchronously from file metadata
// QString title = model->data(index, 2).toString(); // TitleRole = 2
// QString author = model->data(index, 3).toString(); // AuthorRole = 3
// QCOMPARE(title, QStringLiteral("Title A"));
// QCOMPARE(author, QStringLiteral("Author A"));
}
void addLibraryBookPersistsThroughSaveRestore()
{
{
AppState state;
state.addOrUpdateLibraryBook(QStringLiteral("/books/a.epub"),
QStringLiteral("Title A"),
QStringLiteral("Author A"), 0.5);
state.addOrUpdateLibraryBook(QStringLiteral("/books/a.epub"), 0.5);
state.save();
}
AppState state2;
state2.restore();
QVariantList books = state2.libraryBooks();
QCOMPARE(books.size(), 1);
QVariantMap book = books.first().toMap();
QCOMPARE(book[QStringLiteral("filePath")].toString(), QStringLiteral("/books/a.epub"));
QCOMPARE(book[QStringLiteral("title")].toString(), QStringLiteral("Title A"));
QCOMPARE(book[QStringLiteral("progress")].toDouble(), 0.5);
auto* model = qobject_cast<QAbstractListModel*>(state2.libraryModel());
QCOMPARE(model->rowCount(), 1);
QModelIndex index = model->index(0);
QString filePath = model->data(index, LibraryModel::FilePathRole).toString();
double progress = model->data(index, LibraryModel::ProgressRole).toDouble();
QCOMPARE(filePath, QStringLiteral("/books/a.epub"));
// Title is now loaded asynchronously from file metadata
// QString title = model->data(index, 2).toString(); // TitleRole = 2
// QCOMPARE(title, QStringLiteral("Title A"));
QCOMPARE(progress, 0.5);
}
void addLibraryBookUpdatesMetadata()
{
AppState state;
state.addOrUpdateLibraryBook(QStringLiteral("/books/a.epub"),
QStringLiteral("Old Title"),
QStringLiteral("Old Author"), 0.3);
state.addOrUpdateLibraryBook(QStringLiteral("/books/a.epub"),
QStringLiteral("New Title"),
QStringLiteral("New Author"), 0.3);
state.addOrUpdateLibraryBook(QStringLiteral("/books/a.epub"), 0.3);
state.addOrUpdateLibraryBook(QStringLiteral("/books/a.epub"), 0.3);
QVariantList books = state.libraryBooks();
QCOMPARE(books.size(), 1);
QVariantMap book = books.first().toMap();
QCOMPARE(book[QStringLiteral("title")].toString(), QStringLiteral("New Title"));
QCOMPARE(book[QStringLiteral("author")].toString(), QStringLiteral("New Author"));
auto* model = qobject_cast<QAbstractListModel*>(state.libraryModel());
QCOMPARE(model->rowCount(), 1);
QModelIndex index = model->index(0);
// Title and author are now loaded asynchronously from file metadata
// QString title = model->data(index, 2).toString(); // TitleRole = 2
// QString author = model->data(index, 3).toString(); // AuthorRole = 3
// QCOMPARE(title, QStringLiteral("New Title"));
// QCOMPARE(author, QStringLiteral("New Author"));
}
void addLibraryBookOverwritesProgress()
{
AppState state;
state.addOrUpdateLibraryBook(QStringLiteral("/books/a.epub"),
QStringLiteral("Title A"),
QStringLiteral("Author A"), 0.6);
state.addOrUpdateLibraryBook(QStringLiteral("/books/a.epub"), 0.6);
// Lower value should overwrite (always update, no max logic)
state.addOrUpdateLibraryBook(QStringLiteral("/books/a.epub"),
QStringLiteral("Title A"),
QStringLiteral("Author A"), 0.2);
state.addOrUpdateLibraryBook(QStringLiteral("/books/a.epub"), 0.2);
QVariantList books = state.libraryBooks();
QCOMPARE(books.size(), 1);
QCOMPARE(books.first().toMap()[QStringLiteral("progress")].toDouble(), 0.2);
auto* model = qobject_cast<QAbstractListModel*>(state.libraryModel());
QCOMPARE(model->rowCount(), 1);
QModelIndex index = model->index(0);
double progress = model->data(index, LibraryModel::ProgressRole).toDouble();
QCOMPARE(progress, 0.2);
}
void addLibraryBookSentinelPreservesProgress()
{
AppState state;
state.addOrUpdateLibraryBook(QStringLiteral("/books/a.epub"),
QStringLiteral("Title A"),
QStringLiteral("Author A"), 0.5);
state.addOrUpdateLibraryBook(QStringLiteral("/books/a.epub"), 0.5);
// -1.0 sentinel: update metadata but don't touch progress
state.addOrUpdateLibraryBook(QStringLiteral("/books/a.epub"),
QStringLiteral("New Title"),
QStringLiteral("Author A"), -1.0);
state.addOrUpdateLibraryBook(QStringLiteral("/books/a.epub"), -1.0);
QVariantList books = state.libraryBooks();
QCOMPARE(books.size(), 1);
QVariantMap book = books.first().toMap();
QCOMPARE(book[QStringLiteral("progress")].toDouble(), 0.5);
QCOMPARE(book[QStringLiteral("title")].toString(), QStringLiteral("New Title"));
auto* model = qobject_cast<QAbstractListModel*>(state.libraryModel());
QCOMPARE(model->rowCount(), 1);
QModelIndex index = model->index(0);
double progress = model->data(index, LibraryModel::ProgressRole).toDouble();
QCOMPARE(progress, 0.5);
// Title is now loaded asynchronously from file metadata
// QString title = model->data(index, 2).toString(); // TitleRole = 2
// QCOMPARE(title, QStringLiteral("New Title"));
}
void addNewLibraryBookWithSentinelStartsAtZero()
{
AppState state;
// New book added with sentinel should start at 0%
state.addOrUpdateLibraryBook(QStringLiteral("/books/a.epub"),
QStringLiteral("Title A"),
QStringLiteral("Author A"), -1.0);
state.addOrUpdateLibraryBook(QStringLiteral("/books/a.epub"), -1.0);
QVariantList books = state.libraryBooks();
QCOMPARE(books.size(), 1);
QCOMPARE(books.first().toMap()[QStringLiteral("progress")].toDouble(), 0.0);
auto* model = qobject_cast<QAbstractListModel*>(state.libraryModel());
QCOMPARE(model->rowCount(), 1);
QModelIndex index = model->index(0);
double progress = model->data(index, LibraryModel::ProgressRole).toDouble();
QCOMPARE(progress, 0.0);
}
void removeLibraryBookRemovesEntry()
{
AppState state;
state.addOrUpdateLibraryBook(QStringLiteral("/books/a.epub"),
QStringLiteral("Title A"),
QStringLiteral("Author A"), 0.5);
state.addOrUpdateLibraryBook(QStringLiteral("/books/b.epub"),
QStringLiteral("Title B"),
QStringLiteral("Author B"), 0.3);
state.addOrUpdateLibraryBook(QStringLiteral("/books/a.epub"), 0.5);
state.addOrUpdateLibraryBook(QStringLiteral("/books/b.epub"), 0.3);
state.removeLibraryBook(QStringLiteral("/books/a.epub"));
QVariantList books = state.libraryBooks();
QCOMPARE(books.size(), 1);
QCOMPARE(books.first().toMap()[QStringLiteral("filePath")].toString(),
QStringLiteral("/books/b.epub"));
auto* model = qobject_cast<QAbstractListModel*>(state.libraryModel());
QCOMPARE(model->rowCount(), 1);
QModelIndex index = model->index(0);
QString filePath = model->data(index, LibraryModel::FilePathRole).toString();
QCOMPARE(filePath, QStringLiteral("/books/b.epub"));
}
void removeNonexistentLibraryBookIsNoop()
{
AppState state;
state.addOrUpdateLibraryBook(QStringLiteral("/books/a.epub"),
QStringLiteral("Title A"),
QStringLiteral("Author A"), 0.5);
state.addOrUpdateLibraryBook(QStringLiteral("/books/a.epub"), 0.5);
state.removeLibraryBook(QStringLiteral("/books/nonexistent.epub"));
QCOMPARE(state.libraryBooks().size(), 1);
auto* model = qobject_cast<QAbstractListModel*>(state.libraryModel());
QCOMPARE(model->rowCount(), 1);
}
void libraryBooksChangedSignalOnAdd()
{
AppState state;
QSignalSpy spy(&state, &AppState::libraryBooksChanged);
state.addOrUpdateLibraryBook(QStringLiteral("/books/a.epub"),
QStringLiteral("Title A"),
QStringLiteral("Author A"), 0.0);
auto* model = qobject_cast<QAbstractListModel*>(state.libraryModel());
QSignalSpy spy(model, &QAbstractListModel::rowsInserted);
state.addOrUpdateLibraryBook(QStringLiteral("/books/a.epub"), 0.0);
QCOMPARE(spy.count(), 1);
}
void libraryBooksChangedSignalOnRemove()
{
AppState state;
state.addOrUpdateLibraryBook(QStringLiteral("/books/a.epub"),
QStringLiteral("Title A"),
QStringLiteral("Author A"), 0.0);
QSignalSpy spy(&state, &AppState::libraryBooksChanged);
state.addOrUpdateLibraryBook(QStringLiteral("/books/a.epub"), 0.0);
auto* model = qobject_cast<QAbstractListModel*>(state.libraryModel());
QSignalSpy spy(model, &QAbstractListModel::rowsRemoved);
state.removeLibraryBook(QStringLiteral("/books/a.epub"));
QCOMPARE(spy.count(), 1);
}
@@ -497,20 +420,18 @@ private slots:
void multipleLibraryBooksAreStoredInOrder()
{
AppState state;
state.addOrUpdateLibraryBook(QStringLiteral("/books/a.epub"),
QStringLiteral("Title A"),
QStringLiteral("Author A"), 0.1);
state.addOrUpdateLibraryBook(QStringLiteral("/books/b.epub"),
QStringLiteral("Title B"),
QStringLiteral("Author B"), 0.2);
state.addOrUpdateLibraryBook(QStringLiteral("/books/a.epub"), 0.1);
state.addOrUpdateLibraryBook(QStringLiteral("/books/b.epub"), 0.2);
QVariantList books = state.libraryBooks();
QCOMPARE(books.size(), 2);
auto* model = qobject_cast<QAbstractListModel*>(state.libraryModel());
QCOMPARE(model->rowCount(), 2);
// Most recently added/updated comes first
QCOMPARE(books.at(0).toMap()[QStringLiteral("filePath")].toString(),
QStringLiteral("/books/b.epub"));
QCOMPARE(books.at(1).toMap()[QStringLiteral("filePath")].toString(),
QStringLiteral("/books/a.epub"));
QModelIndex index0 = model->index(0);
QModelIndex index1 = model->index(1);
QString filePath0 = model->data(index0, LibraryModel::FilePathRole).toString();
QString filePath1 = model->data(index1, LibraryModel::FilePathRole).toString();
QCOMPARE(filePath0, QStringLiteral("/books/b.epub"));
QCOMPARE(filePath1, QStringLiteral("/books/a.epub"));
}
};
+90 -3
View File
@@ -6,6 +6,7 @@
#include "backend/ReadingModel.h"
#include "backend/AppState.h"
#include "backend/IFileDialogService.h"
#include "backend/LibraryModel.h"
class FakeFileDialogService : public IFileDialogService {
Q_OBJECT
@@ -45,6 +46,7 @@ private slots:
QSignalSpy readySpy(&ctrl, &BookController::bookReady);
ctrl.openBook(QUrl::fromLocalFile(fixturePath("sample.txt")));
QVERIFY(readySpy.wait(5000));
QCOMPARE(readySpy.count(), 1);
QVERIFY(ctrl.hasBook());
@@ -57,6 +59,7 @@ private slots:
QSignalSpy errorSpy(&ctrl, &BookController::bookError);
ctrl.openBook(QUrl::fromLocalFile("/tmp/nonexistent_asteria_file.txt"));
QVERIFY(errorSpy.wait(5000));
QCOMPARE(errorSpy.count(), 1);
QVERIFY(!ctrl.errorMessage().isEmpty());
@@ -69,6 +72,7 @@ private slots:
QSignalSpy errorSpy(&ctrl, &BookController::bookError);
ctrl.openBook(QUrl::fromLocalFile("/tmp/file.xyz"));
QVERIFY(errorSpy.wait(5000));
QCOMPARE(errorSpy.count(), 1);
QCOMPARE(ctrl.errorMessage(), QStringLiteral("No format readers available"));
@@ -78,7 +82,9 @@ private slots:
void closeBook()
{
BookController ctrl;
QSignalSpy readySpy(&ctrl, &BookController::bookReady);
ctrl.openBook(QUrl::fromLocalFile(fixturePath("sample.txt")));
QVERIFY(readySpy.wait(5000));
QVERIFY(ctrl.hasBook());
QSignalSpy changedSpy(&ctrl, &BookController::bookChanged);
@@ -95,8 +101,10 @@ private slots:
BookController ctrl;
ReadingModel model;
ctrl.setReadingModel(&model);
QSignalSpy readySpy(&ctrl, &BookController::bookReady);
ctrl.openBook(QUrl::fromLocalFile(fixturePath("sample.txt")));
QVERIFY(readySpy.wait(5000));
QVERIFY(model.totalChapters() > 0);
}
@@ -105,10 +113,15 @@ private slots:
{
BookController ctrl;
QSignalSpy loadingSpy(&ctrl, &BookController::loadingChanged);
QSignalSpy readySpy(&ctrl, &BookController::bookReady);
ctrl.openBook(QUrl::fromLocalFile(fixturePath("sample.txt")));
// loading goes true then false → 2 emissions
QCOMPARE(loadingSpy.count(), 1);
QVERIFY(ctrl.loading());
QVERIFY(readySpy.wait(5000));
QCOMPARE(loadingSpy.count(), 2);
// After completion, loading should be false
QVERIFY(!ctrl.loading());
@@ -123,7 +136,9 @@ private slots:
void currentFilePathSetOnOpen()
{
BookController ctrl;
QSignalSpy readySpy(&ctrl, &BookController::bookReady);
ctrl.openBook(QUrl::fromLocalFile(fixturePath("sample.txt")));
QVERIFY(readySpy.wait(5000));
QCOMPARE(ctrl.currentFilePath(), fixturePath("sample.txt"));
}
@@ -138,7 +153,9 @@ private slots:
void clearErrorResetsMessage()
{
BookController ctrl;
QSignalSpy errorSpy(&ctrl, &BookController::bookError);
ctrl.openBook(QUrl::fromLocalFile("/tmp/file.xyz"));
QVERIFY(errorSpy.wait(5000));
QVERIFY(!ctrl.errorMessage().isEmpty());
QSignalSpy spy(&ctrl, &BookController::errorMessageChanged);
@@ -155,8 +172,10 @@ private slots:
BookController ctrl;
ctrl.setReadingModel(&model);
ctrl.setAppState(&appState);
QSignalSpy readySpy(&ctrl, &BookController::bookReady);
ctrl.openBook(QUrl::fromLocalFile(fixturePath("sample.txt")));
QVERIFY(readySpy.wait(5000));
QVERIFY(ctrl.hasBook());
QString firstPath = ctrl.currentFilePath();
@@ -164,10 +183,10 @@ private slots:
// regardless of whether the second open succeeds
ctrl.openBook(QUrl::fromLocalFile("/tmp/file.xyz"));
// Position for sample.txt should have been saved (chapter 0 at minimum)
// Position for sample.txt should have been saved (0 at minimum)
QVariantMap pos = appState.loadBookPosition(firstPath);
QVERIFY(pos.contains("chapter"));
QCOMPARE(pos["chapter"].toInt(), 0);
QCOMPARE(pos[QStringLiteral("chunkIndex")].toInt(), 0);
QCOMPARE(pos[QStringLiteral("intraChunkOffset")].toInt(), 0);
}
// IFileDialogService tests
@@ -191,6 +210,7 @@ private slots:
QSignalSpy readySpy(&ctrl, &BookController::bookReady);
svc.simulateSelection(fixturePath("sample.txt"));
QVERIFY(readySpy.wait(5000));
QCOMPARE(readySpy.count(), 1);
QVERIFY(ctrl.hasBook());
@@ -203,6 +223,73 @@ private slots:
ctrl.browseAndOpen();
QVERIFY(!ctrl.hasBook());
}
void coverImageUrlInitiallyEmpty()
{
BookController ctrl;
QVERIFY(ctrl.coverImageUrl().isEmpty());
}
void txtBookHasNoCoverImage()
{
BookController ctrl;
QSignalSpy readySpy(&ctrl, &BookController::bookReady);
ctrl.openBook(QUrl::fromLocalFile(fixturePath("sample.txt")));
QVERIFY(readySpy.wait(5000));
QVERIFY(ctrl.hasBook());
QVERIFY(ctrl.coverImageUrl().isEmpty());
}
void coverImageUrlClearedOnClose()
{
BookController ctrl;
ctrl.openBook(QUrl::fromLocalFile(fixturePath("sample.txt")));
ctrl.closeBook();
QVERIFY(ctrl.coverImageUrl().isEmpty());
}
void openBookUpdatesLibrary()
{
AppState appState;
ReadingModel model;
BookController ctrl;
ctrl.setReadingModel(&model);
ctrl.setAppState(&appState);
auto* libraryModel = qobject_cast<QAbstractListModel*>(appState.libraryModel());
QCOMPARE(libraryModel->rowCount(), 0);
QSignalSpy readySpy(&ctrl, &BookController::bookReady);
// First book open does NOT update the library (only previous reader is saved)
ctrl.openBook(QUrl::fromLocalFile(fixturePath("sample.txt")));
QVERIFY(readySpy.wait(5000));
QVERIFY(ctrl.hasBook());
QCOMPARE(libraryModel->rowCount(), 0);
// Closing the book should save it to library
ctrl.closeBook();
QCOMPARE(libraryModel->rowCount(), 1);
QCOMPARE(libraryModel->data(libraryModel->index(0), LibraryModel::FilePathRole).toString(),
fixturePath("sample.txt"));
}
void closeBookUpdatesLibrary()
{
AppState appState;
ReadingModel model;
BookController ctrl;
ctrl.setReadingModel(&model);
ctrl.setAppState(&appState);
QSignalSpy readySpy(&ctrl, &BookController::bookReady);
ctrl.openBook(QUrl::fromLocalFile(fixturePath("sample.txt")));
QVERIFY(readySpy.wait(5000));
ctrl.closeBook();
auto* libraryModel = qobject_cast<QAbstractListModel*>(appState.libraryModel());
QCOMPARE(libraryModel->rowCount(), 1);
QCOMPARE(libraryModel->data(libraryModel->index(0), LibraryModel::FilePathRole).toString(),
fixturePath("sample.txt"));
}
};
QTEST_MAIN(BookControllerTest)
+81
View File
@@ -0,0 +1,81 @@
#include <QtTest>
#include "backend/ChunkMeasurer.h"
#include "backend/IImageLoader.h"
// A mock image loader that returns a solid-color image of a fixed size
class FixedSizeImageLoader : public IImageLoader {
QSize m_size;
public:
explicit FixedSizeImageLoader(const QSize &size) : m_size(size) {}
QImage load(const QUrl &, int maxWidth) const override {
int w = qMin(m_size.width(), maxWidth);
int h = m_size.height();
if (w <= 0 || h <= 0) return {};
QImage img(w, h, QImage::Format_RGB32);
img.fill(Qt::red);
return img;
}
std::unique_ptr<IImageLoader> clone() const override {
return std::make_unique<FixedSizeImageLoader>(m_size);
}
};
class ChunkMeasurerTest : public QObject {
Q_OBJECT
private slots:
void returnsOneHeightPerChunk() {
ChunkMeasurer m;
QStringList chunks = {"<p>First</p>", "<p>Second</p>", "<p>Third</p>"};
auto h = m.measure(chunks, 800);
QCOMPARE(h.size(), 3);
}
void heightsArePositive() {
ChunkMeasurer m;
auto h = m.measure({"<p>Hello world</p>", "<p>Another paragraph</p>"}, 800);
for (int v : h) QVERIFY(v > 0);
}
void emptyInputReturnsEmpty() {
ChunkMeasurer m;
QVERIFY(m.measure({}, 800).isEmpty());
}
void zeroWidthClampedToOne() {
ChunkMeasurer m;
auto h = m.measure({"<p>text</p>"}, 0);
QCOMPARE(h.size(), 1);
QVERIFY(h.first() > 0);
}
void narrowerWidthGivesGreaterOrEqualHeight() {
ChunkMeasurer m;
QStringList chunks = {"<p>A long paragraph that should wrap when the width is very narrow.</p>"};
int h800 = m.measure(chunks, 800).first();
int h200 = m.measure(chunks, 200).first();
QVERIFY(h200 >= h800);
}
void imageChunkMeasuredWithLoader() {
// 600x400 image, but maxWidth=400 so it gets scaled to 400x267
auto loader = std::make_unique<FixedSizeImageLoader>(QSize(600, 400));
ChunkMeasurer m(std::move(loader));
// Chunk with an image URL
QStringList chunks = {QStringLiteral("<p><img src=\"image://epub/test.jpg\"/></p>")};
auto h = m.measure(chunks, 400);
QCOMPARE(h.size(), 1);
QVERIFY(h.first() > 0); // should include image height
}
void nullLoaderTextOnlyWorks() {
ChunkMeasurer m(nullptr);
auto h = m.measure({"<p>text only</p>"}, 800);
QCOMPARE(h.size(), 1);
QVERIFY(h.first() > 0);
}
void parallelResultsAreConsistent() {
ChunkMeasurer m;
QStringList chunks;
for (int i = 0; i < 100; ++i)
chunks << QStringLiteral("<p>Paragraph number %1 with some text content.</p>").arg(i);
auto h1 = m.measure(chunks, 600);
auto h2 = m.measure(chunks, 600);
QCOMPARE(h1, h2);
}
};
QTEST_MAIN(ChunkMeasurerTest)
#include "ChunkMeasurerTest.moc"
+1 -1
View File
@@ -217,7 +217,7 @@ private slots:
QVERIFY(!epubPath.isEmpty());
EpubImageProvider provider;
provider.setEpubPath(epubPath);
provider.setFilePath(epubPath);
provider.clear();
QQuickImageResponse *resp = provider.requestImageResponse(
-53
View File
@@ -1,53 +0,0 @@
#include <QtTest>
#include "backend/QDocumentChunkMeasurer.h"
class QDocumentChunkMeasurerTest : public QObject {
Q_OBJECT
private slots:
void returnsOneHeightPerChunk()
{
QDocumentChunkMeasurer measurer;
QStringList chunks = {"<p>First</p>", "<p>Second</p>", "<p>Third</p>"};
QVector<qreal> heights = measurer.measure(chunks, 800);
QCOMPARE(heights.size(), 3);
}
void heightsArePositive()
{
QDocumentChunkMeasurer measurer;
QStringList chunks = {"<p>Hello world</p>", "<p>Another paragraph</p>"};
QVector<qreal> heights = measurer.measure(chunks, 800);
for (qreal h : heights)
QVERIFY(h > 0.0);
}
void emptyChunkListReturnsEmpty()
{
QDocumentChunkMeasurer measurer;
QVector<qreal> heights = measurer.measure({}, 800);
QVERIFY(heights.isEmpty());
}
void zeroWidthClampedToOne()
{
// Must not crash and must return positive heights
QDocumentChunkMeasurer measurer;
QStringList chunks = {"<p>text</p>"};
QVector<qreal> heights = measurer.measure(chunks, 0);
QCOMPARE(heights.size(), 1);
QVERIFY(heights.first() > 0.0);
}
void narrowerWidthGivesGreaterOrEqualHeight()
{
QDocumentChunkMeasurer measurer;
QStringList chunks = {"<p>A long paragraph that should wrap when the width is very narrow.</p>"};
qreal height800 = measurer.measure(chunks, 800).first();
qreal height200 = measurer.measure(chunks, 200).first();
QVERIFY(height200 >= height800);
}
};
QTEST_MAIN(QDocumentChunkMeasurerTest)
#include "QDocumentChunkMeasurerTest.moc"
+148 -68
View File
@@ -3,18 +3,7 @@
#include "backend/ReadingModel.h"
#include "backend/FormatReader.h"
class SingleChapterReader : public FormatReader {
public:
bool open(const QString &) override { return true; }
QString lastError() override { return {}; }
int chapterCount() override { return 1; }
Chapter loadChapter(int) override { return {0, {}, {"<p>text</p>"}}; }
QList<TocEntry> tableOfContents() override { return {}; }
QString title() override { return {}; }
QString author() override { return {}; }
};
// 3 chapters, 2 chunks each → 6 total chunks
// A fake reader that has 3 chapters, 2 chunks each → 6 total chunks
class FakeReader : public FormatReader {
public:
bool open(const QString &) override { return true; }
@@ -34,6 +23,23 @@ public:
QList<TocEntry> tableOfContents() override { return {}; }
QString title() override { return QStringLiteral("Fake Book"); }
QString author() override { return QStringLiteral("Fake Author"); }
QString filePath() override { return QStringLiteral("/fake/path.txt"); }
QString coverImagePath() override { return {}; }
bool loadMetadata(const QString &) override { return true; }
};
class SingleChapterReader : public FormatReader {
public:
bool open(const QString &) override { return true; }
QString lastError() override { return {}; }
int chapterCount() override { return 1; }
Chapter loadChapter(int) override { return {0, {}, {"<p>text</p>"}}; }
QList<TocEntry> tableOfContents() override { return {}; }
QString title() override { return {}; }
QString author() override { return {}; }
QString filePath() override { return QStringLiteral("/fake/single.txt"); }
QString coverImagePath() override { return {}; }
bool loadMetadata(const QString &) override { return true; }
};
class ReadingModelTest : public QObject {
@@ -104,17 +110,17 @@ private slots:
QCOMPARE(model.currentChapter(), 0);
// Chunk 2 = first chunk of chapter 1
model.setScrollInfo(2, 0, false);
model.setScrollInfo(2, 0.0);
QCOMPARE(model.currentChapter(), 1);
QCOMPARE(model.chapterTitle(), QStringLiteral("Chapter 1"));
// Chunk 4 = first chunk of chapter 2
model.setScrollInfo(4, 0, false);
model.setScrollInfo(4, 0.0);
QCOMPARE(model.currentChapter(), 2);
QCOMPARE(model.chapterTitle(), QStringLiteral("Chapter 2"));
// Back to chapter 0
model.setScrollInfo(0, 0, false);
model.setScrollInfo(0, 0.0);
QCOMPARE(model.currentChapter(), 0);
}
@@ -126,16 +132,16 @@ private slots:
QSignalSpy spy(&model, &ReadingModel::chapterChanged);
model.setScrollInfo(0, 0, false); // still chapter 0 — no signal
model.setScrollInfo(0, 0.0); // still chapter 0 — no signal
QCOMPARE(spy.count(), 0);
model.setScrollInfo(2, 0, false); // chapter 1 → signal
model.setScrollInfo(2, 0.0); // chapter 1 → signal
QCOMPARE(spy.count(), 1);
model.setScrollInfo(3, 0, false); // still chapter 1 — no signal
model.setScrollInfo(3, 0.0); // still chapter 1 — no signal
QCOMPARE(spy.count(), 1);
model.setScrollInfo(4, 0, false); // chapter 2 → signal
model.setScrollInfo(4, 0.0); // chapter 2 → signal
QCOMPARE(spy.count(), 2);
}
@@ -186,7 +192,7 @@ private slots:
ReadingModel model;
FakeReader reader;
model.setReader(&reader);
model.setScrollInfo(4, 0, false); // chapter 2
model.setScrollInfo(4, 0.0); // chapter 2
QSignalSpy spy(&model, &ReadingModel::scrollToChunkRequested);
model.nextChapter();
@@ -198,7 +204,7 @@ private slots:
ReadingModel model;
FakeReader reader;
model.setReader(&reader);
model.setScrollInfo(4, 0, false); // chapter 2
model.setScrollInfo(4, 0.0); // chapter 2
QSignalSpy spy(&model, &ReadingModel::scrollToChunkRequested);
model.previousChapter();
@@ -217,26 +223,6 @@ private slots:
QCOMPARE(spy.count(), 0);
}
void progressIsBookWide()
{
ReadingModel model;
FakeReader reader;
model.setReader(&reader);
// At chunk 0: progress = 0
QCOMPARE(model.progress(), 0.0);
// At chunk 3 (half-way): progress ~0.5
model.setScrollInfo(3, 0, false);
double p = model.progress();
QVERIFY(p > 0.0);
QVERIFY(p < 1.0);
// At chunk 0 again: progress = 0
model.setScrollInfo(0, 0, false);
QCOMPARE(model.progress(), 0.0);
}
void setReaderNull()
{
ReadingModel model;
@@ -265,40 +251,21 @@ private slots:
QCOMPARE(model.totalPages(), 0);
}
void totalPagesEqualsAllChunks()
{
ReadingModel model;
FakeReader reader;
model.setReader(&reader);
QCOMPARE(model.totalPages(), 6); // 3 chapters × 2 chunks
QCOMPARE(model.currentPage(), 1);
}
void setScrollInfoUpdatesCurrentPage()
{
ReadingModel model;
FakeReader reader;
model.setReader(&reader);
model.setScrollInfo(0, 0, false);
QCOMPARE(model.currentPage(), 1);
model.setScrollInfo(0, 0.0);
// If m_totalPixelHeight is 0, yOffset=0, yOffset/totalHeight is NaN.
// qBound(0, NaN, 1) is 0. 0 * 6 * 1.5 = 0.
QCOMPARE(model.currentPage(), 0);
model.setScrollInfo(3, 0, false);
QCOMPARE(model.currentPage(), 4);
model.setScrollInfo(5, 0, false);
QCOMPARE(model.currentPage(), 6);
}
void atYEndGivesLastPage()
{
ReadingModel model;
FakeReader reader;
model.setReader(&reader);
model.setScrollInfo(0, 0, true); // atYEnd = true
QCOMPARE(model.currentPage(), model.totalPages());
model.setScrollInfo(3, 100.0);
// If m_totalPixelHeight is 0, yOffset=100, yOffset/totalHeight is Infinity.
// qBound(0, Inf, 1) is 1.0. 1.0 * 6 * 1.5 = 9.
QCOMPARE(model.currentPage(), 9);
}
void hasChaptersFalseForSingleChapter()
@@ -324,6 +291,119 @@ private slots:
ReadingModel model;
QVERIFY(!model.hasChapters());
}
// --- Cover image tests ---
void coverImagePrependedToChunks()
{
FakeReader reader;
ReadingModel model;
model.setCoverImageUrl("image://epub/OEBPS/cover.jpg");
model.setReader(&reader);
// Should have cover image chunk + original chunks
QCOMPARE(model.rowCount(QModelIndex()), 7); // 1 cover + 6 original
// First chunk should contain cover image HTML
QString firstChunk = model.data(model.index(0, 0), ReadingModel::ContentRole).toString();
QVERIFY(firstChunk.contains("class=\"cover-image\""));
QVERIFY(firstChunk.contains("image://epub/OEBPS/cover.jpg"));
}
void coverImageNotAddedWhenUrlEmpty()
{
FakeReader reader;
ReadingModel model;
model.setReader(&reader);
model.setCoverImageUrl("");
// Should have only original chunks (no cover)
QCOMPARE(model.rowCount(QModelIndex()), 6);
}
void chapterNavigationSkipsCoverImage()
{
FakeReader reader;
ReadingModel model;
model.setCoverImageUrl("image://epub/OEBPS/cover.jpg");
model.setReader(&reader);
// Chapter 0 should start at chunk 1 (after cover image)
QSignalSpy spy(&model, &ReadingModel::scrollToChunkRequested);
model.goToChapter(0);
QCOMPARE(spy.count(), 1);
QCOMPARE(spy.takeFirst().at(0).toInt(), 1); // Should scroll to chunk 1 (after cover)
// Navigate to chapter 2 (last chapter in FakeReader)
model.goToChapter(2);
QCOMPARE(spy.count(), 1);
QCOMPARE(spy.takeFirst().at(0).toInt(), 5); // Should scroll to chunk 5 (chapter 2 start)
}
void coverImageSetAfterReaderReloadsChunks()
{
FakeReader reader;
ReadingModel model;
model.setReader(&reader);
QCOMPARE(model.rowCount(QModelIndex()), 6); // no cover yet
model.setCoverImageUrl(QStringLiteral("image://epub/OEBPS/cover.jpg"));
// setCoverImageUrl doesn't call loadAllChapters(), it only sets the URL.
// The URL is used when loadAllChapters() is called (via setReader).
// If we want to update it, we might need to re-set the reader or call a reload.
// Looking at ReadingModel.cpp, setCoverImageUrl ONLY sets the member.
model.setReader(&reader); // Re-set to reload with cover
QCOMPARE(model.rowCount(QModelIndex()), 7); // 1 cover + 6
QString first = model.data(model.index(0, 0), ReadingModel::ContentRole).toString();
QVERIFY(first.contains(QStringLiteral("class=\"cover-image\"")));
QVERIFY(first.contains(QStringLiteral("image://epub/OEBPS/cover.jpg")));
}
void clearCoverImageUrlRemovesCover()
{
FakeReader reader;
ReadingModel model;
model.setCoverImageUrl(QStringLiteral("image://epub/OEBPS/cover.jpg"));
model.setReader(&reader);
QCOMPARE(model.rowCount(QModelIndex()), 7); // 1 cover + 6
model.setCoverImageUrl(QStringLiteral(""));
model.setReader(&reader); // Re-set to reload without cover
QCOMPARE(model.rowCount(QModelIndex()), 6); // cover removed
QString first = model.data(model.index(0, 0), ReadingModel::ContentRole).toString();
QVERIFY(!first.contains(QStringLiteral("class=\"cover-image\"")));
}
void roleNamesHasNewRoles()
{
ReadingModel model;
auto roles = model.roleNames();
QVERIFY(roles.contains(ReadingModel::PixelHeightRole));
QVERIFY(roles.contains(ReadingModel::ChapterRole));
QCOMPARE(roles.value(ReadingModel::PixelHeightRole), QByteArray("pixelHeight"));
QCOMPARE(roles.value(ReadingModel::ChapterRole), QByteArray("chapter"));
}
void totalPixelHeightInitiallyZero()
{
ReadingModel model;
QCOMPARE(model.totalPixelHeight(), 0.0);
}
void totalPixelHeightResetOnReaderSet()
{
ReadingModel model;
FakeReader reader;
QSignalSpy spy(&model, &ReadingModel::totalPixelHeightChanged);
model.setReader(&reader);
// loadAllChapters resets m_totalPixelHeight to 0 and emits the signal
QVERIFY(spy.count() >= 1);
QCOMPARE(model.totalPixelHeight(), 0.0); // unmeasured chunks have pixelHeight -1, not yet summed
}
};
QTEST_MAIN(ReadingModelTest)
+119 -4
View File
@@ -305,6 +305,88 @@ static QString buildEpubLargeChapter()
return ok ? path : QString{};
}
// Build an EPUB with a cover image using both meta tag and properties attribute
static QString buildEpubWithCoverImage()
{
static const char opfCover[] =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
"<package xmlns=\"http://www.idpf.org/2007/opf\" version=\"2.0\">"
" <metadata xmlns:dc=\"http://purl.org/dc/elements/1.1/\">"
" <dc:title>Cover Book</dc:title>"
" <dc:creator>Cover Tester</dc:creator>"
" <meta name=\"cover\" content=\"cover-id\"/>"
" </metadata>"
" <manifest>"
" <item id=\"cover-id\" href=\"cover.jpg\" media-type=\"image/jpeg\" properties=\"cover-image\"/>"
" <item id=\"ch1\" href=\"chapter1.xhtml\" media-type=\"application/xhtml+xml\"/>"
" </manifest>"
" <spine>"
" <itemref idref=\"ch1\"/>"
" </spine>"
"</package>";
QTemporaryFile tmp;
tmp.setFileTemplate(QDir::tempPath() + "/epub_cover_XXXXXX.epub");
tmp.setAutoRemove(false);
if (!tmp.open()) return {};
const QString path = tmp.fileName();
tmp.close();
zipFile zf = zipOpen(path.toUtf8().constData(), APPEND_STATUS_CREATE);
if (!zf) return {};
bool ok = true;
ok = ok && addEntry(zf, "mimetype", QByteArray(kMimetype), true);
ok = ok && addEntry(zf, "META-INF/container.xml", QByteArray(kContainer));
ok = ok && addEntry(zf, "OEBPS/content.opf", QByteArray(opfCover));
ok = ok && addEntry(zf, "OEBPS/cover.jpg", QByteArray("DUMMY_JPEG"));
ok = ok && addEntry(zf, "OEBPS/chapter1.xhtml", QByteArray(kChapter1));
zipClose(zf, nullptr);
return ok ? path : QString{};
}
// Build an EPUB with cover image in subdirectory
static QString buildEpubWithCoverImageInSubdir()
{
static const char opfCoverSubdir[] =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
"<package xmlns=\"http://www.idpf.org/2007/opf\" version=\"2.0\">"
" <metadata xmlns:dc=\"http://purl.org/dc/elements/1.1/\">"
" <dc:title>Cover Subdir Book</dc:title>"
" <dc:creator>Subdir Tester</dc:creator>"
" <meta name=\"cover\" content=\"cover-img\"/>"
" </metadata>"
" <manifest>"
" <item id=\"cover-img\" href=\"Images/cover.jpg\" media-type=\"image/jpeg\" properties=\"cover-image\"/>"
" <item id=\"ch1\" href=\"chapter1.xhtml\" media-type=\"application/xhtml+xml\"/>"
" </manifest>"
" <spine>"
" <itemref idref=\"ch1\"/>"
" </spine>"
"</package>";
QTemporaryFile tmp;
tmp.setFileTemplate(QDir::tempPath() + "/epub_coversub_XXXXXX.epub");
tmp.setAutoRemove(false);
if (!tmp.open()) return {};
const QString path = tmp.fileName();
tmp.close();
zipFile zf = zipOpen(path.toUtf8().constData(), APPEND_STATUS_CREATE);
if (!zf) return {};
bool ok = true;
ok = ok && addEntry(zf, "mimetype", QByteArray(kMimetype), true);
ok = ok && addEntry(zf, "META-INF/container.xml", QByteArray(kContainer));
ok = ok && addEntry(zf, "OEBPS/content.opf", QByteArray(opfCoverSubdir));
ok = ok && addEntry(zf, "OEBPS/Images/cover.jpg", QByteArray("DUMMY_JPEG"));
ok = ok && addEntry(zf, "OEBPS/chapter1.xhtml", QByteArray(kChapter1));
zipClose(zf, nullptr);
return ok ? path : QString{};
}
// ---------------------------------------------------------------------------
// Test class
// ---------------------------------------------------------------------------
@@ -318,6 +400,8 @@ private:
QString m_largePath;
QString m_imgPath;
QString m_relImgPath;
QString m_coverPath;
QString m_coverSubdirPath;
private slots:
void initTestCase()
@@ -327,11 +411,15 @@ private slots:
m_largePath = buildEpubLargeChapter();
m_imgPath = buildEpubWithImage();
m_relImgPath = buildEpubWithRelativeImage();
m_coverPath = buildEpubWithCoverImage();
m_coverSubdirPath = buildEpubWithCoverImageInSubdir();
QVERIFY2(!m_epubPath.isEmpty(), "Failed to build sample EPUB fixture");
QVERIFY2(!m_noNcxPath.isEmpty(), "Failed to build no-NCX EPUB fixture");
QVERIFY2(!m_largePath.isEmpty(), "Failed to build large chapter EPUB fixture");
QVERIFY2(!m_imgPath.isEmpty(), "Failed to build image EPUB fixture");
QVERIFY2(!m_relImgPath.isEmpty(), "Failed to build relative-image EPUB fixture");
QVERIFY2(!m_coverPath.isEmpty(), "Failed to build cover image EPUB fixture");
QVERIFY2(!m_coverSubdirPath.isEmpty(), "Failed to build cover image subdir EPUB fixture");
}
void cleanupTestCase()
@@ -341,6 +429,8 @@ private slots:
QFile::remove(m_largePath);
QFile::remove(m_imgPath);
QFile::remove(m_relImgPath);
QFile::remove(m_coverPath);
QFile::remove(m_coverSubdirPath);
}
// --- Phase 2: error handling ---
@@ -479,8 +569,9 @@ private slots:
const Chapter ch = reader.loadChapter(0);
QVERIFY(!ch.contentChunks.isEmpty());
const QString combined = ch.contentChunks.join('\n');
QVERIFY2(combined.contains(QStringLiteral("image://epub/OEBPS/Images/test.png")),
qPrintable(QStringLiteral("Expected image://epub/OEBPS/Images/test.png in: ") + combined));
const QString expected = QStringLiteral("image://epub/OEBPS/Images/test.png");
QVERIFY2(combined.contains(expected),
qPrintable(QStringLiteral("Expected ") + expected + QStringLiteral(" in: ") + combined));
}
void relativeImagePathResolved()
@@ -490,8 +581,32 @@ private slots:
const Chapter ch = reader.loadChapter(0);
QVERIFY(!ch.contentChunks.isEmpty());
const QString combined = ch.contentChunks.join('\n');
QVERIFY2(combined.contains(QStringLiteral("image://epub/OEBPS/Images/test.png")),
qPrintable(QStringLiteral("Expected image://epub/OEBPS/Images/test.png in: ") + combined));
const QString expected = QStringLiteral("image://epub/OEBPS/Images/test.png");
QVERIFY2(combined.contains(expected),
qPrintable(QStringLiteral("Expected ") + expected + QStringLiteral(" in: ") + combined));
}
// --- Phase 8: cover image detection ---
void coverImagePathExtracted()
{
EpubReader reader;
QVERIFY(reader.open(m_coverPath));
QCOMPARE(reader.coverImagePath(), QStringLiteral("OEBPS/cover.jpg"));
}
void coverImagePathWithSubdirectory()
{
EpubReader reader;
QVERIFY(reader.open(m_coverSubdirPath));
QCOMPARE(reader.coverImagePath(), QStringLiteral("OEBPS/Images/cover.jpg"));
}
void coverImagePathEmptyForEpubWithoutCover()
{
EpubReader reader;
QVERIFY(reader.open(m_epubPath));
QVERIFY(reader.coverImagePath().isEmpty());
}
};