From 21656a3e9c0bca455cac6561aa01c1647da8e8bb Mon Sep 17 00:00:00 2001 From: Agel Date: Sun, 15 Mar 2026 22:18:26 +0100 Subject: [PATCH] added txt support --- .claude/settings.local.json | 3 +- CLAUDE.md | 68 +++--------------- README.md | 115 ++++++++++++++++++++++++++++++ src/backend/FormatReader.h | 3 +- src/backend/ReadingModel.cpp | 65 +++++++++++------ src/backend/ReadingModel.h | 20 ++++-- src/backend/formats/TxtReader.cpp | 84 +++++++++++++++++++--- src/qml/components/PageView.qml | 30 ++++---- tests/ReadingModelTest.cpp | 71 ++++++++++++++++-- tests/formats/TxtReaderTest.cpp | 102 ++++++++++++++++++++++++-- 10 files changed, 441 insertions(+), 120 deletions(-) create mode 100644 README.md diff --git a/.claude/settings.local.json b/.claude/settings.local.json index c4f038e..5d37486 100644 --- a/.claude/settings.local.json +++ b/.claude/settings.local.json @@ -9,7 +9,8 @@ "Read(//home/agel/Src/asteria/asteria-bookreader/src/components/**)", "Bash(done)", "Bash(ctest:*)", - "Bash(grep:*)" + "Bash(grep:*)", + "Bash(./build/ReadingModelTest 2>&1)" ] } } diff --git a/CLAUDE.md b/CLAUDE.md index 16eb48b..805a266 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -35,57 +35,9 @@ Full target format list (derived from actual library inventory): > ACSM files are Adobe DRM tokens — not directly readable; skip. > PPT/XLS and source code files (.py, .cs, etc.) are in the library from programming books; no need to render them. -## Installing Dependencies +## Build & Install -### Linux (Ubuntu/Debian) - -```bash -sudo scripts/install-deps-ubuntu.sh -``` - -Installs: Qt6 dev packages (base, QML/Quick, PDF, SVG, shader tools), uchardet, QuaZip, minizip, DjVuLibre, libwpd. - -> **Current status:** Qt6 runtime (6.4.2) is present but dev headers are not yet installed. Run the script above before attempting to build. - -### Windows - -Run in an elevated PowerShell: - -```powershell -scripts\install-deps-windows.ps1 -``` - -Installs: VS Build Tools 2022, CMake, Ninja, Git, vcpkg, and third-party libs via vcpkg. **Qt 6 must be installed manually** via the Qt Online Installer (qt.io/download-open-source) — select MSVC 2022 64-bit + Qt PDF + Qt SVG. - -After Qt is installed, pass its path to CMake: - -```powershell -cmake -B build -DCMAKE_PREFIX_PATH="C:\Qt\6.x.x\msvc2022_64" ` - -DCMAKE_TOOLCHAIN_FILE="C:\vcpkg\scripts\buildsystems\vcpkg.cmake" -``` - -## Build - -```bash -# Configure (Linux — Qt6 found automatically after running install script) -cmake -B build -DCMAKE_BUILD_TYPE=Debug - -# Build -cmake --build build --parallel - -# Run -./build/asteria-qt # Linux -./build/asteria-qt.exe # Windows - -# Release -cmake -B build-release -DCMAKE_BUILD_TYPE=Release -cmake --build build-release --parallel -``` - -Tests: -```bash -ctest --test-dir build --output-on-failure -``` +See [README.md](README.md) for setup instructions, dependency installation, and IDE-specific build guides. ## Test-Driven Development @@ -114,14 +66,14 @@ ctest --test-dir build --output-on-failure | Object | Responsibility | |---|---| | `BookController` | Open/close book, owns reader (via `ReaderFactory`), exposes metadata (title, author), TOC | -| `ReadingModel` | Current chapter content, 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. The content model is defined in `FormatReader.h`: +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`: ```cpp struct TocEntry { @@ -133,7 +85,7 @@ struct TocEntry { struct Chapter { int index; QString title; - QString contentHtml; // normalized HTML + QStringList contentChunks; // standalone HTML fragments }; ``` @@ -147,7 +99,9 @@ struct Chapter { Chapter mapping by format: TXT = 1 chapter (whole file). FB2 = `
` elements. EPUB = spine items. PDF = outline entries or individual pages. -`PageView.qml` renders one chapter at a time via `Text { textFormat: Text.RichText }`. Pagination within a chapter (if ever needed) is a QML-only concern. +**Chunking:** Each format reader splits content into chunks natively — chunking at the reader level is trivial and reliable compared to splitting arbitrary HTML. TxtReader splits raw text at ~4096 character boundaries (preferring `\n`, falling back to whitespace), then converts each chunk to HTML independently. Each chunk is a standalone HTML fragment (contains its own `

` tags). + +**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. ### Reader Factory @@ -159,7 +113,7 @@ Chapter mapping by format: TXT = 1 chapter (whole file). FB2 = `

` eleme ### Error Handling -`FormatReader::open()` returns `bool`. Failed readers expose `QString lastError()`. `BookController` translates errors to a `QString errorMessage` property + `error(QString)` signal. QML shows an `ErrorBanner.qml` component. Error cases: file not found, unsupported format, corrupt archive, encoding failure, permission denied. +`FormatReader::open()` returns `bool`. Failed readers expose `QString lastError()`. `BookController` translates errors to a `QString errorMessage` property + `error(QString)` signal. QML shows an `ErrorPopup.qml` component. Error cases: file not found, unsupported format, corrupt archive, encoding failure, permission denied. ### File Structure @@ -190,9 +144,9 @@ src/ components/ Header.qml SideBar.qml # Renders TOC from BookController - PageView.qml # Renders chapter HTML from ReadingModel + PageView.qml # ListView-based virtualized rendering of ReadingModel chunks Footer.qml - ErrorBanner.qml # Error display popup + ErrorPopup.qml # Error display popup pages/ StarterPage.qml ReaderPage.qml diff --git a/README.md b/README.md new file mode 100644 index 0000000..e676f90 --- /dev/null +++ b/README.md @@ -0,0 +1,115 @@ +# Asteria Qt + +A cross-platform desktop book/document reader built with Qt6/C++. Reimplementation of [asteria-bookreader](../asteria-bookreader) (Electron/React) using a native Qt stack. + +**Target platforms:** Windows and Linux; macOS planned. + +## Prerequisites + +- **Qt 6.4+** (6.4 minimum for QtPdf; 6.5+ recommended) +- **CMake 3.16+** +- **C++17 compiler** — GCC 10+ or Clang 12+ on Linux; MSVC 2022 on Windows + +## Installing Dependencies + +### Linux (Ubuntu/Debian) + +```bash +sudo scripts/install-deps-ubuntu.sh +``` + +The script installs the following package groups: + +| Group | Packages | Required? | +|---|---|---| +| Qt6 core | `qt6-base-dev`, `qt6-declarative-dev`, `qt6-tools-dev` | Required | +| Qt6 extras | `libqt6svg6-dev`, `qt6-shader-baker` | Required | +| Qt6 PDF | `libqt6pdf6-dev` | Optional (PDF support) | +| Encoding | `libuchardet-dev` | Required (TXT encoding detection) | +| Archive | `libquazip-qt6-dev`, `libminizip-dev` | Required (EPUB/ZIP) | +| DjVu | `libdjvulibre-dev` | Optional (DjVu support) | +| DOC | `libwpd-dev` | Optional (legacy .doc support) | + +After the script runs it prints a CMake verify step — run it to confirm Qt6 is found: + +```bash +cmake --find-package -DNAME=Qt6 -DCOMPILER_ID=GNU -DLANGUAGE=CXX -DMODE=EXIST +``` + +### Windows + +**Step 1 — Install Qt 6 manually** via the Qt Online Installer (qt.io/download-open-source): +- Select component: `Qt 6.x → MSVC 2022 64-bit` +- Also select: `Qt PDF`, `Qt SVG` under the same Qt version + +**Step 2 — Install toolchain and third-party libs** (run in an elevated PowerShell): + +```powershell +scripts\install-deps-windows.ps1 +``` + +Installs: VS Build Tools 2022, CMake, Ninja, Git, vcpkg, and third-party libs (QuaZip, uchardet, DjVuLibre, libwpd) via vcpkg. + +**Step 3 — Configure CMake** with your Qt install path: + +```powershell +cmake -B build -DCMAKE_PREFIX_PATH="C:\Qt\6.x.x\msvc2022_64" ` + -DCMAKE_TOOLCHAIN_FILE="C:\vcpkg\scripts\buildsystems\vcpkg.cmake" +``` + +Replace `6.x.x` with your installed Qt version (e.g. `6.7.2`). + +## Building + +### Command Line + +```bash +# Debug build (Linux — Qt6 found automatically after running install script) +cmake -B build -DCMAKE_BUILD_TYPE=Debug +cmake --build build --parallel + +# Release build +cmake -B build-release -DCMAKE_BUILD_TYPE=Release +cmake --build build-release --parallel + +# Run tests +ctest --test-dir build --output-on-failure +``` + +### Running + +```bash +./build/asteria-qt # Linux +./build/asteria-qt.exe # Windows +``` + +### CLion + +1. Open the project root folder (File → Open) +2. CLion auto-detects `CMakeLists.txt` and configures +3. Select a CMake profile (Debug/Release) in Settings → Build, Execution, Deployment → CMake +4. Build: `Ctrl+F9` / `⌘F9` | Run: `Shift+F10` / `⌃R` +5. On Windows: set `CMAKE_PREFIX_PATH` to your Qt install path in the CMake profile options field + +### VSCode + +1. Install extensions: **C/C++**, **CMake Tools** +2. Open the project root +3. CMake Tools detects `CMakeLists.txt` automatically; select a kit (GCC on Linux, MSVC on Windows) +4. On Windows, add to `.vscode/settings.json`: + ```json + { + "cmake.configureArgs": [ + "-DCMAKE_PREFIX_PATH=C:\\Qt\\6.x.x\\msvc2022_64", + "-DCMAKE_TOOLCHAIN_FILE=C:\\vcpkg\\scripts\\buildsystems\\vcpkg.cmake" + ] + } + ``` +5. Build: `Ctrl+Shift+B` | Run: `F5` (with `launch.json`) or CMake Tools' Run button + +### Qt Creator + +1. File → Open File or Project → select `CMakeLists.txt` +2. Configure the kit (Qt 6 kit must be registered under Edit → Preferences → Kits) +3. Build: `Ctrl+B` / `⌘B` | Run: `Ctrl+R` / `⌘R` +4. On Windows: ensure the Qt 6 MSVC kit is selected diff --git a/src/backend/FormatReader.h b/src/backend/FormatReader.h index cc5394e..6d417c5 100644 --- a/src/backend/FormatReader.h +++ b/src/backend/FormatReader.h @@ -2,6 +2,7 @@ #define FORMATREADER_H #include +#include #include struct TocEntry { @@ -13,7 +14,7 @@ struct TocEntry { struct Chapter { int index; QString title; - QString contentHtml; + QStringList contentChunks; }; class FormatReader { diff --git a/src/backend/ReadingModel.cpp b/src/backend/ReadingModel.cpp index 24f1ef4..f5a6fd3 100644 --- a/src/backend/ReadingModel.cpp +++ b/src/backend/ReadingModel.cpp @@ -2,20 +2,38 @@ #include "FormatReader.h" ReadingModel::ReadingModel(QObject *parent) - : QObject(parent) + : QAbstractListModel(parent) { } +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()); + + return {}; +} + +QHash ReadingModel::roleNames() const +{ + return {{ContentRole, "content"}}; +} + QString ReadingModel::chapterTitle() const { return m_chapterTitle; } -QString ReadingModel::chapterContent() const -{ - return m_chapterContent; -} - int ReadingModel::currentChapter() const { return m_currentChapter; @@ -33,19 +51,28 @@ double ReadingModel::progress() const return static_cast(m_currentChapter + 1) / m_totalChapters; } +void ReadingModel::loadChapterData(int index) +{ + beginResetModel(); + m_chunks.clear(); + m_chapterTitle.clear(); + + if (m_reader && index >= 0 && index < m_totalChapters) { + auto chapter = m_reader->loadChapter(index); + m_chapterTitle = chapter.title; + m_chunks = chapter.contentChunks; + } + + endResetModel(); +} + void ReadingModel::setReader(FormatReader *reader) { m_reader = reader; m_currentChapter = 0; m_totalChapters = reader ? reader->chapterCount() : 0; - m_chapterTitle.clear(); - m_chapterContent.clear(); - if (m_reader && m_totalChapters > 0) { - auto chapter = m_reader->loadChapter(0); - m_chapterTitle = chapter.title; - m_chapterContent = chapter.contentHtml; - } + loadChapterData(0); emit totalChaptersChanged(); emit chapterChanged(); @@ -57,9 +84,7 @@ void ReadingModel::nextChapter() return; m_currentChapter++; - auto chapter = m_reader->loadChapter(m_currentChapter); - m_chapterTitle = chapter.title; - m_chapterContent = chapter.contentHtml; + loadChapterData(m_currentChapter); emit chapterChanged(); } @@ -69,9 +94,7 @@ void ReadingModel::previousChapter() return; m_currentChapter--; - auto chapter = m_reader->loadChapter(m_currentChapter); - m_chapterTitle = chapter.title; - m_chapterContent = chapter.contentHtml; + loadChapterData(m_currentChapter); emit chapterChanged(); } @@ -81,8 +104,6 @@ void ReadingModel::goToChapter(int index) return; m_currentChapter = index; - auto chapter = m_reader->loadChapter(m_currentChapter); - m_chapterTitle = chapter.title; - m_chapterContent = chapter.contentHtml; + loadChapterData(m_currentChapter); emit chapterChanged(); } diff --git a/src/backend/ReadingModel.h b/src/backend/ReadingModel.h index 6cdef9b..1a78f01 100644 --- a/src/backend/ReadingModel.h +++ b/src/backend/ReadingModel.h @@ -1,24 +1,32 @@ #ifndef READINGMODEL_H #define READINGMODEL_H -#include +#include #include +#include class FormatReader; -class ReadingModel : public QObject { +class ReadingModel : public QAbstractListModel { Q_OBJECT Q_PROPERTY(QString chapterTitle READ chapterTitle NOTIFY chapterChanged) - Q_PROPERTY(QString chapterContent READ chapterContent NOTIFY chapterChanged) Q_PROPERTY(int currentChapter READ currentChapter NOTIFY chapterChanged) Q_PROPERTY(int totalChapters READ totalChapters NOTIFY totalChaptersChanged) Q_PROPERTY(double progress READ progress NOTIFY chapterChanged) public: + enum Roles { + ContentRole = Qt::UserRole + 1 + }; + explicit ReadingModel(QObject *parent = nullptr); + // QAbstractListModel overrides + int rowCount(const QModelIndex &parent = QModelIndex()) const override; + QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override; + QHash roleNames() const override; + QString chapterTitle() const; - QString chapterContent() const; int currentChapter() const; int totalChapters() const; double progress() const; @@ -34,11 +42,13 @@ signals: void totalChaptersChanged(); private: + void loadChapterData(int index); + FormatReader *m_reader = nullptr; int m_currentChapter = 0; int m_totalChapters = 0; QString m_chapterTitle; - QString m_chapterContent; + QStringList m_chunks; }; #endif // READINGMODEL_H diff --git a/src/backend/formats/TxtReader.cpp b/src/backend/formats/TxtReader.cpp index 3ef91d9..b777cf8 100644 --- a/src/backend/formats/TxtReader.cpp +++ b/src/backend/formats/TxtReader.cpp @@ -8,6 +8,8 @@ #include #include +static constexpr int kChunkSize = 4096; + static QString decodeWithIconv(const QByteArray &raw, const char *charset) { iconv_t cd = iconv_open("UTF-8", charset); @@ -31,6 +33,69 @@ static QString decodeWithIconv(const QByteArray &raw, const char *charset) return QString::fromUtf8(out); } +// Convert a raw text fragment into HTML paragraphs. +// Splits on blank lines (\n\n+) to create

blocks; +// single newlines within a block become
. +static QString textToHtml(const QString &text) +{ + QString html; + const QStringList blocks = text.split(QRegularExpression("\\n\\n+")); + for (const QString &block : blocks) { + QString escaped = block.toHtmlEscaped().trimmed(); + if (escaped.isEmpty()) + continue; + escaped.replace('\n', QStringLiteral("
\n")); + html += QStringLiteral("

") + escaped + QStringLiteral("

\n"); + } + return html; +} + +// Split raw text into chunks of approximately kChunkSize characters, +// preferring to split at \n boundaries, falling back to whitespace. +static QStringList splitRawText(const QString &content) +{ + QStringList rawChunks; + int pos = 0; + const int len = content.size(); + + while (pos < len) { + if (len - pos <= kChunkSize) { + rawChunks.append(content.mid(pos)); + break; + } + + int end = pos + kChunkSize; + + // Look backward for a newline to split at + int splitAt = -1; + for (int i = end; i > pos; --i) { + if (content.at(i) == '\n') { + splitAt = i + 1; // include the newline in the current chunk + break; + } + } + + // No newline found — fall back to whitespace + if (splitAt < 0) { + for (int i = end; i > pos; --i) { + if (content.at(i).isSpace()) { + splitAt = i + 1; + break; + } + } + } + + // No whitespace either — hard split + if (splitAt < 0) + splitAt = end; + + rawChunks.append(content.mid(pos, splitAt - pos)); + pos = splitAt; + } + + return rawChunks; +} + bool TxtReader::open(const QString &filePath) { QFile file(filePath); @@ -89,18 +154,17 @@ Chapter TxtReader::loadChapter(int index) if (index != 0 || m_content.isEmpty()) return Chapter{index, {}, {}}; - // Split on blank lines to create paragraphs; single newlines become
- QString html; - const QStringList blocks = m_content.split(QRegularExpression("\\n\\n+")); - for (const QString &block : blocks) { - QString escaped = block.toHtmlEscaped().trimmed(); - if (escaped.isEmpty()) - continue; - escaped.replace('\n', QStringLiteral("
\n")); - html += QStringLiteral("

") + escaped + QStringLiteral("

\n"); + QStringList rawChunks = splitRawText(m_content); + QStringList htmlChunks; + htmlChunks.reserve(rawChunks.size()); + + for (const QString &raw : rawChunks) { + QString html = textToHtml(raw); + if (!html.isEmpty()) + htmlChunks.append(html); } - return Chapter{0, m_title, html}; + return Chapter{0, m_title, htmlChunks}; } QList TxtReader::tableOfContents() diff --git a/src/qml/components/PageView.qml b/src/qml/components/PageView.qml index 7293270..fce49ff 100644 --- a/src/qml/components/PageView.qml +++ b/src/qml/components/PageView.qml @@ -8,15 +8,24 @@ Rectangle { GradientStop { position: 1.0; color: Theme.gradientBottom } } - Flickable { + ListView { anchors.fill: parent - anchors.topMargin: 0 - anchors.bottomMargin: 0 anchors.leftMargin: 12 - anchors.rightMargin: 0 - contentHeight: contentText.implicitHeight + model: bookController.hasBook ? readingModel : null + cacheBuffer: 2000 clip: true + delegate: Text { + width: ListView.view.width - 18 + rightPadding: 2 + wrapMode: Text.WrapAtWordBoundaryOrAnywhere + textFormat: Text.RichText + font.pixelSize: 16 + lineHeight: 1.6 + color: Theme.readingText + text: model.content + } + ScrollBar.vertical: ScrollBar { policy: ScrollBar.AsNeeded padding: 0 @@ -31,16 +40,13 @@ Rectangle { } } + // Placeholder when no book is open Text { - id: contentText - width: parent.width - rightPadding: 20 - wrapMode: Text.WrapAtWordBoundaryOrAnywhere - textFormat: Text.RichText + anchors.centerIn: parent + visible: !bookController.hasBook + text: "Open a book to start reading" font.pixelSize: 16 - lineHeight: 1.6 color: Theme.readingText - text: bookController.hasBook ? readingModel.chapterContent : "Open a book to start reading" } } } diff --git a/tests/ReadingModelTest.cpp b/tests/ReadingModelTest.cpp index 8d8cd61..503e9fb 100644 --- a/tests/ReadingModelTest.cpp +++ b/tests/ReadingModelTest.cpp @@ -15,7 +15,8 @@ public: return {index, {}, {}}; return {index, QStringLiteral("Chapter %1").arg(index), - QStringLiteral("

Content %1

").arg(index)}; + {QStringLiteral("

Chunk A of %1

").arg(index), + QStringLiteral("

Chunk B of %1

").arg(index)}}; } QList tableOfContents() override { return {}; } @@ -32,8 +33,8 @@ private slots: ReadingModel model; QCOMPARE(model.totalChapters(), 0); QCOMPARE(model.progress(), 0.0); - QVERIFY(model.chapterContent().isEmpty()); QVERIFY(model.chapterTitle().isEmpty()); + QCOMPARE(model.rowCount(QModelIndex()), 0); } void setReaderLoadsFirstChapter() @@ -45,7 +46,39 @@ private slots: QCOMPARE(model.currentChapter(), 0); QCOMPARE(model.totalChapters(), 3); QCOMPARE(model.chapterTitle(), QStringLiteral("Chapter 0")); - QCOMPARE(model.chapterContent(), QStringLiteral("

Content 0

")); + } + + void rowCountMatchesChunks() + { + ReadingModel model; + FakeReader reader; + model.setReader(&reader); + + QCOMPARE(model.rowCount(QModelIndex()), 2); + } + + void dataReturnsChunkContent() + { + ReadingModel model; + FakeReader reader; + model.setReader(&reader); + + QModelIndex idx0 = model.index(0, 0); + QModelIndex idx1 = model.index(1, 0); + QCOMPARE(model.data(idx0, ReadingModel::ContentRole).toString(), + QStringLiteral("

Chunk A of 0

")); + QCOMPARE(model.data(idx1, ReadingModel::ContentRole).toString(), + QStringLiteral("

Chunk B of 0

")); + } + + void dataInvalidForOutOfRange() + { + ReadingModel model; + FakeReader reader; + model.setReader(&reader); + + QModelIndex badIdx = model.index(99, 0); + QVERIFY(!model.data(badIdx, ReadingModel::ContentRole).isValid()); } void nextChapter() @@ -60,6 +93,9 @@ private slots: QCOMPARE(model.currentChapter(), 1); QCOMPARE(model.chapterTitle(), QStringLiteral("Chapter 1")); QCOMPARE(spy.count(), 1); + QCOMPARE(model.rowCount(QModelIndex()), 2); + QCOMPARE(model.data(model.index(0, 0), ReadingModel::ContentRole).toString(), + QStringLiteral("

Chunk A of 1

")); } void nextChapterAtEnd() @@ -112,7 +148,9 @@ private slots: model.goToChapter(2); QCOMPARE(model.currentChapter(), 2); - QCOMPARE(model.chapterContent(), QStringLiteral("

Content 2

")); + QCOMPARE(model.rowCount(QModelIndex()), 2); + QCOMPARE(model.data(model.index(0, 0), ReadingModel::ContentRole).toString(), + QStringLiteral("

Chunk A of 2

")); } void goToChapterOutOfRange() @@ -154,8 +192,31 @@ private slots: QCOMPARE(model.totalChapters(), 0); QCOMPARE(model.progress(), 0.0); - QVERIFY(model.chapterContent().isEmpty()); QVERIFY(model.chapterTitle().isEmpty()); + QCOMPARE(model.rowCount(QModelIndex()), 0); + } + + void navigationResetsModel() + { + ReadingModel model; + FakeReader reader; + model.setReader(&reader); + + QCOMPARE(model.rowCount(QModelIndex()), 2); + + // Navigate and verify model is reset with new chapter's chunks + model.nextChapter(); + QCOMPARE(model.rowCount(QModelIndex()), 2); + QCOMPARE(model.data(model.index(0, 0), ReadingModel::ContentRole).toString(), + QStringLiteral("

Chunk A of 1

")); + } + + void roleNamesContainsContent() + { + ReadingModel model; + QHash roles = model.roleNames(); + QVERIFY(roles.contains(ReadingModel::ContentRole)); + QCOMPARE(roles.value(ReadingModel::ContentRole), QByteArray("content")); } }; diff --git a/tests/formats/TxtReaderTest.cpp b/tests/formats/TxtReaderTest.cpp index c61a0fe..f2c58c4 100644 --- a/tests/formats/TxtReaderTest.cpp +++ b/tests/formats/TxtReaderTest.cpp @@ -26,12 +26,14 @@ private slots: Chapter ch = reader.loadChapter(0); QCOMPARE(ch.index, 0); - QVERIFY(!ch.contentHtml.isEmpty()); - QVERIFY(ch.contentHtml.contains("Books are a uniquely portable magic")); + QVERIFY(!ch.contentChunks.isEmpty()); + // Small file should produce a single chunk + QCOMPARE(ch.contentChunks.size(), 1); + QVERIFY(ch.contentChunks.first().contains("Books are a uniquely portable magic")); // Verify Cyrillic content survived - QVERIFY(ch.contentHtml.contains(QString::fromUtf8("Искусство чтения"))); + QVERIFY(ch.contentChunks.first().contains(QString::fromUtf8("Искусство чтения"))); // Verify HTML paragraph structure - QVERIFY(ch.contentHtml.contains("

")); + QVERIFY(ch.contentChunks.first().contains("

")); } void tableOfContentsEmpty() @@ -61,7 +63,7 @@ private slots: reader.open(fixturePath("sample.txt")); Chapter ch = reader.loadChapter(1); - QVERIFY(ch.contentHtml.isEmpty()); + QVERIFY(ch.contentChunks.isEmpty()); } void openCp1251File() @@ -71,8 +73,94 @@ private slots: QCOMPARE(reader.chapterCount(), 1); Chapter ch = reader.loadChapter(0); - QVERIFY(ch.contentHtml.contains(QString::fromUtf8("Привет, мир!"))); - QVERIFY(ch.contentHtml.contains(QString::fromUtf8("Русская литература"))); + QVERIFY(!ch.contentChunks.isEmpty()); + QString allContent = ch.contentChunks.join(QString()); + QVERIFY(allContent.contains(QString::fromUtf8("Привет, мир!"))); + QVERIFY(allContent.contains(QString::fromUtf8("Русская литература"))); + } + + void largeFileProducesMultipleChunks() + { + // Generate a large file with paragraphs + QTemporaryFile tmpFile; + tmpFile.setAutoRemove(true); + QVERIFY(tmpFile.open()); + + // Write ~20KB of paragraphed text (well above 4096 chunk size) + QString paragraph = QStringLiteral("This is a paragraph of text that has some content. "); + paragraph = paragraph.repeated(10); // ~500 chars per paragraph + for (int i = 0; i < 50; ++i) { + tmpFile.write(paragraph.toUtf8()); + tmpFile.write("\n\n"); + } + tmpFile.close(); + + TxtReader reader; + QVERIFY(reader.open(tmpFile.fileName())); + + Chapter ch = reader.loadChapter(0); + QVERIFY(ch.contentChunks.size() > 1); + // Each chunk should have

tags + for (const QString &chunk : ch.contentChunks) { + QVERIFY(chunk.contains("

")); + } + } + + void wallOfTextProducesMultipleChunks() + { + // Generate a large file with no blank lines + QTemporaryFile tmpFile; + tmpFile.setAutoRemove(true); + QVERIFY(tmpFile.open()); + + // Write ~20KB of text with single newlines only + QString line = QStringLiteral("This is a line of continuous text without blank lines between them. "); + line = line.repeated(5); // ~340 chars per line + for (int i = 0; i < 80; ++i) { + tmpFile.write(line.toUtf8()); + tmpFile.write("\n"); + } + tmpFile.close(); + + TxtReader reader; + QVERIFY(reader.open(tmpFile.fileName())); + + Chapter ch = reader.loadChapter(0); + QVERIFY(ch.contentChunks.size() > 1); + // Each chunk should be standalone HTML + for (const QString &chunk : ch.contentChunks) { + QVERIFY(chunk.contains("

")); + } + } + + void eachChunkIsStandaloneHtml() + { + // Generate a large file + QTemporaryFile tmpFile; + tmpFile.setAutoRemove(true); + QVERIFY(tmpFile.open()); + + QString paragraph = QStringLiteral("Test paragraph content here. "); + paragraph = paragraph.repeated(15); + for (int i = 0; i < 40; ++i) { + tmpFile.write(paragraph.toUtf8()); + tmpFile.write("\n\n"); + } + tmpFile.close(); + + TxtReader reader; + QVERIFY(reader.open(tmpFile.fileName())); + + Chapter ch = reader.loadChapter(0); + QVERIFY(ch.contentChunks.size() > 1); + for (const QString &chunk : ch.contentChunks) { + // Every chunk must start with

and end with

+ QString trimmed = chunk.trimmed(); + QVERIFY2(trimmed.startsWith("

"), + qPrintable("Chunk doesn't start with

: " + trimmed.left(50))); + QVERIFY2(trimmed.endsWith("

"), + qPrintable("Chunk doesn't end with

: " + trimmed.right(50))); + } } };