old render cleanup part 2
This commit is contained in:
40 files changed
+317
-3631
No files matched your search
+10
-77
@@ -15,25 +15,15 @@ find_package(Qt6 REQUIRED COMPONENTS
|
|||||||
Quick
|
Quick
|
||||||
Widgets
|
Widgets
|
||||||
Concurrent
|
Concurrent
|
||||||
Network
|
|
||||||
Svg
|
Svg
|
||||||
QuickControls2
|
QuickControls2
|
||||||
Test
|
Test
|
||||||
Xml
|
Xml
|
||||||
)
|
)
|
||||||
find_package(Qt6 OPTIONAL_COMPONENTS Pdf DBus)
|
find_package(Qt6 OPTIONAL_COMPONENTS DBus)
|
||||||
|
|
||||||
# Third-party libraries
|
# Third-party libraries
|
||||||
find_package(PkgConfig REQUIRED)
|
find_package(PkgConfig REQUIRED)
|
||||||
pkg_check_modules(UCHARDET REQUIRED IMPORTED_TARGET uchardet)
|
|
||||||
|
|
||||||
# Homebrew's uchardet pkg-config sets includedir=…/include/uchardet (one level too deep),
|
|
||||||
# causing #include <uchardet/uchardet.h> to fail. Strip the trailing /uchardet if present.
|
|
||||||
get_target_property(_uchardet_inc PkgConfig::UCHARDET INTERFACE_INCLUDE_DIRECTORIES)
|
|
||||||
list(TRANSFORM _uchardet_inc REPLACE "/uchardet$" "")
|
|
||||||
set_target_properties(PkgConfig::UCHARDET PROPERTIES INTERFACE_INCLUDE_DIRECTORIES "${_uchardet_inc}")
|
|
||||||
|
|
||||||
find_package(Iconv REQUIRED)
|
|
||||||
pkg_check_modules(MINIZIP REQUIRED IMPORTED_TARGET minizip)
|
pkg_check_modules(MINIZIP REQUIRED IMPORTED_TARGET minizip)
|
||||||
pkg_check_modules(LIBARCHIVE REQUIRED IMPORTED_TARGET libarchive)
|
pkg_check_modules(LIBARCHIVE REQUIRED IMPORTED_TARGET libarchive)
|
||||||
# libarchive on Windows is built with CNG enabled (BCryptGenRandom for temp files).
|
# libarchive on Windows is built with CNG enabled (BCryptGenRandom for temp files).
|
||||||
@@ -72,12 +62,6 @@ set(SOURCES
|
|||||||
src/backend/IFileDialogService.h
|
src/backend/IFileDialogService.h
|
||||||
src/backend/NativeFileDialogService.h
|
src/backend/NativeFileDialogService.h
|
||||||
src/backend/NativeFileDialogService.cpp
|
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/Fb2Reader.h
|
|
||||||
src/backend/formats/Fb2Reader.cpp
|
|
||||||
src/backend/formats/IByteSource.h
|
src/backend/formats/IByteSource.h
|
||||||
src/backend/formats/EntryImageProvider.h
|
src/backend/formats/EntryImageProvider.h
|
||||||
src/backend/formats/EntryImageProvider.cpp
|
src/backend/formats/EntryImageProvider.cpp
|
||||||
@@ -87,15 +71,11 @@ set(SOURCES
|
|||||||
src/backend/formats/sources/RarByteSource.cpp
|
src/backend/formats/sources/RarByteSource.cpp
|
||||||
src/backend/formats/sources/DirByteSource.h
|
src/backend/formats/sources/DirByteSource.h
|
||||||
src/backend/formats/sources/DirByteSource.cpp
|
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.h
|
||||||
src/backend/formats/comic/ComicReader.cpp
|
src/backend/formats/comic/ComicReader.cpp
|
||||||
src/backend/formats/comic/CbzReader.h
|
src/backend/formats/comic/CbzReader.h
|
||||||
src/backend/formats/comic/CbrReader.h
|
src/backend/formats/comic/CbrReader.h
|
||||||
src/backend/formats/comic/FolderReader.h
|
src/backend/formats/comic/FolderReader.h
|
||||||
src/backend/formats/WebImageProvider.h
|
|
||||||
src/backend/formats/WebImageProvider.cpp
|
|
||||||
src/backend/formats/AsyncImageResponse.h
|
src/backend/formats/AsyncImageResponse.h
|
||||||
src/backend/formats/AsyncImageResponse.cpp
|
src/backend/formats/AsyncImageResponse.cpp
|
||||||
src/backend/formats/ImageUrl.h
|
src/backend/formats/ImageUrl.h
|
||||||
@@ -108,12 +88,10 @@ set(SOURCES
|
|||||||
src/backend/formats/FileIconProvider.cpp
|
src/backend/formats/FileIconProvider.cpp
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
if(WIN32)
|
if(WIN32)
|
||||||
list(APPEND SOURCES src/asteria.rc)
|
list(APPEND SOURCES src/asteria.rc)
|
||||||
endif()
|
endif()
|
||||||
|
|
||||||
|
|
||||||
# Executable
|
# Executable
|
||||||
qt_add_executable(asteria-qt ${SOURCES})
|
qt_add_executable(asteria-qt ${SOURCES})
|
||||||
|
|
||||||
@@ -145,16 +123,13 @@ target_link_libraries(asteria-qt PRIVATE
|
|||||||
Qt6::Quick
|
Qt6::Quick
|
||||||
Qt6::Widgets
|
Qt6::Widgets
|
||||||
Qt6::Concurrent
|
Qt6::Concurrent
|
||||||
Qt6::Network
|
|
||||||
Qt6::Svg
|
Qt6::Svg
|
||||||
Qt6::QuickControls2
|
Qt6::QuickControls2
|
||||||
|
PkgConfig::MINIZIP
|
||||||
|
PkgConfig::LIBARCHIVE
|
||||||
|
Qt6::Xml
|
||||||
)
|
)
|
||||||
|
|
||||||
if(Qt6Pdf_FOUND)
|
|
||||||
target_link_libraries(asteria-qt PRIVATE Qt6::Pdf)
|
|
||||||
target_compile_definitions(asteria-qt PRIVATE HAS_QT_PDF)
|
|
||||||
endif()
|
|
||||||
|
|
||||||
if(Qt6DBus_FOUND)
|
if(Qt6DBus_FOUND)
|
||||||
target_link_libraries(asteria-qt PRIVATE Qt6::DBus)
|
target_link_libraries(asteria-qt PRIVATE Qt6::DBus)
|
||||||
target_compile_definitions(asteria-qt PRIVATE HAS_QT_DBUS)
|
target_compile_definitions(asteria-qt PRIVATE HAS_QT_DBUS)
|
||||||
@@ -163,10 +138,6 @@ if(Qt6DBus_FOUND)
|
|||||||
src/backend/PortalFileDialogService.cpp)
|
src/backend/PortalFileDialogService.cpp)
|
||||||
endif()
|
endif()
|
||||||
|
|
||||||
target_link_libraries(asteria-qt PRIVATE PkgConfig::UCHARDET)
|
|
||||||
target_link_libraries(asteria-qt PRIVATE Iconv::Iconv)
|
|
||||||
target_link_libraries(asteria-qt PRIVATE PkgConfig::MINIZIP Qt6::Xml PkgConfig::LIBARCHIVE)
|
|
||||||
|
|
||||||
# Set resource aliases so src/qml/* maps to qrc:/Asteria/*
|
# Set resource aliases so src/qml/* maps to qrc:/Asteria/*
|
||||||
set_source_files_properties(src/qml/Main.qml PROPERTIES QT_RESOURCE_ALIAS Main.qml)
|
set_source_files_properties(src/qml/Main.qml PROPERTIES QT_RESOURCE_ALIAS Main.qml)
|
||||||
set_source_files_properties(src/qml/DarkTheme.qml PROPERTIES QT_RESOURCE_ALIAS DarkTheme.qml
|
set_source_files_properties(src/qml/DarkTheme.qml PROPERTIES QT_RESOURCE_ALIAS DarkTheme.qml
|
||||||
@@ -259,11 +230,6 @@ function(add_asteria_test TEST_NAME TEST_SOURCE)
|
|||||||
Qt6::Core
|
Qt6::Core
|
||||||
Qt6::Test
|
Qt6::Test
|
||||||
)
|
)
|
||||||
target_compile_definitions(${TEST_NAME} PRIVATE
|
|
||||||
FIXTURES_DIR="${CMAKE_CURRENT_SOURCE_DIR}/tests/fixtures"
|
|
||||||
)
|
|
||||||
target_link_libraries(${TEST_NAME} PRIVATE PkgConfig::UCHARDET)
|
|
||||||
target_link_libraries(${TEST_NAME} PRIVATE Iconv::Iconv)
|
|
||||||
add_test(NAME ${TEST_NAME} COMMAND ${TEST_NAME})
|
add_test(NAME ${TEST_NAME} COMMAND ${TEST_NAME})
|
||||||
endfunction()
|
endfunction()
|
||||||
|
|
||||||
@@ -273,18 +239,6 @@ add_asteria_test(ImageUrlTest tests/formats/ImageUrlTest.cpp
|
|||||||
add_asteria_test(MangaPaginationTest tests/reading/MangaPaginationTest.cpp
|
add_asteria_test(MangaPaginationTest tests/reading/MangaPaginationTest.cpp
|
||||||
src/backend/reading/MangaPagination.cpp)
|
src/backend/reading/MangaPagination.cpp)
|
||||||
|
|
||||||
add_asteria_test(TxtReaderTest tests/formats/TxtReaderTest.cpp
|
|
||||||
src/backend/formats/TxtReader.cpp)
|
|
||||||
|
|
||||||
add_asteria_test(EpubReaderTest tests/formats/EpubReaderTest.cpp
|
|
||||||
src/backend/formats/EpubReader.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/ImageUrl.cpp)
|
|
||||||
target_link_libraries(Fb2ReaderTest PRIVATE Qt6::Xml)
|
|
||||||
|
|
||||||
add_asteria_test(CbzReaderTest tests/formats/CbzReaderTest.cpp ${COMIC_READER_SOURCES})
|
add_asteria_test(CbzReaderTest tests/formats/CbzReaderTest.cpp ${COMIC_READER_SOURCES})
|
||||||
target_link_libraries(CbzReaderTest PRIVATE PkgConfig::MINIZIP PkgConfig::LIBARCHIVE Qt6::Xml Qt6::Gui)
|
target_link_libraries(CbzReaderTest PRIVATE PkgConfig::MINIZIP PkgConfig::LIBARCHIVE Qt6::Xml Qt6::Gui)
|
||||||
|
|
||||||
@@ -296,30 +250,21 @@ add_asteria_test(FormatRegistryTest tests/FormatRegistryTest.cpp
|
|||||||
src/backend/formats/FormatRegistry.cpp
|
src/backend/formats/FormatRegistry.cpp
|
||||||
src/backend/formats/AsyncImageResponse.cpp
|
src/backend/formats/AsyncImageResponse.cpp
|
||||||
src/backend/formats/EntryImageProvider.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})
|
${COMIC_READER_SOURCES})
|
||||||
target_link_libraries(FormatRegistryTest PRIVATE PkgConfig::MINIZIP PkgConfig::LIBARCHIVE Qt6::Xml Qt6::Gui Qt6::Quick Qt6::Network)
|
target_link_libraries(FormatRegistryTest PRIVATE PkgConfig::MINIZIP PkgConfig::LIBARCHIVE Qt6::Xml Qt6::Gui Qt6::Quick)
|
||||||
set_tests_properties(FormatRegistryTest PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen")
|
set_tests_properties(FormatRegistryTest PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen")
|
||||||
|
|
||||||
add_asteria_test(ReadingModelTest tests/ReadingModelTest.cpp
|
add_asteria_test(ReadingModelTest tests/ReadingModelTest.cpp
|
||||||
src/backend/ReadingModel.cpp
|
src/backend/ReadingModel.cpp
|
||||||
src/backend/reading/MangaPagination.cpp
|
src/backend/reading/MangaPagination.cpp
|
||||||
src/backend/formats/AsyncImageResponse.cpp
|
src/backend/formats/AsyncImageResponse.cpp
|
||||||
src/backend/formats/sources/Fb2ByteSource.cpp
|
|
||||||
src/backend/formats/WebImageProvider.cpp
|
|
||||||
src/backend/formats/FormatRegistry.cpp
|
src/backend/formats/FormatRegistry.cpp
|
||||||
src/backend/AppState.cpp
|
src/backend/AppState.cpp
|
||||||
src/backend/state/BookPositionStore.cpp
|
src/backend/state/BookPositionStore.cpp
|
||||||
src/backend/HistoryBookModel.cpp
|
src/backend/HistoryBookModel.cpp
|
||||||
src/backend/HistoryModel.cpp
|
src/backend/HistoryModel.cpp
|
||||||
src/backend/formats/TxtReader.cpp
|
|
||||||
src/backend/formats/EpubReader.cpp
|
|
||||||
src/backend/formats/Fb2Reader.cpp
|
|
||||||
${COMIC_SOURCES})
|
${COMIC_SOURCES})
|
||||||
target_link_libraries(ReadingModelTest PRIVATE Qt6::Gui Qt6::Concurrent Qt6::Quick Qt6::Network PkgConfig::MINIZIP PkgConfig::LIBARCHIVE Qt6::Xml)
|
target_link_libraries(ReadingModelTest PRIVATE Qt6::Gui Qt6::Concurrent Qt6::Quick PkgConfig::MINIZIP PkgConfig::LIBARCHIVE Qt6::Xml)
|
||||||
set_tests_properties(ReadingModelTest PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen")
|
set_tests_properties(ReadingModelTest PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen")
|
||||||
|
|
||||||
add_asteria_test(AppStateTest tests/AppStateTest.cpp
|
add_asteria_test(AppStateTest tests/AppStateTest.cpp
|
||||||
@@ -346,42 +291,30 @@ add_asteria_test(BookTest tests/book/BookTest.cpp
|
|||||||
src/backend/formats/FormatRegistry.cpp
|
src/backend/formats/FormatRegistry.cpp
|
||||||
src/backend/formats/AsyncImageResponse.cpp
|
src/backend/formats/AsyncImageResponse.cpp
|
||||||
src/backend/formats/EntryImageProvider.cpp
|
src/backend/formats/EntryImageProvider.cpp
|
||||||
src/backend/formats/WebImageProvider.cpp
|
|
||||||
src/backend/IFileDialogService.h
|
src/backend/IFileDialogService.h
|
||||||
src/backend/NativeFileDialogService.cpp
|
src/backend/NativeFileDialogService.cpp
|
||||||
src/backend/formats/TxtReader.cpp
|
|
||||||
src/backend/formats/EpubReader.cpp
|
|
||||||
src/backend/formats/Fb2Reader.cpp
|
|
||||||
${COMIC_READER_SOURCES})
|
${COMIC_READER_SOURCES})
|
||||||
target_link_libraries(BookTest PRIVATE Qt6::Concurrent Qt6::Widgets PkgConfig::MINIZIP PkgConfig::LIBARCHIVE Qt6::Xml Qt6::Gui Qt6::Quick Qt6::Network)
|
target_link_libraries(BookTest PRIVATE Qt6::Concurrent Qt6::Widgets PkgConfig::MINIZIP PkgConfig::LIBARCHIVE Qt6::Xml Qt6::Gui Qt6::Quick)
|
||||||
set_tests_properties(BookTest PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen")
|
set_tests_properties(BookTest PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen")
|
||||||
|
|
||||||
add_asteria_test(EntryImageProviderTest tests/EntryImageProviderTest.cpp
|
add_asteria_test(EntryImageProviderTest tests/EntryImageProviderTest.cpp
|
||||||
src/backend/formats/AsyncImageResponse.cpp
|
src/backend/formats/AsyncImageResponse.cpp
|
||||||
src/backend/formats/EntryImageProvider.cpp
|
src/backend/formats/EntryImageProvider.cpp
|
||||||
src/backend/formats/ImageUrl.cpp
|
src/backend/formats/ImageUrl.cpp
|
||||||
src/backend/formats/sources/ZipByteSource.cpp
|
src/backend/formats/sources/ZipByteSource.cpp)
|
||||||
src/backend/formats/sources/Fb2ByteSource.cpp
|
target_link_libraries(EntryImageProviderTest PRIVATE PkgConfig::MINIZIP Qt6::Quick Qt6::Gui)
|
||||||
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")
|
set_tests_properties(EntryImageProviderTest PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen")
|
||||||
|
|
||||||
add_asteria_test(HistoryBookModelTest tests/HistoryBookModelTest.cpp
|
add_asteria_test(HistoryBookModelTest tests/HistoryBookModelTest.cpp
|
||||||
src/backend/HistoryBookModel.cpp
|
src/backend/HistoryBookModel.cpp
|
||||||
src/backend/formats/AsyncImageResponse.cpp
|
src/backend/formats/AsyncImageResponse.cpp
|
||||||
src/backend/formats/sources/Fb2ByteSource.cpp
|
|
||||||
src/backend/formats/FormatRegistry.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})
|
${COMIC_SOURCES})
|
||||||
target_link_libraries(HistoryBookModelTest PRIVATE
|
target_link_libraries(HistoryBookModelTest PRIVATE
|
||||||
Qt6::Concurrent Qt6::Quick Qt6::Gui Qt6::Xml Qt6::Network PkgConfig::MINIZIP PkgConfig::LIBARCHIVE)
|
Qt6::Concurrent Qt6::Quick Qt6::Gui Qt6::Xml PkgConfig::MINIZIP PkgConfig::LIBARCHIVE)
|
||||||
set_tests_properties(HistoryBookModelTest PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen")
|
set_tests_properties(HistoryBookModelTest PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen")
|
||||||
|
|
||||||
add_asteria_test(FileIconProviderTest tests/FileIconProviderTest.cpp
|
add_asteria_test(FileIconProviderTest tests/FileIconProviderTest.cpp
|
||||||
src/backend/formats/FileIconProvider.cpp)
|
src/backend/formats/FileIconProvider.cpp)
|
||||||
target_link_libraries(FileIconProviderTest PRIVATE Qt6::Quick Qt6::Gui Qt6::Widgets)
|
target_link_libraries(FileIconProviderTest PRIVATE Qt6::Quick Qt6::Gui Qt6::Widgets)
|
||||||
set_tests_properties(FileIconProviderTest PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen")
|
set_tests_properties(FileIconProviderTest PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen")
|
||||||
|
|
||||||
@@ -2,35 +2,22 @@
|
|||||||
#define FORMATREADER_H
|
#define FORMATREADER_H
|
||||||
|
|
||||||
#include <QByteArray>
|
#include <QByteArray>
|
||||||
#include <QString>
|
|
||||||
#include <QList>
|
|
||||||
#include <QSize>
|
#include <QSize>
|
||||||
|
#include <QString>
|
||||||
#include <QVector>
|
#include <QVector>
|
||||||
|
|
||||||
struct TocEntry {
|
struct PageInfo {
|
||||||
QString title;
|
QString imageUrl;
|
||||||
int chapterIndex;
|
QSize naturalSize;
|
||||||
int depth; // 0 = top level
|
|
||||||
};
|
|
||||||
|
|
||||||
struct Chapter {
|
|
||||||
int index;
|
|
||||||
QString title;
|
|
||||||
QStringList contentChunks;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
class FormatReader {
|
class FormatReader {
|
||||||
public:
|
public:
|
||||||
enum class RenderingMode { Scroll, Manga };
|
|
||||||
|
|
||||||
virtual ~FormatReader() = default;
|
virtual ~FormatReader() = default;
|
||||||
|
|
||||||
virtual bool open(const QString &filePath) = 0;
|
virtual bool open(const QString &filePath) = 0;
|
||||||
virtual bool loadMetadata(const QString &filePath) = 0;
|
virtual bool loadMetadata(const QString &filePath) = 0;
|
||||||
virtual QString lastError() = 0;
|
virtual QString lastError() = 0;
|
||||||
virtual int chapterCount() = 0;
|
|
||||||
virtual Chapter loadChapter(int index) = 0;
|
|
||||||
virtual QList<TocEntry> tableOfContents() = 0;
|
|
||||||
virtual QString filePath() = 0;
|
virtual QString filePath() = 0;
|
||||||
virtual QString title() = 0;
|
virtual QString title() = 0;
|
||||||
virtual QString author() = 0;
|
virtual QString author() = 0;
|
||||||
@@ -38,15 +25,10 @@ public:
|
|||||||
// MD5 of file contents, computed once during open(). Used as a stable key for
|
// MD5 of file contents, computed once during open(). Used as a stable key for
|
||||||
// per-book state (bookmarks, etc.) that survives file renames.
|
// per-book state (bookmarks, etc.) that survives file renames.
|
||||||
virtual QByteArray contentHash() = 0;
|
virtual QByteArray contentHash() = 0;
|
||||||
// Returns the lowercase file extension this reader handles (e.g. "txt", "epub").
|
// Returns the lowercase file extension this reader handles (e.g. "cbz", "cbr").
|
||||||
virtual QString fileType() const = 0;
|
virtual QString fileType() const = 0;
|
||||||
|
|
||||||
// Rendering mode this format prefers. Defaults to Scroll; image-only formats override to Manga.
|
virtual QVector<PageInfo> pages() const = 0;
|
||||||
virtual RenderingMode preferredRenderingMode() const { return RenderingMode::Scroll; }
|
|
||||||
|
|
||||||
// Natural pixel sizes for each chunk in a chapter, parallel to loadChapter().contentChunks.
|
|
||||||
// Empty by default; image-based readers override to provide aspect ratios for page pairing.
|
|
||||||
virtual QVector<QSize> chapterPageSizes(int chapterIndex) const { Q_UNUSED(chapterIndex); return {}; }
|
|
||||||
};
|
};
|
||||||
|
|
||||||
#endif // FORMATREADER_H
|
#endif // FORMATREADER_H
|
||||||
+15
-112
@@ -1,6 +1,4 @@
|
|||||||
#include "ReadingModel.h"
|
#include "ReadingModel.h"
|
||||||
#include "FormatReader.h"
|
|
||||||
#include <QRegularExpression>
|
|
||||||
#include <algorithm>
|
#include <algorithm>
|
||||||
|
|
||||||
ReadingModel::ReadingModel(BookPositionStore &positions, QObject *parent)
|
ReadingModel::ReadingModel(BookPositionStore &positions, QObject *parent)
|
||||||
@@ -11,18 +9,7 @@ ReadingModel::ReadingModel(BookPositionStore &positions, QObject *parent)
|
|||||||
|
|
||||||
ReadingModel::~ReadingModel() = default;
|
ReadingModel::~ReadingModel() = default;
|
||||||
|
|
||||||
QString ReadingModel::chapterTitle() const
|
|
||||||
{
|
|
||||||
if (m_currentChapter < 0 || m_currentChapter >= m_chapterTitles.size())
|
|
||||||
return {};
|
|
||||||
return m_chapterTitles.at(m_currentChapter);
|
|
||||||
}
|
|
||||||
|
|
||||||
int ReadingModel::currentChapter() const { return m_currentChapter; }
|
|
||||||
int ReadingModel::totalChapters() const { return m_totalChapters; }
|
|
||||||
bool ReadingModel::hasChapters() const { return m_totalChapters > 1; }
|
|
||||||
int ReadingModel::totalPagePairs() const { return m_pagination.count(); }
|
int ReadingModel::totalPagePairs() const { return m_pagination.count(); }
|
||||||
bool ReadingModel::isMangaMode() const { return m_isMangaMode; }
|
|
||||||
bool ReadingModel::pageShift() const { return m_pageShift; }
|
bool ReadingModel::pageShift() const { return m_pageShift; }
|
||||||
bool ReadingModel::mangaRTL() const { return m_mangaRTL; }
|
bool ReadingModel::mangaRTL() const { return m_mangaRTL; }
|
||||||
|
|
||||||
@@ -38,41 +25,35 @@ void ReadingModel::setScrollInfo(const int topChunkIndex, const qreal proportion
|
|||||||
{
|
{
|
||||||
m_yOffset = proportion;
|
m_yOffset = proportion;
|
||||||
|
|
||||||
// Derive current chapter
|
|
||||||
const auto it = std::upper_bound(m_chapterStartIndices.begin(), m_chapterStartIndices.end(), topChunkIndex);
|
|
||||||
if (const int chapter = std::max(0, static_cast<int>(std::distance(m_chapterStartIndices.begin(), it)) - 1); chapter != m_currentChapter) {
|
|
||||||
m_currentChapter = chapter;
|
|
||||||
emit chapterChanged();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (m_isMangaMode) {
|
|
||||||
const int page = pairIndexForChunk(topChunkIndex) + 1;
|
const int page = pairIndexForChunk(topChunkIndex) + 1;
|
||||||
if (m_currentPage != page) {
|
if (m_currentPage != page) {
|
||||||
m_currentPage = page;
|
m_currentPage = page;
|
||||||
emit currentPageChanged();
|
emit currentPageChanged();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
void ReadingModel::rebuildPagePairs()
|
void ReadingModel::rebuildPagePairs()
|
||||||
{
|
{
|
||||||
const int oldPairs = m_pagination.count();
|
const int oldPairs = m_pagination.count();
|
||||||
|
|
||||||
if (!m_isMangaMode || m_chunks.isEmpty()) {
|
if (m_pages.isEmpty()) {
|
||||||
m_pagination.clear();
|
m_pagination.clear();
|
||||||
if (m_pagination.count() != oldPairs) emit totalPagePairsChanged();
|
if (m_pagination.count() != oldPairs) emit totalPagePairsChanged();
|
||||||
|
if (m_totalPages != 0) {
|
||||||
|
m_totalPages = 0;
|
||||||
|
emit totalPagesChanged();
|
||||||
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
QVector<QSize> sizes;
|
QVector<QSize> sizes;
|
||||||
sizes.reserve(m_chunks.size());
|
sizes.reserve(m_pages.size());
|
||||||
for (const auto &c : m_chunks)
|
for (const auto &p : m_pages)
|
||||||
sizes.append(c.naturalSize);
|
sizes.append(p.naturalSize);
|
||||||
m_pagination.rebuild(sizes, m_mangaLandscape, m_pageShift);
|
m_pagination.rebuild(sizes, m_mangaLandscape, m_pageShift);
|
||||||
|
|
||||||
if (m_pagination.count() != oldPairs) emit totalPagePairsChanged();
|
if (m_pagination.count() != oldPairs) emit totalPagePairsChanged();
|
||||||
|
|
||||||
// Sync totalPages/currentPage to pair count in manga mode.
|
|
||||||
if (const int pairs = m_pagination.count(); m_totalPages != pairs) {
|
if (const int pairs = m_pagination.count(); m_totalPages != pairs) {
|
||||||
m_totalPages = pairs;
|
m_totalPages = pairs;
|
||||||
emit totalPagesChanged();
|
emit totalPagesChanged();
|
||||||
@@ -101,41 +82,36 @@ int ReadingModel::pairIndexForChunk(int chunkIndex) const
|
|||||||
|
|
||||||
QString ReadingModel::imageUrlForChunk(int chunkIndex) const
|
QString ReadingModel::imageUrlForChunk(int chunkIndex) const
|
||||||
{
|
{
|
||||||
if (chunkIndex < 0 || chunkIndex >= m_chunks.size()) return {};
|
if (chunkIndex < 0 || chunkIndex >= m_pages.size()) return {};
|
||||||
return m_chunks.at(chunkIndex).imageUrl;
|
return m_pages.at(chunkIndex).imageUrl;
|
||||||
}
|
}
|
||||||
|
|
||||||
void ReadingModel::setMangaLandscape(bool landscape)
|
void ReadingModel::setMangaLandscape(bool landscape)
|
||||||
{
|
{
|
||||||
if (m_mangaLandscape == landscape) return;
|
if (m_mangaLandscape == landscape) return;
|
||||||
m_mangaLandscape = landscape;
|
m_mangaLandscape = landscape;
|
||||||
if (m_isMangaMode) rebuildPagePairs();
|
rebuildPagePairs();
|
||||||
}
|
}
|
||||||
|
|
||||||
void ReadingModel::setPageShift(bool shift, int currentPairIndex)
|
void ReadingModel::setPageShift(bool shift, int currentPairIndex)
|
||||||
{
|
{
|
||||||
if (m_pageShift == shift) return;
|
if (m_pageShift == shift) return;
|
||||||
|
|
||||||
// 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);
|
const int currentChunk = m_pagination.anchorChunkForShiftToggle(currentPairIndex, shift);
|
||||||
|
|
||||||
m_pageShift = shift;
|
m_pageShift = shift;
|
||||||
rebuildPagePairs();
|
rebuildPagePairs();
|
||||||
|
|
||||||
// Re-locate the pair that contains the chunk we were on.
|
|
||||||
const int newPair = pairIndexForChunk(currentChunk);
|
const int newPair = pairIndexForChunk(currentChunk);
|
||||||
if (m_currentPage != newPair + 1) {
|
if (m_currentPage != newPair + 1) {
|
||||||
m_currentPage = newPair + 1;
|
m_currentPage = newPair + 1;
|
||||||
emit currentPageChanged();
|
emit currentPageChanged();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Persist immediately.
|
|
||||||
if (m_reader)
|
if (m_reader)
|
||||||
m_positions.save(m_reader->contentHash(), currentChunk, m_mangaRTL, m_pageShift);
|
m_positions.save(m_reader->contentHash(), currentChunk, m_mangaRTL, m_pageShift);
|
||||||
|
|
||||||
emit pageShiftChanged();
|
emit pageShiftChanged();
|
||||||
// Tell MangaPageView the exact pair to jump to so it re-evaluates its display binding.
|
|
||||||
emit pagePairsRebuilt(newPair);
|
emit pagePairsRebuilt(newPair);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -150,87 +126,35 @@ void ReadingModel::setMangaRTL(bool rtl)
|
|||||||
emit mangaRTLChanged();
|
emit mangaRTLChanged();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Extract src="..." from a chunk's img tag, done once at load time.
|
void ReadingModel::loadPages()
|
||||||
static QString extractImageUrl(const QString &html)
|
|
||||||
{
|
{
|
||||||
static const QRegularExpression re(QStringLiteral("<img\\s[^>]*src=\"([^\"]+)\""));
|
m_pages.clear();
|
||||||
const auto match = re.match(html);
|
|
||||||
return match.hasMatch() ? match.captured(1) : QString();
|
|
||||||
}
|
|
||||||
|
|
||||||
void ReadingModel::loadAllChapters()
|
|
||||||
{
|
|
||||||
m_chunks.clear();
|
|
||||||
m_chapterStartIndices.clear();
|
|
||||||
m_chapterTitles.clear();
|
|
||||||
m_currentChapter = 0;
|
|
||||||
|
|
||||||
if (m_currentPage != 0) { m_currentPage = 0; emit currentPageChanged(); }
|
if (m_currentPage != 0) { m_currentPage = 0; emit currentPageChanged(); }
|
||||||
if (m_totalPages != 0) { m_totalPages = 0; emit totalPagesChanged(); }
|
if (m_totalPages != 0) { m_totalPages = 0; emit totalPagesChanged(); }
|
||||||
|
|
||||||
if (m_reader) {
|
if (m_reader) {
|
||||||
m_chapterStartIndices.append(0);
|
m_pages = m_reader->pages();
|
||||||
for (int i = 0; i < m_totalChapters; ++i) {
|
|
||||||
auto chapter = m_reader->loadChapter(i);
|
|
||||||
const QVector<QSize> sizes = m_reader->chapterPageSizes(i);
|
|
||||||
if (i > 0)
|
|
||||||
m_chapterStartIndices.append(m_chunks.size());
|
|
||||||
m_chapterTitles.append(chapter.title);
|
|
||||||
int j = 0;
|
|
||||||
for (const auto &html : chapter.contentChunks) {
|
|
||||||
const QSize sz = (j < sizes.size()) ? sizes[j] : QSize();
|
|
||||||
m_chunks.push_back({i, sz, extractImageUrl(html)});
|
|
||||||
++j;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (m_isMangaMode) {
|
|
||||||
rebuildPagePairs();
|
rebuildPagePairs();
|
||||||
} else {
|
|
||||||
if (m_totalPages != m_chunks.size()) {
|
|
||||||
m_totalPages = m_chunks.size();
|
|
||||||
emit totalPagesChanged();
|
|
||||||
}
|
|
||||||
if (const int page = m_chunks.isEmpty() ? 0 : 1; m_currentPage != page) {
|
|
||||||
m_currentPage = page;
|
|
||||||
emit currentPageChanged();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void ReadingModel::setReader(FormatReader *reader)
|
void ReadingModel::setReader(FormatReader *reader)
|
||||||
{
|
{
|
||||||
m_reader = reader;
|
m_reader = reader;
|
||||||
m_currentChapter = 0;
|
|
||||||
m_totalChapters = reader ? reader->chapterCount() : 0;
|
|
||||||
|
|
||||||
const bool wasManga = m_isMangaMode;
|
|
||||||
m_isMangaMode = reader && reader->preferredRenderingMode() == FormatReader::RenderingMode::Manga;
|
|
||||||
if (m_isMangaMode != wasManga)
|
|
||||||
emit isMangaModeChanged();
|
|
||||||
|
|
||||||
// Load per-book pageShift and mangaRTL before loadAllChapters so rebuildPagePairs uses the saved values.
|
|
||||||
int restoreChunk = 0;
|
int restoreChunk = 0;
|
||||||
if (reader) {
|
if (reader) {
|
||||||
const auto pos = m_positions.load(reader->contentHash());
|
const auto pos = m_positions.load(reader->contentHash());
|
||||||
restoreChunk = pos.chunkIndex;
|
restoreChunk = pos.chunkIndex;
|
||||||
if (m_isMangaMode) {
|
|
||||||
m_pageShift = pos.pageShift;
|
m_pageShift = pos.pageShift;
|
||||||
m_mangaRTL = pos.mangaRTL;
|
m_mangaRTL = pos.mangaRTL;
|
||||||
} else {
|
} else {
|
||||||
m_pageShift = true;
|
m_pageShift = true;
|
||||||
m_mangaRTL = true;
|
m_mangaRTL = true;
|
||||||
}
|
}
|
||||||
} else {
|
|
||||||
m_pageShift = true;
|
|
||||||
m_mangaRTL = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
loadAllChapters();
|
loadPages();
|
||||||
|
|
||||||
emit totalChaptersChanged();
|
|
||||||
emit chapterChanged();
|
|
||||||
|
|
||||||
if (m_reader) {
|
if (m_reader) {
|
||||||
QMetaObject::invokeMethod(this, [this, restoreChunk] {
|
QMetaObject::invokeMethod(this, [this, restoreChunk] {
|
||||||
@@ -238,24 +162,3 @@ void ReadingModel::setReader(FormatReader *reader)
|
|||||||
}, Qt::QueuedConnection);
|
}, Qt::QueuedConnection);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void ReadingModel::nextChapter()
|
|
||||||
{
|
|
||||||
if (!m_reader || m_currentChapter >= m_totalChapters - 1)
|
|
||||||
return;
|
|
||||||
emit scrollToChunkRequested(m_chapterStartIndices.at(m_currentChapter + 1));
|
|
||||||
}
|
|
||||||
|
|
||||||
void ReadingModel::previousChapter()
|
|
||||||
{
|
|
||||||
if (!m_reader || m_currentChapter <= 0)
|
|
||||||
return;
|
|
||||||
emit scrollToChunkRequested(m_chapterStartIndices.at(m_currentChapter - 1));
|
|
||||||
}
|
|
||||||
|
|
||||||
void ReadingModel::goToChapter(int index)
|
|
||||||
{
|
|
||||||
if (!m_reader || index < 0 || index >= m_totalChapters)
|
|
||||||
return;
|
|
||||||
emit scrollToChunkRequested(m_chapterStartIndices.at(index));
|
|
||||||
}
|
|
||||||
@@ -6,28 +6,16 @@
|
|||||||
#include <QString>
|
#include <QString>
|
||||||
#include <QVariantList>
|
#include <QVariantList>
|
||||||
#include <QVector>
|
#include <QVector>
|
||||||
|
#include "backend/FormatReader.h"
|
||||||
#include "reading/MangaPagination.h"
|
#include "reading/MangaPagination.h"
|
||||||
#include "state/BookPositionStore.h"
|
#include "state/BookPositionStore.h"
|
||||||
|
|
||||||
class FormatReader;
|
|
||||||
|
|
||||||
struct ContentChunk {
|
|
||||||
int chapterIndex = 0;
|
|
||||||
QSize naturalSize;
|
|
||||||
QString imageUrl;
|
|
||||||
};
|
|
||||||
|
|
||||||
class ReadingModel : public QObject {
|
class ReadingModel : public QObject {
|
||||||
Q_OBJECT
|
Q_OBJECT
|
||||||
Q_PROPERTY(QString chapterTitle READ chapterTitle NOTIFY chapterChanged)
|
|
||||||
Q_PROPERTY(int currentChapter READ currentChapter NOTIFY chapterChanged)
|
|
||||||
Q_PROPERTY(int totalChapters READ totalChapters NOTIFY totalChaptersChanged)
|
|
||||||
Q_PROPERTY(double progress READ progress NOTIFY currentPageChanged)
|
Q_PROPERTY(double progress READ progress NOTIFY currentPageChanged)
|
||||||
Q_PROPERTY(int currentPage READ currentPage NOTIFY currentPageChanged)
|
Q_PROPERTY(int currentPage READ currentPage NOTIFY currentPageChanged)
|
||||||
Q_PROPERTY(int totalPages READ totalPages NOTIFY totalPagesChanged)
|
Q_PROPERTY(int totalPages READ totalPages NOTIFY totalPagesChanged)
|
||||||
Q_PROPERTY(bool hasChapters READ hasChapters NOTIFY totalChaptersChanged)
|
|
||||||
Q_PROPERTY(int totalPagePairs READ totalPagePairs NOTIFY totalPagePairsChanged)
|
Q_PROPERTY(int totalPagePairs READ totalPagePairs NOTIFY totalPagePairsChanged)
|
||||||
Q_PROPERTY(bool isMangaMode READ isMangaMode NOTIFY isMangaModeChanged)
|
|
||||||
Q_PROPERTY(bool pageShift READ pageShift NOTIFY pageShiftChanged)
|
Q_PROPERTY(bool pageShift READ pageShift NOTIFY pageShiftChanged)
|
||||||
Q_PROPERTY(bool mangaRTL READ mangaRTL NOTIFY mangaRTLChanged)
|
Q_PROPERTY(bool mangaRTL READ mangaRTL NOTIFY mangaRTLChanged)
|
||||||
|
|
||||||
@@ -35,15 +23,10 @@ public:
|
|||||||
explicit ReadingModel(BookPositionStore &positions, QObject *parent = nullptr);
|
explicit ReadingModel(BookPositionStore &positions, QObject *parent = nullptr);
|
||||||
~ReadingModel() override;
|
~ReadingModel() override;
|
||||||
|
|
||||||
QString chapterTitle() const;
|
|
||||||
int currentChapter() const;
|
|
||||||
int totalChapters() const;
|
|
||||||
double progress() const;
|
double progress() const;
|
||||||
int currentPage() const;
|
int currentPage() const;
|
||||||
int totalPages() const;
|
int totalPages() const;
|
||||||
bool hasChapters() const;
|
|
||||||
int totalPagePairs() const;
|
int totalPagePairs() const;
|
||||||
bool isMangaMode() const;
|
|
||||||
bool pageShift() const;
|
bool pageShift() const;
|
||||||
bool mangaRTL() const;
|
bool mangaRTL() const;
|
||||||
|
|
||||||
@@ -52,10 +35,6 @@ public:
|
|||||||
// Called from QML on every page navigation
|
// Called from QML on every page navigation
|
||||||
Q_INVOKABLE void setScrollInfo(int topChunkIndex, qreal proportion);
|
Q_INVOKABLE void setScrollInfo(int topChunkIndex, qreal proportion);
|
||||||
|
|
||||||
Q_INVOKABLE void nextChapter();
|
|
||||||
Q_INVOKABLE void previousChapter();
|
|
||||||
Q_INVOKABLE void goToChapter(int index);
|
|
||||||
|
|
||||||
// Manga page-pair API
|
// Manga page-pair API
|
||||||
Q_INVOKABLE QVariantList pagePair(int pairIndex) const;
|
Q_INVOKABLE QVariantList pagePair(int pairIndex) const;
|
||||||
Q_INVOKABLE int pairIndexForChunk(int chunkIndex) const;
|
Q_INVOKABLE int pairIndexForChunk(int chunkIndex) const;
|
||||||
@@ -70,38 +49,28 @@ public:
|
|||||||
Q_INVOKABLE void setMangaRTL(bool rtl);
|
Q_INVOKABLE void setMangaRTL(bool rtl);
|
||||||
|
|
||||||
signals:
|
signals:
|
||||||
void chapterChanged();
|
|
||||||
void totalChaptersChanged();
|
|
||||||
void currentPageChanged();
|
void currentPageChanged();
|
||||||
void totalPagesChanged();
|
void totalPagesChanged();
|
||||||
void totalPagePairsChanged();
|
void totalPagePairsChanged();
|
||||||
void isMangaModeChanged();
|
|
||||||
void pageShiftChanged();
|
void pageShiftChanged();
|
||||||
void mangaRTLChanged();
|
void mangaRTLChanged();
|
||||||
// Fired after setPageShift rebuilds pairs; carries the new pair index to display.
|
// Fired after setPageShift rebuilds pairs; carries the new pair index to display.
|
||||||
void pagePairsRebuilt(int newPairIndex);
|
void pagePairsRebuilt(int newPairIndex);
|
||||||
void scrollToChunkRequested(int chunkIndex);
|
|
||||||
|
|
||||||
void restoreReady(int chunkIndex);
|
void restoreReady(int chunkIndex);
|
||||||
|
|
||||||
private:
|
private:
|
||||||
void loadAllChapters();
|
void loadPages();
|
||||||
void rebuildPagePairs();
|
void rebuildPagePairs();
|
||||||
|
|
||||||
FormatReader *m_reader = nullptr;
|
FormatReader *m_reader = nullptr;
|
||||||
int m_currentChapter = 0;
|
|
||||||
int m_totalChapters = 0;
|
|
||||||
int m_currentPage = 0;
|
int m_currentPage = 0;
|
||||||
int m_totalPages = 0;
|
int m_totalPages = 0;
|
||||||
bool m_isMangaMode = false;
|
|
||||||
bool m_mangaLandscape = false;
|
bool m_mangaLandscape = false;
|
||||||
bool m_pageShift = true;
|
bool m_pageShift = true;
|
||||||
bool m_mangaRTL = true;
|
bool m_mangaRTL = true;
|
||||||
|
|
||||||
QVector<ContentChunk> m_chunks;
|
QVector<PageInfo> m_pages;
|
||||||
QVector<int> m_chapterStartIndices;
|
|
||||||
QVector<QString> m_chapterTitles;
|
|
||||||
|
|
||||||
MangaPagination m_pagination;
|
MangaPagination m_pagination;
|
||||||
qreal m_yOffset = 0.0;
|
qreal m_yOffset = 0.0;
|
||||||
|
|
||||||
|
|||||||
@@ -34,11 +34,6 @@ QString Book::title() const { return m_reader ? m_reader->title() : QString();
|
|||||||
QString Book::author() const { return m_reader ? m_reader->author() : QString(); }
|
QString Book::author() const { return m_reader ? m_reader->author() : QString(); }
|
||||||
QString Book::filePath() const { return m_reader ? m_reader->filePath() : QString(); }
|
QString Book::filePath() const { return m_reader ? m_reader->filePath() : QString(); }
|
||||||
|
|
||||||
QList<TocEntry> Book::toc() const
|
|
||||||
{
|
|
||||||
return m_reader ? m_reader->tableOfContents() : QList<TocEntry>{};
|
|
||||||
}
|
|
||||||
|
|
||||||
FormatReader *Book::reader() const
|
FormatReader *Book::reader() const
|
||||||
{
|
{
|
||||||
return m_reader.get();
|
return m_reader.get();
|
||||||
|
|||||||
@@ -21,7 +21,6 @@ class Book : public QObject {
|
|||||||
Q_PROPERTY(QString author READ author NOTIFY bookChanged)
|
Q_PROPERTY(QString author READ author NOTIFY bookChanged)
|
||||||
Q_PROPERTY(QString filePath READ filePath NOTIFY bookChanged)
|
Q_PROPERTY(QString filePath READ filePath NOTIFY bookChanged)
|
||||||
Q_PROPERTY(QString coverImageUrl READ coverImageUrl NOTIFY bookChanged)
|
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 errorMessage READ errorMessage NOTIFY errorMessageChanged)
|
||||||
public:
|
public:
|
||||||
Book(IFileDialogService &dialog,
|
Book(IFileDialogService &dialog,
|
||||||
@@ -36,7 +35,6 @@ public:
|
|||||||
QString author() const;
|
QString author() const;
|
||||||
QString filePath() const;
|
QString filePath() const;
|
||||||
QString coverImageUrl() const;
|
QString coverImageUrl() const;
|
||||||
QList<TocEntry> toc() const;
|
|
||||||
QString errorMessage() const;
|
QString errorMessage() const;
|
||||||
|
|
||||||
// Called by AppCoordinator::onBookChanged after the image provider resolves the cover URL.
|
// Called by AppCoordinator::onBookChanged after the image provider resolves the cover URL.
|
||||||
|
|||||||
@@ -1,430 +0,0 @@
|
|||||||
#include "EpubReader.h"
|
|
||||||
|
|
||||||
#include <QCryptographicHash>
|
|
||||||
#include <QDir>
|
|
||||||
#include <QDomDocument>
|
|
||||||
#include <QFile>
|
|
||||||
#include <QFileInfo>
|
|
||||||
#include <QTextStream>
|
|
||||||
#include <QUrl>
|
|
||||||
#include <QXmlStreamReader>
|
|
||||||
|
|
||||||
#include "backend/ZipUtils.h"
|
|
||||||
|
|
||||||
using ZipUtils::readZipEntry;
|
|
||||||
|
|
||||||
// Serialize a QDomNode to a string (no XML declaration, no extra indentation).
|
|
||||||
static QString serializeNode(const QDomNode &node)
|
|
||||||
{
|
|
||||||
QString out;
|
|
||||||
QTextStream stream(&out);
|
|
||||||
node.save(stream, 0 /*indent*/);
|
|
||||||
return out;
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
|
||||||
// EpubReader::open
|
|
||||||
// ---------------------------------------------------------------------------
|
|
||||||
|
|
||||||
bool EpubReader::open(const QString &filePath)
|
|
||||||
{
|
|
||||||
// Reset state
|
|
||||||
m_title.clear();
|
|
||||||
m_author.clear();
|
|
||||||
m_error.clear();
|
|
||||||
m_opfDir.clear();
|
|
||||||
m_coverImagePath.clear();
|
|
||||||
m_spineHrefs.clear();
|
|
||||||
m_spineRawContent.clear();
|
|
||||||
m_toc.clear();
|
|
||||||
m_contentHash.clear();
|
|
||||||
|
|
||||||
// Compute content hash from raw file bytes before ZIP parsing
|
|
||||||
{
|
|
||||||
QFile f(filePath);
|
|
||||||
if (f.open(QIODevice::ReadOnly))
|
|
||||||
m_contentHash = QCryptographicHash::hash(f.readAll(), QCryptographicHash::Md5);
|
|
||||||
}
|
|
||||||
|
|
||||||
unzFile zf = unzOpen(filePath.toUtf8().constData());
|
|
||||||
if (!zf) {
|
|
||||||
m_error = QStringLiteral("Cannot open as ZIP archive: ") + filePath;
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
// Ensure the handle is closed on all exit paths
|
|
||||||
auto guard = [&](void *) { unzClose(zf); };
|
|
||||||
std::unique_ptr<void, decltype(guard)> closeGuard(zf, guard);
|
|
||||||
|
|
||||||
// 1. Parse META-INF/container.xml
|
|
||||||
QByteArray containerData = readZipEntry(zf, "META-INF/container.xml");
|
|
||||||
if (containerData.isEmpty()) {
|
|
||||||
m_error = QStringLiteral("Invalid EPUB: missing META-INF/container.xml");
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
QString opfPath;
|
|
||||||
if (!parseContainer(containerData, opfPath)) {
|
|
||||||
m_error = QStringLiteral("Invalid EPUB: cannot parse container.xml");
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
// 2. Determine OPF base directory
|
|
||||||
const int lastSlash = opfPath.lastIndexOf(QLatin1Char('/'));
|
|
||||||
m_opfDir = (lastSlash >= 0) ? opfPath.left(lastSlash + 1) : QString();
|
|
||||||
|
|
||||||
// 3. Parse OPF
|
|
||||||
QByteArray opfData = readZipEntry(zf, opfPath.toUtf8().constData());
|
|
||||||
if (opfData.isEmpty()) {
|
|
||||||
m_error = QStringLiteral("Invalid EPUB: cannot read OPF file: ") + opfPath;
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
QString ncxHref;
|
|
||||||
if (!parseOpf(opfData, ncxHref)) {
|
|
||||||
m_error = QStringLiteral("Invalid EPUB: cannot parse OPF file");
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
// 4. Read each spine item's raw XHTML
|
|
||||||
for (const QString &href : m_spineHrefs)
|
|
||||||
m_spineRawContent.append(readZipEntry(zf, href.toUtf8().constData()));
|
|
||||||
|
|
||||||
// 5. Parse NCX if available
|
|
||||||
if (!ncxHref.isEmpty()) {
|
|
||||||
QByteArray ncxData = readZipEntry(zf, ncxHref.toUtf8().constData());
|
|
||||||
if (!ncxData.isEmpty())
|
|
||||||
parseNcx(ncxData);
|
|
||||||
}
|
|
||||||
m_filePath = filePath;
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
|
||||||
// parseContainer: extract the OPF rootfile full-path
|
|
||||||
// ---------------------------------------------------------------------------
|
|
||||||
|
|
||||||
bool EpubReader::parseContainer(const QByteArray &data, QString &opfPath)
|
|
||||||
{
|
|
||||||
QXmlStreamReader xml(data);
|
|
||||||
while (!xml.atEnd()) {
|
|
||||||
xml.readNext();
|
|
||||||
if (xml.isStartElement() && xml.name() == QLatin1String("rootfile")) {
|
|
||||||
opfPath = xml.attributes().value(QLatin1String("full-path")).toString();
|
|
||||||
if (!opfPath.isEmpty())
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
|
||||||
// parseOpf: extract metadata, manifest, and spine
|
|
||||||
// ---------------------------------------------------------------------------
|
|
||||||
|
|
||||||
bool EpubReader::parseOpf(const QByteArray &data, QString &ncxHref)
|
|
||||||
{
|
|
||||||
QXmlStreamReader xml(data);
|
|
||||||
QHash<QString, QString> manifest; // id -> relative href
|
|
||||||
QString ncxId;
|
|
||||||
QString coverId; // ID of the cover image item
|
|
||||||
|
|
||||||
static const QLatin1String kDcNs("http://purl.org/dc/elements/1.1/");
|
|
||||||
|
|
||||||
while (!xml.atEnd()) {
|
|
||||||
xml.readNext();
|
|
||||||
if (!xml.isStartElement())
|
|
||||||
continue;
|
|
||||||
|
|
||||||
const QStringView name = xml.name();
|
|
||||||
const QStringView ns = xml.namespaceUri();
|
|
||||||
|
|
||||||
if (name == QLatin1String("title") && ns == kDcNs) {
|
|
||||||
if (m_title.isEmpty())
|
|
||||||
m_title = xml.readElementText().trimmed();
|
|
||||||
} else if (name == QLatin1String("creator") && ns == kDcNs) {
|
|
||||||
if (m_author.isEmpty())
|
|
||||||
m_author = xml.readElementText().trimmed();
|
|
||||||
} else if (name == QLatin1String("meta")) {
|
|
||||||
// Check for cover image metadata
|
|
||||||
const QString metaName = xml.attributes().value(QLatin1String("name")).toString();
|
|
||||||
const QString metaContent = xml.attributes().value(QLatin1String("content")).toString();
|
|
||||||
if (metaName == QLatin1String("cover") && !metaContent.isEmpty()) {
|
|
||||||
coverId = metaContent;
|
|
||||||
}
|
|
||||||
} else if (name == QLatin1String("item")) {
|
|
||||||
const QString id = xml.attributes().value(QLatin1String("id")).toString();
|
|
||||||
const QString href = xml.attributes().value(QLatin1String("href")).toString();
|
|
||||||
const QString properties = xml.attributes().value(QLatin1String("properties")).toString();
|
|
||||||
|
|
||||||
if (!id.isEmpty() && !href.isEmpty())
|
|
||||||
manifest.insert(id, href);
|
|
||||||
|
|
||||||
// Check if this item is the cover image
|
|
||||||
if (properties.contains(QLatin1String("cover-image"))) {
|
|
||||||
coverId = id;
|
|
||||||
}
|
|
||||||
} else if (name == QLatin1String("spine")) {
|
|
||||||
ncxId = xml.attributes().value(QLatin1String("toc")).toString();
|
|
||||||
} else if (name == QLatin1String("itemref")) {
|
|
||||||
const QString idref = xml.attributes().value(QLatin1String("idref")).toString();
|
|
||||||
if (manifest.contains(idref))
|
|
||||||
m_spineHrefs.append(m_opfDir + manifest.value(idref));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Resolve cover image path if we found a cover ID
|
|
||||||
if (!coverId.isEmpty() && manifest.contains(coverId)) {
|
|
||||||
m_coverImagePath = m_opfDir + manifest.value(coverId);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!ncxId.isEmpty() && manifest.contains(ncxId))
|
|
||||||
ncxHref = m_opfDir + manifest.value(ncxId);
|
|
||||||
|
|
||||||
return !xml.hasError();
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
|
||||||
// parseNcx: build TOC from navMap
|
|
||||||
// ---------------------------------------------------------------------------
|
|
||||||
|
|
||||||
void EpubReader::parseNcx(const QByteArray &data)
|
|
||||||
{
|
|
||||||
QXmlStreamReader xml(data);
|
|
||||||
int depth = 0;
|
|
||||||
QString currentLabel;
|
|
||||||
QString currentSrc;
|
|
||||||
bool insideNavLabel = false;
|
|
||||||
bool insideText = false;
|
|
||||||
|
|
||||||
// Map both full path and filename-only -> spine index
|
|
||||||
QHash<QString, int> hrefToIndex;
|
|
||||||
for (int i = 0; i < m_spineHrefs.size(); ++i) {
|
|
||||||
hrefToIndex.insert(m_spineHrefs[i], i);
|
|
||||||
hrefToIndex.insert(QFileInfo(m_spineHrefs[i]).fileName(), i);
|
|
||||||
}
|
|
||||||
|
|
||||||
while (!xml.atEnd()) {
|
|
||||||
xml.readNext();
|
|
||||||
|
|
||||||
if (xml.isStartElement()) {
|
|
||||||
const QStringView name = xml.name();
|
|
||||||
if (name == QLatin1String("navPoint")) {
|
|
||||||
++depth;
|
|
||||||
currentLabel.clear();
|
|
||||||
currentSrc.clear();
|
|
||||||
} else if (name == QLatin1String("navLabel")) {
|
|
||||||
insideNavLabel = true;
|
|
||||||
} else if (insideNavLabel && name == QLatin1String("text")) {
|
|
||||||
insideText = true;
|
|
||||||
} else if (name == QLatin1String("content")) {
|
|
||||||
QString src = xml.attributes().value(QLatin1String("src")).toString();
|
|
||||||
const int hashPos = src.indexOf(QLatin1Char('#'));
|
|
||||||
if (hashPos >= 0)
|
|
||||||
src = src.left(hashPos);
|
|
||||||
currentSrc = src;
|
|
||||||
}
|
|
||||||
} else if (xml.isCharacters() && insideText) {
|
|
||||||
currentLabel += xml.text();
|
|
||||||
} else if (xml.isEndElement()) {
|
|
||||||
const QStringView name = xml.name();
|
|
||||||
if (name == QLatin1String("text") && insideText) {
|
|
||||||
insideText = false;
|
|
||||||
} else if (name == QLatin1String("navLabel")) {
|
|
||||||
insideNavLabel = false;
|
|
||||||
} else if (name == QLatin1String("navPoint")) {
|
|
||||||
int chapterIdx = -1;
|
|
||||||
if (!currentSrc.isEmpty()) {
|
|
||||||
const QString fullHref = m_opfDir + currentSrc;
|
|
||||||
if (hrefToIndex.contains(fullHref))
|
|
||||||
chapterIdx = hrefToIndex.value(fullHref);
|
|
||||||
else if (hrefToIndex.contains(currentSrc))
|
|
||||||
chapterIdx = hrefToIndex.value(currentSrc);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (chapterIdx >= 0 && !currentLabel.trimmed().isEmpty()) {
|
|
||||||
TocEntry entry;
|
|
||||||
entry.title = currentLabel.trimmed();
|
|
||||||
entry.chapterIndex = chapterIdx;
|
|
||||||
entry.depth = depth - 1;
|
|
||||||
m_toc.append(entry);
|
|
||||||
}
|
|
||||||
|
|
||||||
--depth;
|
|
||||||
currentLabel.clear();
|
|
||||||
currentSrc.clear();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
|
||||||
// chunkXhtml: DOM-based chunking of a spine XHTML item
|
|
||||||
// ---------------------------------------------------------------------------
|
|
||||||
|
|
||||||
QStringList EpubReader::chunkXhtml(const QByteArray &data, const QString &xhtmlHref)
|
|
||||||
{
|
|
||||||
if (data.isEmpty())
|
|
||||||
return {};
|
|
||||||
|
|
||||||
QDomDocument doc;
|
|
||||||
const auto parseResult = doc.setContent(data, QDomDocument::ParseOption::Default);
|
|
||||||
if (!parseResult) {
|
|
||||||
// Malformed XHTML fallback: return raw as a single chunk
|
|
||||||
return {QString::fromUtf8(data)};
|
|
||||||
}
|
|
||||||
|
|
||||||
// Rewrite <img src="..."> to image://epub/ URLs so Qt can load them from the provider
|
|
||||||
const int slashPos = xhtmlHref.lastIndexOf(QLatin1Char('/'));
|
|
||||||
const QString xhtmlDir = (slashPos >= 0) ? xhtmlHref.left(slashPos + 1) : QString();
|
|
||||||
const QDomNodeList imgs = doc.elementsByTagName(QStringLiteral("img"));
|
|
||||||
for (int i = 0; i < imgs.size(); ++i) {
|
|
||||||
QDomElement img = imgs.at(i).toElement();
|
|
||||||
if (img.isNull())
|
|
||||||
continue;
|
|
||||||
QString src = img.attribute(QStringLiteral("src"));
|
|
||||||
if (src.isEmpty() || src.startsWith(QStringLiteral("image://")))
|
|
||||||
continue;
|
|
||||||
src = QUrl::fromPercentEncoding(src.toUtf8());
|
|
||||||
if (src.startsWith(QLatin1String("http://")) || src.startsWith(QLatin1String("https://"))) {
|
|
||||||
img.setAttribute(QStringLiteral("src"), QStringLiteral("image://web/") + src);
|
|
||||||
} else {
|
|
||||||
const QString resolved = QDir::cleanPath(xhtmlDir + src);
|
|
||||||
img.setAttribute(QStringLiteral("src"),
|
|
||||||
QStringLiteral("image://epub/") + resolved);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Find <body> element (may have namespace prefix in some EPUBs)
|
|
||||||
QDomElement body;
|
|
||||||
const QDomNodeList bodies = doc.elementsByTagName(QStringLiteral("body"));
|
|
||||||
if (!bodies.isEmpty())
|
|
||||||
body = bodies.at(0).toElement();
|
|
||||||
|
|
||||||
if (body.isNull())
|
|
||||||
return {};
|
|
||||||
|
|
||||||
static constexpr int kChunkSize = 4096;
|
|
||||||
QStringList chunks;
|
|
||||||
QString current;
|
|
||||||
|
|
||||||
QDomNode node = body.firstChild();
|
|
||||||
while (!node.isNull()) {
|
|
||||||
QString serialized;
|
|
||||||
if (node.isElement()) {
|
|
||||||
serialized = serializeNode(node);
|
|
||||||
} else if (node.isText()) {
|
|
||||||
const QString text = node.nodeValue().trimmed();
|
|
||||||
if (!text.isEmpty())
|
|
||||||
serialized = QStringLiteral("<p>") + text.toHtmlEscaped() + QStringLiteral("</p>\n");
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!serialized.isEmpty()) {
|
|
||||||
if (!current.isEmpty() && current.size() + serialized.size() > kChunkSize) {
|
|
||||||
chunks.append(current);
|
|
||||||
current.clear();
|
|
||||||
}
|
|
||||||
current += serialized;
|
|
||||||
}
|
|
||||||
|
|
||||||
node = node.nextSibling();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!current.isEmpty())
|
|
||||||
chunks.append(current);
|
|
||||||
|
|
||||||
return chunks;
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
|
||||||
// FormatReader interface
|
|
||||||
// ---------------------------------------------------------------------------
|
|
||||||
|
|
||||||
bool EpubReader::loadMetadata(const QString &filePath)
|
|
||||||
{
|
|
||||||
// Reset state
|
|
||||||
m_title.clear();
|
|
||||||
m_author.clear();
|
|
||||||
m_error.clear();
|
|
||||||
m_opfDir.clear();
|
|
||||||
m_coverImagePath.clear();
|
|
||||||
m_spineHrefs.clear();
|
|
||||||
|
|
||||||
unzFile zf = unzOpen(filePath.toUtf8().constData());
|
|
||||||
if (!zf) {
|
|
||||||
m_error = QStringLiteral("Cannot open as ZIP archive: ") + filePath;
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
// Ensure the handle is closed on all exit paths
|
|
||||||
auto guard = [&](void *) { unzClose(zf); };
|
|
||||||
std::unique_ptr<void, decltype(guard)> closeGuard(zf, guard);
|
|
||||||
|
|
||||||
// 1. Parse META-INF/container.xml
|
|
||||||
QByteArray containerData = readZipEntry(zf, "META-INF/container.xml");
|
|
||||||
if (containerData.isEmpty()) {
|
|
||||||
m_error = QStringLiteral("Invalid EPUB: missing META-INF/container.xml");
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
QString opfPath;
|
|
||||||
if (!parseContainer(containerData, opfPath)) {
|
|
||||||
m_error = QStringLiteral("Invalid EPUB: cannot parse container.xml");
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
// 2. Determine OPF base directory
|
|
||||||
const int lastSlash = opfPath.lastIndexOf(QLatin1Char('/'));
|
|
||||||
m_opfDir = (lastSlash >= 0) ? opfPath.left(lastSlash + 1) : QString();
|
|
||||||
|
|
||||||
// 3. Parse OPF (only metadata and manifest for cover image)
|
|
||||||
QByteArray opfData = readZipEntry(zf, opfPath.toUtf8().constData());
|
|
||||||
if (opfData.isEmpty()) {
|
|
||||||
m_error = QStringLiteral("Invalid EPUB: cannot read OPF file: ") + opfPath;
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
QString ncxHref;
|
|
||||||
if (!parseOpf(opfData, ncxHref)) {
|
|
||||||
m_error = QStringLiteral("Invalid EPUB: cannot parse OPF file");
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
QString EpubReader::lastError() { return m_error; }
|
|
||||||
QString EpubReader::title() { return m_title; }
|
|
||||||
QString EpubReader::author() { return m_author; }
|
|
||||||
QString EpubReader::coverImagePath() { return m_coverImagePath; }
|
|
||||||
int EpubReader::chapterCount() { return m_spineHrefs.size(); }
|
|
||||||
|
|
||||||
QList<TocEntry> EpubReader::tableOfContents() { return m_toc; }
|
|
||||||
|
|
||||||
QString EpubReader::filePath()
|
|
||||||
{
|
|
||||||
return m_filePath;
|
|
||||||
}
|
|
||||||
|
|
||||||
QByteArray EpubReader::contentHash()
|
|
||||||
{
|
|
||||||
return m_contentHash;
|
|
||||||
}
|
|
||||||
|
|
||||||
Chapter EpubReader::loadChapter(int index)
|
|
||||||
{
|
|
||||||
if (index < 0 || index >= m_spineRawContent.size())
|
|
||||||
return Chapter{index, {}, {}};
|
|
||||||
|
|
||||||
QString chTitle;
|
|
||||||
for (const TocEntry &e : m_toc) {
|
|
||||||
if (e.chapterIndex == index) {
|
|
||||||
chTitle = e.title;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (chTitle.isEmpty() && index < m_spineHrefs.size())
|
|
||||||
chTitle = QFileInfo(m_spineHrefs[index]).completeBaseName();
|
|
||||||
|
|
||||||
return Chapter{index, chTitle, chunkXhtml(m_spineRawContent[index], m_spineHrefs[index])};
|
|
||||||
}
|
|
||||||
|
|
||||||
QString EpubReader::fileType() const { return QStringLiteral("epub"); }
|
|
||||||
@@ -1,42 +0,0 @@
|
|||||||
#ifndef EPUBREADER_H
|
|
||||||
#define EPUBREADER_H
|
|
||||||
|
|
||||||
#include "backend/FormatReader.h"
|
|
||||||
#include <QByteArray>
|
|
||||||
#include <QHash>
|
|
||||||
#include <QList>
|
|
||||||
|
|
||||||
class EpubReader : public FormatReader {
|
|
||||||
public:
|
|
||||||
bool open(const QString &filePath) override;
|
|
||||||
bool loadMetadata(const QString &filePath) override;
|
|
||||||
QString lastError() override;
|
|
||||||
int chapterCount() override;
|
|
||||||
Chapter loadChapter(int index) override;
|
|
||||||
QList<TocEntry> tableOfContents() override;
|
|
||||||
QString filePath() override;
|
|
||||||
QString title() override;
|
|
||||||
QString author() override;
|
|
||||||
QString coverImagePath() override;
|
|
||||||
QByteArray contentHash() override;
|
|
||||||
QString fileType() const override;
|
|
||||||
|
|
||||||
private:
|
|
||||||
QString m_filePath;
|
|
||||||
QByteArray m_contentHash;
|
|
||||||
QString m_title;
|
|
||||||
QString m_author;
|
|
||||||
QString m_error;
|
|
||||||
QString m_opfDir;
|
|
||||||
QString m_coverImagePath;
|
|
||||||
QStringList m_spineHrefs;
|
|
||||||
QList<QByteArray> m_spineRawContent;
|
|
||||||
QList<TocEntry> m_toc;
|
|
||||||
|
|
||||||
bool parseContainer(const QByteArray &data, QString &opfPath);
|
|
||||||
bool parseOpf(const QByteArray &data, QString &ncxHref);
|
|
||||||
void parseNcx(const QByteArray &data);
|
|
||||||
static QStringList chunkXhtml(const QByteArray &data, const QString &xhtmlHref);
|
|
||||||
};
|
|
||||||
|
|
||||||
#endif // EPUBREADER_H
|
|
||||||
@@ -1,366 +0,0 @@
|
|||||||
#include "Fb2Reader.h"
|
|
||||||
|
|
||||||
#include "ImageUrl.h"
|
|
||||||
|
|
||||||
#include <QCryptographicHash>
|
|
||||||
#include <QDomDocument>
|
|
||||||
#include <QFileInfo>
|
|
||||||
#include <QStringConverter>
|
|
||||||
#include <QTextStream>
|
|
||||||
#include <QUrl>
|
|
||||||
|
|
||||||
#include <uchardet/uchardet.h>
|
|
||||||
#include <iconv.h>
|
|
||||||
#include <fstream>
|
|
||||||
|
|
||||||
static constexpr int kChunkSize = 4096;
|
|
||||||
|
|
||||||
static QString decodeWithIconv(const QByteArray &raw, const char *charset)
|
|
||||||
{
|
|
||||||
iconv_t cd = iconv_open("UTF-8", charset);
|
|
||||||
if (cd == reinterpret_cast<iconv_t>(-1))
|
|
||||||
return {};
|
|
||||||
QByteArray out(raw.size() * 4, '\0');
|
|
||||||
char *inBuf = const_cast<char *>(raw.constData());
|
|
||||||
size_t inLeft = raw.size();
|
|
||||||
char *outBuf = out.data();
|
|
||||||
size_t outLeft = out.size();
|
|
||||||
const size_t r = iconv(cd, &inBuf, &inLeft, &outBuf, &outLeft);
|
|
||||||
iconv_close(cd);
|
|
||||||
if (r == static_cast<size_t>(-1))
|
|
||||||
return {};
|
|
||||||
out.resize(out.size() - outLeft);
|
|
||||||
return QString::fromUtf8(out);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Decode FB2 bytes to a Unicode string.
|
|
||||||
// Uses the XML encoding declaration as the authoritative charset source
|
|
||||||
// (uchardet is unreliable on files with large binary sections or sparse text).
|
|
||||||
// QStringConverter / iconv handle the actual conversion.
|
|
||||||
QString Fb2Reader::decodeRawBytes(const QByteArray &raw)
|
|
||||||
{
|
|
||||||
// Extract encoding name from XML declaration (first ~200 bytes)
|
|
||||||
QByteArray enc;
|
|
||||||
const int pos = raw.indexOf("encoding=");
|
|
||||||
if (pos >= 0 && pos < 200) {
|
|
||||||
const int qs = pos + 9;
|
|
||||||
if (qs < raw.size()) {
|
|
||||||
const char q = raw[qs];
|
|
||||||
if (q == '"' || q == '\'') {
|
|
||||||
const int qe = raw.indexOf(q, qs + 1);
|
|
||||||
if (qe > qs)
|
|
||||||
enc = raw.mid(qs + 1, qe - qs - 1).toLower();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (enc.isEmpty() || enc == "utf-8" || enc == "utf8")
|
|
||||||
return QString::fromUtf8(raw);
|
|
||||||
|
|
||||||
// Try Qt's built-in converters first, fall back to iconv for exotic charsets
|
|
||||||
auto qtEncoding = QStringConverter::encodingForName(enc.constData());
|
|
||||||
if (qtEncoding) {
|
|
||||||
QTextStream stream(raw);
|
|
||||||
stream.setEncoding(qtEncoding.value());
|
|
||||||
const QString decoded = stream.readAll();
|
|
||||||
if (!decoded.isEmpty())
|
|
||||||
return decoded;
|
|
||||||
}
|
|
||||||
|
|
||||||
const QString decoded = decodeWithIconv(raw, enc.constData());
|
|
||||||
if (!decoded.isEmpty())
|
|
||||||
return decoded;
|
|
||||||
|
|
||||||
// Last resort: uchardet-based detection
|
|
||||||
uchardet_t ud = uchardet_new();
|
|
||||||
if (uchardet_handle_data(ud, raw.constData(), raw.size()) == 0) {
|
|
||||||
uchardet_data_end(ud);
|
|
||||||
const char *charset = uchardet_get_charset(ud);
|
|
||||||
if (charset && charset[0] != '\0') {
|
|
||||||
const QString s = decodeWithIconv(raw, charset);
|
|
||||||
uchardet_delete(ud);
|
|
||||||
if (!s.isEmpty())
|
|
||||||
return s;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
uchardet_delete(ud);
|
|
||||||
return QString::fromUtf8(raw);
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
|
||||||
// Helpers
|
|
||||||
// ---------------------------------------------------------------------------
|
|
||||||
|
|
||||||
static QDomElement firstChildByTag(const QDomElement &parent, const QString &tag)
|
|
||||||
{
|
|
||||||
for (QDomNode n = parent.firstChild(); !n.isNull(); n = n.nextSibling()) {
|
|
||||||
QDomElement el = n.toElement();
|
|
||||||
if (!el.isNull() && el.tagName() == tag)
|
|
||||||
return el;
|
|
||||||
}
|
|
||||||
return {};
|
|
||||||
}
|
|
||||||
|
|
||||||
// Converts a single FB2 DOM node to an HTML string. Handles inline and block elements.
|
|
||||||
// fb2UrlSuffix is appended to image URLs, e.g. "?fb2=<encoded_path>" for self-contained loading.
|
|
||||||
static QString nodeToHtml(const QDomNode &node, const QString &fb2UrlSuffix = {})
|
|
||||||
{
|
|
||||||
if (node.isText())
|
|
||||||
return node.nodeValue().toHtmlEscaped();
|
|
||||||
|
|
||||||
if (!node.isElement())
|
|
||||||
return {};
|
|
||||||
|
|
||||||
const QDomElement el = node.toElement();
|
|
||||||
const QString tag = el.tagName();
|
|
||||||
|
|
||||||
// Build inner HTML from children
|
|
||||||
QString inner;
|
|
||||||
for (QDomNode child = el.firstChild(); !child.isNull(); child = child.nextSibling())
|
|
||||||
inner += nodeToHtml(child, fb2UrlSuffix);
|
|
||||||
|
|
||||||
if (tag == QLatin1String("p") || tag == QLatin1String("v")) {
|
|
||||||
if (inner.trimmed().isEmpty())
|
|
||||||
return {};
|
|
||||||
return QStringLiteral("<p>") + inner + QStringLiteral("</p>\n");
|
|
||||||
}
|
|
||||||
if (tag == QLatin1String("title"))
|
|
||||||
return inner.trimmed().isEmpty() ? QString{} : QStringLiteral("<h2>") + inner + QStringLiteral("</h2>\n");
|
|
||||||
if (tag == QLatin1String("subtitle"))
|
|
||||||
return inner.trimmed().isEmpty() ? QString{} : QStringLiteral("<h3>") + inner + QStringLiteral("</h3>\n");
|
|
||||||
if (tag == QLatin1String("emphasis"))
|
|
||||||
return QStringLiteral("<em>") + inner + QStringLiteral("</em>");
|
|
||||||
if (tag == QLatin1String("strong"))
|
|
||||||
return QStringLiteral("<strong>") + inner + QStringLiteral("</strong>");
|
|
||||||
if (tag == QLatin1String("epigraph") || tag == QLatin1String("poem") || tag == QLatin1String("cite"))
|
|
||||||
return inner.trimmed().isEmpty() ? QString{} : QStringLiteral("<blockquote>") + inner + QStringLiteral("</blockquote>\n");
|
|
||||||
if (tag == QLatin1String("section") || tag == QLatin1String("stanza"))
|
|
||||||
return inner;
|
|
||||||
if (tag == QLatin1String("image")) {
|
|
||||||
QString href = el.attribute(QStringLiteral("l:href"));
|
|
||||||
if (href.isEmpty())
|
|
||||||
href = el.attribute(QStringLiteral("xlink:href"));
|
|
||||||
if (href.startsWith(QLatin1Char('#')))
|
|
||||||
href = href.mid(1);
|
|
||||||
if (!href.isEmpty())
|
|
||||||
return QStringLiteral("<img src=\"image://fb2/") + href + fb2UrlSuffix + QStringLiteral("\"/>\n");
|
|
||||||
return {};
|
|
||||||
}
|
|
||||||
if (tag == QLatin1String("a")) {
|
|
||||||
const QString href = el.attribute(QStringLiteral("l:href"));
|
|
||||||
if (!href.isEmpty() && !href.startsWith(QLatin1Char('#')))
|
|
||||||
return QStringLiteral("<a href=\"") + href.toHtmlEscaped() + QStringLiteral("\">") + inner + QStringLiteral("</a>");
|
|
||||||
return inner;
|
|
||||||
}
|
|
||||||
return inner;
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
|
||||||
// Metadata parsing
|
|
||||||
// ---------------------------------------------------------------------------
|
|
||||||
|
|
||||||
struct Fb2Metadata {
|
|
||||||
QString title, author, coverBinaryId;
|
|
||||||
};
|
|
||||||
|
|
||||||
static Fb2Metadata parseDescription(const QDomElement &desc)
|
|
||||||
{
|
|
||||||
Fb2Metadata meta;
|
|
||||||
const QDomElement titleInfo = firstChildByTag(desc, QStringLiteral("title-info"));
|
|
||||||
if (titleInfo.isNull())
|
|
||||||
return meta;
|
|
||||||
|
|
||||||
const QDomElement bookTitle = firstChildByTag(titleInfo, QStringLiteral("book-title"));
|
|
||||||
if (!bookTitle.isNull())
|
|
||||||
meta.title = bookTitle.text().simplified();
|
|
||||||
|
|
||||||
const QDomElement author = firstChildByTag(titleInfo, QStringLiteral("author"));
|
|
||||||
if (!author.isNull()) {
|
|
||||||
const QString first = firstChildByTag(author, QStringLiteral("first-name")).text().simplified();
|
|
||||||
const QString last = firstChildByTag(author, QStringLiteral("last-name")).text().simplified();
|
|
||||||
if (!first.isEmpty() && !last.isEmpty())
|
|
||||||
meta.author = first + QLatin1Char(' ') + last;
|
|
||||||
else
|
|
||||||
meta.author = first + last;
|
|
||||||
}
|
|
||||||
|
|
||||||
const QDomElement coverpage = firstChildByTag(titleInfo, QStringLiteral("coverpage"));
|
|
||||||
if (!coverpage.isNull()) {
|
|
||||||
const QDomElement img = firstChildByTag(coverpage, QStringLiteral("image"));
|
|
||||||
if (!img.isNull()) {
|
|
||||||
QString href = img.attribute(QStringLiteral("l:href"));
|
|
||||||
if (href.isEmpty())
|
|
||||||
href = img.attribute(QStringLiteral("xlink:href"));
|
|
||||||
if (href.startsWith(QLatin1Char('#')))
|
|
||||||
href = href.mid(1);
|
|
||||||
meta.coverBinaryId = href;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return meta;
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
|
||||||
// FormatReader interface
|
|
||||||
// ---------------------------------------------------------------------------
|
|
||||||
|
|
||||||
bool Fb2Reader::open(const QString &filePath)
|
|
||||||
{
|
|
||||||
m_title.clear();
|
|
||||||
m_author.clear();
|
|
||||||
m_error.clear();
|
|
||||||
m_coverBinaryId.clear();
|
|
||||||
m_chapterHtmlNodes.clear();
|
|
||||||
m_chapterTitles.clear();
|
|
||||||
m_toc.clear();
|
|
||||||
m_contentHash.clear();
|
|
||||||
|
|
||||||
std::ifstream f(filePath.toUtf8().constData(), std::ios::binary | std::ios::ate);
|
|
||||||
if (!f) {
|
|
||||||
m_error = QStringLiteral("Cannot open file: ") + filePath;
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
const auto size = f.tellg();
|
|
||||||
f.seekg(0);
|
|
||||||
QByteArray raw(static_cast<int>(size), '\0');
|
|
||||||
f.read(raw.data(), size);
|
|
||||||
|
|
||||||
m_contentHash = QCryptographicHash::hash(raw, QCryptographicHash::Md5);
|
|
||||||
|
|
||||||
QDomDocument doc;
|
|
||||||
const auto result = doc.setContent(decodeRawBytes(raw), QDomDocument::ParseOption::Default);
|
|
||||||
if (!result) {
|
|
||||||
m_error = QStringLiteral("Failed to parse FB2 XML: ") + result.errorMessage;
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
const QDomElement root = doc.documentElement();
|
|
||||||
|
|
||||||
// Metadata
|
|
||||||
const QDomElement desc = firstChildByTag(root, QStringLiteral("description"));
|
|
||||||
if (!desc.isNull()) {
|
|
||||||
const Fb2Metadata meta = parseDescription(desc);
|
|
||||||
m_title = meta.title;
|
|
||||||
m_author = meta.author;
|
|
||||||
m_coverBinaryId = meta.coverBinaryId;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (m_title.isEmpty())
|
|
||||||
m_title = QFileInfo(filePath).completeBaseName();
|
|
||||||
|
|
||||||
// Pre-compute URL suffix so body image URLs embed the file path (self-contained, encoding-safe).
|
|
||||||
const QString urlSuffix = ImageUrl::querySuffix(filePath);
|
|
||||||
|
|
||||||
// Body sections
|
|
||||||
for (QDomNode bodyNode = root.firstChild(); !bodyNode.isNull(); bodyNode = bodyNode.nextSibling()) {
|
|
||||||
const QDomElement body = bodyNode.toElement();
|
|
||||||
if (body.isNull() || body.tagName() != QLatin1String("body"))
|
|
||||||
continue;
|
|
||||||
// Skip named bodies (e.g. notes)
|
|
||||||
if (!body.attribute(QStringLiteral("name")).isEmpty())
|
|
||||||
continue;
|
|
||||||
|
|
||||||
for (QDomNode secNode = body.firstChild(); !secNode.isNull(); secNode = secNode.nextSibling()) {
|
|
||||||
const QDomElement section = secNode.toElement();
|
|
||||||
if (section.isNull() || section.tagName() != QLatin1String("section"))
|
|
||||||
continue;
|
|
||||||
|
|
||||||
// Extract section title
|
|
||||||
const QDomElement titleEl = firstChildByTag(section, QStringLiteral("title"));
|
|
||||||
QString sectionTitle = titleEl.isNull() ? QString{} : titleEl.text().simplified();
|
|
||||||
if (sectionTitle.isEmpty())
|
|
||||||
sectionTitle = QStringLiteral("Chapter %1").arg(m_chapterHtmlNodes.size() + 1);
|
|
||||||
m_chapterTitles.append(sectionTitle);
|
|
||||||
|
|
||||||
// Convert section children to HTML node list
|
|
||||||
QStringList htmlNodes;
|
|
||||||
for (QDomNode child = section.firstChild(); !child.isNull(); child = child.nextSibling()) {
|
|
||||||
const QString html = nodeToHtml(child, urlSuffix);
|
|
||||||
if (!html.isEmpty())
|
|
||||||
htmlNodes.append(html);
|
|
||||||
}
|
|
||||||
m_chapterHtmlNodes.append(htmlNodes);
|
|
||||||
|
|
||||||
TocEntry entry;
|
|
||||||
entry.title = sectionTitle;
|
|
||||||
entry.chapterIndex = m_chapterHtmlNodes.size() - 1;
|
|
||||||
entry.depth = 0;
|
|
||||||
m_toc.append(entry);
|
|
||||||
}
|
|
||||||
break; // only process first unnamed body
|
|
||||||
}
|
|
||||||
|
|
||||||
m_filePath = filePath;
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool Fb2Reader::loadMetadata(const QString &filePath)
|
|
||||||
{
|
|
||||||
m_title.clear();
|
|
||||||
m_author.clear();
|
|
||||||
m_error.clear();
|
|
||||||
m_coverBinaryId.clear();
|
|
||||||
|
|
||||||
std::ifstream f(filePath.toUtf8().constData(), std::ios::binary | std::ios::ate);
|
|
||||||
if (!f) {
|
|
||||||
m_error = QStringLiteral("Cannot open file: ") + filePath;
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
const auto size = f.tellg();
|
|
||||||
f.seekg(0);
|
|
||||||
QByteArray raw(static_cast<int>(size), '\0');
|
|
||||||
f.read(raw.data(), size);
|
|
||||||
|
|
||||||
QDomDocument doc;
|
|
||||||
const auto result = doc.setContent(decodeRawBytes(raw), QDomDocument::ParseOption::Default);
|
|
||||||
if (!result) {
|
|
||||||
m_error = QStringLiteral("Failed to parse FB2 XML: ") + result.errorMessage;
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
const QDomElement root = doc.documentElement();
|
|
||||||
const QDomElement desc = firstChildByTag(root, QStringLiteral("description"));
|
|
||||||
if (!desc.isNull()) {
|
|
||||||
const Fb2Metadata meta = parseDescription(desc);
|
|
||||||
m_title = meta.title;
|
|
||||||
m_author = meta.author;
|
|
||||||
m_coverBinaryId = meta.coverBinaryId;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (m_title.isEmpty())
|
|
||||||
m_title = QFileInfo(filePath).completeBaseName();
|
|
||||||
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
QString Fb2Reader::lastError() { return m_error; }
|
|
||||||
QString Fb2Reader::title() { return m_title; }
|
|
||||||
QString Fb2Reader::author() { return m_author; }
|
|
||||||
QString Fb2Reader::coverImagePath() { return m_coverBinaryId; }
|
|
||||||
int Fb2Reader::chapterCount() { return m_chapterHtmlNodes.size(); }
|
|
||||||
QList<TocEntry> Fb2Reader::tableOfContents() { return m_toc; }
|
|
||||||
QString Fb2Reader::filePath() { return m_filePath; }
|
|
||||||
QByteArray Fb2Reader::contentHash() { return m_contentHash; }
|
|
||||||
QString Fb2Reader::fileType() const { return QStringLiteral("fb2"); }
|
|
||||||
|
|
||||||
Chapter Fb2Reader::loadChapter(int index)
|
|
||||||
{
|
|
||||||
if (index < 0 || index >= m_chapterHtmlNodes.size())
|
|
||||||
return Chapter{index, {}, {}};
|
|
||||||
|
|
||||||
const QStringList &nodes = m_chapterHtmlNodes[index];
|
|
||||||
QStringList chunks;
|
|
||||||
QString current;
|
|
||||||
|
|
||||||
for (const QString &node : nodes) {
|
|
||||||
if (!current.isEmpty() && current.size() + node.size() > kChunkSize) {
|
|
||||||
chunks.append(current);
|
|
||||||
current.clear();
|
|
||||||
}
|
|
||||||
current += node;
|
|
||||||
}
|
|
||||||
if (!current.isEmpty())
|
|
||||||
chunks.append(current);
|
|
||||||
|
|
||||||
return Chapter{index, m_chapterTitles[index], chunks};
|
|
||||||
}
|
|
||||||
@@ -1,37 +0,0 @@
|
|||||||
#ifndef FB2READER_H
|
|
||||||
#define FB2READER_H
|
|
||||||
|
|
||||||
#include "backend/FormatReader.h"
|
|
||||||
#include <QByteArray>
|
|
||||||
#include <QList>
|
|
||||||
|
|
||||||
class Fb2Reader : public FormatReader {
|
|
||||||
public:
|
|
||||||
static QString decodeRawBytes(const QByteArray &raw);
|
|
||||||
|
|
||||||
bool open(const QString &filePath) override;
|
|
||||||
bool loadMetadata(const QString &filePath) override;
|
|
||||||
QString lastError() override;
|
|
||||||
int chapterCount() override;
|
|
||||||
Chapter loadChapter(int index) override;
|
|
||||||
QList<TocEntry> tableOfContents() override;
|
|
||||||
QString filePath() override;
|
|
||||||
QString title() override;
|
|
||||||
QString author() override;
|
|
||||||
QString coverImagePath() override;
|
|
||||||
QByteArray contentHash() override;
|
|
||||||
QString fileType() const override;
|
|
||||||
|
|
||||||
private:
|
|
||||||
QString m_filePath;
|
|
||||||
QByteArray m_contentHash;
|
|
||||||
QString m_title;
|
|
||||||
QString m_author;
|
|
||||||
QString m_error;
|
|
||||||
QString m_coverBinaryId;
|
|
||||||
QList<QStringList> m_chapterHtmlNodes;
|
|
||||||
QStringList m_chapterTitles;
|
|
||||||
QList<TocEntry> m_toc;
|
|
||||||
};
|
|
||||||
|
|
||||||
#endif // FB2READER_H
|
|
||||||
@@ -1,7 +1,6 @@
|
|||||||
#include "FormatRegistry.h"
|
#include "FormatRegistry.h"
|
||||||
|
|
||||||
#include "EntryImageProvider.h"
|
#include "EntryImageProvider.h"
|
||||||
#include "WebImageProvider.h"
|
|
||||||
#include "backend/FormatReader.h"
|
#include "backend/FormatReader.h"
|
||||||
|
|
||||||
#include <QFileInfo>
|
#include <QFileInfo>
|
||||||
|
|||||||
@@ -2,9 +2,16 @@
|
|||||||
|
|
||||||
#include <QLatin1Char>
|
#include <QLatin1Char>
|
||||||
#include <QLatin1String>
|
#include <QLatin1String>
|
||||||
|
#include <QUrl>
|
||||||
|
|
||||||
namespace {
|
namespace {
|
||||||
const QLatin1String kSrcKey("src=");
|
const QLatin1String kSrcKey("src=");
|
||||||
|
|
||||||
|
QString querySuffix(const QString &sourcePath)
|
||||||
|
{
|
||||||
|
return QStringLiteral("?src=")
|
||||||
|
+ QString::fromUtf8(QUrl::toPercentEncoding(sourcePath));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
namespace ImageUrl {
|
namespace ImageUrl {
|
||||||
@@ -19,12 +26,6 @@ QString build(const QString &scheme, const QString &entry, const QString &source
|
|||||||
return build(scheme, entry) + querySuffix(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 parseProviderId(const QString &id)
|
||||||
{
|
{
|
||||||
Parsed result;
|
Parsed result;
|
||||||
@@ -41,20 +42,4 @@ Parsed parseProviderId(const QString &id)
|
|||||||
return result;
|
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
|
} // namespace ImageUrl
|
||||||
@@ -1,7 +1,6 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include <QString>
|
#include <QString>
|
||||||
#include <QUrl>
|
|
||||||
|
|
||||||
// Single authority for the image-provider URL grammar:
|
// Single authority for the image-provider URL grammar:
|
||||||
// image://<scheme>/<entry>[?src=<percent-encoded-source-path>]
|
// image://<scheme>/<entry>[?src=<percent-encoded-source-path>]
|
||||||
@@ -12,9 +11,6 @@ namespace ImageUrl {
|
|||||||
QString build(const QString &scheme, const QString &entry);
|
QString build(const QString &scheme, const QString &entry);
|
||||||
QString build(const QString &scheme, const QString &entry, const QString &sourcePath);
|
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 {
|
struct Parsed {
|
||||||
QString entry;
|
QString entry;
|
||||||
QString sourcePath; // empty = use the provider's current file
|
QString sourcePath; // empty = use the provider's current file
|
||||||
@@ -24,7 +20,4 @@ struct Parsed {
|
|||||||
// entry arrives percent-encoded).
|
// entry arrives percent-encoded).
|
||||||
Parsed parseProviderId(const QString &id);
|
Parsed parseProviderId(const QString &id);
|
||||||
|
|
||||||
// Parse a full image:// URL (IImageLoader::load path).
|
|
||||||
Parsed parseImageUrl(const QUrl &url);
|
|
||||||
|
|
||||||
} // namespace ImageUrl
|
} // namespace ImageUrl
|
||||||
@@ -1,218 +0,0 @@
|
|||||||
#include "TxtReader.h"
|
|
||||||
|
|
||||||
#include <QCryptographicHash>
|
|
||||||
#include <QFileInfo>
|
|
||||||
#include <QRegularExpression>
|
|
||||||
#include <QTextStream>
|
|
||||||
|
|
||||||
#include <uchardet/uchardet.h>
|
|
||||||
#include <iconv.h>
|
|
||||||
|
|
||||||
#include <fstream>
|
|
||||||
|
|
||||||
static constexpr int kChunkSize = 4096;
|
|
||||||
|
|
||||||
static QString decodeWithIconv(const QByteArray &raw, const char *charset)
|
|
||||||
{
|
|
||||||
iconv_t cd = iconv_open("UTF-8", charset);
|
|
||||||
if (cd == reinterpret_cast<iconv_t>(-1))
|
|
||||||
return {};
|
|
||||||
|
|
||||||
// Worst case: each byte becomes 4 UTF-8 bytes
|
|
||||||
QByteArray out(raw.size() * 4, '\0');
|
|
||||||
char *inBuf = const_cast<char *>(raw.constData());
|
|
||||||
size_t inLeft = raw.size();
|
|
||||||
char *outBuf = out.data();
|
|
||||||
size_t outLeft = out.size();
|
|
||||||
|
|
||||||
size_t result = iconv(cd, &inBuf, &inLeft, &outBuf, &outLeft);
|
|
||||||
iconv_close(cd);
|
|
||||||
|
|
||||||
if (result == static_cast<size_t>(-1))
|
|
||||||
return {};
|
|
||||||
|
|
||||||
out.resize(out.size() - outLeft);
|
|
||||||
return QString::fromUtf8(out);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Convert a raw text fragment into HTML paragraphs.
|
|
||||||
// Splits on blank lines (\n\n+) to create <p> blocks;
|
|
||||||
// single newlines within a block become <br>.
|
|
||||||
static QString textToHtml(const QString &text)
|
|
||||||
{
|
|
||||||
QString html;
|
|
||||||
const QStringList blocks = text.split(QRegularExpression("\\n\\n+"));
|
|
||||||
for (const QString &block : blocks) {
|
|
||||||
QString escaped = block.toHtmlEscaped().trimmed();
|
|
||||||
if (escaped.isEmpty())
|
|
||||||
continue;
|
|
||||||
escaped.replace('\n', QStringLiteral("<br>\n"));
|
|
||||||
html += QStringLiteral("<p>") + escaped + QStringLiteral("</p>\n");
|
|
||||||
}
|
|
||||||
return html;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Split raw text into chunks of approximately kChunkSize characters,
|
|
||||||
// preferring to split at \n boundaries, falling back to whitespace.
|
|
||||||
static QStringList splitRawText(const QString &content)
|
|
||||||
{
|
|
||||||
QStringList rawChunks;
|
|
||||||
int pos = 0;
|
|
||||||
const int len = content.size();
|
|
||||||
|
|
||||||
while (pos < len) {
|
|
||||||
if (len - pos <= kChunkSize) {
|
|
||||||
rawChunks.append(content.mid(pos));
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
int end = pos + kChunkSize;
|
|
||||||
|
|
||||||
// Look backward for a newline to split at
|
|
||||||
int splitAt = -1;
|
|
||||||
for (int i = end; i > pos; --i) {
|
|
||||||
if (content.at(i) == '\n') {
|
|
||||||
splitAt = i + 1; // include the newline in the current chunk
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// No newline found — fall back to whitespace
|
|
||||||
if (splitAt < 0) {
|
|
||||||
for (int i = end; i > pos; --i) {
|
|
||||||
if (content.at(i).isSpace()) {
|
|
||||||
splitAt = i + 1;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// No whitespace either — hard split
|
|
||||||
if (splitAt < 0)
|
|
||||||
splitAt = end;
|
|
||||||
|
|
||||||
rawChunks.append(content.mid(pos, splitAt - pos));
|
|
||||||
pos = splitAt;
|
|
||||||
}
|
|
||||||
|
|
||||||
return rawChunks;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool TxtReader::open(const QString &filePath)
|
|
||||||
{
|
|
||||||
// Use std::ifstream to bypass Qt's CFStringGetFileSystemRepresentation() on macOS,
|
|
||||||
// which re-normalizes paths to NFD and breaks NFC filenames on SMB/ZFS mounts.
|
|
||||||
std::ifstream f(filePath.toUtf8().constData(), std::ios::binary | std::ios::ate);
|
|
||||||
if (!f) {
|
|
||||||
m_error = QStringLiteral("Cannot open file: ") + filePath;
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
const auto size = f.tellg();
|
|
||||||
f.seekg(0);
|
|
||||||
QByteArray raw(static_cast<int>(size), '\0');
|
|
||||||
f.read(raw.data(), size);
|
|
||||||
|
|
||||||
m_contentHash = QCryptographicHash::hash(raw, QCryptographicHash::Md5);
|
|
||||||
|
|
||||||
uchardet_t ud = uchardet_new();
|
|
||||||
if (uchardet_handle_data(ud, raw.constData(), raw.size()) == 0) {
|
|
||||||
uchardet_data_end(ud);
|
|
||||||
const char *charset = uchardet_get_charset(ud);
|
|
||||||
if (charset && charset[0] != '\0') {
|
|
||||||
auto qtEncoding = QStringConverter::encodingForName(charset);
|
|
||||||
if (qtEncoding) {
|
|
||||||
QTextStream stream(raw);
|
|
||||||
stream.setEncoding(qtEncoding.value());
|
|
||||||
m_content = stream.readAll();
|
|
||||||
} else {
|
|
||||||
m_content = decodeWithIconv(raw, charset);
|
|
||||||
}
|
|
||||||
uchardet_delete(ud);
|
|
||||||
if (!m_content.isEmpty()) {
|
|
||||||
m_title = QFileInfo(filePath).completeBaseName();
|
|
||||||
m_filePath = filePath;
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
uchardet_delete(ud);
|
|
||||||
|
|
||||||
// Default: UTF-8
|
|
||||||
m_content = QString::fromUtf8(raw);
|
|
||||||
m_title = QFileInfo(filePath).completeBaseName();
|
|
||||||
m_filePath = filePath;
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool TxtReader::loadMetadata(const QString &filePath)
|
|
||||||
{
|
|
||||||
if (!std::ifstream(filePath.toUtf8().constData())) {
|
|
||||||
m_error = QStringLiteral("File not found: ") + filePath;
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
// For TXT files, we only need the filename for title
|
|
||||||
m_title = QFileInfo(filePath).completeBaseName();
|
|
||||||
m_author.clear(); // No author info in plain text files
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
QString TxtReader::lastError()
|
|
||||||
{
|
|
||||||
return m_error;
|
|
||||||
}
|
|
||||||
|
|
||||||
int TxtReader::chapterCount()
|
|
||||||
{
|
|
||||||
return m_content.isEmpty() ? 0 : 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
Chapter TxtReader::loadChapter(int index)
|
|
||||||
{
|
|
||||||
if (index != 0 || m_content.isEmpty())
|
|
||||||
return Chapter{index, {}, {}};
|
|
||||||
|
|
||||||
QStringList rawChunks = splitRawText(m_content);
|
|
||||||
QStringList htmlChunks;
|
|
||||||
htmlChunks.reserve(rawChunks.size());
|
|
||||||
|
|
||||||
for (const QString &raw : rawChunks) {
|
|
||||||
QString html = textToHtml(raw);
|
|
||||||
if (!html.isEmpty())
|
|
||||||
htmlChunks.append(html);
|
|
||||||
}
|
|
||||||
|
|
||||||
return Chapter{0, m_title, htmlChunks};
|
|
||||||
}
|
|
||||||
|
|
||||||
QList<TocEntry> TxtReader::tableOfContents()
|
|
||||||
{
|
|
||||||
return {};
|
|
||||||
}
|
|
||||||
|
|
||||||
QString TxtReader::filePath()
|
|
||||||
{
|
|
||||||
return m_filePath;
|
|
||||||
}
|
|
||||||
|
|
||||||
QString TxtReader::title()
|
|
||||||
{
|
|
||||||
return m_title;
|
|
||||||
}
|
|
||||||
|
|
||||||
QString TxtReader::author()
|
|
||||||
{
|
|
||||||
return {};
|
|
||||||
}
|
|
||||||
|
|
||||||
QString TxtReader::coverImagePath()
|
|
||||||
{
|
|
||||||
return {};
|
|
||||||
}
|
|
||||||
|
|
||||||
QByteArray TxtReader::contentHash()
|
|
||||||
{
|
|
||||||
return m_contentHash;
|
|
||||||
}
|
|
||||||
|
|
||||||
QString TxtReader::fileType() const { return QStringLiteral("txt"); }
|
|
||||||
@@ -1,30 +0,0 @@
|
|||||||
#ifndef TXTREADER_H
|
|
||||||
#define TXTREADER_H
|
|
||||||
|
|
||||||
#include "backend/FormatReader.h"
|
|
||||||
|
|
||||||
class TxtReader : public FormatReader {
|
|
||||||
public:
|
|
||||||
bool open(const QString &filePath) override;
|
|
||||||
bool loadMetadata(const QString &filePath) override;
|
|
||||||
QString lastError() override;
|
|
||||||
int chapterCount() override;
|
|
||||||
Chapter loadChapter(int index) override;
|
|
||||||
QList<TocEntry> tableOfContents() override;
|
|
||||||
QString filePath() override;
|
|
||||||
QString title() override;
|
|
||||||
QString author() override;
|
|
||||||
QString coverImagePath() override;
|
|
||||||
QByteArray contentHash() override;
|
|
||||||
QString fileType() const override;
|
|
||||||
|
|
||||||
private:
|
|
||||||
QString m_content;
|
|
||||||
QString m_filePath;
|
|
||||||
QString m_title;
|
|
||||||
QString m_author;
|
|
||||||
QString m_error;
|
|
||||||
QByteArray m_contentHash;
|
|
||||||
};
|
|
||||||
|
|
||||||
#endif // TXTREADER_H
|
|
||||||
@@ -1,122 +0,0 @@
|
|||||||
#include "WebImageProvider.h"
|
|
||||||
|
|
||||||
#include <QCryptographicHash>
|
|
||||||
#include <QDir>
|
|
||||||
#include <QEventLoop>
|
|
||||||
#include <QFile>
|
|
||||||
#include <QFileInfo>
|
|
||||||
#include <QImage>
|
|
||||||
#include <QMutexLocker>
|
|
||||||
#include <QNetworkAccessManager>
|
|
||||||
#include <QNetworkReply>
|
|
||||||
#include <QNetworkRequest>
|
|
||||||
#include <QStandardPaths>
|
|
||||||
#include <QThreadPool>
|
|
||||||
|
|
||||||
#include "AsyncImageResponse.h"
|
|
||||||
#include "ImageScaling.h"
|
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
|
||||||
// Helpers
|
|
||||||
// ---------------------------------------------------------------------------
|
|
||||||
|
|
||||||
QString WebImageProvider::cacheDir()
|
|
||||||
{
|
|
||||||
return QStandardPaths::writableLocation(QStandardPaths::CacheLocation)
|
|
||||||
+ QStringLiteral("/web-images");
|
|
||||||
}
|
|
||||||
|
|
||||||
QString WebImageProvider::cacheFilePath(const QString &urlString)
|
|
||||||
{
|
|
||||||
const QByteArray hash =
|
|
||||||
QCryptographicHash::hash(urlString.toUtf8(), QCryptographicHash::Sha256).toHex();
|
|
||||||
const QString ext = QFileInfo(QUrl(urlString).path()).suffix();
|
|
||||||
return cacheDir() + QLatin1Char('/') + QString::fromLatin1(hash)
|
|
||||||
+ (ext.isEmpty() ? QString() : QLatin1Char('.') + ext);
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
|
||||||
// WebImageProvider
|
|
||||||
// ---------------------------------------------------------------------------
|
|
||||||
|
|
||||||
QImage WebImageProvider::loadWebImage(const QString &urlString,
|
|
||||||
const QSize &requestedSize)
|
|
||||||
{
|
|
||||||
if (urlString.isEmpty())
|
|
||||||
return {};
|
|
||||||
|
|
||||||
// Check cache first
|
|
||||||
const QString cachePath = cacheFilePath(urlString);
|
|
||||||
if (QFile::exists(cachePath)) {
|
|
||||||
QImage image;
|
|
||||||
if (image.load(cachePath))
|
|
||||||
return scaleToFit(image, requestedSize);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Download — blocking, safe to call from any thread via a local event loop
|
|
||||||
QNetworkAccessManager nam;
|
|
||||||
QNetworkRequest request{QUrl(urlString)};
|
|
||||||
request.setHeader(QNetworkRequest::UserAgentHeader, QStringLiteral("Asteria/1.0"));
|
|
||||||
request.setAttribute(QNetworkRequest::RedirectPolicyAttribute,
|
|
||||||
QNetworkRequest::NoLessSafeRedirectPolicy);
|
|
||||||
|
|
||||||
QNetworkReply *reply = nam.get(request);
|
|
||||||
|
|
||||||
QEventLoop loop;
|
|
||||||
QObject::connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit);
|
|
||||||
loop.exec();
|
|
||||||
|
|
||||||
if (reply->error() != QNetworkReply::NoError) {
|
|
||||||
reply->deleteLater();
|
|
||||||
return {};
|
|
||||||
}
|
|
||||||
|
|
||||||
const QByteArray data = reply->readAll();
|
|
||||||
reply->deleteLater();
|
|
||||||
|
|
||||||
if (data.isEmpty())
|
|
||||||
return {};
|
|
||||||
|
|
||||||
// Persist to cache
|
|
||||||
QDir().mkpath(cacheDir());
|
|
||||||
QFile f(cachePath);
|
|
||||||
if (f.open(QIODevice::WriteOnly)) {
|
|
||||||
f.write(data);
|
|
||||||
f.close();
|
|
||||||
}
|
|
||||||
|
|
||||||
QImage image;
|
|
||||||
if (!image.loadFromData(data))
|
|
||||||
return {};
|
|
||||||
|
|
||||||
return scaleToFit(image, requestedSize);
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
|
||||||
// WebImageProvider — IImageProvider
|
|
||||||
// ---------------------------------------------------------------------------
|
|
||||||
|
|
||||||
QQuickImageResponse *WebImageProvider::requestImageResponse(const QString &id,
|
|
||||||
const QSize &requestedSize)
|
|
||||||
{
|
|
||||||
// Warmup request: pre-creates QQuickPixmapReader on the main thread at
|
|
||||||
// startup so the render thread never creates it first (which would trigger
|
|
||||||
// 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 AsyncImageResponse([] { return QImage(); });
|
|
||||||
QMetaObject::invokeMethod(response, "finished", Qt::QueuedConnection);
|
|
||||||
return response;
|
|
||||||
}
|
|
||||||
|
|
||||||
auto *response = new AsyncImageResponse([id, requestedSize] {
|
|
||||||
return loadWebImage(id, requestedSize);
|
|
||||||
});
|
|
||||||
QThreadPool::globalInstance()->start(response);
|
|
||||||
return response;
|
|
||||||
}
|
|
||||||
|
|
||||||
QString WebImageProvider::scheme() const
|
|
||||||
{
|
|
||||||
return QStringLiteral("web");
|
|
||||||
}
|
|
||||||
@@ -1,24 +0,0 @@
|
|||||||
#pragma once
|
|
||||||
|
|
||||||
#include <QSize>
|
|
||||||
#include <QString>
|
|
||||||
|
|
||||||
#include "backend/IImageProvider.h"
|
|
||||||
|
|
||||||
class WebImageProvider : public IImageProvider {
|
|
||||||
public:
|
|
||||||
QQuickImageResponse *requestImageResponse(const QString &id,
|
|
||||||
const QSize &requestedSize) override;
|
|
||||||
|
|
||||||
void setFilePath(const QString &) override {}
|
|
||||||
void clear() override {}
|
|
||||||
QString coverImageUrl(const QString &) const override { return {}; }
|
|
||||||
QString scheme() const override;
|
|
||||||
|
|
||||||
// Download (or load from disk cache) a web image. Thread-safe, may block.
|
|
||||||
static QImage loadWebImage(const QString &urlString,
|
|
||||||
const QSize &requestedSize);
|
|
||||||
|
|
||||||
static QString cacheDir();
|
|
||||||
static QString cacheFilePath(const QString &urlString);
|
|
||||||
};
|
|
||||||
@@ -164,39 +164,20 @@ bool ComicReader::loadMetadata(const QString &filePath)
|
|||||||
return parseSource(filePath);
|
return parseSource(filePath);
|
||||||
}
|
}
|
||||||
|
|
||||||
Chapter ComicReader::loadChapter(int index)
|
QVector<PageInfo> ComicReader::pages() const
|
||||||
{
|
{
|
||||||
if (index != 0 || m_pageEntries.isEmpty())
|
QVector<PageInfo> result;
|
||||||
return Chapter{index, {}, {}};
|
result.reserve(m_pageEntries.size());
|
||||||
|
|
||||||
QStringList chunks;
|
|
||||||
chunks.reserve(m_pageEntries.size());
|
|
||||||
for (const PageEntry &page : m_pageEntries) {
|
for (const PageEntry &page : m_pageEntries) {
|
||||||
chunks.append(QStringLiteral("<p style=\"text-align:center;margin:0\">"
|
result.append({ImageUrl::build(m_scheme, page.entry), page.naturalSize});
|
||||||
"<img src=\"%1\"/></p>")
|
|
||||||
.arg(ImageUrl::build(m_scheme, page.entry)));
|
|
||||||
}
|
}
|
||||||
return Chapter{0, m_title, chunks};
|
return result;
|
||||||
}
|
|
||||||
|
|
||||||
QVector<QSize> ComicReader::chapterPageSizes(int chapterIndex) const
|
|
||||||
{
|
|
||||||
if (chapterIndex != 0 || m_pageEntries.isEmpty())
|
|
||||||
return {};
|
|
||||||
QVector<QSize> sizes;
|
|
||||||
sizes.reserve(m_pageEntries.size());
|
|
||||||
for (const PageEntry &page : m_pageEntries)
|
|
||||||
sizes.append(page.naturalSize);
|
|
||||||
return sizes;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
QString ComicReader::lastError() { return m_error; }
|
QString ComicReader::lastError() { return m_error; }
|
||||||
QString ComicReader::title() { return m_title; }
|
QString ComicReader::title() { return m_title; }
|
||||||
QString ComicReader::author() { return m_author; }
|
QString ComicReader::author() { return m_author; }
|
||||||
QString ComicReader::coverImagePath() { return m_coverEntry; }
|
QString ComicReader::coverImagePath() { return m_coverEntry; }
|
||||||
int ComicReader::chapterCount() { return m_pageEntries.isEmpty() ? 0 : 1; }
|
|
||||||
QString ComicReader::filePath() { return m_filePath; }
|
QString ComicReader::filePath() { return m_filePath; }
|
||||||
QByteArray ComicReader::contentHash() { return m_contentHash; }
|
QByteArray ComicReader::contentHash() { return m_contentHash; }
|
||||||
QString ComicReader::fileType() const { return m_fileType; }
|
QString ComicReader::fileType() const { return m_fileType; }
|
||||||
|
|
||||||
QList<TocEntry> ComicReader::tableOfContents() { return {}; }
|
|
||||||
@@ -6,9 +6,8 @@
|
|||||||
#include <functional>
|
#include <functional>
|
||||||
#include <memory>
|
#include <memory>
|
||||||
#include <QByteArray>
|
#include <QByteArray>
|
||||||
#include <QList>
|
|
||||||
#include <QSize>
|
#include <QSize>
|
||||||
#include <QStringList>
|
#include <QString>
|
||||||
#include <QVector>
|
#include <QVector>
|
||||||
|
|
||||||
class ComicReader : public FormatReader {
|
class ComicReader : public FormatReader {
|
||||||
@@ -20,9 +19,6 @@ public:
|
|||||||
bool open(const QString &filePath) override;
|
bool open(const QString &filePath) override;
|
||||||
bool loadMetadata(const QString &filePath) override;
|
bool loadMetadata(const QString &filePath) override;
|
||||||
QString lastError() override;
|
QString lastError() override;
|
||||||
int chapterCount() override;
|
|
||||||
Chapter loadChapter(int index) override;
|
|
||||||
QList<TocEntry> tableOfContents() override;
|
|
||||||
QString filePath() override;
|
QString filePath() override;
|
||||||
QString title() override;
|
QString title() override;
|
||||||
QString author() override;
|
QString author() override;
|
||||||
@@ -30,8 +26,7 @@ public:
|
|||||||
QByteArray contentHash() override;
|
QByteArray contentHash() override;
|
||||||
QString fileType() const override;
|
QString fileType() const override;
|
||||||
|
|
||||||
RenderingMode preferredRenderingMode() const override { return RenderingMode::Manga; }
|
QVector<PageInfo> pages() const override;
|
||||||
QVector<QSize> chapterPageSizes(int chapterIndex) const override;
|
|
||||||
|
|
||||||
private:
|
private:
|
||||||
struct PageEntry {
|
struct PageEntry {
|
||||||
|
|||||||
@@ -1,88 +0,0 @@
|
|||||||
#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;
|
|
||||||
}
|
|
||||||
@@ -1,20 +0,0 @@
|
|||||||
#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;
|
|
||||||
};
|
|
||||||
@@ -13,18 +13,13 @@
|
|||||||
#include "backend/AppState.h"
|
#include "backend/AppState.h"
|
||||||
#include "backend/formats/FileIconProvider.h"
|
#include "backend/formats/FileIconProvider.h"
|
||||||
#include "backend/formats/FormatRegistry.h"
|
#include "backend/formats/FormatRegistry.h"
|
||||||
#include "backend/formats/WebImageProvider.h"
|
|
||||||
#include "backend/formats/sources/DirByteSource.h"
|
#include "backend/formats/sources/DirByteSource.h"
|
||||||
#include "backend/formats/sources/Fb2ByteSource.h"
|
|
||||||
#include "backend/formats/sources/RarByteSource.h"
|
#include "backend/formats/sources/RarByteSource.h"
|
||||||
#include "backend/formats/sources/ZipByteSource.h"
|
#include "backend/formats/sources/ZipByteSource.h"
|
||||||
#include "backend/HistoryModel.h"
|
#include "backend/HistoryModel.h"
|
||||||
#include "backend/ReadingModel.h"
|
#include "backend/ReadingModel.h"
|
||||||
#include "backend/NativeFileDialogService.h"
|
#include "backend/NativeFileDialogService.h"
|
||||||
#include "backend/book/Book.h"
|
#include "backend/book/Book.h"
|
||||||
#include "backend/formats/TxtReader.h"
|
|
||||||
#include "backend/formats/EpubReader.h"
|
|
||||||
#include "backend/formats/Fb2Reader.h"
|
|
||||||
#include "backend/formats/comic/CbzReader.h"
|
#include "backend/formats/comic/CbzReader.h"
|
||||||
#include "backend/formats/comic/CbrReader.h"
|
#include "backend/formats/comic/CbrReader.h"
|
||||||
#include "backend/formats/comic/FolderReader.h"
|
#include "backend/formats/comic/FolderReader.h"
|
||||||
@@ -107,14 +102,6 @@ int main(int argc, char *argv[])
|
|||||||
|
|
||||||
// The format table: one row declares everything a format needs.
|
// The format table: one row declares everything a format needs.
|
||||||
FormatRegistry formatRegistry({
|
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>(); }},
|
|
||||||
{QStringLiteral("fb2"), false, QStringLiteral("fb2"),
|
|
||||||
[] { return std::make_unique<Fb2Reader>(); },
|
|
||||||
[] { return std::make_unique<Fb2ByteSource>(); }},
|
|
||||||
{QStringLiteral("cbz"), false, QStringLiteral("cbz"),
|
{QStringLiteral("cbz"), false, QStringLiteral("cbz"),
|
||||||
[] { return std::make_unique<CbzReader>(); },
|
[] { return std::make_unique<CbzReader>(); },
|
||||||
[] { return std::make_unique<ZipByteSource>(); }},
|
[] { return std::make_unique<ZipByteSource>(); }},
|
||||||
@@ -159,7 +146,6 @@ int main(int argc, char *argv[])
|
|||||||
|
|
||||||
// --- QML engine ---
|
// --- QML engine ---
|
||||||
QQmlApplicationEngine engine;
|
QQmlApplicationEngine engine;
|
||||||
engine.addImageProvider(QStringLiteral("web"), new WebImageProvider());
|
|
||||||
engine.addImageProvider(QStringLiteral("fileicon"), new FileIconProvider());
|
engine.addImageProvider(QStringLiteral("fileicon"), new FileIconProvider());
|
||||||
formatRegistry.registerImageProviders(engine);
|
formatRegistry.registerImageProviders(engine);
|
||||||
engine.rootContext()->setContextProperty(QStringLiteral("isDebugBuild"),
|
engine.rootContext()->setContextProperty(QStringLiteral("isDebugBuild"),
|
||||||
|
|||||||
+4
-4
@@ -213,7 +213,7 @@ ApplicationWindow {
|
|||||||
sequence: "Left"
|
sequence: "Left"
|
||||||
context: Qt.ApplicationShortcut
|
context: Qt.ApplicationShortcut
|
||||||
onActivated: {
|
onActivated: {
|
||||||
if (currentPage === "reader" && readerPage?.pageView && readingModel.isMangaMode) {
|
if (currentPage === "reader" && readerPage?.pageView) {
|
||||||
readingModel.mangaRTL ? readerPage.pageView.handleScrollDown()
|
readingModel.mangaRTL ? readerPage.pageView.handleScrollDown()
|
||||||
: readerPage.pageView.handleScrollUp();
|
: readerPage.pageView.handleScrollUp();
|
||||||
}
|
}
|
||||||
@@ -223,7 +223,7 @@ ApplicationWindow {
|
|||||||
sequence: "Right"
|
sequence: "Right"
|
||||||
context: Qt.ApplicationShortcut
|
context: Qt.ApplicationShortcut
|
||||||
onActivated: {
|
onActivated: {
|
||||||
if (currentPage === "reader" && readerPage?.pageView && readingModel.isMangaMode) {
|
if (currentPage === "reader" && readerPage?.pageView) {
|
||||||
readingModel.mangaRTL ? readerPage.pageView.handleScrollUp()
|
readingModel.mangaRTL ? readerPage.pageView.handleScrollUp()
|
||||||
: readerPage.pageView.handleScrollDown();
|
: readerPage.pageView.handleScrollDown();
|
||||||
}
|
}
|
||||||
@@ -278,7 +278,7 @@ ApplicationWindow {
|
|||||||
sequence: "M"
|
sequence: "M"
|
||||||
context: Qt.ApplicationShortcut
|
context: Qt.ApplicationShortcut
|
||||||
onActivated: {
|
onActivated: {
|
||||||
if (currentPage === "reader" && readingModel.isMangaMode)
|
if (currentPage === "reader")
|
||||||
readingModel.setMangaRTL(!readingModel.mangaRTL)
|
readingModel.setMangaRTL(!readingModel.mangaRTL)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -286,7 +286,7 @@ ApplicationWindow {
|
|||||||
sequence: "S"
|
sequence: "S"
|
||||||
context: Qt.ApplicationShortcut
|
context: Qt.ApplicationShortcut
|
||||||
onActivated: {
|
onActivated: {
|
||||||
if (currentPage === "reader" && readingModel.isMangaMode)
|
if (currentPage === "reader")
|
||||||
readingModel.setPageShift(!readingModel.pageShift, readerPage.pageView.currentPair)
|
readingModel.setPageShift(!readingModel.pageShift, readerPage.pageView.currentPair)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,12 +13,11 @@ Rectangle {
|
|||||||
anchors.top: parent.top
|
anchors.top: parent.top
|
||||||
}
|
}
|
||||||
|
|
||||||
// RTL reading direction toggle (manga mode only).
|
// RTL reading direction toggle.
|
||||||
FlatIconButton {
|
FlatIconButton {
|
||||||
anchors.left: parent.left
|
anchors.left: parent.left
|
||||||
anchors.leftMargin: 16
|
anchors.leftMargin: 16
|
||||||
anchors.verticalCenter: parent.verticalCenter
|
anchors.verticalCenter: parent.verticalCenter
|
||||||
visible: readingModel.isMangaMode
|
|
||||||
padding: 0
|
padding: 0
|
||||||
implicitWidth: 24
|
implicitWidth: 24
|
||||||
implicitHeight: 24
|
implicitHeight: 24
|
||||||
@@ -29,12 +28,11 @@ Rectangle {
|
|||||||
onClicked: readingModel.setMangaRTL(!readingModel.mangaRTL)
|
onClicked: readingModel.setMangaRTL(!readingModel.mangaRTL)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Page-shift toggle (manga mode only). Shifts page 1 to be displayed alone after the cover.
|
// Page-shift toggle. Shifts page 1 to be displayed alone after the cover.
|
||||||
FlatIconButton {
|
FlatIconButton {
|
||||||
anchors.left: parent.left
|
anchors.left: parent.left
|
||||||
anchors.leftMargin: 44
|
anchors.leftMargin: 44
|
||||||
anchors.verticalCenter: parent.verticalCenter
|
anchors.verticalCenter: parent.verticalCenter
|
||||||
visible: readingModel.isMangaMode
|
|
||||||
padding: 0
|
padding: 0
|
||||||
implicitWidth: 24
|
implicitWidth: 24
|
||||||
implicitHeight: 24
|
implicitHeight: 24
|
||||||
@@ -48,50 +46,6 @@ Rectangle {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Prev chapter 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
|
|
||||||
padding: 0
|
|
||||||
implicitWidth: 20
|
|
||||||
implicitHeight: 20
|
|
||||||
iconText: ""
|
|
||||||
iconColor: prevBtn.enabled ? ThemeManager.currentTheme.dimText : ThemeManager.currentTheme.actionDisabled
|
|
||||||
tooltip: "Previous chapter"
|
|
||||||
onClicked: readingModel.previousChapter()
|
|
||||||
}
|
|
||||||
|
|
||||||
Text {
|
|
||||||
id: chapterText
|
|
||||||
anchors.verticalCenter: parent.verticalCenter
|
|
||||||
anchors.horizontalCenter: parent.horizontalCenter
|
|
||||||
text: book.hasBook && readingModel.hasChapters
|
|
||||||
? "Chapter " + (readingModel.currentChapter + 1) + " / " + readingModel.totalChapters
|
|
||||||
: ""
|
|
||||||
font.pixelSize: 11
|
|
||||||
font.bold: true
|
|
||||||
color: ThemeManager.currentTheme.dimText
|
|
||||||
}
|
|
||||||
|
|
||||||
// Next chapter 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
|
|
||||||
padding: 0
|
|
||||||
implicitWidth: 20
|
|
||||||
implicitHeight: 20
|
|
||||||
iconText: ""
|
|
||||||
iconColor: nextBtn.enabled ? ThemeManager.currentTheme.dimText : ThemeManager.currentTheme.actionDisabled
|
|
||||||
tooltip: "Next chapter"
|
|
||||||
onClicked: readingModel.nextChapter()
|
|
||||||
}
|
|
||||||
|
|
||||||
Text {
|
Text {
|
||||||
anchors.right: parent.right
|
anchors.right: parent.right
|
||||||
anchors.rightMargin: 16
|
anchors.rightMargin: 16
|
||||||
|
|||||||
@@ -194,9 +194,6 @@ Rectangle {
|
|||||||
contentReady = true
|
contentReady = true
|
||||||
showPair(readingModel.pairIndexForChunk(chunkIndex))
|
showPair(readingModel.pairIndexForChunk(chunkIndex))
|
||||||
}
|
}
|
||||||
function onScrollToChunkRequested(chunkIndex) {
|
|
||||||
showPair(readingModel.pairIndexForChunk(chunkIndex))
|
|
||||||
}
|
|
||||||
function onTotalPagePairsChanged() {
|
function onTotalPagePairsChanged() {
|
||||||
// Re-clamp after pair rebuild (resize / orientation flip).
|
// Re-clamp after pair rebuild (resize / orientation flip).
|
||||||
showPair(Math.min(currentPair, Math.max(0, readingModel.totalPagePairs - 1)))
|
showPair(Math.min(currentPair, Math.max(0, readingModel.totalPagePairs - 1)))
|
||||||
|
|||||||
@@ -118,70 +118,4 @@ Rectangle {
|
|||||||
onClicked: sidebar.navigateTo("settings")
|
onClicked: sidebar.navigateTo("settings")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TOC section — shown when the current book has a table of contents
|
|
||||||
Item {
|
|
||||||
visible: book.hasBook && book.toc.length > 0
|
|
||||||
anchors.top: navColumn.bottom
|
|
||||||
anchors.bottom: parent.bottom
|
|
||||||
width: parent.width
|
|
||||||
|
|
||||||
Rectangle {
|
|
||||||
id: tocDivider
|
|
||||||
width: parent.width
|
|
||||||
height: 1
|
|
||||||
color: ThemeManager.currentTheme.divider
|
|
||||||
}
|
|
||||||
|
|
||||||
Text {
|
|
||||||
id: tocLabel
|
|
||||||
anchors.top: tocDivider.bottom
|
|
||||||
anchors.topMargin: 8
|
|
||||||
anchors.left: parent.left
|
|
||||||
anchors.leftMargin: 16
|
|
||||||
text: "Contents"
|
|
||||||
font.pixelSize: 10
|
|
||||||
font.bold: true
|
|
||||||
color: ThemeManager.currentTheme.dimText
|
|
||||||
font.letterSpacing: 1
|
|
||||||
}
|
|
||||||
|
|
||||||
ListView {
|
|
||||||
anchors.top: tocLabel.bottom
|
|
||||||
anchors.topMargin: 4
|
|
||||||
anchors.bottom: parent.bottom
|
|
||||||
width: parent.width
|
|
||||||
clip: true
|
|
||||||
model: book.toc
|
|
||||||
|
|
||||||
delegate: Rectangle {
|
|
||||||
width: ListView.view.width
|
|
||||||
height: tocEntryText.implicitHeight + 10
|
|
||||||
color: readingModel.currentChapter === modelData.chapterIndex
|
|
||||||
? Qt.rgba(1, 1, 1, 0.05)
|
|
||||||
: "transparent"
|
|
||||||
|
|
||||||
Text {
|
|
||||||
id: tocEntryText
|
|
||||||
anchors.verticalCenter: parent.verticalCenter
|
|
||||||
x: 16 + modelData.depth * 12
|
|
||||||
width: parent.width - x - 8
|
|
||||||
text: modelData.title
|
|
||||||
font.pixelSize: 13
|
|
||||||
color: readingModel.currentChapter === modelData.chapterIndex
|
|
||||||
? ThemeManager.currentTheme.sidebarButtonText
|
|
||||||
: ThemeManager.currentTheme.uiText
|
|
||||||
elide: Text.ElideRight
|
|
||||||
wrapMode: Text.NoWrap
|
|
||||||
}
|
|
||||||
|
|
||||||
MouseArea {
|
|
||||||
anchors.fill: parent
|
|
||||||
onClicked: {
|
|
||||||
readingModel.goToChapter(modelData.chapterIndex)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -12,23 +12,22 @@
|
|||||||
|
|
||||||
#include "backend/formats/AsyncImageResponse.h"
|
#include "backend/formats/AsyncImageResponse.h"
|
||||||
#include "backend/formats/EntryImageProvider.h"
|
#include "backend/formats/EntryImageProvider.h"
|
||||||
#include "backend/formats/sources/Fb2ByteSource.h"
|
|
||||||
#include "backend/formats/sources/ZipByteSource.h"
|
#include "backend/formats/sources/ZipByteSource.h"
|
||||||
|
|
||||||
// Load one zip member through the generic byte-source pipeline (EPUBs are zips).
|
// Load one zip member through the generic byte-source pipeline (CBZs are zips).
|
||||||
static QImage loadFromEpub(const QString &epubPath, const QString &entry,
|
static QImage loadFromCbz(const QString &cbzPath, const QString &entry,
|
||||||
const QSize &requestedSize)
|
const QSize &requestedSize)
|
||||||
{
|
{
|
||||||
ZipByteSource source;
|
ZipByteSource source;
|
||||||
if (!source.open(epubPath))
|
if (!source.open(cbzPath))
|
||||||
return {};
|
return {};
|
||||||
return EntryImageProvider::loadImageFromSource(source, entry, requestedSize);
|
return EntryImageProvider::loadImageFromSource(source, entry, requestedSize);
|
||||||
}
|
}
|
||||||
|
|
||||||
static EntryImageProvider makeEpubProvider()
|
static EntryImageProvider makeCbzProvider()
|
||||||
{
|
{
|
||||||
return EntryImageProvider([] { return std::make_unique<ZipByteSource>(); },
|
return EntryImageProvider([] { return std::make_unique<ZipByteSource>(); },
|
||||||
QStringLiteral("epub"));
|
QStringLiteral("cbz"));
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
@@ -61,13 +60,13 @@ static QByteArray makePng(int w, int h, QRgb color = qRgb(255, 0, 0))
|
|||||||
return data;
|
return data;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Build a minimal EPUB-like ZIP containing a single image entry.
|
// Build a minimal CBZ containing a single image entry.
|
||||||
// Returns the path of the temp file (caller removes).
|
// Returns the path of the temp file (caller removes).
|
||||||
static QString buildEpubWithPng(const char *entryPath, int imgW, int imgH,
|
static QString buildCbzWithPng(const char *entryPath, int imgW, int imgH,
|
||||||
QRgb color = qRgb(255, 0, 0))
|
QRgb color = qRgb(255, 0, 0))
|
||||||
{
|
{
|
||||||
QTemporaryFile tmp;
|
QTemporaryFile tmp;
|
||||||
tmp.setFileTemplate(QDir::tempPath() + "/provider_test_XXXXXX.epub");
|
tmp.setFileTemplate(QDir::tempPath() + "/provider_test_XXXXXX.cbz");
|
||||||
tmp.setAutoRemove(false);
|
tmp.setAutoRemove(false);
|
||||||
if (!tmp.open()) return {};
|
if (!tmp.open()) return {};
|
||||||
const QString path = tmp.fileName();
|
const QString path = tmp.fileName();
|
||||||
@@ -91,13 +90,13 @@ class EntryImageProviderTest : public QObject {
|
|||||||
private slots:
|
private slots:
|
||||||
void requestImageReturnsValidImage()
|
void requestImageReturnsValidImage()
|
||||||
{
|
{
|
||||||
const QString epubPath = buildEpubWithPng("OEBPS/Images/test.png", 4, 4);
|
const QString cbzPath = buildCbzWithPng("images/test.png", 4, 4);
|
||||||
QVERIFY(!epubPath.isEmpty());
|
QVERIFY(!cbzPath.isEmpty());
|
||||||
|
|
||||||
const QImage img = loadFromEpub(
|
const QImage img = loadFromCbz(
|
||||||
epubPath, QStringLiteral("OEBPS/Images/test.png"), QSize());
|
cbzPath, QStringLiteral("images/test.png"), QSize());
|
||||||
|
|
||||||
QFile::remove(epubPath);
|
QFile::remove(cbzPath);
|
||||||
|
|
||||||
QVERIFY(!img.isNull());
|
QVERIFY(!img.isNull());
|
||||||
QCOMPARE(img.width(), 4);
|
QCOMPARE(img.width(), 4);
|
||||||
@@ -107,47 +106,46 @@ private slots:
|
|||||||
|
|
||||||
void requestImageReturnsNullForMissingEntry()
|
void requestImageReturnsNullForMissingEntry()
|
||||||
{
|
{
|
||||||
const QString epubPath = buildEpubWithPng("OEBPS/Images/test.png", 4, 4);
|
const QString cbzPath = buildCbzWithPng("images/test.png", 4, 4);
|
||||||
QVERIFY(!epubPath.isEmpty());
|
QVERIFY(!cbzPath.isEmpty());
|
||||||
|
|
||||||
const QImage img = loadFromEpub(
|
const QImage img = loadFromCbz(
|
||||||
epubPath, QStringLiteral("OEBPS/Images/nonexistent.png"), QSize());
|
cbzPath, QStringLiteral("images/nonexistent.png"), QSize());
|
||||||
|
|
||||||
QFile::remove(epubPath);
|
QFile::remove(cbzPath);
|
||||||
|
|
||||||
QVERIFY(img.isNull());
|
QVERIFY(img.isNull());
|
||||||
}
|
}
|
||||||
|
|
||||||
void requestImageReturnsNullWhenNoPath()
|
void requestImageReturnsNullWhenNoPath()
|
||||||
{
|
{
|
||||||
const QImage img = loadFromEpub(
|
const QImage img = loadFromCbz(
|
||||||
QString{}, QStringLiteral("OEBPS/Images/test.png"), QSize());
|
QString{}, QStringLiteral("images/test.png"), QSize());
|
||||||
QVERIFY(img.isNull());
|
QVERIFY(img.isNull());
|
||||||
}
|
}
|
||||||
|
|
||||||
void clearResetsState()
|
void clearResetsState()
|
||||||
{
|
{
|
||||||
const QString epubPath = buildEpubWithPng("OEBPS/Images/test.png", 4, 4);
|
const QString cbzPath = buildCbzWithPng("images/test.png", 4, 4);
|
||||||
QVERIFY(!epubPath.isEmpty());
|
QVERIFY(!cbzPath.isEmpty());
|
||||||
|
|
||||||
// After clear the path is empty, so loadImageFromEpub with empty path returns null
|
const QImage img = loadFromCbz(
|
||||||
const QImage img = loadFromEpub(
|
QString{}, QStringLiteral("images/test.png"), QSize());
|
||||||
QString{}, QStringLiteral("OEBPS/Images/test.png"), QSize());
|
|
||||||
|
|
||||||
QFile::remove(epubPath);
|
QFile::remove(cbzPath);
|
||||||
|
|
||||||
QVERIFY(img.isNull());
|
QVERIFY(img.isNull());
|
||||||
}
|
}
|
||||||
|
|
||||||
void requestedSizeHonored()
|
void requestedSizeHonored()
|
||||||
{
|
{
|
||||||
const QString epubPath = buildEpubWithPng("img.png", 400, 300);
|
const QString cbzPath = buildCbzWithPng("img.png", 400, 300);
|
||||||
QVERIFY(!epubPath.isEmpty());
|
QVERIFY(!cbzPath.isEmpty());
|
||||||
|
|
||||||
const QImage img = loadFromEpub(
|
const QImage img = loadFromCbz(
|
||||||
epubPath, QStringLiteral("img.png"), QSize(200, -1));
|
cbzPath, QStringLiteral("img.png"), QSize(200, -1));
|
||||||
|
|
||||||
QFile::remove(epubPath);
|
QFile::remove(cbzPath);
|
||||||
|
|
||||||
QVERIFY(!img.isNull());
|
QVERIFY(!img.isNull());
|
||||||
QCOMPARE(img.width(), 200);
|
QCOMPARE(img.width(), 200);
|
||||||
@@ -159,17 +157,17 @@ private slots:
|
|||||||
|
|
||||||
void asyncResponseEmitsFinished()
|
void asyncResponseEmitsFinished()
|
||||||
{
|
{
|
||||||
const QString epubPath = buildEpubWithPng("img.png", 4, 4);
|
const QString cbzPath = buildCbzWithPng("img.png", 4, 4);
|
||||||
QVERIFY(!epubPath.isEmpty());
|
QVERIFY(!cbzPath.isEmpty());
|
||||||
|
|
||||||
AsyncImageResponse response([epubPath] {
|
AsyncImageResponse response([cbzPath] {
|
||||||
return loadFromEpub(
|
return loadFromCbz(
|
||||||
epubPath, QStringLiteral("img.png"), QSize());
|
cbzPath, QStringLiteral("img.png"), QSize());
|
||||||
});
|
});
|
||||||
QSignalSpy spy(&response, &QQuickImageResponse::finished);
|
QSignalSpy spy(&response, &QQuickImageResponse::finished);
|
||||||
response.run();
|
response.run();
|
||||||
|
|
||||||
QFile::remove(epubPath);
|
QFile::remove(cbzPath);
|
||||||
|
|
||||||
QCOMPARE(spy.count(), 1);
|
QCOMPARE(spy.count(), 1);
|
||||||
QVERIFY(response.textureFactory() != nullptr);
|
QVERIFY(response.textureFactory() != nullptr);
|
||||||
@@ -177,35 +175,35 @@ private slots:
|
|||||||
|
|
||||||
void cancelledResponseDoesNotEmitFinished()
|
void cancelledResponseDoesNotEmitFinished()
|
||||||
{
|
{
|
||||||
const QString epubPath = buildEpubWithPng("img.png", 4, 4);
|
const QString cbzPath = buildCbzWithPng("img.png", 4, 4);
|
||||||
QVERIFY(!epubPath.isEmpty());
|
QVERIFY(!cbzPath.isEmpty());
|
||||||
|
|
||||||
AsyncImageResponse response([epubPath] {
|
AsyncImageResponse response([cbzPath] {
|
||||||
return loadFromEpub(
|
return loadFromCbz(
|
||||||
epubPath, QStringLiteral("img.png"), QSize());
|
cbzPath, QStringLiteral("img.png"), QSize());
|
||||||
});
|
});
|
||||||
QSignalSpy spy(&response, &QQuickImageResponse::finished);
|
QSignalSpy spy(&response, &QQuickImageResponse::finished);
|
||||||
response.cancel();
|
response.cancel();
|
||||||
response.run();
|
response.run();
|
||||||
|
|
||||||
QFile::remove(epubPath);
|
QFile::remove(cbzPath);
|
||||||
|
|
||||||
QCOMPARE(spy.count(), 0);
|
QCOMPARE(spy.count(), 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
void cancelledTextureFactoryIsNull()
|
void cancelledTextureFactoryIsNull()
|
||||||
{
|
{
|
||||||
const QString epubPath = buildEpubWithPng("img.png", 4, 4);
|
const QString cbzPath = buildCbzWithPng("img.png", 4, 4);
|
||||||
QVERIFY(!epubPath.isEmpty());
|
QVERIFY(!cbzPath.isEmpty());
|
||||||
|
|
||||||
AsyncImageResponse response([epubPath] {
|
AsyncImageResponse response([cbzPath] {
|
||||||
return loadFromEpub(
|
return loadFromCbz(
|
||||||
epubPath, QStringLiteral("img.png"), QSize());
|
cbzPath, QStringLiteral("img.png"), QSize());
|
||||||
});
|
});
|
||||||
response.cancel();
|
response.cancel();
|
||||||
response.run();
|
response.run();
|
||||||
|
|
||||||
QFile::remove(epubPath);
|
QFile::remove(cbzPath);
|
||||||
|
|
||||||
QVERIFY(response.textureFactory() == nullptr);
|
QVERIFY(response.textureFactory() == nullptr);
|
||||||
}
|
}
|
||||||
@@ -214,39 +212,36 @@ private slots:
|
|||||||
// Embedded-path URL format tests
|
// Embedded-path URL format tests
|
||||||
// -----------------------------------------------------------------------
|
// -----------------------------------------------------------------------
|
||||||
|
|
||||||
void coverImageUrlEmbedsEpubPath()
|
void coverImageUrlEmbedsCbzPath()
|
||||||
{
|
{
|
||||||
const QString epubPath = buildEpubWithPng("img.png", 4, 4);
|
const QString cbzPath = buildCbzWithPng("img.png", 4, 4);
|
||||||
QVERIFY(!epubPath.isEmpty());
|
QVERIFY(!cbzPath.isEmpty());
|
||||||
|
|
||||||
EntryImageProvider provider = makeEpubProvider();
|
EntryImageProvider provider = makeCbzProvider();
|
||||||
provider.setFilePath(epubPath);
|
provider.setFilePath(cbzPath);
|
||||||
|
|
||||||
const QString url = provider.coverImageUrl(QStringLiteral("OEBPS/cover.jpg"));
|
const QString url = provider.coverImageUrl(QStringLiteral("cover.jpg"));
|
||||||
|
|
||||||
QFile::remove(epubPath);
|
QFile::remove(cbzPath);
|
||||||
|
|
||||||
// New format: image://epub/<internal-path>?src=<encoded-epub-path>
|
QVERIFY2(url.startsWith(QStringLiteral("image://cbz/cover.jpg?src=")),
|
||||||
QVERIFY2(url.startsWith(QStringLiteral("image://epub/OEBPS/cover.jpg?src=")),
|
|
||||||
qPrintable("Expected query-param URL, got: " + url));
|
qPrintable("Expected query-param URL, got: " + url));
|
||||||
const QString encodedPath = QString::fromUtf8(QUrl::toPercentEncoding(epubPath));
|
const QString encodedPath = QString::fromUtf8(QUrl::toPercentEncoding(cbzPath));
|
||||||
QVERIFY2(url.contains(encodedPath),
|
QVERIFY2(url.contains(encodedPath),
|
||||||
qPrintable("URL should contain encoded epub path. URL: " + url));
|
qPrintable("URL should contain encoded cbz path. URL: " + url));
|
||||||
}
|
}
|
||||||
|
|
||||||
void requestImageResponseUsesEmbeddedPath()
|
void requestImageResponseUsesEmbeddedPath()
|
||||||
{
|
{
|
||||||
// Build two EPUBs with different color images; prove the embedded path in the URL
|
const QString cbzA = buildCbzWithPng("img.png", 4, 4, qRgb(255, 0, 0));
|
||||||
// overrides m_epubPath on the provider.
|
const QString cbzB = buildCbzWithPng("img.png", 4, 4, qRgb(0, 255, 0));
|
||||||
const QString epubA = buildEpubWithPng("img.png", 4, 4, qRgb(255, 0, 0));
|
QVERIFY(!cbzA.isEmpty() && !cbzB.isEmpty());
|
||||||
const QString epubB = buildEpubWithPng("img.png", 4, 4, qRgb(0, 255, 0));
|
|
||||||
QVERIFY(!epubA.isEmpty() && !epubB.isEmpty());
|
|
||||||
|
|
||||||
EntryImageProvider provider = makeEpubProvider();
|
EntryImageProvider provider = makeCbzProvider();
|
||||||
provider.setFilePath(epubA); // configured for A
|
provider.setFilePath(cbzA); // configured for A
|
||||||
|
|
||||||
// Build an embedded-format id pointing to B via query parameter
|
// Build an embedded-format id pointing to B via query parameter
|
||||||
const QString encodedB = QString::fromUtf8(QUrl::toPercentEncoding(epubB));
|
const QString encodedB = QString::fromUtf8(QUrl::toPercentEncoding(cbzB));
|
||||||
const QString id = QStringLiteral("img.png?src=") + encodedB;
|
const QString id = QStringLiteral("img.png?src=") + encodedB;
|
||||||
|
|
||||||
QQuickImageResponse *resp = provider.requestImageResponse(id, QSize());
|
QQuickImageResponse *resp = provider.requestImageResponse(id, QSize());
|
||||||
@@ -254,11 +249,10 @@ private slots:
|
|||||||
QThreadPool::globalInstance()->waitForDone();
|
QThreadPool::globalInstance()->waitForDone();
|
||||||
if (spy.isEmpty()) spy.wait(5000);
|
if (spy.isEmpty()) spy.wait(5000);
|
||||||
|
|
||||||
QFile::remove(epubA);
|
QFile::remove(cbzA);
|
||||||
QFile::remove(epubB);
|
QFile::remove(cbzB);
|
||||||
|
|
||||||
QVERIFY(resp->textureFactory() != nullptr);
|
QVERIFY(resp->textureFactory() != nullptr);
|
||||||
// The loaded image should be green (from B), not red (from A)
|
|
||||||
const QImage img = resp->textureFactory()->image();
|
const QImage img = resp->textureFactory()->image();
|
||||||
QVERIFY(!img.isNull());
|
QVERIFY(!img.isNull());
|
||||||
QCOMPARE(img.pixel(0, 0), qRgb(0, 255, 0));
|
QCOMPARE(img.pixel(0, 0), qRgb(0, 255, 0));
|
||||||
@@ -268,21 +262,19 @@ private slots:
|
|||||||
|
|
||||||
void requestImageResponseFallsBackToProviderPath()
|
void requestImageResponseFallsBackToProviderPath()
|
||||||
{
|
{
|
||||||
// Without a leading slash in id, the provider should use m_epubPath.
|
const QString cbzA = buildCbzWithPng("img.png", 4, 4, qRgb(255, 0, 0));
|
||||||
const QString epubA = buildEpubWithPng("img.png", 4, 4, qRgb(255, 0, 0));
|
QVERIFY(!cbzA.isEmpty());
|
||||||
QVERIFY(!epubA.isEmpty());
|
|
||||||
|
|
||||||
EntryImageProvider provider = makeEpubProvider();
|
EntryImageProvider provider = makeCbzProvider();
|
||||||
provider.setFilePath(epubA);
|
provider.setFilePath(cbzA);
|
||||||
|
|
||||||
// No query param — old format, uses m_epubPath
|
|
||||||
QQuickImageResponse *resp = provider.requestImageResponse(
|
QQuickImageResponse *resp = provider.requestImageResponse(
|
||||||
QStringLiteral("img.png"), QSize());
|
QStringLiteral("img.png"), QSize());
|
||||||
QSignalSpy spy(resp, &QQuickImageResponse::finished);
|
QSignalSpy spy(resp, &QQuickImageResponse::finished);
|
||||||
QThreadPool::globalInstance()->waitForDone();
|
QThreadPool::globalInstance()->waitForDone();
|
||||||
if (spy.isEmpty()) spy.wait(5000);
|
if (spy.isEmpty()) spy.wait(5000);
|
||||||
|
|
||||||
QFile::remove(epubA);
|
QFile::remove(cbzA);
|
||||||
|
|
||||||
QVERIFY(resp->textureFactory() != nullptr);
|
QVERIFY(resp->textureFactory() != nullptr);
|
||||||
const QImage img = resp->textureFactory()->image();
|
const QImage img = resp->textureFactory()->image();
|
||||||
@@ -294,74 +286,22 @@ private slots:
|
|||||||
|
|
||||||
void responseAfterClearIsNull()
|
void responseAfterClearIsNull()
|
||||||
{
|
{
|
||||||
const QString epubPath = buildEpubWithPng("img.png", 4, 4);
|
const QString cbzPath = buildCbzWithPng("img.png", 4, 4);
|
||||||
QVERIFY(!epubPath.isEmpty());
|
QVERIFY(!cbzPath.isEmpty());
|
||||||
|
|
||||||
EntryImageProvider provider = makeEpubProvider();
|
EntryImageProvider provider = makeCbzProvider();
|
||||||
provider.setFilePath(epubPath);
|
provider.setFilePath(cbzPath);
|
||||||
provider.clear();
|
provider.clear();
|
||||||
|
|
||||||
QQuickImageResponse *resp = provider.requestImageResponse(
|
QQuickImageResponse *resp = provider.requestImageResponse(
|
||||||
QStringLiteral("img.png"), QSize());
|
QStringLiteral("img.png"), QSize());
|
||||||
QThreadPool::globalInstance()->waitForDone();
|
QThreadPool::globalInstance()->waitForDone();
|
||||||
|
|
||||||
QFile::remove(epubPath);
|
QFile::remove(cbzPath);
|
||||||
|
|
||||||
QVERIFY(resp->textureFactory() == nullptr);
|
QVERIFY(resp->textureFactory() == nullptr);
|
||||||
delete resp;
|
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"), 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(EntryImageProviderTest)
|
QTEST_MAIN(EntryImageProviderTest)
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
#include <QApplication>
|
#include <QApplication>
|
||||||
#include <QImage>
|
#include <QImage>
|
||||||
#include <QSize>
|
#include <QSize>
|
||||||
|
#include <QTemporaryFile>
|
||||||
|
|
||||||
#include "backend/formats/FileIconProvider.h"
|
#include "backend/formats/FileIconProvider.h"
|
||||||
|
|
||||||
@@ -11,11 +12,14 @@ class FileIconProviderTest : public QObject {
|
|||||||
private slots:
|
private slots:
|
||||||
void requestImageReturnsValidImageForExistingFile()
|
void requestImageReturnsValidImageForExistingFile()
|
||||||
{
|
{
|
||||||
|
QTemporaryFile tempFile;
|
||||||
|
QVERIFY(tempFile.open());
|
||||||
|
tempFile.write("test");
|
||||||
|
tempFile.close();
|
||||||
|
|
||||||
FileIconProvider provider;
|
FileIconProvider provider;
|
||||||
QSize size;
|
QSize size;
|
||||||
// Use a known fixture file
|
QImage image = provider.requestImage(tempFile.fileName(), &size, QSize());
|
||||||
const QString path = QStringLiteral(FIXTURES_DIR) + "/sample.txt";
|
|
||||||
QImage image = provider.requestImage(path, &size, QSize());
|
|
||||||
|
|
||||||
QVERIFY(!image.isNull());
|
QVERIFY(!image.isNull());
|
||||||
QVERIFY(size.width() > 0);
|
QVERIFY(size.width() > 0);
|
||||||
@@ -28,18 +32,22 @@ private slots:
|
|||||||
QSize size;
|
QSize size;
|
||||||
// QFileIconProvider returns a generic icon even for missing files
|
// QFileIconProvider returns a generic icon even for missing files
|
||||||
QImage image = provider.requestImage(
|
QImage image = provider.requestImage(
|
||||||
QStringLiteral("/tmp/nonexistent_asteria_test.epub"), &size, QSize());
|
QStringLiteral("/tmp/nonexistent_asteria_test.cbz"), &size, QSize());
|
||||||
|
|
||||||
QVERIFY(!image.isNull());
|
QVERIFY(!image.isNull());
|
||||||
}
|
}
|
||||||
|
|
||||||
void requestImageHonorsRequestedSize()
|
void requestImageHonorsRequestedSize()
|
||||||
{
|
{
|
||||||
|
QTemporaryFile tempFile;
|
||||||
|
QVERIFY(tempFile.open());
|
||||||
|
tempFile.write("test");
|
||||||
|
tempFile.close();
|
||||||
|
|
||||||
FileIconProvider provider;
|
FileIconProvider provider;
|
||||||
QSize size;
|
QSize size;
|
||||||
const QSize requested(32, 32);
|
const QSize requested(32, 32);
|
||||||
const QString path = QStringLiteral(FIXTURES_DIR) + "/sample.txt";
|
QImage image = provider.requestImage(tempFile.fileName(), &size, requested);
|
||||||
QImage image = provider.requestImage(path, &size, requested);
|
|
||||||
|
|
||||||
QVERIFY(!image.isNull());
|
QVERIFY(!image.isNull());
|
||||||
// Icon pixmaps may be slightly different sizes depending on the platform,
|
// Icon pixmaps may be slightly different sizes depending on the platform,
|
||||||
|
|||||||
@@ -3,8 +3,6 @@
|
|||||||
#include "backend/formats/FormatRegistry.h"
|
#include "backend/formats/FormatRegistry.h"
|
||||||
#include "backend/FormatReader.h"
|
#include "backend/FormatReader.h"
|
||||||
#include "backend/IImageProvider.h"
|
#include "backend/IImageProvider.h"
|
||||||
#include "backend/formats/TxtReader.h"
|
|
||||||
#include "backend/formats/EpubReader.h"
|
|
||||||
#include "backend/formats/comic/CbzReader.h"
|
#include "backend/formats/comic/CbzReader.h"
|
||||||
#include "backend/formats/comic/CbrReader.h"
|
#include "backend/formats/comic/CbrReader.h"
|
||||||
#include "backend/formats/comic/FolderReader.h"
|
#include "backend/formats/comic/FolderReader.h"
|
||||||
@@ -15,11 +13,6 @@
|
|||||||
static FormatRegistry makeRegistry()
|
static FormatRegistry makeRegistry()
|
||||||
{
|
{
|
||||||
return FormatRegistry({
|
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>(); }},
|
|
||||||
{QStringLiteral("cbz"), false, QStringLiteral("cbz"),
|
{QStringLiteral("cbz"), false, QStringLiteral("cbz"),
|
||||||
[] { return std::make_unique<CbzReader>(); },
|
[] { return std::make_unique<CbzReader>(); },
|
||||||
[] { return std::make_unique<ZipByteSource>(); }},
|
[] { return std::make_unique<ZipByteSource>(); }},
|
||||||
@@ -36,16 +29,22 @@ class FormatRegistryTest : public QObject {
|
|||||||
Q_OBJECT
|
Q_OBJECT
|
||||||
|
|
||||||
private slots:
|
private slots:
|
||||||
void createTxtReader()
|
void createCbzReader()
|
||||||
{
|
{
|
||||||
auto registry = makeRegistry();
|
auto registry = makeRegistry();
|
||||||
QVERIFY(registry.createReader("file.txt") != nullptr);
|
QVERIFY(registry.createReader("file.cbz") != nullptr);
|
||||||
}
|
}
|
||||||
|
|
||||||
void createTxtReaderUpperCase()
|
void createCbzReaderUpperCase()
|
||||||
{
|
{
|
||||||
auto registry = makeRegistry();
|
auto registry = makeRegistry();
|
||||||
QVERIFY(registry.createReader("file.TXT") != nullptr);
|
QVERIFY(registry.createReader("file.CBZ") != nullptr);
|
||||||
|
}
|
||||||
|
|
||||||
|
void createCbrReader()
|
||||||
|
{
|
||||||
|
auto registry = makeRegistry();
|
||||||
|
QVERIFY(registry.createReader("file.cbr") != nullptr);
|
||||||
}
|
}
|
||||||
|
|
||||||
void createUnknownFormat()
|
void createUnknownFormat()
|
||||||
@@ -66,18 +65,6 @@ private slots:
|
|||||||
QVERIFY(registry.createReader("") == nullptr);
|
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()
|
void createFolderReader()
|
||||||
{
|
{
|
||||||
QTemporaryDir tmp;
|
QTemporaryDir tmp;
|
||||||
@@ -92,22 +79,16 @@ private slots:
|
|||||||
{
|
{
|
||||||
auto registry = makeRegistry();
|
auto registry = makeRegistry();
|
||||||
const QStringList exts = registry.supportedExtensions();
|
const QStringList exts = registry.supportedExtensions();
|
||||||
QVERIFY(exts.contains(QStringLiteral("txt")));
|
|
||||||
QVERIFY(exts.contains(QStringLiteral("epub")));
|
|
||||||
QVERIFY(exts.contains(QStringLiteral("cbz")));
|
QVERIFY(exts.contains(QStringLiteral("cbz")));
|
||||||
QVERIFY(exts.contains(QStringLiteral("cbr")));
|
QVERIFY(exts.contains(QStringLiteral("cbr")));
|
||||||
// The directory row contributes no extension
|
// The directory row contributes no extension
|
||||||
QCOMPARE(exts.size(), 4);
|
QCOMPARE(exts.size(), 2);
|
||||||
}
|
}
|
||||||
|
|
||||||
void imageProviderSchemesMatchTable()
|
void imageProviderSchemesMatchTable()
|
||||||
{
|
{
|
||||||
auto registry = makeRegistry();
|
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"));
|
std::unique_ptr<IImageProvider> cbz(registry.createImageProvider("comic.cbz"));
|
||||||
QVERIFY(cbz);
|
QVERIFY(cbz);
|
||||||
QCOMPARE(cbz->scheme(), QStringLiteral("cbz"));
|
QCOMPARE(cbz->scheme(), QStringLiteral("cbz"));
|
||||||
@@ -121,7 +102,6 @@ private slots:
|
|||||||
void formatsWithoutImagesHaveNoProvider()
|
void formatsWithoutImagesHaveNoProvider()
|
||||||
{
|
{
|
||||||
auto registry = makeRegistry();
|
auto registry = makeRegistry();
|
||||||
QVERIFY(registry.createImageProvider("plain.txt") == nullptr);
|
|
||||||
QVERIFY(registry.createImageProvider("file.xyz") == nullptr);
|
QVERIFY(registry.createImageProvider("file.xyz") == nullptr);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -10,18 +10,15 @@
|
|||||||
|
|
||||||
#include "backend/HistoryBookModel.h"
|
#include "backend/HistoryBookModel.h"
|
||||||
#include "backend/FormatReader.h"
|
#include "backend/FormatReader.h"
|
||||||
#include "backend/formats/EpubReader.h"
|
#include "backend/formats/comic/CbzReader.h"
|
||||||
#include "backend/formats/TxtReader.h"
|
|
||||||
#include "backend/formats/FormatRegistry.h"
|
#include "backend/formats/FormatRegistry.h"
|
||||||
#include "backend/formats/sources/ZipByteSource.h"
|
#include "backend/formats/sources/ZipByteSource.h"
|
||||||
|
|
||||||
static FormatRegistry makeRegistry()
|
static FormatRegistry makeRegistry()
|
||||||
{
|
{
|
||||||
return FormatRegistry({
|
return FormatRegistry({
|
||||||
{QStringLiteral("txt"), false, {},
|
{QStringLiteral("cbz"), false, QStringLiteral("cbz"),
|
||||||
[] { return std::make_unique<TxtReader>(); }, nullptr},
|
[] { return std::make_unique<CbzReader>(); },
|
||||||
{QStringLiteral("epub"), false, QStringLiteral("epub"),
|
|
||||||
[] { return std::make_unique<EpubReader>(); },
|
|
||||||
[] { return std::make_unique<ZipByteSource>(); }},
|
[] { return std::make_unique<ZipByteSource>(); }},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -30,14 +27,12 @@ static FormatRegistry makeRegistry()
|
|||||||
// Helpers
|
// Helpers
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
static bool addEntry(zipFile zf, const char *name, const QByteArray &data, bool store = false)
|
static bool addEntry(zipFile zf, const char *name, const QByteArray &data)
|
||||||
{
|
{
|
||||||
zip_fileinfo fi{};
|
zip_fileinfo fi{};
|
||||||
int method = store ? Z_NO_COMPRESSION : Z_DEFLATED;
|
|
||||||
int level = store ? 0 : Z_DEFAULT_COMPRESSION;
|
|
||||||
if (zipOpenNewFileInZip(zf, name, &fi,
|
if (zipOpenNewFileInZip(zf, name, &fi,
|
||||||
nullptr, 0, nullptr, 0, nullptr,
|
nullptr, 0, nullptr, 0, nullptr,
|
||||||
method, level) != ZIP_OK)
|
Z_DEFLATED, Z_DEFAULT_COMPRESSION) != ZIP_OK)
|
||||||
return false;
|
return false;
|
||||||
if (zipWriteInFileInZip(zf, data.constData(), (unsigned)data.size()) != ZIP_OK) {
|
if (zipWriteInFileInZip(zf, data.constData(), (unsigned)data.size()) != ZIP_OK) {
|
||||||
zipCloseFileInZip(zf);
|
zipCloseFileInZip(zf);
|
||||||
@@ -57,46 +52,17 @@ static QByteArray makePng(int w = 4, int h = 4, QRgb color = qRgb(255, 0, 0))
|
|||||||
return data;
|
return data;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Build a minimal EPUB with a cover image declared in OPF metadata.
|
static QString buildCbzWithCover()
|
||||||
static QString buildEpubWithCover()
|
|
||||||
{
|
{
|
||||||
static const char kMimetype[] = "application/epub+zip";
|
static const char kComicInfo[] =
|
||||||
|
|
||||||
static const char kContainer[] =
|
|
||||||
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
|
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
|
||||||
"<container version=\"1.0\" xmlns=\"urn:oasis:names:tc:opendocument:xmlns:container\">"
|
"<ComicInfo>"
|
||||||
" <rootfiles>"
|
" <Title>Cover Test Book</Title>"
|
||||||
" <rootfile full-path=\"OEBPS/content.opf\""
|
" <Writer>Test Author</Writer>"
|
||||||
" media-type=\"application/oebps-package+xml\"/>"
|
"</ComicInfo>";
|
||||||
" </rootfiles>"
|
|
||||||
"</container>";
|
|
||||||
|
|
||||||
// OPF with <meta name="cover" content="cover-img"/> referencing the cover item.
|
|
||||||
static const char kOpf[] =
|
|
||||||
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
|
|
||||||
"<package xmlns=\"http://www.idpf.org/2007/opf\" version=\"2.0\" unique-identifier=\"BookId\">"
|
|
||||||
" <metadata xmlns:dc=\"http://purl.org/dc/elements/1.1/\">"
|
|
||||||
" <dc:title>Cover Test Book</dc:title>"
|
|
||||||
" <dc:creator>Test Author</dc:creator>"
|
|
||||||
" <meta name=\"cover\" content=\"cover-img\"/>"
|
|
||||||
" </metadata>"
|
|
||||||
" <manifest>"
|
|
||||||
" <item id=\"cover-img\" href=\"Images/cover.png\" media-type=\"image/png\"/>"
|
|
||||||
" <item id=\"ch1\" href=\"chapter1.xhtml\" media-type=\"application/xhtml+xml\"/>"
|
|
||||||
" </manifest>"
|
|
||||||
" <spine>"
|
|
||||||
" <itemref idref=\"ch1\"/>"
|
|
||||||
" </spine>"
|
|
||||||
"</package>";
|
|
||||||
|
|
||||||
static const char kChapter[] =
|
|
||||||
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
|
|
||||||
"<html xmlns=\"http://www.w3.org/1999/xhtml\">"
|
|
||||||
" <body><p>Content</p></body>"
|
|
||||||
"</html>";
|
|
||||||
|
|
||||||
QTemporaryFile tmp;
|
QTemporaryFile tmp;
|
||||||
tmp.setFileTemplate(QDir::tempPath() + "/hbm_cover_test_XXXXXX.epub");
|
tmp.setFileTemplate(QDir::tempPath() + "/hbm_cover_test_XXXXXX.cbz");
|
||||||
tmp.setAutoRemove(false);
|
tmp.setAutoRemove(false);
|
||||||
if (!tmp.open()) return {};
|
if (!tmp.open()) return {};
|
||||||
const QString path = tmp.fileName();
|
const QString path = tmp.fileName();
|
||||||
@@ -106,11 +72,8 @@ static QString buildEpubWithCover()
|
|||||||
if (!zf) return {};
|
if (!zf) return {};
|
||||||
|
|
||||||
bool ok = true;
|
bool ok = true;
|
||||||
ok = ok && addEntry(zf, "mimetype", QByteArray(kMimetype), /*store=*/true);
|
ok = ok && addEntry(zf, "ComicInfo.xml", QByteArray(kComicInfo));
|
||||||
ok = ok && addEntry(zf, "META-INF/container.xml", QByteArray(kContainer));
|
ok = ok && addEntry(zf, "001_cover.png", makePng());
|
||||||
ok = ok && addEntry(zf, "OEBPS/content.opf", QByteArray(kOpf));
|
|
||||||
ok = ok && addEntry(zf, "OEBPS/chapter1.xhtml", QByteArray(kChapter));
|
|
||||||
ok = ok && addEntry(zf, "OEBPS/Images/cover.png", makePng());
|
|
||||||
|
|
||||||
zipClose(zf, nullptr);
|
zipClose(zf, nullptr);
|
||||||
return ok ? path : QString{};
|
return ok ? path : QString{};
|
||||||
@@ -124,66 +87,59 @@ class HistoryBookModelTest : public QObject {
|
|||||||
Q_OBJECT
|
Q_OBJECT
|
||||||
|
|
||||||
private slots:
|
private slots:
|
||||||
void loadMetadataPopulatesCoverImageUrlForEpub()
|
void loadMetadataPopulatesCoverImageUrlForCbz()
|
||||||
{
|
{
|
||||||
const QString epubPath = buildEpubWithCover();
|
const QString cbzPath = buildCbzWithCover();
|
||||||
QVERIFY(!epubPath.isEmpty());
|
QVERIFY(!cbzPath.isEmpty());
|
||||||
|
|
||||||
FormatRegistry registry = makeRegistry();
|
FormatRegistry registry = makeRegistry();
|
||||||
HistoryBookModel model(epubPath, 0.0, QString(), registry);
|
HistoryBookModel model(cbzPath, 0.0, QString(), registry);
|
||||||
|
|
||||||
QSignalSpy spy(&model, &HistoryBookModel::metadataLoaded);
|
QSignalSpy spy(&model, &HistoryBookModel::metadataLoaded);
|
||||||
QSignalSpy coverSpy(&model, &HistoryBookModel::coverImageLoaded);
|
QSignalSpy coverSpy(&model, &HistoryBookModel::coverImageLoaded);
|
||||||
model.loadMetadata();
|
model.loadMetadata();
|
||||||
|
|
||||||
// Wait up to 5 seconds for the async metadata load to complete
|
|
||||||
QVERIFY(spy.wait(5000));
|
QVERIFY(spy.wait(5000));
|
||||||
|
|
||||||
QFile::remove(epubPath);
|
QFile::remove(cbzPath);
|
||||||
|
|
||||||
// coverImageUrl's NOTIFY signal must fire so QML bindings update
|
|
||||||
QCOMPARE(coverSpy.count(), 1);
|
QCOMPARE(coverSpy.count(), 1);
|
||||||
|
|
||||||
const QString url = model.coverImageUrl();
|
const QString url = model.coverImageUrl();
|
||||||
QVERIFY2(!url.isEmpty(), "coverImageUrl should be set after loadMetadata for an EPUB with cover");
|
QVERIFY2(!url.isEmpty(), "coverImageUrl should be set after loadMetadata for a CBZ with cover");
|
||||||
// Format: image://epub/<internal-path>?src=<encoded-epub-path>
|
QVERIFY2(url.startsWith(QStringLiteral("image://cbz/001_cover.png?src=")),
|
||||||
QVERIFY2(url.startsWith(QStringLiteral("image://epub/OEBPS/Images/cover.png?src=")),
|
|
||||||
qPrintable("Expected query-param URL format, got: " + url));
|
qPrintable("Expected query-param URL format, got: " + url));
|
||||||
const QString encodedPath = QString::fromUtf8(QUrl::toPercentEncoding(epubPath));
|
const QString encodedPath = QString::fromUtf8(QUrl::toPercentEncoding(cbzPath));
|
||||||
QVERIFY2(url.contains(encodedPath),
|
QVERIFY2(url.contains(encodedPath),
|
||||||
qPrintable("URL should contain encoded epub path. URL: " + url));
|
qPrintable("URL should contain encoded cbz path. URL: " + url));
|
||||||
}
|
}
|
||||||
|
|
||||||
void loadMetadataLeavesCoverImageUrlEmptyForTxt()
|
void loadMetadataLeavesCoverImageUrlEmptyForMissingFile()
|
||||||
{
|
{
|
||||||
const QString txtPath = QStringLiteral(FIXTURES_DIR) + "/sample.txt";
|
|
||||||
QVERIFY(QFile::exists(txtPath));
|
|
||||||
|
|
||||||
FormatRegistry registry = makeRegistry();
|
FormatRegistry registry = makeRegistry();
|
||||||
HistoryBookModel model(txtPath, 0.0, QString(), registry);
|
HistoryBookModel model(QStringLiteral("/nonexistent/file.cbz"), 0.0, QString(), registry);
|
||||||
|
|
||||||
QSignalSpy spy(&model, &HistoryBookModel::metadataLoaded);
|
QSignalSpy spy(&model, &HistoryBookModel::metadataLoaded);
|
||||||
model.loadMetadata();
|
model.loadMetadata();
|
||||||
|
|
||||||
QVERIFY(spy.wait(5000));
|
// Should finish or not crash, coverImageUrl remains empty
|
||||||
|
|
||||||
QVERIFY2(model.coverImageUrl().isEmpty(),
|
QVERIFY2(model.coverImageUrl().isEmpty(),
|
||||||
"TXT files have no cover; coverImageUrl should remain empty");
|
"Missing files have no cover; coverImageUrl should remain empty");
|
||||||
}
|
}
|
||||||
|
|
||||||
void loadMetadataPopulatesTitle()
|
void loadMetadataPopulatesTitle()
|
||||||
{
|
{
|
||||||
const QString epubPath = buildEpubWithCover();
|
const QString cbzPath = buildCbzWithCover();
|
||||||
QVERIFY(!epubPath.isEmpty());
|
QVERIFY(!cbzPath.isEmpty());
|
||||||
|
|
||||||
FormatRegistry registry = makeRegistry();
|
FormatRegistry registry = makeRegistry();
|
||||||
HistoryBookModel model(epubPath, 0.0, QString(), registry);
|
HistoryBookModel model(cbzPath, 0.0, QString(), registry);
|
||||||
|
|
||||||
QSignalSpy spy(&model, &HistoryBookModel::metadataLoaded);
|
QSignalSpy spy(&model, &HistoryBookModel::metadataLoaded);
|
||||||
model.loadMetadata();
|
model.loadMetadata();
|
||||||
QVERIFY(spy.wait(5000));
|
QVERIFY(spy.wait(5000));
|
||||||
|
|
||||||
QFile::remove(epubPath);
|
QFile::remove(cbzPath);
|
||||||
|
|
||||||
QCOMPARE(model.title(), QStringLiteral("Cover Test Book"));
|
QCOMPARE(model.title(), QStringLiteral("Cover Test Book"));
|
||||||
QCOMPARE(model.author(), QStringLiteral("Test Author"));
|
QCOMPARE(model.author(), QStringLiteral("Test Author"));
|
||||||
|
|||||||
+69
-239
@@ -8,72 +8,18 @@
|
|||||||
#include "backend/FormatReader.h"
|
#include "backend/FormatReader.h"
|
||||||
#include "backend/state/BookPositionStore.h"
|
#include "backend/state/BookPositionStore.h"
|
||||||
|
|
||||||
// A fake reader that has 3 chapters, 2 chunks each → 6 total chunks
|
|
||||||
class FakeReader : public FormatReader {
|
|
||||||
public:
|
|
||||||
bool open(const QString &) override { return true; }
|
|
||||||
QString lastError() override { return {}; }
|
|
||||||
int chapterCount() override { return 3; }
|
|
||||||
|
|
||||||
Chapter loadChapter(int index) override
|
|
||||||
{
|
|
||||||
if (index < 0 || index >= 3)
|
|
||||||
return {index, {}, {}};
|
|
||||||
return {index,
|
|
||||||
QStringLiteral("Chapter %1").arg(index),
|
|
||||||
{QStringLiteral("<p>Chunk A of %1</p>").arg(index),
|
|
||||||
QStringLiteral("<p>Chunk B of %1</p>").arg(index)}};
|
|
||||||
}
|
|
||||||
|
|
||||||
QList<TocEntry> tableOfContents() override { return {}; }
|
|
||||||
QString title() override { return QStringLiteral("Fake Book"); }
|
|
||||||
QString author() override { return QStringLiteral("Fake Author"); }
|
|
||||||
QString filePath() override { return QStringLiteral("/fake/path.txt"); }
|
|
||||||
QString coverImagePath() override { return {}; }
|
|
||||||
QByteArray contentHash() override { return QByteArray("fakehash"); }
|
|
||||||
bool loadMetadata(const QString &) override { return true; }
|
|
||||||
QString fileType() const override { return QStringLiteral("txt"); }
|
|
||||||
};
|
|
||||||
|
|
||||||
class SingleChapterReader : public FormatReader {
|
|
||||||
public:
|
|
||||||
bool open(const QString &) override { return true; }
|
|
||||||
QString lastError() override { return {}; }
|
|
||||||
int chapterCount() override { return 1; }
|
|
||||||
Chapter loadChapter(int) override { return {0, {}, {"<p>text</p>"}}; }
|
|
||||||
QList<TocEntry> tableOfContents() override { return {}; }
|
|
||||||
QString title() override { return {}; }
|
|
||||||
QString author() override { return {}; }
|
|
||||||
QString filePath() override { return QStringLiteral("/fake/single.txt"); }
|
|
||||||
QString coverImagePath() override { return {}; }
|
|
||||||
QByteArray contentHash() override { return QByteArray("singlehash"); }
|
|
||||||
bool loadMetadata(const QString &) override { return true; }
|
|
||||||
QString fileType() const override { return QStringLiteral("txt"); }
|
|
||||||
};
|
|
||||||
|
|
||||||
class FakeMangaReader : public FormatReader {
|
class FakeMangaReader : public FormatReader {
|
||||||
public:
|
public:
|
||||||
bool open(const QString &) override { return true; }
|
bool open(const QString &) override { return true; }
|
||||||
QString lastError() override { return {}; }
|
QString lastError() override { return {}; }
|
||||||
int chapterCount() override { return 1; }
|
QVector<PageInfo> pages() const override
|
||||||
|
|
||||||
Chapter loadChapter(int index) override
|
|
||||||
{
|
{
|
||||||
if (index != 0) return {index, {}, {}};
|
return {
|
||||||
return {0, QStringLiteral("Manga Title"),
|
{QStringLiteral("image://cbz/0.jpg"), QSize(800, 1200)},
|
||||||
{QStringLiteral("<img src=\"image://cbz/0.jpg\"/>"),
|
{QStringLiteral("image://cbz/1.jpg"), QSize(800, 1200)},
|
||||||
QStringLiteral("<img src=\"image://cbz/1.jpg\"/>"),
|
{QStringLiteral("image://cbz/2.jpg"), QSize(800, 1200)}
|
||||||
QStringLiteral("<img src=\"image://cbz/2.jpg\"/>")}};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
QVector<QSize> chapterPageSizes(int index) const override
|
|
||||||
{
|
|
||||||
if (index != 0) return {};
|
|
||||||
return {QSize(800, 1200), QSize(800, 1200), QSize(800, 1200)};
|
|
||||||
}
|
|
||||||
|
|
||||||
RenderingMode preferredRenderingMode() const override { return RenderingMode::Manga; }
|
|
||||||
QList<TocEntry> tableOfContents() override { return {}; }
|
|
||||||
QString title() override { return QStringLiteral("Manga Title"); }
|
QString title() override { return QStringLiteral("Manga Title"); }
|
||||||
QString author() override { return QStringLiteral("Manga Author"); }
|
QString author() override { return QStringLiteral("Manga Author"); }
|
||||||
QString filePath() override { return QStringLiteral("/fake/manga.cbz"); }
|
QString filePath() override { return QStringLiteral("/fake/manga.cbz"); }
|
||||||
@@ -107,184 +53,15 @@ private slots:
|
|||||||
void initialState()
|
void initialState()
|
||||||
{
|
{
|
||||||
Ctx ctx; ReadingModel model(*ctx.store);
|
Ctx ctx; ReadingModel model(*ctx.store);
|
||||||
QCOMPARE(model.totalChapters(), 0);
|
|
||||||
QCOMPARE(model.progress(), 0.0);
|
QCOMPARE(model.progress(), 0.0);
|
||||||
QVERIFY(model.chapterTitle().isEmpty());
|
|
||||||
QCOMPARE(model.currentPage(), 0);
|
QCOMPARE(model.currentPage(), 0);
|
||||||
QCOMPARE(model.totalPages(), 0);
|
QCOMPARE(model.totalPages(), 0);
|
||||||
QVERIFY(!model.isMangaMode());
|
QCOMPARE(model.totalPagePairs(), 0);
|
||||||
|
QVERIFY(model.pageShift());
|
||||||
|
QVERIFY(model.mangaRTL());
|
||||||
}
|
}
|
||||||
|
|
||||||
void setReaderLoadsAllChapters()
|
void setReaderLoadsPagesAndEmitsRestoreReady()
|
||||||
{
|
|
||||||
Ctx ctx; ReadingModel model(*ctx.store);
|
|
||||||
FakeReader reader;
|
|
||||||
model.setReader(&reader);
|
|
||||||
|
|
||||||
QCOMPARE(model.totalChapters(), 3);
|
|
||||||
QCOMPARE(model.currentChapter(), 0);
|
|
||||||
QCOMPARE(model.chapterTitle(), QStringLiteral("Chapter 0"));
|
|
||||||
}
|
|
||||||
|
|
||||||
void currentChapterDerivedFromScroll()
|
|
||||||
{
|
|
||||||
Ctx ctx; ReadingModel model(*ctx.store);
|
|
||||||
FakeReader reader;
|
|
||||||
model.setReader(&reader);
|
|
||||||
|
|
||||||
QCOMPARE(model.currentChapter(), 0);
|
|
||||||
|
|
||||||
// Chunk 2 = first chunk of chapter 1
|
|
||||||
model.setScrollInfo(2, 0.0);
|
|
||||||
QCOMPARE(model.currentChapter(), 1);
|
|
||||||
QCOMPARE(model.chapterTitle(), QStringLiteral("Chapter 1"));
|
|
||||||
|
|
||||||
// Chunk 4 = first chunk of chapter 2
|
|
||||||
model.setScrollInfo(4, 0.0);
|
|
||||||
QCOMPARE(model.currentChapter(), 2);
|
|
||||||
QCOMPARE(model.chapterTitle(), QStringLiteral("Chapter 2"));
|
|
||||||
|
|
||||||
// Back to chapter 0
|
|
||||||
model.setScrollInfo(0, 0.0);
|
|
||||||
QCOMPARE(model.currentChapter(), 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
void chapterChangedSignalOnScroll()
|
|
||||||
{
|
|
||||||
Ctx ctx; ReadingModel model(*ctx.store);
|
|
||||||
FakeReader reader;
|
|
||||||
model.setReader(&reader);
|
|
||||||
|
|
||||||
QSignalSpy spy(&model, &ReadingModel::chapterChanged);
|
|
||||||
|
|
||||||
model.setScrollInfo(0, 0.0); // still chapter 0 — no signal
|
|
||||||
QCOMPARE(spy.count(), 0);
|
|
||||||
|
|
||||||
model.setScrollInfo(2, 0.0); // chapter 1 → signal
|
|
||||||
QCOMPARE(spy.count(), 1);
|
|
||||||
|
|
||||||
model.setScrollInfo(3, 0.0); // still chapter 1 — no signal
|
|
||||||
QCOMPARE(spy.count(), 1);
|
|
||||||
|
|
||||||
model.setScrollInfo(4, 0.0); // chapter 2 → signal
|
|
||||||
QCOMPARE(spy.count(), 2);
|
|
||||||
}
|
|
||||||
|
|
||||||
void goToChapterEmitsScrollSignal()
|
|
||||||
{
|
|
||||||
Ctx ctx; ReadingModel model(*ctx.store);
|
|
||||||
FakeReader reader;
|
|
||||||
model.setReader(&reader);
|
|
||||||
|
|
||||||
QSignalSpy spy(&model, &ReadingModel::scrollToChunkRequested);
|
|
||||||
|
|
||||||
model.goToChapter(1);
|
|
||||||
QCOMPARE(spy.count(), 1);
|
|
||||||
QCOMPARE(spy.at(0).at(0).toInt(), 2); // chapter 1 starts at chunk 2
|
|
||||||
|
|
||||||
model.goToChapter(2);
|
|
||||||
QCOMPARE(spy.count(), 2);
|
|
||||||
QCOMPARE(spy.at(1).at(0).toInt(), 4); // chapter 2 starts at chunk 4
|
|
||||||
}
|
|
||||||
|
|
||||||
void goToChapterOutOfRangeNoSignal()
|
|
||||||
{
|
|
||||||
Ctx ctx; ReadingModel model(*ctx.store);
|
|
||||||
FakeReader reader;
|
|
||||||
model.setReader(&reader);
|
|
||||||
|
|
||||||
QSignalSpy spy(&model, &ReadingModel::scrollToChunkRequested);
|
|
||||||
model.goToChapter(-1);
|
|
||||||
model.goToChapter(99);
|
|
||||||
QCOMPARE(spy.count(), 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
void nextChapterEmitsScrollSignal()
|
|
||||||
{
|
|
||||||
Ctx ctx; ReadingModel model(*ctx.store);
|
|
||||||
FakeReader reader;
|
|
||||||
model.setReader(&reader);
|
|
||||||
|
|
||||||
QSignalSpy spy(&model, &ReadingModel::scrollToChunkRequested);
|
|
||||||
|
|
||||||
model.nextChapter(); // chapter 0 → 1
|
|
||||||
QCOMPARE(spy.count(), 1);
|
|
||||||
QCOMPARE(spy.at(0).at(0).toInt(), 2);
|
|
||||||
}
|
|
||||||
|
|
||||||
void nextChapterAtEndNoSignal()
|
|
||||||
{
|
|
||||||
Ctx ctx; ReadingModel model(*ctx.store);
|
|
||||||
FakeReader reader;
|
|
||||||
model.setReader(&reader);
|
|
||||||
model.setScrollInfo(4, 0.0); // chapter 2
|
|
||||||
|
|
||||||
QSignalSpy spy(&model, &ReadingModel::scrollToChunkRequested);
|
|
||||||
model.nextChapter();
|
|
||||||
QCOMPARE(spy.count(), 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
void previousChapterEmitsScrollSignal()
|
|
||||||
{
|
|
||||||
Ctx ctx; ReadingModel model(*ctx.store);
|
|
||||||
FakeReader reader;
|
|
||||||
model.setReader(&reader);
|
|
||||||
model.setScrollInfo(4, 0.0); // chapter 2
|
|
||||||
|
|
||||||
QSignalSpy spy(&model, &ReadingModel::scrollToChunkRequested);
|
|
||||||
model.previousChapter();
|
|
||||||
QCOMPARE(spy.count(), 1);
|
|
||||||
QCOMPARE(spy.at(0).at(0).toInt(), 2); // chapter 1 starts at chunk 2
|
|
||||||
}
|
|
||||||
|
|
||||||
void previousChapterAtStartNoSignal()
|
|
||||||
{
|
|
||||||
Ctx ctx; ReadingModel model(*ctx.store);
|
|
||||||
FakeReader reader;
|
|
||||||
model.setReader(&reader);
|
|
||||||
|
|
||||||
QSignalSpy spy(&model, &ReadingModel::scrollToChunkRequested);
|
|
||||||
model.previousChapter();
|
|
||||||
QCOMPARE(spy.count(), 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
void setReaderNull()
|
|
||||||
{
|
|
||||||
Ctx ctx; ReadingModel model(*ctx.store);
|
|
||||||
FakeReader reader;
|
|
||||||
model.setReader(&reader);
|
|
||||||
model.setReader(nullptr);
|
|
||||||
|
|
||||||
QCOMPARE(model.totalChapters(), 0);
|
|
||||||
QCOMPARE(model.progress(), 0.0);
|
|
||||||
QVERIFY(model.chapterTitle().isEmpty());
|
|
||||||
}
|
|
||||||
|
|
||||||
void hasChaptersFalseForSingleChapter()
|
|
||||||
{
|
|
||||||
Ctx ctx; ReadingModel model(*ctx.store);
|
|
||||||
SingleChapterReader reader;
|
|
||||||
model.setReader(&reader);
|
|
||||||
|
|
||||||
QVERIFY(!model.hasChapters());
|
|
||||||
}
|
|
||||||
|
|
||||||
void hasChaptersTrueForMultipleChapters()
|
|
||||||
{
|
|
||||||
Ctx ctx; ReadingModel model(*ctx.store);
|
|
||||||
FakeReader reader;
|
|
||||||
model.setReader(&reader);
|
|
||||||
|
|
||||||
QVERIFY(model.hasChapters());
|
|
||||||
}
|
|
||||||
|
|
||||||
void hasChaptersFalseInitially()
|
|
||||||
{
|
|
||||||
Ctx ctx; ReadingModel model(*ctx.store);
|
|
||||||
QVERIFY(!model.hasChapters());
|
|
||||||
}
|
|
||||||
|
|
||||||
void mangaModeDetectionAndPagination()
|
|
||||||
{
|
{
|
||||||
Ctx ctx; ReadingModel model(*ctx.store);
|
Ctx ctx; ReadingModel model(*ctx.store);
|
||||||
FakeMangaReader reader;
|
FakeMangaReader reader;
|
||||||
@@ -292,30 +69,83 @@ private slots:
|
|||||||
|
|
||||||
model.setReader(&reader);
|
model.setReader(&reader);
|
||||||
|
|
||||||
QVERIFY(model.isMangaMode());
|
|
||||||
QCOMPARE(model.imageUrlForChunk(0), QStringLiteral("image://cbz/0.jpg"));
|
QCOMPARE(model.imageUrlForChunk(0), QStringLiteral("image://cbz/0.jpg"));
|
||||||
QCOMPARE(model.imageUrlForChunk(1), QStringLiteral("image://cbz/1.jpg"));
|
QCOMPARE(model.imageUrlForChunk(1), QStringLiteral("image://cbz/1.jpg"));
|
||||||
QCOMPARE(model.imageUrlForChunk(2), QStringLiteral("image://cbz/2.jpg"));
|
QCOMPARE(model.imageUrlForChunk(2), QStringLiteral("image://cbz/2.jpg"));
|
||||||
QCOMPARE(model.totalPagePairs(), 3); // portrait mode: each chunk is solo
|
QCOMPARE(model.totalPagePairs(), 3);
|
||||||
|
QCOMPARE(model.totalPages(), 3);
|
||||||
|
QCOMPARE(model.currentPage(), 1);
|
||||||
|
|
||||||
// restoreReady should be queued and emitted
|
|
||||||
QTRY_COMPARE(restoreSpy.count(), 1);
|
QTRY_COMPARE(restoreSpy.count(), 1);
|
||||||
QCOMPARE(restoreSpy.first().at(0).toInt(), 0);
|
QCOMPARE(restoreSpy.first().at(0).toInt(), 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
void scrollInfoUpdatesCurrentPageAndProgress()
|
||||||
|
{
|
||||||
|
Ctx ctx; ReadingModel model(*ctx.store);
|
||||||
|
FakeMangaReader reader;
|
||||||
|
model.setReader(&reader);
|
||||||
|
|
||||||
|
QSignalSpy pageSpy(&model, &ReadingModel::currentPageChanged);
|
||||||
|
model.setScrollInfo(1, 0.5);
|
||||||
|
|
||||||
|
QCOMPARE(model.currentPage(), 2);
|
||||||
|
QCOMPARE(model.progress(), 0.5);
|
||||||
|
QCOMPARE(pageSpy.count(), 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
void landscapeModeAndPageShift()
|
||||||
|
{
|
||||||
|
Ctx ctx; ReadingModel model(*ctx.store);
|
||||||
|
FakeMangaReader reader;
|
||||||
|
model.setReader(&reader);
|
||||||
|
|
||||||
// Landscape mode pairs portrait pages
|
|
||||||
model.setMangaLandscape(true);
|
model.setMangaLandscape(true);
|
||||||
// With pageShift ON (default): chunk 0 solo (cover), chunk 1 solo (shift), chunk 2 solo -> 3 pairs
|
// Default pageShift = true: chunk 0 solo (cover), chunk 1 solo (shift), chunk 2 solo -> 3 pairs
|
||||||
// If pageShift OFF: chunk 0 solo (cover), chunks 1 and 2 paired -> 2 pairs
|
QCOMPARE(model.totalPagePairs(), 3);
|
||||||
|
|
||||||
|
QSignalSpy shiftSpy(&model, &ReadingModel::pageShiftChanged);
|
||||||
|
QSignalSpy rebuildSpy(&model, &ReadingModel::pagePairsRebuilt);
|
||||||
|
|
||||||
model.setPageShift(false);
|
model.setPageShift(false);
|
||||||
|
QCOMPARE(shiftSpy.count(), 1);
|
||||||
|
QCOMPARE(rebuildSpy.count(), 1);
|
||||||
QCOMPARE(model.totalPagePairs(), 2);
|
QCOMPARE(model.totalPagePairs(), 2);
|
||||||
|
|
||||||
QVariantList pair0 = model.pagePair(0);
|
QVariantList pair0 = model.pagePair(0);
|
||||||
QCOMPARE(pair0.size(), 1);
|
QCOMPARE(pair0.size(), 1);
|
||||||
QCOMPARE(pair0.at(0).toInt(), 0);
|
QCOMPARE(pair0.at(0).toInt(), 0);
|
||||||
|
|
||||||
QVariantList pair1 = model.pagePair(1);
|
QVariantList pair1 = model.pagePair(1);
|
||||||
QCOMPARE(pair1.size(), 2);
|
QCOMPARE(pair1.size(), 2);
|
||||||
QCOMPARE(pair1.at(0).toInt(), 1);
|
QCOMPARE(pair1.at(0).toInt(), 1);
|
||||||
QCOMPARE(pair1.at(1).toInt(), 2);
|
QCOMPARE(pair1.at(1).toInt(), 2);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void mangaRTLToggle()
|
||||||
|
{
|
||||||
|
Ctx ctx; ReadingModel model(*ctx.store);
|
||||||
|
FakeMangaReader reader;
|
||||||
|
model.setReader(&reader);
|
||||||
|
|
||||||
|
QSignalSpy rtlSpy(&model, &ReadingModel::mangaRTLChanged);
|
||||||
|
model.setMangaRTL(false);
|
||||||
|
QCOMPARE(rtlSpy.count(), 1);
|
||||||
|
QVERIFY(!model.mangaRTL());
|
||||||
|
}
|
||||||
|
|
||||||
|
void setReaderNullResetsState()
|
||||||
|
{
|
||||||
|
Ctx ctx; ReadingModel model(*ctx.store);
|
||||||
|
FakeMangaReader reader;
|
||||||
|
model.setReader(&reader);
|
||||||
|
model.setReader(nullptr);
|
||||||
|
|
||||||
|
QCOMPARE(model.totalPagePairs(), 0);
|
||||||
|
QCOMPARE(model.totalPages(), 0);
|
||||||
|
QCOMPARE(model.currentPage(), 0);
|
||||||
|
QCOMPARE(model.progress(), 0.0);
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
QTEST_MAIN(ReadingModelTest)
|
QTEST_MAIN(ReadingModelTest)
|
||||||
|
|||||||
+37
-52
@@ -1,14 +1,16 @@
|
|||||||
#include <QtTest>
|
#include <QtTest>
|
||||||
#include <QDir>
|
#include <QDir>
|
||||||
|
#include <QImage>
|
||||||
#include <QSettings>
|
#include <QSettings>
|
||||||
#include <QSignalSpy>
|
#include <QSignalSpy>
|
||||||
|
#include <QTemporaryDir>
|
||||||
#include <QTemporaryFile>
|
#include <QTemporaryFile>
|
||||||
|
|
||||||
#include "backend/AppState.h"
|
#include "backend/AppState.h"
|
||||||
#include "backend/IFileDialogService.h"
|
#include "backend/IFileDialogService.h"
|
||||||
#include "backend/formats/FormatRegistry.h"
|
#include "backend/formats/FormatRegistry.h"
|
||||||
#include "backend/formats/TxtReader.h"
|
#include "backend/formats/comic/FolderReader.h"
|
||||||
#include "backend/formats/EpubReader.h"
|
#include "backend/formats/sources/DirByteSource.h"
|
||||||
#include "backend/state/BookPositionStore.h"
|
#include "backend/state/BookPositionStore.h"
|
||||||
#include "backend/book/Book.h"
|
#include "backend/book/Book.h"
|
||||||
|
|
||||||
@@ -25,22 +27,13 @@ class BookTest : public QObject {
|
|||||||
Q_OBJECT
|
Q_OBJECT
|
||||||
|
|
||||||
private:
|
private:
|
||||||
static QString epubFixture()
|
static QString createSampleComic(QTemporaryDir &tmp)
|
||||||
{
|
{
|
||||||
#ifdef FIXTURES_DIR
|
if (!tmp.isValid()) return {};
|
||||||
return QStringLiteral(FIXTURES_DIR) + QStringLiteral("/sample.epub");
|
QImage img(8, 8, QImage::Format_RGB888);
|
||||||
#else
|
img.fill(Qt::blue);
|
||||||
return QString();
|
img.save(tmp.filePath(QStringLiteral("page01.png")), "PNG");
|
||||||
#endif
|
return tmp.path();
|
||||||
}
|
|
||||||
|
|
||||||
static QString txtFixture()
|
|
||||||
{
|
|
||||||
#ifdef FIXTURES_DIR
|
|
||||||
return QStringLiteral(FIXTURES_DIR) + QStringLiteral("/sample.txt");
|
|
||||||
#else
|
|
||||||
return QString();
|
|
||||||
#endif
|
|
||||||
}
|
}
|
||||||
|
|
||||||
struct Ctx {
|
struct Ctx {
|
||||||
@@ -60,10 +53,9 @@ private:
|
|||||||
store = new BookPositionStore(*appState);
|
store = new BookPositionStore(*appState);
|
||||||
dialog = new FakeDialogService;
|
dialog = new FakeDialogService;
|
||||||
factory = new FormatRegistry({
|
factory = new FormatRegistry({
|
||||||
{QStringLiteral("txt"), false, {},
|
{{}, /*matchesDirectory=*/true, QStringLiteral("dir"),
|
||||||
[] { return std::make_unique<TxtReader>(); }, nullptr},
|
[] { return std::make_unique<FolderReader>(); },
|
||||||
{QStringLiteral("epub"), false, QStringLiteral("epub"),
|
[] { return std::make_unique<DirByteSource>(); }},
|
||||||
[] { return std::make_unique<EpubReader>(); }, nullptr},
|
|
||||||
});
|
});
|
||||||
book = new Book(*dialog, *store, *factory);
|
book = new Book(*dialog, *store, *factory);
|
||||||
}
|
}
|
||||||
@@ -88,14 +80,13 @@ private slots:
|
|||||||
QCOMPARE(ctx.book->filePath(), QString());
|
QCOMPARE(ctx.book->filePath(), QString());
|
||||||
QCOMPARE(ctx.book->coverImageUrl(),QString());
|
QCOMPARE(ctx.book->coverImageUrl(),QString());
|
||||||
QCOMPARE(ctx.book->errorMessage(), QString());
|
QCOMPARE(ctx.book->errorMessage(), QString());
|
||||||
QVERIFY(ctx.book->toc().isEmpty());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void openValidTxtFile()
|
void openValidFile()
|
||||||
{
|
{
|
||||||
const QString path = txtFixture();
|
QTemporaryDir tmp;
|
||||||
if (path.isEmpty() || !QFileInfo::exists(path))
|
const QString path = createSampleComic(tmp);
|
||||||
QSKIP("No TXT fixture");
|
QVERIFY(!path.isEmpty());
|
||||||
|
|
||||||
Ctx ctx;
|
Ctx ctx;
|
||||||
QSignalSpy bookChanged(ctx.book, &Book::bookChanged);
|
QSignalSpy bookChanged(ctx.book, &Book::bookChanged);
|
||||||
@@ -103,10 +94,7 @@ private slots:
|
|||||||
|
|
||||||
ctx.book->openFromPath(path);
|
ctx.book->openFromPath(path);
|
||||||
|
|
||||||
// loading should have become true
|
|
||||||
QVERIFY(loading.count() > 0 || ctx.book->loading());
|
QVERIFY(loading.count() > 0 || ctx.book->loading());
|
||||||
|
|
||||||
// Wait for the async open to complete
|
|
||||||
QTRY_VERIFY_WITH_TIMEOUT(ctx.book->hasBook(), 5000);
|
QTRY_VERIFY_WITH_TIMEOUT(ctx.book->hasBook(), 5000);
|
||||||
|
|
||||||
QVERIFY(!ctx.book->loading());
|
QVERIFY(!ctx.book->loading());
|
||||||
@@ -120,7 +108,7 @@ private slots:
|
|||||||
Ctx ctx;
|
Ctx ctx;
|
||||||
QSignalSpy errorSpy(ctx.book, &Book::errorMessageChanged);
|
QSignalSpy errorSpy(ctx.book, &Book::errorMessageChanged);
|
||||||
|
|
||||||
ctx.book->openFromPath(QStringLiteral("/nonexistent/file.txt"));
|
ctx.book->openFromPath(QStringLiteral("/nonexistent/file.cbz"));
|
||||||
|
|
||||||
QTRY_VERIFY_WITH_TIMEOUT(!ctx.book->errorMessage().isEmpty(), 5000);
|
QTRY_VERIFY_WITH_TIMEOUT(!ctx.book->errorMessage().isEmpty(), 5000);
|
||||||
QVERIFY(!ctx.book->hasBook());
|
QVERIFY(!ctx.book->hasBook());
|
||||||
@@ -130,7 +118,7 @@ private slots:
|
|||||||
void clearError()
|
void clearError()
|
||||||
{
|
{
|
||||||
Ctx ctx;
|
Ctx ctx;
|
||||||
ctx.book->openFromPath(QStringLiteral("/nonexistent/file.txt"));
|
ctx.book->openFromPath(QStringLiteral("/nonexistent/file.cbz"));
|
||||||
QTRY_VERIFY_WITH_TIMEOUT(!ctx.book->errorMessage().isEmpty(), 5000);
|
QTRY_VERIFY_WITH_TIMEOUT(!ctx.book->errorMessage().isEmpty(), 5000);
|
||||||
|
|
||||||
QSignalSpy errorSpy(ctx.book, &Book::errorMessageChanged);
|
QSignalSpy errorSpy(ctx.book, &Book::errorMessageChanged);
|
||||||
@@ -141,9 +129,9 @@ private slots:
|
|||||||
|
|
||||||
void closeBook()
|
void closeBook()
|
||||||
{
|
{
|
||||||
const QString path = txtFixture();
|
QTemporaryDir tmp;
|
||||||
if (path.isEmpty() || !QFileInfo::exists(path))
|
const QString path = createSampleComic(tmp);
|
||||||
QSKIP("No TXT fixture");
|
QVERIFY(!path.isEmpty());
|
||||||
|
|
||||||
Ctx ctx;
|
Ctx ctx;
|
||||||
ctx.book->openFromPath(path);
|
ctx.book->openFromPath(path);
|
||||||
@@ -157,24 +145,24 @@ private slots:
|
|||||||
|
|
||||||
void willOpenNewBookFiredBeforeSwap()
|
void willOpenNewBookFiredBeforeSwap()
|
||||||
{
|
{
|
||||||
const QString path = txtFixture();
|
QTemporaryDir tmp;
|
||||||
if (path.isEmpty() || !QFileInfo::exists(path))
|
const QString path = createSampleComic(tmp);
|
||||||
QSKIP("No TXT fixture");
|
QVERIFY(!path.isEmpty());
|
||||||
|
|
||||||
Ctx ctx;
|
Ctx ctx;
|
||||||
ctx.book->openFromPath(path);
|
ctx.book->openFromPath(path);
|
||||||
QTRY_VERIFY_WITH_TIMEOUT(ctx.book->hasBook(), 5000);
|
QTRY_VERIFY_WITH_TIMEOUT(ctx.book->hasBook(), 5000);
|
||||||
|
|
||||||
QSignalSpy willOpen(ctx.book, &Book::willOpenNewBook);
|
QSignalSpy willOpen(ctx.book, &Book::willOpenNewBook);
|
||||||
ctx.book->openFromPath(path); // second open triggers willOpenNewBook
|
ctx.book->openFromPath(path);
|
||||||
QCOMPARE(willOpen.count(), 1);
|
QCOMPARE(willOpen.count(), 1);
|
||||||
}
|
}
|
||||||
|
|
||||||
void openFromUrl()
|
void openFromUrl()
|
||||||
{
|
{
|
||||||
const QString path = txtFixture();
|
QTemporaryDir tmp;
|
||||||
if (path.isEmpty() || !QFileInfo::exists(path))
|
const QString path = createSampleComic(tmp);
|
||||||
QSKIP("No TXT fixture");
|
QVERIFY(!path.isEmpty());
|
||||||
|
|
||||||
Ctx ctx;
|
Ctx ctx;
|
||||||
ctx.book->openFromUrl(QUrl::fromLocalFile(path));
|
ctx.book->openFromUrl(QUrl::fromLocalFile(path));
|
||||||
@@ -184,24 +172,21 @@ private slots:
|
|||||||
|
|
||||||
void browseAndOpenDelegatesToDialog()
|
void browseAndOpenDelegatesToDialog()
|
||||||
{
|
{
|
||||||
|
QTemporaryDir tmp;
|
||||||
|
const QString path = createSampleComic(tmp);
|
||||||
|
QVERIFY(!path.isEmpty());
|
||||||
|
|
||||||
Ctx ctx;
|
Ctx ctx;
|
||||||
QSignalSpy loading(ctx.book, &Book::loadingChanged);
|
ctx.book->browseAndOpen();
|
||||||
|
|
||||||
const QString path = txtFixture();
|
|
||||||
if (path.isEmpty() || !QFileInfo::exists(path))
|
|
||||||
QSKIP("No TXT fixture");
|
|
||||||
|
|
||||||
// Simulate the dialog emitting fileSelected
|
|
||||||
ctx.book->browseAndOpen(); // calls dialog.open() which in FakeDialogService is a no-op
|
|
||||||
ctx.dialog->triggerFile(path);
|
ctx.dialog->triggerFile(path);
|
||||||
QTRY_VERIFY_WITH_TIMEOUT(ctx.book->hasBook(), 5000);
|
QTRY_VERIFY_WITH_TIMEOUT(ctx.book->hasBook(), 5000);
|
||||||
}
|
}
|
||||||
|
|
||||||
void saveCurrentPositionUsesHash()
|
void saveCurrentPositionUsesHash()
|
||||||
{
|
{
|
||||||
const QString path = txtFixture();
|
QTemporaryDir tmp;
|
||||||
if (path.isEmpty() || !QFileInfo::exists(path))
|
const QString path = createSampleComic(tmp);
|
||||||
QSKIP("No TXT fixture");
|
QVERIFY(!path.isEmpty());
|
||||||
|
|
||||||
Ctx ctx;
|
Ctx ctx;
|
||||||
ctx.book->openFromPath(path);
|
ctx.book->openFromPath(path);
|
||||||
|
|||||||
Vendored
-13
@@ -1,13 +0,0 @@
|
|||||||
The Art of Reading
|
|
||||||
|
|
||||||
Books are a uniquely portable magic. They transport us to worlds unknown,
|
|
||||||
introduce us to people we would never otherwise meet, and allow us to
|
|
||||||
experience lives vastly different from our own.
|
|
||||||
|
|
||||||
Reading is not just a pastime — it is a journey of the mind.
|
|
||||||
|
|
||||||
Искусство чтения
|
|
||||||
|
|
||||||
Книги — это уникальная портативная магия. Они переносят нас в неизведанные
|
|
||||||
миры, знакомят с людьми, которых мы никогда бы не встретили, и позволяют
|
|
||||||
пережить жизни, совершенно отличные от нашей собственной.
|
|
||||||
Vendored
-2
@@ -1,2 +0,0 @@
|
|||||||
Привет, мир! Это тестовый файл в кодировке Windows-1251.
|
|
||||||
Русская литература — великое наследие.
|
|
||||||
@@ -137,10 +137,7 @@ private slots:
|
|||||||
|
|
||||||
CbzReader reader;
|
CbzReader reader;
|
||||||
QVERIFY(reader.open(path));
|
QVERIFY(reader.open(path));
|
||||||
QCOMPARE(reader.chapterCount(), 1);
|
QCOMPARE(reader.pages().size(), 3);
|
||||||
|
|
||||||
const Chapter ch = reader.loadChapter(0);
|
|
||||||
QCOMPARE(ch.contentChunks.size(), 3);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void pagesAreSorted()
|
void pagesAreSorted()
|
||||||
@@ -155,14 +152,14 @@ private slots:
|
|||||||
|
|
||||||
CbzReader reader;
|
CbzReader reader;
|
||||||
QVERIFY(reader.open(path));
|
QVERIFY(reader.open(path));
|
||||||
const Chapter ch = reader.loadChapter(0);
|
const auto pages = reader.pages();
|
||||||
QCOMPARE(ch.contentChunks.size(), 3);
|
QCOMPARE(pages.size(), 3);
|
||||||
QVERIFY(ch.contentChunks.at(0).contains(QLatin1String("page001.png")));
|
QVERIFY(pages.at(0).imageUrl.contains(QLatin1String("page001.png")));
|
||||||
QVERIFY(ch.contentChunks.at(1).contains(QLatin1String("page002.png")));
|
QVERIFY(pages.at(1).imageUrl.contains(QLatin1String("page002.png")));
|
||||||
QVERIFY(ch.contentChunks.at(2).contains(QLatin1String("page003.png")));
|
QVERIFY(pages.at(2).imageUrl.contains(QLatin1String("page003.png")));
|
||||||
}
|
}
|
||||||
|
|
||||||
void oneChunkPerPage()
|
void pagesHaveValidImageUrls()
|
||||||
{
|
{
|
||||||
const QString path = makeCbz({
|
const QString path = makeCbz({
|
||||||
{"p01.jpg", makePng()},
|
{"p01.jpg", makePng()},
|
||||||
@@ -172,31 +169,18 @@ private slots:
|
|||||||
|
|
||||||
CbzReader reader;
|
CbzReader reader;
|
||||||
QVERIFY(reader.open(path));
|
QVERIFY(reader.open(path));
|
||||||
const Chapter ch = reader.loadChapter(0);
|
const auto pages = reader.pages();
|
||||||
QCOMPARE(ch.contentChunks.size(), 2);
|
QCOMPARE(pages.size(), 2);
|
||||||
|
|
||||||
// Each chunk is an HTML fragment with a single image://cbz/ img tag
|
for (const PageInfo &page : pages) {
|
||||||
for (const QString &chunk : ch.contentChunks) {
|
QVERIFY(page.imageUrl.startsWith(QLatin1String("image://cbz/")));
|
||||||
QVERIFY(chunk.contains(QLatin1String("image://cbz/")));
|
|
||||||
QCOMPARE(chunk.count(QLatin1String("<img")), 1);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void outOfRangeChapterReturnsEmpty()
|
void emptyPagesBeforeOpen()
|
||||||
{
|
|
||||||
const QString path = makeCbz({{"page001.png", makePng()}});
|
|
||||||
QVERIFY(!path.isEmpty());
|
|
||||||
|
|
||||||
CbzReader reader;
|
|
||||||
QVERIFY(reader.open(path));
|
|
||||||
const Chapter ch = reader.loadChapter(5);
|
|
||||||
QVERIFY(ch.contentChunks.isEmpty());
|
|
||||||
}
|
|
||||||
|
|
||||||
void emptyChapterCountBeforeOpen()
|
|
||||||
{
|
{
|
||||||
CbzReader reader;
|
CbzReader reader;
|
||||||
QCOMPARE(reader.chapterCount(), 0);
|
QVERIFY(reader.pages().isEmpty());
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- metadata: ComicInfo.xml present ---
|
// --- metadata: ComicInfo.xml present ---
|
||||||
@@ -272,16 +256,6 @@ private slots:
|
|||||||
QVERIFY(reader.author().isEmpty());
|
QVERIFY(reader.author().isEmpty());
|
||||||
}
|
}
|
||||||
|
|
||||||
void tableOfContentsIsEmpty()
|
|
||||||
{
|
|
||||||
const QString path = makeCbz({{"page001.png", makePng()}});
|
|
||||||
QVERIFY(!path.isEmpty());
|
|
||||||
|
|
||||||
CbzReader reader;
|
|
||||||
QVERIFY(reader.open(path));
|
|
||||||
QVERIFY(reader.tableOfContents().isEmpty());
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- cover ---
|
// --- cover ---
|
||||||
|
|
||||||
void coverFallbackToFirstSortedPage()
|
void coverFallbackToFirstSortedPage()
|
||||||
@@ -396,7 +370,7 @@ private slots:
|
|||||||
|
|
||||||
CbzReader reader;
|
CbzReader reader;
|
||||||
QVERIFY(reader.open(path));
|
QVERIFY(reader.open(path));
|
||||||
QCOMPARE(reader.loadChapter(0).contentChunks.size(), 1);
|
QCOMPARE(reader.pages().size(), 1);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -1,614 +0,0 @@
|
|||||||
#include <QtTest/QtTest>
|
|
||||||
#include <QDir>
|
|
||||||
#include <QFile>
|
|
||||||
#include <QTemporaryFile>
|
|
||||||
|
|
||||||
#include <minizip/zip.h>
|
|
||||||
|
|
||||||
#include "backend/formats/EpubReader.h"
|
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
|
||||||
// Minimal EPUB fixture builder (uses minizip directly)
|
|
||||||
// ---------------------------------------------------------------------------
|
|
||||||
|
|
||||||
static const char kMimetype[] = "application/epub+zip";
|
|
||||||
|
|
||||||
static const char kContainer[] =
|
|
||||||
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
|
|
||||||
"<container version=\"1.0\" xmlns=\"urn:oasis:names:tc:opendocument:xmlns:container\">"
|
|
||||||
" <rootfiles>"
|
|
||||||
" <rootfile full-path=\"OEBPS/content.opf\""
|
|
||||||
" media-type=\"application/oebps-package+xml\"/>"
|
|
||||||
" </rootfiles>"
|
|
||||||
"</container>";
|
|
||||||
|
|
||||||
static const char kOpf[] =
|
|
||||||
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
|
|
||||||
"<package xmlns=\"http://www.idpf.org/2007/opf\" version=\"2.0\" unique-identifier=\"BookId\">"
|
|
||||||
" <metadata xmlns:dc=\"http://purl.org/dc/elements/1.1/\">"
|
|
||||||
" <dc:title>Test Book</dc:title>"
|
|
||||||
" <dc:creator>Test Author</dc:creator>"
|
|
||||||
" </metadata>"
|
|
||||||
" <manifest>"
|
|
||||||
" <item id=\"ncx\" href=\"toc.ncx\" media-type=\"application/x-dtbncx+xml\"/>"
|
|
||||||
" <item id=\"ch1\" href=\"chapter1.xhtml\" media-type=\"application/xhtml+xml\"/>"
|
|
||||||
" <item id=\"ch2\" href=\"chapter2.xhtml\" media-type=\"application/xhtml+xml\"/>"
|
|
||||||
" </manifest>"
|
|
||||||
" <spine toc=\"ncx\">"
|
|
||||||
" <itemref idref=\"ch1\"/>"
|
|
||||||
" <itemref idref=\"ch2\"/>"
|
|
||||||
" </spine>"
|
|
||||||
"</package>";
|
|
||||||
|
|
||||||
static const char kNcx[] =
|
|
||||||
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
|
|
||||||
"<ncx xmlns=\"http://www.daisy.org/z3986/2005/ncx/\" version=\"2005-1\">"
|
|
||||||
" <navMap>"
|
|
||||||
" <navPoint id=\"np1\" playOrder=\"1\">"
|
|
||||||
" <navLabel><text>Chapter One</text></navLabel>"
|
|
||||||
" <content src=\"chapter1.xhtml\"/>"
|
|
||||||
" </navPoint>"
|
|
||||||
" <navPoint id=\"np2\" playOrder=\"2\">"
|
|
||||||
" <navLabel><text>Chapter Two</text></navLabel>"
|
|
||||||
" <content src=\"chapter2.xhtml\"/>"
|
|
||||||
" </navPoint>"
|
|
||||||
" </navMap>"
|
|
||||||
"</ncx>";
|
|
||||||
|
|
||||||
static const char kChapter1[] =
|
|
||||||
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
|
|
||||||
"<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\" \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">"
|
|
||||||
"<html xmlns=\"http://www.w3.org/1999/xhtml\">"
|
|
||||||
" <head><title>Chapter One</title></head>"
|
|
||||||
" <body>"
|
|
||||||
" <h1>Chapter One</h1>"
|
|
||||||
" <p>First paragraph of chapter one.</p>"
|
|
||||||
" <p>Second paragraph of chapter one.</p>"
|
|
||||||
" </body>"
|
|
||||||
"</html>";
|
|
||||||
|
|
||||||
static const char kChapter2[] =
|
|
||||||
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
|
|
||||||
"<html xmlns=\"http://www.w3.org/1999/xhtml\">"
|
|
||||||
" <head><title>Chapter Two</title></head>"
|
|
||||||
" <body>"
|
|
||||||
" <p>This is chapter two content.</p>"
|
|
||||||
" </body>"
|
|
||||||
"</html>";
|
|
||||||
|
|
||||||
// Add one entry to an open zipFile handle.
|
|
||||||
static bool addEntry(zipFile zf, const char *name, const QByteArray &data, bool store = false)
|
|
||||||
{
|
|
||||||
zip_fileinfo fi{};
|
|
||||||
int method = store ? Z_NO_COMPRESSION : Z_DEFLATED;
|
|
||||||
int level = store ? 0 : Z_DEFAULT_COMPRESSION;
|
|
||||||
if (zipOpenNewFileInZip(zf, name, &fi,
|
|
||||||
nullptr, 0, nullptr, 0, nullptr,
|
|
||||||
method, level) != ZIP_OK)
|
|
||||||
return false;
|
|
||||||
if (zipWriteInFileInZip(zf, data.constData(), (unsigned)data.size()) != ZIP_OK) {
|
|
||||||
zipCloseFileInZip(zf);
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
return zipCloseFileInZip(zf) == ZIP_OK;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Build a minimal two-chapter EPUB and return its file path (caller deletes).
|
|
||||||
static QString buildSampleEpub()
|
|
||||||
{
|
|
||||||
QTemporaryFile tmp;
|
|
||||||
tmp.setFileTemplate(QDir::tempPath() + "/epub_test_XXXXXX.epub");
|
|
||||||
tmp.setAutoRemove(false);
|
|
||||||
if (!tmp.open()) return {};
|
|
||||||
const QString path = tmp.fileName();
|
|
||||||
tmp.close();
|
|
||||||
|
|
||||||
zipFile zf = zipOpen(path.toUtf8().constData(), APPEND_STATUS_CREATE);
|
|
||||||
if (!zf) return {};
|
|
||||||
|
|
||||||
bool ok = true;
|
|
||||||
ok = ok && addEntry(zf, "mimetype", QByteArray(kMimetype), /*store=*/true);
|
|
||||||
ok = ok && addEntry(zf, "META-INF/container.xml", QByteArray(kContainer));
|
|
||||||
ok = ok && addEntry(zf, "OEBPS/content.opf", QByteArray(kOpf));
|
|
||||||
ok = ok && addEntry(zf, "OEBPS/toc.ncx", QByteArray(kNcx));
|
|
||||||
ok = ok && addEntry(zf, "OEBPS/chapter1.xhtml", QByteArray(kChapter1));
|
|
||||||
ok = ok && addEntry(zf, "OEBPS/chapter2.xhtml", QByteArray(kChapter2));
|
|
||||||
|
|
||||||
zipClose(zf, nullptr);
|
|
||||||
return ok ? path : QString{};
|
|
||||||
}
|
|
||||||
|
|
||||||
// Build an EPUB with an <img> tag in the chapter (image at OEBPS/Images/test.png).
|
|
||||||
static QString buildEpubWithImage()
|
|
||||||
{
|
|
||||||
static const char opfImg[] =
|
|
||||||
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
|
|
||||||
"<package xmlns=\"http://www.idpf.org/2007/opf\" version=\"2.0\">"
|
|
||||||
" <metadata xmlns:dc=\"http://purl.org/dc/elements/1.1/\">"
|
|
||||||
" <dc:title>Image Book</dc:title>"
|
|
||||||
" <dc:creator>Tester</dc:creator>"
|
|
||||||
" </metadata>"
|
|
||||||
" <manifest>"
|
|
||||||
" <item id=\"ch1\" href=\"chapter1.xhtml\" media-type=\"application/xhtml+xml\"/>"
|
|
||||||
" <item id=\"img\" href=\"Images/test.png\" media-type=\"image/png\"/>"
|
|
||||||
" </manifest>"
|
|
||||||
" <spine>"
|
|
||||||
" <itemref idref=\"ch1\"/>"
|
|
||||||
" </spine>"
|
|
||||||
"</package>";
|
|
||||||
|
|
||||||
static const char chapterImg[] =
|
|
||||||
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
|
|
||||||
"<html xmlns=\"http://www.w3.org/1999/xhtml\">"
|
|
||||||
" <head><title>Image Chapter</title></head>"
|
|
||||||
" <body>"
|
|
||||||
" <p>Chapter with image</p>"
|
|
||||||
" <img src=\"Images/test.png\"/>"
|
|
||||||
" </body>"
|
|
||||||
"</html>";
|
|
||||||
|
|
||||||
QTemporaryFile tmp;
|
|
||||||
tmp.setFileTemplate(QDir::tempPath() + "/epub_img_XXXXXX.epub");
|
|
||||||
tmp.setAutoRemove(false);
|
|
||||||
if (!tmp.open()) return {};
|
|
||||||
const QString path = tmp.fileName();
|
|
||||||
tmp.close();
|
|
||||||
|
|
||||||
zipFile zf = zipOpen(path.toUtf8().constData(), APPEND_STATUS_CREATE);
|
|
||||||
if (!zf) return {};
|
|
||||||
|
|
||||||
bool ok = true;
|
|
||||||
ok = ok && addEntry(zf, "mimetype", QByteArray(kMimetype), true);
|
|
||||||
ok = ok && addEntry(zf, "META-INF/container.xml", QByteArray(kContainer));
|
|
||||||
ok = ok && addEntry(zf, "OEBPS/content.opf", QByteArray(opfImg));
|
|
||||||
ok = ok && addEntry(zf, "OEBPS/chapter1.xhtml", QByteArray(chapterImg));
|
|
||||||
ok = ok && addEntry(zf, "OEBPS/Images/test.png", QByteArray("DUMMY_PNG"));
|
|
||||||
|
|
||||||
zipClose(zf, nullptr);
|
|
||||||
return ok ? path : QString{};
|
|
||||||
}
|
|
||||||
|
|
||||||
// Build an EPUB with a chapter in a subdirectory and a relative image path.
|
|
||||||
static QString buildEpubWithRelativeImage()
|
|
||||||
{
|
|
||||||
static const char opfRel[] =
|
|
||||||
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
|
|
||||||
"<package xmlns=\"http://www.idpf.org/2007/opf\" version=\"2.0\">"
|
|
||||||
" <metadata xmlns:dc=\"http://purl.org/dc/elements/1.1/\">"
|
|
||||||
" <dc:title>Relative Image Book</dc:title>"
|
|
||||||
" <dc:creator>Tester</dc:creator>"
|
|
||||||
" </metadata>"
|
|
||||||
" <manifest>"
|
|
||||||
" <item id=\"ch1\" href=\"Text/chapter1.xhtml\" media-type=\"application/xhtml+xml\"/>"
|
|
||||||
" <item id=\"img\" href=\"Images/test.png\" media-type=\"image/png\"/>"
|
|
||||||
" </manifest>"
|
|
||||||
" <spine>"
|
|
||||||
" <itemref idref=\"ch1\"/>"
|
|
||||||
" </spine>"
|
|
||||||
"</package>";
|
|
||||||
|
|
||||||
static const char chapterRel[] =
|
|
||||||
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
|
|
||||||
"<html xmlns=\"http://www.w3.org/1999/xhtml\">"
|
|
||||||
" <head><title>Relative Image Chapter</title></head>"
|
|
||||||
" <body>"
|
|
||||||
" <p>Chapter with relative image</p>"
|
|
||||||
" <img src=\"../Images/test.png\"/>"
|
|
||||||
" </body>"
|
|
||||||
"</html>";
|
|
||||||
|
|
||||||
QTemporaryFile tmp;
|
|
||||||
tmp.setFileTemplate(QDir::tempPath() + "/epub_relimg_XXXXXX.epub");
|
|
||||||
tmp.setAutoRemove(false);
|
|
||||||
if (!tmp.open()) return {};
|
|
||||||
const QString path = tmp.fileName();
|
|
||||||
tmp.close();
|
|
||||||
|
|
||||||
zipFile zf = zipOpen(path.toUtf8().constData(), APPEND_STATUS_CREATE);
|
|
||||||
if (!zf) return {};
|
|
||||||
|
|
||||||
bool ok = true;
|
|
||||||
ok = ok && addEntry(zf, "mimetype", QByteArray(kMimetype), true);
|
|
||||||
ok = ok && addEntry(zf, "META-INF/container.xml", QByteArray(kContainer));
|
|
||||||
ok = ok && addEntry(zf, "OEBPS/content.opf", QByteArray(opfRel));
|
|
||||||
ok = ok && addEntry(zf, "OEBPS/Text/chapter1.xhtml", QByteArray(chapterRel));
|
|
||||||
ok = ok && addEntry(zf, "OEBPS/Images/test.png", QByteArray("DUMMY_PNG"));
|
|
||||||
|
|
||||||
zipClose(zf, nullptr);
|
|
||||||
return ok ? path : QString{};
|
|
||||||
}
|
|
||||||
|
|
||||||
// Build an EPUB without an NCX.
|
|
||||||
static QString buildEpubNoNcx()
|
|
||||||
{
|
|
||||||
static const char opfNoNcx[] =
|
|
||||||
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
|
|
||||||
"<package xmlns=\"http://www.idpf.org/2007/opf\" version=\"2.0\">"
|
|
||||||
" <metadata xmlns:dc=\"http://purl.org/dc/elements/1.1/\">"
|
|
||||||
" <dc:title>No TOC Book</dc:title>"
|
|
||||||
" <dc:creator>Nobody</dc:creator>"
|
|
||||||
" </metadata>"
|
|
||||||
" <manifest>"
|
|
||||||
" <item id=\"ch1\" href=\"chapter1.xhtml\" media-type=\"application/xhtml+xml\"/>"
|
|
||||||
" </manifest>"
|
|
||||||
" <spine>"
|
|
||||||
" <itemref idref=\"ch1\"/>"
|
|
||||||
" </spine>"
|
|
||||||
"</package>";
|
|
||||||
|
|
||||||
QTemporaryFile tmp;
|
|
||||||
tmp.setFileTemplate(QDir::tempPath() + "/epub_notoc_XXXXXX.epub");
|
|
||||||
tmp.setAutoRemove(false);
|
|
||||||
if (!tmp.open()) return {};
|
|
||||||
const QString path = tmp.fileName();
|
|
||||||
tmp.close();
|
|
||||||
|
|
||||||
zipFile zf = zipOpen(path.toUtf8().constData(), APPEND_STATUS_CREATE);
|
|
||||||
if (!zf) return {};
|
|
||||||
|
|
||||||
bool ok = true;
|
|
||||||
ok = ok && addEntry(zf, "mimetype", QByteArray(kMimetype), true);
|
|
||||||
ok = ok && addEntry(zf, "META-INF/container.xml", QByteArray(kContainer));
|
|
||||||
ok = ok && addEntry(zf, "OEBPS/content.opf", QByteArray(opfNoNcx));
|
|
||||||
ok = ok && addEntry(zf, "OEBPS/chapter1.xhtml", QByteArray(kChapter1));
|
|
||||||
|
|
||||||
zipClose(zf, nullptr);
|
|
||||||
return ok ? path : QString{};
|
|
||||||
}
|
|
||||||
|
|
||||||
// Build an EPUB with one large chapter (>4096 chars of <p> elements).
|
|
||||||
static QString buildEpubLargeChapter()
|
|
||||||
{
|
|
||||||
QString body;
|
|
||||||
for (int i = 0; i < 60; ++i)
|
|
||||||
body += QString("<p>Paragraph %1: The quick brown fox jumped over the lazy dog repeatedly.</p>\n").arg(i + 1);
|
|
||||||
|
|
||||||
QByteArray chapterXhtml =
|
|
||||||
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
|
|
||||||
"<html xmlns=\"http://www.w3.org/1999/xhtml\">"
|
|
||||||
"<head><title>Big</title></head>"
|
|
||||||
"<body>" + body.toUtf8() + "</body>"
|
|
||||||
"</html>";
|
|
||||||
|
|
||||||
static const char opfLarge[] =
|
|
||||||
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
|
|
||||||
"<package xmlns=\"http://www.idpf.org/2007/opf\" version=\"2.0\">"
|
|
||||||
" <metadata xmlns:dc=\"http://purl.org/dc/elements/1.1/\">"
|
|
||||||
" <dc:title>Large</dc:title>"
|
|
||||||
" <dc:creator>Writer</dc:creator>"
|
|
||||||
" </metadata>"
|
|
||||||
" <manifest>"
|
|
||||||
" <item id=\"ch1\" href=\"chapter1.xhtml\" media-type=\"application/xhtml+xml\"/>"
|
|
||||||
" </manifest>"
|
|
||||||
" <spine>"
|
|
||||||
" <itemref idref=\"ch1\"/>"
|
|
||||||
" </spine>"
|
|
||||||
"</package>";
|
|
||||||
|
|
||||||
QTemporaryFile tmp;
|
|
||||||
tmp.setFileTemplate(QDir::tempPath() + "/epub_large_XXXXXX.epub");
|
|
||||||
tmp.setAutoRemove(false);
|
|
||||||
if (!tmp.open()) return {};
|
|
||||||
const QString path = tmp.fileName();
|
|
||||||
tmp.close();
|
|
||||||
|
|
||||||
zipFile zf = zipOpen(path.toUtf8().constData(), APPEND_STATUS_CREATE);
|
|
||||||
if (!zf) return {};
|
|
||||||
|
|
||||||
bool ok = true;
|
|
||||||
ok = ok && addEntry(zf, "mimetype", QByteArray(kMimetype), true);
|
|
||||||
ok = ok && addEntry(zf, "META-INF/container.xml", QByteArray(kContainer));
|
|
||||||
ok = ok && addEntry(zf, "OEBPS/content.opf", QByteArray(opfLarge));
|
|
||||||
ok = ok && addEntry(zf, "OEBPS/chapter1.xhtml", chapterXhtml);
|
|
||||||
|
|
||||||
zipClose(zf, nullptr);
|
|
||||||
return ok ? path : QString{};
|
|
||||||
}
|
|
||||||
|
|
||||||
// Build an EPUB with a cover image using both meta tag and properties attribute
|
|
||||||
static QString buildEpubWithCoverImage()
|
|
||||||
{
|
|
||||||
static const char opfCover[] =
|
|
||||||
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
|
|
||||||
"<package xmlns=\"http://www.idpf.org/2007/opf\" version=\"2.0\">"
|
|
||||||
" <metadata xmlns:dc=\"http://purl.org/dc/elements/1.1/\">"
|
|
||||||
" <dc:title>Cover Book</dc:title>"
|
|
||||||
" <dc:creator>Cover Tester</dc:creator>"
|
|
||||||
" <meta name=\"cover\" content=\"cover-id\"/>"
|
|
||||||
" </metadata>"
|
|
||||||
" <manifest>"
|
|
||||||
" <item id=\"cover-id\" href=\"cover.jpg\" media-type=\"image/jpeg\" properties=\"cover-image\"/>"
|
|
||||||
" <item id=\"ch1\" href=\"chapter1.xhtml\" media-type=\"application/xhtml+xml\"/>"
|
|
||||||
" </manifest>"
|
|
||||||
" <spine>"
|
|
||||||
" <itemref idref=\"ch1\"/>"
|
|
||||||
" </spine>"
|
|
||||||
"</package>";
|
|
||||||
|
|
||||||
QTemporaryFile tmp;
|
|
||||||
tmp.setFileTemplate(QDir::tempPath() + "/epub_cover_XXXXXX.epub");
|
|
||||||
tmp.setAutoRemove(false);
|
|
||||||
if (!tmp.open()) return {};
|
|
||||||
const QString path = tmp.fileName();
|
|
||||||
tmp.close();
|
|
||||||
|
|
||||||
zipFile zf = zipOpen(path.toUtf8().constData(), APPEND_STATUS_CREATE);
|
|
||||||
if (!zf) return {};
|
|
||||||
|
|
||||||
bool ok = true;
|
|
||||||
ok = ok && addEntry(zf, "mimetype", QByteArray(kMimetype), true);
|
|
||||||
ok = ok && addEntry(zf, "META-INF/container.xml", QByteArray(kContainer));
|
|
||||||
ok = ok && addEntry(zf, "OEBPS/content.opf", QByteArray(opfCover));
|
|
||||||
ok = ok && addEntry(zf, "OEBPS/cover.jpg", QByteArray("DUMMY_JPEG"));
|
|
||||||
ok = ok && addEntry(zf, "OEBPS/chapter1.xhtml", QByteArray(kChapter1));
|
|
||||||
|
|
||||||
zipClose(zf, nullptr);
|
|
||||||
return ok ? path : QString{};
|
|
||||||
}
|
|
||||||
|
|
||||||
// Build an EPUB with cover image in subdirectory
|
|
||||||
static QString buildEpubWithCoverImageInSubdir()
|
|
||||||
{
|
|
||||||
static const char opfCoverSubdir[] =
|
|
||||||
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
|
|
||||||
"<package xmlns=\"http://www.idpf.org/2007/opf\" version=\"2.0\">"
|
|
||||||
" <metadata xmlns:dc=\"http://purl.org/dc/elements/1.1/\">"
|
|
||||||
" <dc:title>Cover Subdir Book</dc:title>"
|
|
||||||
" <dc:creator>Subdir Tester</dc:creator>"
|
|
||||||
" <meta name=\"cover\" content=\"cover-img\"/>"
|
|
||||||
" </metadata>"
|
|
||||||
" <manifest>"
|
|
||||||
" <item id=\"cover-img\" href=\"Images/cover.jpg\" media-type=\"image/jpeg\" properties=\"cover-image\"/>"
|
|
||||||
" <item id=\"ch1\" href=\"chapter1.xhtml\" media-type=\"application/xhtml+xml\"/>"
|
|
||||||
" </manifest>"
|
|
||||||
" <spine>"
|
|
||||||
" <itemref idref=\"ch1\"/>"
|
|
||||||
" </spine>"
|
|
||||||
"</package>";
|
|
||||||
|
|
||||||
QTemporaryFile tmp;
|
|
||||||
tmp.setFileTemplate(QDir::tempPath() + "/epub_coversub_XXXXXX.epub");
|
|
||||||
tmp.setAutoRemove(false);
|
|
||||||
if (!tmp.open()) return {};
|
|
||||||
const QString path = tmp.fileName();
|
|
||||||
tmp.close();
|
|
||||||
|
|
||||||
zipFile zf = zipOpen(path.toUtf8().constData(), APPEND_STATUS_CREATE);
|
|
||||||
if (!zf) return {};
|
|
||||||
|
|
||||||
bool ok = true;
|
|
||||||
ok = ok && addEntry(zf, "mimetype", QByteArray(kMimetype), true);
|
|
||||||
ok = ok && addEntry(zf, "META-INF/container.xml", QByteArray(kContainer));
|
|
||||||
ok = ok && addEntry(zf, "OEBPS/content.opf", QByteArray(opfCoverSubdir));
|
|
||||||
ok = ok && addEntry(zf, "OEBPS/Images/cover.jpg", QByteArray("DUMMY_JPEG"));
|
|
||||||
ok = ok && addEntry(zf, "OEBPS/chapter1.xhtml", QByteArray(kChapter1));
|
|
||||||
|
|
||||||
zipClose(zf, nullptr);
|
|
||||||
return ok ? path : QString{};
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
|
||||||
// Test class
|
|
||||||
// ---------------------------------------------------------------------------
|
|
||||||
|
|
||||||
class EpubReaderTest : public QObject {
|
|
||||||
Q_OBJECT
|
|
||||||
|
|
||||||
private:
|
|
||||||
QString m_epubPath;
|
|
||||||
QString m_noNcxPath;
|
|
||||||
QString m_largePath;
|
|
||||||
QString m_imgPath;
|
|
||||||
QString m_relImgPath;
|
|
||||||
QString m_coverPath;
|
|
||||||
QString m_coverSubdirPath;
|
|
||||||
|
|
||||||
private slots:
|
|
||||||
void initTestCase()
|
|
||||||
{
|
|
||||||
m_epubPath = buildSampleEpub();
|
|
||||||
m_noNcxPath = buildEpubNoNcx();
|
|
||||||
m_largePath = buildEpubLargeChapter();
|
|
||||||
m_imgPath = buildEpubWithImage();
|
|
||||||
m_relImgPath = buildEpubWithRelativeImage();
|
|
||||||
m_coverPath = buildEpubWithCoverImage();
|
|
||||||
m_coverSubdirPath = buildEpubWithCoverImageInSubdir();
|
|
||||||
QVERIFY2(!m_epubPath.isEmpty(), "Failed to build sample EPUB fixture");
|
|
||||||
QVERIFY2(!m_noNcxPath.isEmpty(), "Failed to build no-NCX EPUB fixture");
|
|
||||||
QVERIFY2(!m_largePath.isEmpty(), "Failed to build large chapter EPUB fixture");
|
|
||||||
QVERIFY2(!m_imgPath.isEmpty(), "Failed to build image EPUB fixture");
|
|
||||||
QVERIFY2(!m_relImgPath.isEmpty(), "Failed to build relative-image EPUB fixture");
|
|
||||||
QVERIFY2(!m_coverPath.isEmpty(), "Failed to build cover image EPUB fixture");
|
|
||||||
QVERIFY2(!m_coverSubdirPath.isEmpty(), "Failed to build cover image subdir EPUB fixture");
|
|
||||||
}
|
|
||||||
|
|
||||||
void cleanupTestCase()
|
|
||||||
{
|
|
||||||
QFile::remove(m_epubPath);
|
|
||||||
QFile::remove(m_noNcxPath);
|
|
||||||
QFile::remove(m_largePath);
|
|
||||||
QFile::remove(m_imgPath);
|
|
||||||
QFile::remove(m_relImgPath);
|
|
||||||
QFile::remove(m_coverPath);
|
|
||||||
QFile::remove(m_coverSubdirPath);
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- Phase 2: error handling ---
|
|
||||||
|
|
||||||
void openNonexistentFile()
|
|
||||||
{
|
|
||||||
EpubReader reader;
|
|
||||||
QVERIFY(!reader.open("/tmp/does_not_exist_xyzzy.epub"));
|
|
||||||
QVERIFY(!reader.lastError().isEmpty());
|
|
||||||
}
|
|
||||||
|
|
||||||
void openInvalidZip()
|
|
||||||
{
|
|
||||||
QTemporaryFile tmp;
|
|
||||||
QVERIFY(tmp.open());
|
|
||||||
tmp.write("This is not a zip file.\n");
|
|
||||||
tmp.flush();
|
|
||||||
|
|
||||||
EpubReader reader;
|
|
||||||
QVERIFY(!reader.open(tmp.fileName()));
|
|
||||||
QVERIFY(!reader.lastError().isEmpty());
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- Phase 3: metadata ---
|
|
||||||
|
|
||||||
void openValidEpub()
|
|
||||||
{
|
|
||||||
EpubReader reader;
|
|
||||||
QVERIFY(reader.open(m_epubPath));
|
|
||||||
}
|
|
||||||
|
|
||||||
void titleExtracted()
|
|
||||||
{
|
|
||||||
EpubReader reader;
|
|
||||||
QVERIFY(reader.open(m_epubPath));
|
|
||||||
QCOMPARE(reader.title(), QStringLiteral("Test Book"));
|
|
||||||
}
|
|
||||||
|
|
||||||
void authorExtracted()
|
|
||||||
{
|
|
||||||
EpubReader reader;
|
|
||||||
QVERIFY(reader.open(m_epubPath));
|
|
||||||
QCOMPARE(reader.author(), QStringLiteral("Test Author"));
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- Phase 4: chapters ---
|
|
||||||
|
|
||||||
void chapterCountMatchesSpine()
|
|
||||||
{
|
|
||||||
EpubReader reader;
|
|
||||||
QVERIFY(reader.open(m_epubPath));
|
|
||||||
QCOMPARE(reader.chapterCount(), 2);
|
|
||||||
}
|
|
||||||
|
|
||||||
void loadChapterContent()
|
|
||||||
{
|
|
||||||
EpubReader reader;
|
|
||||||
QVERIFY(reader.open(m_epubPath));
|
|
||||||
Chapter ch = reader.loadChapter(0);
|
|
||||||
QCOMPARE(ch.index, 0);
|
|
||||||
QVERIFY(!ch.contentChunks.isEmpty());
|
|
||||||
const QString combined = ch.contentChunks.join('\n');
|
|
||||||
QVERIFY(combined.contains("First paragraph"));
|
|
||||||
}
|
|
||||||
|
|
||||||
void loadChapterTwo()
|
|
||||||
{
|
|
||||||
EpubReader reader;
|
|
||||||
QVERIFY(reader.open(m_epubPath));
|
|
||||||
Chapter ch = reader.loadChapter(1);
|
|
||||||
QCOMPARE(ch.index, 1);
|
|
||||||
QVERIFY(!ch.contentChunks.isEmpty());
|
|
||||||
const QString combined = ch.contentChunks.join('\n');
|
|
||||||
QVERIFY(combined.contains("chapter two"));
|
|
||||||
}
|
|
||||||
|
|
||||||
void loadChapterOutOfRange()
|
|
||||||
{
|
|
||||||
EpubReader reader;
|
|
||||||
QVERIFY(reader.open(m_epubPath));
|
|
||||||
Chapter ch = reader.loadChapter(99);
|
|
||||||
QVERIFY(ch.contentChunks.isEmpty());
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- Phase 5: TOC ---
|
|
||||||
|
|
||||||
void tableOfContentsFromNcx()
|
|
||||||
{
|
|
||||||
EpubReader reader;
|
|
||||||
QVERIFY(reader.open(m_epubPath));
|
|
||||||
const QList<TocEntry> toc = reader.tableOfContents();
|
|
||||||
QCOMPARE(toc.size(), 2);
|
|
||||||
QCOMPARE(toc[0].title, QStringLiteral("Chapter One"));
|
|
||||||
QCOMPARE(toc[0].chapterIndex, 0);
|
|
||||||
QCOMPARE(toc[0].depth, 0);
|
|
||||||
QCOMPARE(toc[1].title, QStringLiteral("Chapter Two"));
|
|
||||||
QCOMPARE(toc[1].chapterIndex, 1);
|
|
||||||
}
|
|
||||||
|
|
||||||
void epubWithNoNcx()
|
|
||||||
{
|
|
||||||
EpubReader reader;
|
|
||||||
QVERIFY(reader.open(m_noNcxPath));
|
|
||||||
QVERIFY(reader.tableOfContents().isEmpty());
|
|
||||||
QCOMPARE(reader.chapterCount(), 1);
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- Phase 6: chunking ---
|
|
||||||
|
|
||||||
void largeChapterProducesMultipleChunks()
|
|
||||||
{
|
|
||||||
EpubReader reader;
|
|
||||||
QVERIFY(reader.open(m_largePath));
|
|
||||||
const Chapter ch = reader.loadChapter(0);
|
|
||||||
QVERIFY(ch.contentChunks.size() > 1);
|
|
||||||
}
|
|
||||||
|
|
||||||
void chunksAreStandaloneHtml()
|
|
||||||
{
|
|
||||||
EpubReader reader;
|
|
||||||
QVERIFY(reader.open(m_largePath));
|
|
||||||
const Chapter ch = reader.loadChapter(0);
|
|
||||||
for (const QString &chunk : ch.contentChunks) {
|
|
||||||
const bool hasBlock = chunk.contains("<p") || chunk.contains("<h1") ||
|
|
||||||
chunk.contains("<h2") || chunk.contains("<div");
|
|
||||||
QVERIFY2(hasBlock, "Chunk lacks any block element");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- Phase 7: image URL rewriting ---
|
|
||||||
|
|
||||||
void imageTagsRewrittenToProviderUrls()
|
|
||||||
{
|
|
||||||
EpubReader reader;
|
|
||||||
QVERIFY(reader.open(m_imgPath));
|
|
||||||
const Chapter ch = reader.loadChapter(0);
|
|
||||||
QVERIFY(!ch.contentChunks.isEmpty());
|
|
||||||
const QString combined = ch.contentChunks.join('\n');
|
|
||||||
const QString expected = QStringLiteral("image://epub/OEBPS/Images/test.png");
|
|
||||||
QVERIFY2(combined.contains(expected),
|
|
||||||
qPrintable(QStringLiteral("Expected ") + expected + QStringLiteral(" in: ") + combined));
|
|
||||||
}
|
|
||||||
|
|
||||||
void relativeImagePathResolved()
|
|
||||||
{
|
|
||||||
EpubReader reader;
|
|
||||||
QVERIFY(reader.open(m_relImgPath));
|
|
||||||
const Chapter ch = reader.loadChapter(0);
|
|
||||||
QVERIFY(!ch.contentChunks.isEmpty());
|
|
||||||
const QString combined = ch.contentChunks.join('\n');
|
|
||||||
const QString expected = QStringLiteral("image://epub/OEBPS/Images/test.png");
|
|
||||||
QVERIFY2(combined.contains(expected),
|
|
||||||
qPrintable(QStringLiteral("Expected ") + expected + QStringLiteral(" in: ") + combined));
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- Phase 8: cover image detection ---
|
|
||||||
|
|
||||||
void coverImagePathExtracted()
|
|
||||||
{
|
|
||||||
EpubReader reader;
|
|
||||||
QVERIFY(reader.open(m_coverPath));
|
|
||||||
QCOMPARE(reader.coverImagePath(), QStringLiteral("OEBPS/cover.jpg"));
|
|
||||||
}
|
|
||||||
|
|
||||||
void coverImagePathWithSubdirectory()
|
|
||||||
{
|
|
||||||
EpubReader reader;
|
|
||||||
QVERIFY(reader.open(m_coverSubdirPath));
|
|
||||||
QCOMPARE(reader.coverImagePath(), QStringLiteral("OEBPS/Images/cover.jpg"));
|
|
||||||
}
|
|
||||||
|
|
||||||
void coverImagePathEmptyForEpubWithoutCover()
|
|
||||||
{
|
|
||||||
EpubReader reader;
|
|
||||||
QVERIFY(reader.open(m_epubPath));
|
|
||||||
QVERIFY(reader.coverImagePath().isEmpty());
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
QTEST_MAIN(EpubReaderTest)
|
|
||||||
#include "EpubReaderTest.moc"
|
|
||||||
@@ -1,384 +0,0 @@
|
|||||||
#include <QtTest/QtTest>
|
|
||||||
#include <QDir>
|
|
||||||
#include <QFile>
|
|
||||||
#include <QTemporaryFile>
|
|
||||||
|
|
||||||
#include "backend/formats/Fb2Reader.h"
|
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
|
||||||
// Minimal FB2 fixture builder
|
|
||||||
// ---------------------------------------------------------------------------
|
|
||||||
|
|
||||||
static const char kFb2Header[] =
|
|
||||||
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
|
|
||||||
"<FictionBook xmlns=\"http://www.gribuser.ru/xml/fictionbook/2.0\""
|
|
||||||
" xmlns:l=\"http://www.w3.org/1999/xlink\">";
|
|
||||||
|
|
||||||
static const char kFb2Footer[] = "</FictionBook>";
|
|
||||||
|
|
||||||
static QString writeTempFb2(const QByteArray &content)
|
|
||||||
{
|
|
||||||
QTemporaryFile tmp;
|
|
||||||
tmp.setFileTemplate(QDir::tempPath() + "/fb2_test_XXXXXX.fb2");
|
|
||||||
tmp.setAutoRemove(false);
|
|
||||||
if (!tmp.open()) return {};
|
|
||||||
tmp.write(content);
|
|
||||||
tmp.flush();
|
|
||||||
return tmp.fileName();
|
|
||||||
}
|
|
||||||
|
|
||||||
static QString buildSampleFb2()
|
|
||||||
{
|
|
||||||
QByteArray xml = kFb2Header;
|
|
||||||
xml +=
|
|
||||||
"<description>"
|
|
||||||
" <title-info>"
|
|
||||||
" <book-title>Test Book</book-title>"
|
|
||||||
" <author>"
|
|
||||||
" <first-name>Test</first-name>"
|
|
||||||
" <last-name>Author</last-name>"
|
|
||||||
" </author>"
|
|
||||||
" </title-info>"
|
|
||||||
"</description>"
|
|
||||||
"<body>"
|
|
||||||
" <section>"
|
|
||||||
" <title><p>Chapter One</p></title>"
|
|
||||||
" <p>First paragraph of chapter one.</p>"
|
|
||||||
" <p>Second paragraph of chapter one.</p>"
|
|
||||||
" </section>"
|
|
||||||
" <section>"
|
|
||||||
" <title><p>Chapter Two</p></title>"
|
|
||||||
" <p>This is chapter two content.</p>"
|
|
||||||
" </section>"
|
|
||||||
"</body>";
|
|
||||||
xml += kFb2Footer;
|
|
||||||
return writeTempFb2(xml);
|
|
||||||
}
|
|
||||||
|
|
||||||
static QString buildFb2WithCover()
|
|
||||||
{
|
|
||||||
QByteArray xml = kFb2Header;
|
|
||||||
xml +=
|
|
||||||
"<description>"
|
|
||||||
" <title-info>"
|
|
||||||
" <book-title>Cover Book</book-title>"
|
|
||||||
" <author>"
|
|
||||||
" <first-name>Cover</first-name>"
|
|
||||||
" <last-name>Tester</last-name>"
|
|
||||||
" </author>"
|
|
||||||
" <coverpage>"
|
|
||||||
" <image l:href=\"#cover_img\"/>"
|
|
||||||
" </coverpage>"
|
|
||||||
" </title-info>"
|
|
||||||
"</description>"
|
|
||||||
"<body>"
|
|
||||||
" <section>"
|
|
||||||
" <title><p>Only Chapter</p></title>"
|
|
||||||
" <p>Some content.</p>"
|
|
||||||
" </section>"
|
|
||||||
"</body>"
|
|
||||||
"<binary id=\"cover_img\" content-type=\"image/png\">AAAA</binary>";
|
|
||||||
xml += kFb2Footer;
|
|
||||||
return writeTempFb2(xml);
|
|
||||||
}
|
|
||||||
|
|
||||||
static QString buildLargeFb2()
|
|
||||||
{
|
|
||||||
QByteArray xml = kFb2Header;
|
|
||||||
xml +=
|
|
||||||
"<description>"
|
|
||||||
" <title-info>"
|
|
||||||
" <book-title>Large Book</book-title>"
|
|
||||||
" </title-info>"
|
|
||||||
"</description>"
|
|
||||||
"<body>"
|
|
||||||
" <section>"
|
|
||||||
" <title><p>Big Chapter</p></title>";
|
|
||||||
for (int i = 0; i < 60; ++i) {
|
|
||||||
xml += QString("<p>Paragraph %1: The quick brown fox jumped over the lazy dog repeatedly.</p>")
|
|
||||||
.arg(i + 1).toUtf8();
|
|
||||||
}
|
|
||||||
xml += " </section></body>";
|
|
||||||
xml += kFb2Footer;
|
|
||||||
return writeTempFb2(xml);
|
|
||||||
}
|
|
||||||
|
|
||||||
static QString buildFb2Windows1251()
|
|
||||||
{
|
|
||||||
// Minimal FB2 with windows-1251 encoding declaration and Cyrillic content.
|
|
||||||
// The bytes below are the windows-1251 encoding of "Тестовая книга" (Test book)
|
|
||||||
// and "Иван Иванов" (Ivan Ivanov), hand-encoded.
|
|
||||||
//
|
|
||||||
// We build the ASCII-safe portions as normal strings, embed raw Cyrillic bytes,
|
|
||||||
// and declare encoding="windows-1251" so the reader must transcode it.
|
|
||||||
QByteArray xml =
|
|
||||||
"<?xml version=\"1.0\" encoding=\"windows-1251\"?>"
|
|
||||||
"<FictionBook xmlns=\"http://www.gribuser.ru/xml/fictionbook/2.0\""
|
|
||||||
" xmlns:l=\"http://www.w3.org/1999/xlink\">"
|
|
||||||
"<description><title-info>"
|
|
||||||
"<book-title>";
|
|
||||||
// "Книга" in windows-1251: К=CA, н=ED, и=E8, г=E3, а=E0
|
|
||||||
xml += QByteArray("\xCA\xED\xE8\xE3\xE0");
|
|
||||||
xml +=
|
|
||||||
"</book-title>"
|
|
||||||
"</title-info></description>"
|
|
||||||
"<body><section>"
|
|
||||||
"<title><p>Глава</p></title>"
|
|
||||||
"<p>";
|
|
||||||
// "Привет" in windows-1251: П=CF, р=F0, и=E8, в=E2, е=E5, т=F2
|
|
||||||
xml += QByteArray("\xCF\xF0\xE8\xE2\xE5\xF2");
|
|
||||||
xml += "</p></section></body></FictionBook>";
|
|
||||||
return writeTempFb2(xml);
|
|
||||||
}
|
|
||||||
|
|
||||||
static QString buildFb2WithImage()
|
|
||||||
{
|
|
||||||
QByteArray xml = kFb2Header;
|
|
||||||
xml +=
|
|
||||||
"<description>"
|
|
||||||
" <title-info>"
|
|
||||||
" <book-title>Image Book</book-title>"
|
|
||||||
" </title-info>"
|
|
||||||
"</description>"
|
|
||||||
"<body>"
|
|
||||||
" <section>"
|
|
||||||
" <title><p>Chapter With Image</p></title>"
|
|
||||||
" <p>Text before image.</p>"
|
|
||||||
" <image l:href=\"#inline_img\"/>"
|
|
||||||
" <p>Text after image.</p>"
|
|
||||||
" </section>"
|
|
||||||
"</body>"
|
|
||||||
"<binary id=\"inline_img\" content-type=\"image/png\">AAAA</binary>";
|
|
||||||
xml += kFb2Footer;
|
|
||||||
return writeTempFb2(xml);
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
|
||||||
// Test class
|
|
||||||
// ---------------------------------------------------------------------------
|
|
||||||
|
|
||||||
class Fb2ReaderTest : public QObject {
|
|
||||||
Q_OBJECT
|
|
||||||
|
|
||||||
private:
|
|
||||||
QString m_samplePath;
|
|
||||||
QString m_coverPath;
|
|
||||||
QString m_largePath;
|
|
||||||
QString m_imagePath;
|
|
||||||
QString m_cp1251Path;
|
|
||||||
|
|
||||||
private slots:
|
|
||||||
void initTestCase()
|
|
||||||
{
|
|
||||||
m_samplePath = buildSampleFb2();
|
|
||||||
m_coverPath = buildFb2WithCover();
|
|
||||||
m_largePath = buildLargeFb2();
|
|
||||||
m_imagePath = buildFb2WithImage();
|
|
||||||
m_cp1251Path = buildFb2Windows1251();
|
|
||||||
QVERIFY2(!m_samplePath.isEmpty(), "Failed to build sample FB2");
|
|
||||||
QVERIFY2(!m_coverPath.isEmpty(), "Failed to build cover FB2");
|
|
||||||
QVERIFY2(!m_largePath.isEmpty(), "Failed to build large FB2");
|
|
||||||
QVERIFY2(!m_imagePath.isEmpty(), "Failed to build image FB2");
|
|
||||||
QVERIFY2(!m_cp1251Path.isEmpty(), "Failed to build windows-1251 FB2");
|
|
||||||
}
|
|
||||||
|
|
||||||
void cleanupTestCase()
|
|
||||||
{
|
|
||||||
QFile::remove(m_samplePath);
|
|
||||||
QFile::remove(m_coverPath);
|
|
||||||
QFile::remove(m_largePath);
|
|
||||||
QFile::remove(m_imagePath);
|
|
||||||
QFile::remove(m_cp1251Path);
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- Error handling ---
|
|
||||||
|
|
||||||
void openNonexistentFile()
|
|
||||||
{
|
|
||||||
Fb2Reader reader;
|
|
||||||
QVERIFY(!reader.open(QStringLiteral("/tmp/does_not_exist_xyzzy.fb2")));
|
|
||||||
QVERIFY(!reader.lastError().isEmpty());
|
|
||||||
}
|
|
||||||
|
|
||||||
void openInvalidXml()
|
|
||||||
{
|
|
||||||
const QString path = writeTempFb2("<not valid xml <<<");
|
|
||||||
Fb2Reader reader;
|
|
||||||
QVERIFY(!reader.open(path));
|
|
||||||
QVERIFY(!reader.lastError().isEmpty());
|
|
||||||
QFile::remove(path);
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- Metadata ---
|
|
||||||
|
|
||||||
void titleExtracted()
|
|
||||||
{
|
|
||||||
Fb2Reader reader;
|
|
||||||
QVERIFY(reader.open(m_samplePath));
|
|
||||||
QCOMPARE(reader.title(), QStringLiteral("Test Book"));
|
|
||||||
}
|
|
||||||
|
|
||||||
void authorExtracted()
|
|
||||||
{
|
|
||||||
Fb2Reader reader;
|
|
||||||
QVERIFY(reader.open(m_samplePath));
|
|
||||||
QCOMPARE(reader.author(), QStringLiteral("Test Author"));
|
|
||||||
}
|
|
||||||
|
|
||||||
void fileTypeIsFb2()
|
|
||||||
{
|
|
||||||
Fb2Reader reader;
|
|
||||||
QCOMPARE(reader.fileType(), QStringLiteral("fb2"));
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- Chapters ---
|
|
||||||
|
|
||||||
void chapterCountMatchesBodySections()
|
|
||||||
{
|
|
||||||
Fb2Reader reader;
|
|
||||||
QVERIFY(reader.open(m_samplePath));
|
|
||||||
QCOMPARE(reader.chapterCount(), 2);
|
|
||||||
}
|
|
||||||
|
|
||||||
void loadChapterContent()
|
|
||||||
{
|
|
||||||
Fb2Reader reader;
|
|
||||||
QVERIFY(reader.open(m_samplePath));
|
|
||||||
const Chapter ch = reader.loadChapter(0);
|
|
||||||
QCOMPARE(ch.index, 0);
|
|
||||||
QVERIFY(!ch.contentChunks.isEmpty());
|
|
||||||
const QString combined = ch.contentChunks.join('\n');
|
|
||||||
QVERIFY(combined.contains(QStringLiteral("First paragraph")));
|
|
||||||
}
|
|
||||||
|
|
||||||
void loadChapterTwo()
|
|
||||||
{
|
|
||||||
Fb2Reader reader;
|
|
||||||
QVERIFY(reader.open(m_samplePath));
|
|
||||||
const Chapter ch = reader.loadChapter(1);
|
|
||||||
QCOMPARE(ch.index, 1);
|
|
||||||
QVERIFY(!ch.contentChunks.isEmpty());
|
|
||||||
const QString combined = ch.contentChunks.join('\n');
|
|
||||||
QVERIFY(combined.contains(QStringLiteral("chapter two")));
|
|
||||||
}
|
|
||||||
|
|
||||||
void loadChapterOutOfRange()
|
|
||||||
{
|
|
||||||
Fb2Reader reader;
|
|
||||||
QVERIFY(reader.open(m_samplePath));
|
|
||||||
const Chapter ch = reader.loadChapter(99);
|
|
||||||
QVERIFY(ch.contentChunks.isEmpty());
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- TOC ---
|
|
||||||
|
|
||||||
void tableOfContentsBuilt()
|
|
||||||
{
|
|
||||||
Fb2Reader reader;
|
|
||||||
QVERIFY(reader.open(m_samplePath));
|
|
||||||
const QList<TocEntry> toc = reader.tableOfContents();
|
|
||||||
QCOMPARE(toc.size(), 2);
|
|
||||||
QCOMPARE(toc[0].title, QStringLiteral("Chapter One"));
|
|
||||||
QCOMPARE(toc[0].chapterIndex, 0);
|
|
||||||
QCOMPARE(toc[0].depth, 0);
|
|
||||||
QCOMPARE(toc[1].title, QStringLiteral("Chapter Two"));
|
|
||||||
QCOMPARE(toc[1].chapterIndex, 1);
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- Chunking ---
|
|
||||||
|
|
||||||
void largeChapterProducesMultipleChunks()
|
|
||||||
{
|
|
||||||
Fb2Reader reader;
|
|
||||||
QVERIFY(reader.open(m_largePath));
|
|
||||||
const Chapter ch = reader.loadChapter(0);
|
|
||||||
QVERIFY(ch.contentChunks.size() > 1);
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- Cover image ---
|
|
||||||
|
|
||||||
void coverImagePathExtracted()
|
|
||||||
{
|
|
||||||
Fb2Reader reader;
|
|
||||||
QVERIFY(reader.open(m_coverPath));
|
|
||||||
QCOMPARE(reader.coverImagePath(), QStringLiteral("cover_img"));
|
|
||||||
}
|
|
||||||
|
|
||||||
void coverImagePathEmptyWhenNoCover()
|
|
||||||
{
|
|
||||||
Fb2Reader reader;
|
|
||||||
QVERIFY(reader.open(m_samplePath));
|
|
||||||
QVERIFY(reader.coverImagePath().isEmpty());
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- Image tag rewriting ---
|
|
||||||
|
|
||||||
void imageTagsRewrittenToProviderUrls()
|
|
||||||
{
|
|
||||||
Fb2Reader reader;
|
|
||||||
QVERIFY(reader.open(m_imagePath));
|
|
||||||
const Chapter ch = reader.loadChapter(0);
|
|
||||||
QVERIFY(!ch.contentChunks.isEmpty());
|
|
||||||
const QString combined = ch.contentChunks.join('\n');
|
|
||||||
QVERIFY2(combined.contains(QStringLiteral("image://fb2/inline_img")),
|
|
||||||
qPrintable(QStringLiteral("Expected image://fb2/inline_img in: ") + combined));
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- loadMetadata ---
|
|
||||||
|
|
||||||
void loadMetadataOnlyParsesDescription()
|
|
||||||
{
|
|
||||||
Fb2Reader reader;
|
|
||||||
QVERIFY(reader.loadMetadata(m_samplePath));
|
|
||||||
QCOMPARE(reader.title(), QStringLiteral("Test Book"));
|
|
||||||
QCOMPARE(reader.author(), QStringLiteral("Test Author"));
|
|
||||||
QCOMPARE(reader.chapterCount(), 0); // chapters not parsed
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- Content hash ---
|
|
||||||
|
|
||||||
void contentHashNonEmptyAfterOpen()
|
|
||||||
{
|
|
||||||
Fb2Reader reader;
|
|
||||||
QVERIFY(reader.open(m_samplePath));
|
|
||||||
QVERIFY(!reader.contentHash().isEmpty());
|
|
||||||
}
|
|
||||||
|
|
||||||
void contentHashEmptyAfterLoadMetadataOnly()
|
|
||||||
{
|
|
||||||
Fb2Reader reader;
|
|
||||||
QVERIFY(reader.loadMetadata(m_samplePath));
|
|
||||||
QVERIFY(reader.contentHash().isEmpty());
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- Encoding ---
|
|
||||||
|
|
||||||
void windows1251FileOpensSuccessfully()
|
|
||||||
{
|
|
||||||
Fb2Reader reader;
|
|
||||||
QVERIFY2(reader.open(m_cp1251Path),
|
|
||||||
qPrintable(QStringLiteral("open() failed: ") + reader.lastError()));
|
|
||||||
}
|
|
||||||
|
|
||||||
void windows1251TitleDecodedCorrectly()
|
|
||||||
{
|
|
||||||
Fb2Reader reader;
|
|
||||||
QVERIFY(reader.open(m_cp1251Path));
|
|
||||||
// "Книга" in Unicode
|
|
||||||
QCOMPARE(reader.title(), QStringLiteral("\u041A\u043D\u0438\u0433\u0430"));
|
|
||||||
}
|
|
||||||
|
|
||||||
void windows1251ContentDecodedCorrectly()
|
|
||||||
{
|
|
||||||
Fb2Reader reader;
|
|
||||||
QVERIFY(reader.open(m_cp1251Path));
|
|
||||||
QCOMPARE(reader.chapterCount(), 1);
|
|
||||||
const Chapter ch = reader.loadChapter(0);
|
|
||||||
const QString combined = ch.contentChunks.join('\n');
|
|
||||||
// "Привет" in Unicode
|
|
||||||
QVERIFY(combined.contains(QStringLiteral("\u041F\u0440\u0438\u0432\u0435\u0442")));
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
QTEST_MAIN(Fb2ReaderTest)
|
|
||||||
#include "Fb2ReaderTest.moc"
|
|
||||||
@@ -42,9 +42,7 @@ private slots:
|
|||||||
|
|
||||||
FolderReader reader;
|
FolderReader reader;
|
||||||
QVERIFY(reader.open(tmp.path()));
|
QVERIFY(reader.open(tmp.path()));
|
||||||
QCOMPARE(reader.chapterCount(), 1);
|
QCOMPARE(reader.pages().size(), 3);
|
||||||
const Chapter ch = reader.loadChapter(0);
|
|
||||||
QCOMPARE(ch.contentChunks.size(), 3);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void sortOrderAlphabetical()
|
void sortOrderAlphabetical()
|
||||||
@@ -57,12 +55,11 @@ private slots:
|
|||||||
|
|
||||||
FolderReader reader;
|
FolderReader reader;
|
||||||
QVERIFY(reader.open(tmp.path()));
|
QVERIFY(reader.open(tmp.path()));
|
||||||
const Chapter ch = reader.loadChapter(0);
|
const auto pages = reader.pages();
|
||||||
QCOMPARE(ch.contentChunks.size(), 3);
|
QCOMPARE(pages.size(), 3);
|
||||||
// Chunks contain the entry name — check alphabetical order
|
QVERIFY(pages.at(0).imageUrl.contains(QStringLiteral("a.png")));
|
||||||
QVERIFY(ch.contentChunks.at(0).contains(QStringLiteral("a.png")));
|
QVERIFY(pages.at(1).imageUrl.contains(QStringLiteral("b.png")));
|
||||||
QVERIFY(ch.contentChunks.at(1).contains(QStringLiteral("b.png")));
|
QVERIFY(pages.at(2).imageUrl.contains(QStringLiteral("c.png")));
|
||||||
QVERIFY(ch.contentChunks.at(2).contains(QStringLiteral("c.png")));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void coverIsFirstImage()
|
void coverIsFirstImage()
|
||||||
@@ -103,12 +100,10 @@ private slots:
|
|||||||
QCOMPARE(ra.contentHash(), rb.contentHash());
|
QCOMPARE(ra.contentHash(), rb.contentHash());
|
||||||
}
|
}
|
||||||
|
|
||||||
void fileTypeAndRenderingMode()
|
void fileType()
|
||||||
{
|
{
|
||||||
FolderReader reader;
|
FolderReader reader;
|
||||||
QCOMPARE(reader.fileType(), QStringLiteral("folder"));
|
QCOMPARE(reader.fileType(), QStringLiteral("folder"));
|
||||||
QCOMPARE(static_cast<int>(reader.preferredRenderingMode()),
|
|
||||||
static_cast<int>(FormatReader::RenderingMode::Manga));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void nonImageFilesIgnored()
|
void nonImageFilesIgnored()
|
||||||
@@ -124,8 +119,7 @@ private slots:
|
|||||||
|
|
||||||
FolderReader reader;
|
FolderReader reader;
|
||||||
QVERIFY(reader.open(tmp.path()));
|
QVERIFY(reader.open(tmp.path()));
|
||||||
QCOMPARE(reader.chapterCount(), 1);
|
QCOMPARE(reader.pages().size(), 1);
|
||||||
QCOMPARE(reader.loadChapter(0).contentChunks.size(), 1);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void dotFilesIgnored()
|
void dotFilesIgnored()
|
||||||
@@ -137,7 +131,7 @@ private slots:
|
|||||||
|
|
||||||
FolderReader reader;
|
FolderReader reader;
|
||||||
QVERIFY(reader.open(tmp.path()));
|
QVERIFY(reader.open(tmp.path()));
|
||||||
QCOMPARE(reader.loadChapter(0).contentChunks.size(), 1);
|
QCOMPARE(reader.pages().size(), 1);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -37,21 +37,10 @@ private slots:
|
|||||||
QCOMPARE(parsed.sourcePath, sourcePath);
|
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()
|
void providerIdWithoutQueryHasEmptySourcePath()
|
||||||
{
|
{
|
||||||
const auto parsed = ImageUrl::parseProviderId(QStringLiteral("OEBPS/img.png"));
|
const auto parsed = ImageUrl::parseProviderId(QStringLiteral("page01.png"));
|
||||||
QCOMPARE(parsed.entry, QStringLiteral("OEBPS/img.png"));
|
QCOMPARE(parsed.entry, QStringLiteral("page01.png"));
|
||||||
QVERIFY(parsed.sourcePath.isEmpty());
|
QVERIFY(parsed.sourcePath.isEmpty());
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -61,22 +50,6 @@ private slots:
|
|||||||
const auto parsed = ImageUrl::parseProviderId(QStringLiteral("page%2001.jpg"));
|
const auto parsed = ImageUrl::parseProviderId(QStringLiteral("page%2001.jpg"));
|
||||||
QCOMPARE(parsed.entry, QStringLiteral("page 01.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)
|
QTEST_MAIN(ImageUrlTest)
|
||||||
|
|||||||
@@ -1,168 +0,0 @@
|
|||||||
#include <QtTest>
|
|
||||||
#include "backend/formats/TxtReader.h"
|
|
||||||
|
|
||||||
class TxtReaderTest : public QObject {
|
|
||||||
Q_OBJECT
|
|
||||||
|
|
||||||
private:
|
|
||||||
QString fixturePath(const QString &filename) const
|
|
||||||
{
|
|
||||||
return QStringLiteral(FIXTURES_DIR) + "/" + filename;
|
|
||||||
}
|
|
||||||
|
|
||||||
private slots:
|
|
||||||
void openValidFile()
|
|
||||||
{
|
|
||||||
TxtReader reader;
|
|
||||||
QVERIFY(reader.open(fixturePath("sample.txt")));
|
|
||||||
QCOMPARE(reader.chapterCount(), 1);
|
|
||||||
QCOMPARE(reader.title(), QStringLiteral("sample"));
|
|
||||||
}
|
|
||||||
|
|
||||||
void loadChapter()
|
|
||||||
{
|
|
||||||
TxtReader reader;
|
|
||||||
reader.open(fixturePath("sample.txt"));
|
|
||||||
|
|
||||||
Chapter ch = reader.loadChapter(0);
|
|
||||||
QCOMPARE(ch.index, 0);
|
|
||||||
QVERIFY(!ch.contentChunks.isEmpty());
|
|
||||||
// Small file should produce a single chunk
|
|
||||||
QCOMPARE(ch.contentChunks.size(), 1);
|
|
||||||
QVERIFY(ch.contentChunks.first().contains("Books are a uniquely portable magic"));
|
|
||||||
// Verify Cyrillic content survived
|
|
||||||
QVERIFY(ch.contentChunks.first().contains(QString::fromUtf8("Искусство чтения")));
|
|
||||||
// Verify HTML paragraph structure
|
|
||||||
QVERIFY(ch.contentChunks.first().contains("<p>"));
|
|
||||||
}
|
|
||||||
|
|
||||||
void tableOfContentsEmpty()
|
|
||||||
{
|
|
||||||
TxtReader reader;
|
|
||||||
reader.open(fixturePath("sample.txt"));
|
|
||||||
QVERIFY(reader.tableOfContents().isEmpty());
|
|
||||||
}
|
|
||||||
|
|
||||||
void authorEmpty()
|
|
||||||
{
|
|
||||||
TxtReader reader;
|
|
||||||
reader.open(fixturePath("sample.txt"));
|
|
||||||
QVERIFY(reader.author().isEmpty());
|
|
||||||
}
|
|
||||||
|
|
||||||
void openNonexistentFile()
|
|
||||||
{
|
|
||||||
TxtReader reader;
|
|
||||||
QVERIFY(!reader.open("/tmp/does_not_exist_asteria.txt"));
|
|
||||||
QVERIFY(!reader.lastError().isEmpty());
|
|
||||||
}
|
|
||||||
|
|
||||||
void loadChapterOutOfRange()
|
|
||||||
{
|
|
||||||
TxtReader reader;
|
|
||||||
reader.open(fixturePath("sample.txt"));
|
|
||||||
|
|
||||||
Chapter ch = reader.loadChapter(1);
|
|
||||||
QVERIFY(ch.contentChunks.isEmpty());
|
|
||||||
}
|
|
||||||
|
|
||||||
void openCp1251File()
|
|
||||||
{
|
|
||||||
TxtReader reader;
|
|
||||||
QVERIFY(reader.open(fixturePath("sample_cp1251.txt")));
|
|
||||||
QCOMPARE(reader.chapterCount(), 1);
|
|
||||||
|
|
||||||
Chapter ch = reader.loadChapter(0);
|
|
||||||
QVERIFY(!ch.contentChunks.isEmpty());
|
|
||||||
QString allContent = ch.contentChunks.join(QString());
|
|
||||||
QVERIFY(allContent.contains(QString::fromUtf8("Привет, мир!")));
|
|
||||||
QVERIFY(allContent.contains(QString::fromUtf8("Русская литература")));
|
|
||||||
}
|
|
||||||
|
|
||||||
void largeFileProducesMultipleChunks()
|
|
||||||
{
|
|
||||||
// Generate a large file with paragraphs
|
|
||||||
QTemporaryFile tmpFile;
|
|
||||||
tmpFile.setAutoRemove(true);
|
|
||||||
QVERIFY(tmpFile.open());
|
|
||||||
|
|
||||||
// Write ~20KB of paragraphed text (well above 4096 chunk size)
|
|
||||||
QString paragraph = QStringLiteral("This is a paragraph of text that has some content. ");
|
|
||||||
paragraph = paragraph.repeated(10); // ~500 chars per paragraph
|
|
||||||
for (int i = 0; i < 50; ++i) {
|
|
||||||
tmpFile.write(paragraph.toUtf8());
|
|
||||||
tmpFile.write("\n\n");
|
|
||||||
}
|
|
||||||
tmpFile.close();
|
|
||||||
|
|
||||||
TxtReader reader;
|
|
||||||
QVERIFY(reader.open(tmpFile.fileName()));
|
|
||||||
|
|
||||||
Chapter ch = reader.loadChapter(0);
|
|
||||||
QVERIFY(ch.contentChunks.size() > 1);
|
|
||||||
// Each chunk should have <p> tags
|
|
||||||
for (const QString &chunk : ch.contentChunks) {
|
|
||||||
QVERIFY(chunk.contains("<p>"));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void wallOfTextProducesMultipleChunks()
|
|
||||||
{
|
|
||||||
// Generate a large file with no blank lines
|
|
||||||
QTemporaryFile tmpFile;
|
|
||||||
tmpFile.setAutoRemove(true);
|
|
||||||
QVERIFY(tmpFile.open());
|
|
||||||
|
|
||||||
// Write ~20KB of text with single newlines only
|
|
||||||
QString line = QStringLiteral("This is a line of continuous text without blank lines between them. ");
|
|
||||||
line = line.repeated(5); // ~340 chars per line
|
|
||||||
for (int i = 0; i < 80; ++i) {
|
|
||||||
tmpFile.write(line.toUtf8());
|
|
||||||
tmpFile.write("\n");
|
|
||||||
}
|
|
||||||
tmpFile.close();
|
|
||||||
|
|
||||||
TxtReader reader;
|
|
||||||
QVERIFY(reader.open(tmpFile.fileName()));
|
|
||||||
|
|
||||||
Chapter ch = reader.loadChapter(0);
|
|
||||||
QVERIFY(ch.contentChunks.size() > 1);
|
|
||||||
// Each chunk should be standalone HTML
|
|
||||||
for (const QString &chunk : ch.contentChunks) {
|
|
||||||
QVERIFY(chunk.contains("<p>"));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void eachChunkIsStandaloneHtml()
|
|
||||||
{
|
|
||||||
// Generate a large file
|
|
||||||
QTemporaryFile tmpFile;
|
|
||||||
tmpFile.setAutoRemove(true);
|
|
||||||
QVERIFY(tmpFile.open());
|
|
||||||
|
|
||||||
QString paragraph = QStringLiteral("Test paragraph content here. ");
|
|
||||||
paragraph = paragraph.repeated(15);
|
|
||||||
for (int i = 0; i < 40; ++i) {
|
|
||||||
tmpFile.write(paragraph.toUtf8());
|
|
||||||
tmpFile.write("\n\n");
|
|
||||||
}
|
|
||||||
tmpFile.close();
|
|
||||||
|
|
||||||
TxtReader reader;
|
|
||||||
QVERIFY(reader.open(tmpFile.fileName()));
|
|
||||||
|
|
||||||
Chapter ch = reader.loadChapter(0);
|
|
||||||
QVERIFY(ch.contentChunks.size() > 1);
|
|
||||||
for (const QString &chunk : ch.contentChunks) {
|
|
||||||
// Every chunk must start with <p> and end with </p>
|
|
||||||
QString trimmed = chunk.trimmed();
|
|
||||||
QVERIFY2(trimmed.startsWith("<p>"),
|
|
||||||
qPrintable("Chunk doesn't start with <p>: " + trimmed.left(50)));
|
|
||||||
QVERIFY2(trimmed.endsWith("</p>"),
|
|
||||||
qPrintable("Chunk doesn't end with </p>: " + trimmed.right(50)));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
QTEST_MAIN(TxtReaderTest)
|
|
||||||
#include "TxtReaderTest.moc"
|
|
||||||
Reference in new issue
Block a user