move to QString

This commit is contained in:
mrbesen 2023-05-31 22:22:23 +02:00
parent 42ff827caf
commit b919a64ae6
Signed by untrusted user: MrBesen
GPG Key ID: 596B2350DCD67504
42 changed files with 476 additions and 474 deletions

View File

@ -8,12 +8,12 @@ class ChampCache {
public: public:
ChampCache(); ChampCache();
std::string getVersion(); QString getVersion();
QJsonDocument getChamps(); QJsonDocument getChamps();
void saveChamps(QJsonDocument doc, const std::string& version); void saveChamps(QJsonDocument doc, const QString& version);
private: private:
std::string basefolder; QString basefolder;
uint64_t maxage = 86400; // is in seconds uint64_t maxage = 86400; // is in seconds
}; };

View File

@ -1,25 +1,25 @@
#pragma once #pragma once
#include <istream> #include <istream>
#include <string>
#include <memory> #include <memory>
#include <vector>
#include <QString>
class ClientAccess { class ClientAccess {
ClientAccess(); ClientAccess();
public: public:
ClientAccess(const std::string& token, uint16_t port); ClientAccess(const QString& token, uint16_t port);
static std::shared_ptr<ClientAccess> find(); static std::shared_ptr<ClientAccess> find();
public: public:
std::string getBasicAuth() const; QString getBasicAuth() const;
uint16_t getPort() const; uint16_t getPort() const;
std::string getURL() const; QString getURL() const;
private: private:
std::string authcode; QString authcode;
uint16_t port = 0; uint16_t port = 0;
}; };

View File

@ -37,7 +37,7 @@ public:
ENDOFGAME, ENDOFGAME,
TERMINATEDINERROR, TERMINATEDINERROR,
}; };
static GameflowPhase toGameflowPhase(const std::string&); static GameflowPhase toGameflowPhase(const QString&);
enum class ChampSelectPhase : uint32_t { enum class ChampSelectPhase : uint32_t {
INVALID = 0, INVALID = 0,
@ -46,7 +46,7 @@ public:
BAN_PICK, BAN_PICK,
FINALIZATION FINALIZATION
}; };
static ChampSelectPhase toChampSelectPhase(const std::string& str); static ChampSelectPhase toChampSelectPhase(const QString& str);
enum class ChampSelectActionType : uint32_t { enum class ChampSelectActionType : uint32_t {
INVALID = 0, INVALID = 0,
@ -54,7 +54,7 @@ public:
PICK, PICK,
TEN_BANS_REVEAL, TEN_BANS_REVEAL,
}; };
static ChampSelectActionType toChampSelectActionType(const std::string& str); static ChampSelectActionType toChampSelectActionType(const QString& str);
struct TimerInfo { struct TimerInfo {
int64_t adjustedTimeLeftInPhase = 0; int64_t adjustedTimeLeftInPhase = 0;
@ -71,12 +71,12 @@ public:
struct PlayerInfo { struct PlayerInfo {
int64_t summonerid = 0; // to test validity -> test if this is not null int64_t summonerid = 0; // to test validity -> test if this is not null
std::string gameName; QString gameName;
std::string name; QString name;
std::string statusMessage; QString statusMessage;
// lol specific // lol specific
std::string puuid; QString puuid;
uint32_t level = 0; uint32_t level = 0;
}; };
@ -139,7 +139,7 @@ public:
struct RunePage { struct RunePage {
uint64_t id = 0; uint64_t id = 0;
uint64_t lastmodified = 0; uint64_t lastmodified = 0;
std::string name; QString name;
bool isDeleteable = true; bool isDeleteable = true;
bool isEditable = true; bool isEditable = true;
bool isActive = false; // what is the difference between active and current???? bool isActive = false; // what is the difference between active and current????
@ -153,30 +153,30 @@ public:
}; };
struct Message { struct Message {
std::string body; QString body;
std::string fromId; QString fromId;
std::string fromPid; QString fromPid;
int64_t fromSummonerId; int64_t fromSummonerId;
std::string id; QString id;
bool isHistorical; bool isHistorical;
std::string timestamp; QString timestamp;
std::string type; // known types: chat (1:1), customGame, championSelect, groupchat QString type; // known types: chat (1:1), customGame, championSelect, groupchat
Message(); Message();
explicit Message(const QJsonObject& json); explicit Message(const QJsonObject& json);
}; };
struct Conversation { struct Conversation {
std::string gameName; QString gameName;
std::string gameTag; QString gameTag;
std::string id; QString id;
bool isMuted; bool isMuted;
std::shared_ptr<Message> lastMessage; std::shared_ptr<Message> lastMessage;
std::string name; QString name;
std::string password; QString password;
std::string pid; QString pid;
std::string targetRegion; QString targetRegion;
std::string type; QString type;
int64_t unreadMessageCount; int64_t unreadMessageCount;
Conversation(); Conversation();
@ -201,7 +201,7 @@ public:
// chats // chats
std::vector<Conversation> getAllConversations(); std::vector<Conversation> getAllConversations();
Message sendMessage(const std::string& chatid, const std::string& messagebody); Message sendMessage(const QString& chatid, const QString& messagebody);
// rune stuff // rune stuff
RunePage getCurrentRunePage(); RunePage getCurrentRunePage();
@ -214,7 +214,7 @@ public:
std::vector<RuneAspekt> getAllRuneAspekts(); std::vector<RuneAspekt> getAllRuneAspekts();
std::vector<RuneStyle> getAllRuneStyles(); std::vector<RuneStyle> getAllRuneStyles();
const std::string& getRuneStyleByID(uint32_t id); const QString& getRuneStyleByID(uint32_t id);
QPixmap getImageResource(QString path); QPixmap getImageResource(QString path);
@ -225,7 +225,13 @@ private:
DataDragonImageCache imageCache; DataDragonImageCache imageCache;
}; };
std::ostream& operator<<(std::ostream&, const ClientAPI::ReadyCheckState&); #define DEFINEOPERATOR(CLASS) \
std::ostream& operator<<(std::ostream&, const ClientAPI::GameflowPhase&); std::ostream& operator<<(std::ostream&, const ClientAPI::CLASS&); \
std::ostream& operator<<(std::ostream&, const ClientAPI::ChampSelectPhase&); QDebug operator<<(QDebug, const ClientAPI::CLASS&);
std::ostream& operator<<(std::ostream&, const ClientAPI::ChampSelectActionType&);
DEFINEOPERATOR(ReadyCheckState);
DEFINEOPERATOR(GameflowPhase);
DEFINEOPERATOR(ChampSelectPhase);
DEFINEOPERATOR(ChampSelectActionType);
#undef DEFINEOPERATOR

View File

@ -13,7 +13,7 @@ public:
StageConfig(const QJsonObject&); StageConfig(const QJsonObject&);
operator QJsonObject() const; operator QJsonObject() const;
std::vector<std::string> champs; std::vector<QString> champs;
bool enabled = false; bool enabled = false;
}; };
@ -71,7 +71,7 @@ public:
RootConfig& getConfig(); RootConfig& getConfig();
private: private:
std::string configFolderPath; QString configFolderPath;
std::string configFilePath; QString configFilePath;
RootConfig root; RootConfig root;
}; };

View File

@ -4,7 +4,7 @@
#include <functional> #include <functional>
#include <mutex> #include <mutex>
#include <set> #include <set>
#include <string> #include <QString>
#include <thread> #include <thread>
#include <vector> #include <vector>
@ -19,7 +19,7 @@ class DataDragon : public RestClient {
public: public:
using notifyImgfunc_t = std::function<void(QPixmap)>; using notifyImgfunc_t = std::function<void(QPixmap)>;
DataDragon(const std::string& locale); DataDragon(const QString& locale);
~DataDragon(); ~DataDragon();
DataDragon(const DataDragon&) = delete; DataDragon(const DataDragon&) = delete;
DataDragon& operator=(const DataDragon&) = delete; DataDragon& operator=(const DataDragon&) = delete;
@ -29,11 +29,11 @@ public:
ChampData(); ChampData();
ChampData(const QJsonObject& source); ChampData(const QJsonObject& source);
std::string name; QString name;
std::string id; QString id;
int key = 0; int key = 0;
std::string partype; QString partype;
std::string title; QString title;
}; };
enum class ImageType { enum class ImageType {
@ -43,25 +43,25 @@ public:
}; };
// might block until version is available // might block until version is available
const std::string& getVersion(); const QString& getVersion();
// might block until champ data is available // might block until champ data is available
const std::vector<ChampData>& getChamps(); const std::vector<ChampData>& getChamps();
// might block until image is downloaded // might block until image is downloaded
QPixmap getImage(const std::string& champid, ImageType imgtype = ImageType::SQUARE, bool writeMemcache = true); QPixmap getImage(const QString& champid, ImageType imgtype = ImageType::SQUARE, bool writeMemcache = true);
void getImageAsnyc(const std::string& champid, notifyImgfunc_t func, ImageType imgtype = ImageType::SQUARE); void getImageAsnyc(const QString& champid, notifyImgfunc_t func, ImageType imgtype = ImageType::SQUARE);
// might block until champ data is available // might block until champ data is available
const ChampData& getBestMatchingChamp(const std::string& name, int* count = nullptr); const ChampData& getBestMatchingChamp(const QString& name, int* count = nullptr);
std::vector<const ChampData*> getMatchingChamp(const std::string& name, uint32_t limit = 25); std::vector<const ChampData*> getMatchingChamp(const QString& name, uint32_t limit = 25);
const ChampData* getChampByID(uint32_t id); const ChampData* getChampByID(uint32_t id);
std::vector<uint32_t> resolveChampIDs(const std::vector<std::string>& champnames); std::vector<uint32_t> resolveChampIDs(const std::vector<QString>& champnames);
static const ChampData EMPTYCHAMP; static const ChampData EMPTYCHAMP;
protected: protected:
std::string getImageUrl(const std::string& champid, ImageType type); QString getImageUrl(const QString& champid, ImageType type);
std::string getCDNString() const; QString getCDNString() const;
void prefetchChampImage(const std::string& champid, ImageType imgtype = ImageType::SQUARE); void prefetchChampImage(const QString& champid, ImageType imgtype = ImageType::SQUARE);
void getVersionInternal(); void getVersionInternal();
void getChampsInternal(); void getChampsInternal();
void startThread(); void startThread();
@ -69,16 +69,16 @@ protected:
void stopAndJoinThread(); void stopAndJoinThread();
void threadLoop(); void threadLoop();
std::string locale; QString locale;
std::string version; QString version;
std::vector<ChampData> champs; std::vector<ChampData> champs;
std::mutex cachedatamutex; std::mutex cachedatamutex;
std::condition_variable cachedatacv; std::condition_variable cachedatacv;
std::set<std::string> notDownloadedImages; // the champions of which the square image is not downloaded yet. Is used to download them on idle std::set<QString> notDownloadedImages; // the champions of which the square image is not downloaded yet. Is used to download them on idle
private: private:
struct Task { struct Task {
std::string champid; QString champid;
notifyImgfunc_t func; notifyImgfunc_t func;
ImageType type; ImageType type;
}; };

View File

@ -1,20 +1,20 @@
#pragma once #pragma once
#include <string> #include <QString>
#include <QByteArray> #include <QByteArray>
#include <QPixmap> #include <QPixmap>
class DataDragonImageCache { class DataDragonImageCache {
public: public:
DataDragonImageCache(const std::string& folderextra, const std::string& imageext = ".jpg"); DataDragonImageCache(const QString& folderextra, const QString& imageext = ".jpg");
~DataDragonImageCache(); ~DataDragonImageCache();
bool hasImage(const std::string& name); bool hasImage(const QString& name);
QPixmap getImage(const std::string& name); QPixmap getImage(const QString& name);
void addImageRaw(const QByteArray& arr, const std::string& name); void addImageRaw(const QByteArray& arr, const QString& name);
private: private:
std::string getFilepath(const std::string& name) const; QString getFilepath(const QString& name) const;
std::string cacheDir; QString cacheDir;
std::string imageext; // file extention including dot QString imageext; // file extention including dot
}; };

View File

@ -3,12 +3,13 @@
// stuff required for file handling // stuff required for file handling
#include <string> #include <string>
#include <QString>
// create a directory and its parents // create a directory and its parents
bool mkdirs(const std::string& path); bool mkdirs(const QString& path);
// get $HOME or a useful default value // get $HOME or a useful default value
std::string getHome(); QString getHome();
// folder for caching example: $HOME/.cache/lolautoaccept/ // folder for caching example: $HOME/.cache/lolautoaccept/
std::string getCache(); QString getCache();

View File

@ -22,7 +22,7 @@ template<>
uint64_t convert(const QJsonValue& val); uint64_t convert(const QJsonValue& val);
template<> template<>
std::string convert(const QJsonValue& val); QString convert(const QJsonValue& val);
template<> template<>
bool convert(const QJsonValue& val); bool convert(const QJsonValue& val);

View File

@ -51,9 +51,9 @@ protected:
bool smiteWarnEnabled = true; bool smiteWarnEnabled = true;
bool autoWriteTextEnabled = false; bool autoWriteTextEnabled = false;
bool autoWriteTextDone = false; bool autoWriteTextDone = false;
std::string autoWriteText; QString autoWriteText;
std::string chatid; // the chatid of the chat from the champselect QString chatid; // the chatid of the chat from the champselect
std::chrono::time_point<std::chrono::system_clock> lastMessageSent; std::chrono::time_point<std::chrono::system_clock> lastMessageSent;
public: public:
@ -88,7 +88,7 @@ public:
const std::vector<RuneStyle>& getRuneStyles(); const std::vector<RuneStyle>& getRuneStyles();
void applyRunes(); void applyRunes();
void setOnRuneChangeFunc(onruneschange_func on); void setOnRuneChangeFunc(onruneschange_func on);
void setAutoWriteText(bool enabled, const std::string& text = {}); void setAutoWriteText(bool enabled, const QString& text = {});
signals: signals:
void statusChanged(LolAutoAccept::Status); // new status: 0 = off, 1 = on, 2 = failed void statusChanged(LolAutoAccept::Status); // new status: 0 = off, 1 = on, 2 = failed
@ -118,7 +118,7 @@ private:
static int32_t getMatchingRunePage(const RunePage& rp, const std::vector<ClientAPI::RunePage>& allpages); static int32_t getMatchingRunePage(const RunePage& rp, const std::vector<ClientAPI::RunePage>& allpages);
void champSelect(); void champSelect();
void smiteWarning(const std::vector<ClientAPI::ChampSelectCell>& cells); void smiteWarning(const std::vector<ClientAPI::ChampSelectCell>& cells);
const std::string& getChatid(); const QString& getChatid();
void applyRunes_internal(uint32_t champid, Position pos); void applyRunes_internal(uint32_t champid, Position pos);
}; };

View File

@ -1,27 +1,27 @@
#pragma once #pragma once
#include <functional> #include <functional>
#include <string> #include <QString>
#include <QPixmap> #include <QPixmap>
class MemoryImageCache { class MemoryImageCache {
public: public:
MemoryImageCache(size_t maxsize = 25); MemoryImageCache(size_t maxsize = 25);
void addImage(QPixmap, const std::string& title, int type); void addImage(QPixmap, const QString& title, int type);
QPixmap getImage(const std::string& title, int type); QPixmap getImage(const QString& title, int type);
private: private:
void cleanUp(); void cleanUp();
struct CachedImage { struct CachedImage {
time_t lastaccessed = 0; time_t lastaccessed = 0;
QPixmap imageref; QPixmap imageref;
std::string title; QString title;
int type; int type;
bool operator<(const CachedImage& other) const; bool operator<(const CachedImage& other) const;
}; };
static std::function<bool(const CachedImage&)> getImageMatcher(const std::string& title, int type); static std::function<bool(const CachedImage&)> getImageMatcher(const QString& title, int type);
std::list<CachedImage> cache; std::list<CachedImage> cache;
size_t maxsize; size_t maxsize;

View File

@ -1,8 +1,8 @@
#pragma once #pragma once
#include <QDebug>
#include <QVariant> #include <QVariant>
enum class Position : uint32_t { enum class Position : uint32_t {
INVALID = 0, INVALID = 0,
TOP, TOP,
@ -11,10 +11,11 @@ enum class Position : uint32_t {
BOTTOM, BOTTOM,
UTILITY UTILITY
}; };
Position toPosition(const std::string& str); Position toPosition(const QString& str);
std::string toString(Position p); QString toString(Position p);
std::string toShortString(Position p); QString toShortString(Position p);
std::ostream& operator<<(std::ostream&, const Position&); std::ostream& operator<<(std::ostream&, const Position&);
QDebug operator<<(QDebug , const Position&);
Q_DECLARE_METATYPE(Position); Q_DECLARE_METATYPE(Position);

View File

@ -1,6 +1,6 @@
#pragma once #pragma once
#include <string> #include <QString>
#include <QJsonDocument> #include <QJsonDocument>
#include <curl/curl.h> #include <curl/curl.h>
@ -11,7 +11,7 @@
class RestClient { class RestClient {
public: public:
RestClient(const std::string& base); RestClient(const QString& base);
RestClient(const RestClient&) = delete; RestClient(const RestClient&) = delete;
virtual ~RestClient(); virtual ~RestClient();
@ -30,16 +30,16 @@ public:
}; };
protected: protected:
QByteArray requestRaw(const std::string& url, Method m = Method::GET, const std::string& data = {}); QByteArray requestRaw(const QString& url, Method m = Method::GET, const QString& data = {});
QJsonDocument request(const std::string& url, Method m = Method::GET, const std::string& data = {}); QJsonDocument request(const QString& url, Method m = Method::GET, const QString& data = {});
void enableDebugging(bool enabled = true); void enableDebugging(bool enabled = true);
std::string escape(const std::string& in) const; QString escape(const QString& in) const;
std::string baseurl; QString baseurl;
CURL* curl = nullptr; // the curl (does curling) CURL* curl = nullptr; // the curl (does curling)
std::string basicauth; // basic auth code (user:pw) or empty string to disable QString basicauth; // basic auth code (user:pw) or empty string to disable
#ifdef WIN32 #ifdef WIN32
bool disableCertCheck = true; bool disableCertCheck = true;
#else #else

View File

@ -7,11 +7,11 @@ class QJsonObject;
struct RuneAspekt { struct RuneAspekt {
uint32_t id = 0; uint32_t id = 0;
std::string name; QString name;
std::string shortDesc; QString shortDesc;
std::string longDesc; QString longDesc;
std::string tooltip; QString tooltip;
std::string iconPath; QString iconPath;
RuneAspekt(); RuneAspekt();
explicit RuneAspekt(const QJsonObject& json); explicit RuneAspekt(const QJsonObject& json);

View File

@ -29,8 +29,8 @@ signals:
private: private:
void updateText(); void updateText();
std::string getRuneText(uint32_t id); QString getRuneText(uint32_t id);
std::string getRuneStyleByID(uint32_t id); QString getRuneStyleByID(uint32_t id);
Ui::RuneDisplay *ui; Ui::RuneDisplay *ui;

View File

@ -4,6 +4,7 @@
#include <ostream> #include <ostream>
#include <vector> #include <vector>
#include <QDebug>
#include <QJsonObject> #include <QJsonObject>
// represents a runepage // represents a runepage
struct RunePage { struct RunePage {
@ -22,3 +23,4 @@ public:
}; };
std::ostream& operator<<(std::ostream&, const RunePage&); std::ostream& operator<<(std::ostream&, const RunePage&);
QDebug operator<<(QDebug, const RunePage&);

View File

@ -18,9 +18,9 @@ struct RuneStyleSlot {
struct RuneStyle { struct RuneStyle {
uint32_t id; uint32_t id;
std::string name; QString name;
std::string iconPath; QString iconPath;
std::string tooltip; QString tooltip;
std::vector<int> allowedSubStyles; std::vector<int> allowedSubStyles;
QString idName; QString idName;

View File

@ -25,7 +25,7 @@ public:
std::vector<StageSettings::SelectedChamp> getChamps(LolAutoAccept::State s) const; std::vector<StageSettings::SelectedChamp> getChamps(LolAutoAccept::State s) const;
bool getState(LolAutoAccept::State s) const; bool getState(LolAutoAccept::State s) const;
void setChamps(LolAutoAccept::State s, const std::vector<std::string>&); void setChamps(LolAutoAccept::State s, const std::vector<QString>&);
void setState(LolAutoAccept::State s, bool b); void setState(LolAutoAccept::State s, bool b);
Position getPosition() const; Position getPosition() const;

View File

@ -27,13 +27,13 @@ public:
void setState(bool); void setState(bool);
struct SelectedChamp { struct SelectedChamp {
SelectedChamp(std::string name, uint32_t id); SelectedChamp(QString name, uint32_t id);
std::string name; QString name;
uint32_t id; uint32_t id;
}; };
std::vector<SelectedChamp> getChampions() const; std::vector<SelectedChamp> getChampions() const;
void setChampions(const std::vector<std::string>& champs); void setChampions(const std::vector<QString>& champs);
void setDataDragon(DataDragon* dd); void setDataDragon(DataDragon* dd);
void addChamp(const DataDragon::ChampData& cd, QPixmap icon); void addChamp(const DataDragon::ChampData& cd, QPixmap icon);
@ -52,7 +52,7 @@ signals:
private: private:
// delete all items // delete all items
void resolveAndAddChamp(const std::string& name, bool emitchange = false); void resolveAndAddChamp(const QString& name, bool emitchange = false);
void clear(); void clear();
void updateEnabled(); void updateEnabled();

View File

@ -12,7 +12,7 @@
// query=query ChampionBuilds($championId:Int!,$queue:Queue!,$role:Role,$opponentChampionId:Int,$key:ChampionBuildKey){championBuildStats(championId:$championId,queue:$queue,role:$role,opponentChampionId:$opponentChampionId,key:$key){championId opponentChampionId queue role builds{completedItems{games index averageIndex itemId wins}games mythicId mythicAverageIndex primaryRune runes{games index runeId wins treeId}skillOrders{games skillOrder wins}startingItems{games startingItemIds wins}summonerSpells{games summonerSpellIds wins}wins}}} // query=query ChampionBuilds($championId:Int!,$queue:Queue!,$role:Role,$opponentChampionId:Int,$key:ChampionBuildKey){championBuildStats(championId:$championId,queue:$queue,role:$role,opponentChampionId:$opponentChampionId,key:$key){championId opponentChampionId queue role builds{completedItems{games index averageIndex itemId wins}games mythicId mythicAverageIndex primaryRune runes{games index runeId wins treeId}skillOrders{games skillOrder wins}startingItems{games startingItemIds wins}summonerSpells{games summonerSpellIds wins}wins}}}
// &variables={"championId":25,"role":"SUPPORT","queue":"RANKED_SOLO_5X5","opponentChampionId":null,"key":"PUBLIC"} // &variables={"championId":25,"role":"SUPPORT","queue":"RANKED_SOLO_5X5","opponentChampionId":null,"key":"PUBLIC"}
static const std::string POSITIONNAMES[] = {"INVALID", "TOP", "JUNGLE", "MIDDLE", "BOTTOM", "SUPPORT"}; static const QString POSITIONNAMES[] = {"INVALID", "TOP", "JUNGLE", "MIDDLE", "BOTTOM", "SUPPORT"};
BlitzAPI::BlitzAPI() : RestClient("https://league-champion-aggregate.iesdev.com/graphql?") {} BlitzAPI::BlitzAPI() : RestClient("https://league-champion-aggregate.iesdev.com/graphql?") {}
@ -58,7 +58,7 @@ BlitzAPI::ChampionInfo::ChampionInfo(const QJsonObject& json) {
auto runeid = rune["runeId"]; auto runeid = rune["runeId"];
if(runeid.isDouble()) { if(runeid.isDouble()) {
runes.at(index+1) = runeid.toDouble(); runes.at(index+1) = runeid.toDouble();
Log::debug << "found rune: index: " << index << " +1 set to: " << runes.at(index+1); qDebug() << "found rune: index: " << index << " +1 set to: " << runes.at(index+1);
if(index == 0) { if(index == 0) {
runepage.primaryStyle = rune["treeId"].toInt(); runepage.primaryStyle = rune["treeId"].toInt();
@ -80,7 +80,7 @@ BlitzAPI::ChampionInfo BlitzAPI::getChampionInfo(uint32_t championID, Position p
vars["championId"] = (int) championID; vars["championId"] = (int) championID;
if(p != Position::INVALID) { if(p != Position::INVALID) {
vars["role"] = QString::fromStdString(POSITIONNAMES[(int) p]); vars["role"] = POSITIONNAMES[(int) p];
} }
vars["queue"] = "RANKED_SOLO_5X5"; vars["queue"] = "RANKED_SOLO_5X5";
@ -91,10 +91,10 @@ BlitzAPI::ChampionInfo BlitzAPI::getChampionInfo(uint32_t championID, Position p
vars["key"] = "PUBLIC"; // ? what does this do? vars["key"] = "PUBLIC"; // ? what does this do?
QJsonDocument jvars(vars); QJsonDocument jvars(vars);
const std::string variables = jvars.toJson(QJsonDocument::Compact).toStdString(); const QString variables = jvars.toJson(QJsonDocument::Compact);
const std::string query = "query ChampionBuilds($championId:Int!,$queue:Queue!,$role:Role,$opponentChampionId:Int,$key:ChampionBuildKey){championBuildStats(championId:$championId,queue:$queue,role:$role,opponentChampionId:$opponentChampionId,key:$key){championId opponentChampionId queue role builds{completedItems{games index averageIndex itemId wins}games mythicId mythicAverageIndex primaryRune runes{games index runeId wins treeId}skillOrders{games skillOrder wins}startingItems{games startingItemIds wins}summonerSpells{games summonerSpellIds wins}wins}}}"; const QString query = "query ChampionBuilds($championId:Int!,$queue:Queue!,$role:Role,$opponentChampionId:Int,$key:ChampionBuildKey){championBuildStats(championId:$championId,queue:$queue,role:$role,opponentChampionId:$opponentChampionId,key:$key){championId opponentChampionId queue role builds{completedItems{games index averageIndex itemId wins}games mythicId mythicAverageIndex primaryRune runes{games index runeId wins treeId}skillOrders{games skillOrder wins}startingItems{games startingItemIds wins}summonerSpells{games summonerSpellIds wins}wins}}}";
const std::string requeststr = "query=" + escape(query) + "&variables=" + escape(variables); const QString requeststr = "query=" + escape(query) + "&variables=" + escape(variables);
Log::debug << "GetChampionInfo requestVariables: " << variables << " requeststr: " << requeststr; qDebug() << "GetChampionInfo requestVariables: " << variables << " requeststr: " << requeststr;
QJsonDocument doc; QJsonDocument doc;
try { try {
@ -105,11 +105,11 @@ BlitzAPI::ChampionInfo BlitzAPI::getChampionInfo(uint32_t championID, Position p
if(!doc.isObject()) { if(!doc.isObject()) {
// error // error
Log::error << "could not get ChampionInfo. Returned Response: " << doc.toJson().toStdString(); qCritical() << "could not get ChampionInfo. Returned Response: " << doc.toJson();
return {}; return {};
} }
Log::debug << "championinfo Response: " << doc.toJson().trimmed().toStdString(); qDebug() << "championinfo Response: " << doc.toJson().trimmed();
QJsonObject obj = doc.object(); QJsonObject obj = doc.object();
QJsonValueRef dataref = obj["data"]; QJsonValueRef dataref = obj["data"];

View File

@ -18,17 +18,17 @@ static qint64 ageOfFile(QFile& f) {
return info.lastModified().secsTo(QDateTime::currentDateTime()); return info.lastModified().secsTo(QDateTime::currentDateTime());
} }
std::string ChampCache::getVersion() { QString ChampCache::getVersion() {
QFile versionfile(QString::fromStdString(basefolder + "version")); QFile versionfile(basefolder + "version");
if(ageOfFile(versionfile) < (qint64) maxage) { if(ageOfFile(versionfile) < (qint64) maxage) {
versionfile.open(QFile::ReadOnly); versionfile.open(QFile::ReadOnly);
return versionfile.readAll().toStdString(); return versionfile.readAll();
} }
return {}; // empty string return {}; // empty string
} }
QJsonDocument ChampCache::getChamps() { QJsonDocument ChampCache::getChamps() {
QFile champsfile(QString::fromStdString(basefolder + "champs.json")); QFile champsfile(basefolder + "champs.json");
if(ageOfFile(champsfile) < (qint64) maxage) { if(ageOfFile(champsfile) < (qint64) maxage) {
champsfile.open(QFile::ReadOnly); champsfile.open(QFile::ReadOnly);
@ -39,16 +39,16 @@ QJsonDocument ChampCache::getChamps() {
return {}; // empty document return {}; // empty document
} }
void ChampCache::saveChamps(QJsonDocument doc, const std::string& version) { void ChampCache::saveChamps(QJsonDocument doc, const QString& version) {
QByteArray arr = doc.toJson(); QByteArray arr = doc.toJson();
QFile champsfile(QString::fromStdString(basefolder + "champs.json")); QFile champsfile(basefolder + "champs.json");
champsfile.open(QFile::WriteOnly | QFile::Truncate); champsfile.open(QFile::WriteOnly | QFile::Truncate);
champsfile.write(arr); champsfile.write(arr);
QFile versionfile(QString::fromStdString(basefolder + "version")); QFile versionfile(basefolder + "version");
versionfile.open(QFile::WriteOnly | QFile::Truncate); versionfile.open(QFile::WriteOnly | QFile::Truncate);
versionfile.write(version.c_str()); versionfile.write(version.toLocal8Bit());
versionfile.close(); versionfile.close();
Log::info << "saved Champs and version Cache"; qInfo() << "saved Champs and version Cache";
} }

View File

@ -20,10 +20,10 @@ ChampRow* ChampionSearch::getSearchResult() {
} }
void ChampionSearch::searchChanged(QString str) { void ChampionSearch::searchChanged(QString str) {
Log::info << "champion search: " << str.toStdString(); qInfo() << "champion search: " << str;
const std::vector<const DataDragon::ChampData*> champs = dd->getMatchingChamp(str.toStdString()); const std::vector<const DataDragon::ChampData*> champs = dd->getMatchingChamp(str);
Log::info << "found " << champs.size() << " champs"; qInfo() << "found " << champs.size() << " champs";
clear(); clear();

View File

@ -7,14 +7,12 @@ ChampRow::~ChampRow() {
} }
void ChampRow::setChamp(const DataDragon::ChampData& cd, QPixmap icon) { void ChampRow::setChamp(const DataDragon::ChampData& cd, QPixmap icon) {
setText(QString::fromStdString(cd.name)); setText(cd.name);
champid = cd.key; champid = cd.key;
this->icon = icon; this->icon = icon;
setIcon(QIcon(icon)); setIcon(QIcon(icon));
#define QS(A) arg(QString::fromStdString(A)) setToolTip(QWidget::tr("Champion: %1\nType: %2\nTitle: %3\nID: %4").arg(cd.name).arg(cd.partype).arg(cd.title).arg(cd.key));
setToolTip(QWidget::tr("Champion: %1\nType: %2\nTitle: %3\nID: %4").QS(cd.name).QS(cd.partype).QS(cd.title).arg(cd.key));
#undef QS
} }
QString ChampRow::getChamp() const { QString ChampRow::getChamp() const {

View File

@ -2,39 +2,39 @@
#include <fstream> #include <fstream>
#include <iomanip> #include <iomanip>
#include <Log.h>
#include <QDebug>
#include <QStringList>
ClientAccess::ClientAccess() {} ClientAccess::ClientAccess() {}
ClientAccess::ClientAccess(const std::string& token, uint16_t port) : authcode(token), port(port) {} ClientAccess::ClientAccess(const QString& token, uint16_t port) : authcode(token), port(port) {}
std::shared_ptr<ClientAccess> createFromLockfile(std::istream& lockfile) { std::shared_ptr<ClientAccess> createFromLockfile(std::istream& lockfile) {
std::vector<std::string> parts;
std::string content; std::string content;
while(std::getline(lockfile, content, ':')) { std::getline(lockfile, content);
parts.push_back(content); QStringList parts = QString::fromStdString(content).split(':');
}
if(parts.size() != 5) { if(parts.size() != 5) {
Log::error << "lockfile contained " << parts.size() << " parts, expected 5"; qCritical() << "lockfile contained " << parts.size() << " parts, expected 5";
return {}; return {};
} }
const std::string portstr = parts.at(2); const QString portstr = parts.at(2);
const std::string token = parts.at(3); const QString token = parts.at(3);
// try to parse port // try to parse port
try { bool success = false;
uint16_t port = std::stoi(portstr); uint16_t port = portstr.toUInt(&success);
if(!success) {
return std::shared_ptr<ClientAccess>(new ClientAccess(token, port)); qCritical() << "could not parse port: " << portstr;
} catch(std::exception& e) { return nullptr;
Log::error << "could not parse port: " << std::quoted(portstr);
} }
return nullptr; return std::shared_ptr<ClientAccess>(new ClientAccess(token, port));
} }
std::string ClientAccess::getBasicAuth() const { QString ClientAccess::getBasicAuth() const {
return "riot:" + authcode; return "riot:" + authcode;
} }
@ -42,6 +42,6 @@ uint16_t ClientAccess::getPort() const {
return port; return port;
} }
std::string ClientAccess::getURL() const { QString ClientAccess::getURL() const {
return "https://127.0.0.1:" + std::to_string(port) + "/"; return "https://127.0.0.1:" + QString::number(port) + "/";
} }

View File

@ -19,22 +19,18 @@
#include "defer.h" #include "defer.h"
static const std::string CLIENTNAME = "LeagueClientUx.exe"; // returns the name and value of a argument or empty string if it could not be parsed static const QString CLIENTNAME = "LeagueClientUx.exe"; // returns the name and value of a argument or empty string if it could not be parsed
static std::shared_ptr<ClientAccess> findUsingLockfile(const std::vector<std::string>& cmdline, pid_t pid); static std::shared_ptr<ClientAccess> findUsingLockfile(const std::vector<QString>& cmdline, pid_t pid);
static bool endsWith(const std::string& all, const std::string& end) {
return all.size() >= end.size() && all.rfind(end) == all.size() - end.size();
}
// reads a procfile into a vector (strings are \0 seperated) // reads a procfile into a vector (strings are \0 seperated)
static std::vector<std::string> readProcFile(const std::string& path) { static std::vector<QString> readProcFile(const QString& path) {
std::ifstream in(path); std::ifstream in(path.toStdString());
std::vector<std::string> out; std::vector<QString> out;
std::string line; std::string line;
while(std::getline(in, line, '\0')) { while(std::getline(in, line, '\0')) {
if(!line.empty()) { if(!line.empty()) {
out.push_back(line); out.push_back(QString::fromStdString(line));
} }
} }
return out; return out;
@ -51,27 +47,27 @@ std::shared_ptr<ClientAccess> ClientAccess::find() {
while ((entry = readdir(procdir)) != NULL) { while ((entry = readdir(procdir)) != NULL) {
if (entry->d_type != DT_DIR) continue; if (entry->d_type != DT_DIR) continue;
std::string name(entry->d_name); QString name(entry->d_name);
pid_t pid = -1; pid_t pid = -1;
try { bool success = false;
pid = std::stoi(name); pid = name.toULong(&success);
} catch(std::exception& e) { if(!success) {
// could not parse -> not a pid // could not parse -> not a pid
continue; continue;
} }
// get info on the exe // get info on the exe
std::string cmdfile = "/proc/" + std::to_string(pid) + "/cmdline"; QString cmdfile = "/proc/" + QString::number(pid) + "/cmdline";
std::vector<std::string> args = readProcFile(cmdfile); std::vector<QString> args = readProcFile(cmdfile);
// Log::debug << "process: " << pid << " has " << args.size() << " args"; // qDebug() << "process: " << pid << " has " << args.size() << " args";
if(args.empty()) continue; if(args.empty()) continue;
std::string& exename = args.at(0); QString& exename = args.at(0);
if(endsWith(exename, CLIENTNAME)) { if(exename.endsWith(CLIENTNAME)) {
Log::info << CLIENTNAME << " found: " << exename; qInfo() << CLIENTNAME << " found: " << exename;
std::shared_ptr<ClientAccess> out; std::shared_ptr<ClientAccess> out;
@ -86,32 +82,32 @@ std::shared_ptr<ClientAccess> ClientAccess::find() {
return nullptr; return nullptr;
} }
std::shared_ptr<ClientAccess> findUsingLockfile(const std::vector<std::string>& cmdline, pid_t pid) { std::shared_ptr<ClientAccess> findUsingLockfile(const std::vector<QString>& cmdline, pid_t pid) {
// get WINEPREFIX env // get WINEPREFIX env
std::vector<std::string> envs = readProcFile("/proc/" + std::to_string(pid) + "/environ"); std::vector<QString> envs = readProcFile("/proc/" + QString::number(pid) + "/environ");
const static std::string WINEPREFIX = "WINEPREFIX="; const static QString WINEPREFIX = "WINEPREFIX=";
// find WINEPREFIX // find WINEPREFIX
auto found = std::find_if(envs.begin(), envs.end(), [](const std::string& s) { auto found = std::find_if(envs.begin(), envs.end(), [](const QString& s) {
return s.find(WINEPREFIX) == 0; return s.startsWith(WINEPREFIX);
}); });
// WINEPREFIX env not present // WINEPREFIX env not present
if(found == envs.end()) { if(found == envs.end()) {
Log::debug << "WINEPREFIX environment variable not set"; qDebug() << "WINEPREFIX environment variable not set";
return {}; return {};
} }
const std::string wineprefix = found->substr(WINEPREFIX.size()); const QString wineprefix = found->remove(0, WINEPREFIX.size());
const std::string binarypath = cmdline.at(0); const QString binarypath = cmdline.at(0);
std::string gamefolder = binarypath.substr(2, binarypath.rfind('/')-1); // remove the "C:" and the name of the binary QString gamefolder = binarypath.mid(2, binarypath.lastIndexOf('/')-1); // remove the "C:" and the name of the binary
// TODO: gamefoldre could contain '\' so replacing every occurance with '/' would be a good idea // TODO: gamefoldre could contain '\' so replacing every occurance with '/' would be a good idea
const std::string lockfilepath = wineprefix + "/drive_c/" + gamefolder + "/lockfile"; const QString lockfilepath = wineprefix + "/drive_c/" + gamefolder + "/lockfile";
Log::debug << "lockfilepath: " << std::quoted(lockfilepath); qDebug() << "lockfilepath: " << lockfilepath;
// read lockfile // read lockfile
std::ifstream lockfile(lockfilepath); std::ifstream lockfile(lockfilepath.toStdString());
return createFromLockfile(lockfile); return createFromLockfile(lockfile);
} }

View File

@ -16,10 +16,10 @@
#include "defer.h" #include "defer.h"
static const std::string CLIENTNAME = "LeagueClientUx.exe"; static const QString CLIENTNAME = "LeagueClientUx.exe";
static std::string narrow(WCHAR* str, size_t len) { static QString narrow(WCHAR* str, size_t len) {
std::string out; QString out;
out.reserve(len); out.reserve(len);
for(uint32_t i = 0; i < len && str[i]; ++i) { for(uint32_t i = 0; i < len && str[i]; ++i) {
out.append(1, (char) str[i]); out.append(1, (char) str[i]);
@ -27,11 +27,11 @@ static std::string narrow(WCHAR* str, size_t len) {
return out; return out;
} }
static std::string getProcessPath(DWORD dwPID) { static QString getProcessPath(DWORD dwPID) {
// Take a snapshot of all modules in the specified process. // Take a snapshot of all modules in the specified process.
HANDLE hModuleSnap = CreateToolhelp32Snapshot( TH32CS_SNAPMODULE, dwPID ); HANDLE hModuleSnap = CreateToolhelp32Snapshot( TH32CS_SNAPMODULE, dwPID );
if(hModuleSnap == INVALID_HANDLE_VALUE) { if(hModuleSnap == INVALID_HANDLE_VALUE) {
Log::error << "CreateToolhelp32Snapshot (of modules) failed"; qCritical() << "CreateToolhelp32Snapshot (of modules) failed";
return {}; // empty string return {}; // empty string
} }
@ -44,7 +44,7 @@ static std::string getProcessPath(DWORD dwPID) {
// Retrieve information about the first module, // Retrieve information about the first module,
// and exit if unsuccessful // and exit if unsuccessful
if( !Module32First( hModuleSnap, &me32 ) ) { if( !Module32First( hModuleSnap, &me32 ) ) {
Log::error << "Module32First"; qCritical() << "Module32First";
return {}; return {};
} }
@ -52,15 +52,15 @@ static std::string getProcessPath(DWORD dwPID) {
} }
static std::shared_ptr<ClientAccess> findUsingLockfile(PROCESSENTRY32& proc) { static std::shared_ptr<ClientAccess> findUsingLockfile(PROCESSENTRY32& proc) {
const std::string exepath = getProcessPath(proc.th32ProcessID); const QString exepath = getProcessPath(proc.th32ProcessID);
Log::note << "exepath: " << exepath; Log::note << "exepath: " << exepath;
// lockfile path // lockfile path
const std::string lockfilepath = exepath.substr(0, exepath.rfind('\\')+1) + "lockfile"; // possible out of bounds const QString lockfilepath = exepath.substr(0, exepath.rfind('\\')+1) + "lockfile"; // possible out of bounds
Log::debug << "Lockfile: " << lockfilepath; qDebug() << "Lockfile: " << lockfilepath;
std::ifstream lockfile(lockfilepath); std::ifstream lockfile(lockfilepath);
if(!lockfile) { if(!lockfile) {
Log::error << "lockfile could not be opend"; qCritical() << "lockfile could not be opend";
return nullptr; return nullptr;
} }
return createFromLockfile(lockfile); return createFromLockfile(lockfile);
@ -72,7 +72,7 @@ std::shared_ptr<ClientAccess> ClientAccess::find() {
// Take a snapshot of all processes in the system. // Take a snapshot of all processes in the system.
HANDLE hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); HANDLE hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (hProcessSnap == INVALID_HANDLE_VALUE) { if (hProcessSnap == INVALID_HANDLE_VALUE) {
Log::error << "CreateToolhelp32Snapshot (of processes) failed"; qCritical() << "CreateToolhelp32Snapshot (of processes) failed";
return nullptr; return nullptr;
} }
@ -85,18 +85,18 @@ std::shared_ptr<ClientAccess> ClientAccess::find() {
// Retrieve information about the first process, // Retrieve information about the first process,
// and exit if unsuccessful // and exit if unsuccessful
if (!Process32First(hProcessSnap, &pe32)) { if (!Process32First(hProcessSnap, &pe32)) {
Log::error << "Process32First failed"; // show cause of failure qCritical() << "Process32First failed"; // show cause of failure
return nullptr; return nullptr;
} }
// Now walk the snapshot of processes, and // Now walk the snapshot of processes, and
// display information about each process in turn // display information about each process in turn
do { do {
std::string exename = narrow((WCHAR*) pe32.szExeFile, sizeof(pe32.szExeFile)); QString exename = narrow((WCHAR*) pe32.szExeFile, sizeof(pe32.szExeFile));
// Log::note << "found process: " << exename; // Log::note << "found process: " << exename;
if(exename == CLIENTNAME) { if(exename == CLIENTNAME) {
Log::info << CLIENTNAME << " found"; qInfo() << CLIENTNAME << " found";
std::shared_ptr<ClientAccess> out; std::shared_ptr<ClientAccess> out;

View File

@ -30,9 +30,9 @@ ClientAPI::GameflowPhase ClientAPI::getGameflowPhase() {
// it is just a json-string no object // it is just a json-string no object
QByteArray data = requestRaw("lol-gameflow/v1/gameflow-phase"); QByteArray data = requestRaw("lol-gameflow/v1/gameflow-phase");
std::string datastr = data.toStdString(); QString datastr = QString::fromLocal8Bit(data);
if (data.size() > 2) { if (data.size() > 2) {
datastr = datastr.substr(1, datastr.size() -2); datastr = datastr.mid(1, datastr.size() -2);
return toGameflowPhase(datastr); return toGameflowPhase(datastr);
} }
@ -63,25 +63,25 @@ bool ClientAPI::setChampSelectAction(int32_t actionid, int32_t champid, bool com
requestj["completed"] = completed; requestj["completed"] = completed;
requestj["id"] = actionid; requestj["id"] = actionid;
QJsonDocument requestdoc(requestj); QJsonDocument requestdoc(requestj);
const std::string requeststr = requestdoc.toJson(QJsonDocument::JsonFormat::Compact).toStdString(); const QString requeststr = requestdoc.toJson(QJsonDocument::JsonFormat::Compact);
Log::debug << "requeststr: " << requeststr; qDebug() << "requeststr: " << requeststr;
QJsonDocument doc = request("lol-champ-select/v1/session/actions/" + std::to_string(actionid), Method::PATCH, requeststr); QJsonDocument doc = request("lol-champ-select/v1/session/actions/" + QString::number(actionid), Method::PATCH, requeststr);
std::string error; QString error;
if(doc.isObject()) { if(doc.isObject()) {
QJsonObject obj = doc.object(); QJsonObject obj = doc.object();
auto errref = obj["errorCode"]; auto errref = obj["errorCode"];
auto msgref = obj["message"]; auto msgref = obj["message"];
if(errref.isString()) { if(errref.isString()) {
error = errref.toString().toStdString() + " "; error = errref.toString() + " ";
} }
if(msgref.isString()) { if(msgref.isString()) {
error += msgref.toString().toStdString(); error += msgref.toString();
} }
} }
Log::note << "patching action: " << actionid << " error: " << error; qDebug() << "patching action: " << actionid << " error: " << error;
return error.empty(); return error.isEmpty();
} }
ClientAPI::PlayerInfo ClientAPI::getSelf() { ClientAPI::PlayerInfo ClientAPI::getSelf() {
@ -91,15 +91,15 @@ ClientAPI::PlayerInfo ClientAPI::getSelf() {
QJsonObject obj = doc.object(); QJsonObject obj = doc.object();
PlayerInfo info; PlayerInfo info;
info.gameName = getValue<std::string>(obj, "gameName"); info.gameName = getValue<QString>(obj, "gameName");
info.name = getValue<std::string>(obj, "name"); info.name = getValue<QString>(obj, "name");
info.statusMessage = getValue<std::string>(obj, "statusMessage", ""); info.statusMessage = getValue<QString>(obj, "statusMessage", "");
info.summonerid = getValue<uint64_t>(obj, "summonerId"); info.summonerid = getValue<uint64_t>(obj, "summonerId");
auto lolref = obj["lol"]; auto lolref = obj["lol"];
if(lolref.isObject()) { if(lolref.isObject()) {
QJsonObject lol = lolref.toObject(); QJsonObject lol = lolref.toObject();
info.puuid = getValue<std::string>(lol, "puuid"); info.puuid = getValue<QString>(lol, "puuid");
info.level = getValue<int32_t>(lol, "level"); info.level = getValue<int32_t>(lol, "level");
} }
@ -165,32 +165,32 @@ std::vector<ClientAPI::Conversation> ClientAPI::getAllConversations() {
return out; return out;
} }
ClientAPI::Message ClientAPI::sendMessage(const std::string& chatid, const std::string& messagebody) { ClientAPI::Message ClientAPI::sendMessage(const QString& chatid, const QString& messagebody) {
QJsonObject requestj; QJsonObject requestj;
requestj["body"] = QString::fromStdString(messagebody); requestj["body"] = messagebody;
QJsonDocument requestdoc(requestj); QJsonDocument requestdoc(requestj);
const std::string requeststr = requestdoc.toJson(QJsonDocument::JsonFormat::Compact).toStdString(); const QString requeststr = requestdoc.toJson(QJsonDocument::JsonFormat::Compact);
Log::debug << "requeststr: " << requeststr; qDebug() << "requeststr: " << requeststr;
QJsonDocument doc = request("lol-chat/v1/conversations/" + chatid + "/messages", Method::POST, requeststr); QJsonDocument doc = request("lol-chat/v1/conversations/" + chatid + "/messages", Method::POST, requeststr);
std::string error; QString error;
if(doc.isObject()) { if(doc.isObject()) {
QJsonObject obj = doc.object(); QJsonObject obj = doc.object();
auto errref = obj["errorCode"]; auto errref = obj["errorCode"];
auto msgref = obj["message"]; auto msgref = obj["message"];
if(errref.isString()) { if(errref.isString()) {
error = errref.toString().toStdString() + " "; error = errref.toString() + " ";
} }
if(msgref.isString()) { if(msgref.isString()) {
error += msgref.toString().toStdString(); error += msgref.toString();
} }
if(error.empty()) { if(error.isEmpty()) {
return (Message) obj; return (Message) obj;
} }
} }
Log::note << "send message error: " << error; qDebug() << "send message error: " << error;
return {}; return {};
} }
@ -220,12 +220,12 @@ std::vector<ClientAPI::RunePage> ClientAPI::getAllRunePages() {
} }
bool ClientAPI::selectRunePage(uint64_t id) { bool ClientAPI::selectRunePage(uint64_t id) {
QJsonDocument doc = request("lol-perks/v1/currentpage", Method::PUT, std::to_string(id)); QJsonDocument doc = request("lol-perks/v1/currentpage", Method::PUT, QString::number(id));
if(doc.isEmpty()) return true; // ok if(doc.isEmpty()) return true; // ok
// error // error
qWarning() << "error selecting runepage: " << id << " " << doc.toJson().toStdString(); qWarning() << "error selecting runepage: " << id << " " << doc.toJson();
return false; return false;
} }
@ -233,7 +233,7 @@ bool ClientAPI::selectRunePage(uint64_t id) {
bool ClientAPI::editRunePage(const RunePage& page) { bool ClientAPI::editRunePage(const RunePage& page) {
QJsonObject pagereq; QJsonObject pagereq;
pagereq["name"] = QString::fromStdString(page.name); pagereq["name"] = page.name;
pagereq["primaryStyleId"] = (int) page.runepage.primaryStyle; pagereq["primaryStyleId"] = (int) page.runepage.primaryStyle;
pagereq["subStyleId"] = (int) page.runepage.secondaryStyle; pagereq["subStyleId"] = (int) page.runepage.secondaryStyle;
@ -245,14 +245,14 @@ bool ClientAPI::editRunePage(const RunePage& page) {
pagereq["selectedPerkIds"] = selected; pagereq["selectedPerkIds"] = selected;
QJsonDocument reqdoc(pagereq); QJsonDocument reqdoc(pagereq);
const std::string requestdocstr = reqdoc.toJson(QJsonDocument::JsonFormat::Compact).toStdString(); const QString requestdocstr = reqdoc.toJson(QJsonDocument::JsonFormat::Compact);
qInfo() << "requeststr: " << requestdocstr; qInfo() << "requeststr: " << requestdocstr;
QJsonDocument doc = request("lol-perks/v1/pages/" + std::to_string(page.id), Method::PUT, requestdocstr); QJsonDocument doc = request("lol-perks/v1/pages/" + QString::number(page.id), Method::PUT, requestdocstr);
if(doc.isEmpty()) return true; // ok if(doc.isEmpty()) return true; // ok
// error // error
qWarning() << "error editing runepage: " << page.id << " " << doc.toJson().toStdString(); qWarning() << "error editing runepage: " << page.id << " " << doc.toJson();
return false; return false;
} }
@ -260,7 +260,7 @@ bool ClientAPI::editRunePage(const RunePage& page) {
bool ClientAPI::createRunePage(const RunePage& page) { bool ClientAPI::createRunePage(const RunePage& page) {
QJsonObject pagereq; QJsonObject pagereq;
pagereq["name"] = QString::fromStdString(page.name); pagereq["name"] = page.name;
pagereq["primaryStyleId"] = (int) page.runepage.primaryStyle; pagereq["primaryStyleId"] = (int) page.runepage.primaryStyle;
pagereq["subStyleId"] = (int) page.runepage.secondaryStyle; pagereq["subStyleId"] = (int) page.runepage.secondaryStyle;
@ -272,25 +272,25 @@ bool ClientAPI::createRunePage(const RunePage& page) {
pagereq["selectedPerkIds"] = selected; pagereq["selectedPerkIds"] = selected;
QJsonDocument reqdoc(pagereq); QJsonDocument reqdoc(pagereq);
const std::string requestdocstr = reqdoc.toJson(QJsonDocument::JsonFormat::Compact).toStdString(); const QString requestdocstr = reqdoc.toJson(QJsonDocument::JsonFormat::Compact);
qInfo() << "requeststr: " << requestdocstr; qInfo() << "requeststr: " << requestdocstr;
QJsonDocument doc = request("lol-perks/v1/pages/", Method::POST, requestdocstr); QJsonDocument doc = request("lol-perks/v1/pages/", Method::POST, requestdocstr);
if(doc.isEmpty()) return true; // ok if(doc.isEmpty()) return true; // ok
// error // error
qWarning() << "error creating runepage: " << page.name << " " << doc.toJson().toStdString(); qWarning() << "error creating runepage: " << page.name << " " << doc.toJson();
return false; return false;
} }
bool ClientAPI::deleteRunePage(uint64_t id) { bool ClientAPI::deleteRunePage(uint64_t id) {
QJsonDocument doc = request("lol-perks/v1/pages/" + std::to_string(id), Method::DELETE); QJsonDocument doc = request("lol-perks/v1/pages/" + QString::number(id), Method::DELETE);
if(doc.isEmpty()) return true; // ok if(doc.isEmpty()) return true; // ok
// error // error
qWarning() << "error deleteing runepage: " << id << " " << doc.toJson().toStdString(); qWarning() << "error deleteing runepage: " << id << " " << doc.toJson();
return false; return false;
} }
@ -336,26 +336,26 @@ std::vector<RuneStyle> ClientAPI::getAllRuneStyles() {
QPixmap ClientAPI::getImageResource(QString path) { QPixmap ClientAPI::getImageResource(QString path) {
if(path.isEmpty()) return {}; if(path.isEmpty()) return {};
std::string simplePath; QString simplePath;
{ {
QString simplePathQ = path; QString simplePathQ = path;
simplePath = simplePathQ.replace('/', '_').toStdString(); simplePath = simplePathQ.replace('/', '_');
} }
// query mem cache // query mem cache
QPixmap img = memImageCache.getImage(path.toStdString(), 0); QPixmap img = memImageCache.getImage(path, 0);
if(!img.isNull()) return img; if(!img.isNull()) return img;
// query HDD cache // query HDD cache
img = imageCache.getImage(simplePath); img = imageCache.getImage(simplePath);
if(!img.isNull()) { if(!img.isNull()) {
// update mem cache // update mem cache
memImageCache.addImage(img, path.toStdString(), 0); memImageCache.addImage(img, path, 0);
return img; return img;
} }
qInfo() << "requesting: " << path; qInfo() << "requesting: " << path;
QByteArray arr = requestRaw(path.toStdString()); QByteArray arr = requestRaw(path);
QPixmap out; QPixmap out;
out.loadFromData(arr); out.loadFromData(arr);
@ -363,7 +363,7 @@ QPixmap ClientAPI::getImageResource(QString path) {
imageCache.addImageRaw(arr, simplePath); imageCache.addImageRaw(arr, simplePath);
// store memchache // store memchache
memImageCache.addImage(out, path.toStdString(), 0); memImageCache.addImage(out, path, 0);
return out; return out;
} }

View File

@ -1,6 +1,5 @@
#include "clientapi.h" #include "clientapi.h"
#include <iomanip>
#include <QJsonArray> #include <QJsonArray>
#include <QJsonObject> #include <QJsonObject>
@ -10,7 +9,7 @@
// calculate the size of a constant sized array // calculate the size of a constant sized array
#define ARRSIZE(ARRNAME) (sizeof(ARRNAME) / sizeof(ARRNAME[0])) #define ARRSIZE(ARRNAME) (sizeof(ARRNAME) / sizeof(ARRNAME[0]))
#define ARR(NAME, ...) static const std::string NAME ## Names[] = {__VA_ARGS__}; \ #define ARR(NAME, ...) static const QString NAME ## Names[] = {__VA_ARGS__}; \
static const uint32_t NAME ## NamesCount = ARRSIZE(NAME ## Names); static const uint32_t NAME ## NamesCount = ARRSIZE(NAME ## Names);
ARR(ReadyCheckState, "Invalid", "None", "InProgress", "Accepted", "Declined"); ARR(ReadyCheckState, "Invalid", "None", "InProgress", "Accepted", "Declined");
@ -21,8 +20,8 @@ ARR(ShortPosition, "", "Top", "Jgl", "Mid", "Bot", "Sup");
ARR(ChampSelectActionType, "Invalid", "ban", "pick", "ten_bans_reveal"); ARR(ChampSelectActionType, "Invalid", "ban", "pick", "ten_bans_reveal");
template<typename T> template<typename T>
static T mapEnum(const std::string& input, const std::string* names, uint32_t count, T defaul) { static T mapEnum(const QString& input, const QString* names, uint32_t count, T defaul) {
if(input.empty()) return defaul; if(input.isEmpty()) return defaul;
for (uint32_t i = 0; i < count; ++i) { for (uint32_t i = 0; i < count; ++i) {
if (names[i] == input) { if (names[i] == input) {
@ -30,7 +29,7 @@ static T mapEnum(const std::string& input, const std::string* names, uint32_t co
} }
} }
Log::warn << "no mapping of enum-string: " << std::quoted(input) << " using default: " << defaul << " type: " << typeid(T).name(); qWarning() << "no mapping of enum-string: " << input << " using default: " << defaul << " type: " << typeid(T).name();
return defaul; return defaul;
} }
@ -50,8 +49,8 @@ static std::vector<T> readVector(QJsonArray arr) {
} }
ClientAPI::ReadyCheckState ClientAPI::toReadyCheckState(const QJsonObject& obj) { ClientAPI::ReadyCheckState ClientAPI::toReadyCheckState(const QJsonObject& obj) {
std::string searchState = getValue<std::string>(obj, "state", "Invalid"); QString searchState = getValue<QString>(obj, "state", "Invalid");
std::string playerresponse = getValue<std::string>(obj, "playerResponse", "None"); QString playerresponse = getValue<QString>(obj, "playerResponse", "None");
ClientAPI::ReadyCheckState response = MAPENUM(playerresponse, ReadyCheckState, NONE); ClientAPI::ReadyCheckState response = MAPENUM(playerresponse, ReadyCheckState, NONE);
@ -65,27 +64,27 @@ ClientAPI::ReadyCheckState ClientAPI::toReadyCheckState(const QJsonObject& obj)
return response; return response;
} }
ClientAPI::GameflowPhase ClientAPI::toGameflowPhase(const std::string& str) { ClientAPI::GameflowPhase ClientAPI::toGameflowPhase(const QString& str) {
return MAPENUM(str, GameflowPhase, NONE); return MAPENUM(str, GameflowPhase, NONE);
} }
ClientAPI::ChampSelectPhase ClientAPI::toChampSelectPhase(const std::string& str) { ClientAPI::ChampSelectPhase ClientAPI::toChampSelectPhase(const QString& str) {
return MAPENUM(str, ChampSelectPhase, INVALID); return MAPENUM(str, ChampSelectPhase, INVALID);
} }
Position toPosition(const std::string& str) { Position toPosition(const QString& str) {
return mapEnum(str, PositionNames, PositionNamesCount, Position::INVALID); return mapEnum(str, PositionNames, PositionNamesCount, Position::INVALID);
} }
std::string toString(Position p) { QString toString(Position p) {
return PositionNames[(int) p]; return PositionNames[(int) p];
} }
std::string toShortString(Position p) { QString toShortString(Position p) {
return ShortPositionNames[(int) p]; return ShortPositionNames[(int) p];
} }
ClientAPI::ChampSelectActionType ClientAPI::toChampSelectActionType(const std::string& str) { ClientAPI::ChampSelectActionType ClientAPI::toChampSelectActionType(const QString& str) {
return MAPENUM(str, ChampSelectActionType, INVALID); return MAPENUM(str, ChampSelectActionType, INVALID);
} }
@ -95,7 +94,7 @@ ClientAPI::TimerInfo::TimerInfo(const QJsonObject& obj) {
internalNowInEpochMs = getValue<int64_t>(obj, "internalNowInEpochMs", 0); internalNowInEpochMs = getValue<int64_t>(obj, "internalNowInEpochMs", 0);
isefinite = getValue<bool>(obj, "isefinite", 0); isefinite = getValue<bool>(obj, "isefinite", 0);
phase = MAPENUM(getValue<std::string>(obj, "phase", "Invalid"), ChampSelectPhase, INVALID); phase = MAPENUM(getValue<QString>(obj, "phase", "Invalid"), ChampSelectPhase, INVALID);
totalTimeInPhase = getValue<int64_t>(obj, "totalTimeInPhase", 0); totalTimeInPhase = getValue<int64_t>(obj, "totalTimeInPhase", 0);
} }
@ -108,13 +107,13 @@ ClientAPI::ChampSelectAction::ChampSelectAction(const QJsonObject& json) {
id = getValue<int32_t>(json, "id"); id = getValue<int32_t>(json, "id");
isAllyAction = getValue<bool>(json, "isAllyAction"); isAllyAction = getValue<bool>(json, "isAllyAction");
isInProgress = getValue<bool>(json, "isInProgress"); isInProgress = getValue<bool>(json, "isInProgress");
const std::string typestr = getValue<std::string>(json, "type", "Invalid"); const QString typestr = getValue<QString>(json, "type", "Invalid");
type = toChampSelectActionType(typestr); type = toChampSelectActionType(typestr);
} }
ClientAPI::ChampSelectCell::ChampSelectCell() {} ClientAPI::ChampSelectCell::ChampSelectCell() {}
ClientAPI::ChampSelectCell::ChampSelectCell(const QJsonObject& json) { ClientAPI::ChampSelectCell::ChampSelectCell(const QJsonObject& json) {
position = toPosition(getValue<std::string>(json, "assignedPosition")); position = toPosition(getValue<QString>(json, "assignedPosition"));
cellID = getValue<int32_t>(json, "cellId"); cellID = getValue<int32_t>(json, "cellId");
championID = getValue<int32_t>(json, "championId"); championID = getValue<int32_t>(json, "championId");
championPickIntentID = getValue<int32_t>(json, "championPickIntent"); championPickIntentID = getValue<int32_t>(json, "championPickIntent");
@ -195,7 +194,7 @@ ClientAPI::RunePage::RunePage(const QJsonObject& json) {
lastmodified = getValue<int64_t>(json, "lastModified", 0); lastmodified = getValue<int64_t>(json, "lastModified", 0);
runepage.primaryStyle = getValue<int32_t>(json, "primaryStyleId", 0); runepage.primaryStyle = getValue<int32_t>(json, "primaryStyleId", 0);
runepage.secondaryStyle = getValue<int32_t>(json, "subStyleId", 0); runepage.secondaryStyle = getValue<int32_t>(json, "subStyleId", 0);
name = getValue<std::string>(json, "name"); name = getValue<QString>(json, "name");
isDeleteable = getValue<bool>(json, "isDeletable", false); isDeleteable = getValue<bool>(json, "isDeletable", false);
isEditable = getValue<bool>(json, "isEditable", false); isEditable = getValue<bool>(json, "isEditable", false);
isActive = getValue<bool>(json, "isActive", false); isActive = getValue<bool>(json, "isActive", false);
@ -222,9 +221,9 @@ RuneStyleSlot::RuneStyleSlot(const QJsonObject& json) {
RuneStyle::RuneStyle() {} RuneStyle::RuneStyle() {}
RuneStyle::RuneStyle(const QJsonObject& json) { RuneStyle::RuneStyle(const QJsonObject& json) {
id = getValue<int32_t>(json, "id", 0); id = getValue<int32_t>(json, "id", 0);
name = getValue<std::string>(json, "name"); name = getValue<QString>(json, "name");
iconPath = getValue<std::string>(json, "iconPath"); iconPath = getValue<QString>(json, "iconPath");
tooltip = getValue<std::string>(json, "tooltip"); tooltip = getValue<QString>(json, "tooltip");
idName = getValue<QString>(json, "idName"); idName = getValue<QString>(json, "idName");
auto subStylesRef = json["allowedSubStyles"]; auto subStylesRef = json["allowedSubStyles"];
@ -242,36 +241,36 @@ RuneStyle::RuneStyle(const QJsonObject& json) {
RuneAspekt::RuneAspekt() {} RuneAspekt::RuneAspekt() {}
RuneAspekt::RuneAspekt(const QJsonObject& json) { RuneAspekt::RuneAspekt(const QJsonObject& json) {
id = getValue<int32_t>(json, "id", 0); id = getValue<int32_t>(json, "id", 0);
name = getValue<std::string>(json, "name"); name = getValue<QString>(json, "name");
shortDesc = getValue<std::string>(json, "shortDesc"); shortDesc = getValue<QString>(json, "shortDesc");
longDesc = getValue<std::string>(json, "longDesc"); longDesc = getValue<QString>(json, "longDesc");
tooltip = getValue<std::string>(json, "tooltip"); tooltip = getValue<QString>(json, "tooltip");
iconPath = getValue<std::string>(json, "iconPath"); iconPath = getValue<QString>(json, "iconPath");
} }
ClientAPI::Message::Message() {} ClientAPI::Message::Message() {}
ClientAPI::Message::Message(const QJsonObject& json) { ClientAPI::Message::Message(const QJsonObject& json) {
body = getValue<std::string>(json, "body"); body = getValue<QString>(json, "body");
fromId = getValue<std::string>(json, "fromId"); fromId = getValue<QString>(json, "fromId");
fromPid = getValue<std::string>(json, "fromPid"); fromPid = getValue<QString>(json, "fromPid");
fromSummonerId = getValue<int64_t>(json, "fromSummonerId"); fromSummonerId = getValue<int64_t>(json, "fromSummonerId");
id = getValue<std::string>(json, "id"); id = getValue<QString>(json, "id");
isHistorical = getValue<bool>(json, "isHistorical", true); isHistorical = getValue<bool>(json, "isHistorical", true);
timestamp = getValue<std::string>(json, "timestamp"); timestamp = getValue<QString>(json, "timestamp");
type = getValue<std::string>(json, "type"); type = getValue<QString>(json, "type");
} }
ClientAPI::Conversation::Conversation() {} ClientAPI::Conversation::Conversation() {}
ClientAPI::Conversation::Conversation(const QJsonObject& json) : lastMessage(nullptr) { ClientAPI::Conversation::Conversation(const QJsonObject& json) : lastMessage(nullptr) {
gameName = getValue<std::string>(json, "gameName"); gameName = getValue<QString>(json, "gameName");
gameTag = getValue<std::string>(json, "gameTag"); gameTag = getValue<QString>(json, "gameTag");
id = getValue<std::string>(json, "id"); id = getValue<QString>(json, "id");
isMuted = getValue<bool>(json, "isMuted"); isMuted = getValue<bool>(json, "isMuted");
name = getValue<std::string>(json, "name"); name = getValue<QString>(json, "name");
password = getValue<std::string>(json, "password"); password = getValue<QString>(json, "password");
pid = getValue<std::string>(json, "pid"); pid = getValue<QString>(json, "pid");
targetRegion = getValue<std::string>(json, "targetRegion"); targetRegion = getValue<QString>(json, "targetRegion");
type = getValue<std::string>(json, "type"); type = getValue<QString>(json, "type");
unreadMessageCount = getValue<int64_t>(json, "unreadMessageCount"); unreadMessageCount = getValue<int64_t>(json, "unreadMessageCount");
auto msgref = json["lastMessage"]; auto msgref = json["lastMessage"];
@ -283,6 +282,11 @@ ClientAPI::Conversation::Conversation(const QJsonObject& json) : lastMessage(nul
#define PRINTENUM(ENUMNAME) \ #define PRINTENUM(ENUMNAME) \
std::ostream& operator<<(std::ostream& str, const ClientAPI:: ENUMNAME & state) { \ std::ostream& operator<<(std::ostream& str, const ClientAPI:: ENUMNAME & state) { \
assert(((uint32_t) state) < ENUMNAME ## NamesCount); \
return str << ENUMNAME ## Names[(uint32_t) state].toStdString() << " (" << (uint32_t) state << ')'; \
} \
\
QDebug operator<<(QDebug str, const ClientAPI:: ENUMNAME & state) { \
assert(((uint32_t) state) < ENUMNAME ## NamesCount); \ assert(((uint32_t) state) < ENUMNAME ## NamesCount); \
return str << ENUMNAME ## Names[(uint32_t) state] << " (" << (uint32_t) state << ')'; \ return str << ENUMNAME ## Names[(uint32_t) state] << " (" << (uint32_t) state << ')'; \
} }
@ -295,6 +299,11 @@ PRINTENUM(ChampSelectActionType)
// not using macro because its not in ClientAPI // not using macro because its not in ClientAPI
std::ostream& operator<<(std::ostream& str, const Position & state) { std::ostream& operator<<(std::ostream& str, const Position & state) {
assert(((uint32_t) state) < PositionNamesCount);
return str << PositionNames[(uint32_t) state].toStdString() << " (" << (uint32_t) state << ')';
}
QDebug operator<<(QDebug str, const Position & state) {
assert(((uint32_t) state) < PositionNamesCount); assert(((uint32_t) state) < PositionNamesCount);
return str << PositionNames[(uint32_t) state] << " (" << (uint32_t) state << ')'; return str << PositionNames[(uint32_t) state] << " (" << (uint32_t) state << ')';
} }

View File

@ -19,7 +19,7 @@ Config::StageConfig::StageConfig() : enabled(false) {}
Config::StageConfig::StageConfig(const QJsonObject& j) { Config::StageConfig::StageConfig(const QJsonObject& j) {
if(j["champ"].isString()) { if(j["champ"].isString()) {
champs.push_back(getValue<std::string>(j, "champ")); champs.push_back(getValue<QString>(j, "champ"));
} }
if(j["champs"].isArray()) { if(j["champs"].isArray()) {
QJsonArray jchamps = j["champs"].toArray(); QJsonArray jchamps = j["champs"].toArray();
@ -27,7 +27,7 @@ Config::StageConfig::StageConfig(const QJsonObject& j) {
if(jchamp.isString()) { if(jchamp.isString()) {
QString jchampstr = jchamp.toString(); QString jchampstr = jchamp.toString();
if(!jchampstr.isEmpty()) { if(!jchampstr.isEmpty()) {
champs.push_back(jchampstr.toStdString()); champs.push_back(jchampstr);
} }
} }
} }
@ -39,9 +39,9 @@ Config::StageConfig::operator QJsonObject() const {
QJsonObject out; QJsonObject out;
QJsonArray jchamps; QJsonArray jchamps;
for(const std::string& champ : champs) { for(const QString& champ : champs) {
if(!champ.empty()) { if(!champ.isEmpty()) {
jchamps.push_back(QString::fromStdString(champ)); jchamps.push_back(champ);
} }
} }
@ -55,9 +55,9 @@ Config::PositionConfig::PositionConfig() {}
Config::PositionConfig::PositionConfig(const QJsonObject& j) { Config::PositionConfig::PositionConfig(const QJsonObject& j) {
ban = getValue<Config::StageConfig>(j, "ban"); ban = getValue<Config::StageConfig>(j, "ban");
pick = getValue<Config::StageConfig>(j, "pick"); pick = getValue<Config::StageConfig>(j, "pick");
position = toPosition(getValue<std::string>(j, "position")); position = toPosition(getValue<QString>(j, "position"));
if((int) position < 0 || position > Position::UTILITY) { if((int) position < 0 || position > Position::UTILITY) {
Log::warn << "invalid config value \"position\""; qWarning() << "invalid config value \"position\"";
position = Position::MIDDLE; position = Position::MIDDLE;
} }
} }
@ -66,7 +66,7 @@ Config::PositionConfig::operator QJsonObject() const {
out["ban"] = (QJsonObject) ban; out["ban"] = (QJsonObject) ban;
out["pick"] = (QJsonObject) pick; out["pick"] = (QJsonObject) pick;
out["position"] = QString::fromStdString(toString(position)); out["position"] = toString(position);
return out; return out;
} }
@ -194,7 +194,7 @@ Config::Config() {
Config::~Config() {} Config::~Config() {}
bool Config::load() { bool Config::load() {
QFile conffile(QString::fromStdString(configFilePath)); QFile conffile(configFilePath);
if(!conffile.open(QIODevice::ReadOnly)) { if(!conffile.open(QIODevice::ReadOnly)) {
qCritical() << "could not open configfile: " << configFilePath; qCritical() << "could not open configfile: " << configFilePath;
return false; return false;
@ -221,9 +221,9 @@ bool Config::load() {
void Config::save() { void Config::save() {
mkdirs(configFolderPath); mkdirs(configFolderPath);
QFile conffile(QString::fromStdString(configFilePath)); QFile conffile(configFilePath);
if(!conffile.open(QIODevice::WriteOnly)) { if(!conffile.open(QIODevice::WriteOnly)) {
Log::error << "could not open configfile: " << configFilePath; qCritical() << "could not open configfile: " << configFilePath;
return; return;
} }

View File

@ -13,10 +13,10 @@
#include "json.h" #include "json.h"
static const std::string BASEURL = "https://ddragon.leagueoflegends.com/"; static const QString BASEURL = "https://ddragon.leagueoflegends.com/";
const DataDragon::ChampData DataDragon::EMPTYCHAMP; const DataDragon::ChampData DataDragon::EMPTYCHAMP;
DataDragon::DataDragon(const std::string& locale) : RestClient(BASEURL), locale(locale), cache({{"square", ".png"}, {"loading", "_0.jpg"}, {"splash", "_0.jpg"}}) { DataDragon::DataDragon(const QString& locale) : RestClient(BASEURL), locale(locale), cache({{"square", ".png"}, {"loading", "_0.jpg"}, {"splash", "_0.jpg"}}) {
startThread(); startThread();
} }
@ -27,16 +27,16 @@ DataDragon::~DataDragon() {
DataDragon::ChampData::ChampData() : key(-1) {} DataDragon::ChampData::ChampData() : key(-1) {}
DataDragon::ChampData::ChampData(const QJsonObject& source) { DataDragon::ChampData::ChampData(const QJsonObject& source) {
name = getValue<std::string>(source, "name", ""); name = getValue<QString>(source, "name", "");
id = getValue<std::string>(source, "id", ""); id = getValue<QString>(source, "id", "");
key = getValue<int>(source, "key", -1); key = getValue<int>(source, "key", -1);
partype = getValue<std::string>(source, "partype", ""); partype = getValue<QString>(source, "partype", "");
title = getValue<std::string>(source, "title", ""); title = getValue<QString>(source, "title", "");
} }
const std::string& DataDragon::getVersion() { const QString& DataDragon::getVersion() {
std::unique_lock lock(cachedatamutex); std::unique_lock lock(cachedatamutex);
while(version.empty() && shouldrun) { while(version.isEmpty() && shouldrun) {
cachedatacv.wait(lock); cachedatacv.wait(lock);
} }
return version; return version;
@ -50,8 +50,8 @@ const std::vector<DataDragon::ChampData>& DataDragon::getChamps() {
return champs; return champs;
} }
QPixmap DataDragon::getImage(const std::string& champid, ImageType imgtype, bool writeMemcache) { QPixmap DataDragon::getImage(const QString& champid, ImageType imgtype, bool writeMemcache) {
if(champid.empty()) return {}; if(champid.isEmpty()) return {};
// query mem cache // query mem cache
QPixmap img = memcache.getImage(champid, (int) imgtype); QPixmap img = memcache.getImage(champid, (int) imgtype);
@ -65,8 +65,8 @@ QPixmap DataDragon::getImage(const std::string& champid, ImageType imgtype, bool
return img; return img;
} }
const std::string url = getImageUrl(champid, imgtype); const QString url = getImageUrl(champid, imgtype);
if(url.empty()) return {}; if(url.isEmpty()) return {};
QByteArray arr; QByteArray arr;
@ -74,14 +74,14 @@ QPixmap DataDragon::getImage(const std::string& champid, ImageType imgtype, bool
arr = requestRaw(url); arr = requestRaw(url);
} catch(RestClient::WebException& e) {} } catch(RestClient::WebException& e) {}
if(arr.isEmpty()) { if(arr.isEmpty()) {
Log::error << "image could not be loaded"; qCritical() << "image could not be loaded";
return {}; return {};
} }
// propably an error // propably an error
if(arr.size() < 1000) { if(arr.size() < 1000) {
Log::info << "small icon url: " << url; qInfo() << "small icon url: " << url;
Log::info << "content: " << std::string(arr.data(), arr.size()); qInfo() << "content: " << QString::fromLocal8Bit(arr);
return {}; return {};
} }
@ -102,7 +102,7 @@ QPixmap DataDragon::getImage(const std::string& champid, ImageType imgtype, bool
return decodedImage; return decodedImage;
} }
void DataDragon::getImageAsnyc(const std::string& champid, notifyImgfunc_t func, ImageType imgtype) { void DataDragon::getImageAsnyc(const QString& champid, notifyImgfunc_t func, ImageType imgtype) {
if(!func) return; if(!func) return;
{ {
@ -112,44 +112,40 @@ void DataDragon::getImageAsnyc(const std::string& champid, notifyImgfunc_t func,
tasksnotemptycv.notify_one(); tasksnotemptycv.notify_one();
} }
static std::string toLower(const std::string& in) { static int startinglength(const QString& original, const QString& prefix) {
return QString::fromStdString(in).toLower().toStdString(); int i = 0;
}
static size_t startinglength(const std::string& original, const std::string& prefix) {
size_t i = 0;
for(; i < original.size() && i < prefix.size(); ++i) { for(; i < original.size() && i < prefix.size(); ++i) {
if(original.substr(0, i+1) != prefix.substr(0, i+1)) { if(original.left(i+1) != prefix.left(i+1)) {
return i; return i;
} }
} }
return i; return i;
} }
static size_t matchChamp(const DataDragon::ChampData& champ, const std::string& lower) { static size_t matchChamp(const DataDragon::ChampData& champ, const QString& lower) {
std::string lowerid = toLower(champ.id); QString lowerid = champ.id.toLower();
std::string lowername = toLower(champ.name); QString lowername = champ.name.toLower();
if(lowerid == lower || lowername == lower) { if(lowerid == lower || lowername == lower) {
return lower.size(); return lower.size();
} }
size_t lengtha = startinglength(lowerid, lower); int lengtha = startinglength(lowerid, lower);
size_t lengthb = startinglength(lowername, lower); int lengthb = startinglength(lowername, lower);
return std::max(lengtha, lengthb); return qMax(lengtha, lengthb);
} }
const DataDragon::ChampData& DataDragon::getBestMatchingChamp(const std::string& name, int* count) { const DataDragon::ChampData& DataDragon::getBestMatchingChamp(const QString& name, int* count) {
getChamps(); getChamps();
// for now: just check for a perfect hit // for now: just check for a perfect hit
std::string lower = toLower(name); QString lower = name.toLower();
int bestmatchingoffset = -1; int bestmatchingoffset = -1;
size_t bestmatchinglength = 0; int bestmatchinglength = 0;
uint32_t bestmatchingcount = 0; uint32_t bestmatchingcount = 0;
for(size_t offset = 0; offset < champs.size(); ++offset) { for(size_t offset = 0; offset < champs.size(); ++offset) {
const ChampData& it = champs.at(offset); const ChampData& it = champs.at(offset);
size_t match = matchChamp(it, lower); int match = matchChamp(it, lower);
if(match > bestmatchinglength) { if(match > bestmatchinglength) {
bestmatchinglength = match; bestmatchinglength = match;
bestmatchingcount = 1; bestmatchingcount = 1;
@ -171,12 +167,12 @@ const DataDragon::ChampData& DataDragon::getBestMatchingChamp(const std::string&
return EMPTYCHAMP; return EMPTYCHAMP;
} }
std::vector<const DataDragon::ChampData*> DataDragon::getMatchingChamp(const std::string& name, uint32_t limit) { std::vector<const DataDragon::ChampData*> DataDragon::getMatchingChamp(const QString& name, uint32_t limit) {
if(limit == 0) return {}; if(limit == 0) return {};
if(name.empty()) return {}; if(name.isEmpty()) return {};
getChamps(); getChamps();
std::string lower = toLower(name); QString lower = name.toLower();
std::vector<size_t> matches; std::vector<size_t> matches;
matches.resize(champs.size()); matches.resize(champs.size());
@ -212,11 +208,11 @@ const DataDragon::ChampData* DataDragon::getChampByID(uint32_t id) {
return &*it; return &*it;
} }
std::vector<uint32_t> DataDragon::resolveChampIDs(const std::vector<std::string>& champnames) { std::vector<uint32_t> DataDragon::resolveChampIDs(const std::vector<QString>& champnames) {
std::vector<uint32_t> out; std::vector<uint32_t> out;
out.reserve(champnames.size()); out.reserve(champnames.size());
std::transform(champnames.begin(), champnames.end(), std::insert_iterator(out, out.begin()), [this](const std::string& champname) { std::transform(champnames.begin(), champnames.end(), std::insert_iterator(out, out.begin()), [this](const QString& champname) {
auto cd = getBestMatchingChamp(champname); auto cd = getBestMatchingChamp(champname);
return cd.key; // might be 0 (invalid) return cd.key; // might be 0 (invalid)
}); });
@ -224,10 +220,10 @@ std::vector<uint32_t> DataDragon::resolveChampIDs(const std::vector<std::string>
return out; return out;
} }
std::string DataDragon::getImageUrl(const std::string& champid, ImageType type) { QString DataDragon::getImageUrl(const QString& champid, ImageType type) {
switch(type) { switch(type) {
case ImageType::SQUARE: { case ImageType::SQUARE: {
if(getVersion().empty()) { if(getVersion().isEmpty()) {
return {}; return {};
} }
@ -244,13 +240,13 @@ std::string DataDragon::getImageUrl(const std::string& champid, ImageType type)
return {}; return {};
} }
std::string DataDragon::getCDNString() const { QString DataDragon::getCDNString() const {
return "cdn/" + version + "/"; return "cdn/" + version + "/";
} }
void DataDragon::prefetchChampImage(const std::string& champid, ImageType imgtype) { void DataDragon::prefetchChampImage(const QString& champid, ImageType imgtype) {
if(!cache[(int) imgtype].hasImage(champid)) { if(!cache[(int) imgtype].hasImage(champid)) {
Log::debug << "prefetch " << champid << " type: " << (int) imgtype; qDebug() << "prefetch " << champid << " type: " << (int) imgtype;
getImage(champid, imgtype, false); getImage(champid, imgtype, false);
} }
} }
@ -258,31 +254,31 @@ void DataDragon::prefetchChampImage(const std::string& champid, ImageType imgtyp
void DataDragon::getVersionInternal() { void DataDragon::getVersionInternal() {
std::unique_lock lock(cachedatamutex); std::unique_lock lock(cachedatamutex);
if(!version.empty()) return; if(!version.isEmpty()) return;
version = champCache.getVersion(); version = champCache.getVersion();
if(!version.empty()) return; if(!version.isEmpty()) return;
try { try {
QJsonDocument jversions = request("api/versions.json"); QJsonDocument jversions = request("api/versions.json");
if(jversions.isArray()) { if(jversions.isArray()) {
QJsonArray jverarr = jversions.array(); QJsonArray jverarr = jversions.array();
if(!jverarr.empty()) { if(!jverarr.empty()) {
version = jverarr.at(0).toString().toStdString(); version = jverarr.at(0).toString();
Log::info << "got League version: " << version; qInfo() << "got League version: " << version;
lock.unlock(); lock.unlock();
cachedatacv.notify_all(); cachedatacv.notify_all();
return; return;
} }
} }
Log::error << "error parsing version object"; qCritical() << "error parsing version object";
} catch(RestClient::WebException& e) {} } catch(RestClient::WebException& e) {}
} }
void DataDragon::getChampsInternal() { void DataDragon::getChampsInternal() {
std::unique_lock lock(cachedatamutex); std::unique_lock lock(cachedatamutex);
if(!champs.empty() && version.empty()) { if(!champs.empty() && version.isEmpty()) {
return; return;
} }
@ -316,7 +312,7 @@ void DataDragon::getChampsInternal() {
} }
} }
} }
Log::info << "loaded " << champs.size() << " champs from cache: " << cacheSuccessfull; qInfo() << "loaded " << champs.size() << " champs from cache: " << cacheSuccessfull;
lock.unlock(); lock.unlock();
cachedatacv.notify_all(); cachedatacv.notify_all();
} }
@ -358,7 +354,7 @@ void DataDragon::threadLoop() {
lock.unlock(); lock.unlock();
auto it = notDownloadedImages.begin(); auto it = notDownloadedImages.begin();
std::string champid = *it; QString champid = *it;
notDownloadedImages.erase(it); notDownloadedImages.erase(it);
prefetchChampImage(champid, ImageType::SQUARE); prefetchChampImage(champid, ImageType::SQUARE);
@ -391,5 +387,5 @@ void DataDragon::threadLoop() {
std::ostream& operator<<(std::ostream& str, const DataDragon::ChampData& cd) { std::ostream& operator<<(std::ostream& str, const DataDragon::ChampData& cd) {
return str << "[n: " << cd.name << " " << " k: " << cd.key << " id: " << cd.id << "]"; return str << "[n: " << cd.name.toStdString() << " " << " k: " << cd.key << " id: " << cd.id.toStdString() << "]";
} }

View File

@ -7,7 +7,7 @@
#include "files.h" #include "files.h"
DataDragonImageCache::DataDragonImageCache(const std::string& folderextra, const std::string& imageext) : imageext(imageext) { DataDragonImageCache::DataDragonImageCache(const QString& folderextra, const QString& imageext) : imageext(imageext) {
// init cache dir // init cache dir
cacheDir = getCache() + folderextra + "/"; cacheDir = getCache() + folderextra + "/";
@ -15,21 +15,21 @@ DataDragonImageCache::DataDragonImageCache(const std::string& folderextra, const
} }
DataDragonImageCache::~DataDragonImageCache() {} DataDragonImageCache::~DataDragonImageCache() {}
bool DataDragonImageCache::hasImage(const std::string& name) { bool DataDragonImageCache::hasImage(const QString& name) {
QFile file(QString::fromStdString(getFilepath(name))); QFile file(getFilepath(name));
return file.size() > 1024; // a image with less than 1KiB? assume it would be readable (r-Permissions) return file.size() > 1024; // a image with less than 1KiB? assume it would be readable (r-Permissions)
} }
QPixmap DataDragonImageCache::getImage(const std::string& name) { QPixmap DataDragonImageCache::getImage(const QString& name) {
return QPixmap(QString::fromStdString(getFilepath(name))); return QPixmap(getFilepath(name));
} }
void DataDragonImageCache::addImageRaw(const QByteArray& arr, const std::string& name) { void DataDragonImageCache::addImageRaw(const QByteArray& arr, const QString& name) {
QFile file(QString::fromStdString(getFilepath(name))); QFile file(getFilepath(name));
file.open(QIODevice::WriteOnly); file.open(QIODevice::WriteOnly);
file.write(arr); file.write(arr);
} }
std::string DataDragonImageCache::getFilepath(const std::string& name) const { QString DataDragonImageCache::getFilepath(const QString& name) const {
return cacheDir + name + imageext; return cacheDir + name + imageext;
} }

View File

@ -2,6 +2,8 @@
#include <sys/stat.h> #include <sys/stat.h>
#include <QDir>
#include <Log.h> #include <Log.h>
#ifdef WIN32 #ifdef WIN32
@ -11,45 +13,31 @@
#endif #endif
#ifdef WIN32 #ifdef WIN32
#include <QDir>
bool mkdirs(const std::string& path) { QString getHome() {
return QDir::root().mkpath(QString::fromStdString(path));
}
std::string getHome() {
const char* homevar = getenv("appdata"); const char* homevar = getenv("appdata");
if(homevar == nullptr) { if(homevar == nullptr) {
Log::warn << "%appdata% is not set! Defaulting to ./"; qWarning() << "%appdata% is not set! Defaulting to ./";
return "./"; return "./";
} }
return std::string(homevar) + "/"; return QString(homevar) + "/";
} }
#else #else
bool mkdirs(const std::string& path) {
size_t offset = 0;
while(offset < path.size()) {
offset = path.find('/', offset+1);
int res = mkdir(path.substr(0, offset).c_str(), S_IRWXU | S_IRWXG); // 770
if(res == -1 && errno != EEXIST) {
// mkdirs failed
return false;
}
}
return true; QString getHome() {
}
std::string getHome() {
const char* homevar = getenv("HOME"); const char* homevar = getenv("HOME");
if(homevar == nullptr) { if(homevar == nullptr) {
Log::warn << "$HOME is not set! Defaulting to ./"; qWarning() << "$HOME is not set! Defaulting to ./";
return "./"; return "./";
} }
return std::string(homevar) + "/"; return QString(homevar) + "/";
} }
#endif #endif
std::string getCache() { bool mkdirs(const QString& path) {
return QDir::root().mkpath(path);
}
QString getCache() {
return getHome() + CACHEPATH; return getHome() + CACHEPATH;
} }

View File

@ -22,22 +22,22 @@ LolAutoAccept::~LolAutoAccept() {
void LolAutoAccept::setChamps(const std::vector<uint32_t>& champs, State s) { void LolAutoAccept::setChamps(const std::vector<uint32_t>& champs, State s) {
if(s == State::LOBBY || s >= State::PICK) { if(s == State::LOBBY || s >= State::PICK) {
Log::warn << "setChamps() called on invalid State"; qWarning() << "setChamps() called on invalid State";
return; return;
} }
Log::debug << "LolAutoAccept::setChamps"; qDebug() << "LolAutoAccept::setChamps";
{ {
std::lock_guard lock(stagesMutex); std::lock_guard lock(stagesMutex);
stages.at((int) s).champids = champs; stages.at((int) s).champids = champs;
stages.at((int) s).currentOffset = 0; stages.at((int) s).currentOffset = 0;
} }
Log::info << "set champs on state: " << (int) s << " count: " << champs.size(); qInfo() << "set champs on state: " << (int) s << " count: " << champs.size();
} }
void LolAutoAccept::setEnabled(bool b, State s) { void LolAutoAccept::setEnabled(bool b, State s) {
if(s > State::PICK) { if(s > State::PICK) {
Log::warn << "setEnabled() called on invalid State"; qWarning() << "setEnabled() called on invalid State";
return; return;
} }
@ -56,7 +56,7 @@ bool LolAutoAccept::init() {
if(ca) { if(ca) {
clientapi = std::make_shared<ClientAPI>(*ca.get()); clientapi = std::make_shared<ClientAPI>(*ca.get());
auto selfinfo = clientapi->getSelf(); auto selfinfo = clientapi->getSelf();
Log::info << "selfinfo: gameName: " << selfinfo.gameName << " name: " << selfinfo.name << " summonerid: " << selfinfo.summonerid << " statusMessage: " << selfinfo.statusMessage << " puuid: " << selfinfo.puuid << " level: " << selfinfo.level; qInfo() << "selfinfo: gameName: " << selfinfo.gameName << " name: " << selfinfo.name << " summonerid: " << selfinfo.summonerid << " statusMessage: " << selfinfo.statusMessage << " puuid: " << selfinfo.puuid << " level: " << selfinfo.level;
} }
return (bool) clientapi; return (bool) clientapi;
@ -89,7 +89,7 @@ const std::vector<RuneAspekt>& LolAutoAccept::getRuneAspekts() {
if(runeaspekts.empty()) { if(runeaspekts.empty()) {
if(clientapi) { if(clientapi) {
runeaspekts = clientapi->getAllRuneAspekts(); runeaspekts = clientapi->getAllRuneAspekts();
Log::info << "Loaded " << runeaspekts.size() << " rune aspekts"; qInfo() << "Loaded " << runeaspekts.size() << " rune aspekts";
} }
} }
@ -100,7 +100,7 @@ const std::vector<RuneStyle>& LolAutoAccept::getRuneStyles() {
if(runestyles.empty()) { if(runestyles.empty()) {
if(clientapi) { if(clientapi) {
runestyles = clientapi->getAllRuneStyles(); runestyles = clientapi->getAllRuneStyles();
Log::info << "Loaded " << runestyles.size() << " rune styles"; qInfo() << "Loaded " << runestyles.size() << " rune styles";
} }
} }
@ -115,7 +115,7 @@ void LolAutoAccept::setOnRuneChangeFunc(onruneschange_func on) {
onRuneschange = on; onRuneschange = on;
} }
void LolAutoAccept::setAutoWriteText(bool enabled, const std::string& text) { void LolAutoAccept::setAutoWriteText(bool enabled, const QString& text) {
if ( enabled && !autoWriteTextEnabled ) { if ( enabled && !autoWriteTextEnabled ) {
// only re-write on rising edge // only re-write on rising edge
autoWriteTextDone = false; autoWriteTextDone = false;
@ -138,7 +138,7 @@ void LolAutoAccept::innerRun() {
try { try {
auto convs = clientapi->getAllConversations(); auto convs = clientapi->getAllConversations();
Log::info << "got " << convs.size() << " conversations"; qInfo() << "got " << convs.size() << " conversations";
emit statusChanged(Status::Running); emit statusChanged(Status::Running);
while(shouldrun) { while(shouldrun) {
@ -146,7 +146,7 @@ void LolAutoAccept::innerRun() {
auto start = std::chrono::high_resolution_clock::now(); auto start = std::chrono::high_resolution_clock::now();
auto phase = clientapi->getGameflowPhase(); auto phase = clientapi->getGameflowPhase();
Log::info << "current Gameflowphase: " << phase; qInfo() << "current Gameflowphase: " << phase;
// do processing // do processing
if(phase == ClientAPI::GameflowPhase::LOBBY) { if(phase == ClientAPI::GameflowPhase::LOBBY) {
@ -160,9 +160,9 @@ void LolAutoAccept::innerRun() {
if(stages.at(0).enabled) { // auto accept enabled if(stages.at(0).enabled) { // auto accept enabled
auto state = clientapi->getReadyCheckState(); auto state = clientapi->getReadyCheckState();
Log::info << "readychack state: " << state; qInfo() << "readychack state: " << state;
if(state == ClientAPI::ReadyCheckState::INPROGRESS) { if(state == ClientAPI::ReadyCheckState::INPROGRESS) {
Log::info << "auto accepting"; qInfo() << "auto accepting";
clientapi->acceptMatch(); clientapi->acceptMatch();
} }
} }
@ -202,7 +202,7 @@ void LolAutoAccept::innerRun() {
} }
emit statusChanged(Status::Off); emit statusChanged(Status::Off);
} catch(RestClient::WebException& e) { } catch(RestClient::WebException& e) {
Log::error << "WebException catched: " << e.curlresponse; qCritical() << "WebException catched: " << e.curlresponse;
if(e.curlresponse == CURLE_COULDNT_CONNECT) { if(e.curlresponse == CURLE_COULDNT_CONNECT) {
// free clientapi // free clientapi
clientapi.reset(); clientapi.reset();
@ -264,8 +264,8 @@ uint32_t LolAutoAccept::getChampOfState(State s) {
uint32_t size = stage.champids.size(); uint32_t size = stage.champids.size();
if(stage.currentOffset >= size) { if(stage.currentOffset >= size) {
// no champ to try left // no champ to try left
Log::warn << "no champ left at stage: " << (int) s; qWarning() << "no champ left at stage: " << (int) s;
Log::warn << "stage size: " << stage.champids.size(); qWarning() << "stage size: " << stage.champids.size();
return 0; return 0;
} }
@ -282,8 +282,8 @@ void LolAutoAccept::nextChampOfState(State s) {
if(stage.currentOffset >= size) { if(stage.currentOffset >= size) {
// no champ to try left // no champ to try left
Log::warn << "no champ left at stage: " << (int) s; qWarning() << "no champ left at stage: " << (int) s;
Log::warn << "stage size: " << stage.champids.size(); qWarning() << "stage size: " << stage.champids.size();
stage.currentOffset = 0; stage.currentOffset = 0;
return; return;
@ -293,7 +293,7 @@ void LolAutoAccept::nextChampOfState(State s) {
bool LolAutoAccept::isChampIntentofTeammate(uint32_t champid, const ClientAPI::ChampSelectSession& session) { bool LolAutoAccept::isChampIntentofTeammate(uint32_t champid, const ClientAPI::ChampSelectSession& session) {
for(const ClientAPI::ChampSelectCell& player : session.myTeam) { for(const ClientAPI::ChampSelectCell& player : session.myTeam) {
if(player.championID == (int32_t) champid || player.championPickIntentID == (int32_t) champid) { if(player.championID == (int32_t) champid || player.championPickIntentID == (int32_t) champid) {
Log::info << "player " << player.cellID << " @ " << player.position << " wants to play " << champid; qInfo() << "player " << player.cellID << " @ " << toString(player.position) << " wants to play " << champid;
return true; return true;
} }
} }
@ -313,7 +313,7 @@ LolAutoAccept::ownactions_t LolAutoAccept::getOwnActions(int32_t cellid, const s
ownactions_t out; ownactions_t out;
for(const auto& it : actions) { for(const auto& it : actions) {
if(it.actorCellID == cellid) { if(it.actorCellID == cellid) {
Log::debug << "ownaction: id: " << it.id << " champid: " << it.championID << " completed: " << it.completed << " type: " << it.type; qDebug() << "ownaction: id: " << it.id << " champid: " << it.championID << " completed: " << it.completed << " type: " << it.type;
if(!it.completed) { // completed cant be interacted anyways, so just ignore them. if(!it.completed) { // completed cant be interacted anyways, so just ignore them.
out.push_back(it); out.push_back(it);
} }
@ -344,7 +344,7 @@ void LolAutoAccept::phase(const ownactions_t& ownactions, ClientAPI::ChampSelect
for(auto it : ownactions) { for(auto it : ownactions) {
if(it.type == type) { if(it.type == type) {
Log::info << type << " action anvailable: " << it.id << " champid: " << it.championID; qInfo() << type << " action anvailable: " << it.id << " champid: " << it.championID;
uint32_t champid = getChampOfState(s); uint32_t champid = getChampOfState(s);
if(filter) { if(filter) {
@ -358,7 +358,7 @@ void LolAutoAccept::phase(const ownactions_t& ownactions, ClientAPI::ChampSelect
if((it.championID != (int32_t) champid || !it.completed) && champid != 0) { if((it.championID != (int32_t) champid || !it.completed) && champid != 0) {
// try to prepick a champion // try to prepick a champion
Log::info << "try to pick champ: " << champid; qInfo() << "try to pick champ: " << champid;
if(!clientapi->setChampSelectAction(it.id, champid, complete)) { if(!clientapi->setChampSelectAction(it.id, champid, complete)) {
nextChampOfState(s); nextChampOfState(s);
@ -370,15 +370,15 @@ void LolAutoAccept::phase(const ownactions_t& ownactions, ClientAPI::ChampSelect
} }
int32_t LolAutoAccept::getBestRunePage(const std::vector<ClientAPI::RunePage>& pages) { int32_t LolAutoAccept::getBestRunePage(const std::vector<ClientAPI::RunePage>& pages) {
Log::debug << "searching RunePages: " << pages.size(); qDebug() << "searching RunePages: " << pages.size();
for(uint32_t i = 0; i < pages.size(); ++i) { for(uint32_t i = 0; i < pages.size(); ++i) {
Log::debug << i << ": " << pages[i].id << " " << pages[i].name << " " << pages[i].isCurrent; qDebug() << i << ": " << pages[i].id << " " << pages[i].name << " " << pages[i].isCurrent;
} }
// search for a rune page with a name that starts with "AA: " // search for a rune page with a name that starts with "AA: "
for(uint32_t i = 0; i < pages.size(); ++i) { for(uint32_t i = 0; i < pages.size(); ++i) {
const ClientAPI::RunePage& rp = pages.at(i); const ClientAPI::RunePage& rp = pages.at(i);
if(rp.name.size() >= 4 && rp.name.substr(0, 4) == "AA: ") { if(rp.name.size() >= 4 && rp.name.left(4) == "AA: ") {
return i; return i;
} }
} }
@ -418,13 +418,13 @@ void LolAutoAccept::champSelect() {
// check if runes need adjustment // check if runes need adjustment
if(pickedChamp != lastPickedChamp) { if(pickedChamp != lastPickedChamp) {
Log::info << "picked champ changed from: " << lastPickedChamp << " to: " << pickedChamp; qInfo() << "picked champ changed from: " << lastPickedChamp << " to: " << pickedChamp;
lastPickedChamp = pickedChamp; lastPickedChamp = pickedChamp;
// update runes // update runes
if(onRuneschange) { if(onRuneschange) {
auto champinfo = blitzapi.getChampionInfo(pickedChamp, pos); // TODO: add detection for enemy champ auto champinfo = blitzapi.getChampionInfo(pickedChamp, pos); // TODO: add detection for enemy champ
Log::info << "champinfo aquired: " << champinfo.runepage; qInfo() << "champinfo aquired: " << champinfo.runepage;
onRuneschange(champinfo.runepage); onRuneschange(champinfo.runepage);
} }
@ -438,13 +438,13 @@ void LolAutoAccept::champSelect() {
emit positionChanged(pos); emit positionChanged(pos);
} }
Log::debug << "cellid: " << cellid << " position: " << pos << " counter: " << session.counter << " timer: timeleftip: " << session.timer.adjustedTimeLeftInPhase << " totaltimephase: " << session.timer.totalTimeInPhase; qDebug() << "cellid: " << cellid << " position: " << toString(pos) << " counter: " << session.counter << " timer: timeleftip: " << session.timer.adjustedTimeLeftInPhase << " totaltimephase: " << session.timer.totalTimeInPhase;
// find actions for own cell // find actions for own cell
auto ownactions = getOwnActions(cellid, session.actions); auto ownactions = getOwnActions(cellid, session.actions);
Log::debug << "ownactions: " << ownactions.size(); qDebug() << "ownactions: " << ownactions.size();
// try to prepick champ // try to prepick champ
Log::info << "champselectphase: " << session.timer.phase; qInfo() << "champselectphase: " << session.timer.phase;
std::lock_guard lock(stagesMutex); std::lock_guard lock(stagesMutex);
if(session.timer.phase == ClientAPI::ChampSelectPhase::PLANNING) { if(session.timer.phase == ClientAPI::ChampSelectPhase::PLANNING) {
@ -466,9 +466,9 @@ void LolAutoAccept::champSelect() {
} }
// check for autowriteText // check for autowriteText
if(autoWriteTextEnabled && !autoWriteTextDone && !autoWriteText.empty()) { if(autoWriteTextEnabled && !autoWriteTextDone && !autoWriteText.isEmpty()) {
const std::string& chatid = getChatid(); const QString& chatid = getChatid();
if(!chatid.empty()) { if(!chatid.isEmpty()) {
clientapi->sendMessage(chatid, autoWriteText); clientapi->sendMessage(chatid, autoWriteText);
autoWriteTextDone = true; autoWriteTextDone = true;
} }
@ -478,7 +478,7 @@ void LolAutoAccept::champSelect() {
void LolAutoAccept::smiteWarning(const std::vector<ClientAPI::ChampSelectCell>& cells) { void LolAutoAccept::smiteWarning(const std::vector<ClientAPI::ChampSelectCell>& cells) {
uint32_t smiteCount = 0; uint32_t smiteCount = 0;
for(const ClientAPI::ChampSelectCell& member : cells) { for(const ClientAPI::ChampSelectCell& member : cells) {
Log::info << "position: " << member.position << " spells: " << member.spell1Id << " " << member.spell2Id; qInfo() << "position: " << toString(member.position) << " spells: " << member.spell1Id << " " << member.spell2Id;
smiteCount += (member.spell1Id == 11 || member.spell2Id == 11); smiteCount += (member.spell1Id == 11 || member.spell2Id == 11);
} }
@ -489,24 +489,24 @@ void LolAutoAccept::smiteWarning(const std::vector<ClientAPI::ChampSelectCell>&
return; return;
} }
Log::info << "smite warning: " << smiteCount; qInfo() << "smite warning: " << smiteCount;
const std::string& chatid = getChatid(); const QString& chatid = getChatid();
if(!chatid.empty()) { if(!chatid.isEmpty()) {
clientapi->sendMessage(chatid, "smite"); clientapi->sendMessage(chatid, "smite");
lastMessageSent = currenttime; lastMessageSent = currenttime;
} }
} }
} }
const std::string& LolAutoAccept::getChatid() { const QString& LolAutoAccept::getChatid() {
if(chatid.empty()) { if(chatid.isEmpty()) {
std::vector<ClientAPI::Conversation> convs = clientapi->getAllConversations(); std::vector<ClientAPI::Conversation> convs = clientapi->getAllConversations();
Log::info << "got " << convs.size() << " conversations"; qInfo() << "got " << convs.size() << " conversations";
for(const ClientAPI::Conversation& conv : convs) { for(const ClientAPI::Conversation& conv : convs) {
Log::info << " id: " << conv.id << " type: " << conv.type << " name: " << conv.name << " gameName: " << conv.gameName; qInfo() << " id: " << conv.id << " type: " << conv.type << " name: " << conv.name << " gameName: " << conv.gameName;
if(conv.type == "championSelect" && conv.name.empty()) { if(conv.type == "championSelect" && conv.name.isEmpty()) {
Log::info << "groupchat found"; qInfo() << "groupchat found";
chatid = conv.id; chatid = conv.id;
return chatid; return chatid;
} }
@ -521,7 +521,7 @@ void LolAutoAccept::applyRunes_internal(uint32_t champid, Position pos) {
// get recommended runes and stuff // get recommended runes and stuff
auto champinfo = blitzapi.getChampionInfo(champid, pos); auto champinfo = blitzapi.getChampionInfo(champid, pos);
Log::info << "fetched champion info runes: " << champinfo.runepage; qInfo() << "fetched champion info runes: " << champinfo.runepage;
// choose page // choose page
auto pages = clientapi->getAllRunePages(); auto pages = clientapi->getAllRunePages();
@ -530,29 +530,29 @@ void LolAutoAccept::applyRunes_internal(uint32_t champid, Position pos) {
int32_t choosepage = getMatchingRunePage(champinfo.runepage, pages); int32_t choosepage = getMatchingRunePage(champinfo.runepage, pages);
if(choosepage != -1) { if(choosepage != -1) {
ClientAPI::RunePage& page = pages.at(choosepage); ClientAPI::RunePage& page = pages.at(choosepage);
Log::info << "matching runepage found, selecting: " << page.id << " " << page.name; qInfo() << "matching runepage found, selecting: " << page.id << " " << page.name;
if(clientapi->selectRunePage(page.id)) { if(clientapi->selectRunePage(page.id)) {
return; return;
} }
Log::warn << "selecting runepage failed"; qWarning() << "selecting runepage failed";
} }
// find page to replace // find page to replace
int32_t pageoffset = getBestRunePage(pages); int32_t pageoffset = getBestRunePage(pages);
if(pageoffset < 0) { if(pageoffset < 0) {
Log::warn << "no rune page found!"; qWarning() << "no rune page found!";
return; return;
} }
// replace the page // replace the page
ClientAPI::RunePage& rp = pages.at(pageoffset); ClientAPI::RunePage& rp = pages.at(pageoffset);
Log::info << "replace runepage id: " << rp.id << " old-name: " << rp.name; qInfo() << "replace runepage id: " << rp.id << " old-name: " << rp.name;
// resolve champion name for the runepage name // resolve champion name for the runepage name
ClientAPI::RunePage newpage; ClientAPI::RunePage newpage;
auto champ = dd.getChampByID(champid); auto champ = dd.getChampByID(champid);
const std::string champname = champ ? champ->name : std::to_string(champid); const QString champname = champ ? champ->name : QString::number(champid);
newpage.id = rp.id; newpage.id = rp.id;
newpage.name = "AA: " + champname + " " + toShortString(pos); // TODO: make role "Utility" resolve to "Support"? newpage.name = "AA: " + champname + " " + toShortString(pos); // TODO: make role "Utility" resolve to "Support"?
@ -561,9 +561,9 @@ void LolAutoAccept::applyRunes_internal(uint32_t champid, Position pos) {
//select runepage //select runepage
if(!rp.isCurrent) { if(!rp.isCurrent) {
Log::info << "page is not selected, selecting now (id: " << newpage.id << ')'; qInfo() << "page is not selected, selecting now (id: " << newpage.id << ')';
clientapi->selectRunePage(newpage.id); clientapi->selectRunePage(newpage.id);
} }
Log::info << "runepage done"; qInfo() << "runepage done";
} }

View File

@ -5,7 +5,7 @@
#include <Log.h> #include <Log.h>
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), loading(true), ui(new Ui::MainWindow), saveTimer(new QTimer(this)), dd(QLocale().name().toStdString()), MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), loading(true), ui(new Ui::MainWindow), saveTimer(new QTimer(this)), dd(QLocale().name()),
lolaa(conf.getConfig(), dd) { lolaa(conf.getConfig(), dd) {
ui->setupUi(this); ui->setupUi(this);
@ -41,7 +41,7 @@ MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), loading(true), ui
ui->enableAutoWrite->setChecked(rc.enabledAutoWrite); ui->enableAutoWrite->setChecked(rc.enabledAutoWrite);
ui->autoWriteText->setText(rc.autoWriteText); ui->autoWriteText->setText(rc.autoWriteText);
lolaa.setAutoWriteText(rc.enabledAutoWrite, rc.autoWriteText.toStdString()); lolaa.setAutoWriteText(rc.enabledAutoWrite, rc.autoWriteText);
resizeEvent(nullptr); resizeEvent(nullptr);
@ -82,7 +82,7 @@ void MainWindow::toggleMainswitch(bool state) {
// TODO: make this non blocking // TODO: make this non blocking
if(!lolaa.init()) { if(!lolaa.init()) {
Log::error << "League Client not found!"; qCritical() << "League Client not found!";
ui->statusbar->showMessage(tr("League of Legends Client not found!")); ui->statusbar->showMessage(tr("League of Legends Client not found!"));
ui->mainswitch->setCheckState(Qt::CheckState::Unchecked); ui->mainswitch->setCheckState(Qt::CheckState::Unchecked);
ui->mainswitch->setEnabled(true); ui->mainswitch->setEnabled(true);
@ -148,7 +148,7 @@ void MainWindow::autoWriteChanged() {
bool enabled = ui->enableAutoWrite->isChecked(); bool enabled = ui->enableAutoWrite->isChecked();
const QString text = ui->autoWriteText->toPlainText(); const QString text = ui->autoWriteText->toPlainText();
lolaa.setAutoWriteText(enabled, text.toStdString()); lolaa.setAutoWriteText(enabled, text);
conf.getConfig().enabledAutoWrite = enabled; conf.getConfig().enabledAutoWrite = enabled;
conf.getConfig().autoWriteText = text; conf.getConfig().autoWriteText = text;

View File

@ -5,7 +5,7 @@
MemoryImageCache::MemoryImageCache(size_t maxsize) : maxsize(maxsize) {} MemoryImageCache::MemoryImageCache(size_t maxsize) : maxsize(maxsize) {}
void MemoryImageCache::addImage(QPixmap img, const std::string& title, int type) { void MemoryImageCache::addImage(QPixmap img, const QString& title, int type) {
auto it = std::find_if(cache.begin(), cache.end(), getImageMatcher(title, type)); auto it = std::find_if(cache.begin(), cache.end(), getImageMatcher(title, type));
if(it == cache.end()) { if(it == cache.end()) {
// insert new // insert new
@ -19,7 +19,7 @@ void MemoryImageCache::addImage(QPixmap img, const std::string& title, int type)
it->imageref = img; it->imageref = img;
} }
QPixmap MemoryImageCache::getImage(const std::string& title, int type) { QPixmap MemoryImageCache::getImage(const QString& title, int type) {
auto it = std::find_if(cache.begin(), cache.end(), getImageMatcher(title, type)); auto it = std::find_if(cache.begin(), cache.end(), getImageMatcher(title, type));
if(it == cache.end()) { if(it == cache.end()) {
return {}; return {};
@ -40,7 +40,7 @@ bool MemoryImageCache::CachedImage::operator<(const MemoryImageCache::CachedImag
return lastaccessed < other.lastaccessed; return lastaccessed < other.lastaccessed;
} }
std::function<bool(const MemoryImageCache::CachedImage&)> MemoryImageCache::getImageMatcher(const std::string& title, int type) { std::function<bool(const MemoryImageCache::CachedImage&)> MemoryImageCache::getImageMatcher(const QString& title, int type) {
return [title, type](const MemoryImageCache::CachedImage& img) -> bool { return [title, type](const MemoryImageCache::CachedImage& img) -> bool {
return img.type == type && img.title == title; return img.type == type && img.title == title;
}; };

View File

@ -63,7 +63,7 @@ static int my_trace(CURL* handle, curl_infotype type, char* data, size_t size, v
return 0; return 0;
} }
RestClient::RestClient(const std::string& base) : baseurl(base) { RestClient::RestClient(const QString& base) : baseurl(base) {
curl = curl_easy_init(); curl = curl_easy_init();
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L); curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, arrayWriteCallback); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, arrayWriteCallback);
@ -77,13 +77,13 @@ RestClient::~RestClient() {
RestClient::WebException::WebException(CURLcode c) : curlresponse(c) { RestClient::WebException::WebException(CURLcode c) : curlresponse(c) {
} }
QByteArray RestClient::requestRaw(const std::string& url, Method m, const std::string& data) { QByteArray RestClient::requestRaw(const QString& url, Method m, const QString& data) {
if (!curl) return {}; if (!curl) return {};
std::string requrl = baseurl + url; QString requrl = baseurl + url;
curl_easy_setopt(curl, CURLOPT_URL, requrl.c_str()); curl_easy_setopt(curl, CURLOPT_URL, requrl.toLocal8Bit().data());
curl_easy_setopt(curl, CURLOPT_USERPWD, basicauth.c_str()); curl_easy_setopt(curl, CURLOPT_USERPWD, basicauth.toLocal8Bit().data());
curl_easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); curl_easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
if (disableCertCheck) { if (disableCertCheck) {
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L); curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
@ -106,22 +106,22 @@ QByteArray RestClient::requestRaw(const std::string& url, Method m, const std::s
curl_easy_setopt(curl, CURLOPT_HTTPGET, 1L); break; curl_easy_setopt(curl, CURLOPT_HTTPGET, 1L); break;
case Method::POST: case Method::POST:
curl_easy_setopt(curl, CURLOPT_POST, 1L); curl_easy_setopt(curl, CURLOPT_POST, 1L);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data.c_str()); curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data.toLocal8Bit().data());
headerlist = curl_slist_append(headerlist, "Content-Type: application/json"); headerlist = curl_slist_append(headerlist, "Content-Type: application/json");
break; break;
case Method::PUT: case Method::PUT:
curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "PUT"); // to use the POSTFIELDS (do not use CURLOPT_PUT, it does not support POSTFIELDS) curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "PUT"); // to use the POSTFIELDS (do not use CURLOPT_PUT, it does not support POSTFIELDS)
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data.c_str()); curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data.toLocal8Bit().data());
headerlist = curl_slist_append(headerlist, "Content-Type: application/json"); headerlist = curl_slist_append(headerlist, "Content-Type: application/json");
break; break;
case Method::PATCH: case Method::PATCH:
curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "PATCH"); curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "PATCH");
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data.c_str()); curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data.toLocal8Bit().data());
headerlist = curl_slist_append(headerlist, "Content-Type: application/json"); headerlist = curl_slist_append(headerlist, "Content-Type: application/json");
break; break;
case Method::DELETE: case Method::DELETE:
curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "DELETE"); curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "DELETE");
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data.c_str()); curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data.toLocal8Bit().data());
headerlist = curl_slist_append(headerlist, "Content-Type: application/json"); headerlist = curl_slist_append(headerlist, "Content-Type: application/json");
break; break;
} }
@ -141,9 +141,9 @@ QByteArray RestClient::requestRaw(const std::string& url, Method m, const std::s
if (res == CURLE_HTTP_RETURNED_ERROR) { if (res == CURLE_HTTP_RETURNED_ERROR) {
long responsecode = -1; long responsecode = -1;
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &responsecode); curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &responsecode);
Log::warn << "API request failed: " << baseurl << " " << url << " -> " << responsecode; qWarning() << "API request failed: " << baseurl << " " << url << " -> " << responsecode;
} else { } else {
Log::warn << "API request failed: " << baseurl << " " << url << " " << curl_easy_strerror(res); qWarning() << "API request failed: " << baseurl << " " << url << " " << curl_easy_strerror(res);
if(res == CURLE_COULDNT_CONNECT) { if(res == CURLE_COULDNT_CONNECT) {
throw WebException(res); throw WebException(res);
} }
@ -153,14 +153,14 @@ QByteArray RestClient::requestRaw(const std::string& url, Method m, const std::s
return ba; return ba;
} }
QJsonDocument RestClient::request(const std::string& url, Method m, const std::string& data) { QJsonDocument RestClient::request(const QString& url, Method m, const QString& data) {
QByteArray arr = requestRaw(url, m, data); QByteArray arr = requestRaw(url, m, data);
if (arr.isEmpty()) return {}; if (arr.isEmpty()) return {};
QJsonParseError err; QJsonParseError err;
QJsonDocument parsed = QJsonDocument::fromJson(arr, &err); QJsonDocument parsed = QJsonDocument::fromJson(arr, &err);
if (parsed.isNull() || err.error != QJsonParseError::NoError) { if (parsed.isNull() || err.error != QJsonParseError::NoError) {
Log::error << "API Json parse error " << err.errorString().toStdString() << " offset: " << err.offset; qCritical() << "API Json parse error " << err.errorString() << " offset: " << err.offset;
return {}; return {};
} }
@ -178,9 +178,9 @@ void RestClient::enableDebugging(bool enabled) {
} }
} }
std::string RestClient::escape(const std::string& in) const { QString RestClient::escape(const QString& in) const {
char* e = curl_easy_escape(curl, in.c_str(), in.length()); char* e = curl_easy_escape(curl, in.toLocal8Bit().data(), in.length());
std::string esc(e); QString esc(e);
curl_free(e); curl_free(e);
return esc; return esc;
} }

View File

@ -1,9 +1,9 @@
#include "runedisplay.h" #include "runedisplay.h"
#include "ui_runedisplay.h" #include "ui_runedisplay.h"
#include <sstream> #include <QTextStream>
const static std::string EMPTY; const static QString EMPTY;
RuneDisplay::RuneDisplay(QWidget *parent) : QWidget(parent), ui(new Ui::RuneDisplay) { RuneDisplay::RuneDisplay(QWidget *parent) : QWidget(parent), ui(new Ui::RuneDisplay) {
ui->setupUi(this); ui->setupUi(this);
@ -32,10 +32,11 @@ void RuneDisplay::applyRunesClicked() {
} }
void RuneDisplay::updateText() { void RuneDisplay::updateText() {
std::ostringstream out; QString outStr;
QTextStream out(&outStr);
if(! (bool) runepage) { if(! (bool) runepage) {
ui->runetext->setText(QString::fromStdString("")); ui->runetext->setText("");
ui->applyRunesBtn->setEnabled(false); ui->applyRunesBtn->setEnabled(false);
return; return;
} }
@ -45,24 +46,24 @@ void RuneDisplay::updateText() {
for(uint32_t rune : runepage.selectedAspects) { for(uint32_t rune : runepage.selectedAspects) {
out << getRuneText(rune) << '\n'; out << getRuneText(rune) << '\n';
} }
ui->runetext->setText(QString::fromStdString(out.str())); ui->runetext->setText(outStr);
ui->applyRunesBtn->setEnabled(true); ui->applyRunesBtn->setEnabled(true);
} }
std::string RuneDisplay::getRuneText(uint32_t id) { QString RuneDisplay::getRuneText(uint32_t id) {
for(const RuneAspekt& ra : runeinfo) { for(const RuneAspekt& ra : runeinfo) {
if(ra.id == id) { if(ra.id == id) {
return ra.name; return ra.name;
} }
} }
return "(" + std::to_string(id) + ")"; return "(" + QString::number(id) + ")";
} }
std::string RuneDisplay::getRuneStyleByID(uint32_t id) { QString RuneDisplay::getRuneStyleByID(uint32_t id) {
auto it = std::find_if(runestyles.begin(), runestyles.end(), [id](const RuneStyle& rs) { return rs.id == id; }); auto it = std::find_if(runestyles.begin(), runestyles.end(), [id](const RuneStyle& rs) { return rs.id == id; });
if(it == runestyles.end()) { if(it == runestyles.end()) {
return '(' + std::to_string(id) + ')'; return '(' + QString::number(id) + ')';
} }
return it->name; return it->name;

View File

@ -140,12 +140,12 @@ const RuneStyle* RuneEditor::getRuneStyle(uint32_t id) const {
} }
RuneAspektButton* RuneEditor::createStyleButton(const RuneStyle& rs, bool selected) { RuneAspektButton* RuneEditor::createStyleButton(const RuneStyle& rs, bool selected) {
RuneAspektButton* styleBtn = createButtonFromResource(QString::fromStdString(rs.iconPath)); RuneAspektButton* styleBtn = createButtonFromResource(rs.iconPath);
if(!styleBtn) return nullptr; if(!styleBtn) return nullptr;
styleBtn->setText(QString::fromStdString(rs.name)); styleBtn->setText(rs.name);
styleBtn->setToolTip(QString::fromStdString(rs.tooltip)); styleBtn->setToolTip(rs.tooltip);
if(selected) { if(selected) {
styleBtn->setStyleSheet("border: 1px solid red;"); styleBtn->setStyleSheet("border: 1px solid red;");
@ -155,12 +155,12 @@ RuneAspektButton* RuneEditor::createStyleButton(const RuneStyle& rs, bool select
} }
RuneAspektButton* RuneEditor::createAspektButton(const RuneAspekt& ra) { RuneAspektButton* RuneEditor::createAspektButton(const RuneAspekt& ra) {
RuneAspektButton* aspektBtn = createButtonFromResource(QString::fromStdString(ra.iconPath)); RuneAspektButton* aspektBtn = createButtonFromResource(ra.iconPath);
if(!aspektBtn) return nullptr; if(!aspektBtn) return nullptr;
aspektBtn->setText(QString::fromStdString(ra.name)); aspektBtn->setText(ra.name);
aspektBtn->setToolTip(QString::fromStdString(ra.tooltip)); aspektBtn->setToolTip(ra.tooltip);
aspektBtn->setAspektsVector(runepage.selectedAspects); aspektBtn->setAspektsVector(runepage.selectedAspects);
aspektBtn->setAspektId(ra.id); aspektBtn->setAspektId(ra.id);

View File

@ -115,7 +115,7 @@ void RuneManager::setRunesEnabled(bool enabled) {
void RuneManager::saveRunePageClient(int id, QString name, const RunePage& rp) { void RuneManager::saveRunePageClient(int id, QString name, const RunePage& rp) {
if(client) { if(client) {
ClientAPI::RunePage newPage; ClientAPI::RunePage newPage;
newPage.name = name.toStdString(); newPage.name = name;
newPage.runepage = rp; newPage.runepage = rp;
newPage.id = id; newPage.id = id;

View File

@ -53,3 +53,7 @@ RunePage::RunePage(const QJsonObject& obj) :
std::ostream& operator<<(std::ostream& str, const RunePage& rp) { std::ostream& operator<<(std::ostream& str, const RunePage& rp) {
return str << "Primary: " << rp.primaryStyle << " Secondary: " << rp.secondaryStyle << " aspects: " << rp.selectedAspects.size(); return str << "Primary: " << rp.primaryStyle << " Secondary: " << rp.secondaryStyle << " aspects: " << rp.selectedAspects.size();
} }
QDebug operator<<(QDebug str, const RunePage& rp) {
return str << "Primary: " << rp.primaryStyle << " Secondary: " << rp.secondaryStyle << " aspects: " << rp.selectedAspects.size();
}

View File

@ -25,7 +25,7 @@ RunePageList::~RunePageList() {
void RunePageList::loadRunePages(const std::vector<ClientAPI::RunePage>& pages) { void RunePageList::loadRunePages(const std::vector<ClientAPI::RunePage>& pages) {
clearItems(); clearItems();
for(const ClientAPI::RunePage& rp : pages) { for(const ClientAPI::RunePage& rp : pages) {
addRunepageItem(QString::fromStdString(rp.name), rp.id, rp.runepage, rp.isCurrent); addRunepageItem(rp.name, rp.id, rp.runepage, rp.isCurrent);
} }
} }
@ -202,7 +202,7 @@ void RunePageList::addRunepageItem(QString name, int id, const ::RunePage& rp, b
item->setData(RolePointer, (qulonglong) new ::RunePage(rp)); item->setData(RolePointer, (qulonglong) new ::RunePage(rp));
if(dd) { if(dd) {
const DataDragon::ChampData& champData = dd->getBestMatchingChamp(name.toStdString()); const DataDragon::ChampData& champData = dd->getBestMatchingChamp(name);
if(champData.key != -1) { if(champData.key != -1) {
QPixmap iamge = dd->getImage(champData.id); QPixmap iamge = dd->getImage(champData.id);
item->setIcon(iamge); item->setIcon(iamge);
@ -244,7 +244,7 @@ QString RunePageList::getRuneText(uint32_t id) {
if(runeInfo != nullptr) { if(runeInfo != nullptr) {
for(const RuneAspekt& ra : *runeInfo) { for(const RuneAspekt& ra : *runeInfo) {
if(ra.id == id) { if(ra.id == id) {
return QString::fromStdString(ra.name); return ra.name;
} }
} }
} }
@ -257,7 +257,7 @@ QString RunePageList::getRuneStyleByID(uint32_t id) {
auto it = std::find_if(runeStyles->begin(), runeStyles->end(), [id](const RuneStyle& rs) { return rs.id == id; }); auto it = std::find_if(runeStyles->begin(), runeStyles->end(), [id](const RuneStyle& rs) { return rs.id == id; });
if(it != runeStyles->end()) { if(it != runeStyles->end()) {
return QString::fromStdString(it->name); return it->name;
} }
} }

View File

@ -4,8 +4,8 @@
#include <algorithm> #include <algorithm>
#include <Log.h> #include <Log.h>
static std::vector<std::string> toChampionNameList(const std::vector<StageSettings::SelectedChamp>& scs) { static std::vector<QString> toChampionNameList(const std::vector<StageSettings::SelectedChamp>& scs) {
std::vector<std::string> out; std::vector<QString> out;
out.reserve(scs.size()); out.reserve(scs.size());
std::transform(scs.begin(), scs.end(), std::insert_iterator(out, out.begin()), [](const StageSettings::SelectedChamp& sc) { return sc.name; }); std::transform(scs.begin(), scs.end(), std::insert_iterator(out, out.begin()), [](const StageSettings::SelectedChamp& sc) { return sc.name; });
@ -42,7 +42,7 @@ bool SettingsTab::getState(LolAutoAccept::State s) const {
return stage->getState(); return stage->getState();
} }
void SettingsTab::setChamps(LolAutoAccept::State s, const std::vector<std::string>& c) { void SettingsTab::setChamps(LolAutoAccept::State s, const std::vector<QString>& c) {
getStage(s)->setChampions(c); getStage(s)->setChampions(c);
} }

View File

@ -39,23 +39,23 @@ void StageSettings::setState(bool b) {
updateEnabled(); updateEnabled();
} }
StageSettings::SelectedChamp::SelectedChamp(std::string name, uint32_t id) : name(name), id(id) {} StageSettings::SelectedChamp::SelectedChamp(QString name, uint32_t id) : name(name), id(id) {}
std::vector<StageSettings::SelectedChamp> StageSettings::getChampions() const { std::vector<StageSettings::SelectedChamp> StageSettings::getChampions() const {
std::vector<SelectedChamp> out; std::vector<SelectedChamp> out;
out.reserve(ui->championList->count()); out.reserve(ui->championList->count());
for(int32_t i = 0; i < ui->championList->count(); ++i) { for(int32_t i = 0; i < ui->championList->count(); ++i) {
ChampRow* cr = (ChampRow*) ui->championList->item(i); ChampRow* cr = (ChampRow*) ui->championList->item(i);
out.emplace_back(cr->getChamp().toStdString(), cr->getChampID()); out.emplace_back(cr->getChamp(), cr->getChampID());
} }
return out; return out;
} }
void StageSettings::setChampions(const std::vector<std::string>& champs) { void StageSettings::setChampions(const std::vector<QString>& champs) {
clear(); clear();
// add new champs // add new champs
for(const std::string& champ : champs) { for(const QString& champ : champs) {
resolveAndAddChamp(champ, champ == champs.back()); resolveAndAddChamp(champ, champ == champs.back());
} }
} }
@ -87,7 +87,7 @@ void StageSettings::addChamp() {
// popup with champion search // popup with champion search
ChampionSearch cs(dd, this); ChampionSearch cs(dd, this);
int res = cs.exec(); int res = cs.exec();
Log::info << "championsearch result: " << res; qInfo() << "championsearch result: " << res;
if(res == QDialog::Accepted) { if(res == QDialog::Accepted) {
auto cr = cs.getSearchResult(); auto cr = cs.getSearchResult();
if(cr) { if(cr) {
@ -110,7 +110,7 @@ void StageSettings::moved() {
emit championsChanged(); emit championsChanged();
} }
void StageSettings::resolveAndAddChamp(const std::string& name, bool emitchange) { void StageSettings::resolveAndAddChamp(const QString& name, bool emitchange) {
if(dd) { if(dd) {
int count = 0; int count = 0;
auto cd = dd->getBestMatchingChamp(name, &count); auto cd = dd->getBestMatchingChamp(name, &count);
@ -122,7 +122,7 @@ void StageSettings::resolveAndAddChamp(const std::string& name, bool emitchange)
} }
}); });
} else { } else {
Log::error << __PRETTY_FUNCTION__ << " Datadragon not set!"; qCritical() << __PRETTY_FUNCTION__ << " Datadragon not set!";
} }
} }