refactor indendation, fix a bug in MinecraftProcess & fix a bug in

InstanceLauncher
This commit is contained in:
Orochimarufan 2013-02-25 22:47:03 +01:00
parent f01bf10dc5
commit f4c9cb8c1d
13 changed files with 206 additions and 210 deletions

View File

@ -7,7 +7,7 @@ namespace java
class constant class constant
{ {
public: public:
enum type_t : uint8_t enum type_t : uint8_t
{ {
j_hole = 0, // HACK: this is a hole in the array, because java is crazy j_hole = 0, // HACK: this is a hole in the array, because java is crazy
j_string_data = 1, j_string_data = 1,
@ -145,7 +145,7 @@ namespace java
uint16_t descriptor_index; uint16_t descriptor_index;
} name_and_type; } name_and_type;
}; };
}; };
/** /**
* A helper class that represents the custom container used in Java class file for storage of constants * A helper class that represents the custom container used in Java class file for storage of constants
@ -185,7 +185,7 @@ namespace java
index++; index++;
} }
} }
} }
typedef std::vector<java::constant> container_type; typedef std::vector<java::constant> container_type;
/** /**
* Access constants based on jar file index numbers (index of the first element is 1) * Access constants based on jar file index numbers (index of the first element is 1)
@ -208,5 +208,5 @@ namespace java
} }
private: private:
container_type constants; container_type constants;
}; };
} }

View File

@ -26,56 +26,56 @@ namespace javautils
QString GetMinecraftJarVersion(QString jarName) QString GetMinecraftJarVersion(QString jarName)
{ {
QString version = MCVer_Unknown; QString version = MCVer_Unknown;
// check if minecraft.jar exists // check if minecraft.jar exists
QFile jar(jarName); QFile jar(jarName);
if (!jar.exists()) if (!jar.exists())
return version; return version;
// open minecraft.jar // open minecraft.jar
QuaZip zip(&jar); QuaZip zip(&jar);
if (!zip.open(QuaZip::mdUnzip)) if (!zip.open(QuaZip::mdUnzip))
return version; return version;
// open Minecraft.class // open Minecraft.class
zip.setCurrentFile("net/minecraft/client/Minecraft.class", QuaZip::csSensitive); zip.setCurrentFile("net/minecraft/client/Minecraft.class", QuaZip::csSensitive);
QuaZipFile Minecraft(&zip); QuaZipFile Minecraft(&zip);
if (!Minecraft.open(QuaZipFile::ReadOnly)) if (!Minecraft.open(QuaZipFile::ReadOnly))
return version; return version;
// read Minecraft.class // read Minecraft.class
qint64 size = Minecraft.size(); qint64 size = Minecraft.size();
char *classfile = new char[size]; char *classfile = new char[size];
Minecraft.read(classfile, size); Minecraft.read(classfile, size);
// parse Minecraft.class // parse Minecraft.class
try { try {
char *temp = classfile; char *temp = classfile;
java::classfile MinecraftClass(temp, size); java::classfile MinecraftClass(temp, size);
java::constant_pool constants = MinecraftClass.constants; java::constant_pool constants = MinecraftClass.constants;
for(java::constant_pool::container_type::const_iterator iter=constants.begin(); for(java::constant_pool::container_type::const_iterator iter=constants.begin();
iter != constants.end(); iter++) iter != constants.end(); iter++)
{ {
const java::constant & constant = *iter; const java::constant & constant = *iter;
if (constant.type != java::constant::j_string_data) if (constant.type != java::constant::j_string_data)
continue; continue;
const std::string & str = constant.str_data; const std::string & str = constant.str_data;
if (str.compare(0, 20, "Minecraft Minecraft ") == 0) if (str.compare(0, 20, "Minecraft Minecraft ") == 0)
{ {
version = str.substr(20).data(); version = str.substr(20).data();
break; break;
} }
} }
} catch(java::classfile_exception &) {} } catch(java::classfile_exception &) {}
// clean up // clean up
delete[] classfile; delete[] classfile;
Minecraft.close(); Minecraft.close();
zip.close(); zip.close();
jar.close(); jar.close();
return version; return version;
} }
} }

View File

@ -21,8 +21,8 @@
namespace javautils namespace javautils
{ {
/** /**
* @brief Get the version from a minecraft.jar by parsing its class files. Expensive! * @brief Get the version from a minecraft.jar by parsing its class files. Expensive!
*/ */
QString GetMinecraftJarVersion(QString jar); QString GetMinecraftJarVersion(QString jar);
} }

View File

@ -85,7 +85,7 @@ protected:
QStringList m_arguments; QStringList m_arguments;
void genArgs(); void genArgs();
void log(QString text); void log(QString text, ConsoleWindow::WriteMode mode = ConsoleWindow::MULTIMC);
protected slots: protected slots:
void finish(int, QProcess::ExitStatus status); void finish(int, QProcess::ExitStatus status);

View File

@ -197,6 +197,8 @@ void MinecraftProcess::launch()
start(m_instance->settings().get("JavaPath").toString(), m_arguments); start(m_instance->settings().get("JavaPath").toString(), m_arguments);
if (!waitForStarted()) if (!waitForStarted())
{ {
log("Could not launch minecraft!", ConsoleWindow::ERROR);
return;
//TODO: error handling //TODO: error handling
} }

View File

@ -6,7 +6,7 @@
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
@ -33,53 +33,53 @@
*/ */
class LIBMMCSETTINGS_EXPORT Keyring : public QObject class LIBMMCSETTINGS_EXPORT Keyring : public QObject
{ {
Q_OBJECT Q_OBJECT
public: public:
/** /**
* @brief the System Keyring instance * @brief the System Keyring instance
* @return the Keyring instance * @return the Keyring instance
*/ */
static Keyring *instance(); static Keyring *instance();
/** /**
* @brief store a password in the Keyring * @brief store a password in the Keyring
* @param service the service name * @param service the service name
* @param username the account name * @param username the account name
* @param password the password to store * @param password the password to store
* @return success * @return success
*/ */
virtual bool storePassword(QString service, QString username, QString password) = 0; virtual bool storePassword(QString service, QString username, QString password) = 0;
/** /**
* @brief get a password from the Keyring * @brief get a password from the Keyring
* @param service the service name * @param service the service name
* @param username the account name * @param username the account name
* @return the password (success=!isNull()) * @return the password (success=!isNull())
*/ */
virtual QString getPassword(QString service, QString username) = 0; virtual QString getPassword(QString service, QString username) = 0;
/** /**
* @brief lookup a password * @brief lookup a password
* @param service the service name * @param service the service name
* @param username the account name * @param username the account name
* @return wether the password is available * @return wether the password is available
*/ */
virtual bool hasPassword(QString service, QString username) = 0; virtual bool hasPassword(QString service, QString username) = 0;
/** /**
* @brief get a list of all stored accounts. * @brief get a list of all stored accounts.
* @param service the service name * @param service the service name
* @return * @return
*/ */
virtual QStringList getStoredAccounts(QString service) = 0; virtual QStringList getStoredAccounts(QString service) = 0;
protected: protected:
/// fall back to StubKeyring if false /// fall back to StubKeyring if false
virtual bool isValid() { return false; } virtual bool isValid() { return false; }
private: private:
static Keyring *m_instance; static Keyring *m_instance;
static void destroy(); static void destroy();
}; };
#endif // KEYRING_H #endif // KEYRING_H

View File

@ -6,7 +6,7 @@
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
@ -37,27 +37,27 @@ class Win32Keystore;
Keyring *Keyring::instance() Keyring *Keyring::instance()
{ {
if (m_instance == nullptr) if (m_instance == nullptr)
{ {
#ifdef KEYRING #ifdef KEYRING
m_instance = new KEYRING(); m_instance = new KEYRING();
if (!m_instance->isValid()) if (!m_instance->isValid())
{ {
qWarning("Could not create SystemKeyring! falling back to StubKeyring."); qWarning("Could not create SystemKeyring! falling back to StubKeyring.");
m_instance = new StubKeyring(); m_instance = new StubKeyring();
} }
#else #else
qWarning("Keyrings are not supported on your OS. Fallback StubKeyring is insecure!"); qWarning("Keyrings are not supported on your OS. Fallback StubKeyring is insecure!");
m_instance = new StubKeyring(); m_instance = new StubKeyring();
#endif #endif
atexit(Keyring::destroy); atexit(Keyring::destroy);
} }
return m_instance; return m_instance;
} }
void Keyring::destroy() void Keyring::destroy()
{ {
delete m_instance; delete m_instance;
} }
Keyring *Keyring::m_instance; Keyring *Keyring::m_instance;

View File

@ -6,7 +6,7 @@
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
@ -25,72 +25,72 @@ int scrambler = 0x9586309;
QString scramble(QString in_) QString scramble(QString in_)
{ {
QByteArray in = in_.toUtf8(); QByteArray in = in_.toUtf8();
QByteArray out; QByteArray out;
for (int i = 0; i<in.length(); i++) for (int i = 0; i<in.length(); i++)
out.append(in.at(i) ^ scrambler); out.append(in.at(i) ^ scrambler);
return QString::fromUtf8(out); return QString::fromUtf8(out);
} }
inline QString base64(QString in) inline QString base64(QString in)
{ {
return QString(in.toUtf8().toBase64()); return QString(in.toUtf8().toBase64());
} }
inline QString unbase64(QString in) inline QString unbase64(QString in)
{ {
return QString::fromUtf8(QByteArray::fromBase64(in.toLatin1())); return QString::fromUtf8(QByteArray::fromBase64(in.toLatin1()));
} }
inline QString scramble64(QString in) inline QString scramble64(QString in)
{ {
return base64(scramble(in)); return base64(scramble(in));
} }
inline QString unscramble64(QString in) inline QString unscramble64(QString in)
{ {
return scramble(unbase64(in)); return scramble(unbase64(in));
} }
// StubKeyring implementation // StubKeyring implementation
inline QString generateKey(QString service, QString username) inline QString generateKey(QString service, QString username)
{ {
return QString("%1/%2").arg(base64(service)).arg(scramble64(username)); return QString("%1/%2").arg(base64(service)).arg(scramble64(username));
} }
bool StubKeyring::storePassword(QString service, QString username, QString password) bool StubKeyring::storePassword(QString service, QString username, QString password)
{ {
m_settings.setValue(generateKey(service, username), scramble64(password)); m_settings.setValue(generateKey(service, username), scramble64(password));
return true; return true;
} }
QString StubKeyring::getPassword(QString service, QString username) QString StubKeyring::getPassword(QString service, QString username)
{ {
QString key = generateKey(service, username); QString key = generateKey(service, username);
if (!m_settings.contains(key)) if (!m_settings.contains(key))
return QString(); return QString();
return unscramble64(m_settings.value(key).toString()); return unscramble64(m_settings.value(key).toString());
} }
inline bool StubKeyring::hasPassword(QString service, QString username) bool StubKeyring::hasPassword(QString service, QString username)
{ {
return m_settings.contains(generateKey(service, username)); return m_settings.contains(generateKey(service, username));
} }
QStringList StubKeyring::getStoredAccounts(QString service) QStringList StubKeyring::getStoredAccounts(QString service)
{ {
service = base64(service).append('/'); service = base64(service).append('/');
QStringList out; QStringList out;
QStringList in(m_settings.allKeys()); QStringList in(m_settings.allKeys());
QStringListIterator it(in); QStringListIterator it(in);
while(it.hasNext()) while(it.hasNext())
{ {
QString c = it.next(); QString c = it.next();
if (c.startsWith(service)) if (c.startsWith(service))
out << unscramble64(c.mid(service.length())); out << unscramble64(c.mid(service.length()));
} }
return out; return out;
} }
StubKeyring::StubKeyring() : StubKeyring::StubKeyring() :
m_settings(QSettings::UserScope, "Orochimarufan", "Keyring") m_settings(QSettings::UserScope, "Orochimarufan", "Keyring")
{ {
} }

View File

@ -6,7 +6,7 @@
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
* You may obtain a copy of the License at * You may obtain a copy of the License at
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
@ -24,19 +24,19 @@
class StubKeyring : public Keyring class StubKeyring : public Keyring
{ {
Q_OBJECT Q_OBJECT
public: public:
virtual bool storePassword(QString service, QString username, QString password); virtual bool storePassword(QString service, QString username, QString password);
virtual QString getPassword(QString service, QString username); virtual QString getPassword(QString service, QString username);
virtual bool hasPassword(QString service, QString username); virtual bool hasPassword(QString service, QString username);
virtual QStringList getStoredAccounts(QString service); virtual QStringList getStoredAccounts(QString service);
private: private:
friend class Keyring; friend class Keyring;
explicit StubKeyring(); explicit StubKeyring();
virtual bool isValid() { return true; } virtual bool isValid() { return true; }
QSettings m_settings; QSettings m_settings;
}; };
#endif // STUBKEYRING_H #endif // STUBKEYRING_H

View File

@ -73,15 +73,6 @@ enum LIBUTIL_EXPORT Enum
}; };
} }
namespace OptionType
{
enum LIBUTIL_EXPORT Enum
{
Switch,
Option
};
}
/** /**
* @brief The ParsingError class * @brief The ParsingError class
*/ */
@ -211,6 +202,12 @@ private:
FlagStyle::Enum m_flagStyle; FlagStyle::Enum m_flagStyle;
ArgumentStyle::Enum m_argStyle; ArgumentStyle::Enum m_argStyle;
enum OptionType
{
otSwitch,
otOption
};
// Important: the common part MUST BE COMMON ON ALL THREE structs // Important: the common part MUST BE COMMON ON ALL THREE structs
struct CommonDef { struct CommonDef {
QString name; QString name;
@ -226,7 +223,7 @@ private:
QString metavar; QString metavar;
QVariant def; QVariant def;
// option // option
OptionType::Enum type; OptionType type;
QChar flag; QChar flag;
}; };

View File

@ -56,7 +56,7 @@ void Parser::addSwitch(QString name, bool def)
throw "Name not unique"; throw "Name not unique";
OptionDef *param = new OptionDef; OptionDef *param = new OptionDef;
param->type = OptionType::Switch; param->type = otSwitch;
param->name = name; param->name = name;
param->metavar = QString("<%1>").arg(name); param->metavar = QString("<%1>").arg(name);
param->def = def; param->def = def;
@ -72,7 +72,7 @@ void Parser::addOption(QString name, QVariant def)
throw "Name not unique"; throw "Name not unique";
OptionDef *param = new OptionDef; OptionDef *param = new OptionDef;
param->type = OptionType::Option; param->type = otOption;
param->name = name; param->name = name;
param->metavar = QString("<%1>").arg(name); param->metavar = QString("<%1>").arg(name);
param->def = def; param->def = def;
@ -161,7 +161,7 @@ QString Parser::compileHelp(QString progName, int helpIndent, bool useFlags)
help << flagPrefix << option->flag << ", "; help << flagPrefix << option->flag << ", ";
} }
help << optPrefix << option->name; help << optPrefix << option->name;
if (option->type == OptionType::Option) if (option->type == otOption)
{ {
QString arg = QString("%1%2").arg(((m_argStyle == ArgumentStyle::Equals) ? "=" : " "), option->metavar); QString arg = QString("%1%2").arg(((m_argStyle == ArgumentStyle::Equals) ? "=" : " "), option->metavar);
nameLength += arg.length(); nameLength += arg.length();
@ -193,7 +193,7 @@ QString Parser::compileUsage(QString progName, bool useFlags)
usage << flagPrefix << option->flag; usage << flagPrefix << option->flag;
else else
usage << optPrefix << option->name; usage << optPrefix << option->name;
if (option->type == OptionType::Option) if (option->type == otOption)
usage << ((m_argStyle == ArgumentStyle::Equals) ? "=" : " ") << option->metavar; usage << ((m_argStyle == ArgumentStyle::Equals) ? "=" : " ") << option->metavar;
usage << "]"; usage << "]";
} }
@ -265,9 +265,9 @@ QHash<QString, QVariant> Parser::parse(QStringList argv)
throw ParsingError(QString("Option %2%1 was given multiple times").arg(name, optionPrefix)); throw ParsingError(QString("Option %2%1 was given multiple times").arg(name, optionPrefix));
OptionDef *option = m_options[name]; OptionDef *option = m_options[name];
if (option->type == OptionType::Switch) if (option->type == otSwitch)
map[name] = true; map[name] = true;
else //if (option->type == OptionType::Option) else //if (option->type == otOption)
{ {
if (m_argStyle == ArgumentStyle::Space) if (m_argStyle == ArgumentStyle::Space)
expecting.append(name); expecting.append(name);
@ -312,9 +312,9 @@ QHash<QString, QVariant> Parser::parse(QStringList argv)
if (map.contains(option->name)) if (map.contains(option->name))
throw ParsingError(QString("Option %2%1 was given multiple times").arg(option->name, optionPrefix)); throw ParsingError(QString("Option %2%1 was given multiple times").arg(option->name, optionPrefix));
if (option->type == OptionType::Switch) if (option->type == otSwitch)
map[option->name] = true; map[option->name] = true;
else //if (option->type == OptionType::Option) else //if (option->type == otOption)
{ {
if (m_argStyle == ArgumentStyle::Space) if (m_argStyle == ArgumentStyle::Space)
expecting.append(option->name); expecting.append(option->name);

View File

@ -66,12 +66,9 @@ private:
{ {
inst = iter.next(); inst = iter.next();
if (inst->id() == instId) if (inst->id() == instId)
break; return inst;
} }
if (inst->id() != instId) return InstancePtr();
return InstancePtr();
else
return iter.peekPrevious();
} }
private slots: private slots:

View File

@ -10,51 +10,51 @@ using namespace Util::Commandline;
int main(int argc, char **argv) int main(int argc, char **argv)
{ {
QCoreApplication app(argc, argv); QCoreApplication app(argc, argv);
app.setApplicationName("MMC Keyring test"); app.setApplicationName("MMC Keyring test");
app.setOrganizationName("Orochimarufan"); app.setOrganizationName("Orochimarufan");
Parser p; Parser p;
p.addArgument("user", false); p.addArgument("user", false);
p.addArgument("password", false); p.addArgument("password", false);
p.addSwitch("set"); p.addSwitch("set");
p.addSwitch("get"); p.addSwitch("get");
p.addSwitch("list"); p.addSwitch("list");
p.addOption("service", "Test"); p.addOption("service", "Test");
p.addShortOpt("service", 's'); p.addShortOpt("service", 's');
QHash<QString, QVariant> args; QHash<QString, QVariant> args;
try { try {
args = p.parse(app.arguments()); args = p.parse(app.arguments());
} catch (ParsingError) { } catch (ParsingError) {
std::cout << "Syntax error." << std::endl; std::cout << "Syntax error." << std::endl;
return 1; return 1;
} }
if (args["set"].toBool()) { if (args["set"].toBool()) {
if (args["user"].isNull() || args["password"].isNull()) { if (args["user"].isNull() || args["password"].isNull()) {
std::cout << "set operation needs bot user and password set" << std::endl; std::cout << "set operation needs bot user and password set" << std::endl;
return 1; return 1;
} }
return Keyring::instance()->storePassword(args["service"].toString(), return Keyring::instance()->storePassword(args["service"].toString(),
args["user"].toString(), args["password"].toString()); args["user"].toString(), args["password"].toString());
} else if (args["get"].toBool()) { } else if (args["get"].toBool()) {
if (args["user"].isNull()) { if (args["user"].isNull()) {
std::cout << "get operation needs user set" << std::endl; std::cout << "get operation needs user set" << std::endl;
return 1; return 1;
} }
std::cout << "Password: " << qPrintable(Keyring::instance()->getPassword(args["service"].toString(), std::cout << "Password: " << qPrintable(Keyring::instance()->getPassword(args["service"].toString(),
args["user"].toString())) << std::endl; args["user"].toString())) << std::endl;
return 0; return 0;
} else if (args["list"].toBool()) { } else if (args["list"].toBool()) {
QStringList accounts = Keyring::instance()->getStoredAccounts(args["service"].toString()); QStringList accounts = Keyring::instance()->getStoredAccounts(args["service"].toString());
std::cout << "stored accounts:" << std::endl << '\t' << qPrintable(accounts.join("\n\t")) << std::endl; std::cout << "stored accounts:" << std::endl << '\t' << qPrintable(accounts.join("\n\t")) << std::endl;
return 0; return 0;
} else { } else {
std::cout << "No operation given!" << std::endl; std::cout << "No operation given!" << std::endl;
std::cout << qPrintable(p.compileHelp(argv[0])) << std::endl; std::cout << qPrintable(p.compileHelp(argv[0])) << std::endl;
return 1; return 1;
} }
} }