Refactor using Fable
This commit is contained in:
90 files changed
+2080
-2267
No files matched your search
@@ -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 = `<section>` 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
|
||||
|
||||
+75
-56
@@ -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
|
||||
|
||||
@@ -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 <QCoreApplication>
|
||||
#include <QQmlApplicationEngine>
|
||||
#include <QSettings>
|
||||
|
||||
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<QVariantMap> 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();
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
#pragma once
|
||||
|
||||
#include <QObject>
|
||||
|
||||
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;
|
||||
};
|
||||
@@ -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<QVariantMap> AppState::loadArray(const QString §ion) const
|
||||
QList<QVariantMap> AppState::loadArray(const QString §ion)
|
||||
{
|
||||
QList<QVariantMap> result;
|
||||
QSettings &s = const_cast<QSettings &>(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<QVariantMap> &items) const
|
||||
void AppState::saveArray(const QString §ion, const QList<QVariantMap> &items)
|
||||
{
|
||||
m_settings.beginWriteArray(section, items.size());
|
||||
for (int i = 0; i < items.size(); ++i) {
|
||||
|
||||
@@ -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<QVariantMap> loadArray(const QString §ion) const;
|
||||
QList<QVariantMap> loadArray(const QString §ion);
|
||||
|
||||
// Atomically replace the named QSettings array.
|
||||
void saveArray(const QString §ion, const QList<QVariantMap> &items) const;
|
||||
void saveArray(const QString §ion, const QList<QVariantMap> &items);
|
||||
|
||||
private:
|
||||
QSettings &m_settings;
|
||||
|
||||
@@ -1,27 +1,17 @@
|
||||
#include "HistoryBookModel.h"
|
||||
#include "FormatReader.h"
|
||||
#include "IImageProvider.h"
|
||||
#include "formats/ImageProviderFactory.h"
|
||||
#include "formats/ReaderFactory.h"
|
||||
#include <QtConcurrent/QtConcurrent>
|
||||
#include <QFileInfo>
|
||||
#include <QUrl>
|
||||
|
||||
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<HistoryBookModel> 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<IImageProvider> provider(ImageProviderFactory::create(filePath));
|
||||
std::unique_ptr<IImageProvider> 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()
|
||||
{
|
||||
}
|
||||
@@ -6,7 +6,7 @@
|
||||
#include <QPointer>
|
||||
#include <QFuture>
|
||||
|
||||
#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<void> m_metadataFuture;
|
||||
ReaderFactory &m_factory;
|
||||
FormatRegistry &m_registry;
|
||||
};
|
||||
|
||||
#endif // HISTORYBOOKMODEL_H
|
||||
@@ -2,9 +2,9 @@
|
||||
#include "HistoryBookModel.h"
|
||||
#include <QDateTime>
|
||||
|
||||
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();
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
#include <QList>
|
||||
#include <QHash>
|
||||
|
||||
#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<HistoryBookModel*> m_books;
|
||||
QHash<int, QByteArray> m_roleNames;
|
||||
ReaderFactory &m_factory;
|
||||
FormatRegistry &m_registry;
|
||||
};
|
||||
|
||||
#endif // HISTORYMODEL_H
|
||||
@@ -1 +0,0 @@
|
||||
#include "IFileDialogService.h"
|
||||
@@ -1,5 +1,4 @@
|
||||
#ifndef IFILEDIAL0GSERVICE_H
|
||||
#define IFILEDIAL0GSERVICE_H
|
||||
#pragma once
|
||||
|
||||
#include <QObject>
|
||||
#include <QString>
|
||||
@@ -16,5 +15,3 @@ public:
|
||||
signals:
|
||||
void fileSelected(const QString &path);
|
||||
};
|
||||
|
||||
#endif // IFILEDIAL0GSERVICE_H
|
||||
@@ -1,5 +1,4 @@
|
||||
#ifndef IIMAGELLOADER_H
|
||||
#define IIMAGELLOADER_H
|
||||
#pragma once
|
||||
#include <QImage>
|
||||
#include <QUrl>
|
||||
#include <memory>
|
||||
@@ -9,4 +8,3 @@ public:
|
||||
virtual QImage load(const QUrl &url, int maxWidth) const = 0;
|
||||
virtual std::unique_ptr<IImageLoader> clone() const = 0;
|
||||
};
|
||||
#endif
|
||||
+50
-116
@@ -1,26 +1,20 @@
|
||||
#include "ReadingModel.h"
|
||||
#include "FormatReader.h"
|
||||
#include "IChunkMeasurer.h"
|
||||
#include "IImageLoader.h"
|
||||
#include "ChunkMeasurer.h"
|
||||
#include <QRegularExpression>
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <QtConcurrent>
|
||||
|
||||
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<int> &heights, const bool isNew)
|
||||
{
|
||||
if (m_measureFuture.isRunning())
|
||||
m_measureFuture.cancel();
|
||||
for (int i = 0; i < qMin(heights.size(), static_cast<int>(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<IImageLoader> 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<int> heights = measurer->measure(htmls, width);
|
||||
QMetaObject::invokeMethod(this, [this, heights, isNew] {
|
||||
for (int i = 0; i < qMin(heights.size(), static_cast<int>(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<IImageLoader> 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<QSize> 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("<img\\s[^>]*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("<img\\s[^>]*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("<div class=\"cover-image\" style=\"text-align: center; margin: 2em 0;\">")
|
||||
+ QStringLiteral("<img src=\"") + m_coverImageUrl
|
||||
+ QStringLiteral("\" style=\"max-width: 100%; max-height: 80vh;\" /></div>");
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,13 +2,13 @@
|
||||
#define READINGMODEL_H
|
||||
|
||||
#include <QAbstractListModel>
|
||||
#include <QFuture>
|
||||
#include <QPair>
|
||||
#include <QSize>
|
||||
#include <QString>
|
||||
#include <QVector>
|
||||
#include <memory>
|
||||
#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<int> &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<int> m_chapterStartIndices;
|
||||
QVector<QString> 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<QPair<int,int>> 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<IImageLoader> m_imageLoader;
|
||||
QFuture<void> m_measureFuture;
|
||||
MeasurementController m_measurer;
|
||||
};
|
||||
|
||||
#endif // READINGMODEL_H
|
||||
+18
-37
@@ -1,16 +1,17 @@
|
||||
#include "Book.h"
|
||||
#include <QtConcurrent>
|
||||
#include <QFileInfo>
|
||||
#include <QSet>
|
||||
|
||||
#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<QString> 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()
|
||||
|
||||
@@ -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<TocEntry> 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<TocEntry> 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<FormatReader> 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;
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
#include "AsyncImageResponse.h"
|
||||
|
||||
#include <QQuickTextureFactory>
|
||||
|
||||
AsyncImageResponse::AsyncImageResponse(std::function<QImage()> 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();
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
#pragma once
|
||||
|
||||
#include <functional>
|
||||
#include <QAtomicInt>
|
||||
#include <QImage>
|
||||
#include <QQuickImageResponse>
|
||||
#include <QRunnable>
|
||||
|
||||
// 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<QImage()> job);
|
||||
|
||||
QQuickTextureFactory *textureFactory() const override;
|
||||
void cancel() override;
|
||||
void run() override;
|
||||
|
||||
private:
|
||||
std::function<QImage()> m_job;
|
||||
QAtomicInt m_cancelled{0};
|
||||
QImage m_image;
|
||||
};
|
||||
@@ -0,0 +1,128 @@
|
||||
#include "EntryImageProvider.h"
|
||||
|
||||
#include <QImage>
|
||||
#include <QMutexLocker>
|
||||
#include <QThreadPool>
|
||||
#include <QUrl>
|
||||
|
||||
#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=<encoded-path>"
|
||||
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<IImageLoader> EntryImageProvider::clone() const
|
||||
{
|
||||
QString sourcePath;
|
||||
{
|
||||
QMutexLocker lock(&m_mutex);
|
||||
sourcePath = m_sourcePath;
|
||||
}
|
||||
auto c = std::make_unique<EntryImageProvider>(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;
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
#pragma once
|
||||
|
||||
#include "IByteSource.h"
|
||||
#include "backend/IImageLoader.h"
|
||||
#include "backend/IImageProvider.h"
|
||||
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <QMutex>
|
||||
#include <QString>
|
||||
|
||||
class EntryImageProvider : public IImageProvider, public IImageLoader {
|
||||
public:
|
||||
using SourceFactory = std::function<std::unique_ptr<IByteSource>()>;
|
||||
|
||||
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<IImageLoader> 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;
|
||||
};
|
||||
@@ -1,202 +0,0 @@
|
||||
#include "EpubImageProvider.h"
|
||||
|
||||
#include <QImage>
|
||||
#include <QMutexLocker>
|
||||
#include <QQuickTextureFactory>
|
||||
#include <QThreadPool>
|
||||
#include <QUrl>
|
||||
|
||||
#include <minizip/unzip.h>
|
||||
|
||||
#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=<percent-encoded-epub-path>" (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=<value> 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=<encoded>
|
||||
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<IImageLoader> EpubImageProvider::clone() const
|
||||
{
|
||||
QString epubPath;
|
||||
{
|
||||
QMutexLocker lock(&m_mutex);
|
||||
epubPath = m_epubPath;
|
||||
}
|
||||
auto c = std::make_unique<EpubImageProvider>();
|
||||
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;
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <QMutex>
|
||||
#include <QRunnable>
|
||||
#include <QString>
|
||||
|
||||
#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<IImageLoader> 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;
|
||||
};
|
||||
@@ -1,210 +0,0 @@
|
||||
#include "Fb2ImageProvider.h"
|
||||
#include "Fb2Reader.h"
|
||||
|
||||
#include <QFile>
|
||||
#include <QImage>
|
||||
#include <QMutexLocker>
|
||||
#include <QQuickTextureFactory>
|
||||
#include <QThreadPool>
|
||||
#include <QUrl>
|
||||
#include <QXmlStreamReader>
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 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=<encoded-path>" 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<IImageLoader> Fb2ImageProvider::clone() const
|
||||
{
|
||||
QString fb2Path;
|
||||
{
|
||||
QMutexLocker lock(&m_mutex);
|
||||
fb2Path = m_fb2Path;
|
||||
}
|
||||
auto c = std::make_unique<Fb2ImageProvider>();
|
||||
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;
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <QMutex>
|
||||
#include <QRunnable>
|
||||
#include <QString>
|
||||
|
||||
#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<IImageLoader> 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;
|
||||
};
|
||||
@@ -1,5 +1,7 @@
|
||||
#include "Fb2Reader.h"
|
||||
|
||||
#include "ImageUrl.h"
|
||||
|
||||
#include <QCryptographicHash>
|
||||
#include <QDomDocument>
|
||||
#include <QFileInfo>
|
||||
@@ -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()) {
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
#include "FormatRegistry.h"
|
||||
|
||||
#include "EntryImageProvider.h"
|
||||
#include "WebImageProvider.h"
|
||||
#include "backend/FormatReader.h"
|
||||
|
||||
#include <QFileInfo>
|
||||
#include <QQmlEngine>
|
||||
|
||||
// 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<IImageLoader> 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<IImageLoader> clone() const override
|
||||
{
|
||||
auto c = std::make_unique<CompositeImageLoader>();
|
||||
for (const auto &[host, loader] : m_loaders)
|
||||
c->add(host, loader->clone());
|
||||
return c;
|
||||
}
|
||||
|
||||
private:
|
||||
std::vector<std::pair<QString, std::unique_ptr<IImageLoader>>> m_loaders;
|
||||
};
|
||||
|
||||
FormatRegistry::FormatRegistry(QVector<FormatSpec> 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<FormatReader> 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<IImageLoader> 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<EntryImageProvider>(spec->makeSource, spec->scheme);
|
||||
loader->setFilePath(filePath);
|
||||
|
||||
if (!spec->loaderIncludesWeb)
|
||||
return loader;
|
||||
|
||||
auto composite = std::make_unique<CompositeImageLoader>();
|
||||
composite->add(spec->scheme, std::move(loader));
|
||||
composite->add(QStringLiteral("web"), std::make_unique<WebImageProvider>());
|
||||
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));
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
#pragma once
|
||||
|
||||
#include <QString>
|
||||
#include <QStringList>
|
||||
#include <QVector>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
|
||||
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<std::unique_ptr<FormatReader>()> makeReader;
|
||||
std::function<std::unique_ptr<IByteSource>()> makeSource; // required when scheme is set
|
||||
bool loaderIncludesWeb = false; // formats whose content may reference web images (epub)
|
||||
};
|
||||
|
||||
class FormatRegistry {
|
||||
public:
|
||||
explicit FormatRegistry(QVector<FormatSpec> specs);
|
||||
|
||||
std::unique_ptr<FormatReader> 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<IImageLoader> 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<FormatSpec> m_specs;
|
||||
};
|
||||
@@ -5,10 +5,10 @@
|
||||
#include <QStringList>
|
||||
|
||||
// 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;
|
||||
@@ -0,0 +1,15 @@
|
||||
#pragma once
|
||||
|
||||
#include <QSet>
|
||||
#include <QString>
|
||||
|
||||
// File extensions treated as standalone images (comic pages, folder comics).
|
||||
inline const QSet<QString> &imageFileExtensions()
|
||||
{
|
||||
static const QSet<QString> kExtensions = {
|
||||
QStringLiteral("jpg"), QStringLiteral("jpeg"),
|
||||
QStringLiteral("png"), QStringLiteral("gif"),
|
||||
QStringLiteral("webp")
|
||||
};
|
||||
return kExtensions;
|
||||
}
|
||||
@@ -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 <QFileInfo>
|
||||
|
||||
// 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<IImageLoader> 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<IImageLoader> clone() const override
|
||||
{
|
||||
auto c = std::make_unique<CompositeImageLoader>();
|
||||
for (const auto &[host, loader] : m_loaders)
|
||||
c->add(host, loader->clone());
|
||||
return c;
|
||||
}
|
||||
|
||||
private:
|
||||
std::vector<std::pair<QString, std::unique_ptr<IImageLoader>>> m_loaders;
|
||||
};
|
||||
|
||||
std::unique_ptr<IImageLoader> ImageLoaderFactory::create(const QString &filePath)
|
||||
{
|
||||
const QFileInfo fi(filePath);
|
||||
|
||||
if (fi.isDir()) {
|
||||
auto loader = std::make_unique<FolderImageProvider>();
|
||||
loader->setFilePath(filePath);
|
||||
return loader;
|
||||
}
|
||||
|
||||
const QString ext = fi.suffix().toLower();
|
||||
if (ext == QLatin1String("epub")) {
|
||||
auto composite = std::make_unique<CompositeImageLoader>();
|
||||
|
||||
auto epubLoader = std::make_unique<EpubImageProvider>();
|
||||
epubLoader->setFilePath(filePath);
|
||||
composite->add(QStringLiteral("epub"), std::move(epubLoader));
|
||||
|
||||
composite->add(QStringLiteral("web"), std::make_unique<WebImageProvider>());
|
||||
|
||||
return composite;
|
||||
}
|
||||
if (ext == QLatin1String("fb2")) {
|
||||
auto loader = std::make_unique<Fb2ImageProvider>();
|
||||
loader->setFilePath(filePath);
|
||||
return loader;
|
||||
}
|
||||
if (ext == QLatin1String("cbz")) {
|
||||
auto loader = std::make_unique<CbzImageProvider>();
|
||||
loader->setFilePath(filePath);
|
||||
return loader;
|
||||
}
|
||||
if (ext == QLatin1String("cbr")) {
|
||||
auto loader = std::make_unique<CbrImageProvider>();
|
||||
loader->setFilePath(filePath);
|
||||
return loader;
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
#pragma once
|
||||
#include <memory>
|
||||
#include <QString>
|
||||
|
||||
class IImageLoader;
|
||||
|
||||
class ImageLoaderFactory {
|
||||
public:
|
||||
// Returns a new loader for the given file format, or nullptr for formats without images.
|
||||
static std::unique_ptr<IImageLoader> create(const QString &filePath);
|
||||
};
|
||||
@@ -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 <QFileInfo>
|
||||
|
||||
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;
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
#pragma once
|
||||
#include <QString>
|
||||
|
||||
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);
|
||||
};
|
||||
@@ -0,0 +1,30 @@
|
||||
#pragma once
|
||||
|
||||
#include <QImage>
|
||||
#include <QSize>
|
||||
|
||||
// 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;
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
#include "ImageUrl.h"
|
||||
|
||||
#include <QLatin1Char>
|
||||
#include <QLatin1String>
|
||||
|
||||
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
|
||||
@@ -0,0 +1,30 @@
|
||||
#pragma once
|
||||
|
||||
#include <QString>
|
||||
#include <QUrl>
|
||||
|
||||
// Single authority for the image-provider URL grammar:
|
||||
// image://<scheme>/<entry>[?src=<percent-encoded-source-path>]
|
||||
// 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=<percent-encoded-source-path>" — 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
|
||||
@@ -1,31 +0,0 @@
|
||||
#include "ReaderFactory.h"
|
||||
#include "backend/FormatReader.h"
|
||||
|
||||
#include <QFileInfo>
|
||||
|
||||
ReaderFactory::ReaderFactory(QList<CreatorFn> creators)
|
||||
{
|
||||
for (const auto &creator : creators) {
|
||||
auto probe = creator();
|
||||
m_registry[probe->fileType()] = creator;
|
||||
}
|
||||
}
|
||||
|
||||
std::unique_ptr<FormatReader> ReaderFactory::create(const QString &filePath) const
|
||||
{
|
||||
const QFileInfo fi(filePath);
|
||||
const QString key = fi.isDir() ? QStringLiteral("<dir>") : 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;
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
#ifndef READERFACTORY_H
|
||||
#define READERFACTORY_H
|
||||
|
||||
#include <QMap>
|
||||
#include <QStringList>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
|
||||
class FormatReader;
|
||||
|
||||
class ReaderFactory {
|
||||
public:
|
||||
using CreatorFn = std::function<std::unique_ptr<FormatReader>()>;
|
||||
|
||||
// Constructs the factory by probing each creator via fileType() to build the registry.
|
||||
explicit ReaderFactory(QList<CreatorFn> creators);
|
||||
|
||||
std::unique_ptr<FormatReader> create(const QString &filePath) const;
|
||||
QStringList supportedExtensions() const;
|
||||
|
||||
private:
|
||||
QMap<QString, CreatorFn> m_registry; // extension -> creator
|
||||
};
|
||||
|
||||
#endif // READERFACTORY_H
|
||||
@@ -10,10 +10,12 @@
|
||||
#include <QNetworkAccessManager>
|
||||
#include <QNetworkReply>
|
||||
#include <QNetworkRequest>
|
||||
#include <QQuickTextureFactory>
|
||||
#include <QStandardPaths>
|
||||
#include <QThreadPool>
|
||||
|
||||
#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;
|
||||
}
|
||||
|
||||
@@ -1,31 +1,12 @@
|
||||
#pragma once
|
||||
|
||||
#include <QAtomicInt>
|
||||
#include <QMutex>
|
||||
#include <QRunnable>
|
||||
#include <QSize>
|
||||
#include <QString>
|
||||
|
||||
#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,
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
// Cbr shells are header-only (constructors inline in Cbr.h).
|
||||
@@ -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"
|
||||
@@ -1,11 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include "ComicImageProvider.h"
|
||||
#include "RarComicSource.h"
|
||||
|
||||
class CbrImageProvider : public ComicImageProvider {
|
||||
public:
|
||||
CbrImageProvider()
|
||||
: ComicImageProvider([] { return std::make_unique<RarComicSource>(); },
|
||||
QStringLiteral("cbr")) {}
|
||||
};
|
||||
@@ -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<RarComicSource>(); },
|
||||
: ComicReader([] { return std::make_unique<RarByteSource>(); },
|
||||
QStringLiteral("cbr"),
|
||||
QStringLiteral("cbr")) {}
|
||||
};
|
||||
@@ -1 +0,0 @@
|
||||
// Cbz shells are header-only (constructors inline in Cbz.h).
|
||||
@@ -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"
|
||||
@@ -1,11 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include "ComicImageProvider.h"
|
||||
#include "ZipComicSource.h"
|
||||
|
||||
class CbzImageProvider : public ComicImageProvider {
|
||||
public:
|
||||
CbzImageProvider()
|
||||
: ComicImageProvider([] { return std::make_unique<ZipComicSource>(); },
|
||||
QStringLiteral("cbz")) {}
|
||||
};
|
||||
@@ -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<ZipComicSource>(); },
|
||||
: ComicReader([] { return std::make_unique<ZipByteSource>(); },
|
||||
QStringLiteral("cbz"),
|
||||
QStringLiteral("cbz")) {}
|
||||
};
|
||||
@@ -1,202 +0,0 @@
|
||||
#include "ComicImageProvider.h"
|
||||
|
||||
#include <QImage>
|
||||
#include <QMutexLocker>
|
||||
#include <QQuickTextureFactory>
|
||||
#include <QThreadPool>
|
||||
#include <QUrl>
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 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=<encoded-path>"
|
||||
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<IImageLoader> ComicImageProvider::clone() const
|
||||
{
|
||||
QString sourcePath;
|
||||
{
|
||||
QMutexLocker lock(&m_mutex);
|
||||
sourcePath = m_sourcePath;
|
||||
}
|
||||
auto c = std::make_unique<ComicImageProvider>(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;
|
||||
}
|
||||
@@ -1,70 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include "IComicSource.h"
|
||||
|
||||
#include "backend/IImageLoader.h"
|
||||
#include "backend/IImageProvider.h"
|
||||
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <QAtomicInt>
|
||||
#include <QMutex>
|
||||
#include <QRunnable>
|
||||
#include <QString>
|
||||
|
||||
class ComicImageResponse : public QQuickImageResponse, public QRunnable {
|
||||
// NO Q_OBJECT — already inherited from QQuickImageResponse
|
||||
public:
|
||||
using SourceFactory = std::function<std::unique_ptr<IComicSource>()>;
|
||||
|
||||
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<std::unique_ptr<IComicSource>()>;
|
||||
|
||||
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<IImageLoader> 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;
|
||||
};
|
||||
@@ -3,9 +3,11 @@
|
||||
#include <QBuffer>
|
||||
#include <QFileInfo>
|
||||
#include <QImageReader>
|
||||
#include <QSet>
|
||||
#include <QXmlStreamReader>
|
||||
|
||||
#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<QString> 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("<p style=\"text-align:center;margin:0\">"
|
||||
"<img src=\"image://%1/%2\"/></p>")
|
||||
.arg(m_scheme, page.entry));
|
||||
"<img src=\"%1\"/></p>")
|
||||
.arg(ImageUrl::build(m_scheme, page.entry)));
|
||||
}
|
||||
return Chapter{0, m_title, chunks};
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#pragma once
|
||||
|
||||
#include "backend/FormatReader.h"
|
||||
#include "IComicSource.h"
|
||||
#include "backend/formats/IByteSource.h"
|
||||
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
@@ -13,7 +13,7 @@
|
||||
|
||||
class ComicReader : public FormatReader {
|
||||
public:
|
||||
using SourceFactory = std::function<std::unique_ptr<IComicSource>()>;
|
||||
using SourceFactory = std::function<std::unique_ptr<IByteSource>()>;
|
||||
|
||||
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;
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
// Folder shells are header-only (constructors inline in Folder.h).
|
||||
@@ -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"
|
||||
@@ -1,11 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include "ComicImageProvider.h"
|
||||
#include "DirComicSource.h"
|
||||
|
||||
class FolderImageProvider : public ComicImageProvider {
|
||||
public:
|
||||
FolderImageProvider()
|
||||
: ComicImageProvider([] { return std::make_unique<DirComicSource>(); },
|
||||
QStringLiteral("dir")) {}
|
||||
};
|
||||
@@ -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<DirComicSource>(); },
|
||||
QStringLiteral("<dir>"),
|
||||
: ComicReader([] { return std::make_unique<DirByteSource>(); },
|
||||
QStringLiteral("folder"),
|
||||
QStringLiteral("dir")) {}
|
||||
};
|
||||
+5
-5
@@ -1,11 +1,11 @@
|
||||
#include "DirComicSource.h"
|
||||
#include "DirByteSource.h"
|
||||
|
||||
#include <QCryptographicHash>
|
||||
#include <QDir>
|
||||
#include <QFile>
|
||||
#include <QFileInfo>
|
||||
|
||||
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;
|
||||
}
|
||||
+2
-2
@@ -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;
|
||||
@@ -0,0 +1,88 @@
|
||||
#include "Fb2ByteSource.h"
|
||||
|
||||
#include "backend/formats/Fb2Reader.h"
|
||||
|
||||
#include <QCryptographicHash>
|
||||
#include <QFile>
|
||||
#include <QFileInfo>
|
||||
#include <QXmlStreamReader>
|
||||
|
||||
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;
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
#pragma once
|
||||
|
||||
#include "backend/formats/IByteSource.h"
|
||||
|
||||
// Byte source over an FB2 document: entries are the ids of its base64
|
||||
// <binary> 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;
|
||||
};
|
||||
+12
-11
@@ -1,4 +1,4 @@
|
||||
#include "RarComicSource.h"
|
||||
#include "RarByteSource.h"
|
||||
|
||||
#include <QCryptographicHash>
|
||||
#include <QFile>
|
||||
@@ -6,7 +6,7 @@
|
||||
#include <archive.h>
|
||||
#include <archive_entry.h>
|
||||
|
||||
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;
|
||||
}
|
||||
+3
-3
@@ -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;
|
||||
};
|
||||
+12
-11
@@ -1,4 +1,4 @@
|
||||
#include "ZipComicSource.h"
|
||||
#include "ZipByteSource.h"
|
||||
|
||||
#include "backend/ZipUtils.h"
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
|
||||
#include <minizip/unzip.h>
|
||||
|
||||
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;
|
||||
}
|
||||
+3
-3
@@ -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;
|
||||
};
|
||||
@@ -0,0 +1,80 @@
|
||||
#include "MangaPagination.h"
|
||||
|
||||
void MangaPagination::clear()
|
||||
{
|
||||
m_pairs.clear();
|
||||
}
|
||||
|
||||
void MangaPagination::rebuild(const QVector<QSize> &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;
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
#pragma once
|
||||
|
||||
#include <QSize>
|
||||
#include <QVector>
|
||||
|
||||
// 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<QSize> &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<Pair> m_pairs;
|
||||
};
|
||||
@@ -0,0 +1,50 @@
|
||||
#include "MeasurementController.h"
|
||||
|
||||
#include "backend/ChunkMeasurer.h"
|
||||
|
||||
#include <QtConcurrent>
|
||||
|
||||
MeasurementController::MeasurementController(QObject *parent)
|
||||
: QObject(parent)
|
||||
{
|
||||
}
|
||||
|
||||
MeasurementController::~MeasurementController()
|
||||
{
|
||||
if (m_future.isRunning()) {
|
||||
m_future.cancel();
|
||||
m_future.waitForFinished();
|
||||
}
|
||||
}
|
||||
|
||||
void MeasurementController::setImageLoader(std::unique_ptr<IImageLoader> 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<IImageLoader> loaderClone = m_imageLoader ? m_imageLoader->clone() : nullptr;
|
||||
auto measurer = std::make_shared<ChunkMeasurer>(std::move(loaderClone), fontSize, lineSpacing);
|
||||
|
||||
m_future = QtConcurrent::run([this, htmls, measurer, contentWidth, isNew]() {
|
||||
QVector<int> heights = measurer->measure(htmls, contentWidth);
|
||||
QMetaObject::invokeMethod(this, [this, heights, isNew] {
|
||||
m_measuring = false;
|
||||
emit measuringChanged();
|
||||
emit heightsReady(heights, isNew);
|
||||
}, Qt::QueuedConnection);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
#pragma once
|
||||
|
||||
#include <QFuture>
|
||||
#include <QObject>
|
||||
#include <QStringList>
|
||||
#include <QVector>
|
||||
#include <memory>
|
||||
|
||||
#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<IImageLoader> 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<int> heights, bool isNew);
|
||||
|
||||
private:
|
||||
std::unique_ptr<IImageLoader> m_imageLoader;
|
||||
bool m_measuring = false;
|
||||
QFuture<void> m_future;
|
||||
};
|
||||
+36
-117
@@ -9,25 +9,25 @@
|
||||
#include <QSettings>
|
||||
#include <QSGRendererInterface>
|
||||
|
||||
#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<TxtReader>(); },
|
||||
[] { return std::make_unique<EpubReader>(); },
|
||||
[] { return std::make_unique<Fb2Reader>(); },
|
||||
[] { return std::make_unique<CbzReader>(); },
|
||||
[] { return std::make_unique<CbrReader>(); },
|
||||
[] { return std::make_unique<FolderReader>(); },
|
||||
// The format table: one row declares everything a format needs.
|
||||
FormatRegistry formatRegistry({
|
||||
{QStringLiteral("txt"), false, {},
|
||||
[] { return std::make_unique<TxtReader>(); }, nullptr},
|
||||
{QStringLiteral("epub"), false, QStringLiteral("epub"),
|
||||
[] { return std::make_unique<EpubReader>(); },
|
||||
[] { return std::make_unique<ZipByteSource>(); },
|
||||
/*loaderIncludesWeb=*/true},
|
||||
{QStringLiteral("fb2"), false, QStringLiteral("fb2"),
|
||||
[] { return std::make_unique<Fb2Reader>(); },
|
||||
[] { return std::make_unique<Fb2ByteSource>(); }},
|
||||
{QStringLiteral("cbz"), false, QStringLiteral("cbz"),
|
||||
[] { return std::make_unique<CbzReader>(); },
|
||||
[] { return std::make_unique<ZipByteSource>(); }},
|
||||
{QStringLiteral("cbr"), false, QStringLiteral("cbr"),
|
||||
[] { return std::make_unique<CbrReader>(); },
|
||||
[] { return std::make_unique<RarByteSource>(); }},
|
||||
{{}, /*matchesDirectory=*/true, QStringLiteral("dir"),
|
||||
[] { return std::make_unique<FolderReader>(); },
|
||||
[] { return std::make_unique<DirByteSource>(); }},
|
||||
});
|
||||
|
||||
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<QVariantMap> 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,
|
||||
|
||||
+5
-5
@@ -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
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+51
-42
@@ -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]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -30,7 +30,7 @@ Item {
|
||||
Loader {
|
||||
id: loader
|
||||
anchors.fill: parent
|
||||
sourceComponent: book.renderingMode === "manga" ? mangaViewComp : scrollViewComp
|
||||
sourceComponent: readingModel.isMangaMode ? mangaViewComp : scrollViewComp
|
||||
}
|
||||
|
||||
Component {
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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 }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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 }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,7 +10,27 @@
|
||||
|
||||
#include <minizip/zip.h>
|
||||
|
||||
#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<ZipByteSource>(); },
|
||||
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/<internal-path>?epub=<encoded-epub-path>
|
||||
QVERIFY2(url.startsWith(QStringLiteral("image://epub/OEBPS/cover.jpg?epub=")),
|
||||
// New format: image://epub/<internal-path>?src=<encoded-epub-path>
|
||||
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(
|
||||
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
|
||||
"<FictionBook><description/><body><p>text</p></body>"
|
||||
"<binary id=\"cover.png\" content-type=\"image/png\">")
|
||||
+ png.toBase64()
|
||||
+ QByteArrayLiteral("</binary></FictionBook>");
|
||||
|
||||
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("<?xml version=\"1.0\"?><FictionBook/>"));
|
||||
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"
|
||||
@@ -0,0 +1,141 @@
|
||||
#include <QtTest>
|
||||
#include <QTemporaryDir>
|
||||
#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<TxtReader>(); }, nullptr},
|
||||
{QStringLiteral("epub"), false, QStringLiteral("epub"),
|
||||
[] { return std::make_unique<EpubReader>(); },
|
||||
[] { return std::make_unique<ZipByteSource>(); },
|
||||
/*loaderIncludesWeb=*/true},
|
||||
{QStringLiteral("cbz"), false, QStringLiteral("cbz"),
|
||||
[] { return std::make_unique<CbzReader>(); },
|
||||
[] { return std::make_unique<ZipByteSource>(); }},
|
||||
{QStringLiteral("cbr"), false, QStringLiteral("cbr"),
|
||||
[] { return std::make_unique<CbrReader>(); },
|
||||
[] { return std::make_unique<RarByteSource>(); }},
|
||||
{{}, /*matchesDirectory=*/true, QStringLiteral("dir"),
|
||||
[] { return std::make_unique<FolderReader>(); },
|
||||
[] { return std::make_unique<DirByteSource>(); }},
|
||||
});
|
||||
}
|
||||
|
||||
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<IImageProvider> epub(registry.createImageProvider("book.epub"));
|
||||
QVERIFY(epub);
|
||||
QCOMPARE(epub->scheme(), QStringLiteral("epub"));
|
||||
|
||||
std::unique_ptr<IImageProvider> cbz(registry.createImageProvider("comic.cbz"));
|
||||
QVERIFY(cbz);
|
||||
QCOMPARE(cbz->scheme(), QStringLiteral("cbz"));
|
||||
|
||||
QTemporaryDir tmp;
|
||||
std::unique_ptr<IImageProvider> 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"
|
||||
@@ -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<TxtReader>(); },
|
||||
[] { return std::make_unique<EpubReader>(); },
|
||||
return FormatRegistry({
|
||||
{QStringLiteral("txt"), false, {},
|
||||
[] { return std::make_unique<TxtReader>(); }, nullptr},
|
||||
{QStringLiteral("epub"), false, QStringLiteral("epub"),
|
||||
[] { return std::make_unique<EpubReader>(); },
|
||||
[] { return std::make_unique<ZipByteSource>(); },
|
||||
/*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/<internal-path>?epub=<encoded-epub-path>
|
||||
QVERIFY2(url.startsWith(QStringLiteral("image://epub/OEBPS/Images/cover.png?epub=")),
|
||||
// Format: image://epub/<internal-path>?src=<encoded-epub-path>
|
||||
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();
|
||||
|
||||
@@ -1,94 +0,0 @@
|
||||
#include <QtTest>
|
||||
#include <QTemporaryDir>
|
||||
#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<TxtReader>(); },
|
||||
[] { return std::make_unique<EpubReader>(); },
|
||||
[] { return std::make_unique<CbzReader>(); },
|
||||
[] { return std::make_unique<CbrReader>(); },
|
||||
[] { return std::make_unique<FolderReader>(); },
|
||||
});
|
||||
}
|
||||
|
||||
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("<dir>"));
|
||||
}
|
||||
|
||||
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("<dir>")));
|
||||
for (const QString &e : exts)
|
||||
QVERIFY(!e.startsWith(QLatin1Char('<')));
|
||||
}
|
||||
};
|
||||
|
||||
QTEST_MAIN(ReaderFactoryTest)
|
||||
#include "ReaderFactoryTest.moc"
|
||||
@@ -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<TxtReader>(); },
|
||||
[] { return std::make_unique<EpubReader>(); },
|
||||
factory = new FormatRegistry({
|
||||
{QStringLiteral("txt"), false, {},
|
||||
[] { return std::make_unique<TxtReader>(); }, nullptr},
|
||||
{QStringLiteral("epub"), false, QStringLiteral("epub"),
|
||||
[] { return std::make_unique<EpubReader>(); }, nullptr},
|
||||
});
|
||||
book = new Book(*dialog, *store, *factory);
|
||||
}
|
||||
|
||||
@@ -106,7 +106,7 @@ private slots:
|
||||
void fileTypeAndRenderingMode()
|
||||
{
|
||||
FolderReader reader;
|
||||
QCOMPARE(reader.fileType(), QStringLiteral("<dir>"));
|
||||
QCOMPARE(reader.fileType(), QStringLiteral("folder"));
|
||||
QCOMPARE(static_cast<int>(reader.preferredRenderingMode()),
|
||||
static_cast<int>(FormatReader::RenderingMode::Manga));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
#include <QtTest/QtTest>
|
||||
#include <QUrl>
|
||||
|
||||
#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://<scheme>/"
|
||||
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"
|
||||
@@ -0,0 +1,124 @@
|
||||
#include <QtTest>
|
||||
|
||||
#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<QSize> 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"
|
||||
Reference in new issue
Block a user