| 1 | /* Copyright (C) 2016 - 2017 Dan Chapman <[email protected]> |
| 2 | |
| 3 | This file is part of Dekko email client for Ubuntu devices |
| 4 | |
| 5 | This program is free software; you can redistribute it and/or |
| 6 | modify it under the terms of the GNU General Public License as |
| 7 | published by the Free Software Foundation; either version 2 of |
| 8 | the License or (at your option) version 3 |
| 9 | |
| 10 | This program is distributed in the hope that it will be useful, |
| 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 13 | GNU General Public License for more details. |
| 14 | |
| 15 | You should have received a copy of the GNU General Public License |
| 16 | along with this program. If not, see <http://www.gnu.org/licenses/>. |
| 17 | */ |
| 18 | #include "Formatting.h" |
| 19 | #include <QDebug> |
| 20 | #include <QStack> |
| 21 | #include <QPair> |
| 22 | #include <QColor> |
| 23 | #include <QPalette> |
| 24 | #include <QStringList> |
| 25 | #include <QTextDocument> |
| 26 | #include <QDir> |
| 27 | #include <QFontInfo> |
| 28 | #include <QRegularExpression> |
| 29 | #include <QRegularExpressionMatch> |
| 30 | #include <QRegularExpressionMatchIterator> |
| 31 | |
| 32 | #define SIGNATURE_SPERATOR -2 |
| 33 | |
| 34 | const QString Formatting::Regex::hyperlink = QStringLiteral("(https?://(?:[;/?:@=$\\-_.+!',0-9a-zA-Z%#~\\[\\]\\(\\)\\*]|&)+(?:[/@=$\\-_+'0-9a-zA-Z%#~]|&))"); |
| 35 | const QString Formatting::Regex::email = QStringLiteral("((?:[a-zA-Z0-9_\\.!#$%'\\*\\+\\-/=?^`\\{|\\}~]|&)+@[a-zA-Z0-9\\.\\-_]+)"); |
| 36 | const QString Formatting::Regex::bold = QStringLiteral("((^|[\\s\\(\\[\\{])\\*((?!\\*)\\S+)\\*($|[\\s\\),;.\\]\\}]))"); |
| 37 | const QString Formatting::Regex::italic = QStringLiteral("((^|[\\s\\(\\[\\{])/((?!/)\\S+)/($|[\\s\\),;.\\]\\}]))"); |
| 38 | const QString Formatting::Regex::underline = QStringLiteral("((^|[\\s\\(\\[\\{])_((?!_)\\S+)_($|[\\s\\),;.\\]\\}]))"); |
| 39 | // We want this to be an exact match so we have to stick the regex between anchoring expression ^(regex)$ |
| 40 | const QString Formatting::Regex::signatureSeperator = QStringLiteral("^(-- |_{45,})(\\r)?$"); |
| 41 | const QString Formatting::Regex::quotePlain = QStringLiteral("^( >|>)+"); |
| 42 | const QString Formatting::Regex::quoteFlowed = QStringLiteral("^>+"); |
| 43 | |
| 44 | struct TextInfo { |
| 45 | int depth; |
| 46 | QString text; |
| 47 | TextInfo(const int depth, const QString &text): depth(depth), text(text){} |
| 48 | }; |
| 49 | |
| 50 | // ptext-2-html passes |
| 51 | namespace { |
| 52 | static QString lineWithoutTrailingCr(const QString &line) { |
| 53 | return line.endsWith(QLatin1Char('\r')) ? line.left(line.size() - 1) : line; |
| 54 | } |
| 55 | |
| 56 | static QRegularExpression quoteMarks(const FlowedFormat &format) { |
| 57 | return QRegularExpression(format == FlowedFormat::Plain ? |
| 58 | Formatting::Regex::quotePlain : |
| 59 | Formatting::Regex::quoteFlowed); |
| 60 | } |
| 61 | |
| 62 | static QString firstNLines(const QString &input, int numLines, const int charsPerLine) |
| 63 | { |
| 64 | Q_ASSERT(numLines >= 2); |
| 65 | QString out = input.section(QLatin1Char('\n'), 0, numLines - 1, QString::SectionSkipEmpty); |
| 66 | const int cutoff = numLines * charsPerLine; |
| 67 | if (out.size() >= cutoff) { |
| 68 | int pos = input.indexOf(QLatin1Char(' '), cutoff); |
| 69 | if (pos != -1) |
| 70 | return out.left(pos - 1); |
| 71 | } |
| 72 | return out; |
| 73 | } |
| 74 | |
| 75 | static void firstPass(std::vector<TextInfo> &buffer, QStringList &lines, bool &sigSeen, const FlowedFormat &format) |
| 76 | { |
| 77 | |
| 78 | static QRegularExpression sig(Formatting::Regex::signatureSeperator); |
| 79 | |
| 80 | Q_FOREACH(const QString &line, lines) { |
| 81 | |
| 82 | if (line.isEmpty()) { |
| 83 | buffer.emplace_back(0, line); |
| 84 | continue; |
| 85 | } |
| 86 | |
| 87 | if (sig.match(line, 0).hasMatch()) { |
| 88 | buffer.emplace_back(SIGNATURE_SPERATOR, lineWithoutTrailingCr(line)); |
| 89 | sigSeen = true; |
| 90 | continue; |
| 91 | } |
| 92 | |
| 93 | int ql = 0; |
| 94 | QRegularExpressionMatch match = quoteMarks(format).match(line); |
| 95 | if (!sigSeen && match.hasMatch() && match.capturedStart() == 0) { |
| 96 | ql = match.captured(0).count(QStringLiteral(">")); |
| 97 | } |
| 98 | buffer.emplace_back(ql, lineWithoutTrailingCr(line)); |
| 99 | } |
| 100 | } |
| 101 | |
| 102 | static void secondPass(std::vector<TextInfo> &buffer, const FlowedFormat &format) |
| 103 | { |
| 104 | auto it = buffer.begin(); |
| 105 | while (it < buffer.end() && it->depth != SIGNATURE_SPERATOR) { |
| 106 | it->text.remove(quoteMarks(format)); |
| 107 | |
| 108 | switch(format) { |
| 109 | case FlowedFormat::Flowed: |
| 110 | case FlowedFormat::Flowed_Delsp: |
| 111 | { |
| 112 | if (it->text.startsWith(QLatin1Char(' '))) { |
| 113 | it->text.remove(0, 1); |
| 114 | } |
| 115 | |
| 116 | // quirk: fix a flowed line which actually isn't flowed |
| 117 | if (it->text.endsWith(QLatin1Char(' ')) && ( |
| 118 | it+1 == buffer.end() || // end-of-document |
| 119 | (it+1)->depth == SIGNATURE_SPERATOR || // right in front of the separator |
| 120 | (it+1)->depth != it->depth // end of paragraph |
| 121 | )) { |
| 122 | it->text.chop(1); |
| 123 | } |
| 124 | break; |
| 125 | |
| 126 | } |
| 127 | case FlowedFormat::Plain: |
| 128 | { |
| 129 | if (it->depth > 0 && it->text.startsWith(QLatin1Char(' '))) { |
| 130 | // Because the space is re-added when we prepend the quotes. Adding that space is done |
| 131 | // in order to make it look nice, i.e. to prevent lines like ">>something". |
| 132 | it->text.remove(0, 1); |
| 133 | } |
| 134 | break; |
| 135 | } |
| 136 | } |
| 137 | |
| 138 | if (it == buffer.begin()) { |
| 139 | // No "previous line" |
| 140 | ++it; |
| 141 | continue; |
| 142 | } |
| 143 | // Check for the line joining |
| 144 | auto prev = it - 1; |
| 145 | if (prev->depth == it->depth) { |
| 146 | |
| 147 | QString separator = QStringLiteral("\n"); |
| 148 | switch (format) { |
| 149 | case FlowedFormat::Plain: |
| 150 | // nothing fancy to do here, we cannot really join lines |
| 151 | break; |
| 152 | case FlowedFormat::Flowed: |
| 153 | case FlowedFormat::Flowed_Delsp: |
| 154 | // CR LF trailing is stripped already (LFs by the split into lines, CRs by lineWithoutTrailingCr in pass #1), |
| 155 | // so we only have to check for the trailing space |
| 156 | if (prev->text.endsWith(QLatin1Char(' '))) { |
| 157 | |
| 158 | // implement the DelSp thingy |
| 159 | if (format == FlowedFormat::Flowed_Delsp) { |
| 160 | prev->text.chop(1); |
| 161 | } |
| 162 | |
| 163 | if (it->text.isEmpty() || prev->text.isEmpty()) { |
| 164 | // This one or the previous line is a blank one, so we cannot really join them |
| 165 | } else { |
| 166 | separator = QString(); |
| 167 | } |
| 168 | } |
| 169 | break; |
| 170 | } |
| 171 | prev->text += separator + it->text; |
| 172 | it = buffer.erase(it); |
| 173 | } else { |
| 174 | ++it; |
| 175 | } |
| 176 | } |
| 177 | } |
| 178 | |
| 179 | static QString finalPass(std::vector<TextInfo> &lineBuffer) |
| 180 | { |
| 181 | bool signatureSeparatorSeen = false; |
| 182 | int quoteLevel = 0; |
| 183 | QStringList markup; |
| 184 | int interactiveControlsId = 0; |
| 185 | QStack<QPair<int,int> > controlStack; |
| 186 | auto closeQuotesUpTo = [](QStringList &markup, QStack<QPair<int, int> > &controlStack, int "eLevel, const int finalQuoteLevel) |
| 187 | { |
| 188 | static QString closingLabel(QStringLiteral("<label for=\"q%1\"></label>")); |
| 189 | static QLatin1String closeSingleQuote("</blockquote>"); |
| 190 | static QLatin1String closeQuoteBlock("</span></span>"); |
| 191 | |
| 192 | Q_ASSERT(quoteLevel >= finalQuoteLevel); |
| 193 | |
| 194 | while (quoteLevel > finalQuoteLevel) { |
| 195 | // Check whether an interactive control element is supposed to be present here |
| 196 | bool controlBlock = !controlStack.isEmpty() && (quoteLevel == controlStack.top().first); |
| 197 | if (controlBlock) { |
| 198 | markup << closingLabel.arg(controlStack.pop().second); |
| 199 | } |
| 200 | markup << closeSingleQuote; |
| 201 | --quoteLevel; |
| 202 | if (controlBlock) { |
| 203 | markup << closeQuoteBlock; |
| 204 | } |
| 205 | } |
| 206 | }; |
| 207 | for (auto it = lineBuffer.begin(); it != lineBuffer.end(); ++it) { |
| 208 | |
| 209 | if (it->depth == SIGNATURE_SPERATOR && !signatureSeparatorSeen) { |
| 210 | // The first signature separator |
| 211 | signatureSeparatorSeen = true; |
| 212 | closeQuotesUpTo(markup, controlStack, quoteLevel, 0); |
| 213 | markup << QStringLiteral("<span class=\"signature\">") + Formatting::singleLinePlainTextToHtml(it->text); |
| 214 | markup << QStringLiteral("\n"); |
| 215 | continue; |
| 216 | } |
| 217 | |
| 218 | if (signatureSeparatorSeen) { |
| 219 | // Just copy the data |
| 220 | markup << Formatting::singleLinePlainTextToHtml(it->text); |
| 221 | if (it+1 != lineBuffer.end()) |
| 222 | markup << QStringLiteral("\n"); |
| 223 | continue; |
| 224 | } |
| 225 | |
| 226 | Q_ASSERT(quoteLevel == 0 || quoteLevel != it->depth); |
| 227 | |
| 228 | if (quoteLevel > it->depth) { |
| 229 | // going back in the quote hierarchy |
| 230 | closeQuotesUpTo(markup, controlStack, quoteLevel, it->depth); |
| 231 | } |
| 232 | |
| 233 | // Pretty-formatted block of the ">>>" characters |
| 234 | QString quotemarks; |
| 235 | |
| 236 | if (it->depth) { |
| 237 | quotemarks += QLatin1String("<span class=\"quotemarks\">"); |
| 238 | for (int i = 0; i < it->depth; ++i) { |
| 239 | quotemarks += QLatin1String(">"); |
| 240 | } |
| 241 | quotemarks += QLatin1String(" </span>"); |
| 242 | } |
| 243 | |
| 244 | static const int previewLines = 5; |
| 245 | static const int charsPerLineEquivalent = 160; |
| 246 | static const int forceCollapseAfterLines = 10; |
| 247 | |
| 248 | if (quoteLevel < it->depth) { |
| 249 | // We're going deeper in the quote hierarchy |
| 250 | QString line; |
| 251 | while (quoteLevel < it->depth) { |
| 252 | ++quoteLevel; |
| 253 | |
| 254 | // Check whether there is anything at the newly entered level of nesting |
| 255 | bool anythingOnJustThisLevel = false; |
| 256 | |
| 257 | // A short summary of the quotation |
| 258 | QString preview; |
| 259 | |
| 260 | auto runner = it; |
| 261 | while (runner != lineBuffer.end()) { |
| 262 | if (runner->depth == quoteLevel) { |
| 263 | anythingOnJustThisLevel = true; |
| 264 | |
| 265 | ++interactiveControlsId; |
| 266 | controlStack.push(qMakePair(quoteLevel, interactiveControlsId)); |
| 267 | |
| 268 | QString omittedStuff; |
| 269 | QString previewPrefix, previewSuffix; |
| 270 | QString currentChunk = firstNLines(runner->text, previewLines, charsPerLineEquivalent); |
| 271 | QString omittedPrefix, omittedSuffix; |
| 272 | QString previewQuotemarks; |
| 273 | |
| 274 | if (runner != it ) { |
| 275 | // we have skipped something, make it obvious to the user |
| 276 | |
| 277 | // Find the closest level which got collapsed |
| 278 | int closestDepth = std::numeric_limits<int>::max(); |
| 279 | auto depthRunner(it); |
| 280 | while (depthRunner != runner) { |
| 281 | closestDepth = std::min(closestDepth, depthRunner->depth); |
| 282 | ++depthRunner; |
| 283 | } |
| 284 | |
| 285 | // The [...] marks shall be prefixed by the closestDepth quote markers |
| 286 | omittedStuff = QStringLiteral("<span class=\"quotemarks\">"); |
| 287 | for (int i = 0; i < closestDepth; ++i) { |
| 288 | omittedStuff += QLatin1String(">"); |
| 289 | } |
| 290 | for (int i = runner->depth; i < closestDepth; ++i) { |
| 291 | omittedPrefix += QLatin1String("<blockquote>"); |
| 292 | omittedSuffix += QLatin1String("</blockquote>"); |
| 293 | } |
| 294 | omittedStuff += QStringLiteral(" </span><label for=\"q%1\">...</label>").arg(interactiveControlsId); |
| 295 | |
| 296 | // Now produce the proper quotation for the preview itself |
| 297 | for (int i = quoteLevel; i < runner->depth; ++i) { |
| 298 | previewPrefix.append(QLatin1String("<blockquote>")); |
| 299 | previewSuffix.append(QLatin1String("</blockquote>")); |
| 300 | } |
| 301 | } |
| 302 | |
| 303 | previewQuotemarks = QStringLiteral("<span class=\"quotemarks\">"); |
| 304 | for (int i = 0; i < runner->depth; ++i) { |
| 305 | previewQuotemarks += QLatin1String(">"); |
| 306 | } |
| 307 | previewQuotemarks += QLatin1String(" </span>"); |
| 308 | |
| 309 | preview = previewPrefix |
| 310 | + omittedPrefix + omittedStuff + omittedSuffix |
| 311 | + previewQuotemarks |
| 312 | + Formatting::singleLinePlainTextToHtml(currentChunk) |
| 313 | .replace(QLatin1String("\n"), QStringLiteral("\n") + previewQuotemarks) |
| 314 | + previewSuffix; |
| 315 | |
| 316 | break; |
| 317 | } |
| 318 | if (runner->depth < quoteLevel) { |
| 319 | // This means that we have left the current level of nesting, so there cannot possible be anything else |
| 320 | // at the current level of nesting *and* in the current quote block |
| 321 | break; |
| 322 | } |
| 323 | ++runner; |
| 324 | } |
| 325 | |
| 326 | // Is there nothing but quotes until the end of mail or until the signature separator? |
| 327 | bool nothingButQuotesAndSpaceTillSignature = true; |
| 328 | runner = it; |
| 329 | while (++runner != lineBuffer.end()) { |
| 330 | if (runner->depth == SIGNATURE_SPERATOR) |
| 331 | break; |
| 332 | if (runner->depth > 0) |
| 333 | continue; |
| 334 | if (runner->depth == 0 && !runner->text.isEmpty()) { |
| 335 | nothingButQuotesAndSpaceTillSignature = false; |
| 336 | break; |
| 337 | } |
| 338 | } |
| 339 | |
| 340 | // Size of the current level, including the nested stuff |
| 341 | int currentLevelCharCount = 0; |
| 342 | int currentLevelLineCount = 0; |
| 343 | runner = it; |
| 344 | while (runner != lineBuffer.end() && runner->depth >= quoteLevel) { |
| 345 | currentLevelCharCount += runner->text.size(); |
| 346 | // one for the actual block |
| 347 | currentLevelLineCount += runner->text.count(QLatin1Char('\n')) + 1; |
| 348 | ++runner; |
| 349 | } |
| 350 | |
| 351 | |
| 352 | if (!anythingOnJustThisLevel) { |
| 353 | // no need for fancy UI controls |
| 354 | line += QLatin1String("<blockquote>"); |
| 355 | continue; |
| 356 | } |
| 357 | |
| 358 | if (quoteLevel == it->depth |
| 359 | && currentLevelCharCount <= charsPerLineEquivalent * previewLines |
| 360 | && currentLevelLineCount <= previewLines) { |
| 361 | // special case: the quote is very short, no point in making it collapsible |
| 362 | line += QStringLiteral("<span class=\"level\"><input type=\"checkbox\" id=\"q%1\"/>").arg(interactiveControlsId) |
| 363 | + QStringLiteral("<span class=\"shortquote\"><blockquote>") + quotemarks |
| 364 | + Formatting::singleLinePlainTextToHtml(it->text).replace(QLatin1String("\n"), QStringLiteral("\n") + quotemarks); |
| 365 | } else { |
| 366 | bool collapsed = nothingButQuotesAndSpaceTillSignature |
| 367 | || quoteLevel > 1 |
| 368 | || currentLevelCharCount >= charsPerLineEquivalent * forceCollapseAfterLines |
| 369 | || currentLevelLineCount >= forceCollapseAfterLines; |
| 370 | |
| 371 | line += QStringLiteral("<span class=\"level\"><input type=\"checkbox\" id=\"q%1\" %2/>") |
| 372 | .arg(QString::number(interactiveControlsId), |
| 373 | collapsed ? QStringLiteral("checked=\"checked\"") : QString()) |
| 374 | + QStringLiteral("<span class=\"short\"><blockquote>") |
| 375 | + preview |
| 376 | + QStringLiteral(" <label for=\"q%1\">...</label>").arg(interactiveControlsId) |
| 377 | + QStringLiteral("</blockquote></span>") |
| 378 | + QStringLiteral("<span class=\"full\"><blockquote>"); |
| 379 | if (quoteLevel == it->depth) { |
| 380 | // We're now finally on the correct level of nesting so we can output the current line |
| 381 | line += quotemarks + Formatting::singleLinePlainTextToHtml(it->text) |
| 382 | .replace(QLatin1String("\n"), QStringLiteral("\n") + quotemarks); |
| 383 | } |
| 384 | } |
| 385 | } |
| 386 | markup << line; |
| 387 | } else { |
| 388 | // Either no quotation or we're continuing an old quote block and there was a nested quotation before |
| 389 | markup << quotemarks + Formatting::singleLinePlainTextToHtml(it->text) |
| 390 | .replace(QLatin1String("\n"), QStringLiteral("\n") + quotemarks); |
| 391 | } |
| 392 | |
| 393 | auto next = it + 1; |
| 394 | if (next != lineBuffer.end()) { |
| 395 | if (next->depth >= 0 && next->depth < it->depth) { |
| 396 | // Decreasing the quotation level -> no starting <blockquote> |
| 397 | markup << QStringLiteral("\n"); |
| 398 | } else if (it->depth == 0) { |
| 399 | // Non-quoted block which is not enclosed in a <blockquote> |
| 400 | markup << QStringLiteral("\n"); |
| 401 | } |
| 402 | } |
| 403 | } |
| 404 | |
| 405 | if (signatureSeparatorSeen) { |
| 406 | // Terminate the signature |
| 407 | markup << QStringLiteral("</span>"); |
| 408 | } |
| 409 | |
| 410 | if (quoteLevel) { |
| 411 | // Terminate the quotes |
| 412 | closeQuotesUpTo(markup, controlStack, quoteLevel, 0); |
| 413 | } |
| 414 | |
| 415 | Q_ASSERT(controlStack.isEmpty()); |
| 416 | |
| 417 | return markup.join(QString()); |
| 418 | } |
| 419 | |
| 420 | } |
| 421 | |
| 422 | QString Formatting::singleLinePlainTextToHtml(QString line) |
| 423 | { |
| 424 | line = line.toHtmlEscaped(); |
| 425 | |
| 426 | auto htmlifyLink = [](QString &line, const QString &link) { |
| 427 | // qDebug() << "Link: " << link; |
| 428 | QString urlreplace(QStringLiteral("<a href=%1>%1</a>").arg(link)); |
| 429 | line.replace(link, urlreplace); |
| 430 | }; |
| 431 | |
| 432 | auto htmlifyEmail = [](QString &line, const QString &mail) { |
| 433 | // qDebug() << "Mailto: " << mail; |
| 434 | QString urlreplace(QStringLiteral("<a href=\"mailto:%1\">%1</a>").arg(mail)); |
| 435 | line.replace(mail, urlreplace); |
| 436 | }; |
| 437 | |
| 438 | auto htmlifySpecials = [](QString &line, const QString &value, const QString &tag) { |
| 439 | // qDebug() << "Specials: " << value << tag; |
| 440 | QString urlreplace(QStringLiteral("<%1>%2</%1>").arg(tag, value)); |
| 441 | line.replace(value, urlreplace); |
| 442 | }; |
| 443 | |
| 444 | auto regexToStringList = [](QString &line, const QString ®ex) -> QStringList { |
| 445 | QRegularExpression rx(regex); |
| 446 | QRegularExpressionMatchIterator it = rx.globalMatch(line); |
| 447 | QStringList result; |
| 448 | while (it.hasNext()) { |
| 449 | QRegularExpressionMatch match = it.next(); |
| 450 | result << match.captured(1).trimmed(); |
| 451 | } |
| 452 | return result; |
| 453 | }; |
| 454 | |
| 455 | // hyperlinks first |
| 456 | foreach(auto link, regexToStringList(line, Formatting::Regex::hyperlink)) { htmlifyLink(line, link); } |
| 457 | // mailto's |
| 458 | foreach(auto email, regexToStringList(line, Formatting::Regex::email)) { htmlifyEmail(line, email); } |
| 459 | // bold's |
| 460 | foreach(auto bold, regexToStringList(line, Formatting::Regex::bold)) { htmlifySpecials(line, bold, QStringLiteral("strong")); } |
| 461 | // italic's |
| 462 | foreach(auto italic, regexToStringList(line, Formatting::Regex::italic)) { htmlifySpecials(line, italic, QStringLiteral("emp")); } |
| 463 | // underscore's |
| 464 | foreach(auto underscore, regexToStringList(line, Formatting::Regex::underline)) { htmlifySpecials(line, underscore, QStringLiteral("u")); } |
| 465 | |
| 466 | return line; |
| 467 | } |
| 468 | |
| 469 | QString Formatting::plainTextToHtml(const QString &text) |
| 470 | { |
| 471 | auto lines = text.split('\n'); |
| 472 | std::vector<TextInfo> lineBuffer; |
| 473 | lineBuffer.reserve(lines.size()); |
| 474 | bool signatureSeen = false; |
| 475 | firstPass(lineBuffer, lines, signatureSeen, FlowedFormat::Plain); // TODO: add format arg. |
| 476 | secondPass(lineBuffer, FlowedFormat::Plain); |
| 477 | return finalPass(lineBuffer); |
| 478 | } |
| 479 | #include "Paths.h" |
| 480 | QString Formatting::markupPlainTextToHtml(const QString &text) |
| 481 | { |
| 482 | static const QString defaultStyle = QString::fromUtf8( |
| 483 | "pre{word-wrap: break-word; white-space: pre-wrap;}" |
| 484 | // The following line, sadly, produces a warning "QFont::setPixelSize: Pixel size <= 0 (0)". |
| 485 | // However, if it is not in place or if the font size is set higher, even to 0.1px, WebKit reserves space for the |
| 486 | // quotation characters and therefore a weird white area appears. Even width: 0px doesn't help, so it looks like |
| 487 | // we will have to live with this warning for the time being. |
| 488 | ".quotemarks{color:transparent;font-size:0px;}" |
| 489 | |
| 490 | // Cannot really use the :dir(rtl) selector for putting the quote indicator to the "correct" side. |
| 491 | // It's CSS4 and it isn't supported yet. |
| 492 | "blockquote{margin: 0 0 0 .8ex; border-left: 1px #ccc solid; unicode-bidi: -webkit-plaintext; padding-left:1ex}" |
| 493 | |
| 494 | // Stop the font size from getting smaller after reaching two levels of quotes |
| 495 | // (ie. starting on the third level, don't make the size any smaller than what it already is) |
| 496 | "blockquote blockquote blockquote {}" |
| 497 | ".signature{opacity: 0.6;}" |
| 498 | |
| 499 | // Dynamic quote collapsing via pure CSS, yay |
| 500 | "input {display: none}" |
| 501 | "input ~ span.full {display: block}" |
| 502 | "input ~ span.short {display: none}" |
| 503 | "input:checked ~ span.full {display: block}" |
| 504 | "input:checked ~ span.short {display: none}" |
| 505 | "label {display: none; border: 1px solid %2; border-radius: 5px; padding: 0px 4px 0px 4px; white-space: nowrap}" |
| 506 | // BLACK UP-POINTING SMALL TRIANGLE (U+25B4) |
| 507 | // BLACK DOWN-POINTING SMALL TRIANGLE (U+25BE) |
| 508 | "span.full > blockquote > label:before {content: \"\u25b4\"}" |
| 509 | "span.short > blockquote > label:after {content: \" \u25be\"}" |
| 510 | "span.shortquote > blockquote > label {display: none}" |
| 511 | ); |
| 512 | |
| 513 | |
| 514 | QPalette palette = QGuiApplication::palette(); |
| 515 | QString textColors = QString::fromUtf8("body { color: #5D5D5D; font-family: Ubuntu !important; font-size: 1.1rem; weight: light }" |
| 516 | "a:link { color: #19b6ee } a:visited { color: #19b6ee } a:hover { color: #19b6ee }"); |
| 517 | // looks like there's no special color for hovered links in Qt |
| 518 | |
| 519 | // build stylesheet and html header |
| 520 | QColor tintForQuoteIndicator = palette.base().color(); |
| 521 | tintForQuoteIndicator.setAlpha(0x66); |
| 522 | static QString stylesheet = defaultStyle + textColors; |
| 523 | static QFile file(Paths::configLocationForFile(QStringLiteral("message.css"))); |
| 524 | static QDateTime lastVersion; |
| 525 | QDateTime lastTouched(file.exists() ? QFileInfo(file).lastModified() : QDateTime()); |
| 526 | if (lastVersion < lastTouched) { |
| 527 | stylesheet = defaultStyle; |
| 528 | if (file.open(QIODevice::ReadOnly | QIODevice::Text)) { |
| 529 | const QString userSheet = QString::fromLocal8Bit(file.readAll().data()); |
| 530 | lastVersion = lastTouched; |
| 531 | stylesheet += "\n" + userSheet; |
| 532 | file.close(); |
| 533 | } |
| 534 | } |
| 535 | |
| 536 | // The dir="auto" is required for WebKit to treat all paragraphs as entities with possibly different text direction. |
| 537 | // The individual paragraphs unfortunately share the same text alignment, though, as per |
| 538 | // https://bugs.webkit.org/show_bug.cgi?id=71194 (fixed in Blink already). |
| 539 | QString htmlHeader("<!DOCTYPE html><html><head><meta name=\"description\" content=\"plaintext\"><style type=\"text/css\"><!--" /*+ textColors + fontSpecification*/ + stylesheet + |
| 540 | "--></style></head><body><pre dir=\"auto\">"); |
| 541 | static QString htmlFooter(QStringLiteral("\n</pre></body></html>")); |
| 542 | |
| 543 | QString markup = Formatting::plainTextToHtml(text); |
| 544 | // and finally set the marked up page. |
| 545 | return htmlHeader + markup + htmlFooter; |
| 546 | } |
| 547 | |
| 548 | // pinched from trojita/Composer/PlainTextFormatter.cpp and modified to use QRegularExpression |
| 549 | QStringList Formatting::quoteBody(QStringList bodyLines) |
| 550 | { |
| 551 | QStringList quote; |
| 552 | for (QStringList::iterator line = bodyLines.begin(); line != bodyLines.end(); ++line) { |
| 553 | if (Formatting::Regex::sigSeperator().exactMatch(*line)) { |
| 554 | // we've hit the top level signature. In Dekko we don't include this |
| 555 | // but other clients do... but they will be nested in > quote blocks so that's fine and we |
| 556 | // will just work with that. |
| 557 | break; |
| 558 | } |
| 559 | // rewrap - we need to keep the quotes at < 79 chars, yet the grow with every level |
| 560 | if (line->length() < 79-2) { |
| 561 | // this line is short enough, prepend quote mark and continue |
| 562 | if (line->isEmpty() || line->at(0) == '>') |
| 563 | line->prepend(">"); |
| 564 | else |
| 565 | line->prepend("> "); |
| 566 | quote << *line; |
| 567 | continue; |
| 568 | } |
| 569 | // long line -> needs to be wrapped |
| 570 | // 1st, detect the quote depth and eventually stript the quotes from the line |
| 571 | int quoteLevel = 0; |
| 572 | int contentStart = 0; |
| 573 | if (line->at(0) == '>') { |
| 574 | quoteLevel = 1; |
| 575 | while (quoteLevel < line->length() && line->at(quoteLevel) == '>') |
| 576 | ++quoteLevel; |
| 577 | contentStart = quoteLevel; |
| 578 | if (quoteLevel < line->length() && line->at(quoteLevel) == ' ') |
| 579 | ++contentStart; |
| 580 | } |
| 581 | |
| 582 | // 2nd, build a quote string |
| 583 | QString quotemarks; |
| 584 | for (int i = 0; i < quoteLevel; ++i) |
| 585 | quotemarks += QLatin1String(">"); |
| 586 | quotemarks += QLatin1String("> "); |
| 587 | |
| 588 | // 3rd, wrap the line, prepend the quotemarks to each line and add it to the quote text |
| 589 | int space(contentStart), lastSpace(contentStart), pos(contentStart), length(0); |
| 590 | while (pos < line->length()) { |
| 591 | if (line->at(pos) == ' ') |
| 592 | space = pos+1; |
| 593 | ++length; |
| 594 | if (length > 65-quotemarks.length() && space != lastSpace) { |
| 595 | // wrap |
| 596 | quote << quotemarks + line->mid(lastSpace, space - lastSpace); |
| 597 | lastSpace = space; |
| 598 | length = pos - space; |
| 599 | } |
| 600 | ++pos; |
| 601 | } |
| 602 | quote << quotemarks + line->mid(lastSpace); |
| 603 | } |
| 604 | return quote; |
| 605 | } |
| 606 | |
| 607 | QString Formatting::mangleReplySubject(const QString &subject) |
| 608 | { |
| 609 | // These operations should *not* check for internationalized variants of "Re"; these are evil. |
| 610 | |
| 611 | #define RE_PREFIX_RE "(?:(?:Re:\\s*)*)" |
| 612 | #define RE_PREFIX_ML "(?:(\\[[^\\]]+\\]\\s*)?)" |
| 613 | |
| 614 | static QRegExp rePrefixMatcher(QLatin1String("^" |
| 615 | RE_PREFIX_RE // a sequence of "Re: " prefixes |
| 616 | RE_PREFIX_ML // something like a mailing list prefix |
| 617 | RE_PREFIX_RE // a sequence of "Re: " prefixes |
| 618 | ), Qt::CaseInsensitive); |
| 619 | rePrefixMatcher.setPatternSyntax(QRegExp::RegExp2); |
| 620 | QLatin1String correctedPrefix("Re: "); |
| 621 | |
| 622 | if (rePrefixMatcher.indexIn(subject) == -1) { |
| 623 | // Our regular expression has failed, so better play it safe and blindly prepend "Re: " |
| 624 | return correctedPrefix + subject; |
| 625 | } else { |
| 626 | QStringList listPrefixes; |
| 627 | int pos = 0; |
| 628 | int oldPos = 0; |
| 629 | while ((pos = rePrefixMatcher.indexIn(subject, pos, QRegExp::CaretAtOffset)) != -1) { |
| 630 | if (rePrefixMatcher.matchedLength() == 0) |
| 631 | break; |
| 632 | pos += rePrefixMatcher.matchedLength(); |
| 633 | if (!listPrefixes.contains(rePrefixMatcher.cap(1))) |
| 634 | listPrefixes << rePrefixMatcher.cap(1); |
| 635 | oldPos = pos; |
| 636 | } |
| 637 | |
| 638 | QString mlPrefix = listPrefixes.join(QString()).trimmed(); |
| 639 | QString baseSubject = subject.mid(oldPos + qMax(0, rePrefixMatcher.matchedLength())); |
| 640 | |
| 641 | if (!mlPrefix.isEmpty() && !baseSubject.isEmpty()) |
| 642 | mlPrefix += QLatin1Char(' '); |
| 643 | |
| 644 | return correctedPrefix + mlPrefix + baseSubject; |
| 645 | } |
| 646 | } |
| 647 | |
| 648 | QString Formatting::mangleForwardSubject(const QString &subject) |
| 649 | { |
| 650 | QLatin1String forwardPrefix("Fwd: "); |
| 651 | return forwardPrefix + subject; |
| 652 | } |
| 653 | |
| 654 | |
| 655 | QRegExp Formatting::Regex::sigSeperator() |
| 656 | { |
| 657 | // "-- " is the standards-compliant signature separator. |
| 658 | // "Line of underscores" is non-standard garbage which Mailman happily generates. Yes, it's nasty and ugly. |
| 659 | return QRegExp(QLatin1String("(-- |_{45,})(\\r)?")); |
| 660 | } |