lint refactor

This commit is contained in:
Agel committed 2026-10-30 16:48:58 +01:00
1 parent da8abf0332
commit 85ae0d4ad9
53 files changed
+880 -659

No files matched your search

+16 -11
View File
@@ -104,20 +104,23 @@ Pre-configured tasks, launch configurations, and CMake presets are available:
## Architecture
Backend (C++) handles all file I/O, format parsing, text layout calculation, and image decoding. QML handles UI. Communication is through `QObject` models and context properties.
Backend (C++) handles all file I/O, format parsing, text layout calculation, and image decoding. QML handles UI. Communication is through declarative compile-time singletons and types registered in the `Asteria` QML module via `QmlRegistrations.h` and `qt_add_qml_module`.
### QObjects Exposed to QML
| Object | Responsibility |
### Declarative Singletons & Types Exposed to QML (`Asteria` module)
| Type / Singleton | Responsibility |
|---|---|
| `book` (`Book`) | Open/close book, async loading, error state, metadata (title, author, coverImageUrl). Owns `FormatReader`. |
| `readingModel` (`ReadingModel`) | `QAbstractListModel` exposing chunks (`ContentRole`, `LayoutRole`, `PixelHeightRole`), layout updates, reading mode (`isTextMode`, `isMangaMode`), normalized pagination (`currentPage`, `totalPages`, `currentChunk`), manga page pairs, and per-book toggles (`pageShift`, `mangaRTL`, `useBookColours`). |
| `readingPreferences` (`ReadingPreferences`) | Font size, line spacing, horizontal margin, vertical margin (`QSettings`). |
| `uiState` (`UiState`) | Current theme, last page, sidebar open state, reader bars visibility (`barsVisible`), last file path, custom theme colors, window geometry. |
| `historyModel` (`HistoryModel`) | `QAbstractListModel` of recent books with async metadata extraction and reading progress. Entries store strongly-typed `QDateTime lastOpened`, immediately drop bogus/unparseable dates on deserialization, and are maintained strictly in descending chronological order (`lastOpened desc`). |
| `isDebugBuild` | Boolean constant indicating debug build. |
| `Book` (`Book`) | Open/close book, async loading, error state, metadata (title, author, coverImageUrl). Owns `FormatReader`. |
| `ReadingModel` (`ReadingModel`) | `QAbstractListModel` exposing chunks (`ContentRole`, `LayoutRole`, `PixelHeightRole`), layout updates, reading mode (`isTextMode`, `isMangaMode`), normalized pagination (`currentPage`, `totalPages`, `currentChunk`), manga page pairs, and per-book toggles (`pageShift`, `mangaRTL`, `useBookColours`). |
| `ReadingPreferences` (`ReadingPreferences`) | Font size, line spacing, horizontal margin, vertical margin (`QSettings`). |
| `UiState` (`UiState`) | Current theme, last page, sidebar open state, reader bars visibility (`barsVisible`), last file path, custom theme colors, window geometry. |
| `HistoryModel` (`HistoryModel`) | `QAbstractListModel` of recent books with async metadata extraction and reading progress. Entries store strongly-typed `QDateTime lastOpened`, immediately drop bogus/unparseable dates on deserialization, and are maintained strictly in descending chronological order (`lastOpened desc`). |
| `AppInfo` | Exposes compile-time build configuration (e.g. `AppInfo.isDebugBuild`). |
Backend singletons are exposed using `QML_FOREIGN` wrapper structs in `src/backend/QmlRegistrations.h`. This decouples backend classes from Qt QML engine headers in headless unit test suites while enabling static type checking, Ahead-Of-Time compilation via `qmlcachegen`, and zero-warning `qmllint` passes.
### Additional Registered Types & Providers
- **`KnuthPlassItem`** (`Asteria` module): Custom `QQuickPaintedItem` that draws `ChunkLayout` via `QPainter`. Supports `useBookColours`, `surfaceColor`, theme colour overrides, and WCAG contrast safety fallback for publisher colours.
- **`KnuthPlassItem`** (`Asteria` module): Custom `QQuickPaintedItem` registered declaratively via `QML_ELEMENT` that draws `ChunkLayout` via `QPainter`. Supports `useBookColours`, `surfaceColor`, theme colour overrides, and WCAG contrast safety fallback for publisher colours.
- **`ThemePalette`** (`Asteria` module): Declarative theme palette base QML type defining all 20 color keys, extended by `DarkTheme`, `LightTheme`, and `ThemeManager.customTheme` for compile-time property verification.
- **`ChunkLayout`**: Declared metatype storing positioned text lines, word runs, inline/block images, rules, and block decorations.
- **Image Providers**:
- `image://fileicon/...`: `FileIconProvider`
@@ -234,6 +237,7 @@ src/
IFileDialogService.h
NativeFileDialogService.h/cpp
PortalFileDialogService.h/cpp
QmlRegistrations.h
ReadingModel.h/cpp
book/
Book.h/cpp
@@ -280,6 +284,7 @@ src/
LightTheme.qml
Main.qml
ThemeManager.qml
ThemePalette.qml
components/
ErrorPopup.qml
FlatIconButton.qml
@@ -334,5 +339,5 @@ tests/
## Qt Conventions
- **Qt 6.10+** preferred — no Qt5 compat shims.
- All UI in **QML**; C++ for logic, parsing, and heavy computation.
- Expose C++ to QML via `rootContext()->setContextProperty()` or `qmlRegisterType`.
- Expose C++ backend singletons declaratively in the `Asteria` QML module via `QML_FOREIGN` wrappers (`QmlRegistrations.h`) and `QML_ELEMENT` for custom items (`KnuthPlassItem`). Avoid runtime `rootContext()->setContextProperty()` so `qmllint` and `qmlcachegen` statically type-check all bindings and properties ahead of time.
- Main window starts with opacity 0 and ticks to 1 on a short timer to prevent white window flash during initial render.
+14 -7
View File
@@ -3,12 +3,9 @@ project(asteria-qt VERSION 0.1.0 LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_AUTOMOC ON)
include(GNUInstallDirs)
# Qt6 components
find_package(Qt6 REQUIRED COMPONENTS
find_package(Qt6 6.8 REQUIRED COMPONENTS
Core
Gui
Qml
@@ -21,6 +18,7 @@ find_package(Qt6 REQUIRED COMPONENTS
Xml
Network
)
qt_standard_project_setup(REQUIRES 6.8)
find_package(Qt6 OPTIONAL_COMPONENTS DBus)
# Third-party libraries
@@ -38,6 +36,7 @@ endif()
# Source files
set(SOURCES
src/main.cpp
src/backend/QmlRegistrations.h
src/backend/FormatReader.h
src/backend/AppState.h
src/backend/AppState.cpp
@@ -137,7 +136,15 @@ if(APPLE)
)
endif()
target_include_directories(asteria-qt PRIVATE src)
target_include_directories(asteria-qt PRIVATE
src
src/backend
src/backend/reading
src/backend/reading/layout
src/backend/book
src/backend/formats
src/backend/state
)
target_link_libraries(asteria-qt PRIVATE
Qt6::Core
@@ -165,6 +172,7 @@ endif()
# 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/ThemePalette.qml PROPERTIES QT_RESOURCE_ALIAS ThemePalette.qml)
set_source_files_properties(src/qml/DarkTheme.qml PROPERTIES QT_RESOURCE_ALIAS DarkTheme.qml
QT_QML_SINGLETON_TYPE TRUE)
set_source_files_properties(src/qml/LightTheme.qml PROPERTIES QT_RESOURCE_ALIAS LightTheme.qml
@@ -188,13 +196,12 @@ set_source_files_properties(src/qml/pages/HistoryPage.qml PROPERTIES QT_RESOURCE
set_source_files_properties(src/qml/pages/CustomThemePage.qml PROPERTIES QT_RESOURCE_ALIAS pages/CustomThemePage.qml)
# QML module
qt_policy(SET QTP0004 NEW)
qt_add_qml_module(asteria-qt
URI Asteria
VERSION 1.0
QML_FILES
src/qml/Main.qml
src/qml/ThemePalette.qml
src/qml/DarkTheme.qml
src/qml/LightTheme.qml
src/qml/ThemeManager.qml
+8 -3
View File
@@ -115,7 +115,7 @@ bool HistoryModel::setData(const QModelIndex &index, const QVariant &value, int
QHash<int, QByteArray> HistoryModel::roleNames() const
{
return {
static const QHash<int, QByteArray> roles = {
{FilePathRole, "filePath"},
{TitleRole, "title"},
{AuthorRole, "author"},
@@ -124,6 +124,7 @@ QHash<int, QByteArray> HistoryModel::roleNames() const
{LastOpenedRole, "lastOpened"},
{CoverImageUrlRole, "coverImageUrl"}
};
return roles;
}
void HistoryModel::load(AppState &state)
@@ -146,7 +147,7 @@ void HistoryModel::load(AppState &state)
seenPaths.insert(fp);
double progress = item.value(QStringLiteral("progress"), 0.0).toDouble();
progress = qBound(0.0, progress, 1.0);
progress = std::clamp(progress, 0.0, 1.0);
HistoryEntry entry;
entry.filePath = fp;
@@ -264,7 +265,7 @@ void HistoryModel::addOrUpdateBook(const QString &filePath, double progress)
if (resolvedProgress < 0.0)
resolvedProgress = 0.0;
}
addOrUpdateBook(filePath, resolvedProgress, QDateTime::currentDateTime());
addOrUpdateBook(filePath, resolvedProgress, QDateTime::currentDateTimeUtc());
}
void HistoryModel::removeBook(const QString &filePath)
@@ -311,6 +312,10 @@ QDateTime HistoryModel::lastOpened(int index) const
void HistoryModel::requestMetadata(const QString &filePath)
{
m_metadataFutures.erase(std::remove_if(m_metadataFutures.begin(), m_metadataFutures.end(),
[](const QFuture<void> &f) { return !f.isRunning(); }),
m_metadataFutures.end());
FormatRegistry *registry = &m_registry;
QPointer<HistoryModel> self(this);
+2 -2
View File
@@ -25,10 +25,10 @@ struct HistoryEntry {
class HistoryModel : public QAbstractListModel
{
Q_OBJECT
Q_PROPERTY(int count READ rowCount NOTIFY countChanged)
Q_PROPERTY(int count READ rowCount NOTIFY countChanged FINAL)
public:
enum HistoryRoles {
enum HistoryRoles : int {
FilePathRole = Qt::UserRole + 1,
TitleRole,
AuthorRole,
+49
View File
@@ -0,0 +1,49 @@
#pragma once
#include <QJSEngine>
#include <QQmlEngine>
#include <QtQmlIntegration/qqmlintegration.h>
#include "backend/HistoryModel.h"
#include "backend/ReadingModel.h"
#include "backend/book/Book.h"
#include "backend/state/ReadingPreferences.h"
#include "backend/state/UiState.h"
class AppInfo : public QObject {
Q_OBJECT
QML_ELEMENT
QML_SINGLETON
Q_PROPERTY(bool isDebugBuild READ isDebugBuild CONSTANT FINAL)
public:
explicit AppInfo(QObject *parent = nullptr) : QObject(parent) {}
bool isDebugBuild() const noexcept {
#ifdef QT_DEBUG
return true;
#else
return false;
#endif
}
};
#define ASTERIA_QML_FOREIGN_SINGLETON(Type, WrapperName) \
struct WrapperName { \
Q_GADGET \
QML_FOREIGN(Type) \
QML_NAMED_ELEMENT(Type) \
QML_SINGLETON \
public: \
static inline Type *s_instance = nullptr; \
static Type *create(QQmlEngine *, QJSEngine *) { \
if (s_instance) \
QJSEngine::setObjectOwnership(s_instance, \
QJSEngine::CppOwnership); \
return s_instance; \
} \
};
ASTERIA_QML_FOREIGN_SINGLETON(Book, BookQmlSingleton)
ASTERIA_QML_FOREIGN_SINGLETON(ReadingModel, ReadingModelQmlSingleton)
ASTERIA_QML_FOREIGN_SINGLETON(ReadingPreferences, ReadingPreferencesQmlSingleton)
ASTERIA_QML_FOREIGN_SINGLETON(UiState, UiStateQmlSingleton)
ASTERIA_QML_FOREIGN_SINGLETON(HistoryModel, HistoryModelQmlSingleton)
+14 -13
View File
@@ -75,11 +75,12 @@ void ReadingModel::ensureChunkLayout(int row) const
QHash<int, QByteArray> ReadingModel::roleNames() const
{
return {
static const QHash<int, QByteArray> roles = {
{ContentRole, "content"},
{LayoutRole, "layout"},
{PixelHeightRole, "pixelHeight"}
};
return roles;
}
bool ReadingModel::isTextMode() const { return m_isTextMode; }
@@ -92,7 +93,7 @@ bool ReadingModel::useBookColours() const { return m_useBookColours; }
double ReadingModel::progress() const
{
return qBound(0.0, m_progress, 1.0);
return std::clamp(m_progress, 0.0, 1.0);
}
int ReadingModel::currentPage() const { return m_currentPage; }
@@ -107,15 +108,15 @@ int ReadingModel::calculatePageFromPosition(int chunkIndex, qreal intraOffset) c
if (m_chunks.isEmpty() || m_totalPages <= 0) {
return 0;
}
const int safeChunk = qBound(0, chunkIndex, m_chunks.size() - 1);
const int safeChunk = std::clamp(chunkIndex, 0, static_cast<int>(m_chunks.size() - 1));
qreal intraFraction = 0.0;
if (safeChunk < m_chunkLayouts.size() && m_chunkLayouts[safeChunk].totalHeight > 0.0) {
intraFraction = qBound(0.0, intraOffset / m_chunkLayouts[safeChunk].totalHeight, 1.0);
intraFraction = std::clamp(intraOffset / m_chunkLayouts[safeChunk].totalHeight, 0.0, 1.0);
}
const qreal charsScrolled = (safeChunk < m_chunkCumulativeChars.size() ? m_chunkCumulativeChars[safeChunk] : 0)
+ intraFraction * m_chunks[safeChunk].charCount;
const int page = static_cast<int>(charsScrolled / kNormalizedCharsPerPage) + 1;
return qBound(1, page, m_totalPages);
return std::clamp(page, 1, m_totalPages);
}
void ReadingModel::setImageResolver(IBookImageResolver *resolver)
@@ -155,8 +156,8 @@ void ReadingModel::updateLayoutMetrics(int contentWidth, int fontSize, qreal lin
params.fontSize = m_layoutFontSize;
params.lineSpacing = m_layoutLineSpacing;
const int startIdx = std::max(0, targetChunk - 5);
const int endIdx = std::min(int(m_preparedChunks.size() - 1), targetChunk + 25);
const int startIdx = (std::max)(0, targetChunk - 5);
const int endIdx = (std::min)(int(m_preparedChunks.size() - 1), targetChunk + 25);
m_lastSyncStart = startIdx;
m_lastSyncEnd = endIdx;
@@ -245,7 +246,7 @@ void ReadingModel::setScrollPosition(int topChunkIndex, qreal intraOffset, qreal
emit currentChunkChanged();
}
const qreal clamped = qBound(0.0, proportion, 1.0);
const qreal clamped = std::clamp(proportion, 0.0, 1.0);
if (!qFuzzyCompare(m_progress, clamped)) {
m_progress = clamped;
emit progressChanged();
@@ -301,8 +302,8 @@ void ReadingModel::startLayoutMeasurement(int restoreChunk, qreal restoreIntraOf
auto *resolver = m_imageResolver;
// Phase 1: Immediately prepare and layout the visible window synchronously (<1ms)
const int startIdx = std::max(0, restoreChunk - 5);
const int endIdx = std::min(int(chunks.size() - 1), restoreChunk + 25);
const int startIdx = (std::max)(0, restoreChunk - 5);
const int endIdx = (std::min)(int(chunks.size() - 1), restoreChunk + 25);
m_preparedChunks.resize(chunks.size());
m_chunkLayouts.resize(chunks.size());
@@ -540,11 +541,11 @@ void ReadingModel::setReader(FormatReader *reader)
} else if (totalChars <= 0) {
m_totalPages = 1;
} else {
m_totalPages = std::max(1, static_cast<int>((totalChars + kNormalizedCharsPerPage - 1) / kNormalizedCharsPerPage));
m_totalPages = (std::max)(1, static_cast<int>((totalChars + kNormalizedCharsPerPage - 1) / kNormalizedCharsPerPage));
}
if (!m_chunks.isEmpty()) {
restoreChunk = qBound(0, restoreChunk, m_chunks.size() - 1);
restoreChunk = std::clamp(restoreChunk, 0, static_cast<int>(m_chunks.size() - 1));
} else {
restoreChunk = 0;
}
@@ -562,7 +563,7 @@ void ReadingModel::setReader(FormatReader *reader)
}
if (m_reader && !m_isTextMode) {
const int safeRestoreChunk = !m_pages.isEmpty() ? qBound(0, restoreChunk, m_pages.size() - 1) : 0;
const int safeRestoreChunk = !m_pages.isEmpty() ? std::clamp(restoreChunk, 0, static_cast<int>(m_pages.size() - 1)) : 0;
QMetaObject::invokeMethod(this, [this, safeRestoreChunk] {
emit restoreReady(safeRestoreChunk, 0.0);
}, Qt::QueuedConnection);
+12 -12
View File
@@ -16,20 +16,20 @@
class ReadingModel : public QAbstractListModel {
Q_OBJECT
Q_PROPERTY(bool isTextMode READ isTextMode NOTIFY modeChanged)
Q_PROPERTY(bool isMangaMode READ isMangaMode NOTIFY modeChanged)
Q_PROPERTY(bool measuring READ measuring NOTIFY measuringChanged)
Q_PROPERTY(double progress READ progress NOTIFY progressChanged)
Q_PROPERTY(int currentPage READ currentPage NOTIFY currentPageChanged)
Q_PROPERTY(int totalPages READ totalPages NOTIFY totalPagesChanged)
Q_PROPERTY(int currentChunk READ currentChunk NOTIFY currentChunkChanged)
Q_PROPERTY(int totalPagePairs READ totalPagePairs NOTIFY totalPagePairsChanged)
Q_PROPERTY(bool pageShift READ pageShift NOTIFY pageShiftChanged)
Q_PROPERTY(bool mangaRTL READ mangaRTL NOTIFY mangaRTLChanged)
Q_PROPERTY(bool useBookColours READ useBookColours NOTIFY useBookColoursChanged)
Q_PROPERTY(bool isTextMode READ isTextMode NOTIFY modeChanged FINAL)
Q_PROPERTY(bool isMangaMode READ isMangaMode NOTIFY modeChanged FINAL)
Q_PROPERTY(bool measuring READ measuring NOTIFY measuringChanged FINAL)
Q_PROPERTY(double progress READ progress NOTIFY progressChanged FINAL)
Q_PROPERTY(int currentPage READ currentPage NOTIFY currentPageChanged FINAL)
Q_PROPERTY(int totalPages READ totalPages NOTIFY totalPagesChanged FINAL)
Q_PROPERTY(int currentChunk READ currentChunk NOTIFY currentChunkChanged FINAL)
Q_PROPERTY(int totalPagePairs READ totalPagePairs NOTIFY totalPagePairsChanged FINAL)
Q_PROPERTY(bool pageShift READ pageShift NOTIFY pageShiftChanged FINAL)
Q_PROPERTY(bool mangaRTL READ mangaRTL NOTIFY mangaRTLChanged FINAL)
Q_PROPERTY(bool useBookColours READ useBookColours NOTIFY useBookColoursChanged FINAL)
public:
enum ReadingRoles {
enum ReadingRoles : int {
ContentRole = Qt::UserRole + 1,
LayoutRole,
PixelHeightRole
+7 -7
View File
@@ -15,13 +15,13 @@
class Book : public QObject {
Q_OBJECT
Q_PROPERTY(bool hasBook READ hasBook NOTIFY bookChanged)
Q_PROPERTY(bool loading READ loading NOTIFY loadingChanged)
Q_PROPERTY(QString title READ title NOTIFY bookChanged)
Q_PROPERTY(QString author READ author NOTIFY bookChanged)
Q_PROPERTY(QString filePath READ filePath NOTIFY bookChanged)
Q_PROPERTY(QString coverImageUrl READ coverImageUrl NOTIFY bookChanged)
Q_PROPERTY(QString errorMessage READ errorMessage NOTIFY errorMessageChanged)
Q_PROPERTY(bool hasBook READ hasBook NOTIFY bookChanged FINAL)
Q_PROPERTY(bool loading READ loading NOTIFY loadingChanged FINAL)
Q_PROPERTY(QString title READ title NOTIFY bookChanged FINAL)
Q_PROPERTY(QString author READ author NOTIFY bookChanged FINAL)
Q_PROPERTY(QString filePath READ filePath NOTIFY bookChanged FINAL)
Q_PROPERTY(QString coverImageUrl READ coverImageUrl NOTIFY bookChanged FINAL)
Q_PROPERTY(QString errorMessage READ errorMessage NOTIFY errorMessageChanged FINAL)
public:
Book(IFileDialogService &dialog,
+3 -3
View File
@@ -17,17 +17,17 @@ QQuickTextureFactory *AsyncImageResponse::textureFactory() const
void AsyncImageResponse::cancel()
{
m_cancelled.storeRelaxed(1);
m_cancelled.store(true, std::memory_order_release);
}
void AsyncImageResponse::run()
{
if (m_cancelled.loadRelaxed())
if (m_cancelled.load(std::memory_order_acquire))
return;
m_image = m_job();
if (m_cancelled.loadRelaxed())
if (m_cancelled.load(std::memory_order_acquire))
return;
emit finished();
+2 -2
View File
@@ -1,7 +1,7 @@
#pragma once
#include <atomic>
#include <functional>
#include <QAtomicInt>
#include <QImage>
#include <QQuickImageResponse>
#include <QRunnable>
@@ -19,6 +19,6 @@ public:
private:
std::function<QImage()> m_job;
QAtomicInt m_cancelled{0};
std::atomic<bool> m_cancelled{false};
QImage m_image;
};
+2 -2
View File
@@ -33,7 +33,7 @@ QString AuthorAttribution::mapRole(const std::optional<QString> &roleCode)
QString AuthorAttribution::formatCreators(const QList<CreatorItem> &creators)
{
QList<QString> roleOrder;
QStringList roleOrder;
QHash<QString, QStringList> roleToNames;
for (const auto &creator : creators) {
@@ -60,7 +60,7 @@ QString AuthorAttribution::formatCreators(const QList<CreatorItem> &creators)
QStringList formattedGroups;
formattedGroups.reserve(roleOrder.size());
for (const auto &role : roleOrder) {
formattedGroups.append(QStringLiteral("%1: %2").arg(role, roleToNames[role].join(QStringLiteral(", "))));
formattedGroups.append(QStringLiteral("%1: %2").arg(role).arg(roleToNames[role].join(QStringLiteral(", "))));
}
return formattedGroups.join(QStringLiteral(", "));
+7 -7
View File
@@ -6,10 +6,10 @@
#include <optional>
struct StructuredAuthor {
std::optional<QString> firstName;
std::optional<QString> middleName;
std::optional<QString> lastName;
std::optional<QString> nickname;
std::optional<QString> firstName = std::nullopt;
std::optional<QString> middleName = std::nullopt;
std::optional<QString> lastName = std::nullopt;
std::optional<QString> nickname = std::nullopt;
bool operator==(const StructuredAuthor &other) const
{
@@ -25,7 +25,7 @@ struct StructuredAuthor {
};
struct CreatorItem {
std::optional<QString> roleCode;
std::optional<QString> roleCode = std::nullopt;
QString name;
bool operator==(const CreatorItem &other) const
@@ -62,7 +62,7 @@ struct BookMetadata {
MetadataStatus status = MetadataStatus::Unparsed;
QList<CreatorItem> rawDcCreators;
QList<StructuredAuthor> rawStructuredAuthors;
std::optional<QString> authorAttribution;
std::optional<QString> authorAttribution = std::nullopt;
bool operator==(const BookMetadata &other) const
{
@@ -121,7 +121,7 @@ public:
private:
BookMetadata m_metadata;
bool m_engineActive;
bool m_engineActive = true;
};
#endif // AUTHORATTRIBUTION_H
+8 -4
View File
@@ -97,15 +97,19 @@ bool EpubReader::parseOpf(const QByteArray &data, IByteSource &source, bool meta
} else if (name == QLatin1String("itemref")) {
const auto attrs = xml.attributes();
const QString idref = attrs.value(QLatin1String("idref")).toString();
if (m_manifest.contains(idref)) {
const QString resolved = QDir::cleanPath(m_opfDir + m_manifest[idref].href);
auto it = m_manifest.constFind(idref);
if (it != m_manifest.constEnd()) {
const QString resolved = QDir::cleanPath(m_opfDir + it.value().href);
m_spineHrefs.append(resolved);
}
}
}
if (!coverId.isEmpty() && m_manifest.contains(coverId)) {
m_coverEntry = QDir::cleanPath(m_opfDir + m_manifest[coverId].href);
if (!coverId.isEmpty()) {
auto it = m_manifest.constFind(coverId);
if (it != m_manifest.constEnd()) {
m_coverEntry = QDir::cleanPath(m_opfDir + it.value().href);
}
} else {
// Fallback: look for item with id cover/cover-image and image media type
for (auto it = m_manifest.begin(); it != m_manifest.end(); ++it) {
+5 -5
View File
@@ -8,10 +8,10 @@
#include "backend/reading/layout/HtmlBlockParser.h"
struct AuthorName {
std::optional<QString> first_name;
std::optional<QString> middle_name;
std::optional<QString> last_name;
std::optional<QString> nickname;
std::optional<QString> first_name = std::nullopt;
std::optional<QString> middle_name = std::nullopt;
std::optional<QString> last_name = std::nullopt;
std::optional<QString> nickname = std::nullopt;
bool has_structured_name() const
{
@@ -51,7 +51,7 @@ struct AuthorName {
struct BinaryResource {
QString id;
std::optional<QString> content_type;
std::optional<QString> content_type = std::nullopt;
QByteArray decoded_bytes;
bool operator==(const BinaryResource &o) const
+2 -1
View File
@@ -3,6 +3,7 @@
#include <QRegularExpression>
#include <QStringDecoder>
#include <QtGlobal>
#include <algorithm>
#include <iconv.h>
namespace TextEncoding {
@@ -16,7 +17,7 @@ QString detectEncoding(const QByteArray &bytes)
if (bytes.startsWith("\xFE\xFF"))
return QStringLiteral("UTF-16BE");
const int checkLen = qMin(1024, bytes.size());
const int checkLen = (std::min)(1024, static_cast<int>(bytes.size()));
const QString headerStr = QString::fromLatin1(bytes.constData(), checkLen);
// 1. XML declaration: <?xml version="1.0" encoding="..."?>
+11 -5
View File
@@ -13,6 +13,9 @@
#include <QStandardPaths>
#include <QThreadPool>
#include <QUrl>
#if QT_CONFIG(ssl)
#include <QSslError>
#endif
#include "AsyncImageResponse.h"
#include "ImageScaling.h"
@@ -87,14 +90,17 @@ static QByteArray defaultHttpFetch(const QString &urlString)
QEventLoop loop;
QObject::connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit);
#if QT_CONFIG(ssl)
QObject::connect(reply, &QNetworkReply::sslErrors, &loop, [&loop](const QList<QSslError> &) {
loop.quit();
});
#endif
loop.exec();
if (reply->error() != QNetworkReply::NoError) {
reply->deleteLater();
return {};
QByteArray data;
if (reply->error() == QNetworkReply::NoError) {
data = reply->readAll();
}
const QByteArray data = reply->readAll();
reply->deleteLater();
return data;
}
+2 -1
View File
@@ -162,11 +162,12 @@ bool ComicReader::parseOpenSource(const QString &filePath, IByteSource &source,
if (!data.isEmpty()) {
QBuffer buf;
buf.setData(data);
buf.open(QIODevice::ReadOnly);
if (buf.open(QIODevice::ReadOnly)) {
QImageReader reader(&buf);
naturalSize = reader.size();
}
}
}
m_pageEntries.append({entry, naturalSize});
}
@@ -4,6 +4,7 @@
#include <QFileInfo>
#include <QRegularExpression>
#include <QXmlStreamReader>
#include <algorithm>
#include "backend/formats/sources/ZipByteSource.h"
@@ -31,7 +32,7 @@ qsizetype findCaseInsensitive(const QByteArray &haystack, const QByteArray &need
const qsizetype hLen = haystack.size();
if (nLen == 0 || from >= hLen)
return -1;
for (qsizetype i = qMax(qsizetype(0), from); i <= hLen - nLen; ++i) {
for (qsizetype i = (std::max)(qsizetype(0), from); i <= hLen - nLen; ++i) {
bool match = true;
for (qsizetype j = 0; j < nLen; ++j) {
char c1 = haystack[i + j];
@@ -82,8 +82,8 @@ bool ZipByteSource::open(const QString &path)
if (unzGoToFirstFile(zf) == UNZ_OK) {
do {
char name[4096];
unz_file_info64 info{};
unz64_file_pos pos{};
unz_file_info64 info = {};
unz64_file_pos pos = {};
unzGetFilePos64(zf, &pos);
if (unzGetCurrentFileInfo64(zf, &info, name, static_cast<uLong>(sizeof(name) - 1),
nullptr, 0, nullptr, 0) == UNZ_OK) {
+2 -1
View File
@@ -135,7 +135,7 @@ QSizeF BookImageResolver::imageSize(const QString &imageUrl)
if (!bytes.isEmpty()) {
QBuffer buffer;
buffer.setData(bytes);
buffer.open(QIODevice::ReadOnly);
if (buffer.open(QIODevice::ReadOnly)) {
QImageReader reader(&buffer);
const QSize sz = reader.size();
if (sz.isValid() && sz.width() > 0 && sz.height() > 0) {
@@ -145,6 +145,7 @@ QSizeF BookImageResolver::imageSize(const QString &imageUrl)
return sizeF;
}
}
}
// Fall back to resolving full image
const QImage img = resolveImage(imageUrl);
+2 -2
View File
@@ -100,8 +100,8 @@ qreal KnuthPlassItem::contrastRatio(const QColor &c1, const QColor &c2)
{
const qreal l1 = relativeLuminance(c1);
const qreal l2 = relativeLuminance(c2);
const qreal lighter = std::max(l1, l2);
const qreal darker = std::min(l1, l2);
const qreal lighter = (std::max)(l1, l2);
const qreal darker = (std::min)(l1, l2);
return (lighter + 0.05) / (darker + 0.05);
}
+9 -7
View File
@@ -4,6 +4,7 @@
#include <QPainter>
#include <QQuickPaintedItem>
#include <QVariant>
#include <QtQmlIntegration/qqmlintegration.h>
#include "layout/ChunkLayoutEngine.h"
@@ -11,13 +12,14 @@ class IBookImageResolver;
class KnuthPlassItem : public QQuickPaintedItem {
Q_OBJECT
Q_PROPERTY(QVariant layout READ layout WRITE setLayout NOTIFY layoutChanged)
Q_PROPERTY(QColor textColor READ textColor WRITE setTextColor NOTIFY colorsChanged)
Q_PROPERTY(QColor linkColor READ linkColor WRITE setLinkColor NOTIFY colorsChanged)
Q_PROPERTY(QColor dimColor READ dimColor WRITE setDimColor NOTIFY colorsChanged)
Q_PROPERTY(QColor surfaceColor READ surfaceColor WRITE setSurfaceColor NOTIFY colorsChanged)
Q_PROPERTY(bool useBookColours READ useBookColours WRITE setUseBookColours NOTIFY useBookColoursChanged)
Q_PROPERTY(qreal horizontalMargin READ horizontalMargin WRITE setHorizontalMargin NOTIFY horizontalMarginChanged)
QML_ELEMENT
Q_PROPERTY(QVariant layout READ layout WRITE setLayout NOTIFY layoutChanged FINAL)
Q_PROPERTY(QColor textColor READ textColor WRITE setTextColor NOTIFY colorsChanged FINAL)
Q_PROPERTY(QColor linkColor READ linkColor WRITE setLinkColor NOTIFY colorsChanged FINAL)
Q_PROPERTY(QColor dimColor READ dimColor WRITE setDimColor NOTIFY colorsChanged FINAL)
Q_PROPERTY(QColor surfaceColor READ surfaceColor WRITE setSurfaceColor NOTIFY colorsChanged FINAL)
Q_PROPERTY(bool useBookColours READ useBookColours WRITE setUseBookColours NOTIFY useBookColoursChanged FINAL)
Q_PROPERTY(qreal horizontalMargin READ horizontalMargin WRITE setHorizontalMargin NOTIFY horizontalMarginChanged FINAL)
public:
explicit KnuthPlassItem(QQuickItem *parent = nullptr);
@@ -128,7 +128,7 @@ public:
private:
void handleContainerStart(const BoxStyle &box)
{
qreal collapsedMargin = std::max(m_prevMarginBottom, box.marginTop);
qreal collapsedMargin = (std::max)(m_prevMarginBottom, box.marginTop);
m_curY += collapsedMargin;
m_prevMarginBottom = 0;
@@ -152,7 +152,7 @@ private:
PositionedDecoration dec;
dec.rect = QRectF(ab.left, ab.startY,
std::max(0.0, m_params.contentWidth - ab.left - ab.right),
(std::max)(0.0, m_params.contentWidth - ab.left - ab.right),
m_curY - ab.startY);
dec.background = box.background;
dec.borderColor = box.borderColor;
@@ -171,11 +171,11 @@ private:
void handleRule(const QColor &color)
{
m_curY += std::max(m_prevMarginBottom, 8.0);
m_curY += (std::max)(m_prevMarginBottom, 8.0);
PositionedRule r;
qreal left = currentLeft();
qreal right = currentRight();
r.rect = QRectF(left, m_curY, std::max(10.0, m_params.contentWidth - left - right), 1.0);
r.rect = QRectF(left, m_curY, (std::max)(10.0, m_params.contentWidth - left - right), 1.0);
r.color = color;
m_layout.rules.append(r);
m_curY += 1.0;
@@ -204,7 +204,7 @@ private:
{
qreal left = currentLeft();
qreal right = currentRight();
qreal availWidth = std::max(50.0, m_params.contentWidth - left - right);
qreal availWidth = (std::max)(50.0, m_params.contentWidth - left - right);
qreal natW = item.naturalSize.width() > 0 ? item.naturalSize.width() : 100.0;
qreal natH = item.naturalSize.height() > 0 ? item.naturalSize.height() : 100.0;
@@ -232,7 +232,7 @@ private:
targetH *= scale;
}
qreal imgX = left + std::max(0.0, (availWidth - targetW) / 2.0);
qreal imgX = left + (std::max)(0.0, (availWidth - targetW) / 2.0);
m_curY += 8.0;
PositionedImage posImg;
@@ -262,7 +262,7 @@ private:
qreal left = currentLeft();
qreal right = currentRight();
qreal availWidth = std::max(50.0, m_params.contentWidth - left - right);
qreal availWidth = (std::max)(50.0, m_params.contentWidth - left - right);
// Check if any word exceeds line width (emergency letter split fallback)
QVector<PreparedWord> activeWords = p.words;
@@ -326,8 +326,8 @@ private:
const auto &it = kpItems[itIdx];
if (it.type == KnuthPlass::ItemType::Box && it.tag >= 0 && it.tag < activeWords.size()) {
const auto &tok = activeWords[it.tag];
maxAscent = std::max(maxAscent, tok.ascent);
maxDescent = std::max(maxDescent, tok.descent);
maxAscent = (std::max)(maxAscent, tok.ascent);
maxDescent = (std::max)(maxDescent, tok.descent);
}
}
@@ -344,7 +344,7 @@ private:
contentW += it.width;
} else {
qreal adj = (line.ratio >= 0) ? (line.ratio * it.stretch) : (line.ratio * it.shrink);
contentW += std::max(0.0, it.width + adj);
contentW += (std::max)(0.0, it.width + adj);
}
}
}
@@ -354,9 +354,9 @@ private:
qreal startX = left;
if (p.align == TextAlign::Center) {
startX += std::max(0.0, (availWidth - contentW) / 2.0);
startX += (std::max)(0.0, (availWidth - contentW) / 2.0);
} else if (p.align == TextAlign::Right) {
startX += std::max(0.0, availWidth - contentW);
startX += (std::max)(0.0, availWidth - contentW);
}
qreal curX = startX;
@@ -407,7 +407,7 @@ private:
qreal spaceW = it.width;
if (!isLastLine && p.align == TextAlign::Justify) {
qreal adj = (line.ratio >= 0) ? (line.ratio * it.stretch) : (line.ratio * it.shrink);
spaceW = std::max(0.0, it.width + adj);
spaceW = (std::max)(0.0, it.width + adj);
}
curX += spaceW;
}
+8 -5
View File
@@ -8,6 +8,8 @@ namespace Css {
namespace {
static const QRegularExpression kUrl(QStringLiteral("url\\(\\s*(['\"]?)([^'\")]+)\\1\\s*\\)"));
QString stripComments(const QString &css)
{
QString out;
@@ -159,7 +161,7 @@ QVector<Declaration> parseDeclarations(QStringView block)
}
if (c == QLatin1Char('"') || c == QLatin1Char('\'')) quote = c;
else if (c == QLatin1Char('(')) ++depth;
else if (c == QLatin1Char(')')) depth = std::max(0, depth - 1);
else if (c == QLatin1Char(')')) depth = (std::max)(0, depth - 1);
else if (c == QLatin1Char(';') && depth == 0) flush(i);
}
flush(block.size());
@@ -178,7 +180,8 @@ std::optional<Selector> parseSelector(QStringView text)
// Normalise child combinators so tokens are whitespace separated.
QString normalized = s;
normalized.replace(QLatin1Char('>'), QStringLiteral(" > "));
const QStringList tokens = normalized.split(QRegularExpression(QStringLiteral("\\s+")), Qt::SkipEmptyParts);
static const QRegularExpression kWhitespace(QStringLiteral("\\s+"));
const QStringList tokens = normalized.split(kWhitespace, Qt::SkipEmptyParts);
Selector sel;
QChar pending = QLatin1Char(' ');
@@ -236,7 +239,6 @@ StyleSheet StyleSheet::parse(const QString &cssIn)
if (d.property == QLatin1String("font-family")) {
face.family = unquote(d.value);
} else if (d.property == QLatin1String("src")) {
static const QRegularExpression kUrl(QStringLiteral("url\\(\\s*(['\"]?)([^'\")]+)\\1\\s*\\)"));
const auto m = kUrl.match(d.value);
if (m.hasMatch() && face.src.isEmpty())
face.src = m.captured(2).trimmed();
@@ -360,7 +362,8 @@ QColor parseColor(QStringView valueIn)
static const QRegularExpression kFunc(QStringLiteral("^(rgba?|hsla?)\\(([^)]*)\\)$"));
const auto m = kFunc.match(value);
if (m.hasMatch()) {
QStringList parts = m.captured(2).split(QRegularExpression(QStringLiteral("[\\s,/]+")), Qt::SkipEmptyParts);
static const QRegularExpression kColorSep(QStringLiteral("[\\s,/]+"));
QStringList parts = m.captured(2).split(kColorSep, Qt::SkipEmptyParts);
if (parts.size() < 3)
return {};
auto channel = [](const QString &p, qreal scale) {
@@ -436,7 +439,7 @@ QStringList splitValue(QStringView value)
int depth = 0;
for (QChar c : value) {
if (c == QLatin1Char('(')) ++depth;
if (c == QLatin1Char(')')) depth = std::max(0, depth - 1);
if (c == QLatin1Char(')')) depth = (std::max)(0, depth - 1);
if (c.isSpace() && depth == 0) {
if (!cur.isEmpty()) out << cur;
cur.clear();
+1 -1
View File
@@ -72,7 +72,7 @@ struct LengthContext {
};
struct BorderSide {
std::optional<qreal> width;
std::optional<qreal> width = std::nullopt;
QColor color;
bool isNone = false;
};
@@ -1,6 +1,7 @@
#include "DocumentChunkBuilder.h"
#include <QRegularExpression>
#include <utility>
namespace {
@@ -294,5 +295,5 @@ QVector<ContentChunk> DocumentChunkBuilder::build()
m_currentChunk.sectionHref = m_sectionHref;
}
return std::move(m_chunks);
return std::exchange(m_chunks, {});
}
@@ -371,7 +371,7 @@ private:
box.marginTop = m_params.baseFontSize * 0.5;
box.marginBottom = m_params.baseFontSize * 0.25;
} else if (tag == QLatin1String("title")) {
const int hLevel = qBound(1, m_headingDepth, 6);
const int hLevel = std::clamp(m_headingDepth, 1, 6);
const qreal hScale = (hLevel == 1) ? 1.8 : (hLevel == 2 ? 1.5 : (hLevel == 3 ? 1.3 : 1.1));
const qreal hMarginTop = (hLevel == 1) ? 1.0 : (hLevel == 2 ? 0.8 : (hLevel == 3 ? 0.6 : 0.5));
ctx.text.fontSize = m_params.baseFontSize * hScale;
+2 -2
View File
@@ -131,7 +131,7 @@ public:
if (r < -1 || r > tolerance)
continue;
const qreal badness = std::min(100.0 * std::pow(std::abs(r), 3), kInfinity);
const qreal badness = (std::min)(100.0 * std::pow(std::abs(r), 3), kInfinity);
qreal d = m_params.linePenalty + badness;
d *= d;
if (brk.type == ItemType::Penalty) {
@@ -246,7 +246,7 @@ QVector<Line> breakLines(const QVector<Item> &items, qreal lineWidth, const Para
return {};
Q_ASSERT(isForced(items.last()));
Solver solver(items, std::max<qreal>(1.0, lineWidth), params);
Solver solver(items, (std::max)(1.0, lineWidth), params);
int finalNode = solver.run(params.tolerance, false);
if (finalNode < 0)
finalNode = solver.run(params.looseTolerance, false);
+5 -4
View File
@@ -1,14 +1,15 @@
#include "ReadingPreferences.h"
#include <algorithm>
#include <QtGlobal>
ReadingPreferences::ReadingPreferences(AppState &state, QObject *parent)
: QObject(parent), m_state(state)
{
const QVariantMap d = state.loadSection(QStringLiteral("reading"));
m_fontSize = qBound(8, d.value(QStringLiteral("fontSize"), 16).toInt(), 72);
m_lineSpacing = qMax(0.1, d.value(QStringLiteral("lineSpacing"), 1.0).toDouble());
m_horizontalMargin = qMax(0, d.value(QStringLiteral("horizontalMargin"), 32).toInt());
m_verticalMargin = qMax(0, d.value(QStringLiteral("verticalMargin"), 8).toInt());
m_fontSize = std::clamp(d.value(QStringLiteral("fontSize"), 16).toInt(), 8, 72);
m_lineSpacing = (std::max)(0.1, d.value(QStringLiteral("lineSpacing"), 1.0).toDouble());
m_horizontalMargin = (std::max)(0, d.value(QStringLiteral("horizontalMargin"), 32).toInt());
m_verticalMargin = (std::max)(0, d.value(QStringLiteral("verticalMargin"), 8).toInt());
}
int ReadingPreferences::fontSize() const { return m_fontSize; }
+4 -4
View File
@@ -6,10 +6,10 @@
class ReadingPreferences : public QObject {
Q_OBJECT
Q_PROPERTY(int fontSize READ fontSize WRITE setFontSize NOTIFY fontSizeChanged)
Q_PROPERTY(qreal lineSpacing READ lineSpacing WRITE setLineSpacing NOTIFY lineSpacingChanged)
Q_PROPERTY(int horizontalMargin READ horizontalMargin WRITE setHorizontalMargin NOTIFY horizontalMarginChanged)
Q_PROPERTY(int verticalMargin READ verticalMargin WRITE setVerticalMargin NOTIFY verticalMarginChanged)
Q_PROPERTY(int fontSize READ fontSize WRITE setFontSize NOTIFY fontSizeChanged FINAL)
Q_PROPERTY(qreal lineSpacing READ lineSpacing WRITE setLineSpacing NOTIFY lineSpacingChanged FINAL)
Q_PROPERTY(int horizontalMargin READ horizontalMargin WRITE setHorizontalMargin NOTIFY horizontalMarginChanged FINAL)
Q_PROPERTY(int verticalMargin READ verticalMargin WRITE setVerticalMargin NOTIFY verticalMarginChanged FINAL)
public:
explicit ReadingPreferences(AppState &state, QObject *parent = nullptr);
+10 -10
View File
@@ -8,16 +8,16 @@
class UiState : public QObject {
Q_OBJECT
Q_PROPERTY(QString themeName READ themeName WRITE setThemeName NOTIFY themeNameChanged)
Q_PROPERTY(QString lastPage READ lastPage WRITE setLastPage NOTIFY lastPageChanged)
Q_PROPERTY(bool sidebarOpen READ sidebarOpen WRITE setSidebarOpen NOTIFY sidebarOpenChanged)
Q_PROPERTY(bool barsVisible READ barsVisible WRITE setBarsVisible NOTIFY barsVisibleChanged)
Q_PROPERTY(QString lastFilePath READ lastFilePath WRITE setLastFilePath NOTIFY lastFilePathChanged)
Q_PROPERTY(QVariantMap customThemeColors READ customThemeColors WRITE setCustomThemeColors NOTIFY customThemeColorsChanged)
Q_PROPERTY(int windowWidth READ windowWidth WRITE setWindowWidth NOTIFY windowWidthChanged)
Q_PROPERTY(int windowHeight READ windowHeight WRITE setWindowHeight NOTIFY windowHeightChanged)
Q_PROPERTY(int windowX READ windowX WRITE setWindowX NOTIFY windowXChanged)
Q_PROPERTY(int windowY READ windowY WRITE setWindowY NOTIFY windowYChanged)
Q_PROPERTY(QString themeName READ themeName WRITE setThemeName NOTIFY themeNameChanged FINAL)
Q_PROPERTY(QString lastPage READ lastPage WRITE setLastPage NOTIFY lastPageChanged FINAL)
Q_PROPERTY(bool sidebarOpen READ sidebarOpen WRITE setSidebarOpen NOTIFY sidebarOpenChanged FINAL)
Q_PROPERTY(bool barsVisible READ barsVisible WRITE setBarsVisible NOTIFY barsVisibleChanged FINAL)
Q_PROPERTY(QString lastFilePath READ lastFilePath WRITE setLastFilePath NOTIFY lastFilePathChanged FINAL)
Q_PROPERTY(QVariantMap customThemeColors READ customThemeColors WRITE setCustomThemeColors NOTIFY customThemeColorsChanged FINAL)
Q_PROPERTY(int windowWidth READ windowWidth WRITE setWindowWidth NOTIFY windowWidthChanged FINAL)
Q_PROPERTY(int windowHeight READ windowHeight WRITE setWindowHeight NOTIFY windowHeightChanged FINAL)
Q_PROPERTY(int windowX READ windowX WRITE setWindowX NOTIFY windowXChanged FINAL)
Q_PROPERTY(int windowY READ windowY WRITE setWindowY NOTIFY windowYChanged FINAL)
public:
explicit UiState(AppState &state, QObject *parent = nullptr);
+20 -8
View File
@@ -11,6 +11,7 @@
#include "backend/AppCoordinator.h"
#include "backend/AppState.h"
#include "backend/QmlRegistrations.h"
#include "backend/formats/FileIconProvider.h"
#include "backend/formats/FormatRegistry.h"
#include "backend/formats/WebImageProvider.h"
@@ -35,7 +36,7 @@
void myMessageHandler(const QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
QString timestamp = QDateTime::currentDateTime().toString(QStringLiteral("yyyy-MM-dd hh:mm:ss.zzz"));
QString timestamp = QDateTime::currentDateTimeUtc().toString(QStringLiteral("yyyy-MM-dd hh:mm:ss.zzz"));
QString level;
switch (type) {
@@ -56,9 +57,9 @@ void myMessageHandler(const QtMsgType type, const QMessageLogContext &context, c
QString formattedMsg;
if (source.isEmpty()) {
formattedMsg = QStringLiteral("%1 [%2] %3").arg(timestamp, level, msg);
formattedMsg = QStringLiteral("%1 [%2] %3").arg(timestamp).arg(level).arg(msg);
} else {
formattedMsg = QStringLiteral("%1 [%2] [%3] %4").arg(timestamp, level, source, msg);
formattedMsg = QStringLiteral("%1 [%2] [%3] %4").arg(timestamp).arg(level).arg(source).arg(msg);
}
QTextStream(stdout, QIODevice::WriteOnly) << formattedMsg << Qt::endl;
@@ -119,19 +120,26 @@ int main(int argc, char *argv[])
}
#if defined(HAS_QT_DBUS) && defined(Q_OS_LINUX)
IFileDialogService *fileDialogService;
std::unique_ptr<IFileDialogService> fileDialogService;
if (QDBusConnection::sessionBus().isConnected()) {
fileDialogService = new PortalFileDialogService(nullptr);
fileDialogService = std::make_unique<PortalFileDialogService>(nullptr);
} else {
fileDialogService = new NativeFileDialogService(nullptr);
fileDialogService = std::make_unique<NativeFileDialogService>(nullptr);
}
#else
IFileDialogService *fileDialogService = new NativeFileDialogService(nullptr);
auto fileDialogService = std::make_unique<NativeFileDialogService>(nullptr);
#endif
Book book(*fileDialogService, formatRegistry);
ReadingModel readingModel(bookPositions);
// Register backend singleton instances for QML
BookQmlSingleton::s_instance = &book;
ReadingModelQmlSingleton::s_instance = &readingModel;
ReadingPreferencesQmlSingleton::s_instance = &readingPreferences;
UiStateQmlSingleton::s_instance = &uiState;
HistoryModelQmlSingleton::s_instance = &historyModel;
auto webStorage = std::make_shared<DiskWebImageStorage>();
auto *webProvider = new WebImageProvider(webStorage);
@@ -144,7 +152,6 @@ int main(int argc, char *argv[])
// --- QML engine ---
QQmlApplicationEngine engine;
qmlRegisterType<KnuthPlassItem>("Asteria", 1, 0, "KnuthPlassItem");
engine.addImageProvider(QStringLiteral("fileicon"), new FileIconProvider());
engine.addImageProvider(QStringLiteral("web"), webProvider);
formatRegistry.registerImageProviders(engine);
@@ -191,5 +198,10 @@ int main(int argc, char *argv[])
const int ret = QApplication::exec();
imageResolver.setWebProvider(nullptr);
BookQmlSingleton::s_instance = nullptr;
ReadingModelQmlSingleton::s_instance = nullptr;
ReadingPreferencesQmlSingleton::s_instance = nullptr;
UiStateQmlSingleton::s_instance = nullptr;
HistoryModelQmlSingleton::s_instance = nullptr;
return ret;
}
+3 -22
View File
@@ -1,26 +1,7 @@
pragma Singleton
import QtQuick
import Asteria
QtObject {
readonly property color backgroundDeepest: "#010620"
readonly property color backgroundDefault: "#191d35"
readonly property color surface: "#191d35"
readonly property color headerBg: "#14172c"
readonly property color footerBg: "#1a1e36"
readonly property color scrollbarTrack: "#131628"
readonly property color scrollbarThumb: "#36486a"
readonly property color primaryAccent: "#3a5688"
readonly property color buttonAccent: "#5785c1"
readonly property color sidebarButtonText: "#98aaf4"
readonly property color readingText: "#c4c8d8"
readonly property color uiText: "#a2a5b4"
readonly property color headerText: "#8488aa"
readonly property color dimText: "#71738c"
readonly property color counterText: "#606175"
readonly property color gradientTop: "#0e1125"
readonly property color gradientBottom: "#191d35"
readonly property color divider: Qt.rgba(1, 1, 1, 0.12)
readonly property color overlayBg: Qt.rgba(0.055, 0.055, 0.067, 0.4)
readonly property color actionDisabled: "#141724"
ThemePalette {
id: root
}
+23 -21
View File
@@ -1,26 +1,28 @@
pragma Singleton
import QtQuick
import Asteria
QtObject {
readonly property color backgroundDeepest: "#4d4e53"
readonly property color backgroundDefault: "#312d2b"
readonly property color surface: "#312d2b"
readonly property color headerBg: "#c1b5a5"
readonly property color footerBg: "#c3b6a8"
readonly property color scrollbarTrack: "#4f505a"
readonly property color scrollbarThumb: "#36486a"
readonly property color primaryAccent: "#3a5688"
readonly property color buttonAccent: "#5785c1"
readonly property color sidebarButtonText: "#d8c6b1"
readonly property color readingText: "#c4c8d8"
readonly property color uiText: "#a2a5b4"
readonly property color headerText: "#8488aa"
readonly property color dimText: "#71738c"
readonly property color counterText: "#606175"
ThemePalette {
id: root
readonly property color gradientTop: "#d8c6b1"
readonly property color gradientBottom: "#312d2b"
readonly property color divider: Qt.rgba(1, 1, 1, 0.12)
readonly property color overlayBg: Qt.rgba(0.055, 0.055, 0.067, 0.4)
readonly property color actionDisabled: "#141724"
backgroundDeepest: "#4d4e53"
backgroundDefault: "#312d2b"
surface: "#312d2b"
headerBg: "#c1b5a5"
footerBg: "#c3b6a8"
scrollbarTrack: "#4f505a"
scrollbarThumb: "#36486a"
primaryAccent: "#3a5688"
buttonAccent: "#5785c1"
sidebarButtonText: "#d8c6b1"
readingText: "#c4c8d8"
uiText: "#a2a5b4"
headerText: "#8488aa"
dimText: "#71738c"
counterText: "#606175"
gradientTop: "#d8c6b1"
gradientBottom: "#312d2b"
divider: Qt.rgba(1, 1, 1, 0.12)
overlayBg: Qt.rgba(0.055, 0.055, 0.067, 0.4)
actionDisabled: "#141724"
}
+97 -91
View File
@@ -1,10 +1,20 @@
import QtQuick
import QtQuick.Controls
import QtQuick.Controls.Basic
import Asteria
import QtQml
ApplicationWindow {
id: window
id: root
// UiState.sidebarOpen is user preference; visible sidebar is gated by barsVisible in reader mode.
readonly property bool barsVisible: UiState.barsVisible
readonly property bool inReader: root.currentPage === "reader" || (root._startupRestore && UiState.lastPage === "reader")
readonly property bool sidebarOpen: (!root.inReader || root.barsVisible) && UiState.sidebarOpen
property string currentPage: "starter"
property bool settingsOpen: false
// Set to true on the first book open at startup so we restore the last page.
property bool _startupRestore: UiState.lastFilePath !== ""
property bool _bookInitializing: false
width: 1024
height: 768
opacity: 0
@@ -17,60 +27,50 @@ ApplicationWindow {
source: "qrc:/Asteria/src/assets/MaterialIconsOutlined-Regular.otf"
}
// uiState.sidebarOpen is user preference; visible sidebar is gated by barsVisible in reader mode.
readonly property bool barsVisible: uiState.barsVisible
readonly property bool inReader: currentPage === "reader" || (_startupRestore && uiState.lastPage === "reader")
readonly property bool sidebarOpen: (!inReader || barsVisible) && uiState.sidebarOpen
property string currentPage: "starter"
property bool settingsOpen: false
// Set to true on the first book open at startup so we restore the last page.
property bool _startupRestore: uiState.lastFilePath !== ""
property bool _bookInitializing: false
function toggleChrome() {
if (currentPage === "reader") {
uiState.barsVisible = !uiState.barsVisible
if (root.currentPage === "reader") {
UiState.barsVisible = !UiState.barsVisible
}
}
onCurrentPageChanged: uiState.lastPage = currentPage
onCurrentPageChanged: UiState.lastPage = root.currentPage
Component.onCompleted: {
width = uiState.windowWidth
height = uiState.windowHeight
if (uiState.windowX >= 0 && uiState.windowY >= 0) {
x = uiState.windowX
y = uiState.windowY
root.width = UiState.windowWidth
root.height = UiState.windowHeight
if (UiState.windowX >= 0 && UiState.windowY >= 0) {
root.x = UiState.windowX
root.y = UiState.windowY
}
ThemeManager.loadCustomColors(uiState.customThemeColors)
if (uiState.themeName !== "")
ThemeManager.currentThemeName = uiState.themeName
ThemeManager.loadCustomColors(UiState.customThemeColors)
if (UiState.themeName !== "")
ThemeManager.currentThemeName = UiState.themeName
}
Connections {
target: uiState
target: UiState
function onThemeNameChanged() {
ThemeManager.currentThemeName = uiState.themeName
ThemeManager.currentThemeName = UiState.themeName
}
}
Connections {
target: book
target: Book
function onLoadingChanged() {
if (book.loading) window._bookInitializing = true
if (Book.loading) root._bookInitializing = true
}
function onErrorMessageChanged() {
if (book.errorMessage !== "") {
window._bookInitializing = false
window._startupRestore = false
uiState.barsVisible = true
if (Book.errorMessage !== "") {
root._bookInitializing = false
root._startupRestore = false
UiState.barsVisible = true
}
}
function onBookChanged() {
if (!book.hasBook) {
uiState.barsVisible = true
if (window.currentPage === "reader")
window.currentPage = "history"
if (!Book.hasBook) {
UiState.barsVisible = true
if (root.currentPage === "reader")
root.currentPage = "history"
}
}
}
@@ -80,10 +80,10 @@ ApplicationWindow {
interval: 250
repeat: false
onTriggered: {
uiState.windowWidth = window.width
uiState.windowHeight = window.height
uiState.windowX = window.x
uiState.windowY = window.y
UiState.windowWidth = root.width
UiState.windowHeight = root.height
UiState.windowX = root.x
UiState.windowY = root.y
}
}
@@ -98,22 +98,22 @@ ApplicationWindow {
SideBar {
id: sidebar
height: parent.height
sidebarOpen: window.sidebarOpen
onCloseDrawer: uiState.sidebarOpen = false
sidebarOpen: root.sidebarOpen
onCloseDrawer: UiState.sidebarOpen = false
onNavigateTo: function(page) {
if (page === "settings") {
window.currentPage = book.hasBook ? "reader" : "starter"
window.settingsOpen = true
root.currentPage = Book.hasBook ? "reader" : "starter"
root.settingsOpen = true
} else {
window.settingsOpen = false
window.currentPage = page
root.settingsOpen = false
root.currentPage = page
}
}
onOpenFile: {
book.browseAndOpen()
Book.browseAndOpen()
}
onCloseBook: {
book.close()
Book.close()
}
}
@@ -124,10 +124,10 @@ ApplicationWindow {
Header {
id: header
width: parent.width
sidebarOpen: window.sidebarOpen
currentPage: window.currentPage
barsVisible: !window.inReader || window.barsVisible
onMenuClicked: uiState.sidebarOpen = true
sidebarOpen: root.sidebarOpen
currentPage: root.currentPage
barsVisible: !root.inReader || root.barsVisible
onMenuClicked: UiState.sidebarOpen = true
}
Item {
@@ -137,36 +137,36 @@ ApplicationWindow {
StarterPage {
anchors.fill: parent
visible: window.currentPage === "starter"
visible: root.currentPage === "starter"
}
ReaderPage {
id: readerPage
anchors.fill: parent
visible: window.currentPage === "reader"
visible: root.currentPage === "reader"
}
HistoryPage {
anchors.fill: parent
visible: window.currentPage === "history"
visible: root.currentPage === "history"
}
CustomThemePage {
anchors.fill: parent
visible: window.currentPage === "customTheme"
visible: root.currentPage === "customTheme"
}
BusyIndicator {
anchors.centerIn: parent
running: window._bookInitializing
running: root._bookInitializing
visible: running
z: 10
}
SettingsPopup {
id: settingsPopup
visible: window.settingsOpen
onCloseRequested: window.settingsOpen = false
visible: root.settingsOpen
onCloseRequested: root.settingsOpen = false
}
}
@@ -174,7 +174,7 @@ ApplicationWindow {
Loader {
id: footerLoader
width: parent.width
active: window.currentPage === "reader" && window.barsVisible
active: root.currentPage === "reader" && root.barsVisible
sourceComponent: Footer {}
}
}
@@ -187,23 +187,29 @@ ApplicationWindow {
// Pre-warms QQuickPixmapReader on the main thread so the render thread
// never creates it first (which logs a QObject parent-thread warning).
Image { width: 0; height: 0; visible: false; source: "image://web/__warmup__" }
Image {
width: 0
height: 0
visible: false
source: "image://web/__warmup__"
sourceSize: Qt.size(1, 1)
}
// Navigate once measurement (and position restoration) is done
Connections {
target: readingModel
target: ReadingModel
function onRestoreReady(chunkIndex) {
if (!book.hasBook) return
window._bookInitializing = false
if (window._startupRestore) {
window._startupRestore = false
var savedPage = uiState.lastPage
if (!Book.hasBook) return
root._bookInitializing = false
if (root._startupRestore) {
root._startupRestore = false
const savedPage = UiState.lastPage
if (savedPage === "history")
window.currentPage = savedPage
root.currentPage = savedPage
else
window.currentPage = "reader"
root.currentPage = "reader"
} else {
window.currentPage = "reader"
root.currentPage = "reader"
}
}
}
@@ -212,14 +218,14 @@ ApplicationWindow {
Shortcut {
sequences: ["F", "F11"]
context: Qt.ApplicationShortcut
onActivated: window.visibility = (window.visibility === Window.FullScreen) ? Window.Windowed : Window.FullScreen
onActivated: root.visibility = (root.visibility === Window.FullScreen) ? Window.Windowed : Window.FullScreen
}
Shortcut {
sequence: "Left"
context: Qt.ApplicationShortcut
onActivated: {
if (currentPage === "reader" && readerPage?.pageView) {
readingModel.mangaRTL ? readerPage.pageView.handleScrollDown()
if (root.currentPage === "reader" && readerPage?.pageView) {
ReadingModel.mangaRTL ? readerPage.pageView.handleScrollDown()
: readerPage.pageView.handleScrollUp();
}
}
@@ -228,8 +234,8 @@ ApplicationWindow {
sequence: "Right"
context: Qt.ApplicationShortcut
onActivated: {
if (currentPage === "reader" && readerPage?.pageView) {
readingModel.mangaRTL ? readerPage.pageView.handleScrollUp()
if (root.currentPage === "reader" && readerPage?.pageView) {
ReadingModel.mangaRTL ? readerPage.pageView.handleScrollUp()
: readerPage.pageView.handleScrollDown();
}
}
@@ -238,7 +244,7 @@ ApplicationWindow {
sequences: ["PgUp", "Prior"]
context: Qt.ApplicationShortcut
onActivated: {
if (currentPage === "reader" && readerPage?.pageView) {
if (root.currentPage === "reader" && readerPage?.pageView) {
readerPage.pageView.handlePageUp();
}
}
@@ -247,7 +253,7 @@ ApplicationWindow {
sequences: ["PgDown", "Next"]
context: Qt.ApplicationShortcut
onActivated: {
if (currentPage === "reader" && readerPage?.pageView) {
if (root.currentPage === "reader" && readerPage?.pageView) {
readerPage.pageView.handlePageDown();
}
}
@@ -256,8 +262,8 @@ ApplicationWindow {
sequence: "Space"
context: Qt.ApplicationShortcut
onActivated: {
if (currentPage === "reader") {
window.toggleChrome();
if (root.currentPage === "reader") {
root.toggleChrome();
}
}
}
@@ -265,16 +271,16 @@ ApplicationWindow {
sequence: "M"
context: Qt.ApplicationShortcut
onActivated: {
if (currentPage === "reader")
readingModel.setMangaRTL(!readingModel.mangaRTL)
if (root.currentPage === "reader")
ReadingModel.setMangaRTL(!ReadingModel.mangaRTL)
}
}
Shortcut {
sequence: "S"
context: Qt.ApplicationShortcut
onActivated: {
if (currentPage === "reader")
readingModel.setPageShift(!readingModel.pageShift, readerPage.pageView.currentPair)
if (root.currentPage === "reader")
ReadingModel.setPageShift(!ReadingModel.pageShift, readerPage.pageView.currentPair)
}
}
@@ -284,16 +290,16 @@ ApplicationWindow {
interval: 1
triggeredOnStart: false
onTriggered: {
window.opacity = 1
if (uiState.lastFilePath !== "") {
window._startupRestore = true
book.openFromPath(uiState.lastFilePath)
root.opacity = 1
if (UiState.lastFilePath !== "") {
root._startupRestore = true
Book.openFromPath(UiState.lastFilePath)
} else {
var savedPage = uiState.lastPage
const savedPage = UiState.lastPage
if (savedPage === "history")
window.currentPage = savedPage
uiState.sidebarOpen = true
uiState.barsVisible = true
root.currentPage = savedPage
UiState.sidebarOpen = true
UiState.barsVisible = true
}
}
}
+45 -42
View File
@@ -1,7 +1,10 @@
pragma Singleton
import QtQuick
import Asteria
QtObject {
id: root
readonly property int sidebarWidth: 240
readonly property int headerHeight: 64
readonly property int footerHeight: 28
@@ -10,27 +13,27 @@ QtObject {
property string currentThemeName: "dark"
property QtObject customTheme: QtObject {
property color backgroundDeepest: "#010620"
property color backgroundDefault: "#191d35"
property color surface: "#191d35"
property color headerBg: "#14172c"
property color footerBg: "#1a1e36"
property color scrollbarTrack: "#131628"
property color scrollbarThumb: "#36486a"
property color primaryAccent: "#3a5688"
property color buttonAccent: "#5785c1"
property color sidebarButtonText: "#98aaf4"
property color readingText: "#c4c8d8"
property color uiText: "#a2a5b4"
property color headerText: "#8488aa"
property color dimText: "#71738c"
property color counterText: "#606175"
property color gradientTop: "#0e1125"
property color gradientBottom: "#191d35"
property color divider: Qt.rgba(1, 1, 1, 0.12)
property color overlayBg: Qt.rgba(0.055, 0.055, 0.067, 0.4)
property color actionDisabled: "#141724"
property ThemePalette customTheme: ThemePalette {
backgroundDeepest: "#010620"
backgroundDefault: "#191d35"
surface: "#191d35"
headerBg: "#14172c"
footerBg: "#1a1e36"
scrollbarTrack: "#131628"
scrollbarThumb: "#36486a"
primaryAccent: "#3a5688"
buttonAccent: "#5785c1"
sidebarButtonText: "#98aaf4"
readingText: "#c4c8d8"
uiText: "#a2a5b4"
headerText: "#8488aa"
dimText: "#71738c"
counterText: "#606175"
gradientTop: "#0e1125"
gradientBottom: "#191d35"
divider: Qt.rgba(1, 1, 1, 0.12)
overlayBg: Qt.rgba(0.055, 0.055, 0.067, 0.4)
actionDisabled: "#141724"
}
// Single authority for the theme color keys. CustomThemePage and the
@@ -77,55 +80,55 @@ QtObject {
property var _lastApplied: ({})
readonly property var currentTheme: currentThemeName === "dark" ? DarkTheme
: currentThemeName === "light" ? LightTheme
: customTheme
readonly property ThemePalette currentTheme: root.currentThemeName === "dark" ? DarkTheme
: root.currentThemeName === "light" ? LightTheme
: root.customTheme
function setDarkTheme() {
currentThemeName = "dark"
uiState.themeName = "dark"
root.currentThemeName = "dark"
UiState.themeName = "dark"
}
function setLightTheme() {
currentThemeName = "light"
uiState.themeName = "light"
root.currentThemeName = "light"
UiState.themeName = "light"
}
function setCustomTheme() {
currentThemeName = "custom"
uiState.themeName = "custom"
root.currentThemeName = "custom"
UiState.themeName = "custom"
}
function loadCustomColors(map) {
if (map && Object.keys(map).length > 0)
_restoreColors(map)
root._restoreColors(map)
// Snapshot current state (loaded or defaults) so Revert always has a target
_lastApplied = _captureColors()
root._lastApplied = root._captureColors()
}
function applyCustomColors() {
var c = _captureColors()
_lastApplied = c
uiState.customThemeColors = c
const c = root._captureColors()
root._lastApplied = c
UiState.customThemeColors = c
}
function revertCustomColors() {
_restoreColors(_lastApplied)
root._restoreColors(root._lastApplied)
}
function _captureColors() {
var out = {}
for (var i = 0; i < colorKeys.length; ++i)
out[colorKeys[i]] = customTheme[colorKeys[i]].toString()
const out = {}
for (let i = 0; i < root.colorKeys.length; ++i)
out[root.colorKeys[i]] = root.customTheme[root.colorKeys[i]].toString()
return out
}
function _restoreColors(c) {
if (!c) return
for (var i = 0; i < colorKeys.length; ++i) {
var key = colorKeys[i]
for (let i = 0; i < root.colorKeys.length; ++i) {
const key = root.colorKeys[i]
if (c[key])
customTheme[key] = c[key]
root.customTheme[key] = c[key]
}
}
}
+26
View File
@@ -0,0 +1,26 @@
import QtQuick
QtObject {
id: root
property color backgroundDeepest: "#010620"
property color backgroundDefault: "#191d35"
property color surface: "#191d35"
property color headerBg: "#14172c"
property color footerBg: "#1a1e36"
property color scrollbarTrack: "#131628"
property color scrollbarThumb: "#36486a"
property color primaryAccent: "#3a5688"
property color buttonAccent: "#5785c1"
property color sidebarButtonText: "#98aaf4"
property color readingText: "#c4c8d8"
property color uiText: "#a2a5b4"
property color headerText: "#8488aa"
property color dimText: "#71738c"
property color counterText: "#606175"
property color gradientTop: "#0e1125"
property color gradientBottom: "#191d35"
property color divider: Qt.rgba(1, 1, 1, 0.12)
property color overlayBg: Qt.rgba(0.055, 0.055, 0.067, 0.4)
property color actionDisabled: "#141724"
}
+11 -9
View File
@@ -1,11 +1,12 @@
import QtQuick
import QtQuick.Controls
import QtQuick.Controls.Basic
import Asteria
Rectangle {
id: overlay
id: root
color: ThemeManager.currentTheme.overlayBg
visible: book.errorMessage !== ""
visible: Book.errorMessage !== ""
MouseArea {
anchors.fill: parent
@@ -14,13 +15,14 @@ Rectangle {
Rectangle {
anchors.centerIn: parent
width: Math.min(overlay.width * 0.7, 440)
width: Math.min(root.width * 0.7, 440)
height: dialogColumn.implicitHeight + 48
color: ThemeManager.currentTheme.surface
radius: 8
Column {
id: dialogColumn
spacing: 20
anchors {
top: parent.top
left: parent.left
@@ -29,11 +31,10 @@ Rectangle {
leftMargin: 24
rightMargin: 24
}
spacing: 20
Text {
width: parent.width
text: book.errorMessage
text: Book.errorMessage
font.pixelSize: 15
color: ThemeManager.currentTheme.readingText
horizontalAlignment: Text.AlignHCenter
@@ -41,10 +42,11 @@ Rectangle {
}
Button {
id: okButton
anchors.horizontalCenter: parent.horizontalCenter
text: "Ok"
contentItem: Text {
text: parent.text
text: okButton.text
font.pixelSize: 14
color: "#ffffff"
horizontalAlignment: Text.AlignHCenter
@@ -53,9 +55,9 @@ Rectangle {
implicitWidth: 80
implicitHeight: 36
radius: 4
color: parent.hovered ? Qt.lighter(ThemeManager.currentTheme.primaryAccent, 1.15) : ThemeManager.currentTheme.primaryAccent
color: okButton.hovered ? Qt.lighter(ThemeManager.currentTheme.primaryAccent, 1.15) : ThemeManager.currentTheme.primaryAccent
}
onClicked: book.clearError()
onClicked: Book.clearError()
}
}
}
+6 -4
View File
@@ -1,5 +1,5 @@
import QtQuick
import QtQuick.Controls
import QtQuick.Controls.Basic
import Asteria
// Chrome-less button showing a single Material icon, with optional tooltip.
@@ -22,7 +22,9 @@ Button {
verticalAlignment: Text.AlignVCenter
}
ToolTip.visible: tooltip !== "" && hovered
ToolTip.delay: 500
ToolTip.text: tooltip
ToolTip {
visible: root.tooltip !== "" && root.hovered
delay: 500
text: root.tooltip
}
}
+35 -25
View File
@@ -1,8 +1,9 @@
import QtQuick
import QtQuick.Controls
import Asteria
Rectangle {
id: root
height: ThemeManager.footerHeight
color: ThemeManager.currentTheme.footerBg
@@ -15,68 +16,77 @@ Rectangle {
// Measuring spinner
Text {
anchors.left: parent.left
anchors.leftMargin: 16
anchors.verticalCenter: parent.verticalCenter
visible: readingModel.measuring
id: spinnerText
visible: ReadingModel.measuring
text: "\ue863"
font.family: "Material Icons Outlined"
font.pixelSize: 16
color: ThemeManager.currentTheme.dimText
anchors {
left: parent.left
leftMargin: 16
verticalCenter: parent.verticalCenter
}
RotationAnimator on rotation {
from: 0; to: 360
duration: 1000
loops: Animation.Infinite
running: parent.visible
running: spinnerText.visible
}
}
// RTL reading direction toggle.
FlatIconButton {
visible: !readingModel.isTextMode
anchors.left: parent.left
anchors.leftMargin: 16
anchors.verticalCenter: parent.verticalCenter
visible: !ReadingModel.isTextMode
padding: 0
implicitWidth: 24
implicitHeight: 24
iconText: ""
iconColor: readingModel.mangaRTL ? ThemeManager.currentTheme.buttonAccent
iconColor: ReadingModel.mangaRTL ? ThemeManager.currentTheme.buttonAccent
: ThemeManager.currentTheme.dimText
tooltip: "Right-to-left reading (M)"
onClicked: readingModel.setMangaRTL(!readingModel.mangaRTL)
onClicked: ReadingModel.setMangaRTL(!ReadingModel.mangaRTL)
anchors {
left: parent.left
leftMargin: 16
verticalCenter: parent.verticalCenter
}
}
// Page-shift toggle. Shifts page 1 to be displayed alone after the cover.
FlatIconButton {
visible: !readingModel.isTextMode
anchors.left: parent.left
anchors.leftMargin: 44
anchors.verticalCenter: parent.verticalCenter
visible: !ReadingModel.isTextMode
padding: 0
implicitWidth: 24
implicitHeight: 24
iconText: ""
iconColor: readingModel.pageShift ? ThemeManager.currentTheme.buttonAccent
iconColor: ReadingModel.pageShift ? ThemeManager.currentTheme.buttonAccent
: ThemeManager.currentTheme.dimText
tooltip: "Page shift (S)"
onClicked: {
const pairIdx = readerPage.mangaView.currentPair
readingModel.setPageShift(!readingModel.pageShift, pairIdx)
const pairIdx = Math.max(0, ReadingModel.currentPage - 1)
ReadingModel.setPageShift(!ReadingModel.pageShift, pairIdx)
}
anchors {
left: parent.left
leftMargin: 44
verticalCenter: parent.verticalCenter
}
}
Text {
anchors.right: parent.right
anchors.rightMargin: 16
anchors.verticalCenter: parent.verticalCenter
visible: book.hasBook
text: book.hasBook
? readingModel.currentPage + "/" + readingModel.totalPages
visible: Book.hasBook
text: Book.hasBook
? ReadingModel.currentPage + "/" + ReadingModel.totalPages
: ""
font.pixelSize: 11
font.bold: true
color: ThemeManager.currentTheme.counterText
anchors {
right: parent.right
rightMargin: 16
verticalCenter: parent.verticalCenter
}
}
}
+28 -24
View File
@@ -1,64 +1,69 @@
import QtQuick
import QtQuick.Controls
import QtQuick.Controls.Basic
import Asteria
Rectangle {
id: header
height: barsVisible ? ThemeManager.headerHeight : 0
clip: true
color: ThemeManager.currentTheme.surface
id: root
property bool sidebarOpen: false
property string currentPage: "starter"
property bool barsVisible: true
signal menuClicked()
height: root.barsVisible ? ThemeManager.headerHeight : 0
clip: true
color: ThemeManager.currentTheme.surface
Behavior on height {
NumberAnimation { duration: 200; easing.type: Easing.InOutQuad }
}
signal menuClicked()
Button {
id: menuButton
anchors.left: parent.left
anchors.leftMargin: 12
anchors.verticalCenter: parent.verticalCenter
visible: !header.sidebarOpen
visible: !root.sidebarOpen
flat: true
onClicked: root.menuClicked()
anchors {
left: parent.left
leftMargin: 12
verticalCenter: parent.verticalCenter
}
contentItem: Text {
text: "\u2630"
font.pixelSize: 24
color: ThemeManager.currentTheme.buttonAccent
}
background: Item {}
onClicked: header.menuClicked()
}
Text {
anchors.centerIn: parent
text: {
switch (header.currentPage) {
switch (root.currentPage) {
case "settings": return "Settings"
case "reader": return book.title || ""
case "reader": return Book.title || ""
default: return ""
}
}
font.pixelSize: 16
color: ThemeManager.currentTheme.headerText
anchors.centerIn: parent
}
Row {
anchors.right: parent.right
anchors.rightMargin: parent.width * 0.02
anchors.verticalCenter: parent.verticalCenter
spacing: 8
anchors {
right: parent.right
rightMargin: parent.width * 0.02
verticalCenter: parent.verticalCenter
}
Text {
id: clockText
anchors.verticalCenter: parent.verticalCenter
font.pixelSize: 16
font.bold: true
color: ThemeManager.currentTheme.dimText
anchors.verticalCenter: parent.verticalCenter
Timer {
running: true
@@ -66,14 +71,13 @@ Rectangle {
interval: 1000
triggeredOnStart: true
onTriggered: {
var d = new Date()
var h = d.getHours().toString().padStart(2, '0')
var m = d.getMinutes().toString().padStart(2, '0')
var s = d.getSeconds().toString().padStart(2, '0')
const d = new Date()
const h = d.getHours().toString().padStart(2, '0')
const m = d.getMinutes().toString().padStart(2, '0')
const s = d.getSeconds().toString().padStart(2, '0')
clockText.text = h + ":" + m + ":" + s
}
}
}
}
}
+8 -4
View File
@@ -1,5 +1,5 @@
import QtQuick
import QtQuick.Controls
import QtQuick.Controls.Basic
import Asteria
// Settings slider with a label row and a debounced committed() signal so
@@ -34,8 +34,10 @@ Column {
text: root.valueText
font.pixelSize: 12
color: ThemeManager.currentTheme.dimText
anchors.right: parent.right
anchors.verticalCenter: parent.verticalCenter
anchors {
right: parent.right
verticalCenter: parent.verticalCenter
}
}
}
@@ -67,7 +69,9 @@ Column {
handle: Rectangle {
x: slider.leftPadding + slider.visualPosition * (slider.availableWidth - width)
y: slider.topPadding + slider.availableHeight / 2 - height / 2
width: 14; height: 14; radius: 7
width: 14
height: 14
radius: 7
color: slider.pressed ? Qt.lighter(ThemeManager.currentTheme.buttonAccent, 1.15)
: ThemeManager.currentTheme.buttonAccent
}
+1 -1
View File
@@ -1,5 +1,5 @@
import QtQuick
import QtQuick.Controls
import QtQuick.Controls.Basic
import Asteria
Row {
+54 -44
View File
@@ -1,67 +1,64 @@
import QtQuick
import QtQuick.Controls
import QtQuick.Controls.Basic
import Asteria
Rectangle {
id: root
focus: true
readonly property bool landscape: root.width > root.height
property bool contentReady: false
property int currentPair: 0
readonly property bool landscape: width > height
focus: true
gradient: Gradient {
GradientStop { position: 0.0; color: ThemeManager.currentTheme.gradientTop }
GradientStop { position: 1.0; color: ThemeManager.currentTheme.gradientBottom }
}
// Keyboard navigation — same names as ScrollPageView so PageView can forward blindly.
function handlePageDown() { nextPair() }
function handlePageUp() { previousPair() }
function handleScrollDown() { nextPair() }
function handleScrollUp() { previousPair() }
function handlePageDown() { root.nextPair() }
function handlePageUp() { root.previousPair() }
function handleScrollDown() { root.nextPair() }
function handleScrollUp() { root.previousPair() }
function nextPair() {
if (currentPair < readingModel.totalPagePairs - 1)
showPair(currentPair + 1)
if (root.currentPair < ReadingModel.totalPagePairs - 1)
root.showPair(root.currentPair + 1)
}
function previousPair() {
if (currentPair > 0)
showPair(currentPair - 1)
if (root.currentPair > 0)
root.showPair(root.currentPair - 1)
}
// Single entry point for displaying a pair: sets the index, refreshes the
// displayed pair contents, and syncs scroll/position state.
function showPair(pairIndex) {
currentPair = pairIndex
pageArea.pair = contentReady ? readingModel.pagePair(pairIndex) : []
root.currentPair = pairIndex
pageArea.pair = root.contentReady ? ReadingModel.pagePair(pairIndex) : []
const pair = pageArea.pair
if (pair.length === 0) return
const firstChunk = pair[0]
// Keep scroll model in sync so Footer page counter and chapter tracking work.
readingModel.setScrollInfo(firstChunk, pairIndex / Math.max(1, readingModel.totalPagePairs - 1))
ReadingModel.setScrollInfo(firstChunk, pairIndex / Math.max(1, ReadingModel.totalPagePairs - 1))
}
// Notify model when orientation changes (triggers pair rebuild).
onLandscapeChanged: landscapeDebounce.restart()
// Initialise landscape state once visible.
Component.onCompleted: ReadingModel.setMangaLandscape(root.landscape)
Timer {
id: landscapeDebounce
interval: 150
repeat: false
onTriggered: readingModel.setMangaLandscape(landscape)
onTriggered: ReadingModel.setMangaLandscape(root.landscape)
}
// Initialise landscape state once visible.
Component.onCompleted: readingModel.setMangaLandscape(landscape)
// Page display area.
Item {
id: pageArea
anchors.fill: parent
anchors.margins: readingPreferences.verticalMargin
// Display pair, updated by showPair(). For RTL mode pages are reversed
// (higher index on the left) via leftChunk/rightChunk below.
@@ -70,47 +67,54 @@ Rectangle {
property int leftChunk: {
if (pair.length === 0) return -1
if (pair.length === 1) return pair[0]
return readingModel.mangaRTL ? pair[1] : pair[0]
return ReadingModel.mangaRTL ? pair[1] : pair[0]
}
property int rightChunk: {
if (pair.length < 2) return -1
return readingModel.mangaRTL ? pair[0] : pair[1]
return ReadingModel.mangaRTL ? pair[0] : pair[1]
}
property bool hasTwoPages: pair.length === 2
anchors {
fill: parent
margins: ReadingPreferences.verticalMargin
}
Behavior on opacity { NumberAnimation { duration: 120 } }
// Left (or solo) page.
Image {
id: leftImg
visible: pageArea.leftChunk >= 0
x: 0
y: 0
width: pageArea.hasTwoPages ? parent.width / 2 : parent.width
height: parent.height
visible: pageArea.leftChunk >= 0
fillMode: Image.PreserveAspectFit
// When paired, pin content to the spine (right edge) so there's no gap between pages.
horizontalAlignment: pageArea.hasTwoPages ? Image.AlignRight : Image.AlignHCenter
asynchronous: true
cache: true
source: pageArea.leftChunk >= 0 ? readingModel.imageUrlForChunk(pageArea.leftChunk) : ""
sourceSize: Qt.size(width, height)
source: pageArea.leftChunk >= 0 ? ReadingModel.imageUrlForChunk(pageArea.leftChunk) : ""
}
// Right page (landscape two-page spread only).
Image {
id: rightImg
visible: pageArea.rightChunk >= 0
x: parent.width / 2
y: 0
width: parent.width / 2
height: parent.height
visible: pageArea.rightChunk >= 0
fillMode: Image.PreserveAspectFit
// Pin content to the spine (left edge) so it meets the left page with no gap.
horizontalAlignment: Image.AlignLeft
asynchronous: true
cache: true
source: pageArea.rightChunk >= 0 ? readingModel.imageUrlForChunk(pageArea.rightChunk) : ""
sourceSize: Qt.size(width, height)
source: pageArea.rightChunk >= 0 ? ReadingModel.imageUrlForChunk(pageArea.rightChunk) : ""
}
// Loading indicator while images load.
@@ -125,13 +129,14 @@ Rectangle {
// Swipe / tap input.
MouseArea {
id: inputArea
anchors.fill: parent
z: 10
property real pressX: 0
property real startPressX: 0
property bool dragging: false
anchors.fill: parent
z: 10
onPressed: function(mouse) {
pressX = mouse.x
startPressX = mouse.x
@@ -147,10 +152,10 @@ Rectangle {
const dx = mouse.x - startPressX
if (Math.abs(dx) > root.width * 0.12) {
// Swipe gesture.
if (readingModel.mangaRTL) {
if (dx < 0) nextPair(); else previousPair()
if (ReadingModel.mangaRTL) {
if (dx < 0) root.nextPair(); else root.previousPair()
} else {
if (dx > 0) nextPair(); else previousPair()
if (dx > 0) root.nextPair(); else root.previousPair()
}
return
}
@@ -162,51 +167,56 @@ Rectangle {
onDoubleClicked: {
clickDebounce.stop()
window.visibility = (window.visibility === Window.FullScreen) ? Window.Windowed : Window.FullScreen
if (root.Window.window) {
root.Window.window.visibility = (root.Window.window.visibility === Window.FullScreen)
? Window.Windowed : Window.FullScreen
}
}
}
Timer {
id: clickDebounce
interval: 150
property real clickX: 0
interval: 150
onTriggered: {
const third = root.width / 3
if (clickX < third) {
// Left third tap.
if (readingModel.mangaRTL) nextPair(); else previousPair()
if (ReadingModel.mangaRTL) root.nextPair(); else root.previousPair()
} else if (clickX > root.width - third) {
// Right third tap.
if (readingModel.mangaRTL) previousPair(); else nextPair()
if (ReadingModel.mangaRTL) root.previousPair(); else root.nextPair()
} else {
// Middle — toggle chrome.
window.toggleChrome()
UiState.barsVisible = !UiState.barsVisible
}
}
}
// Restore position when a new book is loaded.
Connections {
target: readingModel
target: ReadingModel
function onRestoreReady(chunkIndex) {
contentReady = true
showPair(readingModel.pairIndexForChunk(chunkIndex))
root.contentReady = true
root.showPair(ReadingModel.pairIndexForChunk(chunkIndex))
}
function onTotalPagePairsChanged() {
// Re-clamp after pair rebuild (resize / orientation flip).
showPair(Math.min(currentPair, Math.max(0, readingModel.totalPagePairs - 1)))
root.showPair(Math.min(root.currentPair, Math.max(0, ReadingModel.totalPagePairs - 1)))
}
function onPagePairsRebuilt(newPairIndex) {
// setPageShift rebuilt the pairs; refresh even when the index is
// unchanged since the pair contents may differ.
showPair(newPairIndex)
root.showPair(newPairIndex)
}
}
Connections {
target: book
target: Book
function onLoadingChanged() {
if (book.loading) contentReady = false
if (Book.loading) root.contentReady = false
}
}
}
+95 -84
View File
@@ -1,10 +1,10 @@
pragma ComponentBehavior: Bound
import QtQuick
import QtQuick.Controls
import QtQuick.Controls.Basic
import Asteria
Rectangle {
id: root
focus: true
readonly property int scrollbarWidth: 16
@@ -14,48 +14,49 @@ Rectangle {
property real initialOffset: 0
property real lastScrollSyncTime: 0
function syncScrollPosition() {
var probeX = chunkListView.width / 2;
var probeY = chunkListView.contentY + 10;
var topIdx = chunkListView.indexAt(probeX, probeY);
if (topIdx < 0)
return;
var topItem = chunkListView.itemAtIndex(topIdx);
var intraOffset = topItem ? (chunkListView.contentY - topItem.y) : 0;
var maxScroll = Math.max(1, chunkListView.contentHeight - chunkListView.height);
var prop = Math.min(1.0, Math.max(0.0, chunkListView.contentY / maxScroll));
readingModel.setScrollPosition(topIdx, intraOffset, prop);
}
focus: true
gradient: Gradient {
GradientStop { position: 0.0; color: ThemeManager.currentTheme.gradientTop }
GradientStop { position: 1.0; color: ThemeManager.currentTheme.gradientBottom }
}
function syncScrollPosition() {
const probeX = chunkListView.width / 2;
const probeY = chunkListView.contentY + 10;
const topIdx = chunkListView.indexAt(probeX, probeY);
if (topIdx < 0)
return;
const topItem = chunkListView.itemAtIndex(topIdx);
const intraOffset = topItem ? (chunkListView.contentY - topItem.y) : 0;
const maxScroll = Math.max(1, chunkListView.contentHeight - chunkListView.height);
const prop = Math.min(1.0, Math.max(0.0, chunkListView.contentY / maxScroll));
ReadingModel.setScrollPosition(topIdx, intraOffset, prop);
}
// Keyboard navigation
function handlePageUp() {
var scrollAmount = chunkListView.height * 0.9;
var targetY = Math.max(0, chunkListView.contentY - scrollAmount);
const scrollAmount = chunkListView.height * 0.9;
const targetY = Math.max(0, chunkListView.contentY - scrollAmount);
animateScrollTo(targetY);
}
function handlePageDown() {
var scrollAmount = chunkListView.height * 0.9;
var maxY = Math.max(0, chunkListView.contentHeight - chunkListView.height);
var targetY = Math.min(maxY, chunkListView.contentY + scrollAmount);
const scrollAmount = chunkListView.height * 0.9;
const maxY = Math.max(0, chunkListView.contentHeight - chunkListView.height);
const targetY = Math.min(maxY, chunkListView.contentY + scrollAmount);
animateScrollTo(targetY);
}
function handleScrollUp() {
var scrollAmount = readingPreferences.fontSize * readingPreferences.lineSpacing * 3;
var targetY = Math.max(0, chunkListView.contentY - scrollAmount);
const scrollAmount = ReadingPreferences.fontSize * ReadingPreferences.lineSpacing * 3;
const targetY = Math.max(0, chunkListView.contentY - scrollAmount);
animateScrollTo(targetY);
}
function handleScrollDown() {
var scrollAmount = readingPreferences.fontSize * readingPreferences.lineSpacing * 3;
var maxY = Math.max(0, chunkListView.contentHeight - chunkListView.height);
var targetY = Math.min(maxY, chunkListView.contentY + scrollAmount);
const scrollAmount = ReadingPreferences.fontSize * ReadingPreferences.lineSpacing * 3;
const maxY = Math.max(0, chunkListView.contentHeight - chunkListView.height);
const targetY = Math.min(maxY, chunkListView.contentY + scrollAmount);
animateScrollTo(targetY);
}
@@ -72,35 +73,35 @@ Rectangle {
duration: 180
easing.type: Easing.OutQuad
onFinished: {
lastScrollSyncTime = Date.now();
syncScrollPosition();
root.lastScrollSyncTime = Date.now();
root.syncScrollPosition();
}
}
function updateContentMetrics() {
if (chunkListView.width > 0) {
var availW = chunkListView.width - scrollbarWidth - 2 * readingPreferences.horizontalMargin;
var topIdx = -1;
var intraRatio = 0.0;
if (contentReady && restoreReady) {
var probeX = chunkListView.width / 2;
var probeY = chunkListView.contentY + 10;
const availW = chunkListView.width - root.scrollbarWidth - 2 * ReadingPreferences.horizontalMargin;
let topIdx = -1;
let intraRatio = 0.0;
if (root.contentReady && root.restoreReady) {
const probeX = chunkListView.width / 2;
const probeY = chunkListView.contentY + 10;
topIdx = chunkListView.indexAt(probeX, probeY);
if (topIdx >= 0) {
var topItem = chunkListView.itemAtIndex(topIdx);
const topItem = chunkListView.itemAtIndex(topIdx);
if (topItem && topItem.height > 0) {
intraRatio = Math.max(0.0, Math.min(1.0, (chunkListView.contentY - topItem.y) / topItem.height));
}
}
}
readingModel.updateLayoutMetrics(Math.max(100, Math.floor(availW)),
readingPreferences.fontSize,
readingPreferences.lineSpacing,
ReadingModel.updateLayoutMetrics(Math.max(100, Math.floor(availW)),
ReadingPreferences.fontSize,
ReadingPreferences.lineSpacing,
topIdx);
if (contentReady && restoreReady && topIdx >= 0) {
var newTopItem = chunkListView.itemAtIndex(topIdx);
if (root.contentReady && root.restoreReady && topIdx >= 0) {
const newTopItem = chunkListView.itemAtIndex(topIdx);
if (newTopItem && newTopItem.height > 0) {
chunkListView.contentY = newTopItem.y + intraRatio * newTopItem.height;
}
@@ -112,68 +113,75 @@ Rectangle {
onWidthChanged: updateContentMetrics()
Connections {
target: readingPreferences
function onFontSizeChanged() { updateContentMetrics() }
function onLineSpacingChanged() { updateContentMetrics() }
function onHorizontalMarginChanged() { updateContentMetrics() }
target: ReadingPreferences
function onFontSizeChanged() { root.updateContentMetrics() }
function onLineSpacingChanged() { root.updateContentMetrics() }
function onHorizontalMarginChanged() { root.updateContentMetrics() }
}
ListView {
id: chunkListView
anchors.fill: parent
anchors.topMargin: readingPreferences.verticalMargin
anchors.bottomMargin: readingPreferences.verticalMargin
model: contentReady ? readingModel : null
model: root.contentReady ? ReadingModel : null
cacheBuffer: 0
reuseItems: true
clip: true
maximumFlickVelocity: 99999
anchors {
fill: parent
topMargin: ReadingPreferences.verticalMargin
bottomMargin: ReadingPreferences.verticalMargin
}
delegate: KnuthPlassItem {
id: chunkDelegate
required property int index
required property int pixelHeight
required layout
width: chunkListView.width
height: (model && model.pixelHeight > 0) ? model.pixelHeight : 30
layout: model ? model.layout : null
height: chunkDelegate.pixelHeight > 0 ? chunkDelegate.pixelHeight : 30
textColor: ThemeManager.currentTheme.readingText
linkColor: ThemeManager.currentTheme.buttonAccent
dimColor: ThemeManager.currentTheme.dimText
surfaceColor: ThemeManager.currentTheme.surface
useBookColours: readingModel.useBookColours
horizontalMargin: readingPreferences.horizontalMargin
useBookColours: ReadingModel.useBookColours
horizontalMargin: ReadingPreferences.horizontalMargin
Loader {
active: isDebugBuild
visible: isDebugBuild
active: AppInfo.isDebugBuild
visible: AppInfo.isDebugBuild
sourceComponent: Text {
text: index !== undefined ? index.toString() : ""
font.pixelSize: 10
font.family: "monospace"
font.bold: true
color: ThemeManager.currentTheme.buttonAccent
opacity: 0.85
x: 4
y: 2
z: 10
text: chunkDelegate.index !== undefined ? chunkDelegate.index.toString() : ""
font {
bold: true
family: "monospace"
pixelSize: 10
}
color: ThemeManager.currentTheme.buttonAccent
opacity: 0.85
}
}
}
onContentYChanged: {
if (contentReady && restoreReady) {
var now = Date.now();
if (now - lastScrollSyncTime >= 250) {
lastScrollSyncTime = now;
syncScrollPosition();
if (root.contentReady && root.restoreReady) {
const now = Date.now();
if (now - root.lastScrollSyncTime >= 250) {
root.lastScrollSyncTime = now;
root.syncScrollPosition();
}
}
}
onMovementEnded: {
lastScrollSyncTime = Date.now();
syncScrollPosition();
root.lastScrollSyncTime = Date.now();
root.syncScrollPosition();
}
onFlickEnded: {
lastScrollSyncTime = Date.now();
syncScrollPosition();
root.lastScrollSyncTime = Date.now();
root.syncScrollPosition();
}
ScrollBar.vertical: ScrollBar {
@@ -181,40 +189,43 @@ Rectangle {
policy: ScrollBar.AsNeeded
padding: 0
contentItem: Rectangle {
implicitWidth: scrollbarWidth
implicitWidth: root.scrollbarWidth
radius: 3
color: ThemeManager.currentTheme.scrollbarThumb
}
background: Rectangle {
implicitWidth: scrollbarWidth
implicitWidth: root.scrollbarWidth
color: ThemeManager.currentTheme.scrollbarTrack
}
}
MouseArea {
anchors.fill: parent
anchors.rightMargin: scrollbarWidth
anchors.rightMargin: root.scrollbarWidth
z: 1
onClicked: clickDebounce.restart()
onDoubleClicked: {
clickDebounce.stop()
window.visibility = (window.visibility === Window.FullScreen) ? Window.Windowed : Window.FullScreen
if (root.Window.window) {
root.Window.window.visibility = (root.Window.window.visibility === Window.FullScreen)
? Window.Windowed : Window.FullScreen
}
}
}
Timer {
id: clickDebounce
interval: 150
onTriggered: window.toggleChrome()
onTriggered: UiState.barsVisible = !UiState.barsVisible
}
}
Connections {
target: readingModel
target: ReadingModel
function onRestoreReady(chunkIndex, intraOffset) {
contentReady = true;
initialIndex = chunkIndex;
initialOffset = (intraOffset !== undefined) ? intraOffset : 0;
root.contentReady = true;
root.initialIndex = chunkIndex;
root.initialOffset = (intraOffset !== undefined) ? intraOffset : 0;
restoreTimer.start();
}
}
@@ -224,18 +235,18 @@ Rectangle {
interval: 10
repeat: false
onTriggered: {
chunkListView.positionViewAtIndex(initialIndex, ListView.Beginning);
chunkListView.contentY += initialOffset;
restoreReady = true;
chunkListView.positionViewAtIndex(root.initialIndex, ListView.Beginning);
chunkListView.contentY += root.initialOffset;
root.restoreReady = true;
}
}
Connections {
target: book
target: Book
function onLoadingChanged() {
if (book.loading) {
contentReady = false;
restoreReady = false;
if (Book.loading) {
root.contentReady = false;
root.restoreReady = false;
}
}
}
+55 -40
View File
@@ -1,17 +1,18 @@
import QtQuick
import QtQuick.Controls
import QtQuick.Controls.Basic
import Asteria
Item {
id: popup
id: root
signal closeRequested()
width: 300
height: shadow.height
x: parent ? parent.width - width - 24 : 0
y: 24
z: 100
signal closeRequested()
// Shadow
Rectangle {
id: shadow
@@ -33,52 +34,58 @@ Item {
clip: true
// Drag handle / title bar
Rectangle {
Item {
id: headerBar
width: parent.width
height: 44
color: "transparent"
Text {
anchors.verticalCenter: parent.verticalCenter
anchors.left: parent.left
anchors.leftMargin: 16
text: "Settings"
font.pixelSize: 13
font.weight: Font.Medium
color: ThemeManager.currentTheme.dimText
anchors {
left: parent.left
leftMargin: 16
verticalCenter: parent.verticalCenter
}
}
FlatIconButton {
anchors.verticalCenter: parent.verticalCenter
anchors.right: parent.right
anchors.rightMargin: 8
iconText: "\ue5cd"
iconSize: 18
onClicked: popup.closeRequested()
onClicked: root.closeRequested()
anchors {
right: parent.right
rightMargin: 8
verticalCenter: parent.verticalCenter
}
}
MouseArea {
anchors.fill: parent
anchors.rightMargin: 40
property real pressX
property real pressY
id: dragArea
property real pressX: 0
property real pressY: 0
cursorShape: Qt.SizeAllCursor
anchors {
fill: parent
rightMargin: 40
}
onPressed: function(mouse) {
pressX = mouse.x
pressY = mouse.y
}
onPositionChanged: function(mouse) {
if (!pressed) return
var dx = mouse.x - pressX
var dy = mouse.y - pressY
var par = popup.parent
if (!dragArea.pressed) return
const dx = mouse.x - pressX
const dy = mouse.y - pressY
const par = root.parent
if (par) {
popup.x = Math.max(0, Math.min(par.width - popup.width, popup.x + dx))
popup.y = Math.max(0, Math.min(par.height - popup.height, popup.y + dy))
root.x = Math.max(0, Math.min(par.width - root.width, root.x + dx))
root.y = Math.max(0, Math.min(par.height - root.height, root.y + dy))
} else {
popup.x += dx
popup.y += dy
root.x += dx
root.y += dy
}
}
}
@@ -109,46 +116,54 @@ Item {
LabeledSlider {
width: parent.width
label: "Horizontal margin"
from: 0; to: 64; stepSize: 1
value: readingPreferences.horizontalMargin
from: 0
to: 64
stepSize: 1
value: ReadingPreferences.horizontalMargin
valueText: value + " px"
onCommitted: function(v) { readingPreferences.horizontalMargin = v }
onCommitted: function(v) { ReadingPreferences.horizontalMargin = v }
}
LabeledSlider {
width: parent.width
label: "Vertical margin"
from: 0; to: 64; stepSize: 1
value: readingPreferences.verticalMargin
from: 0
to: 64
stepSize: 1
value: ReadingPreferences.verticalMargin
valueText: value + " px"
onCommitted: function(v) { readingPreferences.verticalMargin = v }
onCommitted: function(v) { ReadingPreferences.verticalMargin = v }
}
LabeledSlider {
width: parent.width
label: "Font size"
from: 10; to: 32; stepSize: 1
value: readingPreferences.fontSize
from: 10
to: 32
stepSize: 1
value: ReadingPreferences.fontSize
valueText: value + " px"
onCommitted: function(v) { readingPreferences.fontSize = v }
onCommitted: function(v) { ReadingPreferences.fontSize = v }
}
LabeledSlider {
width: parent.width
label: "Line spacing"
from: 0.5; to: 2.0; stepSize: 0.1
value: readingPreferences.lineSpacing
from: 0.5
to: 2.0
stepSize: 0.1
value: ReadingPreferences.lineSpacing
valueText: value.toFixed(1) + "\u00d7"
onCommitted: function(v) { readingPreferences.lineSpacing = v }
onCommitted: function(v) { ReadingPreferences.lineSpacing = v }
}
LabeledSwitch {
width: parent.width
label: "Use book colours"
description: "Apply publisher text and background colours for this book"
visible: readingModel.isTextMode
checked: readingModel.useBookColours
onToggled: function(c) { readingModel.setUseBookColours(c) }
visible: ReadingModel.isTextMode
checked: ReadingModel.useBookColours
onToggled: function(c) { ReadingModel.setUseBookColours(c) }
}
}
}
+23 -19
View File
@@ -1,12 +1,8 @@
import QtQuick
import QtQuick.Controls
import Asteria
Rectangle {
id: sidebar
width: sidebarOpen ? ThemeManager.sidebarWidth : 0
clip: true
color: ThemeManager.currentTheme.surface
id: root
property bool sidebarOpen: false
@@ -15,33 +11,41 @@ Rectangle {
signal openFile()
signal closeBook()
width: root.sidebarOpen ? ThemeManager.sidebarWidth : 0
clip: true
color: ThemeManager.currentTheme.surface
Behavior on width {
NumberAnimation {
duration: sidebarOpen ? ThemeManager.animDurationOpen : ThemeManager.animDurationClose
duration: root.sidebarOpen ? ThemeManager.animDurationOpen : ThemeManager.animDurationClose
easing.type: Easing.OutQuad
}
}
Text {
anchors.left: parent.left
anchors.leftMargin: 16
y: ThemeManager.headerHeight / 2 - height / 2
text: "Asteria"
font.pixelSize: 18
font.bold: true
color: ThemeManager.currentTheme.uiText
anchors {
left: parent.left
leftMargin: 16
}
}
// Close button aligned with main header row
FlatIconButton {
anchors.right: parent.right
anchors.rightMargin: 12
y: ThemeManager.headerHeight / 2 - height / 2
z: 1
iconText: "\ue5cb"
iconSize: 24
iconColor: ThemeManager.currentTheme.sidebarButtonText
onClicked: sidebar.closeDrawer()
onClicked: root.closeDrawer()
anchors {
right: parent.right
rightMargin: 12
}
}
Column {
@@ -50,29 +54,29 @@ Rectangle {
width: ThemeManager.sidebarWidth
SideBarButton {
visible: book.hasBook
visible: Book.hasBook
iconText: "\ue86d"
title: "Book"
onClicked: sidebar.navigateTo("reader")
onClicked: root.navigateTo("reader")
}
SideBarButton {
iconText: "\ue02f"
title: "History"
onClicked: sidebar.navigateTo("history")
onClicked: root.navigateTo("history")
}
SideBarButton {
iconText: "\ue30a"
title: "Files"
onClicked: sidebar.openFile()
onClicked: root.openFile()
}
SideBarButton {
visible: book.hasBook
visible: Book.hasBook
iconText: "\ue5cd"
title: "Close Book"
onClicked: sidebar.closeBook()
onClicked: root.closeBook()
}
// Divider
@@ -101,7 +105,7 @@ Rectangle {
onClicked: ThemeManager.setCustomTheme()
onRightIconClicked: {
ThemeManager.setCustomTheme()
sidebar.navigateTo("customTheme")
root.navigateTo("customTheme")
}
}
@@ -115,7 +119,7 @@ Rectangle {
SideBarButton {
iconText: "\ue8b8"
title: "Settings"
onClicked: sidebar.navigateTo("settings")
onClicked: root.navigateTo("settings")
}
}
}
+24 -19
View File
@@ -1,12 +1,8 @@
import QtQuick
import QtQuick.Controls
import Asteria
Rectangle {
id: root
height: 48
width: parent ? parent.width : 240
color: mouseArea.containsMouse ? Qt.lighter(ThemeManager.currentTheme.headerBg, 1.3) : "transparent"
property string iconText: ""
property string title: ""
@@ -15,47 +11,54 @@ Rectangle {
signal clicked()
signal rightIconClicked()
height: 48
width: parent ? parent.width : 240
color: mouseArea.containsMouse ? Qt.lighter(ThemeManager.currentTheme.headerBg, 1.3) : Qt.rgba(0, 0, 0, 0)
Row {
anchors.left: parent.left
anchors.leftMargin: 16
anchors.top: parent.top
anchors.bottom: parent.bottom
spacing: 16
anchors {
left: parent.left
leftMargin: 16
top: parent.top
bottom: parent.bottom
}
Text {
anchors.verticalCenter: parent.verticalCenter
text: root.iconText
font.family: "Material Icons Outlined"
font.pixelSize: 24
color: ThemeManager.currentTheme.sidebarButtonText
anchors.verticalCenter: parent.verticalCenter
}
Text {
anchors.verticalCenter: parent.verticalCenter
text: root.title
font.pixelSize: 14
color: ThemeManager.currentTheme.sidebarButtonText
anchors.verticalCenter: parent.verticalCenter
}
}
// Optional right icon zone — zero-width when unused
Rectangle {
Item {
id: rightIconZone
visible: root.rightIconText !== ""
anchors.right: parent.right
anchors.top: parent.top
anchors.bottom: parent.bottom
width: visible ? 44 : 0
color: "transparent"
anchors {
right: parent.right
top: parent.top
bottom: parent.bottom
}
Text {
anchors.centerIn: parent
text: root.rightIconText
font.family: "Material Icons Outlined"
font.pixelSize: 18
color: rightIconArea.containsMouse
? Qt.lighter(ThemeManager.currentTheme.sidebarButtonText, 1.3)
: ThemeManager.currentTheme.sidebarButtonText
anchors.centerIn: parent
}
MouseArea {
@@ -70,12 +73,14 @@ Rectangle {
// Main click area stops before the right icon zone
MouseArea {
id: mouseArea
anchors.left: parent.left
anchors.top: parent.top
anchors.bottom: parent.bottom
width: parent.width - rightIconZone.width
hoverEnabled: true
cursorShape: Qt.PointingHandCursor
onClicked: root.clicked()
anchors {
left: parent.left
top: parent.top
bottom: parent.bottom
}
}
}
+51 -34
View File
@@ -1,9 +1,11 @@
import QtQuick
import QtQuick.Controls
import QtQuick.Controls.Basic
import QtQuick.Dialogs
import Asteria
Rectangle {
id: root
gradient: Gradient {
GradientStop { position: 0.0; color: ThemeManager.currentTheme.gradientTop }
GradientStop { position: 1.0; color: ThemeManager.currentTheme.gradientBottom }
@@ -19,13 +21,15 @@ Rectangle {
Column {
id: topPanel
anchors.top: parent.top
anchors.topMargin: 8
anchors.left: parent.left
anchors.leftMargin: 8
anchors.right: parent.right
anchors.rightMargin: 8
spacing: 12
anchors {
top: parent.top
topMargin: 8
left: parent.left
leftMargin: 8
right: parent.right
rightMargin: 8
}
Text {
text: "Custom Theme"
@@ -46,11 +50,13 @@ Rectangle {
Column {
id: previewColumn
anchors.left: parent.left
anchors.right: parent.right
anchors.top: parent.top
anchors.margins: 16
spacing: 8
anchors {
left: parent.left
right: parent.right
top: parent.top
margins: 16
}
Text {
width: parent.width
@@ -120,11 +126,13 @@ Rectangle {
Rectangle {
id: bottomBar
anchors.left: parent.left
anchors.right: parent.right
anchors.bottom: parent.bottom
height: 56
color: ThemeManager.currentTheme.surface
anchors {
left: parent.left
right: parent.right
bottom: parent.bottom
}
Rectangle {
width: parent.width
@@ -133,8 +141,8 @@ Rectangle {
}
Row {
anchors.centerIn: parent
spacing: 12
anchors.centerIn: parent
Rectangle {
width: revertText.implicitWidth + 32
@@ -194,11 +202,13 @@ Rectangle {
// Full width so the scrollbar sits at the screen edge, outside the 8px margin
ScrollView {
anchors.top: topPanel.bottom
anchors.topMargin: 4
anchors.left: parent.left
anchors.right: parent.right
anchors.bottom: bottomBar.top
anchors {
top: topPanel.bottom
topMargin: 4
left: parent.left
right: parent.right
bottom: bottomBar.top
}
contentWidth: availableWidth
Column {
@@ -213,14 +223,15 @@ Rectangle {
model: ThemeManager.colorSections
delegate: Column {
id: sectionCol
required property var modelData
width: parent.width
spacing: 0
SectionLabel { text: modelData.title }
SectionLabel { text: sectionCol.modelData.title }
Repeater {
model: modelData.keys
model: sectionCol.modelData.keys
delegate: ColorRow {
required property string modelData
@@ -248,37 +259,43 @@ Rectangle {
component ColorRow: Item {
id: colorRowRoot
height: 40
property string label: ""
property color value: "black"
property color value: "#000000"
property var apply: null // (color) => void
property color _savedValue: "black"
property color _savedValue: "#000000"
height: 40
ColorDialog {
id: dlg
onSelectedColorChanged: { if (colorRowRoot.apply) colorRowRoot.apply(selectedColor) }
onSelectedColorChanged: { if (colorRowRoot.apply) colorRowRoot.apply(dlg.selectedColor) }
onRejected: { if (colorRowRoot.apply) colorRowRoot.apply(colorRowRoot._savedValue) }
}
function openPicker() {
_savedValue = value
dlg.selectedColor = value
colorRowRoot._savedValue = colorRowRoot.value
dlg.selectedColor = colorRowRoot.value
dlg.open()
}
Text {
anchors.left: colorRowRoot.left
anchors.leftMargin: 4
anchors.verticalCenter: colorRowRoot.verticalCenter
text: colorRowRoot.label
font.pixelSize: 14
color: ThemeManager.currentTheme.uiText
anchors {
left: colorRowRoot.left
leftMargin: 4
verticalCenter: colorRowRoot.verticalCenter
}
}
Row {
anchors.right: colorRowRoot.right
anchors.verticalCenter: colorRowRoot.verticalCenter
spacing: 8
anchors {
right: colorRowRoot.right
verticalCenter: colorRowRoot.verticalCenter
}
Rectangle {
width: 32
@@ -296,12 +313,12 @@ Rectangle {
}
Text {
width: 90
text: colorRowRoot.value.toString().toUpperCase()
font.pixelSize: 11
font.family: "Courier New"
color: ThemeManager.currentTheme.dimText
anchors.verticalCenter: parent.verticalCenter
width: 90
}
}
}
+38 -23
View File
@@ -1,12 +1,13 @@
import QtQuick
import QtQuick.Controls
import Asteria
Rectangle {
id: root
color: ThemeManager.currentTheme.backgroundDefault
Text {
visible: historyModel.count === 0
visible: HistoryModel.count === 0
anchors.centerIn: parent
text: "No books read yet.\nOpen a book to start your history."
horizontalAlignment: Text.AlignHCenter
@@ -16,38 +17,51 @@ Rectangle {
}
ListView {
visible: historyModel.count > 0
anchors.fill: parent
anchors.margins: 16
visible: HistoryModel.count > 0
spacing: 8
clip: true
model: historyModel
model: HistoryModel
anchors {
fill: parent
margins: 16
}
delegate: Rectangle {
id: bookRow
required property string filePath
required property string coverImageUrl
required property string title
required property string format
required property string author
required property real progress
width: ListView.view.width
height: bookInfoCol.implicitHeight + 24
color: ThemeManager.currentTheme.surface
radius: 4
Row {
anchors.fill: parent
anchors.leftMargin: 14
anchors.rightMargin: 14
anchors.topMargin: 12
anchors.bottomMargin: 12
spacing: 8
anchors {
fill: parent
leftMargin: 14
rightMargin: 14
topMargin: 12
bottomMargin: 12
}
Item {
id: coverSlot
visible: filePath !== ""
visible: bookRow.filePath !== ""
width: 60
height: 80
anchors.verticalCenter: parent.verticalCenter
Image {
anchors.fill: parent
source: filePath !== "" ? ("image://fileicon/" + filePath) : ""
source: bookRow.filePath !== "" ? ("image://fileicon/" + bookRow.filePath) : ""
sourceSize: Qt.size(width, height)
fillMode: Image.PreserveAspectFit
visible: coverImage.status !== Image.Ready
}
@@ -55,9 +69,10 @@ Rectangle {
Image {
id: coverImage
anchors.fill: parent
source: coverImageUrl
source: bookRow.coverImageUrl
sourceSize: Qt.size(width, height)
fillMode: Image.PreserveAspectFit
visible: status === Image.Ready
visible: coverImage.status === Image.Ready
}
}
@@ -69,7 +84,7 @@ Rectangle {
Text {
width: parent.width
text: title || "Unknown Title"
text: bookRow.title !== "" ? bookRow.title : "Unknown Title"
color: ThemeManager.currentTheme.uiText
font.pixelSize: 14
font.bold: true
@@ -77,25 +92,25 @@ Rectangle {
}
Text {
visible: format !== ""
visible: bookRow.format !== ""
width: parent.width
text: format
text: bookRow.format
color: ThemeManager.currentTheme.dimText
font.pixelSize: 12
elide: Text.ElideRight
}
Text {
visible: author !== ""
visible: bookRow.author !== ""
width: parent.width
text: author
text: bookRow.author
color: ThemeManager.currentTheme.dimText
font.pixelSize: 12
elide: Text.ElideRight
}
Text {
text: Math.round(progress * 100) + "%"
text: Math.round(bookRow.progress * 100) + "%"
color: ThemeManager.currentTheme.buttonAccent
font.pixelSize: 12
}
@@ -106,14 +121,14 @@ Rectangle {
anchors.verticalCenter: parent.verticalCenter
iconText: "\ue872"
iconSize: 20
onClicked: historyModel.removeBook(filePath)
onClicked: HistoryModel.removeBook(bookRow.filePath)
}
}
MouseArea {
anchors.fill: parent
z: -1
onClicked: book.openFromPath(filePath)
onClicked: Book.openFromPath(bookRow.filePath)
}
}
}
+4 -4
View File
@@ -2,23 +2,23 @@ import QtQuick
import Asteria
Item {
id: readerPage
id: root
property alias mangaView: internalPageView
property alias scrollView: scrollPageView
readonly property var pageView: readingModel.isTextMode ? scrollPageView : internalPageView
readonly property var pageView: ReadingModel.isTextMode ? scrollPageView : internalPageView
MangaPageView {
id: internalPageView
anchors.fill: parent
visible: !readingModel.isTextMode
visible: !ReadingModel.isTextMode
focus: visible
}
ScrollPageView {
id: scrollPageView
anchors.fill: parent
visible: readingModel.isTextMode
visible: ReadingModel.isTextMode
focus: visible
}
}
+3
View File
@@ -2,6 +2,8 @@ import QtQuick
import Asteria
Rectangle {
id: root
gradient: Gradient {
GradientStop { position: 0.0; color: ThemeManager.currentTheme.gradientTop }
GradientStop { position: 1.0; color: ThemeManager.currentTheme.gradientBottom }
@@ -10,6 +12,7 @@ Rectangle {
Image {
anchors.fill: parent
source: "qrc:/Asteria/src/assets/moon1.svg"
sourceSize: Qt.size(width, height)
fillMode: Image.PreserveAspectCrop
opacity: 0.15
}
+3 -2
View File
@@ -4,6 +4,7 @@
#include <QFile>
#include <QImage>
#include <QTemporaryFile>
#include <utility>
#include <minizip/zip.h>
@@ -41,7 +42,7 @@ static bool addEntry(zipFile zf, const char *name, const QByteArray &data)
// Creates a CBZ at a temp path with the given entries (name -> bytes).
// Caller must delete the returned path when done.
static QString buildCbz(const QList<QPair<QString, QByteArray>> &entries)
static QString buildCbz(const QList<std::pair<QString, QByteArray>> &entries)
{
QTemporaryFile tmp;
tmp.setFileTemplate(QDir::tempPath() + "/cbz_test_XXXXXX.cbz");
@@ -82,7 +83,7 @@ class CbzReaderTest : public QObject {
QStringList m_tempFiles;
QString makeCbz(const QList<QPair<QString, QByteArray>> &entries)
QString makeCbz(const QList<std::pair<QString, QByteArray>> &entries)
{
const QString p = buildCbz(entries);
if (!p.isEmpty())