From adc0f0cca60d87f86a3ea65927ec41c4f1bf2e6b Mon Sep 17 00:00:00 2001 From: Anthony Bilinski Date: Fri, 11 Mar 2022 02:18:35 -0800 Subject: [PATCH] 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 --- audio/src/backend/openal.cpp | 7 +- src/chatlog/chatmessage.cpp | 4 +- src/chatlog/chatwidget.cpp | 4 +- src/chatlog/textformatter.cpp | 52 +++--- src/chatlog/textformatter.h | 7 +- src/core/toxencrypt.cpp | 187 ++++++++++---------- src/main.cpp | 10 +- src/model/group.cpp | 4 +- src/model/profile/profileinfo.cpp | 111 ++++++------ src/nexus.cpp | 4 +- src/persistence/history.cpp | 2 +- src/persistence/settingsserializer.cpp | 8 +- src/persistence/settingsserializer.h | 19 +- src/persistence/smileypack.cpp | 33 ++-- src/persistence/smileypack.h | 1 + src/platform/autorun_osx.cpp | 4 +- src/platform/autorun_win.cpp | 6 +- src/platform/autorun_xdg.cpp | 4 +- src/platform/camera/directshow.cpp | 4 +- src/platform/camera/v4l2.cpp | 10 +- src/platform/posixsignalnotifier.cpp | 24 +-- src/video/cameradevice.cpp | 6 +- src/video/videosurface.cpp | 11 +- src/widget/about/aboutfriendform.cpp | 17 +- src/widget/chatformheader.cpp | 10 +- src/widget/contentdialog.cpp | 10 +- src/widget/form/chatform.cpp | 9 +- src/widget/form/genericchatform.cpp | 14 +- src/widget/form/groupchatform.cpp | 2 +- src/widget/form/profileform.cpp | 10 +- src/widget/form/settings/generalform.cpp | 4 +- src/widget/friendlistwidget.cpp | 4 +- src/widget/splitterrestorer.cpp | 6 +- src/widget/style.cpp | 74 ++++---- test/chatlog/textformatter_test.cpp | 164 ++++++++--------- test/model/exiftransform_test.cpp | 11 +- test/model/friendmessagedispatcher_test.cpp | 5 +- test/model/sessionchatlog_test.cpp | 2 +- test/persistence/dbschema_test.cpp | 1 + test/persistence/offlinemsgengine_test.cpp | 2 + test/persistence/smileypack_test.cpp | 16 +- test/platform/posixsignalnotifier_test.cpp | 2 + 42 files changed, 463 insertions(+), 422 deletions(-) diff --git a/audio/src/backend/openal.cpp b/audio/src/backend/openal.cpp index e7eff0ca1..abd965b78 100644 --- a/audio/src/backend/openal.cpp +++ b/audio/src/backend/openal.cpp @@ -41,7 +41,6 @@ void applyGain(int16_t* buffer, uint32_t bufferSize, qreal gainFactor) std::numeric_limits::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; diff --git a/src/chatlog/chatmessage.cpp b/src/chatlog/chatmessage.cpp index 2b726845d..fd071c7db 100644 --- a/src/chatlog/chatmessage.cpp +++ b/src/chatlog/chatmessage.cpp @@ -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); } diff --git a/src/chatlog/chatwidget.cpp b/src/chatlog/chatwidget.cpp index 748ff7f5e..3452cf768 100644 --- a/src/chatlog/chatwidget.cpp +++ b/src/chatlog/chatwidget.cpp @@ -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 T clamp(T x, T min, T max) diff --git a/src/chatlog/textformatter.cpp b/src/chatlog/textformatter.cpp index 3c5c7ba92..0d7cda09c 100644 --- a/src/chatlog/textformatter.cpp +++ b/src/chatlog/textformatter.cpp @@ -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 REGEX_TO_WRAPPER[] { +const QPair REGEX_TO_WRAPPER[] { REGEXP_WRAPPER_PAIR(SINGLE_SLASH_PATTERN, "%1"), REGEXP_WRAPPER_PAIR(SINGLE_SIGN_PATTERN.arg('*'), "%1"), REGEXP_WRAPPER_PAIR(SINGLE_SIGN_PATTERN.arg('_'), "%1"), @@ -75,14 +76,14 @@ static const QPair REGEX_TO_WRAPPER[] { #undef REGEXP_WRAPPER_PAIR -static const QString HREF_WRAPPER = QStringLiteral(R"(%1)"); -static const QString WWW_WRAPPER = QStringLiteral(R"(%1)"); +const QString HREF_WRAPPER = QStringLiteral(R"(%1)"); +const QString WWW_WRAPPER = QStringLiteral(R"(%1)"); -static const QVector WWW_WORD_PATTERN = { +const QVector WWW_WORD_PATTERN = { QRegularExpression(QStringLiteral(R"((?<=^|\s)\S*((www\.)\S+))")) }; -static const QVector URI_WORD_PATTERNS = { +const QVector 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 URI_WRAPPING_CHARS[] = { +const QPair URI_WRAPPING_CHARS[] = { {QString("("), QString(")")}, {QString("["), QString("]")}, {QString("""), QString(""")}, @@ -111,7 +112,7 @@ static const QPair 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& 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& pair : REGEX_TO_WRAPPER) { diff --git a/src/chatlog/textformatter.h b/src/chatlog/textformatter.h index 8660d2ee9..afa4f312a 100644 --- a/src/chatlog/textformatter.h +++ b/src/chatlog/textformatter.h @@ -21,6 +21,9 @@ #include -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 diff --git a/src/core/toxencrypt.cpp b/src/core/toxencrypt.cpp index b610a8dec..e9195b09b 100644 --- a/src/core/toxencrypt.cpp +++ b/src/core/toxencrypt.cpp @@ -25,12 +25,98 @@ #include #include -// 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."); - } -} diff --git a/src/main.cpp b/src/main.cpp index 77d8a623e..229af9977 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -47,9 +47,10 @@ #include "platform/posixsignalnotifier.h" #endif +namespace { #ifdef LOG_TO_FILE -static QAtomicPointer logFileFile = nullptr; -static QList* logBuffer = +QAtomicPointer logFileFile = nullptr; +QList* logBuffer = new QList(); // 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 uriDialog; +std::unique_ptr 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[]) { diff --git a/src/model/group.cpp b/src/model/group.cpp index c53f73681..975c88610 100644 --- a/src/model/group.cpp +++ b/src/model/group.cpp @@ -28,7 +28,9 @@ #include -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_) diff --git a/src/model/profile/profileinfo.cpp b/src/model/profile/profileinfo.cpp index eebe3934d..71015d531 100644 --- a/src/model/profile/profileinfo.cpp +++ b/src/model/profile/profileinfo.cpp @@ -30,6 +30,62 @@ #include #include +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 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 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. diff --git a/src/nexus.cpp b/src/nexus.cpp index 88decce49..59abf367d 100644 --- a/src/nexus.cpp +++ b/src/nexus.cpp @@ -55,7 +55,9 @@ Q_DECLARE_OPAQUE_POINTER(ToxAV*) -static Nexus* nexus{nullptr}; +namespace { +Nexus* nexus{nullptr}; +} // namespace Nexus::Nexus(QObject* parent) : QObject(parent) diff --git a/src/persistence/history.cpp b/src/persistence/history.cpp index 93fb3a296..d776f4666 100644 --- a/src/persistence/history.cpp +++ b/src/persistence/history.cpp @@ -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) { diff --git a/src/persistence/settingsserializer.cpp b/src/persistence/settingsserializer.cpp index 446c956e5..3f39d8107 100644 --- a/src/persistence/settingsserializer.cpp +++ b/src/persistence/settingsserializer.cpp @@ -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_} diff --git a/src/persistence/settingsserializer.h b/src/persistence/settingsserializer.h index ed4b07fa1..10fa0caa5 100644 --- a/src/persistence/settingsserializer.h +++ b/src/persistence/settingsserializer.h @@ -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() diff --git a/src/persistence/smileypack.cpp b/src/persistence/smileypack.cpp index b924ea3f6..ab20f3448 100644 --- a/src/persistence/smileypack.cpp +++ b/src/persistence/smileypack.cpp @@ -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(""); +const QString RICH_TEXT_PATTERN = QStringLiteral(""); -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; } diff --git a/src/persistence/smileypack.h b/src/persistence/smileypack.h index 1655b3f41..eafa4c8ea 100644 --- a/src/persistence/smileypack.h +++ b/src/persistence/smileypack.h @@ -40,6 +40,7 @@ public: QString smileyfied(const QString& msg); QList getEmoticons() const; std::shared_ptr getAsIcon(const QString& key) const; + static QString getAsRichText(const QString& key); private slots: void onSmileyPackChanged(); diff --git a/src/platform/autorun_osx.cpp b/src/platform/autorun_osx.cpp index 4c1c9cc97..3b764636d 100644 --- a/src/platform/autorun_osx.cpp +++ b/src/platform/autorun_osx.cpp @@ -24,7 +24,9 @@ #include #include -static int state; +namespace { +int state; +} // namespace bool Platform::setAutorun(bool on) { diff --git a/src/platform/autorun_win.cpp b/src/platform/autorun_win.cpp index 6d7c38fdf..f0d445022 100644 --- a/src/platform/autorun_win.cpp +++ b/src/platform/autorun_win.cpp @@ -23,6 +23,7 @@ #include #include +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() diff --git a/src/platform/autorun_xdg.cpp b/src/platform/autorun_xdg.cpp index b1b00f09f..3524d638e 100644 --- a/src/platform/autorun_xdg.cpp +++ b/src/platform/autorun_xdg.cpp @@ -23,7 +23,7 @@ #include #include -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) { diff --git a/src/platform/camera/directshow.cpp b/src/platform/camera/directshow.cpp index 4a85a3e17..3b5660151 100644 --- a/src/platform/camera/directshow.cpp +++ b/src/platform/camera/directshow.cpp @@ -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> DirectShow::getDeviceList() { diff --git a/src/platform/camera/v4l2.cpp b/src/platform/camera/v4l2.cpp index 74f724be5..71cb5e805 100644 --- a/src/platform/camera/v4l2.cpp +++ b/src/platform/camera/v4l2.cpp @@ -37,7 +37,8 @@ * stdout and is not part of the public API for some reason. */ -static std::map createPixFmtToQuality() +namespace { +std::map createPixFmtToQuality() { std::map m; m[V4L2_PIX_FMT_H264] = 3; @@ -48,7 +49,7 @@ static std::map createPixFmtToQuality() } const std::map pixFmtToQuality = createPixFmtToQuality(); -static std::map createPixFmtToName() +std::map createPixFmtToName() { std::map m; m[V4L2_PIX_FMT_H264] = QString("h264"); @@ -59,7 +60,7 @@ static std::map createPixFmtToName() } const std::map 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 getDeviceModeFramerates(int fd, unsigned w, unsigned h, +QVector getDeviceModeFramerates(int fd, unsigned w, unsigned h, uint32_t pixelFormat) { QVector rates; @@ -121,6 +122,7 @@ static QVector getDeviceModeFramerates(int fd, unsigned w, unsigned h, return rates; } +} // namespace QVector v4l2::getDeviceModes(QString devName) { diff --git a/src/platform/posixsignalnotifier.cpp b/src/platform/posixsignalnotifier.cpp index f5813329b..cefeee741 100644 --- a/src/platform/posixsignalnotifier.cpp +++ b/src/platform/posixsignalnotifier.cpp @@ -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 g_signalSocketPair; +std::atomic_flag g_signalSocketUsageFlag = ATOMIC_FLAG_INIT; +std::array 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); } diff --git a/src/video/cameradevice.cpp b/src/video/cameradevice.cpp index 132f8a688..ba2379931 100644 --- a/src/video/cameradevice.cpp +++ b/src/video/cameradevice.cpp @@ -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 CameraDevice::openDevices; QMutex CameraDevice::openDeviceLock, CameraDevice::iformatLock; -static AvFindInputFormatRet idesktopFormat{nullptr}; -static AvFindInputFormatRet iformat{nullptr}; CameraDevice::CameraDevice(const QString& devName_, AVFormatContext* context_) : devName{devName_} diff --git a/src/video/videosurface.cpp b/src/video/videosurface.cpp index b2ddbcecc..e1d3d5b3c 100644 --- a/src/video/videosurface.cpp +++ b/src/video/videosurface.cpp @@ -30,16 +30,17 @@ #include #include -/** - * @var std::atomic_bool VideoSurface::frameLock - * @brief Fast lock for lastFrame. - */ - +namespace { float getSizeRatio(const QSize size) { return size.width() / static_cast(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} diff --git a/src/widget/about/aboutfriendform.cpp b/src/widget/about/aboutfriendform.cpp index ea27f22a0..34a1446cc 100644 --- a/src/widget/about/aboutfriendform.cpp +++ b/src/widget/about/aboutfriendform.cpp @@ -26,6 +26,16 @@ #include #include +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 _about, QWidget* parent) : QDialog(parent) , ui(new Ui::AboutFriendForm) @@ -72,13 +82,6 @@ AboutFriendForm::AboutFriendForm(std::unique_ptr _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 = [&]{ diff --git a/src/widget/chatformheader.cpp b/src/widget/chatformheader.cpp index 0385b8ff0..24e16d301 100644 --- a/src/widget/chatformheader.cpp +++ b/src/widget/chatformheader.cpp @@ -36,12 +36,12 @@ #include #include -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[] = { diff --git a/src/widget/contentdialog.cpp b/src/widget/contentdialog.cpp index 8149bbd1d..b072b7b07 100644 --- a/src/widget/contentdialog.cpp +++ b/src/widget/contentdialog.cpp @@ -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) diff --git a/src/widget/form/chatform.cpp b/src/widget/form/chatform.cpp index c0898cb2f..5b8327981 100644 --- a/src/widget/form/chatform.cpp +++ b/src/widget/form/chatform.cpp @@ -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 "); diff --git a/src/widget/form/genericchatform.cpp b/src/widget/form/genericchatform.cpp index 39068fd3f..a7b73f9c5 100644 --- a/src/widget/form/genericchatform.cpp +++ b/src/widget/form/genericchatform.cpp @@ -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 diff --git a/src/widget/form/groupchatform.cpp b/src/widget/form/groupchatform.cpp index f8fc78814..c815e9b6c 100644 --- a/src/widget/form/groupchatform.cpp +++ b/src/widget/form/groupchatform.cpp @@ -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 GroupChatForm::peerLabels diff --git a/src/widget/form/profileform.cpp b/src/widget/form/profileform.cpp index 89b5cf160..6fe2fa6da 100644 --- a/src/widget/form/profileform.cpp +++ b/src/widget/form/profileform.cpp @@ -49,7 +49,8 @@ #include #include -static const QMap SET_AVATAR_ERROR = { +namespace { +const QMap SET_AVATAR_ERROR = { { IProfileInfo::SetAvatarResult::CanNotOpen, ProfileForm::tr("Unable to open this file.") }, { IProfileInfo::SetAvatarResult::CanNotRead, @@ -60,7 +61,7 @@ static const QMap SET_AVATAR_ERROR = { ProfileForm::tr("Empty path is unavaliable") }, }; -static const QMap> RENAME_ERROR = { +const QMap> 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> RENAME_ER }, }; -static const QMap> SAVE_ERROR = { +const QMap> 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> SAVE_ERROR }, }; -static const QPair CAN_NOT_CHANGE_PASSWORD = { +const QPair 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} diff --git a/src/widget/form/settings/generalform.cpp b/src/widget/form/settings/generalform.cpp index 7fa24b18a..378d85158 100644 --- a/src/widget/form/settings/generalform.cpp +++ b/src/widget/form/settings/generalform.cpp @@ -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 diff --git a/src/widget/friendlistwidget.cpp b/src/widget/friendlistwidget.cpp index f891dc971..bc894992c 100644 --- a/src/widget/friendlistwidget.cpp +++ b/src/widget/friendlistwidget.cpp @@ -37,6 +37,7 @@ #include #include +namespace { enum class Time { Today, @@ -52,7 +53,7 @@ enum class Time Never }; -static const int LAST_TIME = static_cast(Time::Never); +const int LAST_TIME = static_cast(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) diff --git a/src/widget/splitterrestorer.cpp b/src/widget/splitterrestorer.cpp index 55082e757..3c0a18668 100644 --- a/src/widget/splitterrestorer.cpp +++ b/src/widget/splitterrestorer.cpp @@ -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_} diff --git a/src/widget/style.cpp b/src/widget/style.cpp index 0edbf7c86..f16454f53 100644 --- a/src/widget/style.cpp +++ b/src/widget/style.cpp @@ -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 palette; +QMap palette; -static QMap dictColor; -static QMap dictFont; -static QMap dictTheme; +QMap dictColor; +QMap dictFont; +QMap dictTheme; -static const QList themeNameColors = { +const QList 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 themeNameColors = { {Style::Dark, QObject::tr("Dark violet"), QColor("#280d6c")} }; +const QMap 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, 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 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, 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; diff --git a/test/chatlog/textformatter_test.cpp b/test/chatlog/textformatter_test.cpp index 03a7f4b46..3d3c98bf9 100644 --- a/test/chatlog/textformatter_test.cpp +++ b/test/chatlog/textformatter_test.cpp @@ -29,7 +29,8 @@ using StringPair = QPair; -static const StringPair TAGS[] { +namespace { +const StringPair TAGS[] { PAIR_FORMAT("", ""), PAIR_FORMAT("", ""), PAIR_FORMAT("", ""), @@ -55,7 +56,7 @@ struct MarkdownToTags StringPair htmlTags; }; -static const QVector SINGLE_SIGN_MARKDOWN { +const QVector SINGLE_SIGN_MARKDOWN { {QStringLiteral("*"), TAGS[StyleType::BOLD]}, {QStringLiteral("/"), TAGS[StyleType::ITALIC]}, {QStringLiteral("_"), TAGS[StyleType::UNDERLINE]}, @@ -63,14 +64,14 @@ static const QVector SINGLE_SIGN_MARKDOWN { {QStringLiteral("`"), TAGS[StyleType::CODE]}, }; -static const QVector DOUBLE_SIGN_MARKDOWN { +const QVector DOUBLE_SIGN_MARKDOWN { {QStringLiteral("**"), TAGS[StyleType::BOLD]}, {QStringLiteral("//"), TAGS[StyleType::ITALIC]}, {QStringLiteral("__"), TAGS[StyleType::UNDERLINE]}, {QStringLiteral("~~"), TAGS[StyleType::STRIKE]}, }; -static const QVector MULTI_SIGN_MARKDOWN { +const QVector MULTI_SIGN_MARKDOWN { {QStringLiteral("```"), TAGS[StyleType::CODE]}, }; @@ -78,7 +79,7 @@ static const QVector MULTI_SIGN_MARKDOWN { * @brief Creates single container from two */ template -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 ALL_MARKDOWN_TYPES = concat(concat(SINGLE_SIGN_MARKDOWN, +const QVector ALL_MARKDOWN_TYPES = concat(concat(SINGLE_SIGN_MARKDOWN, DOUBLE_SIGN_MARKDOWN), MULTI_SIGN_MARKDOWN); -static const QVector SINGLE_AND_DOUBLE_MARKDOWN = concat(SINGLE_SIGN_MARKDOWN, +const QVector 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 COMMON_WORK_CASES { +const QVector 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 COMMON_WORK_CASES { PAIR_FORMAT("%1aaa%1 %1aaa%1", "%2%1aaa%1%3 %2%1aaa%1%3"), }; -static const QVector SINGLE_SIGN_WORK_CASES { +const QVector 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 SINGLE_SIGN_WORK_CASES { }; // only double-sign markdown must work for this data -static const QVector DOUBLE_SIGN_WORK_CASES { +const QVector 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 DOUBLE_SIGN_WORK_CASES { }; // only multi-sign markdown must work for this data -static const QVector MULTI_SIGN_WORK_CASES { +const QVector 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 MULTI_SIGN_WORK_CASES { }; // any type of markdown must fail for this data -static const QVector COMMON_EXCEPTIONS { +const QVector 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 COMMON_EXCEPTIONS { QStringLiteral("a\n%1aa%1a"), QStringLiteral("a%1aa%1\na"), }; -static const QVector SINGLE_AND_DOUBLE_SIGN_EXCEPTIONS { +const QVector 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 SINGLE_AND_DOUBLE_SIGN_EXCEPTIONS { }; // only single-sign markdown must fail for this data -static const QVector SINGLE_SIGN_EXCEPTIONS { +const QVector 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 MIXED_FORMATTING_SPECIAL_CASES { +const QVector MIXED_FORMATTING_SPECIAL_CASES { // Must allow mixed formatting if there is no tag overlap in result PAIR_FORMAT("aaa *aaa /aaa/ aaa*", "aaa aaa aaa aaa"), PAIR_FORMAT("aaa *aaa /aaa* aaa/", "aaa *aaa aaa* aaa"), @@ -170,7 +171,7 @@ static const QVector MIXED_FORMATTING_SPECIAL_CASES { #define MAKE_LINK(url) "" url "" #define MAKE_WWW_LINK(url) "" url "" -static const QVector> URL_CASES { +const QVector> 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& markdownToTags, const QVector& 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, const QVector& 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& 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>& data) +void urlHighlightTest(UrlHighlightFunction function, const QVector>& data) { for (const QPair& p : data) { QString result = function(p.first); @@ -324,6 +325,66 @@ static void urlHighlightTest(UrlHighlightFunction function, const QVector #include -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 { diff --git a/test/model/friendmessagedispatcher_test.cpp b/test/model/friendmessagedispatcher_test.cpp index 36b92db64..bb55d6c23 100644 --- a/test/model/friendmessagedispatcher_test.cpp +++ b/test/model/friendmessagedispatcher_test.cpp @@ -28,8 +28,9 @@ #include #include -static constexpr uint64_t testMaxExtendedMessageSize = 10 * 1024 * 1024; - +namespace { +constexpr uint64_t testMaxExtendedMessageSize = 10 * 1024 * 1024; +} class MockCoreExtPacket : public ICoreExtPacket { diff --git a/test/model/sessionchatlog_test.cpp b/test/model/sessionchatlog_test.cpp index 248a1946a..23b8e2642 100644 --- a/test/model/sessionchatlog_test.cpp +++ b/test/model/sessionchatlog_test.cpp @@ -24,7 +24,7 @@ #include namespace { -static const QString TEST_USERNAME = "qTox Tester #1"; +const QString TEST_USERNAME = "qTox Tester #1"; Message createMessage(const QString& content) { diff --git a/test/persistence/dbschema_test.cpp b/test/persistence/dbschema_test.cpp index f7862ea4b..41da6adc9 100644 --- a/test/persistence/dbschema_test.cpp +++ b/test/persistence/dbschema_test.cpp @@ -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 && diff --git a/test/persistence/offlinemsgengine_test.cpp b/test/persistence/offlinemsgengine_test.cpp index adff3f29e..481f1baf5 100644 --- a/test/persistence/offlinemsgengine_test.cpp +++ b/test/persistence/offlinemsgengine_test.cpp @@ -37,7 +37,9 @@ private slots: void testExtendedMessageCoordination(); }; +namespace { void completionFn(bool) {} +} // namespace void TestOfflineMsgEngine::testReceiptBeforeMessage() { diff --git a/test/persistence/smileypack_test.cpp b/test/persistence/smileypack_test.cpp index 477737d8e..3d5f25c7d 100644 --- a/test/persistence/smileypack_test.cpp +++ b/test/persistence/smileypack_test.cpp @@ -28,8 +28,6 @@ #include -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(":-)") + " "); } diff --git a/test/platform/posixsignalnotifier_test.cpp b/test/platform/posixsignalnotifier_test.cpp index 41510ad90..74174b03a 100644 --- a/test/platform/posixsignalnotifier_test.cpp +++ b/test/platform/posixsignalnotifier_test.cpp @@ -53,8 +53,10 @@ void TestPosixSignalNotifier::checkUsrSignalHandling() QCOMPARE(args.first().toInt(), SIGUSR1); } +namespace { void sighandler(int) { } +} void TestPosixSignalNotifier::checkIgnoreExtraSignals() {