diff --git a/.clang-format b/.clang-format index e141fff60..bd3f2c430 100644 --- a/.clang-format +++ b/.clang-format @@ -1,23 +1,14 @@ -IndentCaseLabels: true -BasedOnStyle: Google -IndentWidth: 4 -Standard: Auto -PointerBindsToType: false Language: Cpp -SpacesBeforeTrailingComments: 2 + AccessModifierOffset: -1 -AlignEscapedNewlinesLeft: true -AlwaysBreakAfterDefinitionReturnType: false -AlwaysBreakBeforeMultilineStrings: false -BreakConstructorInitializersBeforeComma: true -# BreakBeforeBraces: Linux -BreakBeforeBraces: Custom AccessModifierOffset: -4 -ConstructorInitializerAllOnOneLineOrOnePerLine: false +AlignEscapedNewlinesLeft: true AllowShortFunctionsOnASingleLine: false AllowShortIfStatementsOnASingleLine: true AllowShortLoopsOnASingleLine: false -DerivePointerBinding: false +AlwaysBreakAfterDefinitionReturnType: false +AlwaysBreakBeforeMultilineStrings: false +BasedOnStyle: Google BraceWrapping: { AfterNamespace: 'false' AfterClass: 'true' @@ -26,5 +17,14 @@ BraceWrapping: { AfterFunction: 'true' BeforeCatch: 'false' } -ColumnLimit: 100 +BreakBeforeBraces: Custom +BreakConstructorInitializersBeforeComma: true +ColumnLimit: 80 +ConstructorInitializerAllOnOneLineOrOnePerLine: false +DerivePointerBinding: false FixNamespaceComments: true +IndentCaseLabels: true +IndentWidth: 4 +PointerBindsToType: false +SpacesBeforeTrailingComments: 2 +Standard: Auto diff --git a/src/Application.cpp b/src/Application.cpp index b7d651aa4..414e7c5cf 100644 --- a/src/Application.cpp +++ b/src/Application.cpp @@ -30,7 +30,8 @@ static std::atomic isAppInitialized{false}; Application *Application::instance = nullptr; // this class is responsible for handling the workflow of Chatterino -// It will create the instances of the major classes, and connect their signals to each other +// It will create the instances of the major classes, and connect their signals +// to each other Application::Application(Settings &_settings, Paths &_paths) : settings(&_settings) @@ -53,7 +54,8 @@ Application::Application(Settings &_settings, Paths &_paths) { this->instance = this; - this->fonts->fontChanged.connect([this]() { this->windows->layoutChannelViews(); }); + this->fonts->fontChanged.connect( + [this]() { this->windows->layoutChannelViews(); }); this->twitch.server = this->twitch2; this->twitch.pubsub = this->twitch2->pubsub; @@ -117,40 +119,49 @@ void Application::initPubsub() Log("WHISPER RECEIVED LOL"); // }); - this->twitch.pubsub->signals_.moderation.chatCleared.connect([this](const auto &action) { - auto chan = this->twitch.server->getChannelOrEmptyByID(action.roomID); - if (chan->isEmpty()) { - return; - } + this->twitch.pubsub->signals_.moderation.chatCleared.connect( + [this](const auto &action) { + auto chan = + this->twitch.server->getChannelOrEmptyByID(action.roomID); + if (chan->isEmpty()) { + return; + } - QString text = QString("%1 cleared the chat").arg(action.source.name); + QString text = + QString("%1 cleared the chat").arg(action.source.name); - auto msg = Message::createSystemMessage(text); - postToThread([chan, msg] { chan->addMessage(msg); }); - }); + auto msg = Message::createSystemMessage(text); + postToThread([chan, msg] { chan->addMessage(msg); }); + }); - this->twitch.pubsub->signals_.moderation.modeChanged.connect([this](const auto &action) { - auto chan = this->twitch.server->getChannelOrEmptyByID(action.roomID); - if (chan->isEmpty()) { - return; - } + this->twitch.pubsub->signals_.moderation.modeChanged.connect( + [this](const auto &action) { + auto chan = + this->twitch.server->getChannelOrEmptyByID(action.roomID); + if (chan->isEmpty()) { + return; + } - QString text = QString("%1 turned %2 %3 mode") // - .arg(action.source.name) - .arg(action.state == ModeChangedAction::State::On ? "on" : "off") - .arg(action.getModeName()); + QString text = + QString("%1 turned %2 %3 mode") // + .arg(action.source.name) + .arg(action.state == ModeChangedAction::State::On ? "on" + : "off") + .arg(action.getModeName()); - if (action.duration > 0) { - text.append(" (" + QString::number(action.duration) + " seconds)"); - } + if (action.duration > 0) { + text.append(" (" + QString::number(action.duration) + + " seconds)"); + } - auto msg = Message::createSystemMessage(text); - postToThread([chan, msg] { chan->addMessage(msg); }); - }); + auto msg = Message::createSystemMessage(text); + postToThread([chan, msg] { chan->addMessage(msg); }); + }); this->twitch.pubsub->signals_.moderation.moderationStateChanged.connect( [this](const auto &action) { - auto chan = this->twitch.server->getChannelOrEmptyByID(action.roomID); + auto chan = + this->twitch.server->getChannelOrEmptyByID(action.roomID); if (chan->isEmpty()) { return; } @@ -158,48 +169,55 @@ void Application::initPubsub() QString text; if (action.modded) { - text = QString("%1 modded %2").arg(action.source.name, action.target.name); + text = QString("%1 modded %2") + .arg(action.source.name, action.target.name); } else { - text = QString("%1 unmodded %2").arg(action.source.name, action.target.name); + text = QString("%1 unmodded %2") + .arg(action.source.name, action.target.name); } auto msg = Message::createSystemMessage(text); postToThread([chan, msg] { chan->addMessage(msg); }); }); - this->twitch.pubsub->signals_.moderation.userBanned.connect([&](const auto &action) { - auto chan = this->twitch.server->getChannelOrEmptyByID(action.roomID); + this->twitch.pubsub->signals_.moderation.userBanned.connect( + [&](const auto &action) { + auto chan = + this->twitch.server->getChannelOrEmptyByID(action.roomID); - if (chan->isEmpty()) { - return; - } + if (chan->isEmpty()) { + return; + } - auto msg = Message::createTimeoutMessage(action); - msg->flags |= Message::PubSub; + auto msg = Message::createTimeoutMessage(action); + msg->flags |= Message::PubSub; - postToThread([chan, msg] { chan->addOrReplaceTimeout(msg); }); - }); + postToThread([chan, msg] { chan->addOrReplaceTimeout(msg); }); + }); - this->twitch.pubsub->signals_.moderation.userUnbanned.connect([&](const auto &action) { - auto chan = this->twitch.server->getChannelOrEmptyByID(action.roomID); + this->twitch.pubsub->signals_.moderation.userUnbanned.connect( + [&](const auto &action) { + auto chan = + this->twitch.server->getChannelOrEmptyByID(action.roomID); - if (chan->isEmpty()) { - return; - } + if (chan->isEmpty()) { + return; + } - auto msg = Message::createUntimeoutMessage(action); + auto msg = Message::createUntimeoutMessage(action); - postToThread([chan, msg] { chan->addMessage(msg); }); - }); + postToThread([chan, msg] { chan->addMessage(msg); }); + }); this->twitch.pubsub->start(); auto RequestModerationActions = [=]() { this->twitch.server->pubsub->unlistenAllModerationActions(); - // TODO(pajlada): Unlisten to all authed topics instead of only moderation topics - // this->twitch.pubsub->UnlistenAllAuthedTopics(); + // TODO(pajlada): Unlisten to all authed topics instead of only + // moderation topics this->twitch.pubsub->UnlistenAllAuthedTopics(); - this->twitch.server->pubsub->listenToWhispers(this->accounts->twitch.getCurrent()); // + this->twitch.server->pubsub->listenToWhispers( + this->accounts->twitch.getCurrent()); // }; this->accounts->twitch.currentUserChanged.connect(RequestModerationActions); diff --git a/src/Application.hpp b/src/Application.hpp index c378715f5..fc7051e43 100644 --- a/src/Application.hpp +++ b/src/Application.hpp @@ -77,7 +77,8 @@ private: void initPubsub(); void initNm(); - template ::value>> + template ::value>> T &emplace() { auto t = new T; diff --git a/src/BrowserExtension.cpp b/src/BrowserExtension.cpp index 3440170ab..75a6ef26f 100644 --- a/src/BrowserExtension.cpp +++ b/src/BrowserExtension.cpp @@ -54,15 +54,16 @@ void runLoop(NativeMessagingClient &client) std::cin.read(b.get(), size); *(b.get() + size) = '\0'; - client.sendMessage(QByteArray::fromRawData(b.get(), static_cast(size))); + client.sendMessage( + QByteArray::fromRawData(b.get(), static_cast(size))); } } } // namespace bool shouldRunBrowserExtensionHost(const QStringList &args) { - return args.size() > 0 && - (args[0].startsWith("chrome-extension://") || args[0].endsWith(".json")); + return args.size() > 0 && (args[0].startsWith("chrome-extension://") || + args[0].endsWith(".json")); } void runBrowserExtensionHost() diff --git a/src/RunGui.cpp b/src/RunGui.cpp index a15bce6bc..6f0d86622 100644 --- a/src/RunGui.cpp +++ b/src/RunGui.cpp @@ -32,23 +32,28 @@ void installCustomPalette() darkPalette.setColor(QPalette::Window, QColor(22, 22, 22)); darkPalette.setColor(QPalette::WindowText, Qt::white); darkPalette.setColor(QPalette::Text, Qt::white); - darkPalette.setColor(QPalette::Disabled, QPalette::WindowText, QColor(127, 127, 127)); + darkPalette.setColor(QPalette::Disabled, QPalette::WindowText, + QColor(127, 127, 127)); darkPalette.setColor(QPalette::Base, QColor("#333")); darkPalette.setColor(QPalette::AlternateBase, QColor("#444")); darkPalette.setColor(QPalette::ToolTipBase, Qt::white); darkPalette.setColor(QPalette::ToolTipText, Qt::white); - darkPalette.setColor(QPalette::Disabled, QPalette::Text, QColor(127, 127, 127)); + darkPalette.setColor(QPalette::Disabled, QPalette::Text, + QColor(127, 127, 127)); darkPalette.setColor(QPalette::Dark, QColor(35, 35, 35)); darkPalette.setColor(QPalette::Shadow, QColor(20, 20, 20)); darkPalette.setColor(QPalette::Button, QColor(70, 70, 70)); darkPalette.setColor(QPalette::ButtonText, Qt::white); - darkPalette.setColor(QPalette::Disabled, QPalette::ButtonText, QColor(127, 127, 127)); + darkPalette.setColor(QPalette::Disabled, QPalette::ButtonText, + QColor(127, 127, 127)); darkPalette.setColor(QPalette::BrightText, Qt::red); darkPalette.setColor(QPalette::Link, QColor(42, 130, 218)); darkPalette.setColor(QPalette::Highlight, QColor(42, 130, 218)); - darkPalette.setColor(QPalette::Disabled, QPalette::Highlight, QColor(80, 80, 80)); + darkPalette.setColor(QPalette::Disabled, QPalette::Highlight, + QColor(80, 80, 80)); darkPalette.setColor(QPalette::HighlightedText, Qt::white); - darkPalette.setColor(QPalette::Disabled, QPalette::HighlightedText, QColor(127, 127, 127)); + darkPalette.setColor(QPalette::Disabled, QPalette::HighlightedText, + QColor(127, 127, 127)); qApp->setPalette(darkPalette); } @@ -106,7 +111,8 @@ void runGui(QApplication &a, Paths &paths, Settings &settings) #endif // Running file - auto runningPath = paths.miscDirectory + "/running_" + paths.applicationFilePathHash; + auto runningPath = + paths.miscDirectory + "/running_" + paths.applicationFilePathHash; if (QFile::exists(runningPath)) { showLastCrashDialog(); diff --git a/src/autogenerated/ResourcesAutogen.hpp b/src/autogenerated/ResourcesAutogen.hpp index 048a1a94b..c6adb3576 100644 --- a/src/autogenerated/ResourcesAutogen.hpp +++ b/src/autogenerated/ResourcesAutogen.hpp @@ -3,7 +3,8 @@ namespace chatterino { -class Resources2 : public Singleton { +class Resources2 : public Singleton +{ public: Resources2(); diff --git a/src/common/Channel.cpp b/src/common/Channel.cpp index c03019c43..364d836d2 100644 --- a/src/common/Channel.cpp +++ b/src/common/Channel.cpp @@ -22,9 +22,10 @@ Channel::Channel(const QString &name, Type type) , name_(name) , type_(type) { - QObject::connect(&this->clearCompletionModelTimer_, &QTimer::timeout, [this]() { - this->completionModel.clearExpiredStrings(); // - }); + QObject::connect(&this->clearCompletionModelTimer_, &QTimer::timeout, + [this]() { + this->completionModel.clearExpiredStrings(); // + }); this->clearCompletionModelTimer_.start(60 * 1000); } @@ -65,7 +66,8 @@ void Channel::addMessage(MessagePtr message) const QString &username = message->loginName; if (!username.isEmpty()) { - // TODO: Add recent chatters display name. This should maybe be a setting + // TODO: Add recent chatters display name. This should maybe be a + // setting this->addRecentChatter(message); } @@ -101,17 +103,21 @@ void Channel::addOrReplaceTimeout(MessagePtr message) break; } - if (s->flags.HasFlag(Message::Untimeout) && s->timeoutUser == message->timeoutUser) { + if (s->flags.HasFlag(Message::Untimeout) && + s->timeoutUser == message->timeoutUser) { break; } - if (s->flags.HasFlag(Message::Timeout) && s->timeoutUser == message->timeoutUser) { - if (message->flags.HasFlag(Message::PubSub) && !s->flags.HasFlag(Message::PubSub)) { + if (s->flags.HasFlag(Message::Timeout) && + s->timeoutUser == message->timeoutUser) { + if (message->flags.HasFlag(Message::PubSub) && + !s->flags.HasFlag(Message::PubSub)) { this->replaceMessage(s, message); addMessage = false; break; } - if (!message->flags.HasFlag(Message::PubSub) && s->flags.HasFlag(Message::PubSub)) { + if (!message->flags.HasFlag(Message::PubSub) && + s->flags.HasFlag(Message::PubSub)) { addMessage = false; break; } @@ -119,7 +125,8 @@ void Channel::addOrReplaceTimeout(MessagePtr message) int count = s->count + 1; MessagePtr replacement(Message::createSystemMessage( - message->searchText + QString(" (") + QString::number(count) + " times)")); + message->searchText + QString(" (") + QString::number(count) + + " times)")); replacement->timeoutUser = message->timeoutUser; replacement->count = count; @@ -164,7 +171,8 @@ void Channel::disableAllMessages() void Channel::addMessagesAtStart(std::vector &_messages) { - std::vector addedMessages = this->messages_.pushFront(_messages); + std::vector addedMessages = + this->messages_.pushFront(_messages); if (addedMessages.size() != 0) { this->messagesAddedAtStart.invoke(addedMessages); diff --git a/src/common/Channel.hpp b/src/common/Channel.hpp index e153914c1..043b33fe8 100644 --- a/src/common/Channel.hpp +++ b/src/common/Channel.hpp @@ -32,7 +32,8 @@ public: explicit Channel(const QString &name, Type type); virtual ~Channel(); - pajlada::Signals::Signal sendMessageSignal; + pajlada::Signals::Signal + sendMessageSignal; pajlada::Signals::Signal messageRemovedFromStart; pajlada::Signals::Signal messageAppended; @@ -96,7 +97,8 @@ class IndirectChannel }; public: - IndirectChannel(ChannelPtr channel, Channel::Type type = Channel::Type::Direct) + IndirectChannel(ChannelPtr channel, + Channel::Type type = Channel::Type::Direct) : data_(new Data(channel, type)) { } diff --git a/src/common/Common.hpp b/src/common/Common.hpp index c4abe043f..251727c24 100644 --- a/src/common/Common.hpp +++ b/src/common/Common.hpp @@ -25,8 +25,10 @@ inline QString qS(const std::string &string) return QString::fromStdString(string); } -const Qt::KeyboardModifiers showSplitOverlayModifiers = Qt::ControlModifier | Qt::AltModifier; -const Qt::KeyboardModifiers showAddSplitRegions = Qt::ControlModifier | Qt::AltModifier; +const Qt::KeyboardModifiers showSplitOverlayModifiers = + Qt::ControlModifier | Qt::AltModifier; +const Qt::KeyboardModifiers showAddSplitRegions = + Qt::ControlModifier | Qt::AltModifier; const Qt::KeyboardModifiers showResizeHandlesModifiers = Qt::ControlModifier; static const char *ANONYMOUS_USERNAME_LABEL ATTR_UNUSED = " - anonymous - "; diff --git a/src/common/CompletionModel.cpp b/src/common/CompletionModel.cpp index f56425d27..bd0038107 100644 --- a/src/common/CompletionModel.cpp +++ b/src/common/CompletionModel.cpp @@ -111,26 +111,32 @@ void CompletionModel::refresh() // User-specific: Twitch Emotes if (auto account = app->accounts->twitch.getCurrent()) { for (const auto &emote : account->accessEmotes()->allEmoteNames) { - // XXX: No way to discern between a twitch global emote and sub emote right now - this->addString(emote.string, TaggedString::Type::TwitchGlobalEmote); + // XXX: No way to discern between a twitch global emote and sub + // emote right now + this->addString(emote.string, + TaggedString::Type::TwitchGlobalEmote); } } // // Global: BTTV Global Emotes - // std::vector &bttvGlobalEmoteCodes = app->emotes->bttv.globalEmoteNames_; - // for (const auto &m : bttvGlobalEmoteCodes) { + // std::vector &bttvGlobalEmoteCodes = + // app->emotes->bttv.globalEmoteNames_; for (const auto &m : + // bttvGlobalEmoteCodes) { // this->addString(m, TaggedString::Type::BTTVGlobalEmote); // } // // Global: FFZ Global Emotes - // std::vector &ffzGlobalEmoteCodes = app->emotes->ffz.globalEmoteCodes; - // for (const auto &m : ffzGlobalEmoteCodes) { + // std::vector &ffzGlobalEmoteCodes = + // app->emotes->ffz.globalEmoteCodes; for (const auto &m : + // ffzGlobalEmoteCodes) { // this->addString(m, TaggedString::Type::FFZGlobalEmote); // } // Channel emotes if (auto channel = dynamic_cast( - getApp()->twitch2->getChannelOrEmptyByID(this->channelName_).get())) { + getApp() + ->twitch2->getChannelOrEmptyByID(this->channelName_) + .get())) { auto bttv = channel->accessBttvEmotes(); // auto it = bttv->begin(); // for (const auto &emote : *bttv) { @@ -143,7 +149,8 @@ void CompletionModel::refresh() // Channel-specific: FFZ Channel Emotes for (const auto &emote : *channel->accessFfzEmotes()) { - this->addString(emote.second->name.string, TaggedString::Type::FFZChannelEmote); + this->addString(emote.second->name.string, + TaggedString::Type::FFZChannelEmote); } } @@ -164,7 +171,8 @@ void CompletionModel::refresh() // Channel-specific: Usernames // fourtf: only works with twitch chat - // auto c = ChannelManager::getInstance().getTwitchChannel(this->channelName); + // auto c = + // ChannelManager::getInstance().getTwitchChannel(this->channelName); // auto usernames = c->getUsernamesForCompletions(); // for (const auto &name : usernames) { // assert(!name.displayName.isEmpty()); @@ -191,9 +199,11 @@ void CompletionModel::addUser(const QString &username) auto add = [this](const QString &str) { auto ts = this->createUser(str + " "); // Always add a space at the end of completions - std::pair::iterator, bool> p = this->emotes_.insert(ts); + std::pair::iterator, bool> p = + this->emotes_.insert(ts); if (!p.second) { - // No inseration was made, figure out if we need to replace the username. + // No inseration was made, figure out if we need to replace the + // username. if (p.first->str > ts.str) { // Replace lowercase version of name with mixed-case version diff --git a/src/common/ConcurrentMap.hpp b/src/common/ConcurrentMap.hpp index 2db2d9f58..0b5cbeb0e 100644 --- a/src/common/ConcurrentMap.hpp +++ b/src/common/ConcurrentMap.hpp @@ -65,7 +65,8 @@ public: this->data.insert(name, value); } - void each(std::function func) const + void each( + std::function func) const { QMutexLocker lock(&this->mutex); diff --git a/src/common/Emotemap.hpp b/src/common/Emotemap.hpp index c57f08e91..8c219bc67 100644 --- a/src/common/Emotemap.hpp +++ b/src/common/Emotemap.hpp @@ -14,8 +14,8 @@ namespace chatterino { // bool isValid() const; // Image *getImage(float scale) const; -// // Link to the emote page i.e. https://www.frankerfacez.com/emoticon/144722-pajaCringe -// QString pageLink; +// // Link to the emote page i.e. +// https://www.frankerfacez.com/emoticon/144722-pajaCringe QString pageLink; // Image *image1x = nullptr; // Image *image2x = nullptr; diff --git a/src/common/LinkParser.cpp b/src/common/LinkParser.cpp index ac4ddf734..b4f63a156 100644 --- a/src/common/LinkParser.cpp +++ b/src/common/LinkParser.cpp @@ -45,9 +45,11 @@ LinkParser::LinkParser(const QString &unparsedString) "(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))" "|" // host name - "(?:(?:[_a-z\\x{00a1}-\\x{ffff}0-9]-*)*[a-z\\x{00a1}-\\x{ffff}0-9]+)" + "(?:(?:[_a-z\\x{00a1}-\\x{ffff}0-9]-*)*[a-z\\x{00a1}-\\x{ffff}0-9]+" + ")" // domain name - "(?:\\.(?:[a-z\\x{00a1}-\\x{ffff}0-9]-*)*[a-z\\x{00a1}-\\x{ffff}0-9]+)*" + "(?:\\.(?:[a-z\\x{00a1}-\\x{ffff}0-9]-*)*[a-z\\x{00a1}-\\x{ffff}0-" + "9]+)*" // TLD identifier //"(?:\\.(?:[a-z\\x{00a1}-\\x{ffff}]{2,}))" "(?:[\\.](?:" + @@ -61,7 +63,8 @@ LinkParser::LinkParser(const QString &unparsedString) "(?:[/?#]\\S*)?" "$"; - return QRegularExpression(hyperlinkRegExp, QRegularExpression::CaseInsensitiveOption); + return QRegularExpression(hyperlinkRegExp, + QRegularExpression::CaseInsensitiveOption); }(); this->match_ = linkRegex.match(unparsedString); diff --git a/src/common/NetworkData.cpp b/src/common/NetworkData.cpp index 12aec944d..ad8fe40b2 100644 --- a/src/common/NetworkData.cpp +++ b/src/common/NetworkData.cpp @@ -30,7 +30,8 @@ QString NetworkData::getHash() bytes.append(header); } - QByteArray hashBytes(QCryptographicHash::hash(bytes, QCryptographicHash::Sha256)); + QByteArray hashBytes( + QCryptographicHash::hash(bytes, QCryptographicHash::Sha256)); this->hash_ = hashBytes.toHex(); } diff --git a/src/common/NetworkRequest.cpp b/src/common/NetworkRequest.cpp index 976c0fa14..c6d882551 100644 --- a/src/common/NetworkRequest.cpp +++ b/src/common/NetworkRequest.cpp @@ -11,7 +11,8 @@ namespace chatterino { -NetworkRequest::NetworkRequest(const std::string &url, NetworkRequestType requestType) +NetworkRequest::NetworkRequest(const std::string &url, + NetworkRequestType requestType) : data(new NetworkData) , timer(new NetworkTimer) { @@ -62,7 +63,8 @@ void NetworkRequest::setRawHeader(const char *headerName, const char *value) this->data->request_.setRawHeader(headerName, value); } -void NetworkRequest::setRawHeader(const char *headerName, const QByteArray &value) +void NetworkRequest::setRawHeader(const char *headerName, + const QByteArray &value) { this->data->request_.setRawHeader(headerName, value); } @@ -77,7 +79,8 @@ void NetworkRequest::setTimeout(int ms) this->timer->timeoutMS_ = ms; } -void NetworkRequest::makeAuthorizedV5(const QString &clientID, const QString &oauthToken) +void NetworkRequest::makeAuthorizedV5(const QString &clientID, + const QString &oauthToken) { this->setRawHeader("Client-ID", clientID); this->setRawHeader("Accept", "application/vnd.twitchtv.v5+json"); @@ -114,12 +117,14 @@ void NetworkRequest::execute() } break; case NetworkRequestType::Put: { - // Put requests cannot be cached, therefore the request is called immediately + // Put requests cannot be cached, therefore the request is called + // immediately this->doRequest(); } break; case NetworkRequestType::Delete: { - // Delete requests cannot be cached, therefore the request is called immediately + // Delete requests cannot be cached, therefore the request is called + // immediately this->doRequest(); } break; @@ -152,7 +157,8 @@ Outcome NetworkRequest::tryLoadCachedFile() cachedFile.close(); - // XXX: If success is false, we should invalidate the cache file somehow/somewhere + // XXX: If success is false, we should invalidate the cache file + // somehow/somewhere return outcome; } @@ -166,14 +172,16 @@ void NetworkRequest::doRequest() this->timer->start(); - auto onUrlRequested = [data = this->data, timer = this->timer, worker]() mutable { + auto onUrlRequested = [data = this->data, timer = this->timer, + worker]() mutable { auto reply = [&]() -> QNetworkReply * { switch (data->requestType_) { case NetworkRequestType::Get: return NetworkManager::NaM.get(data->request_); case NetworkRequestType::Put: - return NetworkManager::NaM.put(data->request_, data->payload_); + return NetworkManager::NaM.put(data->request_, + data->payload_); case NetworkRequestType::Delete: return NetworkManager::NaM.deleteResource(data->request_); @@ -221,12 +229,14 @@ void NetworkRequest::doRequest() }; if (data->caller_ != nullptr) { - QObject::connect(worker, &NetworkWorker::doneUrl, data->caller_, handleReply); - QObject::connect(reply, &QNetworkReply::finished, worker, [worker]() mutable { - emit worker->doneUrl(); + QObject::connect(worker, &NetworkWorker::doneUrl, data->caller_, + handleReply); + QObject::connect(reply, &QNetworkReply::finished, worker, + [worker]() mutable { + emit worker->doneUrl(); - delete worker; - }); + delete worker; + }); } else { QObject::connect(reply, &QNetworkReply::finished, worker, [handleReply, worker]() mutable { @@ -237,7 +247,8 @@ void NetworkRequest::doRequest() } }; - QObject::connect(&requester, &NetworkRequester::requestUrl, worker, onUrlRequested); + QObject::connect(&requester, &NetworkRequester::requestUrl, worker, + onUrlRequested); emit requester.requestUrl(); } diff --git a/src/common/NetworkRequest.hpp b/src/common/NetworkRequest.hpp index 049c2cba1..8112a4852 100644 --- a/src/common/NetworkRequest.hpp +++ b/src/common/NetworkRequest.hpp @@ -12,15 +12,18 @@ namespace chatterino { class NetworkRequest { - // Stores all data about the request that needs to be passed around to each part of the request + // Stores all data about the request that needs to be passed around to each + // part of the request std::shared_ptr data; // Timer that tracks the timeout // By default, there's no explicit timeout for the request - // to enable the timer, the "setTimeout" function needs to be called before execute is called + // to enable the timer, the "setTimeout" function needs to be called before + // execute is called std::shared_ptr timer; - // The NetworkRequest destructor will assert if executed_ hasn't been set to true before dying + // The NetworkRequest destructor will assert if executed_ hasn't been set to + // true before dying bool executed_ = false; public: @@ -31,9 +34,11 @@ public: NetworkRequest(NetworkRequest &&other) = default; NetworkRequest &operator=(NetworkRequest &&other) = default; - explicit NetworkRequest(const std::string &url, - NetworkRequestType requestType = NetworkRequestType::Get); - explicit NetworkRequest(QUrl url, NetworkRequestType requestType = NetworkRequestType::Get); + explicit NetworkRequest( + const std::string &url, + NetworkRequestType requestType = NetworkRequestType::Get); + explicit NetworkRequest( + QUrl url, NetworkRequestType requestType = NetworkRequestType::Get); ~NetworkRequest(); @@ -50,14 +55,15 @@ public: void setRawHeader(const char *headerName, const QByteArray &value); void setRawHeader(const char *headerName, const QString &value); void setTimeout(int ms); - void makeAuthorizedV5(const QString &clientID, const QString &oauthToken = QString()); + void makeAuthorizedV5(const QString &clientID, + const QString &oauthToken = QString()); void execute(); private: // Returns true if the file was successfully loaded from cache - // Returns false if the cache file either didn't exist, or it contained "invalid" data - // "invalid" is specified by the onSuccess callback + // Returns false if the cache file either didn't exist, or it contained + // "invalid" data "invalid" is specified by the onSuccess callback Outcome tryLoadCachedFile(); void doRequest(); diff --git a/src/common/NetworkResult.cpp b/src/common/NetworkResult.cpp index 0620bf3c2..443d0aa05 100644 --- a/src/common/NetworkResult.cpp +++ b/src/common/NetworkResult.cpp @@ -27,11 +27,12 @@ rapidjson::Document NetworkResult::parseRapidJson() const { rapidjson::Document ret(rapidjson::kObjectType); - rapidjson::ParseResult result = ret.Parse(this->data_.data(), this->data_.length()); + rapidjson::ParseResult result = + ret.Parse(this->data_.data(), this->data_.length()); if (result.Code() != rapidjson::kParseErrorNone) { - Log("JSON parse error: {} ({})", rapidjson::GetParseError_En(result.Code()), - result.Offset()); + Log("JSON parse error: {} ({})", + rapidjson::GetParseError_En(result.Code()), result.Offset()); return ret; } diff --git a/src/common/NetworkTimer.cpp b/src/common/NetworkTimer.cpp index 522fdd310..858378b17 100644 --- a/src/common/NetworkTimer.cpp +++ b/src/common/NetworkTimer.cpp @@ -28,7 +28,8 @@ bool NetworkTimer::isStarted() const return this->started_; } -void NetworkTimer::onTimeout(NetworkWorker *worker, std::function cb) const +void NetworkTimer::onTimeout(NetworkWorker *worker, + std::function cb) const { assert(this->timer_ != nullptr); assert(worker != nullptr); diff --git a/src/common/NullablePtr.hpp b/src/common/NullablePtr.hpp index fb60af0d8..8bc160fd8 100644 --- a/src/common/NullablePtr.hpp +++ b/src/common/NullablePtr.hpp @@ -59,7 +59,8 @@ public: return !this->hasElement(); } - template ::value>> + template ::value>> operator NullablePtr() const { return NullablePtr(this->element_); diff --git a/src/common/SerializeCustom.hpp b/src/common/SerializeCustom.hpp index 9aa31bcfb..754cbf115 100644 --- a/src/common/SerializeCustom.hpp +++ b/src/common/SerializeCustom.hpp @@ -8,7 +8,8 @@ namespace Settings { template <> struct Serialize { - static rapidjson::Value get(const QString &value, rapidjson::Document::AllocatorType &a) + static rapidjson::Value get(const QString &value, + rapidjson::Document::AllocatorType &a) { return rapidjson::Value(value.toUtf8(), a); } @@ -20,12 +21,14 @@ struct Deserialize { { if (!value.IsString()) { PAJLADA_REPORT_ERROR(error) - PAJLADA_THROW_EXCEPTION("Deserialized rapidjson::Value is not a string"); + PAJLADA_THROW_EXCEPTION( + "Deserialized rapidjson::Value is not a string"); return QString{}; } try { - return QString::fromUtf8(value.GetString(), value.GetStringLength()); + return QString::fromUtf8(value.GetString(), + value.GetStringLength()); } catch (const std::exception &) { // int x = 5; } catch (...) { diff --git a/src/common/SignalVector.hpp b/src/common/SignalVector.hpp index 0594b8847..1ddf2c13a 100644 --- a/src/common/SignalVector.hpp +++ b/src/common/SignalVector.hpp @@ -88,7 +88,8 @@ template class UnsortedSignalVector : public BaseSignalVector { public: - virtual int insertItem(const TVectorItem &item, int index = -1, void *caller = nullptr) override + virtual int insertItem(const TVectorItem &item, int index = -1, + void *caller = nullptr) override { assertInGuiThread(); if (index == -1) { @@ -115,11 +116,13 @@ template class SortedSignalVector : public BaseSignalVector { public: - virtual int insertItem(const TVectorItem &item, int = -1, void *caller = nullptr) override + virtual int insertItem(const TVectorItem &item, int = -1, + void *caller = nullptr) override { assertInGuiThread(); - auto it = std::lower_bound(this->vector_.begin(), this->vector_.end(), item, Compare{}); + auto it = std::lower_bound(this->vector_.begin(), this->vector_.end(), + item, Compare{}); int index = it - this->vector_.begin(); this->vector_.insert(it, item); diff --git a/src/common/SignalVectorModel.hpp b/src/common/SignalVectorModel.hpp index cab31c063..237727d0d 100644 --- a/src/common/SignalVectorModel.hpp +++ b/src/common/SignalVectorModel.hpp @@ -11,7 +11,8 @@ namespace chatterino { template -class SignalVectorModel : public QAbstractTableModel, pajlada::Signals::SignalHolder +class SignalVectorModel : public QAbstractTableModel, + pajlada::Signals::SignalHolder { public: SignalVectorModel(int columnCount, QObject *parent = nullptr) @@ -43,7 +44,8 @@ public: index = this->beforeInsert(args.item, row, index); this->beginInsertRows(QModelIndex(), index, index); - this->rows_.insert(this->rows_.begin() + index, Row(row, args.item)); + this->rows_.insert(this->rows_.begin() + index, + Row(row, args.item)); this->endInsertRows(); }; @@ -65,7 +67,8 @@ public: assert(row >= 0 && row <= this->rows_.size()); // remove row - std::vector items = std::move(this->rows_[row].items); + std::vector items = + std::move(this->rows_[row].items); this->beginRemoveRows(QModelIndex(), row, row); this->rows_.erase(this->rows_.begin() + row); @@ -103,15 +106,18 @@ public: QVariant data(const QModelIndex &index, int role) const override { int row = index.row(), column = index.column(); - assert(row >= 0 && row < this->rows_.size() && column >= 0 && column < this->columnCount_); + assert(row >= 0 && row < this->rows_.size() && column >= 0 && + column < this->columnCount_); return rows_[row].items[column]->data(role); } - bool setData(const QModelIndex &index, const QVariant &value, int role) override + bool setData(const QModelIndex &index, const QVariant &value, + int role) override { int row = index.row(), column = index.column(); - assert(row >= 0 && row < this->rows_.size() && column >= 0 && column < this->columnCount_); + assert(row >= 0 && row < this->rows_.size() && column >= 0 && + column < this->columnCount_); Row &rowItem = this->rows_[row]; @@ -124,15 +130,16 @@ public: this->vector_->removeItem(vecRow, this); assert(this->rows_[row].original); - TVectorItem item = - this->getItemFromRow(this->rows_[row].items, this->rows_[row].original.get()); + TVectorItem item = this->getItemFromRow( + this->rows_[row].items, this->rows_[row].original.get()); this->vector_->insertItem(item, vecRow, this); } return true; } - QVariant headerData(int section, Qt::Orientation orientation, int role) const override + QVariant headerData(int section, Qt::Orientation orientation, + int role) const override { if (orientation != Qt::Horizontal) { return QVariant(); @@ -146,7 +153,8 @@ public: } } - bool setHeaderData(int section, Qt::Orientation orientation, const QVariant &value, + bool setHeaderData(int section, Qt::Orientation orientation, + const QVariant &value, int role = Qt::DisplayRole) override { if (orientation != Qt::Horizontal) { @@ -162,14 +170,16 @@ public: Qt::ItemFlags flags(const QModelIndex &index) const override { int row = index.row(), column = index.column(); - assert(row >= 0 && row < this->rows_.size() && column >= 0 && column < this->columnCount_); + assert(row >= 0 && row < this->rows_.size() && column >= 0 && + column < this->columnCount_); return this->rows_[index.row()].items[index.column()]->flags(); } QStandardItem *getItem(int row, int column) { - assert(row >= 0 && row < this->rows_.size() && column >= 0 && column < this->columnCount_); + assert(row >= 0 && row < this->rows_.size() && column >= 0 && + column < this->columnCount_); return rows_[row].items[column]; } @@ -204,20 +214,23 @@ protected: const TVectorItem &original) = 0; // turns a row in the model into a vector item - virtual void getRowFromItem(const TVectorItem &item, std::vector &row) = 0; + virtual void getRowFromItem(const TVectorItem &item, + std::vector &row) = 0; - virtual int beforeInsert(const TVectorItem &item, std::vector &row, + virtual int beforeInsert(const TVectorItem &item, + std::vector &row, int proposedIndex) { return proposedIndex; } - virtual void afterRemoved(const TVectorItem &item, std::vector &row, int index) + virtual void afterRemoved(const TVectorItem &item, + std::vector &row, int index) { } - virtual void customRowSetData(const std::vector &row, int column, - const QVariant &value, int role) + virtual void customRowSetData(const std::vector &row, + int column, const QVariant &value, int role) { } @@ -226,7 +239,8 @@ protected: assert(index >= 0 && index <= this->rows_.size()); this->beginInsertRows(QModelIndex(), index, index); - this->rows_.insert(this->rows_.begin() + index, Row(std::move(row), true)); + this->rows_.insert(this->rows_.begin() + index, + Row(std::move(row), true)); this->endInsertRows(); } diff --git a/src/controllers/accounts/AccountController.cpp b/src/controllers/accounts/AccountController.cpp index 888c21152..6cd1f2558 100644 --- a/src/controllers/accounts/AccountController.cpp +++ b/src/controllers/accounts/AccountController.cpp @@ -7,7 +7,8 @@ namespace chatterino { AccountController::AccountController() { this->twitch.accounts.itemInserted.connect([this](const auto &args) { - this->accounts_.insertItem(std::dynamic_pointer_cast(args.item)); + this->accounts_.insertItem( + std::dynamic_pointer_cast(args.item)); }); this->twitch.accounts.itemRemoved.connect([this](const auto &args) { diff --git a/src/controllers/accounts/AccountController.hpp b/src/controllers/accounts/AccountController.hpp index 25f0fee5c..023ad9c9e 100644 --- a/src/controllers/accounts/AccountController.hpp +++ b/src/controllers/accounts/AccountController.hpp @@ -28,7 +28,8 @@ public: TwitchAccountManager twitch; private: - SortedSignalVector, SharedPtrElementLess> accounts_; + SortedSignalVector, SharedPtrElementLess> + accounts_; }; } // namespace chatterino diff --git a/src/controllers/accounts/AccountModel.cpp b/src/controllers/accounts/AccountModel.cpp index d18946468..d63f2c288 100644 --- a/src/controllers/accounts/AccountModel.cpp +++ b/src/controllers/accounts/AccountModel.cpp @@ -10,8 +10,8 @@ AccountModel::AccountModel(QObject *parent) } // turn a vector item into a model row -std::shared_ptr AccountModel::getItemFromRow(std::vector &, - const std::shared_ptr &original) +std::shared_ptr AccountModel::getItemFromRow( + std::vector &, const std::shared_ptr &original) { return original; } @@ -25,7 +25,8 @@ void AccountModel::getRowFromItem(const std::shared_ptr &item, } int AccountModel::beforeInsert(const std::shared_ptr &item, - std::vector &row, int proposedIndex) + std::vector &row, + int proposedIndex) { if (this->categoryCount_[item->getCategory()]++ == 0) { auto row = this->createRow(); diff --git a/src/controllers/accounts/AccountModel.hpp b/src/controllers/accounts/AccountModel.hpp index 0ac239a2a..c0b4538d5 100644 --- a/src/controllers/accounts/AccountModel.hpp +++ b/src/controllers/accounts/AccountModel.hpp @@ -18,17 +18,20 @@ public: protected: // turn a vector item into a model row virtual std::shared_ptr getItemFromRow( - std::vector &row, const std::shared_ptr &original) override; + std::vector &row, + const std::shared_ptr &original) override; // turns a row in the model into a vector item virtual void getRowFromItem(const std::shared_ptr &item, std::vector &row) override; virtual int beforeInsert(const std::shared_ptr &item, - std::vector &row, int proposedIndex) override; + std::vector &row, + int proposedIndex) override; virtual void afterRemoved(const std::shared_ptr &item, - std::vector &row, int index) override; + std::vector &row, + int index) override; friend class AccountController; diff --git a/src/controllers/commands/CommandController.cpp b/src/controllers/commands/CommandController.cpp index 1d85052e1..e3026c1be 100644 --- a/src/controllers/commands/CommandController.cpp +++ b/src/controllers/commands/CommandController.cpp @@ -18,12 +18,13 @@ #include #include -#define TWITCH_DEFAULT_COMMANDS \ - { \ - "/help", "/w", "/me", "/disconnect", "/mods", "/color", "/ban", "/unban", "/timeout", \ - "/untimeout", "/slow", "/slowoff", "/r9kbeta", "/r9kbetaoff", "/emoteonly", \ - "/emoteonlyoff", "/clear", "/subscribers", "/subscribersoff", "/followers", \ - "/followersoff" \ +#define TWITCH_DEFAULT_COMMANDS \ + { \ + "/help", "/w", "/me", "/disconnect", "/mods", "/color", "/ban", \ + "/unban", "/timeout", "/untimeout", "/slow", "/slowoff", \ + "/r9kbeta", "/r9kbetaoff", "/emoteonly", "/emoteonlyoff", \ + "/clear", "/subscribers", "/subscribersoff", "/followers", \ + "/followersoff" \ } namespace chatterino { @@ -77,7 +78,8 @@ void CommandController::save() { QFile textFile(this->filePath_); if (!textFile.open(QIODevice::WriteOnly)) { - Log("[CommandController::saveCommands] Unable to open {} for writing", this->filePath_); + Log("[CommandController::saveCommands] Unable to open {} for writing", + this->filePath_); return; } @@ -96,7 +98,8 @@ CommandModel *CommandController::createModel(QObject *parent) return model; } -QString CommandController::execCommand(const QString &text, ChannelPtr channel, bool dryRun) +QString CommandController::execCommand(const QString &text, ChannelPtr channel, + bool dryRun) { QStringList words = text.split(' ', QString::SkipEmptyParts); Command command; @@ -122,11 +125,13 @@ QString CommandController::execCommand(const QString &text, ChannelPtr channel, MessageBuilder b; b.emplace(); - b.emplace(app->accounts->twitch.getCurrent()->getUserName(), - MessageElement::Text, MessageColor::Text, - FontStyle::ChatMediumBold); + b.emplace( + app->accounts->twitch.getCurrent()->getUserName(), + MessageElement::Text, MessageColor::Text, + FontStyle::ChatMediumBold); b.emplace("->", MessageElement::Text); - b.emplace(words[1] + ":", MessageElement::Text, MessageColor::Text, + b.emplace(words[1] + ":", MessageElement::Text, + MessageColor::Text, FontStyle::ChatMediumBold); QString rest = ""; @@ -144,7 +149,9 @@ QString CommandController::execCommand(const QString &text, ChannelPtr channel, if (getSettings()->inlineWhispers) { app->twitch.server->forEachChannel( - [&b](ChannelPtr _channel) { _channel->addMessage(b.getMessage()); }); + [&b](ChannelPtr _channel) { + _channel->addMessage(b.getMessage()); + }); } return ""; @@ -165,15 +172,17 @@ QString CommandController::execCommand(const QString &text, ChannelPtr channel, } else if (commandName == "/uptime") { const auto &streamStatus = twitchChannel->accessStreamStatus(); - QString messageText = - streamStatus->live ? streamStatus->uptime : "Channel is not live."; + QString messageText = streamStatus->live + ? streamStatus->uptime + : "Channel is not live."; channel->addMessage(Message::createSystemMessage(messageText)); return ""; } else if (commandName == "/ignore") { if (words.size() < 2) { - channel->addMessage(Message::createSystemMessage("Usage: /ignore [user]")); + channel->addMessage( + Message::createSystemMessage("Usage: /ignore [user]")); return ""; } auto app = getApp(); @@ -182,19 +191,21 @@ QString CommandController::execCommand(const QString &text, ChannelPtr channel, auto target = words.at(1); if (user->isAnon()) { - channel->addMessage( - Message::createSystemMessage("You must be logged in to ignore someone")); + channel->addMessage(Message::createSystemMessage( + "You must be logged in to ignore someone")); return ""; } - user->ignore(target, [channel](auto resultCode, const QString &message) { + user->ignore(target, [channel](auto resultCode, + const QString &message) { channel->addMessage(Message::createSystemMessage(message)); }); return ""; } else if (commandName == "/unignore") { if (words.size() < 2) { - channel->addMessage(Message::createSystemMessage("Usage: /unignore [user]")); + channel->addMessage(Message::createSystemMessage( + "Usage: /unignore [user]")); return ""; } auto app = getApp(); @@ -203,19 +214,21 @@ QString CommandController::execCommand(const QString &text, ChannelPtr channel, auto target = words.at(1); if (user->isAnon()) { - channel->addMessage( - Message::createSystemMessage("You must be logged in to ignore someone")); + channel->addMessage(Message::createSystemMessage( + "You must be logged in to ignore someone")); return ""; } - user->unignore(target, [channel](auto resultCode, const QString &message) { + user->unignore(target, [channel](auto resultCode, + const QString &message) { channel->addMessage(Message::createSystemMessage(message)); }); return ""; } else if (commandName == "/follow") { if (words.size() < 2) { - channel->addMessage(Message::createSystemMessage("Usage: /follow [user]")); + channel->addMessage( + Message::createSystemMessage("Usage: /follow [user]")); return ""; } auto app = getApp(); @@ -224,27 +237,29 @@ QString CommandController::execCommand(const QString &text, ChannelPtr channel, auto target = words.at(1); if (user->isAnon()) { - channel->addMessage( - Message::createSystemMessage("You must be logged in to follow someone")); + channel->addMessage(Message::createSystemMessage( + "You must be logged in to follow someone")); return ""; } - TwitchApi::findUserId(target, [user, channel, target](QString userId) { - if (userId.isEmpty()) { - channel->addMessage(Message::createSystemMessage( - "User " + target + " could not be followed!")); - return; - } - user->followUser(userId, [channel, target]() { - channel->addMessage( - Message::createSystemMessage("You successfully followed " + target)); + TwitchApi::findUserId( + target, [user, channel, target](QString userId) { + if (userId.isEmpty()) { + channel->addMessage(Message::createSystemMessage( + "User " + target + " could not be followed!")); + return; + } + user->followUser(userId, [channel, target]() { + channel->addMessage(Message::createSystemMessage( + "You successfully followed " + target)); + }); }); - }); return ""; } else if (commandName == "/unfollow") { if (words.size() < 2) { - channel->addMessage(Message::createSystemMessage("Usage: /unfollow [user]")); + channel->addMessage(Message::createSystemMessage( + "Usage: /unfollow [user]")); return ""; } auto app = getApp(); @@ -253,28 +268,29 @@ QString CommandController::execCommand(const QString &text, ChannelPtr channel, auto target = words.at(1); if (user->isAnon()) { - channel->addMessage( - Message::createSystemMessage("You must be logged in to follow someone")); + channel->addMessage(Message::createSystemMessage( + "You must be logged in to follow someone")); return ""; } - TwitchApi::findUserId(target, [user, channel, target](QString userId) { - if (userId.isEmpty()) { - channel->addMessage(Message::createSystemMessage( - "User " + target + " could not be followed!")); - return; - } - user->unfollowUser(userId, [channel, target]() { - channel->addMessage( - Message::createSystemMessage("You successfully unfollowed " + target)); + TwitchApi::findUserId( + target, [user, channel, target](QString userId) { + if (userId.isEmpty()) { + channel->addMessage(Message::createSystemMessage( + "User " + target + " could not be followed!")); + return; + } + user->unfollowUser(userId, [channel, target]() { + channel->addMessage(Message::createSystemMessage( + "You successfully unfollowed " + target)); + }); }); - }); return ""; } else if (commandName == "/logs") { if (words.size() < 2) { - channel->addMessage( - Message::createSystemMessage("Usage: /logs [user] (channel)")); + channel->addMessage(Message::createSystemMessage( + "Usage: /logs [user] (channel)")); return ""; } auto app = getApp(); @@ -293,7 +309,8 @@ QString CommandController::execCommand(const QString &text, ChannelPtr channel, if (words.at(2).at(0) == "#") { channelName = words.at(2).mid(1); } - auto logsChannel = app->twitch.server->getChannelOrEmpty(channelName); + auto logsChannel = + app->twitch.server->getChannelOrEmpty(channelName); if (logsChannel == nullptr) { } else { logs->setInfo(logsChannel, target); @@ -319,7 +336,8 @@ QString CommandController::execCommand(const QString &text, ChannelPtr channel, return this->execCustomCommand(words, command); } -QString CommandController::execCustomCommand(const QStringList &words, const Command &command) +QString CommandController::execCustomCommand(const QStringList &words, + const Command &command) { QString result; @@ -331,13 +349,15 @@ QString CommandController::execCustomCommand(const QStringList &words, const Com int matchOffset = 0; while (true) { - QRegularExpressionMatch match = parseCommand.match(command.func, matchOffset); + QRegularExpressionMatch match = + parseCommand.match(command.func, matchOffset); if (!match.hasMatch()) { break; } - result += command.func.mid(lastCaptureEnd, match.capturedStart() - lastCaptureEnd + 1); + result += command.func.mid(lastCaptureEnd, + match.capturedStart() - lastCaptureEnd + 1); lastCaptureEnd = match.capturedEnd(); matchOffset = lastCaptureEnd - 1; diff --git a/src/controllers/commands/CommandController.hpp b/src/controllers/commands/CommandController.hpp index 45aba5bcc..f7b43b8f6 100644 --- a/src/controllers/commands/CommandController.hpp +++ b/src/controllers/commands/CommandController.hpp @@ -22,7 +22,8 @@ class CommandController final : public Singleton public: CommandController(); - QString execCommand(const QString &text, std::shared_ptr channel, bool dryRun); + QString execCommand(const QString &text, std::shared_ptr channel, + bool dryRun); QStringList getDefaultTwitchCommandList(); virtual void initialize(Settings &settings, Paths &paths) override; diff --git a/src/controllers/commands/CommandModel.cpp b/src/controllers/commands/CommandModel.cpp index 66e088533..e9c7cc529 100644 --- a/src/controllers/commands/CommandModel.cpp +++ b/src/controllers/commands/CommandModel.cpp @@ -9,18 +9,23 @@ CommandModel::CommandModel(QObject *parent) } // turn a vector item into a model row -Command CommandModel::getItemFromRow(std::vector &row, const Command &original) +Command CommandModel::getItemFromRow(std::vector &row, + const Command &original) { - return Command(row[0]->data(Qt::EditRole).toString(), row[1]->data(Qt::EditRole).toString()); + return Command(row[0]->data(Qt::EditRole).toString(), + row[1]->data(Qt::EditRole).toString()); } // turns a row in the model into a vector item -void CommandModel::getRowFromItem(const Command &item, std::vector &row) +void CommandModel::getRowFromItem(const Command &item, + std::vector &row) { row[0]->setData(item.name, Qt::DisplayRole); - row[0]->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsEditable); + row[0]->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable | + Qt::ItemIsEditable); row[1]->setData(item.func, Qt::DisplayRole); - row[1]->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsEditable); + row[1]->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable | + Qt::ItemIsEditable); } } // namespace chatterino diff --git a/src/controllers/commands/CommandModel.hpp b/src/controllers/commands/CommandModel.hpp index 434b8dfd9..648dcf73a 100644 --- a/src/controllers/commands/CommandModel.hpp +++ b/src/controllers/commands/CommandModel.hpp @@ -19,7 +19,8 @@ protected: const Command &command) override; // turns a row in the model into a vector item - virtual void getRowFromItem(const Command &item, std::vector &row) override; + virtual void getRowFromItem(const Command &item, + std::vector &row) override; friend class CommandController; }; diff --git a/src/controllers/highlights/HighlightBlacklistModel.hpp b/src/controllers/highlights/HighlightBlacklistModel.hpp index 494640833..d073425a5 100644 --- a/src/controllers/highlights/HighlightBlacklistModel.hpp +++ b/src/controllers/highlights/HighlightBlacklistModel.hpp @@ -15,8 +15,9 @@ class HighlightBlacklistModel : public SignalVectorModel protected: // turn a vector item into a model row - virtual HighlightBlacklistUser getItemFromRow(std::vector &row, - const HighlightBlacklistUser &original) override; + virtual HighlightBlacklistUser getItemFromRow( + std::vector &row, + const HighlightBlacklistUser &original) override; // turns a row in the model into a vector item virtual void getRowFromItem(const HighlightBlacklistUser &item, diff --git a/src/controllers/highlights/HighlightBlacklistUser.hpp b/src/controllers/highlights/HighlightBlacklistUser.hpp index 122a53e89..5376d9cf5 100644 --- a/src/controllers/highlights/HighlightBlacklistUser.hpp +++ b/src/controllers/highlights/HighlightBlacklistUser.hpp @@ -16,14 +16,16 @@ class HighlightBlacklistUser public: bool operator==(const HighlightBlacklistUser &other) const { - return std::tie(this->pattern_, this->isRegex_) == std::tie(other.pattern_, other.isRegex_); + return std::tie(this->pattern_, this->isRegex_) == + std::tie(other.pattern_, other.isRegex_); } HighlightBlacklistUser(const QString &pattern, bool isRegex = false) : pattern_(pattern) , isRegex_(isRegex) - , regex_(isRegex ? pattern : "", QRegularExpression::CaseInsensitiveOption | - QRegularExpression::UseUnicodePropertiesOption) + , regex_(isRegex ? pattern : "", + QRegularExpression::CaseInsensitiveOption | + QRegularExpression::UseUnicodePropertiesOption) { } diff --git a/src/controllers/highlights/HighlightController.cpp b/src/controllers/highlights/HighlightController.cpp index 4829e981b..bd78b65ac 100644 --- a/src/controllers/highlights/HighlightController.cpp +++ b/src/controllers/highlights/HighlightController.cpp @@ -25,12 +25,14 @@ void HighlightController::initialize(Settings &settings, Paths &paths) this->highlightsSetting_.setValue(this->phrases.getVector()); }); - for (const HighlightBlacklistUser &blacklistedUser : this->blacklistSetting_.getValue()) { + for (const HighlightBlacklistUser &blacklistedUser : + this->blacklistSetting_.getValue()) { this->blacklistedUsers.appendItem(blacklistedUser); } - this->blacklistedUsers.delayedItemsChanged.connect( - [this] { this->blacklistSetting_.setValue(this->blacklistedUsers.getVector()); }); + this->blacklistedUsers.delayedItemsChanged.connect([this] { + this->blacklistSetting_.setValue(this->blacklistedUsers.getVector()); + }); } HighlightModel *HighlightController::createModel(QObject *parent) @@ -61,7 +63,8 @@ bool HighlightController::isHighlightedUser(const QString &username) return false; } -HighlightBlacklistModel *HighlightController::createBlacklistModel(QObject *parent) +HighlightBlacklistModel *HighlightController::createBlacklistModel( + QObject *parent) { auto *model = new HighlightBlacklistModel(parent); model->init(&this->blacklistedUsers); @@ -71,7 +74,8 @@ HighlightBlacklistModel *HighlightController::createBlacklistModel(QObject *pare bool HighlightController::blacklistContains(const QString &username) { - std::vector blacklistItems = this->blacklistedUsers.getVector(); + std::vector blacklistItems = + this->blacklistedUsers.getVector(); for (const auto &blacklistedUser : blacklistItems) { if (blacklistedUser.isMatch(username)) { return true; diff --git a/src/controllers/highlights/HighlightModel.cpp b/src/controllers/highlights/HighlightModel.cpp index fcc36c3b3..cad2fd006 100644 --- a/src/controllers/highlights/HighlightModel.cpp +++ b/src/controllers/highlights/HighlightModel.cpp @@ -13,18 +13,20 @@ HighlightModel::HighlightModel(QObject *parent) } // turn a vector item into a model row -HighlightPhrase HighlightModel::getItemFromRow(std::vector &row, - const HighlightPhrase &original) +HighlightPhrase HighlightModel::getItemFromRow( + std::vector &row, const HighlightPhrase &original) { // key, alert, sound, regex - return HighlightPhrase{ - row[0]->data(Qt::DisplayRole).toString(), row[1]->data(Qt::CheckStateRole).toBool(), - row[2]->data(Qt::CheckStateRole).toBool(), row[3]->data(Qt::CheckStateRole).toBool()}; + return HighlightPhrase{row[0]->data(Qt::DisplayRole).toString(), + row[1]->data(Qt::CheckStateRole).toBool(), + row[2]->data(Qt::CheckStateRole).toBool(), + row[3]->data(Qt::CheckStateRole).toBool()}; } // turns a row in the model into a vector item -void HighlightModel::getRowFromItem(const HighlightPhrase &item, std::vector &row) +void HighlightModel::getRowFromItem(const HighlightPhrase &item, + std::vector &row) { setStringItem(row[0], item.getPattern()); setBoolItem(row[1], item.getAlert()); @@ -35,31 +37,38 @@ void HighlightModel::getRowFromItem(const HighlightPhrase &item, std::vector row = this->createRow(); - setBoolItem(row[0], getApp()->settings->enableHighlightsSelf.getValue(), true, false); + setBoolItem(row[0], getApp()->settings->enableHighlightsSelf.getValue(), + true, false); row[0]->setData("Your username (automatic)", Qt::DisplayRole); - setBoolItem(row[1], getApp()->settings->enableHighlightTaskbar.getValue(), true, false); - setBoolItem(row[2], getApp()->settings->enableHighlightSound.getValue(), true, false); + setBoolItem(row[1], getApp()->settings->enableHighlightTaskbar.getValue(), + true, false); + setBoolItem(row[2], getApp()->settings->enableHighlightSound.getValue(), + true, false); row[3]->setFlags(0); this->insertCustomRow(row, 0); } -void HighlightModel::customRowSetData(const std::vector &row, int column, - const QVariant &value, int role) +void HighlightModel::customRowSetData(const std::vector &row, + int column, const QVariant &value, + int role) { switch (column) { case 0: { if (role == Qt::CheckStateRole) { - getApp()->settings->enableHighlightsSelf.setValue(value.toBool()); + getApp()->settings->enableHighlightsSelf.setValue( + value.toBool()); } } break; case 1: { if (role == Qt::CheckStateRole) { - getApp()->settings->enableHighlightTaskbar.setValue(value.toBool()); + getApp()->settings->enableHighlightTaskbar.setValue( + value.toBool()); } } break; case 2: { if (role == Qt::CheckStateRole) { - getApp()->settings->enableHighlightSound.setValue(value.toBool()); + getApp()->settings->enableHighlightSound.setValue( + value.toBool()); } } break; case 3: { diff --git a/src/controllers/highlights/HighlightModel.hpp b/src/controllers/highlights/HighlightModel.hpp index 7f50287ed..b42246167 100644 --- a/src/controllers/highlights/HighlightModel.hpp +++ b/src/controllers/highlights/HighlightModel.hpp @@ -15,8 +15,9 @@ class HighlightModel : public SignalVectorModel protected: // turn a vector item into a model row - virtual HighlightPhrase getItemFromRow(std::vector &row, - const HighlightPhrase &original) override; + virtual HighlightPhrase getItemFromRow( + std::vector &row, + const HighlightPhrase &original) override; // turns a row in the model into a vector item virtual void getRowFromItem(const HighlightPhrase &item, @@ -24,8 +25,9 @@ protected: virtual void afterInit() override; - virtual void customRowSetData(const std::vector &row, int column, - const QVariant &value, int role) override; + virtual void customRowSetData(const std::vector &row, + int column, const QVariant &value, + int role) override; friend class HighlightController; }; diff --git a/src/controllers/highlights/HighlightPhrase.hpp b/src/controllers/highlights/HighlightPhrase.hpp index fe4ed5cc2..77cd5936b 100644 --- a/src/controllers/highlights/HighlightPhrase.hpp +++ b/src/controllers/highlights/HighlightPhrase.hpp @@ -14,16 +14,20 @@ class HighlightPhrase public: bool operator==(const HighlightPhrase &other) const { - return std::tie(this->pattern_, this->sound_, this->alert_, this->isRegex_) == - std::tie(other.pattern_, other.sound_, other.alert_, other.isRegex_); + return std::tie(this->pattern_, this->sound_, this->alert_, + this->isRegex_) == std::tie(other.pattern_, + other.sound_, other.alert_, + other.isRegex_); } - HighlightPhrase(const QString &pattern, bool alert, bool sound, bool isRegex) + HighlightPhrase(const QString &pattern, bool alert, bool sound, + bool isRegex) : pattern_(pattern) , alert_(alert) , sound_(sound) , isRegex_(isRegex) - , regex_(isRegex_ ? pattern : "\\b" + QRegularExpression::escape(pattern) + "\\b", + , regex_(isRegex_ ? pattern + : "\\b" + QRegularExpression::escape(pattern) + "\\b", QRegularExpression::CaseInsensitiveOption | QRegularExpression::UseUnicodePropertiesOption) { diff --git a/src/controllers/highlights/UserHighlightModel.cpp b/src/controllers/highlights/UserHighlightModel.cpp index 92b862d60..e04c3403e 100644 --- a/src/controllers/highlights/UserHighlightModel.cpp +++ b/src/controllers/highlights/UserHighlightModel.cpp @@ -13,14 +13,15 @@ UserHighlightModel::UserHighlightModel(QObject *parent) } // turn vector item into model row -HighlightPhrase UserHighlightModel::getItemFromRow(std::vector &row, - const HighlightPhrase &original) +HighlightPhrase UserHighlightModel::getItemFromRow( + std::vector &row, const HighlightPhrase &original) { // key, regex - return HighlightPhrase{ - row[0]->data(Qt::DisplayRole).toString(), row[1]->data(Qt::CheckStateRole).toBool(), - row[2]->data(Qt::CheckStateRole).toBool(), row[3]->data(Qt::CheckStateRole).toBool()}; + return HighlightPhrase{row[0]->data(Qt::DisplayRole).toString(), + row[1]->data(Qt::CheckStateRole).toBool(), + row[2]->data(Qt::CheckStateRole).toBool(), + row[3]->data(Qt::CheckStateRole).toBool()}; } // row into vector item diff --git a/src/controllers/highlights/UserHighlightModel.hpp b/src/controllers/highlights/UserHighlightModel.hpp index b6a4023be..dcc42a950 100644 --- a/src/controllers/highlights/UserHighlightModel.hpp +++ b/src/controllers/highlights/UserHighlightModel.hpp @@ -15,8 +15,9 @@ class UserHighlightModel : public SignalVectorModel protected: // vector into model row - virtual HighlightPhrase getItemFromRow(std::vector &row, - const HighlightPhrase &original) override; + virtual HighlightPhrase getItemFromRow( + std::vector &row, + const HighlightPhrase &original) override; virtual void getRowFromItem(const HighlightPhrase &item, std::vector &row) override; diff --git a/src/controllers/ignores/IgnoreController.hpp b/src/controllers/ignores/IgnoreController.hpp index 09c109186..e7a0472e6 100644 --- a/src/controllers/ignores/IgnoreController.hpp +++ b/src/controllers/ignores/IgnoreController.hpp @@ -25,7 +25,8 @@ public: private: bool initialized_ = false; - ChatterinoSetting> ignoresSetting_ = {"/ignore/phrases"}; + ChatterinoSetting> ignoresSetting_ = { + "/ignore/phrases"}; }; } // namespace chatterino diff --git a/src/controllers/ignores/IgnoreModel.cpp b/src/controllers/ignores/IgnoreModel.cpp index 869d2ec4f..84a034525 100644 --- a/src/controllers/ignores/IgnoreModel.cpp +++ b/src/controllers/ignores/IgnoreModel.cpp @@ -23,7 +23,8 @@ IgnorePhrase IgnoreModel::getItemFromRow(std::vector &row, } // turns a row in the model into a vector item -void IgnoreModel::getRowFromItem(const IgnorePhrase &item, std::vector &row) +void IgnoreModel::getRowFromItem(const IgnorePhrase &item, + std::vector &row) { setStringItem(row[0], item.getPattern()); setBoolItem(row[1], item.isRegex()); diff --git a/src/controllers/ignores/IgnorePhrase.hpp b/src/controllers/ignores/IgnorePhrase.hpp index d02bc1902..f42df8442 100644 --- a/src/controllers/ignores/IgnorePhrase.hpp +++ b/src/controllers/ignores/IgnorePhrase.hpp @@ -16,13 +16,15 @@ class IgnorePhrase public: bool operator==(const IgnorePhrase &other) const { - return std::tie(this->pattern_, this->isRegex_) == std::tie(other.pattern_, other.isRegex_); + return std::tie(this->pattern_, this->isRegex_) == + std::tie(other.pattern_, other.isRegex_); } IgnorePhrase(const QString &pattern, bool isRegex) : pattern_(pattern) , isRegex_(isRegex) - , regex_(isRegex_ ? pattern : "\\b" + QRegularExpression::escape(pattern) + "\\b", + , regex_(isRegex_ ? pattern + : "\\b" + QRegularExpression::escape(pattern) + "\\b", QRegularExpression::CaseInsensitiveOption | QRegularExpression::UseUnicodePropertiesOption) { diff --git a/src/controllers/moderationactions/ModerationAction.cpp b/src/controllers/moderationactions/ModerationAction.cpp index d3f07b172..90abe815d 100644 --- a/src/controllers/moderationactions/ModerationAction.cpp +++ b/src/controllers/moderationactions/ModerationAction.cpp @@ -13,7 +13,8 @@ namespace chatterino { //{ //} -// ModerationAction::ModerationAction(const QString &_line1, const QString &_line2, +// ModerationAction::ModerationAction(const QString &_line1, const QString +// &_line2, // const QString &_action) // : _isImage(false) // , image(nullptr) @@ -55,10 +56,12 @@ ModerationAction::ModerationAction(const QString &action) // line1 = this->line1_; // line2 = this->line2_; // } else { - // this->_moderationActions.emplace_back(app->resources->buttonTimeout, str); + // this->_moderationActions.emplace_back(app->resources->buttonTimeout, + // str); // } } else if (action.startsWith("/ban ")) { - this->image_ = Image::fromNonOwningPixmap(&getApp()->resources->buttons.ban); + this->image_ = + Image::fromNonOwningPixmap(&getApp()->resources->buttons.ban); } else { QString xD = action; diff --git a/src/controllers/moderationactions/ModerationActionModel.cpp b/src/controllers/moderationactions/ModerationActionModel.cpp index aa0fe134c..39f093713 100644 --- a/src/controllers/moderationactions/ModerationActionModel.cpp +++ b/src/controllers/moderationactions/ModerationActionModel.cpp @@ -11,8 +11,8 @@ ModerationActionModel ::ModerationActionModel(QObject *parent) } // turn a vector item into a model row -ModerationAction ModerationActionModel::getItemFromRow(std::vector &row, - const ModerationAction &original) +ModerationAction ModerationActionModel::getItemFromRow( + std::vector &row, const ModerationAction &original) { return ModerationAction(row[0]->data(Qt::DisplayRole).toString()); } diff --git a/src/controllers/moderationactions/ModerationActionModel.hpp b/src/controllers/moderationactions/ModerationActionModel.hpp index 3c8a11675..3610561a9 100644 --- a/src/controllers/moderationactions/ModerationActionModel.hpp +++ b/src/controllers/moderationactions/ModerationActionModel.hpp @@ -16,8 +16,9 @@ public: protected: // turn a vector item into a model row - virtual ModerationAction getItemFromRow(std::vector &row, - const ModerationAction &original) override; + virtual ModerationAction getItemFromRow( + std::vector &row, + const ModerationAction &original) override; // turns a row in the model into a vector item virtual void getRowFromItem(const ModerationAction &item, diff --git a/src/controllers/moderationactions/ModerationActions.hpp b/src/controllers/moderationactions/ModerationActions.hpp index 6ecc3281d..d5e510f1c 100644 --- a/src/controllers/moderationactions/ModerationActions.hpp +++ b/src/controllers/moderationactions/ModerationActions.hpp @@ -25,7 +25,8 @@ public: ModerationActionModel *createModel(QObject *parent); private: - ChatterinoSetting> setting_ = {"/moderation/actions"}; + ChatterinoSetting> setting_ = { + "/moderation/actions"}; bool initialized_ = false; }; diff --git a/src/controllers/taggedusers/TaggedUser.cpp b/src/controllers/taggedusers/TaggedUser.cpp index 9694c4fe0..def7de600 100644 --- a/src/controllers/taggedusers/TaggedUser.cpp +++ b/src/controllers/taggedusers/TaggedUser.cpp @@ -4,7 +4,8 @@ namespace chatterino { -TaggedUser::TaggedUser(ProviderId provider, const QString &name, const QString &id) +TaggedUser::TaggedUser(ProviderId provider, const QString &name, + const QString &id) : providerId_(provider) , name_(name) , id_(id) diff --git a/src/controllers/taggedusers/TaggedUsersModel.cpp b/src/controllers/taggedusers/TaggedUsersModel.cpp index b3ef872f9..e3225888c 100644 --- a/src/controllers/taggedusers/TaggedUsersModel.cpp +++ b/src/controllers/taggedusers/TaggedUsersModel.cpp @@ -19,7 +19,8 @@ TaggedUser TaggedUsersModel::getItemFromRow(std::vector &row, } // turns a row in the model into a vector item -void TaggedUsersModel::getRowFromItem(const TaggedUser &item, std::vector &row) +void TaggedUsersModel::getRowFromItem(const TaggedUser &item, + std::vector &row) { setStringItem(row[0], item.getName()); } @@ -27,14 +28,18 @@ void TaggedUsersModel::getRowFromItem(const TaggedUser &item, std::vector row = this->createRow(); - // setBoolItem(row[0], getApp()->settings->enableHighlightsSelf.getValue(), true, - // false); row[0]->setData("Your username (automatic)", Qt::DisplayRole); - // setBoolItem(row[1], getApp()->settings->enableHighlightTaskbar.getValue(), true, - // false); setBoolItem(row[2], getApp()->settings->enableHighlightSound.getValue(), - // true, false); row[3]->setFlags(0); this->insertCustomRow(row, 0); + // setBoolItem(row[0], + // getApp()->settings->enableHighlightsSelf.getValue(), true, false); + // row[0]->setData("Your username (automatic)", Qt::DisplayRole); + // setBoolItem(row[1], + // getApp()->settings->enableHighlightTaskbar.getValue(), true, false); + // setBoolItem(row[2], + // getApp()->settings->enableHighlightSound.getValue(), true, false); + // row[3]->setFlags(0); this->insertCustomRow(row, 0); } -// void TaggedUserModel::customRowSetData(const std::vector &row, int column, +// void TaggedUserModel::customRowSetData(const std::vector +// &row, int column, // const QVariant &value, int role) //{ // switch (column) { diff --git a/src/controllers/taggedusers/TaggedUsersModel.hpp b/src/controllers/taggedusers/TaggedUsersModel.hpp index 44b566e5b..28c89493c 100644 --- a/src/controllers/taggedusers/TaggedUsersModel.hpp +++ b/src/controllers/taggedusers/TaggedUsersModel.hpp @@ -17,12 +17,15 @@ protected: const TaggedUser &original) override; // turns a row in the model into a vector item - virtual void getRowFromItem(const TaggedUser &item, std::vector &row) override; + virtual void getRowFromItem(const TaggedUser &item, + std::vector &row) override; virtual void afterInit() override; - // virtual void customRowSetData(const std::vector &row, int column, - // const QVariant &value, int role) override; + // virtual void customRowSetData(const std::vector &row, + // int column, + // const QVariant &value, int role) + // override; friend class TaggedUsersController; }; diff --git a/src/debug/Benchmark.hpp b/src/debug/Benchmark.hpp index c648382ea..5eeb6cb36 100644 --- a/src/debug/Benchmark.hpp +++ b/src/debug/Benchmark.hpp @@ -29,7 +29,8 @@ public: ~BenchmarkGuard() { - qDebug() << this->name << float(timer.nsecsElapsed()) / 1000000.0f << "ms"; + qDebug() << this->name << float(timer.nsecsElapsed()) / 1000000.0f + << "ms"; } qreal getElapsedMs() diff --git a/src/main.cpp b/src/main.cpp index 4ebb846a3..04a7b934e 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -12,9 +12,10 @@ int main(int argc, char **argv) { QApplication a(argc, argv); - // convert char[][] to QStringList + // convert char** to QStringList auto args = QStringList(); - std::transform(argv + 1, argv + argc, std::back_inserter(args), [&](auto s) { return s; }); + std::transform(argv + 1, argv + argc, std::back_inserter(args), + [&](auto s) { return s; }); // run in gui mode or browser extension host mode if (shouldRunBrowserExtensionHost(args)) { diff --git a/src/messages/Image.cpp b/src/messages/Image.cpp index 44c855dd7..e8df96f57 100644 --- a/src/messages/Image.cpp +++ b/src/messages/Image.cpp @@ -85,7 +85,8 @@ std::vector readFrames(QImageReader &reader, const Url &url) std::vector frames; if (reader.imageCount() <= 0) { - Log("Error while reading image {}: '{}'", url.string, reader.errorString()); + Log("Error while reading image {}: '{}'", url.string, + reader.errorString()); return frames; } @@ -100,7 +101,8 @@ std::vector readFrames(QImageReader &reader, const Url &url) } if (frames.size() != 0) { - Log("Error while reading image {}: '{}'", url.string, reader.errorString()); + Log("Error while reading image {}: '{}'", url.string, + reader.errorString()); } return frames; diff --git a/src/messages/Image.hpp b/src/messages/Image.hpp index 01ccd68eb..50af47f4e 100644 --- a/src/messages/Image.hpp +++ b/src/messages/Image.hpp @@ -47,7 +47,8 @@ class Image : public std::enable_shared_from_this, boost::noncopyable { public: static ImagePtr fromUrl(const Url &url, qreal scale = 1); - static ImagePtr fromOwningPixmap(std::unique_ptr pixmap, qreal scale = 1); + static ImagePtr fromOwningPixmap(std::unique_ptr pixmap, + qreal scale = 1); static ImagePtr fromNonOwningPixmap(QPixmap *pixmap, qreal scale = 1); static ImagePtr getEmpty(); diff --git a/src/messages/ImageSet.cpp b/src/messages/ImageSet.cpp index ebb9b77c7..af3c5e6bd 100644 --- a/src/messages/ImageSet.cpp +++ b/src/messages/ImageSet.cpp @@ -13,7 +13,8 @@ ImageSet::ImageSet() { } -ImageSet::ImageSet(const ImagePtr &image1, const ImagePtr &image2, const ImagePtr &image3) +ImageSet::ImageSet(const ImagePtr &image1, const ImagePtr &image2, + const ImagePtr &image3) : imageX1_(image1) , imageX2_(image2) , imageX3_(image3) diff --git a/src/messages/LimitedQueue.hpp b/src/messages/LimitedQueue.hpp index 4870c6809..5165efa94 100644 --- a/src/messages/LimitedQueue.hpp +++ b/src/messages/LimitedQueue.hpp @@ -16,7 +16,8 @@ namespace chatterino { // // Explanation: // - messages can be appended until 'limit' is reached -// - when the limit is reached for every message added one will be removed at the start +// - when the limit is reached for every message added one will be removed at +// the start // - messages can only be added to the start when there is space for them, // trying to add messages to the start when it's full will not add them // - you are able to get a "Snapshot" which captures the state of this object @@ -41,7 +42,8 @@ public: { std::lock_guard lock(this->mutex_); - this->chunks_ = std::make_shared>>>(); + this->chunks_ = + std::make_shared>>>(); Chunk chunk = std::make_shared>(); chunk->resize(this->chunkSize_); this->chunks_->push_back(chunk); @@ -60,8 +62,8 @@ public: // still space in the last chunk if (lastChunk->size() <= this->lastChunkEnd_) { // create new chunk vector - ChunkVector newVector = - std::make_shared>>>(); + ChunkVector newVector = std::make_shared< + std::vector>>>(); // copy chunks for (Chunk &chunk : *this->chunks_) { @@ -93,8 +95,8 @@ public: std::lock_guard lock(this->mutex_); // create new vector to clone chunks into - ChunkVector newChunks = - std::make_shared>>>(); + ChunkVector newChunks = std::make_shared< + std::vector>>>(); newChunks->resize(this->chunks_->size()); @@ -142,7 +144,8 @@ public: Chunk &chunk = this->chunks_->at(i); size_t start = i == 0 ? this->firstChunkOffset_ : 0; - size_t end = i == chunk->size() - 1 ? this->lastChunkEnd_ : chunk->size(); + size_t end = + i == chunk->size() - 1 ? this->lastChunkEnd_ : chunk->size(); for (size_t j = start; j < end; j++) { if (chunk->at(j) == item) { @@ -176,7 +179,8 @@ public: Chunk &chunk = this->chunks_->at(i); size_t start = i == 0 ? this->firstChunkOffset_ : 0; - size_t end = i == chunk->size() - 1 ? this->lastChunkEnd_ : chunk->size(); + size_t end = + i == chunk->size() - 1 ? this->lastChunkEnd_ : chunk->size(); for (size_t j = start; j < end; j++) { if (x == index) { @@ -204,8 +208,9 @@ public: { std::lock_guard lock(this->mutex_); - return LimitedQueueSnapshot(this->chunks_, this->limit_ - this->space(), - this->firstChunkOffset_, this->lastChunkEnd_); + return LimitedQueueSnapshot( + this->chunks_, this->limit_ - this->space(), + this->firstChunkOffset_, this->lastChunkEnd_); } private: @@ -238,8 +243,8 @@ private: // need to delete the first chunk if (this->firstChunkOffset_ == this->chunks_->front()->size() - 1) { // copy the chunk vector - ChunkVector newVector = - std::make_shared>>>(); + ChunkVector newVector = std::make_shared< + std::vector>>>(); // delete first chunk bool first = true; diff --git a/src/messages/LimitedQueueSnapshot.hpp b/src/messages/LimitedQueueSnapshot.hpp index cd735445e..ce78dad94 100644 --- a/src/messages/LimitedQueueSnapshot.hpp +++ b/src/messages/LimitedQueueSnapshot.hpp @@ -12,8 +12,9 @@ class LimitedQueueSnapshot public: LimitedQueueSnapshot() = default; - LimitedQueueSnapshot(std::shared_ptr>>> chunks, - size_t length, size_t firstChunkOffset, size_t lastChunkEnd) + LimitedQueueSnapshot( + std::shared_ptr>>> chunks, + size_t length, size_t firstChunkOffset, size_t lastChunkEnd) : chunks_(chunks) , length_(length) , firstChunkOffset_(firstChunkOffset) diff --git a/src/messages/Message.cpp b/src/messages/Message.cpp index 2af8b8dcb..2104dd673 100644 --- a/src/messages/Message.cpp +++ b/src/messages/Message.cpp @@ -33,7 +33,8 @@ MessagePtr Message::createSystemMessage(const QString &text) MessagePtr message(new Message); message->addElement(new TimestampElement(QTime::currentTime())); - message->addElement(new TextElement(text, MessageElement::Text, MessageColor::System)); + message->addElement( + new TextElement(text, MessageElement::Text, MessageColor::System)); message->flags |= MessageFlags::System; message->flags |= MessageFlags::DoNotTriggerNotification; message->searchText = text; @@ -46,7 +47,8 @@ MessagePtr Message::createMessage(const QString &text) MessagePtr message(new Message); message->addElement(new TimestampElement(QTime::currentTime())); - message->addElement(new TextElement(text, MessageElement::Text, MessageColor::Text)); + message->addElement( + new TextElement(text, MessageElement::Text, MessageColor::Text)); message->searchText = text; return message; @@ -96,8 +98,10 @@ QString makeDuration(int timeoutSeconds) } // namespace -MessagePtr Message::createTimeoutMessage(const QString &username, const QString &durationInSeconds, - const QString &reason, bool multipleTimes) +MessagePtr Message::createTimeoutMessage(const QString &username, + const QString &durationInSeconds, + const QString &reason, + bool multipleTimes) { QString text; @@ -135,7 +139,8 @@ MessagePtr Message::createTimeoutMessage(const QString &username, const QString return message; } -MessagePtr Message::createTimeoutMessage(const BanAction &action, uint32_t count) +MessagePtr Message::createTimeoutMessage(const BanAction &action, + uint32_t count) { MessagePtr msg(new Message); @@ -178,7 +183,8 @@ MessagePtr Message::createTimeoutMessage(const BanAction &action, uint32_t count } } - msg->addElement(new TextElement(text, MessageElement::Text, MessageColor::System)); + msg->addElement( + new TextElement(text, MessageElement::Text, MessageColor::System)); msg->searchText = text; return msg; @@ -206,7 +212,8 @@ MessagePtr Message::createUntimeoutMessage(const UnbanAction &action) .arg(action.target.name); } - msg->addElement(new TextElement(text, MessageElement::Text, MessageColor::System)); + msg->addElement( + new TextElement(text, MessageElement::Text, MessageColor::System)); msg->searchText = text; return msg; diff --git a/src/messages/Message.hpp b/src/messages/Message.hpp index 102a8d32f..5a2a21074 100644 --- a/src/messages/Message.hpp +++ b/src/messages/Message.hpp @@ -68,13 +68,14 @@ public: static std::shared_ptr createSystemMessage(const QString &text); static std::shared_ptr createMessage(const QString &text); - static std::shared_ptr createTimeoutMessage(const QString &username, - const QString &durationInSeconds, - const QString &reason, bool multipleTimes); + static std::shared_ptr createTimeoutMessage( + const QString &username, const QString &durationInSeconds, + const QString &reason, bool multipleTimes); - static std::shared_ptr createTimeoutMessage(const BanAction &action, - uint32_t count = 1); - static std::shared_ptr createUntimeoutMessage(const UnbanAction &action); + static std::shared_ptr createTimeoutMessage( + const BanAction &action, uint32_t count = 1); + static std::shared_ptr createUntimeoutMessage( + const UnbanAction &action); }; using MessagePtr = std::shared_ptr; diff --git a/src/messages/MessageBuilder.cpp b/src/messages/MessageBuilder.cpp index 01a6ea629..0da3a8445 100644 --- a/src/messages/MessageBuilder.cpp +++ b/src/messages/MessageBuilder.cpp @@ -47,9 +47,12 @@ QString MessageBuilder::matchLink(const QString &string) { LinkParser linkParser(string); - static QRegularExpression httpRegex("\\bhttps?://", QRegularExpression::CaseInsensitiveOption); - static QRegularExpression ftpRegex("\\bftps?://", QRegularExpression::CaseInsensitiveOption); - static QRegularExpression spotifyRegex("\\bspotify:", QRegularExpression::CaseInsensitiveOption); + static QRegularExpression httpRegex( + "\\bhttps?://", QRegularExpression::CaseInsensitiveOption); + static QRegularExpression ftpRegex( + "\\bftps?://", QRegularExpression::CaseInsensitiveOption); + static QRegularExpression spotifyRegex( + "\\bspotify:", QRegularExpression::CaseInsensitiveOption); if (!linkParser.hasMatch()) { return QString(); @@ -57,7 +60,8 @@ QString MessageBuilder::matchLink(const QString &string) QString captured = linkParser.getCaptured(); - if (!captured.contains(httpRegex) && !captured.contains(ftpRegex) && !captured.contains(spotifyRegex)) { + if (!captured.contains(httpRegex) && !captured.contains(ftpRegex) && + !captured.contains(spotifyRegex)) { captured.insert(0, "http://"); } diff --git a/src/messages/MessageBuilder.hpp b/src/messages/MessageBuilder.hpp index d2a617ec3..6951f7255 100644 --- a/src/messages/MessageBuilder.hpp +++ b/src/messages/MessageBuilder.hpp @@ -23,7 +23,8 @@ public: template T *emplace(Args &&... args) { - static_assert(std::is_base_of::value, "T must extend MessageElement"); + static_assert(std::is_base_of::value, + "T must extend MessageElement"); T *element = new T(std::forward(args)...); this->append(element); diff --git a/src/messages/MessageElement.cpp b/src/messages/MessageElement.cpp index ff62aca4e..c2bff2f0d 100644 --- a/src/messages/MessageElement.cpp +++ b/src/messages/MessageElement.cpp @@ -67,14 +67,15 @@ ImageElement::ImageElement(ImagePtr image, MessageElement::Flags flags) // this->setTooltip(image->getTooltip()); } -void ImageElement::addToContainer(MessageLayoutContainer &container, MessageElement::Flags flags) +void ImageElement::addToContainer(MessageLayoutContainer &container, + MessageElement::Flags flags) { if (flags & this->getFlags()) { auto size = QSize(this->image_->width() * container.getScale(), this->image_->height() * container.getScale()); - container.addElement( - (new ImageLayoutElement(*this, this->image_, size))->setLink(this->getLink())); + container.addElement((new ImageLayoutElement(*this, this->image_, size)) + ->setLink(this->getLink())); } } @@ -83,7 +84,8 @@ EmoteElement::EmoteElement(const EmotePtr &emote, MessageElement::Flags flags) : MessageElement(flags) , emote_(emote) { - this->textElement_.reset(new TextElement(emote->getCopyString(), MessageElement::Misc)); + this->textElement_.reset( + new TextElement(emote->getCopyString(), MessageElement::Misc)); this->setTooltip(emote->tooltip.string); } @@ -93,7 +95,8 @@ EmotePtr EmoteElement::getEmote() const return this->emote_; } -void EmoteElement::addToContainer(MessageLayoutContainer &container, MessageElement::Flags flags) +void EmoteElement::addToContainer(MessageLayoutContainer &container, + MessageElement::Flags flags) { if (flags & this->getFlags()) { if (flags & MessageElement::EmoteImages) { @@ -103,11 +106,12 @@ void EmoteElement::addToContainer(MessageLayoutContainer &container, MessageElem auto size = QSize(int(container.getScale() * image->width()), int(container.getScale() * image->height())); - container.addElement( - (new ImageLayoutElement(*this, image, size))->setLink(this->getLink())); + container.addElement((new ImageLayoutElement(*this, image, size)) + ->setLink(this->getLink())); } else { if (this->textElement_) { - this->textElement_->addToContainer(container, MessageElement::Misc); + this->textElement_->addToContainer(container, + MessageElement::Misc); } } } @@ -126,20 +130,24 @@ TextElement::TextElement(const QString &text, MessageElement::Flags flags, } } -void TextElement::addToContainer(MessageLayoutContainer &container, MessageElement::Flags flags) +void TextElement::addToContainer(MessageLayoutContainer &container, + MessageElement::Flags flags) { auto app = getApp(); if (flags & this->getFlags()) { - QFontMetrics metrics = app->fonts->getFontMetrics(this->style_, container.getScale()); + QFontMetrics metrics = + app->fonts->getFontMetrics(this->style_, container.getScale()); for (Word &word : this->words_) { - auto getTextLayoutElement = [&](QString text, int width, bool trailingSpace) { + auto getTextLayoutElement = [&](QString text, int width, + bool trailingSpace) { QColor color = this->color_.getColor(*app->themes); app->themes->normalizeColor(color); - auto e = (new TextLayoutElement(*this, text, QSize(width, metrics.height()), color, - this->style_, container.getScale())) + auto e = (new TextLayoutElement( + *this, text, QSize(width, metrics.height()), + color, this->style_, container.getScale())) ->setLink(this->getLink()); e->setTrailingSpace(trailingSpace); return e; @@ -152,8 +160,8 @@ void TextElement::addToContainer(MessageLayoutContainer &container, MessageEleme // see if the text fits in the current line if (container.fitsInLine(word.width)) { - container.addElementNoLineBreak( - getTextLayoutElement(word.text, word.width, this->hasTrailingSpace())); + container.addElementNoLineBreak(getTextLayoutElement( + word.text, word.width, this->hasTrailingSpace())); continue; } @@ -162,8 +170,8 @@ void TextElement::addToContainer(MessageLayoutContainer &container, MessageEleme container.breakLine(); if (container.fitsInLine(word.width)) { - container.addElementNoLineBreak( - getTextLayoutElement(word.text, word.width, this->hasTrailingSpace())); + container.addElementNoLineBreak(getTextLayoutElement( + word.text, word.width, this->hasTrailingSpace())); continue; } } @@ -178,8 +186,8 @@ void TextElement::addToContainer(MessageLayoutContainer &container, MessageEleme int charWidth = metrics.width(text[i]); if (!container.fitsInLine(width + charWidth)) { - container.addElementNoLineBreak( - getTextLayoutElement(text.mid(wordStart, i - wordStart), width, false)); + container.addElementNoLineBreak(getTextLayoutElement( + text.mid(wordStart, i - wordStart), width, false)); container.breakLine(); wordStart = i; @@ -194,8 +202,8 @@ void TextElement::addToContainer(MessageLayoutContainer &container, MessageEleme width += charWidth; } - container.addElement( - getTextLayoutElement(text.mid(wordStart), width, this->hasTrailingSpace())); + container.addElement(getTextLayoutElement( + text.mid(wordStart), width, this->hasTrailingSpace())); container.breakLine(); } } @@ -230,7 +238,8 @@ TextElement *TimestampElement::formatTime(const QTime &time) QString format = locale.toString(time, getApp()->settings->timestampFormat); - return new TextElement(format, Flags::Timestamp, MessageColor::System, FontStyle::ChatMedium); + return new TextElement(format, Flags::Timestamp, MessageColor::System, + FontStyle::ChatMedium); } // TWITCH MODERATION @@ -243,15 +252,19 @@ void TwitchModerationElement::addToContainer(MessageLayoutContainer &container, MessageElement::Flags flags) { if (flags & MessageElement::ModeratorTools) { - QSize size(int(container.getScale() * 16), int(container.getScale() * 16)); + QSize size(int(container.getScale() * 16), + int(container.getScale() * 16)); - for (const auto &action : getApp()->moderationActions->items.getVector()) { + for (const auto &action : + getApp()->moderationActions->items.getVector()) { if (auto image = action.getImage()) { - container.addElement((new ImageLayoutElement(*this, image.get(), size)) - ->setLink(Link(Link::UserAction, action.getAction()))); + container.addElement( + (new ImageLayoutElement(*this, image.get(), size)) + ->setLink(Link(Link::UserAction, action.getAction()))); } else { container.addElement( - (new TextIconLayoutElement(*this, action.getLine1(), action.getLine2(), + (new TextIconLayoutElement(*this, action.getLine1(), + action.getLine2(), container.getScale(), size)) ->setLink(Link(Link::UserAction, action.getAction()))); } diff --git a/src/messages/MessageElement.hpp b/src/messages/MessageElement.hpp index 2aa25b7e7..cb7ffeebd 100644 --- a/src/messages/MessageElement.hpp +++ b/src/messages/MessageElement.hpp @@ -72,10 +72,11 @@ public: // - Chatterino top donator badge BadgeChatterino = (1 << 18), - // Rest of slots: ffz custom badge? bttv custom badge? mywaifu (puke) custom badge? + // Rest of slots: ffz custom badge? bttv custom badge? mywaifu (puke) + // custom badge? - Badges = BadgeGlobalAuthority | BadgeChannelAuthority | BadgeSubscription | BadgeVanity | - BadgeChatterino, + Badges = BadgeGlobalAuthority | BadgeChannelAuthority | + BadgeSubscription | BadgeVanity | BadgeChatterino, ChannelName = (1 << 19), @@ -89,7 +90,8 @@ public: AlwaysShow = (1 << 25), - // used in the ChannelView class to make the collapse buttons visible if needed + // used in the ChannelView class to make the collapse buttons visible if + // needed Collapsed = (1 << 26), // used for dynamic bold usernames @@ -100,8 +102,9 @@ public: LowercaseLink = (1 << 29), OriginalLink = (1 << 30), - Default = Timestamp | Badges | Username | BitsStatic | FfzEmoteImage | BttvEmoteImage | - TwitchEmoteImage | BitsAmount | Text | AlwaysShow, + Default = Timestamp | Badges | Username | BitsStatic | FfzEmoteImage | + BttvEmoteImage | TwitchEmoteImage | BitsAmount | Text | + AlwaysShow, }; enum UpdateFlags : char { @@ -121,7 +124,8 @@ public: bool hasTrailingSpace() const; Flags getFlags() const; - virtual void addToContainer(MessageLayoutContainer &container, MessageElement::Flags flags) = 0; + virtual void addToContainer(MessageLayoutContainer &container, + MessageElement::Flags flags) = 0; protected: MessageElement(Flags flags); @@ -139,7 +143,8 @@ class ImageElement : public MessageElement public: ImageElement(ImagePtr image, MessageElement::Flags flags); - void addToContainer(MessageLayoutContainer &container, MessageElement::Flags flags) override; + void addToContainer(MessageLayoutContainer &container, + MessageElement::Flags flags) override; private: ImagePtr image_; @@ -154,7 +159,8 @@ public: FontStyle style = FontStyle::ChatMedium); ~TextElement() override = default; - void addToContainer(MessageLayoutContainer &container, MessageElement::Flags flags) override; + void addToContainer(MessageLayoutContainer &container, + MessageElement::Flags flags) override; private: MessageColor color_; @@ -175,7 +181,8 @@ class EmoteElement : public MessageElement public: EmoteElement(const EmotePtr &data, MessageElement::Flags flags_); - void addToContainer(MessageLayoutContainer &container, MessageElement::Flags flags_) override; + void addToContainer(MessageLayoutContainer &container, + MessageElement::Flags flags_) override; EmotePtr getEmote() const; private: @@ -190,7 +197,8 @@ public: TimestampElement(QTime time_ = QTime::currentTime()); ~TimestampElement() override = default; - void addToContainer(MessageLayoutContainer &container, MessageElement::Flags flags) override; + void addToContainer(MessageLayoutContainer &container, + MessageElement::Flags flags) override; TextElement *formatTime(const QTime &time); @@ -200,14 +208,15 @@ private: QString format_; }; -// adds all the custom moderation buttons, adds a variable amount of items depending on settings -// fourtf: implement +// adds all the custom moderation buttons, adds a variable amount of items +// depending on settings fourtf: implement class TwitchModerationElement : public MessageElement { public: TwitchModerationElement(); - void addToContainer(MessageLayoutContainer &container, MessageElement::Flags flags) override; + void addToContainer(MessageLayoutContainer &container, + MessageElement::Flags flags) override; }; } // namespace chatterino diff --git a/src/messages/Selection.hpp b/src/messages/Selection.hpp index e5e6f3042..dbed15d30 100644 --- a/src/messages/Selection.hpp +++ b/src/messages/Selection.hpp @@ -26,7 +26,8 @@ struct SelectionItem { if (this->messageIndex < b.messageIndex) { return true; } - if (this->messageIndex == b.messageIndex && this->charIndex < b.charIndex) { + if (this->messageIndex == b.messageIndex && + this->charIndex < b.charIndex) { return true; } return false; @@ -39,7 +40,8 @@ struct SelectionItem { bool operator==(const SelectionItem &b) const { - return this->messageIndex == b.messageIndex && this->charIndex == b.charIndex; + return this->messageIndex == b.messageIndex && + this->charIndex == b.charIndex; } bool operator!=(const SelectionItem &b) const @@ -74,7 +76,8 @@ struct Selection { bool isSingleMessage() const { - return this->selectionMin.messageIndex == this->selectionMax.messageIndex; + return this->selectionMin.messageIndex == + this->selectionMax.messageIndex; } }; diff --git a/src/messages/layouts/MessageLayout.cpp b/src/messages/layouts/MessageLayout.cpp index 259da3439..376423dea 100644 --- a/src/messages/layouts/MessageLayout.cpp +++ b/src/messages/layouts/MessageLayout.cpp @@ -98,12 +98,14 @@ void MessageLayout::actuallyLayout(int width, MessageElement::Flags _flags) if (this->flags & MessageLayout::Expanded || (_flags & MessageElement::ModeratorTools && !(this->message_->flags & Message::MessageFlags::Disabled))) { - messageFlags = Message::MessageFlags(messageFlags & ~Message::MessageFlags::Collapsed); + messageFlags = Message::MessageFlags(messageFlags & + ~Message::MessageFlags::Collapsed); } this->container_.begin(width, this->scale_, messageFlags); - for (const std::unique_ptr &element : this->message_->getElements()) { + for (const std::unique_ptr &element : + this->message_->getElements()) { element->addToContainer(this->container_, _flags); } @@ -123,7 +125,8 @@ void MessageLayout::actuallyLayout(int width, MessageElement::Flags _flags) // Painting void MessageLayout::paint(QPainter &painter, int width, int y, int messageIndex, - Selection &selection, bool isLastReadMessage, bool isWindowFocused) + Selection &selection, bool isLastReadMessage, + bool isWindowFocused) { auto app = getApp(); QPixmap *pixmap = this->buffer_.get(); @@ -132,7 +135,8 @@ void MessageLayout::paint(QPainter &painter, int width, int y, int messageIndex, if (!pixmap) { #ifdef Q_OS_MACOS pixmap = new QPixmap(int(width * painter.device()->devicePixelRatioF()), - int(container_.getHeight() * painter.device()->devicePixelRatioF())); + int(container_.getHeight() * + painter.device()->devicePixelRatioF())); pixmap->setDevicePixelRatio(painter.device()->devicePixelRatioF()); #else pixmap = new QPixmap(width, std::max(16, this->container_.getHeight())); @@ -149,14 +153,16 @@ void MessageLayout::paint(QPainter &painter, int width, int y, int messageIndex, // draw on buffer painter.drawPixmap(0, y, *pixmap); - // painter.drawPixmap(0, y, this->container.width, this->container.getHeight(), *pixmap); + // painter.drawPixmap(0, y, this->container.width, + // this->container.getHeight(), *pixmap); // draw gif emotes this->container_.paintAnimatedElements(painter, y); // draw disabled if (this->message_->flags.HasFlag(Message::Disabled)) { - painter.fillRect(0, y, pixmap->width(), pixmap->height(), app->themes->messages.disabled); + painter.fillRect(0, y, pixmap->width(), pixmap->height(), + app->themes->messages.disabled); } // draw selection @@ -172,19 +178,23 @@ void MessageLayout::paint(QPainter &painter, int width, int y, int messageIndex, // draw last read message line if (isLastReadMessage) { - QColor color = isWindowFocused ? app->themes->tabs.selected.backgrounds.regular.color() - : app->themes->tabs.selected.backgrounds.unfocused.color(); + QColor color = + isWindowFocused + ? app->themes->tabs.selected.backgrounds.regular.color() + : app->themes->tabs.selected.backgrounds.unfocused.color(); - QBrush brush(color, - static_cast(app->settings->lastMessagePattern.getValue())); + QBrush brush(color, static_cast( + app->settings->lastMessagePattern.getValue())); - painter.fillRect(0, y + this->container_.getHeight() - 1, pixmap->width(), 1, brush); + painter.fillRect(0, y + this->container_.getHeight() - 1, + pixmap->width(), 1, brush); } this->bufferValid_ = true; } -void MessageLayout::updateBuffer(QPixmap *buffer, int /*messageIndex*/, Selection & /*selection*/) +void MessageLayout::updateBuffer(QPixmap *buffer, int /*messageIndex*/, + Selection & /*selection*/) { auto app = getApp(); @@ -212,8 +222,8 @@ void MessageLayout::updateBuffer(QPixmap *buffer, int /*messageIndex*/, Selectio #ifdef FOURTF // debug painter.setPen(QColor(255, 0, 0)); - painter.drawRect(buffer->rect().x(), buffer->rect().y(), buffer->rect().width() - 1, - buffer->rect().height() - 1); + painter.drawRect(buffer->rect().x(), buffer->rect().y(), + buffer->rect().width() - 1, buffer->rect().height() - 1); QTextOption option; option.setAlignment(Qt::AlignRight | Qt::AlignTop); diff --git a/src/messages/layouts/MessageLayout.hpp b/src/messages/layouts/MessageLayout.hpp index f7354a3ae..fc61c7d42 100644 --- a/src/messages/layouts/MessageLayout.hpp +++ b/src/messages/layouts/MessageLayout.hpp @@ -40,8 +40,9 @@ public: bool layout(int width, float scale_, MessageElement::Flags flags); // Painting - void paint(QPainter &painter, int width, int y, int messageIndex, Selection &selection, - bool isLastReadMessage, bool isWindowFocused); + void paint(QPainter &painter, int width, int y, int messageIndex, + Selection &selection, bool isLastReadMessage, + bool isWindowFocused); void invalidateBuffer(); void deleteBuffer(); void deleteCache(); diff --git a/src/messages/layouts/MessageLayoutContainer.cpp b/src/messages/layouts/MessageLayoutContainer.cpp index 19ecfae98..8f9fead59 100644 --- a/src/messages/layouts/MessageLayoutContainer.cpp +++ b/src/messages/layouts/MessageLayoutContainer.cpp @@ -9,7 +9,8 @@ #include #define COMPACT_EMOTES_OFFSET 6 -#define MAX_UNCOLLAPSED_LINES (getApp()->settings->collpseMessagesMinLines.getValue()) +#define MAX_UNCOLLAPSED_LINES \ + (getApp()->settings->collpseMessagesMinLines.getValue()) namespace chatterino { @@ -29,13 +30,15 @@ float MessageLayoutContainer::getScale() const } // methods -void MessageLayoutContainer::begin(int width, float scale, Message::MessageFlags flags) +void MessageLayoutContainer::begin(int width, float scale, + Message::MessageFlags flags) { this->clear(); this->width_ = width; this->scale_ = scale; this->flags_ = flags; - auto mediumFontMetrics = getApp()->fonts->getFontMetrics(FontStyle::ChatMedium, scale); + auto mediumFontMetrics = + getApp()->fonts->getFontMetrics(FontStyle::ChatMedium, scale); this->textLineHeight_ = mediumFontMetrics.height(); this->spaceWidth_ = mediumFontMetrics.width(' '); this->dotdotdotWidth_ = mediumFontMetrics.width("..."); @@ -66,7 +69,8 @@ void MessageLayoutContainer::addElement(MessageLayoutElement *element) this->_addElement(element); } -void MessageLayoutContainer::addElementNoLineBreak(MessageLayoutElement *element) +void MessageLayoutContainer::addElementNoLineBreak( + MessageLayoutElement *element) { this->_addElement(element); } @@ -76,7 +80,8 @@ bool MessageLayoutContainer::canAddElements() return this->canAddMessages_; } -void MessageLayoutContainer::_addElement(MessageLayoutElement *element, bool forceAdd) +void MessageLayoutContainer::_addElement(MessageLayoutElement *element, + bool forceAdd) { if (!this->canAddElements() && !forceAdd) { delete element; @@ -91,8 +96,9 @@ void MessageLayoutContainer::_addElement(MessageLayoutElement *element, bool for int newLineHeight = element->getRect().height(); // compact emote offset - bool isCompactEmote = !(this->flags_ & Message::DisableCompactEmotes) && - element->getCreator().getFlags() & MessageElement::EmoteImages; + bool isCompactEmote = + !(this->flags_ & Message::DisableCompactEmotes) && + element->getCreator().getFlags() & MessageElement::EmoteImages; if (isCompactEmote) { newLineHeight -= COMPACT_EMOTES_OFFSET * this->scale_; @@ -102,7 +108,8 @@ void MessageLayoutContainer::_addElement(MessageLayoutElement *element, bool for this->lineHeight_ = std::max(this->lineHeight_, newLineHeight); // set move element - element->setPosition(QPoint(this->currentX_, this->currentY_ - element->getRect().height())); + element->setPosition( + QPoint(this->currentX_, this->currentY_ - element->getRect().height())); // add element this->elements_.push_back(std::unique_ptr(element)); @@ -120,35 +127,42 @@ void MessageLayoutContainer::breakLine() int xOffset = 0; if (this->flags_ & Message::Centered && this->elements_.size() > 0) { - xOffset = (width_ - this->elements_.at(this->elements_.size() - 1)->getRect().right()) / 2; + xOffset = (width_ - this->elements_.at(this->elements_.size() - 1) + ->getRect() + .right()) / + 2; } for (size_t i = lineStart_; i < this->elements_.size(); i++) { MessageLayoutElement *element = this->elements_.at(i).get(); - bool isCompactEmote = !(this->flags_ & Message::DisableCompactEmotes) && - element->getCreator().getFlags() & MessageElement::EmoteImages; + bool isCompactEmote = + !(this->flags_ & Message::DisableCompactEmotes) && + element->getCreator().getFlags() & MessageElement::EmoteImages; int yExtra = 0; if (isCompactEmote) { yExtra = (COMPACT_EMOTES_OFFSET / 2) * this->scale_; } - // if (element->getCreator().getFlags() & MessageElement::Badges) { + // if (element->getCreator().getFlags() & MessageElement::Badges) + // { if (element->getRect().height() < this->textLineHeight_) { yExtra -= (this->textLineHeight_ - element->getRect().height()) / 2; } - element->setPosition(QPoint(element->getRect().x() + xOffset + this->margin.left, - element->getRect().y() + this->lineHeight_ + yExtra)); + element->setPosition( + QPoint(element->getRect().x() + xOffset + this->margin.left, + element->getRect().y() + this->lineHeight_ + yExtra)); } if (this->lines_.size() != 0) { this->lines_.back().endIndex = this->lineStart_; this->lines_.back().endCharIndex = this->charIndex_; } - this->lines_.push_back({(int)lineStart_, 0, this->charIndex_, 0, - QRect(-100000, this->currentY_, 200000, lineHeight_)}); + this->lines_.push_back( + {(int)lineStart_, 0, this->charIndex_, 0, + QRect(-100000, this->currentY_, 200000, lineHeight_)}); for (int i = this->lineStart_; i < this->elements_.size(); i++) { this->charIndex_ += this->elements_[i]->getSelectionIndexCount(); @@ -178,17 +192,20 @@ bool MessageLayoutContainer::fitsInLine(int _width) { return this->currentX_ + _width <= (this->width_ - this->margin.left - this->margin.right - - (this->line_ + 1 == MAX_UNCOLLAPSED_LINES ? this->dotdotdotWidth_ : 0)); + (this->line_ + 1 == MAX_UNCOLLAPSED_LINES ? this->dotdotdotWidth_ + : 0)); } void MessageLayoutContainer::end() { if (!this->canAddElements()) { - static TextElement dotdotdot("...", MessageElement::Collapsed, MessageColor::Link); + static TextElement dotdotdot("...", MessageElement::Collapsed, + MessageColor::Link); static QString dotdotdotText("..."); auto *element = new TextLayoutElement( - dotdotdot, dotdotdotText, QSize(this->dotdotdotWidth_, this->textLineHeight_), + dotdotdot, dotdotdotText, + QSize(this->dotdotdotWidth_, this->textLineHeight_), QColor("#00D80A"), FontStyle::ChatMediumBold, this->scale_); // getApp()->themes->messages.textColors.system @@ -235,7 +252,8 @@ MessageLayoutElement *MessageLayoutContainer::getElementAt(QPoint point) // painting void MessageLayoutContainer::paintElements(QPainter &painter) { - for (const std::unique_ptr &element : this->elements_) { + for (const std::unique_ptr &element : + this->elements_) { #ifdef FOURTF painter.setPen(QColor(0, 255, 0)); painter.drawRect(element->getRect()); @@ -245,9 +263,11 @@ void MessageLayoutContainer::paintElements(QPainter &painter) } } -void MessageLayoutContainer::paintAnimatedElements(QPainter &painter, int yOffset) +void MessageLayoutContainer::paintAnimatedElements(QPainter &painter, + int yOffset) { - for (const std::unique_ptr &element : this->elements_) { + for (const std::unique_ptr &element : + this->elements_) { element->paintAnimated(painter, yOffset); } } @@ -273,7 +293,8 @@ void MessageLayoutContainer::paintSelection(QPainter &painter, int messageIndex, rect.setTop(std::max(0, rect.top()) + yOffset); rect.setBottom(std::min(this->height_, rect.bottom()) + yOffset); rect.setLeft(this->elements_[line.startIndex]->getRect().left()); - rect.setRight(this->elements_[line.endIndex - 1]->getRect().right()); + rect.setRight( + this->elements_[line.endIndex - 1]->getRect().right()); painter.fillRect(rect, selectionColor); } @@ -302,16 +323,19 @@ void MessageLayoutContainer::paintSelection(QPainter &painter, int messageIndex, int c = this->elements_[i]->getSelectionIndexCount(); if (index + c > selection.selectionMin.charIndex) { - x = this->elements_[i]->getXFromIndex(selection.selectionMin.charIndex - index); + x = this->elements_[i]->getXFromIndex( + selection.selectionMin.charIndex - index); // ends in same line if (selection.selectionMax.messageIndex == messageIndex && - line.endCharIndex > /*=*/selection.selectionMax.charIndex) // + line.endCharIndex > + /*=*/selection.selectionMax.charIndex) // { returnAfter = true; index = line.startCharIndex; for (int i = line.startIndex; i < line.endIndex; i++) { - int c = this->elements_[i]->getSelectionIndexCount(); + int c = + this->elements_[i]->getSelectionIndexCount(); if (index + c > selection.selectionMax.charIndex) { r = this->elements_[i]->getXFromIndex( @@ -330,9 +354,15 @@ void MessageLayoutContainer::paintSelection(QPainter &painter, int messageIndex, QRect rect = line.rect; rect.setTop(std::max(0, rect.top()) + yOffset); - rect.setBottom(std::min(this->height_, rect.bottom()) + yOffset); - rect.setLeft(this->elements_[line.startIndex]->getRect().left()); - rect.setRight(this->elements_[line.endIndex - 1]->getRect().right()); + rect.setBottom( + std::min(this->height_, rect.bottom()) + + yOffset); + rect.setLeft(this->elements_[line.startIndex] + ->getRect() + .left()); + rect.setRight(this->elements_[line.endIndex - 1] + ->getRect() + .right()); painter.fillRect(rect, selectionColor); } @@ -378,7 +408,8 @@ void MessageLayoutContainer::paintSelection(QPainter &painter, int messageIndex, rect.setTop(std::max(0, rect.top()) + yOffset); rect.setBottom(std::min(this->height_, rect.bottom()) + yOffset); rect.setLeft(this->elements_[line.startIndex]->getRect().left()); - rect.setRight(this->elements_[line.endIndex - 1]->getRect().right()); + rect.setRight( + this->elements_[line.endIndex - 1]->getRect().right()); painter.fillRect(rect, selectionColor); continue; @@ -390,7 +421,8 @@ void MessageLayoutContainer::paintSelection(QPainter &painter, int messageIndex, int c = this->elements_[i]->getSelectionIndexCount(); if (index + c > selection.selectionMax.charIndex) { - r = this->elements_[i]->getXFromIndex(selection.selectionMax.charIndex - index); + r = this->elements_[i]->getXFromIndex( + selection.selectionMax.charIndex - index); break; } @@ -424,11 +456,13 @@ int MessageLayoutContainer::getSelectionIndex(QPoint point) } } - int lineStart = line == this->lines_.end() ? this->lines_.back().startIndex : line->startIndex; + int lineStart = line == this->lines_.end() ? this->lines_.back().startIndex + : line->startIndex; if (line != this->lines_.end()) { line++; } - int lineEnd = line == this->lines_.end() ? this->elements_.size() : line->startIndex; + int lineEnd = + line == this->lines_.end() ? this->elements_.size() : line->startIndex; int index = 0; diff --git a/src/messages/layouts/MessageLayoutContainer.hpp b/src/messages/layouts/MessageLayoutContainer.hpp index 3e00effce..3b20e8191 100644 --- a/src/messages/layouts/MessageLayoutContainer.hpp +++ b/src/messages/layouts/MessageLayoutContainer.hpp @@ -66,7 +66,8 @@ struct MessageLayoutContainer { // painting void paintElements(QPainter &painter); void paintAnimatedElements(QPainter &painter, int yOffset); - void paintSelection(QPainter &painter, int messageIndex, Selection &selection, int yOffset); + void paintSelection(QPainter &painter, int messageIndex, + Selection &selection, int yOffset); // selection int getSelectionIndex(QPoint point); diff --git a/src/messages/layouts/MessageLayoutElement.cpp b/src/messages/layouts/MessageLayoutElement.cpp index 3e2c649d2..e8d333e2b 100644 --- a/src/messages/layouts/MessageLayoutElement.cpp +++ b/src/messages/layouts/MessageLayoutElement.cpp @@ -14,7 +14,8 @@ const QRect &MessageLayoutElement::getRect() const return this->rect_; } -MessageLayoutElement::MessageLayoutElement(MessageElement &creator, const QSize &size) +MessageLayoutElement::MessageLayoutElement(MessageElement &creator, + const QSize &size) : creator_(creator) { this->rect_.setSize(size); @@ -63,14 +64,16 @@ const Link &MessageLayoutElement::getLink() const // IMAGE // -ImageLayoutElement::ImageLayoutElement(MessageElement &creator, ImagePtr image, const QSize &size) +ImageLayoutElement::ImageLayoutElement(MessageElement &creator, ImagePtr image, + const QSize &size) : MessageLayoutElement(creator, size) , image_(image) { this->trailingSpace = creator.hasTrailingSpace(); } -void ImageLayoutElement::addCopyTextToString(QString &str, int from, int to) const +void ImageLayoutElement::addCopyTextToString(QString &str, int from, + int to) const { // str += this->image_->getCopyString(); str += "not implemented"; @@ -134,8 +137,9 @@ int ImageLayoutElement::getXFromIndex(int index) // TEXT // -TextLayoutElement::TextLayoutElement(MessageElement &_creator, QString &_text, const QSize &_size, - QColor _color, FontStyle _style, float _scale) +TextLayoutElement::TextLayoutElement(MessageElement &_creator, QString &_text, + const QSize &_size, QColor _color, + FontStyle _style, float _scale) : MessageLayoutElement(_creator, _size) , text(_text) , color(_color) @@ -144,7 +148,8 @@ TextLayoutElement::TextLayoutElement(MessageElement &_creator, QString &_text, c { } -void TextLayoutElement::addCopyTextToString(QString &str, int from, int to) const +void TextLayoutElement::addCopyTextToString(QString &str, int from, + int to) const { str += this->text.mid(from, to - from); @@ -166,8 +171,9 @@ void TextLayoutElement::paint(QPainter &painter) painter.setFont(app->fonts->getFont(this->style, this->scale)); - painter.drawText(QRectF(this->getRect().x(), this->getRect().y(), 10000, 10000), this->text, - QTextOption(Qt::AlignLeft | Qt::AlignTop)); + painter.drawText( + QRectF(this->getRect().x(), this->getRect().y(), 10000, 10000), + this->text, QTextOption(Qt::AlignLeft | Qt::AlignTop)); } void TextLayoutElement::paintAnimated(QPainter &, int) @@ -219,8 +225,10 @@ int TextLayoutElement::getXFromIndex(int index) } // TEXT ICON -TextIconLayoutElement::TextIconLayoutElement(MessageElement &creator, const QString &_line1, - const QString &_line2, float _scale, const QSize &size) +TextIconLayoutElement::TextIconLayoutElement(MessageElement &creator, + const QString &_line1, + const QString &_line2, + float _scale, const QSize &size) : MessageLayoutElement(creator, size) , scale(_scale) , line1(_line1) @@ -228,7 +236,8 @@ TextIconLayoutElement::TextIconLayoutElement(MessageElement &creator, const QStr { } -void TextIconLayoutElement::addCopyTextToString(QString &str, int from, int to) const +void TextIconLayoutElement::addCopyTextToString(QString &str, int from, + int to) const { } @@ -254,11 +263,12 @@ void TextIconLayoutElement::paint(QPainter &painter) painter.drawText(_rect, this->line1, option); } else { painter.drawText( - QPoint(this->getRect().x(), this->getRect().y() + this->getRect().height() / 2), + QPoint(this->getRect().x(), + this->getRect().y() + this->getRect().height() / 2), this->line1); - painter.drawText( - QPoint(this->getRect().x(), this->getRect().y() + this->getRect().height()), - this->line2); + painter.drawText(QPoint(this->getRect().x(), + this->getRect().y() + this->getRect().height()), + this->line2); } } diff --git a/src/messages/layouts/MessageLayoutElement.hpp b/src/messages/layouts/MessageLayoutElement.hpp index d8221726f..44b4c9316 100644 --- a/src/messages/layouts/MessageLayoutElement.hpp +++ b/src/messages/layouts/MessageLayoutElement.hpp @@ -31,7 +31,8 @@ public: MessageLayoutElement *setTrailingSpace(bool value); MessageLayoutElement *setLink(const Link &link_); - virtual void addCopyTextToString(QString &str, int from = 0, int to = INT_MAX) const = 0; + virtual void addCopyTextToString(QString &str, int from = 0, + int to = INT_MAX) const = 0; virtual int getSelectionIndexCount() = 0; virtual void paint(QPainter &painter) = 0; virtual void paintAnimated(QPainter &painter, int yOffset) = 0; @@ -52,10 +53,12 @@ private: class ImageLayoutElement : public MessageLayoutElement { public: - ImageLayoutElement(MessageElement &creator, ImagePtr image, const QSize &size); + ImageLayoutElement(MessageElement &creator, ImagePtr image, + const QSize &size); protected: - void addCopyTextToString(QString &str, int from = 0, int to = INT_MAX) const override; + void addCopyTextToString(QString &str, int from = 0, + int to = INT_MAX) const override; int getSelectionIndexCount() override; void paint(QPainter &painter) override; void paintAnimated(QPainter &painter, int yOffset) override; @@ -70,11 +73,13 @@ private: class TextLayoutElement : public MessageLayoutElement { public: - TextLayoutElement(MessageElement &creator_, QString &text, const QSize &size, QColor color, - FontStyle style, float scale); + TextLayoutElement(MessageElement &creator_, QString &text, + const QSize &size, QColor color, FontStyle style, + float scale); protected: - void addCopyTextToString(QString &str, int from = 0, int to = INT_MAX) const override; + void addCopyTextToString(QString &str, int from = 0, + int to = INT_MAX) const override; int getSelectionIndexCount() override; void paint(QPainter &painter) override; void paintAnimated(QPainter &painter, int yOffset) override; @@ -93,11 +98,12 @@ private: class TextIconLayoutElement : public MessageLayoutElement { public: - TextIconLayoutElement(MessageElement &creator_, const QString &line1, const QString &line2, - float scale, const QSize &size); + TextIconLayoutElement(MessageElement &creator_, const QString &line1, + const QString &line2, float scale, const QSize &size); protected: - void addCopyTextToString(QString &str, int from = 0, int to = INT_MAX) const override; + void addCopyTextToString(QString &str, int from = 0, + int to = INT_MAX) const override; int getSelectionIndexCount() override; void paint(QPainter &painter) override; void paintAnimated(QPainter &painter, int yOffset) override; diff --git a/src/providers/bttv/BttvEmotes.cpp b/src/providers/bttv/BttvEmotes.cpp index 570879210..b9ca7ba99 100644 --- a/src/providers/bttv/BttvEmotes.cpp +++ b/src/providers/bttv/BttvEmotes.cpp @@ -13,11 +13,13 @@ namespace chatterino { namespace { -Url getEmoteLink(QString urlTemplate, const EmoteId &id, const QString &emoteScale) +Url getEmoteLink(QString urlTemplate, const EmoteId &id, + const QString &emoteScale) { urlTemplate.detach(); - return {urlTemplate.replace("{{id}}", id.string).replace("{{image}}", emoteScale)}; + return {urlTemplate.replace("{{id}}", id.string) + .replace("{{image}}", emoteScale)}; } } // namespace @@ -76,23 +78,26 @@ void BttvEmotes::loadGlobalEmotes() request.execute(); } -std::pair BttvEmotes::parseGlobalEmotes(const QJsonObject &jsonRoot, - const EmoteMap ¤tEmotes) +std::pair BttvEmotes::parseGlobalEmotes( + const QJsonObject &jsonRoot, const EmoteMap ¤tEmotes) { auto emotes = EmoteMap(); auto jsonEmotes = jsonRoot.value("emotes").toArray(); - auto urlTemplate = QString("https:" + jsonRoot.value("urlTemplate").toString()); + auto urlTemplate = + QString("https:" + jsonRoot.value("urlTemplate").toString()); for (const QJsonValue &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}}); + 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}}); auto it = currentEmotes.find(name); if (it != currentEmotes.end() && *it->second == emote) { diff --git a/src/providers/bttv/BttvEmotes.hpp b/src/providers/bttv/BttvEmotes.hpp index f8273afb8..f85333df7 100644 --- a/src/providers/bttv/BttvEmotes.hpp +++ b/src/providers/bttv/BttvEmotes.hpp @@ -10,7 +10,8 @@ namespace chatterino { class BttvEmotes final : std::enable_shared_from_this { - static constexpr const char *globalEmoteApiUrl = "https://api.betterttv.net/2/emotes"; + static constexpr const char *globalEmoteApiUrl = + "https://api.betterttv.net/2/emotes"; public: // BttvEmotes(); @@ -22,8 +23,8 @@ public: void loadGlobalEmotes(); private: - std::pair parseGlobalEmotes(const QJsonObject &jsonRoot, - const EmoteMap ¤tEmotes); + std::pair parseGlobalEmotes( + const QJsonObject &jsonRoot, const EmoteMap ¤tEmotes); UniqueAccess globalEmotes_; // UniqueAccess channelEmoteCache_; diff --git a/src/providers/bttv/LoadBttvChannelEmote.cpp b/src/providers/bttv/LoadBttvChannelEmote.cpp index 9829c6e07..ccc52a130 100644 --- a/src/providers/bttv/LoadBttvChannelEmote.cpp +++ b/src/providers/bttv/LoadBttvChannelEmote.cpp @@ -11,12 +11,16 @@ namespace chatterino { -static Url getEmoteLink(QString urlTemplate, const EmoteId &id, const QString &emoteScale); -static std::pair bttvParseChannelEmotes(const QJsonObject &jsonRoot); +static Url getEmoteLink(QString urlTemplate, const EmoteId &id, + const QString &emoteScale); +static std::pair bttvParseChannelEmotes( + const QJsonObject &jsonRoot); -void loadBttvChannelEmotes(const QString &channelName, std::function callback) +void loadBttvChannelEmotes(const QString &channelName, + std::function callback) { - auto request = NetworkRequest(QString(bttvChannelEmoteApiUrl) + channelName); + auto request = + NetworkRequest(QString(bttvChannelEmoteApiUrl) + channelName); request.setCaller(QThread::currentThread()); request.setTimeout(3000); @@ -31,14 +35,17 @@ void loadBttvChannelEmotes(const QString &channelName, std::function bttvParseChannelEmotes(const QJsonObject &jsonRoot) +static std::pair bttvParseChannelEmotes( + const QJsonObject &jsonRoot) { - static UniqueAccess>> cache_; + static UniqueAccess>> + cache_; auto cache = cache_.access(); auto emotes = EmoteMap(); auto jsonEmotes = jsonRoot.value("emotes").toArray(); - auto urlTemplate = QString("https:" + jsonRoot.value("urlTemplate").toString()); + auto urlTemplate = + QString("https:" + jsonRoot.value("urlTemplate").toString()); for (auto jsonEmote_ : jsonEmotes) { auto jsonEmote = jsonEmote_.toObject(); @@ -47,30 +54,35 @@ static std::pair bttvParseChannelEmotes(const QJsonObject &js 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}}); + 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}}); auto shared = (*cache)[id].lock(); if (shared && *shared == emote) { // reuse old shared_ptr if nothing changed emotes[name] = shared; } else { - (*cache)[id] = emotes[name] = std::make_shared(std::move(emote)); + (*cache)[id] = emotes[name] = + std::make_shared(std::move(emote)); } } return {Success, std::move(emotes)}; } -static Url getEmoteLink(QString urlTemplate, const EmoteId &id, const QString &emoteScale) +static Url getEmoteLink(QString urlTemplate, const EmoteId &id, + const QString &emoteScale) { urlTemplate.detach(); - return {urlTemplate.replace("{{id}}", id.string).replace("{{image}}", emoteScale)}; + return {urlTemplate.replace("{{id}}", id.string) + .replace("{{image}}", emoteScale)}; } } // namespace chatterino diff --git a/src/providers/bttv/LoadBttvChannelEmote.hpp b/src/providers/bttv/LoadBttvChannelEmote.hpp index ef9ca160e..ffbb50469 100644 --- a/src/providers/bttv/LoadBttvChannelEmote.hpp +++ b/src/providers/bttv/LoadBttvChannelEmote.hpp @@ -7,8 +7,10 @@ class QString; namespace chatterino { class EmoteMap; -constexpr const char *bttvChannelEmoteApiUrl = "https://api.betterttv.net/2/channels/"; +constexpr const char *bttvChannelEmoteApiUrl = + "https://api.betterttv.net/2/channels/"; -void loadBttvChannelEmotes(const QString &channelName, std::function callback); +void loadBttvChannelEmotes(const QString &channelName, + std::function callback); } // namespace chatterino diff --git a/src/providers/chatterino/ChatterinoBadges.cpp b/src/providers/chatterino/ChatterinoBadges.cpp index 01dc82aa4..98b1841d4 100644 --- a/src/providers/chatterino/ChatterinoBadges.cpp +++ b/src/providers/chatterino/ChatterinoBadges.cpp @@ -32,11 +32,13 @@ void ChatterinoBadges::loadChatterinoBadges() for (auto jsonBadge_ : jsonRoot.value("badges").toArray()) { auto jsonBadge = jsonBadge_.toObject(); - auto emote = Emote{EmoteName{}, ImageSet{Url{jsonBadge.value("image").toString()}}, - Tooltip{jsonBadge.value("tooltip").toString()}, Url{}}; + auto emote = Emote{ + EmoteName{}, ImageSet{Url{jsonBadge.value("image").toString()}}, + Tooltip{jsonBadge.value("tooltip").toString()}, Url{}}; for (auto jsonUser : jsonBadge.value("users").toArray()) { - replacement.add(UserName{jsonUser.toString()}, std::move(emote)); + replacement.add(UserName{jsonUser.toString()}, + std::move(emote)); } } diff --git a/src/providers/emoji/Emojis.cpp b/src/providers/emoji/Emojis.cpp index 064e693f1..ec7bac2b8 100644 --- a/src/providers/emoji/Emojis.cpp +++ b/src/providers/emoji/Emojis.cpp @@ -15,7 +15,8 @@ namespace chatterino { namespace { -void parseEmoji(const std::shared_ptr &emojiData, const rapidjson::Value &unparsedEmoji, +void parseEmoji(const std::shared_ptr &emojiData, + const rapidjson::Value &unparsedEmoji, QString shortCode = QString()) { static uint unicodeBytes[4]; @@ -80,7 +81,8 @@ void parseEmoji(const std::shared_ptr &emojiData, const rapidjson::Va int numUnicodeBytes = 0; for (const QString &unicodeCharacter : unicodeCharacters) { - unicodeBytes[numUnicodeBytes++] = QString(unicodeCharacter).toUInt(nullptr, 16); + unicodeBytes[numUnicodeBytes++] = + QString(unicodeCharacter).toUInt(nullptr, 16); } emojiData->value = QString::fromUcs4(unicodeBytes, numUnicodeBytes); @@ -116,8 +118,8 @@ void Emojis::loadEmojis() rapidjson::ParseResult result = root.Parse(data.toUtf8(), data.length()); if (result.Code() != rapidjson::kParseErrorNone) { - Log("JSON parse error: {} ({})", rapidjson::GetParseError_En(result.Code()), - result.Offset()); + Log("JSON parse error: {} ({})", + rapidjson::GetParseError_En(result.Code()), result.Offset()); return; } @@ -135,7 +137,8 @@ void Emojis::loadEmojis() this->emojis.insert(emojiData->unifiedCode, emojiData); if (unparsedEmoji.HasMember("skin_variations")) { - for (const auto &skinVariation : unparsedEmoji["skin_variations"].GetObject()) { + for (const auto &skinVariation : + unparsedEmoji["skin_variations"].GetObject()) { std::string tone = skinVariation.name.GetString(); const auto &variation = skinVariation.value; @@ -143,20 +146,23 @@ void Emojis::loadEmojis() auto toneNameIt = toneNames.find(tone); if (toneNameIt == toneNames.end()) { - Log("Tone with key {} does not exist in tone names map", tone); + Log("Tone with key {} does not exist in tone names map", + tone); continue; } parseEmoji(variationEmojiData, variation, emojiData->shortCodes[0] + "_" + toneNameIt->second); - this->emojiShortCodeToEmoji_.insert(variationEmojiData->shortCodes[0], - variationEmojiData); + this->emojiShortCodeToEmoji_.insert( + variationEmojiData->shortCodes[0], variationEmojiData); this->shortCodes.push_back(variationEmojiData->shortCodes[0]); - this->emojiFirstByte_[variationEmojiData->value.at(0)].append(variationEmojiData); + this->emojiFirstByte_[variationEmojiData->value.at(0)].append( + variationEmojiData); - this->emojis.insert(variationEmojiData->unifiedCode, variationEmojiData); + this->emojis.insert(variationEmojiData->unifiedCode, + variationEmojiData); } } } @@ -196,14 +202,16 @@ void Emojis::loadEmojiOne2Capabilities() void Emojis::sortEmojis() { for (auto &p : this->emojiFirstByte_) { - std::stable_sort(p.begin(), p.end(), [](const auto &lhs, const auto &rhs) { - return lhs->value.length() > rhs->value.length(); - }); + std::stable_sort(p.begin(), p.end(), + [](const auto &lhs, const auto &rhs) { + return lhs->value.length() > rhs->value.length(); + }); } auto &p = this->shortCodes; - std::stable_sort(p.begin(), p.end(), - [](const auto &lhs, const auto &rhs) { return lhs < rhs; }); + std::stable_sort(p.begin(), p.end(), [](const auto &lhs, const auto &rhs) { + return lhs < rhs; + }); } void Emojis::loadEmojiSet() @@ -212,7 +220,8 @@ void Emojis::loadEmojiSet() app->settings->emojiSet.connect([=](const auto &emojiSet, auto) { Log("Using emoji set {}", emojiSet); - this->emojis.each([=](const auto &name, std::shared_ptr &emoji) { + this->emojis.each([=](const auto &name, + std::shared_ptr &emoji) { QString emojiSetToUse = emojiSet; // clang-format off static std::map emojiSets = { @@ -259,20 +268,22 @@ void Emojis::loadEmojiSet() } } code = code.toLower(); - QString urlPrefix = "https://cdnjs.cloudflare.com/ajax/libs/emojione/2.2.6/assets/png/"; + QString urlPrefix = "https://cdnjs.cloudflare.com/ajax/libs/" + "emojione/2.2.6/assets/png/"; auto it = emojiSets.find(emojiSetToUse); if (it != emojiSets.end()) { urlPrefix = it->second; } QString url = urlPrefix + code + ".png"; - emoji->emote = std::make_shared( - Emote{EmoteName{emoji->value}, ImageSet{Image::fromUrl({url}, 0.35)}, - Tooltip{":" + emoji->shortCodes[0] + ":
Emoji"}, Url{}}); + emoji->emote = std::make_shared(Emote{ + EmoteName{emoji->value}, ImageSet{Image::fromUrl({url}, 0.35)}, + Tooltip{":" + emoji->shortCodes[0] + ":
Emoji"}, Url{}}); }); }); } -std::vector> Emojis::parse(const QString &text) +std::vector> Emojis::parse( + const QString &text) { auto result = std::vector>(); int lastParsedEmojiEndIndex = 0; @@ -330,11 +341,13 @@ std::vector> Emojis::parse(const QString &text int currentParsedEmojiFirstIndex = i; int currentParsedEmojiEndIndex = i + (matchedEmojiLength); - int charactersFromLastParsedEmoji = currentParsedEmojiFirstIndex - lastParsedEmojiEndIndex; + int charactersFromLastParsedEmoji = + currentParsedEmojiFirstIndex - lastParsedEmojiEndIndex; if (charactersFromLastParsedEmoji > 0) { // Add characters inbetween emojis - result.emplace_back(text.mid(lastParsedEmojiEndIndex, charactersFromLastParsedEmoji)); + result.emplace_back(text.mid(lastParsedEmojiEndIndex, + charactersFromLastParsedEmoji)); } // Push the emoji as a word to parsedWords @@ -365,7 +378,8 @@ QString Emojis::replaceShortCodes(const QString &text) auto capturedString = match.captured(); - QString matchString = capturedString.toLower().mid(1, capturedString.size() - 2); + QString matchString = + capturedString.toLower().mid(1, capturedString.size() - 2); auto emojiIt = this->emojiShortCodeToEmoji_.constFind(matchString); @@ -375,7 +389,8 @@ QString Emojis::replaceShortCodes(const QString &text) auto emojiData = emojiIt.value(); - ret.replace(offset + match.capturedStart(), match.capturedLength(), emojiData->value); + ret.replace(offset + match.capturedStart(), match.capturedLength(), + emojiData->value); offset += emojiData->value.size() - match.capturedLength(); } diff --git a/src/providers/emoji/Emojis.hpp b/src/providers/emoji/Emojis.hpp index 59d184d01..6a2f4e74e 100644 --- a/src/providers/emoji/Emojis.hpp +++ b/src/providers/emoji/Emojis.hpp @@ -15,7 +15,8 @@ namespace chatterino { struct EmojiData { - // actual byte-representation of the emoji (i.e. \154075\156150 which is :male:) + // actual byte-representation of the emoji (i.e. \154075\156150 which is + // :male:) QString value; // i.e. 204e-50a2 @@ -57,7 +58,8 @@ private: // shortCodeToEmoji maps strings like "sunglasses" to its emoji QMap> emojiShortCodeToEmoji_; - // Maps the first character of the emoji unicode string to a vector of possible emojis + // Maps the first character of the emoji unicode string to a vector of + // possible emojis QMap>> emojiFirstByte_; }; diff --git a/src/providers/ffz/FfzEmotes.cpp b/src/providers/ffz/FfzEmotes.cpp index 3a9763b22..b5fe65aa2 100644 --- a/src/providers/ffz/FfzEmotes.cpp +++ b/src/providers/ffz/FfzEmotes.cpp @@ -20,8 +20,8 @@ Url getEmoteLink(const QJsonObject &urls, const QString &emoteScale) return {"https:" + emote.toString()}; } -void fillInEmoteData(const QJsonObject &urls, const EmoteName &name, const QString &tooltip, - Emote &emoteData) +void fillInEmoteData(const QJsonObject &urls, const EmoteName &name, + const QString &tooltip, Emote &emoteData) { auto url1x = getEmoteLink(urls, "1"); auto url2x = getEmoteLink(urls, "2"); @@ -30,7 +30,8 @@ void fillInEmoteData(const QJsonObject &urls, const EmoteName &name, const QStri //, code, tooltip emoteData.name = name; emoteData.images = - ImageSet{Image::fromUrl(url1x, 1), Image::fromUrl(url2x, 0.5), Image::fromUrl(url3x, 0.25)}; + ImageSet{Image::fromUrl(url1x, 1), Image::fromUrl(url2x, 0.5), + Image::fromUrl(url3x, 0.25)}; emoteData.tooltip = {tooltip}; } } // namespace @@ -67,8 +68,9 @@ void FfzEmotes::loadGlobalEmotes() NetworkRequest request(url); request.setCaller(QThread::currentThread()); request.setTimeout(30000); - request.onSuccess( - [this](auto result) -> Outcome { return this->parseGlobalEmotes(result.parseJson()); }); + request.onSuccess([this](auto result) -> Outcome { + return this->parseGlobalEmotes(result.parseJson()); + }); request.execute(); } @@ -90,10 +92,12 @@ Outcome FfzEmotes::parseGlobalEmotes(const QJsonObject &jsonRoot) 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)}; + 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)}; replacement.add(name, emote); } @@ -105,7 +109,8 @@ Outcome FfzEmotes::parseGlobalEmotes(const QJsonObject &jsonRoot) void FfzEmotes::loadChannelEmotes(const QString &channelName, std::function callback) { - // printf("[FFZEmotes] Reload FFZ Channel Emotes for channel %s\n", qPrintable(channelName)); + // printf("[FFZEmotes] Reload FFZ Channel Emotes for channel %s\n", + // qPrintable(channelName)); // QString url("https://api.frankerfacez.com/v1/room/" + channelName); @@ -145,10 +150,11 @@ Outcome parseChannelEmotes(const QJsonObject &jsonRoot) // QJsonObject urls = emoteObject.value("urls").toObject(); - // auto emote = this->channelEmoteCache_.getOrAdd(id, [id, &code, &urls] { + // auto emote = this->channelEmoteCache_.getOrAdd(id, [id, &code, + // &urls] { // EmoteData emoteData; - // fillInEmoteData(urls, code, code + "
Channel FFZ Emote", emoteData); - // emoteData.pageLink = + // fillInEmoteData(urls, code, code + "
Channel FFZ Emote", + // emoteData); emoteData.pageLink = // QString("https://www.frankerfacez.com/emoticon/%1-%2").arg(id).arg(code); // return emoteData; diff --git a/src/providers/ffz/FfzEmotes.hpp b/src/providers/ffz/FfzEmotes.hpp index d42885440..2dd747e02 100644 --- a/src/providers/ffz/FfzEmotes.hpp +++ b/src/providers/ffz/FfzEmotes.hpp @@ -10,8 +10,10 @@ namespace chatterino { class FfzEmotes final : std::enable_shared_from_this { - static constexpr const char *globalEmoteApiUrl = "https://api.frankerfacez.com/v1/set/global"; - static constexpr const char *channelEmoteApiUrl = "https://api.betterttv.net/2/channels/"; + static constexpr const char *globalEmoteApiUrl = + "https://api.frankerfacez.com/v1/set/global"; + static constexpr const char *channelEmoteApiUrl = + "https://api.betterttv.net/2/channels/"; public: // FfzEmotes(); @@ -23,7 +25,8 @@ public: boost::optional getEmote(const EmoteId &id); void loadGlobalEmotes(); - void loadChannelEmotes(const QString &channelName, std::function callback); + void loadChannelEmotes(const QString &channelName, + std::function callback); protected: Outcome parseGlobalEmotes(const QJsonObject &jsonRoot); diff --git a/src/providers/irc/AbstractIrcServer.cpp b/src/providers/irc/AbstractIrcServer.cpp index 532b78710..840291c5f 100644 --- a/src/providers/irc/AbstractIrcServer.cpp +++ b/src/providers/irc/AbstractIrcServer.cpp @@ -12,27 +12,35 @@ AbstractIrcServer::AbstractIrcServer() { // Initialize the connections this->writeConnection_.reset(new IrcConnection); - this->writeConnection_->moveToThread(QCoreApplication::instance()->thread()); + this->writeConnection_->moveToThread( + QCoreApplication::instance()->thread()); - QObject::connect(this->writeConnection_.get(), &Communi::IrcConnection::messageReceived, - [this](auto msg) { this->writeConnectionMessageReceived(msg); }); + QObject::connect( + this->writeConnection_.get(), &Communi::IrcConnection::messageReceived, + [this](auto msg) { this->writeConnectionMessageReceived(msg); }); // Listen to read connection message signals this->readConnection_.reset(new IrcConnection); this->readConnection_->moveToThread(QCoreApplication::instance()->thread()); - QObject::connect(this->readConnection_.get(), &Communi::IrcConnection::messageReceived, + QObject::connect(this->readConnection_.get(), + &Communi::IrcConnection::messageReceived, [this](auto msg) { this->messageReceived(msg); }); - QObject::connect(this->readConnection_.get(), &Communi::IrcConnection::privateMessageReceived, + QObject::connect(this->readConnection_.get(), + &Communi::IrcConnection::privateMessageReceived, [this](auto msg) { this->privateMessageReceived(msg); }); - QObject::connect(this->readConnection_.get(), &Communi::IrcConnection::connected, + QObject::connect(this->readConnection_.get(), + &Communi::IrcConnection::connected, [this] { this->onConnected(); }); - QObject::connect(this->readConnection_.get(), &Communi::IrcConnection::disconnected, + QObject::connect(this->readConnection_.get(), + &Communi::IrcConnection::disconnected, [this] { this->onDisconnected(); }); // listen to reconnect request - this->readConnection_->reconnectRequested.connect([this] { this->connect(); }); - // this->writeConnection->reconnectRequested.connect([this] { this->connect(); }); + this->readConnection_->reconnectRequested.connect( + [this] { this->connect(); }); + // this->writeConnection->reconnectRequested.connect([this] { + // this->connect(); }); } void AbstractIrcServer::connect() @@ -75,7 +83,8 @@ void AbstractIrcServer::disconnect() this->writeConnection_->close(); } -void AbstractIrcServer::sendMessage(const QString &channelName, const QString &message) +void AbstractIrcServer::sendMessage(const QString &channelName, + const QString &message) { this->sendRawMessage("PRIVMSG #" + channelName + " :" + message); } @@ -91,11 +100,13 @@ void AbstractIrcServer::sendRawMessage(const QString &rawMessage) } } -void AbstractIrcServer::writeConnectionMessageReceived(Communi::IrcMessage *message) +void AbstractIrcServer::writeConnectionMessageReceived( + Communi::IrcMessage *message) { } -std::shared_ptr AbstractIrcServer::getOrAddChannel(const QString &dirtyChannelName) +std::shared_ptr AbstractIrcServer::getOrAddChannel( + const QString &dirtyChannelName) { auto channelName = this->cleanChannelName(dirtyChannelName); @@ -119,7 +130,8 @@ std::shared_ptr AbstractIrcServer::getOrAddChannel(const QString &dirty chan->destroyed.connect([this, clojuresInCppAreShit] { // fourtf: issues when the server itself is destroyed - Log("[AbstractIrcServer::addChannel] {} was destroyed", clojuresInCppAreShit); + Log("[AbstractIrcServer::addChannel] {} was destroyed", + clojuresInCppAreShit); this->channels.remove(clojuresInCppAreShit); if (this->readConnection_) { @@ -147,7 +159,8 @@ std::shared_ptr AbstractIrcServer::getOrAddChannel(const QString &dirty return chan; } -std::shared_ptr AbstractIrcServer::getChannelOrEmpty(const QString &dirtyChannelName) +std::shared_ptr AbstractIrcServer::getChannelOrEmpty( + const QString &dirtyChannelName) { auto channelName = this->cleanChannelName(dirtyChannelName); @@ -187,9 +200,9 @@ void AbstractIrcServer::onConnected() LimitedQueueSnapshot snapshot = chan->getMessageSnapshot(); - bool replaceMessage = - snapshot.getLength() > 0 && - snapshot[snapshot.getLength() - 1]->flags & Message::DisconnectedMessage; + bool replaceMessage = snapshot.getLength() > 0 && + snapshot[snapshot.getLength() - 1]->flags & + Message::DisconnectedMessage; if (replaceMessage) { chan->replaceMessage(snapshot[snapshot.getLength() - 1], reconnMsg); @@ -217,7 +230,8 @@ void AbstractIrcServer::onDisconnected() } } -std::shared_ptr AbstractIrcServer::getCustomChannel(const QString &channelName) +std::shared_ptr AbstractIrcServer::getCustomChannel( + const QString &channelName) { return nullptr; } @@ -229,16 +243,19 @@ QString AbstractIrcServer::cleanChannelName(const QString &dirtyChannelName) void AbstractIrcServer::addFakeMessage(const QString &data) { - auto fakeMessage = Communi::IrcMessage::fromData(data.toUtf8(), this->readConnection_.get()); + auto fakeMessage = Communi::IrcMessage::fromData( + data.toUtf8(), this->readConnection_.get()); if (fakeMessage->command() == "PRIVMSG") { - this->privateMessageReceived(static_cast(fakeMessage)); + this->privateMessageReceived( + static_cast(fakeMessage)); } else { this->messageReceived(fakeMessage); } } -void AbstractIrcServer::privateMessageReceived(Communi::IrcPrivateMessage *message) +void AbstractIrcServer::privateMessageReceived( + Communi::IrcPrivateMessage *message) { } diff --git a/src/providers/irc/AbstractIrcServer.hpp b/src/providers/irc/AbstractIrcServer.hpp index 734be1d87..580cdd0fe 100644 --- a/src/providers/irc/AbstractIrcServer.hpp +++ b/src/providers/irc/AbstractIrcServer.hpp @@ -30,7 +30,8 @@ public: // signals pajlada::Signals::NoArgSignal connected; pajlada::Signals::NoArgSignal disconnected; - // pajlada::Signals::Signal onPrivateMessage; + // pajlada::Signals::Signal + // onPrivateMessage; void addFakeMessage(const QString &data); @@ -40,8 +41,10 @@ public: protected: AbstractIrcServer(); - virtual void initializeConnection(IrcConnection *connection, bool isRead, bool isWrite) = 0; - virtual std::shared_ptr createChannel(const QString &channelName) = 0; + virtual void initializeConnection(IrcConnection *connection, bool isRead, + bool isWrite) = 0; + virtual std::shared_ptr createChannel( + const QString &channelName) = 0; virtual void privateMessageReceived(Communi::IrcPrivateMessage *message); virtual void messageReceived(Communi::IrcMessage *message); @@ -50,7 +53,8 @@ protected: virtual void onConnected(); virtual void onDisconnected(); - virtual std::shared_ptr getCustomChannel(const QString &channelName); + virtual std::shared_ptr getCustomChannel( + const QString &channelName); virtual bool hasSeparateWriteConnection() const = 0; virtual QString cleanChannelName(const QString &dirtyChannelName); diff --git a/src/providers/irc/IrcAccount.cpp b/src/providers/irc/IrcAccount.cpp index 1b7afad50..96486b7ea 100644 --- a/src/providers/irc/IrcAccount.cpp +++ b/src/providers/irc/IrcAccount.cpp @@ -2,7 +2,8 @@ // namespace chatterino { // -// IrcAccount::IrcAccount(const QString &_userName, const QString &_nickName, const QString +// IrcAccount::IrcAccount(const QString &_userName, const QString &_nickName, +// const QString // &_realName, // const QString &_password) // : userName(_userName) diff --git a/src/providers/irc/IrcAccount.hpp b/src/providers/irc/IrcAccount.hpp index 5906026c6..2c4345b10 100644 --- a/src/providers/irc/IrcAccount.hpp +++ b/src/providers/irc/IrcAccount.hpp @@ -7,7 +7,8 @@ // class IrcAccount //{ // public: -// IrcAccount(const QString &userName, const QString &nickName, const QString &realName, +// IrcAccount(const QString &userName, const QString &nickName, const QString +// &realName, // const QString &password); // const QString &getUserName() const; diff --git a/src/providers/irc/IrcConnection2.cpp b/src/providers/irc/IrcConnection2.cpp index b1d28c20b..4739739aa 100644 --- a/src/providers/irc/IrcConnection2.cpp +++ b/src/providers/irc/IrcConnection2.cpp @@ -27,13 +27,14 @@ IrcConnection::IrcConnection(QObject *parent) } }); - QObject::connect(this, &Communi::IrcConnection::messageReceived, [this](Communi::IrcMessage *) { - this->recentlyReceivedMessage_ = true; + QObject::connect(this, &Communi::IrcConnection::messageReceived, + [this](Communi::IrcMessage *) { + this->recentlyReceivedMessage_ = true; - if (this->reconnectTimer_.isActive()) { - this->reconnectTimer_.stop(); - } - }); + if (this->reconnectTimer_.isActive()) { + this->reconnectTimer_.stop(); + } + }); } } // namespace chatterino diff --git a/src/providers/irc/IrcServer.hpp b/src/providers/irc/IrcServer.hpp index 874179b47..c8faf434c 100644 --- a/src/providers/irc/IrcServer.hpp +++ b/src/providers/irc/IrcServer.hpp @@ -14,7 +14,8 @@ namespace chatterino { // std::shared_ptr getAccount() const; // protected: -// virtual void initializeConnection(Communi::IrcConnection *connection, bool isReadConnection); +// virtual void initializeConnection(Communi::IrcConnection *connection, bool +// isReadConnection); // virtual void privateMessageReceived(Communi::IrcPrivateMessage *message); // virtual void messageReceived(Communi::IrcMessage *message); diff --git a/src/providers/twitch/IrcMessageHandler.cpp b/src/providers/twitch/IrcMessageHandler.cpp index 7460177ab..723156bd7 100644 --- a/src/providers/twitch/IrcMessageHandler.cpp +++ b/src/providers/twitch/IrcMessageHandler.cpp @@ -25,15 +25,17 @@ IrcMessageHandler &IrcMessageHandler::getInstance() return instance; } -void IrcMessageHandler::handlePrivMessage(Communi::IrcPrivateMessage *message, TwitchServer &server) +void IrcMessageHandler::handlePrivMessage(Communi::IrcPrivateMessage *message, + TwitchServer &server) { - this->addMessage(message, message->target(), message->content(), server, false, - message->isAction()); + this->addMessage(message, message->target(), message->content(), server, + false, message->isAction()); } -void IrcMessageHandler::addMessage(Communi::IrcMessage *_message, const QString &target, - const QString &content, TwitchServer &server, bool isSub, - bool isAction) +void IrcMessageHandler::addMessage(Communi::IrcMessage *_message, + const QString &target, + const QString &content, TwitchServer &server, + bool isSub, bool isAction) { QString channelName; if (!trimChannelName(target, channelName)) { @@ -140,14 +142,17 @@ void IrcMessageHandler::handleClearChatMessage(Communi::IrcMessage *message) auto chan = app->twitch.server->getChannelOrEmpty(chanName); if (chan->isEmpty()) { - Log("[IrcMessageHandler:handleClearChatMessage] Twitch channel {} not found", chanName); + Log("[IrcMessageHandler:handleClearChatMessage] Twitch channel {} not " + "found", + chanName); return; } // check if the chat has been cleared by a moderator if (message->parameters().length() == 1) { chan->disableAllMessages(); - chan->addMessage(Message::createSystemMessage("Chat has been cleared by a moderator.")); + chan->addMessage(Message::createSystemMessage( + "Chat has been cleared by a moderator.")); return; } @@ -165,7 +170,8 @@ void IrcMessageHandler::handleClearChatMessage(Communi::IrcMessage *message) reason = v.toString(); } - auto timeoutMsg = Message::createTimeoutMessage(username, durationInSeconds, reason, false); + auto timeoutMsg = Message::createTimeoutMessage(username, durationInSeconds, + reason, false); chan->addOrReplaceTimeout(timeoutMsg); // refresh all @@ -206,7 +212,8 @@ void IrcMessageHandler::handleWhisperMessage(Communi::IrcMessage *message) auto c = app->twitch.server->whispersChannel.get(); - TwitchMessageBuilder builder(c, message, args, message->parameter(1), false); + TwitchMessageBuilder builder(c, message, args, message->parameter(1), + false); if (!builder.isIgnored()) { MessagePtr _message = builder.build(); @@ -229,7 +236,8 @@ void IrcMessageHandler::handleWhisperMessage(Communi::IrcMessage *message) } } -void IrcMessageHandler::handleUserNoticeMessage(Communi::IrcMessage *message, TwitchServer &server) +void IrcMessageHandler::handleUserNoticeMessage(Communi::IrcMessage *message, + TwitchServer &server) { auto data = message->toData(); @@ -244,7 +252,8 @@ void IrcMessageHandler::handleUserNoticeMessage(Communi::IrcMessage *message, Tw } if (msgType == "sub" || msgType == "resub" || msgType == "subgift") { - // Sub-specific message. I think it's only allowed for "resub" messages atm + // Sub-specific message. I think it's only allowed for "resub" messages + // atm if (!content.isEmpty()) { this->addMessage(message, target, content, server, true, false); } @@ -253,7 +262,8 @@ void IrcMessageHandler::handleUserNoticeMessage(Communi::IrcMessage *message, Tw auto it = tags.find("system-msg"); if (it != tags.end()) { - auto newMessage = Message::createSystemMessage(parseTagString(it.value().toString())); + auto newMessage = + Message::createSystemMessage(parseTagString(it.value().toString())); newMessage->flags |= Message::Subscription; @@ -279,7 +289,8 @@ void IrcMessageHandler::handleModeMessage(Communi::IrcMessage *message) { auto app = getApp(); - auto channel = app->twitch.server->getChannelOrEmpty(message->parameter(0).remove(0, 1)); + auto channel = app->twitch.server->getChannelOrEmpty( + message->parameter(0).remove(0, 1)); if (channel->isEmpty()) { return; @@ -299,10 +310,12 @@ void IrcMessageHandler::handleNoticeMessage(Communi::IrcNoticeMessage *message) QString channelName; if (!trimChannelName(message->target(), channelName)) { - // Notice wasn't targeted at a single channel, send to all twitch channels - app->twitch.server->forEachChannelAndSpecialChannels([msg](const auto &c) { - c->addMessage(msg); // - }); + // Notice wasn't targeted at a single channel, send to all twitch + // channels + app->twitch.server->forEachChannelAndSpecialChannels( + [msg](const auto &c) { + c->addMessage(msg); // + }); return; } @@ -310,7 +323,8 @@ void IrcMessageHandler::handleNoticeMessage(Communi::IrcNoticeMessage *message) auto channel = app->twitch.server->getChannelOrEmpty(channelName); if (channel->isEmpty()) { - Log("[IrcManager:handleNoticeMessage] Channel {} not found in channel manager ", + Log("[IrcManager:handleNoticeMessage] Channel {} not found in channel " + "manager ", channelName); return; } @@ -318,7 +332,8 @@ void IrcMessageHandler::handleNoticeMessage(Communi::IrcNoticeMessage *message) channel->addMessage(msg); } -void IrcMessageHandler::handleWriteConnectionNoticeMessage(Communi::IrcNoticeMessage *message) +void IrcMessageHandler::handleWriteConnectionNoticeMessage( + Communi::IrcNoticeMessage *message) { static std::unordered_set readConnectionOnlyIDs{ "host_on", @@ -333,8 +348,9 @@ void IrcMessageHandler::handleWriteConnectionNoticeMessage(Communi::IrcNoticeMes "r9k_on", "r9k_off", - // Display for user who times someone out. This implies you're a moderator, at which point - // you will be connected to PubSub and receive a better message from there + // Display for user who times someone out. This implies you're a + // moderator, at which point you will be connected to PubSub and receive + // a better message from there "timeout_success", "ban_success", }; @@ -347,7 +363,8 @@ void IrcMessageHandler::handleWriteConnectionNoticeMessage(Communi::IrcNoticeMes return; } - Log("Showing notice message from write connection with message id '{}'", msgID); + Log("Showing notice message from write connection with message id '{}'", + msgID); } this->handleNoticeMessage(message); @@ -356,9 +373,11 @@ void IrcMessageHandler::handleWriteConnectionNoticeMessage(Communi::IrcNoticeMes void IrcMessageHandler::handleJoinMessage(Communi::IrcMessage *message) { auto app = getApp(); - auto channel = app->twitch.server->getChannelOrEmpty(message->parameter(0).remove(0, 1)); + auto channel = app->twitch.server->getChannelOrEmpty( + message->parameter(0).remove(0, 1)); - if (TwitchChannel *twitchChannel = dynamic_cast(channel.get())) { + if (TwitchChannel *twitchChannel = + dynamic_cast(channel.get())) { twitchChannel->addJoinedUser(message->nick()); } } @@ -366,9 +385,11 @@ void IrcMessageHandler::handleJoinMessage(Communi::IrcMessage *message) void IrcMessageHandler::handlePartMessage(Communi::IrcMessage *message) { auto app = getApp(); - auto channel = app->twitch.server->getChannelOrEmpty(message->parameter(0).remove(0, 1)); + auto channel = app->twitch.server->getChannelOrEmpty( + message->parameter(0).remove(0, 1)); - if (TwitchChannel *twitchChannel = dynamic_cast(channel.get())) { + if (TwitchChannel *twitchChannel = + dynamic_cast(channel.get())) { twitchChannel->addPartedUser(message->nick()); } } diff --git a/src/providers/twitch/IrcMessageHandler.hpp b/src/providers/twitch/IrcMessageHandler.hpp index 084c88bcd..40f1efb12 100644 --- a/src/providers/twitch/IrcMessageHandler.hpp +++ b/src/providers/twitch/IrcMessageHandler.hpp @@ -13,13 +13,15 @@ class IrcMessageHandler public: static IrcMessageHandler &getInstance(); - void handlePrivMessage(Communi::IrcPrivateMessage *message, TwitchServer &server); + void handlePrivMessage(Communi::IrcPrivateMessage *message, + TwitchServer &server); void handleRoomStateMessage(Communi::IrcMessage *message); void handleClearChatMessage(Communi::IrcMessage *message); void handleUserStateMessage(Communi::IrcMessage *message); void handleWhisperMessage(Communi::IrcMessage *message); - void handleUserNoticeMessage(Communi::IrcMessage *message, TwitchServer &server); + void handleUserNoticeMessage(Communi::IrcMessage *message, + TwitchServer &server); void handleModeMessage(Communi::IrcMessage *message); void handleNoticeMessage(Communi::IrcNoticeMessage *message); void handleWriteConnectionNoticeMessage(Communi::IrcNoticeMessage *message); @@ -28,8 +30,9 @@ public: void handlePartMessage(Communi::IrcMessage *message); private: - void addMessage(Communi::IrcMessage *message, const QString &target, const QString &content, - TwitchServer &server, bool isResub, bool isAction); + void addMessage(Communi::IrcMessage *message, const QString &target, + const QString &content, TwitchServer &server, bool isResub, + bool isAction); }; } // namespace chatterino diff --git a/src/providers/twitch/PartialTwitchUser.cpp b/src/providers/twitch/PartialTwitchUser.cpp index cc8c06f51..98fa2ba42 100644 --- a/src/providers/twitch/PartialTwitchUser.cpp +++ b/src/providers/twitch/PartialTwitchUser.cpp @@ -25,7 +25,8 @@ PartialTwitchUser PartialTwitchUser::byId(const QString &id) return user; } -void PartialTwitchUser::getId(std::function successCallback, const QObject *caller) +void PartialTwitchUser::getId(std::function successCallback, + const QObject *caller) { assert(!this->username_.isEmpty()); @@ -33,7 +34,8 @@ void PartialTwitchUser::getId(std::function successCallback, cons caller = QThread::currentThread(); } - NetworkRequest request("https://api.twitch.tv/kraken/users?login=" + this->username_); + NetworkRequest request("https://api.twitch.tv/kraken/users?login=" + + this->username_); request.setCaller(caller); request.makeAuthorizedV5(getDefaultClientID()); @@ -56,7 +58,8 @@ void PartialTwitchUser::getId(std::function successCallback, cons auto firstUser = users[0].toObject(); auto id = firstUser.value("_id"); if (!id.isString()) { - Log("API Error: while getting user id, first user object `_id` key is not a " + Log("API Error: while getting user id, first user object `_id` key " + "is not a " "string"); return Failure; } diff --git a/src/providers/twitch/PartialTwitchUser.hpp b/src/providers/twitch/PartialTwitchUser.hpp index a868f6fea..36876dc26 100644 --- a/src/providers/twitch/PartialTwitchUser.hpp +++ b/src/providers/twitch/PartialTwitchUser.hpp @@ -19,7 +19,8 @@ public: static PartialTwitchUser byName(const QString &username); static PartialTwitchUser byId(const QString &id); - void getId(std::function successCallback, const QObject *caller = nullptr); + void getId(std::function successCallback, + const QObject *caller = nullptr); }; } // namespace chatterino diff --git a/src/providers/twitch/PubsubActions.hpp b/src/providers/twitch/PubsubActions.hpp index 095cbad85..688468f0e 100644 --- a/src/providers/twitch/PubsubActions.hpp +++ b/src/providers/twitch/PubsubActions.hpp @@ -21,7 +21,8 @@ struct PubSubAction { QString roomID; }; -// Used when a chat mode (i.e. slowmode, subscribers only mode) is enabled or disabled +// Used when a chat mode (i.e. slowmode, subscribers only mode) is enabled or +// disabled struct ModeChangedAction : PubSubAction { using PubSubAction::PubSubAction; diff --git a/src/providers/twitch/PubsubClient.cpp b/src/providers/twitch/PubsubClient.cpp index 0ea37481a..7cdd343ce 100644 --- a/src/providers/twitch/PubsubClient.cpp +++ b/src/providers/twitch/PubsubClient.cpp @@ -24,7 +24,8 @@ static std::map sentMessages; namespace detail { -PubSubClient::PubSubClient(WebsocketClient &websocketClient, WebsocketHandle handle) +PubSubClient::PubSubClient(WebsocketClient &websocketClient, + WebsocketHandle handle) : websocketClient_(websocketClient) , handle_(handle) { @@ -58,7 +59,8 @@ bool PubSubClient::listen(rapidjson::Document &message) this->numListens_ += numRequestedListens; for (const auto &topic : message["data"]["topics"].GetArray()) { - this->listeners_.emplace_back(Listener{topic.GetString(), false, false, false}); + this->listeners_.emplace_back( + Listener{topic.GetString(), false, false, false}); } auto uuid = CreateUUID(); @@ -135,34 +137,38 @@ void PubSubClient::ping() auto self = this->shared_from_this(); - runAfter(this->websocketClient_.get_io_service(), std::chrono::seconds(15), [self](auto timer) { - if (!self->started_) { - return; - } + 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" - } - }); + 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; - } + runAfter(this->websocketClient_.get_io_service(), std::chrono::minutes(5), + [self](auto timer) { + if (!self->started_) { + return; + } - self->ping(); // - }); + self->ping(); // + }); } bool PubSubClient::send(const char *payload) { WebsocketErrorCode ec; - this->websocketClient_.send(this->handle_, payload, websocketpp::frame::opcode::text, 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 + // TODO(pajlada): Check which error code happened and maybe gracefully + // handle it return false; } @@ -176,13 +182,15 @@ PubSub::PubSub() { qDebug() << "init PubSub"; - this->moderationActionHandlers["clear"] = [this](const auto &data, const auto &roomID) { + this->moderationActionHandlers["clear"] = [this](const auto &data, + const auto &roomID) { ClearChatAction action(data, roomID); this->signals_.moderation.chatCleared.invoke(action); }; - this->moderationActionHandlers["slowoff"] = [this](const auto &data, const auto &roomID) { + this->moderationActionHandlers["slowoff"] = [this](const auto &data, + const auto &roomID) { ModeChangedAction action(data, roomID); action.mode = ModeChangedAction::Mode::Slow; @@ -191,7 +199,8 @@ PubSub::PubSub() this->signals_.moderation.modeChanged.invoke(action); }; - this->moderationActionHandlers["slow"] = [this](const auto &data, const auto &roomID) { + this->moderationActionHandlers["slow"] = [this](const auto &data, + const auto &roomID) { ModeChangedAction action(data, roomID); action.mode = ModeChangedAction::Mode::Slow; @@ -228,7 +237,8 @@ PubSub::PubSub() this->signals_.moderation.modeChanged.invoke(action); }; - this->moderationActionHandlers["r9kbetaoff"] = [this](const auto &data, const auto &roomID) { + this->moderationActionHandlers["r9kbetaoff"] = [this](const auto &data, + const auto &roomID) { ModeChangedAction action(data, roomID); action.mode = ModeChangedAction::Mode::R9K; @@ -237,7 +247,8 @@ PubSub::PubSub() this->signals_.moderation.modeChanged.invoke(action); }; - this->moderationActionHandlers["r9kbeta"] = [this](const auto &data, const auto &roomID) { + this->moderationActionHandlers["r9kbeta"] = [this](const auto &data, + const auto &roomID) { ModeChangedAction action(data, roomID); action.mode = ModeChangedAction::Mode::R9K; @@ -246,17 +257,18 @@ PubSub::PubSub() this->signals_.moderation.modeChanged.invoke(action); }; - this->moderationActionHandlers["subscribersoff"] = [this](const auto &data, - const auto &roomID) { - ModeChangedAction action(data, roomID); + this->moderationActionHandlers["subscribersoff"] = + [this](const auto &data, const auto &roomID) { + ModeChangedAction action(data, roomID); - action.mode = ModeChangedAction::Mode::SubscribersOnly; - action.state = ModeChangedAction::State::Off; + action.mode = ModeChangedAction::Mode::SubscribersOnly; + action.state = ModeChangedAction::State::Off; - this->signals_.moderation.modeChanged.invoke(action); - }; + this->signals_.moderation.modeChanged.invoke(action); + }; - this->moderationActionHandlers["subscribers"] = [this](const auto &data, const auto &roomID) { + this->moderationActionHandlers["subscribers"] = [this](const auto &data, + const auto &roomID) { ModeChangedAction action(data, roomID); action.mode = ModeChangedAction::Mode::SubscribersOnly; @@ -265,16 +277,18 @@ PubSub::PubSub() this->signals_.moderation.modeChanged.invoke(action); }; - this->moderationActionHandlers["emoteonlyoff"] = [this](const auto &data, const auto &roomID) { - ModeChangedAction action(data, roomID); + this->moderationActionHandlers["emoteonlyoff"] = + [this](const auto &data, const auto &roomID) { + ModeChangedAction action(data, roomID); - action.mode = ModeChangedAction::Mode::EmoteOnly; - action.state = ModeChangedAction::State::Off; + action.mode = ModeChangedAction::Mode::EmoteOnly; + action.state = ModeChangedAction::State::Off; - this->signals_.moderation.modeChanged.invoke(action); - }; + this->signals_.moderation.modeChanged.invoke(action); + }; - this->moderationActionHandlers["emoteonly"] = [this](const auto &data, const auto &roomID) { + this->moderationActionHandlers["emoteonly"] = [this](const auto &data, + const auto &roomID) { ModeChangedAction action(data, roomID); action.mode = ModeChangedAction::Mode::EmoteOnly; @@ -283,7 +297,8 @@ PubSub::PubSub() this->signals_.moderation.modeChanged.invoke(action); }; - this->moderationActionHandlers["unmod"] = [this](const auto &data, const auto &roomID) { + this->moderationActionHandlers["unmod"] = [this](const auto &data, + const auto &roomID) { ModerationStateAction action(data, roomID); getTargetUser(data, action.target); @@ -307,7 +322,8 @@ PubSub::PubSub() this->signals_.moderation.moderationStateChanged.invoke(action); }; - this->moderationActionHandlers["mod"] = [this](const auto &data, const auto &roomID) { + this->moderationActionHandlers["mod"] = [this](const auto &data, + const auto &roomID) { ModerationStateAction action(data, roomID); getTargetUser(data, action.target); @@ -331,7 +347,8 @@ PubSub::PubSub() this->signals_.moderation.moderationStateChanged.invoke(action); }; - this->moderationActionHandlers["timeout"] = [this](const auto &data, const auto &roomID) { + this->moderationActionHandlers["timeout"] = [this](const auto &data, + const auto &roomID) { BanAction action(data, roomID); getCreatedByUser(data, action.source); @@ -367,7 +384,8 @@ PubSub::PubSub() } }; - this->moderationActionHandlers["ban"] = [this](const auto &data, const auto &roomID) { + this->moderationActionHandlers["ban"] = [this](const auto &data, + const auto &roomID) { BanAction action(data, roomID); getCreatedByUser(data, action.source); @@ -396,7 +414,8 @@ PubSub::PubSub() } }; - this->moderationActionHandlers["unban"] = [this](const auto &data, const auto &roomID) { + this->moderationActionHandlers["unban"] = [this](const auto &data, + const auto &roomID) { UnbanAction action(data, roomID); getCreatedByUser(data, action.source); @@ -421,7 +440,8 @@ PubSub::PubSub() } }; - this->moderationActionHandlers["untimeout"] = [this](const auto &data, const auto &roomID) { + this->moderationActionHandlers["untimeout"] = [this](const auto &data, + const auto &roomID) { UnbanAction action(data, roomID); getCreatedByUser(data, action.source); @@ -447,16 +467,21 @@ PubSub::PubSub() }; this->websocketClient.set_access_channels(websocketpp::log::alevel::all); - this->websocketClient.clear_access_channels(websocketpp::log::alevel::frame_payload); + this->websocketClient.clear_access_channels( + websocketpp::log::alevel::frame_payload); this->websocketClient.init_asio(); // SSL Handshake - this->websocketClient.set_tls_init_handler(bind(&PubSub::onTLSInit, this, ::_1)); + this->websocketClient.set_tls_init_handler( + bind(&PubSub::onTLSInit, this, ::_1)); - this->websocketClient.set_message_handler(bind(&PubSub::onMessage, this, ::_1, ::_2)); - this->websocketClient.set_open_handler(bind(&PubSub::onConnectionOpen, this, ::_1)); - this->websocketClient.set_close_handler(bind(&PubSub::onConnectionClose, this, ::_1)); + this->websocketClient.set_message_handler( + bind(&PubSub::onMessage, this, ::_1, ::_2)); + this->websocketClient.set_open_handler( + bind(&PubSub::onConnectionOpen, this, ::_1)); + this->websocketClient.set_close_handler( + bind(&PubSub::onConnectionClose, this, ::_1)); // Add an initial client this->addClient(); @@ -477,7 +502,8 @@ void PubSub::addClient() void PubSub::start() { - this->mainThread.reset(new std::thread(std::bind(&PubSub::runThread, this))); + this->mainThread.reset( + new std::thread(std::bind(&PubSub::runThread, this))); } void PubSub::listenToWhispers(std::shared_ptr account) @@ -507,8 +533,8 @@ void PubSub::unlistenAllModerationActions() } } -void PubSub::listenToChannelModerationActions(const QString &channelID, - std::shared_ptr account) +void PubSub::listenToChannelModerationActions( + const QString &channelID, std::shared_ptr account) { assert(!channelID.isEmpty()); assert(account != nullptr); @@ -527,7 +553,8 @@ void PubSub::listenToChannelModerationActions(const QString &channelID, this->listenToTopic(topic, account); } -void PubSub::listenToTopic(const std::string &topic, std::shared_ptr account) +void PubSub::listenToTopic(const std::string &topic, + std::shared_ptr account) { auto message = createListenMessage({topic}, account); @@ -542,7 +569,8 @@ void PubSub::listen(rapidjson::Document &&msg) } Log("Added to the back of the queue"); - this->requests.emplace_back(std::make_unique(std::move(msg))); + this->requests.emplace_back( + std::make_unique(std::move(msg))); } bool PubSub::tryListen(rapidjson::Document &msg) @@ -570,7 +598,8 @@ bool PubSub::isListeningToTopic(const std::string &topic) return false; } -void PubSub::onMessage(websocketpp::connection_hdl hdl, WebsocketMessagePtr websocketMessage) +void PubSub::onMessage(websocketpp::connection_hdl hdl, + WebsocketMessagePtr websocketMessage) { const std::string &payload = websocketMessage->get_payload(); @@ -585,7 +614,9 @@ void PubSub::onMessage(websocketpp::connection_hdl hdl, WebsocketMessagePtr webs } if (!msg.IsObject()) { - Log("Error parsing message '{}' from PubSub. Root object is not an object", payload); + Log("Error parsing message '{}' from PubSub. Root object is not an " + "object", + payload); return; } @@ -615,8 +646,8 @@ void PubSub::onMessage(websocketpp::connection_hdl hdl, WebsocketMessagePtr webs } else if (type == "PONG") { auto clientIt = this->clients.find(hdl); - // If this assert goes off, there's something wrong with the connection creation/preserving - // code KKona + // If this assert goes off, there's something wrong with the connection + // creation/preserving code KKona assert(clientIt != this->clients.end()); auto &client = *clientIt; @@ -629,9 +660,11 @@ void PubSub::onMessage(websocketpp::connection_hdl hdl, WebsocketMessagePtr webs void PubSub::onConnectionOpen(WebsocketHandle hdl) { - auto client = std::make_shared(this->websocketClient, hdl); + auto client = + std::make_shared(this->websocketClient, hdl); - // We separate the starting from the constructor because we will want to use shared_from_this + // We separate the starting from the constructor because we will want to use + // shared_from_this client->start(); this->clients.emplace(hdl, client); @@ -643,8 +676,8 @@ void PubSub::onConnectionClose(WebsocketHandle hdl) { auto clientIt = this->clients.find(hdl); - // If this assert goes off, there's something wrong with the connection creation/preserving - // code KKona + // If this assert goes off, there's something wrong with the connection + // creation/preserving code KKona assert(clientIt != this->clients.end()); auto &client = clientIt->second; @@ -658,7 +691,8 @@ void PubSub::onConnectionClose(WebsocketHandle hdl) PubSub::WebsocketContextPtr PubSub::onTLSInit(websocketpp::connection_hdl hdl) { - WebsocketContextPtr ctx(new boost::asio::ssl::context(boost::asio::ssl::context::tlsv1)); + WebsocketContextPtr ctx( + new boost::asio::ssl::context(boost::asio::ssl::context::tlsv1)); try { ctx->set_options(boost::asio::ssl::context::default_workarounds | diff --git a/src/providers/twitch/PubsubClient.hpp b/src/providers/twitch/PubsubClient.hpp index 3d39b7efb..211502176 100644 --- a/src/providers/twitch/PubsubClient.hpp +++ b/src/providers/twitch/PubsubClient.hpp @@ -22,7 +22,8 @@ namespace chatterino { -using WebsocketClient = websocketpp::client; +using WebsocketClient = + websocketpp::client; using WebsocketHandle = websocketpp::connection_hdl; using WebsocketErrorCode = websocketpp::lib::error_code; @@ -71,11 +72,14 @@ private: class PubSub { - using WebsocketMessagePtr = websocketpp::config::asio_tls_client::message_type::ptr; - using WebsocketContextPtr = websocketpp::lib::shared_ptr; + using WebsocketMessagePtr = + websocketpp::config::asio_tls_client::message_type::ptr; + using WebsocketContextPtr = + websocketpp::lib::shared_ptr; template - using Signal = pajlada::Signals::Signal; // type-id is vector> + using Signal = + pajlada::Signals::Signal; // type-id is vector> WebsocketClient websocketClient; std::unique_ptr mainThread; @@ -121,13 +125,14 @@ public: void unlistenAllModerationActions(); - void listenToChannelModerationActions(const QString &channelID, - std::shared_ptr account); + void listenToChannelModerationActions( + const QString &channelID, std::shared_ptr account); std::vector> requests; private: - void listenToTopic(const std::string &topic, std::shared_ptr account); + void listenToTopic(const std::string &topic, + std::shared_ptr account); void listen(rapidjson::Document &&msg); bool tryListen(rapidjson::Document &msg); @@ -142,7 +147,8 @@ private: std::owner_less> clients; - std::unordered_map> + std::unordered_map> moderationActionHandlers; void onMessage(websocketpp::connection_hdl hdl, WebsocketMessagePtr msg); diff --git a/src/providers/twitch/PubsubHelpers.cpp b/src/providers/twitch/PubsubHelpers.cpp index e93340fe4..cf4560f6b 100644 --- a/src/providers/twitch/PubsubHelpers.cpp +++ b/src/providers/twitch/PubsubHelpers.cpp @@ -31,8 +31,9 @@ bool getTargetUser(const rapidjson::Value &data, ActionUser &user) return rj::getSafe(data, "target_user_id", user.id); } -rapidjson::Document createListenMessage(const std::vector &topicsVec, - std::shared_ptr account) +rapidjson::Document createListenMessage( + const std::vector &topicsVec, + std::shared_ptr account) { rapidjson::Document msg(rapidjson::kObjectType); auto &a = msg.GetAllocator(); @@ -57,7 +58,8 @@ rapidjson::Document createListenMessage(const std::vector &topicsVe return msg; } -rapidjson::Document createUnlistenMessage(const std::vector &topicsVec) +rapidjson::Document createUnlistenMessage( + const std::vector &topicsVec) { rapidjson::Document msg(rapidjson::kObjectType); auto &a = msg.GetAllocator(); diff --git a/src/providers/twitch/PubsubHelpers.hpp b/src/providers/twitch/PubsubHelpers.hpp index 07bda24b1..a891edd4f 100644 --- a/src/providers/twitch/PubsubHelpers.hpp +++ b/src/providers/twitch/PubsubHelpers.hpp @@ -19,13 +19,16 @@ bool getCreatedByUser(const rapidjson::Value &data, ActionUser &user); bool getTargetUser(const rapidjson::Value &data, ActionUser &user); -rapidjson::Document createListenMessage(const std::vector &topicsVec, - std::shared_ptr account); -rapidjson::Document createUnlistenMessage(const std::vector &topicsVec); +rapidjson::Document createListenMessage( + const std::vector &topicsVec, + std::shared_ptr account); +rapidjson::Document createUnlistenMessage( + const std::vector &topicsVec); // Create timer using given ioService template -void runAfter(boost::asio::io_service &ioService, Duration duration, Callback cb) +void runAfter(boost::asio::io_service &ioService, Duration duration, + Callback cb) { auto timer = std::make_shared(ioService); timer->expires_from_now(duration); @@ -42,7 +45,8 @@ void runAfter(boost::asio::io_service &ioService, Duration duration, Callback cb // Use provided timer template -void runAfter(std::shared_ptr timer, Duration duration, Callback cb) +void runAfter(std::shared_ptr timer, + Duration duration, Callback cb) { timer->expires_from_now(duration); diff --git a/src/providers/twitch/TwitchAccount.cpp b/src/providers/twitch/TwitchAccount.cpp index bb8510231..8cde777d1 100644 --- a/src/providers/twitch/TwitchAccount.cpp +++ b/src/providers/twitch/TwitchAccount.cpp @@ -20,10 +20,12 @@ EmoteName cleanUpCode(const EmoteName &dirtyEmoteCode) 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"}, {"\\;-?\\)", ";)"}, + {"[oO](_|\\.)[oO]", "O_o"}, {"\\>\\;\\(", ">("}, + {"\\<\\;3", "<3"}, {"\\:-?(o|O)", ":O"}, + {"\\:-?(p|P)", ":P"}, {"\\:-?[\\\\/]", ":/"}, + {"\\:-?[z|Z|\\|]", ":Z"}, {"\\:-?\\(", ":("}, + {"\\:-?\\)", ":)"}, {"\\:-?D", ":D"}, + {"\\;-?(p|P)", ";P"}, {"\\;-?\\)", ";)"}, {"R-?\\)", "R)"}, {"B-?\\)", "B)"}, }; @@ -105,7 +107,8 @@ bool TwitchAccount::isAnon() const void TwitchAccount::loadIgnores() { - QString url("https://api.twitch.tv/kraken/users/" + this->getUserId() + "/blocks"); + QString url("https://api.twitch.tv/kraken/users/" + this->getUserId() + + "/blocks"); NetworkRequest req(url); req.setCaller(QThread::currentThread()); @@ -140,7 +143,8 @@ void TwitchAccount::loadIgnores() } TwitchUser ignoredUser; if (!rj::getSafe(userIt->value, ignoredUser)) { - Log("Error parsing twitch user JSON {}", rj::stringify(userIt->value)); + Log("Error parsing twitch user JSON {}", + rj::stringify(userIt->value)); continue; } @@ -154,28 +158,32 @@ void TwitchAccount::loadIgnores() req.execute(); } -void TwitchAccount::ignore(const QString &targetName, - std::function onFinished) +void TwitchAccount::ignore( + const QString &targetName, + std::function onFinished) { - const auto onIdFetched = [this, targetName, onFinished](QString targetUserId) { + const auto onIdFetched = [this, targetName, + onFinished](QString targetUserId) { this->ignoreByID(targetUserId, targetName, onFinished); // }; PartialTwitchUser::byName(targetName).getId(onIdFetched); } -void TwitchAccount::ignoreByID(const QString &targetUserID, const QString &targetName, - std::function onFinished) +void TwitchAccount::ignoreByID( + const QString &targetUserID, const QString &targetName, + std::function onFinished) { - QString url("https://api.twitch.tv/kraken/users/" + this->getUserId() + "/blocks/" + - targetUserID); + QString url("https://api.twitch.tv/kraken/users/" + this->getUserId() + + "/blocks/" + targetUserID); NetworkRequest req(url, NetworkRequestType::Put); req.setCaller(QThread::currentThread()); req.makeAuthorizedV5(this->getOAuthClient(), this->getOAuthToken()); req.onError([=](int errorCode) { - onFinished(IgnoreResult_Failed, "An unknown error occured while trying to ignore user " + - targetName + " (" + QString::number(errorCode) + ")"); + onFinished(IgnoreResult_Failed, + "An unknown error occured while trying to ignore user " + + targetName + " (" + QString::number(errorCode) + ")"); return true; }); @@ -183,21 +191,24 @@ void TwitchAccount::ignoreByID(const QString &targetUserID, const QString &targe req.onSuccess([=](auto result) -> Outcome { auto document = result.parseRapidJson(); if (!document.IsObject()) { - onFinished(IgnoreResult_Failed, "Bad JSON data while ignoring user " + targetName); + onFinished(IgnoreResult_Failed, + "Bad JSON data while ignoring user " + targetName); return Failure; } auto userIt = document.FindMember("user"); if (userIt == document.MemberEnd()) { onFinished(IgnoreResult_Failed, - "Bad JSON data while ignoring user (missing user) " + targetName); + "Bad JSON data while ignoring user (missing user) " + + targetName); return Failure; } TwitchUser ignoredUser; if (!rj::getSafe(userIt->value, ignoredUser)) { onFinished(IgnoreResult_Failed, - "Bad JSON data while ignoring user (invalid user) " + targetName); + "Bad JSON data while ignoring user (invalid user) " + + targetName); return Failure; } { @@ -212,7 +223,8 @@ void TwitchAccount::ignoreByID(const QString &targetUserID, const QString &targe return Failure; } } - onFinished(IgnoreResult_Success, "Successfully ignored user " + targetName); + onFinished(IgnoreResult_Success, + "Successfully ignored user " + targetName); return Success; }); @@ -220,10 +232,12 @@ void TwitchAccount::ignoreByID(const QString &targetUserID, const QString &targe req.execute(); } -void TwitchAccount::unignore(const QString &targetName, - std::function onFinished) +void TwitchAccount::unignore( + const QString &targetName, + std::function onFinished) { - const auto onIdFetched = [this, targetName, onFinished](QString targetUserId) { + const auto onIdFetched = [this, targetName, + onFinished](QString targetUserId) { this->unignoreByID(targetUserId, targetName, onFinished); // }; @@ -234,8 +248,8 @@ void TwitchAccount::unignoreByID( const QString &targetUserID, const QString &targetName, std::function onFinished) { - QString url("https://api.twitch.tv/kraken/users/" + this->getUserId() + "/blocks/" + - targetUserID); + QString url("https://api.twitch.tv/kraken/users/" + this->getUserId() + + "/blocks/" + targetUserID); NetworkRequest req(url, NetworkRequestType::Delete); req.setCaller(QThread::currentThread()); @@ -243,8 +257,8 @@ void TwitchAccount::unignoreByID( req.onError([=](int errorCode) { onFinished(UnignoreResult_Failed, - "An unknown error occured while trying to unignore user " + targetName + " (" + - QString::number(errorCode) + ")"); + "An unknown error occured while trying to unignore user " + + targetName + " (" + QString::number(errorCode) + ")"); return true; }); @@ -258,7 +272,8 @@ void TwitchAccount::unignoreByID( this->ignores_.erase(ignoredUser); } - onFinished(UnignoreResult_Success, "Successfully unignored user " + targetName); + onFinished(UnignoreResult_Success, + "Successfully unignored user " + targetName); return Success; }); @@ -269,8 +284,8 @@ void TwitchAccount::unignoreByID( void TwitchAccount::checkFollow(const QString targetUserID, std::function onFinished) { - QString url("https://api.twitch.tv/kraken/users/" + this->getUserId() + "/follows/channels/" + - targetUserID); + QString url("https://api.twitch.tv/kraken/users/" + this->getUserId() + + "/follows/channels/" + targetUserID); NetworkRequest req(url); req.setCaller(QThread::currentThread()); @@ -295,7 +310,8 @@ void TwitchAccount::checkFollow(const QString targetUserID, req.execute(); } -void TwitchAccount::followUser(const QString userID, std::function successCallback) +void TwitchAccount::followUser(const QString userID, + std::function successCallback) { QUrl requestUrl("https://api.twitch.tv/kraken/users/" + this->getUserId() + "/follows/channels/" + userID); @@ -315,7 +331,8 @@ void TwitchAccount::followUser(const QString userID, std::function succe request.execute(); } -void TwitchAccount::unfollowUser(const QString userID, std::function successCallback) +void TwitchAccount::unfollowUser(const QString userID, + std::function successCallback) { QUrl requestUrl("https://api.twitch.tv/kraken/users/" + this->getUserId() + "/follows/channels/" + userID); @@ -361,7 +378,8 @@ void TwitchAccount::loadEmotes() return; } - QString url("https://api.twitch.tv/kraken/users/" + this->getUserId() + "/emotes"); + QString url("https://api.twitch.tv/kraken/users/" + this->getUserId() + + "/emotes"); NetworkRequest req(url); req.setCaller(QThread::currentThread()); @@ -387,7 +405,8 @@ void TwitchAccount::loadEmotes() req.execute(); } -AccessGuard TwitchAccount::accessEmotes() const +AccessGuard +TwitchAccount::accessEmotes() const { return this->emotes_.accessConst(); } @@ -412,7 +431,8 @@ void TwitchAccount::parseEmotes(const rapidjson::Document &root) this->loadEmoteSetData(emoteSet); - for (const rapidjson::Value &emoteJSON : emoteSetJSON.value.GetArray()) { + for (const rapidjson::Value &emoteJSON : + emoteSetJSON.value.GetArray()) { if (!emoteJSON.IsObject()) { Log("Emote value was invalid"); return; @@ -459,8 +479,9 @@ void TwitchAccount::loadEmoteSetData(std::shared_ptr emoteSet) return; } - NetworkRequest req("https://braize.pajlada.com/chatterino/twitchemotes/set/" + emoteSet->key + - "/"); + NetworkRequest req( + "https://braize.pajlada.com/chatterino/twitchemotes/set/" + + emoteSet->key + "/"); req.setUseQuickLoadCache(true); req.onError([](int errorCode) -> bool { @@ -488,9 +509,11 @@ void TwitchAccount::loadEmoteSetData(std::shared_ptr emoteSet) Log("Loaded twitch emote set data for {}!", emoteSet->key); if (type == "sub") { - emoteSet->text = QString("Twitch Subscriber Emote (%1)").arg(channelName); + emoteSet->text = + QString("Twitch Subscriber Emote (%1)").arg(channelName); } else { - emoteSet->text = QString("Twitch Account Emote (%1)").arg(channelName); + emoteSet->text = + QString("Twitch Account Emote (%1)").arg(channelName); } emoteSet->channelName = channelName; diff --git a/src/providers/twitch/TwitchAccount.hpp b/src/providers/twitch/TwitchAccount.hpp index be97a0653..1a180f5e2 100644 --- a/src/providers/twitch/TwitchAccount.hpp +++ b/src/providers/twitch/TwitchAccount.hpp @@ -57,8 +57,8 @@ public: EmoteMap emotes; }; - TwitchAccount(const QString &username, const QString &oauthToken_, const QString &oauthClient_, - const QString &_userID); + TwitchAccount(const QString &username, const QString &oauthToken_, + const QString &oauthClient_, const QString &_userID); virtual QString toString() const override; @@ -81,16 +81,22 @@ public: void loadIgnores(); void ignore(const QString &targetName, std::function onFinished); - void ignoreByID(const QString &targetUserID, const QString &targetName, - std::function onFinished); - void unignore(const QString &targetName, - std::function onFinished); - void unignoreByID(const QString &targetUserID, const QString &targetName, - std::function onFinished); + void ignoreByID( + const QString &targetUserID, const QString &targetName, + std::function onFinished); + void unignore( + const QString &targetName, + std::function onFinished); + void unignoreByID( + const QString &targetUserID, const QString &targetName, + std::function onFinished); - void checkFollow(const QString targetUserID, std::function onFinished); - void followUser(const QString userID, std::function successCallback); - void unfollowUser(const QString userID, std::function successCallback); + void checkFollow(const QString targetUserID, + std::function onFinished); + void followUser(const QString userID, + std::function successCallback); + void unfollowUser(const QString userID, + std::function successCallback); std::set getIgnores() const; diff --git a/src/providers/twitch/TwitchAccountManager.cpp b/src/providers/twitch/TwitchAccountManager.cpp index 2f177a146..7d4f932eb 100644 --- a/src/providers/twitch/TwitchAccountManager.cpp +++ b/src/providers/twitch/TwitchAccountManager.cpp @@ -72,16 +72,17 @@ void TwitchAccountManager::reloadUsers() continue; } - std::string username = - pajlada::Settings::Setting::get("/accounts/" + uid + "/username"); - std::string userID = - pajlada::Settings::Setting::get("/accounts/" + uid + "/userID"); - std::string clientID = - pajlada::Settings::Setting::get("/accounts/" + uid + "/clientID"); - std::string oauthToken = - pajlada::Settings::Setting::get("/accounts/" + uid + "/oauthToken"); + std::string username = pajlada::Settings::Setting::get( + "/accounts/" + uid + "/username"); + std::string userID = pajlada::Settings::Setting::get( + "/accounts/" + uid + "/userID"); + std::string clientID = pajlada::Settings::Setting::get( + "/accounts/" + uid + "/clientID"); + std::string oauthToken = pajlada::Settings::Setting::get( + "/accounts/" + uid + "/oauthToken"); - if (username.empty() || userID.empty() || clientID.empty() || oauthToken.empty()) { + if (username.empty() || userID.empty() || clientID.empty() || + oauthToken.empty()) { continue; } @@ -96,9 +97,11 @@ void TwitchAccountManager::reloadUsers() // Do nothing } break; case AddUserResponse::UserValuesUpdated: { - Log("User {} already exists, and values updated!", userData.username); + Log("User {} already exists, and values updated!", + userData.username); if (userData.username == this->getCurrent()->getUserName()) { - Log("It was the current user, so we need to reconnect stuff!"); + Log("It was the current user, so we need to reconnect " + "stuff!"); this->currentUserChanged.invoke(); } } break; @@ -122,11 +125,13 @@ void TwitchAccountManager::load() QString newUsername(QString::fromStdString(newValue)); auto user = this->findUserByUsername(newUsername); if (user) { - Log("[AccountManager:currentUsernameChanged] User successfully updated to {}", + Log("[AccountManager:currentUsernameChanged] User successfully " + "updated to {}", newUsername); this->currentUser_ = user; } else { - Log("[AccountManager:currentUsernameChanged] User successfully updated to anonymous"); + Log("[AccountManager:currentUsernameChanged] User successfully " + "updated to anonymous"); this->currentUser_ = this->anonymousUser_; } @@ -140,8 +145,8 @@ bool TwitchAccountManager::isLoggedIn() const return false; } - // Once `TwitchAccount` class has a way to check, we should also return false if the credentials - // are incorrect + // Once `TwitchAccount` class has a way to check, we should also return + // false if the credentials are incorrect return !this->currentUser_->isAnon(); } @@ -151,11 +156,13 @@ bool TwitchAccountManager::removeUser(TwitchAccount *account) std::string userID(account->getUserId().toStdString()); if (!userID.empty()) { - pajlada::Settings::SettingManager::removeSetting("/accounts/uid" + userID); + pajlada::Settings::SettingManager::removeSetting("/accounts/uid" + + userID); } if (account->getUserName() == qS(this->currentUsername.getValue())) { - // The user that was removed is the current user, log into the anonymous user + // The user that was removed is the current user, log into the anonymous + // user this->currentUsername = ""; } @@ -186,8 +193,9 @@ TwitchAccountManager::AddUserResponse TwitchAccountManager::addUser( } } - auto newUser = std::make_shared(userData.username, userData.oauthToken, - userData.clientID, userData.userID); + auto newUser = + std::make_shared(userData.username, userData.oauthToken, + userData.clientID, userData.userID); // std::lock_guard lock(this->mutex); diff --git a/src/providers/twitch/TwitchAccountManager.hpp b/src/providers/twitch/TwitchAccountManager.hpp index 1cb1df1c2..32961f092 100644 --- a/src/providers/twitch/TwitchAccountManager.hpp +++ b/src/providers/twitch/TwitchAccountManager.hpp @@ -11,7 +11,8 @@ // // Warning: This class is not supposed to be created directly. -// Get yourself an instance from our friends over at AccountManager.hpp +// Get yourself an instance from our friends over at +// AccountManager.hpp // namespace chatterino { @@ -30,12 +31,14 @@ public: QString oauthToken; }; - // Returns the current twitchUsers, or the anonymous user if we're not currently logged in + // Returns the current twitchUsers, or the anonymous user if we're not + // currently logged in std::shared_ptr getCurrent(); std::vector getUsernames() const; - std::shared_ptr findUserByUsername(const QString &username) const; + std::shared_ptr findUserByUsername( + const QString &username) const; bool userExists(const QString &username) const; void reloadUsers(); @@ -43,11 +46,13 @@ public: bool isLoggedIn() const; - pajlada::Settings::Setting currentUsername = {"/accounts/current", ""}; + pajlada::Settings::Setting currentUsername = { + "/accounts/current", ""}; pajlada::Signals::NoArgSignal currentUserChanged; pajlada::Signals::NoArgSignal userListUpdated; - SortedSignalVector, SharedPtrElementLess> + SortedSignalVector, + SharedPtrElementLess> accounts; private: diff --git a/src/providers/twitch/TwitchApi.cpp b/src/providers/twitch/TwitchApi.cpp index 58ab03af1..6b1e537c3 100644 --- a/src/providers/twitch/TwitchApi.cpp +++ b/src/providers/twitch/TwitchApi.cpp @@ -8,7 +8,8 @@ namespace chatterino { -void TwitchApi::findUserId(const QString user, std::function successCallback) +void TwitchApi::findUserId(const QString user, + std::function successCallback) { QString requestUrl("https://api.twitch.tv/kraken/users?login=" + user); @@ -37,7 +38,8 @@ void TwitchApi::findUserId(const QString user, std::function succ auto firstUser = users[0].toObject(); auto id = firstUser.value("_id"); if (!id.isString()) { - Log("API Error: while getting user id, first user object `_id` key is not a " + Log("API Error: while getting user id, first user object `_id` key " + "is not a " "string"); successCallback(""); return Failure; diff --git a/src/providers/twitch/TwitchApi.hpp b/src/providers/twitch/TwitchApi.hpp index 00b8ff4d7..67b26c1ca 100644 --- a/src/providers/twitch/TwitchApi.hpp +++ b/src/providers/twitch/TwitchApi.hpp @@ -7,7 +7,8 @@ namespace chatterino { class TwitchApi { public: - static void findUserId(const QString user, std::function callback); + static void findUserId(const QString user, + std::function callback); private: }; diff --git a/src/providers/twitch/TwitchBadges.cpp b/src/providers/twitch/TwitchBadges.cpp index db329d306..fd9fe7461 100644 --- a/src/providers/twitch/TwitchBadges.cpp +++ b/src/providers/twitch/TwitchBadges.cpp @@ -19,7 +19,8 @@ void TwitchBadges::initialize(Settings &settings, Paths &paths) void TwitchBadges::loadTwitchBadges() { - static QString url("https://badges.twitch.tv/v1/badges/global/display?language=en"); + static QString url( + "https://badges.twitch.tv/v1/badges/global/display?language=en"); NetworkRequest req(url); req.setCaller(QThread::currentThread()); @@ -28,24 +29,29 @@ void TwitchBadges::loadTwitchBadges() QJsonObject sets = root.value("badge_sets").toObject(); for (QJsonObject::iterator it = sets.begin(); it != sets.end(); ++it) { - QJsonObject versions = it.value().toObject().value("versions").toObject(); + QJsonObject versions = + it.value().toObject().value("versions").toObject(); - for (auto versionIt = std::begin(versions); versionIt != std::end(versions); - ++versionIt) { - auto emote = - Emote{{""}, - ImageSet{ - Image::fromUrl({root.value("image_url_1x").toString()}, 1), - Image::fromUrl({root.value("image_url_2x").toString()}, 0.5), - Image::fromUrl({root.value("image_url_4x").toString()}, 0.25), - }, - Tooltip{root.value("description").toString()}, - Url{root.value("clickURL").toString()}}; + for (auto versionIt = std::begin(versions); + versionIt != std::end(versions); ++versionIt) { + auto emote = Emote{ + {""}, + ImageSet{ + Image::fromUrl({root.value("image_url_1x").toString()}, + 1), + Image::fromUrl({root.value("image_url_2x").toString()}, + 0.5), + Image::fromUrl({root.value("image_url_4x").toString()}, + 0.25), + }, + Tooltip{root.value("description").toString()}, + Url{root.value("clickURL").toString()}}; // "title" // "clickAction" QJsonObject versionObj = versionIt.value().toObject(); - this->badges.emplace(versionIt.key(), std::make_shared(emote)); + this->badges.emplace(versionIt.key(), + std::make_shared(emote)); } } diff --git a/src/providers/twitch/TwitchChannel.cpp b/src/providers/twitch/TwitchChannel.cpp index f5a501731..274dd4264 100644 --- a/src/providers/twitch/TwitchChannel.cpp +++ b/src/providers/twitch/TwitchChannel.cpp @@ -57,7 +57,8 @@ TwitchChannel::TwitchChannel(const QString &name) [=] { this->refreshViewerList(); }); this->chattersListTimer_.start(5 * 60 * 1000); - QObject::connect(&this->liveStatusTimer_, &QTimer::timeout, [=] { this->refreshLiveStatus(); }); + QObject::connect(&this->liveStatusTimer_, &QTimer::timeout, + [=] { this->refreshLiveStatus(); }); this->liveStatusTimer_.start(60 * 1000); // -- @@ -84,15 +85,16 @@ bool TwitchChannel::canSendMessage() const void TwitchChannel::refreshChannelEmotes() { - loadBttvChannelEmotes(this->getName(), [this, weak = weakOf(this)](auto &&emoteMap) { - if (auto shared = weak.lock()) // - *this->bttvEmotes_.access() = emoteMap; - }); - getApp()->emotes->ffz.loadChannelEmotes(this->getName(), - [this, weak = weakOf(this)](auto &&emoteMap) { - if (auto shared = weak.lock()) - *this->ffzEmotes_.access() = emoteMap; - }); + loadBttvChannelEmotes( + this->getName(), [this, weak = weakOf(this)](auto &&emoteMap) { + if (auto shared = weak.lock()) // + *this->bttvEmotes_.access() = emoteMap; + }); + getApp()->emotes->ffz.loadChannelEmotes( + this->getName(), [this, weak = weakOf(this)](auto &&emoteMap) { + if (auto shared = weak.lock()) + *this->ffzEmotes_.access() = emoteMap; + }); } void TwitchChannel::sendMessage(const QString &message) @@ -100,11 +102,11 @@ void TwitchChannel::sendMessage(const QString &message) auto app = getApp(); if (!app->accounts->twitch.isLoggedIn()) { - // XXX: It would be nice if we could add a link here somehow that opened the "account - // manager" dialog - this->addMessage( - Message::createSystemMessage("You need to log in to send messages. You can " - "link your Twitch account in the settings.")); + // XXX: It would be nice if we could add a link here somehow that opened + // the "account manager" dialog + this->addMessage(Message::createSystemMessage( + "You need to log in to send messages. You can " + "link your Twitch account in the settings.")); return; } @@ -181,7 +183,8 @@ void TwitchChannel::addJoinedUser(const QString &user) QTimer::singleShot(500, &this->lifetimeGuard_, [this] { auto joinedUsers = this->joinedUsers_.access(); - auto message = Message::createSystemMessage("Users joined: " + joinedUsers->join(", ")); + auto message = Message::createSystemMessage( + "Users joined: " + joinedUsers->join(", ")); message->flags |= Message::Collapsed; joinedUsers->clear(); this->addMessage(message); @@ -208,7 +211,8 @@ void TwitchChannel::addPartedUser(const QString &user) QTimer::singleShot(500, &this->lifetimeGuard_, [this] { auto partedUsers = this->partedUsers_.access(); - auto message = Message::createSystemMessage("Users parted: " + partedUsers->join(", ")); + auto message = Message::createSystemMessage( + "Users parted: " + partedUsers->join(", ")); message->flags |= Message::Collapsed; this->addMessage(message); partedUsers->clear(); @@ -230,7 +234,8 @@ void TwitchChannel::setRoomId(const QString &id) this->loadRecentMessages(); } -AccessGuard TwitchChannel::accessRoomModes() const +AccessGuard TwitchChannel::accessRoomModes() + const { return this->roomModes_.accessConst(); } @@ -247,12 +252,14 @@ bool TwitchChannel::isLive() const return this->streamStatus_.access()->live; } -AccessGuard TwitchChannel::accessStreamStatus() const +AccessGuard +TwitchChannel::accessStreamStatus() const { return this->streamStatus_.accessConst(); } -boost::optional TwitchChannel::getBttvEmote(const EmoteName &name) const +boost::optional TwitchChannel::getBttvEmote( + const EmoteName &name) const { auto emotes = this->bttvEmotes_.access(); auto it = emotes->find(name); @@ -261,7 +268,8 @@ boost::optional TwitchChannel::getBttvEmote(const EmoteName &name) con return it->second; } -boost::optional TwitchChannel::getFfzEmote(const EmoteName &name) const +boost::optional TwitchChannel::getFfzEmote( + const EmoteName &name) const { auto emotes = this->bttvEmotes_.access(); auto it = emotes->find(name); @@ -316,7 +324,8 @@ void TwitchChannel::refreshLiveStatus() auto roomID = this->getRoomId(); if (roomID.isEmpty()) { - Log("[TwitchChannel:{}] Refreshing live status (Missing ID)", this->getName()); + Log("[TwitchChannel:{}] Refreshing live status (Missing ID)", + this->getName()); this->setLive(false); return; } @@ -332,12 +341,13 @@ void TwitchChannel::refreshLiveStatus() request.setCaller(QThread::currentThread()); //>>>>>>> 9bfbdefd2f0972a738230d5b95a009f73b1dd933 - request.onSuccess([this, weak = this->weak_from_this()](auto result) -> Outcome { - ChannelPtr shared = weak.lock(); - if (!shared) return Failure; + request.onSuccess( + [this, weak = this->weak_from_this()](auto result) -> Outcome { + ChannelPtr shared = weak.lock(); + if (!shared) return Failure; - return this->parseLiveStatus(result.parseRapidJson()); - }); + return this->parseLiveStatus(result.parseRapidJson()); + }); request.execute(); } @@ -362,8 +372,8 @@ Outcome TwitchChannel::parseLiveStatus(const rapidjson::Document &document) return Failure; } - if (!stream.HasMember("viewers") || !stream.HasMember("game") || !stream.HasMember("channel") || - !stream.HasMember("created_at")) { + if (!stream.HasMember("viewers") || !stream.HasMember("game") || + !stream.HasMember("channel") || !stream.HasMember("created_at")) { Log("[TwitchChannel:refreshLiveStatus] Missing members in stream"); this->setLive(false); return Failure; @@ -372,7 +382,8 @@ Outcome TwitchChannel::parseLiveStatus(const rapidjson::Document &document) const rapidjson::Value &streamChannel = stream["channel"]; if (!streamChannel.IsObject() || !streamChannel.HasMember("status")) { - Log("[TwitchChannel:refreshLiveStatus] Missing member \"status\" in channel"); + Log("[TwitchChannel:refreshLiveStatus] Missing member \"status\" in " + "channel"); return Failure; } @@ -384,10 +395,11 @@ Outcome TwitchChannel::parseLiveStatus(const rapidjson::Document &document) status->viewerCount = stream["viewers"].GetUint(); status->game = stream["game"].GetString(); status->title = streamChannel["status"].GetString(); - QDateTime since = QDateTime::fromString(stream["created_at"].GetString(), Qt::ISODate); + QDateTime since = QDateTime::fromString( + stream["created_at"].GetString(), Qt::ISODate); auto diff = since.secsTo(QDateTime::currentDateTime()); - status->uptime = - QString::number(diff / 3600) + "h " + QString::number(diff % 3600 / 60) + "m"; + status->uptime = QString::number(diff / 3600) + "h " + + QString::number(diff % 3600 / 60) + "m"; status->rerun = false; if (stream.HasMember("stream_type")) { @@ -400,7 +412,8 @@ Outcome TwitchChannel::parseLiveStatus(const rapidjson::Document &document) const auto &broadcastPlatformValue = stream["broadcast_platform"]; if (broadcastPlatformValue.IsString()) { - const char *broadcastPlatform = stream["broadcast_platform"].GetString(); + const char *broadcastPlatform = + stream["broadcast_platform"].GetString(); if (strcmp(broadcastPlatform, "rerun") == 0) { status->rerun = true; } @@ -417,18 +430,20 @@ Outcome TwitchChannel::parseLiveStatus(const rapidjson::Document &document) void TwitchChannel::loadRecentMessages() { static QString genericURL = - "https://tmi.twitch.tv/api/rooms/%1/recent_messages?client_id=" + getDefaultClientID(); + "https://tmi.twitch.tv/api/rooms/%1/recent_messages?client_id=" + + getDefaultClientID(); NetworkRequest request(genericURL.arg(this->getRoomId())); request.makeAuthorizedV5(getDefaultClientID()); request.setCaller(QThread::currentThread()); - request.onSuccess([this, weak = weakOf(this)](auto result) -> Outcome { - ChannelPtr shared = weak.lock(); - if (!shared) return Failure; + request.onSuccess( + [this, weak = weakOf(this)](auto result) -> Outcome { + ChannelPtr shared = weak.lock(); + if (!shared) return Failure; - return this->parseRecentMessages(result.parseJson()); - }); + return this->parseRecentMessages(result.parseJson()); + }); request.execute(); } @@ -442,8 +457,8 @@ Outcome TwitchChannel::parseRecentMessages(const QJsonObject &jsonRoot) 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 + // 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); @@ -468,7 +483,8 @@ void TwitchChannel::refreshPubsub() if (roomId.isEmpty()) return; auto account = getApp()->accounts->twitch.getCurrent(); - getApp()->twitch2->pubsub->listenToChannelModerationActions(roomId, account); + getApp()->twitch2->pubsub->listenToChannelModerationActions(roomId, + account); } void TwitchChannel::refreshViewerList() @@ -477,35 +493,40 @@ void TwitchChannel::refreshViewerList() const auto streamStatus = this->accessStreamStatus(); if (getSettings()->onlyFetchChattersForSmallerStreamers) { - if (streamStatus->live && streamStatus->viewerCount > getSettings()->smallStreamerLimit) { + if (streamStatus->live && + streamStatus->viewerCount > getSettings()->smallStreamerLimit) { return; } } // get viewer list - NetworkRequest request("https://tmi.twitch.tv/group/user/" + this->getName() + "/chatters"); + NetworkRequest request("https://tmi.twitch.tv/group/user/" + + this->getName() + "/chatters"); request.setCaller(QThread::currentThread()); - request.onSuccess([this, weak = this->weak_from_this()](auto result) -> Outcome { - // channel still exists? - auto shared = weak.lock(); - if (!shared) return Failure; + request.onSuccess( + [this, weak = this->weak_from_this()](auto result) -> Outcome { + // channel still exists? + auto shared = weak.lock(); + if (!shared) return Failure; - return this->parseViewerList(result.parseJson()); - }); + return this->parseViewerList(result.parseJson()); + }); request.execute(); } Outcome TwitchChannel::parseViewerList(const QJsonObject &jsonRoot) { - static QStringList categories = {"moderators", "staff", "admins", "global_mods", "viewers"}; + static QStringList categories = {"moderators", "staff", "admins", + "global_mods", "viewers"}; // parse json QJsonObject jsonCategories = jsonRoot.value("chatters").toObject(); for (const auto &category : categories) { - for (const auto jsonCategory : jsonCategories.value(category).toArray()) { + for (const auto jsonCategory : + jsonCategories.value(category).toArray()) { this->completionModel.addUser(jsonCategory.toString()); } } @@ -515,8 +536,8 @@ Outcome TwitchChannel::parseViewerList(const QJsonObject &jsonRoot) void TwitchChannel::loadBadges() { - auto url = Url{"https://badges.twitch.tv/v1/badges/channels/" + this->getRoomId() + - "/display?language=en"}; + auto url = Url{"https://badges.twitch.tv/v1/badges/channels/" + + this->getRoomId() + "/display?language=en"}; NetworkRequest req(url.string); req.setCaller(QThread::currentThread()); @@ -529,19 +550,24 @@ void TwitchChannel::loadBadges() auto jsonRoot = result.parseJson(); auto _ = jsonRoot["badge_sets"].toObject(); - for (auto jsonBadgeSet = _.begin(); jsonBadgeSet != _.end(); jsonBadgeSet++) { + for (auto jsonBadgeSet = _.begin(); jsonBadgeSet != _.end(); + jsonBadgeSet++) { auto &versions = (*badgeSets)[jsonBadgeSet.key()]; auto _ = jsonBadgeSet->toObject()["versions"].toObject(); - for (auto jsonVersion_ = _.begin(); jsonVersion_ != _.end(); jsonVersion_++) { + for (auto jsonVersion_ = _.begin(); jsonVersion_ != _.end(); + jsonVersion_++) { auto jsonVersion = jsonVersion_->toObject(); - auto emote = std::make_shared( - Emote{EmoteName{}, - ImageSet{Image::fromUrl({jsonVersion["image_url_1x"].toString()}), - Image::fromUrl({jsonVersion["image_url_2x"].toString()}), - Image::fromUrl({jsonVersion["image_url_4x"].toString()})}, - Tooltip{jsonRoot["description"].toString()}, - Url{jsonVersion["clickURL"].toString()}}); + auto emote = std::make_shared(Emote{ + EmoteName{}, + ImageSet{Image::fromUrl( + {jsonVersion["image_url_1x"].toString()}), + Image::fromUrl( + {jsonVersion["image_url_2x"].toString()}), + Image::fromUrl( + {jsonVersion["image_url_4x"].toString()})}, + Tooltip{jsonRoot["description"].toString()}, + Url{jsonVersion["clickURL"].toString()}}); versions.emplace(jsonVersion_.key(), emote); }; @@ -555,63 +581,67 @@ void TwitchChannel::loadBadges() void TwitchChannel::loadCheerEmotes() { - auto url = Url{"https://api.twitch.tv/kraken/bits/actions?channel_id=" + this->getRoomId()}; + auto url = Url{"https://api.twitch.tv/kraken/bits/actions?channel_id=" + + this->getRoomId()}; auto request = NetworkRequest::twitchRequest(url.string); request.setCaller(QThread::currentThread()); - request.onSuccess([this, weak = weakOf(this)](auto result) -> Outcome { - auto cheerEmoteSets = ParseCheermoteSets(result.parseRapidJson()); + request.onSuccess( + [this, weak = weakOf(this)](auto result) -> Outcome { + auto cheerEmoteSets = ParseCheermoteSets(result.parseRapidJson()); - for (auto &set : cheerEmoteSets) { - auto cheerEmoteSet = CheerEmoteSet(); - cheerEmoteSet.regex = QRegularExpression("^" + set.prefix.toLower() + "([1-9][0-9]*)$"); + for (auto &set : cheerEmoteSets) { + auto cheerEmoteSet = CheerEmoteSet(); + cheerEmoteSet.regex = QRegularExpression( + "^" + set.prefix.toLower() + "([1-9][0-9]*)$"); - for (auto &tier : set.tiers) { - CheerEmote cheerEmote; + for (auto &tier : set.tiers) { + CheerEmote cheerEmote; - cheerEmote.color = QColor(tier.color); - cheerEmote.minBits = tier.minBits; + cheerEmote.color = QColor(tier.color); + cheerEmote.minBits = tier.minBits; - // TODO(pajlada): We currently hardcode dark here :| - // We will continue to do so for now since we haven't had to - // solve that anywhere else + // TODO(pajlada): We currently hardcode dark here :| + // We will continue to do so for now since we haven't had to + // solve that anywhere else - cheerEmote.animatedEmote = - std::make_shared(Emote{EmoteName{"cheer emote"}, - ImageSet{ - tier.images["dark"]["animated"]["1"], - tier.images["dark"]["animated"]["2"], - tier.images["dark"]["animated"]["4"], - }, - Tooltip{}, Url{}}); - cheerEmote.staticEmote = - std::make_shared(Emote{EmoteName{"cheer emote"}, - ImageSet{ - tier.images["dark"]["static"]["1"], - tier.images["dark"]["static"]["2"], - tier.images["dark"]["static"]["4"], - }, - Tooltip{}, Url{}}); + cheerEmote.animatedEmote = std::make_shared( + Emote{EmoteName{"cheer emote"}, + ImageSet{ + tier.images["dark"]["animated"]["1"], + tier.images["dark"]["animated"]["2"], + tier.images["dark"]["animated"]["4"], + }, + Tooltip{}, Url{}}); + cheerEmote.staticEmote = std::make_shared( + Emote{EmoteName{"cheer emote"}, + ImageSet{ + tier.images["dark"]["static"]["1"], + tier.images["dark"]["static"]["2"], + tier.images["dark"]["static"]["4"], + }, + Tooltip{}, Url{}}); - cheerEmoteSet.cheerEmotes.emplace_back(cheerEmote); + cheerEmoteSet.cheerEmotes.emplace_back(cheerEmote); + } + + std::sort(cheerEmoteSet.cheerEmotes.begin(), + cheerEmoteSet.cheerEmotes.end(), + [](const auto &lhs, const auto &rhs) { + return lhs.minBits < rhs.minBits; // + }); + + this->cheerEmoteSets_.emplace_back(cheerEmoteSet); } - std::sort(cheerEmoteSet.cheerEmotes.begin(), cheerEmoteSet.cheerEmotes.end(), - [](const auto &lhs, const auto &rhs) { - return lhs.minBits < rhs.minBits; // - }); - - this->cheerEmoteSets_.emplace_back(cheerEmoteSet); - } - - return Success; - }); + return Success; + }); request.execute(); } -boost::optional TwitchChannel::getTwitchBadge(const QString &set, - const QString &version) const +boost::optional TwitchChannel::getTwitchBadge( + const QString &set, const QString &version) const { auto badgeSets = this->badgeSets_.access(); auto it = badgeSets->find(set); diff --git a/src/providers/twitch/TwitchChannel.hpp b/src/providers/twitch/TwitchChannel.hpp index 752fd9008..422b1b68a 100644 --- a/src/providers/twitch/TwitchChannel.hpp +++ b/src/providers/twitch/TwitchChannel.hpp @@ -78,7 +78,8 @@ public: const QString &getChannelUrl(); const QString &getPopoutPlayerUrl(); - boost::optional getTwitchBadge(const QString &set, const QString &version) const; + boost::optional getTwitchBadge(const QString &set, + const QString &version) const; // Signals pajlada::Signals::NoArgSignal roomIdChanged; diff --git a/src/providers/twitch/TwitchEmotes.cpp b/src/providers/twitch/TwitchEmotes.cpp index 80337912e..08c28286f 100644 --- a/src/providers/twitch/TwitchEmotes.cpp +++ b/src/providers/twitch/TwitchEmotes.cpp @@ -14,13 +14,16 @@ TwitchEmotes::TwitchEmotes() // id is used for lookup // emoteName is used for giving a name to the emote in case it doesn't exist -EmotePtr TwitchEmotes::getOrCreateEmote(const EmoteId &id, const EmoteName &name_) +EmotePtr TwitchEmotes::getOrCreateEmote(const EmoteId &id, + const EmoteName &name_) { static QMap replacements{ - {"[oO](_|\\.)[oO]", "O_o"}, {"\\>\\;\\(", ">("}, {"\\<\\;3", "<3"}, - {"\\:-?(o|O)", ":O"}, {"\\:-?(p|P)", ":P"}, {"\\:-?[\\\\/]", ":/"}, - {"\\:-?[z|Z|\\|]", ":Z"}, {"\\:-?\\(", ":("}, {"\\:-?\\)", ":)"}, - {"\\:-?D", ":D"}, {"\\;-?(p|P)", ";P"}, {"\\;-?\\)", ";)"}, + {"[oO](_|\\.)[oO]", "O_o"}, {"\\>\\;\\(", ">("}, + {"\\<\\;3", "<3"}, {"\\:-?(o|O)", ":O"}, + {"\\:-?(p|P)", ":P"}, {"\\:-?[\\\\/]", ":/"}, + {"\\:-?[z|Z|\\|]", ":Z"}, {"\\:-?\\(", ":("}, + {"\\:-?\\)", ":)"}, {"\\:-?D", ":D"}, + {"\\;-?(p|P)", ";P"}, {"\\;-?\\)", ";)"}, {"R-?\\)", "R)"}, {"B-?\\)", "B)"}, }; @@ -42,14 +45,14 @@ EmotePtr TwitchEmotes::getOrCreateEmote(const EmoteId &id, const EmoteName &name auto shared = (*cache)[id].lock(); if (!shared) { - (*cache)[id] = shared = - std::make_shared(Emote{EmoteName{name}, - ImageSet{ - Image::fromUrl(getEmoteLink(id, "1.0"), 1), - Image::fromUrl(getEmoteLink(id, "2.0"), 0.5), - Image::fromUrl(getEmoteLink(id, "3.0"), 0.25), - }, - Tooltip{name}, Url{}}); + (*cache)[id] = shared = std::make_shared( + Emote{EmoteName{name}, + ImageSet{ + Image::fromUrl(getEmoteLink(id, "1.0"), 1), + Image::fromUrl(getEmoteLink(id, "2.0"), 0.5), + Image::fromUrl(getEmoteLink(id, "3.0"), 0.25), + }, + Tooltip{name}, Url{}}); } return shared; @@ -57,8 +60,9 @@ EmotePtr TwitchEmotes::getOrCreateEmote(const EmoteId &id, const EmoteName &name Url TwitchEmotes::getEmoteLink(const EmoteId &id, const QString &emoteScale) { - return { - QString(TWITCH_EMOTE_TEMPLATE).replace("{id}", id.string).replace("{scale}", emoteScale)}; + return {QString(TWITCH_EMOTE_TEMPLATE) + .replace("{id}", id.string) + .replace("{scale}", emoteScale)}; } AccessGuard> TwitchEmotes::accessAll() diff --git a/src/providers/twitch/TwitchEmotes.hpp b/src/providers/twitch/TwitchEmotes.hpp index e403ebb43..665e1e9cd 100644 --- a/src/providers/twitch/TwitchEmotes.hpp +++ b/src/providers/twitch/TwitchEmotes.hpp @@ -11,7 +11,8 @@ #include "providers/twitch/TwitchEmotes.hpp" #include "util/ConcurrentMap.hpp" -#define TWITCH_EMOTE_TEMPLATE "https://static-cdn.jtvnw.net/emoticons/v1/{id}/{scale}" +#define TWITCH_EMOTE_TEMPLATE \ + "https://static-cdn.jtvnw.net/emoticons/v1/{id}/{scale}" namespace chatterino { @@ -26,7 +27,8 @@ public: private: UniqueAccess> twitchEmotes_; - UniqueAccess>> twitchEmotesCache_; + UniqueAccess>> + twitchEmotesCache_; }; } // namespace chatterino diff --git a/src/providers/twitch/TwitchMessageBuilder.cpp b/src/providers/twitch/TwitchMessageBuilder.cpp index d2cd82af7..91c9161fc 100644 --- a/src/providers/twitch/TwitchMessageBuilder.cpp +++ b/src/providers/twitch/TwitchMessageBuilder.cpp @@ -20,9 +20,9 @@ namespace chatterino { -TwitchMessageBuilder::TwitchMessageBuilder(Channel *_channel, - const Communi::IrcPrivateMessage *_ircMessage, - const MessageParseArgs &_args) +TwitchMessageBuilder::TwitchMessageBuilder( + Channel *_channel, const Communi::IrcPrivateMessage *_ircMessage, + const MessageParseArgs &_args) : channel(_channel) , twitchChannel(dynamic_cast(_channel)) , ircMessage(_ircMessage) @@ -35,10 +35,9 @@ TwitchMessageBuilder::TwitchMessageBuilder(Channel *_channel, this->usernameColor_ = app->themes->messages.textColors.system; } -TwitchMessageBuilder::TwitchMessageBuilder(Channel *_channel, - const Communi::IrcMessage *_ircMessage, - const MessageParseArgs &_args, QString content, - bool isAction) +TwitchMessageBuilder::TwitchMessageBuilder( + Channel *_channel, const Communi::IrcMessage *_ircMessage, + const MessageParseArgs &_args, QString content, bool isAction) : channel(_channel) , twitchChannel(dynamic_cast(_channel)) , ircMessage(_ircMessage) @@ -58,17 +57,21 @@ bool TwitchMessageBuilder::isIgnored() const // TODO(pajlada): Do we need to check if the phrase is valid first? for (const auto &phrase : app->ignores->phrases.getVector()) { if (phrase.isMatch(this->originalMessage_)) { - Log("Blocking message because it contains ignored phrase {}", phrase.getPattern()); + Log("Blocking message because it contains ignored phrase {}", + phrase.getPattern()); return true; } } - if (app->settings->enableTwitchIgnoredUsers && this->tags.contains("user-id")) { + if (app->settings->enableTwitchIgnoredUsers && + this->tags.contains("user-id")) { auto sourceUserID = this->tags.value("user-id").toString(); - for (const auto &user : app->accounts->twitch.getCurrent()->getIgnores()) { + for (const auto &user : + app->accounts->twitch.getCurrent()->getIgnores()) { if (sourceUserID == user.id) { - Log("Blocking message because it's from blocked user {}", user.name); + Log("Blocking message because it's from blocked user {}", + user.name); return true; } } @@ -162,8 +165,9 @@ MessagePtr TwitchMessageBuilder::build() this->appendTwitchEmote(ircMessage, emote, twitchEmotes); } - std::sort(twitchEmotes.begin(), twitchEmotes.end(), - [](const auto &a, const auto &b) { return a.first < b.first; }); + std::sort( + twitchEmotes.begin(), twitchEmotes.end(), + [](const auto &a, const auto &b) { return a.first < b.first; }); } // words @@ -176,17 +180,20 @@ MessagePtr TwitchMessageBuilder::build() return this->getMessage(); } -void TwitchMessageBuilder::addWords(const QStringList &words, - const std::vector> &twitchEmotes) +void TwitchMessageBuilder::addWords( + const QStringList &words, + const std::vector> &twitchEmotes) { auto i = int(); auto currentTwitchEmote = twitchEmotes.begin(); for (const auto &word : words) { // check if it's a twitch emote twitch emote - if (currentTwitchEmote != twitchEmotes.end() && currentTwitchEmote->first == i) { + if (currentTwitchEmote != twitchEmotes.end() && + currentTwitchEmote->first == i) { auto emoteImage = currentTwitchEmote->second; - this->emplace(emoteImage, MessageElement::TwitchEmote); + this->emplace(emoteImage, + MessageElement::TwitchEmote); i += word.length() + 1; currentTwitchEmote++; @@ -196,9 +203,12 @@ void TwitchMessageBuilder::addWords(const QStringList &words, // split words for (auto &variant : getApp()->emotes->emojis.parse(word)) { - boost::apply_visitor(/*overloaded{[&](EmotePtr arg) { this->addTextOrEmoji(arg); }, - [&](const QString &arg) { this->addTextOrEmoji(arg); }}*/ - [&](auto &&arg) { this->addTextOrEmoji(arg); }, variant); + boost::apply_visitor(/*overloaded{[&](EmotePtr arg) { + this->addTextOrEmoji(arg); }, + [&](const QString &arg) { + this->addTextOrEmoji(arg); }}*/ + [&](auto &&arg) { this->addTextOrEmoji(arg); }, + variant); } for (int j = 0; j < word.size(); j++) { @@ -240,14 +250,15 @@ void TwitchMessageBuilder::addTextOrEmoji(const QString &string_) // Actually just text auto linkString = this->matchLink(string); auto link = Link(); - auto textColor = - this->action_ ? MessageColor(this->usernameColor_) : MessageColor(MessageColor::Text); + auto textColor = this->action_ ? MessageColor(this->usernameColor_) + : MessageColor(MessageColor::Text); if (linkString.isEmpty()) { if (string.startsWith('@')) { - this->emplace(string, TextElement::BoldUsername, textColor, - FontStyle::ChatMediumBold); - this->emplace(string, TextElement::NonBoldUsername, textColor); + this->emplace(string, TextElement::BoldUsername, + textColor, FontStyle::ChatMediumBold); + this->emplace(string, TextElement::NonBoldUsername, + textColor); } else { this->emplace(string, TextElement::Text, textColor); } @@ -260,22 +271,26 @@ void TwitchMessageBuilder::addTextOrEmoji(const QString &string_) auto match = domainRegex.match(string); if (match.isValid()) { lowercaseLinkString = string.mid(0, match.capturedStart(1)) + - match.captured(1).toLower() + string.mid(match.capturedEnd(1)); + match.captured(1).toLower() + + string.mid(match.capturedEnd(1)); } else { lowercaseLinkString = string; } link = Link(Link::Url, linkString); textColor = MessageColor(MessageColor::Link); - this->emplace(lowercaseLinkString, TextElement::LowercaseLink, textColor) + this->emplace(lowercaseLinkString, + TextElement::LowercaseLink, textColor) + ->setLink(link); + this->emplace(string, TextElement::OriginalLink, textColor) ->setLink(link); - this->emplace(string, TextElement::OriginalLink, textColor)->setLink(link); } // if (!linkString.isEmpty()) { // if (getApp()->settings->lowercaseLink) { // QRegularExpression httpRegex("\\bhttps?://", - // QRegularExpression::CaseInsensitiveOption); QRegularExpression ftpRegex("\\bftps?://", + // QRegularExpression::CaseInsensitiveOption); QRegularExpression + // ftpRegex("\\bftps?://", // QRegularExpression::CaseInsensitiveOption); QRegularExpression // getDomain("\\/\\/([^\\/]*)"); QString tempString = string; @@ -291,7 +306,8 @@ void TwitchMessageBuilder::addTextOrEmoji(const QString &string_) // textColor = MessageColor(MessageColor::Link); //} // if (string.startsWith('@')) { - // this->emplace(string, TextElement::BoldUsername, textColor, + // this->emplace(string, TextElement::BoldUsername, + // textColor, // FontStyle::ChatMediumBold) // // ->setLink(link); // this->emplace(string, TextElement::NonBoldUsername, @@ -334,7 +350,8 @@ void TwitchMessageBuilder::appendChannelName() QString channelName("#" + this->channel->getName()); Link link(Link::Url, this->channel->getName() + "\n" + this->messageID); - this->emplace(channelName, MessageElement::ChannelName, MessageColor::System) // + this->emplace(channelName, MessageElement::ChannelName, + MessageColor::System) // ->setLink(link); } @@ -355,7 +372,8 @@ void TwitchMessageBuilder::parseUsername() // display name // auto displayNameVariant = this->tags.value("display-name"); // if (displayNameVariant.isValid()) { - // this->userName = displayNameVariant.toString() + " (" + this->userName + ")"; + // this->userName = displayNameVariant.toString() + " (" + + // this->userName + ")"; // } this->message_->loginName = this->userName; @@ -371,9 +389,11 @@ void TwitchMessageBuilder::appendUsername() auto iterator = this->tags.find("display-name"); if (iterator != this->tags.end()) { - QString displayName = parseTagString(iterator.value().toString()).trimmed(); + QString displayName = + parseTagString(iterator.value().toString()).trimmed(); - if (QString::compare(displayName, this->userName, Qt::CaseInsensitive) == 0) { + if (QString::compare(displayName, this->userName, + Qt::CaseInsensitive) == 0) { username = displayName; this->message_->displayName = displayName; @@ -391,7 +411,8 @@ void TwitchMessageBuilder::appendUsername() QString usernameText; pajlada::Settings::Setting usernameDisplayMode( - "/appearance/messages/usernameDisplayMode", UsernameDisplayMode::UsernameAndLocalizedName); + "/appearance/messages/usernameDisplayMode", + UsernameDisplayMode::UsernameAndLocalizedName); switch (usernameDisplayMode.getValue()) { case UsernameDisplayMode::Username: { @@ -418,10 +439,12 @@ void TwitchMessageBuilder::appendUsername() if (this->args.isSentWhisper) { // TODO(pajlada): Re-implement - // userDisplayString += IrcManager::getInstance().getUser().getUserName(); + // userDisplayString += + // IrcManager::getInstance().getUser().getUserName(); } else if (this->args.isReceivedWhisper) { // Sender username - this->emplace(usernameText, MessageElement::Text, this->usernameColor_, + this->emplace(usernameText, MessageElement::Text, + this->usernameColor_, FontStyle::ChatMediumBold) ->setLink({Link::UserInfo, this->userName}); @@ -429,7 +452,8 @@ void TwitchMessageBuilder::appendUsername() // Separator this->emplace("->", MessageElement::Text, - app->themes->messages.textColors.system, FontStyle::ChatMedium); + app->themes->messages.textColors.system, + FontStyle::ChatMedium); QColor selfColor = currentUser->color; if (!selfColor.isValid()) { @@ -437,14 +461,16 @@ void TwitchMessageBuilder::appendUsername() } // Your own username - this->emplace(currentUser->getUserName() + ":", MessageElement::Text, - selfColor, FontStyle::ChatMediumBold); + this->emplace(currentUser->getUserName() + ":", + MessageElement::Text, selfColor, + FontStyle::ChatMediumBold); } else { if (!this->action_) { usernameText += ":"; } - this->emplace(usernameText, MessageElement::Text, this->usernameColor_, + this->emplace(usernameText, MessageElement::Text, + this->usernameColor_, FontStyle::ChatMediumBold) ->setLink({Link::UserInfo, this->userName}); } @@ -470,7 +496,8 @@ void TwitchMessageBuilder::parseHighlights(bool isPastMsg) // update the media player url if necessary QUrl highlightSoundUrl; if (app->settings->customHighlightSound) { - highlightSoundUrl = QUrl::fromLocalFile(app->settings->pathHighlightSound.getValue()); + highlightSoundUrl = + QUrl::fromLocalFile(app->settings->pathHighlightSound.getValue()); } else { highlightSoundUrl = QUrl("qrc:/sounds/ping2.wav"); } @@ -483,12 +510,15 @@ void TwitchMessageBuilder::parseHighlights(bool isPastMsg) // TODO: This vector should only be rebuilt upon highlights being changed // fourtf: should be implemented in the HighlightsController - std::vector activeHighlights = app->highlights->phrases.getVector(); - std::vector userHighlights = app->highlights->highlightedUsers.getVector(); + std::vector activeHighlights = + app->highlights->phrases.getVector(); + std::vector userHighlights = + app->highlights->highlightedUsers.getVector(); if (app->settings->enableHighlightsSelf && currentUsername.size() > 0) { - HighlightPhrase selfHighlight(currentUsername, app->settings->enableHighlightTaskbar, - app->settings->enableHighlightSound, false); + HighlightPhrase selfHighlight( + currentUsername, app->settings->enableHighlightTaskbar, + app->settings->enableHighlightSound, false); activeHighlights.emplace_back(std::move(selfHighlight)); } @@ -514,15 +544,17 @@ void TwitchMessageBuilder::parseHighlights(bool isPastMsg) } if (playSound && doAlert) { - // Break if no further action can be taken from other highlights - // This might change if highlights can have custom colors/sounds/actions + // Break if no further action can be taken from other + // highlights This might change if highlights can have + // custom colors/sounds/actions break; } } } for (const HighlightPhrase &userHighlight : userHighlights) { if (userHighlight.isMatch(this->ircMessage->nick())) { - Log("Highlight because user {} sent a message", this->ircMessage->nick()); + Log("Highlight because user {} sent a message", + this->ircMessage->nick()); doHighlight = true; if (userHighlight.getAlert()) { @@ -534,8 +566,8 @@ void TwitchMessageBuilder::parseHighlights(bool isPastMsg) } if (playSound && doAlert) { - // Break if no further action can be taken from other usernames - // Mostly used for regex stuff + // Break if no further action can be taken from other + // usernames Mostly used for regex stuff break; } } @@ -544,12 +576,14 @@ void TwitchMessageBuilder::parseHighlights(bool isPastMsg) this->setHighlight(doHighlight); if (!isPastMsg) { - if (playSound && (!hasFocus || app->settings->highlightAlwaysPlaySound)) { + if (playSound && + (!hasFocus || app->settings->highlightAlwaysPlaySound)) { player->play(); } if (doAlert) { - QApplication::alert(getApp()->windows->getMainWindow().window(), 2500); + QApplication::alert(getApp()->windows->getMainWindow().window(), + 2500); } } @@ -559,9 +593,9 @@ void TwitchMessageBuilder::parseHighlights(bool isPastMsg) } } -void TwitchMessageBuilder::appendTwitchEmote(const Communi::IrcMessage *ircMessage, - const QString &emote, - std::vector> &vec) +void TwitchMessageBuilder::appendTwitchEmote( + const Communi::IrcMessage *ircMessage, const QString &emote, + std::vector> &vec) { auto app = getApp(); if (!emote.contains(':')) { @@ -588,13 +622,16 @@ void TwitchMessageBuilder::appendTwitchEmote(const Communi::IrcMessage *ircMessa auto start = coords.at(0).toInt(); auto end = coords.at(1).toInt(); - if (start >= end || start < 0 || end > this->originalMessage_.length()) { + if (start >= end || start < 0 || + end > this->originalMessage_.length()) { return; } - auto name = EmoteName{this->originalMessage_.mid(start, end - start + 1)}; + auto name = + EmoteName{this->originalMessage_.mid(start, end - start + 1)}; - vec.push_back(std::make_pair(start, app->emotes->twitch.getOrCreateEmote(id, name))); + vec.push_back(std::make_pair( + start, app->emotes->twitch.getOrCreateEmote(id, name))); } } @@ -605,11 +642,13 @@ Outcome TwitchMessageBuilder::tryAppendEmote(const EmoteName &name) if ((emote = getApp()->emotes->bttv.getGlobalEmote(name))) { flags = MessageElement::BttvEmote; - } else if (twitchChannel && (emote = this->twitchChannel->getBttvEmote(name))) { + } else if (twitchChannel && + (emote = this->twitchChannel->getBttvEmote(name))) { flags = MessageElement::BttvEmote; } else if ((emote = getApp()->emotes->ffz.getGlobalEmote(name))) { flags = MessageElement::FfzEmote; - } else if (twitchChannel && (emote = this->twitchChannel->getFfzEmote(name))) { + } else if (twitchChannel && + (emote = this->twitchChannel->getFfzEmote(name))) { flags = MessageElement::FfzEmote; } @@ -622,7 +661,8 @@ Outcome TwitchMessageBuilder::tryAppendEmote(const EmoteName &name) } // fourtf: this is ugly -// maybe put the individual badges into a map instead of this mess +// maybe put the individual badges into a map instead of this +//mess void TwitchMessageBuilder::appendTwitchBadges() { auto app = getApp(); @@ -653,9 +693,10 @@ void TwitchMessageBuilder::appendTwitchBadges() // Try to fetch channel-specific bit badge try { if (twitchChannel) - if (const auto &badge = - this->twitchChannel->getTwitchBadge("bits", cheerAmount)) { - this->emplace(badge.get(), MessageElement::BadgeVanity) + if (const auto &badge = this->twitchChannel->getTwitchBadge( + "bits", cheerAmount)) { + this->emplace(badge.get(), + MessageElement::BadgeVanity) ->setTooltip(tooltip); continue; } @@ -665,62 +706,72 @@ void TwitchMessageBuilder::appendTwitchBadges() // Use default bit badge // try { - // const auto &badge = app->resources->badgeSets.at("bits").versions.at(cheerAmount); - // this->emplace(badge.badgeImage1x, MessageElement::BadgeVanity) + // const auto &badge = + // app->resources->badgeSets.at("bits").versions.at(cheerAmount); + // this->emplace(badge.badgeImage1x, + // MessageElement::BadgeVanity) // ->setTooltip(tooltip); //} catch (const std::out_of_range &) { // Log("No default bit badge for version {} found", cheerAmount); // continue; //} } else if (badge == "staff/1") { - this->emplace(Image::fromNonOwningPixmap(&app->resources->twitch.staff), - MessageElement::BadgeGlobalAuthority) + this->emplace( + Image::fromNonOwningPixmap(&app->resources->twitch.staff), + MessageElement::BadgeGlobalAuthority) ->setTooltip("Twitch Staff"); } else if (badge == "admin/1") { - this->emplace(Image::fromNonOwningPixmap(&app->resources->twitch.admin), - MessageElement::BadgeGlobalAuthority) + this->emplace( + Image::fromNonOwningPixmap(&app->resources->twitch.admin), + MessageElement::BadgeGlobalAuthority) ->setTooltip("Twitch Admin"); } else if (badge == "global_mod/1") { - this->emplace( - Image::fromNonOwningPixmap(&app->resources->twitch.globalmod), - MessageElement::BadgeGlobalAuthority) + this->emplace(Image::fromNonOwningPixmap( + &app->resources->twitch.globalmod), + MessageElement::BadgeGlobalAuthority) ->setTooltip("Twitch Global Moderator"); } else if (badge == "moderator/1") { // TODO: Implement custom FFZ moderator badge - this->emplace( - Image::fromNonOwningPixmap(&app->resources->twitch.moderator), - MessageElement::BadgeChannelAuthority) + this->emplace(Image::fromNonOwningPixmap( + &app->resources->twitch.moderator), + MessageElement::BadgeChannelAuthority) ->setTooltip("Twitch Channel Moderator"); } else if (badge == "turbo/1") { - this->emplace(Image::fromNonOwningPixmap(&app->resources->twitch.turbo), - MessageElement::BadgeGlobalAuthority) + this->emplace( + Image::fromNonOwningPixmap(&app->resources->twitch.turbo), + MessageElement::BadgeGlobalAuthority) ->setTooltip("Twitch Turbo Subscriber"); } else if (badge == "broadcaster/1") { this->emplace( - Image::fromNonOwningPixmap(&app->resources->twitch.broadcaster), + Image::fromNonOwningPixmap( + &app->resources->twitch.broadcaster), MessageElement::BadgeChannelAuthority) ->setTooltip("Twitch Broadcaster"); } else if (badge == "premium/1") { - this->emplace(Image::fromNonOwningPixmap(&app->resources->twitch.prime), - MessageElement::BadgeVanity) + this->emplace( + Image::fromNonOwningPixmap(&app->resources->twitch.prime), + MessageElement::BadgeVanity) ->setTooltip("Twitch Prime Subscriber"); } else if (badge.startsWith("partner/")) { int index = badge.midRef(8).toInt(); switch (index) { case 1: { this->emplace( - Image::fromNonOwningPixmap(&app->resources->twitch.verified), + Image::fromNonOwningPixmap( + &app->resources->twitch.verified), MessageElement::BadgeVanity) ->setTooltip("Twitch Verified"); } break; default: { - printf("[TwitchMessageBuilder] Unhandled partner badge index: %d\n", index); + printf("[TwitchMessageBuilder] Unhandled partner badge " + "index: %d\n", + index); } break; } } else if (badge.startsWith("subscriber/")) { // if (channelResources.loaded == false) { - // // qDebug() << "Channel resources are not loaded, can't add the - // subscriber + // // qDebug() << "Channel resources are not loaded, + // can't add the subscriber // // badge"; // continue; // } @@ -752,7 +803,8 @@ void TwitchMessageBuilder::appendTwitchBadges() // this->emplace(badgeVersion.badgeImage1x, // MessageElement::BadgeSubscription) - // ->setTooltip("Twitch " + QString::fromStdString(badgeVersion.title)); + // ->setTooltip("Twitch " + + // QString::fromStdString(badgeVersion.title)); } else { // if (!app->resources->dynamicBadgesLoaded) { // // Do nothing @@ -762,11 +814,12 @@ void TwitchMessageBuilder::appendTwitchBadges() // QStringList parts = badge.split('/'); // if (parts.length() != 2) { - // qDebug() << "Bad number of parts: " << parts.length() << " in " << parts; - // continue; + // qDebug() << "Bad number of parts: " << parts.length() << " in + // " << parts; continue; //} - // MessageElement::Flags badgeType = MessageElement::Flags::BadgeVanity; + // MessageElement::Flags badgeType = + // MessageElement::Flags::BadgeVanity; // std::string badgeSetKey = parts[0].toStdString(); // std::string versionKey = parts[1].toStdString(); @@ -777,11 +830,14 @@ void TwitchMessageBuilder::appendTwitchBadges() // try { // auto &badgeVersion = badgeSet.versions.at(versionKey); - // this->emplace(badgeVersion.badgeImage1x, badgeType) - // ->setTooltip("Twitch " + QString::fromStdString(badgeVersion.title)); + // this->emplace(badgeVersion.badgeImage1x, + // badgeType) + // ->setTooltip("Twitch " + + // QString::fromStdString(badgeVersion.title)); // } catch (const std::exception &e) { // qDebug() << "Exception caught:" << e.what() - // << "when trying to fetch badge version " << versionKey.c_str(); + // << "when trying to fetch badge version " << + // versionKey.c_str(); // } //} catch (const std::exception &e) { // qDebug() << "No badge set with key" << badgeSetKey.c_str() @@ -804,7 +860,8 @@ void TwitchMessageBuilder::appendChatterinoBadges() // const auto badge = it->second; - // this->emplace(badge->image, MessageElement::BadgeChatterino) + // this->emplace(badge->image, + // MessageElement::BadgeChatterino) // ->setTooltip(QString::fromStdString(badge->tooltip)); } @@ -830,7 +887,8 @@ Outcome TwitchMessageBuilder::tryParseCheermote(const QString &string) // auto savedIt = cheermoteSet.cheermotes.end(); // // Fetch cheermote that matches our numBits - // for (auto it = cheermoteSet.cheermotes.begin(); it != cheermoteSet.cheermotes.end(); + // for (auto it = cheermoteSet.cheermotes.begin(); it != + // cheermoteSet.cheermotes.end(); // ++it) { // if (numBits >= it->minBits) { // savedIt = it; @@ -840,15 +898,17 @@ Outcome TwitchMessageBuilder::tryParseCheermote(const QString &string) // } // if (savedIt == cheermoteSet.cheermotes.end()) { - // Log("Error getting a cheermote from a cheermote set for the bit amount {}", + // Log("Error getting a cheermote from a cheermote set for the + // bit amount {}", // numBits); // return Failure; // } // const auto &cheermote = *savedIt; - // this->emplace(cheermote.animatedEmote, EmoteElement::BitsAnimated); - // this->emplace(amount, EmoteElement::Text, cheermote.color); + // this->emplace(cheermote.animatedEmote, + // EmoteElement::BitsAnimated); this->emplace(amount, + // EmoteElement::Text, cheermote.color); // return Success; // } diff --git a/src/providers/twitch/TwitchMessageBuilder.hpp b/src/providers/twitch/TwitchMessageBuilder.hpp index 1bf538f35..c82364a67 100644 --- a/src/providers/twitch/TwitchMessageBuilder.hpp +++ b/src/providers/twitch/TwitchMessageBuilder.hpp @@ -25,10 +25,13 @@ public: TwitchMessageBuilder() = delete; - explicit TwitchMessageBuilder(Channel *_channel, const Communi::IrcPrivateMessage *_ircMessage, + explicit TwitchMessageBuilder(Channel *_channel, + const Communi::IrcPrivateMessage *_ircMessage, const MessageParseArgs &_args); - explicit TwitchMessageBuilder(Channel *_channel, const Communi::IrcMessage *_ircMessage, - const MessageParseArgs &_args, QString content, bool isAction); + explicit TwitchMessageBuilder(Channel *_channel, + const Communi::IrcMessage *_ircMessage, + const MessageParseArgs &_args, + QString content, bool isAction); Channel *channel; TwitchChannel *twitchChannel; @@ -50,7 +53,8 @@ private: void appendUsername(); void parseHighlights(bool isPastMsg); - void appendTwitchEmote(const Communi::IrcMessage *ircMessage, const QString &emote, + void appendTwitchEmote(const Communi::IrcMessage *ircMessage, + const QString &emote, std::vector> &vec); Outcome tryAppendEmote(const EmoteName &name); diff --git a/src/providers/twitch/TwitchParseCheerEmotes.cpp b/src/providers/twitch/TwitchParseCheerEmotes.cpp index a7193d2f6..47d6427f8 100644 --- a/src/providers/twitch/TwitchParseCheerEmotes.cpp +++ b/src/providers/twitch/TwitchParseCheerEmotes.cpp @@ -9,7 +9,8 @@ namespace chatterino { namespace { template -inline bool ReadValue(const rapidjson::Value &object, const char *key, Type &out) +inline bool ReadValue(const rapidjson::Value &object, const char *key, + Type &out) { if (!object.HasMember(key)) { return false; @@ -27,7 +28,8 @@ inline bool ReadValue(const rapidjson::Value &object, const char *key, Type &out } template <> -inline bool ReadValue(const rapidjson::Value &object, const char *key, QString &out) +inline bool ReadValue(const rapidjson::Value &object, const char *key, + QString &out) { if (!object.HasMember(key)) { return false; @@ -45,7 +47,8 @@ inline bool ReadValue(const rapidjson::Value &object, const char *key, } template <> -inline bool ReadValue>(const rapidjson::Value &object, const char *key, +inline bool ReadValue>(const rapidjson::Value &object, + const char *key, std::vector &out) { if (!object.HasMember(key)) { @@ -70,7 +73,8 @@ inline bool ReadValue>(const rapidjson::Value &object, cons } // Parse a single cheermote set (or "action") from the twitch api -inline bool ParseSingleCheermoteSet(JSONCheermoteSet &set, const rapidjson::Value &action) +inline bool ParseSingleCheermoteSet(JSONCheermoteSet &set, + const rapidjson::Value &action) { if (!action.IsObject()) { return false; @@ -160,13 +164,15 @@ inline bool ParseSingleCheermoteSet(JSONCheermoteSet &set, const rapidjson::Valu continue; } - const rapidjson::Value &imageBackgroundStates = imageBackgroundValue.value; + const rapidjson::Value &imageBackgroundStates = + imageBackgroundValue.value; if (!imageBackgroundStates.IsObject()) { continue; } // Read each key which represents a background - for (const auto &imageBackgroundState : imageBackgroundStates.GetObject()) { + for (const auto &imageBackgroundState : + imageBackgroundStates.GetObject()) { QString state = imageBackgroundState.name.GetString(); bool stateExists = false; for (const auto &_state : set.states) { @@ -180,13 +186,15 @@ inline bool ParseSingleCheermoteSet(JSONCheermoteSet &set, const rapidjson::Valu continue; } - const rapidjson::Value &imageScalesValue = imageBackgroundState.value; + const rapidjson::Value &imageScalesValue = + imageBackgroundState.value; if (!imageScalesValue.IsObject()) { continue; } // Read each key which represents a scale - for (const auto &imageScaleValue : imageScalesValue.GetObject()) { + for (const auto &imageScaleValue : + imageScalesValue.GetObject()) { QString scale = imageScaleValue.name.GetString(); bool scaleExists = false; for (const auto &_scale : set.scales) { @@ -200,7 +208,8 @@ inline bool ParseSingleCheermoteSet(JSONCheermoteSet &set, const rapidjson::Valu continue; } - const rapidjson::Value &imageScaleURLValue = imageScaleValue.value; + const rapidjson::Value &imageScaleURLValue = + imageScaleValue.value; if (!imageScaleURLValue.IsString()) { continue; } @@ -230,8 +239,9 @@ inline bool ParseSingleCheermoteSet(JSONCheermoteSet &set, const rapidjson::Valu } } // namespace -// Look through the results of https://api.twitch.tv/kraken/bits/actions?channel_id=11148817 for -// cheermote sets or "Actions" as they are called in the API +// Look through the results of +// https://api.twitch.tv/kraken/bits/actions?channel_id=11148817 for cheermote +// sets or "Actions" as they are called in the API std::vector ParseCheermoteSets(const rapidjson::Document &d) { std::vector sets; diff --git a/src/providers/twitch/TwitchParseCheerEmotes.hpp b/src/providers/twitch/TwitchParseCheerEmotes.hpp index 150c8b447..284f87bf0 100644 --- a/src/providers/twitch/TwitchParseCheerEmotes.hpp +++ b/src/providers/twitch/TwitchParseCheerEmotes.hpp @@ -25,7 +25,8 @@ struct JSONCheermoteSet { QString color; // Background State Scale - std::map>> images; + std::map>> + images; }; std::vector tiers; diff --git a/src/providers/twitch/TwitchServer.cpp b/src/providers/twitch/TwitchServer.cpp index 14542afcf..49d24c654 100644 --- a/src/providers/twitch/TwitchServer.cpp +++ b/src/providers/twitch/TwitchServer.cpp @@ -29,8 +29,10 @@ TwitchServer::TwitchServer() this->pubsub = new PubSub; - // getSettings()->twitchSeperateWriteConnection.connect([this](auto, auto) { this->connect(); }, - // this->signalHolder_, false); + // getSettings()->twitchSeperateWriteConnection.connect([this](auto, auto) { + // this->connect(); }, + // this->signalHolder_, + // false); } void TwitchServer::initialize(Settings &settings, Paths &paths) @@ -39,11 +41,13 @@ void TwitchServer::initialize(Settings &settings, Paths &paths) [this]() { postToThread([this] { this->connect(); }); }); } -void TwitchServer::initializeConnection(IrcConnection *connection, bool isRead, bool isWrite) +void TwitchServer::initializeConnection(IrcConnection *connection, bool isRead, + bool isWrite) { this->singleConnection_ = isRead == isWrite; - std::shared_ptr account = getApp()->accounts->twitch.getCurrent(); + std::shared_ptr account = + getApp()->accounts->twitch.getCurrent(); qDebug() << "logging in as" << account->getUserName(); @@ -62,9 +66,12 @@ void TwitchServer::initializeConnection(IrcConnection *connection, bool isRead, connection->setPassword(oauthToken); } - connection->sendCommand(Communi::IrcCommand::createCapability("REQ", "twitch.tv/membership")); - connection->sendCommand(Communi::IrcCommand::createCapability("REQ", "twitch.tv/commands")); - connection->sendCommand(Communi::IrcCommand::createCapability("REQ", "twitch.tv/tags")); + connection->sendCommand( + Communi::IrcCommand::createCapability("REQ", "twitch.tv/membership")); + connection->sendCommand( + Communi::IrcCommand::createCapability("REQ", "twitch.tv/commands")); + connection->sendCommand( + Communi::IrcCommand::createCapability("REQ", "twitch.tv/tags")); connection->setHost("irc.chat.twitch.tv"); connection->setPort(6667); @@ -74,9 +81,10 @@ std::shared_ptr TwitchServer::createChannel(const QString &channelName) { TwitchChannel *channel = new TwitchChannel(channelName); - channel->sendMessageSignal.connect([this, channel](auto &chan, auto &msg, bool &sent) { - this->onMessageSendRequested(channel, msg, sent); - }); + channel->sendMessageSignal.connect( + [this, channel](auto &chan, auto &msg, bool &sent) { + this->onMessageSendRequested(channel, msg, sent); + }); return std::shared_ptr(channel); } @@ -113,7 +121,8 @@ void TwitchServer::messageReceived(Communi::IrcMessage *message) } else if (command == "MODE") { handler.handleModeMessage(message); } else if (command == "NOTICE") { - handler.handleNoticeMessage(static_cast(message)); + handler.handleNoticeMessage( + static_cast(message)); } else if (command == "JOIN") { handler.handleJoinMessage(message); } else if (command == "PART") { @@ -133,7 +142,8 @@ void TwitchServer::writeConnectionMessageReceived(Communi::IrcMessage *message) } } -std::shared_ptr TwitchServer::getCustomChannel(const QString &channelName) +std::shared_ptr TwitchServer::getCustomChannel( + const QString &channelName) { if (channelName == "/whispers") { return this->whispersChannel; @@ -146,7 +156,8 @@ std::shared_ptr TwitchServer::getCustomChannel(const QString &channelNa return nullptr; } -void TwitchServer::forEachChannelAndSpecialChannels(std::function func) +void TwitchServer::forEachChannelAndSpecialChannels( + std::function func) { this->forEachChannel(func); @@ -154,7 +165,8 @@ void TwitchServer::forEachChannelAndSpecialChannels(std::functionmentionsChannel); } -std::shared_ptr TwitchServer::getChannelOrEmptyByID(const QString &channelId) +std::shared_ptr TwitchServer::getChannelOrEmptyByID( + const QString &channelId) { std::lock_guard lock(this->channelMutex); @@ -184,8 +196,8 @@ bool TwitchServer::hasSeparateWriteConnection() const // return getSettings()->twitchSeperateWriteConnection; } -void TwitchServer::onMessageSendRequested(TwitchChannel *channel, const QString &message, - bool &sent) +void TwitchServer::onMessageSendRequested(TwitchChannel *channel, + const QString &message, bool &sent) { sent = false; @@ -193,17 +205,19 @@ void TwitchServer::onMessageSendRequested(TwitchChannel *channel, const QString std::lock_guard guard(this->lastMessageMutex_); // std::queue - auto &lastMessage = - channel->hasModRights() ? this->lastMessageMod_ : this->lastMessagePleb_; + auto &lastMessage = channel->hasModRights() ? this->lastMessageMod_ + : this->lastMessagePleb_; size_t maxMessageCount = channel->hasModRights() ? 99 : 19; auto minMessageOffset = (channel->hasModRights() ? 100ms : 1100ms); auto now = std::chrono::steady_clock::now(); // check if you are sending messages too fast - if (!lastMessage.empty() && lastMessage.back() + minMessageOffset > now) { + if (!lastMessage.empty() && + lastMessage.back() + minMessageOffset > now) { if (this->lastErrorTimeSpeed_ + 30s < now) { - auto errorMessage = Message::createSystemMessage("sending messages too fast"); + auto errorMessage = + Message::createSystemMessage("sending messages too fast"); channel->addMessage(errorMessage); @@ -220,7 +234,8 @@ void TwitchServer::onMessageSendRequested(TwitchChannel *channel, const QString // check if you are sending too many messages if (lastMessage.size() >= maxMessageCount) { if (this->lastErrorTimeAmount_ + 30s < now) { - auto errorMessage = Message::createSystemMessage("sending too many messages"); + auto errorMessage = + Message::createSystemMessage("sending too many messages"); channel->addMessage(errorMessage); diff --git a/src/providers/twitch/TwitchServer.hpp b/src/providers/twitch/TwitchServer.hpp index 769f65fd4..edc06ef6a 100644 --- a/src/providers/twitch/TwitchServer.hpp +++ b/src/providers/twitch/TwitchServer.hpp @@ -40,19 +40,24 @@ public: protected: virtual void initializeConnection(IrcConnection *connection, bool isRead, bool isWrite) override; - virtual std::shared_ptr createChannel(const QString &channelName) override; + virtual std::shared_ptr createChannel( + const QString &channelName) override; - virtual void privateMessageReceived(Communi::IrcPrivateMessage *message) override; + virtual void privateMessageReceived( + Communi::IrcPrivateMessage *message) override; virtual void messageReceived(Communi::IrcMessage *message) override; - virtual void writeConnectionMessageReceived(Communi::IrcMessage *message) override; + virtual void writeConnectionMessageReceived( + Communi::IrcMessage *message) override; - virtual std::shared_ptr getCustomChannel(const QString &channelname) override; + virtual std::shared_ptr getCustomChannel( + const QString &channelname) override; virtual QString cleanChannelName(const QString &dirtyChannelName) override; virtual bool hasSeparateWriteConnection() const override; private: - void onMessageSendRequested(TwitchChannel *channel, const QString &message, bool &sent); + void onMessageSendRequested(TwitchChannel *channel, const QString &message, + bool &sent); std::mutex lastMessageMutex_; std::queue lastMessagePleb_; diff --git a/src/providers/twitch/TwitchUser.hpp b/src/providers/twitch/TwitchUser.hpp index d69c05572..74a9c1252 100644 --- a/src/providers/twitch/TwitchUser.hpp +++ b/src/providers/twitch/TwitchUser.hpp @@ -36,7 +36,8 @@ namespace Settings { template <> struct Deserialize { - static chatterino::TwitchUser get(const rapidjson::Value &value, bool *error = nullptr) + static chatterino::TwitchUser get(const rapidjson::Value &value, + bool *error = nullptr) { using namespace chatterino; @@ -44,7 +45,8 @@ struct Deserialize { if (!value.IsObject()) { PAJLADA_REPORT_ERROR(error) - PAJLADA_THROW_EXCEPTION("Deserialized rapidjson::Value is wrong type"); + PAJLADA_THROW_EXCEPTION( + "Deserialized rapidjson::Value is wrong type"); return user; } diff --git a/src/singletons/Fonts.cpp b/src/singletons/Fonts.cpp index faf927e47..69f327285 100644 --- a/src/singletons/Fonts.cpp +++ b/src/singletons/Fonts.cpp @@ -102,17 +102,20 @@ Fonts::FontData Fonts::createFontData(Type type, float scale) {ChatSmall, {0.6f, false, QFont::Normal}}, {ChatMediumSmall, {0.8f, false, QFont::Normal}}, {ChatMedium, {1, false, QFont::Normal}}, - {ChatMediumBold, {1, false, QFont::Weight(getApp()->settings->boldScale.getValue())}}, + {ChatMediumBold, + {1, false, + QFont::Weight(getApp()->settings->boldScale.getValue())}}, {ChatMediumItalic, {1, true, QFont::Normal}}, {ChatLarge, {1.2f, false, QFont::Normal}}, {ChatVeryLarge, {1.4f, false, QFont::Normal}}, }; - sizeScale[ChatMediumBold] = {1, false, - QFont::Weight(getApp()->settings->boldScale.getValue())}; + sizeScale[ChatMediumBold] = { + 1, false, QFont::Weight(getApp()->settings->boldScale.getValue())}; auto data = sizeScale[type]; - return FontData(QFont(QString::fromStdString(this->chatFontFamily.getValue()), - int(this->chatFontSize.getValue() * data.scale * scale), data.weight, - data.italic)); + return FontData( + QFont(QString::fromStdString(this->chatFontFamily.getValue()), + int(this->chatFontSize.getValue() * data.scale * scale), + data.weight, data.italic)); } // normal Ui font (use pt size) @@ -125,8 +128,10 @@ Fonts::FontData Fonts::createFontData(Type type, float scale) static std::unordered_map defaultSize{ {Tiny, {8, "Monospace", false, QFont::Normal}}, - {UiMedium, {int(9 * multiplier), DEFAULT_FONT_FAMILY, false, QFont::Normal}}, - {UiTabs, {int(9 * multiplier), DEFAULT_FONT_FAMILY, false, QFont::Normal}}, + {UiMedium, + {int(9 * multiplier), DEFAULT_FONT_FAMILY, false, QFont::Normal}}, + {UiTabs, + {int(9 * multiplier), DEFAULT_FONT_FAMILY, false, QFont::Normal}}, }; UiFontData &data = defaultSize[type]; diff --git a/src/singletons/Logging.cpp b/src/singletons/Logging.cpp index a8a6495c7..9d5823564 100644 --- a/src/singletons/Logging.cpp +++ b/src/singletons/Logging.cpp @@ -26,8 +26,8 @@ void Logging::addMessage(const QString &channelName, MessagePtr message) if (it == this->loggingChannels_.end()) { auto channel = new LoggingChannel(channelName); channel->addMessage(message); - this->loggingChannels_.emplace(channelName, - std::unique_ptr(std::move(channel))); + this->loggingChannels_.emplace( + channelName, std::unique_ptr(std::move(channel))); } else { it->second->addMessage(message); } diff --git a/src/singletons/NativeMessaging.cpp b/src/singletons/NativeMessaging.cpp index 3bf5b0ff3..4afea4714 100644 --- a/src/singletons/NativeMessaging.cpp +++ b/src/singletons/NativeMessaging.cpp @@ -32,7 +32,8 @@ namespace ipc = boost::interprocess; namespace chatterino { void registerNmManifest(Paths &paths, const QString &manifestFilename, - const QString ®istryKeyName, const QJsonDocument &document); + const QString ®istryKeyName, + const QJsonDocument &document); void registerNmHost(Paths &paths) { @@ -53,14 +54,15 @@ void registerNmHost(Paths &paths) QJsonDocument document; auto obj = getBaseDocument(); - QJsonArray allowed_origins_arr = {"chrome-extension://" EXTENSION_ID "/"}; + QJsonArray allowed_origins_arr = {"chrome-extension://" EXTENSION_ID + "/"}; obj.insert("allowed_origins", allowed_origins_arr); document.setObject(obj); - registerNmManifest( - paths, "/native-messaging-manifest-chrome.json", - "HKCU\\Software\\Google\\Chrome\\NativeMessagingHosts\\com.chatterino.chatterino", - document); + registerNmManifest(paths, "/native-messaging-manifest-chrome.json", + "HKCU\\Software\\Google\\Chrome\\NativeMessagingHost" + "s\\com.chatterino.chatterino", + document); } // firefox @@ -72,14 +74,16 @@ void registerNmHost(Paths &paths) obj.insert("allowed_extensions", allowed_extensions); document.setObject(obj); - registerNmManifest( - paths, "/native-messaging-manifest-firefox.json", - "HKCU\\Software\\Mozilla\\NativeMessagingHosts\\com.chatterino.chatterino", document); + registerNmManifest(paths, "/native-messaging-manifest-firefox.json", + "HKCU\\Software\\Mozilla\\NativeMessagingHosts\\com." + "chatterino.chatterino", + document); } } void registerNmManifest(Paths &paths, const QString &manifestFilename, - const QString ®istryKeyName, const QJsonDocument &document) + const QString ®istryKeyName, + const QJsonDocument &document) { (void)registryKeyName; @@ -99,7 +103,8 @@ void registerNmManifest(Paths &paths, const QString &manifestFilename, std::string &getNmQueueName(Paths &paths) { - static std::string name = "chatterino_gui" + paths.applicationFilePathHash.toStdString(); + static std::string name = + "chatterino_gui" + paths.applicationFilePathHash.toStdString(); return name; } @@ -137,18 +142,20 @@ void NativeMessagingServer::ReceiverThread::run() { ipc::message_queue::remove("chatterino_gui"); - ipc::message_queue messageQueue(ipc::open_or_create, "chatterino_gui", 100, MESSAGE_SIZE); + ipc::message_queue messageQueue(ipc::open_or_create, "chatterino_gui", 100, + MESSAGE_SIZE); while (true) { try { - std::unique_ptr buf(static_cast(malloc(MESSAGE_SIZE))); + std::unique_ptr buf( + static_cast(malloc(MESSAGE_SIZE))); ipc::message_queue::size_type retSize; unsigned int priority; messageQueue.receive(buf.get(), MESSAGE_SIZE, retSize, priority); - QJsonDocument document = - QJsonDocument::fromJson(QByteArray::fromRawData(buf.get(), retSize)); + QJsonDocument document = QJsonDocument::fromJson( + QByteArray::fromRawData(buf.get(), retSize)); this->handleMessage(document.object()); } catch (ipc::interprocess_exception &ex) { @@ -157,7 +164,8 @@ void NativeMessagingServer::ReceiverThread::run() } } -void NativeMessagingServer::ReceiverThread::handleMessage(const QJsonObject &root) +void NativeMessagingServer::ReceiverThread::handleMessage( + const QJsonObject &root) { auto app = getApp(); @@ -199,9 +207,11 @@ void NativeMessagingServer::ReceiverThread::handleMessage(const QJsonObject &roo if (attach) { #ifdef USEWINSDK // if (args.height != -1) { - auto *window = AttachedWindow::get(::GetForegroundWindow(), args); + auto *window = + AttachedWindow::get(::GetForegroundWindow(), args); if (!name.isEmpty()) { - window->setChannel(app->twitch.server->getOrAddChannel(name)); + window->setChannel( + app->twitch.server->getOrAddChannel(name)); } // } // window->show(); diff --git a/src/singletons/Paths.cpp b/src/singletons/Paths.cpp index 40ce32524..21d1f57ad 100644 --- a/src/singletons/Paths.cpp +++ b/src/singletons/Paths.cpp @@ -36,8 +36,9 @@ bool Paths::isPortable() void Paths::initAppFilePathHash() { this->applicationFilePathHash = - QCryptographicHash::hash(QCoreApplication::applicationFilePath().toUtf8(), - QCryptographicHash::Sha224) + QCryptographicHash::hash( + QCoreApplication::applicationFilePath().toUtf8(), + QCryptographicHash::Sha224) .toBase64() .mid(0, 32) .replace("+", "-") @@ -46,15 +47,16 @@ void Paths::initAppFilePathHash() void Paths::initCheckPortable() { - this->portable_ = - QFileInfo::exists(combinePath(QCoreApplication::applicationDirPath(), "portable")); + this->portable_ = QFileInfo::exists( + combinePath(QCoreApplication::applicationDirPath(), "portable")); } void Paths::initAppDataDirectory() { assert(this->portable_.is_initialized()); - // Root path = %APPDATA%/Chatterino or the folder that the executable resides in + // Root path = %APPDATA%/Chatterino or the folder that the executable + // resides in this->rootAppDataDirectory = [&]() -> QString { // portable @@ -63,13 +65,15 @@ void Paths::initAppDataDirectory() } // permanent installation - QString path = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation); + QString path = + QStandardPaths::writableLocation(QStandardPaths::AppDataLocation); if (path.isEmpty()) { - throw std::runtime_error("Error finding writable location for settings"); + throw std::runtime_error( + "Error finding writable location for settings"); } -// create directory Chatterino2 instead of chatterino on windows because the ladder one is takes by -// chatterino 1 already +// create directory Chatterino2 instead of chatterino on windows because the +// ladder one is takes by chatterino 1 already #ifdef Q_OS_WIN path.replace("chatterino", "Chatterino"); @@ -84,12 +88,15 @@ void Paths::initSubDirectories() // required the app data directory to be set first assert(!this->rootAppDataDirectory.isEmpty()); - // create settings subdirectories and validate that they are created properly + // create settings subdirectories and validate that they are created + // properly auto makePath = [&](const std::string &name) -> QString { - auto path = combinePath(this->rootAppDataDirectory, QString::fromStdString(name)); + auto path = combinePath(this->rootAppDataDirectory, + QString::fromStdString(name)); if (!QDir().mkpath(path)) { - throw std::runtime_error("Error creating appdata path %appdata%/chatterino/" + name); + throw std::runtime_error( + "Error creating appdata path %appdata%/chatterino/" + name); } return path; diff --git a/src/singletons/Paths.hpp b/src/singletons/Paths.hpp index b1b59da61..071feb737 100644 --- a/src/singletons/Paths.hpp +++ b/src/singletons/Paths.hpp @@ -12,8 +12,8 @@ public: Paths(); - // Root directory for the configuration files. %APPDATA%/chatterino or ExecutablePath for - // portable mode + // Root directory for the configuration files. %APPDATA%/chatterino or + // ExecutablePath for portable mode QString rootAppDataDirectory; // Directory for settings files. Same as /Settings diff --git a/src/singletons/Settings.cpp b/src/singletons/Settings.cpp index 10be19100..b380a0119 100644 --- a/src/singletons/Settings.cpp +++ b/src/singletons/Settings.cpp @@ -12,7 +12,8 @@ std::vector> _settings; Settings *Settings::instance = nullptr; -void _actuallyRegisterSetting(std::weak_ptr setting) +void _actuallyRegisterSetting( + std::weak_ptr setting) { _settings.push_back(setting); } diff --git a/src/singletons/Settings.hpp b/src/singletons/Settings.hpp index 507868677..3db58f9c2 100644 --- a/src/singletons/Settings.hpp +++ b/src/singletons/Settings.hpp @@ -12,7 +12,8 @@ namespace chatterino { -void _actuallyRegisterSetting(std::weak_ptr setting); +void _actuallyRegisterSetting( + std::weak_ptr setting); class Settings { @@ -25,48 +26,62 @@ public: /// Appearance BoolSetting showTimestamps = {"/appearance/messages/showTimestamps", true}; - QStringSetting timestampFormat = {"/appearance/messages/timestampFormat", "h:mm"}; + QStringSetting timestampFormat = {"/appearance/messages/timestampFormat", + "h:mm"}; BoolSetting showBadges = {"/appearance/messages/showBadges", true}; - BoolSetting showLastMessageIndicator = {"/appearance/messages/showLastMessageIndicator", false}; - IntSetting lastMessagePattern = {"/appearance/messages/lastMessagePattern", Qt::VerPattern}; + BoolSetting showLastMessageIndicator = { + "/appearance/messages/showLastMessageIndicator", false}; + IntSetting lastMessagePattern = {"/appearance/messages/lastMessagePattern", + Qt::VerPattern}; BoolSetting showEmptyInput = {"/appearance/showEmptyInputBox", true}; - BoolSetting showMessageLength = {"/appearance/messages/showMessageLength", false}; - BoolSetting separateMessages = {"/appearance/messages/separateMessages", false}; - // BoolSetting collapseLongMessages = {"/appearance/messages/collapseLongMessages", false}; - IntSetting collpseMessagesMinLines = {"/appearance/messages/collapseMessagesMinLines", 0}; - BoolSetting alternateMessageBackground = {"/appearance/messages/alternateMessageBackground", - false}; + BoolSetting showMessageLength = {"/appearance/messages/showMessageLength", + false}; + BoolSetting separateMessages = {"/appearance/messages/separateMessages", + false}; + // BoolSetting collapseLongMessages = + // {"/appearance/messages/collapseLongMessages", false}; + IntSetting collpseMessagesMinLines = { + "/appearance/messages/collapseMessagesMinLines", 0}; + BoolSetting alternateMessageBackground = { + "/appearance/messages/alternateMessageBackground", false}; IntSetting uiScale = {"/appearance/uiScale", 0}; IntSetting boldScale = {"/appearance/boldScale", 57}; BoolSetting windowTopMost = {"/appearance/windowAlwaysOnTop", false}; BoolSetting showTabCloseButton = {"/appearance/showTabCloseButton", true}; - BoolSetting hidePreferencesButton = {"/appearance/hidePreferencesButton", false}; + BoolSetting hidePreferencesButton = {"/appearance/hidePreferencesButton", + false}; BoolSetting hideUserButton = {"/appearance/hideUserButton", false}; BoolSetting enableSmoothScrolling = {"/appearance/smoothScrolling", true}; - BoolSetting enableSmoothScrollingNewMessages = {"/appearance/smoothScrollingNewMessages", - false}; - BoolSetting enableUsernameBold = {"/appearence/messages/boldUsernames", false}; + BoolSetting enableSmoothScrollingNewMessages = { + "/appearance/smoothScrollingNewMessages", false}; + BoolSetting enableUsernameBold = {"/appearence/messages/boldUsernames", + false}; // BoolSetting customizable splitheader - BoolSetting showViewerCount = {"/appearance/splitheader/showViewerCount", false}; + BoolSetting showViewerCount = {"/appearance/splitheader/showViewerCount", + false}; BoolSetting showTitle = {"/appearance/splitheader/showTitle", false}; BoolSetting showGame = {"/appearance/splitheader/showGame", false}; BoolSetting showUptime = {"/appearance/splitheader/showUptime", false}; - // BoolSetting useCustomWindowFrame = {"/appearance/useCustomWindowFrame", false}; + // BoolSetting useCustomWindowFrame = {"/appearance/useCustomWindowFrame", + // false}; /// Behaviour - BoolSetting allowDuplicateMessages = {"/behaviour/allowDuplicateMessages", true}; + BoolSetting allowDuplicateMessages = {"/behaviour/allowDuplicateMessages", + true}; BoolSetting mentionUsersWithAt = {"/behaviour/mentionUsersWithAt", false}; BoolSetting showJoins = {"/behaviour/showJoins", false}; BoolSetting showParts = {"/behaviour/showParts", false}; - FloatSetting mouseScrollMultiplier = {"/behaviour/mouseScrollMultiplier", 1.0}; - // BoolSetting twitchSeperateWriteConnection = {"/behaviour/twitchSeperateWriteConnection", - // false}; + FloatSetting mouseScrollMultiplier = {"/behaviour/mouseScrollMultiplier", + 1.0}; + // BoolSetting twitchSeperateWriteConnection = + // {"/behaviour/twitchSeperateWriteConnection", false}; // Auto-completion BoolSetting onlyFetchChattersForSmallerStreamers = { "/behaviour/autocompletion/onlyFetchChattersForSmallerStreamers", true}; - IntSetting smallStreamerLimit = {"/behaviour/autocompletion/smallStreamerLimit", 1000}; + IntSetting smallStreamerLimit = { + "/behaviour/autocompletion/smallStreamerLimit", 1000}; BoolSetting pauseChatHover = {"/behaviour/pauseChatHover", false}; @@ -74,7 +89,8 @@ public: BoolSetting allowCommandsAtEnd = {"/commands/allowCommandsAtEnd", false}; /// Emotes - BoolSetting scaleEmotesByLineHeight = {"/emotes/scaleEmotesByLineHeight", false}; + BoolSetting scaleEmotesByLineHeight = {"/emotes/scaleEmotesByLineHeight", + false}; BoolSetting enableTwitchEmotes = {"/emotes/enableTwitchEmotes", true}; BoolSetting enableBttvEmotes = {"/emotes/enableBTTVEmotes", true}; BoolSetting enableFfzEmotes = {"/emotes/enableFFZEmotes", true}; @@ -95,16 +111,19 @@ public: BoolSetting enableLowercaseLink = {"/links/linkLowercase", true}; /// Ingored Users - BoolSetting enableTwitchIgnoredUsers = {"/ignore/enableTwitchIgnoredUsers", true}; + BoolSetting enableTwitchIgnoredUsers = {"/ignore/enableTwitchIgnoredUsers", + true}; /// Moderation QStringSetting timeoutAction = {"/moderation/timeoutAction", "Disable"}; /// Highlighting // BoolSetting enableHighlights = {"/highlighting/enabled", true}; - BoolSetting enableHighlightsSelf = {"/highlighting/nameIsHighlightKeyword", true}; + BoolSetting enableHighlightsSelf = {"/highlighting/nameIsHighlightKeyword", + true}; BoolSetting enableHighlightSound = {"/highlighting/enableSound", true}; - BoolSetting enableHighlightTaskbar = {"/highlighting/enableTaskbarFlashing", true}; + BoolSetting enableHighlightTaskbar = {"/highlighting/enableTaskbarFlashing", + true}; BoolSetting customHighlightSound = {"/highlighting/useCustomSound", false}; /// Logging @@ -115,15 +134,18 @@ public: QStringSetting pathHighlightSound = {"/highlighting/highlightSoundPath", "qrc:/sounds/ping2.wav"}; - BoolSetting highlightAlwaysPlaySound = {"/highlighting/alwaysPlaySound", false}; + BoolSetting highlightAlwaysPlaySound = {"/highlighting/alwaysPlaySound", + false}; BoolSetting inlineWhispers = {"/whispers/enableInlineWhispers", true}; /// External tools // Streamlink - BoolSetting streamlinkUseCustomPath = {"/external/streamlink/useCustomPath", false}; + BoolSetting streamlinkUseCustomPath = {"/external/streamlink/useCustomPath", + false}; QStringSetting streamlinkPath = {"/external/streamlink/customPath", ""}; - QStringSetting preferredQuality = {"/external/streamlink/quality", "Choose"}; + QStringSetting preferredQuality = {"/external/streamlink/quality", + "Choose"}; QStringSetting streamlinkOpts = {"/external/streamlink/options", ""}; /// Misc diff --git a/src/singletons/Theme.cpp b/src/singletons/Theme.cpp index b20a79875..5140db09a 100644 --- a/src/singletons/Theme.cpp +++ b/src/singletons/Theme.cpp @@ -39,7 +39,8 @@ Theme::Theme() void Theme::update() { - this->actuallyUpdate(this->themeHue, detail::getMultiplierByTheme(this->themeName.getValue())); + this->actuallyUpdate(this->themeHue, detail::getMultiplierByTheme( + this->themeName.getValue())); } // hue: theme color (0 - 1) @@ -88,32 +89,40 @@ void Theme::actuallyUpdate(double hue, double multiplier) /// TABS if (lightWin) { - this->tabs.regular = {QColor("#444"), - {QColor("#fff"), QColor("#eee"), QColor("#fff")}, - {QColor("#fff"), QColor("#fff"), QColor("#fff")}}; - this->tabs.newMessage = {QColor("#222"), - {QColor("#fff"), QColor("#eee"), QColor("#fff")}, - {QColor("#bbb"), QColor("#bbb"), QColor("#bbb")}}; - this->tabs.highlighted = {fg, - {QColor("#fff"), QColor("#eee"), QColor("#fff")}, - {highlighted, highlighted, highlighted}}; - this->tabs.selected = {QColor("#000"), - {QColor("#b4d7ff"), QColor("#b4d7ff"), QColor("#b4d7ff")}, - {QColor("#00aeef"), QColor("#00aeef"), QColor("#00aeef")}}; + this->tabs.regular = { + QColor("#444"), + {QColor("#fff"), QColor("#eee"), QColor("#fff")}, + {QColor("#fff"), QColor("#fff"), QColor("#fff")}}; + this->tabs.newMessage = { + QColor("#222"), + {QColor("#fff"), QColor("#eee"), QColor("#fff")}, + {QColor("#bbb"), QColor("#bbb"), QColor("#bbb")}}; + this->tabs.highlighted = { + fg, + {QColor("#fff"), QColor("#eee"), QColor("#fff")}, + {highlighted, highlighted, highlighted}}; + this->tabs.selected = { + QColor("#000"), + {QColor("#b4d7ff"), QColor("#b4d7ff"), QColor("#b4d7ff")}, + {QColor("#00aeef"), QColor("#00aeef"), QColor("#00aeef")}}; } else { - this->tabs.regular = {QColor("#aaa"), - {QColor("#252525"), QColor("#252525"), QColor("#252525")}, - {QColor("#444"), QColor("#444"), QColor("#444")}}; - this->tabs.newMessage = {fg, - {QColor("#252525"), QColor("#252525"), QColor("#252525")}, - {QColor("#888"), QColor("#888"), QColor("#888")}}; - this->tabs.highlighted = {fg, - {QColor("#252525"), QColor("#252525"), QColor("#252525")}, - {highlighted, highlighted, highlighted}}; + this->tabs.regular = { + QColor("#aaa"), + {QColor("#252525"), QColor("#252525"), QColor("#252525")}, + {QColor("#444"), QColor("#444"), QColor("#444")}}; + this->tabs.newMessage = { + fg, + {QColor("#252525"), QColor("#252525"), QColor("#252525")}, + {QColor("#888"), QColor("#888"), QColor("#888")}}; + this->tabs.highlighted = { + fg, + {QColor("#252525"), QColor("#252525"), QColor("#252525")}, + {highlighted, highlighted, highlighted}}; - this->tabs.selected = {QColor("#fff"), - {QColor("#555555"), QColor("#555555"), QColor("#555555")}, - {QColor("#00aeef"), QColor("#00aeef"), QColor("#00aeef")}}; + this->tabs.selected = { + QColor("#fff"), + {QColor("#555555"), QColor("#555555"), QColor("#555555")}, + {QColor("#00aeef"), QColor("#00aeef"), QColor("#00aeef")}}; } this->splits.input.focusedLine = highlighted; @@ -126,16 +135,19 @@ void Theme::actuallyUpdate(double hue, double multiplier) // fg, // {QBrush(blendColors(themeColor, "#ccc", 0.9), Qt::FDiagPattern), // QBrush(blendColors(themeColor, "#ccc", 0.9), Qt::FDiagPattern), - // QBrush(blendColors(themeColorNoSat, "#ccc", 0.9), Qt::FDiagPattern)}}; + // QBrush(blendColors(themeColorNoSat, "#ccc", 0.9), + // Qt::FDiagPattern)}}; // this->tabs.newMessage = { // fg, - // {QBrush(blendColors(themeColor, "#666", 0.7), Qt::FDiagPattern), - // QBrush(blendColors(themeColor, "#666", 0.5), Qt::FDiagPattern), + // {QBrush(blendColors(themeColor, "#666", 0.7), + // Qt::FDiagPattern), + // QBrush(blendColors(themeColor, "#666", 0.5), + // Qt::FDiagPattern), // QBrush(blendColors(themeColorNoSat, "#666", 0.7), // Qt::FDiagPattern)}}; - // this->tabs.highlighted = {fg, {QColor("#777"), QColor("#777"), - // QColor("#666")}}; + // this->tabs.highlighted = {fg, {QColor("#777"), + // QColor("#777"), QColor("#666")}}; this->tabs.bottomLine = this->tabs.selected.backgrounds.regular.color(); } @@ -143,7 +155,8 @@ void Theme::actuallyUpdate(double hue, double multiplier) // Split bool flat = isLight_; - this->splits.messageSeperator = isLight_ ? QColor(127, 127, 127) : QColor(60, 60, 60); + this->splits.messageSeperator = + isLight_ ? QColor(127, 127, 127) : QColor(60, 60, 60); this->splits.background = getColor(0, sat, 1); this->splits.dropPreview = QColor(0, 148, 255, 0x30); this->splits.dropPreviewBorder = QColor(0, 148, 255, 0xff); @@ -165,20 +178,23 @@ void Theme::actuallyUpdate(double hue, double multiplier) this->splits.header.background = getColor(0, sat, flat ? 1 : 0.9); this->splits.header.border = getColor(0, sat, flat ? 1 : 0.85); this->splits.header.text = this->messages.textColors.regular; - this->splits.header.focusedText = isLight_ ? QColor("#198CFF") : QColor("#84C1FF"); + this->splits.header.focusedText = + isLight_ ? QColor("#198CFF") : QColor("#84C1FF"); this->splits.input.background = getColor(0, sat, flat ? 0.95 : 0.95); this->splits.input.border = getColor(0, sat, flat ? 1 : 1); this->splits.input.text = this->messages.textColors.regular; this->splits.input.styleSheet = "background:" + this->splits.input.background.name() + ";" + - "border:" + this->tabs.selected.backgrounds.regular.color().name() + ";" + - "color:" + this->messages.textColors.regular.name() + ";" + // + "border:" + this->tabs.selected.backgrounds.regular.color().name() + + ";" + "color:" + this->messages.textColors.regular.name() + ";" + // "selection-background-color:" + - (isLight_ ? "#68B1FF" : this->tabs.selected.backgrounds.regular.color().name()); + (isLight_ ? "#68B1FF" + : this->tabs.selected.backgrounds.regular.color().name()); // Message - this->messages.textColors.link = isLight_ ? QColor(66, 134, 244) : QColor(66, 134, 244); + this->messages.textColors.link = + isLight_ ? QColor(66, 134, 244) : QColor(66, 134, 244); this->messages.textColors.system = QColor(140, 127, 127); this->messages.backgrounds.regular = splits.background; @@ -212,12 +228,14 @@ void Theme::actuallyUpdate(double hue, double multiplier) this->tooltip.text = QColor(255, 255, 255); // Selection - this->messages.selection = isLightTheme() ? QColor(0, 0, 0, 64) : QColor(255, 255, 255, 64); + this->messages.selection = + isLightTheme() ? QColor(0, 0, 0, 64) : QColor(255, 255, 255, 64); this->updated.invoke(); } -QColor Theme::blendColors(const QColor &color1, const QColor &color2, qreal ratio) +QColor Theme::blendColors(const QColor &color1, const QColor &color2, + qreal ratio) { int r = int(color1.red() * (1 - ratio) + color2.red() * ratio); int g = int(color1.green() * (1 - ratio) + color2.green() * ratio); @@ -233,21 +251,24 @@ void Theme::normalizeColor(QColor &color) color.setHslF(color.hueF(), color.saturationF(), 0.5); } - if (color.lightnessF() > 0.4 && color.hueF() > 0.1 && color.hueF() < 0.33333) { - color.setHslF( - color.hueF(), color.saturationF(), - color.lightnessF() - sin((color.hueF() - 0.1) / (0.3333 - 0.1) * 3.14159) * - color.saturationF() * 0.4); + if (color.lightnessF() > 0.4 && color.hueF() > 0.1 && + color.hueF() < 0.33333) { + color.setHslF(color.hueF(), color.saturationF(), + color.lightnessF() - sin((color.hueF() - 0.1) / + (0.3333 - 0.1) * 3.14159) * + color.saturationF() * 0.4); } } else { if (color.lightnessF() < 0.5) { color.setHslF(color.hueF(), color.saturationF(), 0.5); } - if (color.lightnessF() < 0.6 && color.hueF() > 0.54444 && color.hueF() < 0.83333) { + if (color.lightnessF() < 0.6 && color.hueF() > 0.54444 && + color.hueF() < 0.83333) { color.setHslF( color.hueF(), color.saturationF(), - color.lightnessF() + sin((color.hueF() - 0.54444) / (0.8333 - 0.54444) * 3.14159) * + color.lightnessF() + sin((color.hueF() - 0.54444) / + (0.8333 - 0.54444) * 3.14159) * color.saturationF() * 0.4); } } diff --git a/src/singletons/Theme.hpp b/src/singletons/Theme.hpp index 25a978271..47bb6c3ef 100644 --- a/src/singletons/Theme.hpp +++ b/src/singletons/Theme.hpp @@ -135,8 +135,8 @@ public: private: void actuallyUpdate(double hue, double multiplier); QColor blendColors(const QColor &color1, const QColor &color2, qreal ratio); - void fillLookupTableValues(double (&array)[360], double from, double to, double fromValue, - double toValue); + void fillLookupTableValues(double (&array)[360], double from, double to, + double fromValue, double toValue); double middleLookupTable_[360] = {}; double minLookupTable_[360] = {}; diff --git a/src/singletons/Updates.cpp b/src/singletons/Updates.cpp index a251b39e1..d56a8f510 100644 --- a/src/singletons/Updates.cpp +++ b/src/singletons/Updates.cpp @@ -44,10 +44,11 @@ void Updates::installUpdates() } #ifdef Q_OS_WIN - QMessageBox *box = new QMessageBox(QMessageBox::Information, "Chatterino Update", - "Chatterino is downloading the update " - "in the background and will run the " - "updater once it is finished."); + QMessageBox *box = + new QMessageBox(QMessageBox::Information, "Chatterino Update", + "Chatterino is downloading the update " + "in the background and will run the " + "updater once it is finished."); box->setAttribute(Qt::WA_DeleteOnClose); box->show(); @@ -57,8 +58,9 @@ void Updates::installUpdates() this->setStatus_(DownloadFailed); postToThread([] { - QMessageBox *box = new QMessageBox(QMessageBox::Information, "Chatterino Update", - "Failed while trying to download the update."); + QMessageBox *box = + new QMessageBox(QMessageBox::Information, "Chatterino Update", + "Failed while trying to download the update."); box->setAttribute(Qt::WA_DeleteOnClose); box->show(); box->raise(); @@ -80,7 +82,8 @@ void Updates::installUpdates() } QProcess::startDetached( - combinePath(QCoreApplication::applicationDirPath(), "updater.1/ChatterinoUpdater.exe"), + combinePath(QCoreApplication::applicationDirPath(), + "updater.1/ChatterinoUpdater.exe"), {filename, "restart"}); QApplication::exit(0); @@ -94,7 +97,9 @@ void Updates::installUpdates() void Updates::checkForUpdates() { #ifdef Q_OS_WIN - QString url = "https://notitia.chatterino.com/version/chatterino/" CHATTERINO_OS "/stable"; + QString url = + "https://notitia.chatterino.com/version/chatterino/" CHATTERINO_OS + "/stable"; NetworkRequest req(url); req.setTimeout(30000); @@ -110,7 +115,8 @@ void Updates::checkForUpdates() postToThread([] { QMessageBox *box = new QMessageBox( QMessageBox::Information, "Chatterino Update", - "Error while searching for updates.\n\nEither the service is down " + "Error while searching for updates.\n\nEither the service " + "is down " "temporarily or everything is broken."); box->setAttribute(Qt::WA_DeleteOnClose); box->show(); @@ -125,11 +131,11 @@ void Updates::checkForUpdates() if (this->currentVersion_ != this->onlineVersion_) { this->setStatus_(UpdateAvailable); postToThread([this] { - QMessageBox *box = - new QMessageBox(QMessageBox::Information, "Chatterino Update", - "An update for chatterino is available.\n\nDo you " - "want to download and install it?", - QMessageBox::Yes | QMessageBox::No); + QMessageBox *box = new QMessageBox( + QMessageBox::Information, "Chatterino Update", + "An update for chatterino is available.\n\nDo you " + "want to download and install it?", + QMessageBox::Yes | QMessageBox::No); box->setAttribute(Qt::WA_DeleteOnClose); box->show(); box->raise(); diff --git a/src/singletons/WindowManager.cpp b/src/singletons/WindowManager.cpp index 6825ada39..9f853b20c 100644 --- a/src/singletons/WindowManager.cpp +++ b/src/singletons/WindowManager.cpp @@ -93,14 +93,17 @@ void WindowManager::updateWordTypeMask() } // emotes - flags |= settings->enableTwitchEmotes ? MEF::TwitchEmoteImage : MEF::TwitchEmoteText; + flags |= settings->enableTwitchEmotes ? MEF::TwitchEmoteImage + : MEF::TwitchEmoteText; flags |= settings->enableFfzEmotes ? MEF::FfzEmoteImage : MEF::FfzEmoteText; - flags |= settings->enableBttvEmotes ? MEF::BttvEmoteImage : MEF::BttvEmoteText; + flags |= + settings->enableBttvEmotes ? MEF::BttvEmoteImage : MEF::BttvEmoteText; flags |= settings->enableEmojis ? MEF::EmojiImage : MEF::EmojiText; // bits flags |= MEF::BitsAmount; - flags |= settings->enableGifAnimations ? MEF::BitsAnimated : MEF::BitsStatic; + flags |= + settings->enableGifAnimations ? MEF::BitsAnimated : MEF::BitsStatic; // badges flags |= settings->showBadges ? MEF::Badges : MEF::None; @@ -111,8 +114,10 @@ void WindowManager::updateWordTypeMask() // misc flags |= MEF::AlwaysShow; flags |= MEF::Collapsed; - flags |= settings->enableUsernameBold ? MEF::BoldUsername : MEF::NonBoldUsername; - flags |= settings->enableLowercaseLink ? MEF::LowercaseLink : MEF::OriginalLink; + flags |= + settings->enableUsernameBold ? MEF::BoldUsername : MEF::NonBoldUsername; + flags |= + settings->enableLowercaseLink ? MEF::LowercaseLink : MEF::OriginalLink; // update flags MessageElement::Flags newFlags = static_cast(flags); @@ -180,7 +185,8 @@ Window &WindowManager::createWindow(Window::Type type) window->setAttribute(Qt::WA_DeleteOnClose); QObject::connect(window, &QWidget::destroyed, [this, window] { - for (auto it = this->windows_.begin(); it != this->windows_.end(); it++) { + for (auto it = this->windows_.begin(); it != this->windows_.end(); + it++) { if (*it == window) { this->windows_.erase(it); break; @@ -232,7 +238,8 @@ void WindowManager::initialize(Settings &settings, Paths &paths) // get type QString type_val = window_obj.value("type").toString(); - Window::Type type = type_val == "main" ? Window::Type::Main : Window::Type::Popup; + Window::Type type = + type_val == "main" ? Window::Type::Main : Window::Type::Popup; if (type == Window::Type::Main && mainWindow_ != nullptr) { type = Window::Type::Popup; @@ -304,14 +311,18 @@ void WindowManager::initialize(Settings &settings, Paths &paths) mainWindow_->getNotebook().addPage(true); } - settings.timestampFormat.connect([this](auto, auto) { this->layoutChannelViews(); }); + settings.timestampFormat.connect( + [this](auto, auto) { this->layoutChannelViews(); }); - settings.emoteScale.connect([this](auto, auto) { this->forceLayoutChannelViews(); }); + settings.emoteScale.connect( + [this](auto, auto) { this->forceLayoutChannelViews(); }); - settings.timestampFormat.connect([this](auto, auto) { this->forceLayoutChannelViews(); }); + settings.timestampFormat.connect( + [this](auto, auto) { this->forceLayoutChannelViews(); }); settings.alternateMessageBackground.connect( [this](auto, auto) { this->forceLayoutChannelViews(); }); - settings.separateMessages.connect([this](auto, auto) { this->forceLayoutChannelViews(); }); + settings.separateMessages.connect( + [this](auto, auto) { this->forceLayoutChannelViews(); }); settings.collpseMessagesMinLines.connect( [this](auto, auto) { this->forceLayoutChannelViews(); }); @@ -352,10 +363,11 @@ void WindowManager::save() // window tabs QJsonArray tabs_arr; - for (int tab_i = 0; tab_i < window->getNotebook().getPageCount(); tab_i++) { + for (int tab_i = 0; tab_i < window->getNotebook().getPageCount(); + tab_i++) { QJsonObject tab_obj; - SplitContainer *tab = - dynamic_cast(window->getNotebook().getPageAt(tab_i)); + SplitContainer *tab = dynamic_cast( + window->getNotebook().getPageAt(tab_i)); assert(tab != nullptr); // custom tab title @@ -415,8 +427,9 @@ void WindowManager::encodeNodeRecusively(SplitNode *node, QJsonObject &obj) } break; case SplitNode::HorizontalContainer: case SplitNode::VerticalContainer: { - obj.insert("type", node->getType() == SplitNode::HorizontalContainer ? "horizontal" - : "vertical"); + obj.insert("type", node->getType() == SplitNode::HorizontalContainer + ? "horizontal" + : "vertical"); QJsonArray items_arr; for (const std::unique_ptr &n : node->getChildren()) { @@ -458,7 +471,8 @@ IndirectChannel WindowManager::decodeChannel(const QJsonObject &obj) QString type = obj.value("type").toString(); if (type == "twitch") { - return app->twitch.server->getOrAddChannel(obj.value("name").toString()); + return app->twitch.server->getOrAddChannel( + obj.value("name").toString()); } else if (type == "mentions") { return app->twitch.server->mentionsChannel; } else if (type == "watching") { diff --git a/src/singletons/helper/LoggingChannel.cpp b/src/singletons/helper/LoggingChannel.cpp index cce98a505..0c33fcf0b 100644 --- a/src/singletons/helper/LoggingChannel.cpp +++ b/src/singletons/helper/LoggingChannel.cpp @@ -21,7 +21,8 @@ LoggingChannel::LoggingChannel(const QString &_channelName) } else if (channelName.startsWith("/mentions")) { this->subDirectory = "Mentions"; } else { - this->subDirectory = QStringLiteral("Channels") + QDir::separator() + channelName; + this->subDirectory = + QStringLiteral("Channels") + QDir::separator() + channelName; } // FOURTF: change this when adding more providers @@ -60,7 +61,8 @@ void LoggingChannel::openLogFile() QString baseFileName = this->channelName + "-" + this->dateString + ".log"; - QString directory = this->baseDirectory + QDir::separator() + this->subDirectory; + QString directory = + this->baseDirectory + QDir::separator() + this->subDirectory; if (!QDir().mkpath(directory)) { Log("Unable to create logging path"); diff --git a/src/singletons/helper/LoggingChannel.hpp b/src/singletons/helper/LoggingChannel.hpp index 985ab27b9..3f327538f 100644 --- a/src/singletons/helper/LoggingChannel.hpp +++ b/src/singletons/helper/LoggingChannel.hpp @@ -24,8 +24,10 @@ public: private: void openLogFile(); - QString generateOpeningString(const QDateTime &now = QDateTime::currentDateTime()) const; - QString generateClosingString(const QDateTime &now = QDateTime::currentDateTime()) const; + QString generateOpeningString( + const QDateTime &now = QDateTime::currentDateTime()) const; + QString generateClosingString( + const QDateTime &now = QDateTime::currentDateTime()) const; void appendLine(const QString &line); diff --git a/src/util/ConcurrentMap.hpp b/src/util/ConcurrentMap.hpp index 84cf98365..281f3ce46 100644 --- a/src/util/ConcurrentMap.hpp +++ b/src/util/ConcurrentMap.hpp @@ -65,7 +65,8 @@ public: this->data_.insert(name, value); } - void each(std::function func) const + void each( + std::function func) const { QMutexLocker lock(&this->mutex_); diff --git a/src/util/InitUpdateButton.cpp b/src/util/InitUpdateButton.cpp index acb584175..d10ba2bc1 100644 --- a/src/util/InitUpdateButton.cpp +++ b/src/util/InitUpdateButton.cpp @@ -5,7 +5,8 @@ namespace chatterino { -void initUpdateButton(RippleEffectButton &button, std::unique_ptr &handle, +void initUpdateButton(RippleEffectButton &button, + std::unique_ptr &handle, pajlada::Signals::SignalHolder &signalHolder) { button.hide(); @@ -16,7 +17,8 @@ void initUpdateButton(RippleEffectButton &button, std::unique_ptr auto dialog = new UpdateDialog(); dialog->setActionOnFocusLoss(BaseWindow::Delete); - dialog->move(button.mapToGlobal(QPoint(int(-100 * button.getScale()), button.height()))); + dialog->move(button.mapToGlobal( + QPoint(int(-100 * button.getScale()), button.height()))); dialog->show(); dialog->raise(); @@ -39,15 +41,17 @@ void initUpdateButton(RippleEffectButton &button, std::unique_ptr auto updateChange = [&button](auto) { button.setVisible(Updates::getInstance().shouldShowUpdateButton()); - auto imageUrl = Updates::getInstance().isError() ? ":/images/download_update_error.png" - : ":/images/download_update.png"; + auto imageUrl = Updates::getInstance().isError() + ? ":/images/download_update_error.png" + : ":/images/download_update.png"; button.setPixmap(QPixmap(imageUrl)); }; updateChange(Updates::getInstance().getStatus()); - signalHolder.managedConnect(Updates::getInstance().statusUpdated, - [updateChange](auto status) { updateChange(status); }); + signalHolder.managedConnect( + Updates::getInstance().statusUpdated, + [updateChange](auto status) { updateChange(status); }); } } // namespace chatterino diff --git a/src/util/InitUpdateButton.hpp b/src/util/InitUpdateButton.hpp index 6a0966e54..17237d593 100644 --- a/src/util/InitUpdateButton.hpp +++ b/src/util/InitUpdateButton.hpp @@ -13,7 +13,8 @@ namespace chatterino { class RippleEffectButton; class UpdateDialog; -void initUpdateButton(RippleEffectButton &button, std::unique_ptr &handle, +void initUpdateButton(RippleEffectButton &button, + std::unique_ptr &handle, pajlada::Signals::SignalHolder &signalHolder); } // namespace chatterino diff --git a/src/util/LayoutCreator.hpp b/src/util/LayoutCreator.hpp index af01db373..c519b7659 100644 --- a/src/util/LayoutCreator.hpp +++ b/src/util/LayoutCreator.hpp @@ -53,7 +53,8 @@ public: } template ::value, int>::type = 0> + typename std::enable_if::value, + int>::type = 0> LayoutCreator emplaceScrollAreaWidget() { QWidget *widget = new QWidget; @@ -62,8 +63,10 @@ public: } template ::value, int>::type = 0, - typename std::enable_if::value, int>::type = 0> + typename std::enable_if::value, + int>::type = 0, + typename std::enable_if::value, + int>::type = 0> LayoutCreator setLayoutType() { T2 *layout = new T2; @@ -81,7 +84,8 @@ public: } template ::value, int>::type = 0> + typename std::enable_if::value, + int>::type = 0> LayoutCreator withoutMargin() { this->item_->setContentsMargins(0, 0, 0, 0); @@ -90,7 +94,8 @@ public: } template ::value, int>::type = 0> + typename std::enable_if::value, + int>::type = 0> LayoutCreator hidden() { this->item_->setVisible(false); @@ -99,10 +104,12 @@ public: } template ::value, int>::type = 0> + typename std::enable_if::value, + int>::type = 0> LayoutCreator appendTab(T2 *item, const QString &title) { - static_assert(std::is_base_of::value, "needs to be QLayout"); + static_assert(std::is_base_of::value, + "needs to be QLayout"); QWidget *widget = new QWidget; widget->setLayout(item); @@ -116,14 +123,16 @@ private: T *item_; template ::value, int>::type = 0> + typename std::enable_if::value, + int>::type = 0> void addItem(QLayout *layout, T2 *item) { layout->addWidget(item); } template ::value, int>::type = 0> + typename std::enable_if::value, + int>::type = 0> void addItem(QLayout *layout, T2 *item) { QWidget *widget = new QWidget(); @@ -132,14 +141,16 @@ private: } template ::value, int>::type = 0> + typename std::enable_if::value, + int>::type = 0> QLayout *getOrCreateLayout() { return this->item_; } template ::value, int>::type = 0> + typename std::enable_if::value, + int>::type = 0> QLayout *getOrCreateLayout() { if (!this->item_->layout()) { diff --git a/src/util/PostToThread.hpp b/src/util/PostToThread.hpp index ddf5caa12..ab0fbe1cb 100644 --- a/src/util/PostToThread.hpp +++ b/src/util/PostToThread.hpp @@ -7,7 +7,8 @@ #include -#define async_exec(a) QThreadPool::globalInstance()->start(new LambdaRunnable(a)); +#define async_exec(a) \ + QThreadPool::globalInstance()->start(new LambdaRunnable(a)); namespace chatterino { diff --git a/src/util/RapidjsonHelpers.hpp b/src/util/RapidjsonHelpers.hpp index 25e72ed4b..db6db99f4 100644 --- a/src/util/RapidjsonHelpers.hpp +++ b/src/util/RapidjsonHelpers.hpp @@ -26,7 +26,8 @@ void set(rapidjson::Value &obj, const char *key, const Type &value, } template <> -inline void set(rapidjson::Value &obj, const char *key, const rapidjson::Value &value, +inline void set(rapidjson::Value &obj, const char *key, + const rapidjson::Value &value, rapidjson::Document::AllocatorType &a) { assert(obj.IsObject()); @@ -45,7 +46,8 @@ void set(rapidjson::Document &obj, const char *key, const Type &value) } template <> -inline void set(rapidjson::Document &obj, const char *key, const rapidjson::Value &value) +inline void set(rapidjson::Document &obj, const char *key, + const rapidjson::Value &value) { assert(obj.IsObject()); @@ -55,7 +57,8 @@ inline void set(rapidjson::Document &obj, const char *key, const rapidjson::Valu } template -void add(rapidjson::Value &arr, const Type &value, rapidjson::Document::AllocatorType &a) +void add(rapidjson::Value &arr, const Type &value, + rapidjson::Document::AllocatorType &a) { assert(arr.IsArray()); diff --git a/src/util/RemoveScrollAreaBackground.hpp b/src/util/RemoveScrollAreaBackground.hpp index 66629c4e7..b82bbeea2 100644 --- a/src/util/RemoveScrollAreaBackground.hpp +++ b/src/util/RemoveScrollAreaBackground.hpp @@ -4,7 +4,8 @@ namespace chatterino { -static void removeScrollAreaBackground(QScrollArea *scrollArea, QWidget *childWidget) +static void removeScrollAreaBackground(QScrollArea *scrollArea, + QWidget *childWidget) { scrollArea->setWidgetResizable(true); scrollArea->setFrameStyle(0); diff --git a/src/util/SharedPtrElementLess.hpp b/src/util/SharedPtrElementLess.hpp index 0fa121a1d..b88f20230 100644 --- a/src/util/SharedPtrElementLess.hpp +++ b/src/util/SharedPtrElementLess.hpp @@ -6,7 +6,8 @@ namespace chatterino { template struct SharedPtrElementLess { - bool operator()(const std::shared_ptr &a, const std::shared_ptr &b) const + bool operator()(const std::shared_ptr &a, + const std::shared_ptr &b) const { return a->operator<(*b); } diff --git a/src/util/StandardItemHelper.hpp b/src/util/StandardItemHelper.hpp index 860dddc2a..4638e7277 100644 --- a/src/util/StandardItemHelper.hpp +++ b/src/util/StandardItemHelper.hpp @@ -4,19 +4,21 @@ namespace chatterino { -static void setBoolItem(QStandardItem *item, bool value, bool userCheckable = true, - bool selectable = true) +static void setBoolItem(QStandardItem *item, bool value, + bool userCheckable = true, bool selectable = true) { - item->setFlags((Qt::ItemFlags)(Qt::ItemIsEnabled | (selectable ? Qt::ItemIsSelectable : 0) | - (userCheckable ? Qt::ItemIsUserCheckable : 0))); + item->setFlags((Qt::ItemFlags)( + Qt::ItemIsEnabled | (selectable ? Qt::ItemIsSelectable : 0) | + (userCheckable ? Qt::ItemIsUserCheckable : 0))); item->setCheckState(value ? Qt::Checked : Qt::Unchecked); } -static void setStringItem(QStandardItem *item, const QString &value, bool editable = true, - bool selectable = true) +static void setStringItem(QStandardItem *item, const QString &value, + bool editable = true, bool selectable = true) { item->setData(value, Qt::EditRole); - item->setFlags((Qt::ItemFlags)(Qt::ItemIsEnabled | (selectable ? Qt::ItemIsSelectable : 0) | + item->setFlags((Qt::ItemFlags)(Qt::ItemIsEnabled | + (selectable ? Qt::ItemIsSelectable : 0) | (editable ? (Qt::ItemIsEditable) : 0))); } diff --git a/src/util/StreamLink.cpp b/src/util/StreamLink.cpp index 312f027d2..2fd2ef0a3 100644 --- a/src/util/StreamLink.cpp +++ b/src/util/StreamLink.cpp @@ -50,7 +50,8 @@ bool checkStreamlinkPath(const QString &path) if (!fileinfo.exists()) { return false; - // throw Exception(fS("Streamlink path ({}) is invalid, file does not exist", path)); + // throw Exception(fS("Streamlink path ({}) is invalid, file does not + // exist", path)); } return fileinfo.isExecutable(); @@ -63,11 +64,13 @@ void showStreamlinkNotFoundError() auto app = getApp(); if (app->settings->streamlinkUseCustomPath) { msg->showMessage( - "Unable to find Streamlink executable\nMake sure your custom path is pointing " + "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"); + msg->showMessage( + "Unable to find Streamlink executable.\nIf you have Streamlink " + "installed, you might need to enable the custom path option"); } } @@ -86,51 +89,58 @@ QProcess *createStreamlinkProcess() p->deleteLater(); }); - QObject::connect(p, static_cast(&QProcess::finished), [=](int res) { - p->deleteLater(); // - }); + QObject::connect(p, + static_cast(&QProcess::finished), + [=](int res) { + p->deleteLater(); // + }); return p; } } // namespace -void getStreamQualities(const QString &channelURL, std::function cb) +void getStreamQualities(const QString &channelURL, + std::function cb) { auto p = createStreamlinkProcess(); - QObject::connect(p, static_cast(&QProcess::finished), [=](int res) { - if (res != 0) { - qDebug() << "Got error code" << res; - // return; - } - QString lastLine = QString(p->readAllStandardOutput()); - lastLine = lastLine.trimmed().split('\n').last().trimmed(); - if (lastLine.startsWith("Available streams: ")) { - QStringList options; - QStringList split = lastLine.right(lastLine.length() - 19).split(", "); - - for (int i = split.length() - 1; i >= 0; i--) { - QString option = split.at(i); - if (option.endsWith(" (worst)")) { - options << option.left(option.length() - 8); - } else if (option.endsWith(" (best)")) { - options << option.left(option.length() - 7); - } else { - options << option; - } + QObject::connect( + p, static_cast(&QProcess::finished), + [=](int res) { + if (res != 0) { + qDebug() << "Got error code" << res; + // return; } + QString lastLine = QString(p->readAllStandardOutput()); + lastLine = lastLine.trimmed().split('\n').last().trimmed(); + if (lastLine.startsWith("Available streams: ")) { + QStringList options; + QStringList split = + lastLine.right(lastLine.length() - 19).split(", "); - cb(options); - } - }); + for (int i = split.length() - 1; i >= 0; i--) { + QString option = split.at(i); + if (option.endsWith(" (worst)")) { + options << option.left(option.length() - 8); + } else if (option.endsWith(" (best)")) { + options << option.left(option.length() - 7); + } else { + options << option; + } + } + + cb(options); + } + }); p->setArguments({channelURL, "--default-stream=KKona"}); p->start(); } -void openStreamlink(const QString &channelURL, const QString &quality, QStringList extraArguments) +void openStreamlink(const QString &channelURL, const QString &quality, + QStringList extraArguments) { auto app = getApp(); @@ -149,7 +159,8 @@ void openStreamlink(const QString &channelURL, const QString &quality, QStringLi arguments << quality; } - bool res = QProcess::startDetached(getStreamlinkProgram() + " " + QString(arguments.join(' '))); + bool res = QProcess::startDetached(getStreamlinkProgram() + " " + + QString(arguments.join(' '))); if (!res) { showStreamlinkNotFoundError(); diff --git a/src/util/StreamLink.hpp b/src/util/StreamLink.hpp index 2c5eebf4a..99dbb95b9 100644 --- a/src/util/StreamLink.hpp +++ b/src/util/StreamLink.hpp @@ -15,12 +15,13 @@ public: }; // Open streamlink for given channel, quality and extra arguments -// the "Additional arguments" are fetched and added at the beginning of the streamlink call +// the "Additional arguments" are fetched and added at the beginning of the +// streamlink call void openStreamlink(const QString &channelURL, const QString &quality, QStringList extraArguments = QStringList()); -// Start opening streamlink for the given channel, reading settings like quality from settings -// and opening a quality dialog if the quality is "Choose" +// Start opening streamlink for the given channel, reading settings like quality +// from settings and opening a quality dialog if the quality is "Choose" void openStreamlinkForChannel(const QString &channel); } // namespace chatterino diff --git a/src/util/WindowsHelper.cpp b/src/util/WindowsHelper.cpp index 743362ade..38ca74698 100644 --- a/src/util/WindowsHelper.cpp +++ b/src/util/WindowsHelper.cpp @@ -11,14 +11,17 @@ typedef enum MONITOR_DPI_TYPE { MDT_DEFAULT = MDT_EFFECTIVE_DPI } MONITOR_DPI_TYPE; -typedef HRESULT(CALLBACK *GetDpiForMonitor_)(HMONITOR, MONITOR_DPI_TYPE, UINT *, UINT *); +typedef HRESULT(CALLBACK *GetDpiForMonitor_)(HMONITOR, MONITOR_DPI_TYPE, UINT *, + UINT *); boost::optional getWindowDpi(HWND hwnd) { static HINSTANCE shcore = LoadLibrary(L"Shcore.dll"); if (shcore != nullptr) { - if (auto getDpiForMonitor = GetDpiForMonitor_(GetProcAddress(shcore, "GetDpiForMonitor"))) { - HMONITOR monitor = MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST); + if (auto getDpiForMonitor = + GetDpiForMonitor_(GetProcAddress(shcore, "GetDpiForMonitor"))) { + HMONITOR monitor = + MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST); UINT xScale, yScale; diff --git a/src/widgets/AccountSwitchWidget.cpp b/src/widgets/AccountSwitchWidget.cpp index 3b2acc268..9c307ba73 100644 --- a/src/widgets/AccountSwitchWidget.cpp +++ b/src/widgets/AccountSwitchWidget.cpp @@ -39,10 +39,12 @@ AccountSwitchWidget::AccountSwitchWidget(QWidget *parent) QObject::connect(this, &QListWidget::clicked, [=] { if (!this->selectedItems().isEmpty()) { QString newUsername = this->currentItem()->text(); - if (newUsername.compare(ANONYMOUS_USERNAME_LABEL, Qt::CaseInsensitive) == 0) { + if (newUsername.compare(ANONYMOUS_USERNAME_LABEL, + Qt::CaseInsensitive) == 0) { app->accounts->twitch.currentUsername = ""; } else { - app->accounts->twitch.currentUsername = newUsername.toStdString(); + app->accounts->twitch.currentUsername = + newUsername.toStdString(); } } }); @@ -70,7 +72,8 @@ void AccountSwitchWidget::refreshSelection() for (int i = 0; i < this->count(); ++i) { QString itemText = this->item(i)->text(); - if (itemText.compare(currentUsername, Qt::CaseInsensitive) == 0) { + if (itemText.compare(currentUsername, Qt::CaseInsensitive) == + 0) { this->setCurrentRow(i); break; } diff --git a/src/widgets/AttachedWindow.cpp b/src/widgets/AttachedWindow.cpp index 6fdf93680..b247129b6 100644 --- a/src/widgets/AttachedWindow.cpp +++ b/src/widgets/AttachedWindow.cpp @@ -129,14 +129,17 @@ void AttachedWindow::attachToHwnd(void *_attachedPtr) DWORD processId; ::GetWindowThreadProcessId(attached, &processId); - HANDLE process = - ::OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, false, processId); + HANDLE process = ::OpenProcess( + PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, false, processId); std::unique_ptr filename(new TCHAR[512]); - DWORD filenameLength = ::GetModuleFileNameEx(process, nullptr, filename.get(), 512); - QString qfilename = QString::fromWCharArray(filename.get(), filenameLength); + DWORD filenameLength = + ::GetModuleFileNameEx(process, nullptr, filename.get(), 512); + QString qfilename = + QString::fromWCharArray(filename.get(), filenameLength); - if (!qfilename.endsWith("chrome.exe") && !qfilename.endsWith("firefox.exe")) { + if (!qfilename.endsWith("chrome.exe") && + !qfilename.endsWith("firefox.exe")) { qDebug() << "NM Illegal caller" << qfilename; this->timer_.stop(); this->deleteLater(); @@ -157,9 +160,9 @@ void AttachedWindow::updateWindowRect(void *_attachedPtr) auto hwnd = HWND(this->winId()); auto attached = HWND(_attachedPtr); - // We get the window rect first so we can close this window when it returns an error. - // If we query the process first and check the filename then it will return and empty string - // that doens't match. + // We get the window rect first so we can close this window when it returns + // an error. If we query the process first and check the filename then it + // will return and empty string that doens't match. ::SetLastError(0); RECT rect; ::GetWindowRect(attached, &rect); @@ -189,21 +192,25 @@ void AttachedWindow::updateWindowRect(void *_attachedPtr) } if (this->height_ == -1) { - // ::MoveWindow(hwnd, rect.right - this->width_ - 8, rect.top + this->yOffset_ - 8, - // this->width_, rect.bottom - rect.top - this->yOffset_, false); + // ::MoveWindow(hwnd, rect.right - this->width_ - 8, rect.top + + // this->yOffset_ - 8, + // this->width_, rect.bottom - rect.top - this->yOffset_, + // false); } else { ::MoveWindow(hwnd, // int(rect.right - this->width_ * scale - 8), // int(rect.bottom - this->height_ * scale - 8), // - int(this->width_ * scale), int(this->height_ * scale), true); + int(this->width_ * scale), int(this->height_ * scale), + true); } -// ::MoveWindow(hwnd, rect.right - 360, rect.top + 82, 360 - 8, rect.bottom - -// rect.top - 82 - 8, false); +// ::MoveWindow(hwnd, rect.right - 360, rect.top + 82, 360 - 8, +// rect.bottom - rect.top - 82 - 8, false); #endif } -// void AttachedWindow::nativeEvent(const QByteArray &eventType, void *message, long *result) +// void AttachedWindow::nativeEvent(const QByteArray &eventType, void *message, +// long *result) //{ // MSG *msg = reinterpret_cast diff --git a/src/widgets/AttachedWindow.hpp b/src/widgets/AttachedWindow.hpp index b7a9ad617..80b030fca 100644 --- a/src/widgets/AttachedWindow.hpp +++ b/src/widgets/AttachedWindow.hpp @@ -28,8 +28,8 @@ public: protected: virtual void showEvent(QShowEvent *) override; - // virtual void nativeEvent(const QByteArray &eventType, void *message, long *result) - // override; + // virtual void nativeEvent(const QByteArray &eventType, void *message, + // long *result) override; private: struct { diff --git a/src/widgets/BaseWidget.cpp b/src/widgets/BaseWidget.cpp index 818d951a8..278fe9248 100644 --- a/src/widgets/BaseWidget.cpp +++ b/src/widgets/BaseWidget.cpp @@ -97,12 +97,14 @@ void BaseWidget::setScaleIndependantSize(QSize size) void BaseWidget::setScaleIndependantWidth(int value) { - this->setScaleIndependantSize(QSize(value, this->scaleIndependantSize_.height())); + this->setScaleIndependantSize( + QSize(value, this->scaleIndependantSize_.height())); } void BaseWidget::setScaleIndependantHeight(int value) { - this->setScaleIndependantSize(QSize(this->scaleIndependantSize_.height(), value)); + this->setScaleIndependantSize( + QSize(this->scaleIndependantSize_.height(), value)); } void BaseWidget::childEvent(QChildEvent *event) @@ -114,7 +116,8 @@ void BaseWidget::childEvent(QChildEvent *event) this->widgets_.push_back(widget); } } else if (event->removed()) { - for (auto it = this->widgets_.begin(); it != this->widgets_.end(); it++) { + for (auto it = this->widgets_.begin(); it != this->widgets_.end(); + it++) { if (*it == event->child()) { this->widgets_.erase(it); break; diff --git a/src/widgets/BaseWindow.cpp b/src/widgets/BaseWindow.cpp index 00a841684..424b96e6d 100644 --- a/src/widgets/BaseWindow.cpp +++ b/src/widgets/BaseWindow.cpp @@ -41,7 +41,8 @@ namespace chatterino { BaseWindow::BaseWindow(QWidget *parent, Flags _flags) : BaseWidget(parent, - Qt::Window | ((_flags & TopMost) ? Qt::WindowStaysOnTopHint : Qt::WindowFlags())) + Qt::Window | ((_flags & TopMost) ? Qt::WindowStaysOnTopHint + : Qt::WindowFlags())) , enableCustomFrame_(_flags & EnableCustomFrame) , frameless_(_flags & Frameless) , flags_(_flags) @@ -59,7 +60,8 @@ BaseWindow::BaseWindow(QWidget *parent, Flags _flags) this->updateScale(); - createWindowShortcut(this, "CTRL+0", [] { getApp()->settings->uiScale.setValue(0); }); + createWindowShortcut(this, "CTRL+0", + [] { getApp()->settings->uiScale.setValue(0); }); // QTimer::this->scaleChangedEvent(this->getScale()); } @@ -88,16 +90,19 @@ void BaseWindow::init() this->setLayout(layout); { if (!this->frameless_) { - QHBoxLayout *buttonLayout = this->ui_.titlebarBox = new QHBoxLayout(); + QHBoxLayout *buttonLayout = this->ui_.titlebarBox = + new QHBoxLayout(); buttonLayout->setMargin(0); layout->addLayout(buttonLayout); // title Label *title = new Label("Chatterino"); - QObject::connect(this, &QWidget::windowTitleChanged, - [title](const QString &text) { title->setText(text); }); + QObject::connect( + this, &QWidget::windowTitleChanged, + [title](const QString &text) { title->setText(text); }); - QSizePolicy policy(QSizePolicy::Ignored, QSizePolicy::Preferred); + QSizePolicy policy(QSizePolicy::Ignored, + QSizePolicy::Preferred); policy.setHorizontalStretch(1); // title->setBaseSize(0, 0); // title->setScaledContents(true); @@ -113,14 +118,18 @@ void BaseWindow::init() TitleBarButton *_exitButton = new TitleBarButton; _exitButton->setButtonStyle(TitleBarButton::Close); - QObject::connect(_minButton, &TitleBarButton::clicked, this, [this] { - this->setWindowState(Qt::WindowMinimized | this->windowState()); - }); - QObject::connect(_maxButton, &TitleBarButton::clicked, this, [this] { - this->setWindowState(this->windowState() == Qt::WindowMaximized - ? Qt::WindowActive - : Qt::WindowMaximized); - }); + QObject::connect(_minButton, &TitleBarButton::clicked, this, + [this] { + this->setWindowState(Qt::WindowMinimized | + this->windowState()); + }); + QObject::connect( + _maxButton, &TitleBarButton::clicked, this, [this] { + this->setWindowState(this->windowState() == + Qt::WindowMaximized + ? Qt::WindowActive + : Qt::WindowMaximized); + }); QObject::connect(_exitButton, &TitleBarButton::clicked, this, [this] { this->close(); }); @@ -157,8 +166,10 @@ void BaseWindow::init() QTimer::singleShot(1, this, [this] { getApp()->settings->windowTopMost.connect( [this](bool topMost, auto) { - ::SetWindowPos(HWND(this->winId()), topMost ? HWND_TOPMOST : HWND_NOTOPMOST, 0, - 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE); + ::SetWindowPos(HWND(this->winId()), + topMost ? HWND_TOPMOST : HWND_NOTOPMOST, 0, + 0, 0, 0, + SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE); }, this->managedConnections_); }); @@ -222,8 +233,9 @@ void BaseWindow::themeChangedEvent() if (this->ui_.titleLabel) { QPalette palette_title; - palette_title.setColor(QPalette::Foreground, - this->theme->isLightTheme() ? "#333" : "#ccc"); + palette_title.setColor( + QPalette::Foreground, + this->theme->isLightTheme() ? "#333" : "#ccc"); this->ui_.titleLabel->setPalette(palette_title); } @@ -240,7 +252,8 @@ void BaseWindow::themeChangedEvent() bool BaseWindow::event(QEvent *event) { - if (event->type() == QEvent::WindowDeactivate /*|| event->type() == QEvent::FocusOut*/) { + if (event->type() == + QEvent::WindowDeactivate /*|| event->type() == QEvent::FocusOut*/) { this->onFocusLost(); } @@ -255,11 +268,11 @@ void BaseWindow::wheelEvent(QWheelEvent *event) if (event->modifiers() & Qt::ControlModifier) { if (event->delta() > 0) { - getApp()->settings->uiScale.setValue( - WindowManager::clampUiScale(getApp()->settings->uiScale.getValue() + 1)); + getApp()->settings->uiScale.setValue(WindowManager::clampUiScale( + getApp()->settings->uiScale.getValue() + 1)); } else { - getApp()->settings->uiScale.setValue( - WindowManager::clampUiScale(getApp()->settings->uiScale.getValue() - 1)); + getApp()->settings->uiScale.setValue(WindowManager::clampUiScale( + getApp()->settings->uiScale.getValue() - 1)); } } } @@ -288,7 +301,8 @@ void BaseWindow::mousePressEvent(QMouseEvent *event) #ifndef Q_OS_WIN if (this->flags_ & FramelessDraggable) { this->movingRelativePos = event->localPos(); - if (auto widget = this->childAt(event->localPos().x(), event->localPos().y())) { + if (auto widget = + this->childAt(event->localPos().x(), event->localPos().y())) { std::function recursiveCheckMouseTracking; recursiveCheckMouseTracking = [&](QWidget *widget) { if (widget == nullptr) { @@ -341,8 +355,8 @@ void BaseWindow::mouseMoveEvent(QMouseEvent *event) BaseWidget::mouseMoveEvent(event); } -TitleBarButton *BaseWindow::addTitleBarButton(const TitleBarButton::Style &style, - std::function onClicked) +TitleBarButton *BaseWindow::addTitleBarButton( + const TitleBarButton::Style &style, std::function onClicked) { TitleBarButton *button = new TitleBarButton; button->setScaleIndependantSize(30, 30); @@ -351,7 +365,8 @@ TitleBarButton *BaseWindow::addTitleBarButton(const TitleBarButton::Style &style this->ui_.titlebarBox->insertWidget(1, button); button->setButtonStyle(style); - QObject::connect(button, &TitleBarButton::clicked, this, [onClicked] { onClicked(); }); + QObject::connect(button, &TitleBarButton::clicked, this, + [onClicked] { onClicked(); }); return button; } @@ -364,7 +379,8 @@ RippleEffectLabel *BaseWindow::addTitleBarLabel(std::function onClicked) this->ui_.buttons.push_back(button); this->ui_.titlebarBox->insertWidget(1, button); - QObject::connect(button, &RippleEffectLabel::clicked, this, [onClicked] { onClicked(); }); + QObject::connect(button, &RippleEffectLabel::clicked, this, + [onClicked] { onClicked(); }); return button; } @@ -375,7 +391,8 @@ void BaseWindow::changeEvent(QEvent *) #ifdef USEWINSDK if (this->ui_.maxButton) { - this->ui_.maxButton->setButtonStyle(this->windowState() & Qt::WindowMaximized + this->ui_.maxButton->setButtonStyle(this->windowState() & + Qt::WindowMaximized ? TitleBarButton::Unmaximize : TitleBarButton::Maximize); } @@ -416,8 +433,7 @@ void BaseWindow::closeEvent(QCloseEvent *) void BaseWindow::moveIntoDesktopRect(QWidget *parent) { - if (!this->stayInScreenRect_) - return; + if (!this->stayInScreenRect_) return; // move the widget into the screen geometry if it's not already in there QDesktopWidget *desktop = QApplication::desktop(); @@ -438,11 +454,11 @@ void BaseWindow::moveIntoDesktopRect(QWidget *parent) p.setY(s.bottom() - this->height()); } - if (p != this->pos()) - this->move(p); + if (p != this->pos()) this->move(p); } -bool BaseWindow::nativeEvent(const QByteArray &eventType, void *message, long *result) +bool BaseWindow::nativeEvent(const QByteArray &eventType, void *message, + long *result) { #ifdef USEWINSDK MSG *msg = reinterpret_cast(message); @@ -503,8 +519,10 @@ void BaseWindow::paintEvent(QPaintEvent *) void BaseWindow::updateScale() { - auto scale = this->nativeScale_ * - (this->flags_ & DisableCustomScaling ? 1 : getApp()->windows->getUiScaleValue()); + auto scale = + this->nativeScale_ * (this->flags_ & DisableCustomScaling + ? 1 + : getApp()->windows->getUiScaleValue()); this->setScale(scale); for (auto child : this->findChildren()) { @@ -541,9 +559,11 @@ void BaseWindow::drawCustomWindowFrame(QPainter &painter) if (this->hasCustomWindowFrame()) { QPainter painter(this); - QColor bg = this->overrideBackgroundColor_.value_or(this->theme->window.background); + QColor bg = this->overrideBackgroundColor_.value_or( + this->theme->window.background); - painter.fillRect(QRect(0, 1, this->width() - 0, this->height() - 0), bg); + painter.fillRect(QRect(0, 1, this->width() - 0, this->height() - 0), + bg); } #endif } @@ -561,7 +581,8 @@ bool BaseWindow::handleDPICHANGED(MSG *msg) auto *prcNewWindow = reinterpret_cast(msg->lParam); SetWindowPos(msg->hwnd, nullptr, prcNewWindow->left, prcNewWindow->top, prcNewWindow->right - prcNewWindow->left, - prcNewWindow->bottom - prcNewWindow->top, SWP_NOZORDER | SWP_NOACTIVATE); + prcNewWindow->bottom - prcNewWindow->top, + SWP_NOZORDER | SWP_NOACTIVATE); } firstResize = false; @@ -605,7 +626,8 @@ bool BaseWindow::handleNCCALCSIZE(MSG *msg, long *result) // int cy = GetSystemMetrics(SM_CYSIZEFRAME); if (msg->wParam == TRUE) { - NCCALCSIZE_PARAMS *ncp = (reinterpret_cast(msg->lParam)); + NCCALCSIZE_PARAMS *ncp = + (reinterpret_cast(msg->lParam)); ncp->lppos->flags |= SWP_NOREDRAW; RECT *clientRect = &ncp->rgrc[0]; @@ -634,7 +656,8 @@ bool BaseWindow::handleSIZE(MSG *msg) if (msg->wParam == SIZE_MAXIMIZED) { auto offset = int(this->getScale() * 8); - this->ui_.windowLayout->setContentsMargins(offset, offset, offset, offset); + this->ui_.windowLayout->setContentsMargins(offset, offset, + offset, offset); } else { this->ui_.windowLayout->setContentsMargins(0, 1, 0, 0); } @@ -686,23 +709,23 @@ bool BaseWindow::handleNCHITTEST(MSG *msg, long *result) } if (resizeWidth && resizeHeight) { // bottom left corner - if (x >= winrect.left && x < winrect.left + border_width && y < winrect.bottom && - y >= winrect.bottom - border_width) { + if (x >= winrect.left && x < winrect.left + border_width && + y < winrect.bottom && y >= winrect.bottom - border_width) { *result = HTBOTTOMLEFT; } // bottom right corner - if (x < winrect.right && x >= winrect.right - border_width && y < winrect.bottom && - y >= winrect.bottom - border_width) { + if (x < winrect.right && x >= winrect.right - border_width && + y < winrect.bottom && y >= winrect.bottom - border_width) { *result = HTBOTTOMRIGHT; } // top left corner - if (x >= winrect.left && x < winrect.left + border_width && y >= winrect.top && - y < winrect.top + border_width) { + if (x >= winrect.left && x < winrect.left + border_width && + y >= winrect.top && y < winrect.top + border_width) { *result = HTTOPLEFT; } // top right corner - if (x < winrect.right && x >= winrect.right - border_width && y >= winrect.top && - y < winrect.top + border_width) { + if (x < winrect.right && x >= winrect.right - border_width && + y >= winrect.top && y < winrect.top + border_width) { *result = HTTOPRIGHT; } } diff --git a/src/widgets/BaseWindow.hpp b/src/widgets/BaseWindow.hpp index d25a1be2e..dbfb4b46b 100644 --- a/src/widgets/BaseWindow.hpp +++ b/src/widgets/BaseWindow.hpp @@ -55,7 +55,8 @@ public: pajlada::Signals::NoArgSignal closing; protected: - virtual bool nativeEvent(const QByteArray &eventType, void *message, long *result) override; + virtual bool nativeEvent(const QByteArray &eventType, void *message, + long *result) override; virtual void scaleChangedEvent(float) override; virtual void paintEvent(QPaintEvent *) override; diff --git a/src/widgets/Label.cpp b/src/widgets/Label.cpp index ca851d4b5..aefe07d49 100644 --- a/src/widgets/Label.cpp +++ b/src/widgets/Label.cpp @@ -18,7 +18,8 @@ Label::Label(BaseWidget *parent, QString text, FontStyle style) { auto app = getApp(); - this->connections_.managedConnect(app->fonts->fontChanged, [this] { this->updateSize(); }); + this->connections_.managedConnect(app->fonts->fontChanged, + [this] { this->updateSize(); }); } const QString &Label::getText() const @@ -88,11 +89,11 @@ void Label::paintEvent(QPaintEvent *) QPainter painter(this); QFontMetrics metrics = app->fonts->getFontMetrics( - this->getFontStyle(), - this->getScale() * 96.f / this->logicalDpiX() * this->devicePixelRatioF()); + this->getFontStyle(), this->getScale() * 96.f / this->logicalDpiX() * + this->devicePixelRatioF()); painter.setFont(app->fonts->getFont( - this->getFontStyle(), - this->getScale() * 96.f / this->logicalDpiX() * this->devicePixelRatioF())); + this->getFontStyle(), this->getScale() * 96.f / this->logicalDpiX() * + this->devicePixelRatioF())); int offset = this->getOffset(); @@ -118,7 +119,8 @@ void Label::updateSize() { auto app = getApp(); - QFontMetrics metrics = app->fonts->getFontMetrics(this->fontStyle_, this->getScale()); + QFontMetrics metrics = + app->fonts->getFontMetrics(this->fontStyle_, this->getScale()); int width = metrics.width(this->text_) + (2 * this->getOffset()); int height = metrics.height(); diff --git a/src/widgets/Label.hpp b/src/widgets/Label.hpp index 96e726b08..4a10d307c 100644 --- a/src/widgets/Label.hpp +++ b/src/widgets/Label.hpp @@ -10,7 +10,8 @@ namespace chatterino { class Label : public BaseWidget { public: - explicit Label(QString text = QString(), FontStyle style = FontStyle::UiMedium); + explicit Label(QString text = QString(), + FontStyle style = FontStyle::UiMedium); explicit Label(BaseWidget *parent, QString text = QString(), FontStyle style = FontStyle::UiMedium); diff --git a/src/widgets/Notebook.cpp b/src/widgets/Notebook.cpp index 5068732b7..d99d1f021 100644 --- a/src/widgets/Notebook.cpp +++ b/src/widgets/Notebook.cpp @@ -34,10 +34,12 @@ Notebook::Notebook(QWidget *parent) this->addButton_.setHidden(true); auto *shortcut_next = new QShortcut(QKeySequence("Ctrl+Tab"), this); - QObject::connect(shortcut_next, &QShortcut::activated, [this] { this->selectNextTab(); }); + QObject::connect(shortcut_next, &QShortcut::activated, + [this] { this->selectNextTab(); }); auto *shortcut_prev = new QShortcut(QKeySequence("Ctrl+Shift+Tab"), this); - QObject::connect(shortcut_prev, &QShortcut::activated, [this] { this->selectPreviousTab(); }); + QObject::connect(shortcut_prev, &QShortcut::activated, + [this] { this->selectPreviousTab(); }); } NotebookTab *Notebook::addPage(QWidget *page, QString title, bool select) @@ -134,7 +136,8 @@ void Notebook::select(QWidget *page) qDebug() << item.selectedWidget; item.selectedWidget->setFocus(Qt::MouseFocusReason); } else { - qDebug() << "Notebook: selected child of page doesn't exist anymore"; + qDebug() + << "Notebook: selected child of page doesn't exist anymore"; } } } @@ -165,21 +168,23 @@ bool Notebook::containsPage(QWidget *page) Notebook::Item &Notebook::findItem(QWidget *page) { - auto it = std::find_if(this->items_.begin(), this->items_.end(), - [page](const auto &item) { return page == item.page; }); + auto it = + std::find_if(this->items_.begin(), this->items_.end(), + [page](const auto &item) { return page == item.page; }); assert(it != this->items_.end()); return *it; } bool Notebook::containsChild(const QObject *obj, const QObject *child) { - return std::any_of(obj->children().begin(), obj->children().end(), [child](const QObject *o) { - if (o == child) { - return true; - } + return std::any_of(obj->children().begin(), obj->children().end(), + [child](const QObject *o) { + if (o == child) { + return true; + } - return containsChild(o, child); - }); + return containsChild(o, child); + }); } void Notebook::selectIndex(int index) @@ -328,8 +333,10 @@ void Notebook::performLayout(bool animated) for (auto i = this->items_.begin(); i != this->items_.end(); i++) { bool wrap = - !first && (((i + 1 == this->items_.end() && this->showAddButton_) ? tabHeight : 0) + x + - i->tab->width()) > width(); + !first && + (((i + 1 == this->items_.end() && this->showAddButton_) ? tabHeight + : 0) + + x + i->tab->width()) > width(); if (wrap) { y += i->tab->height(); @@ -376,8 +383,8 @@ void Notebook::paintEvent(QPaintEvent *event) BaseWidget::paintEvent(event); QPainter painter(this); - painter.fillRect(0, this->lineY_, this->width(), (int)(3 * this->getScale()), - this->theme->tabs.bottomLine); + painter.fillRect(0, this->lineY_, this->width(), + (int)(3 * this->getScale()), this->theme->tabs.bottomLine); } NotebookButton *Notebook::getAddButton() @@ -409,8 +416,9 @@ NotebookTab *Notebook::getTabFromPage(QWidget *page) SplitNotebook::SplitNotebook(Window *parent) : Notebook(parent) { - this->connect(this->getAddButton(), &NotebookButton::clicked, - [this]() { QTimer::singleShot(80, this, [this] { this->addPage(true); }); }); + this->connect(this->getAddButton(), &NotebookButton::clicked, [this]() { + QTimer::singleShot(80, this, [this] { this->addPage(true); }); + }); bool customFrame = parent->hasCustomWindowFrame(); @@ -424,10 +432,12 @@ void SplitNotebook::addCustomButtons() // settings auto settingsBtn = this->addCustomButton(); - settingsBtn->setVisible(!getApp()->settings->hidePreferencesButton.getValue()); + settingsBtn->setVisible( + !getApp()->settings->hidePreferencesButton.getValue()); getApp()->settings->hidePreferencesButton.connect( - [settingsBtn](bool hide, auto) { settingsBtn->setVisible(!hide); }, this->connections_); + [settingsBtn](bool hide, auto) { settingsBtn->setVisible(!hide); }, + this->connections_); settingsBtn->setIcon(NotebookButton::Settings); @@ -438,17 +448,20 @@ void SplitNotebook::addCustomButtons() auto userBtn = this->addCustomButton(); userBtn->setVisible(!getApp()->settings->hideUserButton.getValue()); getApp()->settings->hideUserButton.connect( - [userBtn](bool hide, auto) { userBtn->setVisible(!hide); }, this->connections_); + [userBtn](bool hide, auto) { userBtn->setVisible(!hide); }, + this->connections_); userBtn->setIcon(NotebookButton::User); QObject::connect(userBtn, &NotebookButton::clicked, [this, userBtn] { - getApp()->windows->showAccountSelectPopup(this->mapToGlobal(userBtn->rect().bottomRight())); + getApp()->windows->showAccountSelectPopup( + this->mapToGlobal(userBtn->rect().bottomRight())); }); // updates auto updateBtn = this->addCustomButton(); - initUpdateButton(*updateBtn, this->updateDialogHandle_, this->signalHolder_); + initUpdateButton(*updateBtn, this->updateDialogHandle_, + this->signalHolder_); } SplitContainer *SplitNotebook::addPage(bool select) @@ -465,7 +478,8 @@ SplitContainer *SplitNotebook::getOrAddSelectedPage() { auto *selectedPage = this->getSelectedPage(); - return selectedPage != nullptr ? (SplitContainer *)selectedPage : this->addPage(); + return selectedPage != nullptr ? (SplitContainer *)selectedPage + : this->addPage(); } } // namespace chatterino diff --git a/src/widgets/Notebook.hpp b/src/widgets/Notebook.hpp index 4741fbac1..749d12594 100644 --- a/src/widgets/Notebook.hpp +++ b/src/widgets/Notebook.hpp @@ -23,7 +23,8 @@ class Notebook : public BaseWidget public: explicit Notebook(QWidget *parent); - NotebookTab *addPage(QWidget *page, QString title = QString(), bool select = false); + NotebookTab *addPage(QWidget *page, QString title = QString(), + bool select = false); void removePage(QWidget *page); void removeCurrentPage(); diff --git a/src/widgets/Scrollbar.cpp b/src/widgets/Scrollbar.cpp index 37efde61e..9c46cff80 100644 --- a/src/widgets/Scrollbar.cpp +++ b/src/widgets/Scrollbar.cpp @@ -21,7 +21,8 @@ Scrollbar::Scrollbar(ChannelView *parent) { resize(int(16 * this->getScale()), 100); this->currentValueAnimation_.setDuration(150); - this->currentValueAnimation_.setEasingCurve(QEasingCurve(QEasingCurve::OutCubic)); + this->currentValueAnimation_.setEasingCurve( + QEasingCurve(QEasingCurve::OutCubic)); setMouseTracking(true); } @@ -32,7 +33,8 @@ void Scrollbar::addHighlight(ScrollbarHighlight highlight) this->highlights_.pushBack(highlight, deleted); } -void Scrollbar::addHighlightsAtStart(const std::vector &_highlights) +void Scrollbar::addHighlightsAtStart( + const std::vector &_highlights) { this->highlights_.pushFront(_highlights); } @@ -103,28 +105,35 @@ void Scrollbar::setDesiredValue(qreal value, bool animated) { auto app = getApp(); animated &= app->settings->enableSmoothScrolling.getValue(); - value = std::max(this->minimum_, std::min(this->maximum_ - this->largeChange_, value)); + value = std::max(this->minimum_, + std::min(this->maximum_ - this->largeChange_, value)); - if (std::abs(this->desiredValue_ + this->smoothScrollingOffset_ - value) > 0.0001) { + if (std::abs(this->desiredValue_ + this->smoothScrollingOffset_ - value) > + 0.0001) { if (animated) { this->currentValueAnimation_.stop(); - this->currentValueAnimation_.setStartValue(this->currentValue_ + - this->smoothScrollingOffset_); + this->currentValueAnimation_.setStartValue( + this->currentValue_ + this->smoothScrollingOffset_); - // if (((this->getMaximum() - this->getLargeChange()) - value) <= 0.01) { + // if (((this->getMaximum() - this->getLargeChange()) - + // value) <= 0.01) { // value += 1; // } this->currentValueAnimation_.setEndValue(value); this->smoothScrollingOffset_ = 0; - this->atBottom_ = ((this->getMaximum() - this->getLargeChange()) - value) <= 0.0001; + this->atBottom_ = ((this->getMaximum() - this->getLargeChange()) - + value) <= 0.0001; this->currentValueAnimation_.start(); } else { - if (this->currentValueAnimation_.state() != QPropertyAnimation::Running) { + if (this->currentValueAnimation_.state() != + QPropertyAnimation::Running) { this->smoothScrollingOffset_ = 0; this->desiredValue_ = value; this->currentValueAnimation_.stop(); - this->atBottom_ = ((this->getMaximum() - this->getLargeChange()) - value) <= 0.0001; + this->atBottom_ = + ((this->getMaximum() - this->getLargeChange()) - value) <= + 0.0001; setCurrentValue(value); } } @@ -187,8 +196,9 @@ pajlada::Signals::NoArgSignal &Scrollbar::getDesiredValueChanged() void Scrollbar::setCurrentValue(qreal value) { - value = std::max(this->minimum_, std::min(this->maximum_ - this->largeChange_, - value + this->smoothScrollingOffset_)); + value = std::max(this->minimum_, + std::min(this->maximum_ - this->largeChange_, + value + this->smoothScrollingOffset_)); if (std::abs(this->currentValue_ - value) > 0.0001) { this->currentValue_ = value; @@ -221,15 +231,16 @@ void Scrollbar::paintEvent(QPaintEvent *) // painter.fillRect(QRect(xOffset, 0, width(), this->buttonHeight), // this->themeManager->ScrollbarArrow); - // painter.fillRect(QRect(xOffset, height() - this->buttonHeight, width(), - // this->buttonHeight), + // painter.fillRect(QRect(xOffset, height() - this->buttonHeight, + // width(), this->buttonHeight), // this->themeManager->ScrollbarArrow); this->thumbRect_.setX(xOffset); // mouse over thumb if (this->mouseDownIndex_ == 2) { - painter.fillRect(this->thumbRect_, this->theme->scrollbars.thumbSelected); + painter.fillRect(this->thumbRect_, + this->theme->scrollbars.thumbSelected); } // mouse not over thumb else { @@ -265,7 +276,8 @@ void Scrollbar::paintEvent(QPaintEvent *) switch (highlight.getStyle()) { case ScrollbarHighlight::Default: { - painter.fillRect(w / 8 * 3, int(y), w / 4, highlightHeight, color); + painter.fillRect(w / 8 * 3, int(y), w / 4, highlightHeight, + color); } break; case ScrollbarHighlight::Line: { @@ -310,7 +322,8 @@ void Scrollbar::mouseMoveEvent(QMouseEvent *event) } else if (this->mouseDownIndex_ == 2) { int delta = event->pos().y() - this->lastMousePosition_.y(); - setDesiredValue(this->desiredValue_ + qreal(delta) / this->trackHeight_ * this->maximum_); + setDesiredValue(this->desiredValue_ + + qreal(delta) / this->trackHeight_ * this->maximum_); } this->lastMousePosition_ = event->pos(); @@ -370,13 +383,16 @@ void Scrollbar::leaveEvent(QEvent *) void Scrollbar::updateScroll() { - this->trackHeight_ = - this->height() - this->buttonHeight_ - this->buttonHeight_ - MIN_THUMB_HEIGHT - 1; + this->trackHeight_ = this->height() - this->buttonHeight_ - + this->buttonHeight_ - MIN_THUMB_HEIGHT - 1; - this->thumbRect_ = QRect( - 0, int(this->currentValue_ / this->maximum_ * this->trackHeight_) + 1 + this->buttonHeight_, - this->width(), - int(this->largeChange_ / this->maximum_ * this->trackHeight_) + MIN_THUMB_HEIGHT); + this->thumbRect_ = + QRect(0, + int(this->currentValue_ / this->maximum_ * this->trackHeight_) + + 1 + this->buttonHeight_, + this->width(), + int(this->largeChange_ / this->maximum_ * this->trackHeight_) + + MIN_THUMB_HEIGHT); this->update(); } diff --git a/src/widgets/Scrollbar.hpp b/src/widgets/Scrollbar.hpp index 8de43d60a..fe72477c3 100644 --- a/src/widgets/Scrollbar.hpp +++ b/src/widgets/Scrollbar.hpp @@ -22,7 +22,8 @@ public: Scrollbar(ChannelView *parent = nullptr); void addHighlight(ScrollbarHighlight highlight); - void addHighlightsAtStart(const std::vector &highlights_); + void addHighlightsAtStart( + const std::vector &highlights_); void replaceHighlight(size_t index, ScrollbarHighlight replacement); void pauseHighlights(); diff --git a/src/widgets/StreamView.cpp b/src/widgets/StreamView.cpp index 05bd0e68e..ad3f1966c 100644 --- a/src/widgets/StreamView.cpp +++ b/src/widgets/StreamView.cpp @@ -16,9 +16,11 @@ StreamView::StreamView(ChannelPtr channel, const QUrl &url) LayoutCreator layoutCreator(this); #ifdef USEWEBENGINE - auto web = layoutCreator.emplace(this).assign(&this->stream); + auto web = + layoutCreator.emplace(this).assign(&this->stream); web->setUrl(url); - web->settings()->setAttribute(QWebEngineSettings::FullScreenSupportEnabled, true); + web->settings()->setAttribute(QWebEngineSettings::FullScreenSupportEnabled, + true); #endif auto chat = layoutCreator.emplace(); diff --git a/src/widgets/TooltipWidget.cpp b/src/widgets/TooltipWidget.cpp index f703a7c47..0b3b83639 100644 --- a/src/widgets/TooltipWidget.cpp +++ b/src/widgets/TooltipWidget.cpp @@ -36,7 +36,8 @@ TooltipWidget::TooltipWidget(BaseWidget *parent) this->setStayInScreenRect(true); this->setAttribute(Qt::WA_ShowWithoutActivating); - this->setWindowFlags(Qt::Tool | Qt::FramelessWindowHint | Qt::X11BypassWindowManagerHint | + this->setWindowFlags(Qt::Tool | Qt::FramelessWindowHint | + Qt::X11BypassWindowManagerHint | Qt::BypassWindowManagerHint); displayText_->setAlignment(Qt::AlignHCenter); @@ -46,7 +47,8 @@ TooltipWidget::TooltipWidget(BaseWidget *parent) layout->addWidget(displayText_); this->setLayout(layout); - this->fontChangedConnection_ = app->fonts->fontChanged.connect([this] { this->updateFont(); }); + this->fontChangedConnection_ = + app->fonts->fontChanged.connect([this] { this->updateFont(); }); } TooltipWidget::~TooltipWidget() @@ -76,7 +78,8 @@ void TooltipWidget::updateFont() { auto app = getApp(); - this->setFont(app->fonts->getFont(Fonts::Type::ChatMediumSmall, this->getScale())); + this->setFont( + app->fonts->getFont(Fonts::Type::ChatMediumSmall, this->getScale())); } void TooltipWidget::setText(QString text) diff --git a/src/widgets/Window.cpp b/src/widgets/Window.cpp index 37d808c2f..7088e5cb6 100644 --- a/src/widgets/Window.cpp +++ b/src/widgets/Window.cpp @@ -38,7 +38,8 @@ Window::Window(Type type) this->addShortcuts(); this->addLayout(); - getApp()->accounts->twitch.currentUserChanged.connect([this] { this->onAccountSelected(); }); + getApp()->accounts->twitch.currentUserChanged.connect( + [this] { this->onAccountSelected(); }); this->onAccountSelected(); if (type == Type::Main) { @@ -86,7 +87,8 @@ bool Window::event(QEvent *event) } } - if (SplitContainer *container = dynamic_cast(page)) { + if (SplitContainer *container = + dynamic_cast(page)) { container->hideResizeHandles(); } } break; @@ -103,10 +105,11 @@ void Window::showEvent(QShowEvent *event) if (getApp()->settings->startUpNotification.getValue() < 1) { getApp()->settings->startUpNotification = 1; - auto box = - new QMessageBox(QMessageBox::Information, "Chatterino 2 Beta", - "Please note that this software is not stable yet. Things are rough " - "around the edges and everything is subject to change."); + auto box = new QMessageBox( + QMessageBox::Information, "Chatterino 2 Beta", + "Please note that this software is not stable yet. Things are " + "rough " + "around the edges and everything is subject to change."); box->setAttribute(Qt::WA_DeleteOnClose); box->show(); } @@ -114,11 +117,13 @@ void Window::showEvent(QShowEvent *event) // Show changelog if (getApp()->settings->currentVersion.getValue() != "" && getApp()->settings->currentVersion.getValue() != CHATTERINO_VERSION) { - auto box = new QMessageBox(QMessageBox::Information, "Chatterino 2 Beta", "Show changelog?", + auto box = new QMessageBox(QMessageBox::Information, + "Chatterino 2 Beta", "Show changelog?", QMessageBox::Yes | QMessageBox::No); box->setAttribute(Qt::WA_DeleteOnClose); if (box->exec() == QMessageBox::Yes) { - QDesktopServices::openUrl(QUrl("https://fourtf.com/chatterino-changelog/")); + QDesktopServices::openUrl( + QUrl("https://fourtf.com/chatterino-changelog/")); } } @@ -174,8 +179,8 @@ void Window::addCustomTitlebarButtons() // account this->userLabel_ = this->addTitleBarLabel([this] { - getApp()->windows->showAccountSelectPopup( - this->userLabel_->mapToGlobal(this->userLabel_->rect().bottomLeft())); // + getApp()->windows->showAccountSelectPopup(this->userLabel_->mapToGlobal( + this->userLabel_->rect().bottomLeft())); // }); this->userLabel_->setMinimumWidth(20 * getScale()); } @@ -246,26 +251,36 @@ void Window::addShortcuts() createWindowShortcut(this, "CTRL+P", [] { SettingsDialog::showDialog(); }); // Switch tab - createWindowShortcut(this, "CTRL+T", - [this] { this->notebook_.getOrAddSelectedPage()->appendNewSplit(true); }); + createWindowShortcut(this, "CTRL+T", [this] { + this->notebook_.getOrAddSelectedPage()->appendNewSplit(true); + }); - createWindowShortcut(this, "CTRL+1", [this] { this->notebook_.selectIndex(0); }); - createWindowShortcut(this, "CTRL+2", [this] { this->notebook_.selectIndex(1); }); - createWindowShortcut(this, "CTRL+3", [this] { this->notebook_.selectIndex(2); }); - createWindowShortcut(this, "CTRL+4", [this] { this->notebook_.selectIndex(3); }); - createWindowShortcut(this, "CTRL+5", [this] { this->notebook_.selectIndex(4); }); - createWindowShortcut(this, "CTRL+6", [this] { this->notebook_.selectIndex(5); }); - createWindowShortcut(this, "CTRL+7", [this] { this->notebook_.selectIndex(6); }); - createWindowShortcut(this, "CTRL+8", [this] { this->notebook_.selectIndex(7); }); - createWindowShortcut(this, "CTRL+9", [this] { this->notebook_.selectIndex(8); }); + createWindowShortcut(this, "CTRL+1", + [this] { this->notebook_.selectIndex(0); }); + createWindowShortcut(this, "CTRL+2", + [this] { this->notebook_.selectIndex(1); }); + createWindowShortcut(this, "CTRL+3", + [this] { this->notebook_.selectIndex(2); }); + createWindowShortcut(this, "CTRL+4", + [this] { this->notebook_.selectIndex(3); }); + createWindowShortcut(this, "CTRL+5", + [this] { this->notebook_.selectIndex(4); }); + createWindowShortcut(this, "CTRL+6", + [this] { this->notebook_.selectIndex(5); }); + createWindowShortcut(this, "CTRL+7", + [this] { this->notebook_.selectIndex(6); }); + createWindowShortcut(this, "CTRL+8", + [this] { this->notebook_.selectIndex(7); }); + createWindowShortcut(this, "CTRL+9", + [this] { this->notebook_.selectIndex(8); }); // Zoom in { auto s = new QShortcut(QKeySequence::ZoomIn, this); s->setContext(Qt::WindowShortcut); QObject::connect(s, &QShortcut::activated, this, [] { - getApp()->settings->uiScale.setValue( - WindowManager::clampUiScale(getApp()->settings->uiScale.getValue() + 1)); + getApp()->settings->uiScale.setValue(WindowManager::clampUiScale( + getApp()->settings->uiScale.getValue() + 1)); }); } @@ -274,16 +289,18 @@ void Window::addShortcuts() auto s = new QShortcut(QKeySequence::ZoomOut, this); s->setContext(Qt::WindowShortcut); QObject::connect(s, &QShortcut::activated, this, [] { - getApp()->settings->uiScale.setValue( - WindowManager::clampUiScale(getApp()->settings->uiScale.getValue() - 1)); + getApp()->settings->uiScale.setValue(WindowManager::clampUiScale( + getApp()->settings->uiScale.getValue() - 1)); }); } // New tab - createWindowShortcut(this, "CTRL+SHIFT+T", [this] { this->notebook_.addPage(true); }); + createWindowShortcut(this, "CTRL+SHIFT+T", + [this] { this->notebook_.addPage(true); }); // Close tab - createWindowShortcut(this, "CTRL+SHIFT+W", [this] { this->notebook_.removeCurrentPage(); }); + createWindowShortcut(this, "CTRL+SHIFT+W", + [this] { this->notebook_.removeCurrentPage(); }); } void Window::onAccountSelected() diff --git a/src/widgets/dialogs/EmotePopup.cpp b/src/widgets/dialogs/EmotePopup.cpp index aa33925e3..74ce5951e 100644 --- a/src/widgets/dialogs/EmotePopup.cpp +++ b/src/widgets/dialogs/EmotePopup.cpp @@ -19,9 +19,11 @@ EmotePopup::EmotePopup() this->viewEmojis_ = new ChannelView(); this->viewEmotes_->setOverrideFlags(MessageElement::Flags( - MessageElement::Default | MessageElement::AlwaysShow | MessageElement::EmoteImages)); + MessageElement::Default | MessageElement::AlwaysShow | + MessageElement::EmoteImages)); this->viewEmojis_->setOverrideFlags(MessageElement::Flags( - MessageElement::Default | MessageElement::AlwaysShow | MessageElement::EmoteImages)); + MessageElement::Default | MessageElement::AlwaysShow | + MessageElement::EmoteImages)); this->viewEmotes_->setEnableScrollingToBottom(false); this->viewEmojis_->setEnableScrollingToBottom(false); @@ -56,7 +58,8 @@ void EmotePopup::loadChannel(ChannelPtr _channel) ChannelPtr emoteChannel(new Channel("", Channel::Type::None)); - auto addEmotes = [&](const EmoteMap &map, const QString &title, const QString &emoteDesc) { + auto addEmotes = [&](const EmoteMap &map, const QString &title, + const QString &emoteDesc) { // TITLE MessageBuilder builder1; @@ -71,8 +74,10 @@ void EmotePopup::loadChannel(ChannelPtr _channel) builder2.getMessage()->flags |= Message::DisableCompactEmotes; for (auto emote : map) { - builder2.append((new EmoteElement(emote.second, MessageElement::Flags::AlwaysShow)) - ->setLink(Link(Link::InsertText, emote.first.string))); + builder2.append( + (new EmoteElement(emote.second, + MessageElement::Flags::AlwaysShow)) + ->setLink(Link(Link::InsertText, emote.first.string))); } emoteChannel->addMessage(builder2.getMessage()); @@ -80,9 +85,10 @@ void EmotePopup::loadChannel(ChannelPtr _channel) auto app = getApp(); - // fourtf: the entire emote manager needs to be refactored so there's no point in trying to - // fix this pile of garbage - for (const auto &set : app->accounts->twitch.getCurrent()->accessEmotes()->emoteSets) { + // fourtf: the entire emote manager needs to be refactored so there's no + // point in trying to fix this pile of garbage + for (const auto &set : + app->accounts->twitch.getCurrent()->accessEmotes()->emoteSets) { // TITLE MessageBuilder builder1; @@ -109,18 +115,21 @@ void EmotePopup::loadChannel(ChannelPtr _channel) for (const auto &emote : set->emotes) { builder2.append( - (new EmoteElement(app->emotes->twitch.getOrCreateEmote(emote.id, emote.name), - MessageElement::Flags::AlwaysShow)) + (new EmoteElement( + app->emotes->twitch.getOrCreateEmote(emote.id, emote.name), + MessageElement::Flags::AlwaysShow)) ->setLink(Link(Link::InsertText, emote.name.string))); } emoteChannel->addMessage(builder2.getMessage()); } - addEmotes(*app->emotes->bttv.accessGlobalEmotes(), "BetterTTV Global Emotes", - "BetterTTV Global Emote"); - addEmotes(*channel->accessBttvEmotes(), "BetterTTV Channel Emotes", "BetterTTV Channel Emote"); - // addEmotes(*app->emotes->ffz.accessGlobalEmotes(), "FrankerFaceZ Global Emotes", + addEmotes(*app->emotes->bttv.accessGlobalEmotes(), + "BetterTTV Global Emotes", "BetterTTV Global Emote"); + addEmotes(*channel->accessBttvEmotes(), "BetterTTV Channel Emotes", + "BetterTTV Channel Emote"); + // addEmotes(*app->emotes->ffz.accessGlobalEmotes(), "FrankerFaceZ Global + // Emotes", // "FrankerFaceZ Global Emote"); addEmotes(*channel->accessFfzEmotes(), "FrankerFaceZ Channel Emotes", "FrankerFaceZ Channel Emote"); @@ -149,7 +158,8 @@ void EmotePopup::loadEmojis() emojis.each([&builder](const auto &key, const auto &value) { builder.append( (new EmoteElement(value->emote, MessageElement::Flags::AlwaysShow)) - ->setLink(Link(Link::Type::InsertText, ":" + value->shortCodes[0] + ":"))); + ->setLink(Link(Link::Type::InsertText, + ":" + value->shortCodes[0] + ":"))); }); emojiChannel->addMessage(builder.getMessage()); diff --git a/src/widgets/dialogs/LastRunCrashDialog.cpp b/src/widgets/dialogs/LastRunCrashDialog.cpp index 0e46702c6..e67483909 100644 --- a/src/widgets/dialogs/LastRunCrashDialog.cpp +++ b/src/widgets/dialogs/LastRunCrashDialog.cpp @@ -16,10 +16,11 @@ LastRunCrashDialog::LastRunCrashDialog() this->setWindowFlag(Qt::WindowContextHelpButtonHint, false); this->setWindowTitle("Chatterino"); - auto layout = LayoutCreator(this).setLayoutType(); + auto layout = + LayoutCreator(this).setLayoutType(); - layout.emplace( - "The application wasn't terminated properly the last time it was executed."); + layout.emplace("The application wasn't terminated properly the " + "last time it was executed."); layout->addSpacing(16); @@ -28,7 +29,8 @@ LastRunCrashDialog::LastRunCrashDialog() // auto *installUpdateButton = buttons->addButton("Install Update", // QDialogButtonBox::NoRole); installUpdateButton->setEnabled(false); - // QObject::connect(installUpdateButton, &QPushButton::clicked, [this, update]() mutable { + // QObject::connect(installUpdateButton, &QPushButton::clicked, [this, + // update]() mutable { // auto &updateManager = UpdateManager::getInstance(); // updateManager.installUpdates(); @@ -36,8 +38,10 @@ LastRunCrashDialog::LastRunCrashDialog() // update->setText("Downloading updates..."); // }); - auto *okButton = buttons->addButton("Ignore", QDialogButtonBox::ButtonRole::NoRole); - QObject::connect(okButton, &QPushButton::clicked, [this] { this->accept(); }); + auto *okButton = + buttons->addButton("Ignore", QDialogButtonBox::ButtonRole::NoRole); + QObject::connect(okButton, &QPushButton::clicked, + [this] { this->accept(); }); // Updates // auto updateUpdateLabel = [update]() mutable { @@ -57,28 +61,31 @@ LastRunCrashDialog::LastRunCrashDialog() // update->setText("No update abailable."); // } break; // case UpdateManager::SearchFailed: { - // update->setText("Error while searching for update.\nEither the update service - // is " - // "temporarily down or there is an issue with your - // installation."); + // update->setText("Error while searching for update.\nEither + // the update service is " + // "temporarily down or there is an issue + // with your installation."); // } break; // case UpdateManager::Downloading: { // update->setText( - // "Downloading the update. Chatterino will close once the download is - // done."); + // "Downloading the update. Chatterino will close once + // the download is done."); // } break; // case UpdateManager::DownloadFailed: { // update->setText("Download failed."); // } break; // case UpdateManager::WriteFileFailed: { - // update->setText("Writing the update file to the hard drive failed."); + // update->setText("Writing the update file to the hard drive + // failed."); // } break; // } // }; // updateUpdateLabel(); - // this->managedConnect(updateManager.statusUpdated, [updateUpdateLabel](auto) mutable { - // postToThread([updateUpdateLabel]() mutable { updateUpdateLabel(); }); + // this->managedConnect(updateManager.statusUpdated, + // [updateUpdateLabel](auto) mutable { + // postToThread([updateUpdateLabel]() mutable { updateUpdateLabel(); + // }); // }); } diff --git a/src/widgets/dialogs/LoginDialog.cpp b/src/widgets/dialogs/LoginDialog.cpp index bee0e87b0..1b73f143f 100644 --- a/src/widgets/dialogs/LoginDialog.cpp +++ b/src/widgets/dialogs/LoginDialog.cpp @@ -20,8 +20,10 @@ namespace chatterino { namespace { -void LogInWithCredentials(const std::string &userID, const std::string &username, - const std::string &clientID, const std::string &oauthToken) +void LogInWithCredentials(const std::string &userID, + const std::string &username, + const std::string &clientID, + const std::string &oauthToken) { QStringList errors; @@ -49,12 +51,16 @@ void LogInWithCredentials(const std::string &userID, const std::string &username // 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); + // 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(); @@ -142,46 +148,59 @@ AdvancedLoginWidget::AdvancedLoginWidget() this->ui_.oauthTokenInput.setEchoMode(QLineEdit::Password); - connect(&this->ui_.userIDInput, &QLineEdit::textChanged, [=]() { this->refreshButtons(); }); - connect(&this->ui_.usernameInput, &QLineEdit::textChanged, [=]() { this->refreshButtons(); }); - connect(&this->ui_.clientIDInput, &QLineEdit::textChanged, [=]() { this->refreshButtons(); }); - connect(&this->ui_.oauthTokenInput, &QLineEdit::textChanged, [=]() { this->refreshButtons(); }); + connect(&this->ui_.userIDInput, &QLineEdit::textChanged, + [=]() { this->refreshButtons(); }); + connect(&this->ui_.usernameInput, &QLineEdit::textChanged, + [=]() { this->refreshButtons(); }); + connect(&this->ui_.clientIDInput, &QLineEdit::textChanged, + [=]() { this->refreshButtons(); }); + connect(&this->ui_.oauthTokenInput, &QLineEdit::textChanged, + [=]() { this->refreshButtons(); }); /// Upper button row this->ui_.buttonUpperRow.addUserButton.setText("Add user"); this->ui_.buttonUpperRow.clearFieldsButton.setText("Clear fields"); - this->ui_.buttonUpperRow.layout.addWidget(&this->ui_.buttonUpperRow.addUserButton); - this->ui_.buttonUpperRow.layout.addWidget(&this->ui_.buttonUpperRow.clearFieldsButton); + this->ui_.buttonUpperRow.layout.addWidget( + &this->ui_.buttonUpperRow.addUserButton); + this->ui_.buttonUpperRow.layout.addWidget( + &this->ui_.buttonUpperRow.clearFieldsButton); - connect(&this->ui_.buttonUpperRow.clearFieldsButton, &QPushButton::clicked, [=]() { - this->ui_.userIDInput.clear(); - this->ui_.usernameInput.clear(); - this->ui_.clientIDInput.clear(); - this->ui_.oauthTokenInput.clear(); - }); + connect(&this->ui_.buttonUpperRow.clearFieldsButton, &QPushButton::clicked, + [=]() { + this->ui_.userIDInput.clear(); + this->ui_.usernameInput.clear(); + this->ui_.clientIDInput.clear(); + this->ui_.oauthTokenInput.clear(); + }); - connect(&this->ui_.buttonUpperRow.addUserButton, &QPushButton::clicked, [=]() { - std::string userID = this->ui_.userIDInput.text().toStdString(); - std::string username = this->ui_.usernameInput.text().toStdString(); - std::string clientID = this->ui_.clientIDInput.text().toStdString(); - std::string oauthToken = this->ui_.oauthTokenInput.text().toStdString(); + connect( + &this->ui_.buttonUpperRow.addUserButton, &QPushButton::clicked, [=]() { + std::string userID = this->ui_.userIDInput.text().toStdString(); + std::string username = this->ui_.usernameInput.text().toStdString(); + std::string clientID = this->ui_.clientIDInput.text().toStdString(); + std::string oauthToken = + this->ui_.oauthTokenInput.text().toStdString(); - LogInWithCredentials(userID, username, clientID, oauthToken); - }); + LogInWithCredentials(userID, username, clientID, oauthToken); + }); /// Lower button row - this->ui_.buttonLowerRow.fillInUserIDButton.setText("Get user ID from username"); + this->ui_.buttonLowerRow.fillInUserIDButton.setText( + "Get user ID from username"); - this->ui_.buttonLowerRow.layout.addWidget(&this->ui_.buttonLowerRow.fillInUserIDButton); + this->ui_.buttonLowerRow.layout.addWidget( + &this->ui_.buttonLowerRow.fillInUserIDButton); - connect(&this->ui_.buttonLowerRow.fillInUserIDButton, &QPushButton::clicked, [=]() { - const auto onIdFetched = [=](const QString &userID) { - this->ui_.userIDInput.setText(userID); // - }; - PartialTwitchUser::byName(this->ui_.usernameInput.text()).getId(onIdFetched, this); - }); + connect(&this->ui_.buttonLowerRow.fillInUserIDButton, &QPushButton::clicked, + [=]() { + const auto onIdFetched = [=](const QString &userID) { + this->ui_.userIDInput.setText(userID); // + }; + PartialTwitchUser::byName(this->ui_.usernameInput.text()) + .getId(onIdFetched, this); + }); } void AdvancedLoginWidget::refreshButtons() @@ -189,8 +208,10 @@ void AdvancedLoginWidget::refreshButtons() this->ui_.buttonLowerRow.fillInUserIDButton.setEnabled( !this->ui_.usernameInput.text().isEmpty()); - if (this->ui_.userIDInput.text().isEmpty() || this->ui_.usernameInput.text().isEmpty() || - this->ui_.clientIDInput.text().isEmpty() || this->ui_.oauthTokenInput.text().isEmpty()) { + if (this->ui_.userIDInput.text().isEmpty() || + this->ui_.usernameInput.text().isEmpty() || + this->ui_.clientIDInput.text().isEmpty() || + this->ui_.oauthTokenInput.text().isEmpty()) { this->ui_.buttonUpperRow.addUserButton.setEnabled(false); } else { this->ui_.buttonUpperRow.addUserButton.setEnabled(true); @@ -214,9 +235,10 @@ LoginWidget::LoginWidget() this->ui_.buttonBox.setStandardButtons(QDialogButtonBox::Close); - QObject::connect(&this->ui_.buttonBox, &QDialogButtonBox::rejected, [this]() { - this->close(); // - }); + QObject::connect(&this->ui_.buttonBox, &QDialogButtonBox::rejected, + [this]() { + this->close(); // + }); this->ui_.mainLayout.addWidget(&this->ui_.buttonBox); } diff --git a/src/widgets/dialogs/LogsPopup.cpp b/src/widgets/dialogs/LogsPopup.cpp index 5caa14fa2..218505a2d 100644 --- a/src/widgets/dialogs/LogsPopup.cpp +++ b/src/widgets/dialogs/LogsPopup.cpp @@ -35,7 +35,8 @@ void LogsPopup::setInfo(ChannelPtr channel, QString userName) this->channel_ = channel; this->userName_ = userName; this->getRoomID(); - this->setWindowTitle(this->userName_ + "'s logs in #" + this->channel_->getName()); + this->setWindowTitle(this->userName_ + "'s logs in #" + + this->channel_->getName()); this->getLogviewerLogs(); } @@ -49,7 +50,8 @@ void LogsPopup::setMessages(std::vector &messages) void LogsPopup::getRoomID() { - TwitchChannel *twitchChannel = dynamic_cast(this->channel_.get()); + TwitchChannel *twitchChannel = + dynamic_cast(this->channel_.get()); if (twitchChannel == nullptr) { return; } @@ -78,7 +80,8 @@ void LogsPopup::getRoomID() void LogsPopup::getLogviewerLogs() { - TwitchChannel *twitchChannel = dynamic_cast(this->channel_.get()); + TwitchChannel *twitchChannel = + dynamic_cast(this->channel_.get()); if (twitchChannel == nullptr) { return; } @@ -108,12 +111,15 @@ void LogsPopup::getLogviewerLogs() // Hacky way to fix the timestamp message.insert(1, "historical=1;"); - message.insert(1, QString("tmi-sent-ts=%10000;").arg(messageObject["time"].toInt())); + message.insert(1, QString("tmi-sent-ts=%10000;") + .arg(messageObject["time"].toInt())); message.insert(1, QString("room-id=%1;").arg(this->roomID_)); MessageParseArgs args; - auto ircMessage = Communi::IrcMessage::fromData(message.toUtf8(), nullptr); - auto privMsg = static_cast(ircMessage); + auto ircMessage = + Communi::IrcMessage::fromData(message.toUtf8(), nullptr); + auto privMsg = + static_cast(ircMessage); TwitchMessageBuilder builder(this->channel_.get(), privMsg, args); messages.push_back(builder.build()); }; @@ -127,22 +133,25 @@ void LogsPopup::getLogviewerLogs() void LogsPopup::getOverrustleLogs() { - TwitchChannel *twitchChannel = dynamic_cast(this->channel_.get()); + TwitchChannel *twitchChannel = + dynamic_cast(this->channel_.get()); if (twitchChannel == nullptr) { return; } QString channelName = twitchChannel->getName(); - QString url = QString("https://overrustlelogs.net/api/v1/stalk/%1/%2.json?limit=500") - .arg(channelName, this->userName_); + QString url = + QString("https://overrustlelogs.net/api/v1/stalk/%1/%2.json?limit=500") + .arg(channelName, this->userName_); NetworkRequest req(url); req.setCaller(QThread::currentThread()); req.onError([this, channelName](int errorCode) { this->close(); - QMessageBox *box = new QMessageBox(QMessageBox::Information, "Error getting logs", - "No logs could be found for channel " + channelName); + QMessageBox *box = new QMessageBox( + QMessageBox::Information, "Error getting logs", + "No logs could be found for channel " + channelName); box->setAttribute(Qt::WA_DeleteOnClose); box->show(); box->raise(); @@ -157,15 +166,18 @@ void LogsPopup::getOverrustleLogs() QJsonArray dataMessages = data.value("lines").toArray(); for (auto i : dataMessages) { QJsonObject singleMessage = i.toObject(); - QTime timeStamp = - QDateTime::fromSecsSinceEpoch(singleMessage.value("timestamp").toInt()).time(); + QTime timeStamp = QDateTime::fromSecsSinceEpoch( + singleMessage.value("timestamp").toInt()) + .time(); MessagePtr message(new Message); message->addElement(new TimestampElement(timeStamp)); - message->addElement(new TextElement(this->userName_, MessageElement::Username, + message->addElement(new TextElement(this->userName_, + MessageElement::Username, MessageColor::System)); - message->addElement(new TextElement(singleMessage.value("text").toString(), - MessageElement::Text, MessageColor::Text)); + message->addElement( + new TextElement(singleMessage.value("text").toString(), + MessageElement::Text, MessageColor::Text)); messages.push_back(message); } } diff --git a/src/widgets/dialogs/NotificationPopup.cpp b/src/widgets/dialogs/NotificationPopup.cpp index cc7a46abf..46ff7e8af 100644 --- a/src/widgets/dialogs/NotificationPopup.cpp +++ b/src/widgets/dialogs/NotificationPopup.cpp @@ -33,7 +33,8 @@ void NotificationPopup::updatePosition() switch (location) { case BottomRight: { - this->move(rect.right() - this->width(), rect.bottom() - this->height()); + this->move(rect.right() - this->width(), + rect.bottom() - this->height()); } break; } } diff --git a/src/widgets/dialogs/QualityPopup.cpp b/src/widgets/dialogs/QualityPopup.cpp index faaf95b3f..c4f9c4ceb 100644 --- a/src/widgets/dialogs/QualityPopup.cpp +++ b/src/widgets/dialogs/QualityPopup.cpp @@ -15,7 +15,8 @@ QualityPopup::QualityPopup(const QString &_channelName, QStringList options) QObject::connect(&this->ui_.cancelButton, &QPushButton::clicked, this, &QualityPopup::cancelButtonClicked); - this->ui_.buttonBox.addButton(&this->ui_.okButton, QDialogButtonBox::ButtonRole::AcceptRole); + this->ui_.buttonBox.addButton(&this->ui_.okButton, + QDialogButtonBox::ButtonRole::AcceptRole); this->ui_.buttonBox.addButton(&this->ui_.cancelButton, QDialogButtonBox::ButtonRole::RejectRole); diff --git a/src/widgets/dialogs/SelectChannelDialog.cpp b/src/widgets/dialogs/SelectChannelDialog.cpp index 4f026112b..367b626b2 100644 --- a/src/widgets/dialogs/SelectChannelDialog.cpp +++ b/src/widgets/dialogs/SelectChannelDialog.cpp @@ -33,17 +33,20 @@ SelectChannelDialog::SelectChannelDialog(QWidget *parent) auto vbox = obj.setLayoutType(); // channel_btn - auto channel_btn = vbox.emplace("Channel").assign(&this->ui_.twitch.channel); - auto channel_lbl = vbox.emplace("Join a twitch channel by its name.").hidden(); + auto channel_btn = vbox.emplace("Channel").assign( + &this->ui_.twitch.channel); + auto channel_lbl = + vbox.emplace("Join a twitch channel by its name.").hidden(); channel_lbl->setWordWrap(true); - auto channel_edit = - vbox.emplace().hidden().assign(&this->ui_.twitch.channelName); + auto channel_edit = vbox.emplace().hidden().assign( + &this->ui_.twitch.channelName); QObject::connect(channel_btn.getElement(), &QRadioButton::toggled, [=](bool enabled) mutable { if (enabled) { channel_edit->setFocus(); - channel_edit->setSelection(0, channel_edit->text().length()); + channel_edit->setSelection( + 0, channel_edit->text().length()); } channel_edit->setVisible(enabled); @@ -54,50 +57,60 @@ SelectChannelDialog::SelectChannelDialog(QWidget *parent) channel_edit->installEventFilter(&this->tabFilter_); // whispers_btn - auto whispers_btn = - vbox.emplace("Whispers").assign(&this->ui_.twitch.whispers); + auto whispers_btn = vbox.emplace("Whispers") + .assign(&this->ui_.twitch.whispers); auto whispers_lbl = - vbox.emplace("Shows the whispers that you receive while chatterino is running.") + vbox.emplace("Shows the whispers that you receive while " + "chatterino is running.") .hidden(); whispers_lbl->setWordWrap(true); whispers_btn->installEventFilter(&this->tabFilter_); - QObject::connect(whispers_btn.getElement(), &QRadioButton::toggled, - [=](bool enabled) mutable { whispers_lbl->setVisible(enabled); }); + QObject::connect( + whispers_btn.getElement(), &QRadioButton::toggled, + [=](bool enabled) mutable { whispers_lbl->setVisible(enabled); }); // mentions_btn - auto mentions_btn = - vbox.emplace("Mentions").assign(&this->ui_.twitch.mentions); + auto mentions_btn = vbox.emplace("Mentions") + .assign(&this->ui_.twitch.mentions); auto mentions_lbl = - vbox.emplace("Shows all the messages that highlight you from any channel.") + vbox.emplace("Shows all the messages that highlight you " + "from any channel.") .hidden(); mentions_lbl->setWordWrap(true); mentions_btn->installEventFilter(&this->tabFilter_); - QObject::connect(mentions_btn.getElement(), &QRadioButton::toggled, - [=](bool enabled) mutable { mentions_lbl->setVisible(enabled); }); + QObject::connect( + mentions_btn.getElement(), &QRadioButton::toggled, + [=](bool enabled) mutable { mentions_lbl->setVisible(enabled); }); // watching_btn - auto watching_btn = - vbox.emplace("Watching").assign(&this->ui_.twitch.watching); + auto watching_btn = vbox.emplace("Watching") + .assign(&this->ui_.twitch.watching); auto watching_lbl = - vbox.emplace("Requires the chatterino browser extension.").hidden(); + vbox.emplace("Requires the chatterino browser extension.") + .hidden(); watching_lbl->setWordWrap(true); watching_btn->installEventFilter(&this->tabFilter_); - QObject::connect(watching_btn.getElement(), &QRadioButton::toggled, - [=](bool enabled) mutable { watching_lbl->setVisible(enabled); }); + QObject::connect( + watching_btn.getElement(), &QRadioButton::toggled, + [=](bool enabled) mutable { watching_lbl->setVisible(enabled); }); vbox->addStretch(1); // tabbing order - QWidget::setTabOrder(watching_btn.getElement(), channel_btn.getElement()); - QWidget::setTabOrder(channel_btn.getElement(), whispers_btn.getElement()); - QWidget::setTabOrder(whispers_btn.getElement(), mentions_btn.getElement()); - QWidget::setTabOrder(mentions_btn.getElement(), watching_btn.getElement()); + QWidget::setTabOrder(watching_btn.getElement(), + channel_btn.getElement()); + QWidget::setTabOrder(channel_btn.getElement(), + whispers_btn.getElement()); + QWidget::setTabOrder(whispers_btn.getElement(), + mentions_btn.getElement()); + QWidget::setTabOrder(mentions_btn.getElement(), + watching_btn.getElement()); // tab NotebookTab *tab = notebook->addPage(obj.getElement()); @@ -117,12 +130,15 @@ SelectChannelDialog::SelectChannelDialog(QWidget *parent) layout->setStretchFactor(notebook.getElement(), 1); - auto buttons = layout.emplace().emplace(this); + auto buttons = + layout.emplace().emplace(this); { auto *button_ok = buttons->addButton(QDialogButtonBox::Ok); - QObject::connect(button_ok, &QPushButton::clicked, [=](bool) { this->ok(); }); + QObject::connect(button_ok, &QPushButton::clicked, + [=](bool) { this->ok(); }); auto *button_cancel = buttons->addButton(QDialogButtonBox::Cancel); - QObject::connect(button_cancel, &QAbstractButton::clicked, [=](bool) { this->close(); }); + QObject::connect(button_cancel, &QAbstractButton::clicked, + [=](bool) { this->close(); }); } this->setScaleIndependantSize(300, 210); @@ -133,7 +149,8 @@ SelectChannelDialog::SelectChannelDialog(QWidget *parent) auto *shortcut_ok = new QShortcut(QKeySequence("Return"), this); QObject::connect(shortcut_ok, &QShortcut::activated, [=] { this->ok(); }); auto *shortcut_cancel = new QShortcut(QKeySequence("Esc"), this); - QObject::connect(shortcut_cancel, &QShortcut::activated, [=] { this->close(); }); + QObject::connect(shortcut_cancel, &QShortcut::activated, + [=] { this->close(); }); } void SelectChannelDialog::ok() @@ -188,7 +205,8 @@ IndirectChannel SelectChannelDialog::getSelectedChannel() const switch (this->ui_.notebook->getSelectedIndex()) { case TAB_TWITCH: { if (this->ui_.twitch.channel->isChecked()) { - return app->twitch.server->getOrAddChannel(this->ui_.twitch.channelName->text()); + return app->twitch.server->getOrAddChannel( + this->ui_.twitch.channelName->text()); } else if (this->ui_.twitch.watching->isChecked()) { return app->twitch.server->watchingChannel; } else if (this->ui_.twitch.mentions->isChecked()) { @@ -207,7 +225,8 @@ bool SelectChannelDialog::hasSeletedChannel() const return this->hasSelectedChannel_; } -bool SelectChannelDialog::EventFilter::eventFilter(QObject *watched, QEvent *event) +bool SelectChannelDialog::EventFilter::eventFilter(QObject *watched, + QEvent *event) { auto *widget = (QWidget *)watched; @@ -225,7 +244,8 @@ bool SelectChannelDialog::EventFilter::eventFilter(QObject *watched, QEvent *eve return false; } else if (event->type() == QEvent::KeyPress) { QKeyEvent *event_key = static_cast(event); - if ((event_key->key() == Qt::Key_Tab || event_key->key() == Qt::Key_Down) && + if ((event_key->key() == Qt::Key_Tab || + event_key->key() == Qt::Key_Down) && event_key->modifiers() == Qt::NoModifier) { if (widget == this->dialog->ui_.twitch.channelName) { this->dialog->ui_.twitch.whispers->setFocus(); @@ -234,9 +254,11 @@ bool SelectChannelDialog::EventFilter::eventFilter(QObject *watched, QEvent *eve widget->nextInFocusChain()->setFocus(); } return true; - } else if (((event_key->key() == Qt::Key_Tab || event_key->key() == Qt::Key_Backtab) && + } else if (((event_key->key() == Qt::Key_Tab || + event_key->key() == Qt::Key_Backtab) && event_key->modifiers() == Qt::ShiftModifier) || - ((event_key->key() == Qt::Key_Up) && event_key->modifiers() == Qt::NoModifier)) { + ((event_key->key() == Qt::Key_Up) && + event_key->modifiers() == Qt::NoModifier)) { if (widget == this->dialog->ui_.twitch.channelName) { this->dialog->ui_.twitch.watching->setFocus(); return true; @@ -253,7 +275,8 @@ bool SelectChannelDialog::EventFilter::eventFilter(QObject *watched, QEvent *eve return true; } else if (event->type() == QEvent::KeyRelease) { QKeyEvent *event_key = static_cast(event); - if ((event_key->key() == Qt::Key_Backtab || event_key->key() == Qt::Key_Down) && + if ((event_key->key() == Qt::Key_Backtab || + event_key->key() == Qt::Key_Down) && event_key->modifiers() == Qt::NoModifier) { return true; } @@ -272,9 +295,11 @@ void SelectChannelDialog::themeChangedEvent() BaseWindow::themeChangedEvent(); if (this->theme->isLightTheme()) { - this->setStyleSheet("QRadioButton { color: #000 } QLabel { color: #000 }"); + this->setStyleSheet( + "QRadioButton { color: #000 } QLabel { color: #000 }"); } else { - this->setStyleSheet("QRadioButton { color: #fff } QLabel { color: #fff }"); + this->setStyleSheet( + "QRadioButton { color: #fff } QLabel { color: #fff }"); } } diff --git a/src/widgets/dialogs/SettingsDialog.cpp b/src/widgets/dialogs/SettingsDialog.cpp index 72100be2a..8f0746ccb 100644 --- a/src/widgets/dialogs/SettingsDialog.cpp +++ b/src/widgets/dialogs/SettingsDialog.cpp @@ -49,12 +49,16 @@ void SettingsDialog::initUi() // right side layout auto right = layoutCreator.emplace().withoutMargin(); { - right.emplace().assign(&this->ui_.pageStack).withoutMargin(); + right.emplace() + .assign(&this->ui_.pageStack) + .withoutMargin(); auto buttons = right.emplace(Qt::Horizontal); { - this->ui_.okButton = buttons->addButton("Ok", QDialogButtonBox::YesRole); - this->ui_.cancelButton = buttons->addButton("Cancel", QDialogButtonBox::NoRole); + this->ui_.okButton = + buttons->addButton("Ok", QDialogButtonBox::YesRole); + this->ui_.cancelButton = + buttons->addButton("Cancel", QDialogButtonBox::NoRole); } } @@ -62,7 +66,8 @@ void SettingsDialog::initUi() this->ui_.tabContainerContainer->setObjectName("tabWidget"); this->ui_.pageStack->setObjectName("pages"); - QObject::connect(this->ui_.okButton, &QPushButton::clicked, this, &SettingsDialog::onOkClicked); + QObject::connect(this->ui_.okButton, &QPushButton::clicked, this, + &SettingsDialog::onOkClicked); QObject::connect(this->ui_.cancelButton, &QPushButton::clicked, this, &SettingsDialog::onCancelClicked); } diff --git a/src/widgets/dialogs/SettingsDialog.hpp b/src/widgets/dialogs/SettingsDialog.hpp index 2b6b960af..03ddc90a5 100644 --- a/src/widgets/dialogs/SettingsDialog.hpp +++ b/src/widgets/dialogs/SettingsDialog.hpp @@ -25,7 +25,8 @@ public: Accounts, }; - static void showDialog(PreferredTab preferredTab = PreferredTab::NoPreference); + static void showDialog( + PreferredTab preferredTab = PreferredTab::NoPreference); protected: virtual void scaleChangedEvent(float newDpi) override; diff --git a/src/widgets/dialogs/TextInputDialog.cpp b/src/widgets/dialogs/TextInputDialog.cpp index 7d13a3c46..f42c8fe93 100644 --- a/src/widgets/dialogs/TextInputDialog.cpp +++ b/src/widgets/dialogs/TextInputDialog.cpp @@ -15,13 +15,16 @@ TextInputDialog::TextInputDialog(QWidget *parent) this->buttonBox_.addWidget(&okButton_); this->buttonBox_.addWidget(&cancelButton_); - QObject::connect(&this->okButton_, SIGNAL(clicked()), this, SLOT(okButtonClicked())); - QObject::connect(&this->cancelButton_, SIGNAL(clicked()), this, SLOT(cancelButtonClicked())); + QObject::connect(&this->okButton_, SIGNAL(clicked()), this, + SLOT(okButtonClicked())); + QObject::connect(&this->cancelButton_, SIGNAL(clicked()), this, + SLOT(cancelButtonClicked())); this->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); - this->setWindowFlags((this->windowFlags() & ~(Qt::WindowContextHelpButtonHint)) | Qt::Dialog | - Qt::MSWindowsFixedSizeDialogHint); + this->setWindowFlags( + (this->windowFlags() & ~(Qt::WindowContextHelpButtonHint)) | + Qt::Dialog | Qt::MSWindowsFixedSizeDialogHint); } QString TextInputDialog::getText() const diff --git a/src/widgets/dialogs/UpdateDialog.cpp b/src/widgets/dialogs/UpdateDialog.cpp index 1b66177e7..de065283f 100644 --- a/src/widgets/dialogs/UpdateDialog.cpp +++ b/src/widgets/dialogs/UpdateDialog.cpp @@ -11,27 +11,32 @@ namespace chatterino { UpdateDialog::UpdateDialog() - : BaseWindow(nullptr, BaseWindow::Flags(BaseWindow::Frameless | BaseWindow::TopMost | - BaseWindow::EnableCustomFrame)) + : BaseWindow(nullptr, + BaseWindow::Flags(BaseWindow::Frameless | BaseWindow::TopMost | + BaseWindow::EnableCustomFrame)) { - auto layout = LayoutCreator(this).setLayoutType(); + auto layout = + LayoutCreator(this).setLayoutType(); - layout.emplace