Files
asteria-qt/src/backend/formats/FormatRegistry.cpp
T
2026-10-31 00:15:55 +01:00

117 lines
3.1 KiB
C++

#include "FormatRegistry.h"
#include "EntryImageProvider.h"
#include "backend/FormatReader.h"
#include "backend/formats/comic/ComicReader.h"
#include "backend/formats/EpubReader.h"
#include "backend/formats/Fb2Reader.h"
#include "backend/formats/TxtReader.h"
#include <QFileInfo>
#include <QQmlEngine>
#include <QSet>
FormatSpec FormatSpec::comic(const QString &ext, bool matchesDirectory, const QString &scheme,
SourceFactory makeSource)
{
return FormatSpec{
ext,
matchesDirectory,
scheme,
[makeSource, scheme] { return std::make_unique<ComicReader>(makeSource, scheme); },
makeSource
};
}
FormatSpec FormatSpec::epub(SourceFactory makeSource)
{
return FormatSpec{
QStringLiteral("epub"),
false,
QStringLiteral("epub"),
[makeSource] { return std::make_unique<EpubReader>(makeSource, QStringLiteral("epub")); },
makeSource
};
}
FormatSpec FormatSpec::fb2(const QString &ext, SourceFactory makeSource)
{
return FormatSpec{
ext,
false,
QStringLiteral("fb2"),
[makeSource] { return std::make_unique<Fb2Reader>(makeSource, QStringLiteral("fb2")); },
makeSource
};
}
FormatSpec FormatSpec::txt(const QString &ext)
{
return FormatSpec{
ext,
false,
QString(),
[] { return std::make_unique<TxtReader>(); },
nullptr
};
}
FormatRegistry::FormatRegistry(QVector<FormatSpec> specs)
: m_specs(std::move(specs))
{
}
const FormatSpec *FormatRegistry::specFor(const QString &filePath) const
{
const QFileInfo fi(filePath);
const bool isDir = fi.isDir();
const QString lowerPath = filePath.toLower();
for (const FormatSpec &spec : m_specs) {
if (isDir) {
if (spec.matchesDirectory)
return &spec;
} else if (!spec.matchesDirectory) {
if (lowerPath.endsWith(QLatin1Char('.') + spec.extension.toLower()))
return &spec;
}
}
return nullptr;
}
std::unique_ptr<FormatReader> FormatRegistry::createReader(const QString &filePath) const
{
const FormatSpec *spec = specFor(filePath);
return spec ? spec->makeReader() : nullptr;
}
std::unique_ptr<IByteSource> FormatRegistry::createByteSourceForScheme(const QString &scheme) const
{
for (const FormatSpec &spec : m_specs) {
if (spec.scheme == scheme && spec.makeSource)
return spec.makeSource();
}
return nullptr;
}
QStringList FormatRegistry::supportedExtensions() const
{
QStringList out;
for (const FormatSpec &spec : m_specs)
if (!spec.matchesDirectory && !spec.extension.isEmpty())
out << spec.extension;
return out;
}
void FormatRegistry::registerImageProviders(QQmlEngine &engine) const
{
QSet<QString> registeredSchemes;
for (const FormatSpec &spec : m_specs) {
if (!spec.scheme.isEmpty() && spec.makeSource && !registeredSchemes.contains(spec.scheme)) {
registeredSchemes.insert(spec.scheme);
engine.addImageProvider(spec.scheme,
new EntryImageProvider(spec.makeSource, spec.scheme));
}
}
}