1
0
mirror of https://github.com/qTox/qTox.git synced 2024-03-22 14:00:36 +08:00

refactor: improved HTML-formatting mechanism for text messages

Added class provides text font formatting with HTML font tags
Supported stuff:
  - nested formatting;
  - several text pieces formatted with the same formatting style at the
    one message;
  - styling applies only if non-whitespace symbol follows opening
    formatting symbol and also non-whitespace symbol preceds closing
    symbol;
  - only multiline code font formatting supports new line inside of
    message text.
Also fix #3804
This commit is contained in:
noavarice 2017-02-06 18:20:45 +03:00
parent 60e5375ef7
commit 5047a65e11
6 changed files with 160 additions and 69 deletions

View File

@ -188,6 +188,8 @@ set(${PROJECT_NAME}_SOURCES
src/chatlog/documentcache.h
src/chatlog/pixmapcache.cpp
src/chatlog/pixmapcache.h
src/chatlog/textformatter.cpp
src/chatlog/textformatter.h
src/core/coreav.cpp
src/core/coreav.h
src/core/core.cpp

View File

@ -436,6 +436,7 @@ HEADERS += \
src/chatlog/customtextdocument.h \
src/chatlog/documentcache.h \
src/chatlog/pixmapcache.h \
src/chatlog/textformatter.h \
src/core/core.h \
src/core/coreav.h \
src/core/coredefines.h \
@ -554,6 +555,7 @@ SOURCES += \
src/chatlog/customtextdocument.cpp\
src/chatlog/documentcache.cpp \
src/chatlog/pixmapcache.cpp \
src/chatlog/textformatter.cpp \
src/core/core.cpp \
src/core/coreav.cpp \
src/core/corefile.cpp \

View File

@ -19,6 +19,7 @@
#include "chatmessage.h"
#include "chatlinecontentproxy.h"
#include "textformatter.h"
#include "content/text.h"
#include "content/timestamp.h"
#include "content/spinner.h"
@ -56,8 +57,12 @@ ChatMessage::Ptr ChatMessage::createChatMessage(const QString &sender, const QSt
text = detectQuotes(detectAnchors(text), type);
//text styling
if (Settings::getInstance().getStylePreference() != Settings::StyleType::NONE)
text = detectStyle(text);
auto styleType = Settings::getInstance().getStylePreference();
if (styleType != Settings::StyleType::NONE) {
TextFormatter tf = TextFormatter(text);
text = tf.applyStyling(styleType == Settings::StyleType::WITHOUT_CHARS);
}
switch(type)
{
@ -199,71 +204,6 @@ void ChatMessage::hideDate()
c->hide();
}
QString ChatMessage::detectStyle(const QString &str)
{
QString out = str;
// Create regex for text styling syntax
QRegExp exp("(\\*)([^\\*]{2,})(\\*)" // Bold *text*
"|(\\*\\*)([^\\*\\*]{2,})(\\*\\*)" // Bold **text**
"|(\\/)([^\\/]{2,})(\\/)" // Italics /text/
"|(\\/\\/)([^\\/\\/]{2,})(\\/\\/)" // Italics //text//
"|(\\_)([^\\_]{2,})(\\_)" // Underline _text_
"|(\\_\\_)([^\\_\\_]{2,})(\\_\\_)" // Underline __text__
"|(\\~)([^\\~]{2,})(\\~)" // Strike ~text~
"|(\\~\\~)([^\\~\\~]{2,})(\\~\\~)" // Strike ~~text~~
"|(\\`)([^\\`]{2,})(\\`)" // Codeblock `text`
"|(\\`\\`\\`)([^\\`\\`\\`]{2,})(\\`\\`\\`)" // Codeblock ```\ntext\n```
);
int offset = 0;
while ((offset = exp.indexIn(out, offset)) != -1)
{
QString snipCheck = out.mid(offset-1,exp.cap(0).length()+2);
QString snippet = exp.cap(0).trimmed();
QString htmledSnippet;
// Only parse if surrounded by spaces, newline(s) and/or beginning/end of line
if ((snipCheck.startsWith(' ') || snipCheck.startsWith('>') || offset == 0)
&& ((snipCheck.endsWith(' ') || snipCheck.endsWith('<')) || offset + snippet.length() == out.length()))
{
int mul = 0; // Determines how many characters to strip from text
// Set mul depending on styleownPreference
if (Settings::getInstance().getStylePreference() == Settings::StyleType::WITHOUT_CHARS)
mul = 2;
// Match captured string to corresponding style format
if (exp.cap(1) == "*" && snippet.length() > 2) // Bold *text*
htmledSnippet = QString("<b>%1</b>").arg(snippet.mid(mul/2,snippet.length()-mul));
else if (exp.cap(4) == "**" && snippet.length() > 4) // Bold **text**
htmledSnippet = QString("<b>%1</b>").arg(snippet.mid(mul,snippet.length()-2*mul));
else if (exp.cap(7) == "/" && snippet.length() > 2) // Italics /text/
htmledSnippet = QString("<i>%1</i>").arg(snippet.mid(mul/2,snippet.length()-mul));
else if (exp.cap(10) == "//" && snippet.length() > 4) // Italics //text//
htmledSnippet = QString("<i>%1</i>").arg(snippet.mid(mul,snippet.length()-2*mul));
else if (exp.cap(13) == "_"&& snippet.length() > 2) // Underline _text_
htmledSnippet = QString("<u>%1</u>").arg(snippet.mid(mul/2,snippet.length()-mul));
else if (exp.cap(16) == "__" && snippet.length() > 4) // Underline __text__
htmledSnippet = QString("<u>%1</u>").arg(snippet.mid(mul,snippet.length()-2*mul));
else if (exp.cap(19) == "~" && snippet.length() > 2) // Strike ~text~
htmledSnippet = QString("<s>%1</s>").arg(snippet.mid(mul/2,snippet.length()-mul));
else if (exp.cap(22) == "~~" && snippet.length() > 4) // Strike ~~text~~
htmledSnippet = QString("<s>%1</s>").arg(snippet.mid(mul,snippet.length()-2*mul));
else if (exp.cap(25) == "`" && snippet.length() > 2) // Codeblock `text`
htmledSnippet = QString("<font color=#595959><code>%1</code></font>").arg(snippet.mid(mul/2,snippet.length()-mul));
else if (exp.cap(28) == "```" && snippet.length() > 6) // Codeblock ```text```
htmledSnippet = QString("<font color=#595959><code>%1</code></font>").arg(snippet.mid(4*mul,snippet.length()-8*mul));
else
htmledSnippet = snippet;
out.replace(offset, exp.cap().length(), htmledSnippet);
offset += htmledSnippet.length();
} else
offset += snippet.length();
}
return out;
}
QString ChatMessage::detectAnchors(const QString &str)
{
QString out = str;
@ -324,7 +264,7 @@ QString ChatMessage::detectQuotes(const QString& str, MessageType type)
}
if (i < messageLines.size() - 1)
quotedText += "<br/>";
quotedText += '\n';
}
return quotedText;

View File

@ -61,7 +61,6 @@ public:
void hideDate();
protected:
static QString detectStyle(const QString& str);
static QString detectAnchors(const QString& str);
static QString detectQuotes(const QString& str, MessageType type);
static QString wrapDiv(const QString& str, const QString& div);

View File

@ -0,0 +1,124 @@
#include "textformatter.h"
#include <QMap>
#include <QPair>
#include <QRegularExpression>
#include <QVector>
enum TextStyle {
BOLD = 0,
ITALIC,
UNDERLINE,
STRIKE,
CODE
};
static const QString SINGLE_SIGN_FORMATTING_TEXT_FONT_PATTERN = QStringLiteral("(?:(^|[^\\%1]))(\\%1[^\\s\\%1])([^\\%1\\n]+)([^\\s\\%1]\\%1)(?:($|[^\\%1]))");
//Pattern for escaping slashes from inserted HTML tags
static const QString SINGLE_SLASH_FORMATTING_TEXT_FONT_PATTERN = QStringLiteral("(?:(^|[^/<]))(\\/[^\\s/])([^\\n/]+)([^<\\s/]\\/)(?:($|[^/]))");
static const QString DOUBLE_SIGN_FORMATTING_TEXT_FONT_PATTERN = QStringLiteral("(?:(^|[^\\%1]))([\\%1]{2}[^\\s\\%1])([^\\n]+)([^\\s\\%1][\\%1]{2})(?:($|[^\\%1]))");
static const QString MULTILINE_CODE_FORMATTING_TEXT_FONT_PATTERN = QStringLiteral("(?:(^|[^`]))([`]{3})((\\n|.)+)([`]{3})(?:($|[^`]))");
// Items in vector associated with TextStyle values respectively. Do NOT change this order
static const QVector<QString> fontStylePatterns {
QStringLiteral("<b>%1</b>"),
QStringLiteral("<i>%1</i>"),
QStringLiteral("<u>%1</u>"),
QStringLiteral("<s>%1</s>"),
QStringLiteral("<font color=#595959><code>%1</code></font>")
};
// Unfortunately, can't use simple QMap because ordered applying of styles is required
static const QVector<QPair<QRegularExpression, QString>> textPatternStyle {
{ QRegularExpression(SINGLE_SLASH_FORMATTING_TEXT_FONT_PATTERN), fontStylePatterns[ITALIC] },
{ QRegularExpression(SINGLE_SIGN_FORMATTING_TEXT_FONT_PATTERN.arg('*')), fontStylePatterns[BOLD] },
{ QRegularExpression(SINGLE_SIGN_FORMATTING_TEXT_FONT_PATTERN.arg('_')), fontStylePatterns[UNDERLINE] },
{ QRegularExpression(SINGLE_SIGN_FORMATTING_TEXT_FONT_PATTERN.arg('~')), fontStylePatterns[STRIKE] },
{ QRegularExpression(SINGLE_SIGN_FORMATTING_TEXT_FONT_PATTERN.arg('`')), fontStylePatterns[CODE] },
{ QRegularExpression(DOUBLE_SIGN_FORMATTING_TEXT_FONT_PATTERN.arg('*')), fontStylePatterns[BOLD] },
{ QRegularExpression(DOUBLE_SIGN_FORMATTING_TEXT_FONT_PATTERN.arg('/')), fontStylePatterns[ITALIC] },
{ QRegularExpression(DOUBLE_SIGN_FORMATTING_TEXT_FONT_PATTERN.arg('_')), fontStylePatterns[UNDERLINE] },
{ QRegularExpression(DOUBLE_SIGN_FORMATTING_TEXT_FONT_PATTERN.arg('~')), fontStylePatterns[STRIKE] },
{ QRegularExpression(MULTILINE_CODE_FORMATTING_TEXT_FONT_PATTERN), fontStylePatterns[CODE] }
};
TextFormatter::TextFormatter(const QString &str)
: sourceString(str) {}
/**
* @brief TextFormatter::patternEscapeSignsCount Counts equal symbols at the beginning of the string
* @param str Source string
* @return Amount of equal symbols at the beginning of the string
*/
int TextFormatter::patternEscapeSignsCount(const QString &str) {
QChar escapeSign = str.at(0);
int result = 0;
for (const QChar c : str) {
if (c == escapeSign)
++result;
else
break;
}
return result;
}
/**
* @brief TextFormatter::getCapturedLength Get length of string captured by subexpression with appropriate checks
* @param match Global match of QRegularExpression
* @param exprNumber Number of subexpression
* @return Length of captured string. If nothing was captured, returns 0
*/
int TextFormatter::getCapturedLength(const QRegularExpressionMatch &match, const int exprNumber) {
QString captured = match.captured(exprNumber);
return captured.isNull() || captured.isEmpty() ? 0 : captured.length();
}
/**
* @brief TextFormatter::applyHtmlFontStyling Applies styles to the font of text that was passed to the constructor
* @param dontShowFormattingSymbols True, if it does not suppose to include formatting symbols into resulting string
* @return Source text with styled font
*/
QString TextFormatter::applyHtmlFontStyling(bool dontShowFormattingSymbols){
QString out = sourceString;
int choppingSignsCountMultiplier = dontShowFormattingSymbols ? 0 : 1;
for (QPair<QRegularExpression, QString> pair : textPatternStyle) {
QRegularExpression exp = pair.first;
QRegularExpressionMatchIterator matchesIterator = exp.globalMatch(out);
int insertedTagSymbolsCount = 0;
while (matchesIterator.hasNext()) {
QRegularExpressionMatch match = matchesIterator.next();
// Regular expressions may capture one redundant symbol from both sides because of extra check, so we don't need to handle them
int firstCheckResultLength = getCapturedLength(match, 1);
int matchStart = match.capturedStart() + firstCheckResultLength + insertedTagSymbolsCount;
int matchLength = match.capturedLength() - firstCheckResultLength - getCapturedLength(match, exp.captureCount());
int choppingSignsCount = patternEscapeSignsCount(out.mid(matchStart, matchLength));
int textStart = matchStart + choppingSignsCount;
int textLength = matchLength - choppingSignsCount * 2;
QString styledText = pair.second.arg(out.mid(textStart, textLength));
textStart = matchStart + choppingSignsCount * choppingSignsCountMultiplier;
textLength = matchLength - choppingSignsCount * choppingSignsCountMultiplier * 2;
out.replace(textStart, textLength, styledText);
insertedTagSymbolsCount += pair.second.length() - 2 - choppingSignsCount * (1 - choppingSignsCountMultiplier) * 2;
}
}
return out;
}
/**
* @brief TextFormatter::applyStyling Applies all styling for the text
* @param dontShowFormattingSymbols True, if it does not suppose to include formatting symbols into resulting string
* @return Styled string
*/
QString TextFormatter::applyStyling(bool dontShowFormattingSymbols) {
return applyHtmlFontStyling(dontShowFormattingSymbols);
}

View File

@ -0,0 +1,24 @@
#ifndef TEXTFORMATTER_H
#define TEXTFORMATTER_H
#include <QString>
class TextFormatter
{
private:
QString sourceString;
int patternEscapeSignsCount(const QString& str);
int getCapturedLength(const QRegularExpressionMatch& match, const int exprNumber);
QString applyHtmlFontStyling(bool dontShowFormattingSymbols);
public:
explicit TextFormatter(const QString& str);
QString applyStyling(bool dontShowFormattingSymbols);
};
#endif // TEXTFORMATTER_H