#include #include "previewgeneratorplaintext.h" #include "previewresultplaintext.h" QString PreviewGeneratorPlainText::generatePreviewText(QString content, RenderConfig config, QString fileName) { QString resulText = ""; QMap snippet; int coveredRange = -1; int lastWordPos = -1; QHash countmap; unsigned int currentSnippets = 0; for(QString &word : config.wordsToHighlight) { int lastPos = 0; int index = content.indexOf(word, lastPos, Qt::CaseInsensitive); while(index != -1 && currentSnippets < MAX_SNIPPETS) { countmap[word] = countmap.value(word, 0) + 1; if(index >= lastWordPos && index <= coveredRange) { break; } int begin = index - 50; if(begin < 0) { begin = 0; } int after = index + 50; if(after > content.size()) { after = content.size(); } snippet[index] = "...
" + content.mid(begin, after) + "...
"; coveredRange = after; lastPos = index; index = content.indexOf(word, lastPos + 1, Qt::CaseInsensitive); ++currentSnippets; } lastWordPos = lastPos; } auto i = snippet.constBegin(); while(i != snippet.constEnd()) { resulText.append(i.value()); ++i; } QString header = "" + fileName + " "; for(QString &word : config.wordsToHighlight) { resulText.replace(word, "" + word + "", Qt::CaseInsensitive); header += word + ": " + QString::number(countmap[word]) + " "; } if(currentSnippets == MAX_SNIPPETS) { header += "(truncated)"; } header += "
"; return header + resulText.replace("\n", "
").mid(0, 1000); } QSharedPointer PreviewGeneratorPlainText::generate(RenderConfig config, QString documentPath, unsigned int page) { PreviewResultPlainText *result = new PreviewResultPlainText(documentPath, page); QFile file(documentPath); if(!file.open(QFile::ReadOnly | QFile::Text)) { return QSharedPointer(result); } QTextStream in(&file); QString content = in.readAll(); QFileInfo info{documentPath}; result->setText(generatePreviewText(content, config, info.fileName())); return QSharedPointer(result); }