From f84e109a64e62381f4a2727b040a17e683607b7a Mon Sep 17 00:00:00 2001 From: Agel Date: Mon, 23 Mar 2026 22:49:46 +0100 Subject: [PATCH] a bit of refactor --- CLAUDE.md | 3 + CMakeLists.txt | 20 ++- src/backend/BookController.cpp | 190 ++---------------------- src/backend/BookController.h | 13 +- src/backend/IChunkMeasurer.h | 14 ++ src/backend/IFileDialogService.cpp | 1 + src/backend/IFileDialogService.h | 19 +++ src/backend/NativeFileDialogService.cpp | 18 +++ src/backend/NativeFileDialogService.h | 13 ++ src/backend/PortalFileDialogService.cpp | 155 +++++++++++++++++++ src/backend/PortalFileDialogService.h | 22 +++ src/backend/QDocumentChunkMeasurer.cpp | 41 +++++ src/backend/QDocumentChunkMeasurer.h | 16 ++ src/backend/ReadingModel.cpp | 41 ++--- src/backend/ReadingModel.h | 4 + src/main.cpp | 22 +++ tests/BookControllerTest.cpp | 47 ++++++ tests/QDocumentChunkMeasurerTest.cpp | 53 +++++++ tests/ReadingModelTest.cpp | 86 ++++++++++- 19 files changed, 546 insertions(+), 232 deletions(-) create mode 100644 src/backend/IChunkMeasurer.h create mode 100644 src/backend/IFileDialogService.cpp create mode 100644 src/backend/IFileDialogService.h create mode 100644 src/backend/NativeFileDialogService.cpp create mode 100644 src/backend/NativeFileDialogService.h create mode 100644 src/backend/PortalFileDialogService.cpp create mode 100644 src/backend/PortalFileDialogService.h create mode 100644 src/backend/QDocumentChunkMeasurer.cpp create mode 100644 src/backend/QDocumentChunkMeasurer.h create mode 100644 tests/QDocumentChunkMeasurerTest.cpp diff --git a/CLAUDE.md b/CLAUDE.md index 4602b9b..4e0a396 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -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 | | `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 **All new backend logic must be test-driven.** Follow the red-green-refactor cycle strictly: diff --git a/CMakeLists.txt b/CMakeLists.txt index e406a40..f354091 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -40,6 +40,13 @@ set(SOURCES src/backend/ReadingModel.cpp src/backend/BookController.h 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.cpp src/backend/formats/EpubReader.h @@ -83,6 +90,9 @@ endif() if(Qt6DBus_FOUND) target_link_libraries(asteria-qt PRIVATE Qt6::DBus) target_compile_definitions(asteria-qt PRIVATE HAS_QT_DBUS) + target_sources(asteria-qt PRIVATE + src/backend/PortalFileDialogService.h + src/backend/PortalFileDialogService.cpp) endif() 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/ReaderFactory.cpp src/backend/ReadingModel.cpp + src/backend/IFileDialogService.cpp + src/backend/NativeFileDialogService.cpp src/backend/formats/TxtReader.cpp src/backend/formats/EpubReader.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) set_tests_properties(BookControllerTest PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen") -if(Qt6DBus_FOUND) - target_link_libraries(BookControllerTest PRIVATE Qt6::DBus) - target_compile_definitions(BookControllerTest PRIVATE HAS_QT_DBUS) -endif() +add_asteria_test(QDocumentChunkMeasurerTest tests/QDocumentChunkMeasurerTest.cpp + src/backend/QDocumentChunkMeasurer.cpp) +target_link_libraries(QDocumentChunkMeasurerTest PRIVATE Qt6::Gui) +set_tests_properties(QDocumentChunkMeasurerTest PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen") diff --git a/src/backend/BookController.cpp b/src/backend/BookController.cpp index eb27502..257a1f8 100644 --- a/src/backend/BookController.cpp +++ b/src/backend/BookController.cpp @@ -2,71 +2,6 @@ #include "AppState.h" #include "ReaderFactory.h" #include "ReadingModel.h" -#include - -#ifdef HAS_QT_DBUS -#include -#include -#include -#include -#include - -// 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 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(); - qDBusRegisterMetaType>(); - qDBusRegisterMetaType(); - qDBusRegisterMetaType>(); -} -#endif BookController::BookController(QObject *parent) : QObject(parent) @@ -120,6 +55,14 @@ void BookController::setAppState(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) { openBook(QUrl::fromLocalFile(filePath)); @@ -184,121 +127,8 @@ void BookController::openBook(const QUrl &fileUrl) void BookController::browseAndOpen() { -#ifdef HAS_QT_DBUS - auto bus = QDBusConnection::sessionBus(); - 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 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)); + if (m_fileDialogService) + m_fileDialogService->open(); } void BookController::closeBook() diff --git a/src/backend/BookController.h b/src/backend/BookController.h index ed5d2ae..82038d7 100644 --- a/src/backend/BookController.h +++ b/src/backend/BookController.h @@ -8,6 +8,7 @@ #include #include "FormatReader.h" +#include "IFileDialogService.h" class AppState; class ReadingModel; @@ -35,6 +36,7 @@ public: void setReadingModel(ReadingModel *model); void setAppState(AppState *state); + void setFileDialogService(IFileDialogService *service); Q_INVOKABLE void openBook(const QUrl &fileUrl); Q_INVOKABLE void openBookFromPath(const QString &filePath); @@ -49,25 +51,16 @@ signals: void loadingChanged(); void errorMessageChanged(); -private slots: -#ifdef HAS_QT_DBUS - void handlePortalResponse(uint response, const QVariantMap &results); -#endif - private: - void browseAndOpenFallback(); - std::unique_ptr m_reader; ReadingModel *m_readingModel = nullptr; AppState *m_appState = nullptr; + IFileDialogService *m_fileDialogService = nullptr; QString m_bookTitle; QString m_bookAuthor; QString m_currentFilePath; bool m_loading = false; QString m_errorMessage; -#ifdef HAS_QT_DBUS - QString m_portalHandlePath; -#endif }; #endif // BOOKCONTROLLER_H diff --git a/src/backend/IChunkMeasurer.h b/src/backend/IChunkMeasurer.h new file mode 100644 index 0000000..5338de7 --- /dev/null +++ b/src/backend/IChunkMeasurer.h @@ -0,0 +1,14 @@ +#ifndef ICHUNKMEASURER_H +#define ICHUNKMEASURER_H + +#include +#include +#include + +class IChunkMeasurer { +public: + virtual ~IChunkMeasurer() = default; + virtual QVector measure(const QStringList &chunks, qreal textWidth) const = 0; +}; + +#endif // ICHUNKMEASURER_H diff --git a/src/backend/IFileDialogService.cpp b/src/backend/IFileDialogService.cpp new file mode 100644 index 0000000..98e0f73 --- /dev/null +++ b/src/backend/IFileDialogService.cpp @@ -0,0 +1 @@ +#include "IFileDialogService.h" diff --git a/src/backend/IFileDialogService.h b/src/backend/IFileDialogService.h new file mode 100644 index 0000000..73a65fa --- /dev/null +++ b/src/backend/IFileDialogService.h @@ -0,0 +1,19 @@ +#ifndef IFILEDIAL0GSERVICE_H +#define IFILEDIAL0GSERVICE_H + +#include +#include + +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 diff --git a/src/backend/NativeFileDialogService.cpp b/src/backend/NativeFileDialogService.cpp new file mode 100644 index 0000000..3e4ec34 --- /dev/null +++ b/src/backend/NativeFileDialogService.cpp @@ -0,0 +1,18 @@ +#include "NativeFileDialogService.h" +#include + +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); +} diff --git a/src/backend/NativeFileDialogService.h b/src/backend/NativeFileDialogService.h new file mode 100644 index 0000000..4049cb7 --- /dev/null +++ b/src/backend/NativeFileDialogService.h @@ -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 diff --git a/src/backend/PortalFileDialogService.cpp b/src/backend/PortalFileDialogService.cpp new file mode 100644 index 0000000..62632d3 --- /dev/null +++ b/src/backend/PortalFileDialogService.cpp @@ -0,0 +1,155 @@ +#ifdef HAS_QT_DBUS + +#include "PortalFileDialogService.h" +#include +#include +#include +#include +#include +#include + +// 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 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(); + qDBusRegisterMetaType>(); + qDBusRegisterMetaType(); + qDBusRegisterMetaType>(); +} + +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 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 diff --git a/src/backend/PortalFileDialogService.h b/src/backend/PortalFileDialogService.h new file mode 100644 index 0000000..f5594dc --- /dev/null +++ b/src/backend/PortalFileDialogService.h @@ -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 diff --git a/src/backend/QDocumentChunkMeasurer.cpp b/src/backend/QDocumentChunkMeasurer.cpp new file mode 100644 index 0000000..a5bf7b5 --- /dev/null +++ b/src/backend/QDocumentChunkMeasurer.cpp @@ -0,0 +1,41 @@ +#include "QDocumentChunkMeasurer.h" +#include +#include +#include +#include + +QDocumentChunkMeasurer::QDocumentChunkMeasurer(int pixelSize, qreal lineHeightPercent) + : m_pixelSize(pixelSize) + , m_lineHeightPercent(lineHeightPercent) +{ +} + +QVector 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 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; +} diff --git a/src/backend/QDocumentChunkMeasurer.h b/src/backend/QDocumentChunkMeasurer.h new file mode 100644 index 0000000..1fb40ce --- /dev/null +++ b/src/backend/QDocumentChunkMeasurer.h @@ -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 measure(const QStringList &chunks, qreal textWidth) const override; + +private: + int m_pixelSize; + qreal m_lineHeightPercent; +}; + +#endif // QDOCUMENTCHUNKMEASURER_H diff --git a/src/backend/ReadingModel.cpp b/src/backend/ReadingModel.cpp index 0c9300f..f910289 100644 --- a/src/backend/ReadingModel.cpp +++ b/src/backend/ReadingModel.cpp @@ -1,10 +1,6 @@ #include "ReadingModel.h" #include "FormatReader.h" #include -#include -#include -#include -#include ReadingModel::ReadingModel(QObject *parent) : QAbstractListModel(parent) @@ -74,6 +70,11 @@ int ReadingModel::totalPages() const return m_totalPages; } +void ReadingModel::setChunkMeasurer(IChunkMeasurer *measurer) +{ + m_chunkMeasurer = measurer; +} + void ReadingModel::setViewportSize(qreal width, qreal height) { bool widthChanged = (width != m_viewportWidth); @@ -99,36 +100,12 @@ void ReadingModel::setScrollInfo(int topChunkIndex, qreal offsetInChunk, bool at void ReadingModel::computeChunkHeights() { - // Caller passes effective text width: - // chunkListView.width - 18 (scrollbar) - 2 * horizontalMargin (delegate padding) - qreal textWidth = m_viewportWidth; - if (textWidth <= 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()); + if (m_chunkMeasurer) { + m_chunkHeights = m_chunkMeasurer->measure(m_chunks, m_viewportWidth); + } else { + m_chunkHeights.assign(m_chunks.size(), 0.0); } - // Build prefix sums m_chunkOffsets.clear(); m_chunkOffsets.reserve(m_chunks.size()); qreal offset = 0; diff --git a/src/backend/ReadingModel.h b/src/backend/ReadingModel.h index d3c662e..7372fcd 100644 --- a/src/backend/ReadingModel.h +++ b/src/backend/ReadingModel.h @@ -6,6 +6,8 @@ #include #include +#include "IChunkMeasurer.h" + class FormatReader; class ReadingModel : public QAbstractListModel { @@ -38,6 +40,7 @@ public: int totalPages() const; bool hasChapters() const; void setReader(FormatReader *reader); + void setChunkMeasurer(IChunkMeasurer *measurer); // Called from QML on resize Q_INVOKABLE void setViewportSize(qreal width, qreal height); @@ -61,6 +64,7 @@ private: void recalculateCurrentPage(); FormatReader *m_reader = nullptr; + IChunkMeasurer *m_chunkMeasurer = nullptr; int m_currentChapter = 0; int m_totalChapters = 0; int m_currentPage = 0; diff --git a/src/main.cpp b/src/main.cpp index 191b48f..2ea73fe 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -11,6 +11,13 @@ #include "backend/BookController.h" #include "backend/ReadingModel.h" #include "backend/AppState.h" +#include "backend/QDocumentChunkMeasurer.h" +#include "backend/NativeFileDialogService.h" + +#ifdef HAS_QT_DBUS +#include +#include "backend/PortalFileDialogService.h" +#endif 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")); + QDocumentChunkMeasurer chunkMeasurer(16, 160.0); + ReadingModel readingModel; + readingModel.setChunkMeasurer(&chunkMeasurer); BookController bookController; bookController.setReadingModel(&readingModel); @@ -80,6 +90,18 @@ int main(int argc, char *argv[]) appState.restore(); 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) { const QString& filePath = args.at(1); if (QFileInfo::exists(filePath)) diff --git a/tests/BookControllerTest.cpp b/tests/BookControllerTest.cpp index 8df8155..eee8311 100644 --- a/tests/BookControllerTest.cpp +++ b/tests/BookControllerTest.cpp @@ -5,6 +5,19 @@ #include "backend/BookController.h" #include "backend/ReadingModel.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 { Q_OBJECT @@ -156,6 +169,40 @@ private slots: QVERIFY(pos.contains("chapter")); 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) diff --git a/tests/QDocumentChunkMeasurerTest.cpp b/tests/QDocumentChunkMeasurerTest.cpp new file mode 100644 index 0000000..a74a867 --- /dev/null +++ b/tests/QDocumentChunkMeasurerTest.cpp @@ -0,0 +1,53 @@ +#include +#include "backend/QDocumentChunkMeasurer.h" + +class QDocumentChunkMeasurerTest : public QObject { + Q_OBJECT + +private slots: + void returnsOneHeightPerChunk() + { + QDocumentChunkMeasurer measurer; + QStringList chunks = {"

First

", "

Second

", "

Third

"}; + QVector heights = measurer.measure(chunks, 800); + QCOMPARE(heights.size(), 3); + } + + void heightsArePositive() + { + QDocumentChunkMeasurer measurer; + QStringList chunks = {"

Hello world

", "

Another paragraph

"}; + QVector heights = measurer.measure(chunks, 800); + for (qreal h : heights) + QVERIFY(h > 0.0); + } + + void emptyChunkListReturnsEmpty() + { + QDocumentChunkMeasurer measurer; + QVector heights = measurer.measure({}, 800); + QVERIFY(heights.isEmpty()); + } + + void zeroWidthClampedToOne() + { + // Must not crash and must return positive heights + QDocumentChunkMeasurer measurer; + QStringList chunks = {"

text

"}; + QVector heights = measurer.measure(chunks, 0); + QCOMPARE(heights.size(), 1); + QVERIFY(heights.first() > 0.0); + } + + void narrowerWidthGivesGreaterOrEqualHeight() + { + QDocumentChunkMeasurer measurer; + QStringList chunks = {"

A long paragraph that should wrap when the width is very narrow.

"}; + qreal height800 = measurer.measure(chunks, 800).first(); + qreal height200 = measurer.measure(chunks, 200).first(); + QVERIFY(height200 >= height800); + } +}; + +QTEST_MAIN(QDocumentChunkMeasurerTest) +#include "QDocumentChunkMeasurerTest.moc" diff --git a/tests/ReadingModelTest.cpp b/tests/ReadingModelTest.cpp index c00cd1b..46b05c4 100644 --- a/tests/ReadingModelTest.cpp +++ b/tests/ReadingModelTest.cpp @@ -2,6 +2,7 @@ #include #include "backend/ReadingModel.h" #include "backend/FormatReader.h" +#include "backend/IChunkMeasurer.h" class SingleChapterReader : public FormatReader { public: @@ -35,6 +36,25 @@ public: 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 measure(const QStringList &chunks, qreal textWidth) const override + { + lastTextWidth = textWidth; + QVector 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 { Q_OBJECT @@ -231,6 +251,7 @@ private slots: } // Page calculation tests + void initialPageState() { ReadingModel model; @@ -242,6 +263,8 @@ private slots: { ReadingModel model; FakeReader reader; + FakeChunkMeasurer measurer; + model.setChunkMeasurer(&measurer); model.setReader(&reader); model.setViewportSize(0, 0); QCOMPARE(model.totalPages(), 0); @@ -252,6 +275,8 @@ private slots: { ReadingModel model; FakeReader reader; + FakeChunkMeasurer measurer(100.0); // 2 chunks × 100px = 200px total + model.setChunkMeasurer(&measurer); model.setReader(&reader); model.setViewportSize(800, 600); QVERIFY(model.totalPages() > 0); @@ -262,6 +287,8 @@ private slots: { ReadingModel model; FakeReader reader; + FakeChunkMeasurer measurer(100.0); + model.setChunkMeasurer(&measurer); model.setReader(&reader); model.setViewportSize(800, 600); model.setScrollInfo(0, 0); @@ -272,6 +299,8 @@ private slots: { ReadingModel model; FakeReader reader; + FakeChunkMeasurer measurer(100.0); + model.setChunkMeasurer(&measurer); model.setReader(&reader); model.setViewportSize(800, 600); model.setScrollInfo(0, 0); @@ -282,6 +311,8 @@ private slots: { ReadingModel model; FakeReader reader; + FakeChunkMeasurer measurer(100.0); + model.setChunkMeasurer(&measurer); model.setReader(&reader); model.setViewportSize(800, 600); // Scroll to last chunk with huge offset @@ -293,6 +324,8 @@ private slots: { ReadingModel model; FakeReader reader; + FakeChunkMeasurer measurer(100.0); + model.setChunkMeasurer(&measurer); model.setReader(&reader); model.setViewportSize(800, 600); int pages = model.totalPages(); @@ -306,6 +339,8 @@ private slots: { ReadingModel model; FakeReader reader; + FakeChunkMeasurer measurer(100.0); + model.setChunkMeasurer(&measurer); model.setReader(&reader); model.setViewportSize(800, 600); model.setScrollInfo(0, 50); @@ -321,29 +356,33 @@ private slots: { ReadingModel model; FakeReader reader; + FakeChunkMeasurer measurer(100.0); + model.setChunkMeasurer(&measurer); model.setReader(&reader); model.setViewportSize(800, 600); int pages800 = model.totalPages(); - // Narrower viewport → chunks taller → more pages + // Narrower viewport (FakeChunkMeasurer returns same heights, so pages >=) model.setViewportSize(400, 600); QVERIFY(model.totalPages() >= pages800); - // Shorter viewport (same width) → more pages - model.setViewportSize(400, 300); + // Shorter viewport → more pages + model.setViewportSize(400, 50); // 200px content / 50px viewport = 4 pages QVERIFY(model.totalPages() > 0); } void setScrollInfoAdvancesMonotonically() { - // Build a FakeReader with many chunks so we can scroll across pages + // tiny viewport to guarantee multiple pages ReadingModel model; FakeReader reader; + FakeChunkMeasurer measurer(100.0); // 2 chunks × 100px = 200px total + model.setChunkMeasurer(&measurer); 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); // chunk 0 at offset 0 → page 1 model.setScrollInfo(0, 0); 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); int secondPage = model.currentPage(); QVERIFY(secondPage >= firstPage); @@ -372,6 +411,41 @@ private slots: ReadingModel model; 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)