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

refactor: Comply with Wmissing-declarations

* Move free functions to the anonymous namespace
* Additionally move static free functions to the anonymous namespace
* Move functions that must be accessed externally to static class functions
This commit is contained in:
Anthony Bilinski 2022-03-11 02:18:35 -08:00
parent b0bf3d77cb
commit adc0f0cca6
No known key found for this signature in database
GPG Key ID: 2AA8E0DA1B31FB3C
42 changed files with 463 additions and 422 deletions

View File

@ -41,7 +41,6 @@ void applyGain(int16_t* buffer, uint32_t bufferSize, qreal gainFactor)
std::numeric_limits<int16_t>::max());
}
}
} // namespace
/**
* @class OpenAL
@ -54,8 +53,10 @@ void applyGain(int16_t* buffer, uint32_t bufferSize, qreal gainFactor)
* @brief Ideally, we'd auto-detect, but that's a sane default
*/
static const unsigned int BUFFER_COUNT = 16;
static const uint32_t AUDIO_CHANNELS = 2;
const unsigned int BUFFER_COUNT = 16;
const uint32_t AUDIO_CHANNELS = 2;
} // namespace
constexpr qreal OpenAL::minInGain;
constexpr qreal OpenAL::maxInGain;

View File

@ -63,12 +63,12 @@ ChatMessage::Ptr ChatMessage::createChatMessage(const QString& sender, const QSt
// quotes (green text)
text = detectQuotes(text, type);
text = highlightURI(text);
text = TextFormatter::highlightURI(text);
// text styling
Settings::StyleType styleType = Settings::getInstance().getStylePreference();
if (styleType != Settings::StyleType::NONE) {
text = applyMarkdown(text, styleType == Settings::StyleType::WITH_CHARS);
text = TextFormatter::applyMarkdown(text, styleType == Settings::StyleType::WITH_CHARS);
}

View File

@ -48,9 +48,9 @@ namespace
{
// Maximum number of rendered messages at any given time
static int constexpr maxWindowSize = 300;
int constexpr maxWindowSize = 300;
// Amount of messages to purge when removing messages
static int constexpr windowChunkSize = 100;
int constexpr windowChunkSize = 100;
template <class T>
T clamp(T x, T min, T max)

View File

@ -24,8 +24,9 @@
// clang-format off
namespace {
// Note: escaping of '\' is only needed because QStringLiteral is broken by linebreak
static const QString SINGLE_SIGN_PATTERN = QStringLiteral("(?<=^|\\s)"
const QString SINGLE_SIGN_PATTERN = QStringLiteral("(?<=^|\\s)"
"[%1]"
"(?!\\s)"
"([^%1\\n]+?)"
@ -33,7 +34,7 @@ static const QString SINGLE_SIGN_PATTERN = QStringLiteral("(?<=^|\\s)"
"[%1]"
"(?=$|\\s)");
static const QString SINGLE_SLASH_PATTERN = QStringLiteral("(?<=^|\\s)"
const QString SINGLE_SLASH_PATTERN = QStringLiteral("(?<=^|\\s)"
"/"
"(?!\\s)"
"([^/\\n]+?)"
@ -41,7 +42,7 @@ static const QString SINGLE_SLASH_PATTERN = QStringLiteral("(?<=^|\\s)"
"/"
"(?=$|\\s)");
static const QString DOUBLE_SIGN_PATTERN = QStringLiteral("(?<=^|\\s)"
const QString DOUBLE_SIGN_PATTERN = QStringLiteral("(?<=^|\\s)"
"[%1]{2}"
"(?!\\s)"
"([^\\n]+?)"
@ -49,7 +50,7 @@ static const QString DOUBLE_SIGN_PATTERN = QStringLiteral("(?<=^|\\s)"
"[%1]{2}"
"(?=$|\\s)");
static const QString MULTILINE_CODE = QStringLiteral("(?<=^|\\s)"
const QString MULTILINE_CODE = QStringLiteral("(?<=^|\\s)"
"```"
"(?!`)"
"((.|\\n)+?)"
@ -60,7 +61,7 @@ static const QString MULTILINE_CODE = QStringLiteral("(?<=^|\\s)"
#define REGEXP_WRAPPER_PAIR(pattern, wrapper)\
{QRegularExpression(pattern,QRegularExpression::UseUnicodePropertiesOption),QStringLiteral(wrapper)}
static const QPair<QRegularExpression, QString> REGEX_TO_WRAPPER[] {
const QPair<QRegularExpression, QString> REGEX_TO_WRAPPER[] {
REGEXP_WRAPPER_PAIR(SINGLE_SLASH_PATTERN, "<i>%1</i>"),
REGEXP_WRAPPER_PAIR(SINGLE_SIGN_PATTERN.arg('*'), "<b>%1</b>"),
REGEXP_WRAPPER_PAIR(SINGLE_SIGN_PATTERN.arg('_'), "<u>%1</u>"),
@ -75,14 +76,14 @@ static const QPair<QRegularExpression, QString> REGEX_TO_WRAPPER[] {
#undef REGEXP_WRAPPER_PAIR
static const QString HREF_WRAPPER = QStringLiteral(R"(<a href="%1">%1</a>)");
static const QString WWW_WRAPPER = QStringLiteral(R"(<a href="http://%1">%1</a>)");
const QString HREF_WRAPPER = QStringLiteral(R"(<a href="%1">%1</a>)");
const QString WWW_WRAPPER = QStringLiteral(R"(<a href="http://%1">%1</a>)");
static const QVector<QRegularExpression> WWW_WORD_PATTERN = {
const QVector<QRegularExpression> WWW_WORD_PATTERN = {
QRegularExpression(QStringLiteral(R"((?<=^|\s)\S*((www\.)\S+))"))
};
static const QVector<QRegularExpression> URI_WORD_PATTERNS = {
const QVector<QRegularExpression> URI_WORD_PATTERNS = {
// Note: This does not match only strictly valid URLs, but we broaden search to any string following scheme to
// allow UTF-8 "IRI"s instead of ASCII-only URLs
QRegularExpression(QStringLiteral(R"((?<=^|\s)\S*((((http[s]?)|ftp)://)\S+))")),
@ -103,7 +104,7 @@ struct MatchingUri {
};
// pairs of characters that are ignored when surrounding a URI
static const QPair<QString, QString> URI_WRAPPING_CHARS[] = {
const QPair<QString, QString> URI_WRAPPING_CHARS[] = {
{QString("("), QString(")")},
{QString("["), QString("]")},
{QString("&quot;"), QString("&quot;")},
@ -111,7 +112,7 @@ static const QPair<QString, QString> URI_WRAPPING_CHARS[] = {
};
// characters which are ignored from the end of URI
static const QChar URI_ENDING_CHARS[] = {
const QChar URI_ENDING_CHARS[] = {
QChar::fromLatin1('?'),
QChar::fromLatin1('.'),
QChar::fromLatin1('!'),
@ -194,24 +195,12 @@ QString highlight(const QString& message, const QVector<QRegularExpression>& pat
return result;
}
/**
* @brief Highlights URLs within passed message string
* @param message Where search for URLs
* @return Copy of message with highlighted URLs
*/
QString highlightURI(const QString& message)
{
QString result = highlight(message, URI_WORD_PATTERNS, HREF_WRAPPER);
result = highlight(result, WWW_WORD_PATTERN, WWW_WRAPPER);
return result;
}
/**
* @brief Checks HTML tags intersection while applying styles to the message text
* @param str Checking string
* @return True, if tag intersection detected
*/
static bool isTagIntersection(const QString& str)
bool isTagIntersection(const QString& str)
{
const QRegularExpression TAG_PATTERN("(?<=<)/?[a-zA-Z0-9]+(?=>)");
@ -224,6 +213,19 @@ static bool isTagIntersection(const QString& str)
}
return openingTagCount != closingTagCount;
}
} // namespace
/**
* @brief Highlights URLs within passed message string
* @param message Where search for URLs
* @return Copy of message with highlighted URLs
*/
QString TextFormatter::highlightURI(const QString& message)
{
QString result = highlight(message, URI_WORD_PATTERNS, HREF_WRAPPER);
result = highlight(result, WWW_WORD_PATTERN, WWW_WRAPPER);
return result;
}
/**
* @brief Applies markdown to passed message string
@ -232,7 +234,7 @@ static bool isTagIntersection(const QString& str)
* string
* @return Copy of message with markdown applied
*/
QString applyMarkdown(const QString& message, bool showFormattingSymbols)
QString TextFormatter::applyMarkdown(const QString& message, bool showFormattingSymbols)
{
QString result = message;
for (const QPair<QRegularExpression, QString>& pair : REGEX_TO_WRAPPER) {

View File

@ -21,6 +21,9 @@
#include <QString>
QString highlightURI(const QString& message);
namespace TextFormatter
{
QString highlightURI(const QString& message);
QString applyMarkdown(const QString& message, bool showFormattingSymbols);
QString applyMarkdown(const QString& message, bool showFormattingSymbols);
} // namespace TextFormatter

View File

@ -25,12 +25,98 @@
#include <QString>
#include <memory>
// functions for nice debug output
static QString getKeyDerivationError(Tox_Err_Key_Derivation error);
static QString getEncryptionError(Tox_Err_Encryption error);
static QString getDecryptionError(Tox_Err_Decryption error);
static QString getSaltError(Tox_Err_Get_Salt error);
namespace {
/**
* @brief Gets the error string for Tox_Err_Key_Derivation errors.
* @param error The error number.
* @return The verbose error message.
*/
QString getKeyDerivationError(Tox_Err_Key_Derivation error)
{
switch (error) {
case TOX_ERR_KEY_DERIVATION_OK:
return QStringLiteral("The function returned successfully.");
case TOX_ERR_KEY_DERIVATION_NULL:
return QStringLiteral(
"One of the arguments to the function was NULL when it was not expected.");
case TOX_ERR_KEY_DERIVATION_FAILED:
return QStringLiteral(
"The crypto lib was unable to derive a key from the given passphrase.");
default:
return QStringLiteral("Unknown key derivation error.");
}
}
/**
* @brief Gets the error string for Tox_Err_Encryption errors.
* @param error The error number.
* @return The verbose error message.
*/
QString getEncryptionError(Tox_Err_Encryption error)
{
switch (error) {
case TOX_ERR_ENCRYPTION_OK:
return QStringLiteral("The function returned successfully.");
case TOX_ERR_ENCRYPTION_NULL:
return QStringLiteral(
"One of the arguments to the function was NULL when it was not expected.");
case TOX_ERR_ENCRYPTION_KEY_DERIVATION_FAILED:
return QStringLiteral(
"The crypto lib was unable to derive a key from the given passphrase.");
case TOX_ERR_ENCRYPTION_FAILED:
return QStringLiteral("The encryption itself failed.");
default:
return QStringLiteral("Unknown encryption error.");
}
}
/**
* @brief Gets the error string for Tox_Err_Decryption errors.
* @param error The error number.
* @return The verbose error message.
*/
QString getDecryptionError(Tox_Err_Decryption error)
{
switch (error) {
case TOX_ERR_DECRYPTION_OK:
return QStringLiteral("The function returned successfully.");
case TOX_ERR_DECRYPTION_NULL:
return QStringLiteral(
"One of the arguments to the function was NULL when it was not expected.");
case TOX_ERR_DECRYPTION_INVALID_LENGTH:
return QStringLiteral(
"The input data was shorter than TOX_PASS_ENCRYPTION_EXTRA_LENGTH bytes.");
case TOX_ERR_DECRYPTION_BAD_FORMAT:
return QStringLiteral("The input data is missing the magic number or is corrupted.");
case TOX_ERR_DECRYPTION_KEY_DERIVATION_FAILED:
return QStringLiteral("The crypto lib was unable to derive a key from the given passphrase.");
case TOX_ERR_DECRYPTION_FAILED:
return QStringLiteral("Decryption failed. Either the data was corrupted or the password/key was incorrect.");
default:
return QStringLiteral("Unknown decryption error.");
}
}
/**
* @brief Gets the error string for Tox_Err_Get_Salt errors.
* @param error The error number.
* @return The verbose error message.
*/
QString getSaltError(Tox_Err_Get_Salt error)
{
switch (error) {
case TOX_ERR_GET_SALT_OK:
return QStringLiteral("The function returned successfully.");
case TOX_ERR_GET_SALT_NULL:
return QStringLiteral(
"One of the arguments to the function was NULL when it was not expected.");
case TOX_ERR_GET_SALT_BAD_FORMAT:
return QStringLiteral("The input data is missing the magic number or is corrupted.");
default:
return QStringLiteral("Unknown salt error.");
}
}
}
/**
* @class ToxEncrypt
* @brief Encapsulates the toxencrypsave API.
@ -262,94 +348,3 @@ QByteArray ToxEncrypt::decrypt(const QByteArray& ciphertext) const
return plaintext;
}
/**
* @brief Gets the error string for Tox_Err_Key_Derivation errors.
* @param error The error number.
* @return The verbose error message.
*/
QString getKeyDerivationError(Tox_Err_Key_Derivation error)
{
switch (error) {
case TOX_ERR_KEY_DERIVATION_OK:
return QStringLiteral("The function returned successfully.");
case TOX_ERR_KEY_DERIVATION_NULL:
return QStringLiteral(
"One of the arguments to the function was NULL when it was not expected.");
case TOX_ERR_KEY_DERIVATION_FAILED:
return QStringLiteral(
"The crypto lib was unable to derive a key from the given passphrase.");
default:
return QStringLiteral("Unknown key derivation error.");
}
}
/**
* @brief Gets the error string for Tox_Err_Encryption errors.
* @param error The error number.
* @return The verbose error message.
*/
QString getEncryptionError(Tox_Err_Encryption error)
{
switch (error) {
case TOX_ERR_ENCRYPTION_OK:
return QStringLiteral("The function returned successfully.");
case TOX_ERR_ENCRYPTION_NULL:
return QStringLiteral(
"One of the arguments to the function was NULL when it was not expected.");
case TOX_ERR_ENCRYPTION_KEY_DERIVATION_FAILED:
return QStringLiteral(
"The crypto lib was unable to derive a key from the given passphrase.");
case TOX_ERR_ENCRYPTION_FAILED:
return QStringLiteral("The encryption itself failed.");
default:
return QStringLiteral("Unknown encryption error.");
}
}
/**
* @brief Gets the error string for Tox_Err_Decryption errors.
* @param error The error number.
* @return The verbose error message.
*/
QString getDecryptionError(Tox_Err_Decryption error)
{
switch (error) {
case TOX_ERR_DECRYPTION_OK:
return QStringLiteral("The function returned successfully.");
case TOX_ERR_DECRYPTION_NULL:
return QStringLiteral(
"One of the arguments to the function was NULL when it was not expected.");
case TOX_ERR_DECRYPTION_INVALID_LENGTH:
return QStringLiteral(
"The input data was shorter than TOX_PASS_ENCRYPTION_EXTRA_LENGTH bytes.");
case TOX_ERR_DECRYPTION_BAD_FORMAT:
return QStringLiteral("The input data is missing the magic number or is corrupted.");
case TOX_ERR_DECRYPTION_KEY_DERIVATION_FAILED:
return QStringLiteral("The crypto lib was unable to derive a key from the given passphrase.");
case TOX_ERR_DECRYPTION_FAILED:
return QStringLiteral("Decryption failed. Either the data was corrupted or the password/key was incorrect.");
default:
return QStringLiteral("Unknown decryption error.");
}
}
/**
* @brief Gets the error string for Tox_Err_Get_Salt errors.
* @param error The error number.
* @return The verbose error message.
*/
QString getSaltError(Tox_Err_Get_Salt error)
{
switch (error) {
case TOX_ERR_GET_SALT_OK:
return QStringLiteral("The function returned successfully.");
case TOX_ERR_GET_SALT_NULL:
return QStringLiteral(
"One of the arguments to the function was NULL when it was not expected.");
case TOX_ERR_GET_SALT_BAD_FORMAT:
return QStringLiteral("The input data is missing the magic number or is corrupted.");
default:
return QStringLiteral("Unknown salt error.");
}
}

View File

@ -47,9 +47,10 @@
#include "platform/posixsignalnotifier.h"
#endif
namespace {
#ifdef LOG_TO_FILE
static QAtomicPointer<FILE> logFileFile = nullptr;
static QList<QByteArray>* logBuffer =
QAtomicPointer<FILE> logFileFile = nullptr;
QList<QByteArray>* logBuffer =
new QList<QByteArray>(); // Store log messages until log file opened
QMutex* logBufferMutex = new QMutex();
#endif
@ -176,9 +177,9 @@ void logMessageHandler(QtMsgType type, const QMessageLogContext& ctxt, const QSt
#endif
}
static std::unique_ptr<ToxURIDialog> uriDialog;
std::unique_ptr<ToxURIDialog> uriDialog;
static bool toxURIEventHandler(const QByteArray& eventData)
bool toxURIEventHandler(const QByteArray& eventData)
{
if (!eventData.startsWith("tox:")) {
return false;
@ -191,6 +192,7 @@ static bool toxURIEventHandler(const QByteArray& eventData)
uriDialog->handleToxURI(eventData);
return true;
}
}
int main(int argc, char* argv[])
{

View File

@ -28,7 +28,9 @@
#include <QDebug>
static const int MAX_GROUP_TITLE_LENGTH = 128;
namespace {
const int MAX_GROUP_TITLE_LENGTH = 128;
} // namespace
Group::Group(int groupId_, const GroupId persistentGroupId, const QString& name, bool isAvGroupchat,
const QString& selfName_, ICoreGroupQuery& groupQuery_, ICoreIdHandler& idHandler_)

View File

@ -30,6 +30,62 @@
#include <QFile>
#include <QImageReader>
namespace {
/**
* @brief Convert QImage to png image.
* @param pic Picture to convert.
* @return Byte array with png image.
*/
QByteArray picToPng(const QImage& pic)
{
QByteArray bytes;
QBuffer buffer(&bytes);
buffer.open(QIODevice::WriteOnly);
pic.save(&buffer, "PNG");
buffer.close();
return bytes;
}
/**
* @brief Remove characters not supported for profile name from string.
* @param src Source string.
* @return Sanitized string.
*/
QString sanitize(const QString& src)
{
QString name = src;
// these are pretty much Windows banned filename characters
QList<QChar> banned{'/', '\\', ':', '<', '>', '"', '|', '?', '*'};
for (QChar c : banned) {
name.replace(c, '_');
}
// also remove leading and trailing periods
if (name[0] == '.') {
name[0] = '_';
}
if (name.endsWith('.')) {
name[name.length() - 1] = '_';
}
return name;
}
// TODO: Find out what is dangerous?
/**
* @brief Dangerous way to find out if a path is writable.
* @param filepath Path to file which should be deleted.
* @return True, if file writeable, false otherwise.
*/
bool tryRemoveFile(const QString& filepath)
{
QFile tmp(filepath);
bool writable = tmp.open(QIODevice::WriteOnly);
tmp.remove();
return writable;
}
} // namespace
/**
* @class ProfileInfo
* @brief Implement interface, that provides invormation about self profile.
@ -123,32 +179,6 @@ QString ProfileInfo::getProfileName() const
return profile->getName();
}
/**
* @brief Remove characters not supported for profile name from string.
* @param src Source string.
* @return Sanitized string.
*/
static QString sanitize(const QString& src)
{
QString name = src;
// these are pretty much Windows banned filename characters
QList<QChar> banned{'/', '\\', ':', '<', '>', '"', '|', '?', '*'};
for (QChar c : banned) {
name.replace(c, '_');
}
// also remove leading and trailing periods
if (name[0] == '.') {
name[0] = '_';
}
if (name.endsWith('.')) {
name[name.length() - 1] = '_';
}
return name;
}
/**
* @brief Rename profile file.
* @param name New profile name.
@ -174,20 +204,6 @@ IProfileInfo::RenameResult ProfileInfo::renameProfile(const QString& name)
return RenameResult::OK;
}
// TODO: Find out what is dangerous?
/**
* @brief Dangerous way to find out if a path is writable.
* @param filepath Path to file which should be deleted.
* @return True, if file writeable, false otherwise.
*/
static bool tryRemoveFile(const QString& filepath)
{
QFile tmp(filepath);
bool writable = tmp.open(QIODevice::WriteOnly);
tmp.remove();
return writable;
}
/**
* @brief Save profile in custom place.
* @param path Path to save profile.
@ -268,21 +284,6 @@ IProfileInfo::SaveResult ProfileInfo::saveQr(const QImage& image, const QString&
return SaveResult::OK;
}
/**
* @brief Convert QImage to png image.
* @param pic Picture to convert.
* @return Byte array with png image.
*/
QByteArray picToPng(const QImage& pic)
{
QByteArray bytes;
QBuffer buffer(&bytes);
buffer.open(QIODevice::WriteOnly);
pic.save(&buffer, "PNG");
buffer.close();
return bytes;
}
/**
* @brief Set self avatar.
* @param path Path to image, which should be the new avatar.

View File

@ -55,7 +55,9 @@
Q_DECLARE_OPAQUE_POINTER(ToxAV*)
static Nexus* nexus{nullptr};
namespace {
Nexus* nexus{nullptr};
} // namespace
Nexus::Nexus(QObject* parent)
: QObject(parent)

View File

@ -27,7 +27,7 @@
#include "src/core/toxpk.h"
namespace {
static constexpr int SCHEMA_VERSION = 9;
constexpr int SCHEMA_VERSION = 9;
bool createCurrentSchema(RawDatabase& db)
{

View File

@ -50,15 +50,12 @@
* @var ArrayEnd
* Not followed by any data
*/
enum class RecordTag : uint8_t
{
};
/**
/**
* @var static const char magic[];
* @brief Little endian ASCII "QTOX" magic
*/
const char SettingsSerializer::magic[] = {0x51, 0x54, 0x4F, 0x58};
namespace {
QDataStream& writeStream(QDataStream& dataStream, const SettingsSerializer::RecordTag& tag)
{
@ -98,6 +95,7 @@ QDataStream& readStream(QDataStream& dataStream, QByteArray& data)
dataStream.readRawData(data.data(), num);
return dataStream;
}
} // namespace
SettingsSerializer::SettingsSerializer(QString filePath_, const ToxEncrypt* passKey_)
: path{filePath_}

View File

@ -29,6 +29,14 @@
class SettingsSerializer
{
public:
enum class RecordTag : uint8_t
{
Value = 0,
GroupStart = 1,
ArrayStart = 2,
ArrayValue = 3,
ArrayEnd = 4,
};
SettingsSerializer(QString filePath_, const ToxEncrypt* passKey_ = nullptr);
static bool isSerializedFormat(QString filePath);
@ -48,17 +56,6 @@ public:
QVariant value(const QString& key, const QVariant& defaultValue = QVariant()) const;
private:
enum class RecordTag : uint8_t
{
Value = 0,
GroupStart = 1,
ArrayStart = 2,
ArrayValue = 3,
ArrayEnd = 4,
};
friend QDataStream& writeStream(QDataStream& dataStream, const SettingsSerializer::RecordTag& tag);
friend QDataStream& readStream(QDataStream& dataStream, SettingsSerializer::RecordTag& tag);
struct Value
{
Value()

View File

@ -52,15 +52,16 @@
* @brief Contains all directories where smileys could be found
*/
namespace {
QStringList loadDefaultPaths();
static const QStringList DEFAULT_PATHS = loadDefaultPaths();
const QStringList DEFAULT_PATHS = loadDefaultPaths();
static const QString RICH_TEXT_PATTERN = QStringLiteral("<img title=\"%1\" src=\"key:%1\"\\>");
const QString RICH_TEXT_PATTERN = QStringLiteral("<img title=\"%1\" src=\"key:%1\"\\>");
static const QString EMOTICONS_FILE_NAME = QStringLiteral("emoticons.xml");
const QString EMOTICONS_FILE_NAME = QStringLiteral("emoticons.xml");
static constexpr int CLEANUP_TIMEOUT = 5 * 60 * 1000; // 5 minutes
constexpr int CLEANUP_TIMEOUT = 5 * 60 * 1000; // 5 minutes
/**
* @brief Construct list of standard directories with "emoticons" sub dir, whether these directories
@ -95,16 +96,6 @@ QStringList loadDefaultPaths()
return paths;
}
/**
* @brief Wraps passed string into smiley HTML image reference
* @param key Describes which smiley is needed
* @return Key that wrapped into image ref
*/
QString getAsRichText(const QString& key)
{
return RICH_TEXT_PATTERN.arg(key);
}
bool isAscii(const QString& string)
{
constexpr auto asciiExtMask = 0x80;
@ -112,6 +103,8 @@ bool isAscii(const QString& string)
return (string.toUtf8()[0] & asciiExtMask) == 0;
}
} // namespace
SmileyPack::SmileyPack()
: cleanupTimer{new QTimer(this)}
{
@ -128,6 +121,16 @@ SmileyPack::~SmileyPack()
delete cleanupTimer;
}
/**
* @brief Wraps passed string into smiley HTML image reference
* @param key Describes which smiley is needed
* @return Key that wrapped into image ref
*/
QString SmileyPack::getAsRichText(const QString& key)
{
return RICH_TEXT_PATTERN.arg(key);
}
void SmileyPack::cleanupIconsCache()
{
QMutexLocker locker(&loadingMutex);
@ -311,7 +314,7 @@ QString SmileyPack::smileyfied(const QString& msg)
QRegularExpressionMatch match = iter.next();
int startPos = match.capturedStart();
int keyLength = match.capturedLength();
QString imgRichText = getAsRichText(match.captured());
QString imgRichText = SmileyPack::getAsRichText(match.captured());
result.replace(startPos + replaceDiff, keyLength, imgRichText);
replaceDiff += imgRichText.length() - keyLength;
}

View File

@ -40,6 +40,7 @@ public:
QString smileyfied(const QString& msg);
QList<QStringList> getEmoticons() const;
std::shared_ptr<QIcon> getAsIcon(const QString& key) const;
static QString getAsRichText(const QString& key);
private slots:
void onSmileyPackChanged();

View File

@ -24,7 +24,9 @@
#include <QSettings>
#include <QStandardPaths>
static int state;
namespace {
int state;
} // namespace
bool Platform::setAutorun(bool on)
{

View File

@ -23,6 +23,7 @@
#include <string>
#include <windows.h>
namespace {
#ifdef UNICODE
/**
* tstring is either std::wstring or std::string, depending on whether the user
@ -30,17 +31,18 @@
* easier to reuse and compatible with both setups.
*/
using tstring = std::wstring;
static inline tstring toTString(QString s)
inline tstring toTString(QString s)
{
return s.toStdWString();
}
#else
using tstring = std::string;
static inline tstring toTString(QString s)
inline tstring toTString(QString s)
{
return s.toStdString();
}
#endif
} // namespace
namespace Platform {
inline tstring currentCommandLine()

View File

@ -23,7 +23,7 @@
#include <QDir>
#include <QProcessEnvironment>
namespace Platform {
namespace {
QString getAutostartDirPath()
{
QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
@ -55,7 +55,7 @@ inline QString profileRunCommand()
return "\"" + currentBinPath() + "\" -p \""
+ Settings::getInstance().getCurrentProfile() + "\"";
}
}
} // namespace
bool Platform::setAutorun(bool on)
{

View File

@ -40,7 +40,8 @@
* stdout and is not part of the public API for some reason.
*/
static char* wcharToUtf8(wchar_t* w)
namespace {
char* wcharToUtf8(wchar_t* w)
{
int l = WideCharToMultiByte(CP_UTF8, 0, w, -1, nullptr, 0, nullptr, nullptr);
char* s = new char[l];
@ -48,6 +49,7 @@ static char* wcharToUtf8(wchar_t* w)
WideCharToMultiByte(CP_UTF8, 0, w, -1, s, l, nullptr, nullptr);
return s;
}
} // namespace
QVector<QPair<QString, QString>> DirectShow::getDeviceList()
{

View File

@ -37,7 +37,8 @@
* stdout and is not part of the public API for some reason.
*/
static std::map<uint32_t, uint8_t> createPixFmtToQuality()
namespace {
std::map<uint32_t, uint8_t> createPixFmtToQuality()
{
std::map<uint32_t, uint8_t> m;
m[V4L2_PIX_FMT_H264] = 3;
@ -48,7 +49,7 @@ static std::map<uint32_t, uint8_t> createPixFmtToQuality()
}
const std::map<uint32_t, uint8_t> pixFmtToQuality = createPixFmtToQuality();
static std::map<uint32_t, QString> createPixFmtToName()
std::map<uint32_t, QString> createPixFmtToName()
{
std::map<uint32_t, QString> m;
m[V4L2_PIX_FMT_H264] = QString("h264");
@ -59,7 +60,7 @@ static std::map<uint32_t, QString> createPixFmtToName()
}
const std::map<uint32_t, QString> pixFmtToName = createPixFmtToName();
static int deviceOpen(QString devName, int* error)
int deviceOpen(QString devName, int* error)
{
struct v4l2_capability cap;
int fd;
@ -93,7 +94,7 @@ fail:
return -1;
}
static QVector<float> getDeviceModeFramerates(int fd, unsigned w, unsigned h,
QVector<float> getDeviceModeFramerates(int fd, unsigned w, unsigned h,
uint32_t pixelFormat)
{
QVector<float> rates;
@ -121,6 +122,7 @@ static QVector<float> getDeviceModeFramerates(int fd, unsigned w, unsigned h,
return rates;
}
} // namespace
QVector<VideoMode> v4l2::getDeviceModes(QString devName)
{

View File

@ -36,12 +36,12 @@
* @brief Class for converting POSIX signals to Qt signals
*/
namespace detail {
namespace {
static std::atomic_flag g_signalSocketUsageFlag = ATOMIC_FLAG_INIT;
static std::array<int, 2> g_signalSocketPair;
std::atomic_flag g_signalSocketUsageFlag = ATOMIC_FLAG_INIT;
std::array<int, 2> g_signalSocketPair;
static void signalHandler(int signum)
void signalHandler(int signum)
{
// DO NOT call any Qt functions directly, only limited amount of so-called async-signal-safe
// functions can be called in signal handlers.
@ -63,17 +63,17 @@ static void signalHandler(int signum)
g_signalSocketUsageFlag.clear();
}
} // namespace detail
} // namespace
PosixSignalNotifier::~PosixSignalNotifier()
{
while (detail::g_signalSocketUsageFlag.test_and_set()) {
while (g_signalSocketUsageFlag.test_and_set()) {
// spin-loop until we aquire flag (signal handler might be running and have flag in use)
}
// do not leak sockets
::close(detail::g_signalSocketPair[0]);
::close(detail::g_signalSocketPair[1]);
::close(g_signalSocketPair[0]);
::close(g_signalSocketPair[1]);
// do not clear the usage flag here, signal handler cannot use socket any more!
}
@ -85,7 +85,7 @@ void PosixSignalNotifier::watchSignal(int signum)
sigaddset(&blockMask, signum); // do not prefix with ::, it's a macro on macOS
struct sigaction action = {}; // all zeroes by default
action.sa_handler = detail::signalHandler;
action.sa_handler = signalHandler;
action.sa_mask = blockMask; // allow old signal to finish before new is raised
if (::sigaction(signum, &action, nullptr)) {
@ -114,7 +114,7 @@ PosixSignalNotifier& PosixSignalNotifier::globalInstance()
void PosixSignalNotifier::onSignalReceived()
{
int signum{0};
if (::read(detail::g_signalSocketPair[1], &signum, sizeof(signum)) == -1) {
if (::read(g_signalSocketPair[1], &signum, sizeof(signum)) == -1) {
qFatal("Failed to read from signal socket, error = %d", errno);
}
@ -124,10 +124,10 @@ void PosixSignalNotifier::onSignalReceived()
PosixSignalNotifier::PosixSignalNotifier()
{
if (::socketpair(AF_UNIX, SOCK_STREAM, 0, detail::g_signalSocketPair.data())) {
if (::socketpair(AF_UNIX, SOCK_STREAM, 0, g_signalSocketPair.data())) {
qFatal("Failed to create socket pair, error = %d", errno);
}
notifier = new QSocketNotifier(detail::g_signalSocketPair[1], QSocketNotifier::Read, this);
notifier = new QSocketNotifier(g_signalSocketPair[1], QSocketNotifier::Read, this);
connect(notifier, &QSocketNotifier::activated, this, &PosixSignalNotifier::onSignalReceived);
}

View File

@ -71,11 +71,13 @@ using AvFindInputFormatRet = decltype(av_find_input_format(""));
* @brief Number of times the device was opened
*/
namespace {
AvFindInputFormatRet idesktopFormat{nullptr};
AvFindInputFormatRet iformat{nullptr};
} // namespace
QHash<QString, CameraDevice*> CameraDevice::openDevices;
QMutex CameraDevice::openDeviceLock, CameraDevice::iformatLock;
static AvFindInputFormatRet idesktopFormat{nullptr};
static AvFindInputFormatRet iformat{nullptr};
CameraDevice::CameraDevice(const QString& devName_, AVFormatContext* context_)
: devName{devName_}

View File

@ -30,16 +30,17 @@
#include <QLabel>
#include <QPainter>
/**
* @var std::atomic_bool VideoSurface::frameLock
* @brief Fast lock for lastFrame.
*/
namespace {
float getSizeRatio(const QSize size)
{
return size.width() / static_cast<float>(size.height());
}
} // namespace
/**
* @var std::atomic_bool VideoSurface::frameLock
* @brief Fast lock for lastFrame.
*/
VideoSurface::VideoSurface(const QPixmap& avatar_, QWidget* parent, bool expanding_)
: QWidget{parent}
, source{nullptr}

View File

@ -26,6 +26,16 @@
#include <QFileDialog>
#include <QMessageBox>
namespace {
QString getAutoAcceptDir(const QString& dir)
{
//: popup title
const QString title = AboutFriendForm::tr("Choose an auto-accept directory");
return QFileDialog::getExistingDirectory(Q_NULLPTR, title, dir);
}
} // namespace
AboutFriendForm::AboutFriendForm(std::unique_ptr<IAboutFriend> _about, QWidget* parent)
: QDialog(parent)
, ui(new Ui::AboutFriendForm)
@ -72,13 +82,6 @@ AboutFriendForm::AboutFriendForm(std::unique_ptr<IAboutFriend> _about, QWidget*
reloadTheme();
}
static QString getAutoAcceptDir(const QString& dir)
{
//: popup title
const QString title = AboutFriendForm::tr("Choose an auto-accept directory");
return QFileDialog::getExistingDirectory(Q_NULLPTR, title, dir);
}
void AboutFriendForm::onAutoAcceptDirClicked()
{
const QString dir = [&]{

View File

@ -36,12 +36,12 @@
#include <QTextDocument>
#include <QToolButton>
static const QSize AVATAR_SIZE{40, 40};
static const short HEAD_LAYOUT_SPACING = 5;
static const short MIC_BUTTONS_LAYOUT_SPACING = 4;
static const short BUTTONS_LAYOUT_HOR_SPACING = 4;
namespace {
const QSize AVATAR_SIZE{40, 40};
const short HEAD_LAYOUT_SPACING = 5;
const short MIC_BUTTONS_LAYOUT_SPACING = 4;
const short BUTTONS_LAYOUT_HOR_SPACING = 4;
const QString STYLE_PATH = QStringLiteral("chatForm/buttons.css");
const QString STATE_NAME[] = {

View File

@ -46,10 +46,12 @@
#include "src/widget/translator.h"
#include "src/widget/widget.h"
static const int minWidget = 220;
static const int minHeight = 220;
static const QSize minSize(minHeight, minWidget);
static const QSize defaultSize(720, 400);
namespace {
const int minWidget = 220;
const int minHeight = 220;
const QSize minSize(minHeight, minWidget);
const QSize defaultSize(720, 400);
} // namespace
ContentDialog::ContentDialog(const Core &core, QWidget* parent)
: ActivateDialog(parent, Qt::Window)

View File

@ -69,10 +69,11 @@
*
* @brief stopNotification Tell others to stop notification of a call.
*/
static constexpr int CHAT_WIDGET_MIN_HEIGHT = 50;
static constexpr int SCREENSHOT_GRABBER_OPENING_DELAY = 500;
static constexpr int TYPING_NOTIFICATION_DURATION = 3000;
namespace {
constexpr int CHAT_WIDGET_MIN_HEIGHT = 50;
constexpr int SCREENSHOT_GRABBER_OPENING_DELAY = 500;
constexpr int TYPING_NOTIFICATION_DURATION = 3000;
} // namespace
const QString ChatForm::ACTION_PREFIX = QStringLiteral("/me ");

View File

@ -64,11 +64,12 @@
* elements and methods to work with chat messages.
*/
static const QSize FILE_FLYOUT_SIZE{24, 24};
static const short FOOT_BUTTONS_SPACING = 2;
static const short MESSAGE_EDIT_HEIGHT = 50;
static const short MAIN_FOOT_LAYOUT_SPACING = 5;
static const QString FONT_STYLE[]{"normal", "italic", "oblique"};
namespace {
const QSize FILE_FLYOUT_SIZE{24, 24};
const short FOOT_BUTTONS_SPACING = 2;
const short MESSAGE_EDIT_HEIGHT = 50;
const short MAIN_FOOT_LAYOUT_SPACING = 5;
const QString FONT_STYLE[]{"normal", "italic", "oblique"};
/**
* @brief Creates CSS style string for needed class with specified font
@ -76,7 +77,7 @@ static const QString FONT_STYLE[]{"normal", "italic", "oblique"};
* @param name Class name
* @return Style string
*/
static QString fontToCss(const QFont& font, const QString& name)
QString fontToCss(const QFont& font, const QString& name)
{
QString result{"%1{"
"font-family: \"%2\"; "
@ -85,6 +86,7 @@ static QString fontToCss(const QFont& font, const QString& name)
"font-weight: normal;}"};
return result.arg(name).arg(font.family()).arg(font.pixelSize()).arg(FONT_STYLE[font.style()]);
}
} // namespace
/**
* @brief Searches for name (possibly alias) of someone with specified public key among all of your

View File

@ -52,7 +52,6 @@ const auto LABEL_PEER_TYPE_MUTED = QVariant(QStringLiteral("muted"));
const auto LABEL_PEER_PLAYING_AUDIO = QVariant(QStringLiteral("true"));
const auto LABEL_PEER_NOT_PLAYING_AUDIO = QVariant(QStringLiteral("false"));
const auto PEER_LABEL_STYLE_SHEET_PATH = QStringLiteral("chatArea/chatHead.css");
}
/**
* @brief Edit name for correct representation if it is needed
@ -73,6 +72,7 @@ QString editName(const QString& name)
result.append(QStringLiteral("")); // \u2026 Unicode symbol, not just three separate dots
return result;
}
}
/**
* @var QList<QLabel*> GroupChatForm::peerLabels

View File

@ -49,7 +49,8 @@
#include <QMouseEvent>
#include <QWindow>
static const QMap<IProfileInfo::SetAvatarResult, QString> SET_AVATAR_ERROR = {
namespace {
const QMap<IProfileInfo::SetAvatarResult, QString> SET_AVATAR_ERROR = {
{ IProfileInfo::SetAvatarResult::CanNotOpen,
ProfileForm::tr("Unable to open this file.") },
{ IProfileInfo::SetAvatarResult::CanNotRead,
@ -60,7 +61,7 @@ static const QMap<IProfileInfo::SetAvatarResult, QString> SET_AVATAR_ERROR = {
ProfileForm::tr("Empty path is unavaliable") },
};
static const QMap<IProfileInfo::RenameResult, QPair<QString, QString>> RENAME_ERROR = {
const QMap<IProfileInfo::RenameResult, QPair<QString, QString>> RENAME_ERROR = {
{ IProfileInfo::RenameResult::Error,
{ ProfileForm::tr("Failed to rename"),
ProfileForm::tr("Couldn't rename the profile to \"%1\"") }
@ -75,7 +76,7 @@ static const QMap<IProfileInfo::RenameResult, QPair<QString, QString>> RENAME_ER
},
};
static const QMap<IProfileInfo::SaveResult, QPair<QString, QString>> SAVE_ERROR = {
const QMap<IProfileInfo::SaveResult, QPair<QString, QString>> SAVE_ERROR = {
{ IProfileInfo::SaveResult::NoWritePermission,
{ ProfileForm::tr("Location not writable", "Title of permissions popup"),
ProfileForm::tr("You do not have permission to write to that location. Choose "
@ -91,11 +92,12 @@ static const QMap<IProfileInfo::SaveResult, QPair<QString, QString>> SAVE_ERROR
},
};
static const QPair<QString, QString> CAN_NOT_CHANGE_PASSWORD = {
const QPair<QString, QString> CAN_NOT_CHANGE_PASSWORD = {
ProfileForm::tr("Couldn't change password"),
ProfileForm::tr("Couldn't change database password, "
"it may be corrupted or use the old password.")
};
} // namespace
ProfileForm::ProfileForm(IProfileInfo* profileInfo_, QWidget* parent)
: QWidget{parent}

View File

@ -34,8 +34,9 @@
#include "src/widget/translator.h"
#include "src/widget/widget.h"
namespace {
// clang-format off
static QStringList locales = {
QStringList locales = {
"ar",
"be",
"ber",
@ -88,6 +89,7 @@ static QStringList locales = {
"zh_TW"
};
// clang-format on
} // namespace
/**
* @class GeneralForm

View File

@ -37,6 +37,7 @@
#include <QTimer>
#include <cassert>
namespace {
enum class Time
{
Today,
@ -52,7 +53,7 @@ enum class Time
Never
};
static const int LAST_TIME = static_cast<int>(Time::Never);
const int LAST_TIME = static_cast<int>(Time::Never);
Time getTimeBucket(const QDateTime& date)
{
@ -96,6 +97,7 @@ qint64 timeUntilTomorrow()
tomorrow.setTime(QTime()); // Midnight.
return now.msecsTo(tomorrow);
}
} // namespace
FriendListWidget::FriendListWidget(const Core &_core, Widget* parent, bool groupsOnTop)
: QWidget(parent)

View File

@ -26,17 +26,19 @@
* @brief Restore splitter from saved state and reset to default
*/
namespace {
/**
* @brief The width of the default splitter handles.
* By default, this property contains a value that depends on the user's
* platform and style preferences.
*/
static int defaultWidth = 0;
int defaultWidth = 0;
/**
* @brief Width of left splitter size in percents.
*/
const static int leftWidthPercent = 33;
const int leftWidthPercent = 33;
} // namespace
SplitterRestorer::SplitterRestorer(QSplitter* splitter_)
: splitter{splitter_}

View File

@ -64,10 +64,9 @@
*/
namespace {
const QLatin1String ThemeSubFolder{"themes/"};
const QLatin1String BuiltinThemeDefaultPath{":themes/default/"};
const QLatin1String BuiltinThemeDarkPath{":themes/dark/"};
}
const QLatin1String ThemeSubFolder{"themes/"};
const QLatin1String BuiltinThemeDefaultPath{":themes/default/"};
const QLatin1String BuiltinThemeDarkPath{":themes/dark/"};
// helper functions
QFont appFont(int pixelSize, int weight)
@ -83,13 +82,13 @@ QString qssifyFont(QFont font)
return QString("%1 %2px \"%3\"").arg(font.weight() * 8).arg(font.pixelSize()).arg(font.family());
}
static QMap<Style::ColorPalette, QColor> palette;
QMap<Style::ColorPalette, QColor> palette;
static QMap<QString, QString> dictColor;
static QMap<QString, QString> dictFont;
static QMap<QString, QString> dictTheme;
QMap<QString, QString> dictColor;
QMap<QString, QString> dictFont;
QMap<QString, QString> dictTheme;
static const QList<Style::ThemeNameColor> themeNameColors = {
const QList<Style::ThemeNameColor> themeNameColors = {
{Style::Light, QObject::tr("Default"), QColor()},
{Style::Light, QObject::tr("Blue"), QColor("#004aa4")},
{Style::Light, QObject::tr("Olive"), QColor("#97ba00")},
@ -102,6 +101,35 @@ static const QList<Style::ThemeNameColor> themeNameColors = {
{Style::Dark, QObject::tr("Dark violet"), QColor("#280d6c")}
};
const QMap<Style::ColorPalette, QString> aliasColors = {
{Style::TransferGood, "transferGood"},
{Style::TransferWait, "transferWait"},
{Style::TransferBad, "transferBad"},
{Style::TransferMiddle, "transferMiddle"},
{Style::MainText,"mainText"},
{Style::NameActive, "nameActive"},
{Style::StatusActive,"statusActive"},
{Style::GroundExtra, "groundExtra"},
{Style::GroundBase, "groundBase"},
{Style::Orange, "orange"},
{Style::Yellow, "yellow"},
{Style::ThemeDark, "themeDark"},
{Style::ThemeMediumDark, "themeMediumDark"},
{Style::ThemeMedium, "themeMedium"},
{Style::ThemeLight, "themeLight"},
{Style::Action, "action"},
{Style::Link, "link"},
{Style::SearchHighlighted, "searchHighlighted"},
{Style::SelectText, "selectText"},
};
// stylesheet filename, font -> stylesheet
// QString implicit sharing deduplicates stylesheets rather than constructing a new one each time
std::map<std::pair<const QString, const QFont>, const QString> stylesheetsCache;
QStringList existingImagesCache;
} // namespace
QStringList Style::getThemeColorNames()
{
QStringList l;
@ -135,33 +163,6 @@ QString Style::getThemeFolder()
return fullPath % QDir::separator();
}
static const QMap<Style::ColorPalette, QString> aliasColors = {
{Style::TransferGood, "transferGood"},
{Style::TransferWait, "transferWait"},
{Style::TransferBad, "transferBad"},
{Style::TransferMiddle, "transferMiddle"},
{Style::MainText,"mainText"},
{Style::NameActive, "nameActive"},
{Style::StatusActive,"statusActive"},
{Style::GroundExtra, "groundExtra"},
{Style::GroundBase, "groundBase"},
{Style::Orange, "orange"},
{Style::Yellow, "yellow"},
{Style::ThemeDark, "themeDark"},
{Style::ThemeMediumDark, "themeMediumDark"},
{Style::ThemeMedium, "themeMedium"},
{Style::ThemeLight, "themeLight"},
{Style::Action, "action"},
{Style::Link, "link"},
{Style::SearchHighlighted, "searchHighlighted"},
{Style::SelectText, "selectText"},
};
// stylesheet filename, font -> stylesheet
// QString implicit sharing deduplicates stylesheets rather than constructing a new one each time
static std::map<std::pair<const QString, const QFont>, const QString> stylesheetsCache;
const QString Style::getStylesheet(const QString& filename, const QFont& baseFont)
{
const QString fullPath = getThemeFolder() + filename;
@ -178,7 +179,6 @@ const QString Style::getStylesheet(const QString& filename, const QFont& baseFon
return newStylesheet;
}
static QStringList existingImagesCache;
const QString Style::getImagePath(const QString& filename)
{
QString fullPath = getThemeFolder() + filename;

View File

@ -29,7 +29,8 @@
using StringPair = QPair<QString, QString>;
static const StringPair TAGS[] {
namespace {
const StringPair TAGS[] {
PAIR_FORMAT("<b>", "</b>"),
PAIR_FORMAT("<i>", "</i>"),
PAIR_FORMAT("<u>", "</u>"),
@ -55,7 +56,7 @@ struct MarkdownToTags
StringPair htmlTags;
};
static const QVector<MarkdownToTags> SINGLE_SIGN_MARKDOWN {
const QVector<MarkdownToTags> SINGLE_SIGN_MARKDOWN {
{QStringLiteral("*"), TAGS[StyleType::BOLD]},
{QStringLiteral("/"), TAGS[StyleType::ITALIC]},
{QStringLiteral("_"), TAGS[StyleType::UNDERLINE]},
@ -63,14 +64,14 @@ static const QVector<MarkdownToTags> SINGLE_SIGN_MARKDOWN {
{QStringLiteral("`"), TAGS[StyleType::CODE]},
};
static const QVector<MarkdownToTags> DOUBLE_SIGN_MARKDOWN {
const QVector<MarkdownToTags> DOUBLE_SIGN_MARKDOWN {
{QStringLiteral("**"), TAGS[StyleType::BOLD]},
{QStringLiteral("//"), TAGS[StyleType::ITALIC]},
{QStringLiteral("__"), TAGS[StyleType::UNDERLINE]},
{QStringLiteral("~~"), TAGS[StyleType::STRIKE]},
};
static const QVector<MarkdownToTags> MULTI_SIGN_MARKDOWN {
const QVector<MarkdownToTags> MULTI_SIGN_MARKDOWN {
{QStringLiteral("```"), TAGS[StyleType::CODE]},
};
@ -78,7 +79,7 @@ static const QVector<MarkdownToTags> MULTI_SIGN_MARKDOWN {
* @brief Creates single container from two
*/
template<class Container>
static Container concat(const Container& first, const Container& last)
Container concat(const Container& first, const Container& last)
{
Container result;
result.reserve(first.size() + last.size());
@ -87,15 +88,15 @@ static Container concat(const Container& first, const Container& last)
return result;
}
static const QVector<MarkdownToTags> ALL_MARKDOWN_TYPES = concat(concat(SINGLE_SIGN_MARKDOWN,
const QVector<MarkdownToTags> ALL_MARKDOWN_TYPES = concat(concat(SINGLE_SIGN_MARKDOWN,
DOUBLE_SIGN_MARKDOWN),
MULTI_SIGN_MARKDOWN);
static const QVector<MarkdownToTags> SINGLE_AND_DOUBLE_MARKDOWN = concat(SINGLE_SIGN_MARKDOWN,
const QVector<MarkdownToTags> SINGLE_AND_DOUBLE_MARKDOWN = concat(SINGLE_SIGN_MARKDOWN,
DOUBLE_SIGN_MARKDOWN);
// any markdown type must work for this data the same way
static const QVector<StringPair> COMMON_WORK_CASES {
const QVector<StringPair> COMMON_WORK_CASES {
PAIR_FORMAT("%1a%1", "%2%1a%1%3"),
PAIR_FORMAT("%1aa%1", "%2%1aa%1%3"),
PAIR_FORMAT("%1aaa%1", "%2%1aaa%1%3"),
@ -103,7 +104,7 @@ static const QVector<StringPair> COMMON_WORK_CASES {
PAIR_FORMAT("%1aaa%1 %1aaa%1", "%2%1aaa%1%3 %2%1aaa%1%3"),
};
static const QVector<StringPair> SINGLE_SIGN_WORK_CASES {
const QVector<StringPair> SINGLE_SIGN_WORK_CASES {
PAIR_FORMAT("a %1a%1", "a %2%1a%1%3"),
PAIR_FORMAT("%1a%1 a", "%2%1a%1%3 a"),
PAIR_FORMAT("a %1a%1 a", "a %2%1a%1%3 a"),
@ -112,7 +113,7 @@ static const QVector<StringPair> SINGLE_SIGN_WORK_CASES {
};
// only double-sign markdown must work for this data
static const QVector<StringPair> DOUBLE_SIGN_WORK_CASES {
const QVector<StringPair> DOUBLE_SIGN_WORK_CASES {
// Must apply formatting to strings which contain reserved symbols
PAIR_FORMAT("%1aaa%2%1", "%3%1aaa%2%1%4"),
PAIR_FORMAT("%1%2aaa%1", "%3%1%2aaa%1%4"),
@ -123,7 +124,7 @@ static const QVector<StringPair> DOUBLE_SIGN_WORK_CASES {
};
// only multi-sign markdown must work for this data
static const QVector<StringPair> MULTI_SIGN_WORK_CASES {
const QVector<StringPair> MULTI_SIGN_WORK_CASES {
PAIR_FORMAT("%1int main()\n{ return 0;\n}%1", "%2%1"
"int main()\n{ return 0;\n}"
"%1%3"),
@ -137,7 +138,7 @@ static const QVector<StringPair> MULTI_SIGN_WORK_CASES {
};
// any type of markdown must fail for this data
static const QVector<QString> COMMON_EXCEPTIONS {
const QVector<QString> COMMON_EXCEPTIONS {
// No empty formatting string
QStringLiteral("%1%1"),
// Formatting string must be enclosed by whitespace symbols, newlines or message start/end
@ -146,7 +147,7 @@ static const QVector<QString> COMMON_EXCEPTIONS {
QStringLiteral("a\n%1aa%1a"), QStringLiteral("a%1aa%1\na"),
};
static const QVector<QString> SINGLE_AND_DOUBLE_SIGN_EXCEPTIONS {
const QVector<QString> SINGLE_AND_DOUBLE_SIGN_EXCEPTIONS {
// Formatting text must not start/end with whitespace symbols
QStringLiteral("%1 %1"), QStringLiteral("%1 a%1"), QStringLiteral("%1a %1"),
// No newlines
@ -155,13 +156,13 @@ static const QVector<QString> SINGLE_AND_DOUBLE_SIGN_EXCEPTIONS {
};
// only single-sign markdown must fail for this data
static const QVector<QString> SINGLE_SIGN_EXCEPTIONS {
const QVector<QString> SINGLE_SIGN_EXCEPTIONS {
// Reserved symbols within formatting string are disallowed
QStringLiteral("%1aa%1a%1"), QStringLiteral("%1aa%1%1"), QStringLiteral("%1%1aa%1"),
QStringLiteral("%1%1%1"),
};
static const QVector<StringPair> MIXED_FORMATTING_SPECIAL_CASES {
const QVector<StringPair> MIXED_FORMATTING_SPECIAL_CASES {
// Must allow mixed formatting if there is no tag overlap in result
PAIR_FORMAT("aaa *aaa /aaa/ aaa*", "aaa <b>aaa <i>aaa</i> aaa</b>"),
PAIR_FORMAT("aaa *aaa /aaa* aaa/", "aaa *aaa <i>aaa* aaa</i>"),
@ -170,7 +171,7 @@ static const QVector<StringPair> MIXED_FORMATTING_SPECIAL_CASES {
#define MAKE_LINK(url) "<a href=\"" url "\">" url "</a>"
#define MAKE_WWW_LINK(url) "<a href=\"http://" url "\">" url "</a>"
static const QVector<QPair<QString, QString>> URL_CASES {
const QVector<QPair<QString, QString>> URL_CASES {
PAIR_FORMAT("https://github.com/qTox/qTox/issues/4233",
MAKE_LINK("https://github.com/qTox/qTox/issues/4233")),
PAIR_FORMAT("www.youtube.com", MAKE_WWW_LINK("www.youtube.com")),
@ -254,7 +255,7 @@ using OutputProcessor = std::function<QString(const QString&, const MarkdownToTa
* depending on user need
* @param processOutput Same as previous parameter but is applied to markdown output
*/
static void workCasesTest(MarkdownFunction applyMarkdown,
void workCasesTest(MarkdownFunction applyMarkdown,
const QVector<MarkdownToTags>& markdownToTags,
const QVector<StringPair>& testData,
bool showSymbols,
@ -282,7 +283,7 @@ static void workCasesTest(MarkdownFunction applyMarkdown,
* @param showSymbols True if it is supposed to leave markdown symbols after formatting, false
* otherwise
*/
static void exceptionsTest(MarkdownFunction applyMarkdown,
void exceptionsTest(MarkdownFunction applyMarkdown,
const QVector<MarkdownToTags>& markdownToTags,
const QVector<QString>& exceptions,
bool showSymbols)
@ -301,7 +302,7 @@ static void exceptionsTest(MarkdownFunction applyMarkdown,
* @param pairs Collection of "source message - markdown result" pairs representing cases where
* markdown must not to work
*/
static void specialCasesTest(MarkdownFunction applyMarkdown,
void specialCasesTest(MarkdownFunction applyMarkdown,
const QVector<StringPair>& pairs)
{
for (const auto& p : pairs) {
@ -316,7 +317,7 @@ using UrlHighlightFunction = QString(*)(const QString&);
* @brief Function for testing URL highlighting
* @param data Test data - map of "URL - HTML-wrapped URL"
*/
static void urlHighlightTest(UrlHighlightFunction function, const QVector<QPair<QString, QString>>& data)
void urlHighlightTest(UrlHighlightFunction function, const QVector<QPair<QString, QString>>& data)
{
for (const QPair<QString, QString>& p : data) {
QString result = function(p.first);
@ -324,6 +325,66 @@ static void urlHighlightTest(UrlHighlightFunction function, const QVector<QPair<
}
}
QString commonWorkCasesProcessInput(const QString& str, const MarkdownToTags& mtt)
{
return str.arg(mtt.markdownSequence);
}
QString commonWorkCasesProcessOutput(const QString& str,
const MarkdownToTags& mtt,
bool showSymbols)
{
const StringPair& tags = mtt.htmlTags;
return str.arg(showSymbols ? mtt.markdownSequence : QString{}).arg(tags.first).arg(tags.second);
}
QString singleSignWorkCasesProcessInput(const QString& str, const MarkdownToTags& mtt)
{
return str.arg(mtt.markdownSequence);
}
QString singleSignWorkCasesProcessOutput(const QString& str,
const MarkdownToTags& mtt,
bool showSymbols)
{
const StringPair& tags = mtt.htmlTags;
return str.arg(showSymbols ? mtt.markdownSequence : "")
.arg(tags.first)
.arg(tags.second)
.arg(mtt.markdownSequence);
}
QString doubleSignWorkCasesProcessInput(const QString& str, const MarkdownToTags& mtt)
{
return str.arg(mtt.markdownSequence).arg(mtt.markdownSequence[0]);
}
QString doubleSignWorkCasesProcessOutput(const QString& str,
const MarkdownToTags& mtt,
bool showSymbols)
{
const StringPair& tags = mtt.htmlTags;
return str.arg(showSymbols ? mtt.markdownSequence : "")
.arg(mtt.markdownSequence[0])
.arg(tags.first)
.arg(tags.second);
}
QString multiSignWorkCasesProcessInput(const QString& str, const MarkdownToTags& mtt)
{
return str.arg(mtt.markdownSequence);
}
QString multiSignWorkCasesProcessOutput(const QString& str,
const MarkdownToTags& mtt,
bool showSymbols)
{
const auto tags = mtt.htmlTags;
return str.arg(showSymbols ? mtt.markdownSequence : "", tags.first, tags.second);
}
} // namespace
class TestTextFormatter : public QObject
{
Q_OBJECT
@ -345,23 +406,10 @@ private slots:
void mixedFormattingSpecialCases();
void urlTest();
private:
const MarkdownFunction markdownFunction = applyMarkdown;
UrlHighlightFunction urlHighlightFunction = highlightURI;
const MarkdownFunction markdownFunction = TextFormatter::applyMarkdown;
UrlHighlightFunction urlHighlightFunction = TextFormatter::highlightURI;
};
static QString commonWorkCasesProcessInput(const QString& str, const MarkdownToTags& mtt)
{
return str.arg(mtt.markdownSequence);
}
static QString commonWorkCasesProcessOutput(const QString& str,
const MarkdownToTags& mtt,
bool showSymbols)
{
const StringPair& tags = mtt.htmlTags;
return str.arg(showSymbols ? mtt.markdownSequence : QString{}).arg(tags.first).arg(tags.second);
}
void TestTextFormatter::commonWorkCasesShowSymbols()
{
workCasesTest(markdownFunction,
@ -382,22 +430,6 @@ void TestTextFormatter::commonWorkCasesHideSymbols()
commonWorkCasesProcessOutput);
}
static QString singleSignWorkCasesProcessInput(const QString& str, const MarkdownToTags& mtt)
{
return str.arg(mtt.markdownSequence);
}
static QString singleSignWorkCasesProcessOutput(const QString& str,
const MarkdownToTags& mtt,
bool showSymbols)
{
const StringPair& tags = mtt.htmlTags;
return str.arg(showSymbols ? mtt.markdownSequence : "")
.arg(tags.first)
.arg(tags.second)
.arg(mtt.markdownSequence);
}
void TestTextFormatter::singleSignWorkCasesShowSymbols()
{
workCasesTest(markdownFunction,
@ -418,22 +450,6 @@ void TestTextFormatter::singleSignWorkCasesHideSymbols()
singleSignWorkCasesProcessOutput);
}
static QString doubleSignWorkCasesProcessInput(const QString& str, const MarkdownToTags& mtt)
{
return str.arg(mtt.markdownSequence).arg(mtt.markdownSequence[0]);
}
static QString doubleSignWorkCasesProcessOutput(const QString& str,
const MarkdownToTags& mtt,
bool showSymbols)
{
const StringPair& tags = mtt.htmlTags;
return str.arg(showSymbols ? mtt.markdownSequence : "")
.arg(mtt.markdownSequence[0])
.arg(tags.first)
.arg(tags.second);
}
void TestTextFormatter::doubleSignWorkCasesShowSymbols()
{
workCasesTest(markdownFunction,
@ -454,19 +470,6 @@ void TestTextFormatter::doubleSignWorkCasesHideSymbols()
doubleSignWorkCasesProcessOutput);
}
static QString multiSignWorkCasesProcessInput(const QString& str, const MarkdownToTags& mtt)
{
return str.arg(mtt.markdownSequence);
}
static QString multiSignWorkCasesProcessOutput(const QString& str,
const MarkdownToTags& mtt,
bool showSymbols)
{
const auto tags = mtt.htmlTags;
return str.arg(showSymbols ? mtt.markdownSequence : "", tags.first, tags.second);
}
void TestTextFormatter::multiSignWorkCasesHideSymbols()
{
workCasesTest(markdownFunction,
@ -535,4 +538,3 @@ void TestTextFormatter::urlTest()
QTEST_GUILESS_MAIN(TestTextFormatter)
#include "textformatter_test.moc"

View File

@ -22,8 +22,9 @@
#include <QPainter>
#include <QTest>
static const auto rowColor = QColor(Qt::green).rgb();
static const auto colColor = QColor(Qt::blue).rgb();
namespace {
const auto rowColor = QColor(Qt::green).rgb();
const auto colColor = QColor(Qt::blue).rgb();
enum class Side
{
@ -33,7 +34,7 @@ enum class Side
right
};
static QPoint getPosition(Side side)
QPoint getPosition(Side side)
{
int x, y;
switch (side)
@ -67,11 +68,11 @@ static QPoint getPosition(Side side)
return {x, y};
}
static QRgb getColor(const QImage& image, Side side)
QRgb getColor(const QImage& image, Side side)
{
return image.pixel(getPosition(side));
}
} // namespace
class TestExifTransform : public QObject
{

View File

@ -28,8 +28,9 @@
#include <set>
#include <deque>
static constexpr uint64_t testMaxExtendedMessageSize = 10 * 1024 * 1024;
namespace {
constexpr uint64_t testMaxExtendedMessageSize = 10 * 1024 * 1024;
}
class MockCoreExtPacket : public ICoreExtPacket
{

View File

@ -24,7 +24,7 @@
#include <QtTest/QtTest>
namespace {
static const QString TEST_USERNAME = "qTox Tester #1";
const QString TEST_USERNAME = "qTox Tester #1";
Message createMessage(const QString& content)
{

View File

@ -33,6 +33,7 @@ struct SqliteMasterEntry {
QString sql;
};
bool operator==(const SqliteMasterEntry& lhs, const SqliteMasterEntry& rhs);
bool operator==(const SqliteMasterEntry& lhs, const SqliteMasterEntry& rhs)
{
return lhs.name == rhs.name &&

View File

@ -37,7 +37,9 @@ private slots:
void testExtendedMessageCoordination();
};
namespace {
void completionFn(bool) {}
} // namespace
void TestOfflineMsgEngine::testReceiptBeforeMessage()
{

View File

@ -28,8 +28,6 @@
#include <memory>
QString getAsRichText(const QString& key);
class TestSmileyPack : public QObject
{
Q_OBJECT
@ -63,10 +61,10 @@ void TestSmileyPack::testSmilifySingleCharEmoji()
auto& smileyPack = SmileyPack::getInstance();
auto result = smileyPack.smileyfied("😊");
QVERIFY(result == getAsRichText("😊"));
QVERIFY(result == SmileyPack::getAsRichText("😊"));
result = smileyPack.smileyfied("Some😊Letters");
QVERIFY(result == "Some" + getAsRichText("😊") + "Letters");
QVERIFY(result == "Some" + SmileyPack::getAsRichText("😊") + "Letters");
}
/**
@ -78,15 +76,15 @@ void TestSmileyPack::testSmilifyMultiCharEmoji()
auto& smileyPack = SmileyPack::getInstance();
auto result = smileyPack.smileyfied("🇬🇧");
QVERIFY(result == getAsRichText("🇬🇧"));
QVERIFY(result == SmileyPack::getAsRichText("🇬🇧"));
result = smileyPack.smileyfied("Some🇬🇧Letters");
QVERIFY(result == "Some" + getAsRichText("🇬🇧") + "Letters");
QVERIFY(result == "Some" + SmileyPack::getAsRichText("🇬🇧") + "Letters");
// This verifies that multi-char emojis are not accidentally
// considered a multichar ascii smiley
result = smileyPack.smileyfied("🇫🇷🇬🇧");
QVERIFY(result == getAsRichText("🇫🇷") + getAsRichText("🇬🇧"));
QVERIFY(result == SmileyPack::getAsRichText("🇫🇷") + SmileyPack::getAsRichText("🇬🇧"));
}
@ -99,7 +97,7 @@ void TestSmileyPack::testSmilifyAsciiEmoticon()
auto& smileyPack = SmileyPack::getInstance();
auto result = smileyPack.smileyfied(":-)");
QVERIFY(result == getAsRichText(":-)"));
QVERIFY(result == SmileyPack::getAsRichText(":-)"));
constexpr auto testMsg = "Some:-)Letters";
result = smileyPack.smileyfied(testMsg);
@ -109,7 +107,7 @@ void TestSmileyPack::testSmilifyAsciiEmoticon()
QVERIFY(result == testMsg);
result = smileyPack.smileyfied(" :-) ");
QVERIFY(result == " " + getAsRichText(":-)") + " ");
QVERIFY(result == " " + SmileyPack::getAsRichText(":-)") + " ");
}

View File

@ -53,8 +53,10 @@ void TestPosixSignalNotifier::checkUsrSignalHandling()
QCOMPARE(args.first().toInt(), SIGUSR1);
}
namespace {
void sighandler(int) {
}
}
void TestPosixSignalNotifier::checkIgnoreExtraSignals()
{