a bit of refactor

This commit is contained in:
Agel committed 2026-03-23 22:49:46 +01:00
1 parent 24d0b84aab
commit f84e109a64
19 files changed
+546 -232

No files matched your search

+10 -180
View File
@@ -2,71 +2,6 @@
#include "AppState.h"
#include "ReaderFactory.h"
#include "ReadingModel.h"
#include <QFileDialog>
#ifdef HAS_QT_DBUS
#include <QDBusConnection>
#include <QDBusMessage>
#include <QDBusArgument>
#include <QDBusMetaType>
#include <QRandomGenerator>
// Typed structs so Qt can derive D-Bus signatures without reading a
// write-only QDBusArgument (which causes a SIGSEGV).
struct PortalGlob {
uint type; // 0 = glob pattern
QString pattern;
};
Q_DECLARE_METATYPE(PortalGlob)
QDBusArgument &operator<<(QDBusArgument &a, const PortalGlob &g)
{
a.beginStructure();
a << g.type << g.pattern;
a.endStructure();
return a;
}
const QDBusArgument &operator>>(const QDBusArgument &a, PortalGlob &g)
{
a.beginStructure();
a >> g.type >> g.pattern;
a.endStructure();
return a;
}
struct PortalFilter {
QString name;
QList<PortalGlob> globs;
};
Q_DECLARE_METATYPE(PortalFilter)
QDBusArgument &operator<<(QDBusArgument &a, const PortalFilter &f)
{
a.beginStructure();
a << f.name << f.globs;
a.endStructure();
return a;
}
const QDBusArgument &operator>>(const QDBusArgument &a, PortalFilter &f)
{
a.beginStructure();
a >> f.name >> f.globs;
a.endStructure();
return a;
}
static void registerPortalTypes()
{
static bool done = false;
if (done) return;
done = true;
qDBusRegisterMetaType<PortalGlob>();
qDBusRegisterMetaType<QList<PortalGlob>>();
qDBusRegisterMetaType<PortalFilter>();
qDBusRegisterMetaType<QList<PortalFilter>>();
}
#endif
BookController::BookController(QObject *parent)
: QObject(parent)
@@ -120,6 +55,14 @@ void BookController::setAppState(AppState *state)
m_appState = state;
}
void BookController::setFileDialogService(IFileDialogService *service)
{
m_fileDialogService = service;
if (m_fileDialogService)
connect(m_fileDialogService, &IFileDialogService::fileSelected,
this, &BookController::openBookFromPath);
}
void BookController::openBookFromPath(const QString &filePath)
{
openBook(QUrl::fromLocalFile(filePath));
@@ -184,121 +127,8 @@ void BookController::openBook(const QUrl &fileUrl)
void BookController::browseAndOpen()
{
#ifdef HAS_QT_DBUS
auto bus = QDBusConnection::sessionBus();
if (!bus.isConnected()) {
browseAndOpenFallback();
return;
}
// Check if the FileChooser portal is available
QDBusMessage ping = QDBusMessage::createMethodCall(
QStringLiteral("org.freedesktop.portal.Desktop"),
QStringLiteral("/org/freedesktop/portal/desktop"),
QStringLiteral("org.freedesktop.DBus.Properties"),
QStringLiteral("Get"));
ping << QStringLiteral("org.freedesktop.portal.FileChooser")
<< QStringLiteral("version");
QDBusMessage pong = bus.call(ping, QDBus::Block, 500);
if (pong.type() == QDBusMessage::ErrorMessage) {
browseAndOpenFallback();
return;
}
// Generate a unique handle token and compute the expected response path
QString token = QStringLiteral("asteria_")
+ QString::number(QRandomGenerator::global()->generate());
QString sender = bus.baseService();
sender.remove(0, 1); // strip leading ':'
sender.replace(QLatin1Char('.'), QLatin1Char('_'));
m_portalHandlePath = QStringLiteral("/org/freedesktop/portal/desktop/request/%1/%2")
.arg(sender, token);
// Connect to the Response signal BEFORE making the call (avoids race)
bus.connect(QStringLiteral("org.freedesktop.portal.Desktop"),
m_portalHandlePath,
QStringLiteral("org.freedesktop.portal.Request"),
QStringLiteral("Response"),
this,
SLOT(handlePortalResponse(uint,QVariantMap)));
registerPortalTypes();
// Build file filters using registered types (no raw QDBusArgument in QVariant)
PortalFilter bookFilter;
bookFilter.name = QStringLiteral("Book files");
for (const char *ext : {"*.txt", "*.fb2", "*.epub", "*.pdf", "*.doc",
"*.rtf", "*.html", "*.htm", "*.docx",
"*.djvu", "*.odt", "*.chm"}) {
bookFilter.globs.append({0, QString::fromLatin1(ext)});
}
PortalFilter allFilter;
allFilter.name = QStringLiteral("All files");
allFilter.globs.append({0, QStringLiteral("*")});
QList<PortalFilter> filters{bookFilter, allFilter};
QVariantMap options;
options[QStringLiteral("handle_token")] = token;
options[QStringLiteral("filters")] = QVariant::fromValue(filters);
// Build the OpenFile call
QDBusMessage msg = QDBusMessage::createMethodCall(
QStringLiteral("org.freedesktop.portal.Desktop"),
QStringLiteral("/org/freedesktop/portal/desktop"),
QStringLiteral("org.freedesktop.portal.FileChooser"),
QStringLiteral("OpenFile"));
msg << QString(); // parent_window (empty)
msg << QStringLiteral("Open Book"); // title
msg << options;
QDBusMessage reply = bus.call(msg);
if (reply.type() == QDBusMessage::ErrorMessage) {
bus.disconnect(QStringLiteral("org.freedesktop.portal.Desktop"),
m_portalHandlePath,
QStringLiteral("org.freedesktop.portal.Request"),
QStringLiteral("Response"),
this,
SLOT(handlePortalResponse(uint,QVariantMap)));
browseAndOpenFallback();
}
#else
browseAndOpenFallback();
#endif
}
#ifdef HAS_QT_DBUS
void BookController::handlePortalResponse(uint response,
const QVariantMap &results)
{
QDBusConnection::sessionBus().disconnect(
QStringLiteral("org.freedesktop.portal.Desktop"),
m_portalHandlePath,
QStringLiteral("org.freedesktop.portal.Request"),
QStringLiteral("Response"),
this,
SLOT(handlePortalResponse(uint,QVariantMap)));
if (response != 0)
return; // user cancelled or error
QStringList uris = results.value(QStringLiteral("uris")).toStringList();
if (!uris.isEmpty())
openBook(QUrl(uris.first()));
}
#endif
void BookController::browseAndOpenFallback()
{
QString path = QFileDialog::getOpenFileName(
nullptr,
QStringLiteral("Open Book"),
QString(),
QStringLiteral("Book files (*.txt *.fb2 *.epub *.pdf *.doc *.rtf *.html *.htm *.docx *.djvu *.odt *.chm);;All files (*)"));
if (!path.isEmpty())
openBook(QUrl::fromLocalFile(path));
if (m_fileDialogService)
m_fileDialogService->open();
}
void BookController::closeBook()
+3 -10
View File
@@ -8,6 +8,7 @@
#include <memory>
#include "FormatReader.h"
#include "IFileDialogService.h"
class AppState;
class ReadingModel;
@@ -35,6 +36,7 @@ public:
void setReadingModel(ReadingModel *model);
void setAppState(AppState *state);
void setFileDialogService(IFileDialogService *service);
Q_INVOKABLE void openBook(const QUrl &fileUrl);
Q_INVOKABLE void openBookFromPath(const QString &filePath);
@@ -49,25 +51,16 @@ signals:
void loadingChanged();
void errorMessageChanged();
private slots:
#ifdef HAS_QT_DBUS
void handlePortalResponse(uint response, const QVariantMap &results);
#endif
private:
void browseAndOpenFallback();
std::unique_ptr<FormatReader> m_reader;
ReadingModel *m_readingModel = nullptr;
AppState *m_appState = nullptr;
IFileDialogService *m_fileDialogService = nullptr;
QString m_bookTitle;
QString m_bookAuthor;
QString m_currentFilePath;
bool m_loading = false;
QString m_errorMessage;
#ifdef HAS_QT_DBUS
QString m_portalHandlePath;
#endif
};
#endif // BOOKCONTROLLER_H
+14
View File
@@ -0,0 +1,14 @@
#ifndef ICHUNKMEASURER_H
#define ICHUNKMEASURER_H
#include <QStringList>
#include <QVector>
#include <QtGlobal>
class IChunkMeasurer {
public:
virtual ~IChunkMeasurer() = default;
virtual QVector<qreal> measure(const QStringList &chunks, qreal textWidth) const = 0;
};
#endif // ICHUNKMEASURER_H
+1
View File
@@ -0,0 +1 @@
#include "IFileDialogService.h"
+19
View File
@@ -0,0 +1,19 @@
#ifndef IFILEDIAL0GSERVICE_H
#define IFILEDIAL0GSERVICE_H
#include <QObject>
#include <QString>
class IFileDialogService : public QObject {
Q_OBJECT
public:
explicit IFileDialogService(QObject *parent = nullptr) : QObject(parent) {}
~IFileDialogService() override = default;
virtual void open() = 0;
signals:
void fileSelected(const QString &path);
};
#endif // IFILEDIAL0GSERVICE_H
+18
View File
@@ -0,0 +1,18 @@
#include "NativeFileDialogService.h"
#include <QFileDialog>
NativeFileDialogService::NativeFileDialogService(QObject *parent)
: IFileDialogService(parent)
{
}
void NativeFileDialogService::open()
{
QString path = QFileDialog::getOpenFileName(
nullptr,
QStringLiteral("Open Book"),
QString(),
QStringLiteral("Book files (*.txt *.fb2 *.epub *.pdf *.doc *.rtf *.html *.htm *.docx *.djvu *.odt *.chm);;All files (*)"));
if (!path.isEmpty())
emit fileSelected(path);
}
+13
View File
@@ -0,0 +1,13 @@
#ifndef NATIVEFILEDIALOGSERVICE_H
#define NATIVEFILEDIALOGSERVICE_H
#include "IFileDialogService.h"
class NativeFileDialogService : public IFileDialogService {
Q_OBJECT
public:
explicit NativeFileDialogService(QObject *parent = nullptr);
void open() override;
};
#endif // NATIVEFILEDIALOGSERVICE_H
+155
View File
@@ -0,0 +1,155 @@
#ifdef HAS_QT_DBUS
#include "PortalFileDialogService.h"
#include <QDBusConnection>
#include <QDBusMessage>
#include <QDBusArgument>
#include <QDBusMetaType>
#include <QRandomGenerator>
#include <QUrl>
// Typed structs so Qt can derive D-Bus signatures without reading a
// write-only QDBusArgument (which causes a SIGSEGV).
struct PortalGlob {
uint type; // 0 = glob pattern
QString pattern;
};
Q_DECLARE_METATYPE(PortalGlob)
QDBusArgument &operator<<(QDBusArgument &a, const PortalGlob &g)
{
a.beginStructure();
a << g.type << g.pattern;
a.endStructure();
return a;
}
const QDBusArgument &operator>>(const QDBusArgument &a, PortalGlob &g)
{
a.beginStructure();
a >> g.type >> g.pattern;
a.endStructure();
return a;
}
struct PortalFilter {
QString name;
QList<PortalGlob> globs;
};
Q_DECLARE_METATYPE(PortalFilter)
QDBusArgument &operator<<(QDBusArgument &a, const PortalFilter &f)
{
a.beginStructure();
a << f.name << f.globs;
a.endStructure();
return a;
}
const QDBusArgument &operator>>(const QDBusArgument &a, PortalFilter &f)
{
a.beginStructure();
a >> f.name >> f.globs;
a.endStructure();
return a;
}
static void registerPortalTypes()
{
static bool done = false;
if (done) return;
done = true;
qDBusRegisterMetaType<PortalGlob>();
qDBusRegisterMetaType<QList<PortalGlob>>();
qDBusRegisterMetaType<PortalFilter>();
qDBusRegisterMetaType<QList<PortalFilter>>();
}
PortalFileDialogService::PortalFileDialogService(QObject *parent)
: IFileDialogService(parent)
{
}
void PortalFileDialogService::open()
{
auto bus = QDBusConnection::sessionBus();
// Generate a unique handle token and compute the expected response path
QString token = QStringLiteral("asteria_")
+ QString::number(QRandomGenerator::global()->generate());
QString sender = bus.baseService();
sender.remove(0, 1); // strip leading ':'
sender.replace(QLatin1Char('.'), QLatin1Char('_'));
m_portalHandlePath = QStringLiteral("/org/freedesktop/portal/desktop/request/%1/%2")
.arg(sender, token);
// Connect to the Response signal BEFORE making the call (avoids race)
bus.connect(QStringLiteral("org.freedesktop.portal.Desktop"),
m_portalHandlePath,
QStringLiteral("org.freedesktop.portal.Request"),
QStringLiteral("Response"),
this,
SLOT(handlePortalResponse(uint,QVariantMap)));
registerPortalTypes();
// Build file filters using registered types (no raw QDBusArgument in QVariant)
PortalFilter bookFilter;
bookFilter.name = QStringLiteral("Book files");
for (const char *ext : {"*.txt", "*.fb2", "*.epub", "*.pdf", "*.doc",
"*.rtf", "*.html", "*.htm", "*.docx",
"*.djvu", "*.odt", "*.chm"}) {
bookFilter.globs.append({0, QString::fromLatin1(ext)});
}
PortalFilter allFilter;
allFilter.name = QStringLiteral("All files");
allFilter.globs.append({0, QStringLiteral("*")});
QList<PortalFilter> filters{bookFilter, allFilter};
QVariantMap options;
options[QStringLiteral("handle_token")] = token;
options[QStringLiteral("filters")] = QVariant::fromValue(filters);
// Build the OpenFile call
QDBusMessage msg = QDBusMessage::createMethodCall(
QStringLiteral("org.freedesktop.portal.Desktop"),
QStringLiteral("/org/freedesktop/portal/desktop"),
QStringLiteral("org.freedesktop.portal.FileChooser"),
QStringLiteral("OpenFile"));
msg << QString(); // parent_window (empty)
msg << QStringLiteral("Open Book"); // title
msg << options;
QDBusMessage reply = bus.call(msg);
if (reply.type() == QDBusMessage::ErrorMessage) {
bus.disconnect(QStringLiteral("org.freedesktop.portal.Desktop"),
m_portalHandlePath,
QStringLiteral("org.freedesktop.portal.Request"),
QStringLiteral("Response"),
this,
SLOT(handlePortalResponse(uint,QVariantMap)));
}
}
void PortalFileDialogService::handlePortalResponse(uint response,
const QVariantMap &results)
{
QDBusConnection::sessionBus().disconnect(
QStringLiteral("org.freedesktop.portal.Desktop"),
m_portalHandlePath,
QStringLiteral("org.freedesktop.portal.Request"),
QStringLiteral("Response"),
this,
SLOT(handlePortalResponse(uint,QVariantMap)));
if (response != 0)
return; // user cancelled or error
QStringList uris = results.value(QStringLiteral("uris")).toStringList();
if (!uris.isEmpty())
emit fileSelected(QUrl(uris.first()).toLocalFile());
}
#endif // HAS_QT_DBUS
+22
View File
@@ -0,0 +1,22 @@
#ifndef PORTALFILEDIALOGSERVICE_H
#define PORTALFILEDIALOGSERVICE_H
#ifdef HAS_QT_DBUS
#include "IFileDialogService.h"
class PortalFileDialogService : public IFileDialogService {
Q_OBJECT
public:
explicit PortalFileDialogService(QObject *parent = nullptr);
void open() override;
private slots:
void handlePortalResponse(uint response, const QVariantMap &results);
private:
QString m_portalHandlePath;
};
#endif // HAS_QT_DBUS
#endif // PORTALFILEDIALOGSERVICE_H
+41
View File
@@ -0,0 +1,41 @@
#include "QDocumentChunkMeasurer.h"
#include <QFont>
#include <QTextBlockFormat>
#include <QTextCursor>
#include <QTextDocument>
QDocumentChunkMeasurer::QDocumentChunkMeasurer(int pixelSize, qreal lineHeightPercent)
: m_pixelSize(pixelSize)
, m_lineHeightPercent(lineHeightPercent)
{
}
QVector<qreal> QDocumentChunkMeasurer::measure(const QStringList &chunks, qreal textWidth) const
{
if (textWidth <= 0)
textWidth = 1;
QFont font;
font.setPixelSize(m_pixelSize);
QTextDocument doc;
doc.setDefaultFont(font);
QVector<qreal> heights;
heights.reserve(chunks.size());
for (const QString &chunk : chunks) {
doc.setHtml(chunk);
doc.setTextWidth(textWidth);
QTextBlockFormat fmt;
fmt.setLineHeight(m_lineHeightPercent, QTextBlockFormat::ProportionalHeight);
QTextCursor cursor(&doc);
cursor.select(QTextCursor::Document);
cursor.mergeBlockFormat(fmt);
heights.append(doc.size().height());
}
return heights;
}
+16
View File
@@ -0,0 +1,16 @@
#ifndef QDOCUMENTCHUNKMEASURER_H
#define QDOCUMENTCHUNKMEASURER_H
#include "IChunkMeasurer.h"
class QDocumentChunkMeasurer : public IChunkMeasurer {
public:
explicit QDocumentChunkMeasurer(int pixelSize = 16, qreal lineHeightPercent = 160.0);
QVector<qreal> measure(const QStringList &chunks, qreal textWidth) const override;
private:
int m_pixelSize;
qreal m_lineHeightPercent;
};
#endif // QDOCUMENTCHUNKMEASURER_H
+9 -32
View File
@@ -1,10 +1,6 @@
#include "ReadingModel.h"
#include "FormatReader.h"
#include <cmath>
#include <QTextDocument>
#include <QTextCursor>
#include <QTextBlockFormat>
#include <QFont>
ReadingModel::ReadingModel(QObject *parent)
: QAbstractListModel(parent)
@@ -74,6 +70,11 @@ int ReadingModel::totalPages() const
return m_totalPages;
}
void ReadingModel::setChunkMeasurer(IChunkMeasurer *measurer)
{
m_chunkMeasurer = measurer;
}
void ReadingModel::setViewportSize(qreal width, qreal height)
{
bool widthChanged = (width != m_viewportWidth);
@@ -99,36 +100,12 @@ void ReadingModel::setScrollInfo(int topChunkIndex, qreal offsetInChunk, bool at
void ReadingModel::computeChunkHeights()
{
// Caller passes effective text width:
// chunkListView.width - 18 (scrollbar) - 2 * horizontalMargin (delegate padding)
qreal textWidth = m_viewportWidth;
if (textWidth <= 0)
textWidth = 1;
QFont font;
font.setPixelSize(16);
QTextDocument doc;
doc.setDefaultFont(font);
m_chunkHeights.clear();
m_chunkHeights.reserve(m_chunks.size());
for (const QString &chunk : m_chunks) {
doc.setHtml(chunk);
doc.setTextWidth(textWidth);
// Apply lineHeight: 1.6 (matching QML Text lineHeight property)
QTextBlockFormat fmt;
fmt.setLineHeight(160, QTextBlockFormat::ProportionalHeight);
QTextCursor cursor(&doc);
cursor.select(QTextCursor::Document);
cursor.mergeBlockFormat(fmt);
m_chunkHeights.append(doc.size().height());
if (m_chunkMeasurer) {
m_chunkHeights = m_chunkMeasurer->measure(m_chunks, m_viewportWidth);
} else {
m_chunkHeights.assign(m_chunks.size(), 0.0);
}
// Build prefix sums
m_chunkOffsets.clear();
m_chunkOffsets.reserve(m_chunks.size());
qreal offset = 0;
+4
View File
@@ -6,6 +6,8 @@
#include <QStringList>
#include <QVector>
#include "IChunkMeasurer.h"
class FormatReader;
class ReadingModel : public QAbstractListModel {
@@ -38,6 +40,7 @@ public:
int totalPages() const;
bool hasChapters() const;
void setReader(FormatReader *reader);
void setChunkMeasurer(IChunkMeasurer *measurer);
// Called from QML on resize
Q_INVOKABLE void setViewportSize(qreal width, qreal height);
@@ -61,6 +64,7 @@ private:
void recalculateCurrentPage();
FormatReader *m_reader = nullptr;
IChunkMeasurer *m_chunkMeasurer = nullptr;
int m_currentChapter = 0;
int m_totalChapters = 0;
int m_currentPage = 0;
+22
View File
@@ -11,6 +11,13 @@
#include "backend/BookController.h"
#include "backend/ReadingModel.h"
#include "backend/AppState.h"
#include "backend/QDocumentChunkMeasurer.h"
#include "backend/NativeFileDialogService.h"
#ifdef HAS_QT_DBUS
#include <QDBusConnection>
#include "backend/PortalFileDialogService.h"
#endif
void myMessageHandler(const QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
@@ -71,7 +78,10 @@ int main(int argc, char *argv[])
QQuickStyle::setStyle(QStringLiteral("Basic"));
QDocumentChunkMeasurer chunkMeasurer(16, 160.0);
ReadingModel readingModel;
readingModel.setChunkMeasurer(&chunkMeasurer);
BookController bookController;
bookController.setReadingModel(&readingModel);
@@ -80,6 +90,18 @@ int main(int argc, char *argv[])
appState.restore();
bookController.setAppState(&appState);
#ifdef HAS_QT_DBUS
IFileDialogService *fileDialogService;
if (QDBusConnection::sessionBus().isConnected()) {
fileDialogService = new PortalFileDialogService(&bookController);
} else {
fileDialogService = new NativeFileDialogService(&bookController);
}
#else
IFileDialogService *fileDialogService = new NativeFileDialogService(&bookController);
#endif
bookController.setFileDialogService(fileDialogService);
if (const QStringList args = QCoreApplication::arguments(); args.size() > 1) {
const QString& filePath = args.at(1);
if (QFileInfo::exists(filePath))