From 0221eb08bc7b0a58a110cc7a942159afa755aeec Mon Sep 17 00:00:00 2001 From: Kitsune Ral Date: Thu, 18 Jan 2018 08:51:29 +0900 Subject: Move links pretty-printing code from Quaternion to lib This code is useful for all clients, and extensions to pretty-printing can be later added either via making prettyPrint() virtual or even by providing a registry of additional "text transformers" or even "event content renderers" applied to visualise the event. --- room.cpp | 43 +++++++++++++++++++++++++++++++++++++++++++ room.h | 5 +++++ 2 files changed, 48 insertions(+) diff --git a/room.cpp b/room.cpp index 3481f684..f8640573 100644 --- a/room.cpp +++ b/room.cpp @@ -43,6 +43,7 @@ #include #include #include +#include #include #include @@ -490,6 +491,48 @@ FileTransferInfo Room::fileTransferInfo(const QString& id) const #endif } +static const auto RegExpOptions = + QRegularExpression::CaseInsensitiveOption + | QRegularExpression::OptimizeOnFirstUsageOption + | QRegularExpression::UseUnicodePropertiesOption; + +// regexp is originally taken from Konsole (https://github.com/KDE/konsole) +// full url: +// protocolname:// or www. followed by anything other than whitespaces, +// <, >, ' or ", and ends before whitespaces, <, >, ', ", ], !, ), :, +// comma or dot +// Note: outer parentheses are a part of C++ raw string delimiters, not of +// the regex (see http://en.cppreference.com/w/cpp/language/string_literal). +static const QRegularExpression FullUrlRegExp(QStringLiteral( + R"(((www\.(?!\.)|[a-z][a-z0-9+.-]*://)(&(?![lg]t;)|[^&\s<>'"])+(&(?![lg]t;)|[^&!,.\s<>'"\]):])))" + ), RegExpOptions); +// email address: +// [word chars, dots or dashes]@[word chars, dots or dashes].[word chars] +static const QRegularExpression EmailAddressRegExp(QStringLiteral( + R"((mailto:)?(\b(\w|\.|-)+@(\w|\.|-)+\.\w+\b))" + ), RegExpOptions); + +/** Converts all that looks like a URL into HTML links */ +static void linkifyUrls(QString& htmlEscapedText) +{ + // NOTE: htmlEscapedText is already HTML-escaped (no literal <,>,&)! + + htmlEscapedText.replace(EmailAddressRegExp, + QStringLiteral(R"(\1\2)")); + htmlEscapedText.replace(FullUrlRegExp, + QStringLiteral(R"(\1")")); +} + +QString Room::prettyPrint(const QString& plainText) const +{ + auto pt = QStringLiteral("") + + plainText.toHtmlEscaped() + QStringLiteral(""); + pt.replace('\n', "
"); + + linkifyUrls(pt); + return pt; +} + QList< User* > Room::usersTyping() const { return d->usersTyping; diff --git a/room.h b/room.h index f5bf0839..ac540fea 100644 --- a/room.h +++ b/room.h @@ -192,6 +192,11 @@ namespace QMatrixClient Q_INVOKABLE FileTransferInfo fileTransferInfo(const QString& id) const; + /** Pretty-prints plain text into HTML + * This includes HTML escaping of <,>,",& and URLs linkification. + */ + QString prettyPrint(const QString& plainText) const; + MemberSorter memberSorter() const; QJsonObject toJson() const; -- cgit v1.2.3