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

refactor: message text formatting works better now

- tag intersection detected
- variables and constants' names became shorter
This commit is contained in:
noavarice 2017-02-19 17:48:44 +03:00
parent 445ba28e7b
commit 87f219a78f
6 changed files with 207 additions and 86 deletions

View File

@ -57,10 +57,11 @@ ChatMessage::Ptr ChatMessage::createChatMessage(const QString &sender, const QSt
text = detectQuotes(detectAnchors(text), type); text = detectQuotes(detectAnchors(text), type);
//text styling //text styling
auto styleType = Settings::getInstance().getStylePreference(); Settings::StyleType styleType = Settings::getInstance().getStylePreference();
if (styleType != Settings::StyleType::NONE) { if (styleType != Settings::StyleType::NONE)
{
TextFormatter tf = TextFormatter(text); TextFormatter tf = TextFormatter(text);
text = tf.applyStyling(styleType == Settings::StyleType::WITHOUT_CHARS); text = tf.applyStyling(styleType == Settings::StyleType::WITH_CHARS);
} }
@ -254,17 +255,22 @@ QString ChatMessage::detectQuotes(const QString& str, MessageType type)
// don't quote first line in action message. This makes co-existence of // don't quote first line in action message. This makes co-existence of
// quotes and action messages possible, since only first line can cause // quotes and action messages possible, since only first line can cause
// problems in case where there is quote in it used. // problems in case where there is quote in it used.
if (QRegExp("^(>|).*").exactMatch(messageLines[i])) { if (QRegExp("^(>|).*").exactMatch(messageLines[i]))
{
if (i > 0 || type != ACTION) if (i > 0 || type != ACTION)
quotedText += "<span class=quote>" + messageLines[i] + "</span>"; quotedText += "<span class=quote>" + messageLines[i] + "</span>";
else else
quotedText += messageLines[i]; quotedText += messageLines[i];
} else { }
else
{
quotedText += messageLines[i]; quotedText += messageLines[i];
} }
if (i < messageLines.size() - 1) if (i < messageLines.size() - 1)
{
quotedText += '\n'; quotedText += '\n';
}
} }
return quotedText; return quotedText;

View File

@ -1,3 +1,22 @@
/*
Copyright © 2017 by The qTox Project Contributors
This file is part of qTox, a Qt-based graphical interface for Tox.
qTox is libre software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
qTox is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with qTox. If not, see <http://www.gnu.org/licenses/>.
*/
#include "textformatter.h" #include "textformatter.h"
#include <QMap> #include <QMap>
@ -13,17 +32,25 @@ enum TextStyle {
CODE CODE
}; };
static const QString SINGLE_SIGN_FORMATTING_TEXT_FONT_PATTERN = QStringLiteral("(?:(^|[^\\%1]))(\\%1[^\\s\\%1])([^\\%1\\n]+)([^\\s\\%1]\\%1)(?:($|[^\\%1]))"); static const QString COMMON_PATTERN = QStringLiteral("(?<=^|[^%1<])"
"[%1]{%3}"
"(?![%1 \\n])"
".+?"
"(?<![%1< \\n])"
"[%1]{%3}"
"(?=$|[^%1])");
//Pattern for escaping slashes from inserted HTML tags static const QString MULTILINE_CODE = QStringLiteral("(?<=^|[^`])"
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]))"); "(.|\\n)+"
"(?<!`)"
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 // Items in vector associated with TextStyle values respectively. Do NOT change this order
static const QVector<QString> fontStylePatterns { static const QVector<QString> fontStylePatterns
{
QStringLiteral("<b>%1</b>"), QStringLiteral("<b>%1</b>"),
QStringLiteral("<i>%1</i>"), QStringLiteral("<i>%1</i>"),
QStringLiteral("<u>%1</u>"), QStringLiteral("<u>%1</u>"),
@ -32,93 +59,110 @@ static const QVector<QString> fontStylePatterns {
}; };
// Unfortunately, can't use simple QMap because ordered applying of styles is required // Unfortunately, can't use simple QMap because ordered applying of styles is required
static const QVector<QPair<QRegularExpression, QString>> textPatternStyle { 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(COMMON_PATTERN.arg("*", "1")), fontStylePatterns[BOLD] },
{ QRegularExpression(SINGLE_SIGN_FORMATTING_TEXT_FONT_PATTERN.arg('_')), fontStylePatterns[UNDERLINE] }, { QRegularExpression(COMMON_PATTERN.arg("/", "1")), fontStylePatterns[ITALIC] },
{ QRegularExpression(SINGLE_SIGN_FORMATTING_TEXT_FONT_PATTERN.arg('~')), fontStylePatterns[STRIKE] }, { QRegularExpression(COMMON_PATTERN.arg("_", "1")), fontStylePatterns[UNDERLINE] },
{ QRegularExpression(SINGLE_SIGN_FORMATTING_TEXT_FONT_PATTERN.arg('`')), fontStylePatterns[CODE] }, { QRegularExpression(COMMON_PATTERN.arg("~", "1")), fontStylePatterns[STRIKE] },
{ QRegularExpression(DOUBLE_SIGN_FORMATTING_TEXT_FONT_PATTERN.arg('*')), fontStylePatterns[BOLD] }, { QRegularExpression(COMMON_PATTERN.arg("`", "1")), fontStylePatterns[CODE] },
{ QRegularExpression(DOUBLE_SIGN_FORMATTING_TEXT_FONT_PATTERN.arg('/')), fontStylePatterns[ITALIC] }, { QRegularExpression(COMMON_PATTERN.arg("*", "2")), fontStylePatterns[BOLD] },
{ QRegularExpression(DOUBLE_SIGN_FORMATTING_TEXT_FONT_PATTERN.arg('_')), fontStylePatterns[UNDERLINE] }, { QRegularExpression(COMMON_PATTERN.arg("/", "2")), fontStylePatterns[ITALIC] },
{ QRegularExpression(DOUBLE_SIGN_FORMATTING_TEXT_FONT_PATTERN.arg('~')), fontStylePatterns[STRIKE] }, { QRegularExpression(COMMON_PATTERN.arg("_", "2")), fontStylePatterns[UNDERLINE] },
{ QRegularExpression(MULTILINE_CODE_FORMATTING_TEXT_FONT_PATTERN), fontStylePatterns[CODE] } { QRegularExpression(COMMON_PATTERN.arg("~", "2")), fontStylePatterns[STRIKE] },
{ QRegularExpression(MULTILINE_CODE), fontStylePatterns[CODE] }
}; };
TextFormatter::TextFormatter(const QString &str) TextFormatter::TextFormatter(const QString &str)
: sourceString(str) {} : sourceString(str)
{
}
/** /**
* @brief TextFormatter::patternEscapeSignsCount Counts equal symbols at the beginning of the string * @brief Counts equal symbols at the beginning of the string
* @param str Source string * @param str Source string
* @return Amount of equal symbols at the beginning of the string * @return Amount of equal symbols at the beginning of the string
*/ */
int TextFormatter::patternEscapeSignsCount(const QString &str) { static int patternSignsCount(const QString& str)
{
QChar escapeSign = str.at(0); QChar escapeSign = str.at(0);
int result = 0; int result = 0;
for (const QChar c : str) { int length = str.length();
if (c == escapeSign) while (result < length && str[result] == escapeSign)
++result; {
else ++result;
break;
} }
return result; return result;
} }
/** /**
* @brief TextFormatter::getCapturedLength Get length of string captured by subexpression with appropriate checks * @brief Checks HTML tags intersection while applying styles to the message text
* @param match Global match of QRegularExpression * @param str Checking string
* @param exprNumber Number of subexpression * @return True, if tag intersection detected
* @return Length of captured string. If nothing was captured, returns 0
*/ */
int TextFormatter::getCapturedLength(const QRegularExpressionMatch &match, const int exprNumber) { static bool isTagIntersection(const QString& str)
QString captured = match.captured(exprNumber); {
return captured.isNull() || captured.isEmpty() ? 0 : captured.length(); const QRegularExpression TAG_PATTERN("(?<=<)/?[a-zA-Z0-9]+(?=>)");
int openingTagCount = 0;
int closingTagCount = 0;
QRegularExpressionMatchIterator iter = TAG_PATTERN.globalMatch(str);
while (iter.hasNext())
{
iter.next().captured()[0] == '/'
? ++closingTagCount
: ++openingTagCount;
}
return openingTagCount != closingTagCount;
} }
/** /**
* @brief TextFormatter::applyHtmlFontStyling Applies styles to the font of text that was passed to the constructor * @brief 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 * @param showFormattingSymbols True, if it is supposed to include formatting symbols into resulting string
* @return Source text with styled font * @return Source text with styled font
*/ */
QString TextFormatter::applyHtmlFontStyling(bool dontShowFormattingSymbols){ QString TextFormatter::applyHtmlFontStyling(bool showFormattingSymbols)
{
QString out = sourceString; QString out = sourceString;
int choppingSignsCountMultiplier = dontShowFormattingSymbols ? 0 : 1;
for (QPair<QRegularExpression, QString> pair : textPatternStyle) { for (QPair<QRegularExpression, QString> pair : textPatternStyle)
QRegularExpression exp = pair.first; {
QRegularExpressionMatchIterator matchesIterator = exp.globalMatch(out); QRegularExpressionMatchIterator matchesIterator = pair.first.globalMatch(out);
int insertedTagSymbolsCount = 0; int insertedTagSymbolsCount = 0;
while (matchesIterator.hasNext()) { while (matchesIterator.hasNext())
{
QRegularExpressionMatch match = matchesIterator.next(); QRegularExpressionMatch match = matchesIterator.next();
if (isTagIntersection(match.captured()))
{
continue;
}
// Regular expressions may capture one redundant symbol from both sides because of extra check, so we don't need to handle them int capturedStart = match.capturedStart() + insertedTagSymbolsCount;
int firstCheckResultLength = getCapturedLength(match, 1); int capturedLength = match.capturedLength();
int matchStart = match.capturedStart() + firstCheckResultLength + insertedTagSymbolsCount;
int matchLength = match.capturedLength() - firstCheckResultLength - getCapturedLength(match, exp.captureCount());
int choppingSignsCount = patternEscapeSignsCount(out.mid(matchStart, matchLength)); QString stylingText = out.mid(capturedStart, capturedLength);
int textStart = matchStart + choppingSignsCount; int choppingSignsCount = showFormattingSymbols ? 0 : patternSignsCount(stylingText);
int textLength = matchLength - choppingSignsCount * 2; int textStart = capturedStart + choppingSignsCount;
int textLength = capturedLength - 2 * choppingSignsCount;
QString styledText = pair.second.arg(out.mid(textStart, textLength)); QString styledText = pair.second.arg(out.mid(textStart, textLength));
textStart = matchStart + choppingSignsCount * choppingSignsCountMultiplier; out.replace(capturedStart, capturedLength, styledText);
textLength = matchLength - choppingSignsCount * choppingSignsCountMultiplier * 2; // Subtracting length of "%1"
insertedTagSymbolsCount += pair.second.length() - 2 - 2 * choppingSignsCount;
out.replace(textStart, textLength, styledText);
insertedTagSymbolsCount += pair.second.length() - 2 - choppingSignsCount * (1 - choppingSignsCountMultiplier) * 2;
} }
} }
return out; return out;
} }
/** /**
* @brief TextFormatter::applyStyling Applies all styling for the text * @brief Applies all styling for the text
* @param dontShowFormattingSymbols True, if it does not suppose to include formatting symbols into resulting string * @param showFormattingSymbols True, if it is supposed to include formatting symbols into resulting string
* @return Styled string * @return Styled string
*/ */
QString TextFormatter::applyStyling(bool dontShowFormattingSymbols) { QString TextFormatter::applyStyling(bool showFormattingSymbols)
return applyHtmlFontStyling(dontShowFormattingSymbols); {
return applyHtmlFontStyling(showFormattingSymbols);
} }

View File

@ -1,3 +1,22 @@
/*
Copyright © 2017 by The qTox Project Contributors
This file is part of qTox, a Qt-based graphical interface for Tox.
qTox is libre software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
qTox is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with qTox. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef TEXTFORMATTER_H #ifndef TEXTFORMATTER_H
#define TEXTFORMATTER_H #define TEXTFORMATTER_H
@ -9,16 +28,12 @@ private:
QString sourceString; QString sourceString;
int patternEscapeSignsCount(const QString& str); QString applyHtmlFontStyling(bool showFormattingSymbols);
int getCapturedLength(const QRegularExpressionMatch& match, const int exprNumber);
QString applyHtmlFontStyling(bool dontShowFormattingSymbols);
public: public:
explicit TextFormatter(const QString& str); explicit TextFormatter(const QString& str);
QString applyStyling(bool dontShowFormattingSymbols); QString applyStyling(bool showFormattingSymbols);
}; };
#endif // TEXTFORMATTER_H #endif // TEXTFORMATTER_H

View File

@ -1,7 +1,25 @@
/*
Copyright © 2017 by The qTox Project Contributors
This file is part of qTox, a Qt-based graphical interface for Tox.
qTox is libre software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
qTox is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with qTox. If not, see <http://www.gnu.org/licenses/>.
*/
#include "src/chatlog/textformatter.h" #include "src/chatlog/textformatter.h"
#include "test/common.h" #include "test/common.h"
#include <iostream>
#include <QString> #include <QString>
#include <QVector> #include <QVector>
#include <QVector> #include <QVector>
@ -74,81 +92,81 @@ static const StringToString multilineCode
}; };
/** /**
* @brief commonTest Testing cases which are common for all types of formatting except multiline code * @brief Testing cases which are common for all types of formatting except multiline code
* @param noSymbols True if it's not allowed to show formatting symbols * @param noSymbols True if it's not allowed to show formatting symbols
* @param map Grouped cases * @param map Grouped cases
* @param signs Combination of formatting symbols * @param signs Combination of formatting symbols
*/ */
void commonTest(bool noSymbols, const StringToString map, const QString signs) static void commonTest(bool showSymbols, const StringToString map, const QString signs)
{ {
for (QString key : map.keys()) for (QString key : map.keys())
{ {
QString source = key.arg(signs); QString source = key.arg(signs);
TextFormatter tf = TextFormatter(source); TextFormatter tf = TextFormatter(source);
QString result = map[key].arg(noSymbols ? "" : signs, signsToTags[signs]); QString result = map[key].arg(showSymbols ? signs : "", signsToTags[signs]);
ck_assert(tf.applyStyling(noSymbols) == result); ck_assert(tf.applyStyling(showSymbols) == result);
} }
} }
/** /**
* @brief commonExceptionsTest Testing exception cases * @brief Testing exception cases
* @param signs Combination of formatting symbols * @param signs Combination of formatting symbols
*/ */
void commonExceptionsTest(const QString signs) static void commonExceptionsTest(const QString signs)
{ {
for (QString source : commonExceptions) for (QString source : commonExceptions)
{ {
TextFormatter tf = TextFormatter(source.arg(signs)); TextFormatter tf = TextFormatter(source.arg(signs));
ck_assert(tf.applyStyling(true) == source.arg(signs)); ck_assert(tf.applyStyling(false) == source.arg(signs));
} }
} }
/** /**
* @brief specialTest Testing some uncommon, special cases * @brief Testing some uncommon, special cases
* @param map Grouped cases * @param map Grouped cases
*/ */
void specialTest(const StringToString map) static void specialTest(const StringToString map)
{ {
for (QString key : map.keys()) for (QString key : map.keys())
{ {
TextFormatter tf = TextFormatter(key); TextFormatter tf = TextFormatter(key);
ck_assert(tf.applyStyling(true) == map[key]); ck_assert(tf.applyStyling(false) == map[key]);
} }
} }
START_TEST(singleSignNoSymbolsTest) START_TEST(singleSignNoSymbolsTest)
{ {
commonTest(true, commonWorkCases, "*"); commonTest(false, commonWorkCases, "*");
} }
END_TEST END_TEST
START_TEST(slashNoSymbolsTest) START_TEST(slashNoSymbolsTest)
{ {
commonTest(true, commonWorkCases, "/"); commonTest(false, commonWorkCases, "/");
} }
END_TEST END_TEST
START_TEST(doubleSignNoSymbolsTest) START_TEST(doubleSignNoSymbolsTest)
{ {
commonTest(true, commonWorkCases, "**"); commonTest(false, commonWorkCases, "**");
} }
END_TEST END_TEST
START_TEST(singleSignWithSymbolsTest) START_TEST(singleSignWithSymbolsTest)
{ {
commonTest(false, commonWorkCases, "*"); commonTest(true, commonWorkCases, "*");
} }
END_TEST END_TEST
START_TEST(slashWithSymbolsTest) START_TEST(slashWithSymbolsTest)
{ {
commonTest(false, commonWorkCases, "/"); commonTest(true, commonWorkCases, "/");
} }
END_TEST END_TEST
START_TEST(doubleSignWithSymbolsTest) START_TEST(doubleSignWithSymbolsTest)
{ {
commonTest(false, commonWorkCases, "**"); commonTest(true, commonWorkCases, "**");
} }
END_TEST END_TEST

View File

@ -1,3 +1,22 @@
/*
Copyright © 2017 by The qTox Project Contributors
This file is part of qTox, a Qt-based graphical interface for Tox.
qTox is libre software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
qTox is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with qTox. If not, see <http://www.gnu.org/licenses/>.
*/
#include "src/core/toxid.h" #include "src/core/toxid.h"
#include "test/common.h" #include "test/common.h"

View File

@ -1,3 +1,22 @@
/*
Copyright © 2017 by The qTox Project Contributors
This file is part of qTox, a Qt-based graphical interface for Tox.
qTox is libre software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
qTox is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with qTox. If not, see <http://www.gnu.org/licenses/>.
*/
#include "src/core/toxid.h" #include "src/core/toxid.h"
#include "test/common.h" #include "test/common.h"