From af7b742a234efa0c34ca352ad0d56c001d5ec96b Mon Sep 17 00:00:00 2001 From: fourtf Date: Wed, 15 Aug 2018 22:46:20 +0200 Subject: [PATCH] changed .clang-format --- .clang-format | 3 + src/Application.cpp | 10 +- src/BrowserExtension.cpp | 42 +-- src/PrecompiledHeader.hpp | 326 ++++++++-------- src/RunGui.cpp | 138 +++---- src/common/Version.hpp | 6 +- .../highlights/HighlightBlacklistUser.hpp | 52 +-- .../highlights/HighlightPhrase.hpp | 64 ++-- src/controllers/ignores/IgnorePhrase.hpp | 50 +-- .../moderationactions/ModerationAction.hpp | 44 +-- src/messages/Image.cpp | 272 +++++++------- src/messages/Image.hpp | 42 +-- src/messages/MessageParseArgs.hpp | 1 - src/providers/bttv/BttvEmotes.cpp | 121 +++--- src/providers/emoji/Emojis.cpp | 133 ++++--- src/providers/ffz/FfzEmotes.cpp | 167 +++++---- src/providers/twitch/PubsubClient.cpp | 254 ++++++------- src/providers/twitch/PubsubClient.hpp | 53 +-- src/providers/twitch/PubsubHelpers.hpp | 5 +- src/providers/twitch/TwitchAccount.cpp | 46 +-- src/providers/twitch/TwitchChannel.cpp | 67 ++-- .../twitch/TwitchParseCheerEmotes.cpp | 354 +++++++++--------- src/providers/twitch/TwitchUser.hpp | 66 ++-- src/singletons/Fonts.cpp | 21 +- src/singletons/NativeMessaging.cpp | 8 +- src/singletons/Theme.cpp | 24 +- src/util/FormatTime.cpp | 10 +- src/util/InitUpdateButton.hpp | 2 +- src/util/RapidJsonSerializeQString.hpp | 58 +-- src/util/RapidjsonHelpers.cpp | 36 +- src/util/RapidjsonHelpers.hpp | 150 ++++---- src/util/StreamLink.cpp | 137 +++---- src/util/WindowsHelper.hpp | 4 +- src/widgets/AttachedWindow.cpp | 8 +- src/widgets/BaseWindow.cpp | 26 +- src/widgets/Notebook.cpp | 3 +- src/widgets/StreamView.cpp | 2 +- src/widgets/TooltipWidget.cpp | 2 +- src/widgets/dialogs/EmotePopup.cpp | 82 ++-- src/widgets/dialogs/LoginDialog.cpp | 94 ++--- src/widgets/helper/ChannelView.cpp | 98 ++--- .../settingspages/ExternalToolsPage.cpp | 18 +- src/widgets/settingspages/IgnoresPage.cpp | 5 +- src/widgets/settingspages/LookPage.cpp | 4 +- src/widgets/settingspages/ModerationPage.cpp | 2 +- src/widgets/splits/SplitHeader.cpp | 137 +++---- 46 files changed, 1636 insertions(+), 1611 deletions(-) diff --git a/.clang-format b/.clang-format index bd3f2c430..eeb9eb929 100644 --- a/.clang-format +++ b/.clang-format @@ -25,6 +25,9 @@ DerivePointerBinding: false FixNamespaceComments: true IndentCaseLabels: true IndentWidth: 4 +IndentWrappedFunctionNames: true +IndentPPDirectives: AfterHash +NamespaceIndentation: Inner PointerBindsToType: false SpacesBeforeTrailingComments: 2 Standard: Auto diff --git a/src/Application.cpp b/src/Application.cpp index b53940702..68ccc78f8 100644 --- a/src/Application.cpp +++ b/src/Application.cpp @@ -99,15 +99,15 @@ void Application::save() void Application::initNm() { #ifdef Q_OS_WIN -#ifdef QT_DEBUG -#ifdef C_DEBUG_NM +# ifdef QT_DEBUG +# ifdef C_DEBUG_NM this->nativeMessaging->registerHost(); this->nativeMessaging->openGuiMessageQueue(); -#endif -#else +# endif +# else this->nativeMessaging->registerHost(); this->nativeMessaging->openGuiMessageQueue(); -#endif +# endif #endif } diff --git a/src/BrowserExtension.cpp b/src/BrowserExtension.cpp index 5275e0648..f12d19b5e 100644 --- a/src/BrowserExtension.cpp +++ b/src/BrowserExtension.cpp @@ -9,31 +9,31 @@ #include #ifdef Q_OS_WIN -#include -#include -#include +# include +# include +# include #endif namespace chatterino { namespace { -void initFileMode() -{ + void initFileMode() + { #ifdef Q_OS_WIN - _setmode(_fileno(stdin), _O_BINARY); - _setmode(_fileno(stdout), _O_BINARY); + _setmode(_fileno(stdin), _O_BINARY); + _setmode(_fileno(stdout), _O_BINARY); #endif -} + } -void runLoop(NativeMessagingClient &client) -{ - while (true) { - char size_c[4]; - std::cin.read(size_c, 4); + void runLoop(NativeMessagingClient &client) + { + while (true) { + char size_c[4]; + std::cin.read(size_c, 4); - if (std::cin.eof()) break; + if (std::cin.eof()) break; - auto size = *reinterpret_cast(size_c); + auto size = *reinterpret_cast(size_c); #if 0 bool bigEndian = isBigEndian(); @@ -48,14 +48,14 @@ void runLoop(NativeMessagingClient &client) } #endif - std::unique_ptr buffer(new char[size + 1]); - std::cin.read(buffer.get(), size); - *(buffer.get() + size) = '\0'; + std::unique_ptr buffer(new char[size + 1]); + std::cin.read(buffer.get(), size); + *(buffer.get() + size) = '\0'; - client.sendMessage( - QByteArray::fromRawData(buffer.get(), static_cast(size))); + client.sendMessage(QByteArray::fromRawData( + buffer.get(), static_cast(size))); + } } -} } // namespace bool shouldRunBrowserExtensionHost(const QStringList &args) diff --git a/src/PrecompiledHeader.hpp b/src/PrecompiledHeader.hpp index 6eec78c8e..10dfcd418 100644 --- a/src/PrecompiledHeader.hpp +++ b/src/PrecompiledHeader.hpp @@ -1,168 +1,168 @@ #ifdef __cplusplus -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include +# include -#ifndef UNUSED -#define UNUSED(x) (void)(x) -#endif +# ifndef UNUSED +# define UNUSED(x) (void)(x) +# endif -#ifndef ATTR_UNUSED -#ifdef Q_OS_WIN -#define ATTR_UNUSED -#else -#define ATTR_UNUSED __attribute__((unused)) -#endif -#endif +# ifndef ATTR_UNUSED +# ifdef Q_OS_WIN +# define ATTR_UNUSED +# else +# define ATTR_UNUSED __attribute__((unused)) +# endif +# endif #endif diff --git a/src/RunGui.cpp b/src/RunGui.cpp index 7ed61be87..e342ca7c1 100644 --- a/src/RunGui.cpp +++ b/src/RunGui.cpp @@ -12,7 +12,7 @@ #include "widgets/dialogs/LastRunCrashDialog.hpp" #ifdef C_USE_BREAKPAD -#include +# include #endif // void initQt(); @@ -23,80 +23,82 @@ namespace chatterino { namespace { -void installCustomPalette() -{ - // borrowed from - // https://stackoverflow.com/questions/15035767/is-the-qt-5-dark-fusion-theme-available-for-windows - auto dark = qApp->palette(); + void installCustomPalette() + { + // borrowed from + // https://stackoverflow.com/questions/15035767/is-the-qt-5-dark-fusion-theme-available-for-windows + auto dark = qApp->palette(); - dark.setColor(QPalette::Window, QColor(22, 22, 22)); - dark.setColor(QPalette::WindowText, Qt::white); - dark.setColor(QPalette::Text, Qt::white); - dark.setColor(QPalette::Disabled, QPalette::WindowText, - QColor(127, 127, 127)); - dark.setColor(QPalette::Base, QColor("#333")); - dark.setColor(QPalette::AlternateBase, QColor("#444")); - dark.setColor(QPalette::ToolTipBase, Qt::white); - dark.setColor(QPalette::ToolTipText, Qt::white); - dark.setColor(QPalette::Disabled, QPalette::Text, QColor(127, 127, 127)); - dark.setColor(QPalette::Dark, QColor(35, 35, 35)); - dark.setColor(QPalette::Shadow, QColor(20, 20, 20)); - dark.setColor(QPalette::Button, QColor(70, 70, 70)); - dark.setColor(QPalette::ButtonText, Qt::white); - dark.setColor(QPalette::Disabled, QPalette::ButtonText, - QColor(127, 127, 127)); - dark.setColor(QPalette::BrightText, Qt::red); - dark.setColor(QPalette::Link, QColor(42, 130, 218)); - dark.setColor(QPalette::Highlight, QColor(42, 130, 218)); - dark.setColor(QPalette::Disabled, QPalette::Highlight, QColor(80, 80, 80)); - dark.setColor(QPalette::HighlightedText, Qt::white); - dark.setColor(QPalette::Disabled, QPalette::HighlightedText, - QColor(127, 127, 127)); + dark.setColor(QPalette::Window, QColor(22, 22, 22)); + dark.setColor(QPalette::WindowText, Qt::white); + dark.setColor(QPalette::Text, Qt::white); + dark.setColor(QPalette::Disabled, QPalette::WindowText, + QColor(127, 127, 127)); + dark.setColor(QPalette::Base, QColor("#333")); + dark.setColor(QPalette::AlternateBase, QColor("#444")); + dark.setColor(QPalette::ToolTipBase, Qt::white); + dark.setColor(QPalette::ToolTipText, Qt::white); + dark.setColor(QPalette::Disabled, QPalette::Text, + QColor(127, 127, 127)); + dark.setColor(QPalette::Dark, QColor(35, 35, 35)); + dark.setColor(QPalette::Shadow, QColor(20, 20, 20)); + dark.setColor(QPalette::Button, QColor(70, 70, 70)); + dark.setColor(QPalette::ButtonText, Qt::white); + dark.setColor(QPalette::Disabled, QPalette::ButtonText, + QColor(127, 127, 127)); + dark.setColor(QPalette::BrightText, Qt::red); + dark.setColor(QPalette::Link, QColor(42, 130, 218)); + dark.setColor(QPalette::Highlight, QColor(42, 130, 218)); + dark.setColor(QPalette::Disabled, QPalette::Highlight, + QColor(80, 80, 80)); + dark.setColor(QPalette::HighlightedText, Qt::white); + dark.setColor(QPalette::Disabled, QPalette::HighlightedText, + QColor(127, 127, 127)); - qApp->setPalette(dark); -} - -void initQt() -{ - // set up the QApplication flags - QApplication::setAttribute(Qt::AA_Use96Dpi, true); -#ifdef Q_OS_WIN32 - QApplication::setAttribute(Qt::AA_DisableHighDpiScaling, true); -#endif - - QApplication::setStyle(QStyleFactory::create("Fusion")); - - installCustomPalette(); -} - -void showLastCrashDialog() -{ -#ifndef C_DISABLE_CRASH_DIALOG - LastRunCrashDialog dialog; - - switch (dialog.exec()) { - case QDialog::Accepted: { - }; break; - default: { - _exit(0); - } + qApp->setPalette(dark); } + + void initQt() + { + // set up the QApplication flags + QApplication::setAttribute(Qt::AA_Use96Dpi, true); +#ifdef Q_OS_WIN32 + QApplication::setAttribute(Qt::AA_DisableHighDpiScaling, true); #endif -} -void createRunningFile(const QString &path) -{ - QFile runningFile(path); + QApplication::setStyle(QStyleFactory::create("Fusion")); - runningFile.open(QIODevice::WriteOnly | QIODevice::Truncate); - runningFile.flush(); - runningFile.close(); -} + installCustomPalette(); + } -void removeRunningFile(const QString &path) -{ - QFile::remove(path); -} + void showLastCrashDialog() + { +#ifndef C_DISABLE_CRASH_DIALOG + LastRunCrashDialog dialog; + + switch (dialog.exec()) { + case QDialog::Accepted: { + }; break; + default: { + _exit(0); + } + } +#endif + } + + void createRunningFile(const QString &path) + { + QFile runningFile(path); + + runningFile.open(QIODevice::WriteOnly | QIODevice::Truncate); + runningFile.flush(); + runningFile.close(); + } + + void removeRunningFile(const QString &path) + { + QFile::remove(path); + } } // namespace void runGui(QApplication &a, Paths &paths, Settings &settings) diff --git a/src/common/Version.hpp b/src/common/Version.hpp index 2b1b51b39..4101f3a56 100644 --- a/src/common/Version.hpp +++ b/src/common/Version.hpp @@ -5,9 +5,9 @@ #define CHATTERINO_VERSION "2.0.4" #if defined(Q_OS_WIN) -#define CHATTERINO_OS "win" +# define CHATTERINO_OS "win" #elif defined(Q_OS_MACOS) -#define CHATTERINO_OS "macos" +# define CHATTERINO_OS "macos" #elif defined(Q_OS_LINUX) -#define CHATTERINO_OS "linux" +# define CHATTERINO_OS "linux" #endif diff --git a/src/controllers/highlights/HighlightBlacklistUser.hpp b/src/controllers/highlights/HighlightBlacklistUser.hpp index 4ce8683d0..b2e3e4a06 100644 --- a/src/controllers/highlights/HighlightBlacklistUser.hpp +++ b/src/controllers/highlights/HighlightBlacklistUser.hpp @@ -68,37 +68,39 @@ private: namespace pajlada { namespace Settings { -template <> -struct Serialize { - static rapidjson::Value get(const chatterino::HighlightBlacklistUser &value, - rapidjson::Document::AllocatorType &a) - { - rapidjson::Value ret(rapidjson::kObjectType); + template <> + struct Serialize { + static rapidjson::Value get( + const chatterino::HighlightBlacklistUser &value, + rapidjson::Document::AllocatorType &a) + { + rapidjson::Value ret(rapidjson::kObjectType); - AddMember(ret, "pattern", value.getPattern(), a); - AddMember(ret, "regex", value.isRegex(), a); + AddMember(ret, "pattern", value.getPattern(), a); + AddMember(ret, "regex", value.isRegex(), a); - return ret; - } -}; + return ret; + } + }; -template <> -struct Deserialize { - static chatterino::HighlightBlacklistUser get(const rapidjson::Value &value) - { - QString pattern; - bool isRegex = false; + template <> + struct Deserialize { + static chatterino::HighlightBlacklistUser get( + const rapidjson::Value &value) + { + QString pattern; + bool isRegex = false; + + if (!value.IsObject()) { + return chatterino::HighlightBlacklistUser(pattern, isRegex); + } + + chatterino::rj::getSafe(value, "pattern", pattern); + chatterino::rj::getSafe(value, "regex", isRegex); - if (!value.IsObject()) { return chatterino::HighlightBlacklistUser(pattern, isRegex); } - - chatterino::rj::getSafe(value, "pattern", pattern); - chatterino::rj::getSafe(value, "regex", isRegex); - - return chatterino::HighlightBlacklistUser(pattern, isRegex); - } -}; + }; } // namespace Settings } // namespace pajlada diff --git a/src/controllers/highlights/HighlightPhrase.hpp b/src/controllers/highlights/HighlightPhrase.hpp index 91abaadce..cfbee6588 100644 --- a/src/controllers/highlights/HighlightPhrase.hpp +++ b/src/controllers/highlights/HighlightPhrase.hpp @@ -72,43 +72,45 @@ private: namespace pajlada { namespace Settings { -template <> -struct Serialize { - static rapidjson::Value get(const chatterino::HighlightPhrase &value, - rapidjson::Document::AllocatorType &a) - { - rapidjson::Value ret(rapidjson::kObjectType); + template <> + struct Serialize { + static rapidjson::Value get(const chatterino::HighlightPhrase &value, + rapidjson::Document::AllocatorType &a) + { + rapidjson::Value ret(rapidjson::kObjectType); - AddMember(ret, "pattern", value.getPattern(), a); - AddMember(ret, "alert", value.getAlert(), a); - AddMember(ret, "sound", value.getSound(), a); - AddMember(ret, "regex", value.isRegex(), a); + AddMember(ret, "pattern", value.getPattern(), a); + AddMember(ret, "alert", value.getAlert(), a); + AddMember(ret, "sound", value.getSound(), a); + AddMember(ret, "regex", value.isRegex(), a); - return ret; - } -}; - -template <> -struct Deserialize { - static chatterino::HighlightPhrase get(const rapidjson::Value &value) - { - if (!value.IsObject()) { - return chatterino::HighlightPhrase(QString(), true, false, false); + return ret; } + }; - QString _pattern; - bool _alert = true; - bool _sound = false; - bool _isRegex = false; + template <> + struct Deserialize { + static chatterino::HighlightPhrase get(const rapidjson::Value &value) + { + if (!value.IsObject()) { + return chatterino::HighlightPhrase(QString(), true, false, + false); + } - chatterino::rj::getSafe(value, "pattern", _pattern); - chatterino::rj::getSafe(value, "alert", _alert); - chatterino::rj::getSafe(value, "sound", _sound); - chatterino::rj::getSafe(value, "regex", _isRegex); + QString _pattern; + bool _alert = true; + bool _sound = false; + bool _isRegex = false; - return chatterino::HighlightPhrase(_pattern, _alert, _sound, _isRegex); - } -}; + chatterino::rj::getSafe(value, "pattern", _pattern); + chatterino::rj::getSafe(value, "alert", _alert); + chatterino::rj::getSafe(value, "sound", _sound); + chatterino::rj::getSafe(value, "regex", _isRegex); + + return chatterino::HighlightPhrase(_pattern, _alert, _sound, + _isRegex); + } + }; } // namespace Settings } // namespace pajlada diff --git a/src/controllers/ignores/IgnorePhrase.hpp b/src/controllers/ignores/IgnorePhrase.hpp index 81eb83a87..16601708a 100644 --- a/src/controllers/ignores/IgnorePhrase.hpp +++ b/src/controllers/ignores/IgnorePhrase.hpp @@ -59,37 +59,37 @@ private: namespace pajlada { namespace Settings { -template <> -struct Serialize { - static rapidjson::Value get(const chatterino::IgnorePhrase &value, - rapidjson::Document::AllocatorType &a) - { - rapidjson::Value ret(rapidjson::kObjectType); + template <> + struct Serialize { + static rapidjson::Value get(const chatterino::IgnorePhrase &value, + rapidjson::Document::AllocatorType &a) + { + rapidjson::Value ret(rapidjson::kObjectType); - AddMember(ret, "pattern", value.getPattern(), a); - AddMember(ret, "regex", value.isRegex(), a); + AddMember(ret, "pattern", value.getPattern(), a); + AddMember(ret, "regex", value.isRegex(), a); - return ret; - } -}; - -template <> -struct Deserialize { - static chatterino::IgnorePhrase get(const rapidjson::Value &value) - { - if (!value.IsObject()) { - return chatterino::IgnorePhrase(QString(), false); + return ret; } + }; - QString _pattern; - bool _isRegex = false; + template <> + struct Deserialize { + static chatterino::IgnorePhrase get(const rapidjson::Value &value) + { + if (!value.IsObject()) { + return chatterino::IgnorePhrase(QString(), false); + } - chatterino::rj::getSafe(value, "pattern", _pattern); - chatterino::rj::getSafe(value, "regex", _isRegex); + QString _pattern; + bool _isRegex = false; - return chatterino::IgnorePhrase(_pattern, _isRegex); - } -}; + chatterino::rj::getSafe(value, "pattern", _pattern); + chatterino::rj::getSafe(value, "regex", _isRegex); + + return chatterino::IgnorePhrase(_pattern, _isRegex); + } + }; } // namespace Settings } // namespace pajlada diff --git a/src/controllers/moderationactions/ModerationAction.hpp b/src/controllers/moderationactions/ModerationAction.hpp index 6a36157df..8dbdba93f 100644 --- a/src/controllers/moderationactions/ModerationAction.hpp +++ b/src/controllers/moderationactions/ModerationAction.hpp @@ -36,34 +36,34 @@ private: namespace pajlada { namespace Settings { -template <> -struct Serialize { - static rapidjson::Value get(const chatterino::ModerationAction &value, - rapidjson::Document::AllocatorType &a) - { - rapidjson::Value ret(rapidjson::kObjectType); + template <> + struct Serialize { + static rapidjson::Value get(const chatterino::ModerationAction &value, + rapidjson::Document::AllocatorType &a) + { + rapidjson::Value ret(rapidjson::kObjectType); - AddMember(ret, "pattern", value.getAction(), a); + AddMember(ret, "pattern", value.getAction(), a); - return ret; - } -}; - -template <> -struct Deserialize { - static chatterino::ModerationAction get(const rapidjson::Value &value) - { - if (!value.IsObject()) { - return chatterino::ModerationAction(QString()); + return ret; } + }; - QString pattern; + template <> + struct Deserialize { + static chatterino::ModerationAction get(const rapidjson::Value &value) + { + if (!value.IsObject()) { + return chatterino::ModerationAction(QString()); + } - chatterino::rj::getSafe(value, "pattern", pattern); + QString pattern; - return chatterino::ModerationAction(pattern); - } -}; + chatterino::rj::getSafe(value, "pattern", pattern); + + return chatterino::ModerationAction(pattern); + } + }; } // namespace Settings } // namespace pajlada diff --git a/src/messages/Image.cpp b/src/messages/Image.cpp index b48234536..e6dcfbc8b 100644 --- a/src/messages/Image.cpp +++ b/src/messages/Image.cpp @@ -22,157 +22,163 @@ namespace chatterino { namespace { -// Frames -Frames::Frames() -{ - DebugCount::increase("images"); -} - -Frames::Frames(const QVector> &frames) - : items_(frames) -{ - assertInGuiThread(); - DebugCount::increase("images"); - - if (this->animated()) { - DebugCount::increase("animated images"); - - this->gifTimerConnection_ = getApp()->emotes->gifTimer.signal.connect( - [this] { this->advance(); }); - } -} - -Frames::~Frames() -{ - assertInGuiThread(); - DebugCount::decrease("images"); - - if (this->animated()) { - DebugCount::decrease("animated images"); + // Frames + Frames::Frames() + { + DebugCount::increase("images"); } - this->gifTimerConnection_.disconnect(); -} + Frames::Frames(const QVector> &frames) + : items_(frames) + { + assertInGuiThread(); + DebugCount::increase("images"); -void Frames::advance() -{ - this->durationOffset_ += GIF_FRAME_LENGTH; + if (this->animated()) { + DebugCount::increase("animated images"); - while (true) { - this->index_ %= this->items_.size(); - - if (this->index_ >= this->items_.size()) { - this->index_ = this->index_; - } - - if (this->durationOffset_ > this->items_[this->index_].duration) { - this->durationOffset_ -= this->items_[this->index_].duration; - this->index_ = (this->index_ + 1) % this->items_.size(); - } else { - break; + this->gifTimerConnection_ = + getApp()->emotes->gifTimer.signal.connect( + [this] { this->advance(); }); } } -} -bool Frames::animated() const -{ - return this->items_.size() > 1; -} + Frames::~Frames() + { + assertInGuiThread(); + DebugCount::decrease("images"); -boost::optional Frames::current() const -{ - if (this->items_.size() == 0) return boost::none; - return this->items_[this->index_].image; -} + if (this->animated()) { + DebugCount::decrease("animated images"); + } -boost::optional Frames::first() const -{ - if (this->items_.size() == 0) return boost::none; - return this->items_.front().image; -} + this->gifTimerConnection_.disconnect(); + } -// functions -QVector> readFrames(QImageReader &reader, const Url &url) -{ - QVector> frames; + void Frames::advance() + { + this->durationOffset_ += GIF_FRAME_LENGTH; + + while (true) { + this->index_ %= this->items_.size(); + + if (this->index_ >= this->items_.size()) { + this->index_ = this->index_; + } + + if (this->durationOffset_ > this->items_[this->index_].duration) { + this->durationOffset_ -= this->items_[this->index_].duration; + this->index_ = (this->index_ + 1) % this->items_.size(); + } else { + break; + } + } + } + + bool Frames::animated() const + { + return this->items_.size() > 1; + } + + boost::optional Frames::current() const + { + if (this->items_.size() == 0) return boost::none; + return this->items_[this->index_].image; + } + + boost::optional Frames::first() const + { + if (this->items_.size() == 0) return boost::none; + return this->items_.front().image; + } + + // functions + QVector> readFrames(QImageReader &reader, const Url &url) + { + QVector> frames; + + if (reader.imageCount() == 0) { + log("Error while reading image {}: '{}'", url.string, + reader.errorString()); + return frames; + } + + QImage image; + for (int index = 0; index < reader.imageCount(); ++index) { + if (reader.read(&image)) { + QPixmap::fromImage(image); + + int duration = std::max(20, reader.nextImageDelay()); + frames.push_back(Frame{image, duration}); + } + } + + if (frames.size() == 0) { + log("Error while reading image {}: '{}'", url.string, + reader.errorString()); + } - if (reader.imageCount() == 0) { - log("Error while reading image {}: '{}'", url.string, - reader.errorString()); return frames; } - QImage image; - for (int index = 0; index < reader.imageCount(); ++index) { - if (reader.read(&image)) { - QPixmap::fromImage(image); - - int duration = std::max(20, reader.nextImageDelay()); - frames.push_back(Frame{image, duration}); - } - } - - if (frames.size() == 0) { - log("Error while reading image {}: '{}'", url.string, - reader.errorString()); - } - - return frames; -} - -// parsed -template -void assignDelayed( - std::queue>>> &queued, - std::mutex &mutex, std::atomic_bool &loadedEventQueued) -{ - std::lock_guard lock(mutex); - int i = 0; - - while (!queued.empty()) { - queued.front().first(queued.front().second); - queued.pop(); - - if (++i > 50) { - QTimer::singleShot( - 3, [&] { assignDelayed(queued, mutex, loadedEventQueued); }); - return; - } - } - - getApp()->windows->forceLayoutChannelViews(); - loadedEventQueued = false; -} - -template -auto makeConvertCallback(const QVector> &parsed, Assign assign) -{ - return [parsed, assign] { - // convert to pixmap - auto frames = QVector>(); - std::transform(parsed.begin(), parsed.end(), std::back_inserter(frames), - [](auto &frame) { - return Frame{ - QPixmap::fromImage(frame.image), frame.duration}; - }); - - // put into stack - static std::queue>>> queued; - static std::mutex mutex; - + // parsed + template + void assignDelayed( + std::queue>>> &queued, + std::mutex &mutex, std::atomic_bool &loadedEventQueued) + { std::lock_guard lock(mutex); - queued.emplace(assign, frames); + int i = 0; - static std::atomic_bool loadedEventQueued{false}; + while (!queued.empty()) { + queued.front().first(queued.front().second); + queued.pop(); - if (!loadedEventQueued) { - loadedEventQueued = true; - - QTimer::singleShot( - 100, [=] { assignDelayed(queued, mutex, loadedEventQueued); }); + if (++i > 50) { + QTimer::singleShot(3, [&] { + assignDelayed(queued, mutex, loadedEventQueued); + }); + return; + } } - }; -} + + getApp()->windows->forceLayoutChannelViews(); + loadedEventQueued = false; + } + + template + auto makeConvertCallback(const QVector> &parsed, + Assign assign) + { + return [parsed, assign] { + // convert to pixmap + auto frames = QVector>(); + std::transform(parsed.begin(), parsed.end(), + std::back_inserter(frames), [](auto &frame) { + return Frame{ + QPixmap::fromImage(frame.image), + frame.duration}; + }); + + // put into stack + static std::queue>>> + queued; + static std::mutex mutex; + + std::lock_guard lock(mutex); + queued.emplace(assign, frames); + + static std::atomic_bool loadedEventQueued{false}; + + if (!loadedEventQueued) { + loadedEventQueued = true; + + QTimer::singleShot(100, [=] { + assignDelayed(queued, mutex, loadedEventQueued); + }); + } + }; + } } // namespace // IMAGE2 diff --git a/src/messages/Image.hpp b/src/messages/Image.hpp index 68b96392b..678af25ce 100644 --- a/src/messages/Image.hpp +++ b/src/messages/Image.hpp @@ -17,29 +17,29 @@ namespace chatterino { namespace { -template -struct Frame { - Image image; - int duration; -}; -class Frames : boost::noncopyable -{ -public: - Frames(); - Frames(const QVector> &frames); - ~Frames(); + template + struct Frame { + Image image; + int duration; + }; + class Frames : boost::noncopyable + { + public: + Frames(); + Frames(const QVector> &frames); + ~Frames(); - bool animated() const; - void advance(); - boost::optional current() const; - boost::optional first() const; + bool animated() const; + void advance(); + boost::optional current() const; + boost::optional first() const; -private: - QVector> items_; - int index_{0}; - int durationOffset_{0}; - pajlada::Signals::Connection gifTimerConnection_; -}; + private: + QVector> items_; + int index_{0}; + int durationOffset_{0}; + pajlada::Signals::Connection gifTimerConnection_; + }; } // namespace class Image; diff --git a/src/messages/MessageParseArgs.hpp b/src/messages/MessageParseArgs.hpp index 519262dc1..471d1d648 100644 --- a/src/messages/MessageParseArgs.hpp +++ b/src/messages/MessageParseArgs.hpp @@ -2,5 +2,4 @@ namespace chatterino { - } // namespace chatterino diff --git a/src/providers/bttv/BttvEmotes.cpp b/src/providers/bttv/BttvEmotes.cpp index cf32bd414..2efe00d64 100644 --- a/src/providers/bttv/BttvEmotes.cpp +++ b/src/providers/bttv/BttvEmotes.cpp @@ -13,73 +13,76 @@ namespace chatterino { namespace { -Url getEmoteLink(QString urlTemplate, const EmoteId &id, - const QString &emoteScale) -{ - urlTemplate.detach(); + Url getEmoteLink(QString urlTemplate, const EmoteId &id, + const QString &emoteScale) + { + urlTemplate.detach(); - return {urlTemplate.replace("{{id}}", id.string) - .replace("{{image}}", emoteScale)}; -} -std::pair parseGlobalEmotes(const QJsonObject &jsonRoot, - const EmoteMap ¤tEmotes) -{ - auto emotes = EmoteMap(); - auto jsonEmotes = jsonRoot.value("emotes").toArray(); - auto urlTemplate = qS("https:") + jsonRoot.value("urlTemplate").toString(); - - for (auto jsonEmote : jsonEmotes) { - auto id = EmoteId{jsonEmote.toObject().value("id").toString()}; - auto name = EmoteName{jsonEmote.toObject().value("code").toString()}; - - auto emote = Emote( - {name, - ImageSet{ - Image::fromUrl(getEmoteLink(urlTemplate, id, "1x"), 1), - Image::fromUrl(getEmoteLink(urlTemplate, id, "2x"), 0.5), - Image::fromUrl(getEmoteLink(urlTemplate, id, "3x"), 0.25)}, - Tooltip{name.string + "
Global Bttv Emote"}, - Url{"https://manage.betterttv.net/emotes/" + id.string}}); - - emotes[name] = cachedOrMakeEmotePtr(std::move(emote), currentEmotes); + return {urlTemplate.replace("{{id}}", id.string) + .replace("{{image}}", emoteScale)}; } + std::pair parseGlobalEmotes( + const QJsonObject &jsonRoot, const EmoteMap ¤tEmotes) + { + auto emotes = EmoteMap(); + auto jsonEmotes = jsonRoot.value("emotes").toArray(); + auto urlTemplate = + qS("https:") + jsonRoot.value("urlTemplate").toString(); - return {Success, std::move(emotes)}; -} -EmotePtr cachedOrMake(Emote &&emote, const EmoteId &id) -{ - static std::unordered_map> cache; - static std::mutex mutex; + for (auto jsonEmote : jsonEmotes) { + auto id = EmoteId{jsonEmote.toObject().value("id").toString()}; + auto name = + EmoteName{jsonEmote.toObject().value("code").toString()}; - return cachedOrMakeEmotePtr(std::move(emote), cache, mutex, id); -} -std::pair parseChannelEmotes(const QJsonObject &jsonRoot) -{ - auto emotes = EmoteMap(); - auto jsonEmotes = jsonRoot.value("emotes").toArray(); - auto urlTemplate = "https:" + jsonRoot.value("urlTemplate").toString(); + auto emote = Emote( + {name, + ImageSet{ + Image::fromUrl(getEmoteLink(urlTemplate, id, "1x"), 1), + Image::fromUrl(getEmoteLink(urlTemplate, id, "2x"), 0.5), + Image::fromUrl(getEmoteLink(urlTemplate, id, "3x"), 0.25)}, + Tooltip{name.string + "
Global Bttv Emote"}, + Url{"https://manage.betterttv.net/emotes/" + id.string}}); - for (auto jsonEmote_ : jsonEmotes) { - auto jsonEmote = jsonEmote_.toObject(); + emotes[name] = + cachedOrMakeEmotePtr(std::move(emote), currentEmotes); + } - auto id = EmoteId{jsonEmote.value("id").toString()}; - auto name = EmoteName{jsonEmote.value("code").toString()}; - // emoteObject.value("imageType").toString(); - - auto emote = Emote( - {name, - ImageSet{ - Image::fromUrl(getEmoteLink(urlTemplate, id, "1x"), 1), - Image::fromUrl(getEmoteLink(urlTemplate, id, "2x"), 0.5), - Image::fromUrl(getEmoteLink(urlTemplate, id, "3x"), 0.25)}, - Tooltip{name.string + "
Channel Bttv Emote"}, - Url{"https://manage.betterttv.net/emotes/" + id.string}}); - - emotes[name] = cachedOrMake(std::move(emote), id); + return {Success, std::move(emotes)}; } + EmotePtr cachedOrMake(Emote &&emote, const EmoteId &id) + { + static std::unordered_map> cache; + static std::mutex mutex; - return {Success, std::move(emotes)}; -} + return cachedOrMakeEmotePtr(std::move(emote), cache, mutex, id); + } + std::pair parseChannelEmotes(const QJsonObject &jsonRoot) + { + auto emotes = EmoteMap(); + auto jsonEmotes = jsonRoot.value("emotes").toArray(); + auto urlTemplate = "https:" + jsonRoot.value("urlTemplate").toString(); + + for (auto jsonEmote_ : jsonEmotes) { + auto jsonEmote = jsonEmote_.toObject(); + + auto id = EmoteId{jsonEmote.value("id").toString()}; + auto name = EmoteName{jsonEmote.value("code").toString()}; + // emoteObject.value("imageType").toString(); + + auto emote = Emote( + {name, + ImageSet{ + Image::fromUrl(getEmoteLink(urlTemplate, id, "1x"), 1), + Image::fromUrl(getEmoteLink(urlTemplate, id, "2x"), 0.5), + Image::fromUrl(getEmoteLink(urlTemplate, id, "3x"), 0.25)}, + Tooltip{name.string + "
Channel Bttv Emote"}, + Url{"https://manage.betterttv.net/emotes/" + id.string}}); + + emotes[name] = cachedOrMake(std::move(emote), id); + } + + return {Success, std::move(emotes)}; + } } // namespace // diff --git a/src/providers/emoji/Emojis.cpp b/src/providers/emoji/Emojis.cpp index 5140d2fe1..809b7c3d5 100644 --- a/src/providers/emoji/Emojis.cpp +++ b/src/providers/emoji/Emojis.cpp @@ -13,82 +13,81 @@ #include namespace chatterino { - namespace { + void parseEmoji(const std::shared_ptr &emojiData, + const rapidjson::Value &unparsedEmoji, + QString shortCode = QString()) + { + static uint unicodeBytes[4]; -void parseEmoji(const std::shared_ptr &emojiData, - const rapidjson::Value &unparsedEmoji, - QString shortCode = QString()) -{ - static uint unicodeBytes[4]; + struct { + bool apple; + bool google; + bool twitter; + bool emojione; + bool facebook; + bool messenger; + } capabilities; - struct { - bool apple; - bool google; - bool twitter; - bool emojione; - bool facebook; - bool messenger; - } capabilities; - - if (!shortCode.isEmpty()) { - emojiData->shortCodes.push_back(shortCode); - } else { - const auto &shortCodes = unparsedEmoji["short_names"]; - for (const auto &shortCode : shortCodes.GetArray()) { - emojiData->shortCodes.emplace_back(shortCode.GetString()); + if (!shortCode.isEmpty()) { + emojiData->shortCodes.push_back(shortCode); + } else { + const auto &shortCodes = unparsedEmoji["short_names"]; + for (const auto &shortCode : shortCodes.GetArray()) { + emojiData->shortCodes.emplace_back(shortCode.GetString()); + } } - } - rj::getSafe(unparsedEmoji, "non_qualified", emojiData->nonQualifiedCode); - rj::getSafe(unparsedEmoji, "unified", emojiData->unifiedCode); + rj::getSafe(unparsedEmoji, "non_qualified", + emojiData->nonQualifiedCode); + rj::getSafe(unparsedEmoji, "unified", emojiData->unifiedCode); - rj::getSafe(unparsedEmoji, "has_img_apple", capabilities.apple); - rj::getSafe(unparsedEmoji, "has_img_google", capabilities.google); - rj::getSafe(unparsedEmoji, "has_img_twitter", capabilities.twitter); - rj::getSafe(unparsedEmoji, "has_img_emojione", capabilities.emojione); - rj::getSafe(unparsedEmoji, "has_img_facebook", capabilities.facebook); - rj::getSafe(unparsedEmoji, "has_img_messenger", capabilities.messenger); + rj::getSafe(unparsedEmoji, "has_img_apple", capabilities.apple); + rj::getSafe(unparsedEmoji, "has_img_google", capabilities.google); + rj::getSafe(unparsedEmoji, "has_img_twitter", capabilities.twitter); + rj::getSafe(unparsedEmoji, "has_img_emojione", capabilities.emojione); + rj::getSafe(unparsedEmoji, "has_img_facebook", capabilities.facebook); + rj::getSafe(unparsedEmoji, "has_img_messenger", capabilities.messenger); - if (capabilities.apple) { - emojiData->capabilities.insert("Apple"); - } - if (capabilities.google) { - emojiData->capabilities.insert("Google"); - } - if (capabilities.twitter) { - emojiData->capabilities.insert("Twitter"); - } - if (capabilities.emojione) { - emojiData->capabilities.insert("EmojiOne 3"); - } - if (capabilities.facebook) { - emojiData->capabilities.insert("Facebook"); - } - if (capabilities.messenger) { - emojiData->capabilities.insert("Messenger"); - } + if (capabilities.apple) { + emojiData->capabilities.insert("Apple"); + } + if (capabilities.google) { + emojiData->capabilities.insert("Google"); + } + if (capabilities.twitter) { + emojiData->capabilities.insert("Twitter"); + } + if (capabilities.emojione) { + emojiData->capabilities.insert("EmojiOne 3"); + } + if (capabilities.facebook) { + emojiData->capabilities.insert("Facebook"); + } + if (capabilities.messenger) { + emojiData->capabilities.insert("Messenger"); + } - QStringList unicodeCharacters; - if (!emojiData->nonQualifiedCode.isEmpty()) { - unicodeCharacters = emojiData->nonQualifiedCode.toLower().split('-'); - } else { - unicodeCharacters = emojiData->unifiedCode.toLower().split('-'); + QStringList unicodeCharacters; + if (!emojiData->nonQualifiedCode.isEmpty()) { + unicodeCharacters = + emojiData->nonQualifiedCode.toLower().split('-'); + } else { + unicodeCharacters = emojiData->unifiedCode.toLower().split('-'); + } + if (unicodeCharacters.length() < 1) { + return; + } + + int numUnicodeBytes = 0; + + for (const QString &unicodeCharacter : unicodeCharacters) { + unicodeBytes[numUnicodeBytes++] = + QString(unicodeCharacter).toUInt(nullptr, 16); + } + + emojiData->value = QString::fromUcs4(unicodeBytes, numUnicodeBytes); } - if (unicodeCharacters.length() < 1) { - return; - } - - int numUnicodeBytes = 0; - - for (const QString &unicodeCharacter : unicodeCharacters) { - unicodeBytes[numUnicodeBytes++] = - QString(unicodeCharacter).toUInt(nullptr, 16); - } - - emojiData->value = QString::fromUcs4(unicodeBytes, numUnicodeBytes); -} - } // namespace void Emojis::load() diff --git a/src/providers/ffz/FfzEmotes.cpp b/src/providers/ffz/FfzEmotes.cpp index f8be4baa0..eb6912ff7 100644 --- a/src/providers/ffz/FfzEmotes.cpp +++ b/src/providers/ffz/FfzEmotes.cpp @@ -10,99 +10,100 @@ namespace chatterino { namespace { -Url getEmoteLink(const QJsonObject &urls, const QString &emoteScale) -{ - auto emote = urls.value(emoteScale); - if (emote.isUndefined()) { - return {""}; - } - - assert(emote.isString()); - - return {"https:" + emote.toString()}; -} -void fillInEmoteData(const QJsonObject &urls, const EmoteName &name, - const QString &tooltip, Emote &emoteData) -{ - auto url1x = getEmoteLink(urls, "1"); - auto url2x = getEmoteLink(urls, "2"); - auto url3x = getEmoteLink(urls, "4"); - - //, code, tooltip - emoteData.name = name; - emoteData.images = - ImageSet{Image::fromUrl(url1x, 1), Image::fromUrl(url2x, 0.5), - Image::fromUrl(url3x, 0.25)}; - emoteData.tooltip = {tooltip}; -} -EmotePtr cachedOrMake(Emote &&emote, const EmoteId &id) -{ - static std::unordered_map> cache; - static std::mutex mutex; - - return cachedOrMakeEmotePtr(std::move(emote), cache, mutex, id); -} -std::pair parseGlobalEmotes(const QJsonObject &jsonRoot, - const EmoteMap ¤tEmotes) -{ - auto jsonSets = jsonRoot.value("sets").toObject(); - auto emotes = EmoteMap(); - - for (auto jsonSet : jsonSets) { - auto jsonEmotes = jsonSet.toObject().value("emoticons").toArray(); - - for (auto jsonEmoteValue : jsonEmotes) { - auto jsonEmote = jsonEmoteValue.toObject(); - - auto name = EmoteName{jsonEmote.value("name").toString()}; - auto id = EmoteId{jsonEmote.value("id").toString()}; - auto urls = jsonEmote.value("urls").toObject(); - - auto emote = Emote(); - fillInEmoteData(urls, name, name.string + "
Global FFZ Emote", - emote); - emote.homePage = - Url{QString("https://www.frankerfacez.com/emoticon/%1-%2") - .arg(id.string) - .arg(name.string)}; - - emotes[name] = - cachedOrMakeEmotePtr(std::move(emote), currentEmotes); + Url getEmoteLink(const QJsonObject &urls, const QString &emoteScale) + { + auto emote = urls.value(emoteScale); + if (emote.isUndefined()) { + return {""}; } + + assert(emote.isString()); + + return {"https:" + emote.toString()}; } + void fillInEmoteData(const QJsonObject &urls, const EmoteName &name, + const QString &tooltip, Emote &emoteData) + { + auto url1x = getEmoteLink(urls, "1"); + auto url2x = getEmoteLink(urls, "2"); + auto url3x = getEmoteLink(urls, "4"); - return {Success, std::move(emotes)}; -} -std::pair parseChannelEmotes(const QJsonObject &jsonRoot) -{ - auto jsonSets = jsonRoot.value("sets").toObject(); - auto emotes = EmoteMap(); + //, code, tooltip + emoteData.name = name; + emoteData.images = + ImageSet{Image::fromUrl(url1x, 1), Image::fromUrl(url2x, 0.5), + Image::fromUrl(url3x, 0.25)}; + emoteData.tooltip = {tooltip}; + } + EmotePtr cachedOrMake(Emote &&emote, const EmoteId &id) + { + static std::unordered_map> cache; + static std::mutex mutex; - for (auto jsonSet : jsonSets) { - auto jsonEmotes = jsonSet.toObject().value("emoticons").toArray(); + return cachedOrMakeEmotePtr(std::move(emote), cache, mutex, id); + } + std::pair parseGlobalEmotes( + const QJsonObject &jsonRoot, const EmoteMap ¤tEmotes) + { + auto jsonSets = jsonRoot.value("sets").toObject(); + auto emotes = EmoteMap(); - for (auto _jsonEmote : jsonEmotes) { - auto jsonEmote = _jsonEmote.toObject(); + for (auto jsonSet : jsonSets) { + auto jsonEmotes = jsonSet.toObject().value("emoticons").toArray(); - // margins - auto id = EmoteId{QString::number(jsonEmote.value("id").toInt())}; - auto name = EmoteName{jsonEmote.value("name").toString()}; - auto urls = jsonEmote.value("urls").toObject(); + for (auto jsonEmoteValue : jsonEmotes) { + auto jsonEmote = jsonEmoteValue.toObject(); - Emote emote; - fillInEmoteData(urls, name, name.string + "
Channel FFZ Emote", - emote); - emote.homePage = - Url{QString("https://www.frankerfacez.com/emoticon/%1-%2") - .arg(id.string) - .arg(name.string)}; + auto name = EmoteName{jsonEmote.value("name").toString()}; + auto id = EmoteId{jsonEmote.value("id").toString()}; + auto urls = jsonEmote.value("urls").toObject(); - emotes[name] = cachedOrMake(std::move(emote), id); + auto emote = Emote(); + fillInEmoteData(urls, name, + name.string + "
Global FFZ Emote", emote); + emote.homePage = + Url{QString("https://www.frankerfacez.com/emoticon/%1-%2") + .arg(id.string) + .arg(name.string)}; + + emotes[name] = + cachedOrMakeEmotePtr(std::move(emote), currentEmotes); + } } - } - return {Success, std::move(emotes)}; -} + return {Success, std::move(emotes)}; + } + std::pair parseChannelEmotes(const QJsonObject &jsonRoot) + { + auto jsonSets = jsonRoot.value("sets").toObject(); + auto emotes = EmoteMap(); + + for (auto jsonSet : jsonSets) { + auto jsonEmotes = jsonSet.toObject().value("emoticons").toArray(); + + for (auto _jsonEmote : jsonEmotes) { + auto jsonEmote = _jsonEmote.toObject(); + + // margins + auto id = + EmoteId{QString::number(jsonEmote.value("id").toInt())}; + auto name = EmoteName{jsonEmote.value("name").toString()}; + auto urls = jsonEmote.value("urls").toObject(); + + Emote emote; + fillInEmoteData(urls, name, + name.string + "
Channel FFZ Emote", emote); + emote.homePage = + Url{QString("https://www.frankerfacez.com/emoticon/%1-%2") + .arg(id.string) + .arg(name.string)}; + + emotes[name] = cachedOrMake(std::move(emote), id); + } + } + + return {Success, std::move(emotes)}; + } } // namespace FfzEmotes::FfzEmotes() diff --git a/src/providers/twitch/PubsubClient.cpp b/src/providers/twitch/PubsubClient.cpp index 7f591aebc..77b6ba1d4 100644 --- a/src/providers/twitch/PubsubClient.cpp +++ b/src/providers/twitch/PubsubClient.cpp @@ -24,157 +24,159 @@ static std::map sentMessages; namespace detail { -PubSubClient::PubSubClient(WebsocketClient &websocketClient, - WebsocketHandle handle) - : websocketClient_(websocketClient) - , handle_(handle) -{ -} - -void PubSubClient::start() -{ - assert(!this->started_); - - this->started_ = true; - - this->ping(); -} - -void PubSubClient::stop() -{ - assert(this->started_); - - this->started_ = false; -} - -bool PubSubClient::listen(rapidjson::Document &message) -{ - int numRequestedListens = message["data"]["topics"].Size(); - - if (this->numListens_ + numRequestedListens > MAX_PUBSUB_LISTENS) { - // This PubSubClient is already at its peak listens - return false; + PubSubClient::PubSubClient(WebsocketClient &websocketClient, + WebsocketHandle handle) + : websocketClient_(websocketClient) + , handle_(handle) + { } - this->numListens_ += numRequestedListens; + void PubSubClient::start() + { + assert(!this->started_); - for (const auto &topic : message["data"]["topics"].GetArray()) { - this->listeners_.emplace_back( - Listener{topic.GetString(), false, false, false}); + this->started_ = true; + + this->ping(); } - auto uuid = CreateUUID(); + void PubSubClient::stop() + { + assert(this->started_); - rj::set(message, "nonce", uuid); + this->started_ = false; + } - std::string payload = rj::stringify(message); - sentMessages[uuid] = payload; + bool PubSubClient::listen(rapidjson::Document &message) + { + int numRequestedListens = message["data"]["topics"].Size(); - this->send(payload.c_str()); - - return true; -} - -void PubSubClient::unlistenPrefix(const std::string &prefix) -{ - std::vector topics; - - for (auto it = this->listeners_.begin(); it != this->listeners_.end();) { - const auto &listener = *it; - if (listener.topic.find(prefix) == 0) { - topics.push_back(listener.topic); - it = this->listeners_.erase(it); - } else { - ++it; + if (this->numListens_ + numRequestedListens > MAX_PUBSUB_LISTENS) { + // This PubSubClient is already at its peak listens + return false; } - } - if (topics.empty()) { - return; - } + this->numListens_ += numRequestedListens; - auto message = createUnlistenMessage(topics); - - auto uuid = CreateUUID(); - - rj::set(message, "nonce", CreateUUID()); - - std::string payload = rj::stringify(message); - sentMessages[uuid] = payload; - - this->send(payload.c_str()); -} - -void PubSubClient::handlePong() -{ - assert(this->awaitingPong_); - - log("Got pong!"); - - this->awaitingPong_ = false; -} - -bool PubSubClient::isListeningToTopic(const std::string &payload) -{ - for (const auto &listener : this->listeners_) { - if (listener.topic == payload) { - return true; + for (const auto &topic : message["data"]["topics"].GetArray()) { + this->listeners_.emplace_back( + Listener{topic.GetString(), false, false, false}); } + + auto uuid = CreateUUID(); + + rj::set(message, "nonce", uuid); + + std::string payload = rj::stringify(message); + sentMessages[uuid] = payload; + + this->send(payload.c_str()); + + return true; } - return false; -} + void PubSubClient::unlistenPrefix(const std::string &prefix) + { + std::vector topics; -void PubSubClient::ping() -{ - assert(this->started_); + for (auto it = this->listeners_.begin(); + it != this->listeners_.end();) { + const auto &listener = *it; + if (listener.topic.find(prefix) == 0) { + topics.push_back(listener.topic); + it = this->listeners_.erase(it); + } else { + ++it; + } + } - if (!this->send(pingPayload)) { - return; + if (topics.empty()) { + return; + } + + auto message = createUnlistenMessage(topics); + + auto uuid = CreateUUID(); + + rj::set(message, "nonce", CreateUUID()); + + std::string payload = rj::stringify(message); + sentMessages[uuid] = payload; + + this->send(payload.c_str()); } - this->awaitingPong_ = true; + void PubSubClient::handlePong() + { + assert(this->awaitingPong_); - auto self = this->shared_from_this(); + log("Got pong!"); - runAfter(this->websocketClient_.get_io_service(), std::chrono::seconds(15), - [self](auto timer) { - if (!self->started_) { - return; - } + this->awaitingPong_ = false; + } - if (self->awaitingPong_) { - log("No pong respnose, disconnect!"); - // TODO(pajlada): Label this connection as "disconnect me" - } - }); - - runAfter(this->websocketClient_.get_io_service(), std::chrono::minutes(5), - [self](auto timer) { - if (!self->started_) { - return; - } - - self->ping(); // - }); -} - -bool PubSubClient::send(const char *payload) -{ - WebsocketErrorCode ec; - this->websocketClient_.send(this->handle_, payload, - websocketpp::frame::opcode::text, ec); - - if (ec) { - log("Error sending message {}: {}", payload, ec.message()); - // TODO(pajlada): Check which error code happened and maybe gracefully - // handle it + bool PubSubClient::isListeningToTopic(const std::string &payload) + { + for (const auto &listener : this->listeners_) { + if (listener.topic == payload) { + return true; + } + } return false; } - return true; -} + void PubSubClient::ping() + { + assert(this->started_); + + if (!this->send(pingPayload)) { + return; + } + + this->awaitingPong_ = true; + + auto self = this->shared_from_this(); + + runAfter(this->websocketClient_.get_io_service(), + std::chrono::seconds(15), [self](auto timer) { + if (!self->started_) { + return; + } + + if (self->awaitingPong_) { + log("No pong respnose, disconnect!"); + // TODO(pajlada): Label this connection as "disconnect + // me" + } + }); + + runAfter(this->websocketClient_.get_io_service(), + std::chrono::minutes(5), [self](auto timer) { + if (!self->started_) { + return; + } + + self->ping(); // + }); + } + + bool PubSubClient::send(const char *payload) + { + WebsocketErrorCode ec; + this->websocketClient_.send(this->handle_, payload, + websocketpp::frame::opcode::text, ec); + + if (ec) { + log("Error sending message {}: {}", payload, ec.message()); + // TODO(pajlada): Check which error code happened and maybe + // gracefully handle it + + return false; + } + + return true; + } } // namespace detail diff --git a/src/providers/twitch/PubsubClient.hpp b/src/providers/twitch/PubsubClient.hpp index 211502176..f3cc10f15 100644 --- a/src/providers/twitch/PubsubClient.hpp +++ b/src/providers/twitch/PubsubClient.hpp @@ -32,41 +32,42 @@ using WebsocketErrorCode = websocketpp::lib::error_code; namespace detail { -struct Listener { - std::string topic; - bool authed; - bool persistent; - bool confirmed = false; -}; + struct Listener { + std::string topic; + bool authed; + bool persistent; + bool confirmed = false; + }; -class PubSubClient : public std::enable_shared_from_this -{ -public: - PubSubClient(WebsocketClient &_websocketClient, WebsocketHandle _handle); + class PubSubClient : public std::enable_shared_from_this + { + public: + PubSubClient(WebsocketClient &_websocketClient, + WebsocketHandle _handle); - void start(); - void stop(); + void start(); + void stop(); - bool listen(rapidjson::Document &message); - void unlistenPrefix(const std::string &prefix); + bool listen(rapidjson::Document &message); + void unlistenPrefix(const std::string &prefix); - void handlePong(); + void handlePong(); - bool isListeningToTopic(const std::string &topic); + bool isListeningToTopic(const std::string &topic); -private: - void ping(); - bool send(const char *payload); + private: + void ping(); + bool send(const char *payload); - WebsocketClient &websocketClient_; - WebsocketHandle handle_; - uint16_t numListens_ = 0; + WebsocketClient &websocketClient_; + WebsocketHandle handle_; + uint16_t numListens_ = 0; - std::vector listeners_; + std::vector listeners_; - std::atomic awaitingPong_{false}; - std::atomic started_{false}; -}; + std::atomic awaitingPong_{false}; + std::atomic started_{false}; + }; } // namespace detail diff --git a/src/providers/twitch/PubsubHelpers.hpp b/src/providers/twitch/PubsubHelpers.hpp index fe7056dc8..c478ed437 100644 --- a/src/providers/twitch/PubsubHelpers.hpp +++ b/src/providers/twitch/PubsubHelpers.hpp @@ -1,11 +1,10 @@ #pragma once -#include "debug/Log.hpp" -#include "util/RapidjsonHelpers.hpp" -#include "debug/Log.hpp" #include #include #include +#include "debug/Log.hpp" +#include "util/RapidjsonHelpers.hpp" namespace chatterino { diff --git a/src/providers/twitch/TwitchAccount.cpp b/src/providers/twitch/TwitchAccount.cpp index 238d9a6be..3e7ea237d 100644 --- a/src/providers/twitch/TwitchAccount.cpp +++ b/src/providers/twitch/TwitchAccount.cpp @@ -15,32 +15,32 @@ namespace chatterino { namespace { -EmoteName cleanUpCode(const EmoteName &dirtyEmoteCode) -{ - auto cleanCode = dirtyEmoteCode.string; - cleanCode.detach(); + EmoteName cleanUpCode(const EmoteName &dirtyEmoteCode) + { + auto cleanCode = dirtyEmoteCode.string; + cleanCode.detach(); - static QMap emoteNameReplacements{ - {"[oO](_|\\.)[oO]", "O_o"}, {"\\>\\;\\(", ">("}, - {"\\<\\;3", "<3"}, {"\\:-?(o|O)", ":O"}, - {"\\:-?(p|P)", ":P"}, {"\\:-?[\\\\/]", ":/"}, - {"\\:-?[z|Z|\\|]", ":Z"}, {"\\:-?\\(", ":("}, - {"\\:-?\\)", ":)"}, {"\\:-?D", ":D"}, - {"\\;-?(p|P)", ";P"}, {"\\;-?\\)", ";)"}, - {"R-?\\)", "R)"}, {"B-?\\)", "B)"}, - }; + static QMap emoteNameReplacements{ + {"[oO](_|\\.)[oO]", "O_o"}, {"\\>\\;\\(", ">("}, + {"\\<\\;3", "<3"}, {"\\:-?(o|O)", ":O"}, + {"\\:-?(p|P)", ":P"}, {"\\:-?[\\\\/]", ":/"}, + {"\\:-?[z|Z|\\|]", ":Z"}, {"\\:-?\\(", ":("}, + {"\\:-?\\)", ":)"}, {"\\:-?D", ":D"}, + {"\\;-?(p|P)", ";P"}, {"\\;-?\\)", ";)"}, + {"R-?\\)", "R)"}, {"B-?\\)", "B)"}, + }; - auto it = emoteNameReplacements.find(dirtyEmoteCode.string); - if (it != emoteNameReplacements.end()) { - cleanCode = it.value(); + auto it = emoteNameReplacements.find(dirtyEmoteCode.string); + if (it != emoteNameReplacements.end()) { + cleanCode = it.value(); + } + + cleanCode.replace("<", "<"); + cleanCode.replace(">", ">"); + + return {cleanCode}; } - cleanCode.replace("<", "<"); - cleanCode.replace(">", ">"); - - return {cleanCode}; -} - } // namespace TwitchAccount::TwitchAccount(const QString &username, const QString &oauthToken, @@ -417,7 +417,7 @@ void TwitchAccount::loadEmotes() } AccessGuard -TwitchAccount::accessEmotes() const + TwitchAccount::accessEmotes() const { return this->emotes_.accessConst(); } diff --git a/src/providers/twitch/TwitchChannel.cpp b/src/providers/twitch/TwitchChannel.cpp index 06ed13739..d6c55d224 100644 --- a/src/providers/twitch/TwitchChannel.cpp +++ b/src/providers/twitch/TwitchChannel.cpp @@ -25,48 +25,49 @@ namespace chatterino { namespace { -auto parseRecentMessages(const QJsonObject &jsonRoot, TwitchChannel &channel) -{ - QJsonArray jsonMessages = jsonRoot.value("messages").toArray(); - std::vector messages; + auto parseRecentMessages(const QJsonObject &jsonRoot, + TwitchChannel &channel) + { + QJsonArray jsonMessages = jsonRoot.value("messages").toArray(); + std::vector messages; - if (jsonMessages.empty()) return messages; + if (jsonMessages.empty()) return messages; - for (const auto jsonMessage : jsonMessages) { - auto content = jsonMessage.toString().toUtf8(); - // passing nullptr as the channel makes the message invalid but we don't - // check for that anyways - auto message = Communi::IrcMessage::fromData(content, nullptr); - auto privMsg = dynamic_cast(message); - assert(privMsg); + for (const auto jsonMessage : jsonMessages) { + auto content = jsonMessage.toString().toUtf8(); + // passing nullptr as the channel makes the message invalid but we + // don't check for that anyways + auto message = Communi::IrcMessage::fromData(content, nullptr); + auto privMsg = dynamic_cast(message); + assert(privMsg); - MessageParseArgs args; - TwitchMessageBuilder builder(&channel, privMsg, args); - if (!builder.isIgnored()) { - messages.push_back(builder.build()); + MessageParseArgs args; + TwitchMessageBuilder builder(&channel, privMsg, args); + if (!builder.isIgnored()) { + messages.push_back(builder.build()); + } } + + return messages; } + std::pair parseChatters(const QJsonObject &jsonRoot) + { + static QStringList categories = {"moderators", "staff", "admins", + "global_mods", "viewers"}; - return messages; -} -std::pair parseChatters(const QJsonObject &jsonRoot) -{ - static QStringList categories = {"moderators", "staff", "admins", - "global_mods", "viewers"}; + auto usernames = UsernameSet(); - auto usernames = UsernameSet(); + // parse json + QJsonObject jsonCategories = jsonRoot.value("chatters").toObject(); - // parse json - QJsonObject jsonCategories = jsonRoot.value("chatters").toObject(); - - for (const auto &category : categories) { - for (auto jsonCategory : jsonCategories.value(category).toArray()) { - usernames.insert(jsonCategory.toString()); + for (const auto &category : categories) { + for (auto jsonCategory : jsonCategories.value(category).toArray()) { + usernames.insert(jsonCategory.toString()); + } } - } - return {Success, std::move(usernames)}; -} + return {Success, std::move(usernames)}; + } } // namespace TwitchChannel::TwitchChannel(const QString &name, @@ -309,7 +310,7 @@ bool TwitchChannel::isLive() const } AccessGuard -TwitchChannel::accessStreamStatus() const + TwitchChannel::accessStreamStatus() const { return this->streamStatus_.accessConst(); } diff --git a/src/providers/twitch/TwitchParseCheerEmotes.cpp b/src/providers/twitch/TwitchParseCheerEmotes.cpp index 47d6427f8..65eca1fa3 100644 --- a/src/providers/twitch/TwitchParseCheerEmotes.cpp +++ b/src/providers/twitch/TwitchParseCheerEmotes.cpp @@ -8,235 +8,235 @@ namespace chatterino { namespace { -template -inline bool ReadValue(const rapidjson::Value &object, const char *key, - Type &out) -{ - if (!object.HasMember(key)) { - return false; - } - - const auto &value = object[key]; - - if (!value.Is()) { - return false; - } - - out = value.Get(); - - return true; -} - -template <> -inline bool ReadValue(const rapidjson::Value &object, const char *key, - QString &out) -{ - if (!object.HasMember(key)) { - return false; - } - - const auto &value = object[key]; - - if (!value.IsString()) { - return false; - } - - out = value.GetString(); - - return true; -} - -template <> -inline bool ReadValue>(const rapidjson::Value &object, - const char *key, - std::vector &out) -{ - if (!object.HasMember(key)) { - return false; - } - - const auto &value = object[key]; - - if (!value.IsArray()) { - return false; - } - - for (const rapidjson::Value &innerValue : value.GetArray()) { - if (!innerValue.IsString()) { + template + inline bool ReadValue(const rapidjson::Value &object, const char *key, + Type &out) + { + if (!object.HasMember(key)) { return false; } - out.emplace_back(innerValue.GetString()); - } + const auto &value = object[key]; - return true; -} - -// Parse a single cheermote set (or "action") from the twitch api -inline bool ParseSingleCheermoteSet(JSONCheermoteSet &set, - const rapidjson::Value &action) -{ - if (!action.IsObject()) { - return false; - } - - if (!ReadValue(action, "prefix", set.prefix)) { - return false; - } - - if (!ReadValue(action, "scales", set.scales)) { - return false; - } - - if (!ReadValue(action, "backgrounds", set.backgrounds)) { - return false; - } - - if (!ReadValue(action, "states", set.states)) { - return false; - } - - if (!ReadValue(action, "type", set.type)) { - return false; - } - - if (!ReadValue(action, "updated_at", set.updatedAt)) { - return false; - } - - if (!ReadValue(action, "priority", set.priority)) { - return false; - } - - // Tiers - if (!action.HasMember("tiers")) { - return false; - } - - const auto &tiersValue = action["tiers"]; - - if (!tiersValue.IsArray()) { - return false; - } - - for (const rapidjson::Value &tierValue : tiersValue.GetArray()) { - JSONCheermoteSet::CheermoteTier tier; - - if (!tierValue.IsObject()) { + if (!value.Is()) { return false; } - if (!ReadValue(tierValue, "min_bits", tier.minBits)) { + out = value.Get(); + + return true; + } + + template <> + inline bool ReadValue(const rapidjson::Value &object, + const char *key, QString &out) + { + if (!object.HasMember(key)) { return false; } - if (!ReadValue(tierValue, "id", tier.id)) { + const auto &value = object[key]; + + if (!value.IsString()) { return false; } - if (!ReadValue(tierValue, "color", tier.color)) { + out = value.GetString(); + + return true; + } + + template <> + inline bool ReadValue>(const rapidjson::Value &object, + const char *key, + std::vector &out) + { + if (!object.HasMember(key)) { return false; } - // Images - if (!tierValue.HasMember("images")) { + const auto &value = object[key]; + + if (!value.IsArray()) { return false; } - const auto &imagesValue = tierValue["images"]; - - if (!imagesValue.IsObject()) { - return false; - } - - // Read images object - for (const auto &imageBackgroundValue : imagesValue.GetObject()) { - QString background = imageBackgroundValue.name.GetString(); - bool backgroundExists = false; - for (const auto &bg : set.backgrounds) { - if (background == bg) { - backgroundExists = true; - break; - } + for (const rapidjson::Value &innerValue : value.GetArray()) { + if (!innerValue.IsString()) { + return false; } - if (!backgroundExists) { - continue; + out.emplace_back(innerValue.GetString()); + } + + return true; + } + + // Parse a single cheermote set (or "action") from the twitch api + inline bool ParseSingleCheermoteSet(JSONCheermoteSet &set, + const rapidjson::Value &action) + { + if (!action.IsObject()) { + return false; + } + + if (!ReadValue(action, "prefix", set.prefix)) { + return false; + } + + if (!ReadValue(action, "scales", set.scales)) { + return false; + } + + if (!ReadValue(action, "backgrounds", set.backgrounds)) { + return false; + } + + if (!ReadValue(action, "states", set.states)) { + return false; + } + + if (!ReadValue(action, "type", set.type)) { + return false; + } + + if (!ReadValue(action, "updated_at", set.updatedAt)) { + return false; + } + + if (!ReadValue(action, "priority", set.priority)) { + return false; + } + + // Tiers + if (!action.HasMember("tiers")) { + return false; + } + + const auto &tiersValue = action["tiers"]; + + if (!tiersValue.IsArray()) { + return false; + } + + for (const rapidjson::Value &tierValue : tiersValue.GetArray()) { + JSONCheermoteSet::CheermoteTier tier; + + if (!tierValue.IsObject()) { + return false; } - const rapidjson::Value &imageBackgroundStates = - imageBackgroundValue.value; - if (!imageBackgroundStates.IsObject()) { - continue; + if (!ReadValue(tierValue, "min_bits", tier.minBits)) { + return false; } - // Read each key which represents a background - for (const auto &imageBackgroundState : - imageBackgroundStates.GetObject()) { - QString state = imageBackgroundState.name.GetString(); - bool stateExists = false; - for (const auto &_state : set.states) { - if (state == _state) { - stateExists = true; + if (!ReadValue(tierValue, "id", tier.id)) { + return false; + } + + if (!ReadValue(tierValue, "color", tier.color)) { + return false; + } + + // Images + if (!tierValue.HasMember("images")) { + return false; + } + + const auto &imagesValue = tierValue["images"]; + + if (!imagesValue.IsObject()) { + return false; + } + + // Read images object + for (const auto &imageBackgroundValue : imagesValue.GetObject()) { + QString background = imageBackgroundValue.name.GetString(); + bool backgroundExists = false; + for (const auto &bg : set.backgrounds) { + if (background == bg) { + backgroundExists = true; break; } } - if (!stateExists) { + if (!backgroundExists) { continue; } - const rapidjson::Value &imageScalesValue = - imageBackgroundState.value; - if (!imageScalesValue.IsObject()) { + const rapidjson::Value &imageBackgroundStates = + imageBackgroundValue.value; + if (!imageBackgroundStates.IsObject()) { continue; } - // Read each key which represents a scale - for (const auto &imageScaleValue : - imageScalesValue.GetObject()) { - QString scale = imageScaleValue.name.GetString(); - bool scaleExists = false; - for (const auto &_scale : set.scales) { - if (scale == _scale) { - scaleExists = true; + // Read each key which represents a background + for (const auto &imageBackgroundState : + imageBackgroundStates.GetObject()) { + QString state = imageBackgroundState.name.GetString(); + bool stateExists = false; + for (const auto &_state : set.states) { + if (state == _state) { + stateExists = true; break; } } - if (!scaleExists) { + if (!stateExists) { continue; } - const rapidjson::Value &imageScaleURLValue = - imageScaleValue.value; - if (!imageScaleURLValue.IsString()) { + const rapidjson::Value &imageScalesValue = + imageBackgroundState.value; + if (!imageScalesValue.IsObject()) { continue; } - QString url = imageScaleURLValue.GetString(); + // Read each key which represents a scale + for (const auto &imageScaleValue : + imageScalesValue.GetObject()) { + QString scale = imageScaleValue.name.GetString(); + bool scaleExists = false; + for (const auto &_scale : set.scales) { + if (scale == _scale) { + scaleExists = true; + break; + } + } - bool ok = false; - qreal scaleNumber = scale.toFloat(&ok); - if (!ok) { - continue; + if (!scaleExists) { + continue; + } + + const rapidjson::Value &imageScaleURLValue = + imageScaleValue.value; + if (!imageScaleURLValue.IsString()) { + continue; + } + + QString url = imageScaleURLValue.GetString(); + + bool ok = false; + qreal scaleNumber = scale.toFloat(&ok); + if (!ok) { + continue; + } + + qreal chatterinoScale = 1 / scaleNumber; + + auto image = Image::fromUrl({url}, chatterinoScale); + + // TODO(pajlada): Fill in name and tooltip + tier.images[background][state][scale] = image; } - - qreal chatterinoScale = 1 / scaleNumber; - - auto image = Image::fromUrl({url}, chatterinoScale); - - // TODO(pajlada): Fill in name and tooltip - tier.images[background][state][scale] = image; } } + + set.tiers.emplace_back(tier); } - set.tiers.emplace_back(tier); + return true; } - - return true; -} } // namespace // Look through the results of diff --git a/src/providers/twitch/TwitchUser.hpp b/src/providers/twitch/TwitchUser.hpp index 74a9c1252..27539386d 100644 --- a/src/providers/twitch/TwitchUser.hpp +++ b/src/providers/twitch/TwitchUser.hpp @@ -34,43 +34,43 @@ struct TwitchUser { namespace pajlada { namespace Settings { -template <> -struct Deserialize { - static chatterino::TwitchUser get(const rapidjson::Value &value, - bool *error = nullptr) - { - using namespace chatterino; + template <> + struct Deserialize { + static chatterino::TwitchUser get(const rapidjson::Value &value, + bool *error = nullptr) + { + using namespace chatterino; - TwitchUser user; + TwitchUser user; + + if (!value.IsObject()) { + PAJLADA_REPORT_ERROR(error) + PAJLADA_THROW_EXCEPTION( + "Deserialized rapidjson::Value is wrong type"); + return user; + } + + if (!rj::getSafe(value, "_id", user.id)) { + PAJLADA_REPORT_ERROR(error) + PAJLADA_THROW_EXCEPTION("Missing ID key"); + return user; + } + + if (!rj::getSafe(value, "name", user.name)) { + PAJLADA_REPORT_ERROR(error) + PAJLADA_THROW_EXCEPTION("Missing name key"); + return user; + } + + if (!rj::getSafe(value, "display_name", user.displayName)) { + PAJLADA_REPORT_ERROR(error) + PAJLADA_THROW_EXCEPTION("Missing display name key"); + return user; + } - if (!value.IsObject()) { - PAJLADA_REPORT_ERROR(error) - PAJLADA_THROW_EXCEPTION( - "Deserialized rapidjson::Value is wrong type"); return user; } - - if (!rj::getSafe(value, "_id", user.id)) { - PAJLADA_REPORT_ERROR(error) - PAJLADA_THROW_EXCEPTION("Missing ID key"); - return user; - } - - if (!rj::getSafe(value, "name", user.name)) { - PAJLADA_REPORT_ERROR(error) - PAJLADA_THROW_EXCEPTION("Missing name key"); - return user; - } - - if (!rj::getSafe(value, "display_name", user.displayName)) { - PAJLADA_REPORT_ERROR(error) - PAJLADA_THROW_EXCEPTION("Missing display name key"); - return user; - } - - return user; - } -}; + }; } // namespace Settings } // namespace pajlada diff --git a/src/singletons/Fonts.cpp b/src/singletons/Fonts.cpp index cc2f00727..991646acd 100644 --- a/src/singletons/Fonts.cpp +++ b/src/singletons/Fonts.cpp @@ -9,16 +9,16 @@ #include #ifdef Q_OS_WIN32 -#define DEFAULT_FONT_FAMILY "Segoe UI" -#define DEFAULT_FONT_SIZE 10 +# define DEFAULT_FONT_FAMILY "Segoe UI" +# define DEFAULT_FONT_SIZE 10 #else -#ifdef Q_OS_MACOS -#define DEFAULT_FONT_FAMILY "Helvetica Neue" -#define DEFAULT_FONT_SIZE 12 -#else -#define DEFAULT_FONT_FAMILY "Arial" -#define DEFAULT_FONT_SIZE 11 -#endif +# ifdef Q_OS_MACOS +# define DEFAULT_FONT_FAMILY "Helvetica Neue" +# define DEFAULT_FONT_SIZE 12 +# else +# define DEFAULT_FONT_FAMILY "Arial" +# define DEFAULT_FONT_SIZE 11 +# endif #endif namespace chatterino { @@ -104,8 +104,7 @@ Fonts::FontData Fonts::createFontData(FontStyle type, float scale) {FontStyle::ChatMediumSmall, {0.8f, false, QFont::Normal}}, {FontStyle::ChatMedium, {1, false, QFont::Normal}}, {FontStyle::ChatMediumBold, - {1, false, - QFont::Weight(getSettings()->boldScale.getValue())}}, + {1, false, QFont::Weight(getSettings()->boldScale.getValue())}}, {FontStyle::ChatMediumItalic, {1, true, QFont::Normal}}, {FontStyle::ChatLarge, {1.2f, false, QFont::Normal}}, {FontStyle::ChatVeryLarge, {1.4f, false, QFont::Normal}}, diff --git a/src/singletons/NativeMessaging.cpp b/src/singletons/NativeMessaging.cpp index cd80f8021..ed113f716 100644 --- a/src/singletons/NativeMessaging.cpp +++ b/src/singletons/NativeMessaging.cpp @@ -17,11 +17,11 @@ namespace ipc = boost::interprocess; #ifdef Q_OS_WIN -#include +# include -#include -#include "singletons/WindowManager.hpp" -#include "widgets/AttachedWindow.hpp" +# include +# include "singletons/WindowManager.hpp" +# include "widgets/AttachedWindow.hpp" #endif #include diff --git a/src/singletons/Theme.cpp b/src/singletons/Theme.cpp index c5aa16b71..e39a6c873 100644 --- a/src/singletons/Theme.cpp +++ b/src/singletons/Theme.cpp @@ -10,21 +10,21 @@ namespace chatterino { namespace detail { -double getMultiplierByTheme(const QString &themeName) -{ - if (themeName == "Light") { - return 0.8; - } else if (themeName == "White") { - return 1.0; - } else if (themeName == "Black") { - return -1.0; - } else if (themeName == "Dark") { + double getMultiplierByTheme(const QString &themeName) + { + if (themeName == "Light") { + return 0.8; + } else if (themeName == "White") { + return 1.0; + } else if (themeName == "Black") { + return -1.0; + } else if (themeName == "Dark") { + return -0.8; + } + return -0.8; } - return -0.8; -} - } // namespace detail Theme::Theme() diff --git a/src/util/FormatTime.cpp b/src/util/FormatTime.cpp index 2eccca901..63b2e3c6b 100644 --- a/src/util/FormatTime.cpp +++ b/src/util/FormatTime.cpp @@ -2,11 +2,11 @@ namespace chatterino { namespace { -void appendDuration(int count, QChar &&order, QString &outString) -{ - outString.append(QString::number(count)); - outString.append(order); -} + void appendDuration(int count, QChar &&order, QString &outString) + { + outString.append(QString::number(count)); + outString.append(order); + } } // namespace QString formatTime(int totalSeconds) diff --git a/src/util/InitUpdateButton.hpp b/src/util/InitUpdateButton.hpp index 9a88382a2..c8caaf204 100644 --- a/src/util/InitUpdateButton.hpp +++ b/src/util/InitUpdateButton.hpp @@ -4,7 +4,7 @@ namespace pajlada { namespace Signals { -class SignalHolder; + class SignalHolder; } } // namespace pajlada diff --git a/src/util/RapidJsonSerializeQString.hpp b/src/util/RapidJsonSerializeQString.hpp index 754cbf115..0d34a256b 100644 --- a/src/util/RapidJsonSerializeQString.hpp +++ b/src/util/RapidJsonSerializeQString.hpp @@ -6,38 +6,38 @@ namespace pajlada { namespace Settings { -template <> -struct Serialize { - static rapidjson::Value get(const QString &value, - rapidjson::Document::AllocatorType &a) - { - return rapidjson::Value(value.toUtf8(), a); - } -}; + template <> + struct Serialize { + static rapidjson::Value get(const QString &value, + rapidjson::Document::AllocatorType &a) + { + return rapidjson::Value(value.toUtf8(), a); + } + }; + + template <> + struct Deserialize { + static QString get(const rapidjson::Value &value, bool *error = nullptr) + { + if (!value.IsString()) { + PAJLADA_REPORT_ERROR(error) + PAJLADA_THROW_EXCEPTION( + "Deserialized rapidjson::Value is not a string"); + return QString{}; + } + + try { + return QString::fromUtf8(value.GetString(), + value.GetStringLength()); + } catch (const std::exception &) { + // int x = 5; + } catch (...) { + // int y = 5; + } -template <> -struct Deserialize { - static QString get(const rapidjson::Value &value, bool *error = nullptr) - { - if (!value.IsString()) { - PAJLADA_REPORT_ERROR(error) - PAJLADA_THROW_EXCEPTION( - "Deserialized rapidjson::Value is not a string"); return QString{}; } - - try { - return QString::fromUtf8(value.GetString(), - value.GetStringLength()); - } catch (const std::exception &) { - // int x = 5; - } catch (...) { - // int y = 5; - } - - return QString{}; - } -}; + }; } // namespace Settings } // namespace pajlada diff --git a/src/util/RapidjsonHelpers.cpp b/src/util/RapidjsonHelpers.cpp index 78256b4a2..2a9742df2 100644 --- a/src/util/RapidjsonHelpers.cpp +++ b/src/util/RapidjsonHelpers.cpp @@ -5,26 +5,28 @@ namespace chatterino { namespace rj { -void addMember(rapidjson::Value &obj, const char *key, rapidjson::Value &&value, - rapidjson::Document::AllocatorType &a) -{ - obj.AddMember(rapidjson::Value(key, a).Move(), value, a); -} + void addMember(rapidjson::Value &obj, const char *key, + rapidjson::Value &&value, + rapidjson::Document::AllocatorType &a) + { + obj.AddMember(rapidjson::Value(key, a).Move(), value, a); + } -void addMember(rapidjson::Value &obj, const char *key, rapidjson::Value &value, - rapidjson::Document::AllocatorType &a) -{ - obj.AddMember(rapidjson::Value(key, a).Move(), value.Move(), a); -} + void addMember(rapidjson::Value &obj, const char *key, + rapidjson::Value &value, + rapidjson::Document::AllocatorType &a) + { + obj.AddMember(rapidjson::Value(key, a).Move(), value.Move(), a); + } -std::string stringify(const rapidjson::Value &value) -{ - rapidjson::StringBuffer buffer; - rapidjson::Writer writer(buffer); - value.Accept(writer); + std::string stringify(const rapidjson::Value &value) + { + rapidjson::StringBuffer buffer; + rapidjson::Writer writer(buffer); + value.Accept(writer); - return std::string(buffer.GetString()); -} + return std::string(buffer.GetString()); + } } // namespace rj } // namespace chatterino diff --git a/src/util/RapidjsonHelpers.hpp b/src/util/RapidjsonHelpers.hpp index 8dbfe07a2..d3e73e8f9 100644 --- a/src/util/RapidjsonHelpers.hpp +++ b/src/util/RapidjsonHelpers.hpp @@ -11,91 +11,95 @@ namespace chatterino { namespace rj { -void addMember(rapidjson::Value &obj, const char *key, rapidjson::Value &&value, - rapidjson::Document::AllocatorType &a); -void addMember(rapidjson::Value &obj, const char *key, rapidjson::Value &value, - rapidjson::Document::AllocatorType &a); + void addMember(rapidjson::Value &obj, const char *key, + rapidjson::Value &&value, + rapidjson::Document::AllocatorType &a); + void addMember(rapidjson::Value &obj, const char *key, + rapidjson::Value &value, + rapidjson::Document::AllocatorType &a); -template -void set(rapidjson::Value &obj, const char *key, const Type &value, - rapidjson::Document::AllocatorType &a) -{ - assert(obj.IsObject()); + template + void set(rapidjson::Value &obj, const char *key, const Type &value, + rapidjson::Document::AllocatorType &a) + { + assert(obj.IsObject()); - addMember(obj, key, pajlada::Settings::Serialize::get(value, a), a); -} - -template <> -inline void set(rapidjson::Value &obj, const char *key, - const rapidjson::Value &value, - rapidjson::Document::AllocatorType &a) -{ - assert(obj.IsObject()); - - addMember(obj, key, const_cast(value), a); -} - -template -void set(rapidjson::Document &obj, const char *key, const Type &value) -{ - assert(obj.IsObject()); - - auto &a = obj.GetAllocator(); - - addMember(obj, key, pajlada::Settings::Serialize::get(value, a), a); -} - -template <> -inline void set(rapidjson::Document &obj, const char *key, - const rapidjson::Value &value) -{ - assert(obj.IsObject()); - - auto &a = obj.GetAllocator(); - - addMember(obj, key, const_cast(value), a); -} - -template -void add(rapidjson::Value &arr, const Type &value, - rapidjson::Document::AllocatorType &a) -{ - assert(arr.IsArray()); - - arr.PushBack(pajlada::Settings::Serialize::get(value, a), a); -} - -template -bool getSafe(const rapidjson::Value &obj, const char *key, Type &out) -{ - if (!obj.IsObject()) { - return false; + addMember(obj, key, pajlada::Settings::Serialize::get(value, a), + a); } - if (!obj.HasMember(key)) { - return false; + template <> + inline void set(rapidjson::Value &obj, const char *key, + const rapidjson::Value &value, + rapidjson::Document::AllocatorType &a) + { + assert(obj.IsObject()); + + addMember(obj, key, const_cast(value), a); } - if (obj.IsNull()) { - return false; + template + void set(rapidjson::Document &obj, const char *key, const Type &value) + { + assert(obj.IsObject()); + + auto &a = obj.GetAllocator(); + + addMember(obj, key, pajlada::Settings::Serialize::get(value, a), + a); } - bool error = false; - out = pajlada::Settings::Deserialize::get(obj[key], &error); + template <> + inline void set(rapidjson::Document &obj, const char *key, + const rapidjson::Value &value) + { + assert(obj.IsObject()); - return !error; -} + auto &a = obj.GetAllocator(); -template -bool getSafe(const rapidjson::Value &value, Type &out) -{ - bool error = false; - out = pajlada::Settings::Deserialize::get(value, &error); + addMember(obj, key, const_cast(value), a); + } - return !error; -} + template + void add(rapidjson::Value &arr, const Type &value, + rapidjson::Document::AllocatorType &a) + { + assert(arr.IsArray()); -std::string stringify(const rapidjson::Value &value); + arr.PushBack(pajlada::Settings::Serialize::get(value, a), a); + } + + template + bool getSafe(const rapidjson::Value &obj, const char *key, Type &out) + { + if (!obj.IsObject()) { + return false; + } + + if (!obj.HasMember(key)) { + return false; + } + + if (obj.IsNull()) { + return false; + } + + bool error = false; + out = pajlada::Settings::Deserialize::get(obj[key], &error); + + return !error; + } + + template + bool getSafe(const rapidjson::Value &value, Type &out) + { + bool error = false; + out = pajlada::Settings::Deserialize::get(value, &error); + + return !error; + } + + std::string stringify(const rapidjson::Value &value); } // namespace rj } // namespace chatterino diff --git a/src/util/StreamLink.cpp b/src/util/StreamLink.cpp index 3cf639b6c..972c47f59 100644 --- a/src/util/StreamLink.cpp +++ b/src/util/StreamLink.cpp @@ -2,9 +2,9 @@ #include "Application.hpp" #include "Helpers.hpp" +#include "debug/Log.hpp" #include "singletons/Settings.hpp" #include "widgets/dialogs/QualityPopup.hpp" -#include "debug/Log.hpp" #include #include @@ -16,88 +16,89 @@ namespace chatterino { namespace { -const char *getBinaryName() -{ + const char *getBinaryName() + { #ifdef _WIN32 - return "streamlink.exe"; + return "streamlink.exe"; #else - return "streamlink"; + return "streamlink"; #endif -} + } -const char *getDefaultBinaryPath() -{ + const char *getDefaultBinaryPath() + { #ifdef _WIN32 - return "C:\\Program Files (x86)\\Streamlink\\bin\\streamlink.exe"; + return "C:\\Program Files (x86)\\Streamlink\\bin\\streamlink.exe"; #else - return "/usr/bin/streamlink"; + return "/usr/bin/streamlink"; #endif -} - -QString getStreamlinkProgram() -{ - auto app = getApp(); - - if (getSettings()->streamlinkUseCustomPath) { - return getSettings()->streamlinkPath + "/" + getBinaryName(); - } else { - return getBinaryName(); - } -} - -bool checkStreamlinkPath(const QString &path) -{ - QFileInfo fileinfo(path); - - if (!fileinfo.exists()) { - return false; - // throw Exception(fS("Streamlink path ({}) is invalid, file does not - // exist", path)); } - return fileinfo.isExecutable(); -} + QString getStreamlinkProgram() + { + auto app = getApp(); -void showStreamlinkNotFoundError() -{ - static QErrorMessage *msg = new QErrorMessage; - - auto app = getApp(); - if (getSettings()->streamlinkUseCustomPath) { - msg->showMessage( - "Unable to find Streamlink executable\nMake sure your custom path " - "is pointing " - "to the DIRECTORY where the streamlink executable is located"); - } else { - msg->showMessage( - "Unable to find Streamlink executable.\nIf you have Streamlink " - "installed, you might need to enable the custom path option"); - } -} - -QProcess *createStreamlinkProcess() -{ - auto p = new QProcess; - p->setProgram(getStreamlinkProgram()); - - QObject::connect(p, &QProcess::errorOccurred, [=](auto err) { - if (err == QProcess::FailedToStart) { - showStreamlinkNotFoundError(); + if (getSettings()->streamlinkUseCustomPath) { + return getSettings()->streamlinkPath + "/" + getBinaryName(); } else { - log("Error occured {}", err); + return getBinaryName(); + } + } + + bool checkStreamlinkPath(const QString &path) + { + QFileInfo fileinfo(path); + + if (!fileinfo.exists()) { + return false; + // throw Exception(fS("Streamlink path ({}) is invalid, file does + // not exist", path)); } - p->deleteLater(); - }); + return fileinfo.isExecutable(); + } - QObject::connect(p, - static_cast(&QProcess::finished), - [=](int res) { - p->deleteLater(); // - }); + void showStreamlinkNotFoundError() + { + static QErrorMessage *msg = new QErrorMessage; - return p; -} + auto app = getApp(); + if (getSettings()->streamlinkUseCustomPath) { + msg->showMessage( + "Unable to find Streamlink executable\nMake sure your custom " + "path " + "is pointing " + "to the DIRECTORY where the streamlink executable is located"); + } else { + msg->showMessage( + "Unable to find Streamlink executable.\nIf you have Streamlink " + "installed, you might need to enable the custom path option"); + } + } + + QProcess *createStreamlinkProcess() + { + auto p = new QProcess; + p->setProgram(getStreamlinkProgram()); + + QObject::connect(p, &QProcess::errorOccurred, [=](auto err) { + if (err == QProcess::FailedToStart) { + showStreamlinkNotFoundError(); + } else { + log("Error occured {}", err); + } + + p->deleteLater(); + }); + + QObject::connect( + p, static_cast(&QProcess::finished), + [=](int res) { + p->deleteLater(); // + }); + + return p; + } } // namespace diff --git a/src/util/WindowsHelper.hpp b/src/util/WindowsHelper.hpp index fdbafa9c2..f02bb1362 100644 --- a/src/util/WindowsHelper.hpp +++ b/src/util/WindowsHelper.hpp @@ -2,8 +2,8 @@ #ifdef USEWINSDK -#include -#include +# include +# include namespace chatterino { diff --git a/src/widgets/AttachedWindow.cpp b/src/widgets/AttachedWindow.cpp index b247129b6..fee940591 100644 --- a/src/widgets/AttachedWindow.cpp +++ b/src/widgets/AttachedWindow.cpp @@ -8,12 +8,12 @@ #include #ifdef USEWINSDK -#include "util/WindowsHelper.hpp" +# include "util/WindowsHelper.hpp" -#include "Windows.h" +# include "Windows.h" // don't even think about reordering these -#include "Psapi.h" -#pragma comment(lib, "Dwmapi.lib") +# include "Psapi.h" +# pragma comment(lib, "Dwmapi.lib") #endif namespace chatterino { diff --git a/src/widgets/BaseWindow.cpp b/src/widgets/BaseWindow.cpp index af97b224b..6394284e0 100644 --- a/src/widgets/BaseWindow.cpp +++ b/src/widgets/BaseWindow.cpp @@ -20,20 +20,20 @@ #include #ifdef USEWINSDK -#include -#include -#include -#include -#include -#include +# include +# include +# include +# include +# include +# include //#include -#pragma comment(lib, "Dwmapi.lib") +# pragma comment(lib, "Dwmapi.lib") -#include -#include +# include +# include -#define WM_DPICHANGED 0x02E0 +# define WM_DPICHANGED 0x02E0 #endif #include "widgets/helper/TitlebarButton.hpp" @@ -460,11 +460,11 @@ bool BaseWindow::nativeEvent(const QByteArray &eventType, void *message, long *result) { #ifdef USEWINSDK -#if (QT_VERSION == QT_VERSION_CHECK(5, 11, 1)) +# if (QT_VERSION == QT_VERSION_CHECK(5, 11, 1)) MSG *msg = *reinterpret_cast(message); -#else +# else MSG *msg = reinterpret_cast(message); -#endif +# endif bool returnValue = false; diff --git a/src/widgets/Notebook.cpp b/src/widgets/Notebook.cpp index 04ecd0840..c56fba8b5 100644 --- a/src/widgets/Notebook.cpp +++ b/src/widgets/Notebook.cpp @@ -433,8 +433,7 @@ void SplitNotebook::addCustomButtons() // settings auto settingsBtn = this->addCustomButton(); - settingsBtn->setVisible( - !getSettings()->hidePreferencesButton.getValue()); + settingsBtn->setVisible(!getSettings()->hidePreferencesButton.getValue()); getSettings()->hidePreferencesButton.connect( [settingsBtn](bool hide, auto) { settingsBtn->setVisible(!hide); }, diff --git a/src/widgets/StreamView.cpp b/src/widgets/StreamView.cpp index 9277ba825..f548deceb 100644 --- a/src/widgets/StreamView.cpp +++ b/src/widgets/StreamView.cpp @@ -7,7 +7,7 @@ #include "widgets/splits/Split.hpp" #ifdef USEWEBENGINE -#include +# include #endif namespace chatterino { diff --git a/src/widgets/TooltipWidget.cpp b/src/widgets/TooltipWidget.cpp index 3479826b8..084f729ac 100644 --- a/src/widgets/TooltipWidget.cpp +++ b/src/widgets/TooltipWidget.cpp @@ -10,7 +10,7 @@ #include #ifdef USEWINSDK -#include +# include #endif namespace chatterino { diff --git a/src/widgets/dialogs/EmotePopup.cpp b/src/widgets/dialogs/EmotePopup.cpp index 735d68f63..2fe6bb28a 100644 --- a/src/widgets/dialogs/EmotePopup.cpp +++ b/src/widgets/dialogs/EmotePopup.cpp @@ -16,55 +16,57 @@ namespace chatterino { namespace { -auto makeTitleMessage(const QString &title) -{ - MessageBuilder builder; - builder.emplace(title, MessageElementFlag::Text); - builder->flags.set(MessageFlag::Centered); - return builder.release(); -} -auto makeEmoteMessage(const EmoteMap &map) -{ - MessageBuilder builder; - builder->flags.set(MessageFlag::Centered); - builder->flags.set(MessageFlag::DisableCompactEmotes); - - for (const auto &emote : map) { - builder - .emplace(emote.second, MessageElementFlag::AlwaysShow) - ->setLink(Link(Link::InsertText, emote.first.string)); + auto makeTitleMessage(const QString &title) + { + MessageBuilder builder; + builder.emplace(title, MessageElementFlag::Text); + builder->flags.set(MessageFlag::Centered); + return builder.release(); } - - return builder.release(); -} -void addEmoteSets(std::vector> sets, - Channel &globalChannel, Channel &subChannel) -{ - for (const auto &set : sets) { - auto &channel = set->key == "0" ? globalChannel : subChannel; - - // TITLE - auto text = - set->key == "0" || set->text.isEmpty() ? "Twitch" : set->text; - channel.addMessage(makeTitleMessage(text)); - - // EMOTES + auto makeEmoteMessage(const EmoteMap &map) + { MessageBuilder builder; builder->flags.set(MessageFlag::Centered); builder->flags.set(MessageFlag::DisableCompactEmotes); - for (const auto &emote : set->emotes) { + for (const auto &emote : map) { builder - .emplace( - getApp()->emotes->twitch.getOrCreateEmote(emote.id, - emote.name), - MessageElementFlag::AlwaysShow) - ->setLink(Link(Link::InsertText, emote.name.string)); + .emplace(emote.second, + MessageElementFlag::AlwaysShow) + ->setLink(Link(Link::InsertText, emote.first.string)); } - channel.addMessage(builder.release()); + return builder.release(); + } + void addEmoteSets( + std::vector> sets, + Channel &globalChannel, Channel &subChannel) + { + for (const auto &set : sets) { + auto &channel = set->key == "0" ? globalChannel : subChannel; + + // TITLE + auto text = + set->key == "0" || set->text.isEmpty() ? "Twitch" : set->text; + channel.addMessage(makeTitleMessage(text)); + + // EMOTES + MessageBuilder builder; + builder->flags.set(MessageFlag::Centered); + builder->flags.set(MessageFlag::DisableCompactEmotes); + + for (const auto &emote : set->emotes) { + builder + .emplace( + getApp()->emotes->twitch.getOrCreateEmote(emote.id, + emote.name), + MessageElementFlag::AlwaysShow) + ->setLink(Link(Link::InsertText, emote.name.string)); + } + + channel.addMessage(builder.release()); + } } -} } // namespace EmotePopup::EmotePopup() diff --git a/src/widgets/dialogs/LoginDialog.cpp b/src/widgets/dialogs/LoginDialog.cpp index daf3c201e..35c18c7d6 100644 --- a/src/widgets/dialogs/LoginDialog.cpp +++ b/src/widgets/dialogs/LoginDialog.cpp @@ -7,7 +7,7 @@ #include "providers/twitch/PartialTwitchUser.hpp" #ifdef USEWINSDK -#include +# include #endif #include @@ -21,54 +21,54 @@ namespace chatterino { namespace { -void LogInWithCredentials(const std::string &userID, - const std::string &username, - const std::string &clientID, - const std::string &oauthToken) -{ - QStringList errors; + void LogInWithCredentials(const std::string &userID, + const std::string &username, + const std::string &clientID, + const std::string &oauthToken) + { + QStringList errors; - if (userID.empty()) { - errors.append("Missing user ID"); + if (userID.empty()) { + errors.append("Missing user ID"); + } + if (username.empty()) { + errors.append("Missing username"); + } + if (clientID.empty()) { + errors.append("Missing Client ID"); + } + if (oauthToken.empty()) { + errors.append("Missing OAuth Token"); + } + + if (errors.length() > 0) { + QMessageBox messageBox; + messageBox.setIcon(QMessageBox::Critical); + messageBox.setText(errors.join("
")); + messageBox.setStandardButtons(QMessageBox::Ok); + messageBox.exec(); + return; + } + + // QMessageBox messageBox; + // messageBox.setIcon(QMessageBox::Information); + // messageBox.setText("Successfully logged in with user " + + // qS(username) + "!"); + pajlada::Settings::Setting::set( + "/accounts/uid" + userID + "/username", username); + pajlada::Settings::Setting::set( + "/accounts/uid" + userID + "/userID", userID); + pajlada::Settings::Setting::set( + "/accounts/uid" + userID + "/clientID", clientID); + pajlada::Settings::Setting::set( + "/accounts/uid" + userID + "/oauthToken", oauthToken); + + getApp()->accounts->twitch.reloadUsers(); + + // messageBox.exec(); + + getApp()->accounts->twitch.currentUsername = username; } - if (username.empty()) { - errors.append("Missing username"); - } - if (clientID.empty()) { - errors.append("Missing Client ID"); - } - if (oauthToken.empty()) { - errors.append("Missing OAuth Token"); - } - - if (errors.length() > 0) { - QMessageBox messageBox; - messageBox.setIcon(QMessageBox::Critical); - messageBox.setText(errors.join("
")); - messageBox.setStandardButtons(QMessageBox::Ok); - messageBox.exec(); - return; - } - - // QMessageBox messageBox; - // messageBox.setIcon(QMessageBox::Information); - // messageBox.setText("Successfully logged in with user " + - // qS(username) + "!"); - pajlada::Settings::Setting::set( - "/accounts/uid" + userID + "/username", username); - pajlada::Settings::Setting::set( - "/accounts/uid" + userID + "/userID", userID); - pajlada::Settings::Setting::set( - "/accounts/uid" + userID + "/clientID", clientID); - pajlada::Settings::Setting::set( - "/accounts/uid" + userID + "/oauthToken", oauthToken); - - getApp()->accounts->twitch.reloadUsers(); - - // messageBox.exec(); - - getApp()->accounts->twitch.currentUsername = username; -} } // namespace diff --git a/src/widgets/helper/ChannelView.cpp b/src/widgets/helper/ChannelView.cpp index 467d34630..18139219e 100644 --- a/src/widgets/helper/ChannelView.cpp +++ b/src/widgets/helper/ChannelView.cpp @@ -39,62 +39,62 @@ namespace chatterino { namespace { -void addEmoteContextMenuItems(const Emote &emote, - MessageElementFlags creatorFlags, QMenu &menu) -{ - auto openAction = menu.addAction("Open"); - auto openMenu = new QMenu; - openAction->setMenu(openMenu); + void addEmoteContextMenuItems(const Emote &emote, + MessageElementFlags creatorFlags, QMenu &menu) + { + auto openAction = menu.addAction("Open"); + auto openMenu = new QMenu; + openAction->setMenu(openMenu); - auto copyAction = menu.addAction("Copy"); - auto copyMenu = new QMenu; - copyAction->setMenu(copyMenu); + auto copyAction = menu.addAction("Copy"); + auto copyMenu = new QMenu; + copyAction->setMenu(copyMenu); - // see if the QMenu actually gets destroyed - QObject::connect(openMenu, &QMenu::destroyed, [] { - QMessageBox(QMessageBox::Information, "xD", "the menu got deleted") - .exec(); - }); + // see if the QMenu actually gets destroyed + QObject::connect(openMenu, &QMenu::destroyed, [] { + QMessageBox(QMessageBox::Information, "xD", "the menu got deleted") + .exec(); + }); + + // Add copy and open links for 1x, 2x, 3x + auto addImageLink = [&](const ImagePtr &image, char scale) { + if (!image->isEmpty()) { + copyMenu->addAction( + QString(scale) + "x link", [url = image->url()] { + QApplication::clipboard()->setText(url.string); + }); + openMenu->addAction( + QString(scale) + "x link", [url = image->url()] { + QDesktopServices::openUrl(QUrl(url.string)); + }); + } + }; + + addImageLink(emote.images.getImage1(), '1'); + addImageLink(emote.images.getImage2(), '2'); + addImageLink(emote.images.getImage3(), '3'); + + // Copy and open emote page link + auto addPageLink = [&](const QString &name) { + copyMenu->addSeparator(); + openMenu->addSeparator(); - // Add copy and open links for 1x, 2x, 3x - auto addImageLink = [&](const ImagePtr &image, char scale) { - if (!image->isEmpty()) { copyMenu->addAction( - QString(scale) + "x link", [url = image->url()] { - QApplication::clipboard()->setText(url.string); + "Copy " + name + " emote link", [url = emote.homePage] { + QApplication::clipboard()->setText(url.string); // }); - openMenu->addAction(QString(scale) + "x link", - [url = image->url()] { - QDesktopServices::openUrl(QUrl(url.string)); - }); + openMenu->addAction( + "Open " + name + " emote link", [url = emote.homePage] { + QDesktopServices::openUrl(QUrl(url.string)); // + }); + }; + + if (creatorFlags.has(MessageElementFlag::BttvEmote)) { + addPageLink("BTTV"); + } else if (creatorFlags.has(MessageElementFlag::FfzEmote)) { + addPageLink("FFZ"); } - }; - - addImageLink(emote.images.getImage1(), '1'); - addImageLink(emote.images.getImage2(), '2'); - addImageLink(emote.images.getImage3(), '3'); - - // Copy and open emote page link - auto addPageLink = [&](const QString &name) { - copyMenu->addSeparator(); - openMenu->addSeparator(); - - copyMenu->addAction( - "Copy " + name + " emote link", [url = emote.homePage] { - QApplication::clipboard()->setText(url.string); // - }); - openMenu->addAction("Open " + name + " emote link", - [url = emote.homePage] { - QDesktopServices::openUrl(QUrl(url.string)); // - }); - }; - - if (creatorFlags.has(MessageElementFlag::BttvEmote)) { - addPageLink("BTTV"); - } else if (creatorFlags.has(MessageElementFlag::FfzEmote)) { - addPageLink("FFZ"); } -} } // namespace ChannelView::ChannelView(BaseWidget *parent) diff --git a/src/widgets/settingspages/ExternalToolsPage.cpp b/src/widgets/settingspages/ExternalToolsPage.cpp index bdb164e36..49204d9cb 100644 --- a/src/widgets/settingspages/ExternalToolsPage.cpp +++ b/src/widgets/settingspages/ExternalToolsPage.cpp @@ -9,15 +9,13 @@ "Choose", "Source", "High", "Medium", "Low", "Audio only" namespace chatterino { - namespace { - -QString CreateLink(const QString &url, const QString &name) -{ - return QString("" + - name + ""); -} - + QString createLink(const QString &url, const QString &name) + { + return QString("" + name + + ""); + } } // namespace ExternalToolsPage::ExternalToolsPage() @@ -41,8 +39,8 @@ ExternalToolsPage::ExternalToolsPage() description->setStyleSheet("color: #bbb"); auto links = new QLabel( - CreateLink("https://streamlink.github.io/", "Website") + " " + - CreateLink( + createLink("https://streamlink.github.io/", "Website") + " " + + createLink( "https://github.com/streamlink/streamlink/releases/latest", "Download")); links->setTextFormat(Qt::RichText); diff --git a/src/widgets/settingspages/IgnoresPage.cpp b/src/widgets/settingspages/IgnoresPage.cpp index 8aa6c5c4a..6691ee625 100644 --- a/src/widgets/settingspages/IgnoresPage.cpp +++ b/src/widgets/settingspages/IgnoresPage.cpp @@ -69,9 +69,8 @@ void addPhrasesTab(LayoutCreator layout) void addUsersTab(IgnoresPage &page, LayoutCreator users, QStringListModel &userModel) { - users.append( - page.createCheckBox("Enable twitch ignored users", - getSettings()->enableTwitchIgnoredUsers)); + users.append(page.createCheckBox("Enable twitch ignored users", + getSettings()->enableTwitchIgnoredUsers)); auto anyways = users.emplace().withoutMargin(); { diff --git a/src/widgets/settingspages/LookPage.cpp b/src/widgets/settingspages/LookPage.cpp index 5daec0464..4db671499 100644 --- a/src/widgets/settingspages/LookPage.cpp +++ b/src/widgets/settingspages/LookPage.cpp @@ -31,9 +31,9 @@ // clang-format on #ifdef USEWINSDK -#define WINDOW_TOPMOST "Window always on top" +# define WINDOW_TOPMOST "Window always on top" #else -#define WINDOW_TOPMOST "Window always on top (requires restart)" +# define WINDOW_TOPMOST "Window always on top (requires restart)" #endif #define INPUT_EMPTY "Show input box when empty" #define LAST_MSG "Mark the last message you read" diff --git a/src/widgets/settingspages/ModerationPage.cpp b/src/widgets/settingspages/ModerationPage.cpp index 28e0f7419..89d6b2411 100644 --- a/src/widgets/settingspages/ModerationPage.cpp +++ b/src/widgets/settingspages/ModerationPage.cpp @@ -25,7 +25,7 @@ namespace chatterino { -inline QString CreateLink(const QString &url, bool file = false) +inline QString createLink(const QString &url, bool file = false) { if (file) { return QString(" #ifdef USEWEBENGINE -#include "widgets/StreamView.hpp" +# include "widgets/StreamView.hpp" #endif namespace chatterino { namespace { -auto formatRoomMode(TwitchChannel &channel) -> QString -{ - QString text; - + auto formatRoomMode(TwitchChannel &channel) -> QString { - auto modes = channel.accessRoomModes(); + QString text; - if (modes->r9k) text += "r9k, "; - if (modes->slowMode) - text += QString("slow(%1), ").arg(QString::number(modes->slowMode)); - if (modes->emoteOnly) text += "emote, "; - if (modes->submode) text += "sub, "; + { + auto modes = channel.accessRoomModes(); + + if (modes->r9k) text += "r9k, "; + if (modes->slowMode) + text += + QString("slow(%1), ").arg(QString::number(modes->slowMode)); + if (modes->emoteOnly) text += "emote, "; + if (modes->submode) text += "sub, "; + } + + if (text.length() > 2) { + text = text.mid(0, text.size() - 2); + } + + if (!text.isEmpty()) { + static QRegularExpression commaReplacement("^(.+?, .+?,) (.+)$"); + + auto match = commaReplacement.match(text); + if (match.hasMatch()) + text = match.captured(1) + '\n' + match.captured(2); + } + + if (text.isEmpty() && channel.hasModRights()) return "none"; + + return text; } - - if (text.length() > 2) { - text = text.mid(0, text.size() - 2); + auto formatTooltip(const TwitchChannel::StreamStatus &s) + { + return QStringList{"", + "

", + s.title, + "

", + s.game, + "
", + s.rerun ? "Vod-casting" : "Live", + " for ", + s.uptime, + " with ", + QString::number(s.viewerCount), + " viewers", + "

"} + .join(""); } + auto formatTitle(const TwitchChannel::StreamStatus &s, Settings &settings) + { + auto title = QString(); - if (!text.isEmpty()) { - static QRegularExpression commaReplacement("^(.+?, .+?,) (.+)$"); + // live + if (s.rerun) + title += " (rerun)"; + else if (s.streamType.isEmpty()) + title += " (" + s.streamType + ")"; + else + title += " (live)"; - auto match = commaReplacement.match(text); - if (match.hasMatch()) - text = match.captured(1) + '\n' + match.captured(2); + // description + if (settings.showViewerCount) + title += " - " + QString::number(s.viewerCount); + if (settings.showTitle) title += " - " + s.title; + if (settings.showGame) title += " - " + s.game; + if (settings.showUptime) title += " - " + s.uptime; + + return title; } + auto distance(QPoint a, QPoint b) + { + auto x = std::abs(a.x() - b.x()); + auto y = std::abs(a.y() - b.y()); - if (text.isEmpty() && channel.hasModRights()) return "none"; - - return text; -} -auto formatTooltip(const TwitchChannel::StreamStatus &s) -{ - return QStringList{"", - "

", - s.title, - "

", - s.game, - "
", - s.rerun ? "Vod-casting" : "Live", - " for ", - s.uptime, - " with ", - QString::number(s.viewerCount), - " viewers", - "

"} - .join(""); -} -auto formatTitle(const TwitchChannel::StreamStatus &s, Settings &settings) -{ - auto title = QString(); - - // live - if (s.rerun) - title += " (rerun)"; - else if (s.streamType.isEmpty()) - title += " (" + s.streamType + ")"; - else - title += " (live)"; - - // description - if (settings.showViewerCount) - title += " - " + QString::number(s.viewerCount); - if (settings.showTitle) title += " - " + s.title; - if (settings.showGame) title += " - " + s.game; - if (settings.showUptime) title += " - " + s.uptime; - - return title; -} -auto distance(QPoint a, QPoint b) -{ - auto x = std::abs(a.x() - b.x()); - auto y = std::abs(a.y() - b.y()); - - return std::sqrt(x * x + y * y); -} + return std::sqrt(x * x + y * y); + } } // namespace SplitHeader::SplitHeader(Split *_split)