changed CommandManager to CommandController

This commit is contained in:
fourtf
2018-04-30 23:30:05 +02:00
parent b907bf5639
commit 4c3f0921e2
17 changed files with 524 additions and 398 deletions
+34
View File
@@ -0,0 +1,34 @@
#include "command.hpp"
namespace chatterino {
namespace controllers {
namespace commands {
// command
Command::Command(const QString &_text)
{
int index = _text.indexOf(' ');
if (index == -1) {
this->name = _text;
return;
}
this->name = _text.mid(0, index);
this->func = _text.mid(index + 1);
}
Command::Command(const QString &_name, const QString &_func)
: name(_name)
, func(_func)
{
}
QString Command::toString() const
{
return this->name + " " + this->func;
}
} // namespace commands
} // namespace controllers
} // namespace chatterino
+22
View File
@@ -0,0 +1,22 @@
#pragma once
#include <QString>
namespace chatterino {
namespace controllers {
namespace commands {
struct Command {
QString name;
QString func;
Command() = default;
explicit Command(const QString &text);
Command(const QString &name, const QString &func);
QString toString() const;
};
} // namespace commands
} // namespace controllers
} // namespace chatterino
@@ -0,0 +1,245 @@
#include "commandcontroller.hpp"
#include "application.hpp"
#include "controllers/commands/command.hpp"
#include "controllers/commands/commandmodel.hpp"
#include "messages/messagebuilder.hpp"
#include "providers/twitch/twitchchannel.hpp"
#include "providers/twitch/twitchserver.hpp"
#include "singletons/accountmanager.hpp"
#include "singletons/pathmanager.hpp"
#include "util/signalvector2.hpp"
#include <QApplication>
#include <QFile>
#include <QRegularExpression>
using namespace chatterino::providers::twitch;
namespace chatterino {
namespace controllers {
namespace commands {
CommandController::CommandController()
{
auto addFirstMatchToMap = [this](auto args) {
this->commandsMap.remove(args.item.name);
for (const Command &cmd : this->items.getVector()) {
if (cmd.name == args.item.name) {
this->commandsMap[cmd.name] = cmd;
break;
}
}
};
this->items.itemInserted.connect(addFirstMatchToMap);
this->items.itemRemoved.connect(addFirstMatchToMap);
}
void CommandController::load()
{
auto app = getApp();
this->filePath = app->paths->customFolderPath + "/Commands.txt";
QFile textFile(this->filePath);
if (!textFile.open(QIODevice::ReadOnly)) {
// No commands file created yet
return;
}
QList<QByteArray> test = textFile.readAll().split('\n');
for (const auto &command : test) {
if (command.isEmpty()) {
continue;
}
this->items.appendItem(Command(command));
}
textFile.close();
}
void CommandController::save()
{
QFile textFile(this->filePath);
if (!textFile.open(QIODevice::WriteOnly)) {
debug::Log("[CommandController::saveCommands] Unable to open {} for writing",
this->filePath);
return;
}
for (const Command &cmd : this->items.getVector()) {
textFile.write((cmd.toString() + "\n").toUtf8());
}
textFile.close();
}
CommandModel *CommandController::createModel(QObject *parent)
{
CommandModel *model = new CommandModel(parent);
model->init(&this->items);
return model;
}
QString CommandController::execCommand(const QString &text, ChannelPtr channel, bool dryRun)
{
QStringList words = text.split(' ', QString::SkipEmptyParts);
Command command;
{
std::lock_guard<std::mutex> lock(this->mutex);
if (words.length() == 0) {
return text;
}
QString commandName = words[0];
// check if default command exists
auto *twitchChannel = dynamic_cast<TwitchChannel *>(channel.get());
if (!dryRun && twitchChannel != nullptr) {
if (commandName == "/debug-args") {
QString msg = QApplication::instance()->arguments().join(' ');
channel->addMessage(messages::Message::createSystemMessage(msg));
return "";
} else if (commandName == "/uptime") {
const auto &streamStatus = twitchChannel->GetStreamStatus();
QString messageText =
streamStatus.live ? streamStatus.uptime : "Channel is not live.";
channel->addMessage(messages::Message::createSystemMessage(messageText));
return "";
} else if (commandName == "/ignore" && words.size() >= 2) {
// fourtf: ignore user
// QString messageText;
// if (IrcManager::getInstance().tryAddIgnoredUser(words.at(1),
// messageText)) {
// messageText = "Ignored user \"" + words.at(1) + "\".";
// }
// channel->addMessage(messages::Message::createSystemMessage(messageText));
return "";
} else if (commandName == "/unignore") {
// fourtf: ignore user
// QString messageText;
// if (IrcManager::getInstance().tryRemoveIgnoredUser(words.at(1),
// messageText)) {
// messageText = "Ignored user \"" + words.at(1) + "\".";
// }
// channel->addMessage(messages::Message::createSystemMessage(messageText));
return "";
} else if (commandName == "/w") {
if (words.length() <= 2) {
return "";
}
auto app = getApp();
messages::MessageBuilder b;
b.emplace<messages::TextElement>(app->accounts->Twitch.getCurrent()->getUserName(),
messages::MessageElement::Text);
b.emplace<messages::TextElement>("->", messages::MessageElement::Text);
b.emplace<messages::TextElement>(words[1], messages::MessageElement::Text);
QString rest = "";
for (int i = 2; i < words.length(); i++) {
rest += words[i];
}
b.emplace<messages::TextElement>(rest, messages::MessageElement::Text);
app->twitch.server->whispersChannel->addMessage(b.getMessage());
}
}
// check if custom command exists
auto it = this->commandsMap.find(commandName);
if (it == this->commandsMap.end()) {
return text;
}
command = it.value();
}
return this->execCustomCommand(words, command);
}
QString CommandController::execCustomCommand(const QStringList &words, const Command &command)
{
QString result;
static QRegularExpression parseCommand("(^|[^{])({{)*{(\\d+\\+?)}");
int lastCaptureEnd = 0;
auto globalMatch = parseCommand.globalMatch(command.func);
int matchOffset = 0;
while (true) {
QRegularExpressionMatch match = parseCommand.match(command.func, matchOffset);
if (!match.hasMatch()) {
break;
}
result += command.func.mid(lastCaptureEnd, match.capturedStart() - lastCaptureEnd + 1);
lastCaptureEnd = match.capturedEnd();
matchOffset = lastCaptureEnd - 1;
QString wordIndexMatch = match.captured(3);
bool plus = wordIndexMatch.at(wordIndexMatch.size() - 1) == '+';
wordIndexMatch = wordIndexMatch.replace("+", "");
bool ok;
int wordIndex = wordIndexMatch.replace("=", "").toInt(&ok);
if (!ok || wordIndex == 0) {
result += "{" + match.captured(3) + "}";
continue;
}
if (words.length() <= wordIndex) {
continue;
}
if (plus) {
bool first = true;
for (int i = wordIndex; i < words.length(); i++) {
if (!first) {
result += " ";
}
result += words[i];
first = false;
}
} else {
result += words[wordIndex];
}
}
result += command.func.mid(lastCaptureEnd);
if (result.size() > 0 && result.at(0) == '{') {
result = result.mid(1);
}
return result.replace("{{", "{");
}
} // namespace commands
} // namespace controllers
} // namespace chatterino
@@ -0,0 +1,42 @@
#pragma once
#include <QMap>
#include <memory>
#include "controllers/commands/command.hpp"
#include "util/signalvector2.hpp"
namespace chatterino {
class Channel;
namespace controllers {
namespace commands {
class CommandModel;
class CommandController
{
public:
CommandController();
QString execCommand(const QString &text, std::shared_ptr<Channel> channel, bool dryRun);
void load();
void save();
CommandModel *createModel(QObject *parent);
util::UnsortedSignalVector<Command> items;
private:
QMap<QString, Command> commandsMap;
std::mutex mutex;
QString filePath;
QString execCustomCommand(const QStringList &words, const Command &command);
};
} // namespace commands
} // namespace controllers
} // namespace chatterino
+42
View File
@@ -0,0 +1,42 @@
#include "commandmodel.hpp"
namespace chatterino {
namespace controllers {
namespace commands {
// commandmodel
CommandModel::CommandModel(QObject *parent)
: util::SignalVectorModel<Command>(2, parent)
{
}
// turn a vector item into a model row
Command CommandModel::getItemFromRow(std::vector<QStandardItem *> &row)
{
return Command(row[0]->data(Qt::EditRole).toString(), row[1]->data(Qt::EditRole).toString());
}
// turns a row in the model into a vector item
void CommandModel::getRowFromItem(const Command &item, std::vector<QStandardItem *> &row)
{
row[0]->setData(item.name, Qt::DisplayRole);
row[0]->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsEditable);
row[1]->setData(item.func, Qt::DisplayRole);
row[1]->setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsEditable);
}
// returns the related index of the SignalVector
int CommandModel::getVectorIndexFromModelIndex(int index)
{
return index;
}
// returns the related index of the model
int CommandModel::getModelIndexFromVectorIndex(int index)
{
return index;
}
} // namespace commands
} // namespace controllers
} // namespace chatterino
+36
View File
@@ -0,0 +1,36 @@
#pragma once
#include <QObject>
#include "controllers/commands/command.hpp"
#include "util/signalvectormodel.hpp"
namespace chatterino {
namespace controllers {
namespace commands {
class CommandController;
class CommandModel : public util::SignalVectorModel<Command>
{
explicit CommandModel(QObject *parent);
protected:
// turn a vector item into a model row
virtual Command getItemFromRow(std::vector<QStandardItem *> &row) override;
// turns a row in the model into a vector item
virtual void getRowFromItem(const Command &item, std::vector<QStandardItem *> &row) override;
// returns the related index of the SignalVector
virtual int getVectorIndexFromModelIndex(int index) override;
// returns the related index of the model
virtual int getModelIndexFromVectorIndex(int index) override;
friend class CommandController;
};
} // namespace commands
} // namespace controllers
} // namespace chatterino