removed namespaces

This commit is contained in:
fourtf 2018-06-26 17:06:17 +02:00
parent 2df0566492
commit 54eb07e116
132 changed files with 805 additions and 823 deletions

View file

@ -54,22 +54,22 @@ void Application::construct()
isAppConstructed = true; isAppConstructed = true;
// 1. Instantiate all classes // 1. Instantiate all classes
this->settings = new singletons::SettingManager; this->settings = new chatterino::SettingManager;
this->paths = singletons::PathManager::getInstance(); this->paths = chatterino::PathManager::getInstance();
this->themes = new singletons::ThemeManager; this->themes = new chatterino::ThemeManager;
this->windows = new singletons::WindowManager; this->windows = new chatterino::WindowManager;
this->logging = new singletons::LoggingManager; this->logging = new chatterino::LoggingManager;
this->commands = new controllers::commands::CommandController; this->commands = new CommandController;
this->highlights = new controllers::highlights::HighlightController; this->highlights = new HighlightController;
this->ignores = new controllers::ignores::IgnoreController; this->ignores = new IgnoreController;
this->taggedUsers = new controllers::taggedusers::TaggedUsersController; this->taggedUsers = new TaggedUsersController;
this->accounts = new controllers::accounts::AccountController; this->accounts = new AccountController;
this->emotes = new singletons::EmoteManager; this->emotes = new chatterino::EmoteManager;
this->fonts = new singletons::FontManager; this->fonts = new chatterino::FontManager;
this->resources = new singletons::ResourceManager; this->resources = new chatterino::ResourceManager;
this->twitch.server = new providers::twitch::TwitchServer; this->twitch.server = new TwitchServer;
this->twitch.pubsub = new providers::twitch::PubSub; this->twitch.pubsub = new PubSub;
} }
void Application::instantiate(int argc, char **argv) void Application::instantiate(int argc, char **argv)
@ -119,11 +119,11 @@ void Application::initialize()
#endif #endif
this->twitch.pubsub->sig.whisper.sent.connect([](const auto &msg) { this->twitch.pubsub->sig.whisper.sent.connect([](const auto &msg) {
debug::Log("WHISPER SENT LOL"); // Log("WHISPER SENT LOL"); //
}); });
this->twitch.pubsub->sig.whisper.received.connect([](const auto &msg) { this->twitch.pubsub->sig.whisper.received.connect([](const auto &msg) {
debug::Log("WHISPER RECEIVED LOL"); // Log("WHISPER RECEIVED LOL"); //
}); });
this->twitch.pubsub->sig.moderation.chatCleared.connect([this](const auto &action) { this->twitch.pubsub->sig.moderation.chatCleared.connect([this](const auto &action) {
@ -134,8 +134,8 @@ void Application::initialize()
QString text = QString("%1 cleared the chat").arg(action.source.name); QString text = QString("%1 cleared the chat").arg(action.source.name);
auto msg = messages::Message::createSystemMessage(text); auto msg = chatterino::Message::createSystemMessage(text);
util::postToThread([chan, msg] { chan->addMessage(msg); }); postToThread([chan, msg] { chan->addMessage(msg); });
}); });
this->twitch.pubsub->sig.moderation.modeChanged.connect([this](const auto &action) { this->twitch.pubsub->sig.moderation.modeChanged.connect([this](const auto &action) {
@ -144,18 +144,17 @@ void Application::initialize()
return; return;
} }
QString text = QString text = QString("%1 turned %2 %3 mode") //
QString("%1 turned %2 %3 mode") //
.arg(action.source.name) .arg(action.source.name)
.arg(action.state == providers::twitch::ModeChangedAction::State::On ? "on" : "off") .arg(action.state == ModeChangedAction::State::On ? "on" : "off")
.arg(action.getModeName()); .arg(action.getModeName());
if (action.duration > 0) { if (action.duration > 0) {
text.append(" (" + QString::number(action.duration) + " seconds)"); text.append(" (" + QString::number(action.duration) + " seconds)");
} }
auto msg = messages::Message::createSystemMessage(text); auto msg = chatterino::Message::createSystemMessage(text);
util::postToThread([chan, msg] { chan->addMessage(msg); }); postToThread([chan, msg] { chan->addMessage(msg); });
}); });
this->twitch.pubsub->sig.moderation.moderationStateChanged.connect([this](const auto &action) { this->twitch.pubsub->sig.moderation.moderationStateChanged.connect([this](const auto &action) {
@ -172,8 +171,8 @@ void Application::initialize()
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 = messages::Message::createSystemMessage(text); auto msg = chatterino::Message::createSystemMessage(text);
util::postToThread([chan, msg] { chan->addMessage(msg); }); postToThread([chan, msg] { chan->addMessage(msg); });
}); });
this->twitch.pubsub->sig.moderation.userBanned.connect([&](const auto &action) { this->twitch.pubsub->sig.moderation.userBanned.connect([&](const auto &action) {
@ -183,10 +182,10 @@ void Application::initialize()
return; return;
} }
auto msg = messages::Message::createTimeoutMessage(action); auto msg = chatterino::Message::createTimeoutMessage(action);
msg->flags |= messages::Message::PubSub; msg->flags |= chatterino::Message::PubSub;
util::postToThread([chan, msg] { chan->addOrReplaceTimeout(msg); }); postToThread([chan, msg] { chan->addOrReplaceTimeout(msg); });
}); });
this->twitch.pubsub->sig.moderation.userUnbanned.connect([&](const auto &action) { this->twitch.pubsub->sig.moderation.userUnbanned.connect([&](const auto &action) {
@ -196,9 +195,9 @@ void Application::initialize()
return; return;
} }
auto msg = messages::Message::createUntimeoutMessage(action); auto msg = chatterino::Message::createUntimeoutMessage(action);
util::postToThread([chan, msg] { chan->addMessage(msg); }); postToThread([chan, msg] { chan->addMessage(msg); });
}); });
this->twitch.pubsub->start(); this->twitch.pubsub->start();

View file

@ -44,25 +44,25 @@ public:
friend void test(); friend void test();
singletons::PathManager *paths = nullptr; chatterino::PathManager *paths = nullptr;
singletons::ThemeManager *themes = nullptr; chatterino::ThemeManager *themes = nullptr;
singletons::WindowManager *windows = nullptr; chatterino::WindowManager *windows = nullptr;
singletons::LoggingManager *logging = nullptr; chatterino::LoggingManager *logging = nullptr;
controllers::commands::CommandController *commands = nullptr; CommandController *commands = nullptr;
controllers::highlights::HighlightController *highlights = nullptr; HighlightController *highlights = nullptr;
controllers::ignores::IgnoreController *ignores = nullptr; IgnoreController *ignores = nullptr;
controllers::taggedusers::TaggedUsersController *taggedUsers = nullptr; TaggedUsersController *taggedUsers = nullptr;
controllers::accounts::AccountController *accounts = nullptr; AccountController *accounts = nullptr;
singletons::EmoteManager *emotes = nullptr; chatterino::EmoteManager *emotes = nullptr;
singletons::NativeMessagingManager *nativeMessaging = nullptr; chatterino::NativeMessagingManager *nativeMessaging = nullptr;
singletons::SettingManager *settings = nullptr; chatterino::SettingManager *settings = nullptr;
singletons::FontManager *fonts = nullptr; chatterino::FontManager *fonts = nullptr;
singletons::ResourceManager *resources = nullptr; chatterino::ResourceManager *resources = nullptr;
/// Provider-specific /// Provider-specific
struct { struct {
providers::twitch::TwitchServer *server = nullptr; TwitchServer *server = nullptr;
providers::twitch::PubSub *pubsub = nullptr; PubSub *pubsub = nullptr;
} twitch; } twitch;
void save(); void save();

View file

@ -53,7 +53,7 @@ bool Channel::isEmpty() const
return this->name.isEmpty(); return this->name.isEmpty();
} }
messages::LimitedQueueSnapshot<messages::MessagePtr> Channel::getMessageSnapshot() chatterino::LimitedQueueSnapshot<chatterino::MessagePtr> Channel::getMessageSnapshot()
{ {
return this->messages.getSnapshot(); return this->messages.getSnapshot();
} }
@ -81,7 +81,7 @@ void Channel::addMessage(MessagePtr message)
this->messageAppended.invoke(message); this->messageAppended.invoke(message);
} }
void Channel::addOrReplaceTimeout(messages::MessagePtr message) void Channel::addOrReplaceTimeout(chatterino::MessagePtr message)
{ {
LimitedQueueSnapshot<MessagePtr> snapshot = this->getMessageSnapshot(); LimitedQueueSnapshot<MessagePtr> snapshot = this->getMessageSnapshot();
int snapshotLength = snapshot.getLength(); int snapshotLength = snapshot.getLength();
@ -118,7 +118,7 @@ void Channel::addOrReplaceTimeout(messages::MessagePtr message)
int count = s->count + 1; int count = s->count + 1;
messages::MessagePtr replacement(Message::createSystemMessage( chatterino::MessagePtr replacement(Message::createSystemMessage(
message->searchText + QString(" (") + QString::number(count) + " times)")); message->searchText + QString(" (") + QString::number(count) + " times)"));
replacement->timeoutUser = message->timeoutUser; replacement->timeoutUser = message->timeoutUser;
@ -162,16 +162,16 @@ void Channel::disableAllMessages()
} }
} }
void Channel::addMessagesAtStart(std::vector<messages::MessagePtr> &_messages) void Channel::addMessagesAtStart(std::vector<chatterino::MessagePtr> &_messages)
{ {
std::vector<messages::MessagePtr> addedMessages = this->messages.pushFront(_messages); std::vector<chatterino::MessagePtr> addedMessages = this->messages.pushFront(_messages);
if (addedMessages.size() != 0) { if (addedMessages.size() != 0) {
this->messagesAddedAtStart.invoke(addedMessages); this->messagesAddedAtStart.invoke(addedMessages);
} }
} }
void Channel::replaceMessage(messages::MessagePtr message, messages::MessagePtr replacement) void Channel::replaceMessage(chatterino::MessagePtr message, chatterino::MessagePtr replacement)
{ {
int index = this->messages.replaceItem(message, replacement); int index = this->messages.replaceItem(message, replacement);
@ -180,7 +180,7 @@ void Channel::replaceMessage(messages::MessagePtr message, messages::MessagePtr
} }
} }
void Channel::addRecentChatter(const std::shared_ptr<messages::Message> &message) void Channel::addRecentChatter(const std::shared_ptr<chatterino::Message> &message)
{ {
// Do nothing by default // Do nothing by default
} }

View file

@ -35,23 +35,23 @@ public:
pajlada::Signals::Signal<const QString &, const QString &, bool &> sendMessageSignal; pajlada::Signals::Signal<const QString &, const QString &, bool &> sendMessageSignal;
pajlada::Signals::Signal<messages::MessagePtr &> messageRemovedFromStart; pajlada::Signals::Signal<chatterino::MessagePtr &> messageRemovedFromStart;
pajlada::Signals::Signal<messages::MessagePtr &> messageAppended; pajlada::Signals::Signal<chatterino::MessagePtr &> messageAppended;
pajlada::Signals::Signal<std::vector<messages::MessagePtr> &> messagesAddedAtStart; pajlada::Signals::Signal<std::vector<chatterino::MessagePtr> &> messagesAddedAtStart;
pajlada::Signals::Signal<size_t, messages::MessagePtr &> messageReplaced; pajlada::Signals::Signal<size_t, chatterino::MessagePtr &> messageReplaced;
pajlada::Signals::NoArgSignal destroyed; pajlada::Signals::NoArgSignal destroyed;
Type getType() const; Type getType() const;
bool isTwitchChannel() const; bool isTwitchChannel() const;
virtual bool isEmpty() const; virtual bool isEmpty() const;
messages::LimitedQueueSnapshot<messages::MessagePtr> getMessageSnapshot(); chatterino::LimitedQueueSnapshot<chatterino::MessagePtr> getMessageSnapshot();
void addMessage(messages::MessagePtr message); void addMessage(chatterino::MessagePtr message);
void addMessagesAtStart(std::vector<messages::MessagePtr> &messages); void addMessagesAtStart(std::vector<chatterino::MessagePtr> &messages);
void addOrReplaceTimeout(messages::MessagePtr message); void addOrReplaceTimeout(chatterino::MessagePtr message);
void disableAllMessages(); void disableAllMessages();
void replaceMessage(messages::MessagePtr message, messages::MessagePtr replacement); void replaceMessage(chatterino::MessagePtr message, chatterino::MessagePtr replacement);
virtual void addRecentChatter(const std::shared_ptr<messages::Message> &message); virtual void addRecentChatter(const std::shared_ptr<chatterino::Message> &message);
QString name; QString name;
QStringList modList; QStringList modList;
@ -69,7 +69,7 @@ protected:
virtual void onConnected(); virtual void onConnected();
private: private:
messages::LimitedQueue<messages::MessagePtr> messages; chatterino::LimitedQueue<chatterino::MessagePtr> messages;
Type type; Type type;
}; };

View file

@ -19,7 +19,7 @@ CompletionModel::CompletionModel(const QString &_channelName)
void CompletionModel::refresh() void CompletionModel::refresh()
{ {
debug::Log("[CompletionModel:{}] Refreshing...]", this->channelName); Log("[CompletionModel:{}] Refreshing...]", this->channelName);
auto app = getApp(); auto app = getApp();
@ -75,7 +75,7 @@ void CompletionModel::refresh()
// Channel-specific: Usernames // Channel-specific: Usernames
// fourtf: only works with twitch chat // fourtf: only works with twitch chat
// auto c = singletons::ChannelManager::getInstance().getTwitchChannel(this->channelName); // auto c = chatterino::ChannelManager::getInstance().getTwitchChannel(this->channelName);
// auto usernames = c->getUsernamesForCompletions(); // auto usernames = c->getUsernamesForCompletions();
// for (const auto &name : usernames) { // for (const auto &name : usernames) {
// assert(!name.displayName.isEmpty()); // assert(!name.displayName.isEmpty());
@ -131,7 +131,7 @@ void CompletionModel::ClearExpiredStrings()
const auto &taggedString = *it; const auto &taggedString = *it;
if (taggedString.HasExpired(now)) { if (taggedString.HasExpired(now)) {
// debug::Log("String {} expired", taggedString.str); // Log("String {} expired", taggedString.str);
it = this->emotes.erase(it); it = this->emotes.erase(it);
} else { } else {
++it; ++it;

View file

@ -5,7 +5,7 @@
namespace chatterino { namespace chatterino {
EmoteData::EmoteData(messages::Image *_image) EmoteData::EmoteData(chatterino::Image *_image)
: image1x(_image) : image1x(_image)
{ {
} }
@ -16,7 +16,7 @@ bool EmoteData::isValid() const
return this->image1x != nullptr; return this->image1x != nullptr;
} }
messages::Image *EmoteData::getImage(float scale) const chatterino::Image *EmoteData::getImage(float scale) const
{ {
int quality = getApp()->settings->preferredEmoteQuality; int quality = getApp()->settings->preferredEmoteQuality;
@ -31,7 +31,7 @@ messages::Image *EmoteData::getImage(float scale) const
}(); }();
} }
messages::Image *_image; chatterino::Image *_image;
if (quality == 3 && this->image3x != nullptr) { if (quality == 3 && this->image3x != nullptr) {
_image = this->image3x; _image = this->image3x;
} else if (quality >= 2 && this->image2x != nullptr) { } else if (quality >= 2 && this->image2x != nullptr) {

View file

@ -8,15 +8,15 @@ namespace chatterino {
struct EmoteData { struct EmoteData {
EmoteData() = default; EmoteData() = default;
EmoteData(messages::Image *_image); EmoteData(chatterino::Image *_image);
// Emotes must have a 1x image to be valid // Emotes must have a 1x image to be valid
bool isValid() const; bool isValid() const;
messages::Image *getImage(float scale) const; chatterino::Image *getImage(float scale) const;
messages::Image *image1x = nullptr; chatterino::Image *image1x = nullptr;
messages::Image *image2x = nullptr; chatterino::Image *image2x = nullptr;
messages::Image *image3x = nullptr; chatterino::Image *image3x = nullptr;
// Link to the emote page i.e. https://www.frankerfacez.com/emoticon/144722-pajaCringe // Link to the emote page i.e. https://www.frankerfacez.com/emoticon/144722-pajaCringe
QString pageLink; QString pageLink;

View file

@ -31,7 +31,7 @@ static rapidjson::Document parseJSONFromData2(const QByteArray &data)
rapidjson::ParseResult result = ret.Parse(data.data(), data.length()); rapidjson::ParseResult result = ret.Parse(data.data(), data.length());
if (result.Code() != rapidjson::kParseErrorNone) { if (result.Code() != rapidjson::kParseErrorNone) {
debug::Log("JSON parse error: {} ({})", rapidjson::GetParseError_En(result.Code()), Log("JSON parse error: {} ({})", rapidjson::GetParseError_En(result.Code()),
result.Offset()); result.Offset());
return ret; return ret;
} }
@ -51,7 +51,7 @@ static rapidjson::Document parseJSONFromReply2(QNetworkReply *reply)
rapidjson::ParseResult result = ret.Parse(data.data(), data.length()); rapidjson::ParseResult result = ret.Parse(data.data(), data.length());
if (result.Code() != rapidjson::kParseErrorNone) { if (result.Code() != rapidjson::kParseErrorNone) {
debug::Log("JSON parse error: {} ({})", rapidjson::GetParseError_En(result.Code()), Log("JSON parse error: {} ({})", rapidjson::GetParseError_En(result.Code()),
result.Offset()); result.Offset());
return ret; return ret;
} }
@ -242,7 +242,7 @@ public:
if (timer != nullptr) { if (timer != nullptr) {
QObject::connect(timer, &QTimer::timeout, worker, [reply, timer]() { QObject::connect(timer, &QTimer::timeout, worker, [reply, timer]() {
debug::Log("Aborted!"); Log("Aborted!");
reply->abort(); reply->abort();
timer->deleteLater(); timer->deleteLater();
}); });
@ -314,7 +314,7 @@ public:
} break; } break;
default: { default: {
debug::Log("[Execute] Unhandled request type {}", (int)this->data.requestType); Log("[Execute] Unhandled request type {}", (int)this->data.requestType);
} break; } break;
} }
} }
@ -407,14 +407,14 @@ private:
} }
if (reply == nullptr) { if (reply == nullptr) {
debug::Log("Unhandled request type {}", (int)data.requestType); Log("Unhandled request type {}", (int)data.requestType);
return; return;
} }
if (timer != nullptr) { if (timer != nullptr) {
QObject::connect(timer, &QTimer::timeout, worker, QObject::connect(timer, &QTimer::timeout, worker,
[reply, timer, data]() { [reply, timer, data]() {
debug::Log("Aborted!"); Log("Aborted!");
reply->abort(); reply->abort();
timer->deleteLater(); timer->deleteLater();
data.onError(-2); data.onError(-2);

View file

@ -36,14 +36,14 @@ public:
const std::vector<TVectorItem> &getVector() const const std::vector<TVectorItem> &getVector() const
{ {
util::assertInGuiThread(); assertInGuiThread();
return this->vector; return this->vector;
} }
void invokeDelayedItemsChanged() void invokeDelayedItemsChanged()
{ {
util::assertInGuiThread(); assertInGuiThread();
if (!this->itemsChangedTimer.isActive()) { if (!this->itemsChangedTimer.isActive()) {
itemsChangedTimer.start(); itemsChangedTimer.start();
@ -64,7 +64,7 @@ public:
void removeItem(int index, void *caller = 0) void removeItem(int index, void *caller = 0)
{ {
util::assertInGuiThread(); assertInGuiThread();
assert(index >= 0 && index < this->vector.size()); assert(index >= 0 && index < this->vector.size());
TVectorItem item = this->vector[index]; TVectorItem item = this->vector[index];
@ -87,7 +87,7 @@ class UnsortedSignalVector : public BaseSignalVector<TVectorItem>
public: public:
virtual int insertItem(const TVectorItem &item, int index = -1, void *caller = 0) override virtual int insertItem(const TVectorItem &item, int index = -1, void *caller = 0) override
{ {
util::assertInGuiThread(); assertInGuiThread();
if (index == -1) { if (index == -1) {
index = this->vector.size(); index = this->vector.size();
} else { } else {
@ -109,7 +109,7 @@ class SortedSignalVector : public BaseSignalVector<TVectorItem>
public: 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
{ {
util::assertInGuiThread(); 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(); int index = it - this->vector.begin();

View file

@ -23,7 +23,7 @@ public:
} }
} }
void init(util::BaseSignalVector<TVectorItem> *vec) void init(BaseSignalVector<TVectorItem> *vec)
{ {
this->vector = vec; this->vector = vec;

View file

@ -1,10 +1,10 @@
#pragma once #pragma once
#include "controllers/accounts/AccountController.hpp"
#include "providers/twitch/Credentials.hpp"
#include "debug/Log.hpp"
#include "common/NetworkManager.hpp" #include "common/NetworkManager.hpp"
#include "common/NetworkRequest.hpp" #include "common/NetworkRequest.hpp"
#include "controllers/accounts/AccountController.hpp"
#include "debug/Log.hpp"
#include "providers/twitch/Credentials.hpp"
#include <rapidjson/document.h> #include <rapidjson/document.h>
#include <rapidjson/error/en.h> #include <rapidjson/error/en.h>
@ -26,7 +26,7 @@ namespace chatterino {
static void get(QString url, const QObject *caller, static void get(QString url, const QObject *caller,
std::function<void(const QJsonObject &)> successCallback) std::function<void(const QJsonObject &)> successCallback)
{ {
util::NetworkRequest req(url); NetworkRequest req(url);
req.setCaller(caller); req.setCaller(caller);
req.setRawHeader("Client-ID", getDefaultClientID()); req.setRawHeader("Client-ID", getDefaultClientID());
req.setRawHeader("Accept", "application/vnd.twitchtv.v5+json"); req.setRawHeader("Accept", "application/vnd.twitchtv.v5+json");
@ -39,7 +39,7 @@ static void get(QString url, const QObject *caller,
static void get2(QString url, const QObject *caller, bool useQuickLoadCache, static void get2(QString url, const QObject *caller, bool useQuickLoadCache,
std::function<void(const rapidjson::Document &)> successCallback) std::function<void(const rapidjson::Document &)> successCallback)
{ {
util::NetworkRequest req(url); NetworkRequest req(url);
req.setCaller(caller); req.setCaller(caller);
req.setRawHeader("Client-ID", getDefaultClientID()); req.setRawHeader("Client-ID", getDefaultClientID());
req.setRawHeader("Accept", "application/vnd.twitchtv.v5+json"); req.setRawHeader("Accept", "application/vnd.twitchtv.v5+json");
@ -54,7 +54,7 @@ static void getAuthorized(QString url, const QString &clientID, const QString &o
const QObject *caller, const QObject *caller,
std::function<void(const QJsonObject &)> successCallback) std::function<void(const QJsonObject &)> successCallback)
{ {
util::NetworkRequest req(url); NetworkRequest req(url);
req.setCaller(caller); req.setCaller(caller);
req.setRawHeader("Client-ID", clientID.toUtf8()); req.setRawHeader("Client-ID", clientID.toUtf8());
req.setRawHeader("Authorization", "OAuth " + oauthToken.toUtf8()); req.setRawHeader("Authorization", "OAuth " + oauthToken.toUtf8());
@ -71,23 +71,23 @@ static void getUserID(QString username, const QObject *caller,
get("https://api.twitch.tv/kraken/users?login=" + username, caller, get("https://api.twitch.tv/kraken/users?login=" + username, caller,
[=](const QJsonObject &root) { [=](const QJsonObject &root) {
if (!root.value("users").isArray()) { if (!root.value("users").isArray()) {
debug::Log("API Error while getting user id, users is not an array"); Log("API Error while getting user id, users is not an array");
return; return;
} }
auto users = root.value("users").toArray(); auto users = root.value("users").toArray();
if (users.size() != 1) { if (users.size() != 1) {
debug::Log("API Error while getting user id, users array size is not 1"); Log("API Error while getting user id, users array size is not 1");
return; return;
} }
if (!users[0].isObject()) { if (!users[0].isObject()) {
debug::Log("API Error while getting user id, first user is not an object"); Log("API Error while getting user id, first user is not an object");
return; return;
} }
auto firstUser = users[0].toObject(); auto firstUser = users[0].toObject();
auto id = firstUser.value("_id"); auto id = firstUser.value("_id");
if (!id.isString()) { if (!id.isString()) {
debug::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"); "string");
return; return;
} }

View file

@ -20,10 +20,10 @@ public:
void load(); void load();
providers::twitch::TwitchAccountManager twitch; TwitchAccountManager twitch;
private: private:
util::SortedSignalVector<std::shared_ptr<Account>, util::SharedPtrElementLess<Account>> SortedSignalVector<std::shared_ptr<Account>, SharedPtrElementLess<Account>>
accounts; accounts;
}; };

View file

@ -5,7 +5,7 @@
namespace chatterino { namespace chatterino {
AccountModel::AccountModel(QObject *parent) AccountModel::AccountModel(QObject *parent)
: util::SignalVectorModel<std::shared_ptr<Account>>(1, parent) : SignalVectorModel<std::shared_ptr<Account>>(1, parent)
{ {
} }
@ -20,7 +20,7 @@ std::shared_ptr<Account> AccountModel::getItemFromRow(std::vector<QStandardItem
void AccountModel::getRowFromItem(const std::shared_ptr<Account> &item, void AccountModel::getRowFromItem(const std::shared_ptr<Account> &item,
std::vector<QStandardItem *> &row) std::vector<QStandardItem *> &row)
{ {
util::setStringItem(row[0], item->toString(), false); setStringItem(row[0], item->toString(), false);
row[0]->setData(QFont("Segoe UI", 10), Qt::FontRole); row[0]->setData(QFont("Segoe UI", 10), Qt::FontRole);
} }
@ -30,7 +30,7 @@ int AccountModel::beforeInsert(const std::shared_ptr<Account> &item,
if (this->categoryCount[item->getCategory()]++ == 0) { if (this->categoryCount[item->getCategory()]++ == 0) {
auto row = this->createRow(); auto row = this->createRow();
util::setStringItem(row[0], item->getCategory(), false, false); setStringItem(row[0], item->getCategory(), false, false);
row[0]->setData(QFont("Segoe UI Light", 16), Qt::FontRole); row[0]->setData(QFont("Segoe UI Light", 16), Qt::FontRole);
this->insertCustomRow(std::move(row), proposedIndex); this->insertCustomRow(std::move(row), proposedIndex);

View file

@ -10,7 +10,7 @@ namespace chatterino {
class AccountController; class AccountController;
class AccountModel : public util::SignalVectorModel<std::shared_ptr<Account>> class AccountModel : public SignalVectorModel<std::shared_ptr<Account>>
{ {
public: public:
AccountModel(QObject *parent); AccountModel(QObject *parent);

View file

@ -23,8 +23,6 @@
"/followersoff" \ "/followersoff" \
} }
using namespace chatterino::providers::twitch;
namespace chatterino { namespace chatterino {
CommandController::CommandController() CommandController::CommandController()
@ -72,8 +70,7 @@ void CommandController::save()
{ {
QFile textFile(this->filePath); QFile textFile(this->filePath);
if (!textFile.open(QIODevice::WriteOnly)) { if (!textFile.open(QIODevice::WriteOnly)) {
debug::Log("[CommandController::saveCommands] Unable to open {} for writing", Log("[CommandController::saveCommands] Unable to open {} for writing", this->filePath);
this->filePath);
return; return;
} }
@ -115,16 +112,14 @@ QString CommandController::execCommand(const QString &text, ChannelPtr channel,
auto app = getApp(); auto app = getApp();
messages::MessageBuilder b; MessageBuilder b;
b.emplace<messages::TimestampElement>(); b.emplace<TimestampElement>();
b.emplace<messages::TextElement>(app->accounts->twitch.getCurrent()->getUserName(), b.emplace<TextElement>(app->accounts->twitch.getCurrent()->getUserName(),
messages::MessageElement::Text, MessageElement::Text, MessageColor::Text,
messages::MessageColor::Text,
FontStyle::ChatMediumBold); FontStyle::ChatMediumBold);
b.emplace<messages::TextElement>("->", messages::MessageElement::Text); b.emplace<TextElement>("->", MessageElement::Text);
b.emplace<messages::TextElement>(words[1] + ":", messages::MessageElement::Text, b.emplace<TextElement>(words[1] + ":", MessageElement::Text, MessageColor::Text,
messages::MessageColor::Text,
FontStyle::ChatMediumBold); FontStyle::ChatMediumBold);
QString rest = ""; QString rest = "";
@ -133,8 +128,8 @@ QString CommandController::execCommand(const QString &text, ChannelPtr channel,
rest += words[i] + " "; rest += words[i] + " ";
} }
b.emplace<messages::TextElement>(rest, messages::MessageElement::Text); b.emplace<TextElement>(rest, MessageElement::Text);
b.getMessage()->flags |= messages::Message::DoNotTriggerNotification; b.getMessage()->flags |= Message::DoNotTriggerNotification;
app->twitch.server->whispersChannel->addMessage(b.getMessage()); app->twitch.server->whispersChannel->addMessage(b.getMessage());
@ -157,7 +152,7 @@ QString CommandController::execCommand(const QString &text, ChannelPtr channel,
if (commandName == "/debug-args") { if (commandName == "/debug-args") {
QString msg = QApplication::instance()->arguments().join(' '); QString msg = QApplication::instance()->arguments().join(' ');
channel->addMessage(messages::Message::createSystemMessage(msg)); channel->addMessage(chatterino::Message::createSystemMessage(msg));
return ""; return "";
} else if (commandName == "/uptime") { } else if (commandName == "/uptime") {
@ -166,7 +161,7 @@ QString CommandController::execCommand(const QString &text, ChannelPtr channel,
QString messageText = QString messageText =
streamStatus.live ? streamStatus.uptime : "Channel is not live."; streamStatus.live ? streamStatus.uptime : "Channel is not live.";
channel->addMessage(messages::Message::createSystemMessage(messageText)); channel->addMessage(chatterino::Message::createSystemMessage(messageText));
return ""; return "";
} else if (commandName == "/ignore" && words.size() >= 2) { } else if (commandName == "/ignore" && words.size() >= 2) {
@ -176,13 +171,13 @@ QString CommandController::execCommand(const QString &text, ChannelPtr channel,
auto target = words.at(1); auto target = words.at(1);
if (user->isAnon()) { if (user->isAnon()) {
channel->addMessage(messages::Message::createSystemMessage( channel->addMessage(chatterino::Message::createSystemMessage(
"You must be logged in to ignore someone")); "You must be logged in to ignore someone"));
return ""; return "";
} }
user->ignore(target, [channel](auto resultCode, const QString &message) { user->ignore(target, [channel](auto resultCode, const QString &message) {
channel->addMessage(messages::Message::createSystemMessage(message)); channel->addMessage(chatterino::Message::createSystemMessage(message));
}); });
return ""; return "";
@ -193,13 +188,13 @@ QString CommandController::execCommand(const QString &text, ChannelPtr channel,
auto target = words.at(1); auto target = words.at(1);
if (user->isAnon()) { if (user->isAnon()) {
channel->addMessage(messages::Message::createSystemMessage( channel->addMessage(chatterino::Message::createSystemMessage(
"You must be logged in to ignore someone")); "You must be logged in to ignore someone"));
return ""; return "";
} }
user->unignore(target, [channel](auto resultCode, const QString &message) { user->unignore(target, [channel](auto resultCode, const QString &message) {
channel->addMessage(messages::Message::createSystemMessage(message)); channel->addMessage(chatterino::Message::createSystemMessage(message));
}); });
return ""; return "";

View file

@ -26,7 +26,7 @@ public:
CommandModel *createModel(QObject *parent); CommandModel *createModel(QObject *parent);
util::UnsortedSignalVector<Command> items; UnsortedSignalVector<Command> items;
private: private:
QMap<QString, Command> commandsMap; QMap<QString, Command> commandsMap;

View file

@ -4,7 +4,7 @@ namespace chatterino {
// commandmodel // commandmodel
CommandModel::CommandModel(QObject *parent) CommandModel::CommandModel(QObject *parent)
: util::SignalVectorModel<Command>(2, parent) : SignalVectorModel<Command>(2, parent)
{ {
} }

View file

@ -9,7 +9,7 @@ namespace chatterino {
class CommandController; class CommandController;
class CommandModel : public util::SignalVectorModel<Command> class CommandModel : public SignalVectorModel<Command>
{ {
explicit CommandModel(QObject *parent); explicit CommandModel(QObject *parent);

View file

@ -32,9 +32,9 @@ HighlightModel *HighlightController::createModel(QObject *parent)
return model; return model;
} }
void HighlightController::addHighlight(const messages::MessagePtr &msg) void HighlightController::addHighlight(const chatterino::MessagePtr &msg)
{ {
// static widgets::NotificationPopup popup; // static NotificationPopup popup;
// popup.updatePosition(); // popup.updatePosition();
// popup.addMessage(msg); // popup.addMessage(msg);

View file

@ -1,9 +1,9 @@
#pragma once #pragma once
#include "common/SignalVector2.hpp"
#include "controllers/highlights/HighlightPhrase.hpp" #include "controllers/highlights/HighlightPhrase.hpp"
#include "messages/Message.hpp" #include "messages/Message.hpp"
#include "singletons/SettingsManager.hpp" #include "singletons/SettingsManager.hpp"
#include "common/SignalVector2.hpp"
namespace chatterino { namespace chatterino {
@ -16,16 +16,16 @@ public:
void initialize(); void initialize();
util::UnsortedSignalVector<HighlightPhrase> phrases; UnsortedSignalVector<HighlightPhrase> phrases;
HighlightModel *createModel(QObject *parent); HighlightModel *createModel(QObject *parent);
void addHighlight(const messages::MessagePtr &msg); void addHighlight(const chatterino::MessagePtr &msg);
private: private:
bool initialized = false; bool initialized = false;
singletons::ChatterinoSetting<std::vector<highlights::HighlightPhrase>> highlightsSetting = { chatterino::ChatterinoSetting<std::vector<HighlightPhrase>> highlightsSetting = {
"/highlighting/highlights"}; "/highlighting/highlights"};
}; };

View file

@ -8,7 +8,7 @@ namespace chatterino {
// commandmodel // commandmodel
HighlightModel::HighlightModel(QObject *parent) HighlightModel::HighlightModel(QObject *parent)
: util::SignalVectorModel<HighlightPhrase>(4, parent) : SignalVectorModel<HighlightPhrase>(4, parent)
{ {
} }
@ -26,19 +26,19 @@ HighlightPhrase HighlightModel::getItemFromRow(std::vector<QStandardItem *> &row
// turns a row in the model into a vector item // turns a row in the model into a vector item
void HighlightModel::getRowFromItem(const HighlightPhrase &item, std::vector<QStandardItem *> &row) void HighlightModel::getRowFromItem(const HighlightPhrase &item, std::vector<QStandardItem *> &row)
{ {
util::setStringItem(row[0], item.getPattern()); setStringItem(row[0], item.getPattern());
util::setBoolItem(row[1], item.getAlert()); setBoolItem(row[1], item.getAlert());
util::setBoolItem(row[2], item.getSound()); setBoolItem(row[2], item.getSound());
util::setBoolItem(row[3], item.isRegex()); setBoolItem(row[3], item.isRegex());
} }
void HighlightModel::afterInit() void HighlightModel::afterInit()
{ {
std::vector<QStandardItem *> row = this->createRow(); std::vector<QStandardItem *> row = this->createRow();
util::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); row[0]->setData("Your username (automatic)", Qt::DisplayRole);
util::setBoolItem(row[1], getApp()->settings->enableHighlightTaskbar.getValue(), true, false); setBoolItem(row[1], getApp()->settings->enableHighlightTaskbar.getValue(), true, false);
util::setBoolItem(row[2], getApp()->settings->enableHighlightSound.getValue(), true, false); setBoolItem(row[2], getApp()->settings->enableHighlightSound.getValue(), true, false);
row[3]->setFlags(0); row[3]->setFlags(0);
this->insertCustomRow(row, 0); this->insertCustomRow(row, 0);
} }

View file

@ -9,7 +9,7 @@ namespace chatterino {
class HighlightController; class HighlightController;
class HighlightModel : public util::SignalVectorModel<HighlightPhrase> class HighlightModel : public SignalVectorModel<HighlightPhrase>
{ {
explicit HighlightModel(QObject *parent); explicit HighlightModel(QObject *parent);

View file

@ -74,8 +74,8 @@ namespace pajlada {
namespace Settings { namespace Settings {
template <> template <>
struct Serialize<chatterino::controllers::highlights::HighlightPhrase> { struct Serialize<chatterino::HighlightPhrase> {
static rapidjson::Value get(const chatterino::controllers::highlights::HighlightPhrase &value, static rapidjson::Value get(const chatterino::HighlightPhrase &value,
rapidjson::Document::AllocatorType &a) rapidjson::Document::AllocatorType &a)
{ {
rapidjson::Value ret(rapidjson::kObjectType); rapidjson::Value ret(rapidjson::kObjectType);
@ -90,11 +90,11 @@ struct Serialize<chatterino::controllers::highlights::HighlightPhrase> {
}; };
template <> template <>
struct Deserialize<chatterino::controllers::highlights::HighlightPhrase> { struct Deserialize<chatterino::HighlightPhrase> {
static chatterino::controllers::highlights::HighlightPhrase get(const rapidjson::Value &value) static chatterino::HighlightPhrase get(const rapidjson::Value &value)
{ {
if (!value.IsObject()) { if (!value.IsObject()) {
return chatterino::controllers::highlights::HighlightPhrase(QString(), true, false, return chatterino::HighlightPhrase(QString(), true, false,
false); false);
} }
@ -108,7 +108,7 @@ struct Deserialize<chatterino::controllers::highlights::HighlightPhrase> {
chatterino::rj::getSafe(value, "sound", _sound); chatterino::rj::getSafe(value, "sound", _sound);
chatterino::rj::getSafe(value, "regex", _isRegex); chatterino::rj::getSafe(value, "regex", _isRegex);
return chatterino::controllers::highlights::HighlightPhrase(_pattern, _alert, _sound, return chatterino::HighlightPhrase(_pattern, _alert, _sound,
_isRegex); _isRegex);
} }
}; };

View file

@ -13,14 +13,14 @@ class IgnoreController
public: public:
void initialize(); void initialize();
util::UnsortedSignalVector<IgnorePhrase> phrases; UnsortedSignalVector<IgnorePhrase> phrases;
IgnoreModel *createModel(QObject *parent); IgnoreModel *createModel(QObject *parent);
private: private:
bool initialized = false; bool initialized = false;
singletons::ChatterinoSetting<std::vector<ignores::IgnorePhrase>> ignoresSetting = { chatterino::ChatterinoSetting<std::vector<IgnorePhrase>> ignoresSetting = {
"/ignore/phrases"}; "/ignore/phrases"};
}; };

View file

@ -8,7 +8,7 @@ namespace chatterino {
// commandmodel // commandmodel
IgnoreModel::IgnoreModel(QObject *parent) IgnoreModel::IgnoreModel(QObject *parent)
: util::SignalVectorModel<IgnorePhrase>(2, parent) : SignalVectorModel<IgnorePhrase>(2, parent)
{ {
} }
@ -25,8 +25,8 @@ IgnorePhrase IgnoreModel::getItemFromRow(std::vector<QStandardItem *> &row,
// turns a row in the model into a vector item // turns a row in the model into a vector item
void IgnoreModel::getRowFromItem(const IgnorePhrase &item, std::vector<QStandardItem *> &row) void IgnoreModel::getRowFromItem(const IgnorePhrase &item, std::vector<QStandardItem *> &row)
{ {
util::setStringItem(row[0], item.getPattern()); setStringItem(row[0], item.getPattern());
util::setBoolItem(row[1], item.isRegex()); setBoolItem(row[1], item.isRegex());
} }
} // namespace chatterino } // namespace chatterino

View file

@ -9,7 +9,7 @@ namespace chatterino {
class IgnoreController; class IgnoreController;
class IgnoreModel : public util::SignalVectorModel<IgnorePhrase> class IgnoreModel : public SignalVectorModel<IgnorePhrase>
{ {
explicit IgnoreModel(QObject *parent); explicit IgnoreModel(QObject *parent);

View file

@ -57,8 +57,8 @@ namespace pajlada {
namespace Settings { namespace Settings {
template <> template <>
struct Serialize<chatterino::controllers::ignores::IgnorePhrase> { struct Serialize<chatterino::IgnorePhrase> {
static rapidjson::Value get(const chatterino::controllers::ignores::IgnorePhrase &value, static rapidjson::Value get(const chatterino::IgnorePhrase &value,
rapidjson::Document::AllocatorType &a) rapidjson::Document::AllocatorType &a)
{ {
rapidjson::Value ret(rapidjson::kObjectType); rapidjson::Value ret(rapidjson::kObjectType);
@ -71,11 +71,11 @@ struct Serialize<chatterino::controllers::ignores::IgnorePhrase> {
}; };
template <> template <>
struct Deserialize<chatterino::controllers::ignores::IgnorePhrase> { struct Deserialize<chatterino::IgnorePhrase> {
static chatterino::controllers::ignores::IgnorePhrase get(const rapidjson::Value &value) static chatterino::IgnorePhrase get(const rapidjson::Value &value)
{ {
if (!value.IsObject()) { if (!value.IsObject()) {
return chatterino::controllers::ignores::IgnorePhrase(QString(), false); return chatterino::IgnorePhrase(QString(), false);
} }
QString _pattern; QString _pattern;
@ -84,7 +84,7 @@ struct Deserialize<chatterino::controllers::ignores::IgnorePhrase> {
chatterino::rj::getSafe(value, "pattern", _pattern); chatterino::rj::getSafe(value, "pattern", _pattern);
chatterino::rj::getSafe(value, "regex", _isRegex); chatterino::rj::getSafe(value, "regex", _isRegex);
return chatterino::controllers::ignores::IgnorePhrase(_pattern, _isRegex); return chatterino::IgnorePhrase(_pattern, _isRegex);
} }
}; };

View file

@ -12,7 +12,7 @@ class TaggedUsersController
public: public:
TaggedUsersController(); TaggedUsersController();
util::SortedSignalVector<TaggedUser, std::less<TaggedUser>> users; SortedSignalVector<TaggedUser, std::less<TaggedUser>> users;
TaggedUsersModel *createModel(QObject *parent = nullptr); TaggedUsersModel *createModel(QObject *parent = nullptr);
}; };

View file

@ -7,7 +7,7 @@ namespace chatterino {
// commandmodel // commandmodel
TaggedUsersModel::TaggedUsersModel(QObject *parent) TaggedUsersModel::TaggedUsersModel(QObject *parent)
: util::SignalVectorModel<TaggedUser>(1, parent) : SignalVectorModel<TaggedUser>(1, parent)
{ {
} }
@ -21,16 +21,16 @@ TaggedUser TaggedUsersModel::getItemFromRow(std::vector<QStandardItem *> &row,
// turns a row in the model into a vector item // turns a row in the model into a vector item
void TaggedUsersModel::getRowFromItem(const TaggedUser &item, std::vector<QStandardItem *> &row) void TaggedUsersModel::getRowFromItem(const TaggedUser &item, std::vector<QStandardItem *> &row)
{ {
util::setStringItem(row[0], item.name); setStringItem(row[0], item.name);
} }
void TaggedUsersModel::afterInit() void TaggedUsersModel::afterInit()
{ {
// std::vector<QStandardItem *> row = this->createRow(); // std::vector<QStandardItem *> row = this->createRow();
// util::setBoolItem(row[0], getApp()->settings->enableHighlightsSelf.getValue(), true, // setBoolItem(row[0], getApp()->settings->enableHighlightsSelf.getValue(), true,
// false); row[0]->setData("Your username (automatic)", Qt::DisplayRole); // false); row[0]->setData("Your username (automatic)", Qt::DisplayRole);
// util::setBoolItem(row[1], getApp()->settings->enableHighlightTaskbar.getValue(), true, // setBoolItem(row[1], getApp()->settings->enableHighlightTaskbar.getValue(), true,
// false); util::setBoolItem(row[2], getApp()->settings->enableHighlightSound.getValue(), // false); setBoolItem(row[2], getApp()->settings->enableHighlightSound.getValue(),
// true, false); row[3]->setFlags(0); this->insertCustomRow(row, 0); // true, false); row[3]->setFlags(0); this->insertCustomRow(row, 0);
} }

View file

@ -7,7 +7,7 @@ namespace chatterino {
class TaggedUsersController; class TaggedUsersController;
class TaggedUsersModel : public util::SignalVectorModel<TaggedUser> class TaggedUsersModel : public SignalVectorModel<TaggedUser>
{ {
explicit TaggedUsersModel(QObject *parent); explicit TaggedUsersModel(QObject *parent);

View file

@ -1,9 +1,9 @@
#include "Application.hpp" #include "Application.hpp"
#include "common/NetworkManager.hpp"
#include "singletons/NativeMessagingManager.hpp" #include "singletons/NativeMessagingManager.hpp"
#include "singletons/PathManager.hpp" #include "singletons/PathManager.hpp"
#include "singletons/UpdateManager.hpp" #include "singletons/UpdateManager.hpp"
#include "util/DebugCount.hpp" #include "util/DebugCount.hpp"
#include "common/NetworkManager.hpp"
#include "widgets/dialogs/LastRunCrashDialog.hpp" #include "widgets/dialogs/LastRunCrashDialog.hpp"
#include <QAbstractNativeEventFilter> #include <QAbstractNativeEventFilter>
@ -40,7 +40,7 @@ int main(int argc, char *argv[])
// QApplication::setAttribute(Qt::AA_UseSoftwareOpenGL, true); // QApplication::setAttribute(Qt::AA_UseSoftwareOpenGL, true);
QApplication a(argc, argv); QApplication a(argc, argv);
chatterino::singletons::PathManager::initInstance(); chatterino::PathManager::initInstance();
// read args // read args
QStringList args; QStringList args;
@ -49,10 +49,6 @@ int main(int argc, char *argv[])
args << argv[i]; args << argv[i];
} }
for (auto &arg : args) {
chatterino::util::DebugCount::increase(arg);
}
// TODO: can be any argument // TODO: can be any argument
if (args.size() > 0 && if (args.size() > 0 &&
(args[0].startsWith("chrome-extension://") || args[0].endsWith(".json"))) { (args[0].startsWith("chrome-extension://") || args[0].endsWith(".json"))) {
@ -71,10 +67,10 @@ int runGui(QApplication &a, int argc, char *argv[])
installCustomPalette(); installCustomPalette();
// Initialize NetworkManager // Initialize NetworkManager
chatterino::util::NetworkManager::init(); chatterino::NetworkManager::init();
// Check for upates // Check for upates
chatterino::singletons::UpdateManager::getInstance().checkForUpdates(); chatterino::UpdateManager::getInstance().checkForUpdates();
// Initialize application // Initialize application
chatterino::Application::instantiate(argc, argv); chatterino::Application::instantiate(argc, argv);
@ -88,7 +84,7 @@ int runGui(QApplication &a, int argc, char *argv[])
if (QFile::exists(runningPath)) { if (QFile::exists(runningPath)) {
#ifndef DISABLE_CRASH_DIALOG #ifndef DISABLE_CRASH_DIALOG
chatterino::widgets::LastRunCrashDialog dialog; chatterino::LastRunCrashDialog dialog;
switch (dialog.exec()) { switch (dialog.exec()) {
case QDialog::Accepted: { case QDialog::Accepted: {
@ -122,14 +118,14 @@ int runGui(QApplication &a, int argc, char *argv[])
pajlada::Settings::SettingManager::save(); pajlada::Settings::SettingManager::save();
// Deinitialize NetworkManager (stop thread and wait for finish, should be instant) // Deinitialize NetworkManager (stop thread and wait for finish, should be instant)
chatterino::util::NetworkManager::deinit(); chatterino::NetworkManager::deinit();
_exit(0); _exit(0);
} }
void runNativeMessagingHost() void runNativeMessagingHost()
{ {
auto *nm = new chatterino::singletons::NativeMessagingManager; auto *nm = new chatterino::NativeMessagingManager;
#ifdef Q_OS_WIN #ifdef Q_OS_WIN
_setmode(_fileno(stdin), _O_BINARY); _setmode(_fileno(stdin), _O_BINARY);

View file

@ -1,13 +1,13 @@
#include "messages/Image.hpp" #include "messages/Image.hpp"
#include "Application.hpp" #include "Application.hpp"
#include "common/NetworkManager.hpp"
#include "common/UrlFetch.hpp"
#include "debug/Log.hpp" #include "debug/Log.hpp"
#include "singletons/EmoteManager.hpp" #include "singletons/EmoteManager.hpp"
#include "singletons/IrcManager.hpp" #include "singletons/IrcManager.hpp"
#include "singletons/WindowManager.hpp" #include "singletons/WindowManager.hpp"
#include "common/NetworkManager.hpp"
#include "util/PostToThread.hpp" #include "util/PostToThread.hpp"
#include "common/UrlFetch.hpp"
#include <QBuffer> #include <QBuffer>
#include <QImageReader> #include <QImageReader>
@ -32,7 +32,7 @@ Image::Image(const QString &url, qreal scale, const QString &name, const QString
, ishat(isHat) , ishat(isHat)
, scale(scale) , scale(scale)
{ {
util::DebugCount::increase("images"); DebugCount::increase("images");
} }
Image::Image(QPixmap *image, qreal scale, const QString &name, const QString &tooltip, Image::Image(QPixmap *image, qreal scale, const QString &name, const QString &tooltip,
@ -46,25 +46,25 @@ Image::Image(QPixmap *image, qreal scale, const QString &name, const QString &to
, isLoading(true) , isLoading(true)
, isLoaded(true) , isLoaded(true)
{ {
util::DebugCount::increase("images"); DebugCount::increase("images");
} }
Image::~Image() Image::~Image()
{ {
util::DebugCount::decrease("images"); DebugCount::decrease("images");
if (this->isAnimated()) { if (this->isAnimated()) {
util::DebugCount::decrease("animated images"); DebugCount::decrease("animated images");
} }
if (this->isLoaded) { if (this->isLoaded) {
util::DebugCount::decrease("loaded images"); DebugCount::decrease("loaded images");
} }
} }
void Image::loadImage() void Image::loadImage()
{ {
util::NetworkRequest req(this->getUrl()); NetworkRequest req(this->getUrl());
req.setCaller(this); req.setCaller(this);
req.setUseQuickLoadCache(true); req.setUseQuickLoadCache(true);
req.get([this](QByteArray bytes) -> bool { req.get([this](QByteArray bytes) -> bool {
@ -80,21 +80,21 @@ void Image::loadImage()
// clear stuff before loading the image again // clear stuff before loading the image again
this->allFrames.clear(); this->allFrames.clear();
if (this->isAnimated()) { if (this->isAnimated()) {
util::DebugCount::decrease("animated images"); DebugCount::decrease("animated images");
} }
if (this->isLoaded) { if (this->isLoaded) {
util::DebugCount::decrease("loaded images"); DebugCount::decrease("loaded images");
} }
if (reader.imageCount() == -1) { if (reader.imageCount() == -1) {
// An error occured in the reader // An error occured in the reader
debug::Log("An error occured reading the image: '{}'", reader.errorString()); Log("An error occured reading the image: '{}'", reader.errorString());
debug::Log("Image url: {}", this->url); Log("Image url: {}", this->url);
return false; return false;
} }
if (reader.imageCount() == 0) { if (reader.imageCount() == 0) {
debug::Log("Error: No images read in the buffer"); Log("Error: No images read in the buffer");
// No images read in the buffer. maybe a cache error? // No images read in the buffer. maybe a cache error?
return false; return false;
} }
@ -108,7 +108,7 @@ void Image::loadImage()
this->loadedPixmap = pixmap; this->loadedPixmap = pixmap;
} }
chatterino::messages::Image::FrameData data; chatterino::Image::FrameData data;
data.duration = std::max(20, reader.nextImageDelay()); data.duration = std::max(20, reader.nextImageDelay());
data.image = pixmap; data.image = pixmap;
@ -117,14 +117,14 @@ void Image::loadImage()
} }
if (this->allFrames.size() != reader.imageCount()) { if (this->allFrames.size() != reader.imageCount()) {
// debug::Log("Error: Wrong amount of images read"); // Log("Error: Wrong amount of images read");
// One or more images failed to load from the buffer // One or more images failed to load from the buffer
// return false; // return false;
} }
if (this->allFrames.size() > 1) { if (this->allFrames.size() > 1) {
if (!this->animated) { if (!this->animated) {
util::postToThread([this] { postToThread([this] {
getApp()->emotes->gifTimer.signal.connect([=]() { getApp()->emotes->gifTimer.signal.connect([=]() {
this->gifUpdateTimout(); this->gifUpdateTimout();
}); // For some reason when Boost signal is in }); // For some reason when Boost signal is in
@ -135,13 +135,13 @@ void Image::loadImage()
this->animated = true; this->animated = true;
util::DebugCount::increase("animated images"); DebugCount::increase("animated images");
} }
this->currentPixmap = this->loadedPixmap; this->currentPixmap = this->loadedPixmap;
this->isLoaded = true; this->isLoaded = true;
util::DebugCount::increase("loaded images"); DebugCount::increase("loaded images");
if (!loadedEventQueued) { if (!loadedEventQueued) {
loadedEventQueued = true; loadedEventQueued = true;

View file

@ -200,7 +200,7 @@ public:
// void insertAfter(const std::vector<T> &items, const T &index) // void insertAfter(const std::vector<T> &items, const T &index)
messages::LimitedQueueSnapshot<T> getSnapshot() chatterino::LimitedQueueSnapshot<T> getSnapshot()
{ {
std::lock_guard<std::mutex> lock(this->mutex); std::lock_guard<std::mutex> lock(this->mutex);

View file

@ -3,7 +3,7 @@
#include "providers/twitch/PubsubActions.hpp" #include "providers/twitch/PubsubActions.hpp"
#include "util/IrcHelpers.hpp" #include "util/IrcHelpers.hpp"
using SBHighlight = chatterino::widgets::ScrollbarHighlight; using SBHighlight = chatterino::ScrollbarHighlight;
namespace chatterino { namespace chatterino {
@ -116,7 +116,7 @@ MessagePtr Message::createTimeoutMessage(const QString &username, const QString
if (reason.length() > 0) { if (reason.length() > 0) {
text.append(": \""); text.append(": \"");
text.append(util::parseTagString(reason)); text.append(parseTagString(reason));
text.append("\""); text.append("\"");
} }
text.append("."); text.append(".");
@ -132,7 +132,7 @@ MessagePtr Message::createTimeoutMessage(const QString &username, const QString
return message; return message;
} }
MessagePtr Message::createTimeoutMessage(const providers::twitch::BanAction &action, uint32_t count) MessagePtr Message::createTimeoutMessage(const BanAction &action, uint32_t count)
{ {
MessagePtr msg(new Message); MessagePtr msg(new Message);
@ -175,14 +175,14 @@ MessagePtr Message::createTimeoutMessage(const providers::twitch::BanAction &act
} }
} }
msg->addElement(new messages::TextElement(text, messages::MessageElement::Text, msg->addElement(new chatterino::TextElement(text, chatterino::MessageElement::Text,
messages::MessageColor::System)); chatterino::MessageColor::System));
msg->searchText = text; msg->searchText = text;
return msg; return msg;
} }
MessagePtr Message::createUntimeoutMessage(const providers::twitch::UnbanAction &action) MessagePtr Message::createUntimeoutMessage(const UnbanAction &action)
{ {
MessagePtr msg(new Message); MessagePtr msg(new Message);
@ -204,8 +204,8 @@ MessagePtr Message::createUntimeoutMessage(const providers::twitch::UnbanAction
.arg(action.target.name); .arg(action.target.name);
} }
msg->addElement(new messages::TextElement(text, messages::MessageElement::Text, msg->addElement(new chatterino::TextElement(text, chatterino::MessageElement::Text,
messages::MessageColor::System)); chatterino::MessageColor::System));
msg->searchText = text; msg->searchText = text;
return msg; return msg;

View file

@ -19,12 +19,12 @@ struct Message {
Message() Message()
: parseTime(QTime::currentTime()) : parseTime(QTime::currentTime())
{ {
util::DebugCount::increase("messages"); DebugCount::increase("messages");
} }
~Message() ~Message()
{ {
util::DebugCount::decrease("messages"); DebugCount::decrease("messages");
} }
enum MessageFlags : uint16_t { enum MessageFlags : uint16_t {
@ -43,7 +43,7 @@ struct Message {
Subscription = (1 << 11), Subscription = (1 << 11),
}; };
util::FlagsEnum<MessageFlags> flags; FlagsEnum<MessageFlags> flags;
QTime parseTime; QTime parseTime;
QString id; QString id;
QString searchText; QString searchText;
@ -59,7 +59,7 @@ struct Message {
const std::vector<std::unique_ptr<MessageElement>> &getElements() const; const std::vector<std::unique_ptr<MessageElement>> &getElements() const;
// Scrollbar // Scrollbar
widgets::ScrollbarHighlight getScrollBarHighlight() const; ScrollbarHighlight getScrollBarHighlight() const;
private: private:
std::vector<std::unique_ptr<MessageElement>> elements; std::vector<std::unique_ptr<MessageElement>> elements;
@ -72,10 +72,10 @@ public:
const QString &durationInSeconds, const QString &durationInSeconds,
const QString &reason, bool multipleTimes); const QString &reason, bool multipleTimes);
static std::shared_ptr<Message> createTimeoutMessage(const providers::twitch::BanAction &action, static std::shared_ptr<Message> createTimeoutMessage(const BanAction &action,
uint32_t count = 1); uint32_t count = 1);
static std::shared_ptr<Message> createUntimeoutMessage( static std::shared_ptr<Message> createUntimeoutMessage(
const providers::twitch::UnbanAction &action); const UnbanAction &action);
}; };
using MessagePtr = std::shared_ptr<Message>; using MessagePtr = std::shared_ptr<Message>;

View file

@ -13,7 +13,7 @@ MessageColor::MessageColor(Type _type)
{ {
} }
const QColor &MessageColor::getColor(singletons::ThemeManager &themeManager) const const QColor &MessageColor::getColor(chatterino::ThemeManager &themeManager) const
{ {
switch (this->type) { switch (this->type) {
case Type::Custom: case Type::Custom:

View file

@ -12,7 +12,7 @@ struct MessageColor {
MessageColor(const QColor &color); MessageColor(const QColor &color);
MessageColor(Type type = Text); MessageColor(Type type = Text);
const QColor &getColor(singletons::ThemeManager &themeManager) const; const QColor &getColor(chatterino::ThemeManager &themeManager) const;
private: private:
Type type; Type type;

View file

@ -12,12 +12,12 @@ namespace chatterino {
MessageElement::MessageElement(Flags _flags) MessageElement::MessageElement(Flags _flags)
: flags(_flags) : flags(_flags)
{ {
util::DebugCount::increase("message elements"); DebugCount::increase("message elements");
} }
MessageElement::~MessageElement() MessageElement::~MessageElement()
{ {
util::DebugCount::decrease("message elements"); DebugCount::decrease("message elements");
} }
MessageElement *MessageElement::setLink(const Link &_link) MessageElement *MessageElement::setLink(const Link &_link)
@ -78,7 +78,7 @@ void ImageElement::addToContainer(MessageLayoutContainer &container, MessageElem
} }
// EMOTE // EMOTE
EmoteElement::EmoteElement(const util::EmoteData &_data, MessageElement::Flags flags) EmoteElement::EmoteElement(const EmoteData &_data, MessageElement::Flags flags)
: MessageElement(flags) : MessageElement(flags)
, data(_data) , data(_data)
{ {
@ -248,7 +248,7 @@ void TwitchModerationElement::addToContainer(MessageLayoutContainer &container,
if (_flags & MessageElement::ModeratorTools) { 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 singletons::ModerationAction &m : getApp()->settings->getModerationActions()) { for (const chatterino::ModerationAction &m : getApp()->settings->getModerationActions()) {
if (m.isImage()) { if (m.isImage()) {
container.addElement((new ImageLayoutElement(*this, m.getImage(), size)) container.addElement((new ImageLayoutElement(*this, m.getImage(), size))
->setLink(Link(Link::UserAction, m.getAction()))); ->setLink(Link(Link::UserAction, m.getAction())));

View file

@ -1,10 +1,10 @@
#pragma once #pragma once
#include "common/Emotemap.hpp"
#include "messages/Image.hpp" #include "messages/Image.hpp"
#include "messages/Link.hpp" #include "messages/Link.hpp"
#include "messages/MessageColor.hpp" #include "messages/MessageColor.hpp"
#include "singletons/FontManager.hpp" #include "singletons/FontManager.hpp"
#include "common/Emotemap.hpp"
#include <QRect> #include <QRect>
#include <QString> #include <QString>
@ -19,8 +19,6 @@ class Channel;
struct EmoteData; struct EmoteData;
struct MessageLayoutContainer; struct MessageLayoutContainer;
using namespace chatterino::messages::layouts;
class MessageElement : boost::noncopyable class MessageElement : boost::noncopyable
{ {
public: public:
@ -167,12 +165,12 @@ class EmoteElement : public MessageElement
std::unique_ptr<TextElement> textElement; std::unique_ptr<TextElement> textElement;
public: public:
EmoteElement(const util::EmoteData &data, MessageElement::Flags flags); EmoteElement(const EmoteData &data, MessageElement::Flags flags);
~EmoteElement() override = default; ~EmoteElement() override = default;
void addToContainer(MessageLayoutContainer &container, MessageElement::Flags flags) override; void addToContainer(MessageLayoutContainer &container, MessageElement::Flags flags) override;
const util::EmoteData data; const EmoteData data;
}; };
// contains a text, formated depending on the preferences // contains a text, formated depending on the preferences

View file

@ -24,12 +24,12 @@ MessageLayout::MessageLayout(MessagePtr message)
: message_(message) : message_(message)
, buffer_(nullptr) , buffer_(nullptr)
{ {
util::DebugCount::increase("message layout"); DebugCount::increase("message layout");
} }
MessageLayout::~MessageLayout() MessageLayout::~MessageLayout()
{ {
util::DebugCount::decrease("message layout"); DebugCount::decrease("message layout");
} }
Message *MessageLayout::getMessage() Message *MessageLayout::getMessage()
@ -140,7 +140,7 @@ void MessageLayout::paint(QPainter &painter, int width, int y, int messageIndex,
this->buffer_ = std::shared_ptr<QPixmap>(pixmap); this->buffer_ = std::shared_ptr<QPixmap>(pixmap);
this->bufferValid_ = false; this->bufferValid_ = false;
util::DebugCount::increase("message drawing buffers"); DebugCount::increase("message drawing buffers");
} }
if (!this->bufferValid_ || !selection.isEmpty()) { if (!this->bufferValid_ || !selection.isEmpty()) {
@ -230,7 +230,7 @@ void MessageLayout::invalidateBuffer()
void MessageLayout::deleteBuffer() void MessageLayout::deleteBuffer()
{ {
if (this->buffer_ != nullptr) { if (this->buffer_ != nullptr) {
util::DebugCount::decrease("message drawing buffers"); DebugCount::decrease("message drawing buffers");
this->buffer_ = nullptr; this->buffer_ = nullptr;
} }

View file

@ -34,7 +34,7 @@ public:
int getHeight() const; int getHeight() const;
// Flags // Flags
util::FlagsEnum<Flags> flags; FlagsEnum<Flags> flags;
// Layout // Layout
bool layout(int width, float scale_, MessageElement::Flags flags); bool layout(int width, float scale_, MessageElement::Flags flags);

View file

@ -18,12 +18,12 @@ MessageLayoutElement::MessageLayoutElement(MessageElement &_creator, const QSize
: creator(_creator) : creator(_creator)
{ {
this->rect.setSize(size); this->rect.setSize(size);
util::DebugCount::increase("message layout elements"); DebugCount::increase("message layout elements");
} }
MessageLayoutElement::~MessageLayoutElement() MessageLayoutElement::~MessageLayoutElement()
{ {
util::DebugCount::decrease("message layout elements"); DebugCount::decrease("message layout elements");
} }
MessageElement &MessageLayoutElement::getCreator() const MessageElement &MessageLayoutElement::getCreator() const

View file

@ -21,7 +21,7 @@ void BTTVEmotes::loadGlobalEmotes()
{ {
QString url("https://api.betterttv.net/2/emotes"); QString url("https://api.betterttv.net/2/emotes");
util::NetworkRequest req(url); NetworkRequest req(url);
req.setCaller(QThread::currentThread()); req.setCaller(QThread::currentThread());
req.setTimeout(30000); req.setTimeout(30000);
req.setUseQuickLoadCache(true); req.setUseQuickLoadCache(true);
@ -35,12 +35,12 @@ void BTTVEmotes::loadGlobalEmotes()
QString id = emote.toObject().value("id").toString(); QString id = emote.toObject().value("id").toString();
QString code = emote.toObject().value("code").toString(); QString code = emote.toObject().value("code").toString();
util::EmoteData emoteData; EmoteData emoteData;
emoteData.image1x = new messages::Image(getEmoteLink(urlTemplate, id, "1x"), 1, code, emoteData.image1x = new chatterino::Image(getEmoteLink(urlTemplate, id, "1x"), 1, code,
code + "<br />Global BTTV Emote"); code + "<br />Global BTTV Emote");
emoteData.image2x = new messages::Image(getEmoteLink(urlTemplate, id, "2x"), 0.5, code, emoteData.image2x = new chatterino::Image(getEmoteLink(urlTemplate, id, "2x"), 0.5, code,
code + "<br />Global BTTV Emote"); code + "<br />Global BTTV Emote");
emoteData.image3x = new messages::Image(getEmoteLink(urlTemplate, id, "3x"), 0.25, code, emoteData.image3x = new chatterino::Image(getEmoteLink(urlTemplate, id, "3x"), 0.25, code,
code + "<br />Global BTTV Emote"); code + "<br />Global BTTV Emote");
emoteData.pageLink = "https://manage.betterttv.net/emotes/" + id; emoteData.pageLink = "https://manage.betterttv.net/emotes/" + id;
@ -52,15 +52,15 @@ void BTTVEmotes::loadGlobalEmotes()
}); });
} }
void BTTVEmotes::loadChannelEmotes(const QString &channelName, std::weak_ptr<util::EmoteMap> _map) void BTTVEmotes::loadChannelEmotes(const QString &channelName, std::weak_ptr<EmoteMap> _map)
{ {
printf("[BTTVEmotes] Reload BTTV Channel Emotes for channel %s\n", qPrintable(channelName)); printf("[BTTVEmotes] Reload BTTV Channel Emotes for channel %s\n", qPrintable(channelName));
QString url("https://api.betterttv.net/2/channels/" + channelName); QString url("https://api.betterttv.net/2/channels/" + channelName);
debug::Log("Request bttv channel emotes for {}", channelName); Log("Request bttv channel emotes for {}", channelName);
util::NetworkRequest req(url); NetworkRequest req(url);
req.setCaller(QThread::currentThread()); req.setCaller(QThread::currentThread());
req.setTimeout(3000); req.setTimeout(3000);
req.setUseQuickLoadCache(true); req.setUseQuickLoadCache(true);
@ -86,21 +86,21 @@ void BTTVEmotes::loadChannelEmotes(const QString &channelName, std::weak_ptr<uti
// emoteObject.value("imageType").toString(); // emoteObject.value("imageType").toString();
auto emote = this->channelEmoteCache.getOrAdd(id, [&] { auto emote = this->channelEmoteCache.getOrAdd(id, [&] {
util::EmoteData emoteData; EmoteData emoteData;
QString link = linkTemplate; QString link = linkTemplate;
link.detach(); link.detach();
emoteData.image1x = emoteData.image1x =
new messages::Image(link.replace("{{id}}", id).replace("{{image}}", "1x"), 1, new chatterino::Image(link.replace("{{id}}", id).replace("{{image}}", "1x"), 1,
code, code + "<br />Channel BTTV Emote"); code, code + "<br />Channel BTTV Emote");
link = linkTemplate; link = linkTemplate;
link.detach(); link.detach();
emoteData.image2x = emoteData.image2x =
new messages::Image(link.replace("{{id}}", id).replace("{{image}}", "2x"), 0.5, new chatterino::Image(link.replace("{{id}}", id).replace("{{image}}", "2x"), 0.5,
code, code + "<br />Channel BTTV Emote"); code, code + "<br />Channel BTTV Emote");
link = linkTemplate; link = linkTemplate;
link.detach(); link.detach();
emoteData.image3x = emoteData.image3x =
new messages::Image(link.replace("{{id}}", id).replace("{{image}}", "3x"), 0.25, new chatterino::Image(link.replace("{{id}}", id).replace("{{image}}", "3x"), 0.25,
code, code + "<br />Channel BTTV Emote"); code, code + "<br />Channel BTTV Emote");
emoteData.pageLink = "https://manage.betterttv.net/emotes/" + id; emoteData.pageLink = "https://manage.betterttv.net/emotes/" + id;

View file

@ -11,18 +11,18 @@ namespace chatterino {
class BTTVEmotes class BTTVEmotes
{ {
public: public:
util::EmoteMap globalEmotes; EmoteMap globalEmotes;
SignalVector<QString> globalEmoteCodes; SignalVector<QString> globalEmoteCodes;
util::EmoteMap channelEmotes; EmoteMap channelEmotes;
std::map<QString, SignalVector<QString>> channelEmoteCodes; std::map<QString, SignalVector<QString>> channelEmoteCodes;
void loadGlobalEmotes(); void loadGlobalEmotes();
void loadChannelEmotes(const QString &channelName, void loadChannelEmotes(const QString &channelName,
std::weak_ptr<util::EmoteMap> channelEmoteMap); std::weak_ptr<EmoteMap> channelEmoteMap);
private: private:
util::EmoteMap channelEmoteCache; EmoteMap channelEmoteCache;
}; };
} // namespace chatterino } // namespace chatterino

View file

@ -111,7 +111,7 @@ void Emojis::loadEmojis()
rapidjson::ParseResult result = root.Parse(data.toUtf8(), data.length()); rapidjson::ParseResult result = root.Parse(data.toUtf8(), data.length());
if (result.Code() != rapidjson::kParseErrorNone) { if (result.Code() != rapidjson::kParseErrorNone) {
debug::Log("JSON parse error: {} ({})", rapidjson::GetParseError_En(result.Code()), Log("JSON parse error: {} ({})", rapidjson::GetParseError_En(result.Code()),
result.Offset()); result.Offset());
return; return;
} }
@ -138,7 +138,7 @@ void Emojis::loadEmojis()
auto toneNameIt = toneNames.find(tone); auto toneNameIt = toneNames.find(tone);
if (toneNameIt == toneNames.end()) { if (toneNameIt == toneNames.end()) {
debug::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; continue;
} }
@ -206,7 +206,7 @@ void Emojis::loadEmojiSet()
auto app = getApp(); auto app = getApp();
app->settings->emojiSet.connect([=](const auto &emojiSet, auto) { app->settings->emojiSet.connect([=](const auto &emojiSet, auto) {
debug::Log("Using emoji set {}", emojiSet); Log("Using emoji set {}", emojiSet);
this->emojis.each([=](const auto &name, std::shared_ptr<EmojiData> &emoji) { this->emojis.each([=](const auto &name, std::shared_ptr<EmojiData> &emoji) {
QString emojiSetToUse = emojiSet; QString emojiSetToUse = emojiSet;
// clang-format off // clang-format off
@ -260,13 +260,13 @@ void Emojis::loadEmojiSet()
urlPrefix = it->second; urlPrefix = it->second;
} }
QString url = urlPrefix + code + ".png"; QString url = urlPrefix + code + ".png";
emoji->emoteData.image1x = new messages::Image( emoji->emoteData.image1x = new chatterino::Image(
url, 0.35, emoji->value, ":" + emoji->shortCodes[0] + ":<br/>Emoji"); url, 0.35, emoji->value, ":" + emoji->shortCodes[0] + ":<br/>Emoji");
}); });
}); });
} }
void Emojis::parse(std::vector<std::tuple<util::EmoteData, QString>> &parsedWords, void Emojis::parse(std::vector<std::tuple<EmoteData, QString>> &parsedWords,
const QString &text) const QString &text)
{ {
int lastParsedEmojiEndIndex = 0; int lastParsedEmojiEndIndex = 0;
@ -328,13 +328,13 @@ void Emojis::parse(std::vector<std::tuple<util::EmoteData, QString>> &parsedWord
if (charactersFromLastParsedEmoji > 0) { if (charactersFromLastParsedEmoji > 0) {
// Add characters inbetween emojis // Add characters inbetween emojis
parsedWords.emplace_back(util::EmoteData(), text.mid(lastParsedEmojiEndIndex, parsedWords.emplace_back(EmoteData(), text.mid(lastParsedEmojiEndIndex,
charactersFromLastParsedEmoji)); charactersFromLastParsedEmoji));
} }
// Push the emoji as a word to parsedWords // Push the emoji as a word to parsedWords
parsedWords.push_back( parsedWords.push_back(
std::tuple<util::EmoteData, QString>(matchedEmoji->emoteData, QString())); std::tuple<EmoteData, QString>(matchedEmoji->emoteData, QString()));
lastParsedEmojiEndIndex = currentParsedEmojiEndIndex; lastParsedEmojiEndIndex = currentParsedEmojiEndIndex;
@ -343,7 +343,7 @@ void Emojis::parse(std::vector<std::tuple<util::EmoteData, QString>> &parsedWord
if (lastParsedEmojiEndIndex < text.length()) { if (lastParsedEmojiEndIndex < text.length()) {
// Add remaining characters // Add remaining characters
parsedWords.emplace_back(util::EmoteData(), text.mid(lastParsedEmojiEndIndex)); parsedWords.emplace_back(EmoteData(), text.mid(lastParsedEmojiEndIndex));
} }
} }

View file

@ -26,10 +26,10 @@ struct EmojiData {
std::vector<EmojiData> variations; std::vector<EmojiData> variations;
util::EmoteData emoteData; EmoteData emoteData;
}; };
using EmojiMap = util::ConcurrentMap<QString, std::shared_ptr<EmojiData>>; using EmojiMap = ConcurrentMap<QString, std::shared_ptr<EmojiData>>;
class Emojis class Emojis
{ {
@ -51,7 +51,7 @@ private:
public: public:
QString replaceShortCodes(const QString &text); QString replaceShortCodes(const QString &text);
void parse(std::vector<std::tuple<util::EmoteData, QString>> &parsedWords, const QString &text); void parse(std::vector<std::tuple<EmoteData, QString>> &parsedWords, const QString &text);
private: private:
/// Emojis /// Emojis

View file

@ -21,7 +21,7 @@ QString getEmoteLink(const QJsonObject &urls, const QString &emoteScale)
} }
void fillInEmoteData(const QJsonObject &urls, const QString &code, const QString &tooltip, void fillInEmoteData(const QJsonObject &urls, const QString &code, const QString &tooltip,
util::EmoteData &emoteData) EmoteData &emoteData)
{ {
QString url1x = getEmoteLink(urls, "1"); QString url1x = getEmoteLink(urls, "1");
QString url2x = getEmoteLink(urls, "2"); QString url2x = getEmoteLink(urls, "2");
@ -29,14 +29,14 @@ void fillInEmoteData(const QJsonObject &urls, const QString &code, const QString
assert(!url1x.isEmpty()); assert(!url1x.isEmpty());
emoteData.image1x = new messages::Image(url1x, 1, code, tooltip); emoteData.image1x = new chatterino::Image(url1x, 1, code, tooltip);
if (!url2x.isEmpty()) { if (!url2x.isEmpty()) {
emoteData.image2x = new messages::Image(url2x, 0.5, code, tooltip); emoteData.image2x = new chatterino::Image(url2x, 0.5, code, tooltip);
} }
if (!url3x.isEmpty()) { if (!url3x.isEmpty()) {
emoteData.image3x = new messages::Image(url3x, 0.25, code, tooltip); emoteData.image3x = new chatterino::Image(url3x, 0.25, code, tooltip);
} }
} }
@ -46,7 +46,7 @@ void FFZEmotes::loadGlobalEmotes()
{ {
QString url("https://api.frankerfacez.com/v1/set/global"); QString url("https://api.frankerfacez.com/v1/set/global");
util::NetworkRequest req(url); NetworkRequest req(url);
req.setCaller(QThread::currentThread()); req.setCaller(QThread::currentThread());
req.setTimeout(30000); req.setTimeout(30000);
req.setUseQuickLoadCache(true); req.setUseQuickLoadCache(true);
@ -64,7 +64,7 @@ void FFZEmotes::loadGlobalEmotes()
int id = object.value("id").toInt(); int id = object.value("id").toInt();
QJsonObject urls = object.value("urls").toObject(); QJsonObject urls = object.value("urls").toObject();
util::EmoteData emoteData; EmoteData emoteData;
fillInEmoteData(urls, code, code + "<br/>Global FFZ Emote", emoteData); fillInEmoteData(urls, code, code + "<br/>Global FFZ Emote", emoteData);
emoteData.pageLink = emoteData.pageLink =
QString("https://www.frankerfacez.com/emoticon/%1-%2").arg(id).arg(code); QString("https://www.frankerfacez.com/emoticon/%1-%2").arg(id).arg(code);
@ -78,13 +78,13 @@ void FFZEmotes::loadGlobalEmotes()
}); });
} }
void FFZEmotes::loadChannelEmotes(const QString &channelName, std::weak_ptr<util::EmoteMap> _map) void FFZEmotes::loadChannelEmotes(const QString &channelName, std::weak_ptr<EmoteMap> _map)
{ {
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); QString url("https://api.frankerfacez.com/v1/room/" + channelName);
util::NetworkRequest req(url); NetworkRequest req(url);
req.setCaller(QThread::currentThread()); req.setCaller(QThread::currentThread());
req.setTimeout(3000); req.setTimeout(3000);
req.setUseQuickLoadCache(true); req.setUseQuickLoadCache(true);
@ -113,7 +113,7 @@ void FFZEmotes::loadChannelEmotes(const QString &channelName, std::weak_ptr<util
QJsonObject urls = emoteObject.value("urls").toObject(); QJsonObject urls = emoteObject.value("urls").toObject();
auto emote = this->channelEmoteCache.getOrAdd(id, [id, &code, &urls] { auto emote = this->channelEmoteCache.getOrAdd(id, [id, &code, &urls] {
util::EmoteData emoteData; EmoteData emoteData;
fillInEmoteData(urls, code, code + "<br/>Channel FFZ Emote", emoteData); fillInEmoteData(urls, code, code + "<br/>Channel FFZ Emote", emoteData);
emoteData.pageLink = emoteData.pageLink =
QString("https://www.frankerfacez.com/emoticon/%1-%2").arg(id).arg(code); QString("https://www.frankerfacez.com/emoticon/%1-%2").arg(id).arg(code);

View file

@ -11,18 +11,18 @@ namespace chatterino {
class FFZEmotes class FFZEmotes
{ {
public: public:
util::EmoteMap globalEmotes; EmoteMap globalEmotes;
SignalVector<QString> globalEmoteCodes; SignalVector<QString> globalEmoteCodes;
util::EmoteMap channelEmotes; EmoteMap channelEmotes;
std::map<QString, SignalVector<QString>> channelEmoteCodes; std::map<QString, SignalVector<QString>> channelEmoteCodes;
void loadGlobalEmotes(); void loadGlobalEmotes();
void loadChannelEmotes(const QString &channelName, void loadChannelEmotes(const QString &channelName,
std::weak_ptr<util::EmoteMap> channelEmoteMap); std::weak_ptr<EmoteMap> channelEmoteMap);
private: private:
util::ConcurrentMap<int, util::EmoteData> channelEmoteCache; ConcurrentMap<int, EmoteData> channelEmoteCache;
}; };
} // namespace chatterino } // namespace chatterino

View file

@ -126,7 +126,7 @@ std::shared_ptr<Channel> AbstractIrcServer::getOrAddChannel(const QString &dirty
chan->destroyed.connect([this, clojuresInCppAreShit] { chan->destroyed.connect([this, clojuresInCppAreShit] {
// fourtf: issues when the server itself is destroyed // fourtf: issues when the server itself is destroyed
debug::Log("[AbstractIrcServer::addChannel] {} was destroyed", clojuresInCppAreShit); Log("[AbstractIrcServer::addChannel] {} was destroyed", clojuresInCppAreShit);
this->channels.remove(clojuresInCppAreShit); this->channels.remove(clojuresInCppAreShit);
if (this->readConnection_) { if (this->readConnection_) {

View file

@ -46,7 +46,7 @@ void IrcMessageHandler::addMessage(Communi::IrcMessage *_message, const QString
return; return;
} }
messages::MessageParseArgs args; chatterino::MessageParseArgs args;
if (isSub) { if (isSub) {
args.trimSubscriberUsername = true; args.trimSubscriberUsername = true;
} }
@ -58,13 +58,13 @@ void IrcMessageHandler::addMessage(Communi::IrcMessage *_message, const QString
TwitchMessageBuilder builder(chan.get(), _message, args, content, isAction); TwitchMessageBuilder builder(chan.get(), _message, args, content, isAction);
if (isSub || !builder.isIgnored()) { if (isSub || !builder.isIgnored()) {
messages::MessagePtr msg = builder.build(); chatterino::MessagePtr msg = builder.build();
if (isSub) { if (isSub) {
msg->flags |= messages::Message::Subscription; msg->flags |= chatterino::Message::Subscription;
msg->flags &= ~messages::Message::Highlighted; msg->flags &= ~chatterino::Message::Highlighted;
} else { } else {
if (msg->flags & messages::Message::Highlighted) { if (msg->flags & chatterino::Message::Highlighted) {
server.mentionsChannel->addMessage(msg); server.mentionsChannel->addMessage(msg);
getApp()->highlights->addHighlight(msg); getApp()->highlights->addHighlight(msg);
} }
@ -85,7 +85,7 @@ void IrcMessageHandler::handleRoomStateMessage(Communi::IrcMessage *message)
return; return;
} }
auto chan = app->twitch.server->getChannelOrEmpty(chanName); auto chan = app->twitch.server->getChannelOrEmpty(chanName);
TwitchChannel *twitchChannel = dynamic_cast<twitch::TwitchChannel *>(chan.get()); TwitchChannel *twitchChannel = dynamic_cast<TwitchChannel *>(chan.get());
if (twitchChannel) { if (twitchChannel) {
// room-id // room-id
@ -140,7 +140,7 @@ void IrcMessageHandler::handleClearChatMessage(Communi::IrcMessage *message)
auto chan = app->twitch.server->getChannelOrEmpty(chanName); auto chan = app->twitch.server->getChannelOrEmpty(chanName);
if (chan->isEmpty()) { if (chan->isEmpty()) {
debug::Log("[IrcMessageHandler:handleClearChatMessage] Twitch channel {} not found", Log("[IrcMessageHandler:handleClearChatMessage] Twitch channel {} not found",
chanName); chanName);
return; return;
} }
@ -190,7 +190,7 @@ void IrcMessageHandler::handleUserStateMessage(Communi::IrcMessage *message)
return; return;
} }
twitch::TwitchChannel *tc = dynamic_cast<twitch::TwitchChannel *>(c.get()); TwitchChannel *tc = dynamic_cast<TwitchChannel *>(c.get());
if (tc != nullptr) { if (tc != nullptr) {
tc->setMod(_mod == "1"); tc->setMod(_mod == "1");
} }
@ -200,20 +200,20 @@ void IrcMessageHandler::handleUserStateMessage(Communi::IrcMessage *message)
void IrcMessageHandler::handleWhisperMessage(Communi::IrcMessage *message) void IrcMessageHandler::handleWhisperMessage(Communi::IrcMessage *message)
{ {
auto app = getApp(); auto app = getApp();
debug::Log("Received whisper!"); Log("Received whisper!");
messages::MessageParseArgs args; chatterino::MessageParseArgs args;
args.isReceivedWhisper = true; args.isReceivedWhisper = true;
auto c = app->twitch.server->whispersChannel.get(); auto c = app->twitch.server->whispersChannel.get();
twitch::TwitchMessageBuilder builder(c, message, args, message->parameter(1), false); TwitchMessageBuilder builder(c, message, args, message->parameter(1), false);
if (!builder.isIgnored()) { if (!builder.isIgnored()) {
messages::MessagePtr _message = builder.build(); chatterino::MessagePtr _message = builder.build();
_message->flags |= messages::Message::DoNotTriggerNotification; _message->flags |= chatterino::Message::DoNotTriggerNotification;
if (_message->flags & messages::Message::Highlighted) { if (_message->flags & chatterino::Message::Highlighted) {
app->twitch.server->mentionsChannel->addMessage(_message); app->twitch.server->mentionsChannel->addMessage(_message);
} }
@ -254,9 +254,9 @@ void IrcMessageHandler::handleUserNoticeMessage(Communi::IrcMessage *message, Tw
if (it != tags.end()) { if (it != tags.end()) {
auto newMessage = auto newMessage =
messages::Message::createSystemMessage(util::parseTagString(it.value().toString())); chatterino::Message::createSystemMessage(parseTagString(it.value().toString()));
newMessage->flags |= messages::Message::Subscription; newMessage->flags |= chatterino::Message::Subscription;
QString channelName; QString channelName;
@ -311,7 +311,7 @@ void IrcMessageHandler::handleNoticeMessage(Communi::IrcNoticeMessage *message)
auto channel = app->twitch.server->getChannelOrEmpty(channelName); auto channel = app->twitch.server->getChannelOrEmpty(channelName);
if (channel->isEmpty()) { if (channel->isEmpty()) {
debug::Log("[IrcManager:handleNoticeMessage] Channel {} not found in channel manager ", Log("[IrcManager:handleNoticeMessage] Channel {} not found in channel manager ",
channelName); channelName);
return; return;
} }
@ -338,7 +338,7 @@ void IrcMessageHandler::handleWriteConnectionNoticeMessage(Communi::IrcNoticeMes
return; return;
} }
debug::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); this->handleNoticeMessage(message);

View file

@ -107,7 +107,7 @@ void PubSubClient::handlePong()
{ {
assert(this->awaitingPong); assert(this->awaitingPong);
debug::Log("Got pong!"); Log("Got pong!");
this->awaitingPong = false; this->awaitingPong = false;
} }
@ -141,7 +141,7 @@ void PubSubClient::ping()
} }
if (self->awaitingPong) { if (self->awaitingPong) {
debug::Log("No pong respnose, disconnect!"); Log("No pong respnose, disconnect!");
// TODO(pajlada): Label this connection as "disconnect me" // TODO(pajlada): Label this connection as "disconnect me"
} }
}); });
@ -161,7 +161,7 @@ bool PubSubClient::send(const char *payload)
this->websocketClient.send(this->handle, payload, websocketpp::frame::opcode::text, ec); this->websocketClient.send(this->handle, payload, websocketpp::frame::opcode::text, ec);
if (ec) { if (ec) {
debug::Log("Error sending message {}: {}", payload, ec.message()); 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; return false;
@ -198,26 +198,26 @@ PubSub::PubSub()
action.state = ModeChangedAction::State::On; action.state = ModeChangedAction::State::On;
if (!data.HasMember("args")) { if (!data.HasMember("args")) {
debug::Log("Missing required args member"); Log("Missing required args member");
return; return;
} }
const auto &args = data["args"]; const auto &args = data["args"];
if (!args.IsArray()) { if (!args.IsArray()) {
debug::Log("args member must be an array"); Log("args member must be an array");
return; return;
} }
if (args.Size() == 0) { if (args.Size() == 0) {
debug::Log("Missing duration argument in slowmode on"); Log("Missing duration argument in slowmode on");
return; return;
} }
const auto &durationArg = args[0]; const auto &durationArg = args[0];
if (!durationArg.IsString()) { if (!durationArg.IsString()) {
debug::Log("Duration arg must be a string"); Log("Duration arg must be a string");
return; return;
} }
@ -299,7 +299,7 @@ PubSub::PubSub()
return; return;
} }
} catch (const std::runtime_error &ex) { } catch (const std::runtime_error &ex) {
debug::Log("Error parsing moderation action: {}", ex.what()); Log("Error parsing moderation action: {}", ex.what());
} }
action.modded = false; action.modded = false;
@ -323,7 +323,7 @@ PubSub::PubSub()
return; return;
} }
} catch (const std::runtime_error &ex) { } catch (const std::runtime_error &ex) {
debug::Log("Error parsing moderation action: {}", ex.what()); Log("Error parsing moderation action: {}", ex.what());
} }
action.modded = true; action.modded = true;
@ -363,7 +363,7 @@ PubSub::PubSub()
this->sig.moderation.userBanned.invoke(action); this->sig.moderation.userBanned.invoke(action);
} catch (const std::runtime_error &ex) { } catch (const std::runtime_error &ex) {
debug::Log("Error parsing moderation action: {}", ex.what()); Log("Error parsing moderation action: {}", ex.what());
} }
}; };
@ -392,7 +392,7 @@ PubSub::PubSub()
this->sig.moderation.userBanned.invoke(action); this->sig.moderation.userBanned.invoke(action);
} catch (const std::runtime_error &ex) { } catch (const std::runtime_error &ex) {
debug::Log("Error parsing moderation action: {}", ex.what()); Log("Error parsing moderation action: {}", ex.what());
} }
}; };
@ -417,7 +417,7 @@ PubSub::PubSub()
this->sig.moderation.userUnbanned.invoke(action); this->sig.moderation.userUnbanned.invoke(action);
} catch (const std::runtime_error &ex) { } catch (const std::runtime_error &ex) {
debug::Log("Error parsing moderation action: {}", ex.what()); Log("Error parsing moderation action: {}", ex.what());
} }
}; };
@ -442,7 +442,7 @@ PubSub::PubSub()
this->sig.moderation.userUnbanned.invoke(action); this->sig.moderation.userUnbanned.invoke(action);
} catch (const std::runtime_error &ex) { } catch (const std::runtime_error &ex) {
debug::Log("Error parsing moderation action: {}", ex.what()); Log("Error parsing moderation action: {}", ex.what());
} }
}; };
@ -468,7 +468,7 @@ void PubSub::addClient()
auto con = this->websocketClient.get_connection(TWITCH_PUBSUB_URL, ec); auto con = this->websocketClient.get_connection(TWITCH_PUBSUB_URL, ec);
if (ec) { if (ec) {
debug::Log("Unable to establish connection: {}", ec.message()); Log("Unable to establish connection: {}", ec.message());
return; return;
} }
@ -480,13 +480,13 @@ 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<providers::twitch::TwitchAccount> account) void PubSub::listenToWhispers(std::shared_ptr<TwitchAccount> account)
{ {
assert(account != nullptr); assert(account != nullptr);
std::string userID = account->getUserId().toStdString(); std::string userID = account->getUserId().toStdString();
debug::Log("Connection open!"); Log("Connection open!");
websocketpp::lib::error_code ec; websocketpp::lib::error_code ec;
std::vector<std::string> topics({"whispers." + userID}); std::vector<std::string> topics({"whispers." + userID});
@ -494,7 +494,7 @@ void PubSub::listenToWhispers(std::shared_ptr<providers::twitch::TwitchAccount>
this->listen(std::move(createListenMessage(topics, account))); this->listen(std::move(createListenMessage(topics, account)));
if (ec) { if (ec) {
debug::Log("Unable to send message to websocket server: {}", ec.message()); Log("Unable to send message to websocket server: {}", ec.message());
return; return;
} }
} }
@ -508,7 +508,7 @@ void PubSub::unlistenAllModerationActions()
} }
void PubSub::listenToChannelModerationActions( void PubSub::listenToChannelModerationActions(
const QString &channelID, std::shared_ptr<providers::twitch::TwitchAccount> account) const QString &channelID, std::shared_ptr<TwitchAccount> account)
{ {
assert(!channelID.isEmpty()); assert(!channelID.isEmpty());
assert(account != nullptr); assert(account != nullptr);
@ -518,17 +518,17 @@ void PubSub::listenToChannelModerationActions(
std::string topic(fS("chat_moderator_actions.{}.{}", userID, channelID)); std::string topic(fS("chat_moderator_actions.{}.{}", userID, channelID));
if (this->isListeningToTopic(topic)) { if (this->isListeningToTopic(topic)) {
debug::Log("We are already listening to topic {}", topic); Log("We are already listening to topic {}", topic);
return; return;
} }
debug::Log("Listen to topic {}", topic); Log("Listen to topic {}", topic);
this->listenToTopic(topic, account); this->listenToTopic(topic, account);
} }
void PubSub::listenToTopic(const std::string &topic, void PubSub::listenToTopic(const std::string &topic,
std::shared_ptr<providers::twitch::TwitchAccount> account) std::shared_ptr<TwitchAccount> account)
{ {
auto message = createListenMessage({topic}, account); auto message = createListenMessage({topic}, account);
@ -538,17 +538,17 @@ void PubSub::listenToTopic(const std::string &topic,
void PubSub::listen(rapidjson::Document &&msg) void PubSub::listen(rapidjson::Document &&msg)
{ {
if (this->tryListen(msg)) { if (this->tryListen(msg)) {
debug::Log("Successfully listened!"); Log("Successfully listened!");
return; return;
} }
debug::Log("Added to the back of the queue"); Log("Added to the back of the queue");
this->requests.emplace_back(std::make_unique<rapidjson::Document>(std::move(msg))); this->requests.emplace_back(std::make_unique<rapidjson::Document>(std::move(msg)));
} }
bool PubSub::tryListen(rapidjson::Document &msg) bool PubSub::tryListen(rapidjson::Document &msg)
{ {
debug::Log("tryListen with {} clients", this->clients.size()); Log("tryListen with {} clients", this->clients.size());
for (const auto &p : this->clients) { for (const auto &p : this->clients) {
const auto &client = p.second; const auto &client = p.second;
if (client->listen(msg)) { if (client->listen(msg)) {
@ -580,20 +580,20 @@ void PubSub::onMessage(websocketpp::connection_hdl hdl, WebsocketMessagePtr webs
rapidjson::ParseResult res = msg.Parse(payload.c_str()); rapidjson::ParseResult res = msg.Parse(payload.c_str());
if (!res) { if (!res) {
debug::Log("Error parsing message '{}' from PubSub: {}", payload, Log("Error parsing message '{}' from PubSub: {}", payload,
rapidjson::GetParseError_En(res.Code())); rapidjson::GetParseError_En(res.Code()));
return; return;
} }
if (!msg.IsObject()) { if (!msg.IsObject()) {
debug::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; return;
} }
std::string type; std::string type;
if (!rj::getSafe(msg, "type", type)) { if (!rj::getSafe(msg, "type", type)) {
debug::Log("Missing required string member `type` in message root"); Log("Missing required string member `type` in message root");
return; return;
} }
@ -601,14 +601,14 @@ void PubSub::onMessage(websocketpp::connection_hdl hdl, WebsocketMessagePtr webs
this->handleListenResponse(msg); this->handleListenResponse(msg);
} else if (type == "MESSAGE") { } else if (type == "MESSAGE") {
if (!msg.HasMember("data")) { if (!msg.HasMember("data")) {
debug::Log("Missing required object member `data` in message root"); Log("Missing required object member `data` in message root");
return; return;
} }
const auto &data = msg["data"]; const auto &data = msg["data"];
if (!data.IsObject()) { if (!data.IsObject()) {
debug::Log("Member `data` must be an object"); Log("Member `data` must be an object");
return; return;
} }
@ -624,7 +624,7 @@ void PubSub::onMessage(websocketpp::connection_hdl hdl, WebsocketMessagePtr webs
client.second->handlePong(); client.second->handlePong();
} else { } else {
debug::Log("Unknown message type: {}", type); Log("Unknown message type: {}", type);
} }
} }
@ -666,7 +666,7 @@ PubSub::WebsocketContextPtr PubSub::onTLSInit(websocketpp::connection_hdl hdl)
boost::asio::ssl::context::no_sslv2 | boost::asio::ssl::context::no_sslv2 |
boost::asio::ssl::context::single_dh_use); boost::asio::ssl::context::single_dh_use);
} catch (const std::exception &e) { } catch (const std::exception &e) {
debug::Log("Exception caught in OnTLSInit: {}", e.what()); Log("Exception caught in OnTLSInit: {}", e.what());
} }
return ctx; return ctx;
@ -681,12 +681,12 @@ void PubSub::handleListenResponse(const rapidjson::Document &msg)
rj::getSafe(msg, "nonce", nonce); rj::getSafe(msg, "nonce", nonce);
if (error.empty()) { if (error.empty()) {
debug::Log("Successfully listened to nonce {}", nonce); Log("Successfully listened to nonce {}", nonce);
// Nothing went wrong // Nothing went wrong
return; return;
} }
debug::Log("PubSub error: {} on nonce {}", error, nonce); Log("PubSub error: {} on nonce {}", error, nonce);
return; return;
} }
} }
@ -696,14 +696,14 @@ void PubSub::handleMessageResponse(const rapidjson::Value &outerData)
QString topic; QString topic;
if (!rj::getSafe(outerData, "topic", topic)) { if (!rj::getSafe(outerData, "topic", topic)) {
debug::Log("Missing required string member `topic` in outerData"); Log("Missing required string member `topic` in outerData");
return; return;
} }
std::string payload; std::string payload;
if (!rj::getSafe(outerData, "message", payload)) { if (!rj::getSafe(outerData, "message", payload)) {
debug::Log("Expected string message in outerData"); Log("Expected string message in outerData");
return; return;
} }
@ -712,7 +712,7 @@ void PubSub::handleMessageResponse(const rapidjson::Value &outerData)
rapidjson::ParseResult res = msg.Parse(payload.c_str()); rapidjson::ParseResult res = msg.Parse(payload.c_str());
if (!res) { if (!res) {
debug::Log("Error parsing message '{}' from PubSub: {}", payload, Log("Error parsing message '{}' from PubSub: {}", payload,
rapidjson::GetParseError_En(res.Code())); rapidjson::GetParseError_En(res.Code()));
return; return;
} }
@ -721,7 +721,7 @@ void PubSub::handleMessageResponse(const rapidjson::Value &outerData)
std::string whisperType; std::string whisperType;
if (!rj::getSafe(msg, "type", whisperType)) { if (!rj::getSafe(msg, "type", whisperType)) {
debug::Log("Bad whisper data"); Log("Bad whisper data");
return; return;
} }
@ -732,7 +732,7 @@ void PubSub::handleMessageResponse(const rapidjson::Value &outerData)
} else if (whisperType == "thread") { } else if (whisperType == "thread") {
// Handle thread? // Handle thread?
} else { } else {
debug::Log("Invalid whisper type: {}", whisperType); Log("Invalid whisper type: {}", whisperType);
assert(false); assert(false);
return; return;
} }
@ -744,30 +744,30 @@ void PubSub::handleMessageResponse(const rapidjson::Value &outerData)
std::string moderationAction; std::string moderationAction;
if (!rj::getSafe(data, "moderation_action", moderationAction)) { if (!rj::getSafe(data, "moderation_action", moderationAction)) {
debug::Log("Missing moderation action in data: {}", rj::stringify(data)); Log("Missing moderation action in data: {}", rj::stringify(data));
return; return;
} }
auto handlerIt = this->moderationActionHandlers.find(moderationAction); auto handlerIt = this->moderationActionHandlers.find(moderationAction);
if (handlerIt == this->moderationActionHandlers.end()) { if (handlerIt == this->moderationActionHandlers.end()) {
debug::Log("No handler found for moderation action {}", moderationAction); Log("No handler found for moderation action {}", moderationAction);
return; return;
} }
// Invoke handler function // Invoke handler function
handlerIt->second(data, topicParts[2]); handlerIt->second(data, topicParts[2]);
} else { } else {
debug::Log("Unknown topic: {}", topic); Log("Unknown topic: {}", topic);
return; return;
} }
} }
void PubSub::runThread() void PubSub::runThread()
{ {
debug::Log("Start pubsub manager thread"); Log("Start pubsub manager thread");
this->websocketClient.run(); this->websocketClient.run();
debug::Log("Done with pubsub manager thread"); Log("Done with pubsub manager thread");
} }
} // namespace chatterino } // namespace chatterino

View file

@ -117,18 +117,18 @@ public:
} whisper; } whisper;
} sig; } sig;
void listenToWhispers(std::shared_ptr<providers::twitch::TwitchAccount> account); void listenToWhispers(std::shared_ptr<TwitchAccount> account);
void unlistenAllModerationActions(); void unlistenAllModerationActions();
void listenToChannelModerationActions( void listenToChannelModerationActions(
const QString &channelID, std::shared_ptr<providers::twitch::TwitchAccount> account); const QString &channelID, std::shared_ptr<TwitchAccount> account);
std::vector<std::unique_ptr<rapidjson::Document>> requests; std::vector<std::unique_ptr<rapidjson::Document>> requests;
private: private:
void listenToTopic(const std::string &topic, void listenToTopic(const std::string &topic,
std::shared_ptr<providers::twitch::TwitchAccount> account); std::shared_ptr<TwitchAccount> account);
void listen(rapidjson::Document &&msg); void listen(rapidjson::Document &&msg);
bool tryListen(rapidjson::Document &msg); bool tryListen(rapidjson::Document &msg);

View file

@ -32,7 +32,7 @@ bool getTargetUser(const rapidjson::Value &data, ActionUser &user)
} }
rapidjson::Document createListenMessage(const std::vector<std::string> &topicsVec, rapidjson::Document createListenMessage(const std::vector<std::string> &topicsVec,
std::shared_ptr<providers::twitch::TwitchAccount> account) std::shared_ptr<TwitchAccount> account)
{ {
rapidjson::Document msg(rapidjson::kObjectType); rapidjson::Document msg(rapidjson::kObjectType);
auto &a = msg.GetAllocator(); auto &a = msg.GetAllocator();

View file

@ -20,7 +20,7 @@ bool getCreatedByUser(const rapidjson::Value &data, ActionUser &user);
bool getTargetUser(const rapidjson::Value &data, ActionUser &user); bool getTargetUser(const rapidjson::Value &data, ActionUser &user);
rapidjson::Document createListenMessage(const std::vector<std::string> &topicsVec, rapidjson::Document createListenMessage(const std::vector<std::string> &topicsVec,
std::shared_ptr<providers::twitch::TwitchAccount> account); std::shared_ptr<TwitchAccount> account);
rapidjson::Document createUnlistenMessage(const std::vector<std::string> &topicsVec); rapidjson::Document createUnlistenMessage(const std::vector<std::string> &topicsVec);
// Create timer using given ioService // Create timer using given ioService
@ -32,7 +32,7 @@ void runAfter(boost::asio::io_service &ioService, Duration duration, Callback cb
timer->async_wait([timer, cb](const boost::system::error_code &ec) { timer->async_wait([timer, cb](const boost::system::error_code &ec) {
if (ec) { if (ec) {
debug::Log("Error in runAfter: {}", ec.message()); Log("Error in runAfter: {}", ec.message());
return; return;
} }
@ -48,7 +48,7 @@ void runAfter(std::shared_ptr<boost::asio::steady_timer> timer, Duration duratio
timer->async_wait([timer, cb](const boost::system::error_code &ec) { timer->async_wait([timer, cb](const boost::system::error_code &ec) {
if (ec) { if (ec) {
debug::Log("Error in runAfter: {}", ec.message()); Log("Error in runAfter: {}", ec.message());
return; return;
} }

View file

@ -10,7 +10,7 @@ namespace chatterino {
TwitchAccount::TwitchAccount(const QString &_username, const QString &_oauthToken, TwitchAccount::TwitchAccount(const QString &_username, const QString &_oauthToken,
const QString &_oauthClient, const QString &_userID) const QString &_oauthClient, const QString &_userID)
: controllers::accounts::Account(ProviderId::Twitch) : Account(ProviderId::Twitch)
, oauthClient(_oauthClient) , oauthClient(_oauthClient)
, oauthToken(_oauthToken) , oauthToken(_oauthToken)
, userName(_username) , userName(_username)
@ -75,8 +75,8 @@ 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");
util::NetworkRequest req(url); NetworkRequest req(url);
req.setRequestType(util::NetworkRequest::GetRequest); req.setRequestType(NetworkRequest::GetRequest);
req.setCaller(QThread::currentThread()); req.setCaller(QThread::currentThread());
req.makeAuthorizedV5(this->getOAuthClient(), this->getOAuthToken()); req.makeAuthorizedV5(this->getOAuthClient(), this->getOAuthToken());
req.onSuccess([=](const rapidjson::Document &document) { req.onSuccess([=](const rapidjson::Document &document) {
@ -119,7 +119,7 @@ void TwitchAccount::loadIgnores()
void TwitchAccount::ignore(const QString &targetName, void TwitchAccount::ignore(const QString &targetName,
std::function<void(IgnoreResult, const QString &)> onFinished) std::function<void(IgnoreResult, const QString &)> onFinished)
{ {
util::twitch::getUserID(targetName, QThread::currentThread(), [=](QString targetUserID) { getUserID(targetName, QThread::currentThread(), [=](QString targetUserID) {
this->ignoreByID(targetUserID, targetName, onFinished); // this->ignoreByID(targetUserID, targetName, onFinished); //
}); });
} }
@ -130,8 +130,8 @@ void TwitchAccount::ignoreByID(const QString &targetUserID, const QString &targe
QString url("https://api.twitch.tv/kraken/users/" + this->getUserId() + "/blocks/" + QString url("https://api.twitch.tv/kraken/users/" + this->getUserId() + "/blocks/" +
targetUserID); targetUserID);
util::NetworkRequest req(url); NetworkRequest req(url);
req.setRequestType(util::NetworkRequest::PutRequest); req.setRequestType(NetworkRequest::PutRequest);
req.setCaller(QThread::currentThread()); req.setCaller(QThread::currentThread());
req.makeAuthorizedV5(this->getOAuthClient(), this->getOAuthToken()); req.makeAuthorizedV5(this->getOAuthClient(), this->getOAuthToken());
@ -179,7 +179,7 @@ void TwitchAccount::ignoreByID(const QString &targetUserID, const QString &targe
void TwitchAccount::unignore(const QString &targetName, void TwitchAccount::unignore(const QString &targetName,
std::function<void(UnignoreResult, const QString &message)> onFinished) std::function<void(UnignoreResult, const QString &message)> onFinished)
{ {
util::twitch::getUserID(targetName, QThread::currentThread(), [=](QString targetUserID) { getUserID(targetName, QThread::currentThread(), [=](QString targetUserID) {
this->unignoreByID(targetUserID, targetName, onFinished); // this->unignoreByID(targetUserID, targetName, onFinished); //
}); });
} }
@ -191,8 +191,8 @@ void TwitchAccount::unignoreByID(
QString url("https://api.twitch.tv/kraken/users/" + this->getUserId() + "/blocks/" + QString url("https://api.twitch.tv/kraken/users/" + this->getUserId() + "/blocks/" +
targetUserID); targetUserID);
util::NetworkRequest req(url); NetworkRequest req(url);
req.setRequestType(util::NetworkRequest::DeleteRequest); req.setRequestType(NetworkRequest::DeleteRequest);
req.setCaller(QThread::currentThread()); req.setCaller(QThread::currentThread());
req.makeAuthorizedV5(this->getOAuthClient(), this->getOAuthToken()); req.makeAuthorizedV5(this->getOAuthClient(), this->getOAuthToken());
@ -226,8 +226,8 @@ void TwitchAccount::checkFollow(const QString targetUserID,
QString url("https://api.twitch.tv/kraken/users/" + this->getUserId() + "/follows/channels/" + QString url("https://api.twitch.tv/kraken/users/" + this->getUserId() + "/follows/channels/" +
targetUserID); targetUserID);
util::NetworkRequest req(url); NetworkRequest req(url);
req.setRequestType(util::NetworkRequest::GetRequest); req.setRequestType(NetworkRequest::GetRequest);
req.setCaller(QThread::currentThread()); req.setCaller(QThread::currentThread());
req.makeAuthorizedV5(this->getOAuthClient(), this->getOAuthToken()); req.makeAuthorizedV5(this->getOAuthClient(), this->getOAuthToken());

View file

@ -27,7 +27,7 @@ enum FollowResult {
FollowResult_Failed, FollowResult_Failed,
}; };
class TwitchAccount : public controllers::accounts::Account class TwitchAccount : public Account
{ {
public: public:
TwitchAccount(const QString &username, const QString &oauthToken, const QString &oauthClient, TwitchAccount(const QString &username, const QString &oauthToken, const QString &oauthClient,

View file

@ -92,18 +92,18 @@ void TwitchAccountManager::reloadUsers()
switch (this->addUser(userData)) { switch (this->addUser(userData)) {
case AddUserResponse::UserAlreadyExists: { case AddUserResponse::UserAlreadyExists: {
debug::Log("User {} already exists", userData.username); Log("User {} already exists", userData.username);
// Do nothing // Do nothing
} break; } break;
case AddUserResponse::UserValuesUpdated: { case AddUserResponse::UserValuesUpdated: {
debug::Log("User {} already exists, and values updated!", userData.username); Log("User {} already exists, and values updated!", userData.username);
if (userData.username == this->getCurrent()->getUserName()) { if (userData.username == this->getCurrent()->getUserName()) {
debug::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(); this->currentUserChanged.invoke();
} }
} break; } break;
case AddUserResponse::UserAdded: { case AddUserResponse::UserAdded: {
debug::Log("Added user {}", userData.username); Log("Added user {}", userData.username);
listUpdated = true; listUpdated = true;
} break; } break;
} }
@ -122,11 +122,11 @@ void TwitchAccountManager::load()
QString newUsername(QString::fromStdString(newValue)); QString newUsername(QString::fromStdString(newValue));
auto user = this->findUserByUsername(newUsername); auto user = this->findUserByUsername(newUsername);
if (user) { if (user) {
debug::Log("[AccountManager:currentUsernameChanged] User successfully updated to {}", Log("[AccountManager:currentUsernameChanged] User successfully updated to {}",
newUsername); newUsername);
this->currentUser = user; this->currentUser = user;
} else { } else {
debug::Log( Log(
"[AccountManager:currentUsernameChanged] User successfully updated to anonymous"); "[AccountManager:currentUsernameChanged] User successfully updated to anonymous");
this->currentUser = this->anonymousUser; this->currentUser = this->anonymousUser;
} }

View file

@ -1,8 +1,8 @@
#pragma once #pragma once
#include "common/SignalVector2.hpp"
#include "providers/twitch/TwitchAccount.hpp" #include "providers/twitch/TwitchAccount.hpp"
#include "util/SharedPtrElementLess.hpp" #include "util/SharedPtrElementLess.hpp"
#include "common/SignalVector2.hpp"
#include <pajlada/settings/setting.hpp> #include <pajlada/settings/setting.hpp>
@ -15,8 +15,8 @@
// //
namespace chatterino { namespace chatterino {
class AccountController; class AccountController;
}
class TwitchAccountManager class TwitchAccountManager
{ {
@ -47,8 +47,7 @@ public:
pajlada::Signals::NoArgSignal currentUserChanged; pajlada::Signals::NoArgSignal currentUserChanged;
pajlada::Signals::NoArgSignal userListUpdated; pajlada::Signals::NoArgSignal userListUpdated;
util::SortedSignalVector<std::shared_ptr<TwitchAccount>, SortedSignalVector<std::shared_ptr<TwitchAccount>, SharedPtrElementLess<TwitchAccount>>
util::SharedPtrElementLess<TwitchAccount>>
accounts; accounts;
private: private:
@ -65,7 +64,7 @@ private:
std::shared_ptr<TwitchAccount> anonymousUser; std::shared_ptr<TwitchAccount> anonymousUser;
mutable std::mutex mutex; mutable std::mutex mutex;
friend class chatterino::controllers::accounts::AccountController; friend class chatterino::AccountController;
}; };
} // namespace chatterino } // namespace chatterino

View file

@ -19,15 +19,15 @@ namespace chatterino {
TwitchChannel::TwitchChannel(const QString &channelName, Communi::IrcConnection *_readConnection) TwitchChannel::TwitchChannel(const QString &channelName, Communi::IrcConnection *_readConnection)
: Channel(channelName, Channel::Twitch) : Channel(channelName, Channel::Twitch)
, bttvChannelEmotes(new util::EmoteMap) , bttvChannelEmotes(new EmoteMap)
, ffzChannelEmotes(new util::EmoteMap) , ffzChannelEmotes(new EmoteMap)
, subscriptionURL("https://www.twitch.tv/subs/" + name) , subscriptionURL("https://www.twitch.tv/subs/" + name)
, channelURL("https://twitch.tv/" + name) , channelURL("https://twitch.tv/" + name)
, popoutPlayerURL("https://player.twitch.tv/?channel=" + name) , popoutPlayerURL("https://player.twitch.tv/?channel=" + name)
, mod(false) , mod(false)
, readConnection(_readConnection) , readConnection(_readConnection)
{ {
debug::Log("[TwitchChannel:{}] Opened", this->name); Log("[TwitchChannel:{}] Opened", this->name);
this->startRefreshLiveStatusTimer(60 * 1000); this->startRefreshLiveStatusTimer(60 * 1000);
@ -83,7 +83,7 @@ TwitchChannel::TwitchChannel(const QString &channelName, Communi::IrcConnection
} }
} }
util::twitch::get("https://tmi.twitch.tv/group/user/" + this->name + "/chatters", get("https://tmi.twitch.tv/group/user/" + this->name + "/chatters",
QThread::currentThread(), refreshChatters); QThread::currentThread(), refreshChatters);
}; };
@ -95,7 +95,7 @@ TwitchChannel::TwitchChannel(const QString &channelName, Communi::IrcConnection
#if 0 #if 0
for (int i = 0; i < 1000; i++) { for (int i = 0; i < 1000; i++) {
this->addMessage(messages::Message::createSystemMessage("asdf")); this->addMessage(chatterino::Message::createSystemMessage("asdf"));
} }
#endif #endif
} }
@ -130,7 +130,7 @@ void TwitchChannel::reloadChannelEmotes()
{ {
auto app = getApp(); auto app = getApp();
debug::Log("[TwitchChannel:{}] Reloading channel emotes", this->name); Log("[TwitchChannel:{}] Reloading channel emotes", this->name);
app->emotes->bttv.loadChannelEmotes(this->name, this->bttvChannelEmotes); app->emotes->bttv.loadChannelEmotes(this->name, this->bttvChannelEmotes);
app->emotes->ffz.loadChannelEmotes(this->name, this->ffzChannelEmotes); app->emotes->ffz.loadChannelEmotes(this->name, this->ffzChannelEmotes);
@ -144,12 +144,12 @@ void TwitchChannel::sendMessage(const QString &message)
// XXX: It would be nice if we could add a link here somehow that opened the "account // XXX: It would be nice if we could add a link here somehow that opened the "account
// manager" dialog // manager" dialog
this->addMessage( this->addMessage(
messages::Message::createSystemMessage("You need to log in to send messages. You can " chatterino::Message::createSystemMessage("You need to log in to send messages. You can "
"link your Twitch account in the settings.")); "link your Twitch account in the settings."));
return; return;
} }
debug::Log("[TwitchChannel:{}] Send message: {}", this->name, message); Log("[TwitchChannel:{}] Send message: {}", this->name, message);
// Do last message processing // Do last message processing
QString parsedMessage = app->emotes->emojis.replaceShortCodes(message); QString parsedMessage = app->emotes->emojis.replaceShortCodes(message);
@ -204,7 +204,7 @@ bool TwitchChannel::hasModRights()
return this->isMod() || this->isBroadcaster(); return this->isMod() || this->isBroadcaster();
} }
void TwitchChannel::addRecentChatter(const std::shared_ptr<messages::Message> &message) void TwitchChannel::addRecentChatter(const std::shared_ptr<chatterino::Message> &message)
{ {
assert(!message->loginName.isEmpty()); assert(!message->loginName.isEmpty());
@ -233,9 +233,9 @@ void TwitchChannel::addJoinedUser(const QString &user)
QTimer::singleShot(500, &this->object, [this] { QTimer::singleShot(500, &this->object, [this] {
std::lock_guard<std::mutex> guard(this->joinedUserMutex); std::lock_guard<std::mutex> guard(this->joinedUserMutex);
auto message = messages::Message::createSystemMessage("Users joined: " + auto message = chatterino::Message::createSystemMessage("Users joined: " +
this->joinedUsers.join(", ")); this->joinedUsers.join(", "));
message->flags |= messages::Message::Collapsed; message->flags |= chatterino::Message::Collapsed;
this->addMessage(message); this->addMessage(message);
this->joinedUsers.clear(); this->joinedUsers.clear();
this->joinedUsersMergeQueued = false; this->joinedUsersMergeQueued = false;
@ -262,9 +262,9 @@ void TwitchChannel::addPartedUser(const QString &user)
QTimer::singleShot(500, &this->object, [this] { QTimer::singleShot(500, &this->object, [this] {
std::lock_guard<std::mutex> guard(this->partedUserMutex); std::lock_guard<std::mutex> guard(this->partedUserMutex);
auto message = messages::Message::createSystemMessage("Users parted: " + auto message = chatterino::Message::createSystemMessage("Users parted: " +
this->partedUsers.join(", ")); this->partedUsers.join(", "));
message->flags |= messages::Message::Collapsed; message->flags |= chatterino::Message::Collapsed;
this->addMessage(message); this->addMessage(message);
this->partedUsers.clear(); this->partedUsers.clear();
@ -321,18 +321,18 @@ void TwitchChannel::setLive(bool newLiveStatus)
void TwitchChannel::refreshLiveStatus() void TwitchChannel::refreshLiveStatus()
{ {
if (this->roomID.isEmpty()) { if (this->roomID.isEmpty()) {
debug::Log("[TwitchChannel:{}] Refreshing live status (Missing ID)", this->name); Log("[TwitchChannel:{}] Refreshing live status (Missing ID)", this->name);
this->setLive(false); this->setLive(false);
return; return;
} }
debug::Log("[TwitchChannel:{}] Refreshing live status", this->name); Log("[TwitchChannel:{}] Refreshing live status", this->name);
QString url("https://api.twitch.tv/kraken/streams/" + this->roomID); QString url("https://api.twitch.tv/kraken/streams/" + this->roomID);
std::weak_ptr<Channel> weak = this->shared_from_this(); std::weak_ptr<Channel> weak = this->shared_from_this();
util::twitch::get2(url, QThread::currentThread(), false, [weak](const rapidjson::Document &d) { get2(url, QThread::currentThread(), false, [weak](const rapidjson::Document &d) {
ChannelPtr shared = weak.lock(); ChannelPtr shared = weak.lock();
if (!shared) { if (!shared) {
@ -342,12 +342,12 @@ void TwitchChannel::refreshLiveStatus()
TwitchChannel *channel = dynamic_cast<TwitchChannel *>(shared.get()); TwitchChannel *channel = dynamic_cast<TwitchChannel *>(shared.get());
if (!d.IsObject()) { if (!d.IsObject()) {
debug::Log("[TwitchChannel:refreshLiveStatus] root is not an object"); Log("[TwitchChannel:refreshLiveStatus] root is not an object");
return; return;
} }
if (!d.HasMember("stream")) { if (!d.HasMember("stream")) {
debug::Log("[TwitchChannel:refreshLiveStatus] Missing stream in root"); Log("[TwitchChannel:refreshLiveStatus] Missing stream in root");
return; return;
} }
@ -361,7 +361,7 @@ void TwitchChannel::refreshLiveStatus()
if (!stream.HasMember("viewers") || !stream.HasMember("game") || if (!stream.HasMember("viewers") || !stream.HasMember("game") ||
!stream.HasMember("channel") || !stream.HasMember("created_at")) { !stream.HasMember("channel") || !stream.HasMember("created_at")) {
debug::Log("[TwitchChannel:refreshLiveStatus] Missing members in stream"); Log("[TwitchChannel:refreshLiveStatus] Missing members in stream");
channel->setLive(false); channel->setLive(false);
return; return;
} }
@ -369,7 +369,7 @@ void TwitchChannel::refreshLiveStatus()
const rapidjson::Value &streamChannel = stream["channel"]; const rapidjson::Value &streamChannel = stream["channel"];
if (!streamChannel.IsObject() || !streamChannel.HasMember("status")) { if (!streamChannel.IsObject() || !streamChannel.HasMember("status")) {
debug::Log("[TwitchChannel:refreshLiveStatus] Missing member \"status\" in channel"); Log("[TwitchChannel:refreshLiveStatus] Missing member \"status\" in channel");
return; return;
} }
@ -432,7 +432,7 @@ void TwitchChannel::fetchRecentMessages()
std::weak_ptr<Channel> weak = this->shared_from_this(); std::weak_ptr<Channel> weak = this->shared_from_this();
util::twitch::get(genericURL.arg(roomID), QThread::currentThread(), [weak](QJsonObject obj) { get(genericURL.arg(roomID), QThread::currentThread(), [weak](QJsonObject obj) {
ChannelPtr shared = weak.lock(); ChannelPtr shared = weak.lock();
if (!shared) { if (!shared) {
@ -449,15 +449,15 @@ void TwitchChannel::fetchRecentMessages()
return; return;
} }
std::vector<messages::MessagePtr> messages; std::vector<chatterino::MessagePtr> messages;
for (const QJsonValueRef _msg : msgArray) { for (const QJsonValueRef _msg : msgArray) {
QByteArray content = _msg.toString().toUtf8(); QByteArray content = _msg.toString().toUtf8();
auto msg = Communi::IrcMessage::fromData(content, readConnection); auto msg = Communi::IrcMessage::fromData(content, readConnection);
auto privMsg = static_cast<Communi::IrcPrivateMessage *>(msg); auto privMsg = static_cast<Communi::IrcPrivateMessage *>(msg);
messages::MessageParseArgs args; chatterino::MessageParseArgs args;
twitch::TwitchMessageBuilder builder(channel, privMsg, args); TwitchMessageBuilder builder(channel, privMsg, args);
if (!builder.isIgnored()) { if (!builder.isIgnored()) {
messages.push_back(builder.build()); messages.push_back(builder.build());
} }

View file

@ -60,12 +60,12 @@ public:
bool isBroadcaster() const override; bool isBroadcaster() const override;
bool hasModRights(); bool hasModRights();
void addRecentChatter(const std::shared_ptr<messages::Message> &message) final; void addRecentChatter(const std::shared_ptr<chatterino::Message> &message) final;
void addJoinedUser(const QString &user); void addJoinedUser(const QString &user);
void addPartedUser(const QString &user); void addPartedUser(const QString &user);
const std::shared_ptr<chatterino::util::EmoteMap> bttvChannelEmotes; const std::shared_ptr<EmoteMap> bttvChannelEmotes;
const std::shared_ptr<chatterino::util::EmoteMap> ffzChannelEmotes; const std::shared_ptr<EmoteMap> ffzChannelEmotes;
const QString subscriptionURL; const QString subscriptionURL;
const QString channelURL; const QString channelURL;

View file

@ -1,10 +1,10 @@
#include "providers/twitch/TwitchEmotes.hpp" #include "providers/twitch/TwitchEmotes.hpp"
#include "common/UrlFetch.hpp"
#include "debug/Benchmark.hpp"
#include "debug/Log.hpp" #include "debug/Log.hpp"
#include "messages/Image.hpp" #include "messages/Image.hpp"
#include "debug/Benchmark.hpp"
#include "util/RapidjsonHelpers.hpp" #include "util/RapidjsonHelpers.hpp"
#include "common/UrlFetch.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}"
@ -47,19 +47,19 @@ QString cleanUpCode(const QString &dirtyEmoteCode)
void loadSetData(std::shared_ptr<TwitchEmotes::EmoteSet> emoteSet) void loadSetData(std::shared_ptr<TwitchEmotes::EmoteSet> emoteSet)
{ {
debug::Log("Load twitch emote set data for {}", emoteSet->key); Log("Load twitch emote set data for {}", emoteSet->key);
util::NetworkRequest req("https://braize.pajlada.com/chatterino/twitchemotes/set/" + NetworkRequest req("https://braize.pajlada.com/chatterino/twitchemotes/set/" + emoteSet->key +
emoteSet->key + "/"); "/");
req.setRequestType(util::NetworkRequest::GetRequest); req.setRequestType(NetworkRequest::GetRequest);
req.onError([](int errorCode) -> bool { req.onError([](int errorCode) -> bool {
debug::Log("Emote sets on ERROR {}", errorCode); Log("Emote sets on ERROR {}", errorCode);
return true; return true;
}); });
req.onSuccess([emoteSet](const rapidjson::Document &root) -> bool { req.onSuccess([emoteSet](const rapidjson::Document &root) -> bool {
debug::Log("Emote sets on success"); Log("Emote sets on success");
if (!root.IsObject()) { if (!root.IsObject()) {
return false; return false;
} }
@ -99,7 +99,7 @@ TwitchEmotes::TwitchEmotes()
// id is used for lookup // id is used for lookup
// emoteName is used for giving a name to the emote in case it doesn't exist // emoteName is used for giving a name to the emote in case it doesn't exist
util::EmoteData TwitchEmotes::getEmoteById(const QString &id, const QString &emoteName) EmoteData TwitchEmotes::getEmoteById(const QString &id, const QString &emoteName)
{ {
QString _emoteName = emoteName; QString _emoteName = emoteName;
_emoteName.replace("<", "&lt;"); _emoteName.replace("<", "&lt;");
@ -121,17 +121,17 @@ util::EmoteData TwitchEmotes::getEmoteById(const QString &id, const QString &emo
} }
return _twitchEmoteFromCache.getOrAdd(id, [&emoteName, &_emoteName, &id] { return _twitchEmoteFromCache.getOrAdd(id, [&emoteName, &_emoteName, &id] {
util::EmoteData newEmoteData; EmoteData newEmoteData;
auto cleanCode = cleanUpCode(emoteName); auto cleanCode = cleanUpCode(emoteName);
newEmoteData.image1x = new messages::Image(getEmoteLink(id, "1.0"), 1, emoteName, newEmoteData.image1x = new chatterino::Image(getEmoteLink(id, "1.0"), 1, emoteName,
_emoteName + "<br/>Twitch Emote 1x"); _emoteName + "<br/>Twitch Emote 1x");
newEmoteData.image1x->setCopyString(cleanCode); newEmoteData.image1x->setCopyString(cleanCode);
newEmoteData.image2x = new messages::Image(getEmoteLink(id, "2.0"), .5, emoteName, newEmoteData.image2x = new chatterino::Image(getEmoteLink(id, "2.0"), .5, emoteName,
_emoteName + "<br/>Twitch Emote 2x"); _emoteName + "<br/>Twitch Emote 2x");
newEmoteData.image2x->setCopyString(cleanCode); newEmoteData.image2x->setCopyString(cleanCode);
newEmoteData.image3x = new messages::Image(getEmoteLink(id, "3.0"), .25, emoteName, newEmoteData.image3x = new chatterino::Image(getEmoteLink(id, "3.0"), .25, emoteName,
_emoteName + "<br/>Twitch Emote 3x"); _emoteName + "<br/>Twitch Emote 3x");
newEmoteData.image3x->setCopyString(cleanCode); newEmoteData.image3x->setCopyString(cleanCode);
@ -142,21 +142,21 @@ util::EmoteData TwitchEmotes::getEmoteById(const QString &id, const QString &emo
void TwitchEmotes::refresh(const std::shared_ptr<TwitchAccount> &user) void TwitchEmotes::refresh(const std::shared_ptr<TwitchAccount> &user)
{ {
debug::Log("Loading Twitch emotes for user {}", user->getUserName()); Log("Loading Twitch emotes for user {}", user->getUserName());
const auto &roomID = user->getUserId(); const auto &roomID = user->getUserId();
const auto &clientID = user->getOAuthClient(); const auto &clientID = user->getOAuthClient();
const auto &oauthToken = user->getOAuthToken(); const auto &oauthToken = user->getOAuthToken();
if (clientID.isEmpty() || oauthToken.isEmpty()) { if (clientID.isEmpty() || oauthToken.isEmpty()) {
debug::Log("Missing Client ID or OAuth token"); Log("Missing Client ID or OAuth token");
return; return;
} }
TwitchAccountEmoteData &emoteData = this->emotes[roomID]; TwitchAccountEmoteData &emoteData = this->emotes[roomID];
if (emoteData.filled) { if (emoteData.filled) {
debug::Log("Emotes are already loaded for room id {}", roomID); Log("Emotes are already loaded for room id {}", roomID);
return; return;
} }
@ -183,7 +183,7 @@ void TwitchEmotes::refresh(const std::shared_ptr<TwitchAccount> &user)
emoteSet->emotes.emplace_back(id, cleanCode); emoteSet->emotes.emplace_back(id, cleanCode);
emoteData.emoteCodes.push_back(cleanCode); emoteData.emoteCodes.push_back(cleanCode);
util::EmoteData emote = this->getEmoteById(id, code); EmoteData emote = this->getEmoteById(id, code);
emoteData.emotes.insert(code, emote); emoteData.emotes.insert(code, emote);
} }
@ -193,13 +193,13 @@ void TwitchEmotes::refresh(const std::shared_ptr<TwitchAccount> &user)
emoteData.filled = true; emoteData.filled = true;
}; };
util::twitch::getAuthorized(url, clientID, oauthToken, QThread::currentThread(), loadEmotes); getAuthorized(url, clientID, oauthToken, QThread::currentThread(), loadEmotes);
} }
void TwitchEmotes::loadSetData(std::shared_ptr<TwitchEmotes::EmoteSet> emoteSet) void TwitchEmotes::loadSetData(std::shared_ptr<TwitchEmotes::EmoteSet> emoteSet)
{ {
if (!emoteSet) { if (!emoteSet) {
debug::Log("null emote set sent"); Log("null emote set sent");
return; return;
} }
@ -211,14 +211,14 @@ void TwitchEmotes::loadSetData(std::shared_ptr<TwitchEmotes::EmoteSet> emoteSet)
return; return;
} }
debug::Log("Load twitch emote set data for {}..", emoteSet->key); Log("Load twitch emote set data for {}..", emoteSet->key);
util::NetworkRequest req("https://braize.pajlada.com/chatterino/twitchemotes/set/" + NetworkRequest req("https://braize.pajlada.com/chatterino/twitchemotes/set/" + emoteSet->key +
emoteSet->key + "/"); "/");
req.setRequestType(util::NetworkRequest::GetRequest); req.setRequestType(NetworkRequest::GetRequest);
req.onError([](int errorCode) -> bool { req.onError([](int errorCode) -> bool {
debug::Log("Emote sets on ERROR {}", errorCode); Log("Emote sets on ERROR {}", errorCode);
return true; return true;
}); });
@ -238,7 +238,7 @@ void TwitchEmotes::loadSetData(std::shared_ptr<TwitchEmotes::EmoteSet> emoteSet)
return false; return false;
} }
debug::Log("Loaded twitch emote set data for {}!", emoteSet->key); Log("Loaded twitch emote set data for {}!", emoteSet->key);
if (type == "sub") { if (type == "sub") {
emoteSet->text = QString("Twitch Subscriber Emote (%1)").arg(channelName); emoteSet->text = QString("Twitch Subscriber Emote (%1)").arg(channelName);

View file

@ -17,10 +17,10 @@ class TwitchEmotes
public: public:
TwitchEmotes(); TwitchEmotes();
util::EmoteData getEmoteById(const QString &id, const QString &emoteName); EmoteData getEmoteById(const QString &id, const QString &emoteName);
/// Twitch emotes /// Twitch emotes
void refresh(const std::shared_ptr<providers::twitch::TwitchAccount> &user); void refresh(const std::shared_ptr<TwitchAccount> &user);
struct TwitchEmote { struct TwitchEmote {
TwitchEmote(const QString &_id, const QString &_code) TwitchEmote(const QString &_id, const QString &_code)
@ -50,7 +50,7 @@ public:
std::vector<QString> emoteCodes; std::vector<QString> emoteCodes;
util::EmoteMap emotes; EmoteMap emotes;
bool filled = false; bool filled = false;
}; };
@ -62,10 +62,10 @@ private:
void loadSetData(std::shared_ptr<TwitchEmotes::EmoteSet> emoteSet); void loadSetData(std::shared_ptr<TwitchEmotes::EmoteSet> emoteSet);
// emote code // emote code
util::ConcurrentMap<QString, providers::twitch::EmoteValue *> _twitchEmotes; ConcurrentMap<QString, EmoteValue *> _twitchEmotes;
// emote id // emote id
util::ConcurrentMap<QString, util::EmoteData> _twitchEmoteFromCache; ConcurrentMap<QString, EmoteData> _twitchEmoteFromCache;
}; };
} // namespace chatterino } // namespace chatterino

View file

@ -6,7 +6,7 @@ namespace chatterino {
bool trimChannelName(const QString &channelName, QString &outChannelName) bool trimChannelName(const QString &channelName, QString &outChannelName)
{ {
if (channelName.length() < 3) { if (channelName.length() < 3) {
debug::Log("channel name length below 3"); Log("channel name length below 3");
return false; return false;
} }

View file

@ -18,13 +18,11 @@
#include <QDebug> #include <QDebug>
#include <QMediaPlayer> #include <QMediaPlayer>
using namespace chatterino::messages;
namespace chatterino { namespace chatterino {
TwitchMessageBuilder::TwitchMessageBuilder(Channel *_channel, TwitchMessageBuilder::TwitchMessageBuilder(Channel *_channel,
const Communi::IrcPrivateMessage *_ircMessage, const Communi::IrcPrivateMessage *_ircMessage,
const messages::MessageParseArgs &_args) const chatterino::MessageParseArgs &_args)
: channel(_channel) : channel(_channel)
, twitchChannel(dynamic_cast<TwitchChannel *>(_channel)) , twitchChannel(dynamic_cast<TwitchChannel *>(_channel))
, ircMessage(_ircMessage) , ircMessage(_ircMessage)
@ -39,8 +37,8 @@ TwitchMessageBuilder::TwitchMessageBuilder(Channel *_channel,
TwitchMessageBuilder::TwitchMessageBuilder(Channel *_channel, TwitchMessageBuilder::TwitchMessageBuilder(Channel *_channel,
const Communi::IrcMessage *_ircMessage, const Communi::IrcMessage *_ircMessage,
const messages::MessageParseArgs &_args, QString content, const chatterino::MessageParseArgs &_args,
bool isAction) QString content, bool isAction)
: channel(_channel) : channel(_channel)
, twitchChannel(dynamic_cast<TwitchChannel *>(_channel)) , twitchChannel(dynamic_cast<TwitchChannel *>(_channel))
, ircMessage(_ircMessage) , ircMessage(_ircMessage)
@ -60,8 +58,7 @@ bool TwitchMessageBuilder::isIgnored() const
// TODO(pajlada): Do we need to check if the phrase is valid first? // TODO(pajlada): Do we need to check if the phrase is valid first?
for (const auto &phrase : app->ignores->phrases.getVector()) { for (const auto &phrase : app->ignores->phrases.getVector()) {
if (phrase.isMatch(this->originalMessage)) { if (phrase.isMatch(this->originalMessage)) {
debug::Log("Blocking message because it contains ignored phrase {}", Log("Blocking message because it contains ignored phrase {}", phrase.getPattern());
phrase.getPattern());
return true; return true;
} }
} }
@ -71,7 +68,7 @@ bool TwitchMessageBuilder::isIgnored() const
for (const auto &user : app->accounts->twitch.getCurrent()->getIgnores()) { for (const auto &user : app->accounts->twitch.getCurrent()->getIgnores()) {
if (sourceUserID == user.id) { if (sourceUserID == user.id) {
debug::Log("Blocking message because it's from blocked user {}", user.name); Log("Blocking message because it's from blocked user {}", user.name);
return true; return true;
} }
} }
@ -82,7 +79,7 @@ bool TwitchMessageBuilder::isIgnored() const
for (const auto &user : app->accounts->twitch.getCurrent()->getIgnores()) { for (const auto &user : app->accounts->twitch.getCurrent()->getIgnores()) {
if (sourceUserID == user.id) { if (sourceUserID == user.id) {
debug::Log("Blocking message because it's from blocked user {}", user.name); Log("Blocking message because it's from blocked user {}", user.name);
return true; return true;
} }
} }
@ -167,7 +164,7 @@ MessagePtr TwitchMessageBuilder::build()
} }
// twitch emotes // twitch emotes
std::vector<std::pair<long, util::EmoteData>> twitchEmotes; std::vector<std::pair<long, EmoteData>> twitchEmotes;
iterator = this->tags.find("emotes"); iterator = this->tags.find("emotes");
if (iterator != this->tags.end()) { if (iterator != this->tags.end()) {
@ -205,13 +202,13 @@ MessagePtr TwitchMessageBuilder::build()
} }
// split words // split words
std::vector<std::tuple<util::EmoteData, QString>> parsed; std::vector<std::tuple<EmoteData, QString>> parsed;
// Parse emojis and take all non-emojis and put them in parsed as full text-words // Parse emojis and take all non-emojis and put them in parsed as full text-words
app->emotes->emojis.parse(parsed, split); app->emotes->emojis.parse(parsed, split);
for (const auto &tuple : parsed) { for (const auto &tuple : parsed) {
const util::EmoteData &emoteData = std::get<0>(tuple); const EmoteData &emoteData = std::get<0>(tuple);
if (!emoteData.isValid()) { // is text if (!emoteData.isValid()) { // is text
QString string = std::get<1>(tuple); QString string = std::get<1>(tuple);
@ -334,7 +331,7 @@ void TwitchMessageBuilder::appendUsername()
auto iterator = this->tags.find("display-name"); auto iterator = this->tags.find("display-name");
if (iterator != this->tags.end()) { if (iterator != this->tags.end()) {
QString displayName = util::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; username = displayName;
@ -449,12 +446,10 @@ void TwitchMessageBuilder::parseHighlights()
// TODO: This vector should only be rebuilt upon highlights being changed // TODO: This vector should only be rebuilt upon highlights being changed
// fourtf: should be implemented in the HighlightsController // fourtf: should be implemented in the HighlightsController
std::vector<controllers::highlights::HighlightPhrase> activeHighlights = std::vector<HighlightPhrase> activeHighlights = app->highlights->phrases.getVector();
app->highlights->phrases.getVector();
if (app->settings->enableHighlightsSelf && currentUsername.size() > 0) { if (app->settings->enableHighlightsSelf && currentUsername.size() > 0) {
controllers::highlights::HighlightPhrase selfHighlight( HighlightPhrase selfHighlight(currentUsername, app->settings->enableHighlightTaskbar,
currentUsername, app->settings->enableHighlightTaskbar,
app->settings->enableHighlightSound, false); app->settings->enableHighlightSound, false);
activeHighlights.emplace_back(std::move(selfHighlight)); activeHighlights.emplace_back(std::move(selfHighlight));
} }
@ -466,9 +461,9 @@ void TwitchMessageBuilder::parseHighlights()
bool hasFocus = (QApplication::focusWidget() != nullptr); bool hasFocus = (QApplication::focusWidget() != nullptr);
if (!blackList.contains(this->ircMessage->nick(), Qt::CaseInsensitive)) { if (!blackList.contains(this->ircMessage->nick(), Qt::CaseInsensitive)) {
for (const controllers::highlights::HighlightPhrase &highlight : activeHighlights) { for (const HighlightPhrase &highlight : activeHighlights) {
if (highlight.isMatch(this->originalMessage)) { if (highlight.isMatch(this->originalMessage)) {
debug::Log("Highlight because {} matches {}", this->originalMessage, Log("Highlight because {} matches {}", this->originalMessage,
highlight.getPattern()); highlight.getPattern());
doHighlight = true; doHighlight = true;
@ -506,7 +501,7 @@ void TwitchMessageBuilder::parseHighlights()
void TwitchMessageBuilder::appendTwitchEmote(const Communi::IrcMessage *ircMessage, void TwitchMessageBuilder::appendTwitchEmote(const Communi::IrcMessage *ircMessage,
const QString &emote, const QString &emote,
std::vector<std::pair<long int, util::EmoteData>> &vec) std::vector<std::pair<long int, EmoteData>> &vec)
{ {
auto app = getApp(); auto app = getApp();
if (!emote.contains(':')) { if (!emote.contains(':')) {
@ -539,15 +534,15 @@ void TwitchMessageBuilder::appendTwitchEmote(const Communi::IrcMessage *ircMessa
QString name = this->originalMessage.mid(start, end - start + 1); QString name = this->originalMessage.mid(start, end - start + 1);
vec.push_back(std::pair<long int, util::EmoteData>( vec.push_back(
start, app->emotes->twitch.getEmoteById(id, name))); std::pair<long int, EmoteData>(start, app->emotes->twitch.getEmoteById(id, name)));
} }
} }
bool TwitchMessageBuilder::tryAppendEmote(QString &emoteString) bool TwitchMessageBuilder::tryAppendEmote(QString &emoteString)
{ {
auto app = getApp(); auto app = getApp();
util::EmoteData emoteData; EmoteData emoteData;
auto appendEmote = [&](MessageElement::Flags flags) { auto appendEmote = [&](MessageElement::Flags flags) {
this->emplace<EmoteElement>(emoteData, flags); this->emplace<EmoteElement>(emoteData, flags);
@ -621,7 +616,7 @@ void TwitchMessageBuilder::appendTwitchBadges()
this->emplace<ImageElement>(badge.badgeImage1x, MessageElement::BadgeVanity) this->emplace<ImageElement>(badge.badgeImage1x, MessageElement::BadgeVanity)
->setTooltip(tooltip); ->setTooltip(tooltip);
} catch (const std::out_of_range &) { } catch (const std::out_of_range &) {
debug::Log("No default bit badge for version {} found", versionKey); Log("No default bit badge for version {} found", versionKey);
continue; continue;
} }
} else if (badge == "staff/1") { } else if (badge == "staff/1") {
@ -768,7 +763,7 @@ bool TwitchMessageBuilder::tryParseCheermote(const QString &string)
bool ok = false; bool ok = false;
int numBits = amount.toInt(&ok); int numBits = amount.toInt(&ok);
if (!ok) { if (!ok) {
debug::Log("Error parsing bit amount in tryParseCheermote"); Log("Error parsing bit amount in tryParseCheermote");
return false; return false;
} }
@ -785,7 +780,7 @@ bool TwitchMessageBuilder::tryParseCheermote(const QString &string)
} }
if (savedIt == cheermoteSet.cheermotes.end()) { if (savedIt == cheermoteSet.cheermotes.end()) {
debug::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); numBits);
return false; return false;
} }

View file

@ -14,7 +14,7 @@ namespace chatterino {
class Channel; class Channel;
class TwitchChannel; class TwitchChannel;
class TwitchMessageBuilder : public messages::MessageBuilder class TwitchMessageBuilder : public chatterino::MessageBuilder
{ {
public: public:
enum UsernameDisplayMode : int { enum UsernameDisplayMode : int {
@ -26,22 +26,22 @@ public:
TwitchMessageBuilder() = delete; TwitchMessageBuilder() = delete;
explicit TwitchMessageBuilder(Channel *_channel, const Communi::IrcPrivateMessage *_ircMessage, explicit TwitchMessageBuilder(Channel *_channel, const Communi::IrcPrivateMessage *_ircMessage,
const messages::MessageParseArgs &_args); const chatterino::MessageParseArgs &_args);
explicit TwitchMessageBuilder(Channel *_channel, const Communi::IrcMessage *_ircMessage, explicit TwitchMessageBuilder(Channel *_channel, const Communi::IrcMessage *_ircMessage,
const messages::MessageParseArgs &_args, QString content, const chatterino::MessageParseArgs &_args, QString content,
bool isAction); bool isAction);
Channel *channel; Channel *channel;
TwitchChannel *twitchChannel; TwitchChannel *twitchChannel;
const Communi::IrcMessage *ircMessage; const Communi::IrcMessage *ircMessage;
messages::MessageParseArgs args; chatterino::MessageParseArgs args;
const QVariantMap tags; const QVariantMap tags;
QString messageID; QString messageID;
QString userName; QString userName;
bool isIgnored() const; bool isIgnored() const;
messages::MessagePtr build(); chatterino::MessagePtr build();
private: private:
QString roomID; QString roomID;
@ -60,7 +60,7 @@ private:
void parseHighlights(); void parseHighlights();
void appendTwitchEmote(const Communi::IrcMessage *ircMessage, const QString &emote, void appendTwitchEmote(const Communi::IrcMessage *ircMessage, const QString &emote,
std::vector<std::pair<long, util::EmoteData>> &vec); std::vector<std::pair<long, EmoteData>> &vec);
bool tryAppendEmote(QString &emoteString); bool tryAppendEmote(QString &emoteString);
void appendTwitchBadges(); void appendTwitchBadges();

View file

@ -29,10 +29,10 @@ TwitchServer::TwitchServer()
void TwitchServer::initialize() void TwitchServer::initialize()
{ {
getApp()->accounts->twitch.currentUserChanged.connect( getApp()->accounts->twitch.currentUserChanged.connect(
[this]() { util::postToThread([this] { this->connect(); }); }); [this]() { postToThread([this] { this->connect(); }); });
} }
void TwitchServer::initializeConnection(providers::irc::IrcConnection *connection, bool isRead, void TwitchServer::initializeConnection(IrcConnection *connection, bool isRead,
bool isWrite) bool isWrite)
{ {
std::shared_ptr<TwitchAccount> account = getApp()->accounts->twitch.getCurrent(); std::shared_ptr<TwitchAccount> account = getApp()->accounts->twitch.getCurrent();
@ -196,7 +196,7 @@ void TwitchServer::onMessageSendRequested(TwitchChannel *channel, const QString
if (!lastMessage.empty() && lastMessage.back() + minMessageOffset > now) { if (!lastMessage.empty() && lastMessage.back() + minMessageOffset > now) {
if (this->lastErrorTimeSpeed_ + 30s < now) { if (this->lastErrorTimeSpeed_ + 30s < now) {
auto errorMessage = auto errorMessage =
messages::Message::createSystemMessage("sending messages too fast"); chatterino::Message::createSystemMessage("sending messages too fast");
channel->addMessage(errorMessage); channel->addMessage(errorMessage);
@ -214,7 +214,7 @@ void TwitchServer::onMessageSendRequested(TwitchChannel *channel, const QString
if (lastMessage.size() >= maxMessageCount) { if (lastMessage.size() >= maxMessageCount) {
if (this->lastErrorTimeAmount_ + 30s < now) { if (this->lastErrorTimeAmount_ + 30s < now) {
auto errorMessage = auto errorMessage =
messages::Message::createSystemMessage("sending too many messages"); chatterino::Message::createSystemMessage("sending too many messages");
channel->addMessage(errorMessage); channel->addMessage(errorMessage);

View file

@ -11,7 +11,7 @@
namespace chatterino { namespace chatterino {
class TwitchServer final : public irc::AbstractIrcServer class TwitchServer final : public AbstractIrcServer
{ {
public: public:
TwitchServer(); TwitchServer();
@ -23,15 +23,14 @@ public:
std::shared_ptr<Channel> getChannelOrEmptyByID(const QString &channelID); std::shared_ptr<Channel> getChannelOrEmptyByID(const QString &channelID);
util::MutexValue<QString> lastUserThatWhisperedMe; MutexValue<QString> lastUserThatWhisperedMe;
const ChannelPtr whispersChannel; const ChannelPtr whispersChannel;
const ChannelPtr mentionsChannel; const ChannelPtr mentionsChannel;
IndirectChannel watchingChannel; IndirectChannel watchingChannel;
protected: protected:
void initializeConnection(providers::irc::IrcConnection *connection, bool isRead, void initializeConnection(IrcConnection *connection, bool isRead, bool isWrite) override;
bool isWrite) override;
std::shared_ptr<Channel> createChannel(const QString &channelName) override; std::shared_ptr<Channel> createChannel(const QString &channelName) override;
void privateMessageReceived(Communi::IrcPrivateMessage *message) override; void privateMessageReceived(Communi::IrcPrivateMessage *message) override;

View file

@ -17,10 +17,10 @@ public:
void initialize(); void initialize();
providers::twitch::TwitchEmotes twitch; TwitchEmotes twitch;
providers::bttv::BTTVEmotes bttv; BTTVEmotes bttv;
providers::ffz::FFZEmotes ffz; FFZEmotes ffz;
providers::emoji::Emojis emojis; Emojis emojis;
GIFTimer gifTimer; GIFTimer gifTimer;
}; };

View file

@ -29,7 +29,7 @@ FontManager::FontManager()
qDebug() << "init FontManager"; qDebug() << "init FontManager";
this->chatFontFamily.connect([this](const std::string &, auto) { this->chatFontFamily.connect([this](const std::string &, auto) {
util::assertInGuiThread(); assertInGuiThread();
if (getApp()->windows) { if (getApp()->windows) {
getApp()->windows->incGeneration(); getApp()->windows->incGeneration();
@ -42,7 +42,7 @@ FontManager::FontManager()
}); });
this->chatFontSize.connect([this](const int &, auto) { this->chatFontSize.connect([this](const int &, auto) {
util::assertInGuiThread(); assertInGuiThread();
if (getApp()->windows) { if (getApp()->windows) {
getApp()->windows->incGeneration(); getApp()->windows->incGeneration();
@ -69,7 +69,7 @@ QFontMetrics FontManager::getFontMetrics(FontManager::Type type, float scale)
FontManager::FontData &FontManager::getOrCreateFontData(Type type, float scale) FontManager::FontData &FontManager::getOrCreateFontData(Type type, float scale)
{ {
util::assertInGuiThread(); assertInGuiThread();
assert(type >= 0 && type < EndType); assert(type >= 0 && type < EndType);

View file

@ -77,6 +77,6 @@ private:
std::vector<std::unordered_map<float, FontData>> fontsByType; std::vector<std::unordered_map<float, FontData>> fontsByType;
}; };
using FontStyle = singletons::FontManager::Type; using FontStyle = chatterino::FontManager::Type;
} // namespace chatterino } // namespace chatterino

View file

@ -17,7 +17,7 @@ void LoggingManager::initialize()
this->pathManager = getApp()->paths; this->pathManager = getApp()->paths;
} }
void LoggingManager::addMessage(const QString &channelName, messages::MessagePtr message) void LoggingManager::addMessage(const QString &channelName, chatterino::MessagePtr message)
{ {
auto app = getApp(); auto app = getApp();

View file

@ -20,7 +20,7 @@ public:
void initialize(); void initialize();
void addMessage(const QString &channelName, messages::MessagePtr message); void addMessage(const QString &channelName, chatterino::MessagePtr message);
private: private:
std::map<QString, std::unique_ptr<LoggingChannel>> loggingChannels; std::map<QString, std::unique_ptr<LoggingChannel>> loggingChannels;

View file

@ -176,7 +176,7 @@ void NativeMessagingManager::ReceiverThread::handleMessage(const QJsonObject &ro
qDebug() << attach; qDebug() << attach;
#ifdef USEWINSDK #ifdef USEWINSDK
widgets::AttachedWindow::GetArgs args; AttachedWindow::GetArgs args;
args.winId = root.value("winId").toString(); args.winId = root.value("winId").toString();
args.yOffset = root.value("yOffset").toInt(-1); args.yOffset = root.value("yOffset").toInt(-1);
args.width = root.value("size").toObject().value("width").toInt(-1); args.width = root.value("size").toObject().value("width").toInt(-1);
@ -190,7 +190,7 @@ void NativeMessagingManager::ReceiverThread::handleMessage(const QJsonObject &ro
#endif #endif
if (_type == "twitch") { if (_type == "twitch") {
util::postToThread([=] { postToThread([=] {
if (!name.isEmpty()) { if (!name.isEmpty()) {
app->twitch.server->watchingChannel.update( app->twitch.server->watchingChannel.update(
app->twitch.server->getOrAddChannel(name)); app->twitch.server->getOrAddChannel(name));
@ -199,7 +199,7 @@ void NativeMessagingManager::ReceiverThread::handleMessage(const QJsonObject &ro
if (attach) { if (attach) {
#ifdef USEWINSDK #ifdef USEWINSDK
// if (args.height != -1) { // if (args.height != -1) {
auto *window = widgets::AttachedWindow::get(::GetForegroundWindow(), args); auto *window = AttachedWindow::get(::GetForegroundWindow(), args);
if (!name.isEmpty()) { if (!name.isEmpty()) {
window->setChannel(app->twitch.server->getOrAddChannel(name)); window->setChannel(app->twitch.server->getOrAddChannel(name));
} }
@ -221,9 +221,9 @@ void NativeMessagingManager::ReceiverThread::handleMessage(const QJsonObject &ro
} }
#ifdef USEWINSDK #ifdef USEWINSDK
util::postToThread([winId] { postToThread([winId] {
qDebug() << "NW detach"; qDebug() << "NW detach";
widgets::AttachedWindow::detach(winId); AttachedWindow::detach(winId);
}); });
#endif #endif
} else { } else {
@ -235,7 +235,7 @@ std::string &NativeMessagingManager::getGuiMessageQueueName()
{ {
static std::string name = static std::string name =
"chatterino_gui" + "chatterino_gui" +
singletons::PathManager::getInstance()->applicationFilePathHash.toStdString(); chatterino::PathManager::getInstance()->applicationFilePathHash.toStdString();
return name; return name;
} }

View file

@ -59,7 +59,7 @@ void PathManager::initAppFilePathHash()
void PathManager::initCheckPortable() void PathManager::initCheckPortable()
{ {
this->portable = this->portable =
QFileInfo::exists(util::combinePath(QCoreApplication::applicationDirPath(), "portable")); QFileInfo::exists(combinePath(QCoreApplication::applicationDirPath(), "portable"));
} }
void PathManager::initAppDataDirectory() void PathManager::initAppDataDirectory()
@ -99,7 +99,7 @@ void PathManager::initSubDirectories()
// 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 makePath = [&](const std::string &name) -> QString {
auto path = util::combinePath(this->rootAppDataDirectory, QString::fromStdString(name)); auto path = combinePath(this->rootAppDataDirectory, QString::fromStdString(name));
if (!QDir().mkpath(path)) { 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);

View file

@ -8,9 +8,9 @@ namespace chatterino {
namespace { namespace {
inline messages::Image *lli(const char *pixmapPath, qreal scale = 1) inline chatterino::Image *lli(const char *pixmapPath, qreal scale = 1)
{ {
return new messages::Image(new QPixmap(pixmapPath), scale); return new chatterino::Image(new QPixmap(pixmapPath), scale);
} }
template <typename Type> template <typename Type>
@ -221,7 +221,7 @@ inline bool ParseSingleCheermoteSet(ResourceManager::JSONCheermoteSet &set,
qreal chatterinoScale = 1 / scaleNumber; qreal chatterinoScale = 1 / scaleNumber;
auto image = new messages::Image(url, chatterinoScale); auto image = new chatterino::Image(url, chatterinoScale);
// TODO(pajlada): Fill in name and tooltip // TODO(pajlada): Fill in name and tooltip
tier.images[background][state][scale] = image; tier.images[background][state][scale] = image;
@ -310,9 +310,9 @@ void ResourceManager::initialize()
} }
ResourceManager::BadgeVersion::BadgeVersion(QJsonObject &&root) ResourceManager::BadgeVersion::BadgeVersion(QJsonObject &&root)
: badgeImage1x(new messages::Image(root.value("image_url_1x").toString())) : badgeImage1x(new chatterino::Image(root.value("image_url_1x").toString()))
, badgeImage2x(new messages::Image(root.value("image_url_2x").toString())) , badgeImage2x(new chatterino::Image(root.value("image_url_2x").toString()))
, badgeImage4x(new messages::Image(root.value("image_url_4x").toString())) , badgeImage4x(new chatterino::Image(root.value("image_url_4x").toString()))
, description(root.value("description").toString().toStdString()) , description(root.value("description").toString().toStdString())
, title(root.value("title").toString().toStdString()) , title(root.value("title").toString().toStdString())
, clickAction(root.value("clickAction").toString().toStdString()) , clickAction(root.value("clickAction").toString().toStdString())
@ -324,7 +324,7 @@ void ResourceManager::loadChannelData(const QString &roomID, bool bypassCache)
{ {
QString url = "https://badges.twitch.tv/v1/badges/channels/" + roomID + "/display?language=en"; QString url = "https://badges.twitch.tv/v1/badges/channels/" + roomID + "/display?language=en";
util::NetworkRequest req(url); NetworkRequest req(url);
req.setCaller(QThread::currentThread()); req.setCaller(QThread::currentThread());
req.getJSON([this, roomID](QJsonObject &root) { req.getJSON([this, roomID](QJsonObject &root) {
@ -352,8 +352,8 @@ void ResourceManager::loadChannelData(const QString &roomID, bool bypassCache)
QString cheermoteURL = "https://api.twitch.tv/kraken/bits/actions?channel_id=" + roomID; QString cheermoteURL = "https://api.twitch.tv/kraken/bits/actions?channel_id=" + roomID;
util::twitch::get2( get2(cheermoteURL, QThread::currentThread(), true,
cheermoteURL, QThread::currentThread(), true, [this, roomID](const rapidjson::Document &d) { [this, roomID](const rapidjson::Document &d) {
ResourceManager::Channel &ch = this->channels[roomID]; ResourceManager::Channel &ch = this->channels[roomID];
ParseCheermoteSets(ch.jsonCheermoteSets, d); ParseCheermoteSets(ch.jsonCheermoteSets, d);
@ -397,7 +397,7 @@ void ResourceManager::loadDynamicTwitchBadges()
{ {
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");
util::NetworkRequest req(url); NetworkRequest req(url);
req.setCaller(QThread::currentThread()); req.setCaller(QThread::currentThread());
req.getJSON([this](QJsonObject &root) { req.getJSON([this](QJsonObject &root) {
QJsonObject sets = root.value("badge_sets").toObject(); QJsonObject sets = root.value("badge_sets").toObject();
@ -426,7 +426,7 @@ void ResourceManager::loadChatterinoBadges()
static QString url("https://fourtf.com/chatterino/badges.json"); static QString url("https://fourtf.com/chatterino/badges.json");
util::NetworkRequest req(url); NetworkRequest req(url);
req.setCaller(QThread::currentThread()); req.setCaller(QThread::currentThread());
req.getJSON([this](QJsonObject &root) { req.getJSON([this](QJsonObject &root) {
@ -438,7 +438,7 @@ void ResourceManager::loadChatterinoBadges()
const QString &badgeVariantImageURL = badgeVariant.value("image").toString(); const QString &badgeVariantImageURL = badgeVariant.value("image").toString();
auto badgeVariantPtr = std::make_shared<ChatterinoBadge>( auto badgeVariantPtr = std::make_shared<ChatterinoBadge>(
badgeVariantTooltip, new messages::Image(badgeVariantImageURL)); badgeVariantTooltip, new chatterino::Image(badgeVariantImageURL));
QJsonArray badgeVariantUsers = badgeVariant.value("users").toArray(); QJsonArray badgeVariantUsers = badgeVariant.value("users").toArray();

View file

@ -35,39 +35,39 @@ public:
QPixmap unmod; QPixmap unmod;
} buttons; } buttons;
messages::Image *badgeStaff; chatterino::Image *badgeStaff;
messages::Image *badgeAdmin; chatterino::Image *badgeAdmin;
messages::Image *badgeGlobalModerator; chatterino::Image *badgeGlobalModerator;
messages::Image *badgeModerator; chatterino::Image *badgeModerator;
messages::Image *badgeTurbo; chatterino::Image *badgeTurbo;
messages::Image *badgeBroadcaster; chatterino::Image *badgeBroadcaster;
messages::Image *badgePremium; chatterino::Image *badgePremium;
messages::Image *badgeVerified; chatterino::Image *badgeVerified;
messages::Image *badgeSubscriber; chatterino::Image *badgeSubscriber;
messages::Image *badgeCollapsed; chatterino::Image *badgeCollapsed;
messages::Image *cheerBadge100000; chatterino::Image *cheerBadge100000;
messages::Image *cheerBadge10000; chatterino::Image *cheerBadge10000;
messages::Image *cheerBadge5000; chatterino::Image *cheerBadge5000;
messages::Image *cheerBadge1000; chatterino::Image *cheerBadge1000;
messages::Image *cheerBadge100; chatterino::Image *cheerBadge100;
messages::Image *cheerBadge1; chatterino::Image *cheerBadge1;
messages::Image *moderationmode_enabled; chatterino::Image *moderationmode_enabled;
messages::Image *moderationmode_disabled; chatterino::Image *moderationmode_disabled;
messages::Image *splitHeaderContext; chatterino::Image *splitHeaderContext;
std::map<std::string, messages::Image *> cheerBadges; std::map<std::string, chatterino::Image *> cheerBadges;
struct BadgeVersion { struct BadgeVersion {
BadgeVersion() = delete; BadgeVersion() = delete;
explicit BadgeVersion(QJsonObject &&root); explicit BadgeVersion(QJsonObject &&root);
messages::Image *badgeImage1x; chatterino::Image *badgeImage1x;
messages::Image *badgeImage2x; chatterino::Image *badgeImage2x;
messages::Image *badgeImage4x; chatterino::Image *badgeImage4x;
std::string description; std::string description;
std::string title; std::string title;
std::string clickAction; std::string clickAction;
@ -82,8 +82,8 @@ public:
bool dynamicBadgesLoaded = false; bool dynamicBadgesLoaded = false;
messages::Image *buttonBan; chatterino::Image *buttonBan;
messages::Image *buttonTimeout; chatterino::Image *buttonTimeout;
struct JSONCheermoteSet { struct JSONCheermoteSet {
QString prefix; QString prefix;
@ -102,7 +102,7 @@ public:
QString color; QString color;
// Background State Scale // Background State Scale
std::map<QString, std::map<QString, std::map<QString, messages::Image *>>> images; std::map<QString, std::map<QString, std::map<QString, chatterino::Image *>>> images;
}; };
std::vector<CheermoteTier> tiers; std::vector<CheermoteTier> tiers;
@ -113,8 +113,8 @@ public:
QColor color; QColor color;
int minBits; int minBits;
util::EmoteData emoteDataAnimated; EmoteData emoteDataAnimated;
util::EmoteData emoteDataStatic; EmoteData emoteDataStatic;
}; };
struct CheermoteSet { struct CheermoteSet {
@ -135,14 +135,14 @@ public:
// Chatterino badges // Chatterino badges
struct ChatterinoBadge { struct ChatterinoBadge {
ChatterinoBadge(const std::string &_tooltip, messages::Image *_image) ChatterinoBadge(const std::string &_tooltip, chatterino::Image *_image)
: tooltip(_tooltip) : tooltip(_tooltip)
, image(_image) , image(_image)
{ {
} }
std::string tooltip; std::string tooltip;
messages::Image *image; chatterino::Image *image;
}; };
// username // username

View file

@ -122,7 +122,7 @@ void SettingManager::saveSnapshot()
this->snapshot.reset(d); this->snapshot.reset(d);
debug::Log("hehe: {}", pajlada::Settings::SettingManager::stringify(*d)); Log("hehe: {}", pajlada::Settings::SettingManager::stringify(*d));
} }
void SettingManager::recallSnapshot() void SettingManager::recallSnapshot()
@ -136,14 +136,14 @@ void SettingManager::recallSnapshot()
for (const auto &weakSetting : _settings) { for (const auto &weakSetting : _settings) {
auto setting = weakSetting.lock(); auto setting = weakSetting.lock();
if (!setting) { if (!setting) {
debug::Log("Error stage 1 of loading"); Log("Error stage 1 of loading");
continue; continue;
} }
const char *path = setting->getPath().c_str(); const char *path = setting->getPath().c_str();
if (!snapshotObject.HasMember(path)) { if (!snapshotObject.HasMember(path)) {
debug::Log("Error stage 2 of loading"); Log("Error stage 2 of loading");
continue; continue;
} }

View file

@ -25,7 +25,7 @@ public:
~SettingManager() = delete; ~SettingManager() = delete;
messages::MessageElement::Flags getWordFlags(); chatterino::MessageElement::Flags getWordFlags();
bool isIgnoredEmote(const QString &emote); bool isIgnoredEmote(const QString &emote);
void initialize(); void initialize();
@ -142,7 +142,7 @@ private:
void updateModerationActions(); void updateModerationActions();
messages::MessageElement::Flags wordFlags = messages::MessageElement::Default; chatterino::MessageElement::Flags wordFlags = chatterino::MessageElement::Default;
pajlada::Settings::SettingListener wordFlagsListener; pajlada::Settings::SettingListener wordFlagsListener;
}; };

View file

@ -49,12 +49,12 @@ void UpdateManager::installUpdates()
box->setAttribute(Qt::WA_DeleteOnClose); box->setAttribute(Qt::WA_DeleteOnClose);
box->show(); box->show();
util::NetworkRequest req(this->updateUrl_); NetworkRequest req(this->updateUrl_);
req.setTimeout(600000); req.setTimeout(600000);
req.onError([this](int) -> bool { req.onError([this](int) -> bool {
this->setStatus_(DownloadFailed); this->setStatus_(DownloadFailed);
util::postToThread([] { postToThread([] {
QMessageBox *box = new QMessageBox(QMessageBox::Information, "Chatterino Update", QMessageBox *box = new QMessageBox(QMessageBox::Information, "Chatterino Update",
"Failed while trying to download the update."); "Failed while trying to download the update.");
box->setAttribute(Qt::WA_DeleteOnClose); box->setAttribute(Qt::WA_DeleteOnClose);
@ -65,7 +65,7 @@ void UpdateManager::installUpdates()
return true; return true;
}); });
req.get([this](QByteArray &object) { req.get([this](QByteArray &object) {
auto filename = util::combinePath(getApp()->paths->miscDirectory, "update.zip"); auto filename = combinePath(getApp()->paths->miscDirectory, "update.zip");
QFile file(filename); QFile file(filename);
file.open(QIODevice::Truncate | QIODevice::WriteOnly); file.open(QIODevice::Truncate | QIODevice::WriteOnly);
@ -75,7 +75,7 @@ void UpdateManager::installUpdates()
return false; return false;
} }
QProcess::startDetached(util::combinePath(QCoreApplication::applicationDirPath(), QProcess::startDetached(combinePath(QCoreApplication::applicationDirPath(),
"updater.1/ChatterinoUpdater.exe"), "updater.1/ChatterinoUpdater.exe"),
{filename, "restart"}); {filename, "restart"});
@ -92,7 +92,7 @@ void UpdateManager::checkForUpdates()
#ifdef Q_OS_WIN #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";
util::NetworkRequest req(url); NetworkRequest req(url);
req.setTimeout(30000); req.setTimeout(30000);
req.getJSON([this](QJsonObject &object) { req.getJSON([this](QJsonObject &object) {
QJsonValue version_val = object.value("version"); QJsonValue version_val = object.value("version");
@ -102,7 +102,7 @@ void UpdateManager::checkForUpdates()
this->setStatus_(SearchFailed); this->setStatus_(SearchFailed);
qDebug() << "error updating"; qDebug() << "error updating";
util::postToThread([] { postToThread([] {
QMessageBox *box = new QMessageBox( QMessageBox *box = new QMessageBox(
QMessageBox::Information, "Chatterino Update", 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 "
@ -119,7 +119,7 @@ void UpdateManager::checkForUpdates()
if (this->currentVersion_ != this->onlineVersion_) { if (this->currentVersion_ != this->onlineVersion_) {
this->setStatus_(UpdateAvailable); this->setStatus_(UpdateAvailable);
util::postToThread([this] { postToThread([this] {
QMessageBox *box = QMessageBox *box =
new QMessageBox(QMessageBox::Information, "Chatterino Update", new QMessageBox(QMessageBox::Information, "Chatterino Update",
"An update for chatterino is available.\n\nDo you " "An update for chatterino is available.\n\nDo you "
@ -150,7 +150,7 @@ void UpdateManager::setStatus_(UpdateStatus status)
{ {
if (this->status_ != status) { if (this->status_ != status) {
this->status_ = status; this->status_ = status;
util::postToThread([this, status] { this->statusUpdated.invoke(status); }); postToThread([this, status] { this->statusUpdated.invoke(status); });
} }
} }

View file

@ -21,21 +21,21 @@
namespace chatterino { namespace chatterino {
using SplitNode = widgets::SplitContainer::Node; using SplitNode = SplitContainer::Node;
using SplitDirection = widgets::SplitContainer::Direction; using SplitDirection = SplitContainer::Direction;
const int WindowManager::uiScaleMin = -5; const int WindowManager::uiScaleMin = -5;
const int WindowManager::uiScaleMax = 10; const int WindowManager::uiScaleMax = 10;
void WindowManager::showSettingsDialog() void WindowManager::showSettingsDialog()
{ {
QTimer::singleShot(80, [] { widgets::SettingsDialog::showDialog(); }); QTimer::singleShot(80, [] { SettingsDialog::showDialog(); });
} }
void WindowManager::showAccountSelectPopup(QPoint point) void WindowManager::showAccountSelectPopup(QPoint point)
{ {
// static QWidget *lastFocusedWidget = nullptr; // static QWidget *lastFocusedWidget = nullptr;
static widgets::AccountSwitchPopupWidget *w = new widgets::AccountSwitchPopupWidget(); static AccountSwitchPopupWidget *w = new AccountSwitchPopupWidget();
if (w->hasFocus()) { if (w->hasFocus()) {
w->hide(); w->hide();
@ -91,29 +91,29 @@ void WindowManager::repaintGifEmotes()
// } // }
//} //}
widgets::Window &WindowManager::getMainWindow() Window &WindowManager::getMainWindow()
{ {
util::assertInGuiThread(); assertInGuiThread();
return *this->mainWindow; return *this->mainWindow;
} }
widgets::Window &WindowManager::getSelectedWindow() Window &WindowManager::getSelectedWindow()
{ {
util::assertInGuiThread(); assertInGuiThread();
return *this->selectedWindow; return *this->selectedWindow;
} }
widgets::Window &WindowManager::createWindow(widgets::Window::WindowType type) Window &WindowManager::createWindow(Window::WindowType type)
{ {
util::assertInGuiThread(); assertInGuiThread();
auto *window = new widgets::Window(type); auto *window = new Window(type);
this->windows.push_back(window); this->windows.push_back(window);
window->show(); window->show();
if (type != widgets::Window::Main) { if (type != Window::Main) {
window->setAttribute(Qt::WA_DeleteOnClose); window->setAttribute(Qt::WA_DeleteOnClose);
QObject::connect(window, &QWidget::destroyed, [this, window] { QObject::connect(window, &QWidget::destroyed, [this, window] {
@ -134,21 +134,21 @@ int WindowManager::windowCount()
return this->windows.size(); return this->windows.size();
} }
widgets::Window *WindowManager::windowAt(int index) Window *WindowManager::windowAt(int index)
{ {
util::assertInGuiThread(); assertInGuiThread();
if (index < 0 || (size_t)index >= this->windows.size()) { if (index < 0 || (size_t)index >= this->windows.size()) {
return nullptr; return nullptr;
} }
debug::Log("getting window at bad index {}", index); Log("getting window at bad index {}", index);
return this->windows.at(index); return this->windows.at(index);
} }
void WindowManager::initialize() void WindowManager::initialize()
{ {
util::assertInGuiThread(); assertInGuiThread();
auto app = getApp(); auto app = getApp();
app->themes->repaintVisibleChatWidgets.connect([this] { this->repaintVisibleChatWidgets(); }); app->themes->repaintVisibleChatWidgets.connect([this] { this->repaintVisibleChatWidgets(); });
@ -169,16 +169,16 @@ void WindowManager::initialize()
// get type // get type
QString type_val = window_obj.value("type").toString(); QString type_val = window_obj.value("type").toString();
widgets::Window::WindowType type = Window::WindowType type =
type_val == "main" ? widgets::Window::Main : widgets::Window::Popup; type_val == "main" ? Window::Main : Window::Popup;
if (type == widgets::Window::Main && mainWindow != nullptr) { if (type == Window::Main && mainWindow != nullptr) {
type = widgets::Window::Popup; type = Window::Popup;
} }
widgets::Window &window = createWindow(type); Window &window = createWindow(type);
if (type == widgets::Window::Main) { if (type == Window::Main) {
mainWindow = &window; mainWindow = &window;
} }
@ -197,7 +197,7 @@ void WindowManager::initialize()
// load tabs // load tabs
QJsonArray tabs = window_obj.value("tabs").toArray(); QJsonArray tabs = window_obj.value("tabs").toArray();
for (QJsonValue tab_val : tabs) { for (QJsonValue tab_val : tabs) {
widgets::SplitContainer *page = window.getNotebook().addPage(false); SplitContainer *page = window.getNotebook().addPage(false);
QJsonObject tab_obj = tab_val.toObject(); QJsonObject tab_obj = tab_val.toObject();
@ -225,7 +225,7 @@ void WindowManager::initialize()
int colNr = 0; int colNr = 0;
for (QJsonValue column_val : tab_obj.value("splits").toArray()) { for (QJsonValue column_val : tab_obj.value("splits").toArray()) {
for (QJsonValue split_val : column_val.toArray()) { for (QJsonValue split_val : column_val.toArray()) {
widgets::Split *split = new widgets::Split(page); Split *split = new Split(page);
QJsonObject split_obj = split_val.toObject(); QJsonObject split_obj = split_val.toObject();
split->setChannel(decodeChannel(split_obj)); split->setChannel(decodeChannel(split_obj));
@ -238,7 +238,7 @@ void WindowManager::initialize()
} }
if (mainWindow == nullptr) { if (mainWindow == nullptr) {
mainWindow = &createWindow(widgets::Window::Main); mainWindow = &createWindow(Window::Main);
mainWindow->getNotebook().addPage(true); mainWindow->getNotebook().addPage(true);
} }
@ -247,22 +247,22 @@ void WindowManager::initialize()
void WindowManager::save() void WindowManager::save()
{ {
util::assertInGuiThread(); assertInGuiThread();
auto app = getApp(); auto app = getApp();
QJsonDocument document; QJsonDocument document;
// "serialize" // "serialize"
QJsonArray window_arr; QJsonArray window_arr;
for (widgets::Window *window : this->windows) { for (Window *window : this->windows) {
QJsonObject window_obj; QJsonObject window_obj;
// window type // window type
switch (window->getType()) { switch (window->getType()) {
case widgets::Window::Main: case Window::Main:
window_obj.insert("type", "main"); window_obj.insert("type", "main");
break; break;
case widgets::Window::Popup: case Window::Popup:
window_obj.insert("type", "popup"); window_obj.insert("type", "popup");
break; break;
} }
@ -278,8 +278,8 @@ void WindowManager::save()
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; QJsonObject tab_obj;
widgets::SplitContainer *tab = SplitContainer *tab =
dynamic_cast<widgets::SplitContainer *>(window->getNotebook().getPageAt(tab_i)); dynamic_cast<SplitContainer *>(window->getNotebook().getPageAt(tab_i));
assert(tab != nullptr); assert(tab != nullptr);
// custom tab title // custom tab title
@ -355,7 +355,7 @@ void WindowManager::encodeNodeRecusively(SplitNode *node, QJsonObject &obj)
void WindowManager::encodeChannel(IndirectChannel channel, QJsonObject &obj) void WindowManager::encodeChannel(IndirectChannel channel, QJsonObject &obj)
{ {
util::assertInGuiThread(); assertInGuiThread();
switch (channel.getType()) { switch (channel.getType()) {
case Channel::Twitch: { case Channel::Twitch: {
@ -376,7 +376,7 @@ void WindowManager::encodeChannel(IndirectChannel channel, QJsonObject &obj)
IndirectChannel WindowManager::decodeChannel(const QJsonObject &obj) IndirectChannel WindowManager::decodeChannel(const QJsonObject &obj)
{ {
util::assertInGuiThread(); assertInGuiThread();
auto app = getApp(); auto app = getApp();
@ -396,9 +396,9 @@ IndirectChannel WindowManager::decodeChannel(const QJsonObject &obj)
void WindowManager::closeAll() void WindowManager::closeAll()
{ {
util::assertInGuiThread(); assertInGuiThread();
for (widgets::Window *window : windows) { for (Window *window : windows) {
window->close(); window->close();
} }
} }
@ -415,7 +415,7 @@ void WindowManager::incGeneration()
int WindowManager::clampUiScale(int scale) int WindowManager::clampUiScale(int scale)
{ {
return util::clamp(scale, uiScaleMin, uiScaleMax); return clamp(scale, uiScaleMin, uiScaleMax);
} }
float WindowManager::getUiScaleValue() float WindowManager::getUiScaleValue()

View file

@ -21,12 +21,12 @@ public:
void repaintGifEmotes(); void repaintGifEmotes();
// void updateAll(); // void updateAll();
widgets::Window &getMainWindow(); Window &getMainWindow();
widgets::Window &getSelectedWindow(); Window &getSelectedWindow();
widgets::Window &createWindow(widgets::Window::WindowType type); Window &createWindow(Window::WindowType type);
int windowCount(); int windowCount();
widgets::Window *windowAt(int index); Window *windowAt(int index);
void save(); void save();
void initialize(); void initialize();
@ -49,12 +49,12 @@ private:
std::atomic<int> generation{0}; std::atomic<int> generation{0};
std::vector<widgets::Window *> windows; std::vector<Window *> windows;
widgets::Window *mainWindow = nullptr; Window *mainWindow = nullptr;
widgets::Window *selectedWindow = nullptr; Window *selectedWindow = nullptr;
void encodeNodeRecusively(widgets::SplitContainer::Node *node, QJsonObject &obj); void encodeNodeRecusively(SplitContainer::Node *node, QJsonObject &obj);
public: public:
static void encodeChannel(IndirectChannel channel, QJsonObject &obj); static void encodeChannel(IndirectChannel channel, QJsonObject &obj);

View file

@ -63,13 +63,13 @@ void LoggingChannel::openLogFile()
QString directory = this->baseDirectory + QDir::separator() + this->subDirectory; QString directory = this->baseDirectory + QDir::separator() + this->subDirectory;
if (!QDir().mkpath(directory)) { if (!QDir().mkpath(directory)) {
debug::Log("Unable to create logging path"); Log("Unable to create logging path");
return; return;
} }
// Open file handle to log file of current date // Open file handle to log file of current date
QString fileName = directory + QDir::separator() + baseFileName; QString fileName = directory + QDir::separator() + baseFileName;
debug::Log("Logging to {}", fileName); Log("Logging to {}", fileName);
this->fileHandle.setFileName(fileName); this->fileHandle.setFileName(fileName);
this->fileHandle.open(QIODevice::Append); this->fileHandle.open(QIODevice::Append);
@ -77,7 +77,7 @@ void LoggingChannel::openLogFile()
this->appendLine(this->generateOpeningString(now)); this->appendLine(this->generateOpeningString(now));
} }
void LoggingChannel::addMessage(std::shared_ptr<messages::Message> message) void LoggingChannel::addMessage(std::shared_ptr<chatterino::Message> message)
{ {
QDateTime now = QDateTime::currentDateTime(); QDateTime now = QDateTime::currentDateTime();

View file

@ -17,7 +17,7 @@ class LoggingChannel : boost::noncopyable
public: public:
~LoggingChannel(); ~LoggingChannel();
void addMessage(std::shared_ptr<messages::Message> message); void addMessage(std::shared_ptr<chatterino::Message> message);
private: private:
void openLogFile(); void openLogFile();

View file

@ -4,7 +4,7 @@
namespace chatterino { namespace chatterino {
ModerationAction::ModerationAction(messages::Image *_image, const QString &_action) ModerationAction::ModerationAction(chatterino::Image *_image, const QString &_action)
: _isImage(true) : _isImage(true)
, image(_image) , image(_image)
, action(_action) , action(_action)
@ -26,7 +26,7 @@ bool ModerationAction::isImage() const
return this->_isImage; return this->_isImage;
} }
messages::Image *ModerationAction::getImage() const chatterino::Image *ModerationAction::getImage() const
{ {
return this->image; return this->image;
} }

View file

@ -9,18 +9,18 @@ class Image;
class ModerationAction class ModerationAction
{ {
public: public:
ModerationAction(messages::Image *image, const QString &action); ModerationAction(chatterino::Image *image, const QString &action);
ModerationAction(const QString &line1, const QString &line2, const QString &action); ModerationAction(const QString &line1, const QString &line2, const QString &action);
bool isImage() const; bool isImage() const;
messages::Image *getImage() const; chatterino::Image *getImage() const;
const QString &getLine1() const; const QString &getLine1() const;
const QString &getLine2() const; const QString &getLine2() const;
const QString &getAction() const; const QString &getAction() const;
private: private:
bool _isImage; bool _isImage;
messages::Image *image; chatterino::Image *image;
QString line1; QString line1;
QString line2; QString line2;
QString action; QString action;

View file

@ -167,7 +167,7 @@ void Start(const QString &channel)
if (preferredQuality == "choose") { if (preferredQuality == "choose") {
GetStreamQualities(channelURL, [=](QStringList qualityOptions) { GetStreamQualities(channelURL, [=](QStringList qualityOptions) {
widgets::QualityPopup::showDialog(channel, qualityOptions); QualityPopup::showDialog(channel, qualityOptions);
}); });
return; return;

View file

@ -32,7 +32,7 @@ AttachedWindow::AttachedWindow(void *_target, int _yOffset)
split->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::MinimumExpanding); split->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::MinimumExpanding);
layout->addWidget(split); layout->addWidget(split);
util::DebugCount::increase("attached window"); DebugCount::increase("attached window");
} }
AttachedWindow::~AttachedWindow() AttachedWindow::~AttachedWindow()
@ -44,7 +44,7 @@ AttachedWindow::~AttachedWindow()
} }
} }
util::DebugCount::decrease("attached window"); DebugCount::decrease("attached window");
} }
AttachedWindow *AttachedWindow::get(void *target, const GetArgs &args) AttachedWindow *AttachedWindow::get(void *target, const GetArgs &args)
@ -179,7 +179,7 @@ void AttachedWindow::updateWindowRect_(void *_attachedPtr)
SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE); SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
float scale = 1.f; float scale = 1.f;
if (auto dpi = util::getWindowDpi(attached)) { if (auto dpi = getWindowDpi(attached)) {
scale = dpi.get() / 96.f; scale = dpi.get() / 96.f;
// for (auto w : this->ui_.split->findChildren<BaseWidget *>()) { // for (auto w : this->ui_.split->findChildren<BaseWidget *>()) {

View file

@ -41,7 +41,7 @@ protected:
void setScale(float value); void setScale(float value);
singletons::ThemeManager *themeManager; chatterino::ThemeManager *themeManager;
private: private:
void init(); void init();

View file

@ -8,10 +8,10 @@
#include "util/NativeEventHelper.hpp" #include "util/NativeEventHelper.hpp"
#include "util/PostToThread.hpp" #include "util/PostToThread.hpp"
#include "util/WindowsHelper.hpp" #include "util/WindowsHelper.hpp"
#include "widgets/helper/RippleEffectLabel.hpp"
#include "widgets/helper/Shortcut.hpp"
#include "widgets/Label.hpp" #include "widgets/Label.hpp"
#include "widgets/TooltipWidget.hpp" #include "widgets/TooltipWidget.hpp"
#include "widgets/helper/RippleEffectLabel.hpp"
#include "widgets/helper/Shortcut.hpp"
#include <QApplication> #include <QApplication>
#include <QDebug> #include <QDebug>
@ -60,7 +60,7 @@ BaseWindow::BaseWindow(QWidget *parent, Flags _flags)
this->connections_.managedConnect( this->connections_.managedConnect(
getApp()->settings->uiScale.getValueChangedSignal(), getApp()->settings->uiScale.getValueChangedSignal(),
[this](auto, auto) { util::postToThread([this] { this->updateScale(); }); }); [this](auto, auto) { postToThread([this] { this->updateScale(); }); });
this->updateScale(); this->updateScale();
@ -147,7 +147,7 @@ void BaseWindow::init()
} }
// DPI // DPI
// auto dpi = util::getWindowDpi(this->winId()); // auto dpi = getWindowDpi(this->winId());
// if (dpi) { // if (dpi) {
// this->scale = dpi.value() / 96.f; // this->scale = dpi.value() / 96.f;
@ -171,6 +171,7 @@ void BaseWindow::init()
// this->setWindowFlag(Qt::WindowStaysOnTopHint); // this->setWindowFlag(Qt::WindowStaysOnTopHint);
// } // }
#endif #endif
}
void BaseWindow::setStayInScreenRect(bool value) void BaseWindow::setStayInScreenRect(bool value)
{ {
@ -249,10 +250,10 @@ void BaseWindow::wheelEvent(QWheelEvent *event)
if (event->modifiers() & Qt::ControlModifier) { if (event->modifiers() & Qt::ControlModifier) {
if (event->delta() > 0) { if (event->delta() > 0) {
getApp()->settings->uiScale.setValue(singletons::WindowManager::clampUiScale( getApp()->settings->uiScale.setValue(chatterino::WindowManager::clampUiScale(
getApp()->settings->uiScale.getValue() + 1)); getApp()->settings->uiScale.getValue() + 1));
} else { } else {
getApp()->settings->uiScale.setValue(singletons::WindowManager::clampUiScale( getApp()->settings->uiScale.setValue(chatterino::WindowManager::clampUiScale(
getApp()->settings->uiScale.getValue() - 1)); getApp()->settings->uiScale.getValue() - 1));
} }
} }
@ -278,7 +279,7 @@ void BaseWindow::mousePressEvent(QMouseEvent *event)
}; };
if (!recursiveCheckMouseTracking(widget)) { if (!recursiveCheckMouseTracking(widget)) {
debug::Log("Start moving"); Log("Start moving");
this->moving = true; this->moving = true;
} }
} }
@ -293,7 +294,7 @@ void BaseWindow::mouseReleaseEvent(QMouseEvent *event)
#ifndef Q_OS_WIN #ifndef Q_OS_WIN
if (this->flags_ & FramelessDraggable) { if (this->flags_ & FramelessDraggable) {
if (this->moving) { if (this->moving) {
debug::Log("Stop moving"); Log("Stop moving");
this->moving = false; this->moving = false;
} }
} }
@ -438,7 +439,7 @@ bool BaseWindow::nativeEvent(const QByteArray &eventType, void *message, long *r
return true; return true;
} }
case WM_SHOWWINDOW: { case WM_SHOWWINDOW: {
if (auto dpi = util::getWindowDpi(msg->hwnd)) { if (auto dpi = getWindowDpi(msg->hwnd)) {
this->nativeScale_ = dpi.get() / 96.f; this->nativeScale_ = dpi.get() / 96.f;
this->updateScale(); this->updateScale();
} }

View file

@ -52,7 +52,7 @@ void Scrollbar::unpauseHighlights()
this->highlightsPaused_ = false; this->highlightsPaused_ = false;
} }
messages::LimitedQueueSnapshot<ScrollbarHighlight> Scrollbar::getHighlightSnapshot() chatterino::LimitedQueueSnapshot<ScrollbarHighlight> Scrollbar::getHighlightSnapshot()
{ {
if (!this->highlightsPaused_) { if (!this->highlightsPaused_) {
this->highlightSnapshot_ = this->highlights_.getSnapshot(); this->highlightSnapshot_ = this->highlights_.getSnapshot();

View file

@ -68,10 +68,10 @@ private:
QPropertyAnimation currentValueAnimation_; QPropertyAnimation currentValueAnimation_;
messages::LimitedQueue<ScrollbarHighlight> highlights_; chatterino::LimitedQueue<ScrollbarHighlight> highlights_;
bool highlightsPaused_{false}; bool highlightsPaused_{false};
messages::LimitedQueueSnapshot<ScrollbarHighlight> highlightSnapshot_; chatterino::LimitedQueueSnapshot<ScrollbarHighlight> highlightSnapshot_;
messages::LimitedQueueSnapshot<ScrollbarHighlight> getHighlightSnapshot(); chatterino::LimitedQueueSnapshot<ScrollbarHighlight> getHighlightSnapshot();
bool atBottom_{false}; bool atBottom_{false};

View file

@ -13,7 +13,7 @@ namespace chatterino {
StreamView::StreamView(ChannelPtr channel, const QUrl &url) StreamView::StreamView(ChannelPtr channel, const QUrl &url)
{ {
util::LayoutCreator<StreamView> layoutCreator(this); LayoutCreator<StreamView> layoutCreator(this);
#ifdef USEWEBENGINE #ifdef USEWEBENGINE
auto web = layoutCreator.emplace<QWebEngineView>(this).assign(&this->stream); auto web = layoutCreator.emplace<QWebEngineView>(this).assign(&this->stream);

View file

@ -77,7 +77,7 @@ void TooltipWidget::updateFont()
auto app = getApp(); auto app = getApp();
this->setFont( this->setFont(
app->fonts->getFont(singletons::FontManager::Type::ChatMediumSmall, this->getScale())); app->fonts->getFont(chatterino::FontManager::Type::ChatMediumSmall, this->getScale()));
} }
void TooltipWidget::setText(QString text) void TooltipWidget::setText(QString text)

View file

@ -100,7 +100,7 @@ Window::Window(WindowType _type)
auto s = new QShortcut(QKeySequence::ZoomIn, this); auto s = new QShortcut(QKeySequence::ZoomIn, this);
s->setContext(Qt::WindowShortcut); s->setContext(Qt::WindowShortcut);
QObject::connect(s, &QShortcut::activated, this, [] { QObject::connect(s, &QShortcut::activated, this, [] {
getApp()->settings->uiScale.setValue(singletons::WindowManager::clampUiScale( getApp()->settings->uiScale.setValue(chatterino::WindowManager::clampUiScale(
getApp()->settings->uiScale.getValue() + 1)); getApp()->settings->uiScale.getValue() + 1));
}); });
} }
@ -108,7 +108,7 @@ Window::Window(WindowType _type)
auto s = new QShortcut(QKeySequence::ZoomOut, this); auto s = new QShortcut(QKeySequence::ZoomOut, this);
s->setContext(Qt::WindowShortcut); s->setContext(Qt::WindowShortcut);
QObject::connect(s, &QShortcut::activated, this, [] { QObject::connect(s, &QShortcut::activated, this, [] {
getApp()->settings->uiScale.setValue(singletons::WindowManager::clampUiScale( getApp()->settings->uiScale.setValue(chatterino::WindowManager::clampUiScale(
getApp()->settings->uiScale.getValue() - 1)); getApp()->settings->uiScale.getValue() - 1));
}); });
} }

View file

@ -56,9 +56,9 @@ void EmotePopup::loadChannel(ChannelPtr _channel)
ChannelPtr emoteChannel(new Channel("", Channel::None)); ChannelPtr emoteChannel(new Channel("", Channel::None));
auto addEmotes = [&](util::EmoteMap &map, const QString &title, const QString &emoteDesc) { auto addEmotes = [&](EmoteMap &map, const QString &title, const QString &emoteDesc) {
// TITLE // TITLE
messages::MessageBuilder builder1; chatterino::MessageBuilder builder1;
builder1.append(new TextElement(title, MessageElement::Text)); builder1.append(new TextElement(title, MessageElement::Text));
@ -66,11 +66,11 @@ void EmotePopup::loadChannel(ChannelPtr _channel)
emoteChannel->addMessage(builder1.getMessage()); emoteChannel->addMessage(builder1.getMessage());
// EMOTES // EMOTES
messages::MessageBuilder builder2; chatterino::MessageBuilder builder2;
builder2.getMessage()->flags |= Message::Centered; builder2.getMessage()->flags |= Message::Centered;
builder2.getMessage()->flags |= Message::DisableCompactEmotes; builder2.getMessage()->flags |= Message::DisableCompactEmotes;
map.each([&](const QString &key, const util::EmoteData &value) { map.each([&](const QString &key, const EmoteData &value) {
builder2.append((new EmoteElement(value, MessageElement::Flags::AlwaysShow)) builder2.append((new EmoteElement(value, MessageElement::Flags::AlwaysShow))
->setLink(Link(Link::InsertText, key))); ->setLink(Link(Link::InsertText, key)));
}); });
@ -86,7 +86,7 @@ void EmotePopup::loadChannel(ChannelPtr _channel)
// fix this pile of garbage // fix this pile of garbage
for (const auto &set : app->emotes->twitch.emotes[userID].emoteSets) { for (const auto &set : app->emotes->twitch.emotes[userID].emoteSets) {
// TITLE // TITLE
messages::MessageBuilder builder1; chatterino::MessageBuilder builder1;
QString setText; QString setText;
if (set->text.isEmpty()) { if (set->text.isEmpty()) {
@ -105,12 +105,12 @@ void EmotePopup::loadChannel(ChannelPtr _channel)
emoteChannel->addMessage(builder1.getMessage()); emoteChannel->addMessage(builder1.getMessage());
// EMOTES // EMOTES
messages::MessageBuilder builder2; chatterino::MessageBuilder builder2;
builder2.getMessage()->flags |= Message::Centered; builder2.getMessage()->flags |= Message::Centered;
builder2.getMessage()->flags |= Message::DisableCompactEmotes; builder2.getMessage()->flags |= Message::DisableCompactEmotes;
for (const auto &emote : set->emotes) { for (const auto &emote : set->emotes) {
[&](const QString &key, const util::EmoteData &value) { [&](const QString &key, const EmoteData &value) {
builder2.append((new EmoteElement(value, MessageElement::Flags::AlwaysShow)) builder2.append((new EmoteElement(value, MessageElement::Flags::AlwaysShow))
->setLink(Link(Link::InsertText, key))); ->setLink(Link(Link::InsertText, key)));
}(emote.code, app->emotes->twitch.getEmoteById(emote.id, emote.code)); }(emote.code, app->emotes->twitch.getEmoteById(emote.id, emote.code));
@ -137,14 +137,14 @@ void EmotePopup::loadEmojis()
ChannelPtr emojiChannel(new Channel("", Channel::None)); ChannelPtr emojiChannel(new Channel("", Channel::None));
// title // title
messages::MessageBuilder builder1; chatterino::MessageBuilder builder1;
builder1.append(new TextElement("emojis", MessageElement::Text)); builder1.append(new TextElement("emojis", MessageElement::Text));
builder1.getMessage()->flags |= Message::Centered; builder1.getMessage()->flags |= Message::Centered;
emojiChannel->addMessage(builder1.getMessage()); emojiChannel->addMessage(builder1.getMessage());
// emojis // emojis
messages::MessageBuilder builder; chatterino::MessageBuilder builder;
builder.getMessage()->flags |= Message::Centered; builder.getMessage()->flags |= Message::Centered;
builder.getMessage()->flags |= Message::DisableCompactEmotes; builder.getMessage()->flags |= Message::DisableCompactEmotes;

View file

@ -16,7 +16,7 @@ public:
void loadChannel(ChannelPtr channel); void loadChannel(ChannelPtr channel);
void loadEmojis(); void loadEmojis();
pajlada::Signals::Signal<messages::Link> linkClicked; pajlada::Signals::Signal<chatterino::Link> linkClicked;
private: private:
ChannelView *viewEmotes; ChannelView *viewEmotes;

View file

@ -16,9 +16,9 @@ LastRunCrashDialog::LastRunCrashDialog()
this->setWindowFlag(Qt::WindowContextHelpButtonHint, false); this->setWindowFlag(Qt::WindowContextHelpButtonHint, false);
this->setWindowTitle("Chatterino"); this->setWindowTitle("Chatterino");
auto &updateManager = singletons::UpdateManager::getInstance(); auto &updateManager = chatterino::UpdateManager::getInstance();
auto layout = util::LayoutCreator<LastRunCrashDialog>(this).setLayoutType<QVBoxLayout>(); auto layout = LayoutCreator<LastRunCrashDialog>(this).setLayoutType<QVBoxLayout>();
layout.emplace<QLabel>( layout.emplace<QLabel>(
"The application wasn't terminated properly the last time it was executed."); "The application wasn't terminated properly the last time it was executed.");
@ -31,7 +31,7 @@ LastRunCrashDialog::LastRunCrashDialog()
// auto *installUpdateButton = buttons->addButton("Install Update", // auto *installUpdateButton = buttons->addButton("Install Update",
// QDialogButtonBox::NoRole); installUpdateButton->setEnabled(false); // QDialogButtonBox::NoRole); installUpdateButton->setEnabled(false);
// QObject::connect(installUpdateButton, &QPushButton::clicked, [this, update]() mutable { // QObject::connect(installUpdateButton, &QPushButton::clicked, [this, update]() mutable {
// auto &updateManager = singletons::UpdateManager::getInstance(); // auto &updateManager = chatterino::UpdateManager::getInstance();
// updateManager.installUpdates(); // updateManager.installUpdates();
// this->setEnabled(false); // this->setEnabled(false);
@ -43,36 +43,36 @@ LastRunCrashDialog::LastRunCrashDialog()
// Updates // Updates
// auto updateUpdateLabel = [update]() mutable { // auto updateUpdateLabel = [update]() mutable {
// auto &updateManager = singletons::UpdateManager::getInstance(); // auto &updateManager = chatterino::UpdateManager::getInstance();
// switch (updateManager.getStatus()) { // switch (updateManager.getStatus()) {
// case singletons::UpdateManager::None: { // case chatterino::UpdateManager::None: {
// update->setText("Not checking for updates."); // update->setText("Not checking for updates.");
// } break; // } break;
// case singletons::UpdateManager::Searching: { // case chatterino::UpdateManager::Searching: {
// update->setText("Checking for updates..."); // update->setText("Checking for updates...");
// } break; // } break;
// case singletons::UpdateManager::UpdateAvailable: { // case chatterino::UpdateManager::UpdateAvailable: {
// update->setText("Update available."); // update->setText("Update available.");
// } break; // } break;
// case singletons::UpdateManager::NoUpdateAvailable: { // case chatterino::UpdateManager::NoUpdateAvailable: {
// update->setText("No update abailable."); // update->setText("No update abailable.");
// } break; // } break;
// case singletons::UpdateManager::SearchFailed: { // case chatterino::UpdateManager::SearchFailed: {
// update->setText("Error while searching for update.\nEither the update service // update->setText("Error while searching for update.\nEither the update service
// is " // is "
// "temporarily down or there is an issue with your // "temporarily down or there is an issue with your
// installation."); // installation.");
// } break; // } break;
// case singletons::UpdateManager::Downloading: { // case chatterino::UpdateManager::Downloading: {
// update->setText( // update->setText(
// "Downloading the update. Chatterino will close once the download is // "Downloading the update. Chatterino will close once the download is
// done."); // done.");
// } break; // } break;
// case singletons::UpdateManager::DownloadFailed: { // case chatterino::UpdateManager::DownloadFailed: {
// update->setText("Download failed."); // update->setText("Download failed.");
// } break; // } break;
// case singletons::UpdateManager::WriteFileFailed: { // case chatterino::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; // } break;
// } // }
@ -80,7 +80,7 @@ LastRunCrashDialog::LastRunCrashDialog()
// updateUpdateLabel(); // updateUpdateLabel();
// this->managedConnect(updateManager.statusUpdated, [updateUpdateLabel](auto) mutable { // this->managedConnect(updateManager.statusUpdated, [updateUpdateLabel](auto) mutable {
// util::postToThread([updateUpdateLabel]() mutable { updateUpdateLabel(); }); // postToThread([updateUpdateLabel]() mutable { updateUpdateLabel(); });
// }); // });
} }

View file

@ -172,7 +172,7 @@ AdvancedLoginWidget::AdvancedLoginWidget()
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, [=]() { connect(&this->ui.buttonLowerRow.fillInUserIDButton, &QPushButton::clicked, [=]() {
util::twitch::getUserID(this->ui.usernameInput.text(), this, [=](const QString &userID) { getUserID(this->ui.usernameInput.text(), this, [=](const QString &userID) {
this->ui.userIDInput.setText(userID); // this->ui.userIDInput.setText(userID); //
}); });
}); });

View file

@ -38,7 +38,7 @@ void NotificationPopup::updatePosition()
} }
} }
void NotificationPopup::addMessage(messages::MessagePtr msg) void NotificationPopup::addMessage(chatterino::MessagePtr msg)
{ {
this->channel->addMessage(msg); this->channel->addMessage(msg);

View file

@ -14,7 +14,7 @@ public:
enum Location { TopLeft, TopRight, BottomLeft, BottomRight }; enum Location { TopLeft, TopRight, BottomLeft, BottomRight };
NotificationPopup(); NotificationPopup();
void addMessage(messages::MessagePtr msg); void addMessage(chatterino::MessagePtr msg);
void updatePosition(); void updatePosition();
private: private:

Some files were not shown because too many files have changed in this diff Show more