Clang script (#3085)

This commit is contained in:
Zach H 2018-02-06 08:45:13 -05:00 committed by GitHub
parent fcfb2b12b7
commit 35159ef61a
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
24 changed files with 2098 additions and 2054 deletions

18
clangify.sh Executable file
View file

@ -0,0 +1,18 @@
#!/bin/bash
# This script will run clang-format on all non-3rd-party C++/Header files.
set -e
if hash clang-format 2>/dev/null; then
find . \( -name "*.cpp" -o -name "*.h" \) \
-not -path "./cockatrice/src/qt-json/*" \
-not -path "./servatrice/src/smtp/*" \
-not -path "./common/sfmt/*" \
-not -path "./oracle/src/zip/*" \
-not -path "./build*/*" \
-exec clang-format -style=file -i {} \;
echo "Repository properly formatted"
else
echo "Please install clang-format to use this program"
fi

View file

@ -1,23 +1,28 @@
#include <QTextEdit>
#include <QDateTime>
#include <QScrollBar>
#include <QMouseEvent>
#include <QDesktopServices>
#include <QApplication>
#include "chatview.h" #include "chatview.h"
#include "user_level.h"
#include "../user_context_menu.h"
#include "../pixmapgenerator.h" #include "../pixmapgenerator.h"
#include "../settingscache.h" #include "../settingscache.h"
#include "../tab_userlists.h"
#include "../soundengine.h" #include "../soundengine.h"
#include "../tab_userlists.h"
#include "../user_context_menu.h"
#include "user_level.h"
#include <QApplication>
#include <QDateTime>
#include <QDesktopServices>
#include <QMouseEvent>
#include <QScrollBar>
#include <QTextEdit>
const QColor DEFAULT_MENTION_COLOR = QColor(194, 31, 47); const QColor DEFAULT_MENTION_COLOR = QColor(194, 31, 47);
const QColor OTHER_USER_COLOR = QColor(0, 65, 255); // dark blue const QColor OTHER_USER_COLOR = QColor(0, 65, 255); // dark blue
const QString SERVER_MESSAGE_COLOR = "#851515"; const QString SERVER_MESSAGE_COLOR = "#851515";
ChatView::ChatView(const TabSupervisor *_tabSupervisor, const UserlistProxy *_userlistProxy, TabGame *_game, bool _showTimestamps, QWidget *parent) ChatView::ChatView(const TabSupervisor *_tabSupervisor,
: QTextBrowser(parent), tabSupervisor(_tabSupervisor), game(_game), userlistProxy(_userlistProxy), evenNumber(true), showTimestamps(_showTimestamps), hoveredItemType(HoveredNothing) const UserlistProxy *_userlistProxy,
TabGame *_game,
bool _showTimestamps,
QWidget *parent)
: QTextBrowser(parent), tabSupervisor(_tabSupervisor), game(_game), userlistProxy(_userlistProxy), evenNumber(true),
showTimestamps(_showTimestamps), hoveredItemType(HoveredNothing)
{ {
document()->setDefaultStyleSheet("a { text-decoration: none; color: blue; }"); document()->setDefaultStyleSheet("a { text-decoration: none; color: blue; }");
userContextMenu = new UserContextMenu(tabSupervisor, this, game); userContextMenu = new UserContextMenu(tabSupervisor, this, game);
@ -75,7 +80,8 @@ void ChatView::appendHtmlServerMessage(const QString &html, bool optionalIsBold,
{ {
bool atBottom = verticalScrollBar()->value() >= verticalScrollBar()->maximum(); bool atBottom = verticalScrollBar()->value() >= verticalScrollBar()->maximum();
QString htmlText = "<font color=" + ((optionalFontColor.size() > 0) ? optionalFontColor : SERVER_MESSAGE_COLOR) + ">" + QDateTime::currentDateTime().toString("[hh:mm:ss] ")+ html + "</font>"; QString htmlText = "<font color=" + ((optionalFontColor.size() > 0) ? optionalFontColor : SERVER_MESSAGE_COLOR) +
">" + QDateTime::currentDateTime().toString("[hh:mm:ss] ") + html + "</font>";
if (optionalIsBold) if (optionalIsBold)
htmlText = "<b>" + htmlText + "</b>"; htmlText = "<b>" + htmlText + "</b>";
@ -117,7 +123,12 @@ void ChatView::appendUrlTag(QTextCursor &cursor, QString url)
cursor.setCharFormat(oldFormat); cursor.setCharFormat(oldFormat);
} }
void ChatView::appendMessage(QString message, RoomMessageTypeFlags messageType, QString sender, UserLevelFlags userLevel, QString UserPrivLevel, bool playerBold) void ChatView::appendMessage(QString message,
RoomMessageTypeFlags messageType,
QString sender,
UserLevelFlags userLevel,
QString UserPrivLevel,
bool playerBold)
{ {
bool atBottom = verticalScrollBar()->value() >= verticalScrollBar()->maximum(); bool atBottom = verticalScrollBar()->value() >= verticalScrollBar()->maximum();
bool sameSender = (sender == lastSender) && !lastSender.isEmpty(); bool sameSender = (sender == lastSender) && !lastSender.isEmpty();
@ -153,7 +164,8 @@ void ChatView::appendMessage(QString message, RoomMessageTypeFlags messageType,
if (!sender.isEmpty()) { if (!sender.isEmpty()) {
const int pixelSize = QFontInfo(cursor.charFormat().font()).pixelSize(); const int pixelSize = QFontInfo(cursor.charFormat().font()).pixelSize();
bool isBuddy = userlistProxy->isUserBuddy(sender); bool isBuddy = userlistProxy->isUserBuddy(sender);
cursor.insertImage(UserLevelPixmapGenerator::generatePixmap(pixelSize, userLevel, isBuddy, UserPrivLevel).toImage()); cursor.insertImage(
UserLevelPixmapGenerator::generatePixmap(pixelSize, userLevel, isBuddy, UserPrivLevel).toImage());
cursor.insertText(" "); cursor.insertText(" ");
} }
cursor.setCharFormat(senderFormat); cursor.setCharFormat(senderFormat);
@ -190,11 +202,9 @@ void ChatView::appendMessage(QString message, RoomMessageTypeFlags messageType,
highlightedWords = settingsCache->getHighlightWords().split(' ', QString::SkipEmptyParts); highlightedWords = settingsCache->getHighlightWords().split(' ', QString::SkipEmptyParts);
// parse the message // parse the message
while (message.size()) while (message.size()) {
{
QChar c = message.at(0); QChar c = message.at(0);
switch(c.toLatin1()) switch (c.toLatin1()) {
{
case '[': case '[':
checkTag(cursor, message); checkTag(cursor, message);
break; break;
@ -225,11 +235,9 @@ void ChatView::appendMessage(QString message, RoomMessageTypeFlags messageType,
verticalScrollBar()->setValue(verticalScrollBar()->maximum()); verticalScrollBar()->setValue(verticalScrollBar()->maximum());
} }
void ChatView::checkTag(QTextCursor &cursor, QString &message) void ChatView::checkTag(QTextCursor &cursor, QString &message)
{ {
if (message.startsWith("[card]")) if (message.startsWith("[card]")) {
{
message = message.mid(6); message = message.mid(6);
int closeTagIndex = message.indexOf("[/card]"); int closeTagIndex = message.indexOf("[/card]");
QString cardName = message.left(closeTagIndex); QString cardName = message.left(closeTagIndex);
@ -242,8 +250,7 @@ void ChatView::checkTag(QTextCursor &cursor, QString &message)
return; return;
} }
if (message.startsWith("[[")) if (message.startsWith("[[")) {
{
message = message.mid(2); message = message.mid(2);
int closeTagIndex = message.indexOf("]]"); int closeTagIndex = message.indexOf("]]");
QString cardName = message.left(closeTagIndex); QString cardName = message.left(closeTagIndex);
@ -256,8 +263,7 @@ void ChatView::checkTag(QTextCursor &cursor, QString &message)
return; return;
} }
if (message.startsWith("[url]")) if (message.startsWith("[url]")) {
{
message = message.mid(5); message = message.mid(5);
int closeTagIndex = message.indexOf("[/url]"); int closeTagIndex = message.indexOf("[/url]");
QString url = message.left(closeTagIndex); QString url = message.left(closeTagIndex);
@ -282,8 +288,7 @@ void ChatView::checkMention(QTextCursor &cursor, QString &message, QString &send
QString fullMentionUpToSpaceOrEnd = (firstSpace == -1) ? message.mid(1) : message.mid(1, firstSpace - 1); QString fullMentionUpToSpaceOrEnd = (firstSpace == -1) ? message.mid(1) : message.mid(1, firstSpace - 1);
QString mentionIntact = fullMentionUpToSpaceOrEnd; QString mentionIntact = fullMentionUpToSpaceOrEnd;
while (fullMentionUpToSpaceOrEnd.size()) while (fullMentionUpToSpaceOrEnd.size()) {
{
const ServerInfo_User *onlineUser = userlistProxy->getOnlineUser(fullMentionUpToSpaceOrEnd); const ServerInfo_User *onlineUser = userlistProxy->getOnlineUser(fullMentionUpToSpaceOrEnd);
if (onlineUser) // Is there a user online named this? if (onlineUser) // Is there a user online named this?
{ {
@ -292,13 +297,15 @@ void ChatView::checkMention(QTextCursor &cursor, QString &message, QString &send
// You have received a valid mention!! // You have received a valid mention!!
soundEngine->playSound("chat_mention"); soundEngine->playSound("chat_mention");
mentionFormat.setBackground(QBrush(getCustomMentionColor())); mentionFormat.setBackground(QBrush(getCustomMentionColor()));
mentionFormat.setForeground(settingsCache->getChatMentionForeground() ? QBrush(Qt::white) : QBrush(Qt::black)); mentionFormat.setForeground(settingsCache->getChatMentionForeground() ? QBrush(Qt::white)
: QBrush(Qt::black));
cursor.insertText(mention, mentionFormat); cursor.insertText(mention, mentionFormat);
message = message.mid(mention.size()); message = message.mid(mention.size());
showSystemPopup(sender); showSystemPopup(sender);
} else { } else {
QString correctUserName = QString::fromStdString(onlineUser->name()); QString correctUserName = QString::fromStdString(onlineUser->name());
mentionFormatOtherUser.setAnchorHref("user://" + QString::number(onlineUser->user_level()) + "_" + correctUserName); mentionFormatOtherUser.setAnchorHref("user://" + QString::number(onlineUser->user_level()) + "_" +
correctUserName);
cursor.insertText("@" + correctUserName, mentionFormatOtherUser); cursor.insertText("@" + correctUserName, mentionFormatOtherUser);
message = message.mid(correctUserName.size() + 1); message = message.mid(correctUserName.size() + 1);
@ -312,7 +319,8 @@ void ChatView::checkMention(QTextCursor &cursor, QString &message, QString &send
// Moderator Sending Global Message // Moderator Sending Global Message
soundEngine->playSound("all_mention"); soundEngine->playSound("all_mention");
mentionFormat.setBackground(QBrush(getCustomMentionColor())); mentionFormat.setBackground(QBrush(getCustomMentionColor()));
mentionFormat.setForeground(settingsCache->getChatMentionForeground() ? QBrush(Qt::white) : QBrush(Qt::black)); mentionFormat.setForeground(settingsCache->getChatMentionForeground() ? QBrush(Qt::white)
: QBrush(Qt::black));
cursor.insertText("@" + fullMentionUpToSpaceOrEnd, mentionFormat); cursor.insertText("@" + fullMentionUpToSpaceOrEnd, mentionFormat);
message = message.mid(fullMentionUpToSpaceOrEnd.size() + 1); message = message.mid(fullMentionUpToSpaceOrEnd.size() + 1);
showSystemPopup(sender); showSystemPopup(sender);
@ -321,8 +329,8 @@ void ChatView::checkMention(QTextCursor &cursor, QString &message, QString &send
return; return;
} }
if (fullMentionUpToSpaceOrEnd.right(1).indexOf(notALetterOrNumber) == -1 || fullMentionUpToSpaceOrEnd.size() < 2) if (fullMentionUpToSpaceOrEnd.right(1).indexOf(notALetterOrNumber) == -1 ||
{ fullMentionUpToSpaceOrEnd.size() < 2) {
cursor.insertText("@" + mentionIntact, defaultFormat); cursor.insertText("@" + mentionIntact, defaultFormat);
message = message.mid(mentionIntact.size() + 1); message = message.mid(mentionIntact.size() + 1);
cursor.setCharFormat(defaultFormat); cursor.setCharFormat(defaultFormat);
@ -345,11 +353,9 @@ void ChatView::checkWord(QTextCursor &cursor, QString &message)
// check urls // check urls
if (fullWordUpToSpaceOrEnd.startsWith("http://", Qt::CaseInsensitive) || if (fullWordUpToSpaceOrEnd.startsWith("http://", Qt::CaseInsensitive) ||
fullWordUpToSpaceOrEnd.startsWith("https://", Qt::CaseInsensitive) || fullWordUpToSpaceOrEnd.startsWith("https://", Qt::CaseInsensitive) ||
fullWordUpToSpaceOrEnd.startsWith("www.", Qt::CaseInsensitive)) fullWordUpToSpaceOrEnd.startsWith("www.", Qt::CaseInsensitive)) {
{
QUrl qUrl(fullWordUpToSpaceOrEnd); QUrl qUrl(fullWordUpToSpaceOrEnd);
if (qUrl.isValid()) if (qUrl.isValid()) {
{
appendUrlTag(cursor, fullWordUpToSpaceOrEnd); appendUrlTag(cursor, fullWordUpToSpaceOrEnd);
cursor.insertText(rest, defaultFormat); cursor.insertText(rest, defaultFormat);
return; return;
@ -357,13 +363,12 @@ void ChatView::checkWord(QTextCursor &cursor, QString &message)
} }
// check word mentions // check word mentions
foreach (QString word, highlightedWords) foreach (QString word, highlightedWords) {
{ if (fullWordUpToSpaceOrEnd.compare(word, Qt::CaseInsensitive) == 0) {
if (fullWordUpToSpaceOrEnd.compare(word, Qt::CaseInsensitive) == 0)
{
// You have received a valid mention of custom word!! // You have received a valid mention of custom word!!
highlightFormat.setBackground(QBrush(getCustomHighlightColor())); highlightFormat.setBackground(QBrush(getCustomHighlightColor()));
highlightFormat.setForeground(settingsCache->getChatHighlightForeground() ? QBrush(Qt::white) : QBrush(Qt::black)); highlightFormat.setForeground(settingsCache->getChatHighlightForeground() ? QBrush(Qt::white)
: QBrush(Qt::black));
cursor.insertText(fullWordUpToSpaceOrEnd, highlightFormat); cursor.insertText(fullWordUpToSpaceOrEnd, highlightFormat);
cursor.insertText(rest, defaultFormat); cursor.insertText(rest, defaultFormat);
QApplication::alert(this); QApplication::alert(this);
@ -380,8 +385,7 @@ QString ChatView::extractNextWord(QString &message, QString &rest)
// get the first next space and extract the word // get the first next space and extract the word
QString word; QString word;
int firstSpace = message.indexOf(' '); int firstSpace = message.indexOf(' ');
if(firstSpace == -1) if (firstSpace == -1) {
{
word = message; word = message;
message.clear(); message.clear();
} else { } else {
@ -390,10 +394,8 @@ QString ChatView::extractNextWord(QString &message, QString &rest)
} }
// remove any punctuation from the end and pass it separately // remove any punctuation from the end and pass it separately
for (int len = word.size() - 1; len >= 0; --len) for (int len = word.size() - 1; len >= 0; --len) {
{ if (word.at(len).isLetterOrNumber()) {
if(word.at(len).isLetterOrNumber())
{
rest = word.mid(len + 1); rest = word.mid(len + 1);
return word.mid(0, len + 1); return word.mid(0, len + 1);
} }
@ -403,7 +405,6 @@ QString ChatView::extractNextWord(QString &message, QString &rest)
return QString(); return QString();
} }
bool ChatView::isModeratorSendingGlobal(QFlags<ServerInfo_User::UserLevelFlag> userLevelFlag, QString message) bool ChatView::isModeratorSendingGlobal(QFlags<ServerInfo_User::UserLevelFlag> userLevelFlag, QString message)
{ {
int userLevel = QString::number(userLevelFlag).toInt(); int userLevel = QString::number(userLevelFlag).toInt();
@ -411,17 +412,17 @@ bool ChatView::isModeratorSendingGlobal(QFlags<ServerInfo_User::UserLevelFlag> u
QStringList getAttentionList; QStringList getAttentionList;
getAttentionList << "/all"; // Send a message to all users getAttentionList << "/all"; // Send a message to all users
return (getAttentionList.contains(message) return (getAttentionList.contains(message) &&
&& (userLevel & ServerInfo_User::IsModerator (userLevel & ServerInfo_User::IsModerator || userLevel & ServerInfo_User::IsAdmin));
|| userLevel & ServerInfo_User::IsAdmin));
} }
void ChatView::actMessageClicked() { void ChatView::actMessageClicked()
{
emit messageClickedSignal(); emit messageClickedSignal();
} }
void ChatView::showSystemPopup(QString &sender) { void ChatView::showSystemPopup(QString &sender)
{
QApplication::alert(this); QApplication::alert(this);
if (settingsCache->getShowMentionPopup()) { if (settingsCache->getShowMentionPopup()) {
QString ref = sender.left(sender.length() - 2); QString ref = sender.left(sender.length() - 2);
@ -429,19 +430,22 @@ void ChatView::showSystemPopup(QString &sender) {
} }
} }
QColor ChatView::getCustomMentionColor() { QColor ChatView::getCustomMentionColor()
{
QColor customColor; QColor customColor;
customColor.setNamedColor("#" + settingsCache->getChatMentionColor()); customColor.setNamedColor("#" + settingsCache->getChatMentionColor());
return customColor.isValid() ? customColor : DEFAULT_MENTION_COLOR; return customColor.isValid() ? customColor : DEFAULT_MENTION_COLOR;
} }
QColor ChatView::getCustomHighlightColor() { QColor ChatView::getCustomHighlightColor()
{
QColor customColor; QColor customColor;
customColor.setNamedColor("#" + settingsCache->getChatHighlightColor()); customColor.setNamedColor("#" + settingsCache->getChatHighlightColor());
return customColor.isValid() ? customColor : DEFAULT_MENTION_COLOR; return customColor.isValid() ? customColor : DEFAULT_MENTION_COLOR;
} }
void ChatView::clearChat() { void ChatView::clearChat()
{
document()->clear(); document()->clear();
lastSender = ""; lastSender = "";
} }

View file

@ -1,29 +1,37 @@
#ifndef CHATVIEW_H #ifndef CHATVIEW_H
#define CHATVIEW_H #define CHATVIEW_H
#include <QTextBrowser>
#include <QTextFragment>
#include <QTextCursor>
#include <QColor>
#include <QAction>
#include "../userlist.h"
#include "user_level.h"
#include "room_message_type.h"
#include "../tab_supervisor.h" #include "../tab_supervisor.h"
#include "../userlist.h"
#include "room_message_type.h"
#include "user_level.h"
#include "userlistProxy.h" #include "userlistProxy.h"
#include <QAction>
#include <QColor>
#include <QTextBrowser>
#include <QTextCursor>
#include <QTextFragment>
class QTextTable; class QTextTable;
class QMouseEvent; class QMouseEvent;
class UserContextMenu; class UserContextMenu;
class TabGame; class TabGame;
class ChatView : public QTextBrowser { class ChatView : public QTextBrowser
{
Q_OBJECT Q_OBJECT
protected: protected:
const TabSupervisor *const tabSupervisor; const TabSupervisor *const tabSupervisor;
TabGame *const game; TabGame *const game;
private: private:
enum HoveredItemType { HoveredNothing, HoveredUrl, HoveredCard, HoveredUser }; enum HoveredItemType
{
HoveredNothing,
HoveredUrl,
HoveredCard,
HoveredUser
};
const UserlistProxy *const userlistProxy; const UserlistProxy *const userlistProxy;
UserContextMenu *userContextMenu; UserContextMenu *userContextMenu;
QString lastSender; QString lastSender;
@ -54,13 +62,25 @@ private:
private slots: private slots:
void openLink(const QUrl &link); void openLink(const QUrl &link);
void actMessageClicked(); void actMessageClicked();
public: public:
ChatView(const TabSupervisor *_tabSupervisor, const UserlistProxy *_userlistProxy, TabGame *_game, bool _showTimestamps, QWidget *parent = 0); ChatView(const TabSupervisor *_tabSupervisor,
const UserlistProxy *_userlistProxy,
TabGame *_game,
bool _showTimestamps,
QWidget *parent = 0);
void retranslateUi(); void retranslateUi();
void appendHtml(const QString &html); void appendHtml(const QString &html);
void appendHtmlServerMessage(const QString &html, bool optionalIsBold = false, QString optionalFontColor = QString()); void
void appendMessage(QString message, RoomMessageTypeFlags messageType = 0, QString sender = QString(), UserLevelFlags userLevel = UserLevelFlags(), QString UserPrivLevel = "NONE", bool playerBold = false); appendHtmlServerMessage(const QString &html, bool optionalIsBold = false, QString optionalFontColor = QString());
void appendMessage(QString message,
RoomMessageTypeFlags messageType = 0,
QString sender = QString(),
UserLevelFlags userLevel = UserLevelFlags(),
QString UserPrivLevel = "NONE",
bool playerBold = false);
void clearChat(); void clearChat();
protected: protected:
void enterEvent(QEvent *event); void enterEvent(QEvent *event);
void leaveEvent(QEvent *event); void leaveEvent(QEvent *event);

View file

@ -8,7 +8,8 @@ class ServerInfo_User;
* Responsible for providing a bare-bones minimal interface into userlist information, * Responsible for providing a bare-bones minimal interface into userlist information,
* including your current connection to the server as well as buddy/ignore/alluser lists. * including your current connection to the server as well as buddy/ignore/alluser lists.
*/ */
class UserlistProxy { class UserlistProxy
{
public: public:
virtual bool isOwnUserRegistered() const = 0; virtual bool isOwnUserRegistered() const = 0;
virtual QString getOwnUsername() const = 0; virtual QString getOwnUsername() const = 0;

View file

@ -1,10 +1,10 @@
#include "sequenceedit.h" #include "sequenceedit.h"
#include "../settingscache.h" #include "../settingscache.h"
#include <QEvent>
#include <QHBoxLayout>
#include <QKeyEvent>
#include <QLineEdit> #include <QLineEdit>
#include <QPushButton> #include <QPushButton>
#include <QHBoxLayout>
#include <QEvent>
#include <QKeyEvent>
#include <QToolTip> #include <QToolTip>
#include <utility> #include <utility>
@ -53,15 +53,11 @@ QString SequenceEdit::getSecuence()
void SequenceEdit::removeLastShortcut() void SequenceEdit::removeLastShortcut()
{ {
QString secuences = lineEdit->text(); QString secuences = lineEdit->text();
if (!secuences.isEmpty()) if (!secuences.isEmpty()) {
{ if (secuences.lastIndexOf(";") > 0) {
if (secuences.lastIndexOf(";") > 0)
{
QString valid = secuences.left(secuences.lastIndexOf(";")); QString valid = secuences.left(secuences.lastIndexOf(";"));
lineEdit->setText(valid); lineEdit->setText(valid);
} } else {
else
{
lineEdit->clear(); lineEdit->clear();
} }
@ -87,16 +83,12 @@ void SequenceEdit::clear()
bool SequenceEdit::eventFilter(QObject *, QEvent *event) bool SequenceEdit::eventFilter(QObject *, QEvent *event)
{ {
if (event->type() == QEvent::KeyPress || event->type() == QEvent::KeyRelease) if (event->type() == QEvent::KeyPress || event->type() == QEvent::KeyRelease) {
{
auto *keyEvent = reinterpret_cast<QKeyEvent *>(event); auto *keyEvent = reinterpret_cast<QKeyEvent *>(event);
if (event->type() == QEvent::KeyPress && !keyEvent->isAutoRepeat()) if (event->type() == QEvent::KeyPress && !keyEvent->isAutoRepeat()) {
{
processKey(keyEvent); processKey(keyEvent);
} } else if (event->type() == QEvent::KeyRelease && !keyEvent->isAutoRepeat()) {
else if (event->type() == QEvent::KeyRelease && !keyEvent->isAutoRepeat())
{
finishShortcut(); finishShortcut();
} }
@ -108,16 +100,14 @@ bool SequenceEdit::eventFilter(QObject *, QEvent * event)
void SequenceEdit::processKey(QKeyEvent *e) void SequenceEdit::processKey(QKeyEvent *e)
{ {
int key = e->key(); int key = e->key();
if (key != Qt::Key_Control && key != Qt::Key_Shift && key != Qt::Key_Meta && key != Qt::Key_Alt) if (key != Qt::Key_Control && key != Qt::Key_Shift && key != Qt::Key_Meta && key != Qt::Key_Alt) {
{
valid = true; valid = true;
key |= translateModifiers(e->modifiers(), e->text()); key |= translateModifiers(e->modifiers(), e->text());
} }
keys = key; keys = key;
currentKey++; currentKey++;
if (currentKey >= key) if (currentKey >= key) {
{
finishShortcut(); finishShortcut();
} }
} }
@ -127,26 +117,20 @@ int SequenceEdit::translateModifiers(Qt::KeyboardModifiers state, const QString
int result = 0; int result = 0;
// The shift modifier only counts when it is not used to type a symbol // The shift modifier only counts when it is not used to type a symbol
// that is only reachable using the shift key anyway // that is only reachable using the shift key anyway
if ((state & Qt::ShiftModifier) && (text.isEmpty() || if ((state & Qt::ShiftModifier) &&
!text.at(0).isPrint() || (text.isEmpty() || !text.at(0).isPrint() || text.at(0).isLetterOrNumber() || text.at(0).isSpace())) {
text.at(0).isLetterOrNumber() ||
text.at(0).isSpace()))
{
result |= Qt::SHIFT; result |= Qt::SHIFT;
} }
if (state & Qt::ControlModifier) if (state & Qt::ControlModifier) {
{
result |= Qt::CTRL; result |= Qt::CTRL;
} }
if (state & Qt::MetaModifier) if (state & Qt::MetaModifier) {
{
result |= Qt::META; result |= Qt::META;
} }
if (state & Qt::AltModifier) if (state & Qt::AltModifier) {
{
result |= Qt::ALT; result |= Qt::ALT;
} }
@ -156,23 +140,17 @@ int SequenceEdit::translateModifiers(Qt::KeyboardModifiers state, const QString
void SequenceEdit::finishShortcut() void SequenceEdit::finishShortcut()
{ {
QKeySequence secuence(keys); QKeySequence secuence(keys);
if (!secuence.isEmpty() && valid) if (!secuence.isEmpty() && valid) {
{
QString secuenceString = secuence.toString(); QString secuenceString = secuence.toString();
if (settingsCache->shortcuts().isValid(shorcutName,secuenceString)) if (settingsCache->shortcuts().isValid(shorcutName, secuenceString)) {
{ if (!lineEdit->text().isEmpty()) {
if (!lineEdit->text().isEmpty()) if (lineEdit->text().contains(secuenceString)) {
{
if (lineEdit->text().contains(secuenceString))
{
return; return;
} }
lineEdit->setText(lineEdit->text() + ";"); lineEdit->setText(lineEdit->text() + ";");
} }
lineEdit->setText(lineEdit->text() + secuenceString); lineEdit->setText(lineEdit->text() + secuenceString);
} } else {
else
{
QToolTip::showText(lineEdit->mapToGlobal(QPoint()), tr("Shortcut already in use")); QToolTip::showText(lineEdit->mapToGlobal(QPoint()), tr("Shortcut already in use"));
} }
} }

View file

@ -1,8 +1,8 @@
#ifndef SECUENCEEDIT_H #ifndef SECUENCEEDIT_H
#define SECUENCEEDIT_H #define SECUENCEEDIT_H
#include <QWidget>
#include <QKeySequence> #include <QKeySequence>
#include <QWidget>
class QLineEdit; class QLineEdit;
class QPushButton; class QPushButton;

View file

@ -26,8 +26,7 @@ ShortcutsTab::~ShortcutsTab()
void ShortcutsTab::resetShortcuts() void ShortcutsTab::resetShortcuts()
{ {
if (QMessageBox::question(this, tr("Restore all default shortcuts"), if (QMessageBox::question(this, tr("Restore all default shortcuts"),
tr("Do you really want to restore all default shortcuts?")) == QMessageBox::Yes) tr("Do you really want to restore all default shortcuts?")) == QMessageBox::Yes) {
{
settingsCache->shortcuts().resetAllShortcuts(); settingsCache->shortcuts().resetAllShortcuts();
} }
} }
@ -35,8 +34,7 @@ void ShortcutsTab::resetShortcuts()
void ShortcutsTab::refreshEdits() void ShortcutsTab::refreshEdits()
{ {
QList<SequenceEdit *> edits = this->findChildren<SequenceEdit *>(); QList<SequenceEdit *> edits = this->findChildren<SequenceEdit *>();
for (auto edit : edits) for (auto edit : edits) {
{
edit->refreshShortcut(); edit->refreshShortcut();
} }
} }
@ -44,8 +42,7 @@ void ShortcutsTab::refreshEdits()
void ShortcutsTab::clearShortcuts() void ShortcutsTab::clearShortcuts()
{ {
if (QMessageBox::question(this, tr("Clear all default shortcuts"), if (QMessageBox::question(this, tr("Clear all default shortcuts"),
tr("Do you really want to clear all shortcuts?")) == QMessageBox::Yes) tr("Do you really want to clear all shortcuts?")) == QMessageBox::Yes) {
{
settingsCache->shortcuts().clearAllShortcuts(); settingsCache->shortcuts().clearAllShortcuts();
} }
} }
@ -53,8 +50,7 @@ void ShortcutsTab::clearShortcuts()
void ShortcutsTab::afterClear() void ShortcutsTab::afterClear()
{ {
QList<SequenceEdit *> edits = this->findChildren<SequenceEdit *>(); QList<SequenceEdit *> edits = this->findChildren<SequenceEdit *>();
for (auto edit : edits) for (auto edit : edits) {
{
edit->clear(); edit->clear();
} }
} }

View file

@ -1,7 +1,7 @@
#ifndef UI_SHORTCUTSTAB_H #ifndef UI_SHORTCUTSTAB_H
#define UI_SHORTCUTSTAB_H #define UI_SHORTCUTSTAB_H
#include <QtCore/QVariant> #include "sequenceedit.h"
#include <QAction> #include <QAction>
#include <QApplication> #include <QApplication>
#include <QButtonGroup> #include <QButtonGroup>
@ -15,7 +15,7 @@
#include <QTabWidget> #include <QTabWidget>
#include <QVBoxLayout> #include <QVBoxLayout>
#include <QWidget> #include <QWidget>
#include "sequenceedit.h" #include <QtCore/QVariant>
QT_BEGIN_NAMESPACE QT_BEGIN_NAMESPACE
@ -1752,11 +1752,13 @@ class Ui_shortcutsTab
lbl_MainWindow_aExit->setText(QApplication::translate("shortcutsTab", "Exit", 0)); lbl_MainWindow_aExit->setText(QApplication::translate("shortcutsTab", "Exit", 0));
groupBox_2->setTitle(QApplication::translate("shortcutsTab", "Deck Editor", 0)); groupBox_2->setTitle(QApplication::translate("shortcutsTab", "Deck Editor", 0));
lbl_TabDeckEditor_aAnalyzeDeck->setText(QApplication::translate("shortcutsTab", "Analyze deck", 0)); lbl_TabDeckEditor_aAnalyzeDeck->setText(QApplication::translate("shortcutsTab", "Analyze deck", 0));
lbl_TabDeckEditor_aLoadDeckFromClipboard->setText(QApplication::translate("shortcutsTab", "Load deck (clipboard)", 0)); lbl_TabDeckEditor_aLoadDeckFromClipboard->setText(
QApplication::translate("shortcutsTab", "Load deck (clipboard)", 0));
lbl_TabDeckEditor_aClearFilterAll->setText(QApplication::translate("shortcutsTab", "Clear all filters", 0)); lbl_TabDeckEditor_aClearFilterAll->setText(QApplication::translate("shortcutsTab", "Clear all filters", 0));
lbl_TabDeckEditor_aNewDeck->setText(QApplication::translate("shortcutsTab", "New deck", 0)); lbl_TabDeckEditor_aNewDeck->setText(QApplication::translate("shortcutsTab", "New deck", 0));
lbl_TabDeckEditor_aClearFilterOne->setText(QApplication::translate("shortcutsTab", "Clear selected filter", 0)); lbl_TabDeckEditor_aClearFilterOne->setText(QApplication::translate("shortcutsTab", "Clear selected filter", 0));
lbl_TabDeckEditor_aOpenCustomFolder->setText(QApplication::translate("shortcutsTab", "Open custom pic folder", 0)); lbl_TabDeckEditor_aOpenCustomFolder->setText(
QApplication::translate("shortcutsTab", "Open custom pic folder", 0));
lbl_TabDeckEditor_aClose->setText(QApplication::translate("shortcutsTab", "Close", 0)); lbl_TabDeckEditor_aClose->setText(QApplication::translate("shortcutsTab", "Close", 0));
lbl_TabDeckEditor_aPrintDeck->setText(QApplication::translate("shortcutsTab", "Print deck", 0)); lbl_TabDeckEditor_aPrintDeck->setText(QApplication::translate("shortcutsTab", "Print deck", 0));
lbl_TabDeckEditor_aManageSets->setText(QApplication::translate("shortcutsTab", "Manage sets", 0)); lbl_TabDeckEditor_aManageSets->setText(QApplication::translate("shortcutsTab", "Manage sets", 0));
@ -1770,7 +1772,8 @@ class Ui_shortcutsTab
lbl_TabDeckEditor_aSaveDeckAs->setText(QApplication::translate("shortcutsTab", "Save deck as", 0)); lbl_TabDeckEditor_aSaveDeckAs->setText(QApplication::translate("shortcutsTab", "Save deck as", 0));
lbl_TabDeckEditor_aLoadDeck->setText(QApplication::translate("shortcutsTab", "Load deck", 0)); lbl_TabDeckEditor_aLoadDeck->setText(QApplication::translate("shortcutsTab", "Load deck", 0));
lbl_TabDeckEditor_aSaveDeckToClipboard->setText(QApplication::translate("shortcutsTab", "Save deck (clip)", 0)); lbl_TabDeckEditor_aSaveDeckToClipboard->setText(QApplication::translate("shortcutsTab", "Save deck (clip)", 0));
lbl_TabDeckEditor_aSaveDeckToClipboardRaw->setText(QApplication::translate("shortcutsTab", "Save deck (clip; no annotations)", 0)); lbl_TabDeckEditor_aSaveDeckToClipboardRaw->setText(
QApplication::translate("shortcutsTab", "Save deck (clip; no annotations)", 0));
groupBox_3->setTitle(QApplication::translate("shortcutsTab", "Counters", 0)); groupBox_3->setTitle(QApplication::translate("shortcutsTab", "Counters", 0));
groupBox_4->setTitle(QApplication::translate("shortcutsTab", "Life", 0)); groupBox_4->setTitle(QApplication::translate("shortcutsTab", "Life", 0));
lbl_abstractCounter_sSet->setText(QApplication::translate("shortcutsTab", "Set", 0)); lbl_abstractCounter_sSet->setText(QApplication::translate("shortcutsTab", "Set", 0));
@ -1821,7 +1824,8 @@ class Ui_shortcutsTab
lbl_Player_aSCYellow->setText(QApplication::translate("shortcutsTab", "Set", 0)); lbl_Player_aSCYellow->setText(QApplication::translate("shortcutsTab", "Set", 0));
lbl_Player_aCCYellow->setText(QApplication::translate("shortcutsTab", "Add", 0)); lbl_Player_aCCYellow->setText(QApplication::translate("shortcutsTab", "Add", 0));
lbl_Player_aRCYellow->setText(QApplication::translate("shortcutsTab", "Remove", 0)); lbl_Player_aRCYellow->setText(QApplication::translate("shortcutsTab", "Remove", 0));
tabWidget->setTabText(tabWidget->indexOf(tab), QApplication::translate("shortcutsTab", "Main Window | Deck Editor", 0)); tabWidget->setTabText(tabWidget->indexOf(tab),
QApplication::translate("shortcutsTab", "Main Window | Deck Editor", 0));
groupBox_9->setTitle(QApplication::translate("shortcutsTab", "Power / Toughness", 0)); groupBox_9->setTitle(QApplication::translate("shortcutsTab", "Power / Toughness", 0));
groupBox_12->setTitle(QApplication::translate("shortcutsTab", "Power and Toughness", 0)); groupBox_12->setTitle(QApplication::translate("shortcutsTab", "Power and Toughness", 0));
lbl_Player_aIncPT->setText(QApplication::translate("shortcutsTab", "Add (+1/+1)", 0)); lbl_Player_aIncPT->setText(QApplication::translate("shortcutsTab", "Add (+1/+1)", 0));
@ -1858,10 +1862,12 @@ class Ui_shortcutsTab
lbl_Player_aUnattach->setText(QApplication::translate("shortcutsTab", "Unattach card", 0)); lbl_Player_aUnattach->setText(QApplication::translate("shortcutsTab", "Unattach card", 0));
lbl_Player_aClone->setText(QApplication::translate("shortcutsTab", "Clone card", 0)); lbl_Player_aClone->setText(QApplication::translate("shortcutsTab", "Clone card", 0));
lbl_Player_aCreateToken->setText(QApplication::translate("shortcutsTab", "Create token", 0)); lbl_Player_aCreateToken->setText(QApplication::translate("shortcutsTab", "Create token", 0));
lbl_Player_aCreateRelatedTokens->setText(QApplication::translate("shortcutsTab", "Create all related tokens", 0)); lbl_Player_aCreateRelatedTokens->setText(
QApplication::translate("shortcutsTab", "Create all related tokens", 0));
lbl_Player_aCreateAnotherToken->setText(QApplication::translate("shortcutsTab", "Create another token", 0)); lbl_Player_aCreateAnotherToken->setText(QApplication::translate("shortcutsTab", "Create another token", 0));
lbl_Player_aSetAnnotation->setText(QApplication::translate("shortcutsTab", "Set annotation", 0)); lbl_Player_aSetAnnotation->setText(QApplication::translate("shortcutsTab", "Set annotation", 0));
tabWidget->setTabText(tabWidget->indexOf(tab_2), QApplication::translate("shortcutsTab", "Phases | P/T | Playing Area", 0)); tabWidget->setTabText(tabWidget->indexOf(tab_2),
QApplication::translate("shortcutsTab", "Phases | P/T | Playing Area", 0));
groupBox_15->setTitle(QApplication::translate("shortcutsTab", "Move card to", 0)); groupBox_15->setTitle(QApplication::translate("shortcutsTab", "Move card to", 0));
lbl_Player_aMoveToBottomLibrary->setText(QApplication::translate("shortcutsTab", "Bottom library", 0)); lbl_Player_aMoveToBottomLibrary->setText(QApplication::translate("shortcutsTab", "Bottom library", 0));
lbl_Player_aMoveToTopLibrary->setText(QApplication::translate("shortcutsTab", "Top library", 0)); lbl_Player_aMoveToTopLibrary->setText(QApplication::translate("shortcutsTab", "Top library", 0));
@ -1893,9 +1899,12 @@ class Ui_shortcutsTab
lbl_Player_aDrawCards->setText(QApplication::translate("shortcutsTab", "Draw cards", 0)); lbl_Player_aDrawCards->setText(QApplication::translate("shortcutsTab", "Draw cards", 0));
lbl_Player_aUndoDraw->setText(QApplication::translate("shortcutsTab", "Undo draw", 0)); lbl_Player_aUndoDraw->setText(QApplication::translate("shortcutsTab", "Undo draw", 0));
lbl_Player_aAlwaysRevealTopCard->setText(QApplication::translate("shortcutsTab", "Always reveal top card", 0)); lbl_Player_aAlwaysRevealTopCard->setText(QApplication::translate("shortcutsTab", "Always reveal top card", 0));
tabWidget->setTabText(tabWidget->indexOf(tab_3), QApplication::translate("shortcutsTab", "Draw | Move | View | Gameplay", 0)); tabWidget->setTabText(tabWidget->indexOf(tab_3),
QApplication::translate("shortcutsTab", "Draw | Move | View | Gameplay", 0));
tabWidget->setTabText(tabWidget->indexOf(tab_4), QApplication::translate("shortcutsTab", "Counters", 0)); tabWidget->setTabText(tabWidget->indexOf(tab_4), QApplication::translate("shortcutsTab", "Counters", 0));
faqLabel->setText(QString("<a href='%1'>%2</a>").arg(WIKI).arg(QApplication::translate("shortcutsTab","How to set custom shortcuts",0))); faqLabel->setText(QString("<a href='%1'>%2</a>")
.arg(WIKI)
.arg(QApplication::translate("shortcutsTab", "How to set custom shortcuts", 0)));
btnResetAll->setText(QApplication::translate("shortcutsTab", "Restore all default shortcuts", 0)); btnResetAll->setText(QApplication::translate("shortcutsTab", "Restore all default shortcuts", 0));
btnClearAll->setText(QApplication::translate("shortcutsTab", "Clear all shortcuts", 0)); btnClearAll->setText(QApplication::translate("shortcutsTab", "Clear all shortcuts", 0));
} // retranslateUi } // retranslateUi
@ -1903,7 +1912,9 @@ class Ui_shortcutsTab
namespace Ui namespace Ui
{ {
class shortcutsTab: public Ui_shortcutsTab {}; class shortcutsTab : public Ui_shortcutsTab
{
};
} // namespace Ui } // namespace Ui
QT_END_NAMESPACE QT_END_NAMESPACE

View file

@ -1,8 +1,8 @@
#include "carddatabasesettings.h" #include "carddatabasesettings.h"
CardDatabaseSettings::CardDatabaseSettings(QString settingPath, QObject *parent) : SettingsManager(settingPath+"cardDatabase.ini", parent) CardDatabaseSettings::CardDatabaseSettings(QString settingPath, QObject *parent)
: SettingsManager(settingPath + "cardDatabase.ini", parent)
{ {
} }
void CardDatabaseSettings::setSortKey(QString shortName, unsigned int sortKey) void CardDatabaseSettings::setSortKey(QString shortName, unsigned int sortKey)

View file

@ -4,13 +4,14 @@
#include "settingsmanager.h" #include "settingsmanager.h"
#include <QObject> #include <QObject>
#include <QVariant>
#include <QSettings> #include <QSettings>
#include <QVariant>
class CardDatabaseSettings : public SettingsManager class CardDatabaseSettings : public SettingsManager
{ {
Q_OBJECT Q_OBJECT
friend class SettingsCache; friend class SettingsCache;
public: public:
void setSortKey(QString shortName, unsigned int sortKey); void setSortKey(QString shortName, unsigned int sortKey);
void setEnabled(QString shortName, bool enabled); void setEnabled(QString shortName, bool enabled);

View file

@ -95,5 +95,3 @@ bool GameFiltersSettings::isGameTypeEnabled(QString gametype)
QVariant previous = getValue("game_type/" + hashGameType(gametype), "filter_games"); QVariant previous = getValue("game_type/" + hashGameType(gametype), "filter_games");
return previous == QVariant() ? false : previous.toBool(); return previous == QVariant() ? false : previous.toBool();
} }

View file

@ -7,6 +7,7 @@ class GameFiltersSettings : public SettingsManager
{ {
Q_OBJECT Q_OBJECT
friend class SettingsCache; friend class SettingsCache;
public: public:
bool isShowBuddiesOnlyGames(); bool isShowBuddiesOnlyGames();
bool isUnavailableGamesVisible(); bool isUnavailableGamesVisible();

View file

@ -8,6 +8,7 @@ class LayoutsSettings : public SettingsManager
{ {
Q_OBJECT Q_OBJECT
friend class SettingsCache; friend class SettingsCache;
public: public:
void setDeckEditorLayoutState(const QByteArray &value); void setDeckEditorLayoutState(const QByteArray &value);
void setDeckEditorGeometry(const QByteArray &value); void setDeckEditorGeometry(const QByteArray &value);

View file

@ -175,7 +175,12 @@ bool ServersSettings::getClearDebugLogStatus(bool abDefaultValue)
return cbFlushLog == QVariant() ? abDefaultValue : cbFlushLog.toBool(); return cbFlushLog == QVariant() ? abDefaultValue : cbFlushLog.toBool();
} }
void ServersSettings::addNewServer(QString saveName, QString serv, QString port, QString username, QString password, bool savePassword) void ServersSettings::addNewServer(QString saveName,
QString serv,
QString port,
QString username,
QString password,
bool savePassword)
{ {
if (updateExistingServer(saveName, serv, port, username, password, savePassword)) if (updateExistingServer(saveName, serv, port, username, password, savePassword))
return; return;
@ -189,17 +194,19 @@ void ServersSettings::addNewServer(QString saveName, QString serv, QString port,
setValue(savePassword, QString("savePassword%1").arg(index), "server", "server_details"); setValue(savePassword, QString("savePassword%1").arg(index), "server", "server_details");
setValue(index, "totalServers", "server", "server_details"); setValue(index, "totalServers", "server", "server_details");
setValue(password, QString("password%1").arg(index), "server", "server_details"); setValue(password, QString("password%1").arg(index), "server", "server_details");
} }
bool ServersSettings::updateExistingServer(QString saveName, QString serv, QString port, QString username, QString password, bool savePassword) bool ServersSettings::updateExistingServer(QString saveName,
QString serv,
QString port,
QString username,
QString password,
bool savePassword)
{ {
int size = getValue("totalServers", "server", "server_details").toInt() + 1; int size = getValue("totalServers", "server", "server_details").toInt() + 1;
for (int i = 0; i < size; i++) for (int i = 0; i < size; i++) {
{ if (saveName == getValue(QString("saveName%1").arg(i), "server", "server_details").toString()) {
if (saveName == getValue(QString("saveName%1").arg(i), "server", "server_details").toString())
{
setValue(serv, QString("server%1").arg(i), "server", "server_details"); setValue(serv, QString("server%1").arg(i), "server", "server_details");
setValue(port, QString("port%1").arg(i), "server", "server_details"); setValue(port, QString("port%1").arg(i), "server", "server_details");
setValue(username, QString("username%1").arg(i), "server", "server_details"); setValue(username, QString("username%1").arg(i), "server", "server_details");

View file

@ -37,8 +37,14 @@ public:
void setFPPort(QString port); void setFPPort(QString port);
void setSavePassword(int save); void setSavePassword(int save);
void setFPPlayerName(QString playerName); void setFPPlayerName(QString playerName);
void addNewServer(QString saveName, QString serv, QString port, QString username, QString password, bool savePassword); void
bool updateExistingServer(QString saveName, QString serv, QString port, QString username, QString password, bool savePassword); addNewServer(QString saveName, QString serv, QString port, QString username, QString password, bool savePassword);
bool updateExistingServer(QString saveName,
QString serv,
QString port,
QString username,
QString password,
bool savePassword);
void setClearDebugLogStatus(bool abIsChecked); void setClearDebugLogStatus(bool abIsChecked);
bool getClearDebugLogStatus(bool abDefaultValue); bool getClearDebugLogStatus(bool abDefaultValue);

View file

@ -1,56 +1,48 @@
#include "settingsmanager.h" #include "settingsmanager.h"
SettingsManager::SettingsManager(QString settingPath, QObject *parent) : QObject(parent), settings(settingPath, QSettings::IniFormat) SettingsManager::SettingsManager(QString settingPath, QObject *parent)
: QObject(parent), settings(settingPath, QSettings::IniFormat)
{ {
} }
void SettingsManager::setValue(QVariant value, QString name, QString group, QString subGroup) void SettingsManager::setValue(QVariant value, QString name, QString group, QString subGroup)
{ {
if (!group.isEmpty()) if (!group.isEmpty()) {
{
settings.beginGroup(group); settings.beginGroup(group);
} }
if (!subGroup.isEmpty()) if (!subGroup.isEmpty()) {
{
settings.beginGroup(subGroup); settings.beginGroup(subGroup);
} }
settings.setValue(name, value); settings.setValue(name, value);
if (!subGroup.isEmpty()) if (!subGroup.isEmpty()) {
{
settings.endGroup(); settings.endGroup();
} }
if (!group.isEmpty()) if (!group.isEmpty()) {
{
settings.endGroup(); settings.endGroup();
} }
} }
QVariant SettingsManager::getValue(QString name, QString group, QString subGroup) QVariant SettingsManager::getValue(QString name, QString group, QString subGroup)
{ {
if (!group.isEmpty()) if (!group.isEmpty()) {
{
settings.beginGroup(group); settings.beginGroup(group);
} }
if (!subGroup.isEmpty()) if (!subGroup.isEmpty()) {
{
settings.beginGroup(subGroup); settings.beginGroup(subGroup);
} }
QVariant value = settings.value(name); QVariant value = settings.value(name);
if (!subGroup.isEmpty()) if (!subGroup.isEmpty()) {
{
settings.endGroup(); settings.endGroup();
} }
if (!group.isEmpty()) if (!group.isEmpty()) {
{
settings.endGroup(); settings.endGroup();
} }

View file

@ -5,25 +5,59 @@
void CardDatabaseSettings::setSortKey(QString /* shortName */, unsigned int /* sortKey */){}; void CardDatabaseSettings::setSortKey(QString /* shortName */, unsigned int /* sortKey */){};
void CardDatabaseSettings::setEnabled(QString /* shortName */, bool /* enabled */){}; void CardDatabaseSettings::setEnabled(QString /* shortName */, bool /* enabled */){};
void CardDatabaseSettings::setIsKnown(QString /* shortName */, bool /* isknown */){}; void CardDatabaseSettings::setIsKnown(QString /* shortName */, bool /* isknown */){};
unsigned int CardDatabaseSettings::getSortKey(QString /* shortName */) { return 0; }; unsigned int CardDatabaseSettings::getSortKey(QString /* shortName */)
bool CardDatabaseSettings::isEnabled(QString /* shortName */) { return true; }; {
bool CardDatabaseSettings::isKnown(QString /* shortName */) { return true; }; return 0;
};
bool CardDatabaseSettings::isEnabled(QString /* shortName */)
{
return true;
};
bool CardDatabaseSettings::isKnown(QString /* shortName */)
{
return true;
};
SettingsCache::SettingsCache() { cardDatabaseSettings = new CardDatabaseSettings(); }; SettingsCache::SettingsCache()
SettingsCache::~SettingsCache() { delete cardDatabaseSettings; }; {
QString SettingsCache::getCustomCardDatabasePath() const { return QString("%1/customsets/").arg(CARDDB_DATADIR); } cardDatabaseSettings = new CardDatabaseSettings();
QString SettingsCache::getCardDatabasePath() const { return QString("%1/cards.xml").arg(CARDDB_DATADIR); } };
QString SettingsCache::getTokenDatabasePath() const { return QString("%1/tokens.xml").arg(CARDDB_DATADIR); } SettingsCache::~SettingsCache()
QString SettingsCache::getSpoilerCardDatabasePath() const { return QString("%1/spoiler.xml").arg(CARDDB_DATADIR); } {
CardDatabaseSettings& SettingsCache::cardDatabase() const { return *cardDatabaseSettings; } delete cardDatabaseSettings;
};
QString SettingsCache::getCustomCardDatabasePath() const
{
return QString("%1/customsets/").arg(CARDDB_DATADIR);
}
QString SettingsCache::getCardDatabasePath() const
{
return QString("%1/cards.xml").arg(CARDDB_DATADIR);
}
QString SettingsCache::getTokenDatabasePath() const
{
return QString("%1/tokens.xml").arg(CARDDB_DATADIR);
}
QString SettingsCache::getSpoilerCardDatabasePath() const
{
return QString("%1/spoiler.xml").arg(CARDDB_DATADIR);
}
CardDatabaseSettings &SettingsCache::cardDatabase() const
{
return *cardDatabaseSettings;
}
SettingsCache *settingsCache; SettingsCache *settingsCache;
void PictureLoader::clearPixmapCache(CardInfoPtr /* card */) { } void PictureLoader::clearPixmapCache(CardInfoPtr /* card */)
{
}
namespace { namespace
{
TEST(CardDatabaseTest, LoadXml) { TEST(CardDatabaseTest, LoadXml)
{
settingsCache = new SettingsCache; settingsCache = new SettingsCache;
CardDatabase *db = new CardDatabase; CardDatabase *db = new CardDatabase;
@ -50,9 +84,10 @@ namespace {
ASSERT_EQ(0, db->getAllMainCardTypes().size()) << "Types not empty after clear"; ASSERT_EQ(0, db->getAllMainCardTypes().size()) << "Types not empty after clear";
ASSERT_EQ(NotLoaded, db->getLoadStatus()) << "Incorrect status after clear"; ASSERT_EQ(NotLoaded, db->getLoadStatus()) << "Incorrect status after clear";
} }
} } // namespace
int main(int argc, char **argv) { int main(int argc, char **argv)
{
::testing::InitGoogleTest(&argc, argv); ::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS(); return RUN_ALL_TESTS();
} }

View file

@ -22,10 +22,12 @@ public:
bool isKnown(QString shortName); bool isKnown(QString shortName);
}; };
class SettingsCache: public QObject { class SettingsCache : public QObject
{
Q_OBJECT Q_OBJECT
private: private:
CardDatabaseSettings *cardDatabaseSettings; CardDatabaseSettings *cardDatabaseSettings;
public: public:
SettingsCache(); SettingsCache();
~SettingsCache(); ~SettingsCache();
@ -38,9 +40,9 @@ signals:
void cardDatabasePathChanged(); void cardDatabasePathChanged();
}; };
#define PICTURELOADER_H #define PICTURELOADER_H
class PictureLoader { class PictureLoader
{
void clearPixmapCache(CardInfoPtr card); void clearPixmapCache(CardInfoPtr card);
}; };

View file

@ -1,16 +1,19 @@
#include "gtest/gtest.h" #include "gtest/gtest.h"
namespace { namespace
class FooTest : public ::testing::Test { {
class FooTest : public ::testing::Test
{
}; };
TEST(DummyTest, Works) { TEST(DummyTest, Works)
{
ASSERT_EQ(1, 1) << "One is not equal to one"; ASSERT_EQ(1, 1) << "One is not equal to one";
} }
} } // namespace
int main(int argc, char **argv) { int main(int argc, char **argv)
{
::testing::InitGoogleTest(&argc, argv); ::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS(); return RUN_ALL_TESTS();
} }

View file

@ -1,10 +1,11 @@
#include "gtest/gtest.h"
#include "loading_from_clipboard_test.h" #include "loading_from_clipboard_test.h"
#include <QTextStream>
#include "../../common/decklist.h" #include "../../common/decklist.h"
#include "gtest/gtest.h"
#include <QTextStream>
DeckList *fromClipboard(QString *clipboard); DeckList *fromClipboard(QString *clipboard);
DeckList *fromClipboard(QString *clipboard) { DeckList *fromClipboard(QString *clipboard)
{
DeckList *deckList = new DeckList; DeckList *deckList = new DeckList;
QTextStream *stream = new QTextStream(clipboard); QTextStream *stream = new QTextStream(clipboard);
deckList->loadFromStream_Plain(*stream); deckList->loadFromStream_Plain(*stream);
@ -13,13 +14,17 @@ DeckList *fromClipboard(QString *clipboard) {
using CardRows = QMap<QString, int>; using CardRows = QMap<QString, int>;
struct DecklistBuilder { struct DecklistBuilder
{
CardRows actualMainboard; CardRows actualMainboard;
CardRows actualSideboard; CardRows actualSideboard;
explicit DecklistBuilder() : actualMainboard({}), actualSideboard({}) {} explicit DecklistBuilder() : actualMainboard({}), actualSideboard({})
{
}
void operator()(const InnerDecklistNode *innerDecklistNode, const DecklistCardNode *card) { void operator()(const InnerDecklistNode *innerDecklistNode, const DecklistCardNode *card)
{
if (innerDecklistNode->getName() == DECK_ZONE_MAIN) { if (innerDecklistNode->getName() == DECK_ZONE_MAIN) {
actualMainboard[card->getName()] += card->getNumber(); actualMainboard[card->getName()] += card->getNumber();
} else if (innerDecklistNode->getName() == DECK_ZONE_SIDE) { } else if (innerDecklistNode->getName() == DECK_ZONE_SIDE) {
@ -29,55 +34,53 @@ struct DecklistBuilder {
} }
} }
CardRows mainboard() { CardRows mainboard()
{
return actualMainboard; return actualMainboard;
} }
CardRows sideboard() { CardRows sideboard()
{
return actualSideboard; return actualSideboard;
} }
}; };
namespace { namespace
{
TEST(LoadingFromClipboardTest, EmptyDeck) TEST(LoadingFromClipboardTest, EmptyDeck)
{ {
DeckList *deckList = fromClipboard(new QString("")); DeckList *deckList = fromClipboard(new QString(""));
ASSERT_TRUE(deckList->getCardList().isEmpty()); ASSERT_TRUE(deckList->getCardList().isEmpty());
} }
TEST(LoadingFromClipboardTest, EmptySideboard) { TEST(LoadingFromClipboardTest, EmptySideboard)
{
DeckList *deckList = fromClipboard(new QString("Sideboard")); DeckList *deckList = fromClipboard(new QString("Sideboard"));
ASSERT_TRUE(deckList->getCardList().isEmpty()); ASSERT_TRUE(deckList->getCardList().isEmpty());
} }
TEST(LoadingFromClipboardTest, QuantityPrefixed) { TEST(LoadingFromClipboardTest, QuantityPrefixed)
QString *clipboard = new QString( {
"1 Mountain\n" QString *clipboard = new QString("1 Mountain\n"
"2x Island\n" "2x Island\n"
"3X FOREST\n" "3X FOREST\n");
);
DeckList *deckList = fromClipboard(clipboard); DeckList *deckList = fromClipboard(clipboard);
DecklistBuilder decklistBuilder = DecklistBuilder(); DecklistBuilder decklistBuilder = DecklistBuilder();
deckList->forEachCard(decklistBuilder); deckList->forEachCard(decklistBuilder);
CardRows expectedMainboard = CardRows({ CardRows expectedMainboard = CardRows({{"mountain", 1}, {"island", 2}, {"forest", 3}});
{"mountain", 1},
{"island", 2},
{"forest", 3}
});
CardRows expectedSideboard = CardRows({}); CardRows expectedSideboard = CardRows({});
ASSERT_EQ(expectedMainboard, decklistBuilder.mainboard()); ASSERT_EQ(expectedMainboard, decklistBuilder.mainboard());
ASSERT_EQ(expectedSideboard, decklistBuilder.sideboard()); ASSERT_EQ(expectedSideboard, decklistBuilder.sideboard());
} }
TEST(LoadingFromClipboardTest, CommentsAreIgnored) { TEST(LoadingFromClipboardTest, CommentsAreIgnored)
QString *clipboard = new QString( {
"//1 Mountain\n" QString *clipboard = new QString("//1 Mountain\n"
"//2x Island\n" "//2x Island\n"
"//SB:2x Island\n" "//SB:2x Island\n");
);
DeckList *deckList = fromClipboard(clipboard); DeckList *deckList = fromClipboard(clipboard);
@ -91,130 +94,106 @@ namespace {
ASSERT_EQ(expectedSideboard, decklistBuilder.sideboard()); ASSERT_EQ(expectedSideboard, decklistBuilder.sideboard());
} }
TEST(LoadingFromClipboardTest, SideboardPrefix) { TEST(LoadingFromClipboardTest, SideboardPrefix)
QString *clipboard = new QString( {
"1 Mountain\n" QString *clipboard = new QString("1 Mountain\n"
"SB: 1 Mountain\n" "SB: 1 Mountain\n"
"SB: 2x Island\n" "SB: 2x Island\n");
);
DeckList *deckList = fromClipboard(clipboard); DeckList *deckList = fromClipboard(clipboard);
DecklistBuilder decklistBuilder = DecklistBuilder(); DecklistBuilder decklistBuilder = DecklistBuilder();
deckList->forEachCard(decklistBuilder); deckList->forEachCard(decklistBuilder);
CardRows expectedMainboard = CardRows({ CardRows expectedMainboard = CardRows({{"mountain", 1}});
{"mountain", 1} CardRows expectedSideboard = CardRows({{"mountain", 1}, {"island", 2}});
});
CardRows expectedSideboard = CardRows({
{"mountain", 1},
{"island", 2}
});
ASSERT_EQ(expectedMainboard, decklistBuilder.mainboard()); ASSERT_EQ(expectedMainboard, decklistBuilder.mainboard());
ASSERT_EQ(expectedSideboard, decklistBuilder.sideboard()); ASSERT_EQ(expectedSideboard, decklistBuilder.sideboard());
} }
TEST(LoadingFromClipboardTest, UnknownCardsAreNotDiscarded) { TEST(LoadingFromClipboardTest, UnknownCardsAreNotDiscarded)
QString *clipboard = new QString( {
"1 CardThatDoesNotExistInCardsXml\n" QString *clipboard = new QString("1 CardThatDoesNotExistInCardsXml\n");
);
DeckList *deckList = fromClipboard(clipboard); DeckList *deckList = fromClipboard(clipboard);
DecklistBuilder decklistBuilder = DecklistBuilder(); DecklistBuilder decklistBuilder = DecklistBuilder();
deckList->forEachCard(decklistBuilder); deckList->forEachCard(decklistBuilder);
CardRows expectedMainboard = CardRows({ CardRows expectedMainboard = CardRows({{"cardthatdoesnotexistincardsxml", 1}});
{"cardthatdoesnotexistincardsxml", 1}
});
CardRows expectedSideboard = CardRows({}); CardRows expectedSideboard = CardRows({});
ASSERT_EQ(expectedMainboard, decklistBuilder.mainboard()); ASSERT_EQ(expectedMainboard, decklistBuilder.mainboard());
ASSERT_EQ(expectedSideboard, decklistBuilder.sideboard()); ASSERT_EQ(expectedSideboard, decklistBuilder.sideboard());
} }
TEST(LoadingFromClipboardTest, RemoveBlankEntriesFromBeginningAndEnd) { TEST(LoadingFromClipboardTest, RemoveBlankEntriesFromBeginningAndEnd)
QString *clipboard = new QString( {
"\n" QString *clipboard = new QString("\n"
"\n" "\n"
"\n" "\n"
"1x Algae Gharial\n" "1x Algae Gharial\n"
"3x CardThatDoesNotExistInCardsXml\n" "3x CardThatDoesNotExistInCardsXml\n"
"2x Phelddagrif\n" "2x Phelddagrif\n"
"\n" "\n"
"\n" "\n");
);
DeckList *deckList = fromClipboard(clipboard); DeckList *deckList = fromClipboard(clipboard);
DecklistBuilder decklistBuilder = DecklistBuilder(); DecklistBuilder decklistBuilder = DecklistBuilder();
deckList->forEachCard(decklistBuilder); deckList->forEachCard(decklistBuilder);
CardRows expectedMainboard = CardRows({ CardRows expectedMainboard =
{"algae gharial", 1}, CardRows({{"algae gharial", 1}, {"cardthatdoesnotexistincardsxml", 3}, {"phelddagrif", 2}});
{"cardthatdoesnotexistincardsxml", 3},
{"phelddagrif", 2}
});
CardRows expectedSideboard = CardRows({}); CardRows expectedSideboard = CardRows({});
ASSERT_EQ(expectedMainboard, decklistBuilder.mainboard()); ASSERT_EQ(expectedMainboard, decklistBuilder.mainboard());
ASSERT_EQ(expectedSideboard, decklistBuilder.sideboard()); ASSERT_EQ(expectedSideboard, decklistBuilder.sideboard());
} }
TEST(LoadingFromClipboardTest, UseFirstBlankIfOnlyOneBlankToSplitSideboard) { TEST(LoadingFromClipboardTest, UseFirstBlankIfOnlyOneBlankToSplitSideboard)
QString *clipboard = new QString( {
"1x Algae Gharial\n" QString *clipboard = new QString("1x Algae Gharial\n"
"3x CardThatDoesNotExistInCardsXml\n" "3x CardThatDoesNotExistInCardsXml\n"
"\n" "\n"
"2x Phelddagrif\n" "2x Phelddagrif\n");
);
DeckList *deckList = fromClipboard(clipboard); DeckList *deckList = fromClipboard(clipboard);
DecklistBuilder decklistBuilder = DecklistBuilder(); DecklistBuilder decklistBuilder = DecklistBuilder();
deckList->forEachCard(decklistBuilder); deckList->forEachCard(decklistBuilder);
CardRows expectedMainboard = CardRows({ CardRows expectedMainboard = CardRows({{"algae gharial", 1}, {"cardthatdoesnotexistincardsxml", 3}});
{"algae gharial", 1}, CardRows expectedSideboard = CardRows({{"phelddagrif", 2}});
{"cardthatdoesnotexistincardsxml", 3}
});
CardRows expectedSideboard = CardRows({
{"phelddagrif", 2}
});
ASSERT_EQ(expectedMainboard, decklistBuilder.mainboard()); ASSERT_EQ(expectedMainboard, decklistBuilder.mainboard());
ASSERT_EQ(expectedSideboard, decklistBuilder.sideboard()); ASSERT_EQ(expectedSideboard, decklistBuilder.sideboard());
} }
TEST(LoadingFromClipboardTest, IfMultipleScatteredBlanksAllMainBoard) { TEST(LoadingFromClipboardTest, IfMultipleScatteredBlanksAllMainBoard)
QString *clipboard = new QString( {
"1x Algae Gharial\n" QString *clipboard = new QString("1x Algae Gharial\n"
"3x CardThatDoesNotExistInCardsXml\n" "3x CardThatDoesNotExistInCardsXml\n"
"\n" "\n"
"2x Phelddagrif\n" "2x Phelddagrif\n"
"\n" "\n"
"3 Giant Growth\n" "3 Giant Growth\n");
);
DeckList *deckList = fromClipboard(clipboard); DeckList *deckList = fromClipboard(clipboard);
DecklistBuilder decklistBuilder = DecklistBuilder(); DecklistBuilder decklistBuilder = DecklistBuilder();
deckList->forEachCard(decklistBuilder); deckList->forEachCard(decklistBuilder);
CardRows expectedMainboard = CardRows({ CardRows expectedMainboard = CardRows(
{"algae gharial", 1}, {{"algae gharial", 1}, {"cardthatdoesnotexistincardsxml", 3}, {"phelddagrif", 2}, {"giant growth", 3}});
{"cardthatdoesnotexistincardsxml", 3},
{"phelddagrif", 2},
{"giant growth", 3}
});
CardRows expectedSideboard = CardRows({}); CardRows expectedSideboard = CardRows({});
ASSERT_EQ(expectedMainboard, decklistBuilder.mainboard()); ASSERT_EQ(expectedMainboard, decklistBuilder.mainboard());
ASSERT_EQ(expectedSideboard, decklistBuilder.sideboard()); ASSERT_EQ(expectedSideboard, decklistBuilder.sideboard());
} }
TEST(LoadingFromClipboardTest, LotsOfStuffInBulkTesting) { TEST(LoadingFromClipboardTest, LotsOfStuffInBulkTesting)
QString *clipboard = new QString( {
"\n" QString *clipboard = new QString("\n"
"\n" "\n"
"\n" "\n"
"1x test1\n" "1x test1\n"
@ -233,35 +212,26 @@ namespace {
"\n" "\n"
"\n" "\n"
"\n" "\n"
"\n" "\n");
);
DeckList *deckList = fromClipboard(clipboard); DeckList *deckList = fromClipboard(clipboard);
DecklistBuilder decklistBuilder = DecklistBuilder(); DecklistBuilder decklistBuilder = DecklistBuilder();
deckList->forEachCard(decklistBuilder); deckList->forEachCard(decklistBuilder);
CardRows expectedMainboard = CardRows({ CardRows expectedMainboard = CardRows({{"test1", 1}, {"test2", 2}, {"test3", 3}, {"test4", 4}, {"testnovaluemb", 1}
{"test1", 1},
{"test2", 2},
{"test3", 3},
{"test4", 4},
{"testnovaluemb", 1}
}); });
CardRows expectedSideboard = CardRows({ CardRows expectedSideboard = CardRows({{"testsb", 10}, {"test5", 5}, {"test6", 6}, {"testnovaluesb", 1}
{"testsb", 10},
{"test5", 5},
{"test6", 6},
{"testnovaluesb", 1}
}); });
ASSERT_EQ(expectedMainboard, decklistBuilder.mainboard()); ASSERT_EQ(expectedMainboard, decklistBuilder.mainboard());
ASSERT_EQ(expectedSideboard, decklistBuilder.sideboard()); ASSERT_EQ(expectedSideboard, decklistBuilder.sideboard());
} }
} } // namespace
int main(int argc, char **argv) { int main(int argc, char **argv)
{
::testing::InitGoogleTest(&argc, argv); ::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS(); return RUN_ALL_TESTS();
} }