added txt support

This commit is contained in:
Agel committed 2026-03-15 22:18:26 +01:00
1 parent 64a70bc4cf
commit 21656a3e9c
10 files changed
+441 -120

No files matched your search

+2 -1
View File
@@ -9,7 +9,8 @@
"Read(//home/agel/Src/asteria/asteria-bookreader/src/components/**)", "Read(//home/agel/Src/asteria/asteria-bookreader/src/components/**)",
"Bash(done)", "Bash(done)",
"Bash(ctest:*)", "Bash(ctest:*)",
"Bash(grep:*)" "Bash(grep:*)",
"Bash(./build/ReadingModelTest 2>&1)"
] ]
} }
} }
+11 -57
View File
@@ -35,57 +35,9 @@ Full target format list (derived from actual library inventory):
> ACSM files are Adobe DRM tokens — not directly readable; skip. > 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. > 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) See [README.md](README.md) for setup instructions, dependency installation, and IDE-specific build guides.
```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
```
## Test-Driven Development ## Test-Driven Development
@@ -114,14 +66,14 @@ ctest --test-dir build --output-on-failure
| Object | Responsibility | | Object | Responsibility |
|---|---| |---|---|
| `BookController` | Open/close book, owns reader (via `ReaderFactory`), exposes metadata (title, author), TOC | | `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`) | | `AppState` | Window geometry, last file, preferences (`QSettings`) |
Sidebar state, header state, etc. stay as pure QML properties — no C++ needed. Sidebar state, header state, etc. stay as pure QML properties — no C++ needed.
### Content Model ### 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 ```cpp
struct TocEntry { struct TocEntry {
@@ -133,7 +85,7 @@ struct TocEntry {
struct Chapter { struct Chapter {
int index; int index;
QString title; 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 = `<section>` elements. EPUB = spine items. PDF = outline entries or individual pages. Chapter mapping by format: TXT = 1 chapter (whole file). FB2 = `<section>` 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 `<p>` 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 ### Reader Factory
@@ -159,7 +113,7 @@ Chapter mapping by format: TXT = 1 chapter (whole file). FB2 = `<section>` eleme
### Error Handling ### 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 ### File Structure
@@ -190,9 +144,9 @@ src/
components/ components/
Header.qml Header.qml
SideBar.qml # Renders TOC from BookController SideBar.qml # Renders TOC from BookController
PageView.qml # Renders chapter HTML from ReadingModel PageView.qml # ListView-based virtualized rendering of ReadingModel chunks
Footer.qml Footer.qml
ErrorBanner.qml # Error display popup ErrorPopup.qml # Error display popup
pages/ pages/
StarterPage.qml StarterPage.qml
ReaderPage.qml ReaderPage.qml
+115
View File
@@ -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
+2 -1
View File
@@ -2,6 +2,7 @@
#define FORMATREADER_H #define FORMATREADER_H
#include <QString> #include <QString>
#include <QStringList>
#include <QList> #include <QList>
struct TocEntry { struct TocEntry {
@@ -13,7 +14,7 @@ struct TocEntry {
struct Chapter { struct Chapter {
int index; int index;
QString title; QString title;
QString contentHtml; QStringList contentChunks;
}; };
class FormatReader { class FormatReader {
+43 -22
View File
@@ -2,20 +2,38 @@
#include "FormatReader.h" #include "FormatReader.h"
ReadingModel::ReadingModel(QObject *parent) 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<int, QByteArray> ReadingModel::roleNames() const
{
return {{ContentRole, "content"}};
}
QString ReadingModel::chapterTitle() const QString ReadingModel::chapterTitle() const
{ {
return m_chapterTitle; return m_chapterTitle;
} }
QString ReadingModel::chapterContent() const
{
return m_chapterContent;
}
int ReadingModel::currentChapter() const int ReadingModel::currentChapter() const
{ {
return m_currentChapter; return m_currentChapter;
@@ -33,19 +51,28 @@ double ReadingModel::progress() const
return static_cast<double>(m_currentChapter + 1) / m_totalChapters; return static_cast<double>(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) void ReadingModel::setReader(FormatReader *reader)
{ {
m_reader = reader; m_reader = reader;
m_currentChapter = 0; m_currentChapter = 0;
m_totalChapters = reader ? reader->chapterCount() : 0; m_totalChapters = reader ? reader->chapterCount() : 0;
m_chapterTitle.clear();
m_chapterContent.clear();
if (m_reader && m_totalChapters > 0) { loadChapterData(0);
auto chapter = m_reader->loadChapter(0);
m_chapterTitle = chapter.title;
m_chapterContent = chapter.contentHtml;
}
emit totalChaptersChanged(); emit totalChaptersChanged();
emit chapterChanged(); emit chapterChanged();
@@ -57,9 +84,7 @@ void ReadingModel::nextChapter()
return; return;
m_currentChapter++; m_currentChapter++;
auto chapter = m_reader->loadChapter(m_currentChapter); loadChapterData(m_currentChapter);
m_chapterTitle = chapter.title;
m_chapterContent = chapter.contentHtml;
emit chapterChanged(); emit chapterChanged();
} }
@@ -69,9 +94,7 @@ void ReadingModel::previousChapter()
return; return;
m_currentChapter--; m_currentChapter--;
auto chapter = m_reader->loadChapter(m_currentChapter); loadChapterData(m_currentChapter);
m_chapterTitle = chapter.title;
m_chapterContent = chapter.contentHtml;
emit chapterChanged(); emit chapterChanged();
} }
@@ -81,8 +104,6 @@ void ReadingModel::goToChapter(int index)
return; return;
m_currentChapter = index; m_currentChapter = index;
auto chapter = m_reader->loadChapter(m_currentChapter); loadChapterData(m_currentChapter);
m_chapterTitle = chapter.title;
m_chapterContent = chapter.contentHtml;
emit chapterChanged(); emit chapterChanged();
} }
+15 -5
View File
@@ -1,24 +1,32 @@
#ifndef READINGMODEL_H #ifndef READINGMODEL_H
#define READINGMODEL_H #define READINGMODEL_H
#include <QObject> #include <QAbstractListModel>
#include <QString> #include <QString>
#include <QStringList>
class FormatReader; class FormatReader;
class ReadingModel : public QObject { class ReadingModel : public QAbstractListModel {
Q_OBJECT Q_OBJECT
Q_PROPERTY(QString chapterTitle READ chapterTitle NOTIFY chapterChanged) 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 currentChapter READ currentChapter NOTIFY chapterChanged)
Q_PROPERTY(int totalChapters READ totalChapters NOTIFY totalChaptersChanged) Q_PROPERTY(int totalChapters READ totalChapters NOTIFY totalChaptersChanged)
Q_PROPERTY(double progress READ progress NOTIFY chapterChanged) Q_PROPERTY(double progress READ progress NOTIFY chapterChanged)
public: public:
enum Roles {
ContentRole = Qt::UserRole + 1
};
explicit ReadingModel(QObject *parent = nullptr); 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<int, QByteArray> roleNames() const override;
QString chapterTitle() const; QString chapterTitle() const;
QString chapterContent() const;
int currentChapter() const; int currentChapter() const;
int totalChapters() const; int totalChapters() const;
double progress() const; double progress() const;
@@ -34,11 +42,13 @@ signals:
void totalChaptersChanged(); void totalChaptersChanged();
private: private:
void loadChapterData(int index);
FormatReader *m_reader = nullptr; FormatReader *m_reader = nullptr;
int m_currentChapter = 0; int m_currentChapter = 0;
int m_totalChapters = 0; int m_totalChapters = 0;
QString m_chapterTitle; QString m_chapterTitle;
QString m_chapterContent; QStringList m_chunks;
}; };
#endif // READINGMODEL_H #endif // READINGMODEL_H
+74 -10
View File
@@ -8,6 +8,8 @@
#include <uchardet/uchardet.h> #include <uchardet/uchardet.h>
#include <iconv.h> #include <iconv.h>
static constexpr int kChunkSize = 4096;
static QString decodeWithIconv(const QByteArray &raw, const char *charset) static QString decodeWithIconv(const QByteArray &raw, const char *charset)
{ {
iconv_t cd = iconv_open("UTF-8", 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); return QString::fromUtf8(out);
} }
// Convert a raw text fragment into HTML paragraphs.
// Splits on blank lines (\n\n+) to create <p> blocks;
// single newlines within a block become <br>.
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("<br>\n"));
html += QStringLiteral("<p>") + escaped + QStringLiteral("</p>\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) bool TxtReader::open(const QString &filePath)
{ {
QFile file(filePath); QFile file(filePath);
@@ -89,18 +154,17 @@ Chapter TxtReader::loadChapter(int index)
if (index != 0 || m_content.isEmpty()) if (index != 0 || m_content.isEmpty())
return Chapter{index, {}, {}}; return Chapter{index, {}, {}};
// Split on blank lines to create paragraphs; single newlines become <br> QStringList rawChunks = splitRawText(m_content);
QString html; QStringList htmlChunks;
const QStringList blocks = m_content.split(QRegularExpression("\\n\\n+")); htmlChunks.reserve(rawChunks.size());
for (const QString &block : blocks) {
QString escaped = block.toHtmlEscaped().trimmed(); for (const QString &raw : rawChunks) {
if (escaped.isEmpty()) QString html = textToHtml(raw);
continue; if (!html.isEmpty())
escaped.replace('\n', QStringLiteral("<br>\n")); htmlChunks.append(html);
html += QStringLiteral("<p>") + escaped + QStringLiteral("</p>\n");
} }
return Chapter{0, m_title, html}; return Chapter{0, m_title, htmlChunks};
} }
QList<TocEntry> TxtReader::tableOfContents() QList<TocEntry> TxtReader::tableOfContents()
+18 -12
View File
@@ -8,15 +8,24 @@ Rectangle {
GradientStop { position: 1.0; color: Theme.gradientBottom } GradientStop { position: 1.0; color: Theme.gradientBottom }
} }
Flickable { ListView {
anchors.fill: parent anchors.fill: parent
anchors.topMargin: 0
anchors.bottomMargin: 0
anchors.leftMargin: 12 anchors.leftMargin: 12
anchors.rightMargin: 0 model: bookController.hasBook ? readingModel : null
contentHeight: contentText.implicitHeight cacheBuffer: 2000
clip: true 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 { ScrollBar.vertical: ScrollBar {
policy: ScrollBar.AsNeeded policy: ScrollBar.AsNeeded
padding: 0 padding: 0
@@ -31,16 +40,13 @@ Rectangle {
} }
} }
// Placeholder when no book is open
Text { Text {
id: contentText anchors.centerIn: parent
width: parent.width visible: !bookController.hasBook
rightPadding: 20 text: "Open a book to start reading"
wrapMode: Text.WrapAtWordBoundaryOrAnywhere
textFormat: Text.RichText
font.pixelSize: 16 font.pixelSize: 16
lineHeight: 1.6
color: Theme.readingText color: Theme.readingText
text: bookController.hasBook ? readingModel.chapterContent : "Open a book to start reading"
} }
} }
} }
+66 -5
View File
@@ -15,7 +15,8 @@ public:
return {index, {}, {}}; return {index, {}, {}};
return {index, return {index,
QStringLiteral("Chapter %1").arg(index), QStringLiteral("Chapter %1").arg(index),
QStringLiteral("<p>Content %1</p>").arg(index)}; {QStringLiteral("<p>Chunk A of %1</p>").arg(index),
QStringLiteral("<p>Chunk B of %1</p>").arg(index)}};
} }
QList<TocEntry> tableOfContents() override { return {}; } QList<TocEntry> tableOfContents() override { return {}; }
@@ -32,8 +33,8 @@ private slots:
ReadingModel model; ReadingModel model;
QCOMPARE(model.totalChapters(), 0); QCOMPARE(model.totalChapters(), 0);
QCOMPARE(model.progress(), 0.0); QCOMPARE(model.progress(), 0.0);
QVERIFY(model.chapterContent().isEmpty());
QVERIFY(model.chapterTitle().isEmpty()); QVERIFY(model.chapterTitle().isEmpty());
QCOMPARE(model.rowCount(QModelIndex()), 0);
} }
void setReaderLoadsFirstChapter() void setReaderLoadsFirstChapter()
@@ -45,7 +46,39 @@ private slots:
QCOMPARE(model.currentChapter(), 0); QCOMPARE(model.currentChapter(), 0);
QCOMPARE(model.totalChapters(), 3); QCOMPARE(model.totalChapters(), 3);
QCOMPARE(model.chapterTitle(), QStringLiteral("Chapter 0")); QCOMPARE(model.chapterTitle(), QStringLiteral("Chapter 0"));
QCOMPARE(model.chapterContent(), QStringLiteral("<p>Content 0</p>")); }
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("<p>Chunk A of 0</p>"));
QCOMPARE(model.data(idx1, ReadingModel::ContentRole).toString(),
QStringLiteral("<p>Chunk B of 0</p>"));
}
void dataInvalidForOutOfRange()
{
ReadingModel model;
FakeReader reader;
model.setReader(&reader);
QModelIndex badIdx = model.index(99, 0);
QVERIFY(!model.data(badIdx, ReadingModel::ContentRole).isValid());
} }
void nextChapter() void nextChapter()
@@ -60,6 +93,9 @@ private slots:
QCOMPARE(model.currentChapter(), 1); QCOMPARE(model.currentChapter(), 1);
QCOMPARE(model.chapterTitle(), QStringLiteral("Chapter 1")); QCOMPARE(model.chapterTitle(), QStringLiteral("Chapter 1"));
QCOMPARE(spy.count(), 1); QCOMPARE(spy.count(), 1);
QCOMPARE(model.rowCount(QModelIndex()), 2);
QCOMPARE(model.data(model.index(0, 0), ReadingModel::ContentRole).toString(),
QStringLiteral("<p>Chunk A of 1</p>"));
} }
void nextChapterAtEnd() void nextChapterAtEnd()
@@ -112,7 +148,9 @@ private slots:
model.goToChapter(2); model.goToChapter(2);
QCOMPARE(model.currentChapter(), 2); QCOMPARE(model.currentChapter(), 2);
QCOMPARE(model.chapterContent(), QStringLiteral("<p>Content 2</p>")); QCOMPARE(model.rowCount(QModelIndex()), 2);
QCOMPARE(model.data(model.index(0, 0), ReadingModel::ContentRole).toString(),
QStringLiteral("<p>Chunk A of 2</p>"));
} }
void goToChapterOutOfRange() void goToChapterOutOfRange()
@@ -154,8 +192,31 @@ private slots:
QCOMPARE(model.totalChapters(), 0); QCOMPARE(model.totalChapters(), 0);
QCOMPARE(model.progress(), 0.0); QCOMPARE(model.progress(), 0.0);
QVERIFY(model.chapterContent().isEmpty());
QVERIFY(model.chapterTitle().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("<p>Chunk A of 1</p>"));
}
void roleNamesContainsContent()
{
ReadingModel model;
QHash<int, QByteArray> roles = model.roleNames();
QVERIFY(roles.contains(ReadingModel::ContentRole));
QCOMPARE(roles.value(ReadingModel::ContentRole), QByteArray("content"));
} }
}; };
+95 -7
View File
@@ -26,12 +26,14 @@ private slots:
Chapter ch = reader.loadChapter(0); Chapter ch = reader.loadChapter(0);
QCOMPARE(ch.index, 0); QCOMPARE(ch.index, 0);
QVERIFY(!ch.contentHtml.isEmpty()); QVERIFY(!ch.contentChunks.isEmpty());
QVERIFY(ch.contentHtml.contains("Books are a uniquely portable magic")); // 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 // Verify Cyrillic content survived
QVERIFY(ch.contentHtml.contains(QString::fromUtf8("Искусство чтения"))); QVERIFY(ch.contentChunks.first().contains(QString::fromUtf8("Искусство чтения")));
// Verify HTML paragraph structure // Verify HTML paragraph structure
QVERIFY(ch.contentHtml.contains("<p>")); QVERIFY(ch.contentChunks.first().contains("<p>"));
} }
void tableOfContentsEmpty() void tableOfContentsEmpty()
@@ -61,7 +63,7 @@ private slots:
reader.open(fixturePath("sample.txt")); reader.open(fixturePath("sample.txt"));
Chapter ch = reader.loadChapter(1); Chapter ch = reader.loadChapter(1);
QVERIFY(ch.contentHtml.isEmpty()); QVERIFY(ch.contentChunks.isEmpty());
} }
void openCp1251File() void openCp1251File()
@@ -71,8 +73,94 @@ private slots:
QCOMPARE(reader.chapterCount(), 1); QCOMPARE(reader.chapterCount(), 1);
Chapter ch = reader.loadChapter(0); Chapter ch = reader.loadChapter(0);
QVERIFY(ch.contentHtml.contains(QString::fromUtf8("Привет, мир!"))); QVERIFY(!ch.contentChunks.isEmpty());
QVERIFY(ch.contentHtml.contains(QString::fromUtf8("Русская литература"))); 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 <p> tags
for (const QString &chunk : ch.contentChunks) {
QVERIFY(chunk.contains("<p>"));
}
}
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("<p>"));
}
}
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 <p> and end with </p>
QString trimmed = chunk.trimmed();
QVERIFY2(trimmed.startsWith("<p>"),
qPrintable("Chunk doesn't start with <p>: " + trimmed.left(50)));
QVERIFY2(trimmed.endsWith("</p>"),
qPrintable("Chunk doesn't end with </p>: " + trimmed.right(50)));
}
} }
}; };