`): unstyled paragraphs default to zero vertical margins (`marginTop = 0`, `marginBottom = 0`) and `2.0em` first-line indent (`textIndent = 2.0 * baseFontSize`), eliminating `ContainerStart`/`ContainerEnd` box allocation overhead and preventing blank vertical gaps between prose/dialogue lines. Explicit CSS margins in publisher stylesheets override this default. Shorthand `margin` and `padding` (1 to 4 token syntax) are fully parsed.
- Headings (`h1`..`h6`) default to left-aligned (`TextAlign::Left`) without first-line indentation (`textIndent = 0`). In `Fb2Reader`, `
` flattens child `` lines separated by `
` with `text-align: left; text-indent: 0;`, preventing nested paragraph indent on titles. Scene transitions via FB2 `` use explicit margins to provide intended section gaps.
- When viewport geometry or font preferences change, `ReadingModel::updateLayoutMetrics()` runs `ChunkLayoutEngine` off-thread:
@@ -211,6 +212,7 @@ Driven by `FormatSpec` table built in `main.cpp`:
- `FormatSpec::comic(ext, matchesDirectory, scheme, makeSource)`
- `FormatSpec::epub(makeSource)`
- `FormatSpec::fb2(ext, makeSource)`
+- `FormatSpec::txt(ext)`
Each format registers its file extension / directory matcher, reader factory, `IByteSource` factory, and image URL scheme in a single table entry.
---
@@ -256,6 +258,7 @@ src/
ImageScaling.h
ImageUrl.h/cpp
TextEncoding.h/cpp
+ TxtReader.h/cpp
WebImageProvider.h/cpp
comic/
ComicReader.h/cpp
@@ -320,6 +323,7 @@ tests/
FolderReaderTest.cpp
ImageUrlTest.cpp
TextEncodingTest.cpp
+ TxtReaderTest.cpp
WebImageProviderTest.cpp
reading/
KnuthPlassRenderingSpecTest.cpp
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 168b6b4..24720ab 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -26,6 +26,13 @@ find_package(PkgConfig REQUIRED)
find_package(Iconv REQUIRED)
pkg_check_modules(MINIZIP REQUIRED IMPORTED_TARGET minizip)
pkg_check_modules(LIBARCHIVE REQUIRED IMPORTED_TARGET libarchive)
+pkg_check_modules(UCHARDET IMPORTED_TARGET uchardet)
+if(TARGET PkgConfig::UCHARDET)
+ add_compile_definitions(HAS_UCHARDET)
+ set(UCHARDET_LIB PkgConfig::UCHARDET)
+else()
+ set(UCHARDET_LIB "")
+endif()
# libarchive on Windows is built with CNG enabled (BCryptGenRandom for temp files).
# bcrypt.lib and iconv are not listed in the .pc file, so inject them here.
if(WIN32)
@@ -93,6 +100,8 @@ set(SOURCES
src/backend/formats/sources/Fb2ByteSource.cpp
src/backend/formats/Fb2Reader.h
src/backend/formats/Fb2Reader.cpp
+ src/backend/formats/TxtReader.h
+ src/backend/formats/TxtReader.cpp
src/backend/reading/BookImageResolver.h
src/backend/reading/BookImageResolver.cpp
src/backend/reading/KnuthPlassItem.h
@@ -160,6 +169,7 @@ target_link_libraries(asteria-qt PRIVATE
Iconv::Iconv
Qt6::Xml
Qt6::Network
+ ${UCHARDET_LIB}
)
if(Qt6DBus_FOUND)
@@ -281,6 +291,10 @@ set(FB2_READER_SOURCES
${LAYOUT_SOURCES}
)
+set(TXT_READER_SOURCES
+ src/backend/formats/TxtReader.cpp
+)
+
# Testing
enable_testing()
@@ -291,6 +305,7 @@ function(add_asteria_test TEST_NAME TEST_SOURCE)
target_link_libraries(${TEST_NAME} PRIVATE
Qt6::Core
Qt6::Test
+ ${UCHARDET_LIB}
)
add_test(NAME ${TEST_NAME} COMMAND ${TEST_NAME})
endfunction()
@@ -349,7 +364,8 @@ add_asteria_test(FormatRegistryTest tests/FormatRegistryTest.cpp
src/backend/formats/EntryImageProvider.cpp
${COMIC_READER_SOURCES}
${EPUB_READER_SOURCES}
- ${FB2_READER_SOURCES})
+ ${FB2_READER_SOURCES}
+ ${TXT_READER_SOURCES})
target_link_libraries(FormatRegistryTest PRIVATE PkgConfig::MINIZIP PkgConfig::LIBARCHIVE Iconv::Iconv Qt6::Xml Qt6::Gui Qt6::Quick Qt6::Network)
set_tests_properties(FormatRegistryTest PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen")
@@ -363,7 +379,8 @@ add_asteria_test(ReadingModelTest tests/ReadingModelTest.cpp
src/backend/HistoryModel.cpp
${COMIC_SOURCES}
${EPUB_READER_SOURCES}
- ${FB2_READER_SOURCES})
+ ${FB2_READER_SOURCES}
+ ${TXT_READER_SOURCES})
target_link_libraries(ReadingModelTest PRIVATE Qt6::Gui Qt6::Concurrent Qt6::Quick PkgConfig::MINIZIP PkgConfig::LIBARCHIVE Iconv::Iconv Qt6::Xml Qt6::Network)
set_tests_properties(ReadingModelTest PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen")
@@ -378,7 +395,8 @@ add_asteria_test(TextLayoutEngineSpecTest tests/reading/TextLayoutEngineSpecTest
src/backend/HistoryModel.cpp
${COMIC_SOURCES}
${EPUB_READER_SOURCES}
- ${FB2_READER_SOURCES})
+ ${FB2_READER_SOURCES}
+ ${TXT_READER_SOURCES})
target_link_libraries(TextLayoutEngineSpecTest PRIVATE Qt6::Gui Qt6::Concurrent Qt6::Quick PkgConfig::MINIZIP PkgConfig::LIBARCHIVE Iconv::Iconv Qt6::Xml Qt6::Network)
set_tests_properties(TextLayoutEngineSpecTest PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen")
@@ -393,10 +411,20 @@ add_asteria_test(KnuthPlassRenderingSpecTest tests/reading/KnuthPlassRenderingSp
src/backend/HistoryModel.cpp
${COMIC_SOURCES}
${EPUB_READER_SOURCES}
- ${FB2_READER_SOURCES})
+ ${FB2_READER_SOURCES}
+ ${TXT_READER_SOURCES})
target_link_libraries(KnuthPlassRenderingSpecTest PRIVATE Qt6::Gui Qt6::Concurrent Qt6::Quick PkgConfig::MINIZIP PkgConfig::LIBARCHIVE Iconv::Iconv Qt6::Xml Qt6::Network)
set_tests_properties(KnuthPlassRenderingSpecTest PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen")
+add_asteria_test(TxtReaderTest tests/formats/TxtReaderTest.cpp
+ src/backend/formats/TxtReader.cpp
+ src/backend/formats/TextEncoding.cpp
+ src/backend/formats/HtmlEntities.cpp
+ src/backend/formats/ImageUrl.cpp
+ ${LAYOUT_SOURCES})
+target_link_libraries(TxtReaderTest PRIVATE Iconv::Iconv Qt6::Gui Qt6::Xml)
+set_tests_properties(TxtReaderTest PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen")
+
add_asteria_test(AppStateTest tests/AppStateTest.cpp
src/backend/AppState.cpp)
@@ -422,7 +450,8 @@ add_asteria_test(BookTest tests/book/BookTest.cpp
src/backend/NativeFileDialogService.cpp
${COMIC_SOURCES}
${EPUB_READER_SOURCES}
- ${FB2_READER_SOURCES})
+ ${FB2_READER_SOURCES}
+ ${TXT_READER_SOURCES})
target_link_libraries(BookTest PRIVATE Qt6::Concurrent Qt6::Widgets PkgConfig::MINIZIP PkgConfig::LIBARCHIVE Iconv::Iconv Qt6::Xml Qt6::Gui Qt6::Quick Qt6::Network)
set_tests_properties(BookTest PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen")
@@ -441,7 +470,8 @@ add_asteria_test(HistoryModelTest tests/HistoryModelTest.cpp
src/backend/formats/FormatRegistry.cpp
${COMIC_SOURCES}
${EPUB_READER_SOURCES}
- ${FB2_READER_SOURCES})
+ ${FB2_READER_SOURCES}
+ ${TXT_READER_SOURCES})
target_link_libraries(HistoryModelTest PRIVATE
Qt6::Concurrent Qt6::Quick Qt6::Gui Qt6::Xml Qt6::Network PkgConfig::MINIZIP PkgConfig::LIBARCHIVE Iconv::Iconv)
set_tests_properties(HistoryModelTest PROPERTIES ENVIRONMENT "QT_QPA_PLATFORM=offscreen")
diff --git a/src/backend/formats/FormatRegistry.cpp b/src/backend/formats/FormatRegistry.cpp
index ad3dc52..9704d58 100644
--- a/src/backend/formats/FormatRegistry.cpp
+++ b/src/backend/formats/FormatRegistry.cpp
@@ -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
#include
@@ -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(); },
+ nullptr
+ };
+}
+
FormatRegistry::FormatRegistry(QVector specs)
: m_specs(std::move(specs))
{
diff --git a/src/backend/formats/FormatRegistry.h b/src/backend/formats/FormatRegistry.h
index 4bd1f37..ed33014 100644
--- a/src/backend/formats/FormatRegistry.h
+++ b/src/backend/formats/FormatRegistry.h
@@ -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 {
diff --git a/src/backend/formats/TextEncoding.cpp b/src/backend/formats/TextEncoding.cpp
index 0205d5e..9106da0 100644
--- a/src/backend/formats/TextEncoding.cpp
+++ b/src/backend/formats/TextEncoding.cpp
@@ -6,10 +6,74 @@
#include
#include
+#ifdef HAS_UCHARDET
+#include
+#endif
+
+namespace {
+
+bool isValidUtf8(const QByteArray &bytes, bool &hasNonAscii)
+{
+ hasNonAscii = false;
+ const auto *data = reinterpret_cast(bytes.constData());
+ const int n = static_cast(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(bytes.size()), 32768);
+ for (int i = 0; i < sampleSize; ++i) {
+ const unsigned char b = static_cast(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);
diff --git a/src/backend/formats/TxtReader.cpp b/src/backend/formats/TxtReader.cpp
new file mode 100644
index 0000000..af93234
--- /dev/null
+++ b/src/backend/formats/TxtReader.cpp
@@ -0,0 +1,189 @@
+#include "TxtReader.h"
+
+#include
+#include
+#include
+#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(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(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(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 ¶Text) {
+ 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;
+}
diff --git a/src/backend/formats/TxtReader.h b/src/backend/formats/TxtReader.h
new file mode 100644
index 0000000..77cb168
--- /dev/null
+++ b/src/backend/formats/TxtReader.h
@@ -0,0 +1,37 @@
+#pragma once
+
+#include
+#include
+#include
+
+#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 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 m_chunks;
+};
diff --git a/src/main.cpp b/src/main.cpp
index dc77502..421a459 100644
--- a/src/main.cpp
+++ b/src/main.cpp
@@ -107,6 +107,7 @@ int main(int argc, char *argv[])
FormatSpec::fb2(QStringLiteral("fb2"), [] { return std::make_unique(); }),
FormatSpec::fb2(QStringLiteral("fbz"), [] { return std::make_unique(); }),
FormatSpec::fb2(QStringLiteral("fb2.zip"), [] { return std::make_unique(); }),
+ FormatSpec::txt(QStringLiteral("txt")),
});
HistoryModel historyModel(formatRegistry);
diff --git a/tests/FormatRegistryTest.cpp b/tests/FormatRegistryTest.cpp
index 7c8f9ec..f5ea29f 100644
--- a/tests/FormatRegistryTest.cpp
+++ b/tests/FormatRegistryTest.cpp
@@ -58,6 +58,18 @@ private slots:
QVERIFY(registry.createReader("file.EPUB") != nullptr);
}
+ void createTxtReader()
+ {
+ FormatRegistry registry({FormatSpec::txt()});
+ auto reader = registry.createReader("file.txt");
+ QVERIFY(reader != nullptr);
+ QCOMPARE(reader->mode(), ReadingMode::Text);
+
+ auto upperReader = registry.createReader("file.TXT");
+ QVERIFY(upperReader != nullptr);
+ QCOMPARE(upperReader->mode(), ReadingMode::Text);
+ }
+
void createUnknownFormat()
{
auto registry = makeRegistry();
diff --git a/tests/formats/TextEncodingTest.cpp b/tests/formats/TextEncodingTest.cpp
index a87fa56..d24bf7a 100644
--- a/tests/formats/TextEncodingTest.cpp
+++ b/tests/formats/TextEncodingTest.cpp
@@ -16,6 +16,7 @@ private slots:
void testDecodeWindows1251();
void testDecodeWithHint();
void testDecodeWithExplicitEncoding();
+ void testAutoDetectWindows1251();
};
void TextEncodingTest::testEmpty()
@@ -108,5 +109,17 @@ void TextEncodingTest::testDecodeWithExplicitEncoding()
QVERIFY(invalid.isEmpty());
}
+void TextEncodingTest::testAutoDetectWindows1251()
+{
+ // Russian text in windows-1251 without BOM or headers: "Версия для программистов"
+ const QByteArray win1251("\xC2\xE5\xF0\xF1\xE8\xFF\x20\xE4\xEB\xFF\x20\xEF\xF0\xEE\xE3\xF0\xE0\xEC\xEC\xE8\xF1\xF2\xEE\xE2");
+ const QString enc = TextEncoding::detectEncoding(win1251);
+ QCOMPARE(enc.toLower(), QStringLiteral("windows-1251"));
+
+ const QString result = TextEncoding::decode(win1251);
+ QCOMPARE(result, QString::fromUtf8("Версия для программистов"));
+ QVERIFY(!result.contains(QChar::ReplacementCharacter));
+}
+
QTEST_MAIN(TextEncodingTest)
#include "TextEncodingTest.moc"
diff --git a/tests/formats/TxtReaderTest.cpp b/tests/formats/TxtReaderTest.cpp
new file mode 100644
index 0000000..7715571
--- /dev/null
+++ b/tests/formats/TxtReaderTest.cpp
@@ -0,0 +1,360 @@
+#include
+#include
+#include
+#include
+#include
+#include
+
+#include "backend/formats/TxtReader.h"
+#include "backend/reading/layout/ChunkLayoutEngine.h"
+
+class TxtReaderTest : public QObject {
+ Q_OBJECT
+
+private slots:
+ void testOpenNonExistentFile();
+ void testOpenEmptyFile();
+ void testStandardBlankLineParagraphs();
+ void testSceneBreaks();
+ void testUnwrappedTextWithoutBlankLines();
+ void testGutenbergMetadataExtraction();
+ void testMetadataOnlyMode();
+ void testUtf8WithBom();
+ void testUtf16Le();
+ void testWindows1251WithoutBom();
+ void testElochkaFileIfExists();
+ void testBulbaFile();
+ void testLuideFile();
+ void testBondarFile();
+ void testArinFile();
+ void testTonkiyFile();
+};
+
+void TxtReaderTest::testOpenNonExistentFile()
+{
+ TxtReader reader;
+ QVERIFY(!reader.open(QStringLiteral("/path/to/nonexistent_file.txt")));
+ QVERIFY(!reader.lastError().isEmpty());
+}
+
+void TxtReaderTest::testOpenEmptyFile()
+{
+ QTemporaryFile tempFile;
+ QVERIFY(tempFile.open());
+ tempFile.close();
+
+ TxtReader reader;
+ QVERIFY(reader.open(tempFile.fileName()));
+ QCOMPARE(reader.mode(), ReadingMode::Text);
+ QVERIFY(reader.chunks().isEmpty());
+ QVERIFY(!reader.contentHash().isEmpty());
+}
+
+void TxtReaderTest::testStandardBlankLineParagraphs()
+{
+ QTemporaryFile tempFile;
+ QVERIFY(tempFile.open());
+
+ const QByteArray content =
+ "This is the first line of the story,\n"
+ "and this is the second line of the same paragraph.\n"
+ "\n"
+ "Here begins the second paragraph, which\n"
+ "also spans across multiple wrapped lines.\n";
+
+ tempFile.write(content);
+ tempFile.close();
+
+ TxtReader reader;
+ QVERIFY(reader.open(tempFile.fileName()));
+ const auto chunks = reader.chunks();
+ QVERIFY(!chunks.isEmpty());
+
+ // Count paragraphs across all chunks
+ int paragraphCount = 0;
+ for (const auto &chunk : chunks) {
+ for (const auto &block : chunk.blocks) {
+ if (block.kind == BlockItem::Kind::Paragraph) {
+ ++paragraphCount;
+ QCOMPARE(block.align, TextAlign::Justify);
+ QCOMPARE(block.textIndent, 32.0);
+ }
+ }
+ }
+ QCOMPARE(paragraphCount, 2);
+}
+
+void TxtReaderTest::testSceneBreaks()
+{
+ QTemporaryFile tempFile;
+ QVERIFY(tempFile.open());
+
+ const QByteArray content =
+ "First scene paragraph.\n"
+ "\n"
+ "\n"
+ "Second scene paragraph after double blank lines.\n";
+
+ tempFile.write(content);
+ tempFile.close();
+
+ TxtReader reader;
+ QVERIFY(reader.open(tempFile.fileName()));
+ const auto chunks = reader.chunks();
+ QVERIFY(!chunks.isEmpty());
+
+ bool foundSceneBreakContainer = false;
+ for (const auto &chunk : chunks) {
+ for (const auto &block : chunk.blocks) {
+ if (block.kind == BlockItem::Kind::ContainerStart) {
+ foundSceneBreakContainer = true;
+ }
+ }
+ }
+ QVERIFY(foundSceneBreakContainer);
+}
+
+void TxtReaderTest::testUnwrappedTextWithoutBlankLines()
+{
+ QTemporaryFile tempFile;
+ QVERIFY(tempFile.open());
+
+ const QByteArray content =
+ "Single line paragraph one.\n"
+ "Single line paragraph two.\n"
+ "Single line paragraph three.\n";
+
+ tempFile.write(content);
+ tempFile.close();
+
+ TxtReader reader;
+ QVERIFY(reader.open(tempFile.fileName()));
+ const auto chunks = reader.chunks();
+ QVERIFY(!chunks.isEmpty());
+
+ int paragraphCount = 0;
+ for (const auto &chunk : chunks) {
+ for (const auto &block : chunk.blocks) {
+ if (block.kind == BlockItem::Kind::Paragraph) {
+ ++paragraphCount;
+ }
+ }
+ }
+ QCOMPARE(paragraphCount, 3);
+}
+
+void TxtReaderTest::testGutenbergMetadataExtraction()
+{
+ QTemporaryFile tempFile;
+ QVERIFY(tempFile.open());
+
+ const QByteArray content =
+ "The Project Gutenberg eBook of Wonderland\n"
+ "\n"
+ "Title: Alice's Adventures in Wonderland\n"
+ "Author: Lewis Carroll\n"
+ "\n"
+ "CHAPTER I. Down the Rabbit-Hole\n";
+
+ tempFile.write(content);
+ tempFile.close();
+
+ TxtReader reader;
+ QVERIFY(reader.open(tempFile.fileName()));
+ QCOMPARE(reader.title(), QStringLiteral("Alice's Adventures in Wonderland"));
+ QCOMPARE(reader.author(), QStringLiteral("Lewis Carroll"));
+}
+
+void TxtReaderTest::testMetadataOnlyMode()
+{
+ QTemporaryFile tempFile;
+ QVERIFY(tempFile.open());
+
+ const QByteArray content =
+ "Title: Metamorphosis\n"
+ "Author: Franz Kafka\n"
+ "\n"
+ "One morning, when Gregor Samsa woke from troubled dreams...\n";
+
+ tempFile.write(content);
+ tempFile.close();
+
+ TxtReader reader;
+ QVERIFY(reader.loadMetadata(tempFile.fileName()));
+ QCOMPARE(reader.title(), QStringLiteral("Metamorphosis"));
+ QCOMPARE(reader.author(), QStringLiteral("Franz Kafka"));
+ QVERIFY(reader.chunks().isEmpty());
+ QVERIFY(!reader.contentHash().isEmpty());
+}
+
+void TxtReaderTest::testUtf8WithBom()
+{
+ QTemporaryFile tempFile;
+ QVERIFY(tempFile.open());
+
+ QByteArray content;
+ content.append("\xEF\xBB\xBF"); // UTF-8 BOM
+ content.append("Привет, мир!\n\nВторой абзац книги.\n");
+
+ tempFile.write(content);
+ tempFile.close();
+
+ TxtReader reader;
+ QVERIFY(reader.open(tempFile.fileName()));
+ const auto chunks = reader.chunks();
+ QVERIFY(!chunks.isEmpty());
+
+ QString firstParagraphText;
+ for (const auto &chunk : chunks) {
+ for (const auto &block : chunk.blocks) {
+ if (block.kind == BlockItem::Kind::Paragraph && !block.inlines.isEmpty()) {
+ firstParagraphText = block.inlines.first().text;
+ break;
+ }
+ }
+ if (!firstParagraphText.isEmpty()) break;
+ }
+ QCOMPARE(firstParagraphText, QString::fromUtf8("Привет, мир!"));
+}
+
+void TxtReaderTest::testUtf16Le()
+{
+ QTemporaryFile tempFile;
+ QVERIFY(tempFile.open());
+
+ const QString text = QStringLiteral("Hello in UTF-16LE.\n\nSecond paragraph.\n");
+ QByteArray content;
+ content.append("\xFF\xFE", 2); // UTF-16LE BOM
+ content.append(reinterpret_cast(text.utf16()), text.size() * sizeof(char16_t));
+
+ tempFile.write(content);
+ tempFile.close();
+
+ TxtReader reader;
+ QVERIFY(reader.open(tempFile.fileName()));
+ const auto chunks = reader.chunks();
+ QVERIFY(!chunks.isEmpty());
+
+ QString firstParagraphText;
+ for (const auto &chunk : chunks) {
+ for (const auto &block : chunk.blocks) {
+ if (block.kind == BlockItem::Kind::Paragraph && !block.inlines.isEmpty()) {
+ firstParagraphText = block.inlines.first().text;
+ break;
+ }
+ }
+ if (!firstParagraphText.isEmpty()) break;
+ }
+ QCOMPARE(firstParagraphText, QStringLiteral("Hello in UTF-16LE."));
+}
+
+void TxtReaderTest::testWindows1251WithoutBom()
+{
+ QTemporaryFile tempFile;
+ QVERIFY(tempFile.open());
+
+ // "Версия для программистов\n\nЛес.елочка.create();\n" in windows-1251
+ const QByteArray win1251 =
+ "\xC2\xE5\xF0\xF1\xE8\xFF\x20\xE4\xEB\xFF\x20\xEF\xF0\xEE\xE3\xF0\xE0\xEC\xEC\xE8\xF1\xF2\xEE\xE2\n\n"
+ "\xCB\xE5\xF1\x2E\xE5\xEB\xEE\xF7\xEA\xE0\x2E\x63\x72\x65\x61\x74\x65\x28\x29\x3B\n";
+
+ tempFile.write(win1251);
+ tempFile.close();
+
+ TxtReader reader;
+ QVERIFY(reader.open(tempFile.fileName()));
+ const auto chunks = reader.chunks();
+ QVERIFY(!chunks.isEmpty());
+
+ QString firstParagraphText;
+ for (const auto &chunk : chunks) {
+ for (const auto &block : chunk.blocks) {
+ if (block.kind == BlockItem::Kind::Paragraph && !block.inlines.isEmpty()) {
+ firstParagraphText = block.inlines.first().text;
+ break;
+ }
+ }
+ if (!firstParagraphText.isEmpty()) break;
+ }
+ QCOMPARE(firstParagraphText, QString::fromUtf8("Версия для программистов"));
+ QVERIFY(!firstParagraphText.contains(QChar::ReplacementCharacter));
+}
+
+void TxtReaderTest::testElochkaFileIfExists()
+{
+ const QString path = QStringLiteral("/Users/agel/OpenCloud/Personal/Books/elochka.txt");
+ if (!QFile::exists(path)) return;
+
+ TxtReader reader;
+ QVERIFY(reader.open(path));
+ const auto chunks = reader.chunks();
+ QVERIFY(!chunks.isEmpty());
+
+ QString firstParagraphText;
+ for (const auto &chunk : chunks) {
+ for (const auto &block : chunk.blocks) {
+ if (block.kind == BlockItem::Kind::Paragraph && !block.inlines.isEmpty()) {
+ firstParagraphText = block.inlines.first().text;
+ break;
+ }
+ }
+ if (!firstParagraphText.isEmpty()) break;
+ }
+ QCOMPARE(firstParagraphText, QString::fromUtf8("Версия для программистов"));
+ QVERIFY(!firstParagraphText.contains(QChar::ReplacementCharacter));
+}
+
+void TxtReaderTest::testBulbaFile()
+{
+ const QString path = QStringLiteral("/Users/agel/OpenCloud/Personal/Books/bulba nataliyaохотники за диковинками.txt");
+ if (!QFile::exists(path)) return;
+
+ TxtReader reader;
+ QVERIFY(!reader.open(path));
+ QVERIFY(reader.lastError().contains(QStringLiteral("corrupted, binary, or encrypted data")));
+}
+
+void TxtReaderTest::testLuideFile()
+{
+ const QString path = QStringLiteral("/Users/agel/OpenCloud/Personal/Books/Луиде записки практикующего адвоката.txt");
+ if (!QFile::exists(path)) return;
+
+ TxtReader reader;
+ QVERIFY(!reader.open(path));
+ QVERIFY(reader.lastError().contains(QStringLiteral("corrupted, binary, or encrypted data")));
+}
+
+void TxtReaderTest::testBondarFile()
+{
+ const QString path = QStringLiteral("/Users/agel/OpenCloud/Personal/Books/бондарь ирина последний дракон.txt");
+ if (!QFile::exists(path)) return;
+
+ TxtReader reader;
+ QVERIFY(!reader.open(path));
+ QVERIFY(reader.lastError().contains(QStringLiteral("corrupted, binary, or encrypted data")));
+}
+
+void TxtReaderTest::testArinFile()
+{
+ const QString path = QStringLiteral("/Users/agel/OpenCloud/Personal/Books/арин когда сила в твоей крови.txt");
+ if (!QFile::exists(path)) return;
+
+ TxtReader reader;
+ QVERIFY(reader.open(path));
+ QVERIFY(!reader.chunks().isEmpty());
+ QVERIFY(!reader.title().isEmpty());
+}
+
+void TxtReaderTest::testTonkiyFile()
+{
+ const QString path = QStringLiteral("/Users/agel/OpenCloud/Personal/Books/Тонкий японистский юмор.txt");
+ if (!QFile::exists(path)) return;
+
+ TxtReader reader;
+ QVERIFY(reader.open(path));
+ QVERIFY(!reader.chunks().isEmpty());
+ QVERIFY(!reader.title().isEmpty());
+}
+
+QTEST_MAIN(TxtReaderTest)
+#include "TxtReaderTest.moc"