mirror-chatterino2/src/commandmanager.cpp

78 lines
1.9 KiB
C++
Raw Normal View History

2017-11-12 17:21:50 +01:00
#include "commandmanager.hpp"
2017-12-27 19:50:05 +01:00
#include <QRegularExpression>
2017-11-12 17:21:50 +01:00
namespace chatterino {
2017-12-27 19:50:05 +01:00
void CommandManager::execCommand(QString text)
2017-11-12 17:21:50 +01:00
{
2017-12-27 19:50:05 +01:00
QStringList words = text.split(' ', QString::SkipEmptyParts);
if (words.length() == 0) {
return text;
2017-11-12 17:21:50 +01:00
}
2017-12-27 19:50:05 +01:00
QString commandName = words[0];
if (commandName[0] == "/") {
commandName = commandName.mid(1);
2017-11-12 17:21:50 +01:00
}
2017-12-27 19:50:05 +01:00
Command *command = nullptr;
for (Command &command : this->commands) {
if (command.name == commandName) {
command = &command;
break;
}
2017-11-12 17:21:50 +01:00
}
2017-12-27 19:50:05 +01:00
if (command == nullptr) {
return text;
2017-11-12 17:21:50 +01:00
}
2017-12-27 19:50:05 +01:00
QString result;
static QRegularExpression parseCommand("[^{]({{)*{(\d+\+?)}");
for (QRegularExpressionMatch &match : parseCommand.globalMatch(command->text)) {
result += text.mid(match.capturedStart(), match.capturedLength());
QString wordIndexMatch = match.captured(2);
bool ok;
int wordIndex = wordIndexMatch.replace("=", "").toInt(ok);
if (!ok) {
result += match.captured();
continue;
}
if (words.length() <= wordIndex) {
// alternatively return text because the operation failed
result += "";
return;
}
2017-11-12 17:21:50 +01:00
2017-12-27 19:50:05 +01:00
if (wordIndexMatch[wordIndexMatch.length() - 1] == '+') {
for (int i = wordIndex; i < words.length(); i++) {
result += words[i];
}
} else {
result += words[wordIndex];
}
}
result += text.mid(match.capturedStart(), match.capturedLength());
return result;
}
CommandManager::Command::Command(QString _text)
2017-11-12 17:21:50 +01:00
{
2017-12-27 19:50:05 +01:00
int index = _text.indexOf(' ');
if (index == -1) {
this->name == _text;
return;
}
this->name = _text.mid(0, index);
this->text = _text.mid(index + 1);
2017-11-12 17:21:50 +01:00
}
}