Files
asteria-qt/src/backend/formats/TxtReader.cpp
T

219 lines
5.5 KiB
C++

#include "TxtReader.h"
#include <QCryptographicHash>
#include <QFileInfo>
#include <QRegularExpression>
#include <QTextStream>
#include <uchardet/uchardet.h>
#include <iconv.h>
static constexpr int kChunkSize = 4096;
static QString decodeWithIconv(const QByteArray &raw, const char *charset)
{
iconv_t cd = iconv_open("UTF-8", charset);
if (cd == reinterpret_cast<iconv_t>(-1))
return {};
// Worst case: each byte becomes 4 UTF-8 bytes
QByteArray out(raw.size() * 4, '\0');
char *inBuf = const_cast<char *>(raw.constData());
size_t inLeft = raw.size();
char *outBuf = out.data();
size_t outLeft = out.size();
size_t result = iconv(cd, &inBuf, &inLeft, &outBuf, &outLeft);
iconv_close(cd);
if (result == static_cast<size_t>(-1))
return {};
out.resize(out.size() - outLeft);
return QString::fromUtf8(out);
}
// Convert a raw text fragment into HTML paragraphs.
// Splits on blank lines (\n\n+) to create <p> blocks;
// single newlines within a block become <br>.
static QString textToHtml(const QString &text)
{
QString html;
const QStringList blocks = text.split(QRegularExpression("\\n\\n+"));
for (const QString &block : blocks) {
QString escaped = block.toHtmlEscaped().trimmed();
if (escaped.isEmpty())
continue;
escaped.replace('\n', QStringLiteral("<br>\n"));
html += QStringLiteral("<p>") + escaped + QStringLiteral("</p>\n");
}
return html;
}
// Split raw text into chunks of approximately kChunkSize characters,
// preferring to split at \n boundaries, falling back to whitespace.
static QStringList splitRawText(const QString &content)
{
QStringList rawChunks;
int pos = 0;
const int len = content.size();
while (pos < len) {
if (len - pos <= kChunkSize) {
rawChunks.append(content.mid(pos));
break;
}
int end = pos + kChunkSize;
// Look backward for a newline to split at
int splitAt = -1;
for (int i = end; i > pos; --i) {
if (content.at(i) == '\n') {
splitAt = i + 1; // include the newline in the current chunk
break;
}
}
// No newline found — fall back to whitespace
if (splitAt < 0) {
for (int i = end; i > pos; --i) {
if (content.at(i).isSpace()) {
splitAt = i + 1;
break;
}
}
}
// No whitespace either — hard split
if (splitAt < 0)
splitAt = end;
rawChunks.append(content.mid(pos, splitAt - pos));
pos = splitAt;
}
return rawChunks;
}
bool TxtReader::open(const QString &filePath)
{
QFile file(filePath);
if (!file.exists()) {
m_error = QStringLiteral("File not found: ") + filePath;
return false;
}
if (!file.open(QIODevice::ReadOnly)) {
m_error = QStringLiteral("Cannot open file: ") + file.errorString();
return false;
}
QByteArray raw = file.readAll();
file.close();
m_contentHash = QCryptographicHash::hash(raw, QCryptographicHash::Md5);
uchardet_t ud = uchardet_new();
if (uchardet_handle_data(ud, raw.constData(), raw.size()) == 0) {
uchardet_data_end(ud);
const char *charset = uchardet_get_charset(ud);
if (charset && charset[0] != '\0') {
auto qtEncoding = QStringConverter::encodingForName(charset);
if (qtEncoding) {
QTextStream stream(raw);
stream.setEncoding(qtEncoding.value());
m_content = stream.readAll();
} else {
m_content = decodeWithIconv(raw, charset);
}
uchardet_delete(ud);
if (!m_content.isEmpty()) {
m_title = QFileInfo(filePath).completeBaseName();
m_filePath = filePath;
return true;
}
}
}
uchardet_delete(ud);
// Default: UTF-8
m_content = QString::fromUtf8(raw);
m_title = QFileInfo(filePath).completeBaseName();
m_filePath = filePath;
return true;
}
bool TxtReader::loadMetadata(const QString &filePath)
{
QFile file(filePath);
if (!file.exists()) {
m_error = QStringLiteral("File not found: ") + filePath;
return false;
}
// For TXT files, we only need the filename for title
m_title = QFileInfo(filePath).completeBaseName();
m_author.clear(); // No author info in plain text files
return true;
}
QString TxtReader::lastError()
{
return m_error;
}
int TxtReader::chapterCount()
{
return m_content.isEmpty() ? 0 : 1;
}
Chapter TxtReader::loadChapter(int index)
{
if (index != 0 || m_content.isEmpty())
return Chapter{index, {}, {}};
QStringList rawChunks = splitRawText(m_content);
QStringList htmlChunks;
htmlChunks.reserve(rawChunks.size());
for (const QString &raw : rawChunks) {
QString html = textToHtml(raw);
if (!html.isEmpty())
htmlChunks.append(html);
}
return Chapter{0, m_title, htmlChunks};
}
QList<TocEntry> TxtReader::tableOfContents()
{
return {};
}
QString TxtReader::filePath()
{
return m_filePath;
}
QString TxtReader::title()
{
return m_title;
}
QString TxtReader::author()
{
return {};
}
QString TxtReader::coverImagePath()
{
return {};
}
QByteArray TxtReader::contentHash()
{
return m_contentHash;
}
QString TxtReader::fileType() const { return QStringLiteral("txt"); }