a bit of refactor

This commit is contained in:
Agel committed 2026-03-23 22:49:46 +01:00
1 parent 24d0b84aab
commit f84e109a64
19 files changed
+546 -232

No files matched your search

+3
View File
@@ -112,6 +112,9 @@ When `CMakeLists.txt` gains a new `find_package` or `pkg_check_modules` dependen
| `scripts/install-deps-windows.sh` | `pacman` package for Windows host builds | | `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 | | `docker/Dockerfile.build` | `apt` package for CI Linux build; cross-compiled lib for CI Windows cross-build if needed |
## Architecture
Strictly follow SOLID principles.
## Test-Driven Development ## Test-Driven Development
**All new backend logic must be test-driven.** Follow the red-green-refactor cycle strictly: **All new backend logic must be test-driven.** Follow the red-green-refactor cycle strictly:
+16 -4
View File
@@ -40,6 +40,13 @@ set(SOURCES
src/backend/ReadingModel.cpp src/backend/ReadingModel.cpp
src/backend/BookController.h src/backend/BookController.h
src/backend/BookController.cpp src/backend/BookController.cpp
src/backend/IFileDialogService.h
src/backend/IFileDialogService.cpp
src/backend/NativeFileDialogService.h
src/backend/NativeFileDialogService.cpp
src/backend/IChunkMeasurer.h
src/backend/QDocumentChunkMeasurer.h
src/backend/QDocumentChunkMeasurer.cpp
src/backend/formats/TxtReader.h src/backend/formats/TxtReader.h
src/backend/formats/TxtReader.cpp src/backend/formats/TxtReader.cpp
src/backend/formats/EpubReader.h src/backend/formats/EpubReader.h
@@ -83,6 +90,9 @@ endif()
if(Qt6DBus_FOUND) if(Qt6DBus_FOUND)
target_link_libraries(asteria-qt PRIVATE Qt6::DBus) target_link_libraries(asteria-qt PRIVATE Qt6::DBus)
target_compile_definitions(asteria-qt PRIVATE HAS_QT_DBUS) target_compile_definitions(asteria-qt PRIVATE HAS_QT_DBUS)
target_sources(asteria-qt PRIVATE
src/backend/PortalFileDialogService.h
src/backend/PortalFileDialogService.cpp)
endif() endif()
target_link_libraries(asteria-qt PRIVATE PkgConfig::UCHARDET) target_link_libraries(asteria-qt PRIVATE PkgConfig::UCHARDET)
@@ -185,6 +195,8 @@ add_asteria_test(BookControllerTest tests/BookControllerTest.cpp
src/backend/AppState.cpp src/backend/AppState.cpp
src/backend/ReaderFactory.cpp src/backend/ReaderFactory.cpp
src/backend/ReadingModel.cpp src/backend/ReadingModel.cpp
src/backend/IFileDialogService.cpp
src/backend/NativeFileDialogService.cpp
src/backend/formats/TxtReader.cpp src/backend/formats/TxtReader.cpp
src/backend/formats/EpubReader.cpp) src/backend/formats/EpubReader.cpp)
add_asteria_test(AppStateTest tests/AppStateTest.cpp add_asteria_test(AppStateTest tests/AppStateTest.cpp
@@ -193,7 +205,7 @@ add_asteria_test(AppStateTest tests/AppStateTest.cpp
target_link_libraries(BookControllerTest PRIVATE Qt6::Widgets PkgConfig::MINIZIP Qt6::Xml) target_link_libraries(BookControllerTest PRIVATE Qt6::Widgets PkgConfig::MINIZIP Qt6::Xml)
set_tests_properties(BookControllerTest PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen") set_tests_properties(BookControllerTest PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen")
if(Qt6DBus_FOUND) add_asteria_test(QDocumentChunkMeasurerTest tests/QDocumentChunkMeasurerTest.cpp
target_link_libraries(BookControllerTest PRIVATE Qt6::DBus) src/backend/QDocumentChunkMeasurer.cpp)
target_compile_definitions(BookControllerTest PRIVATE HAS_QT_DBUS) target_link_libraries(QDocumentChunkMeasurerTest PRIVATE Qt6::Gui)
endif() set_tests_properties(QDocumentChunkMeasurerTest PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen")
+10 -180
View File
@@ -2,71 +2,6 @@
#include "AppState.h" #include "AppState.h"
#include "ReaderFactory.h" #include "ReaderFactory.h"
#include "ReadingModel.h" #include "ReadingModel.h"
#include <QFileDialog>
#ifdef HAS_QT_DBUS
#include <QDBusConnection>
#include <QDBusMessage>
#include <QDBusArgument>
#include <QDBusMetaType>
#include <QRandomGenerator>
// Typed structs so Qt can derive D-Bus signatures without reading a
// write-only QDBusArgument (which causes a SIGSEGV).
struct PortalGlob {
uint type; // 0 = glob pattern
QString pattern;
};
Q_DECLARE_METATYPE(PortalGlob)
QDBusArgument &operator<<(QDBusArgument &a, const PortalGlob &g)
{
a.beginStructure();
a << g.type << g.pattern;
a.endStructure();
return a;
}
const QDBusArgument &operator>>(const QDBusArgument &a, PortalGlob &g)
{
a.beginStructure();
a >> g.type >> g.pattern;
a.endStructure();
return a;
}
struct PortalFilter {
QString name;
QList<PortalGlob> globs;
};
Q_DECLARE_METATYPE(PortalFilter)
QDBusArgument &operator<<(QDBusArgument &a, const PortalFilter &f)
{
a.beginStructure();
a << f.name << f.globs;
a.endStructure();
return a;
}
const QDBusArgument &operator>>(const QDBusArgument &a, PortalFilter &f)
{
a.beginStructure();
a >> f.name >> f.globs;
a.endStructure();
return a;
}
static void registerPortalTypes()
{
static bool done = false;
if (done) return;
done = true;
qDBusRegisterMetaType<PortalGlob>();
qDBusRegisterMetaType<QList<PortalGlob>>();
qDBusRegisterMetaType<PortalFilter>();
qDBusRegisterMetaType<QList<PortalFilter>>();
}
#endif
BookController::BookController(QObject *parent) BookController::BookController(QObject *parent)
: QObject(parent) : QObject(parent)
@@ -120,6 +55,14 @@ void BookController::setAppState(AppState *state)
m_appState = state; m_appState = state;
} }
void BookController::setFileDialogService(IFileDialogService *service)
{
m_fileDialogService = service;
if (m_fileDialogService)
connect(m_fileDialogService, &IFileDialogService::fileSelected,
this, &BookController::openBookFromPath);
}
void BookController::openBookFromPath(const QString &filePath) void BookController::openBookFromPath(const QString &filePath)
{ {
openBook(QUrl::fromLocalFile(filePath)); openBook(QUrl::fromLocalFile(filePath));
@@ -184,121 +127,8 @@ void BookController::openBook(const QUrl &fileUrl)
void BookController::browseAndOpen() void BookController::browseAndOpen()
{ {
#ifdef HAS_QT_DBUS if (m_fileDialogService)
auto bus = QDBusConnection::sessionBus(); m_fileDialogService->open();
if (!bus.isConnected()) {
browseAndOpenFallback();
return;
}
// Check if the FileChooser portal is available
QDBusMessage ping = QDBusMessage::createMethodCall(
QStringLiteral("org.freedesktop.portal.Desktop"),
QStringLiteral("/org/freedesktop/portal/desktop"),
QStringLiteral("org.freedesktop.DBus.Properties"),
QStringLiteral("Get"));
ping << QStringLiteral("org.freedesktop.portal.FileChooser")
<< QStringLiteral("version");
QDBusMessage pong = bus.call(ping, QDBus::Block, 500);
if (pong.type() == QDBusMessage::ErrorMessage) {
browseAndOpenFallback();
return;
}
// Generate a unique handle token and compute the expected response path
QString token = QStringLiteral("asteria_")
+ QString::number(QRandomGenerator::global()->generate());
QString sender = bus.baseService();
sender.remove(0, 1); // strip leading ':'
sender.replace(QLatin1Char('.'), QLatin1Char('_'));
m_portalHandlePath = QStringLiteral("/org/freedesktop/portal/desktop/request/%1/%2")
.arg(sender, token);
// Connect to the Response signal BEFORE making the call (avoids race)
bus.connect(QStringLiteral("org.freedesktop.portal.Desktop"),
m_portalHandlePath,
QStringLiteral("org.freedesktop.portal.Request"),
QStringLiteral("Response"),
this,
SLOT(handlePortalResponse(uint,QVariantMap)));
registerPortalTypes();
// Build file filters using registered types (no raw QDBusArgument in QVariant)
PortalFilter bookFilter;
bookFilter.name = QStringLiteral("Book files");
for (const char *ext : {"*.txt", "*.fb2", "*.epub", "*.pdf", "*.doc",
"*.rtf", "*.html", "*.htm", "*.docx",
"*.djvu", "*.odt", "*.chm"}) {
bookFilter.globs.append({0, QString::fromLatin1(ext)});
}
PortalFilter allFilter;
allFilter.name = QStringLiteral("All files");
allFilter.globs.append({0, QStringLiteral("*")});
QList<PortalFilter> filters{bookFilter, allFilter};
QVariantMap options;
options[QStringLiteral("handle_token")] = token;
options[QStringLiteral("filters")] = QVariant::fromValue(filters);
// Build the OpenFile call
QDBusMessage msg = QDBusMessage::createMethodCall(
QStringLiteral("org.freedesktop.portal.Desktop"),
QStringLiteral("/org/freedesktop/portal/desktop"),
QStringLiteral("org.freedesktop.portal.FileChooser"),
QStringLiteral("OpenFile"));
msg << QString(); // parent_window (empty)
msg << QStringLiteral("Open Book"); // title
msg << options;
QDBusMessage reply = bus.call(msg);
if (reply.type() == QDBusMessage::ErrorMessage) {
bus.disconnect(QStringLiteral("org.freedesktop.portal.Desktop"),
m_portalHandlePath,
QStringLiteral("org.freedesktop.portal.Request"),
QStringLiteral("Response"),
this,
SLOT(handlePortalResponse(uint,QVariantMap)));
browseAndOpenFallback();
}
#else
browseAndOpenFallback();
#endif
}
#ifdef HAS_QT_DBUS
void BookController::handlePortalResponse(uint response,
const QVariantMap &results)
{
QDBusConnection::sessionBus().disconnect(
QStringLiteral("org.freedesktop.portal.Desktop"),
m_portalHandlePath,
QStringLiteral("org.freedesktop.portal.Request"),
QStringLiteral("Response"),
this,
SLOT(handlePortalResponse(uint,QVariantMap)));
if (response != 0)
return; // user cancelled or error
QStringList uris = results.value(QStringLiteral("uris")).toStringList();
if (!uris.isEmpty())
openBook(QUrl(uris.first()));
}
#endif
void BookController::browseAndOpenFallback()
{
QString path = QFileDialog::getOpenFileName(
nullptr,
QStringLiteral("Open Book"),
QString(),
QStringLiteral("Book files (*.txt *.fb2 *.epub *.pdf *.doc *.rtf *.html *.htm *.docx *.djvu *.odt *.chm);;All files (*)"));
if (!path.isEmpty())
openBook(QUrl::fromLocalFile(path));
} }
void BookController::closeBook() void BookController::closeBook()
+3 -10
View File
@@ -8,6 +8,7 @@
#include <memory> #include <memory>
#include "FormatReader.h" #include "FormatReader.h"
#include "IFileDialogService.h"
class AppState; class AppState;
class ReadingModel; class ReadingModel;
@@ -35,6 +36,7 @@ public:
void setReadingModel(ReadingModel *model); void setReadingModel(ReadingModel *model);
void setAppState(AppState *state); void setAppState(AppState *state);
void setFileDialogService(IFileDialogService *service);
Q_INVOKABLE void openBook(const QUrl &fileUrl); Q_INVOKABLE void openBook(const QUrl &fileUrl);
Q_INVOKABLE void openBookFromPath(const QString &filePath); Q_INVOKABLE void openBookFromPath(const QString &filePath);
@@ -49,25 +51,16 @@ signals:
void loadingChanged(); void loadingChanged();
void errorMessageChanged(); void errorMessageChanged();
private slots:
#ifdef HAS_QT_DBUS
void handlePortalResponse(uint response, const QVariantMap &results);
#endif
private: private:
void browseAndOpenFallback();
std::unique_ptr<FormatReader> m_reader; std::unique_ptr<FormatReader> m_reader;
ReadingModel *m_readingModel = nullptr; ReadingModel *m_readingModel = nullptr;
AppState *m_appState = nullptr; AppState *m_appState = nullptr;
IFileDialogService *m_fileDialogService = nullptr;
QString m_bookTitle; QString m_bookTitle;
QString m_bookAuthor; QString m_bookAuthor;
QString m_currentFilePath; QString m_currentFilePath;
bool m_loading = false; bool m_loading = false;
QString m_errorMessage; QString m_errorMessage;
#ifdef HAS_QT_DBUS
QString m_portalHandlePath;
#endif
}; };
#endif // BOOKCONTROLLER_H #endif // BOOKCONTROLLER_H
+14
View File
@@ -0,0 +1,14 @@
#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;
};
#endif // ICHUNKMEASURER_H
+1
View File
@@ -0,0 +1 @@
#include "IFileDialogService.h"
+19
View File
@@ -0,0 +1,19 @@
#ifndef IFILEDIAL0GSERVICE_H
#define IFILEDIAL0GSERVICE_H
#include <QObject>
#include <QString>
class IFileDialogService : public QObject {
Q_OBJECT
public:
explicit IFileDialogService(QObject *parent = nullptr) : QObject(parent) {}
~IFileDialogService() override = default;
virtual void open() = 0;
signals:
void fileSelected(const QString &path);
};
#endif // IFILEDIAL0GSERVICE_H
+18
View File
@@ -0,0 +1,18 @@
#include "NativeFileDialogService.h"
#include <QFileDialog>
NativeFileDialogService::NativeFileDialogService(QObject *parent)
: IFileDialogService(parent)
{
}
void NativeFileDialogService::open()
{
QString path = QFileDialog::getOpenFileName(
nullptr,
QStringLiteral("Open Book"),
QString(),
QStringLiteral("Book files (*.txt *.fb2 *.epub *.pdf *.doc *.rtf *.html *.htm *.docx *.djvu *.odt *.chm);;All files (*)"));
if (!path.isEmpty())
emit fileSelected(path);
}
+13
View File
@@ -0,0 +1,13 @@
#ifndef NATIVEFILEDIALOGSERVICE_H
#define NATIVEFILEDIALOGSERVICE_H
#include "IFileDialogService.h"
class NativeFileDialogService : public IFileDialogService {
Q_OBJECT
public:
explicit NativeFileDialogService(QObject *parent = nullptr);
void open() override;
};
#endif // NATIVEFILEDIALOGSERVICE_H
+155
View File
@@ -0,0 +1,155 @@
#ifdef HAS_QT_DBUS
#include "PortalFileDialogService.h"
#include <QDBusConnection>
#include <QDBusMessage>
#include <QDBusArgument>
#include <QDBusMetaType>
#include <QRandomGenerator>
#include <QUrl>
// Typed structs so Qt can derive D-Bus signatures without reading a
// write-only QDBusArgument (which causes a SIGSEGV).
struct PortalGlob {
uint type; // 0 = glob pattern
QString pattern;
};
Q_DECLARE_METATYPE(PortalGlob)
QDBusArgument &operator<<(QDBusArgument &a, const PortalGlob &g)
{
a.beginStructure();
a << g.type << g.pattern;
a.endStructure();
return a;
}
const QDBusArgument &operator>>(const QDBusArgument &a, PortalGlob &g)
{
a.beginStructure();
a >> g.type >> g.pattern;
a.endStructure();
return a;
}
struct PortalFilter {
QString name;
QList<PortalGlob> globs;
};
Q_DECLARE_METATYPE(PortalFilter)
QDBusArgument &operator<<(QDBusArgument &a, const PortalFilter &f)
{
a.beginStructure();
a << f.name << f.globs;
a.endStructure();
return a;
}
const QDBusArgument &operator>>(const QDBusArgument &a, PortalFilter &f)
{
a.beginStructure();
a >> f.name >> f.globs;
a.endStructure();
return a;
}
static void registerPortalTypes()
{
static bool done = false;
if (done) return;
done = true;
qDBusRegisterMetaType<PortalGlob>();
qDBusRegisterMetaType<QList<PortalGlob>>();
qDBusRegisterMetaType<PortalFilter>();
qDBusRegisterMetaType<QList<PortalFilter>>();
}
PortalFileDialogService::PortalFileDialogService(QObject *parent)
: IFileDialogService(parent)
{
}
void PortalFileDialogService::open()
{
auto bus = QDBusConnection::sessionBus();
// Generate a unique handle token and compute the expected response path
QString token = QStringLiteral("asteria_")
+ QString::number(QRandomGenerator::global()->generate());
QString sender = bus.baseService();
sender.remove(0, 1); // strip leading ':'
sender.replace(QLatin1Char('.'), QLatin1Char('_'));
m_portalHandlePath = QStringLiteral("/org/freedesktop/portal/desktop/request/%1/%2")
.arg(sender, token);
// Connect to the Response signal BEFORE making the call (avoids race)
bus.connect(QStringLiteral("org.freedesktop.portal.Desktop"),
m_portalHandlePath,
QStringLiteral("org.freedesktop.portal.Request"),
QStringLiteral("Response"),
this,
SLOT(handlePortalResponse(uint,QVariantMap)));
registerPortalTypes();
// Build file filters using registered types (no raw QDBusArgument in QVariant)
PortalFilter bookFilter;
bookFilter.name = QStringLiteral("Book files");
for (const char *ext : {"*.txt", "*.fb2", "*.epub", "*.pdf", "*.doc",
"*.rtf", "*.html", "*.htm", "*.docx",
"*.djvu", "*.odt", "*.chm"}) {
bookFilter.globs.append({0, QString::fromLatin1(ext)});
}
PortalFilter allFilter;
allFilter.name = QStringLiteral("All files");
allFilter.globs.append({0, QStringLiteral("*")});
QList<PortalFilter> filters{bookFilter, allFilter};
QVariantMap options;
options[QStringLiteral("handle_token")] = token;
options[QStringLiteral("filters")] = QVariant::fromValue(filters);
// Build the OpenFile call
QDBusMessage msg = QDBusMessage::createMethodCall(
QStringLiteral("org.freedesktop.portal.Desktop"),
QStringLiteral("/org/freedesktop/portal/desktop"),
QStringLiteral("org.freedesktop.portal.FileChooser"),
QStringLiteral("OpenFile"));
msg << QString(); // parent_window (empty)
msg << QStringLiteral("Open Book"); // title
msg << options;
QDBusMessage reply = bus.call(msg);
if (reply.type() == QDBusMessage::ErrorMessage) {
bus.disconnect(QStringLiteral("org.freedesktop.portal.Desktop"),
m_portalHandlePath,
QStringLiteral("org.freedesktop.portal.Request"),
QStringLiteral("Response"),
this,
SLOT(handlePortalResponse(uint,QVariantMap)));
}
}
void PortalFileDialogService::handlePortalResponse(uint response,
const QVariantMap &results)
{
QDBusConnection::sessionBus().disconnect(
QStringLiteral("org.freedesktop.portal.Desktop"),
m_portalHandlePath,
QStringLiteral("org.freedesktop.portal.Request"),
QStringLiteral("Response"),
this,
SLOT(handlePortalResponse(uint,QVariantMap)));
if (response != 0)
return; // user cancelled or error
QStringList uris = results.value(QStringLiteral("uris")).toStringList();
if (!uris.isEmpty())
emit fileSelected(QUrl(uris.first()).toLocalFile());
}
#endif // HAS_QT_DBUS
+22
View File
@@ -0,0 +1,22 @@
#ifndef PORTALFILEDIALOGSERVICE_H
#define PORTALFILEDIALOGSERVICE_H
#ifdef HAS_QT_DBUS
#include "IFileDialogService.h"
class PortalFileDialogService : public IFileDialogService {
Q_OBJECT
public:
explicit PortalFileDialogService(QObject *parent = nullptr);
void open() override;
private slots:
void handlePortalResponse(uint response, const QVariantMap &results);
private:
QString m_portalHandlePath;
};
#endif // HAS_QT_DBUS
#endif // PORTALFILEDIALOGSERVICE_H
+41
View File
@@ -0,0 +1,41 @@
#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
@@ -0,0 +1,16 @@
#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
+9 -32
View File
@@ -1,10 +1,6 @@
#include "ReadingModel.h" #include "ReadingModel.h"
#include "FormatReader.h" #include "FormatReader.h"
#include <cmath> #include <cmath>
#include <QTextDocument>
#include <QTextCursor>
#include <QTextBlockFormat>
#include <QFont>
ReadingModel::ReadingModel(QObject *parent) ReadingModel::ReadingModel(QObject *parent)
: QAbstractListModel(parent) : QAbstractListModel(parent)
@@ -74,6 +70,11 @@ int ReadingModel::totalPages() const
return m_totalPages; return m_totalPages;
} }
void ReadingModel::setChunkMeasurer(IChunkMeasurer *measurer)
{
m_chunkMeasurer = measurer;
}
void ReadingModel::setViewportSize(qreal width, qreal height) void ReadingModel::setViewportSize(qreal width, qreal height)
{ {
bool widthChanged = (width != m_viewportWidth); bool widthChanged = (width != m_viewportWidth);
@@ -99,36 +100,12 @@ void ReadingModel::setScrollInfo(int topChunkIndex, qreal offsetInChunk, bool at
void ReadingModel::computeChunkHeights() void ReadingModel::computeChunkHeights()
{ {
// Caller passes effective text width: if (m_chunkMeasurer) {
// chunkListView.width - 18 (scrollbar) - 2 * horizontalMargin (delegate padding) m_chunkHeights = m_chunkMeasurer->measure(m_chunks, m_viewportWidth);
qreal textWidth = m_viewportWidth; } else {
if (textWidth <= 0) m_chunkHeights.assign(m_chunks.size(), 0.0);
textWidth = 1;
QFont font;
font.setPixelSize(16);
QTextDocument doc;
doc.setDefaultFont(font);
m_chunkHeights.clear();
m_chunkHeights.reserve(m_chunks.size());
for (const QString &chunk : m_chunks) {
doc.setHtml(chunk);
doc.setTextWidth(textWidth);
// Apply lineHeight: 1.6 (matching QML Text lineHeight property)
QTextBlockFormat fmt;
fmt.setLineHeight(160, QTextBlockFormat::ProportionalHeight);
QTextCursor cursor(&doc);
cursor.select(QTextCursor::Document);
cursor.mergeBlockFormat(fmt);
m_chunkHeights.append(doc.size().height());
} }
// Build prefix sums
m_chunkOffsets.clear(); m_chunkOffsets.clear();
m_chunkOffsets.reserve(m_chunks.size()); m_chunkOffsets.reserve(m_chunks.size());
qreal offset = 0; qreal offset = 0;
+4
View File
@@ -6,6 +6,8 @@
#include <QStringList> #include <QStringList>
#include <QVector> #include <QVector>
#include "IChunkMeasurer.h"
class FormatReader; class FormatReader;
class ReadingModel : public QAbstractListModel { class ReadingModel : public QAbstractListModel {
@@ -38,6 +40,7 @@ public:
int totalPages() const; int totalPages() const;
bool hasChapters() const; bool hasChapters() const;
void setReader(FormatReader *reader); void setReader(FormatReader *reader);
void setChunkMeasurer(IChunkMeasurer *measurer);
// Called from QML on resize // Called from QML on resize
Q_INVOKABLE void setViewportSize(qreal width, qreal height); Q_INVOKABLE void setViewportSize(qreal width, qreal height);
@@ -61,6 +64,7 @@ private:
void recalculateCurrentPage(); void recalculateCurrentPage();
FormatReader *m_reader = nullptr; FormatReader *m_reader = nullptr;
IChunkMeasurer *m_chunkMeasurer = nullptr;
int m_currentChapter = 0; int m_currentChapter = 0;
int m_totalChapters = 0; int m_totalChapters = 0;
int m_currentPage = 0; int m_currentPage = 0;
+22
View File
@@ -11,6 +11,13 @@
#include "backend/BookController.h" #include "backend/BookController.h"
#include "backend/ReadingModel.h" #include "backend/ReadingModel.h"
#include "backend/AppState.h" #include "backend/AppState.h"
#include "backend/QDocumentChunkMeasurer.h"
#include "backend/NativeFileDialogService.h"
#ifdef HAS_QT_DBUS
#include <QDBusConnection>
#include "backend/PortalFileDialogService.h"
#endif
void myMessageHandler(const QtMsgType type, const QMessageLogContext &context, const QString &msg) void myMessageHandler(const QtMsgType type, const QMessageLogContext &context, const QString &msg)
{ {
@@ -71,7 +78,10 @@ int main(int argc, char *argv[])
QQuickStyle::setStyle(QStringLiteral("Basic")); QQuickStyle::setStyle(QStringLiteral("Basic"));
QDocumentChunkMeasurer chunkMeasurer(16, 160.0);
ReadingModel readingModel; ReadingModel readingModel;
readingModel.setChunkMeasurer(&chunkMeasurer);
BookController bookController; BookController bookController;
bookController.setReadingModel(&readingModel); bookController.setReadingModel(&readingModel);
@@ -80,6 +90,18 @@ int main(int argc, char *argv[])
appState.restore(); appState.restore();
bookController.setAppState(&appState); bookController.setAppState(&appState);
#ifdef HAS_QT_DBUS
IFileDialogService *fileDialogService;
if (QDBusConnection::sessionBus().isConnected()) {
fileDialogService = new PortalFileDialogService(&bookController);
} else {
fileDialogService = new NativeFileDialogService(&bookController);
}
#else
IFileDialogService *fileDialogService = new NativeFileDialogService(&bookController);
#endif
bookController.setFileDialogService(fileDialogService);
if (const QStringList args = QCoreApplication::arguments(); args.size() > 1) { if (const QStringList args = QCoreApplication::arguments(); args.size() > 1) {
const QString& filePath = args.at(1); const QString& filePath = args.at(1);
if (QFileInfo::exists(filePath)) if (QFileInfo::exists(filePath))
+47
View File
@@ -5,6 +5,19 @@
#include "backend/BookController.h" #include "backend/BookController.h"
#include "backend/ReadingModel.h" #include "backend/ReadingModel.h"
#include "backend/AppState.h" #include "backend/AppState.h"
#include "backend/IFileDialogService.h"
class FakeFileDialogService : public IFileDialogService {
Q_OBJECT
public:
explicit FakeFileDialogService(QObject *parent = nullptr)
: IFileDialogService(parent) {}
void open() override { openCalled = true; }
void simulateSelection(const QString &path) { emit fileSelected(path); }
bool openCalled = false;
};
class BookControllerTest : public QObject { class BookControllerTest : public QObject {
Q_OBJECT Q_OBJECT
@@ -156,6 +169,40 @@ private slots:
QVERIFY(pos.contains("chapter")); QVERIFY(pos.contains("chapter"));
QCOMPARE(pos["chapter"].toInt(), 0); QCOMPARE(pos["chapter"].toInt(), 0);
} }
// IFileDialogService tests
void browseAndOpenCallsServiceOpen()
{
BookController ctrl;
FakeFileDialogService svc;
ctrl.setFileDialogService(&svc);
ctrl.browseAndOpen();
QVERIFY(svc.openCalled);
}
void browseAndOpenUsesService()
{
BookController ctrl;
FakeFileDialogService svc;
ctrl.setFileDialogService(&svc);
QSignalSpy readySpy(&ctrl, &BookController::bookReady);
svc.simulateSelection(fixturePath("sample.txt"));
QCOMPARE(readySpy.count(), 1);
QVERIFY(ctrl.hasBook());
}
void browseAndOpenNoopWhenNoService()
{
BookController ctrl;
// No service set — must not crash
ctrl.browseAndOpen();
QVERIFY(!ctrl.hasBook());
}
}; };
QTEST_MAIN(BookControllerTest) QTEST_MAIN(BookControllerTest)
+53
View File
@@ -0,0 +1,53 @@
#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"
+80 -6
View File
@@ -2,6 +2,7 @@
#include <QSignalSpy> #include <QSignalSpy>
#include "backend/ReadingModel.h" #include "backend/ReadingModel.h"
#include "backend/FormatReader.h" #include "backend/FormatReader.h"
#include "backend/IChunkMeasurer.h"
class SingleChapterReader : public FormatReader { class SingleChapterReader : public FormatReader {
public: public:
@@ -35,6 +36,25 @@ public:
QString author() override { return QStringLiteral("Fake Author"); } QString author() override { return QStringLiteral("Fake Author"); }
}; };
// Returns a fixed height for every chunk regardless of width.
class FakeChunkMeasurer : public IChunkMeasurer {
public:
explicit FakeChunkMeasurer(qreal fixedHeight = 100.0) : m_fixedHeight(fixedHeight) {}
QVector<qreal> measure(const QStringList &chunks, qreal textWidth) const override
{
lastTextWidth = textWidth;
QVector<qreal> heights;
heights.reserve(chunks.size());
for (int i = 0; i < chunks.size(); ++i)
heights.append(m_fixedHeight);
return heights;
}
qreal m_fixedHeight;
mutable qreal lastTextWidth = 0.0;
};
class ReadingModelTest : public QObject { class ReadingModelTest : public QObject {
Q_OBJECT Q_OBJECT
@@ -231,6 +251,7 @@ private slots:
} }
// Page calculation tests // Page calculation tests
void initialPageState() void initialPageState()
{ {
ReadingModel model; ReadingModel model;
@@ -242,6 +263,8 @@ private slots:
{ {
ReadingModel model; ReadingModel model;
FakeReader reader; FakeReader reader;
FakeChunkMeasurer measurer;
model.setChunkMeasurer(&measurer);
model.setReader(&reader); model.setReader(&reader);
model.setViewportSize(0, 0); model.setViewportSize(0, 0);
QCOMPARE(model.totalPages(), 0); QCOMPARE(model.totalPages(), 0);
@@ -252,6 +275,8 @@ private slots:
{ {
ReadingModel model; ReadingModel model;
FakeReader reader; FakeReader reader;
FakeChunkMeasurer measurer(100.0); // 2 chunks × 100px = 200px total
model.setChunkMeasurer(&measurer);
model.setReader(&reader); model.setReader(&reader);
model.setViewportSize(800, 600); model.setViewportSize(800, 600);
QVERIFY(model.totalPages() > 0); QVERIFY(model.totalPages() > 0);
@@ -262,6 +287,8 @@ private slots:
{ {
ReadingModel model; ReadingModel model;
FakeReader reader; FakeReader reader;
FakeChunkMeasurer measurer(100.0);
model.setChunkMeasurer(&measurer);
model.setReader(&reader); model.setReader(&reader);
model.setViewportSize(800, 600); model.setViewportSize(800, 600);
model.setScrollInfo(0, 0); model.setScrollInfo(0, 0);
@@ -272,6 +299,8 @@ private slots:
{ {
ReadingModel model; ReadingModel model;
FakeReader reader; FakeReader reader;
FakeChunkMeasurer measurer(100.0);
model.setChunkMeasurer(&measurer);
model.setReader(&reader); model.setReader(&reader);
model.setViewportSize(800, 600); model.setViewportSize(800, 600);
model.setScrollInfo(0, 0); model.setScrollInfo(0, 0);
@@ -282,6 +311,8 @@ private slots:
{ {
ReadingModel model; ReadingModel model;
FakeReader reader; FakeReader reader;
FakeChunkMeasurer measurer(100.0);
model.setChunkMeasurer(&measurer);
model.setReader(&reader); model.setReader(&reader);
model.setViewportSize(800, 600); model.setViewportSize(800, 600);
// Scroll to last chunk with huge offset // Scroll to last chunk with huge offset
@@ -293,6 +324,8 @@ private slots:
{ {
ReadingModel model; ReadingModel model;
FakeReader reader; FakeReader reader;
FakeChunkMeasurer measurer(100.0);
model.setChunkMeasurer(&measurer);
model.setReader(&reader); model.setReader(&reader);
model.setViewportSize(800, 600); model.setViewportSize(800, 600);
int pages = model.totalPages(); int pages = model.totalPages();
@@ -306,6 +339,8 @@ private slots:
{ {
ReadingModel model; ReadingModel model;
FakeReader reader; FakeReader reader;
FakeChunkMeasurer measurer(100.0);
model.setChunkMeasurer(&measurer);
model.setReader(&reader); model.setReader(&reader);
model.setViewportSize(800, 600); model.setViewportSize(800, 600);
model.setScrollInfo(0, 50); model.setScrollInfo(0, 50);
@@ -321,29 +356,33 @@ private slots:
{ {
ReadingModel model; ReadingModel model;
FakeReader reader; FakeReader reader;
FakeChunkMeasurer measurer(100.0);
model.setChunkMeasurer(&measurer);
model.setReader(&reader); model.setReader(&reader);
model.setViewportSize(800, 600); model.setViewportSize(800, 600);
int pages800 = model.totalPages(); int pages800 = model.totalPages();
// Narrower viewport → chunks taller → more pages // Narrower viewport (FakeChunkMeasurer returns same heights, so pages >=)
model.setViewportSize(400, 600); model.setViewportSize(400, 600);
QVERIFY(model.totalPages() >= pages800); QVERIFY(model.totalPages() >= pages800);
// Shorter viewport (same width) → more pages // Shorter viewport → more pages
model.setViewportSize(400, 300); model.setViewportSize(400, 50); // 200px content / 50px viewport = 4 pages
QVERIFY(model.totalPages() > 0); QVERIFY(model.totalPages() > 0);
} }
void setScrollInfoAdvancesMonotonically() void setScrollInfoAdvancesMonotonically()
{ {
// Build a FakeReader with many chunks so we can scroll across pages // tiny viewport to guarantee multiple pages
ReadingModel model; ReadingModel model;
FakeReader reader; FakeReader reader;
FakeChunkMeasurer measurer(100.0); // 2 chunks × 100px = 200px total
model.setChunkMeasurer(&measurer);
model.setReader(&reader); model.setReader(&reader);
model.setViewportSize(800, 5); // tiny viewport to guarantee multiple pages model.setViewportSize(800, 5); // 200px / 5px = 40 pages
QVERIFY(model.totalPages() > 1); QVERIFY(model.totalPages() > 1);
// chunk 0 at offset 0 → page 1 // chunk 0 at offset 0 → page 1
model.setScrollInfo(0, 0); model.setScrollInfo(0, 0);
int firstPage = model.currentPage(); int firstPage = model.currentPage();
// chunk 1 at offset 0 → page ≥ firstPage // chunk 1 at offset 0 → page 21 (offset 100 / 5 + 1)
model.setScrollInfo(1, 0); model.setScrollInfo(1, 0);
int secondPage = model.currentPage(); int secondPage = model.currentPage();
QVERIFY(secondPage >= firstPage); QVERIFY(secondPage >= firstPage);
@@ -372,6 +411,41 @@ private slots:
ReadingModel model; ReadingModel model;
QVERIFY(!model.hasChapters()); QVERIFY(!model.hasChapters());
} }
// IChunkMeasurer interface tests
void chunkMeasurerIsUsedForHeights()
{
ReadingModel model;
FakeReader reader;
FakeChunkMeasurer measurer(100.0); // 2 chunks × 100px = 200px
model.setChunkMeasurer(&measurer);
model.setReader(&reader);
model.setViewportSize(800, 600);
// totalPages = ceil(200 / 600) = 1
QCOMPARE(model.totalPages(), 1);
}
void chunkMeasurerNotSetGivesZeroPages()
{
ReadingModel model;
FakeReader reader;
// No measurer → heights are 0 → totalPages = 0
model.setReader(&reader);
model.setViewportSize(800, 600);
QCOMPARE(model.totalPages(), 0);
}
void chunkMeasurerReceivesViewportWidth()
{
ReadingModel model;
FakeReader reader;
FakeChunkMeasurer measurer(50.0);
model.setChunkMeasurer(&measurer);
model.setReader(&reader);
model.setViewportSize(500, 600);
QCOMPARE(measurer.lastTextWidth, 500.0);
}
}; };
QTEST_MAIN(ReadingModelTest) QTEST_MAIN(ReadingModelTest)