txt support

This commit is contained in:
Agel committed 2026-10-31 00:15:55 +01:00
1 parent 85ae0d4ad9
commit fe969bab16
11 files changed
+781 -14

No files matched your search

+12
View File
@@ -5,6 +5,7 @@
#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>
@@ -44,6 +45,17 @@ FormatSpec FormatSpec::fb2(const QString &ext, SourceFactory 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))
{
+1
View File
@@ -27,6 +27,7 @@ struct FormatSpec {
SourceFactory makeSource);
static FormatSpec epub(SourceFactory makeSource);
static FormatSpec fb2(const QString &ext, SourceFactory makeSource);
static FormatSpec txt(const QString &ext = QStringLiteral("txt"));
};
class FormatRegistry {
+111 -3
View File
@@ -6,10 +6,74 @@
#include <algorithm>
#include <iconv.h>
#ifdef HAS_UCHARDET
#include <uchardet.h>
#endif
namespace {
bool isValidUtf8(const QByteArray &bytes, bool &hasNonAscii)
{
hasNonAscii = false;
const auto *data = reinterpret_cast<const unsigned char*>(bytes.constData());
const int n = static_cast<int>(bytes.size());
int i = 0;
while (i < n) {
const unsigned char b = data[i];
if (b <= 0x7F) {
++i;
} else if (b >= 0xC2 && b <= 0xDF) {
if (i + 1 >= n || data[i + 1] < 0x80 || data[i + 1] > 0xBF)
return false;
i += 2;
hasNonAscii = true;
} else if (b == 0xE0) {
if (i + 2 >= n || data[i + 1] < 0xA0 || data[i + 1] > 0xBF || data[i + 2] < 0x80 || data[i + 2] > 0xBF)
return false;
i += 3;
hasNonAscii = true;
} else if ((b >= 0xE1 && b <= 0xEC) || (b >= 0xEE && b <= 0xEF)) {
if (i + 2 >= n || data[i + 1] < 0x80 || data[i + 1] > 0xBF || data[i + 2] < 0x80 || data[i + 2] > 0xBF)
return false;
i += 3;
hasNonAscii = true;
} else if (b == 0xED) {
if (i + 2 >= n || data[i + 1] < 0x80 || data[i + 1] > 0x9F || data[i + 2] < 0x80 || data[i + 2] > 0xBF)
return false;
i += 3;
hasNonAscii = true;
} else if (b == 0xF0) {
if (i + 3 >= n || data[i + 1] < 0x90 || data[i + 1] > 0xBF || data[i + 2] < 0x80 || data[i + 2] > 0xBF || data[i + 3] < 0x80 || data[i + 3] > 0xBF)
return false;
i += 4;
hasNonAscii = true;
} else if (b >= 0xF1 && b <= 0xF3) {
if (i + 3 >= n || data[i + 1] < 0x80 || data[i + 1] > 0xBF || data[i + 2] < 0x80 || data[i + 2] > 0xBF || data[i + 3] < 0x80 || data[i + 3] > 0xBF)
return false;
i += 4;
hasNonAscii = true;
} else if (b == 0xF4) {
if (i + 3 >= n || data[i + 1] < 0x80 || data[i + 1] > 0x8F || data[i + 2] < 0x80 || data[i + 2] > 0xBF || data[i + 3] < 0x80 || data[i + 3] > 0xBF)
return false;
i += 4;
hasNonAscii = true;
} else {
return false;
}
}
return true;
}
} // namespace
namespace TextEncoding {
QString detectEncoding(const QByteArray &bytes)
{
if (bytes.isEmpty())
return QString();
if (bytes.startsWith("\xEF\xBB\xBF"))
return QStringLiteral("UTF-8");
if (bytes.startsWith("\xFF\xFE"))
@@ -44,7 +108,51 @@ QString detectEncoding(const QByteArray &bytes)
if (match.hasMatch())
return match.captured(1).trimmed();
return QString();
// 4. Validate UTF-8: if bytes is strictly valid UTF-8, return UTF-8
bool hasNonAscii = false;
if (isValidUtf8(bytes, hasNonAscii))
return QStringLiteral("UTF-8");
#ifdef HAS_UCHARDET
uchardet_t ud = uchardet_new();
uchardet_handle_data(ud, bytes.constData(), bytes.size());
uchardet_data_end(ud);
const char *cs = uchardet_get_charset(ud);
QString detected = cs ? QString::fromLatin1(cs).trimmed() : QString();
uchardet_delete(ud);
if (!detected.isEmpty()
&& detected.compare(QLatin1String("ASCII"), Qt::CaseInsensitive) != 0
&& detected.compare(QLatin1String("unknown"), Qt::CaseInsensitive) != 0)
return detected;
#endif
// 5. Heuristic statistical fallback for single-byte encodings
int score1251 = 0;
int score866 = 0;
int scoreKoi8 = 0;
const int sampleSize = (std::min)(static_cast<int>(bytes.size()), 32768);
for (int i = 0; i < sampleSize; ++i) {
const unsigned char b = static_cast<unsigned char>(bytes[i]);
if (b >= 0xE0) score1251 += 2;
else if (b >= 0xC0) score1251 += 1;
if (b >= 0xC0 && b <= 0xDF) scoreKoi8 += 2;
else if (b >= 0xE0) scoreKoi8 += 1;
if ((b >= 0xA0 && b <= 0xAF) || (b >= 0xE0 && b <= 0xEF)) score866 += 2;
else if (b >= 0x80 && b <= 0x9F) score866 += 1;
else if (b >= 0xB0 && b <= 0xDF) score866 -= 5;
}
int maxScore = std::max({score1251, score866, scoreKoi8});
if (maxScore > 5) {
if (maxScore == score1251) return QStringLiteral("windows-1251");
if (maxScore == score866) return QStringLiteral("cp866");
if (maxScore == scoreKoi8) return QStringLiteral("koi8-r");
}
return QStringLiteral("windows-1252");
}
QString decodeWithEncoding(const QByteArray &bytes, const QString &encodingName)
@@ -114,9 +222,9 @@ QString decode(const QByteArray &bytes, const QString &hintEncoding)
return decoder(bytes.mid(2));
}
QString enc = detectEncoding(bytes);
QString enc = hintEncoding;
if (enc.isEmpty())
enc = hintEncoding;
enc = detectEncoding(bytes);
if (!enc.isEmpty()) {
const QString decoded = decodeWithEncoding(bytes, enc);
+189
View File
@@ -0,0 +1,189 @@
#include "TxtReader.h"
#include <QFile>
#include <QFileInfo>
#include <QStringView>
#include "backend/formats/IByteSource.h"
#include "backend/formats/TextEncoding.h"
#include "backend/reading/layout/DocumentChunkBuilder.h"
bool TxtReader::open(const QString &filePath)
{
return parseOpen(filePath, false);
}
bool TxtReader::loadMetadata(const QString &filePath)
{
return parseOpen(filePath, true);
}
bool TxtReader::parseOpen(const QString &filePath, bool metadataOnly)
{
m_filePath = filePath;
m_error.clear();
m_title.clear();
m_author.clear();
m_chunks.clear();
m_contentHash = IByteSource::hashFileMd5(filePath);
QFile file(filePath);
if (!file.open(QIODevice::ReadOnly)) {
m_error = QStringLiteral("Cannot open file: ") + filePath;
return false;
}
const QByteArray rawBytes = file.readAll();
// Reject files containing binary, encrypted, or corrupted data (null bytes, excessive control characters,
// or excessive unmappable replacement characters '?', excluding valid UTF-16/32 BOMs)
const bool hasUtf16Bom = rawBytes.startsWith("\xFF\xFE") || rawBytes.startsWith("\xFE\xFF");
if (!hasUtf16Bom) {
const int checkLen = (std::min)(static_cast<int>(rawBytes.size()), 4096);
int controlChars = 0;
int questionMarks = 0;
bool hasNull = false;
for (int i = 0; i < checkLen; ++i) {
const unsigned char c = static_cast<unsigned char>(rawBytes[i]);
if (c == 0) {
hasNull = true;
break;
}
if (c < 32 && c != '\t' && c != '\n' && c != '\r') {
++controlChars;
} else if (c == '?') {
++questionMarks;
}
}
if (hasNull || (checkLen > 0 && (controlChars > checkLen / 50 || questionMarks > checkLen / 5))) {
m_error = QStringLiteral("File contains corrupted, binary, or encrypted data and cannot be read as plain text: ") + QFileInfo(filePath).fileName();
return false;
}
}
if (rawBytes.isEmpty()) {
return true;
}
const QString decodedText = TextEncoding::decode(rawBytes);
if (decodedText.isEmpty()) {
m_error = QStringLiteral("Failed to decode text: ") + QFileInfo(filePath).fileName();
return false;
}
const int checkDecoded = (std::min)(static_cast<int>(decodedText.size()), 4096);
if (checkDecoded > 0 && decodedText.left(checkDecoded).count(QChar::ReplacementCharacter) > checkDecoded / 5) {
m_error = QStringLiteral("File contains corrupted, binary, or encrypted data and cannot be read as plain text: ") + QFileInfo(filePath).fileName();
return false;
}
// Metadata extraction (check first 60 lines for Gutenberg headers)
m_title = QFileInfo(filePath).completeBaseName();
qsizetype scanPos = 0;
int lineCount = 0;
while (scanPos < decodedText.size() && lineCount < 60) {
qsizetype nextPos = decodedText.indexOf(QLatin1Char('\n'), scanPos);
if (nextPos == -1) nextPos = decodedText.size();
QStringView line = QStringView(decodedText).mid(scanPos, nextPos - scanPos).trimmed();
if (line.startsWith(QLatin1String("Title:"), Qt::CaseInsensitive)) {
m_title = line.mid(6).trimmed().toString();
} else if (line.startsWith(QLatin1String("Author:"), Qt::CaseInsensitive)) {
m_author = line.mid(7).trimmed().toString();
}
if (nextPos >= decodedText.size()) break;
scanPos = nextPos + 1;
++lineCount;
}
if (metadataOnly) {
return true;
}
// Full text parsing into DocumentChunkBuilder
DocumentChunkBuilder builder(QString(), 512);
QString normalized = decodedText;
normalized.replace(QLatin1String("\r\n"), QLatin1String("\n"));
normalized.replace(QLatin1Char('\r'), QLatin1Char('\n'));
// Detect if file utilizes blank lines between paragraphs
bool hasBlankLines = false;
{
qsizetype pos = 0;
while (pos < normalized.size()) {
qsizetype nextPos = normalized.indexOf(QLatin1Char('\n'), pos);
if (nextPos == -1) nextPos = normalized.size();
QStringView line = QStringView(normalized).mid(pos, nextPos - pos);
if (line.trimmed().isEmpty() && pos > 0 && nextPos < normalized.size()) {
hasBlankLines = true;
break;
}
pos = nextPos + 1;
}
}
const qreal baseFontSize = 16.0;
const qreal textIndent = baseFontSize * 2.0;
auto emitParagraph = [&](const QString &paraText) {
if (paraText.trimmed().isEmpty()) return;
builder.startParagraph(TextAlign::Justify, textIndent, 0, baseFontSize);
builder.appendText(paraText, TextStyle());
builder.finishParagraph();
};
auto emitSceneBreak = [&]() {
BoxStyle emptyBox;
emptyBox.marginTop = baseFontSize * 0.5;
emptyBox.marginBottom = baseFontSize * 0.5;
builder.startContainer(emptyBox);
builder.startParagraph(TextAlign::Left, 0, 0, baseFontSize);
builder.appendLineBreak();
builder.finishParagraph();
builder.endContainer(emptyBox);
};
QString currentParagraph;
int consecutiveBlankLines = 0;
qsizetype pos = 0;
while (pos < normalized.size()) {
qsizetype nextPos = normalized.indexOf(QLatin1Char('\n'), pos);
if (nextPos == -1) nextPos = normalized.size();
QStringView line = QStringView(normalized).mid(pos, nextPos - pos);
if (hasBlankLines) {
if (line.trimmed().isEmpty()) {
if (!currentParagraph.isEmpty()) {
emitParagraph(currentParagraph);
currentParagraph.clear();
}
++consecutiveBlankLines;
if (consecutiveBlankLines == 2) {
emitSceneBreak();
}
} else {
consecutiveBlankLines = 0;
if (currentParagraph.isEmpty()) {
currentParagraph = line.trimmed().toString();
} else {
currentParagraph.append(QLatin1Char(' '));
currentParagraph.append(line.trimmed());
}
}
} else {
if (!line.trimmed().isEmpty()) {
emitParagraph(line.trimmed().toString());
}
}
pos = nextPos + 1;
}
if (!currentParagraph.isEmpty()) {
emitParagraph(currentParagraph);
}
m_chunks = builder.build();
return true;
}
+37
View File
@@ -0,0 +1,37 @@
#pragma once
#include <QByteArray>
#include <QString>
#include <QVector>
#include "backend/FormatReader.h"
#include "backend/reading/layout/DocumentIr.h"
class TxtReader : public FormatReader {
public:
TxtReader() = default;
~TxtReader() override = default;
ReadingMode mode() const override { return ReadingMode::Text; }
bool open(const QString &filePath) override;
bool loadMetadata(const QString &filePath) override;
QString lastError() const override { return m_error; }
QString filePath() const override { return m_filePath; }
QString title() const override { return m_title; }
QString author() const override { return m_author; }
QString coverImageUrl() const override { return {}; }
QByteArray contentHash() const override { return m_contentHash; }
QVector<ContentChunk> chunks() const override { return m_chunks; }
private:
bool parseOpen(const QString &filePath, bool metadataOnly);
QString m_filePath;
QByteArray m_contentHash;
QString m_title;
QString m_author;
QString m_error;
QVector<ContentChunk> m_chunks;
};