diff --git a/AGENTS.md b/AGENTS.md index 528cb0a..aa23e97 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -157,7 +157,7 @@ When `CMakeLists.txt` gains a new `find_package` or `pkg_check_modules` dependen | Object | Responsibility | |---|---| -| `Book` | Open/close book, owns reader (via `ReaderFactory`), exposes metadata (title, author), TOC | +| `Book` | Open/close book, owns reader (via `FormatRegistry`), exposes metadata (title, author), TOC | | `ReadingModel` | QAbstractListModel exposing chapter chunks (ContentRole), position, next/prev navigation, progress | | `AppState` | Window geometry, last file, preferences (`QSettings`) | @@ -195,9 +195,9 @@ Chapter mapping by format: TXT = 1 chapter (whole file). FB2 = `
` eleme **Progress tracking** to track reading position ONLY ListView y offset must be used. Current page / progress percentage must be calculated using this and total height only. -### Reader Factory +### Format Registry -`ReaderFactory` is separate from `FormatReader`. It provides a static `create(const QString &filePath)` method backed by a registration map (extension → factory function). Adding a new format requires only a new map entry — no modifications to existing factory logic (OCP). No plugin system needed. +`FormatRegistry` is separate from `FormatReader`. It is driven by a `FormatSpec` table (one row per format: extension or directory match, image scheme, reader factory, byte-source factory) built in `main()`. Readers, image providers, sync image loaders, and QML scheme registration all derive from the same row, so adding a new format requires only a new table row — no modifications to existing factory logic (OCP). No plugin system needed. ### Async Book Opening @@ -218,13 +218,18 @@ src/ ReadingModel.h/cpp # Chapter content, position, navigation — exposed to QML AppState.h/cpp # Window/session state (QSettings) — exposed to QML FormatReader.h # Abstract interface + Chapter/TocEntry structs - ReaderFactory.h/cpp # Extension → reader mapping + AppCoordinator.h/cpp # Cross-class signal wiring (book open, history, quit) + reading/ + MangaPagination.h/cpp # Pure page-pair layout for manga mode + MeasurementController.h/cpp # Off-thread chunk height measurement formats/ + FormatRegistry.h/cpp # FormatSpec table: readers, providers, schemes + IByteSource.h # Byte access to named entries (zip/rar/dir/fb2) + EntryImageProvider.h/cpp # Generic image provider over any IByteSource + sources/ # ZipByteSource, RarByteSource, DirByteSource, Fb2ByteSource TxtReader.h/cpp Fb2Reader.h/cpp EpubReader.h/cpp - CbzReader.h/cpp - CbzImageProvider.h/cpp PdfReader.h/cpp RtfReader.h/cpp DocReader.h/cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index e3bb432..49c77ee 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -49,12 +49,18 @@ set(SOURCES src/backend/FormatReader.h src/backend/AppState.h src/backend/AppState.cpp + src/backend/AppCoordinator.h + src/backend/AppCoordinator.cpp src/backend/HistoryBookModel.h src/backend/HistoryBookModel.cpp src/backend/HistoryModel.h src/backend/HistoryModel.cpp src/backend/ReadingModel.h src/backend/ReadingModel.cpp + src/backend/reading/MangaPagination.h + src/backend/reading/MangaPagination.cpp + src/backend/reading/MeasurementController.h + src/backend/reading/MeasurementController.cpp src/backend/state/ReadingPreferences.h src/backend/state/ReadingPreferences.cpp src/backend/state/UiState.h @@ -69,50 +75,40 @@ set(SOURCES src/backend/ChunkMeasurer.h src/backend/ChunkMeasurer.cpp src/backend/IFileDialogService.h - src/backend/IFileDialogService.cpp src/backend/NativeFileDialogService.h src/backend/NativeFileDialogService.cpp src/backend/formats/TxtReader.h src/backend/formats/TxtReader.cpp src/backend/formats/EpubReader.h src/backend/formats/EpubReader.cpp - src/backend/formats/EpubImageProvider.h - src/backend/formats/EpubImageProvider.cpp src/backend/formats/Fb2Reader.h src/backend/formats/Fb2Reader.cpp - src/backend/formats/Fb2ImageProvider.h - src/backend/formats/Fb2ImageProvider.cpp - src/backend/formats/comic/IComicSource.h - src/backend/formats/comic/ZipComicSource.h - src/backend/formats/comic/ZipComicSource.cpp - src/backend/formats/comic/RarComicSource.h - src/backend/formats/comic/RarComicSource.cpp - src/backend/formats/comic/DirComicSource.h - src/backend/formats/comic/DirComicSource.cpp + src/backend/formats/IByteSource.h + src/backend/formats/EntryImageProvider.h + src/backend/formats/EntryImageProvider.cpp + src/backend/formats/sources/ZipByteSource.h + src/backend/formats/sources/ZipByteSource.cpp + src/backend/formats/sources/RarByteSource.h + src/backend/formats/sources/RarByteSource.cpp + src/backend/formats/sources/DirByteSource.h + src/backend/formats/sources/DirByteSource.cpp + src/backend/formats/sources/Fb2ByteSource.h + src/backend/formats/sources/Fb2ByteSource.cpp src/backend/formats/comic/ComicReader.h src/backend/formats/comic/ComicReader.cpp - src/backend/formats/comic/ComicImageProvider.h - src/backend/formats/comic/ComicImageProvider.cpp src/backend/formats/comic/CbzReader.h - src/backend/formats/comic/CbzProvider.h - src/backend/formats/comic/Cbz.h - src/backend/formats/comic/Cbz.cpp src/backend/formats/comic/CbrReader.h - src/backend/formats/comic/CbrProvider.h - src/backend/formats/comic/Cbr.h - src/backend/formats/comic/Cbr.cpp src/backend/formats/comic/FolderReader.h - src/backend/formats/comic/FolderProvider.h - src/backend/formats/comic/Folder.h - src/backend/formats/comic/Folder.cpp src/backend/formats/WebImageProvider.h src/backend/formats/WebImageProvider.cpp - src/backend/formats/ImageProviderFactory.h - src/backend/formats/ImageProviderFactory.cpp - src/backend/formats/ImageLoaderFactory.h - src/backend/formats/ImageLoaderFactory.cpp - src/backend/formats/ReaderFactory.h - src/backend/formats/ReaderFactory.cpp + src/backend/formats/AsyncImageResponse.h + src/backend/formats/AsyncImageResponse.cpp + src/backend/formats/ImageUrl.h + src/backend/formats/ImageUrl.cpp + src/backend/formats/ImageScaling.h + src/backend/formats/ImageExtensions.h + src/backend/formats/FormatRegistry.h + src/backend/formats/FormatRegistry.cpp src/backend/formats/FileIconProvider.h src/backend/formats/FileIconProvider.cpp ) @@ -192,6 +188,8 @@ set_source_files_properties(src/qml/components/MangaPageView.qml PROPERTIES QT_R set_source_files_properties(src/qml/components/Footer.qml PROPERTIES QT_RESOURCE_ALIAS components/Footer.qml) set_source_files_properties(src/qml/components/ErrorPopup.qml PROPERTIES QT_RESOURCE_ALIAS components/ErrorPopup.qml) set_source_files_properties(src/qml/components/SideBarButton.qml PROPERTIES QT_RESOURCE_ALIAS components/SideBarButton.qml) +set_source_files_properties(src/qml/components/FlatIconButton.qml PROPERTIES QT_RESOURCE_ALIAS components/FlatIconButton.qml) +set_source_files_properties(src/qml/components/LabeledSlider.qml PROPERTIES QT_RESOURCE_ALIAS components/LabeledSlider.qml) set_source_files_properties(src/qml/pages/StarterPage.qml PROPERTIES QT_RESOURCE_ALIAS pages/StarterPage.qml) set_source_files_properties(src/qml/pages/ReaderPage.qml PROPERTIES QT_RESOURCE_ALIAS pages/ReaderPage.qml) set_source_files_properties(src/qml/components/SettingsPopup.qml PROPERTIES QT_RESOURCE_ALIAS components/SettingsPopup.qml) @@ -217,6 +215,8 @@ qt_add_qml_module(asteria-qt src/qml/components/Footer.qml src/qml/components/ErrorPopup.qml src/qml/components/SideBarButton.qml + src/qml/components/FlatIconButton.qml + src/qml/components/LabeledSlider.qml src/qml/components/SettingsPopup.qml src/qml/pages/StarterPage.qml src/qml/pages/ReaderPage.qml @@ -246,15 +246,16 @@ endif() # Reader-only comic sources (no Qt::Quick dependency) set(COMIC_READER_SOURCES - src/backend/formats/comic/ZipComicSource.cpp - src/backend/formats/comic/RarComicSource.cpp - src/backend/formats/comic/DirComicSource.cpp + src/backend/formats/ImageUrl.cpp + src/backend/formats/sources/ZipByteSource.cpp + src/backend/formats/sources/RarByteSource.cpp + src/backend/formats/sources/DirByteSource.cpp src/backend/formats/comic/ComicReader.cpp) # Full comic sources including image provider (requires Qt::Quick) set(COMIC_SOURCES ${COMIC_READER_SOURCES} - src/backend/formats/comic/ComicImageProvider.cpp) + src/backend/formats/EntryImageProvider.cpp) # Testing enable_testing() @@ -275,6 +276,12 @@ function(add_asteria_test TEST_NAME TEST_SOURCE) add_test(NAME ${TEST_NAME} COMMAND ${TEST_NAME}) endfunction() +add_asteria_test(ImageUrlTest tests/formats/ImageUrlTest.cpp + src/backend/formats/ImageUrl.cpp) + +add_asteria_test(MangaPaginationTest tests/reading/MangaPaginationTest.cpp + src/backend/reading/MangaPagination.cpp) + add_asteria_test(TxtReaderTest tests/formats/TxtReaderTest.cpp src/backend/formats/TxtReader.cpp) @@ -283,7 +290,8 @@ add_asteria_test(EpubReaderTest tests/formats/EpubReaderTest.cpp target_link_libraries(EpubReaderTest PRIVATE PkgConfig::MINIZIP Qt6::Xml) add_asteria_test(Fb2ReaderTest tests/formats/Fb2ReaderTest.cpp - src/backend/formats/Fb2Reader.cpp) + src/backend/formats/Fb2Reader.cpp + src/backend/formats/ImageUrl.cpp) target_link_libraries(Fb2ReaderTest PRIVATE Qt6::Xml) add_asteria_test(CbzReaderTest tests/formats/CbzReaderTest.cpp ${COMIC_READER_SOURCES}) @@ -293,33 +301,36 @@ add_asteria_test(FolderReaderTest tests/formats/FolderReaderTest.cpp ${COMIC_REA target_link_libraries(FolderReaderTest PRIVATE PkgConfig::MINIZIP PkgConfig::LIBARCHIVE Qt6::Xml Qt6::Gui) set_tests_properties(FolderReaderTest PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen") -add_asteria_test(ReaderFactoryTest tests/ReaderFactoryTest.cpp - src/backend/formats/ReaderFactory.cpp +add_asteria_test(FormatRegistryTest tests/FormatRegistryTest.cpp + src/backend/formats/FormatRegistry.cpp + src/backend/formats/AsyncImageResponse.cpp + src/backend/formats/EntryImageProvider.cpp + src/backend/formats/WebImageProvider.cpp src/backend/formats/TxtReader.cpp src/backend/formats/EpubReader.cpp src/backend/formats/Fb2Reader.cpp ${COMIC_READER_SOURCES}) -target_link_libraries(ReaderFactoryTest PRIVATE PkgConfig::MINIZIP PkgConfig::LIBARCHIVE Qt6::Xml Qt6::Gui) +target_link_libraries(FormatRegistryTest PRIVATE PkgConfig::MINIZIP PkgConfig::LIBARCHIVE Qt6::Xml Qt6::Gui Qt6::Quick Qt6::Network) +set_tests_properties(FormatRegistryTest PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen") add_asteria_test(ChunkMeasurerTest tests/ChunkMeasurerTest.cpp - src/backend/ChunkMeasurer.cpp - src/backend/formats/EpubImageProvider.cpp - src/backend/formats/WebImageProvider.cpp) + src/backend/ChunkMeasurer.cpp) target_link_libraries(ChunkMeasurerTest PRIVATE Qt6::Gui Qt6::Concurrent Qt6::Quick Qt6::Network PkgConfig::MINIZIP) set_tests_properties(ChunkMeasurerTest PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen") add_asteria_test(ReadingModelTest tests/ReadingModelTest.cpp src/backend/ReadingModel.cpp + src/backend/reading/MangaPagination.cpp + src/backend/reading/MeasurementController.cpp src/backend/ChunkMeasurer.cpp - src/backend/formats/EpubImageProvider.cpp - src/backend/formats/Fb2ImageProvider.cpp + src/backend/formats/AsyncImageResponse.cpp + src/backend/formats/sources/Fb2ByteSource.cpp src/backend/formats/WebImageProvider.cpp - src/backend/formats/ImageProviderFactory.cpp + src/backend/formats/FormatRegistry.cpp src/backend/AppState.cpp src/backend/state/BookPositionStore.cpp src/backend/HistoryBookModel.cpp src/backend/HistoryModel.cpp - src/backend/formats/ReaderFactory.cpp src/backend/formats/TxtReader.cpp src/backend/formats/EpubReader.cpp src/backend/formats/Fb2Reader.cpp @@ -348,33 +359,41 @@ add_asteria_test(BookTest tests/book/BookTest.cpp src/backend/book/Book.cpp src/backend/AppState.cpp src/backend/state/BookPositionStore.cpp - src/backend/formats/ReaderFactory.cpp - src/backend/IFileDialogService.cpp + src/backend/formats/FormatRegistry.cpp + src/backend/formats/AsyncImageResponse.cpp + src/backend/formats/EntryImageProvider.cpp + src/backend/formats/WebImageProvider.cpp + src/backend/IFileDialogService.h src/backend/NativeFileDialogService.cpp src/backend/formats/TxtReader.cpp src/backend/formats/EpubReader.cpp src/backend/formats/Fb2Reader.cpp ${COMIC_READER_SOURCES}) -target_link_libraries(BookTest PRIVATE Qt6::Concurrent Qt6::Widgets PkgConfig::MINIZIP PkgConfig::LIBARCHIVE Qt6::Xml Qt6::Gui) +target_link_libraries(BookTest PRIVATE Qt6::Concurrent Qt6::Widgets PkgConfig::MINIZIP PkgConfig::LIBARCHIVE Qt6::Xml Qt6::Gui Qt6::Quick Qt6::Network) set_tests_properties(BookTest PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen") -add_asteria_test(EpubImageProviderTest tests/EpubImageProviderTest.cpp - src/backend/formats/EpubImageProvider.cpp) -target_link_libraries(EpubImageProviderTest PRIVATE PkgConfig::MINIZIP Qt6::Quick Qt6::Gui) -set_tests_properties(EpubImageProviderTest PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen") +add_asteria_test(EntryImageProviderTest tests/EntryImageProviderTest.cpp + src/backend/formats/AsyncImageResponse.cpp + src/backend/formats/EntryImageProvider.cpp + src/backend/formats/ImageUrl.cpp + src/backend/formats/sources/ZipByteSource.cpp + src/backend/formats/sources/Fb2ByteSource.cpp + src/backend/formats/Fb2Reader.cpp) +target_link_libraries(EntryImageProviderTest PRIVATE PkgConfig::MINIZIP Qt6::Quick Qt6::Gui Qt6::Xml) +set_tests_properties(EntryImageProviderTest PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen") add_asteria_test(HistoryBookModelTest tests/HistoryBookModelTest.cpp src/backend/HistoryBookModel.cpp - src/backend/formats/EpubImageProvider.cpp - src/backend/formats/Fb2ImageProvider.cpp - src/backend/formats/ImageProviderFactory.cpp - src/backend/formats/ReaderFactory.cpp + src/backend/formats/AsyncImageResponse.cpp + src/backend/formats/sources/Fb2ByteSource.cpp + src/backend/formats/FormatRegistry.cpp + src/backend/formats/WebImageProvider.cpp src/backend/formats/TxtReader.cpp src/backend/formats/EpubReader.cpp src/backend/formats/Fb2Reader.cpp ${COMIC_SOURCES}) target_link_libraries(HistoryBookModelTest PRIVATE - Qt6::Concurrent Qt6::Quick Qt6::Gui Qt6::Xml PkgConfig::MINIZIP PkgConfig::LIBARCHIVE) + Qt6::Concurrent Qt6::Quick Qt6::Gui Qt6::Xml Qt6::Network PkgConfig::MINIZIP PkgConfig::LIBARCHIVE) set_tests_properties(HistoryBookModelTest PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen") add_asteria_test(FileIconProviderTest tests/FileIconProviderTest.cpp diff --git a/src/backend/AppCoordinator.cpp b/src/backend/AppCoordinator.cpp new file mode 100644 index 0000000..c81dcd1 --- /dev/null +++ b/src/backend/AppCoordinator.cpp @@ -0,0 +1,143 @@ +#include "AppCoordinator.h" + +#include "AppState.h" +#include "HistoryModel.h" +#include "IImageProvider.h" +#include "ReadingModel.h" +#include "book/Book.h" +#include "formats/FormatRegistry.h" +#include "state/ReadingPreferences.h" +#include "state/UiState.h" + +#include +#include +#include + +AppCoordinator::AppCoordinator(Book &book, + ReadingModel &readingModel, + HistoryModel &historyModel, + UiState &uiState, + ReadingPreferences &readingPreferences, + AppState &appState, + QSettings &settings, + FormatRegistry &formatRegistry, + QQmlApplicationEngine &engine, + QObject *parent) + : QObject(parent) + , m_book(book) + , m_readingModel(readingModel) + , m_historyModel(historyModel) + , m_uiState(uiState) + , m_readingPreferences(readingPreferences) + , m_appState(appState) + , m_settings(settings) + , m_formatRegistry(formatRegistry) + , m_engine(engine) +{ + // Typography changes → re-push font params into ReadingModel + connect(&m_readingPreferences, &ReadingPreferences::fontSizeChanged, + this, &AppCoordinator::onFontPrefsChanged); + connect(&m_readingPreferences, &ReadingPreferences::lineSpacingChanged, + this, &AppCoordinator::onFontPrefsChanged); + + connect(&m_book, &Book::willOpenNewBook, this, &AppCoordinator::onWillOpenNewBook); + connect(&m_book, &Book::positionSaved, this, &AppCoordinator::onPositionSaved); + connect(&m_book, &Book::bookChanged, this, &AppCoordinator::onBookChanged); + connect(&m_book, &Book::contentWidthChanged, this, &AppCoordinator::onContentWidthChanged); + + connect(QCoreApplication::instance(), &QCoreApplication::aboutToQuit, + this, &AppCoordinator::onAboutToQuit); +} + +void AppCoordinator::onFontPrefsChanged() +{ + m_readingModel.setFontParams(m_readingPreferences.fontSize(), + m_readingPreferences.lineSpacing()); +} + +// Before a new book open: snapshot the outgoing book's progress into the library. +// Scroll position is handled by PageView's scroll tracker via book.saveCurrentPosition(). +void AppCoordinator::onWillOpenNewBook() +{ + if (m_book.hasBook()) + m_historyModel.addOrUpdateBook(m_book.filePath(), m_readingModel.progress()); +} + +// Real-time history update: fired by PageView's scrollTrackTimer on every scroll. +void AppCoordinator::onPositionSaved() +{ + m_historyModel.addOrUpdateBook(m_book.filePath(), m_readingModel.progress()); +} + +// After the new reader is installed: wire up image provider + ReadingModel +void AppCoordinator::onBookChanged() +{ + m_currentImageProvider = nullptr; + + if (!m_book.hasBook()) { + m_readingModel.setReader(nullptr); + return; + } + + FormatReader *reader = m_book.reader(); + const QString filePath = reader->filePath(); + + IImageProvider *provider = m_formatRegistry.createImageProvider(filePath); + if (provider) { + m_engine.removeImageProvider(provider->scheme()); + m_engine.addImageProvider(provider->scheme(), provider); + provider->setFilePath(filePath); + provider->setDisplayWidth(m_contentWidth); + m_currentImageProvider = provider; + + if (!reader->coverImagePath().isEmpty()) + m_book.setCoverImageUrl(provider->coverImageUrl(reader->coverImagePath())); + } + + m_readingModel.setFontParams(m_readingPreferences.fontSize(), + m_readingPreferences.lineSpacing()); + m_readingModel.setImageLoader(m_formatRegistry.createImageLoader(filePath)); + m_readingModel.setCoverImageUrl(m_book.coverImageUrl()); + m_readingModel.setReader(reader); + m_readingModel.measure(true); + + m_uiState.setLastFilePath(filePath); + m_historyModel.addOrUpdateBook(filePath, -1.0); +} + +// Propagate content-width changes to image provider + reading model. +// Called from Book::setContentWidth which is triggered by QML's PageView. +void AppCoordinator::onContentWidthChanged(int width) +{ + m_contentWidth = width; + if (m_currentImageProvider) + m_currentImageProvider->setDisplayWidth(width); + m_readingModel.setContentWidth(width); +} + +// Quit: flush everything to persistent storage. +// Scroll position was last saved by PageView's scroll tracker; we save library progress here. +void AppCoordinator::onAboutToQuit() +{ + if (m_book.hasBook()) { + m_historyModel.addOrUpdateBook(m_book.filePath(), m_readingModel.progress()); + m_uiState.setLastFilePath(m_book.filePath()); + } else { + m_uiState.setLastFilePath(QString()); + } + + m_readingPreferences.save(); + m_uiState.save(); + + QList items; + for (int i = 0; i < m_historyModel.rowCount(); ++i) { + items.append({ + {QStringLiteral("filePath"), m_historyModel.filePath(i)}, + {QStringLiteral("progress"), m_historyModel.progress(i)}, + {QStringLiteral("lastOpened"), m_historyModel.lastOpened(i)}, + }); + } + m_appState.saveArray(QStringLiteral("history"), items); + + qInfo() << "Settings saved to:" << m_settings.fileName(); +} diff --git a/src/backend/AppCoordinator.h b/src/backend/AppCoordinator.h new file mode 100644 index 0000000..fa6a7c4 --- /dev/null +++ b/src/backend/AppCoordinator.h @@ -0,0 +1,55 @@ +#pragma once + +#include + +class AppState; +class Book; +class FormatRegistry; +class HistoryModel; +class IImageProvider; +class QQmlApplicationEngine; +class QSettings; +class ReadingModel; +class ReadingPreferences; +class UiState; + +// Wires the top-level objects together: reacts to book changes by swapping +// image providers and configuring the reading model, keeps history and +// persistent state in sync, and flushes everything on quit. main() only +// constructs the object graph; the coordination lives here. +class AppCoordinator : public QObject { + Q_OBJECT +public: + AppCoordinator(Book &book, + ReadingModel &readingModel, + HistoryModel &historyModel, + UiState &uiState, + ReadingPreferences &readingPreferences, + AppState &appState, + QSettings &settings, + FormatRegistry &formatRegistry, + QQmlApplicationEngine &engine, + QObject *parent = nullptr); + +private slots: + void onBookChanged(); + void onWillOpenNewBook(); + void onPositionSaved(); + void onContentWidthChanged(int width); + void onFontPrefsChanged(); + void onAboutToQuit(); + +private: + Book &m_book; + ReadingModel &m_readingModel; + HistoryModel &m_historyModel; + UiState &m_uiState; + ReadingPreferences &m_readingPreferences; + AppState &m_appState; + QSettings &m_settings; + FormatRegistry &m_formatRegistry; + QQmlApplicationEngine &m_engine; + + IImageProvider *m_currentImageProvider = nullptr; + int m_contentWidth = 0; +}; diff --git a/src/backend/AppState.cpp b/src/backend/AppState.cpp index c8fea44..428522e 100644 --- a/src/backend/AppState.cpp +++ b/src/backend/AppState.cpp @@ -9,7 +9,7 @@ AppState::AppState(QSettings &settings) } } -QVariantMap AppState::loadSection(const QString §ion) const +QVariantMap AppState::loadSection(const QString §ion) { QVariantMap result; m_settings.beginGroup(section); @@ -20,7 +20,7 @@ QVariantMap AppState::loadSection(const QString §ion) const return result; } -void AppState::saveSection(const QString §ion, const QVariantMap &data) const +void AppState::saveSection(const QString §ion, const QVariantMap &data) { m_settings.beginGroup(section); m_settings.remove(QStringLiteral("")); // clear existing group @@ -29,23 +29,22 @@ void AppState::saveSection(const QString §ion, const QVariantMap &data) cons m_settings.endGroup(); } -QList AppState::loadArray(const QString §ion) const +QList AppState::loadArray(const QString §ion) { QList result; - QSettings &s = const_cast(m_settings); - const int size = s.beginReadArray(section); + const int size = m_settings.beginReadArray(section); for (int i = 0; i < size; ++i) { - s.setArrayIndex(i); + m_settings.setArrayIndex(i); QVariantMap entry; - for (const QString &key : s.childKeys()) - entry[key] = s.value(key); + for (const QString &key : m_settings.childKeys()) + entry[key] = m_settings.value(key); result.append(entry); } - s.endArray(); + m_settings.endArray(); return result; } -void AppState::saveArray(const QString §ion, const QList &items) const +void AppState::saveArray(const QString §ion, const QList &items) { m_settings.beginWriteArray(section, items.size()); for (int i = 0; i < items.size(); ++i) { diff --git a/src/backend/AppState.h b/src/backend/AppState.h index 9d74457..489c247 100644 --- a/src/backend/AppState.h +++ b/src/backend/AppState.h @@ -15,16 +15,16 @@ public: explicit AppState(QSettings &settings); // Load all key/value pairs from the named QSettings group. - QVariantMap loadSection(const QString §ion) const; + QVariantMap loadSection(const QString §ion); // Atomically replace the named QSettings group with the given data. - void saveSection(const QString §ion, const QVariantMap &data) const; + void saveSection(const QString §ion, const QVariantMap &data); // Load an ordered array (e.g., library books) from the named QSettings array. - QList loadArray(const QString §ion) const; + QList loadArray(const QString §ion); // Atomically replace the named QSettings array. - void saveArray(const QString §ion, const QList &items) const; + void saveArray(const QString §ion, const QList &items); private: QSettings &m_settings; diff --git a/src/backend/HistoryBookModel.cpp b/src/backend/HistoryBookModel.cpp index 29d87e0..7ee5abe 100644 --- a/src/backend/HistoryBookModel.cpp +++ b/src/backend/HistoryBookModel.cpp @@ -1,27 +1,17 @@ #include "HistoryBookModel.h" #include "FormatReader.h" #include "IImageProvider.h" -#include "formats/ImageProviderFactory.h" -#include "formats/ReaderFactory.h" #include #include #include -HistoryBookModel::HistoryBookModel(ReaderFactory &factory, QObject *parent) - : QObject(parent) - , m_factory(factory) -{ - connect(this, &HistoryBookModel::metadataLoaded, this, &HistoryBookModel::onMetadataLoaded); -} - -HistoryBookModel::HistoryBookModel(const QString &filePath, double progress, const QString &lastOpened, ReaderFactory &factory, QObject *parent) +HistoryBookModel::HistoryBookModel(const QString &filePath, double progress, const QString &lastOpened, FormatRegistry ®istry, QObject *parent) : QObject(parent) , m_filePath(filePath) , m_progress(progress) , m_lastOpened(lastOpened) - , m_factory(factory) + , m_registry(registry) { - connect(this, &HistoryBookModel::metadataLoaded, this, &HistoryBookModel::onMetadataLoaded); } HistoryBookModel::~HistoryBookModel() @@ -91,9 +81,9 @@ void HistoryBookModel::loadMetadata() QPointer self = this; QString filePath = m_filePath; - ReaderFactory *factory = &m_factory; - m_metadataFuture = QtConcurrent::run([self, filePath, factory]() { - auto reader = factory->create(filePath); + FormatRegistry *registry = &m_registry; + m_metadataFuture = QtConcurrent::run([self, filePath, registry]() { + auto reader = registry->createReader(filePath); QString title; QString author; bool success = false; @@ -108,7 +98,7 @@ void HistoryBookModel::loadMetadata() if (success) { QString coverPath = reader->coverImagePath(); if (!coverPath.isEmpty()) { - std::unique_ptr provider(ImageProviderFactory::create(filePath)); + std::unique_ptr provider(registry->createImageProvider(filePath)); if (provider) { provider->setFilePath(filePath); coverImageUrl = provider->coverImageUrl(coverPath); @@ -123,11 +113,8 @@ void HistoryBookModel::loadMetadata() self->m_author = author; self->m_coverImageUrl = coverImageUrl; self->m_metadataLoaded = true; + emit self->coverImageLoaded(); emit self->metadataLoaded(); }, Qt::QueuedConnection); }); -} - -void HistoryBookModel::onMetadataLoaded() -{ } \ No newline at end of file diff --git a/src/backend/HistoryBookModel.h b/src/backend/HistoryBookModel.h index 671e2a0..e3ba0a9 100644 --- a/src/backend/HistoryBookModel.h +++ b/src/backend/HistoryBookModel.h @@ -6,7 +6,7 @@ #include #include -#include "formats/ReaderFactory.h" +#include "formats/FormatRegistry.h" class FormatReader; @@ -21,8 +21,7 @@ class HistoryBookModel : public QObject { Q_PROPERTY(QString coverImageUrl READ coverImageUrl NOTIFY coverImageLoaded) public: - explicit HistoryBookModel(ReaderFactory &factory, QObject *parent = nullptr); - explicit HistoryBookModel(const QString &filePath, double progress, const QString &lastOpened, ReaderFactory &factory, QObject *parent = nullptr); + explicit HistoryBookModel(const QString &filePath, double progress, const QString &lastOpened, FormatRegistry ®istry, QObject *parent = nullptr); ~HistoryBookModel() override; QString filePath() const; @@ -39,9 +38,6 @@ public: void loadMetadata(); -public slots: - void onMetadataLoaded(); - signals: void progressChanged(); void lastOpenedChanged(); @@ -57,7 +53,7 @@ private: QString m_coverImageUrl; bool m_metadataLoaded = false; QFuture m_metadataFuture; - ReaderFactory &m_factory; + FormatRegistry &m_registry; }; #endif // HISTORYBOOKMODEL_H \ No newline at end of file diff --git a/src/backend/HistoryModel.cpp b/src/backend/HistoryModel.cpp index 8caa22f..8f5e851 100644 --- a/src/backend/HistoryModel.cpp +++ b/src/backend/HistoryModel.cpp @@ -2,9 +2,9 @@ #include "HistoryBookModel.h" #include -HistoryModel::HistoryModel(ReaderFactory &factory, QObject *parent) +HistoryModel::HistoryModel(FormatRegistry ®istry, QObject *parent) : QAbstractListModel(parent) - , m_factory(factory) + , m_registry(registry) { // Initialize role names m_roleNames[FilePathRole] = "filePath"; @@ -103,7 +103,7 @@ void HistoryModel::addOrUpdateBook(const QString &filePath, double progress, con } // New book — HistoryModel takes ownership via parent - auto* book = new HistoryBookModel(filePath, progress, lastOpened, m_factory, this); + auto* book = new HistoryBookModel(filePath, progress, lastOpened, m_registry, this); connect(book, &HistoryBookModel::metadataLoaded, this, &HistoryModel::onBookMetadataLoaded); beginInsertRows(QModelIndex(), 0, 0); @@ -119,14 +119,11 @@ void HistoryModel::removeBook(const QString &filePath) for (int i = 0; i < m_books.size(); i++) { if (m_books[i]->filePath() == filePath) { HistoryBookModel* book = m_books[i]; - - // Disconnect signals - disconnect(book, &HistoryBookModel::metadataLoaded, this, &HistoryModel::onBookMetadataLoaded); - + beginRemoveRows(QModelIndex(), i, i); m_books.removeAt(i); endRemoveRows(); - + book->deleteLater(); emit countChanged(); return; @@ -150,13 +147,10 @@ void HistoryModel::clear() return; beginRemoveRows(QModelIndex(), 0, m_books.size() - 1); - - // Disconnect and delete all books - for (HistoryBookModel* book : m_books) { - disconnect(book, &HistoryBookModel::metadataLoaded, this, &HistoryModel::onBookMetadataLoaded); + + for (HistoryBookModel* book : m_books) book->deleteLater(); - } - + m_books.clear(); endRemoveRows(); diff --git a/src/backend/HistoryModel.h b/src/backend/HistoryModel.h index b666215..62b704f 100644 --- a/src/backend/HistoryModel.h +++ b/src/backend/HistoryModel.h @@ -5,7 +5,7 @@ #include #include -#include "formats/ReaderFactory.h" +#include "formats/FormatRegistry.h" class HistoryBookModel; @@ -26,7 +26,7 @@ public: }; Q_ENUM(HistoryRoles) - explicit HistoryModel(ReaderFactory &factory, QObject *parent = nullptr); + explicit HistoryModel(FormatRegistry ®istry, QObject *parent = nullptr); ~HistoryModel() override; // QAbstractItemModel interface @@ -62,7 +62,7 @@ private slots: private: QList m_books; QHash m_roleNames; - ReaderFactory &m_factory; + FormatRegistry &m_registry; }; #endif // HISTORYMODEL_H \ No newline at end of file diff --git a/src/backend/IFileDialogService.cpp b/src/backend/IFileDialogService.cpp deleted file mode 100644 index 98e0f73..0000000 --- a/src/backend/IFileDialogService.cpp +++ /dev/null @@ -1 +0,0 @@ -#include "IFileDialogService.h" diff --git a/src/backend/IFileDialogService.h b/src/backend/IFileDialogService.h index 15a1d2c..568fab6 100644 --- a/src/backend/IFileDialogService.h +++ b/src/backend/IFileDialogService.h @@ -1,5 +1,4 @@ -#ifndef IFILEDIAL0GSERVICE_H -#define IFILEDIAL0GSERVICE_H +#pragma once #include #include @@ -16,5 +15,3 @@ public: signals: void fileSelected(const QString &path); }; - -#endif // IFILEDIAL0GSERVICE_H diff --git a/src/backend/IImageLoader.h b/src/backend/IImageLoader.h index 6488224..3ea7881 100644 --- a/src/backend/IImageLoader.h +++ b/src/backend/IImageLoader.h @@ -1,5 +1,4 @@ -#ifndef IIMAGELLOADER_H -#define IIMAGELLOADER_H +#pragma once #include #include #include @@ -9,4 +8,3 @@ public: virtual QImage load(const QUrl &url, int maxWidth) const = 0; virtual std::unique_ptr clone() const = 0; }; -#endif diff --git a/src/backend/ReadingModel.cpp b/src/backend/ReadingModel.cpp index 4c7d632..642b2fb 100644 --- a/src/backend/ReadingModel.cpp +++ b/src/backend/ReadingModel.cpp @@ -1,26 +1,20 @@ #include "ReadingModel.h" #include "FormatReader.h" -#include "IChunkMeasurer.h" -#include "IImageLoader.h" -#include "ChunkMeasurer.h" #include #include #include -#include ReadingModel::ReadingModel(BookPositionStore &positions, QObject *parent) : QAbstractListModel(parent) , m_positions(positions) { + connect(&m_measurer, &MeasurementController::measuringChanged, + this, &ReadingModel::measuringChanged); + connect(&m_measurer, &MeasurementController::heightsReady, + this, &ReadingModel::onHeightsReady); } -ReadingModel::~ReadingModel() -{ - if (m_measureFuture.isRunning()) { - m_measureFuture.cancel(); - m_measureFuture.waitForFinished(); - } -} +ReadingModel::~ReadingModel() = default; int ReadingModel::rowCount(const QModelIndex &parent) const { if (parent.isValid()) return 0; @@ -59,9 +53,9 @@ QString ReadingModel::chapterTitle() const int ReadingModel::currentChapter() const { return m_currentChapter; } int ReadingModel::totalChapters() const { return m_totalChapters; } bool ReadingModel::hasChapters() const { return m_totalChapters > 1; } -bool ReadingModel::measuring() const { return m_measuring; } +bool ReadingModel::measuring() const { return m_measurer.measuring(); } qreal ReadingModel::totalPixelHeight() const { return m_totalPixelHeight; } -int ReadingModel::totalPagePairs() const { return m_pagePairs.size(); } +int ReadingModel::totalPagePairs() const { return m_pagination.count(); } bool ReadingModel::isMangaMode() const { return m_isMangaMode; } bool ReadingModel::pageShift() const { return m_pageShift; } bool ReadingModel::mangaRTL() const { return m_mangaRTL; } @@ -109,7 +103,8 @@ void ReadingModel::measure(const bool isNew) for (const auto &c : m_chunks) htmls.append(c.html); - runMeasurement(htmls, isNew); + const int width = m_contentWidth > 0 ? m_contentWidth : 800; + m_measurer.start(htmls, width, m_fontSize, m_lineSpacing, isNew); } void ReadingModel::emitRestoreReady(const bool isNew) @@ -119,41 +114,19 @@ void ReadingModel::emitRestoreReady(const bool isNew) emit restoreReady(pos.chunkIndex, pos.intraOffset); } -void ReadingModel::runMeasurement(const QStringList &htmls, const bool isNew) +void ReadingModel::onHeightsReady(const QVector &heights, const bool isNew) { - if (m_measureFuture.isRunning()) - m_measureFuture.cancel(); + for (int i = 0; i < qMin(heights.size(), static_cast(m_chunks.size())); ++i) { + m_chunks[i].pixelHeight = heights[i]; + m_totalPixelHeight += heights[i]; + } + qInfo("Measured %lld chunks, total height: %f", heights.size(), m_totalPixelHeight); + emit totalPixelHeightChanged(); + emit dataChanged(createIndex(0, 0), + createIndex(m_chunks.size() - 1, 0), + {PixelHeightRole}); - m_measuring = true; - emit measuringChanged(); - - const int width = m_contentWidth > 0 ? m_contentWidth : 800; - const int fontSize = m_fontSize; - const qreal lineSpacing = m_lineSpacing; - - std::unique_ptr loaderClone = m_imageLoader ? m_imageLoader->clone() : nullptr; - auto measurer = new ChunkMeasurer(std::move(loaderClone), fontSize, lineSpacing); - - - m_measureFuture = QtConcurrent::run( - [this, htmls, measurer, width, isNew]() { - QVector heights = measurer->measure(htmls, width); - QMetaObject::invokeMethod(this, [this, heights, isNew] { - for (int i = 0; i < qMin(heights.size(), static_cast(m_chunks.size())); ++i) { - m_chunks[i].pixelHeight = heights[i]; - m_totalPixelHeight += heights[i]; - } - qInfo("Measured %lld chunks, total height: %f", heights.size(), m_totalPixelHeight); - m_measuring = false; - emit measuringChanged(); - emit totalPixelHeightChanged(); - emit dataChanged(createIndex(0, 0), - createIndex(m_chunks.size() - 1, 0), - {PixelHeightRole}); - - emitRestoreReady(isNew); - }, Qt::QueuedConnection); - }); + emitRestoreReady(isNew); } void ReadingModel::setContentWidth(int width) @@ -173,7 +146,7 @@ void ReadingModel::setFontParams(int fontSize, qreal lineSpacing) void ReadingModel::setImageLoader(std::unique_ptr loader) { - m_imageLoader = std::move(loader); + m_measurer.setImageLoader(std::move(loader)); } void ReadingModel::recalculateCurrentPage() @@ -193,59 +166,28 @@ void ReadingModel::recalculateCurrentPage() void ReadingModel::rebuildPagePairs() { - const int oldPairs = m_pagePairs.size(); - m_pagePairs.clear(); + const int oldPairs = m_pagination.count(); if (!m_isMangaMode || m_chunks.isEmpty()) { - if (m_pagePairs.size() != oldPairs) emit totalPagePairsChanged(); + m_pagination.clear(); + if (m_pagination.count() != oldPairs) emit totalPagePairsChanged(); return; } - if (!m_mangaLandscape) { - // Portrait: every chunk is its own solo pair. - m_pagePairs.reserve(m_chunks.size()); - for (int i = 0; i < m_chunks.size(); ++i) - m_pagePairs.append({i, -1}); - } else { - // Landscape: cover alone, optional shift page alone, then portrait-pair the rest. - m_pagePairs.append({0, -1}); // cover always solo - int i = 1; - if (m_pageShift && i < m_chunks.size()) { - m_pagePairs.append({i, -1}); // page 1 solo when shift is ON - ++i; - } - while (i < m_chunks.size()) { - const QSize sz = m_chunks[i].naturalSize; - const bool isLandscape = sz.isValid() && sz.width() > sz.height(); - if (isLandscape) { - m_pagePairs.append({i, -1}); - ++i; - } else { - // Try to pair with next portrait page. - const int next = i + 1; - if (next < m_chunks.size()) { - const QSize nextSz = m_chunks[next].naturalSize; - const bool nextLandscape = nextSz.isValid() && nextSz.width() > nextSz.height(); - if (!nextLandscape) { - m_pagePairs.append({i, next}); - i += 2; - continue; - } - } - m_pagePairs.append({i, -1}); - ++i; - } - } - } + QVector sizes; + sizes.reserve(m_chunks.size()); + for (const auto &c : m_chunks) + sizes.append(c.naturalSize); + m_pagination.rebuild(sizes, m_mangaLandscape, m_pageShift); - if (m_pagePairs.size() != oldPairs) emit totalPagePairsChanged(); + if (m_pagination.count() != oldPairs) emit totalPagePairsChanged(); // Sync totalPages/currentPage to pair count in manga mode. - if (const int pairs = m_pagePairs.size(); m_totalPages != pairs) { + if (const int pairs = m_pagination.count(); m_totalPages != pairs) { m_totalPages = pairs; emit totalPagesChanged(); } - if (m_currentPage == 0 && !m_pagePairs.isEmpty()) { + if (m_currentPage == 0 && m_pagination.count() > 0) { m_currentPage = 1; emit currentPageChanged(); } @@ -253,8 +195,8 @@ void ReadingModel::rebuildPagePairs() QVariantList ReadingModel::pagePair(int pairIndex) const { - if (pairIndex < 0 || pairIndex >= m_pagePairs.size()) return {}; - const auto &p = m_pagePairs.at(pairIndex); + if (pairIndex < 0 || pairIndex >= m_pagination.count()) return {}; + const auto p = m_pagination.at(pairIndex); QVariantList list; list.append(p.first); if (p.second >= 0) @@ -264,23 +206,13 @@ QVariantList ReadingModel::pagePair(int pairIndex) const int ReadingModel::pairIndexForChunk(int chunkIndex) const { - for (int i = 0; i < m_pagePairs.size(); ++i) { - if (m_pagePairs[i].first == chunkIndex || m_pagePairs[i].second == chunkIndex) - return i; - } - return 0; + return m_pagination.pairIndexForChunk(chunkIndex); } QString ReadingModel::imageUrlForChunk(int chunkIndex) const { if (chunkIndex < 0 || chunkIndex >= m_chunks.size()) return {}; - const QString &html = m_chunks.at(chunkIndex).html; - // Extract src="..." from the img tag. - static const QRegularExpression re(QStringLiteral("]*src=\"([^\"]+)\"")); - const auto match = re.match(html); - if (match.hasMatch()) - return match.captured(1); - return {}; + return m_chunks.at(chunkIndex).imageUrl; } void ReadingModel::setMangaLandscape(bool landscape) @@ -294,16 +226,9 @@ void ReadingModel::setPageShift(bool shift, int currentPairIndex) { if (m_pageShift == shift) return; - // Pick an anchor chunk that keeps an image on screen across the rebuild AND keeps - // back-and-forth toggling stable (no cumulative drift): - // - turning shift ON: anchor on the higher-index chunk (.second). - // - turning shift OFF: anchor on the lower-index chunk (.first). - // For solo pairs (cover, wide spread) fall back to .first. - int currentChunk = 0; - if (currentPairIndex >= 0 && currentPairIndex < m_pagePairs.size()) { - const auto &pair = m_pagePairs.at(currentPairIndex); - currentChunk = (shift && pair.second >= 0) ? pair.second : pair.first; - } + // Anchor on a chunk that keeps an image on screen across the rebuild and + // keeps back-and-forth toggling stable (see MangaPagination for the rule). + const int currentChunk = m_pagination.anchorChunkForShiftToggle(currentPairIndex, shift); m_pageShift = shift; rebuildPagePairs(); @@ -333,6 +258,14 @@ void ReadingModel::setMangaRTL(bool rtl) emit mangaRTLChanged(); } +// Extract src="..." from a chunk's img tag, done once at load time. +static QString extractImageUrl(const QString &html) +{ + static const QRegularExpression re(QStringLiteral("]*src=\"([^\"]+)\"")); + const auto match = re.match(html); + return match.hasMatch() ? match.captured(1) : QString(); +} + void ReadingModel::loadAllChapters() { beginResetModel(); @@ -352,7 +285,8 @@ void ReadingModel::loadAllChapters() QString coverHtml = QStringLiteral("
") + QStringLiteral("
"); - m_chunks.push_back({coverHtml, 0, -1, -1, QSize()}); // chunkInChapter=-1 = cover sentinel + m_chunks.push_back({coverHtml, 0, -1, -1, QSize(), + extractImageUrl(coverHtml)}); // chunkInChapter=-1 = cover sentinel m_chapterStartIndices.append(1); // chapter 0 starts after cover } else { m_chapterStartIndices.append(0); @@ -366,7 +300,7 @@ void ReadingModel::loadAllChapters() int j = 0; for (const auto &html : chapter.contentChunks) { const QSize sz = (j < sizes.size()) ? sizes[j] : QSize(); - m_chunks.push_back({html, i, j, -1, sz}); + m_chunks.push_back({html, i, j, -1, sz, extractImageUrl(html)}); ++j; } } diff --git a/src/backend/ReadingModel.h b/src/backend/ReadingModel.h index 2cc9246..c1074b3 100644 --- a/src/backend/ReadingModel.h +++ b/src/backend/ReadingModel.h @@ -2,13 +2,13 @@ #define READINGMODEL_H #include -#include -#include #include #include #include #include #include "IImageLoader.h" +#include "reading/MangaPagination.h" +#include "reading/MeasurementController.h" #include "state/BookPositionStore.h" class FormatReader; @@ -19,6 +19,7 @@ struct ContentChunk { int chunkInChapter = 0; // 0-based index within chapter (-1 for cover) int pixelHeight = -1; // -1 = not yet measured QSize naturalSize; // image pixel dimensions (null for text chunks) + QString imageUrl; // src of the chunk's img tag (empty for text chunks) }; class ReadingModel : public QAbstractListModel { @@ -114,13 +115,15 @@ signals: void restoreReady(int chunkIndex, int intraChunkOffset); +private slots: + void onHeightsReady(const QVector &heights, bool isNew); + private: static constexpr qreal page_ratio = 1.5; void loadAllChapters(); void recalculateCurrentPage(); void rebuildPagePairs(); - void runMeasurement(const QStringList &htmls, bool isNew); void emitRestoreReady(bool isNew); FormatReader *m_reader = nullptr; @@ -129,7 +132,6 @@ private: int m_totalChapters = 0; int m_currentPage = 0; int m_totalPages = 0; - bool m_measuring = false; bool m_isMangaMode = false; bool m_mangaLandscape = false; bool m_pageShift = true; @@ -139,9 +141,8 @@ private: QVector m_chapterStartIndices; QVector m_chapterTitles; - // Manga page pairs: each QPair holds (leftChunkIdx, rightChunkIdx) where rightChunkIdx - // may be -1 for solo pages. In RTL mode the "left" slot is the later page visually. - QVector> m_pagePairs; + // Manga page-pair layout. In RTL mode the "left" slot is the later page visually. + MangaPagination m_pagination; qreal m_totalPixelHeight = 0.0; qreal m_yOffset = 0.0; @@ -150,8 +151,7 @@ private: qreal m_lineSpacing = 0; BookPositionStore &m_positions; - std::unique_ptr m_imageLoader; - QFuture m_measureFuture; + MeasurementController m_measurer; }; #endif // READINGMODEL_H diff --git a/src/backend/book/Book.cpp b/src/backend/book/Book.cpp index f83ace2..d63f7a4 100644 --- a/src/backend/book/Book.cpp +++ b/src/backend/book/Book.cpp @@ -1,16 +1,17 @@ #include "Book.h" #include #include -#include + +#include "backend/formats/ImageExtensions.h" Book::Book(IFileDialogService &dialog, BookPositionStore &positions, - ReaderFactory &factory, + FormatRegistry ®istry, QObject *parent) : QObject(parent) , m_dialog(dialog) , m_positions(positions) - , m_factory(factory) + , m_registry(registry) { connect(&m_dialog, &IFileDialogService::fileSelected, this, &Book::openFromPath); @@ -28,7 +29,6 @@ bool Book::hasBook() const { return m_reader != nullptr; } bool Book::loading() const { return m_loading; } QString Book::errorMessage() const { return m_errorMessage; } QString Book::coverImageUrl() const { return m_coverImageUrl; } -QString Book::renderingMode() const { return m_renderingMode; } QString Book::title() const { return m_reader ? m_reader->title() : QString(); } QString Book::author() const { return m_reader ? m_reader->author() : QString(); } @@ -61,16 +61,10 @@ void Book::openFromPath(const QString &path) openImpl(path); } -static const QSet kImageExtensions = { - QStringLiteral("jpg"), QStringLiteral("jpeg"), - QStringLiteral("png"), QStringLiteral("gif"), - QStringLiteral("webp") -}; - void Book::browseAndOpen() { - QStringList exts = m_factory.supportedExtensions(); - for (const QString &e : kImageExtensions) + QStringList exts = m_registry.supportedExtensions(); + for (const QString &e : imageFileExtensions()) if (!exts.contains(e)) exts << e; m_dialog.open(exts); } @@ -79,7 +73,7 @@ void Book::openImpl(const QString &filePath) { // Opening a standalone image file triggers folder-comic mode for its parent directory. const QFileInfo fi(filePath); - const QString effectivePath = (!fi.isDir() && kImageExtensions.contains(fi.suffix().toLower())) + const QString effectivePath = (!fi.isDir() && imageFileExtensions().contains(fi.suffix().toLower())) ? fi.absolutePath() : filePath; @@ -97,21 +91,7 @@ void Book::openImpl(const QString &filePath) const int generation = ++m_openGeneration; m_openFuture = QtConcurrent::run([this, effectivePath, generation]() { - auto reader = m_factory.create(effectivePath); - if (!reader) { - QMetaObject::invokeMethod(this, [this, generation, effectivePath]() { - if (generation != m_openGeneration) return; - m_loading = false; - emit loadingChanged(); - m_errorMessage = QStringLiteral("No format reader available for this file type"); - qWarning() << "Book load failed:" << effectivePath << "—" << m_errorMessage; - emit errorMessageChanged(); - }, Qt::QueuedConnection); - return; - } - - if (!reader->open(effectivePath)) { - const QString err = reader->lastError(); + const auto reportError = [this, generation, effectivePath](const QString &err) { QMetaObject::invokeMethod(this, [this, generation, effectivePath, err]() { if (generation != m_openGeneration) return; m_loading = false; @@ -120,6 +100,16 @@ void Book::openImpl(const QString &filePath) qWarning() << "Book load failed:" << effectivePath << "—" << m_errorMessage; emit errorMessageChanged(); }, Qt::QueuedConnection); + }; + + auto reader = m_registry.createReader(effectivePath); + if (!reader) { + reportError(QStringLiteral("No format reader available for this file type")); + return; + } + + if (!reader->open(effectivePath)) { + reportError(reader->lastError()); return; } @@ -132,14 +122,8 @@ void Book::openImpl(const QString &filePath) m_coverImageUrl.clear(); m_loading = false; - const QString newMode = (m_reader->preferredRenderingMode() == FormatReader::RenderingMode::Manga) - ? QStringLiteral("manga") : QStringLiteral("scroll"); - const bool modeChanged = (newMode != m_renderingMode); - m_renderingMode = newMode; - emit loadingChanged(); emit bookChanged(); - if (modeChanged) emit renderingModeChanged(); }, Qt::QueuedConnection); }); } @@ -149,10 +133,7 @@ void Book::close() if (!m_reader) return; m_reader.reset(); m_coverImageUrl.clear(); - const bool modeChanged = (m_renderingMode != QStringLiteral("scroll")); - m_renderingMode = QStringLiteral("scroll"); emit bookChanged(); - if (modeChanged) emit renderingModeChanged(); } void Book::clearError() diff --git a/src/backend/book/Book.h b/src/backend/book/Book.h index 3b8fc2b..b379bfd 100644 --- a/src/backend/book/Book.h +++ b/src/backend/book/Book.h @@ -10,7 +10,7 @@ #include "backend/FormatReader.h" #include "backend/IFileDialogService.h" -#include "backend/formats/ReaderFactory.h" +#include "backend/formats/FormatRegistry.h" #include "backend/state/BookPositionStore.h" class Book : public QObject { @@ -23,11 +23,10 @@ class Book : public QObject { Q_PROPERTY(QString coverImageUrl READ coverImageUrl NOTIFY bookChanged) Q_PROPERTY(QList toc READ toc NOTIFY bookChanged) Q_PROPERTY(QString errorMessage READ errorMessage NOTIFY errorMessageChanged) - Q_PROPERTY(QString renderingMode READ renderingMode NOTIFY renderingModeChanged) public: Book(IFileDialogService &dialog, BookPositionStore &positions, - ReaderFactory &factory, + FormatRegistry ®istry, QObject *parent = nullptr); ~Book() override; @@ -39,9 +38,8 @@ public: QString coverImageUrl() const; QList toc() const; QString errorMessage() const; - QString renderingMode() const; - // Called by main.cpp's bookChanged lambda after the image provider resolves the cover URL. + // Called by AppCoordinator::onBookChanged after the image provider resolves the cover URL. void setCoverImageUrl(const QString &url); // Access the underlying reader for wiring purposes (e.g., to push into ReadingModel). @@ -69,7 +67,6 @@ signals: void bookChanged(); void loadingChanged(); void errorMessageChanged(); - void renderingModeChanged(); void contentWidthChanged(int width); private: @@ -77,11 +74,10 @@ private: IFileDialogService &m_dialog; BookPositionStore &m_positions; - ReaderFactory &m_factory; + FormatRegistry &m_registry; std::unique_ptr m_reader; QString m_coverImageUrl; QString m_errorMessage; - QString m_renderingMode = QStringLiteral("scroll"); bool m_loading = false; int m_openGeneration = 0; int m_contentWidth = 0; diff --git a/src/backend/formats/AsyncImageResponse.cpp b/src/backend/formats/AsyncImageResponse.cpp new file mode 100644 index 0000000..92de8b5 --- /dev/null +++ b/src/backend/formats/AsyncImageResponse.cpp @@ -0,0 +1,34 @@ +#include "AsyncImageResponse.h" + +#include + +AsyncImageResponse::AsyncImageResponse(std::function job) + : m_job(std::move(job)) +{ + setAutoDelete(false); +} + +QQuickTextureFactory *AsyncImageResponse::textureFactory() const +{ + if (m_image.isNull()) + return nullptr; + return QQuickTextureFactory::textureFactoryForImage(m_image); +} + +void AsyncImageResponse::cancel() +{ + m_cancelled.storeRelaxed(1); +} + +void AsyncImageResponse::run() +{ + if (m_cancelled.loadRelaxed()) + return; + + m_image = m_job(); + + if (m_cancelled.loadRelaxed()) + return; + + emit finished(); +} diff --git a/src/backend/formats/AsyncImageResponse.h b/src/backend/formats/AsyncImageResponse.h new file mode 100644 index 0000000..6109c4e --- /dev/null +++ b/src/backend/formats/AsyncImageResponse.h @@ -0,0 +1,24 @@ +#pragma once + +#include +#include +#include +#include +#include + +// Generic async image response: runs the given job on a thread pool and +// publishes the resulting image. Shared by all image providers. +class AsyncImageResponse : public QQuickImageResponse, public QRunnable { + // NO Q_OBJECT — already inherited from QQuickImageResponse +public: + explicit AsyncImageResponse(std::function job); + + QQuickTextureFactory *textureFactory() const override; + void cancel() override; + void run() override; + +private: + std::function m_job; + QAtomicInt m_cancelled{0}; + QImage m_image; +}; diff --git a/src/backend/formats/EntryImageProvider.cpp b/src/backend/formats/EntryImageProvider.cpp new file mode 100644 index 0000000..d34b366 --- /dev/null +++ b/src/backend/formats/EntryImageProvider.cpp @@ -0,0 +1,128 @@ +#include "EntryImageProvider.h" + +#include +#include +#include +#include + +#include "AsyncImageResponse.h" +#include "ImageScaling.h" +#include "ImageUrl.h" + +QImage EntryImageProvider::loadImageFromSource(IByteSource &source, + const QString &entryName, + int displayWidth, + const QSize &requestedSize) +{ + if (entryName.isEmpty()) + return {}; + + const QByteArray data = source.readEntry(entryName); + if (data.isEmpty()) + return {}; + + QImage image; + if (!image.loadFromData(data)) + return {}; + + return scaleToFit(image, displayWidth, requestedSize); +} + +EntryImageProvider::EntryImageProvider(SourceFactory sourceFactory, QString scheme) + : m_sourceFactory(std::move(sourceFactory)) + , m_scheme(std::move(scheme)) +{ +} + +QQuickImageResponse *EntryImageProvider::requestImageResponse(const QString &id, + const QSize &requestedSize) +{ + QString sourcePath; + int displayWidth; + { + QMutexLocker lock(&m_mutex); + sourcePath = m_sourcePath; + displayWidth = m_displayWidth; + } + + // id may be "entry/name.jpg?src=" + const ImageUrl::Parsed parsed = ImageUrl::parseProviderId(id); + const QString entryName = parsed.entry; + if (!parsed.sourcePath.isEmpty()) + sourcePath = parsed.sourcePath; + + auto *response = new AsyncImageResponse( + [factory = m_sourceFactory, sourcePath, entryName, displayWidth, requestedSize]() -> QImage { + auto source = factory(); + if (!source->open(sourcePath)) + return {}; + return loadImageFromSource(*source, entryName, displayWidth, requestedSize); + }); + QThreadPool::globalInstance()->start(response); + return response; +} + +QImage EntryImageProvider::load(const QUrl &url, int maxWidth) const +{ + if (url.scheme() != QLatin1String("image")) + return {}; + + const ImageUrl::Parsed parsed = ImageUrl::parseImageUrl(url); + const QString entryName = parsed.entry; + if (entryName.isEmpty()) + return {}; + + QString sourcePath = parsed.sourcePath; + if (sourcePath.isEmpty()) { + QMutexLocker lock(&m_mutex); + sourcePath = m_sourcePath; + } + + auto source = m_sourceFactory(); + if (!source->open(sourcePath)) + return {}; + return loadImageFromSource(*source, entryName, maxWidth, {}); +} + +std::unique_ptr EntryImageProvider::clone() const +{ + QString sourcePath; + { + QMutexLocker lock(&m_mutex); + sourcePath = m_sourcePath; + } + auto c = std::make_unique(m_sourceFactory, m_scheme); + c->setFilePath(sourcePath); + return c; +} + +void EntryImageProvider::setFilePath(const QString &filePath) +{ + QMutexLocker lock(&m_mutex); + m_sourcePath = filePath; +} + +QString EntryImageProvider::coverImageUrl(const QString &coverPath) const +{ + QString sourcePath; + { QMutexLocker lock(&m_mutex); sourcePath = m_sourcePath; } + return ImageUrl::build(m_scheme, coverPath, sourcePath); +} + +QString EntryImageProvider::scheme() const +{ + return m_scheme; +} + +void EntryImageProvider::setDisplayWidth(int width) +{ + QMutexLocker lock(&m_mutex); + m_displayWidth = width; +} + +void EntryImageProvider::clear() +{ + QMutexLocker lock(&m_mutex); + m_sourcePath.clear(); + m_displayWidth = 0; +} diff --git a/src/backend/formats/EntryImageProvider.h b/src/backend/formats/EntryImageProvider.h new file mode 100644 index 0000000..11d8fef --- /dev/null +++ b/src/backend/formats/EntryImageProvider.h @@ -0,0 +1,41 @@ +#pragma once + +#include "IByteSource.h" +#include "backend/IImageLoader.h" +#include "backend/IImageProvider.h" + +#include +#include +#include +#include + +class EntryImageProvider : public IImageProvider, public IImageLoader { +public: + using SourceFactory = std::function()>; + + EntryImageProvider(SourceFactory sourceFactory, QString scheme); + + QQuickImageResponse *requestImageResponse(const QString &id, + const QSize &requestedSize) override; + + void setFilePath(const QString &filePath) override; + void setDisplayWidth(int width) override; + void clear() override; + QString coverImageUrl(const QString &coverPath) const override; + QString scheme() const override; + + QImage load(const QUrl &url, int maxWidth) const override; + std::unique_ptr clone() const override; + + static QImage loadImageFromSource(IByteSource &source, + const QString &entryName, + int displayWidth, + const QSize &requestedSize); + +private: + SourceFactory m_sourceFactory; + QString m_scheme; + mutable QMutex m_mutex; + QString m_sourcePath; + int m_displayWidth = 0; +}; diff --git a/src/backend/formats/EpubImageProvider.cpp b/src/backend/formats/EpubImageProvider.cpp deleted file mode 100644 index 717f443..0000000 --- a/src/backend/formats/EpubImageProvider.cpp +++ /dev/null @@ -1,202 +0,0 @@ -#include "EpubImageProvider.h" - -#include -#include -#include -#include -#include - -#include - -#include "backend/ZipUtils.h" - -// --------------------------------------------------------------------------- -// EpubImageResponse -// --------------------------------------------------------------------------- - -EpubImageResponse::EpubImageResponse(const QString &epubPath, const QString &id, - int displayWidth, const QSize &requestedSize) - : m_epubPath(epubPath) - , m_id(id) - , m_displayWidth(displayWidth) - , m_requestedSize(requestedSize) -{ - setAutoDelete(false); -} - -QQuickTextureFactory *EpubImageResponse::textureFactory() const -{ - if (m_image.isNull()) - return nullptr; - return QQuickTextureFactory::textureFactoryForImage(m_image); -} - -void EpubImageResponse::cancel() -{ - m_cancelled.storeRelaxed(1); -} - -void EpubImageResponse::run() -{ - if (m_cancelled.loadRelaxed()) - return; - - m_image = EpubImageProvider::loadImageFromEpub( - m_epubPath, m_id, m_displayWidth, m_requestedSize); - - if (m_cancelled.loadRelaxed()) - return; - - emit finished(); -} - -// --------------------------------------------------------------------------- -// EpubImageProvider -// --------------------------------------------------------------------------- - -QQuickImageResponse *EpubImageProvider::requestImageResponse(const QString &id, - const QSize &requestedSize) -{ - QString epubPath; - int displayWidth; - { - QMutexLocker lock(&m_mutex); - epubPath = m_epubPath; - displayWidth = m_displayWidth; - } - - // id may be "internal/path.jpg" (old format) or - // "internal/path.jpg?epub=" (new embedded format). - QString internalPath = id; - const int qmark = id.indexOf(QLatin1Char('?')); - if (qmark >= 0) { - internalPath = id.left(qmark); - const QString query = id.mid(qmark + 1); - // Parse epub= from query string - const QLatin1String key("epub="); - if (query.startsWith(key)) - epubPath = QUrl::fromPercentEncoding(query.mid(key.size()).toUtf8()); - } - - auto *response = new EpubImageResponse(epubPath, internalPath, displayWidth, requestedSize); - QThreadPool::globalInstance()->start(response); - return response; -} - -QImage EpubImageProvider::loadImageFromEpub(const QString &epubPath, const QString &id, - int displayWidth, const QSize &requestedSize) -{ - if (epubPath.isEmpty()) - return {}; - - unzFile zf = unzOpen(epubPath.toUtf8().constData()); - if (!zf) - return {}; - - const QByteArray data = ZipUtils::readZipEntry(zf, id.toUtf8().constData()); - unzClose(zf); - - if (data.isEmpty()) - return {}; - - QImage image; - if (!image.loadFromData(data)) - return {}; - - // Sizing logic: honor EPUB explicit dimensions, scale down to fit display width otherwise - if (requestedSize.width() > 0 || requestedSize.height() > 0) { - int targetW = requestedSize.width() > 0 ? requestedSize.width() : -1; - int targetH = requestedSize.height() > 0 ? requestedSize.height() : -1; - - // Clamp to display width - if (displayWidth > 0 && targetW > 0 && targetW > displayWidth) - targetW = displayWidth; - - if (targetW > 0 && targetH > 0) { - image = image.scaled(QSize(targetW, targetH), Qt::KeepAspectRatio, - Qt::SmoothTransformation); - } else if (targetW > 0) { - image = image.scaledToWidth(targetW, Qt::SmoothTransformation); - } else { - image = image.scaledToHeight(targetH, Qt::SmoothTransformation); - } - } else { - // No EPUB hints: scale down if wider than display, never enlarge - if (displayWidth > 0 && image.width() > displayWidth) - image = image.scaledToWidth(displayWidth, Qt::SmoothTransformation); - } - - return image; -} - -QImage EpubImageProvider::load(const QUrl &url, int maxWidth) const -{ - if (url.scheme() != QLatin1String("image")) - return {}; - - QString zipPath = url.path(); - if (zipPath.startsWith(QLatin1Char('/'))) - zipPath = zipPath.mid(1); - if (zipPath.isEmpty()) - return {}; - - QString epubPath; - if (url.hasQuery()) { - // Embedded format: epub path is in the query string as epub= - const QString q = url.query(); - const QLatin1String key("epub="); - if (q.startsWith(key)) - epubPath = QUrl::fromPercentEncoding(q.mid(key.size()).toUtf8()); - } - if (epubPath.isEmpty()) { - QMutexLocker lock(&m_mutex); - epubPath = m_epubPath; - } - - return loadImageFromEpub(epubPath, zipPath, maxWidth, {}); -} - -std::unique_ptr EpubImageProvider::clone() const -{ - QString epubPath; - { - QMutexLocker lock(&m_mutex); - epubPath = m_epubPath; - } - auto c = std::make_unique(); - c->setFilePath(epubPath); - return c; -} - -void EpubImageProvider::setFilePath(const QString &filePath) -{ - QMutexLocker lock(&m_mutex); - m_epubPath = filePath; -} - -QString EpubImageProvider::coverImageUrl(const QString &coverPath) const -{ - QString epubPath; - { QMutexLocker lock(&m_mutex); epubPath = m_epubPath; } - return QStringLiteral("image://epub/") + coverPath - + QStringLiteral("?epub=") - + QString::fromUtf8(QUrl::toPercentEncoding(epubPath)); -} - -QString EpubImageProvider::scheme() const -{ - return QStringLiteral("epub"); -} - -void EpubImageProvider::setDisplayWidth(int width) -{ - QMutexLocker lock(&m_mutex); - m_displayWidth = width; -} - -void EpubImageProvider::clear() -{ - QMutexLocker lock(&m_mutex); - m_epubPath.clear(); - m_displayWidth = 0; -} diff --git a/src/backend/formats/EpubImageProvider.h b/src/backend/formats/EpubImageProvider.h deleted file mode 100644 index db638e6..0000000 --- a/src/backend/formats/EpubImageProvider.h +++ /dev/null @@ -1,50 +0,0 @@ -#pragma once - -#include -#include -#include - -#include "backend/IImageLoader.h" -#include "backend/IImageProvider.h" - -class EpubImageResponse : public QQuickImageResponse, public QRunnable { - // NO Q_OBJECT — already inherited from QQuickImageResponse -public: - EpubImageResponse(const QString &epubPath, const QString &id, - int displayWidth, const QSize &requestedSize); - - QQuickTextureFactory *textureFactory() const override; - void cancel() override; - void run() override; - -private: - const QString m_epubPath; - const QString m_id; - const int m_displayWidth; - const QSize m_requestedSize; - QAtomicInt m_cancelled{0}; - QImage m_image; -}; - -class EpubImageProvider : public IImageProvider, public IImageLoader { -public: - QQuickImageResponse *requestImageResponse(const QString &id, - const QSize &requestedSize) override; - - void setFilePath(const QString &filePath) override; - void setDisplayWidth(int width) override; - void clear() override; - QString coverImageUrl(const QString &coverPath) const override; - QString scheme() const override; - - QImage load(const QUrl &url, int maxWidth) const override; - std::unique_ptr clone() const override; - - static QImage loadImageFromEpub(const QString &epubPath, const QString &id, - int displayWidth, const QSize &requestedSize); - -private: - mutable QMutex m_mutex; - QString m_epubPath; - int m_displayWidth = 0; -}; diff --git a/src/backend/formats/Fb2ImageProvider.cpp b/src/backend/formats/Fb2ImageProvider.cpp deleted file mode 100644 index 3a04865..0000000 --- a/src/backend/formats/Fb2ImageProvider.cpp +++ /dev/null @@ -1,210 +0,0 @@ -#include "Fb2ImageProvider.h" -#include "Fb2Reader.h" - -#include -#include -#include -#include -#include -#include -#include - -// --------------------------------------------------------------------------- -// Fb2ImageResponse -// --------------------------------------------------------------------------- - -Fb2ImageResponse::Fb2ImageResponse(const QString &fb2Path, const QString &id, - int displayWidth, const QSize &requestedSize) - : m_fb2Path(fb2Path) - , m_id(id) - , m_displayWidth(displayWidth) - , m_requestedSize(requestedSize) -{ - setAutoDelete(false); -} - -QQuickTextureFactory *Fb2ImageResponse::textureFactory() const -{ - if (m_image.isNull()) - return nullptr; - return QQuickTextureFactory::textureFactoryForImage(m_image); -} - -void Fb2ImageResponse::cancel() -{ - m_cancelled.storeRelaxed(1); -} - -void Fb2ImageResponse::run() -{ - if (m_cancelled.loadRelaxed()) - return; - - m_image = Fb2ImageProvider::loadImageFromFb2(m_fb2Path, m_id, m_displayWidth, m_requestedSize); - - if (m_cancelled.loadRelaxed()) - return; - - emit finished(); -} - -// --------------------------------------------------------------------------- -// Fb2ImageProvider -// --------------------------------------------------------------------------- - -QImage Fb2ImageProvider::loadImageFromFb2(const QString &fb2Path, const QString &id, - int displayWidth, const QSize &requestedSize) -{ - if (fb2Path.isEmpty() || id.isEmpty()) - return {}; - - QFile f(fb2Path); - if (!f.open(QIODevice::ReadOnly)) - return {}; - const QByteArray raw = f.readAll(); - f.close(); - - // Construct from decoded QString so the reader operates on pure Unicode, - // bypassing QXmlStreamReader's own encoding detection which may fail for - // Windows-1251 and other encodings not natively supported by Qt 6. - QXmlStreamReader xml(Fb2Reader::decodeRawBytes(raw)); - while (!xml.atEnd()) { - xml.readNext(); - if (!xml.isStartElement() || xml.name() != QLatin1String("binary")) - continue; - if (xml.attributes().value(QLatin1String("id")) != id) - continue; - - // Accumulate text (base64 data may span multiple character events) - QString base64; - while (!xml.atEnd()) { - xml.readNext(); - if (xml.isCharacters()) - base64 += xml.text(); - else - break; - } - - const QByteArray data = QByteArray::fromBase64(base64.toLatin1()); - QImage image; - if (!image.loadFromData(data)) - return {}; - - if (requestedSize.width() > 0 || requestedSize.height() > 0) { - int targetW = requestedSize.width() > 0 ? requestedSize.width() : -1; - int targetH = requestedSize.height() > 0 ? requestedSize.height() : -1; - if (displayWidth > 0 && targetW > 0 && targetW > displayWidth) - targetW = displayWidth; - if (targetW > 0 && targetH > 0) - image = image.scaled(QSize(targetW, targetH), Qt::KeepAspectRatio, Qt::SmoothTransformation); - else if (targetW > 0) - image = image.scaledToWidth(targetW, Qt::SmoothTransformation); - else - image = image.scaledToHeight(targetH, Qt::SmoothTransformation); - } else if (displayWidth > 0 && image.width() > displayWidth) { - image = image.scaledToWidth(displayWidth, Qt::SmoothTransformation); - } - - return image; - } - - return {}; -} - -QQuickImageResponse *Fb2ImageProvider::requestImageResponse(const QString &id, - const QSize &requestedSize) -{ - QString fb2Path; - int displayWidth; - { - QMutexLocker lock(&m_mutex); - fb2Path = m_fb2Path; - displayWidth = m_displayWidth; - } - - // id may have "?fb2=" appended - QString binaryId = id; - const int qmark = id.indexOf(QLatin1Char('?')); - if (qmark >= 0) { - binaryId = id.left(qmark); - const QString query = id.mid(qmark + 1); - const QLatin1String key("fb2="); - if (query.startsWith(key)) - fb2Path = QUrl::fromPercentEncoding(query.mid(key.size()).toUtf8()); - } - - auto *response = new Fb2ImageResponse(fb2Path, binaryId, displayWidth, requestedSize); - QThreadPool::globalInstance()->start(response); - return response; -} - -QImage Fb2ImageProvider::load(const QUrl &url, int maxWidth) const -{ - if (url.scheme() != QLatin1String("image")) - return {}; - - QString binaryId = url.path(); - if (binaryId.startsWith(QLatin1Char('/'))) - binaryId = binaryId.mid(1); - if (binaryId.isEmpty()) - return {}; - - QString fb2Path; - if (url.hasQuery()) { - const QString q = url.query(); - const QLatin1String key("fb2="); - if (q.startsWith(key)) - fb2Path = QUrl::fromPercentEncoding(q.mid(key.size()).toUtf8()); - } - if (fb2Path.isEmpty()) { - QMutexLocker lock(&m_mutex); - fb2Path = m_fb2Path; - } - - return loadImageFromFb2(fb2Path, binaryId, maxWidth, {}); -} - -std::unique_ptr Fb2ImageProvider::clone() const -{ - QString fb2Path; - { - QMutexLocker lock(&m_mutex); - fb2Path = m_fb2Path; - } - auto c = std::make_unique(); - c->setFilePath(fb2Path); - return c; -} - -void Fb2ImageProvider::setFilePath(const QString &filePath) -{ - QMutexLocker lock(&m_mutex); - m_fb2Path = filePath; -} - -QString Fb2ImageProvider::coverImageUrl(const QString &coverPath) const -{ - QString fb2Path; - { QMutexLocker lock(&m_mutex); fb2Path = m_fb2Path; } - return QStringLiteral("image://fb2/") + coverPath - + QStringLiteral("?fb2=") - + QString::fromUtf8(QUrl::toPercentEncoding(fb2Path)); -} - -QString Fb2ImageProvider::scheme() const -{ - return QStringLiteral("fb2"); -} - -void Fb2ImageProvider::setDisplayWidth(int width) -{ - QMutexLocker lock(&m_mutex); - m_displayWidth = width; -} - -void Fb2ImageProvider::clear() -{ - QMutexLocker lock(&m_mutex); - m_fb2Path.clear(); - m_displayWidth = 0; -} diff --git a/src/backend/formats/Fb2ImageProvider.h b/src/backend/formats/Fb2ImageProvider.h deleted file mode 100644 index 1a84445..0000000 --- a/src/backend/formats/Fb2ImageProvider.h +++ /dev/null @@ -1,50 +0,0 @@ -#pragma once - -#include -#include -#include - -#include "backend/IImageLoader.h" -#include "backend/IImageProvider.h" - -class Fb2ImageResponse : public QQuickImageResponse, public QRunnable { - // NO Q_OBJECT — already inherited from QQuickImageResponse -public: - Fb2ImageResponse(const QString &fb2Path, const QString &id, - int displayWidth, const QSize &requestedSize); - - QQuickTextureFactory *textureFactory() const override; - void cancel() override; - void run() override; - -private: - const QString m_fb2Path; - const QString m_id; - const int m_displayWidth; - const QSize m_requestedSize; - QAtomicInt m_cancelled{0}; - QImage m_image; -}; - -class Fb2ImageProvider : public IImageProvider, public IImageLoader { -public: - QQuickImageResponse *requestImageResponse(const QString &id, - const QSize &requestedSize) override; - - void setFilePath(const QString &filePath) override; - void setDisplayWidth(int width) override; - void clear() override; - QString coverImageUrl(const QString &coverPath) const override; - QString scheme() const override; - - QImage load(const QUrl &url, int maxWidth) const override; - std::unique_ptr clone() const override; - - static QImage loadImageFromFb2(const QString &fb2Path, const QString &id, - int displayWidth, const QSize &requestedSize); - -private: - mutable QMutex m_mutex; - QString m_fb2Path; - int m_displayWidth = 0; -}; diff --git a/src/backend/formats/Fb2Reader.cpp b/src/backend/formats/Fb2Reader.cpp index a41059b..5679c73 100644 --- a/src/backend/formats/Fb2Reader.cpp +++ b/src/backend/formats/Fb2Reader.cpp @@ -1,5 +1,7 @@ #include "Fb2Reader.h" +#include "ImageUrl.h" + #include #include #include @@ -247,8 +249,7 @@ bool Fb2Reader::open(const QString &filePath) m_title = QFileInfo(filePath).completeBaseName(); // Pre-compute URL suffix so body image URLs embed the file path (self-contained, encoding-safe). - const QString urlSuffix = QStringLiteral("?fb2=") - + QString::fromUtf8(QUrl::toPercentEncoding(filePath)); + const QString urlSuffix = ImageUrl::querySuffix(filePath); // Body sections for (QDomNode bodyNode = root.firstChild(); !bodyNode.isNull(); bodyNode = bodyNode.nextSibling()) { diff --git a/src/backend/formats/FormatRegistry.cpp b/src/backend/formats/FormatRegistry.cpp new file mode 100644 index 0000000..55dccbf --- /dev/null +++ b/src/backend/formats/FormatRegistry.cpp @@ -0,0 +1,105 @@ +#include "FormatRegistry.h" + +#include "EntryImageProvider.h" +#include "WebImageProvider.h" +#include "backend/FormatReader.h" + +#include +#include + +// Dispatches load() calls to the right child loader based on the image:// host (scheme name). +class CompositeImageLoader : public IImageLoader { +public: + void add(const QString &host, std::unique_ptr loader) + { + m_loaders.emplace_back(host, std::move(loader)); + } + + QImage load(const QUrl &url, int maxWidth) const override + { + const QString host = url.host(); + for (const auto &[h, loader] : m_loaders) { + if (h == host) + return loader->load(url, maxWidth); + } + return {}; + } + + std::unique_ptr clone() const override + { + auto c = std::make_unique(); + for (const auto &[host, loader] : m_loaders) + c->add(host, loader->clone()); + return c; + } + +private: + std::vector>> m_loaders; +}; + +FormatRegistry::FormatRegistry(QVector specs) + : m_specs(std::move(specs)) +{ +} + +const FormatSpec *FormatRegistry::specFor(const QString &filePath) const +{ + const QFileInfo fi(filePath); + const bool isDir = fi.isDir(); + const QString ext = fi.suffix().toLower(); + + for (const FormatSpec &spec : m_specs) { + if (isDir ? spec.matchesDirectory : (!spec.matchesDirectory && spec.extension == ext)) + return &spec; + } + return nullptr; +} + +std::unique_ptr FormatRegistry::createReader(const QString &filePath) const +{ + const FormatSpec *spec = specFor(filePath); + return spec ? spec->makeReader() : nullptr; +} + +IImageProvider *FormatRegistry::createImageProvider(const QString &filePath) const +{ + const FormatSpec *spec = specFor(filePath); + if (!spec || spec->scheme.isEmpty() || !spec->makeSource) + return nullptr; + return new EntryImageProvider(spec->makeSource, spec->scheme); +} + +std::unique_ptr FormatRegistry::createImageLoader(const QString &filePath) const +{ + const FormatSpec *spec = specFor(filePath); + if (!spec || spec->scheme.isEmpty() || !spec->makeSource) + return nullptr; + + auto loader = std::make_unique(spec->makeSource, spec->scheme); + loader->setFilePath(filePath); + + if (!spec->loaderIncludesWeb) + return loader; + + auto composite = std::make_unique(); + composite->add(spec->scheme, std::move(loader)); + composite->add(QStringLiteral("web"), std::make_unique()); + return composite; +} + +QStringList FormatRegistry::supportedExtensions() const +{ + QStringList out; + for (const FormatSpec &spec : m_specs) + if (!spec.matchesDirectory && !spec.extension.isEmpty()) + out << spec.extension; + return out; +} + +void FormatRegistry::registerImageProviders(QQmlEngine &engine) const +{ + for (const FormatSpec &spec : m_specs) + if (!spec.scheme.isEmpty() && spec.makeSource) + engine.addImageProvider(spec.scheme, + new EntryImageProvider(spec.makeSource, spec.scheme)); +} diff --git a/src/backend/formats/FormatRegistry.h b/src/backend/formats/FormatRegistry.h new file mode 100644 index 0000000..ed11352 --- /dev/null +++ b/src/backend/formats/FormatRegistry.h @@ -0,0 +1,49 @@ +#pragma once + +#include +#include +#include +#include +#include + +class FormatReader; +class IByteSource; +class IImageLoader; +class IImageProvider; +class QQmlEngine; + +// One row per supported format. Everything a format needs — reader, image +// byte source, provider scheme — is declared in one place; adding a format +// means adding one row to the table built in main(). +struct FormatSpec { + QString extension; // lowercase, without dot; unused when matchesDirectory + bool matchesDirectory = false; + QString scheme; // image:// scheme; empty = format has no images + std::function()> makeReader; + std::function()> makeSource; // required when scheme is set + bool loaderIncludesWeb = false; // formats whose content may reference web images (epub) +}; + +class FormatRegistry { +public: + explicit FormatRegistry(QVector specs); + + std::unique_ptr createReader(const QString &filePath) const; + + // New provider for the format, or nullptr for formats without images. + // Caller owns the pointer (the QML engine takes ownership on registration). + IImageProvider *createImageProvider(const QString &filePath) const; + + // Synchronous loader for measurement, or nullptr for formats without images. + std::unique_ptr createImageLoader(const QString &filePath) const; + + QStringList supportedExtensions() const; + + // Register one provider per scheme with the QML engine (engine takes ownership). + void registerImageProviders(QQmlEngine &engine) const; + +private: + const FormatSpec *specFor(const QString &filePath) const; + + QVector m_specs; +}; diff --git a/src/backend/formats/comic/IComicSource.h b/src/backend/formats/IByteSource.h similarity index 81% rename from src/backend/formats/comic/IComicSource.h rename to src/backend/formats/IByteSource.h index a9f12ae..8cce60d 100644 --- a/src/backend/formats/comic/IComicSource.h +++ b/src/backend/formats/IByteSource.h @@ -5,10 +5,10 @@ #include // Abstracts how raw image bytes are obtained from a named entry. -// Implementations: ZipComicSource (minizip), RarComicSource (libarchive), DirComicSource (QDir/QFile). -class IComicSource { +// Implementations: ZipByteSource (minizip), RarByteSource (libarchive), DirByteSource (QDir/QFile). +class IByteSource { public: - virtual ~IComicSource() = default; + virtual ~IByteSource() = default; // Opens the source. After returning true, listEntries/readEntry/contentHash are valid. virtual bool open(const QString &path) = 0; diff --git a/src/backend/formats/ImageExtensions.h b/src/backend/formats/ImageExtensions.h new file mode 100644 index 0000000..e6bbd10 --- /dev/null +++ b/src/backend/formats/ImageExtensions.h @@ -0,0 +1,15 @@ +#pragma once + +#include +#include + +// File extensions treated as standalone images (comic pages, folder comics). +inline const QSet &imageFileExtensions() +{ + static const QSet kExtensions = { + QStringLiteral("jpg"), QStringLiteral("jpeg"), + QStringLiteral("png"), QStringLiteral("gif"), + QStringLiteral("webp") + }; + return kExtensions; +} diff --git a/src/backend/formats/ImageLoaderFactory.cpp b/src/backend/formats/ImageLoaderFactory.cpp deleted file mode 100644 index bc26bcb..0000000 --- a/src/backend/formats/ImageLoaderFactory.cpp +++ /dev/null @@ -1,78 +0,0 @@ -#include "ImageLoaderFactory.h" -#include "comic/Cbz.h" -#include "comic/Cbr.h" -#include "comic/Folder.h" -#include "EpubImageProvider.h" -#include "Fb2ImageProvider.h" -#include "WebImageProvider.h" -#include - -// Dispatches load() calls to the right child loader based on the image:// host (scheme name). -class CompositeImageLoader : public IImageLoader { -public: - void add(const QString &host, std::unique_ptr loader) - { - m_loaders.emplace_back(host, std::move(loader)); - } - - QImage load(const QUrl &url, int maxWidth) const override - { - const QString host = url.host(); - for (const auto &[h, loader] : m_loaders) { - if (h == host) - return loader->load(url, maxWidth); - } - return {}; - } - - std::unique_ptr clone() const override - { - auto c = std::make_unique(); - for (const auto &[host, loader] : m_loaders) - c->add(host, loader->clone()); - return c; - } - -private: - std::vector>> m_loaders; -}; - -std::unique_ptr ImageLoaderFactory::create(const QString &filePath) -{ - const QFileInfo fi(filePath); - - if (fi.isDir()) { - auto loader = std::make_unique(); - loader->setFilePath(filePath); - return loader; - } - - const QString ext = fi.suffix().toLower(); - if (ext == QLatin1String("epub")) { - auto composite = std::make_unique(); - - auto epubLoader = std::make_unique(); - epubLoader->setFilePath(filePath); - composite->add(QStringLiteral("epub"), std::move(epubLoader)); - - composite->add(QStringLiteral("web"), std::make_unique()); - - return composite; - } - if (ext == QLatin1String("fb2")) { - auto loader = std::make_unique(); - loader->setFilePath(filePath); - return loader; - } - if (ext == QLatin1String("cbz")) { - auto loader = std::make_unique(); - loader->setFilePath(filePath); - return loader; - } - if (ext == QLatin1String("cbr")) { - auto loader = std::make_unique(); - loader->setFilePath(filePath); - return loader; - } - return nullptr; -} diff --git a/src/backend/formats/ImageLoaderFactory.h b/src/backend/formats/ImageLoaderFactory.h deleted file mode 100644 index 244445a..0000000 --- a/src/backend/formats/ImageLoaderFactory.h +++ /dev/null @@ -1,11 +0,0 @@ -#pragma once -#include -#include - -class IImageLoader; - -class ImageLoaderFactory { -public: - // Returns a new loader for the given file format, or nullptr for formats without images. - static std::unique_ptr create(const QString &filePath); -}; diff --git a/src/backend/formats/ImageProviderFactory.cpp b/src/backend/formats/ImageProviderFactory.cpp deleted file mode 100644 index 85c0d3c..0000000 --- a/src/backend/formats/ImageProviderFactory.cpp +++ /dev/null @@ -1,24 +0,0 @@ -#include "ImageProviderFactory.h" -#include "comic/Cbz.h" -#include "comic/Cbr.h" -#include "comic/Folder.h" -#include "EpubImageProvider.h" -#include "Fb2ImageProvider.h" -#include - -IImageProvider *ImageProviderFactory::create(const QString &filePath) -{ - const QFileInfo fi(filePath); - if (fi.isDir()) - return new FolderImageProvider(); - const QString ext = fi.suffix().toLower(); - if (ext == QLatin1String("epub")) - return new EpubImageProvider(); - if (ext == QLatin1String("fb2")) - return new Fb2ImageProvider(); - if (ext == QLatin1String("cbz")) - return new CbzImageProvider(); - if (ext == QLatin1String("cbr")) - return new CbrImageProvider(); - return nullptr; -} diff --git a/src/backend/formats/ImageProviderFactory.h b/src/backend/formats/ImageProviderFactory.h deleted file mode 100644 index 013a73d..0000000 --- a/src/backend/formats/ImageProviderFactory.h +++ /dev/null @@ -1,11 +0,0 @@ -#pragma once -#include - -class IImageProvider; - -class ImageProviderFactory { -public: - // Returns a new provider for the given file format, or nullptr for formats without images. - // Caller is responsible for the returned pointer's lifetime. - static IImageProvider *create(const QString &filePath); -}; diff --git a/src/backend/formats/ImageScaling.h b/src/backend/formats/ImageScaling.h new file mode 100644 index 0000000..b32b037 --- /dev/null +++ b/src/backend/formats/ImageScaling.h @@ -0,0 +1,30 @@ +#pragma once + +#include +#include + +// Honor an explicit requested size (clamped to the display width), otherwise +// scale down to fit the display width — never enlarge. +inline QImage scaleToFit(QImage image, int displayWidth, const QSize &requestedSize) +{ + if (requestedSize.width() > 0 || requestedSize.height() > 0) { + int targetW = requestedSize.width() > 0 ? requestedSize.width() : -1; + int targetH = requestedSize.height() > 0 ? requestedSize.height() : -1; + + if (displayWidth > 0 && targetW > 0 && targetW > displayWidth) + targetW = displayWidth; + + if (targetW > 0 && targetH > 0) { + image = image.scaled(QSize(targetW, targetH), Qt::KeepAspectRatio, + Qt::SmoothTransformation); + } else if (targetW > 0) { + image = image.scaledToWidth(targetW, Qt::SmoothTransformation); + } else { + image = image.scaledToHeight(targetH, Qt::SmoothTransformation); + } + } else { + if (displayWidth > 0 && image.width() > displayWidth) + image = image.scaledToWidth(displayWidth, Qt::SmoothTransformation); + } + return image; +} diff --git a/src/backend/formats/ImageUrl.cpp b/src/backend/formats/ImageUrl.cpp new file mode 100644 index 0000000..17e4b05 --- /dev/null +++ b/src/backend/formats/ImageUrl.cpp @@ -0,0 +1,60 @@ +#include "ImageUrl.h" + +#include +#include + +namespace { +const QLatin1String kSrcKey("src="); +} + +namespace ImageUrl { + +QString build(const QString &scheme, const QString &entry) +{ + return QStringLiteral("image://") + scheme + QLatin1Char('/') + entry; +} + +QString build(const QString &scheme, const QString &entry, const QString &sourcePath) +{ + return build(scheme, entry) + querySuffix(sourcePath); +} + +QString querySuffix(const QString &sourcePath) +{ + return QStringLiteral("?src=") + + QString::fromUtf8(QUrl::toPercentEncoding(sourcePath)); +} + +Parsed parseProviderId(const QString &id) +{ + Parsed result; + result.entry = id; + + const int qmark = id.indexOf(QLatin1Char('?')); + if (qmark >= 0) { + result.entry = id.left(qmark); + const QString query = id.mid(qmark + 1); + if (query.startsWith(kSrcKey)) + result.sourcePath = QUrl::fromPercentEncoding(query.mid(kSrcKey.size()).toUtf8()); + } + result.entry = QUrl::fromPercentEncoding(result.entry.toUtf8()); + return result; +} + +Parsed parseImageUrl(const QUrl &url) +{ + Parsed result; + + result.entry = url.path(); + if (result.entry.startsWith(QLatin1Char('/'))) + result.entry = result.entry.mid(1); + + if (url.hasQuery()) { + const QString query = url.query(); + if (query.startsWith(kSrcKey)) + result.sourcePath = QUrl::fromPercentEncoding(query.mid(kSrcKey.size()).toUtf8()); + } + return result; +} + +} // namespace ImageUrl diff --git a/src/backend/formats/ImageUrl.h b/src/backend/formats/ImageUrl.h new file mode 100644 index 0000000..ac95943 --- /dev/null +++ b/src/backend/formats/ImageUrl.h @@ -0,0 +1,30 @@ +#pragma once + +#include +#include + +// Single authority for the image-provider URL grammar: +// image:///[?src=] +// The optional src query names the container file (archive, document) the +// entry lives in; when absent, providers fall back to their current file. +namespace ImageUrl { + +QString build(const QString &scheme, const QString &entry); +QString build(const QString &scheme, const QString &entry, const QString &sourcePath); + +// "?src=" — for appending to an existing URL. +QString querySuffix(const QString &sourcePath); + +struct Parsed { + QString entry; + QString sourcePath; // empty = use the provider's current file +}; + +// Parse the id handed to QQuickAsyncImageProvider (scheme already stripped, +// entry arrives percent-encoded). +Parsed parseProviderId(const QString &id); + +// Parse a full image:// URL (IImageLoader::load path). +Parsed parseImageUrl(const QUrl &url); + +} // namespace ImageUrl diff --git a/src/backend/formats/ReaderFactory.cpp b/src/backend/formats/ReaderFactory.cpp deleted file mode 100644 index 083b1e8..0000000 --- a/src/backend/formats/ReaderFactory.cpp +++ /dev/null @@ -1,31 +0,0 @@ -#include "ReaderFactory.h" -#include "backend/FormatReader.h" - -#include - -ReaderFactory::ReaderFactory(QList creators) -{ - for (const auto &creator : creators) { - auto probe = creator(); - m_registry[probe->fileType()] = creator; - } -} - -std::unique_ptr ReaderFactory::create(const QString &filePath) const -{ - const QFileInfo fi(filePath); - const QString key = fi.isDir() ? QStringLiteral("") : fi.suffix().toLower(); - auto it = m_registry.find(key); - if (it == m_registry.end()) - return nullptr; - return it.value()(); -} - -QStringList ReaderFactory::supportedExtensions() const -{ - QStringList out; - for (auto it = m_registry.cbegin(); it != m_registry.cend(); ++it) - if (!it.key().startsWith(QLatin1Char('<'))) - out << it.key(); - return out; -} diff --git a/src/backend/formats/ReaderFactory.h b/src/backend/formats/ReaderFactory.h deleted file mode 100644 index b672b85..0000000 --- a/src/backend/formats/ReaderFactory.h +++ /dev/null @@ -1,25 +0,0 @@ -#ifndef READERFACTORY_H -#define READERFACTORY_H - -#include -#include -#include -#include - -class FormatReader; - -class ReaderFactory { -public: - using CreatorFn = std::function()>; - - // Constructs the factory by probing each creator via fileType() to build the registry. - explicit ReaderFactory(QList creators); - - std::unique_ptr create(const QString &filePath) const; - QStringList supportedExtensions() const; - -private: - QMap m_registry; // extension -> creator -}; - -#endif // READERFACTORY_H diff --git a/src/backend/formats/WebImageProvider.cpp b/src/backend/formats/WebImageProvider.cpp index 4d78513..d695646 100644 --- a/src/backend/formats/WebImageProvider.cpp +++ b/src/backend/formats/WebImageProvider.cpp @@ -10,10 +10,12 @@ #include #include #include -#include #include #include +#include "AsyncImageResponse.h" +#include "ImageScaling.h" + // --------------------------------------------------------------------------- // Helpers // --------------------------------------------------------------------------- @@ -33,30 +35,6 @@ QString WebImageProvider::cacheFilePath(const QString &urlString) + (ext.isEmpty() ? QString() : QLatin1Char('.') + ext); } -static QImage scaleToFit(QImage image, int displayWidth, const QSize &requestedSize) -{ - if (requestedSize.width() > 0 || requestedSize.height() > 0) { - int targetW = requestedSize.width() > 0 ? requestedSize.width() : -1; - int targetH = requestedSize.height() > 0 ? requestedSize.height() : -1; - - if (displayWidth > 0 && targetW > 0 && targetW > displayWidth) - targetW = displayWidth; - - if (targetW > 0 && targetH > 0) { - image = image.scaled(QSize(targetW, targetH), Qt::KeepAspectRatio, - Qt::SmoothTransformation); - } else if (targetW > 0) { - image = image.scaledToWidth(targetW, Qt::SmoothTransformation); - } else { - image = image.scaledToHeight(targetH, Qt::SmoothTransformation); - } - } else { - if (displayWidth > 0 && image.width() > displayWidth) - image = image.scaledToWidth(displayWidth, Qt::SmoothTransformation); - } - return image; -} - // --------------------------------------------------------------------------- // WebImageProvider // --------------------------------------------------------------------------- @@ -114,44 +92,6 @@ QImage WebImageProvider::loadWebImage(const QString &urlString, int displayWidth return scaleToFit(image, displayWidth, requestedSize); } -// --------------------------------------------------------------------------- -// WebImageResponse -// --------------------------------------------------------------------------- - -WebImageResponse::WebImageResponse(const QString &url, int displayWidth, - const QSize &requestedSize) - : m_url(url) - , m_displayWidth(displayWidth) - , m_requestedSize(requestedSize) -{ - setAutoDelete(false); -} - -QQuickTextureFactory *WebImageResponse::textureFactory() const -{ - if (m_image.isNull()) - return nullptr; - return QQuickTextureFactory::textureFactoryForImage(m_image); -} - -void WebImageResponse::cancel() -{ - m_cancelled.storeRelaxed(1); -} - -void WebImageResponse::run() -{ - if (m_cancelled.loadRelaxed()) - return; - - m_image = WebImageProvider::loadWebImage(m_url, m_displayWidth, m_requestedSize); - - if (m_cancelled.loadRelaxed()) - return; - - emit finished(); -} - // --------------------------------------------------------------------------- // WebImageProvider — IImageProvider // --------------------------------------------------------------------------- @@ -164,7 +104,7 @@ QQuickImageResponse *WebImageProvider::requestImageResponse(const QString &id, // a "Cannot create children for a parent in a different thread" warning). // Return an empty response immediately — no network request needed. if (id == QLatin1String("__warmup__")) { - auto *response = new WebImageResponse(id, 0, requestedSize); + auto *response = new AsyncImageResponse([] { return QImage(); }); QMetaObject::invokeMethod(response, "finished", Qt::QueuedConnection); return response; } @@ -174,7 +114,9 @@ QQuickImageResponse *WebImageProvider::requestImageResponse(const QString &id, QMutexLocker lock(&m_mutex); displayWidth = m_displayWidth; } - auto *response = new WebImageResponse(id, displayWidth, requestedSize); + auto *response = new AsyncImageResponse([id, displayWidth, requestedSize] { + return loadWebImage(id, displayWidth, requestedSize); + }); QThreadPool::globalInstance()->start(response); return response; } diff --git a/src/backend/formats/WebImageProvider.h b/src/backend/formats/WebImageProvider.h index da74f9a..04ea272 100644 --- a/src/backend/formats/WebImageProvider.h +++ b/src/backend/formats/WebImageProvider.h @@ -1,31 +1,12 @@ #pragma once -#include #include -#include #include #include #include "backend/IImageLoader.h" #include "backend/IImageProvider.h" -class WebImageResponse : public QQuickImageResponse, public QRunnable { - // NO Q_OBJECT — already inherited from QQuickImageResponse -public: - WebImageResponse(const QString &url, int displayWidth, const QSize &requestedSize); - - QQuickTextureFactory *textureFactory() const override; - void cancel() override; - void run() override; - -private: - const QString m_url; - const int m_displayWidth; - const QSize m_requestedSize; - QAtomicInt m_cancelled{0}; - QImage m_image; -}; - class WebImageProvider : public IImageProvider, public IImageLoader { public: QQuickImageResponse *requestImageResponse(const QString &id, diff --git a/src/backend/formats/comic/Cbr.cpp b/src/backend/formats/comic/Cbr.cpp deleted file mode 100644 index 8f8a12c..0000000 --- a/src/backend/formats/comic/Cbr.cpp +++ /dev/null @@ -1 +0,0 @@ -// Cbr shells are header-only (constructors inline in Cbr.h). diff --git a/src/backend/formats/comic/Cbr.h b/src/backend/formats/comic/Cbr.h deleted file mode 100644 index 23a7db1..0000000 --- a/src/backend/formats/comic/Cbr.h +++ /dev/null @@ -1,7 +0,0 @@ -#pragma once - -// Convenience header — includes both reader and provider shells. -// Use CbrReader.h if you only need the reader (avoids Qt::Quick dependency). - -#include "CbrReader.h" -#include "CbrProvider.h" diff --git a/src/backend/formats/comic/CbrProvider.h b/src/backend/formats/comic/CbrProvider.h deleted file mode 100644 index 1ec661c..0000000 --- a/src/backend/formats/comic/CbrProvider.h +++ /dev/null @@ -1,11 +0,0 @@ -#pragma once - -#include "ComicImageProvider.h" -#include "RarComicSource.h" - -class CbrImageProvider : public ComicImageProvider { -public: - CbrImageProvider() - : ComicImageProvider([] { return std::make_unique(); }, - QStringLiteral("cbr")) {} -}; diff --git a/src/backend/formats/comic/CbrReader.h b/src/backend/formats/comic/CbrReader.h index 37bc6c1..b492dc6 100644 --- a/src/backend/formats/comic/CbrReader.h +++ b/src/backend/formats/comic/CbrReader.h @@ -1,12 +1,12 @@ #pragma once #include "ComicReader.h" -#include "RarComicSource.h" +#include "backend/formats/sources/RarByteSource.h" class CbrReader : public ComicReader { public: CbrReader() - : ComicReader([] { return std::make_unique(); }, + : ComicReader([] { return std::make_unique(); }, QStringLiteral("cbr"), QStringLiteral("cbr")) {} }; diff --git a/src/backend/formats/comic/Cbz.cpp b/src/backend/formats/comic/Cbz.cpp deleted file mode 100644 index aa7b88e..0000000 --- a/src/backend/formats/comic/Cbz.cpp +++ /dev/null @@ -1 +0,0 @@ -// Cbz shells are header-only (constructors inline in Cbz.h). diff --git a/src/backend/formats/comic/Cbz.h b/src/backend/formats/comic/Cbz.h deleted file mode 100644 index 6820a03..0000000 --- a/src/backend/formats/comic/Cbz.h +++ /dev/null @@ -1,7 +0,0 @@ -#pragma once - -// Convenience header — includes both reader and provider shells. -// Use CbzReader.h if you only need the reader (avoids Qt::Quick dependency). - -#include "CbzReader.h" -#include "CbzProvider.h" diff --git a/src/backend/formats/comic/CbzProvider.h b/src/backend/formats/comic/CbzProvider.h deleted file mode 100644 index 3a82fdc..0000000 --- a/src/backend/formats/comic/CbzProvider.h +++ /dev/null @@ -1,11 +0,0 @@ -#pragma once - -#include "ComicImageProvider.h" -#include "ZipComicSource.h" - -class CbzImageProvider : public ComicImageProvider { -public: - CbzImageProvider() - : ComicImageProvider([] { return std::make_unique(); }, - QStringLiteral("cbz")) {} -}; diff --git a/src/backend/formats/comic/CbzReader.h b/src/backend/formats/comic/CbzReader.h index a31cf36..8bf6128 100644 --- a/src/backend/formats/comic/CbzReader.h +++ b/src/backend/formats/comic/CbzReader.h @@ -1,12 +1,12 @@ #pragma once #include "ComicReader.h" -#include "ZipComicSource.h" +#include "backend/formats/sources/ZipByteSource.h" class CbzReader : public ComicReader { public: CbzReader() - : ComicReader([] { return std::make_unique(); }, + : ComicReader([] { return std::make_unique(); }, QStringLiteral("cbz"), QStringLiteral("cbz")) {} }; diff --git a/src/backend/formats/comic/ComicImageProvider.cpp b/src/backend/formats/comic/ComicImageProvider.cpp deleted file mode 100644 index 1eda5bb..0000000 --- a/src/backend/formats/comic/ComicImageProvider.cpp +++ /dev/null @@ -1,202 +0,0 @@ -#include "ComicImageProvider.h" - -#include -#include -#include -#include -#include - -// --------------------------------------------------------------------------- -// ComicImageResponse -// --------------------------------------------------------------------------- - -ComicImageResponse::ComicImageResponse(SourceFactory sourceFactory, - const QString &sourcePath, - const QString &entryName, - int displayWidth, - const QSize &requestedSize) - : m_sourceFactory(std::move(sourceFactory)) - , m_sourcePath(sourcePath) - , m_entryName(entryName) - , m_displayWidth(displayWidth) - , m_requestedSize(requestedSize) -{ - setAutoDelete(false); -} - -QQuickTextureFactory *ComicImageResponse::textureFactory() const -{ - if (m_image.isNull()) - return nullptr; - return QQuickTextureFactory::textureFactoryForImage(m_image); -} - -void ComicImageResponse::cancel() -{ - m_cancelled.storeRelaxed(1); -} - -void ComicImageResponse::run() -{ - if (m_cancelled.loadRelaxed()) - return; - - auto source = m_sourceFactory(); - if (source->open(m_sourcePath)) - m_image = ComicImageProvider::loadImageFromSource(*source, m_sourcePath, - m_entryName, m_displayWidth, - m_requestedSize); - - if (m_cancelled.loadRelaxed()) - return; - - emit finished(); -} - -// --------------------------------------------------------------------------- -// ComicImageProvider -// --------------------------------------------------------------------------- - -QImage ComicImageProvider::loadImageFromSource(IComicSource &source, - const QString &/*sourcePath*/, - const QString &entryName, - int displayWidth, - const QSize &requestedSize) -{ - if (entryName.isEmpty()) - return {}; - - const QByteArray data = source.readEntry(entryName); - if (data.isEmpty()) - return {}; - - QImage image; - if (!image.loadFromData(data)) - return {}; - - if (requestedSize.width() > 0 || requestedSize.height() > 0) { - int targetW = requestedSize.width() > 0 ? requestedSize.width() : -1; - int targetH = requestedSize.height() > 0 ? requestedSize.height() : -1; - if (displayWidth > 0 && targetW > 0 && targetW > displayWidth) - targetW = displayWidth; - if (targetW > 0 && targetH > 0) - image = image.scaled(QSize(targetW, targetH), Qt::KeepAspectRatio, Qt::SmoothTransformation); - else if (targetW > 0) - image = image.scaledToWidth(targetW, Qt::SmoothTransformation); - else - image = image.scaledToHeight(targetH, Qt::SmoothTransformation); - } else if (displayWidth > 0 && image.width() > displayWidth) { - image = image.scaledToWidth(displayWidth, Qt::SmoothTransformation); - } - - return image; -} - -ComicImageProvider::ComicImageProvider(SourceFactory sourceFactory, QString scheme) - : m_sourceFactory(std::move(sourceFactory)) - , m_scheme(std::move(scheme)) -{ -} - -QQuickImageResponse *ComicImageProvider::requestImageResponse(const QString &id, - const QSize &requestedSize) -{ - QString sourcePath; - int displayWidth; - { - QMutexLocker lock(&m_mutex); - sourcePath = m_sourcePath; - displayWidth = m_displayWidth; - } - - // id may be "entry/name.jpg?src=" - QString entryName = id; - const int qmark = id.indexOf(QLatin1Char('?')); - if (qmark >= 0) { - entryName = id.left(qmark); - const QString query = id.mid(qmark + 1); - const QLatin1String key("src="); - if (query.startsWith(key)) - sourcePath = QUrl::fromPercentEncoding(query.mid(key.size()).toUtf8()); - } - entryName = QUrl::fromPercentEncoding(entryName.toUtf8()); - - auto *response = new ComicImageResponse(m_sourceFactory, sourcePath, entryName, - displayWidth, requestedSize); - QThreadPool::globalInstance()->start(response); - return response; -} - -QImage ComicImageProvider::load(const QUrl &url, int maxWidth) const -{ - if (url.scheme() != QLatin1String("image")) - return {}; - - QString entryName = url.path(); - if (entryName.startsWith(QLatin1Char('/'))) - entryName = entryName.mid(1); - if (entryName.isEmpty()) - return {}; - - QString sourcePath; - if (url.hasQuery()) { - const QString q = url.query(); - const QLatin1String key("src="); - if (q.startsWith(key)) - sourcePath = QUrl::fromPercentEncoding(q.mid(key.size()).toUtf8()); - } - if (sourcePath.isEmpty()) { - QMutexLocker lock(&m_mutex); - sourcePath = m_sourcePath; - } - - auto source = m_sourceFactory(); - if (!source->open(sourcePath)) - return {}; - return loadImageFromSource(*source, sourcePath, entryName, maxWidth, {}); -} - -std::unique_ptr ComicImageProvider::clone() const -{ - QString sourcePath; - { - QMutexLocker lock(&m_mutex); - sourcePath = m_sourcePath; - } - auto c = std::make_unique(m_sourceFactory, m_scheme); - c->setFilePath(sourcePath); - return c; -} - -void ComicImageProvider::setFilePath(const QString &filePath) -{ - QMutexLocker lock(&m_mutex); - m_sourcePath = filePath; -} - -QString ComicImageProvider::coverImageUrl(const QString &coverPath) const -{ - QString sourcePath; - { QMutexLocker lock(&m_mutex); sourcePath = m_sourcePath; } - return QStringLiteral("image://") + m_scheme + QLatin1Char('/') + coverPath - + QStringLiteral("?src=") - + QString::fromUtf8(QUrl::toPercentEncoding(sourcePath)); -} - -QString ComicImageProvider::scheme() const -{ - return m_scheme; -} - -void ComicImageProvider::setDisplayWidth(int width) -{ - QMutexLocker lock(&m_mutex); - m_displayWidth = width; -} - -void ComicImageProvider::clear() -{ - QMutexLocker lock(&m_mutex); - m_sourcePath.clear(); - m_displayWidth = 0; -} diff --git a/src/backend/formats/comic/ComicImageProvider.h b/src/backend/formats/comic/ComicImageProvider.h deleted file mode 100644 index 3e5fcd9..0000000 --- a/src/backend/formats/comic/ComicImageProvider.h +++ /dev/null @@ -1,70 +0,0 @@ -#pragma once - -#include "IComicSource.h" - -#include "backend/IImageLoader.h" -#include "backend/IImageProvider.h" - -#include -#include -#include -#include -#include -#include - -class ComicImageResponse : public QQuickImageResponse, public QRunnable { - // NO Q_OBJECT — already inherited from QQuickImageResponse -public: - using SourceFactory = std::function()>; - - ComicImageResponse(SourceFactory sourceFactory, - const QString &sourcePath, - const QString &entryName, - int displayWidth, - const QSize &requestedSize); - - QQuickTextureFactory *textureFactory() const override; - void cancel() override; - void run() override; - -private: - SourceFactory m_sourceFactory; - const QString m_sourcePath; - const QString m_entryName; - const int m_displayWidth; - const QSize m_requestedSize; - QAtomicInt m_cancelled{0}; - QImage m_image; -}; - -class ComicImageProvider : public IImageProvider, public IImageLoader { -public: - using SourceFactory = std::function()>; - - ComicImageProvider(SourceFactory sourceFactory, QString scheme); - - QQuickImageResponse *requestImageResponse(const QString &id, - const QSize &requestedSize) override; - - void setFilePath(const QString &filePath) override; - void setDisplayWidth(int width) override; - void clear() override; - QString coverImageUrl(const QString &coverPath) const override; - QString scheme() const override; - - QImage load(const QUrl &url, int maxWidth) const override; - std::unique_ptr clone() const override; - - static QImage loadImageFromSource(IComicSource &source, - const QString &sourcePath, - const QString &entryName, - int displayWidth, - const QSize &requestedSize); - -private: - SourceFactory m_sourceFactory; - QString m_scheme; - mutable QMutex m_mutex; - QString m_sourcePath; - int m_displayWidth = 0; -}; diff --git a/src/backend/formats/comic/ComicReader.cpp b/src/backend/formats/comic/ComicReader.cpp index b4876fe..8496bd0 100644 --- a/src/backend/formats/comic/ComicReader.cpp +++ b/src/backend/formats/comic/ComicReader.cpp @@ -3,9 +3,11 @@ #include #include #include -#include #include +#include "backend/formats/ImageExtensions.h" +#include "backend/formats/ImageUrl.h" + // --------------------------------------------------------------------------- // ComicInfo.xml parsing // --------------------------------------------------------------------------- @@ -55,12 +57,6 @@ static void parseComicInfo(const QByteArray &data, // ComicReader // --------------------------------------------------------------------------- -static const QSet kImageExtensions = { - QStringLiteral("jpg"), QStringLiteral("jpeg"), - QStringLiteral("png"), QStringLiteral("gif"), - QStringLiteral("webp") -}; - ComicReader::ComicReader(SourceFactory sourceFactory, QString fileType, QString scheme) : m_sourceFactory(std::move(sourceFactory)) , m_fileType(std::move(fileType)) @@ -79,7 +75,7 @@ bool ComicReader::parseSource(const QString &filePath) return parseOpenSource(filePath, *source); } -bool ComicReader::parseOpenSource(const QString &filePath, IComicSource &source) +bool ComicReader::parseOpenSource(const QString &filePath, IByteSource &source) { const QStringList allEntries = source.listEntries(); @@ -91,7 +87,7 @@ bool ComicReader::parseOpenSource(const QString &filePath, IComicSource &source) ? entry.section(QLatin1Char('/'), -1) : entry; if (baseName.startsWith(QLatin1Char('.'))) continue; - if (kImageExtensions.contains(QFileInfo(entry).suffix().toLower())) + if (imageFileExtensions().contains(QFileInfo(entry).suffix().toLower())) imageEntries.append(entry); } imageEntries.sort(); @@ -177,8 +173,8 @@ Chapter ComicReader::loadChapter(int index) chunks.reserve(m_pageEntries.size()); for (const PageEntry &page : m_pageEntries) { chunks.append(QStringLiteral("

" - "

") - .arg(m_scheme, page.entry)); + "

") + .arg(ImageUrl::build(m_scheme, page.entry))); } return Chapter{0, m_title, chunks}; } diff --git a/src/backend/formats/comic/ComicReader.h b/src/backend/formats/comic/ComicReader.h index 589520f..13a0b60 100644 --- a/src/backend/formats/comic/ComicReader.h +++ b/src/backend/formats/comic/ComicReader.h @@ -1,7 +1,7 @@ #pragma once #include "backend/FormatReader.h" -#include "IComicSource.h" +#include "backend/formats/IByteSource.h" #include #include @@ -13,7 +13,7 @@ class ComicReader : public FormatReader { public: - using SourceFactory = std::function()>; + using SourceFactory = std::function()>; ComicReader(SourceFactory sourceFactory, QString fileType, QString scheme); @@ -40,7 +40,7 @@ private: }; bool parseSource(const QString &filePath); - bool parseOpenSource(const QString &filePath, IComicSource &source); + bool parseOpenSource(const QString &filePath, IByteSource &source); SourceFactory m_sourceFactory; QString m_fileType; diff --git a/src/backend/formats/comic/Folder.cpp b/src/backend/formats/comic/Folder.cpp deleted file mode 100644 index ddb95ba..0000000 --- a/src/backend/formats/comic/Folder.cpp +++ /dev/null @@ -1 +0,0 @@ -// Folder shells are header-only (constructors inline in Folder.h). diff --git a/src/backend/formats/comic/Folder.h b/src/backend/formats/comic/Folder.h deleted file mode 100644 index c3bb04f..0000000 --- a/src/backend/formats/comic/Folder.h +++ /dev/null @@ -1,7 +0,0 @@ -#pragma once - -// Convenience header — includes both reader and provider shells. -// Use FolderReader.h if you only need the reader (avoids Qt::Quick dependency). - -#include "FolderReader.h" -#include "FolderProvider.h" diff --git a/src/backend/formats/comic/FolderProvider.h b/src/backend/formats/comic/FolderProvider.h deleted file mode 100644 index a0fe3a1..0000000 --- a/src/backend/formats/comic/FolderProvider.h +++ /dev/null @@ -1,11 +0,0 @@ -#pragma once - -#include "ComicImageProvider.h" -#include "DirComicSource.h" - -class FolderImageProvider : public ComicImageProvider { -public: - FolderImageProvider() - : ComicImageProvider([] { return std::make_unique(); }, - QStringLiteral("dir")) {} -}; diff --git a/src/backend/formats/comic/FolderReader.h b/src/backend/formats/comic/FolderReader.h index de9d0cb..983ab20 100644 --- a/src/backend/formats/comic/FolderReader.h +++ b/src/backend/formats/comic/FolderReader.h @@ -1,12 +1,12 @@ #pragma once #include "ComicReader.h" -#include "DirComicSource.h" +#include "backend/formats/sources/DirByteSource.h" class FolderReader : public ComicReader { public: FolderReader() - : ComicReader([] { return std::make_unique(); }, - QStringLiteral(""), + : ComicReader([] { return std::make_unique(); }, + QStringLiteral("folder"), QStringLiteral("dir")) {} }; diff --git a/src/backend/formats/comic/DirComicSource.cpp b/src/backend/formats/sources/DirByteSource.cpp similarity index 80% rename from src/backend/formats/comic/DirComicSource.cpp rename to src/backend/formats/sources/DirByteSource.cpp index 7c42eac..4e66f78 100644 --- a/src/backend/formats/comic/DirComicSource.cpp +++ b/src/backend/formats/sources/DirByteSource.cpp @@ -1,11 +1,11 @@ -#include "DirComicSource.h" +#include "DirByteSource.h" #include #include #include #include -bool DirComicSource::open(const QString &path) +bool DirByteSource::open(const QString &path) { m_dir.clear(); m_hash.clear(); @@ -32,12 +32,12 @@ bool DirComicSource::open(const QString &path) return true; } -QStringList DirComicSource::listEntries() const +QStringList DirByteSource::listEntries() const { return m_entries; } -QByteArray DirComicSource::readEntry(const QString &entryName) const +QByteArray DirByteSource::readEntry(const QString &entryName) const { if (m_dir.isEmpty() || entryName.isEmpty()) return {}; @@ -47,7 +47,7 @@ QByteArray DirComicSource::readEntry(const QString &entryName) const return f.readAll(); } -QByteArray DirComicSource::contentHash() const +QByteArray DirByteSource::contentHash() const { return m_hash; } diff --git a/src/backend/formats/comic/DirComicSource.h b/src/backend/formats/sources/DirByteSource.h similarity index 78% rename from src/backend/formats/comic/DirComicSource.h rename to src/backend/formats/sources/DirByteSource.h index 0a8e220..44b6ae5 100644 --- a/src/backend/formats/comic/DirComicSource.h +++ b/src/backend/formats/sources/DirByteSource.h @@ -1,8 +1,8 @@ #pragma once -#include "IComicSource.h" +#include "backend/formats/IByteSource.h" -class DirComicSource : public IComicSource { +class DirByteSource : public IByteSource { public: bool open(const QString &path) override; QStringList listEntries() const override; diff --git a/src/backend/formats/sources/Fb2ByteSource.cpp b/src/backend/formats/sources/Fb2ByteSource.cpp new file mode 100644 index 0000000..10e60e4 --- /dev/null +++ b/src/backend/formats/sources/Fb2ByteSource.cpp @@ -0,0 +1,88 @@ +#include "Fb2ByteSource.h" + +#include "backend/formats/Fb2Reader.h" + +#include +#include +#include +#include + +bool Fb2ByteSource::open(const QString &path) +{ + m_path.clear(); + m_hash.clear(); + + if (!QFileInfo::exists(path)) + return false; + + m_path = path; + return true; +} + +QByteArray Fb2ByteSource::rawBytes() const +{ + if (m_path.isEmpty()) + return {}; + QFile f(m_path); + if (!f.open(QIODevice::ReadOnly)) + return {}; + return f.readAll(); +} + +QStringList Fb2ByteSource::listEntries() const +{ + const QByteArray raw = rawBytes(); + if (raw.isEmpty()) + return {}; + + QStringList ids; + // Decode first so parsing works for encodings Qt 6 does not natively + // detect (e.g. Windows-1251); see Fb2Reader::decodeRawBytes. + QXmlStreamReader xml(Fb2Reader::decodeRawBytes(raw)); + while (!xml.atEnd()) { + xml.readNext(); + if (xml.isStartElement() && xml.name() == QLatin1String("binary")) + ids.append(xml.attributes().value(QLatin1String("id")).toString()); + } + return ids; +} + +QByteArray Fb2ByteSource::readEntry(const QString &binaryId) const +{ + if (binaryId.isEmpty()) + return {}; + const QByteArray raw = rawBytes(); + if (raw.isEmpty()) + return {}; + + QXmlStreamReader xml(Fb2Reader::decodeRawBytes(raw)); + while (!xml.atEnd()) { + xml.readNext(); + if (!xml.isStartElement() || xml.name() != QLatin1String("binary")) + continue; + if (xml.attributes().value(QLatin1String("id")) != binaryId) + continue; + + // Accumulate text (base64 data may span multiple character events) + QString base64; + while (!xml.atEnd()) { + xml.readNext(); + if (xml.isCharacters()) + base64 += xml.text(); + else + break; + } + return QByteArray::fromBase64(base64.toLatin1()); + } + return {}; +} + +QByteArray Fb2ByteSource::contentHash() const +{ + if (m_hash.isEmpty() && !m_path.isEmpty()) { + const QByteArray raw = rawBytes(); + if (!raw.isEmpty()) + m_hash = QCryptographicHash::hash(raw, QCryptographicHash::Md5); + } + return m_hash; +} diff --git a/src/backend/formats/sources/Fb2ByteSource.h b/src/backend/formats/sources/Fb2ByteSource.h new file mode 100644 index 0000000..d3b87e5 --- /dev/null +++ b/src/backend/formats/sources/Fb2ByteSource.h @@ -0,0 +1,20 @@ +#pragma once + +#include "backend/formats/IByteSource.h" + +// Byte source over an FB2 document: entries are the ids of its base64 +// elements. Parsing is deferred to the calls that need it so that +// open() stays cheap for per-request provider use. +class Fb2ByteSource : public IByteSource { +public: + bool open(const QString &path) override; + QStringList listEntries() const override; + QByteArray readEntry(const QString &binaryId) const override; + QByteArray contentHash() const override; + +private: + QByteArray rawBytes() const; + + QString m_path; + mutable QByteArray m_hash; +}; diff --git a/src/backend/formats/comic/RarComicSource.cpp b/src/backend/formats/sources/RarByteSource.cpp similarity index 77% rename from src/backend/formats/comic/RarComicSource.cpp rename to src/backend/formats/sources/RarByteSource.cpp index 0f519aa..6960fd7 100644 --- a/src/backend/formats/comic/RarComicSource.cpp +++ b/src/backend/formats/sources/RarByteSource.cpp @@ -1,4 +1,4 @@ -#include "RarComicSource.h" +#include "RarByteSource.h" #include #include @@ -6,7 +6,7 @@ #include #include -bool RarComicSource::open(const QString &path) +bool RarByteSource::open(const QString &path) { m_path.clear(); m_hash.clear(); @@ -30,22 +30,16 @@ bool RarComicSource::open(const QString &path) if (!opened || m_entries.isEmpty()) return false; - QFile f(path); - if (f.open(QIODevice::ReadOnly)) { - m_hash = QCryptographicHash::hash(f.readAll(), QCryptographicHash::Md5); - f.close(); - } - m_path = path; return true; } -QStringList RarComicSource::listEntries() const +QStringList RarByteSource::listEntries() const { return m_entries; } -QByteArray RarComicSource::readEntry(const QString &entryName) const +QByteArray RarByteSource::readEntry(const QString &entryName) const { if (m_path.isEmpty() || entryName.isEmpty()) return {}; @@ -79,7 +73,14 @@ QByteArray RarComicSource::readEntry(const QString &entryName) const return result; } -QByteArray RarComicSource::contentHash() const +QByteArray RarByteSource::contentHash() const { + // Computed lazily: hashing reads the whole file, which providers opening + // a source per image request must not pay for. + if (m_hash.isEmpty() && !m_path.isEmpty()) { + QFile f(m_path); + if (f.open(QIODevice::ReadOnly)) + m_hash = QCryptographicHash::hash(f.readAll(), QCryptographicHash::Md5); + } return m_hash; } diff --git a/src/backend/formats/comic/RarComicSource.h b/src/backend/formats/sources/RarByteSource.h similarity index 71% rename from src/backend/formats/comic/RarComicSource.h rename to src/backend/formats/sources/RarByteSource.h index 0a5e602..da23b7a 100644 --- a/src/backend/formats/comic/RarComicSource.h +++ b/src/backend/formats/sources/RarByteSource.h @@ -1,8 +1,8 @@ #pragma once -#include "IComicSource.h" +#include "backend/formats/IByteSource.h" -class RarComicSource : public IComicSource { +class RarByteSource : public IByteSource { public: bool open(const QString &path) override; QStringList listEntries() const override; @@ -11,6 +11,6 @@ public: private: QString m_path; - QByteArray m_hash; + mutable QByteArray m_hash; QStringList m_entries; }; diff --git a/src/backend/formats/comic/ZipComicSource.cpp b/src/backend/formats/sources/ZipByteSource.cpp similarity index 58% rename from src/backend/formats/comic/ZipComicSource.cpp rename to src/backend/formats/sources/ZipByteSource.cpp index c219eea..e547b49 100644 --- a/src/backend/formats/comic/ZipComicSource.cpp +++ b/src/backend/formats/sources/ZipByteSource.cpp @@ -1,4 +1,4 @@ -#include "ZipComicSource.h" +#include "ZipByteSource.h" #include "backend/ZipUtils.h" @@ -7,7 +7,7 @@ #include -bool ZipComicSource::open(const QString &path) +bool ZipByteSource::open(const QString &path) { m_path.clear(); m_hash.clear(); @@ -19,22 +19,16 @@ bool ZipComicSource::open(const QString &path) m_entries = ZipUtils::listZipEntries(zf); unzClose(zf); - QFile f(path); - if (f.open(QIODevice::ReadOnly)) { - m_hash = QCryptographicHash::hash(f.readAll(), QCryptographicHash::Md5); - f.close(); - } - m_path = path; return true; } -QStringList ZipComicSource::listEntries() const +QStringList ZipByteSource::listEntries() const { return m_entries; } -QByteArray ZipComicSource::readEntry(const QString &entryName) const +QByteArray ZipByteSource::readEntry(const QString &entryName) const { if (m_path.isEmpty() || entryName.isEmpty()) return {}; @@ -46,7 +40,14 @@ QByteArray ZipComicSource::readEntry(const QString &entryName) const return ZipUtils::readZipEntry(zf, entryName.toUtf8().constData()); } -QByteArray ZipComicSource::contentHash() const +QByteArray ZipByteSource::contentHash() const { + // Computed lazily: hashing reads the whole file, which providers opening + // a source per image request must not pay for. + if (m_hash.isEmpty() && !m_path.isEmpty()) { + QFile f(m_path); + if (f.open(QIODevice::ReadOnly)) + m_hash = QCryptographicHash::hash(f.readAll(), QCryptographicHash::Md5); + } return m_hash; } diff --git a/src/backend/formats/comic/ZipComicSource.h b/src/backend/formats/sources/ZipByteSource.h similarity index 71% rename from src/backend/formats/comic/ZipComicSource.h rename to src/backend/formats/sources/ZipByteSource.h index 3c089f0..3f0630b 100644 --- a/src/backend/formats/comic/ZipComicSource.h +++ b/src/backend/formats/sources/ZipByteSource.h @@ -1,8 +1,8 @@ #pragma once -#include "IComicSource.h" +#include "backend/formats/IByteSource.h" -class ZipComicSource : public IComicSource { +class ZipByteSource : public IByteSource { public: bool open(const QString &path) override; QStringList listEntries() const override; @@ -11,6 +11,6 @@ public: private: QString m_path; - QByteArray m_hash; + mutable QByteArray m_hash; QStringList m_entries; }; diff --git a/src/backend/reading/MangaPagination.cpp b/src/backend/reading/MangaPagination.cpp new file mode 100644 index 0000000..1342d3d --- /dev/null +++ b/src/backend/reading/MangaPagination.cpp @@ -0,0 +1,80 @@ +#include "MangaPagination.h" + +void MangaPagination::clear() +{ + m_pairs.clear(); +} + +void MangaPagination::rebuild(const QVector &naturalSizes, bool landscape, bool pageShift) +{ + m_pairs.clear(); + if (naturalSizes.isEmpty()) + return; + + const int count = naturalSizes.size(); + const auto isLandscapePage = [&naturalSizes](int i) { + const QSize sz = naturalSizes.at(i); + return sz.isValid() && sz.width() > sz.height(); + }; + + if (!landscape) { + // Portrait: every chunk is its own solo pair. + m_pairs.reserve(count); + for (int i = 0; i < count; ++i) + m_pairs.append({i, -1}); + return; + } + + // Landscape: cover alone, optional shift page alone, then portrait-pair the rest. + m_pairs.append({0, -1}); // cover always solo + int i = 1; + if (pageShift && i < count) { + m_pairs.append({i, -1}); // page 1 solo when shift is ON + ++i; + } + while (i < count) { + if (isLandscapePage(i)) { + m_pairs.append({i, -1}); + ++i; + } else { + // Try to pair with next portrait page. + const int next = i + 1; + if (next < count && !isLandscapePage(next)) { + m_pairs.append({i, next}); + i += 2; + continue; + } + m_pairs.append({i, -1}); + ++i; + } + } +} + +int MangaPagination::count() const +{ + return m_pairs.size(); +} + +MangaPagination::Pair MangaPagination::at(int pairIndex) const +{ + if (pairIndex < 0 || pairIndex >= m_pairs.size()) + return {}; + return m_pairs.at(pairIndex); +} + +int MangaPagination::pairIndexForChunk(int chunkIndex) const +{ + for (int i = 0; i < m_pairs.size(); ++i) { + if (m_pairs[i].first == chunkIndex || m_pairs[i].second == chunkIndex) + return i; + } + return 0; +} + +int MangaPagination::anchorChunkForShiftToggle(int currentPairIndex, bool shiftTurningOn) const +{ + if (currentPairIndex < 0 || currentPairIndex >= m_pairs.size()) + return 0; + const Pair &pair = m_pairs.at(currentPairIndex); + return (shiftTurningOn && pair.second >= 0) ? pair.second : pair.first; +} diff --git a/src/backend/reading/MangaPagination.h b/src/backend/reading/MangaPagination.h new file mode 100644 index 0000000..a747da3 --- /dev/null +++ b/src/backend/reading/MangaPagination.h @@ -0,0 +1,34 @@ +#pragma once + +#include +#include + +// Pure page-pairing logic for manga mode. Given the natural sizes of the +// page images, decides which pages display alone and which form two-page +// spreads. Holds no Qt object state and emits nothing — the owning model +// drives signals and persistence. +class MangaPagination { +public: + struct Pair { + int first = -1; + int second = -1; // -1 = solo page + }; + + void clear(); + + // Portrait viewport: every page solo. Landscape: cover solo, optional + // shift page solo, consecutive portrait pages paired, wide pages solo. + void rebuild(const QVector &naturalSizes, bool landscape, bool pageShift); + + int count() const; + Pair at(int pairIndex) const; + int pairIndexForChunk(int chunkIndex) const; + + // Chunk to keep on screen across a shift toggle. Anchoring on the + // higher-index chunk when shift turns on (and lower when it turns off) + // keeps repeated back-and-forth toggling stable with no drift. + int anchorChunkForShiftToggle(int currentPairIndex, bool shiftTurningOn) const; + +private: + QVector m_pairs; +}; diff --git a/src/backend/reading/MeasurementController.cpp b/src/backend/reading/MeasurementController.cpp new file mode 100644 index 0000000..62ac1fa --- /dev/null +++ b/src/backend/reading/MeasurementController.cpp @@ -0,0 +1,50 @@ +#include "MeasurementController.h" + +#include "backend/ChunkMeasurer.h" + +#include + +MeasurementController::MeasurementController(QObject *parent) + : QObject(parent) +{ +} + +MeasurementController::~MeasurementController() +{ + if (m_future.isRunning()) { + m_future.cancel(); + m_future.waitForFinished(); + } +} + +void MeasurementController::setImageLoader(std::unique_ptr loader) +{ + m_imageLoader = std::move(loader); +} + +bool MeasurementController::measuring() const +{ + return m_measuring; +} + +void MeasurementController::start(const QStringList &htmls, int contentWidth, + int fontSize, qreal lineSpacing, bool isNew) +{ + if (m_future.isRunning()) + m_future.cancel(); + + m_measuring = true; + emit measuringChanged(); + + std::unique_ptr loaderClone = m_imageLoader ? m_imageLoader->clone() : nullptr; + auto measurer = std::make_shared(std::move(loaderClone), fontSize, lineSpacing); + + m_future = QtConcurrent::run([this, htmls, measurer, contentWidth, isNew]() { + QVector heights = measurer->measure(htmls, contentWidth); + QMetaObject::invokeMethod(this, [this, heights, isNew] { + m_measuring = false; + emit measuringChanged(); + emit heightsReady(heights, isNew); + }, Qt::QueuedConnection); + }); +} diff --git a/src/backend/reading/MeasurementController.h b/src/backend/reading/MeasurementController.h new file mode 100644 index 0000000..36392b7 --- /dev/null +++ b/src/backend/reading/MeasurementController.h @@ -0,0 +1,37 @@ +#pragma once + +#include +#include +#include +#include +#include + +#include "backend/IImageLoader.h" + +// Runs chunk height measurement off the GUI thread and reports the results +// back on it. Owns the image loader used to resolve embedded images and the +// lifetime of the in-flight measurement. +class MeasurementController : public QObject { + Q_OBJECT +public: + explicit MeasurementController(QObject *parent = nullptr); + ~MeasurementController() override; + + void setImageLoader(std::unique_ptr loader); + + // isNew is passed through untouched to heightsReady so the owner knows + // whether this measurement should trigger a position restore. + void start(const QStringList &htmls, int contentWidth, + int fontSize, qreal lineSpacing, bool isNew); + + bool measuring() const; + +signals: + void measuringChanged(); + void heightsReady(QVector heights, bool isNew); + +private: + std::unique_ptr m_imageLoader; + bool m_measuring = false; + QFuture m_future; +}; diff --git a/src/main.cpp b/src/main.cpp index 90377ba..0bdf932 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -9,25 +9,25 @@ #include #include +#include "backend/AppCoordinator.h" #include "backend/AppState.h" -#include "backend/IImageProvider.h" -#include "backend/formats/ImageLoaderFactory.h" -#include "backend/formats/ImageProviderFactory.h" -#include "backend/formats/EpubImageProvider.h" #include "backend/formats/FileIconProvider.h" +#include "backend/formats/FormatRegistry.h" #include "backend/formats/WebImageProvider.h" +#include "backend/formats/sources/DirByteSource.h" +#include "backend/formats/sources/Fb2ByteSource.h" +#include "backend/formats/sources/RarByteSource.h" +#include "backend/formats/sources/ZipByteSource.h" #include "backend/HistoryModel.h" #include "backend/ReadingModel.h" #include "backend/NativeFileDialogService.h" -#include "backend/formats/ReaderFactory.h" #include "backend/book/Book.h" #include "backend/formats/TxtReader.h" #include "backend/formats/EpubReader.h" #include "backend/formats/Fb2Reader.h" -#include "backend/formats/Fb2ImageProvider.h" -#include "backend/formats/comic/Cbz.h" -#include "backend/formats/comic/Cbr.h" -#include "backend/formats/comic/Folder.h" +#include "backend/formats/comic/CbzReader.h" +#include "backend/formats/comic/CbrReader.h" +#include "backend/formats/comic/FolderReader.h" #include "backend/state/BookPositionStore.h" #include "backend/state/ReadingPreferences.h" #include "backend/state/UiState.h" @@ -105,16 +105,29 @@ int main(int argc, char *argv[]) UiState uiState(appState); BookPositionStore bookPositions(appState); - ReaderFactory readerFactory({ - [] { return std::make_unique(); }, - [] { return std::make_unique(); }, - [] { return std::make_unique(); }, - [] { return std::make_unique(); }, - [] { return std::make_unique(); }, - [] { return std::make_unique(); }, + // The format table: one row declares everything a format needs. + FormatRegistry formatRegistry({ + {QStringLiteral("txt"), false, {}, + [] { return std::make_unique(); }, nullptr}, + {QStringLiteral("epub"), false, QStringLiteral("epub"), + [] { return std::make_unique(); }, + [] { return std::make_unique(); }, + /*loaderIncludesWeb=*/true}, + {QStringLiteral("fb2"), false, QStringLiteral("fb2"), + [] { return std::make_unique(); }, + [] { return std::make_unique(); }}, + {QStringLiteral("cbz"), false, QStringLiteral("cbz"), + [] { return std::make_unique(); }, + [] { return std::make_unique(); }}, + {QStringLiteral("cbr"), false, QStringLiteral("cbr"), + [] { return std::make_unique(); }, + [] { return std::make_unique(); }}, + {{}, /*matchesDirectory=*/true, QStringLiteral("dir"), + [] { return std::make_unique(); }, + [] { return std::make_unique(); }}, }); - HistoryModel historyModel(readerFactory); + HistoryModel historyModel(formatRegistry); for (const QVariantMap &entry : appState.loadArray(QStringLiteral("history"))) { const QString fp = entry.value(QStringLiteral("filePath")).toString(); if (fp.isEmpty()) continue; @@ -142,18 +155,14 @@ int main(int argc, char *argv[]) IFileDialogService *fileDialogService = new NativeFileDialogService(nullptr); #endif - Book book(*fileDialogService, bookPositions, readerFactory); + Book book(*fileDialogService, bookPositions, formatRegistry); ReadingModel readingModel(bookPositions); // --- QML engine --- QQmlApplicationEngine engine; engine.addImageProvider(QStringLiteral("web"), new WebImageProvider()); - engine.addImageProvider(QStringLiteral("epub"), new EpubImageProvider()); - engine.addImageProvider(QStringLiteral("fb2"), new Fb2ImageProvider()); - engine.addImageProvider(QStringLiteral("cbz"), new CbzImageProvider()); - engine.addImageProvider(QStringLiteral("cbr"), new CbrImageProvider()); - engine.addImageProvider(QStringLiteral("dir"), new FolderImageProvider()); engine.addImageProvider(QStringLiteral("fileicon"), new FileIconProvider()); + formatRegistry.registerImageProviders(engine); engine.rootContext()->setContextProperty(QStringLiteral("isDebugBuild"), #ifdef QT_DEBUG true @@ -168,100 +177,10 @@ int main(int argc, char *argv[]) engine.rootContext()->setContextProperty(QStringLiteral("uiState"), &uiState); engine.rootContext()->setContextProperty(QStringLiteral("historyModel"), &historyModel); - // --- Cross-class signal wiring --- - - // Typography changes → re-push font params into ReadingModel - QObject::connect(&readingPreferences, &ReadingPreferences::fontSizeChanged, [&]{ - readingModel.setFontParams(readingPreferences.fontSize(), readingPreferences.lineSpacing()); - }); - QObject::connect(&readingPreferences, &ReadingPreferences::lineSpacingChanged, [&]{ - readingModel.setFontParams(readingPreferences.fontSize(), readingPreferences.lineSpacing()); - }); - - // Track the current image provider and content width so both stay in sync. - IImageProvider *currentImageProvider = nullptr; - int currentContentWidth = 0; - - // Before a new book open: snapshot the outgoing book's progress into the library. - // Scroll position is handled by PageView's scroll tracker via book.saveCurrentPosition(). - QObject::connect(&book, &Book::willOpenNewBook, [&]{ - if (book.hasBook()) - historyModel.addOrUpdateBook(book.filePath(), readingModel.progress()); - }); - - // Real-time history update: fired by PageView's scrollTrackTimer on every scroll. - QObject::connect(&book, &Book::positionSaved, [&]{ - historyModel.addOrUpdateBook(book.filePath(), readingModel.progress()); - }); - - // After the new reader is installed: wire up image provider + ReadingModel - QObject::connect(&book, &Book::bookChanged, [&]{ - currentImageProvider = nullptr; - - if (!book.hasBook()) { - readingModel.setReader(nullptr); - return; - } - - FormatReader *reader = book.reader(); - const QString filePath = reader->filePath(); - - IImageProvider *provider = ImageProviderFactory::create(filePath); - if (provider) { - engine.removeImageProvider(provider->scheme()); - engine.addImageProvider(provider->scheme(), provider); - provider->setFilePath(filePath); - provider->setDisplayWidth(currentContentWidth); - currentImageProvider = provider; - - if (!reader->coverImagePath().isEmpty()) - book.setCoverImageUrl(provider->coverImageUrl(reader->coverImagePath())); - } - - readingModel.setFontParams(readingPreferences.fontSize(), readingPreferences.lineSpacing()); - readingModel.setImageLoader(ImageLoaderFactory::create(filePath)); - readingModel.setCoverImageUrl(book.coverImageUrl()); - readingModel.setReader(reader); - readingModel.measure(true); - - uiState.setLastFilePath(filePath); - historyModel.addOrUpdateBook(filePath, -1.0); - }); - - // Propagate content-width changes to image provider + reading model. - // Called from Book::setContentWidth which is triggered by QML's PageView. - QObject::connect(&book, &Book::contentWidthChanged, [&](int width){ - currentContentWidth = width; - if (currentImageProvider) - currentImageProvider->setDisplayWidth(width); - readingModel.setContentWidth(width); - }); - - // Quit: flush everything to persistent storage. - // Scroll position was last saved by PageView's scroll tracker; we save library progress here. - QObject::connect(&app, &QCoreApplication::aboutToQuit, [&]{ - if (book.hasBook()) { - historyModel.addOrUpdateBook(book.filePath(), readingModel.progress()); - uiState.setLastFilePath(book.filePath()); - } else { - uiState.setLastFilePath(QString()); - } - - readingPreferences.save(); - uiState.save(); - - QList items; - for (int i = 0; i < historyModel.rowCount(); ++i) { - items.append({ - {QStringLiteral("filePath"), historyModel.filePath(i)}, - {QStringLiteral("progress"), historyModel.progress(i)}, - {QStringLiteral("lastOpened"), historyModel.lastOpened(i)}, - }); - } - appState.saveArray(QStringLiteral("history"), items); - - qInfo() << "Settings saved to:" << settings.fileName(); - }); + // All cross-class signal wiring lives in the coordinator. + AppCoordinator coordinator(book, readingModel, historyModel, uiState, + readingPreferences, appState, settings, + formatRegistry, engine); const QUrl url(QStringLiteral("qrc:/Asteria/Main.qml")); QObject::connect(&engine, &QQmlApplicationEngine::objectCreationFailed, diff --git a/src/qml/Main.qml b/src/qml/Main.qml index 0a941df..606bb41 100644 --- a/src/qml/Main.qml +++ b/src/qml/Main.qml @@ -17,8 +17,8 @@ ApplicationWindow { source: "qrc:/Asteria/src/assets/MaterialIconsOutlined-Regular.otf" } - property bool sidebarOpen: uiState.sidebarOpen - onSidebarOpenChanged: uiState.sidebarOpen = sidebarOpen + // uiState.sidebarOpen is the single source of truth; writers set it directly. + readonly property bool sidebarOpen: uiState.sidebarOpen property string currentPage: "starter" property bool settingsOpen: false property bool barsVisible: true @@ -88,7 +88,7 @@ ApplicationWindow { id: sidebar height: parent.height sidebarOpen: window.sidebarOpen - onCloseDrawer: window.sidebarOpen = false + onCloseDrawer: uiState.sidebarOpen = false onNavigateTo: function(page) { if (page === "settings") { window.currentPage = book.hasBook ? "reader" : "starter" @@ -116,7 +116,7 @@ ApplicationWindow { sidebarOpen: window.sidebarOpen currentPage: window.currentPage barsVisible: window.currentPage !== "reader" || window.barsVisible - onMenuClicked: window.sidebarOpen = true + onMenuClicked: uiState.sidebarOpen = true } Item { @@ -333,7 +333,7 @@ ApplicationWindow { var savedPage = uiState.lastPage if (savedPage === "history") window.currentPage = savedPage - window.sidebarOpen = true + uiState.sidebarOpen = true } } } diff --git a/src/qml/ThemeManager.qml b/src/qml/ThemeManager.qml index 14c4db1..e979598 100644 --- a/src/qml/ThemeManager.qml +++ b/src/qml/ThemeManager.qml @@ -33,6 +33,48 @@ QtObject { property color actionDisabled: "#141724" } + // Single authority for the theme color keys. CustomThemePage and the + // capture/restore round-trip below iterate this list; the palette files + // (DarkTheme/LightTheme/customTheme above) are the only other places + // where the keys appear. + readonly property var colorKeys: [ + "backgroundDeepest", "backgroundDefault", "surface", "headerBg", + "footerBg", "scrollbarTrack", "scrollbarThumb", "primaryAccent", + "buttonAccent", "sidebarButtonText", "readingText", "uiText", + "headerText", "dimText", "counterText", "gradientTop", + "gradientBottom", "divider", "overlayBg", "actionDisabled" + ] + + // Display names for the custom-theme editor, grouped by section. + readonly property var colorSections: [ + { title: "Background", keys: ["backgroundDeepest", "backgroundDefault", "gradientTop", "gradientBottom"] }, + { title: "Surfaces", keys: ["surface", "headerBg", "footerBg", "overlayBg", "scrollbarTrack", "scrollbarThumb", "divider"] }, + { title: "Text", keys: ["readingText", "uiText", "headerText", "dimText", "counterText", "sidebarButtonText"] }, + { title: "Accents", keys: ["primaryAccent", "buttonAccent", "actionDisabled"] } + ] + readonly property var colorLabels: ({ + backgroundDeepest: "Deepest background", + backgroundDefault: "Default background", + gradientTop: "Gradient top", + gradientBottom: "Gradient bottom", + surface: "Surface", + headerBg: "Header background", + footerBg: "Footer background", + overlayBg: "Overlay background", + scrollbarTrack: "Scrollbar track", + scrollbarThumb: "Scrollbar thumb", + divider: "Divider", + readingText: "Reading text", + uiText: "UI text", + headerText: "Header text", + dimText: "Dim text", + counterText: "Counter text", + sidebarButtonText: "Sidebar button text", + primaryAccent: "Primary accent", + buttonAccent: "Button accent", + actionDisabled: "Action disabled" + }) + property var _lastApplied: ({}) readonly property var currentTheme: currentThemeName === "dark" ? DarkTheme @@ -72,51 +114,18 @@ QtObject { } function _captureColors() { - return { - backgroundDeepest: customTheme.backgroundDeepest.toString(), - backgroundDefault: customTheme.backgroundDefault.toString(), - surface: customTheme.surface.toString(), - headerBg: customTheme.headerBg.toString(), - footerBg: customTheme.footerBg.toString(), - scrollbarTrack: customTheme.scrollbarTrack.toString(), - scrollbarThumb: customTheme.scrollbarThumb.toString(), - primaryAccent: customTheme.primaryAccent.toString(), - buttonAccent: customTheme.buttonAccent.toString(), - sidebarButtonText: customTheme.sidebarButtonText.toString(), - readingText: customTheme.readingText.toString(), - uiText: customTheme.uiText.toString(), - headerText: customTheme.headerText.toString(), - dimText: customTheme.dimText.toString(), - counterText: customTheme.counterText.toString(), - gradientTop: customTheme.gradientTop.toString(), - gradientBottom: customTheme.gradientBottom.toString(), - divider: customTheme.divider.toString(), - overlayBg: customTheme.overlayBg.toString(), - actionDisabled: customTheme.actionDisabled.toString() - } + var out = {} + for (var i = 0; i < colorKeys.length; ++i) + out[colorKeys[i]] = customTheme[colorKeys[i]].toString() + return out } function _restoreColors(c) { if (!c) return - if (c.backgroundDeepest) customTheme.backgroundDeepest = c.backgroundDeepest - if (c.backgroundDefault) customTheme.backgroundDefault = c.backgroundDefault - if (c.surface) customTheme.surface = c.surface - if (c.headerBg) customTheme.headerBg = c.headerBg - if (c.footerBg) customTheme.footerBg = c.footerBg - if (c.scrollbarTrack) customTheme.scrollbarTrack = c.scrollbarTrack - if (c.scrollbarThumb) customTheme.scrollbarThumb = c.scrollbarThumb - if (c.primaryAccent) customTheme.primaryAccent = c.primaryAccent - if (c.buttonAccent) customTheme.buttonAccent = c.buttonAccent - if (c.sidebarButtonText) customTheme.sidebarButtonText = c.sidebarButtonText - if (c.readingText) customTheme.readingText = c.readingText - if (c.uiText) customTheme.uiText = c.uiText - if (c.headerText) customTheme.headerText = c.headerText - if (c.dimText) customTheme.dimText = c.dimText - if (c.counterText) customTheme.counterText = c.counterText - if (c.gradientTop) customTheme.gradientTop = c.gradientTop - if (c.gradientBottom) customTheme.gradientBottom = c.gradientBottom - if (c.divider) customTheme.divider = c.divider - if (c.overlayBg) customTheme.overlayBg = c.overlayBg - if (c.actionDisabled) customTheme.actionDisabled = c.actionDisabled + for (var i = 0; i < colorKeys.length; ++i) { + var key = colorKeys[i] + if (c[key]) + customTheme[key] = c[key] + } } } diff --git a/src/qml/components/FlatIconButton.qml b/src/qml/components/FlatIconButton.qml new file mode 100644 index 0000000..42177e2 --- /dev/null +++ b/src/qml/components/FlatIconButton.qml @@ -0,0 +1,28 @@ +import QtQuick +import QtQuick.Controls +import Asteria + +// Chrome-less button showing a single Material icon, with optional tooltip. +Button { + id: root + + property alias iconText: label.text + property int iconSize: 16 + property color iconColor: ThemeManager.currentTheme.dimText + property string tooltip: "" + + flat: true + background: Item {} + contentItem: Text { + id: label + font.family: "Material Icons Outlined" + font.pixelSize: root.iconSize + color: root.iconColor + horizontalAlignment: Text.AlignHCenter + verticalAlignment: Text.AlignVCenter + } + + ToolTip.visible: tooltip !== "" && hovered + ToolTip.delay: 500 + ToolTip.text: tooltip +} diff --git a/src/qml/components/Footer.qml b/src/qml/components/Footer.qml index 3e3563e..6c4ab90 100644 --- a/src/qml/components/Footer.qml +++ b/src/qml/components/Footer.qml @@ -18,7 +18,7 @@ Rectangle { anchors.left: parent.left anchors.leftMargin: 16 anchors.verticalCenter: parent.verticalCenter - visible: typeof readingModel !== "undefined" && readingModel.measuring + visible: readingModel.measuring text: "" font.family: "Material Icons Outlined" font.pixelSize: 14 @@ -33,87 +33,55 @@ Rectangle { } // RTL reading direction toggle (manga mode only). - Button { + FlatIconButton { anchors.left: parent.left anchors.leftMargin: 16 anchors.verticalCenter: parent.verticalCenter - visible: typeof readingModel !== "undefined" && readingModel.isMangaMode - flat: true + visible: readingModel.isMangaMode padding: 0 implicitWidth: 24 implicitHeight: 24 - contentItem: Text { - text: "" - font.family: "Material Icons Outlined" - font.pixelSize: 16 - color: (typeof readingModel !== "undefined" && readingModel.mangaRTL) - ? ThemeManager.currentTheme.buttonAccent - : ThemeManager.currentTheme.dimText - horizontalAlignment: Text.AlignHCenter - verticalAlignment: Text.AlignVCenter - } - background: Item {} + iconText: "" + iconColor: readingModel.mangaRTL ? ThemeManager.currentTheme.buttonAccent + : ThemeManager.currentTheme.dimText + tooltip: "Right-to-left reading (M)" onClicked: readingModel.setMangaRTL(!readingModel.mangaRTL) - ToolTip.visible: hovered - ToolTip.delay: 500 - ToolTip.text: "Right-to-left reading (M)" } // Page-shift toggle (manga mode only). Shifts page 1 to be displayed alone after the cover. - Button { + FlatIconButton { anchors.left: parent.left anchors.leftMargin: 44 anchors.verticalCenter: parent.verticalCenter - visible: typeof readingModel !== "undefined" && readingModel.isMangaMode - flat: true + visible: readingModel.isMangaMode padding: 0 implicitWidth: 24 implicitHeight: 24 - contentItem: Text { - text: "" - font.family: "Material Icons Outlined" - font.pixelSize: 16 - color: (typeof readingModel !== "undefined" && readingModel.pageShift) - ? ThemeManager.currentTheme.buttonAccent - : ThemeManager.currentTheme.dimText - horizontalAlignment: Text.AlignHCenter - verticalAlignment: Text.AlignVCenter - } - background: Item {} + iconText: "" + iconColor: readingModel.pageShift ? ThemeManager.currentTheme.buttonAccent + : ThemeManager.currentTheme.dimText + tooltip: "Page shift (S)" onClicked: { // currentPair lives on MangaPageView; reach it via the PageView router alias. const pairIdx = readerPage.pageView.currentMangaPair readingModel.setPageShift(!readingModel.pageShift, pairIdx) } - ToolTip.visible: hovered - ToolTip.delay: 500 - ToolTip.text: "Page shift (S)" } // Prev chapter button - Button { + FlatIconButton { id: prevBtn anchors.verticalCenter: parent.verticalCenter x: parent.width * 0.5 - chapterText.implicitWidth / 2 - width - 4 visible: book.hasBook && readingModel.hasChapters enabled: readingModel.currentChapter > 0 - flat: true padding: 0 implicitWidth: 20 implicitHeight: 20 - contentItem: Text { - text: "" - font.family: "Material Icons Outlined" - font.pixelSize: 16 - color: prevBtn.enabled ? ThemeManager.currentTheme.dimText : ThemeManager.currentTheme.actionDisabled - horizontalAlignment: Text.AlignHCenter - verticalAlignment: Text.AlignVCenter - } - background: Item {} + iconText: "" + iconColor: prevBtn.enabled ? ThemeManager.currentTheme.dimText : ThemeManager.currentTheme.actionDisabled + tooltip: "Previous chapter" onClicked: readingModel.previousChapter() - ToolTip.visible: hovered - ToolTip.delay: 500 - ToolTip.text: "Previous chapter" } Text { @@ -129,29 +97,19 @@ Rectangle { } // Next chapter button - Button { + FlatIconButton { id: nextBtn anchors.verticalCenter: parent.verticalCenter x: parent.width * 0.5 + chapterText.implicitWidth / 2 + 4 visible: book.hasBook && readingModel.hasChapters enabled: readingModel.currentChapter < readingModel.totalChapters - 1 - flat: true padding: 0 implicitWidth: 20 implicitHeight: 20 - contentItem: Text { - text: "" - font.family: "Material Icons Outlined" - font.pixelSize: 16 - color: nextBtn.enabled ? ThemeManager.currentTheme.dimText : ThemeManager.currentTheme.actionDisabled - horizontalAlignment: Text.AlignHCenter - verticalAlignment: Text.AlignVCenter - } - background: Item {} + iconText: "" + iconColor: nextBtn.enabled ? ThemeManager.currentTheme.dimText : ThemeManager.currentTheme.actionDisabled + tooltip: "Next chapter" onClicked: readingModel.nextChapter() - ToolTip.visible: hovered - ToolTip.delay: 500 - ToolTip.text: "Next chapter" } Text { diff --git a/src/qml/components/LabeledSlider.qml b/src/qml/components/LabeledSlider.qml new file mode 100644 index 0000000..e459998 --- /dev/null +++ b/src/qml/components/LabeledSlider.qml @@ -0,0 +1,75 @@ +import QtQuick +import QtQuick.Controls +import Asteria + +// Settings slider with a label row and a debounced committed() signal so +// preference writes don't fire on every pixel of a drag. +Column { + id: root + + property string label: "" + property string valueText: slider.value.toString() + property alias from: slider.from + property alias to: slider.to + property alias stepSize: slider.stepSize + property alias value: slider.value + + signal committed(real value) + + spacing: 4 + + Item { + width: parent.width + height: Math.max(labelItem.implicitHeight, valueItem.implicitHeight) + + Text { + id: labelItem + text: root.label + font.pixelSize: 13 + color: ThemeManager.currentTheme.uiText + anchors.verticalCenter: parent.verticalCenter + } + Text { + id: valueItem + text: root.valueText + font.pixelSize: 12 + color: ThemeManager.currentTheme.dimText + anchors.right: parent.right + anchors.verticalCenter: parent.verticalCenter + } + } + + Timer { + id: debounce + interval: 250 + onTriggered: root.committed(slider.value) + } + + Slider { + id: slider + width: parent.width + onMoved: debounce.restart() + + background: Rectangle { + x: slider.leftPadding + y: slider.topPadding + slider.availableHeight / 2 - height / 2 + width: slider.availableWidth + height: 3 + radius: 2 + color: ThemeManager.currentTheme.scrollbarThumb + Rectangle { + width: slider.visualPosition * parent.width + height: parent.height + radius: 2 + color: ThemeManager.currentTheme.buttonAccent + } + } + handle: Rectangle { + x: slider.leftPadding + slider.visualPosition * (slider.availableWidth - width) + y: slider.topPadding + slider.availableHeight / 2 - height / 2 + width: 14; height: 14; radius: 7 + color: slider.pressed ? Qt.lighter(ThemeManager.currentTheme.buttonAccent, 1.15) + : ThemeManager.currentTheme.buttonAccent + } + } +} diff --git a/src/qml/components/MangaPageView.qml b/src/qml/components/MangaPageView.qml index c001672..dbb061c 100644 --- a/src/qml/components/MangaPageView.qml +++ b/src/qml/components/MangaPageView.qml @@ -29,28 +29,26 @@ Rectangle { function handleScrollUp() { previousPair() } function nextPair() { - if (currentPair < readingModel.totalPagePairs - 1) { - currentPair++ - onPairChanged() - } + if (currentPair < readingModel.totalPagePairs - 1) + showPair(currentPair + 1) } function previousPair() { - if (currentPair > 0) { - currentPair-- - onPairChanged() - } + if (currentPair > 0) + showPair(currentPair - 1) } - function onPairChanged() { - const pair = readingModel.pagePair(currentPair) + // Single entry point for displaying a pair: sets the index, refreshes the + // displayed pair contents, and syncs scroll/position state. + function showPair(pairIndex) { + currentPair = pairIndex + pageArea.pair = contentReady ? readingModel.pagePair(pairIndex) : [] + const pair = pageArea.pair if (pair.length === 0) return const firstChunk = pair[0] // Keep scroll model in sync so Footer page counter and chapter tracking work. - readingModel.setScrollInfo(firstChunk, currentPair / Math.max(1, readingModel.totalPagePairs - 1)) + readingModel.setScrollInfo(firstChunk, pairIndex / Math.max(1, readingModel.totalPagePairs - 1)) book.saveCurrentPosition(firstChunk, 0, readingModel.pageShift) - // Sync currentPage for footer display. - // totalPages is already set to totalPagePairs by the model in manga mode. } // Notify model when orientation changes (triggers pair rebuild). @@ -72,8 +70,9 @@ Rectangle { anchors.fill: parent anchors.margins: readingPreferences.verticalMargin - // Build display pair: for RTL mode pages are reversed (higher index on the left). - property var pair: contentReady ? readingModel.pagePair(currentPair) : [] + // Display pair, updated by showPair(). For RTL mode pages are reversed + // (higher index on the left) via leftChunk/rightChunk below. + property var pair: [] property int leftChunk: { if (pair.length === 0) return -1 @@ -189,7 +188,7 @@ Rectangle { } else { // Middle — toggle bars. window.barsVisible = !window.barsVisible - window.sidebarOpen = !window.sidebarOpen + uiState.sidebarOpen = !uiState.sidebarOpen } } } @@ -199,23 +198,17 @@ Rectangle { target: readingModel function onRestoreReady(chunkIndex, intraOffset) { contentReady = true - const pair = readingModel.pairIndexForChunk(chunkIndex) - currentPair = pair restoreReady = true - onPairChanged() + showPair(readingModel.pairIndexForChunk(chunkIndex)) } function onTotalPagePairsChanged() { // Re-clamp after pair rebuild (resize / orientation flip). - currentPair = Math.min(currentPair, Math.max(0, readingModel.totalPagePairs - 1)) + showPair(Math.min(currentPair, Math.max(0, readingModel.totalPagePairs - 1))) } function onPagePairsRebuilt(newPairIndex) { - // setPageShift rebuilt the pairs — the pair-content binding needs to re-evaluate - // even when newPairIndex equals the existing currentPair (toggling shift can leave - // the index unchanged while pair contents change). Two writes force two change - // notifications; the binding is read once after the function returns with the - // final value, so the -1 intermediate is never displayed. - currentPair = -1 - currentPair = newPairIndex + // setPageShift rebuilt the pairs; refresh even when the index is + // unchanged since the pair contents may differ. + showPair(newPairIndex) } } diff --git a/src/qml/components/PageView.qml b/src/qml/components/PageView.qml index 8962330..fb03236 100644 --- a/src/qml/components/PageView.qml +++ b/src/qml/components/PageView.qml @@ -30,7 +30,7 @@ Item { Loader { id: loader anchors.fill: parent - sourceComponent: book.renderingMode === "manga" ? mangaViewComp : scrollViewComp + sourceComponent: readingModel.isMangaMode ? mangaViewComp : scrollViewComp } Component { diff --git a/src/qml/components/ScrollPageView.qml b/src/qml/components/ScrollPageView.qml index cb6a954..2088618 100644 --- a/src/qml/components/ScrollPageView.qml +++ b/src/qml/components/ScrollPageView.qml @@ -5,6 +5,9 @@ import Asteria Rectangle { focus: true + // Width reserved for the vertical scrollbar on the right edge. + readonly property int scrollbarWidth: 18 + property bool contentReady: false property bool resizing: false property bool restoreReady: false @@ -60,7 +63,7 @@ Rectangle { } function updateContentWidth() { - book.setContentWidth(chunkListView.width - 18 - 2 * readingPreferences.horizontalMargin) + book.setContentWidth(chunkListView.width - scrollbarWidth - 2 * readingPreferences.horizontalMargin) } Component.onCompleted: updateContentWidth() @@ -104,7 +107,7 @@ Rectangle { } Text { id: contentText - width: parent.width - 18 // subtract scrollbar + width: parent.width - scrollbarWidth leftPadding: readingPreferences.horizontalMargin rightPadding: readingPreferences.horizontalMargin wrapMode: Text.WrapAtWordBoundaryOrAnywhere @@ -115,8 +118,8 @@ Rectangle { text: model.content visible: model.content !== "" onImplicitHeightChanged: { - if (model.pixelHeight > 0 && implicitHeight > 0) { - var diff = model.pixelHeight - implicitHeight + if (isDebugBuild && model.pixelHeight > 0 && implicitHeight > 0) { + const diff = model.pixelHeight - implicitHeight if (Math.abs(diff) > 1) { console.warn("Chunk", model.index, "height mismatch: measured=" + model.pixelHeight, @@ -136,19 +139,19 @@ Rectangle { policy: ScrollBar.AsNeeded padding: 0 contentItem: Rectangle { - implicitWidth: 18 + implicitWidth: scrollbarWidth radius: 3 color: ThemeManager.currentTheme.scrollbarThumb } background: Rectangle { - implicitWidth: 18 + implicitWidth: scrollbarWidth color: ThemeManager.currentTheme.scrollbarTrack } } MouseArea { anchors.fill: parent - anchors.rightMargin: 18 + anchors.rightMargin: scrollbarWidth z: 1 onClicked: clickDebounce.restart() onDoubleClicked: { @@ -162,7 +165,7 @@ Rectangle { interval: 150 onTriggered: { window.barsVisible = !window.barsVisible - window.sidebarOpen = !window.sidebarOpen + uiState.sidebarOpen = !uiState.sidebarOpen } } } @@ -210,7 +213,8 @@ Rectangle { interval: 1 repeat: false onTriggered: { - console.info("Restoring contentHeight:", chunkListView.contentHeight, "originY:", chunkListView.originY, "chunkIndex:", initialIndex, "intraOffset:", initialOffset) + if (isDebugBuild) + console.info("Restoring contentHeight:", chunkListView.contentHeight, "originY:", chunkListView.originY, "chunkIndex:", initialIndex, "intraOffset:", initialOffset) chunkListView.positionViewAtIndex(initialIndex, ListView.Beginning) chunkListView.contentY += initialOffset restoreReady = true diff --git a/src/qml/components/SettingsPopup.qml b/src/qml/components/SettingsPopup.qml index b9e558a..962913c 100644 --- a/src/qml/components/SettingsPopup.qml +++ b/src/qml/components/SettingsPopup.qml @@ -49,20 +49,12 @@ Item { color: ThemeManager.currentTheme.dimText } - Button { + FlatIconButton { anchors.verticalCenter: parent.verticalCenter anchors.right: parent.right anchors.rightMargin: 8 - flat: true - contentItem: Text { - text: "\ue5cd" - font.family: "Material Icons Outlined" - font.pixelSize: 18 - color: ThemeManager.currentTheme.dimText - horizontalAlignment: Text.AlignHCenter - verticalAlignment: Text.AlignVCenter - } - background: Item {} + iconText: "\ue5cd" + iconSize: 18 onClicked: popup.closeRequested() } @@ -114,236 +106,40 @@ Item { bottomPadding: 16 spacing: 16 - // Horizontal margin - Column { + LabeledSlider { width: parent.width - spacing: 4 - - Item { - width: parent.width - height: Math.max(labelH.implicitHeight, valueH.implicitHeight) - Text { - id: labelH - text: "Horizontal margin" - font.pixelSize: 13 - color: ThemeManager.currentTheme.uiText - anchors.verticalCenter: parent.verticalCenter - } - Text { - id: valueH - text: hmSlider.value + " px" - font.pixelSize: 12 - color: ThemeManager.currentTheme.dimText - anchors.right: parent.right - anchors.verticalCenter: parent.verticalCenter - } - } - Timer { - id: hmTimer - interval: 250 - onTriggered: readingPreferences.horizontalMargin = hmSlider.value - } - Slider { - id: hmSlider - width: parent.width - from: 0; to: 64; stepSize: 1 - value: readingPreferences.horizontalMargin - onValueChanged: { if (value !== readingPreferences.horizontalMargin) hmTimer.restart() } - background: Rectangle { - x: hmSlider.leftPadding - y: hmSlider.topPadding + hmSlider.availableHeight / 2 - height / 2 - width: hmSlider.availableWidth - height: 3 - radius: 2 - color: ThemeManager.currentTheme.scrollbarThumb - Rectangle { - width: hmSlider.visualPosition * parent.width - height: parent.height - radius: 2 - color: ThemeManager.currentTheme.buttonAccent - } - } - handle: Rectangle { - x: hmSlider.leftPadding + hmSlider.visualPosition * (hmSlider.availableWidth - width) - y: hmSlider.topPadding + hmSlider.availableHeight / 2 - height / 2 - width: 14; height: 14; radius: 7 - color: hmSlider.pressed ? Qt.lighter(ThemeManager.currentTheme.buttonAccent, 1.15) : ThemeManager.currentTheme.buttonAccent - } - } + label: "Horizontal margin" + from: 0; to: 64; stepSize: 1 + value: readingPreferences.horizontalMargin + valueText: value + " px" + onCommitted: function(v) { readingPreferences.horizontalMargin = v } } - // Vertical margin - Column { + LabeledSlider { width: parent.width - spacing: 4 - - Item { - width: parent.width - height: Math.max(labelV.implicitHeight, valueV.implicitHeight) - Text { - id: labelV - text: "Vertical margin" - font.pixelSize: 13 - color: ThemeManager.currentTheme.uiText - anchors.verticalCenter: parent.verticalCenter - } - Text { - id: valueV - text: vmSlider.value + " px" - font.pixelSize: 12 - color: ThemeManager.currentTheme.dimText - anchors.right: parent.right - anchors.verticalCenter: parent.verticalCenter - } - } - Timer { - id: vmTimer - interval: 250 - onTriggered: readingPreferences.verticalMargin = vmSlider.value - } - Slider { - id: vmSlider - width: parent.width - from: 0; to: 64; stepSize: 1 - value: readingPreferences.verticalMargin - onValueChanged: { if (value !== readingPreferences.verticalMargin) vmTimer.restart() } - background: Rectangle { - x: vmSlider.leftPadding - y: vmSlider.topPadding + vmSlider.availableHeight / 2 - height / 2 - width: vmSlider.availableWidth - height: 3 - radius: 2 - color: ThemeManager.currentTheme.scrollbarThumb - Rectangle { - width: vmSlider.visualPosition * parent.width - height: parent.height - radius: 2 - color: ThemeManager.currentTheme.buttonAccent - } - } - handle: Rectangle { - x: vmSlider.leftPadding + vmSlider.visualPosition * (vmSlider.availableWidth - width) - y: vmSlider.topPadding + vmSlider.availableHeight / 2 - height / 2 - width: 14; height: 14; radius: 7 - color: vmSlider.pressed ? Qt.lighter(ThemeManager.currentTheme.buttonAccent, 1.15) : ThemeManager.currentTheme.buttonAccent - } - } + label: "Vertical margin" + from: 0; to: 64; stepSize: 1 + value: readingPreferences.verticalMargin + valueText: value + " px" + onCommitted: function(v) { readingPreferences.verticalMargin = v } } - // Font size - Column { + LabeledSlider { width: parent.width - spacing: 4 - - Item { - width: parent.width - height: Math.max(labelF.implicitHeight, valueF.implicitHeight) - Text { - id: labelF - text: "Font size" - font.pixelSize: 13 - color: ThemeManager.currentTheme.uiText - anchors.verticalCenter: parent.verticalCenter - } - Text { - id: valueF - text: fsSlider.value + " px" - font.pixelSize: 12 - color: ThemeManager.currentTheme.dimText - anchors.right: parent.right - anchors.verticalCenter: parent.verticalCenter - } - } - Timer { - id: fsTimer - interval: 250 - onTriggered: readingPreferences.fontSize = fsSlider.value - } - Slider { - id: fsSlider - width: parent.width - from: 10; to: 32; stepSize: 1 - value: readingPreferences.fontSize - onValueChanged: { if (value !== readingPreferences.fontSize) fsTimer.restart() } - background: Rectangle { - x: fsSlider.leftPadding - y: fsSlider.topPadding + fsSlider.availableHeight / 2 - height / 2 - width: fsSlider.availableWidth - height: 3 - radius: 2 - color: ThemeManager.currentTheme.scrollbarThumb - Rectangle { - width: fsSlider.visualPosition * parent.width - height: parent.height - radius: 2 - color: ThemeManager.currentTheme.buttonAccent - } - } - handle: Rectangle { - x: fsSlider.leftPadding + fsSlider.visualPosition * (fsSlider.availableWidth - width) - y: fsSlider.topPadding + fsSlider.availableHeight / 2 - height / 2 - width: 14; height: 14; radius: 7 - color: fsSlider.pressed ? Qt.lighter(ThemeManager.currentTheme.buttonAccent, 1.15) : ThemeManager.currentTheme.buttonAccent - } - } + label: "Font size" + from: 10; to: 32; stepSize: 1 + value: readingPreferences.fontSize + valueText: value + " px" + onCommitted: function(v) { readingPreferences.fontSize = v } } - // Line spacing - Column { + LabeledSlider { width: parent.width - spacing: 4 - - Item { - width: parent.width - height: Math.max(labelL.implicitHeight, valueL.implicitHeight) - Text { - id: labelL - text: "Line spacing" - font.pixelSize: 13 - color: ThemeManager.currentTheme.uiText - anchors.verticalCenter: parent.verticalCenter - } - Text { - id: valueL - text: lsSlider.value.toFixed(1) + "×" - font.pixelSize: 12 - color: ThemeManager.currentTheme.dimText - anchors.right: parent.right - anchors.verticalCenter: parent.verticalCenter - } - } - Timer { - id: lsTimer - interval: 250 - onTriggered: readingPreferences.lineSpacing = lsSlider.value - } - Slider { - id: lsSlider - width: parent.width - from: 0.5; to: 2.0; stepSize: 0.1 - value: readingPreferences.lineSpacing - onValueChanged: { if (Math.abs(value - readingPreferences.lineSpacing) > 0.01) lsTimer.restart() } - background: Rectangle { - x: lsSlider.leftPadding - y: lsSlider.topPadding + lsSlider.availableHeight / 2 - height / 2 - width: lsSlider.availableWidth - height: 3 - radius: 2 - color: ThemeManager.currentTheme.scrollbarThumb - Rectangle { - width: lsSlider.visualPosition * parent.width - height: parent.height - radius: 2 - color: ThemeManager.currentTheme.buttonAccent - } - } - handle: Rectangle { - x: lsSlider.leftPadding + lsSlider.visualPosition * (lsSlider.availableWidth - width) - y: lsSlider.topPadding + lsSlider.availableHeight / 2 - height / 2 - width: 14; height: 14; radius: 7 - color: lsSlider.pressed ? Qt.lighter(ThemeManager.currentTheme.buttonAccent, 1.15) : ThemeManager.currentTheme.buttonAccent - } - } + label: "Line spacing" + from: 0.5; to: 2.0; stepSize: 0.1 + value: readingPreferences.lineSpacing + valueText: value.toFixed(1) + "\u00d7" + onCommitted: function(v) { readingPreferences.lineSpacing = v } } } } diff --git a/src/qml/components/SideBar.qml b/src/qml/components/SideBar.qml index ef435b5..155303d 100644 --- a/src/qml/components/SideBar.qml +++ b/src/qml/components/SideBar.qml @@ -33,19 +33,14 @@ Rectangle { } // Close button aligned with main header row - Button { + FlatIconButton { anchors.right: parent.right anchors.rightMargin: 12 y: ThemeManager.headerHeight / 2 - height / 2 z: 1 - flat: true - contentItem: Text { - text: "\ue5cb" - font.family: "Material Icons Outlined" - font.pixelSize: 24 - color: DarkTheme.sidebarButtonText - } - background: Item {} + iconText: "\ue5cb" + iconSize: 24 + iconColor: ThemeManager.currentTheme.sidebarButtonText onClicked: sidebar.closeDrawer() } @@ -174,8 +169,8 @@ Rectangle { text: modelData.title font.pixelSize: 13 color: readingModel.currentChapter === modelData.chapterIndex - ? ThemeManager.sidebarButtonText - : ThemeManager.uiText + ? ThemeManager.currentTheme.sidebarButtonText + : ThemeManager.currentTheme.uiText elide: Text.ElideRight wrapMode: Text.NoWrap } diff --git a/src/qml/pages/CustomThemePage.qml b/src/qml/pages/CustomThemePage.qml index cfe4834..613e41e 100644 --- a/src/qml/pages/CustomThemePage.qml +++ b/src/qml/pages/CustomThemePage.qml @@ -208,160 +208,29 @@ Rectangle { bottomPadding: 16 spacing: 0 - // ── Background ───────────────────────────────────────────────── + // One section + row per entry in ThemeManager's key tables. + Repeater { + model: ThemeManager.colorSections - SectionLabel { text: "Background" } + delegate: Column { + required property var modelData + width: parent.width + spacing: 0 - ColorRow { - width: parent.width - 16 - label: "Deepest background" - value: ThemeManager.customTheme.backgroundDeepest - apply: function(c) { ThemeManager.customTheme.backgroundDeepest = c } - } + SectionLabel { text: modelData.title } - ColorRow { - width: parent.width - 16 - label: "Default background" - value: ThemeManager.customTheme.backgroundDefault - apply: function(c) { ThemeManager.customTheme.backgroundDefault = c } - } + Repeater { + model: modelData.keys - ColorRow { - width: parent.width - 16 - label: "Gradient top" - value: ThemeManager.customTheme.gradientTop - apply: function(c) { ThemeManager.customTheme.gradientTop = c } - } - - ColorRow { - width: parent.width - 16 - label: "Gradient bottom" - value: ThemeManager.customTheme.gradientBottom - apply: function(c) { ThemeManager.customTheme.gradientBottom = c } - } - - // ── Surfaces ─────────────────────────────────────────────────── - - SectionLabel { text: "Surfaces" } - - ColorRow { - width: parent.width - 16 - label: "Surface" - value: ThemeManager.customTheme.surface - apply: function(c) { ThemeManager.customTheme.surface = c } - } - - ColorRow { - width: parent.width - 16 - label: "Header background" - value: ThemeManager.customTheme.headerBg - apply: function(c) { ThemeManager.customTheme.headerBg = c } - } - - ColorRow { - width: parent.width - 16 - label: "Footer background" - value: ThemeManager.customTheme.footerBg - apply: function(c) { ThemeManager.customTheme.footerBg = c } - } - - ColorRow { - width: parent.width - 16 - label: "Overlay background" - value: ThemeManager.customTheme.overlayBg - apply: function(c) { ThemeManager.customTheme.overlayBg = c } - } - - ColorRow { - width: parent.width - 16 - label: "Scrollbar track" - value: ThemeManager.customTheme.scrollbarTrack - apply: function(c) { ThemeManager.customTheme.scrollbarTrack = c } - } - - ColorRow { - width: parent.width - 16 - label: "Scrollbar thumb" - value: ThemeManager.customTheme.scrollbarThumb - apply: function(c) { ThemeManager.customTheme.scrollbarThumb = c } - } - - ColorRow { - width: parent.width - 16 - label: "Divider" - value: ThemeManager.customTheme.divider - apply: function(c) { ThemeManager.customTheme.divider = c } - } - - // ── Text ─────────────────────────────────────────────────────── - - SectionLabel { text: "Text" } - - ColorRow { - width: parent.width - 16 - label: "Reading text" - value: ThemeManager.customTheme.readingText - apply: function(c) { ThemeManager.customTheme.readingText = c } - } - - ColorRow { - width: parent.width - 16 - label: "UI text" - value: ThemeManager.customTheme.uiText - apply: function(c) { ThemeManager.customTheme.uiText = c } - } - - ColorRow { - width: parent.width - 16 - label: "Header text" - value: ThemeManager.customTheme.headerText - apply: function(c) { ThemeManager.customTheme.headerText = c } - } - - ColorRow { - width: parent.width - 16 - label: "Dim text" - value: ThemeManager.customTheme.dimText - apply: function(c) { ThemeManager.customTheme.dimText = c } - } - - ColorRow { - width: parent.width - 16 - label: "Counter text" - value: ThemeManager.customTheme.counterText - apply: function(c) { ThemeManager.customTheme.counterText = c } - } - - ColorRow { - width: parent.width - 16 - label: "Sidebar button text" - value: ThemeManager.customTheme.sidebarButtonText - apply: function(c) { ThemeManager.customTheme.sidebarButtonText = c } - } - - // ── Accents ──────────────────────────────────────────────────── - - SectionLabel { text: "Accents" } - - ColorRow { - width: parent.width - 16 - label: "Primary accent" - value: ThemeManager.customTheme.primaryAccent - apply: function(c) { ThemeManager.customTheme.primaryAccent = c } - } - - ColorRow { - width: parent.width - 16 - label: "Button accent" - value: ThemeManager.customTheme.buttonAccent - apply: function(c) { ThemeManager.customTheme.buttonAccent = c } - } - - ColorRow { - width: parent.width - 16 - label: "Action disabled" - value: ThemeManager.customTheme.actionDisabled - apply: function(c) { ThemeManager.customTheme.actionDisabled = c } + delegate: ColorRow { + required property string modelData + width: parent.width - 16 + label: ThemeManager.colorLabels[modelData] + value: ThemeManager.customTheme[modelData] + apply: function(c) { ThemeManager.customTheme[modelData] = c } + } + } + } } } } diff --git a/src/qml/pages/HistoryPage.qml b/src/qml/pages/HistoryPage.qml index eca458a..8770850 100644 --- a/src/qml/pages/HistoryPage.qml +++ b/src/qml/pages/HistoryPage.qml @@ -101,19 +101,11 @@ Rectangle { } } - Button { + FlatIconButton { id: removeBtn anchors.verticalCenter: parent.verticalCenter - flat: true - contentItem: Text { - text: "\ue872" - font.family: "Material Icons Outlined" - font.pixelSize: 20 - color: ThemeManager.currentTheme.dimText - horizontalAlignment: Text.AlignHCenter - verticalAlignment: Text.AlignVCenter - } - background: Item {} + iconText: "\ue872" + iconSize: 20 onClicked: historyModel.removeBook(filePath) } } diff --git a/tests/EpubImageProviderTest.cpp b/tests/EntryImageProviderTest.cpp similarity index 70% rename from tests/EpubImageProviderTest.cpp rename to tests/EntryImageProviderTest.cpp index 8992360..686a2f0 100644 --- a/tests/EpubImageProviderTest.cpp +++ b/tests/EntryImageProviderTest.cpp @@ -10,7 +10,27 @@ #include -#include "backend/formats/EpubImageProvider.h" +#include "backend/formats/AsyncImageResponse.h" +#include "backend/formats/EntryImageProvider.h" +#include "backend/formats/sources/Fb2ByteSource.h" +#include "backend/formats/sources/ZipByteSource.h" + +// Load one zip member through the generic byte-source pipeline (EPUBs are zips). +static QImage loadFromEpub(const QString &epubPath, const QString &entry, + int displayWidth, const QSize &requestedSize) +{ + ZipByteSource source; + if (!source.open(epubPath)) + return {}; + return EntryImageProvider::loadImageFromSource(source, entry, displayWidth, + requestedSize); +} + +static EntryImageProvider makeEpubProvider() +{ + return EntryImageProvider([] { return std::make_unique(); }, + QStringLiteral("epub")); +} // --------------------------------------------------------------------------- // Helpers @@ -66,7 +86,7 @@ static QString buildEpubWithPng(const char *entryPath, int imgW, int imgH, // Test class // --------------------------------------------------------------------------- -class EpubImageProviderTest : public QObject { +class EntryImageProviderTest : public QObject { Q_OBJECT private slots: @@ -75,7 +95,7 @@ private slots: const QString epubPath = buildEpubWithPng("OEBPS/Images/test.png", 4, 4); QVERIFY(!epubPath.isEmpty()); - const QImage img = EpubImageProvider::loadImageFromEpub( + const QImage img = loadFromEpub( epubPath, QStringLiteral("OEBPS/Images/test.png"), 0, QSize()); QFile::remove(epubPath); @@ -91,7 +111,7 @@ private slots: const QString epubPath = buildEpubWithPng("OEBPS/Images/test.png", 4, 4); QVERIFY(!epubPath.isEmpty()); - const QImage img = EpubImageProvider::loadImageFromEpub( + const QImage img = loadFromEpub( epubPath, QStringLiteral("OEBPS/Images/nonexistent.png"), 0, QSize()); QFile::remove(epubPath); @@ -101,7 +121,7 @@ private slots: void requestImageReturnsNullWhenNoPath() { - const QImage img = EpubImageProvider::loadImageFromEpub( + const QImage img = loadFromEpub( QString{}, QStringLiteral("OEBPS/Images/test.png"), 0, QSize()); QVERIFY(img.isNull()); } @@ -112,7 +132,7 @@ private slots: QVERIFY(!epubPath.isEmpty()); // After clear the path is empty, so loadImageFromEpub with empty path returns null - const QImage img = EpubImageProvider::loadImageFromEpub( + const QImage img = loadFromEpub( QString{}, QStringLiteral("OEBPS/Images/test.png"), 0, QSize()); QFile::remove(epubPath); @@ -125,7 +145,7 @@ private slots: const QString epubPath = buildEpubWithPng("img.png", 600, 400); QVERIFY(!epubPath.isEmpty()); - const QImage img = EpubImageProvider::loadImageFromEpub( + const QImage img = loadFromEpub( epubPath, QStringLiteral("img.png"), 300, QSize()); QFile::remove(epubPath); @@ -141,7 +161,7 @@ private slots: const QString epubPath = buildEpubWithPng("img.png", 100, 100); QVERIFY(!epubPath.isEmpty()); - const QImage img = EpubImageProvider::loadImageFromEpub( + const QImage img = loadFromEpub( epubPath, QStringLiteral("img.png"), 300, QSize()); QFile::remove(epubPath); @@ -156,7 +176,7 @@ private slots: const QString epubPath = buildEpubWithPng("img.png", 400, 300); QVERIFY(!epubPath.isEmpty()); - const QImage img = EpubImageProvider::loadImageFromEpub( + const QImage img = loadFromEpub( epubPath, QStringLiteral("img.png"), 600, QSize(200, -1)); QFile::remove(epubPath); @@ -174,7 +194,10 @@ private slots: const QString epubPath = buildEpubWithPng("img.png", 4, 4); QVERIFY(!epubPath.isEmpty()); - EpubImageResponse response(epubPath, QStringLiteral("img.png"), 0, QSize()); + AsyncImageResponse response([epubPath] { + return loadFromEpub( + epubPath, QStringLiteral("img.png"), 0, QSize()); + }); QSignalSpy spy(&response, &QQuickImageResponse::finished); response.run(); @@ -189,7 +212,10 @@ private slots: const QString epubPath = buildEpubWithPng("img.png", 4, 4); QVERIFY(!epubPath.isEmpty()); - EpubImageResponse response(epubPath, QStringLiteral("img.png"), 0, QSize()); + AsyncImageResponse response([epubPath] { + return loadFromEpub( + epubPath, QStringLiteral("img.png"), 0, QSize()); + }); QSignalSpy spy(&response, &QQuickImageResponse::finished); response.cancel(); response.run(); @@ -204,7 +230,10 @@ private slots: const QString epubPath = buildEpubWithPng("img.png", 4, 4); QVERIFY(!epubPath.isEmpty()); - EpubImageResponse response(epubPath, QStringLiteral("img.png"), 0, QSize()); + AsyncImageResponse response([epubPath] { + return loadFromEpub( + epubPath, QStringLiteral("img.png"), 0, QSize()); + }); response.cancel(); response.run(); @@ -222,15 +251,15 @@ private slots: const QString epubPath = buildEpubWithPng("img.png", 4, 4); QVERIFY(!epubPath.isEmpty()); - EpubImageProvider provider; + EntryImageProvider provider = makeEpubProvider(); provider.setFilePath(epubPath); const QString url = provider.coverImageUrl(QStringLiteral("OEBPS/cover.jpg")); QFile::remove(epubPath); - // New format: image://epub/?epub= - QVERIFY2(url.startsWith(QStringLiteral("image://epub/OEBPS/cover.jpg?epub=")), + // New format: image://epub/?src= + QVERIFY2(url.startsWith(QStringLiteral("image://epub/OEBPS/cover.jpg?src=")), qPrintable("Expected query-param URL, got: " + url)); const QString encodedPath = QString::fromUtf8(QUrl::toPercentEncoding(epubPath)); QVERIFY2(url.contains(encodedPath), @@ -245,12 +274,12 @@ private slots: const QString epubB = buildEpubWithPng("img.png", 4, 4, qRgb(0, 255, 0)); QVERIFY(!epubA.isEmpty() && !epubB.isEmpty()); - EpubImageProvider provider; + EntryImageProvider provider = makeEpubProvider(); provider.setFilePath(epubA); // configured for A // Build an embedded-format id pointing to B via query parameter const QString encodedB = QString::fromUtf8(QUrl::toPercentEncoding(epubB)); - const QString id = QStringLiteral("img.png?epub=") + encodedB; + const QString id = QStringLiteral("img.png?src=") + encodedB; QQuickImageResponse *resp = provider.requestImageResponse(id, QSize()); QSignalSpy spy(resp, &QQuickImageResponse::finished); @@ -274,10 +303,10 @@ private slots: const QString epubPath = buildEpubWithPng("img.png", 4, 4, qRgb(255, 0, 0)); QVERIFY(!epubPath.isEmpty()); - EpubImageProvider provider; + EntryImageProvider provider = makeEpubProvider(); // m_epubPath is intentionally NOT set — embedded URL must supply it via query const QString encodedPath = QString::fromUtf8(QUrl::toPercentEncoding(epubPath)); - const QUrl url(QStringLiteral("image://epub/img.png?epub=") + encodedPath); + const QUrl url(QStringLiteral("image://epub/img.png?src=") + encodedPath); const QImage img = provider.load(url, 0); @@ -293,7 +322,7 @@ private slots: const QString epubA = buildEpubWithPng("img.png", 4, 4, qRgb(255, 0, 0)); QVERIFY(!epubA.isEmpty()); - EpubImageProvider provider; + EntryImageProvider provider = makeEpubProvider(); provider.setFilePath(epubA); // No query param — old format, uses m_epubPath @@ -318,7 +347,7 @@ private slots: const QString epubPath = buildEpubWithPng("img.png", 4, 4); QVERIFY(!epubPath.isEmpty()); - EpubImageProvider provider; + EntryImageProvider provider = makeEpubProvider(); provider.setFilePath(epubPath); provider.clear(); @@ -331,7 +360,59 @@ private slots: QVERIFY(resp->textureFactory() == nullptr); delete resp; } + + // ----------------------------------------------------------------------- + // Fb2ByteSource + // ----------------------------------------------------------------------- + + void fb2ByteSourceReadsBinaryById() + { + const QByteArray png = makePng(4, 4, qRgb(0, 0, 255)); + const QByteArray fb2 = QByteArrayLiteral( + "" + "

text

" + "") + + png.toBase64() + + QByteArrayLiteral("
"); + + QTemporaryFile tmp(QDir::tempPath() + "/fb2_source_XXXXXX.fb2"); + tmp.setAutoRemove(false); + QVERIFY(tmp.open()); + tmp.write(fb2); + const QString path = tmp.fileName(); + tmp.close(); + + Fb2ByteSource source; + QVERIFY(source.open(path)); + QCOMPARE(source.listEntries(), QStringList{QStringLiteral("cover.png")}); + + const QImage img = EntryImageProvider::loadImageFromSource( + source, QStringLiteral("cover.png"), 0, QSize()); + QVERIFY(!source.contentHash().isEmpty()); + + QFile::remove(path); + + QVERIFY(!img.isNull()); + QCOMPARE(img.pixel(0, 0), qRgb(0, 0, 255)); + } + + void fb2ByteSourceMissingIdReturnsEmpty() + { + QTemporaryFile tmp(QDir::tempPath() + "/fb2_source_XXXXXX.fb2"); + tmp.setAutoRemove(false); + QVERIFY(tmp.open()); + tmp.write(QByteArrayLiteral("")); + const QString path = tmp.fileName(); + tmp.close(); + + Fb2ByteSource source; + QVERIFY(source.open(path)); + const QByteArray data = source.readEntry(QStringLiteral("nope")); + + QFile::remove(path); + QVERIFY(data.isEmpty()); + } }; -QTEST_MAIN(EpubImageProviderTest) -#include "EpubImageProviderTest.moc" +QTEST_MAIN(EntryImageProviderTest) +#include "EntryImageProviderTest.moc" diff --git a/tests/FormatRegistryTest.cpp b/tests/FormatRegistryTest.cpp new file mode 100644 index 0000000..e8120cf --- /dev/null +++ b/tests/FormatRegistryTest.cpp @@ -0,0 +1,141 @@ +#include +#include +#include "backend/formats/FormatRegistry.h" +#include "backend/FormatReader.h" +#include "backend/IImageProvider.h" +#include "backend/IImageLoader.h" +#include "backend/formats/TxtReader.h" +#include "backend/formats/EpubReader.h" +#include "backend/formats/comic/CbzReader.h" +#include "backend/formats/comic/CbrReader.h" +#include "backend/formats/comic/FolderReader.h" +#include "backend/formats/sources/DirByteSource.h" +#include "backend/formats/sources/RarByteSource.h" +#include "backend/formats/sources/ZipByteSource.h" + +static FormatRegistry makeRegistry() +{ + return FormatRegistry({ + {QStringLiteral("txt"), false, {}, + [] { return std::make_unique(); }, nullptr}, + {QStringLiteral("epub"), false, QStringLiteral("epub"), + [] { return std::make_unique(); }, + [] { return std::make_unique(); }, + /*loaderIncludesWeb=*/true}, + {QStringLiteral("cbz"), false, QStringLiteral("cbz"), + [] { return std::make_unique(); }, + [] { return std::make_unique(); }}, + {QStringLiteral("cbr"), false, QStringLiteral("cbr"), + [] { return std::make_unique(); }, + [] { return std::make_unique(); }}, + {{}, /*matchesDirectory=*/true, QStringLiteral("dir"), + [] { return std::make_unique(); }, + [] { return std::make_unique(); }}, + }); +} + +class FormatRegistryTest : public QObject { + Q_OBJECT + +private slots: + void createTxtReader() + { + auto registry = makeRegistry(); + QVERIFY(registry.createReader("file.txt") != nullptr); + } + + void createTxtReaderUpperCase() + { + auto registry = makeRegistry(); + QVERIFY(registry.createReader("file.TXT") != nullptr); + } + + void createUnknownFormat() + { + auto registry = makeRegistry(); + QVERIFY(registry.createReader("file.xyz") == nullptr); + } + + void createNoExtension() + { + auto registry = makeRegistry(); + QVERIFY(registry.createReader("noext") == nullptr); + } + + void createEmptyPath() + { + auto registry = makeRegistry(); + QVERIFY(registry.createReader("") == nullptr); + } + + void createCbzReader() + { + auto registry = makeRegistry(); + QVERIFY(registry.createReader("file.cbz") != nullptr); + } + + void createCbrReader() + { + auto registry = makeRegistry(); + QVERIFY(registry.createReader("file.cbr") != nullptr); + } + + void createFolderReader() + { + QTemporaryDir tmp; + QVERIFY(tmp.isValid()); + auto registry = makeRegistry(); + auto reader = registry.createReader(tmp.path()); + QVERIFY(reader != nullptr); + QCOMPARE(reader->fileType(), QStringLiteral("folder")); + } + + void supportedExtensions() + { + auto registry = makeRegistry(); + const QStringList exts = registry.supportedExtensions(); + QVERIFY(exts.contains(QStringLiteral("txt"))); + QVERIFY(exts.contains(QStringLiteral("epub"))); + QVERIFY(exts.contains(QStringLiteral("cbz"))); + QVERIFY(exts.contains(QStringLiteral("cbr"))); + // The directory row contributes no extension + QCOMPARE(exts.size(), 4); + } + + void imageProviderSchemesMatchTable() + { + auto registry = makeRegistry(); + + std::unique_ptr epub(registry.createImageProvider("book.epub")); + QVERIFY(epub); + QCOMPARE(epub->scheme(), QStringLiteral("epub")); + + std::unique_ptr cbz(registry.createImageProvider("comic.cbz")); + QVERIFY(cbz); + QCOMPARE(cbz->scheme(), QStringLiteral("cbz")); + + QTemporaryDir tmp; + std::unique_ptr dir(registry.createImageProvider(tmp.path())); + QVERIFY(dir); + QCOMPARE(dir->scheme(), QStringLiteral("dir")); + } + + void formatsWithoutImagesHaveNoProviderOrLoader() + { + auto registry = makeRegistry(); + QVERIFY(registry.createImageProvider("plain.txt") == nullptr); + QVERIFY(registry.createImageLoader("plain.txt") == nullptr); + QVERIFY(registry.createImageProvider("file.xyz") == nullptr); + } + + void createImageLoaderReturnsLoader() + { + auto registry = makeRegistry(); + QVERIFY(registry.createImageLoader("comic.cbz") != nullptr); + // epub loader is a composite (epub + web) but still non-null + QVERIFY(registry.createImageLoader("book.epub") != nullptr); + } +}; + +QTEST_MAIN(FormatRegistryTest) +#include "FormatRegistryTest.moc" diff --git a/tests/HistoryBookModelTest.cpp b/tests/HistoryBookModelTest.cpp index 1417cfd..99a29c3 100644 --- a/tests/HistoryBookModelTest.cpp +++ b/tests/HistoryBookModelTest.cpp @@ -12,13 +12,18 @@ #include "backend/FormatReader.h" #include "backend/formats/EpubReader.h" #include "backend/formats/TxtReader.h" -#include "backend/formats/ReaderFactory.h" +#include "backend/formats/FormatRegistry.h" +#include "backend/formats/sources/ZipByteSource.h" -static ReaderFactory makeFactory() +static FormatRegistry makeRegistry() { - return ReaderFactory({ - [] { return std::make_unique(); }, - [] { return std::make_unique(); }, + return FormatRegistry({ + {QStringLiteral("txt"), false, {}, + [] { return std::make_unique(); }, nullptr}, + {QStringLiteral("epub"), false, QStringLiteral("epub"), + [] { return std::make_unique(); }, + [] { return std::make_unique(); }, + /*loaderIncludesWeb=*/true}, }); } @@ -125,10 +130,11 @@ private slots: const QString epubPath = buildEpubWithCover(); QVERIFY(!epubPath.isEmpty()); - ReaderFactory factory = makeFactory(); - HistoryBookModel model(epubPath, 0.0, QString(), factory); + FormatRegistry registry = makeRegistry(); + HistoryBookModel model(epubPath, 0.0, QString(), registry); QSignalSpy spy(&model, &HistoryBookModel::metadataLoaded); + QSignalSpy coverSpy(&model, &HistoryBookModel::coverImageLoaded); model.loadMetadata(); // Wait up to 5 seconds for the async metadata load to complete @@ -136,10 +142,13 @@ private slots: QFile::remove(epubPath); + // coverImageUrl's NOTIFY signal must fire so QML bindings update + QCOMPARE(coverSpy.count(), 1); + const QString url = model.coverImageUrl(); QVERIFY2(!url.isEmpty(), "coverImageUrl should be set after loadMetadata for an EPUB with cover"); - // Format: image://epub/?epub= - QVERIFY2(url.startsWith(QStringLiteral("image://epub/OEBPS/Images/cover.png?epub=")), + // Format: image://epub/?src= + QVERIFY2(url.startsWith(QStringLiteral("image://epub/OEBPS/Images/cover.png?src=")), qPrintable("Expected query-param URL format, got: " + url)); const QString encodedPath = QString::fromUtf8(QUrl::toPercentEncoding(epubPath)); QVERIFY2(url.contains(encodedPath), @@ -151,8 +160,8 @@ private slots: const QString txtPath = QStringLiteral(FIXTURES_DIR) + "/sample.txt"; QVERIFY(QFile::exists(txtPath)); - ReaderFactory factory = makeFactory(); - HistoryBookModel model(txtPath, 0.0, QString(), factory); + FormatRegistry registry = makeRegistry(); + HistoryBookModel model(txtPath, 0.0, QString(), registry); QSignalSpy spy(&model, &HistoryBookModel::metadataLoaded); model.loadMetadata(); @@ -168,8 +177,8 @@ private slots: const QString epubPath = buildEpubWithCover(); QVERIFY(!epubPath.isEmpty()); - ReaderFactory factory = makeFactory(); - HistoryBookModel model(epubPath, 0.0, QString(), factory); + FormatRegistry registry = makeRegistry(); + HistoryBookModel model(epubPath, 0.0, QString(), registry); QSignalSpy spy(&model, &HistoryBookModel::metadataLoaded); model.loadMetadata(); diff --git a/tests/ReaderFactoryTest.cpp b/tests/ReaderFactoryTest.cpp deleted file mode 100644 index a4db30d..0000000 --- a/tests/ReaderFactoryTest.cpp +++ /dev/null @@ -1,94 +0,0 @@ -#include -#include -#include "backend/formats/ReaderFactory.h" -#include "backend/FormatReader.h" -#include "backend/formats/TxtReader.h" -#include "backend/formats/EpubReader.h" -#include "backend/formats/comic/CbzReader.h" -#include "backend/formats/comic/CbrReader.h" -#include "backend/formats/comic/FolderReader.h" - -static ReaderFactory makeFactory() -{ - return ReaderFactory({ - [] { return std::make_unique(); }, - [] { return std::make_unique(); }, - [] { return std::make_unique(); }, - [] { return std::make_unique(); }, - [] { return std::make_unique(); }, - }); -} - -class ReaderFactoryTest : public QObject { - Q_OBJECT - -private slots: - void createTxtReader() - { - auto factory = makeFactory(); - QVERIFY(factory.create("file.txt") != nullptr); - } - - void createTxtReaderUpperCase() - { - auto factory = makeFactory(); - QVERIFY(factory.create("file.TXT") != nullptr); - } - - void createUnknownFormat() - { - auto factory = makeFactory(); - QVERIFY(factory.create("file.xyz") == nullptr); - } - - void createNoExtension() - { - auto factory = makeFactory(); - QVERIFY(factory.create("noext") == nullptr); - } - - void createEmptyPath() - { - auto factory = makeFactory(); - QVERIFY(factory.create("") == nullptr); - } - - void createCbzReader() - { - auto factory = makeFactory(); - QVERIFY(factory.create("file.cbz") != nullptr); - } - - void createCbrReader() - { - auto factory = makeFactory(); - QVERIFY(factory.create("file.cbr") != nullptr); - } - - void createFolderReader() - { - QTemporaryDir tmp; - QVERIFY(tmp.isValid()); - auto factory = makeFactory(); - auto reader = factory.create(tmp.path()); - QVERIFY(reader != nullptr); - QCOMPARE(reader->fileType(), QStringLiteral("")); - } - - void supportedExtensions() - { - auto factory = makeFactory(); - const QStringList exts = factory.supportedExtensions(); - QVERIFY(exts.contains(QStringLiteral("txt"))); - QVERIFY(exts.contains(QStringLiteral("epub"))); - QVERIFY(exts.contains(QStringLiteral("cbz"))); - QVERIFY(exts.contains(QStringLiteral("cbr"))); - // Sentinel for directory must not appear in the extensions list - QVERIFY(!exts.contains(QStringLiteral(""))); - for (const QString &e : exts) - QVERIFY(!e.startsWith(QLatin1Char('<'))); - } -}; - -QTEST_MAIN(ReaderFactoryTest) -#include "ReaderFactoryTest.moc" diff --git a/tests/book/BookTest.cpp b/tests/book/BookTest.cpp index 99a7064..b1d9391 100644 --- a/tests/book/BookTest.cpp +++ b/tests/book/BookTest.cpp @@ -6,7 +6,7 @@ #include "backend/AppState.h" #include "backend/IFileDialogService.h" -#include "backend/formats/ReaderFactory.h" +#include "backend/formats/FormatRegistry.h" #include "backend/formats/TxtReader.h" #include "backend/formats/EpubReader.h" #include "backend/state/BookPositionStore.h" @@ -49,7 +49,7 @@ private: AppState *appState = nullptr; BookPositionStore *store = nullptr; FakeDialogService *dialog = nullptr; - ReaderFactory *factory = nullptr; + FormatRegistry *factory = nullptr; Book *book = nullptr; Ctx() { @@ -59,9 +59,11 @@ private: appState = new AppState(*s); store = new BookPositionStore(*appState); dialog = new FakeDialogService; - factory = new ReaderFactory({ - [] { return std::make_unique(); }, - [] { return std::make_unique(); }, + factory = new FormatRegistry({ + {QStringLiteral("txt"), false, {}, + [] { return std::make_unique(); }, nullptr}, + {QStringLiteral("epub"), false, QStringLiteral("epub"), + [] { return std::make_unique(); }, nullptr}, }); book = new Book(*dialog, *store, *factory); } diff --git a/tests/formats/FolderReaderTest.cpp b/tests/formats/FolderReaderTest.cpp index eee5592..8744ba9 100644 --- a/tests/formats/FolderReaderTest.cpp +++ b/tests/formats/FolderReaderTest.cpp @@ -106,7 +106,7 @@ private slots: void fileTypeAndRenderingMode() { FolderReader reader; - QCOMPARE(reader.fileType(), QStringLiteral("")); + QCOMPARE(reader.fileType(), QStringLiteral("folder")); QCOMPARE(static_cast(reader.preferredRenderingMode()), static_cast(FormatReader::RenderingMode::Manga)); } diff --git a/tests/formats/ImageUrlTest.cpp b/tests/formats/ImageUrlTest.cpp new file mode 100644 index 0000000..ca97d93 --- /dev/null +++ b/tests/formats/ImageUrlTest.cpp @@ -0,0 +1,83 @@ +#include +#include + +#include "backend/formats/ImageUrl.h" + +class ImageUrlTest : public QObject { + Q_OBJECT + +private slots: + void buildWithoutQuery() + { + QCOMPARE(ImageUrl::build(QStringLiteral("cbz"), QStringLiteral("page01.jpg")), + QStringLiteral("image://cbz/page01.jpg")); + } + + void buildWithSourcePath() + { + const QString url = ImageUrl::build(QStringLiteral("cbz"), + QStringLiteral("page01.jpg"), + QStringLiteral("/books/My Comic #1.cbz")); + QVERIFY(url.startsWith(QStringLiteral("image://cbz/page01.jpg?src="))); + // Source path must be percent-encoded (space and '#') + QVERIFY(!url.contains(QLatin1Char(' '))); + QVERIFY(!url.contains(QLatin1Char('#'))); + } + + void roundTripThroughProviderId() + { + const QString sourcePath = QStringLiteral("/books/My Comic #1.cbz"); + const QString url = ImageUrl::build(QStringLiteral("cbz"), + QStringLiteral("page01.jpg"), sourcePath); + // QML hands the provider everything after "image:///" + const QString id = url.mid(QStringLiteral("image://cbz/").size()); + + const auto parsed = ImageUrl::parseProviderId(id); + QCOMPARE(parsed.entry, QStringLiteral("page01.jpg")); + QCOMPARE(parsed.sourcePath, sourcePath); + } + + void roundTripThroughImageUrl() + { + const QString sourcePath = QStringLiteral("/books/unicode путь.cbz"); + const QString url = ImageUrl::build(QStringLiteral("cbz"), + QStringLiteral("dir/page01.jpg"), sourcePath); + + const auto parsed = ImageUrl::parseImageUrl(QUrl(url)); + QCOMPARE(parsed.entry, QStringLiteral("dir/page01.jpg")); + QCOMPARE(parsed.sourcePath, sourcePath); + } + + void providerIdWithoutQueryHasEmptySourcePath() + { + const auto parsed = ImageUrl::parseProviderId(QStringLiteral("OEBPS/img.png")); + QCOMPARE(parsed.entry, QStringLiteral("OEBPS/img.png")); + QVERIFY(parsed.sourcePath.isEmpty()); + } + + void providerIdDecodesPercentEncodedEntry() + { + // QML percent-encodes entry names before they reach the provider + const auto parsed = ImageUrl::parseProviderId(QStringLiteral("page%2001.jpg")); + QCOMPARE(parsed.entry, QStringLiteral("page 01.jpg")); + } + + void entryWithSlashesSurvivesParsing() + { + const auto parsed = ImageUrl::parseImageUrl( + QUrl(QStringLiteral("image://dir/nested/deep/page.png"))); + QCOMPARE(parsed.entry, QStringLiteral("nested/deep/page.png")); + QVERIFY(parsed.sourcePath.isEmpty()); + } + + void querySuffixMatchesBuild() + { + const QString sourcePath = QStringLiteral("/tmp/a b.fb2"); + QCOMPARE(ImageUrl::build(QStringLiteral("fb2"), QStringLiteral("cover"), sourcePath), + ImageUrl::build(QStringLiteral("fb2"), QStringLiteral("cover")) + + ImageUrl::querySuffix(sourcePath)); + } +}; + +QTEST_MAIN(ImageUrlTest) +#include "ImageUrlTest.moc" diff --git a/tests/reading/MangaPaginationTest.cpp b/tests/reading/MangaPaginationTest.cpp new file mode 100644 index 0000000..928ddbc --- /dev/null +++ b/tests/reading/MangaPaginationTest.cpp @@ -0,0 +1,124 @@ +#include + +#include "backend/reading/MangaPagination.h" + +static QSize portrait() { return {800, 1200}; } +static QSize landscape() { return {1600, 1200}; } + +class MangaPaginationTest : public QObject { + Q_OBJECT + +private slots: + void portraitViewportAllSolo() + { + MangaPagination p; + p.rebuild({portrait(), portrait(), portrait()}, /*landscape=*/false, /*shift=*/true); + QCOMPARE(p.count(), 3); + for (int i = 0; i < 3; ++i) { + QCOMPARE(p.at(i).first, i); + QCOMPARE(p.at(i).second, -1); + } + } + + void landscapeCoverSoloThenPairs() + { + MangaPagination p; + // cover + 4 portrait pages, shift off: cover solo, (1,2), (3,4) + p.rebuild({portrait(), portrait(), portrait(), portrait(), portrait()}, + true, /*shift=*/false); + QCOMPARE(p.count(), 3); + QCOMPARE(p.at(0).first, 0); + QCOMPARE(p.at(0).second, -1); + QCOMPARE(p.at(1).first, 1); + QCOMPARE(p.at(1).second, 2); + QCOMPARE(p.at(2).first, 3); + QCOMPARE(p.at(2).second, 4); + } + + void shiftMakesFirstPageSolo() + { + MangaPagination p; + // shift on: cover solo, page 1 solo, (2,3), 4 solo + p.rebuild({portrait(), portrait(), portrait(), portrait(), portrait()}, + true, /*shift=*/true); + QCOMPARE(p.count(), 4); + QCOMPARE(p.at(1).first, 1); + QCOMPARE(p.at(1).second, -1); + QCOMPARE(p.at(2).first, 2); + QCOMPARE(p.at(2).second, 3); + QCOMPARE(p.at(3).first, 4); + QCOMPARE(p.at(3).second, -1); + } + + void widePagesStaySolo() + { + MangaPagination p; + // cover, portrait, WIDE, portrait, portrait — wide page must not pair + p.rebuild({portrait(), portrait(), landscape(), portrait(), portrait()}, + true, /*shift=*/false); + QCOMPARE(p.count(), 4); + QCOMPARE(p.at(1).first, 1); + QCOMPARE(p.at(1).second, -1); // can't pair: next is wide + QCOMPARE(p.at(2).first, 2); + QCOMPARE(p.at(2).second, -1); // wide page solo + QCOMPARE(p.at(3).first, 3); + QCOMPARE(p.at(3).second, 4); + } + + void invalidSizesTreatedAsPortrait() + { + MangaPagination p; + p.rebuild({QSize(), QSize(), QSize()}, true, /*shift=*/false); + QCOMPARE(p.count(), 2); + QCOMPARE(p.at(1).first, 1); + QCOMPARE(p.at(1).second, 2); + } + + void pairIndexForChunkFindsBothSlots() + { + MangaPagination p; + p.rebuild({portrait(), portrait(), portrait(), portrait(), portrait()}, + true, /*shift=*/false); + QCOMPARE(p.pairIndexForChunk(0), 0); + QCOMPARE(p.pairIndexForChunk(1), 1); + QCOMPARE(p.pairIndexForChunk(2), 1); + QCOMPARE(p.pairIndexForChunk(3), 2); + QCOMPARE(p.pairIndexForChunk(4), 2); + QCOMPARE(p.pairIndexForChunk(99), 0); // not found falls back to 0 + } + + void anchorStableAcrossDoubleToggle() + { + const QVector sizes = {portrait(), portrait(), portrait(), + portrait(), portrait()}; + MangaPagination p; + p.rebuild(sizes, true, /*shift=*/false); // pairs: [0], (1,2), (3,4) + + // Viewing pair (1,2); toggle shift ON → anchor on .second (chunk 2) + const int anchorOn = p.anchorChunkForShiftToggle(1, /*shiftTurningOn=*/true); + QCOMPARE(anchorOn, 2); + + p.rebuild(sizes, true, /*shift=*/true); // pairs: [0], [1], (2,3), [4] + const int pairOn = p.pairIndexForChunk(anchorOn); + QCOMPARE(pairOn, 2); + + // Toggle back OFF → anchor on .first (chunk 2), land on (1,2) again + const int anchorOff = p.anchorChunkForShiftToggle(pairOn, /*shiftTurningOn=*/false); + QCOMPARE(anchorOff, 2); + p.rebuild(sizes, true, /*shift=*/false); + QCOMPARE(p.pairIndexForChunk(anchorOff), 1); + } + + void clearEmpties() + { + MangaPagination p; + p.rebuild({portrait()}, false, false); + QCOMPARE(p.count(), 1); + p.clear(); + QCOMPARE(p.count(), 0); + QCOMPARE(p.at(0).first, -1); // out of range is safe + } +}; + +QTEST_MAIN(MangaPaginationTest) +#include "MangaPaginationTest.moc"