1
0
mirror of https://github.com/vcmi/vcmi.git synced 2024-12-24 22:14:36 +02:00

Merge pull request #1156 from vcmi/features/online

Online mode
This commit is contained in:
Nordsoft91 2022-11-29 20:43:39 +04:00 committed by GitHub
commit 89b8b87a6b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
27 changed files with 1618 additions and 123 deletions

View File

@ -201,7 +201,14 @@ int main(int argc, char * argv[])
("donotstartserver,d","do not attempt to start server and just connect to it instead server")
("serverport", po::value<si64>(), "override port specified in config file")
("saveprefix", po::value<std::string>(), "prefix for auto save files")
("savefrequency", po::value<si64>(), "limit auto save creation to each N days");
("savefrequency", po::value<si64>(), "limit auto save creation to each N days")
("lobby", "parameters address, port, uuid to connect ro remote lobby session")
("lobby-address", po::value<std::string>(), "address to remote lobby")
("lobby-port", po::value<ui16>(), "port to remote lobby")
("lobby-host", "if this client hosts session")
("lobby-uuid", po::value<std::string>(), "uuid to the server")
("lobby-connections", po::value<ui16>(), "connections of server")
("uuid", po::value<std::string>(), "uuid for the client");
if(argc > 1)
{
@ -483,6 +490,28 @@ int main(int argc, char * argv[])
session["autoSkip"].Bool() = vm.count("autoSkip");
session["oneGoodAI"].Bool() = vm.count("oneGoodAI");
session["aiSolo"].Bool() = false;
session["lobby"].Bool() = false;
if(vm.count("lobby"))
{
session["lobby"].Bool() = true;
session["host"].Bool() = false;
session["address"].String() = vm["lobby-address"].as<std::string>();
CSH->uuid = vm["uuid"].as<std::string>();
session["port"].Integer() = vm["lobby-port"].as<ui16>();
logGlobal->info("Remote lobby mode at %s:%d, uuid is %s", session["address"].String(), session["port"].Integer(), CSH->uuid);
if(vm.count("lobby-host"))
{
session["host"].Bool() = true;
session["hostConnections"].String() = std::to_string(vm["lobby-connections"].as<ui16>());
session["hostUuid"].String() = vm["lobby-uuid"].as<std::string>();
logGlobal->info("This client will host session, server uuid is %s", session["hostUuid"].String());
}
//we should not reconnect to previous game in online mode
Settings saveSession = settings.write["server"]["reconnect"];
saveSession->Bool() = false;
}
if(vm.count("testmap"))
{

View File

@ -118,6 +118,9 @@ CServerHandler::CServerHandler()
: state(EClientState::NONE), mx(std::make_shared<boost::recursive_mutex>()), client(nullptr), loadMode(0), campaignStateToSend(nullptr), campaignServerRestartLock(false)
{
uuid = boost::uuids::to_string(boost::uuids::random_generator()());
//read from file to restore last session
if(!settings["server"]["uuid"].isNull() && !settings["server"]["uuid"].String().empty())
uuid = settings["server"]["uuid"].String();
applier = std::make_shared<CApplier<CBaseForLobbyApply>>();
registerTypesLobbyPacks(*applier);
}
@ -190,9 +193,17 @@ void CServerHandler::startLocalServerAndConnect()
}
#elif defined(SINGLE_PROCESS_APP)
boost::condition_variable cond;
threadRunLocalServer = std::make_shared<boost::thread>([&cond, this] {
std::vector<std::string> args{"--uuid=" + uuid, "--port=" + boost::lexical_cast<std::string>(getHostPort())};
if(settings["session"]["lobby"].Bool() && settings["session"]["host"].Bool())
{
args.push_back("--lobby=" + settings["session"]["address"].String());
args.push_back("--connections=" + settings["session"]["hostConnections"].String());
args.push_back("--lobby-port=" + boost::lexical_cast<std::string>(settings["session"]["port"].Integer()));
args.push_back("--lobby-uuid=" + settings["session"]["hostUuid"].String());
}
threadRunLocalServer = std::make_shared<boost::thread>([&cond, args, this] {
setThreadName("CVCMIServer");
CVCMIServer::create(&cond, uuid);
CVCMIServer::create(&cond, args);
onServerFinished();
});
threadRunLocalServer->detach();
@ -259,8 +270,8 @@ void CServerHandler::justConnectToServer(const std::string & addr, const ui16 po
{
logNetwork->info("Establishing connection...");
c = std::make_shared<CConnection>(
addr.size() ? addr : settings["server"]["server"].String(),
port ? port : getDefaultPort(),
addr.size() ? addr : getHostAddress(),
port ? port : getHostPort(),
NAME, uuid);
}
catch(...)
@ -278,12 +289,12 @@ void CServerHandler::justConnectToServer(const std::string & addr, const ui16 po
c->handler = std::make_shared<boost::thread>(&CServerHandler::threadHandleConnection, this);
if(!addr.empty() && addr != localhostAddress)
if(!addr.empty() && addr != getHostAddress())
{
Settings serverAddress = settings.write["server"]["server"];
serverAddress->String() = addr;
}
if(port && port != getDefaultPort())
if(port && port != getHostPort())
{
Settings serverPort = settings.write["server"]["port"];
serverPort->Integer() = port;
@ -358,10 +369,7 @@ bool CServerHandler::isGuest() const
ui16 CServerHandler::getDefaultPort()
{
if(settings["session"]["serverport"].Integer())
return static_cast<ui16>(settings["session"]["serverport"].Integer());
else
return static_cast<ui16>(settings["server"]["port"].Integer());
return static_cast<ui16>(settings["server"]["port"].Integer());
}
std::string CServerHandler::getDefaultPortStr()
@ -369,6 +377,28 @@ std::string CServerHandler::getDefaultPortStr()
return boost::lexical_cast<std::string>(getDefaultPort());
}
std::string CServerHandler::getHostAddress() const
{
if(settings["session"]["lobby"].isNull() || !settings["session"]["lobby"].Bool())
return settings["server"]["server"].String();
if(settings["session"]["host"].Bool())
return localhostAddress;
return settings["session"]["address"].String();
}
ui16 CServerHandler::getHostPort() const
{
if(settings["session"]["lobby"].isNull() || !settings["session"]["lobby"].Bool())
return getDefaultPort();
if(settings["session"]["host"].Bool())
return getDefaultPort();
return settings["session"]["port"].Integer();
}
void CServerHandler::sendClientConnecting() const
{
LobbyClientConnected lcc;
@ -813,9 +843,17 @@ void CServerHandler::threadRunServer()
setThreadName("CServerHandler::threadRunServer");
const std::string logName = (VCMIDirs::get().userLogsPath() / "server_log.txt").string();
std::string comm = VCMIDirs::get().serverPath().string()
+ " --port=" + getDefaultPortStr()
+ " --port=" + boost::lexical_cast<std::string>(getHostPort())
+ " --run-by-client"
+ " --uuid=" + uuid;
if(settings["session"]["lobby"].Bool() && settings["session"]["host"].Bool())
{
comm += " --lobby=" + settings["session"]["address"].String();
comm += " --connections=" + settings["session"]["hostConnections"].String();
comm += " --lobby-port=" + boost::lexical_cast<std::string>(settings["session"]["port"].Integer());
comm += " --lobby-uuid=" + settings["session"]["hostUuid"].String();
}
if(shm)
{
comm += " --enable-shm";
@ -823,6 +861,7 @@ void CServerHandler::threadRunServer()
comm += " --enable-shm-uuid";
}
comm += " > \"" + logName + '\"';
logGlobal->info("Server command line: %s", comm);
#ifdef VCMI_WINDOWS
int result = -1;

View File

@ -111,6 +111,9 @@ public:
static const std::string localhostAddress;
CServerHandler();
std::string getHostAddress() const;
ui16 getHostPort() const;
void resetStateForLobby(const StartInfo::EMode mode, const std::vector<std::string> * names = nullptr);
void startLocalServerAndConnect();

View File

@ -50,7 +50,13 @@ int client_main(int argc, char * argv[])
id __block startGameObserver = [NSNotificationCenter.defaultCenter addObserverForName:@"StartGame" object:nil queue:nil usingBlock:^(NSNotification * _Nonnull note) {
[NSNotificationCenter.defaultCenter removeObserver:startGameObserver];
startGameObserver = nil;
startSDLManually(argc, argv);
NSArray<NSString *> * args = note.userInfo[@"args"];
const char * newArgv[args.count];
NSUInteger i = 0;
for (NSString * obj in args)
newArgv[i++] = obj.UTF8String;
startSDLManually(args.count, (char **)(newArgv));
}];
return qt_main_wrapper(argc, argv);
}

View File

@ -481,8 +481,8 @@ CSimpleJoinScreen::CSimpleJoinScreen(bool host)
inputAddress->giveFocus();
}
inputAddress->setText(host ? CServerHandler::localhostAddress : settings["server"]["server"].String(), true);
inputPort->setText(CServerHandler::getDefaultPortStr(), true);
inputAddress->setText(host ? CServerHandler::localhostAddress : CSH->getHostAddress(), true);
inputPort->setText(boost::lexical_cast<std::string>(CSH->getHostPort()), true);
buttonCancel = std::make_shared<CButton>(Point(142, 142), "MUBCANC.DEF", CGI->generaltexth->zelp[561], std::bind(&CSimpleJoinScreen::leaveScreen, this), SDLK_ESCAPE);
statusBar = CGStatusBar::create(std::make_shared<CPicture>(Rect(7, 186, 218, 18), 0));

View File

@ -293,7 +293,7 @@
},
"names" : {
"type" : "array",
"default" : {},
"default" : [],
"items":
{
"type" : "string",
@ -380,7 +380,7 @@
"type" : "object",
"default": {},
"additionalProperties" : false,
"required" : [ "repositoryURL", "enableInstalledMods", "extraResolutionsModPath", "autoCheckRepositories", "updateOnStartup", "updateConfigUrl" ],
"required" : [ "repositoryURL", "enableInstalledMods", "extraResolutionsModPath", "autoCheckRepositories", "updateOnStartup", "updateConfigUrl", "lobbyUrl", "lobbyPort", "lobbyUsername", "connectionTimeout" ],
"properties" : {
"repositoryURL" : {
"type" : "array",
@ -410,6 +410,26 @@
"updateConfigUrl" : {
"type" : "string",
"default" : "https://raw.githubusercontent.com/vcmi/vcmi-updates/master/vcmi-updates.json"
},
"lobbyUrl" : {
"type" : "string",
"description" : "ip address or web link to remote proxy server",
"default" : "beholder.vcmi.eu"
},
"lobbyPort" : {
"type" : "number",
"description" : "connection port for remote proxy server",
"default" : 5002
},
"lobbyUsername" : {
"type" : "string",
"description" : "username for the client on the remote proxy server",
"default" : ""
},
"connectionTimeout" : {
"type" : "number",
"description" : "maximum time in ms, should be enough to establish socket connection to remote proxy server.",
"default" : 2000
}
}
}

View File

@ -33,6 +33,9 @@ set(launcher_SRCS
launcherdirs.cpp
jsonutils.cpp
updatedialog_moc.cpp
lobby/lobby.cpp
lobby/lobby_moc.cpp
lobby/lobbyroomrequest_moc.cpp
)
set(launcher_HEADERS
@ -43,6 +46,9 @@ set(launcher_HEADERS
launcherdirs.h
jsonutils.h
updatedialog_moc.h
lobby/lobby.h
lobby/lobby_moc.h
lobby/lobbyroomrequest_moc.h
main.h
)
@ -52,6 +58,8 @@ set(launcher_FORMS
settingsView/csettingsview_moc.ui
mainwindow_moc.ui
updatedialog_moc.ui
lobby/lobby_moc.ui
lobby/lobbyroomrequest_moc.ui
)
if(APPLE_IOS)

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 683 B

View File

@ -26,5 +26,9 @@ void launchGame(int argc, char * argv[]) {
qtNativeWindow.windowScene = nil;
#endif
}
[NSNotificationCenter.defaultCenter postNotificationName:@"StartGame" object:nil];
}
__auto_type args = [NSMutableArray arrayWithCapacity:argc];
for (int i = 0; i < argc; ++i)
[args addObject:@(argv[i])];
[NSNotificationCenter.defaultCenter postNotificationName:@"StartGame" object:nil userInfo:@{@"args": args}];
}

123
launcher/lobby/lobby.cpp Normal file
View File

@ -0,0 +1,123 @@
/*
* lobby.cpp, part of VCMI engine
*
* Authors: listed in file AUTHORS in main folder
*
* License: GNU General Public License v2.0 or later
* Full text of license available in license.txt file, in main folder
*
*/
#include "StdInc.h"
#include "lobby.h"
#include "../lib/GameConstants.h"
SocketLobby::SocketLobby(QObject *parent) :
QObject(parent)
{
socket = new QTcpSocket(this);
connect(socket, SIGNAL(connected()), this, SLOT(connected()));
connect(socket, SIGNAL(disconnected()), this, SLOT(disconnected()));
connect(socket, SIGNAL(readyRead()), this, SLOT(readyRead()));
connect(socket, SIGNAL(bytesWritten(qint64)), this, SLOT(bytesWritten(qint64)));
}
void SocketLobby::connectServer(const QString & host, int port, const QString & usr, int timeout)
{
username = usr;
socket->connectToHost(host, port);
if(!socket->waitForDisconnected(timeout) && !isConnected)
{
emit text("Error: " + socket->errorString());
emit disconnect();
}
}
void SocketLobby::disconnectServer()
{
socket->disconnectFromHost();
}
void SocketLobby::requestNewSession(const QString & session, int totalPlayers, const QString & pswd, const QMap<QString, QString> & mods)
{
const QString sessionMessage = ProtocolStrings[CREATE].arg(session, pswd, QString::number(totalPlayers), prepareModsClientString(mods));
send(sessionMessage);
}
void SocketLobby::requestJoinSession(const QString & session, const QString & pswd, const QMap<QString, QString> & mods)
{
const QString sessionMessage = ProtocolStrings[JOIN].arg(session, pswd, prepareModsClientString(mods));
send(sessionMessage);
}
void SocketLobby::requestLeaveSession(const QString & session)
{
const QString sessionMessage = ProtocolStrings[LEAVE].arg(session);
send(sessionMessage);
}
void SocketLobby::requestReadySession(const QString & session)
{
const QString sessionMessage = ProtocolStrings[READY].arg(session);
send(sessionMessage);
}
void SocketLobby::send(const QString & msg)
{
QByteArray str = msg.toUtf8();
int sz = str.size();
QByteArray pack((const char *)&sz, sizeof(sz));
pack.append(str);
socket->write(pack);
}
void SocketLobby::connected()
{
isConnected = true;
emit text("Connected!");
QByteArray greetingBytes;
greetingBytes.append(ProtocolVersion);
greetingBytes.append(ProtocolEncoding.size());
const QString greetingConst = QString(greetingBytes)
+ ProtocolStrings[GREETING].arg(QString::fromStdString(ProtocolEncoding),
username,
QString::fromStdString(GameConstants::VCMI_VERSION));
send(greetingConst);
}
void SocketLobby::disconnected()
{
isConnected = false;
emit disconnect();
emit text("Disconnected!");
}
void SocketLobby::bytesWritten(qint64 bytes)
{
qDebug() << "We wrote: " << bytes;
}
void SocketLobby::readyRead()
{
qDebug() << "Reading...";
emit receive(socket->readAll());
}
ServerCommand::ServerCommand(ProtocolConsts cmd, const QStringList & args):
command(cmd),
arguments(args)
{
}
QString prepareModsClientString(const QMap<QString, QString> & mods)
{
QStringList result;
for(auto & mod : mods.keys())
{
result << mod + "&" + mods[mod];
}
return result.join(";");
}

188
launcher/lobby/lobby.h Normal file
View File

@ -0,0 +1,188 @@
/*
* lobby.h, part of VCMI engine
*
* Authors: listed in file AUTHORS in main folder
*
* License: GNU General Public License v2.0 or later
* Full text of license available in license.txt file, in main folder
*
*/
#pragma once
#include <QTcpSocket>
#include <QAbstractSocket>
const unsigned int ProtocolVersion = 3;
const std::string ProtocolEncoding = "utf8";
class ProtocolError: public std::runtime_error
{
public:
ProtocolError(const char * w): std::runtime_error(w) {}
};
enum ProtocolConsts
{
//client consts
GREETING, USERNAME, MESSAGE, VERSION, CREATE, JOIN, LEAVE, KICK, READY, FORCESTART,
//server consts
SESSIONS, CREATED, JOINED, KICKED, SRVERROR, CHAT, START, STATUS, HOST, MODS, CLIENTMODS
};
const QMap<ProtocolConsts, QString> ProtocolStrings
{
//=== client commands ===
//handshaking with server
//%1: first byte is protocol_version, then size of encoding string in bytes, then encoding string
//%2: client name
//%3: VCMI version
{GREETING, "%1<GREETINGS>%2<VER>%3"},
//[unsupported] autorization with username
//%1: username
{USERNAME, "<USER>%1"},
//sending message to the chat
//%1: message text
{MESSAGE, "<MSG>%1"},
//create new room
//%1: room name
//%2: password for the room
//%3: max number of players
//%4: mods used by host
// each mod has a format modname&modversion, mods should be separated by ; symbol
{CREATE, "<NEW>%1<PSWD>%2<COUNT>%3<MODS>%4"},
//join to the room
//%1: room name
//%2: password for the room
//%3: list of mods used by player
// each mod has a format modname&modversion, mods should be separated by ; symbol
{JOIN, "<JOIN>%1<PSWD>%2<MODS>%3"},
//leave the room
//%1: room name
{LEAVE, "<LEAVE>%1"},
//kick user from the current room
//%1: player username
{KICK, "<KICK>%1"},
//signal that player is ready for game
//%1: room name
{READY, "<READY>%1"},
//[unsupported] start session immediately
//%1: room name
{FORCESTART, "<FORCESTART>%1"},
//=== server commands ===
//server commands are started from :>>, arguments are enumerated by : symbol
//new session was created
//arg[0]: room name
{CREATED, "CREATED"},
//list of existing sessions
//arg[0]: amount of sessions, following arguments depending on it
//arg[x]: session name
//arg[x+1]: amount of players in the session
//arg[x+2]: total amount of players allowed
//arg[x+3]: True if session is protected by password
{SESSIONS, "SESSIONS"},
//user has joined to the session
//arg[0]: session name
//arg[1]: username (who was joined)
{JOINED, "JOIN"},
//user has left the session
//arg[0]: session name
//arg[1]: username (who has left)
{KICKED, "KICK"},
//session has been started
//arg[0]: session name
//arg[1]: uuid to be used for connection
{START, "START"},
//host ownership for the game session
//arg[0]: uuid to be used by vcmiserver
//arg[1]: amount of players (clients) to be connected
{HOST, "HOST"},
//room status
//arg[0]: amount of players, following arguments depending on it
//arg[x]: player username
//arg[x+1]: True if player is ready
{STATUS, "STATUS"}, //joined_players:player_name:is_ready
//server error
//arg[0]: error message
{SRVERROR, "ERROR"},
//mods used in the session by host player
//arg[0]: amount of mods, following arguments depending on it
//arg[x]: mod name
//arg[x+1]: mod version
{MODS, "MODS"},
//mods used by user
//arg[0]: username
//arg[1]: amount of mods, following arguments depending on it
//arg[x]: mod name
//arg[x+1]: mod version
{CLIENTMODS, "MODSOTHER"},
//received chat message
//arg[0]: sender username
//arg[1]: message text
{CHAT, "MSG"}
};
class ServerCommand
{
public:
ServerCommand(ProtocolConsts, const QStringList & arguments);
const ProtocolConsts command;
const QStringList arguments;
};
class SocketLobby : public QObject
{
Q_OBJECT
public:
explicit SocketLobby(QObject *parent = 0);
void connectServer(const QString & host, int port, const QString & username, int timeout);
void disconnectServer();
void requestNewSession(const QString & session, int totalPlayers, const QString & pswd, const QMap<QString, QString> & mods);
void requestJoinSession(const QString & session, const QString & pswd, const QMap<QString, QString> & mods);
void requestLeaveSession(const QString & session);
void requestReadySession(const QString & session);
void send(const QString &);
signals:
void text(QString);
void receive(QString);
void disconnect();
public slots:
void connected();
void disconnected();
void bytesWritten(qint64 bytes);
void readyRead();
private:
QTcpSocket *socket;
bool isConnected = false;
QString username;
};
QString prepareModsClientString(const QMap<QString, QString> & mods);

View File

@ -0,0 +1,417 @@
/*
* lobby_moc.cpp, part of VCMI engine
*
* Authors: listed in file AUTHORS in main folder
*
* License: GNU General Public License v2.0 or later
* Full text of license available in license.txt file, in main folder
*
*/
#include "StdInc.h"
#include "main.h"
#include "lobby_moc.h"
#include "ui_lobby_moc.h"
#include "lobbyroomrequest_moc.h"
#include "../mainwindow_moc.h"
#include "../modManager/cmodlist.h"
#include "../../lib/CConfigHandler.h"
Lobby::Lobby(QWidget *parent) :
QWidget(parent),
ui(new Ui::Lobby)
{
ui->setupUi(this);
connect(&socketLobby, SIGNAL(text(QString)), this, SLOT(sysMessage(QString)));
connect(&socketLobby, SIGNAL(receive(QString)), this, SLOT(dispatchMessage(QString)));
connect(&socketLobby, SIGNAL(disconnect()), this, SLOT(onDisconnected()));
QString hostString("%1:%2");
hostString = hostString.arg(QString::fromStdString(settings["launcher"]["lobbyUrl"].String()));
hostString = hostString.arg(settings["launcher"]["lobbyPort"].Integer());
ui->serverEdit->setText(hostString);
ui->userEdit->setText(QString::fromStdString(settings["launcher"]["lobbyUsername"].String()));
ui->kickButton->setVisible(false);
}
Lobby::~Lobby()
{
delete ui;
}
QMap<QString, QString> Lobby::buildModsMap() const
{
QMap<QString, QString> result;
QObject * mainWindow = qApp->activeWindow();
if(!mainWindow)
mainWindow = parent();
if(!mainWindow)
return result; //probably something is really wrong here
while(mainWindow->parent())
mainWindow = mainWindow->parent();
const auto & modlist = qobject_cast<MainWindow*>(mainWindow)->getModList();
for(auto & modname : modlist.getModList())
{
auto mod = modlist.getMod(modname);
if(mod.isEnabled())
{
result[modname] = mod.getValue("version").toString();
}
}
return result;
}
bool Lobby::isModAvailable(const QString & modName, const QString & modVersion) const
{
QObject * mainWindow = qApp->activeWindow();
while(mainWindow->parent())
mainWindow = mainWindow->parent();
const auto & modlist = qobject_cast<MainWindow*>(mainWindow)->getModList();
if(!modlist.hasMod(modName))
return false;
auto mod = modlist.getMod(modName);
return (mod.isInstalled () || mod.isAvailable()) && (mod.getValue("version") == modVersion);
}
void Lobby::serverCommand(const ServerCommand & command) try
{
//initialize variables outside of switch block
const QString statusPlaceholder("%1 %2\n");
const auto & args = command.arguments;
int amount, tagPoint;
QString joinStr;
switch(command.command)
{
case SRVERROR:
protocolAssert(args.size());
chatMessage("System error", args[0], true);
if(authentificationStatus == AuthStatus::AUTH_NONE)
authentificationStatus = AuthStatus::AUTH_ERROR;
break;
case CREATED:
protocolAssert(args.size());
hostSession = args[0];
session = args[0];
sysMessage("new session started");
break;
case SESSIONS:
protocolAssert(args.size());
amount = args[0].toInt();
protocolAssert(amount * 4 == (args.size() - 1));
ui->sessionsTable->setRowCount(amount);
tagPoint = 1;
for(int i = 0; i < amount; ++i)
{
QTableWidgetItem * sessionNameItem = new QTableWidgetItem(args[tagPoint++]);
ui->sessionsTable->setItem(i, 0, sessionNameItem);
int playersJoined = args[tagPoint++].toInt();
int playersTotal = args[tagPoint++].toInt();
QTableWidgetItem * sessionPlayerItem = new QTableWidgetItem(QString("%1/%2").arg(playersJoined).arg(playersTotal));
ui->sessionsTable->setItem(i, 1, sessionPlayerItem);
QTableWidgetItem * sessionProtectedItem = new QTableWidgetItem();
bool isPrivate = (args[tagPoint++] == "True");
sessionProtectedItem->setData(Qt::UserRole, isPrivate);
if(isPrivate)
sessionProtectedItem->setIcon(QIcon("icons:room-private.png"));
ui->sessionsTable->setItem(i, 2, sessionProtectedItem);
}
break;
case JOINED:
case KICKED:
protocolAssert(args.size() == 2);
joinStr = (command.command == JOINED ? "%1 joined to the session %2" : "%1 left session %2");
if(args[1] == username)
{
ui->buttonReady->setText("Ready");
ui->chat->clear(); //cleanup the chat
sysMessage(joinStr.arg("you", args[0]));
session = args[0];
ui->stackedWidget->setCurrentWidget(command.command == JOINED ? ui->roomPage : ui->sessionsPage);
}
else
{
sysMessage(joinStr.arg(args[1], args[0]));
}
break;
case MODS: {
protocolAssert(args.size() > 0);
amount = args[0].toInt();
protocolAssert(amount * 2 == (args.size() - 1));
tagPoint = 1;
ui->modsList->clear();
auto enabledMods = buildModsMap();
for(int i = 0; i < amount; ++i, tagPoint += 2)
{
if(enabledMods.contains(args[tagPoint]))
{
if(enabledMods[args[tagPoint]] == args[tagPoint + 1])
enabledMods.remove(args[tagPoint]);
else
ui->modsList->addItem(new QListWidgetItem(QIcon("icons:mod-update.png"), QString("%1 (v%2)").arg(args[tagPoint], args[tagPoint + 1])));
}
else if(isModAvailable(args[tagPoint], args[tagPoint + 1]))
ui->modsList->addItem(new QListWidgetItem(QIcon("icons:mod-enabled.png"), QString("%1 (v%2)").arg(args[tagPoint], args[tagPoint + 1])));
else
ui->modsList->addItem(new QListWidgetItem(QIcon("icons:mod-delete.png"), QString("%1 (v%2)").arg(args[tagPoint], args[tagPoint + 1])));
}
for(auto & remainMod : enabledMods.keys())
{
ui->modsList->addItem(new QListWidgetItem(QIcon("icons:mod-disabled.png"), QString("%1 (v%2)").arg(remainMod, enabledMods[remainMod])));
}
if(!ui->modsList->count())
ui->modsList->addItem("No issues detected");
break;
}
case CLIENTMODS: {
protocolAssert(args.size() > 1);
amount = args[1].toInt();
protocolAssert(amount * 2 == (args.size() - 2));
tagPoint = 2;
break;
}
case STATUS:
protocolAssert(args.size() > 0);
amount = args[0].toInt();
protocolAssert(amount * 2 == (args.size() - 1));
tagPoint = 1;
ui->playersList->clear();
for(int i = 0; i < amount; ++i, tagPoint += 2)
{
if(args[tagPoint + 1] == "True")
ui->playersList->addItem(new QListWidgetItem(QIcon("icons:mod-enabled.png"), args[tagPoint]));
else
ui->playersList->addItem(new QListWidgetItem(QIcon("icons:mod-disabled.png"), args[tagPoint]));
if(args[tagPoint] == username)
if(args[tagPoint + 1] == "True")
ui->buttonReady->setText("Not ready");
else
ui->buttonReady->setText("Ready");
}
break;
case START: {
protocolAssert(args.size() == 1);
//actually start game
gameArgs << "--lobby";
gameArgs << "--lobby-address" << serverUrl;
gameArgs << "--lobby-port" << QString::number(serverPort);
gameArgs << "--uuid" << args[0];
startGame(gameArgs);
break;
}
case HOST: {
protocolAssert(args.size() == 2);
gameArgs << "--lobby-host";
gameArgs << "--lobby-uuid" << args[0];
gameArgs << "--lobby-connections" << args[1];
break;
}
case CHAT: {
protocolAssert(args.size() > 1);
QString msg;
for(int i = 1; i < args.size(); ++i)
msg += args[i];
chatMessage(args[0], msg);
break;
}
default:
sysMessage("Unknown server command");
}
if(authentificationStatus == AuthStatus::AUTH_ERROR)
{
socketLobby.disconnectServer();
}
else
{
authentificationStatus = AuthStatus::AUTH_OK;
ui->newButton->setEnabled(true);
}
}
catch(const ProtocolError & e)
{
chatMessage("System error", e.what(), true);
}
void Lobby::dispatchMessage(QString txt) try
{
if(txt.isEmpty())
return;
QStringList parseTags = txt.split(":>>");
protocolAssert(parseTags.size() > 1 && parseTags[0].isEmpty() && !parseTags[1].isEmpty());
for(int c = 1; c < parseTags.size(); ++c)
{
QStringList parseArgs = parseTags[c].split(":");
protocolAssert(parseArgs.size() > 1);
auto ctype = ProtocolStrings.key(parseArgs[0]);
parseArgs.pop_front();
ServerCommand cmd(ctype, parseArgs);
serverCommand(cmd);
}
}
catch(const ProtocolError & e)
{
chatMessage("System error", e.what(), true);
}
void Lobby::onDisconnected()
{
authentificationStatus = AuthStatus::AUTH_NONE;
ui->stackedWidget->setCurrentWidget(ui->sessionsPage);
ui->connectButton->setChecked(false);
ui->serverEdit->setEnabled(true);
ui->userEdit->setEnabled(true);
ui->newButton->setEnabled(false);
ui->joinButton->setEnabled(false);
ui->sessionsTable->clear();
}
void Lobby::chatMessage(QString title, QString body, bool isSystem)
{
QTextCharFormat fmtBody, fmtTitle;
fmtTitle.setFontWeight(QFont::Bold);
if(isSystem)
fmtBody.setFontWeight(QFont::DemiBold);
QTextCursor curs(ui->chat->document());
curs.movePosition(QTextCursor::End);
curs.insertText(title + ": ", fmtTitle);
curs.insertText(body + "\n", fmtBody);
ui->chat->ensureCursorVisible();
}
void Lobby::sysMessage(QString body)
{
chatMessage("System", body, true);
}
void Lobby::protocolAssert(bool expr)
{
if(!expr)
throw ProtocolError("Protocol error");
}
void Lobby::on_messageEdit_returnPressed()
{
socketLobby.send(ProtocolStrings[MESSAGE].arg(ui->messageEdit->text()));
ui->messageEdit->clear();
}
void Lobby::on_connectButton_toggled(bool checked)
{
if(checked)
{
authentificationStatus = AuthStatus::AUTH_NONE;
username = ui->userEdit->text();
const int connectionTimeout = settings["launcher"]["connectionTimeout"].Integer();
auto serverStrings = ui->serverEdit->text().split(":");
if(serverStrings.size() != 2)
{
QMessageBox::critical(this, "Connection error", "Server address must have the format URL:port");
return;
}
serverUrl = serverStrings[0];
serverPort = serverStrings[1].toInt();
Settings node = settings.write["launcher"];
node["lobbyUrl"].String() = serverUrl.toStdString();
node["lobbyPort"].Integer() = serverPort;
node["lobbyUsername"].String() = username.toStdString();
ui->serverEdit->setEnabled(false);
ui->userEdit->setEnabled(false);
sysMessage("Connecting to " + serverUrl + ":" + QString::number(serverPort));
//show text immediately
ui->chat->repaint();
qApp->processEvents();
socketLobby.connectServer(serverUrl, serverPort, username, connectionTimeout);
}
else
{
ui->serverEdit->setEnabled(true);
ui->userEdit->setEnabled(true);
socketLobby.disconnectServer();
}
}
void Lobby::on_newButton_clicked()
{
new LobbyRoomRequest(socketLobby, "", buildModsMap(), this);
}
void Lobby::on_joinButton_clicked()
{
auto * item = ui->sessionsTable->item(ui->sessionsTable->currentRow(), 0);
if(item)
{
auto isPrivate = ui->sessionsTable->item(ui->sessionsTable->currentRow(), 2)->data(Qt::UserRole).toBool();
if(isPrivate)
new LobbyRoomRequest(socketLobby, item->text(), buildModsMap(), this);
else
socketLobby.requestJoinSession(item->text(), "", buildModsMap());
}
}
void Lobby::on_buttonLeave_clicked()
{
socketLobby.requestLeaveSession(session);
}
void Lobby::on_buttonReady_clicked()
{
if(ui->buttonReady->text() == "Ready")
ui->buttonReady->setText("Not ready");
else
ui->buttonReady->setText("Ready");
socketLobby.requestReadySession(session);
}
void Lobby::on_sessionsTable_itemSelectionChanged()
{
auto selection = ui->sessionsTable->selectedItems();
ui->joinButton->setEnabled(!selection.empty());
}
void Lobby::on_playersList_currentRowChanged(int currentRow)
{
ui->kickButton->setVisible(ui->playersList->currentItem()
&& currentRow > 0
&& ui->playersList->currentItem()->text() != username);
}
void Lobby::on_kickButton_clicked()
{
if(ui->playersList->currentItem() && ui->playersList->currentItem()->text() != username)
socketLobby.send(ProtocolStrings[KICK].arg(ui->playersList->currentItem()->text()));
}

View File

@ -0,0 +1,76 @@
/*
* lobby_moc.h, part of VCMI engine
*
* Authors: listed in file AUTHORS in main folder
*
* License: GNU General Public License v2.0 or later
* Full text of license available in license.txt file, in main folder
*
*/
#pragma once
#include <QWidget>
#include "lobby.h"
namespace Ui {
class Lobby;
}
class Lobby : public QWidget
{
Q_OBJECT
public:
explicit Lobby(QWidget *parent = nullptr);
~Lobby();
private slots:
void on_messageEdit_returnPressed();
void chatMessage(QString title, QString body, bool isSystem = false);
void sysMessage(QString body);
void dispatchMessage(QString);
void serverCommand(const ServerCommand &);
void on_connectButton_toggled(bool checked);
void on_newButton_clicked();
void on_joinButton_clicked();
void on_buttonLeave_clicked();
void on_buttonReady_clicked();
void onDisconnected();
void on_sessionsTable_itemSelectionChanged();
void on_playersList_currentRowChanged(int currentRow);
void on_kickButton_clicked();
private:
QString serverUrl;
int serverPort;
Ui::Lobby *ui;
SocketLobby socketLobby;
QString hostSession;
QString session;
QString username;
QStringList gameArgs;
enum AuthStatus
{
AUTH_NONE, AUTH_OK, AUTH_ERROR
};
AuthStatus authentificationStatus = AUTH_NONE;
private:
QMap<QString, QString> buildModsMap() const;
bool isModAvailable(const QString & modName, const QString & modVersion) const;
void protocolAssert(bool);
};

216
launcher/lobby/lobby_moc.ui Normal file
View File

@ -0,0 +1,216 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>Lobby</class>
<widget class="QWidget" name="Lobby">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>652</width>
<height>329</height>
</rect>
</property>
<property name="windowTitle">
<string>Form</string>
</property>
<layout class="QGridLayout" name="gridLayout">
<item row="0" column="5">
<widget class="QPushButton" name="connectButton">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>Connect</string>
</property>
<property name="checkable">
<bool>true</bool>
</property>
</widget>
</item>
<item row="3" column="0" colspan="3">
<widget class="QLineEdit" name="messageEdit"/>
</item>
<item row="0" column="3">
<widget class="QLabel" name="label_4">
<property name="sizePolicy">
<sizepolicy hsizetype="Expanding" vsizetype="Preferred">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="text">
<string>Username</string>
</property>
</widget>
</item>
<item row="0" column="4">
<widget class="QLineEdit" name="userEdit"/>
</item>
<item row="0" column="1">
<widget class="QLineEdit" name="serverEdit">
<property name="text">
<string>127.0.0.1:5002</string>
</property>
</widget>
</item>
<item row="2" column="0" colspan="3">
<widget class="QPlainTextEdit" name="chat">
<property name="readOnly">
<bool>true</bool>
</property>
</widget>
</item>
<item row="0" column="0">
<widget class="QLabel" name="label">
<property name="text">
<string>Server</string>
</property>
</widget>
</item>
<item row="2" column="3" rowspan="2" colspan="3">
<widget class="QStackedWidget" name="stackedWidget">
<property name="currentIndex">
<number>0</number>
</property>
<widget class="QWidget" name="sessionsPage">
<layout class="QGridLayout" name="gridLayout_2">
<item row="0" column="0" colspan="2">
<widget class="QTableWidget" name="sessionsTable">
<property name="editTriggers">
<set>QAbstractItemView::NoEditTriggers</set>
</property>
<property name="selectionMode">
<enum>QAbstractItemView::SingleSelection</enum>
</property>
<property name="selectionBehavior">
<enum>QAbstractItemView::SelectRows</enum>
</property>
<attribute name="horizontalHeaderCascadingSectionResizes">
<bool>false</bool>
</attribute>
<attribute name="horizontalHeaderDefaultSectionSize">
<number>80</number>
</attribute>
<attribute name="horizontalHeaderShowSortIndicator" stdset="0">
<bool>false</bool>
</attribute>
<attribute name="horizontalHeaderStretchLastSection">
<bool>true</bool>
</attribute>
<attribute name="verticalHeaderMinimumSectionSize">
<number>20</number>
</attribute>
<attribute name="verticalHeaderDefaultSectionSize">
<number>20</number>
</attribute>
<column>
<property name="text">
<string>Session</string>
</property>
</column>
<column>
<property name="text">
<string>Players</string>
</property>
</column>
<column>
<property name="text">
<string/>
</property>
</column>
</widget>
</item>
<item row="1" column="0">
<widget class="QPushButton" name="newButton">
<property name="enabled">
<bool>false</bool>
</property>
<property name="text">
<string>New room</string>
</property>
</widget>
</item>
<item row="1" column="1">
<widget class="QPushButton" name="joinButton">
<property name="enabled">
<bool>false</bool>
</property>
<property name="text">
<string>Join room</string>
</property>
</widget>
</item>
</layout>
</widget>
<widget class="QWidget" name="roomPage">
<layout class="QGridLayout" name="gridLayout_3">
<item row="5" column="1">
<widget class="QPushButton" name="buttonReady">
<property name="text">
<string>Ready</string>
</property>
</widget>
</item>
<item row="3" column="0">
<widget class="QLabel" name="label_5">
<property name="text">
<string>Mods mismatch</string>
</property>
</widget>
</item>
<item row="5" column="0">
<widget class="QPushButton" name="buttonLeave">
<property name="text">
<string>Leave</string>
</property>
</widget>
</item>
<item row="4" column="0" colspan="2">
<widget class="QListWidget" name="modsList">
<property name="editTriggers">
<set>QAbstractItemView::NoEditTriggers</set>
</property>
<property name="selectionMode">
<enum>QAbstractItemView::NoSelection</enum>
</property>
</widget>
</item>
<item row="2" column="0" colspan="2">
<widget class="QListWidget" name="playersList">
<property name="editTriggers">
<set>QAbstractItemView::NoEditTriggers</set>
</property>
<property name="selectionMode">
<enum>QAbstractItemView::SingleSelection</enum>
</property>
<property name="selectionBehavior">
<enum>QAbstractItemView::SelectRows</enum>
</property>
</widget>
</item>
<item row="1" column="1">
<widget class="QPushButton" name="kickButton">
<property name="text">
<string>Kick player</string>
</property>
</widget>
</item>
<item row="1" column="0">
<widget class="QLabel" name="label_3">
<property name="text">
<string>Players in the room</string>
</property>
</widget>
</item>
</layout>
</widget>
</widget>
</item>
</layout>
</widget>
<resources/>
<connections/>
</ui>

View File

@ -0,0 +1,50 @@
/*
* lobbyroomrequest_moc.cpp, part of VCMI engine
*
* Authors: listed in file AUTHORS in main folder
*
* License: GNU General Public License v2.0 or later
* Full text of license available in license.txt file, in main folder
*
*/
#include "lobbyroomrequest_moc.h"
#include "ui_lobbyroomrequest_moc.h"
LobbyRoomRequest::LobbyRoomRequest(SocketLobby & socket, const QString & room, const QMap<QString, QString> & mods, QWidget *parent) :
QDialog(parent),
ui(new Ui::LobbyRoomRequest),
socketLobby(socket),
mods(mods)
{
ui->setupUi(this);
ui->nameEdit->setText(room);
if(!room.isEmpty())
{
ui->nameEdit->setReadOnly(true);
ui->totalPlayers->setEnabled(false);
}
show();
}
LobbyRoomRequest::~LobbyRoomRequest()
{
delete ui;
}
void LobbyRoomRequest::on_buttonBox_accepted()
{
if(ui->nameEdit->isReadOnly())
{
socketLobby.requestJoinSession(ui->nameEdit->text(), ui->passwordEdit->text(), mods);
}
else
{
if(!ui->nameEdit->text().isEmpty())
{
int totalPlayers = ui->totalPlayers->currentIndex() + 2; //where 2 is a minimum amount of players
socketLobby.requestNewSession(ui->nameEdit->text(), totalPlayers, ui->passwordEdit->text(), mods);
}
}
}

View File

@ -0,0 +1,37 @@
/*
* lobbyroomrequest_moc.h, part of VCMI engine
*
* Authors: listed in file AUTHORS in main folder
*
* License: GNU General Public License v2.0 or later
* Full text of license available in license.txt file, in main folder
*
*/
#ifndef LOBBYROOMREQUEST_MOC_H
#define LOBBYROOMREQUEST_MOC_H
#include <QDialog>
#include "lobby.h"
namespace Ui {
class LobbyRoomRequest;
}
class LobbyRoomRequest : public QDialog
{
Q_OBJECT
public:
explicit LobbyRoomRequest(SocketLobby & socket, const QString & room, const QMap<QString, QString> & mods, QWidget *parent = nullptr);
~LobbyRoomRequest();
private slots:
void on_buttonBox_accepted();
private:
Ui::LobbyRoomRequest *ui;
SocketLobby & socketLobby;
QMap<QString, QString> mods;
};
#endif // LOBBYROOMREQUEST_MOC_H

View File

@ -0,0 +1,148 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>LobbyRoomRequest</class>
<widget class="QDialog" name="LobbyRoomRequest">
<property name="windowModality">
<enum>Qt::WindowModal</enum>
</property>
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>193</width>
<height>188</height>
</rect>
</property>
<property name="windowTitle">
<string>Room settings</string>
</property>
<property name="locale">
<locale language="English" country="UnitedStates"/>
</property>
<property name="sizeGripEnabled">
<bool>false</bool>
</property>
<property name="modal">
<bool>true</bool>
</property>
<layout class="QGridLayout" name="gridLayout">
<item row="0" column="0" colspan="2">
<widget class="QLabel" name="label">
<property name="text">
<string>Room name</string>
</property>
</widget>
</item>
<item row="1" column="0" colspan="2">
<widget class="QLineEdit" name="nameEdit"/>
</item>
<item row="2" column="0">
<widget class="QLabel" name="label_2">
<property name="text">
<string>Maximum players</string>
</property>
</widget>
</item>
<item row="2" column="1">
<widget class="QComboBox" name="totalPlayers">
<property name="sizePolicy">
<sizepolicy hsizetype="Minimum" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<item>
<property name="text">
<string>2</string>
</property>
</item>
<item>
<property name="text">
<string>3</string>
</property>
</item>
<item>
<property name="text">
<string>4</string>
</property>
</item>
<item>
<property name="text">
<string>5</string>
</property>
</item>
<item>
<property name="text">
<string>6</string>
</property>
</item>
<item>
<property name="text">
<string>7</string>
</property>
</item>
<item>
<property name="text">
<string>8</string>
</property>
</item>
</widget>
</item>
<item row="3" column="0" colspan="2">
<widget class="QLabel" name="label_3">
<property name="text">
<string>Password (optional)</string>
</property>
</widget>
</item>
<item row="4" column="0" colspan="2">
<widget class="QLineEdit" name="passwordEdit"/>
</item>
<item row="5" column="0" colspan="2">
<widget class="QDialogButtonBox" name="buttonBox">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="standardButtons">
<set>QDialogButtonBox::Cancel|QDialogButtonBox::Ok</set>
</property>
</widget>
</item>
</layout>
</widget>
<resources/>
<connections>
<connection>
<sender>buttonBox</sender>
<signal>rejected()</signal>
<receiver>LobbyRoomRequest</receiver>
<slot>reject()</slot>
<hints>
<hint type="sourcelabel">
<x>316</x>
<y>260</y>
</hint>
<hint type="destinationlabel">
<x>286</x>
<y>274</y>
</hint>
</hints>
</connection>
<connection>
<sender>buttonBox</sender>
<signal>accepted()</signal>
<receiver>LobbyRoomRequest</receiver>
<slot>accept()</slot>
<hints>
<hint type="sourcelabel">
<x>248</x>
<y>254</y>
</hint>
<hint type="destinationlabel">
<x>157</x>
<y>274</y>
</hint>
</hints>
</connection>
</connections>
</ui>

View File

@ -1,38 +1,86 @@
/*
* main.cpp, part of VCMI engine
*
* Authors: listed in file AUTHORS in main folder
*
* License: GNU General Public License v2.0 or later
* Full text of license available in license.txt file, in main folder
*
*/
#include "main.h"
#include "mainwindow_moc.h"
#include <QApplication>
// Conan workaround https://github.com/conan-io/conan-center-index/issues/13332
#ifdef VCMI_IOS
#if __has_include("QIOSIntegrationPlugin.h")
#include "QIOSIntegrationPlugin.h"
#endif
#endif
int main(int argc, char * argv[])
{
int result;
#ifdef VCMI_IOS
{
#endif
QApplication vcmilauncher(argc, argv);
MainWindow mainWindow;
mainWindow.show();
result = vcmilauncher.exec();
#ifdef VCMI_IOS
}
if (result == 0)
launchGame(argc, argv);
#endif
return result;
}
/*
* main.cpp, part of VCMI engine
*
* Authors: listed in file AUTHORS in main folder
*
* License: GNU General Public License v2.0 or later
* Full text of license available in license.txt file, in main folder
*
*/
#include "StdInc.h"
#include "main.h"
#include "mainwindow_moc.h"
#include <QApplication>
#include <QProcess>
#include <QMessageBox>
#include "../lib/VCMIDirs.h"
// Conan workaround https://github.com/conan-io/conan-center-index/issues/13332
#ifdef VCMI_IOS
#if __has_include("QIOSIntegrationPlugin.h")
#include "QIOSIntegrationPlugin.h"
#endif
int argcForClient;
char ** argvForClient;
#endif
int main(int argc, char * argv[])
{
int result;
#ifdef VCMI_IOS
{
#endif
QApplication vcmilauncher(argc, argv);
MainWindow mainWindow;
mainWindow.show();
result = vcmilauncher.exec();
#ifdef VCMI_IOS
}
if (result == 0)
launchGame(argcForClient, argvForClient);
#endif
return result;
}
void startGame(const QStringList & args)
{
logGlobal->warn("Starting game with the arguments: %s", args.join(" ").toStdString());
#ifdef Q_OS_IOS
argcForClient = args.size() + 1; //first argument is omitted
argvForClient = new char*[argcForClient];
argvForClient[0] = "vcmiclient";
for(int i = 1; i < argcForClient; ++i)
{
std::string s = args.at(i - 1).toStdString();
argvForClient[i] = new char[s.size() + 1];
strcpy(argvForClient[i], s.c_str());
}
qApp->quit();
#else
startExecutable(pathToQString(VCMIDirs::get().clientPath()), args);
#endif
}
#ifndef Q_OS_IOS
void startExecutable(QString name, const QStringList & args)
{
QProcess process;
// Start the executable
if(process.startDetached(name, args))
{
qApp->quit();
}
else
{
QMessageBox::critical(qApp->activeWindow(),
"Error starting executable",
"Failed to start " + name + "\n"
"Reason: " + process.errorString(),
QMessageBox::Ok,
QMessageBox::Ok);
}
}
#endif

View File

@ -1,14 +1,18 @@
/*
* main.h, part of VCMI engine
*
* Authors: listed in file AUTHORS in main folder
*
* License: GNU General Public License v2.0 or later
* Full text of license available in license.txt file, in main folder
*
*/
#pragma once
#ifdef VCMI_IOS
extern "C" void launchGame(int argc, char * argv[]);
#endif
/*
* main.h, part of VCMI engine
*
* Authors: listed in file AUTHORS in main folder
*
* License: GNU General Public License v2.0 or later
* Full text of license available in license.txt file, in main folder
*
*/
#pragma once
void startGame(const QStringList & args);
#ifdef VCMI_IOS
extern "C" void launchGame(int argc, char * argv[]);
#else
void startExecutable(QString name, const QStringList & args);
#endif

View File

@ -11,7 +11,6 @@
#include "mainwindow_moc.h"
#include "ui_mainwindow_moc.h"
#include <QProcess>
#include <QDir>
#include "../lib/CConfigHandler.h"
@ -20,6 +19,7 @@
#include "../lib/logging/CBasicLogConfigurator.h"
#include "updatedialog_moc.h"
#include "main.h"
void MainWindow::load()
{
@ -85,9 +85,9 @@ MainWindow::MainWindow(QWidget * parent)
}
ui->tabListWidget->setCurrentIndex(0);
ui->settingsView->isExtraResolutionsModEnabled = ui->stackedWidgetPage2->isExtraResolutionsModEnabled();
ui->settingsView->isExtraResolutionsModEnabled = ui->modlistView->isExtraResolutionsModEnabled();
ui->settingsView->setDisplayList();
connect(ui->stackedWidgetPage2, &CModListView::extraResolutionsEnabledChanged,
connect(ui->modlistView, &CModListView::extraResolutionsEnabledChanged,
ui->settingsView, &CSettingsView::fillValidResolutions);
connect(ui->tabSelectList, &QListWidget::currentRowChanged, [this](int i) {
@ -97,6 +97,11 @@ MainWindow::MainWindow(QWidget * parent)
#endif
ui->tabListWidget->setCurrentIndex(i);
});
#ifdef Q_OS_IOS
QScroller::grabGesture(ui->tabSelectList, QScroller::LeftMouseButtonGesture);
ui->tabSelectList->setVerticalScrollMode(QAbstractItemView::ScrollPerPixel);
#endif
if(settings["launcher"]["updateOnStartup"].Bool())
UpdateDialog::showUpdateDialog(false);
@ -114,31 +119,15 @@ MainWindow::~MainWindow()
void MainWindow::on_startGameButton_clicked()
{
#ifdef Q_OS_IOS
qApp->quit();
#else
startExecutable(pathToQString(VCMIDirs::get().clientPath()));
#endif
startGame({});
}
#ifndef Q_OS_IOS
void MainWindow::startExecutable(QString name)
void MainWindow::on_tabSelectList_currentRowChanged(int currentRow)
{
QProcess process;
// Start the executable
if(process.startDetached(name, {}))
{
close(); // exit launcher
}
else
{
QMessageBox::critical(this,
"Error starting executable",
"Failed to start " + name + "\n"
"Reason: " + process.errorString(),
QMessageBox::Ok,
QMessageBox::Ok);
}
ui->startGameButton->setEnabled(currentRow != TabRows::LOBBY);
}
const CModList & MainWindow::getModList() const
{
return ui->modlistView->getModList();
}
#endif

View File

@ -19,6 +19,8 @@ const QString appName = "VCMI Launcher";
}
class QTableWidgetItem;
class CModList;
class MainWindow : public QMainWindow
{
@ -27,14 +29,22 @@ class MainWindow : public QMainWindow
private:
Ui::MainWindow * ui;
void load();
#ifndef Q_OS_IOS
void startExecutable(QString name);
#endif
enum TabRows
{
MODS = 0, SETTINGS = 1, LOBBY = 2
};
public:
explicit MainWindow(QWidget * parent = 0);
~MainWindow();
private slots:
const CModList & getModList() const;
public slots:
void on_startGameButton_clicked();
private slots:
void on_tabSelectList_currentRowChanged(int currentRow);
};

View File

@ -51,6 +51,9 @@
<property name="horizontalScrollBarPolicy">
<enum>Qt::ScrollBarAlwaysOff</enum>
</property>
<property name="sizeAdjustPolicy">
<enum>QAbstractScrollArea::AdjustToContents</enum>
</property>
<property name="editTriggers">
<set>QAbstractItemView::NoEditTriggers</set>
</property>
@ -75,6 +78,9 @@
<property name="flow">
<enum>QListView::TopToBottom</enum>
</property>
<property name="isWrapping" stdset="0">
<bool>false</bool>
</property>
<property name="resizeMode">
<enum>QListView::Adjust</enum>
</property>
@ -91,7 +97,7 @@
<bool>true</bool>
</property>
<property name="wordWrap">
<bool>true</bool>
<bool>false</bool>
</property>
<item>
<property name="text">
@ -111,13 +117,21 @@
<normaloff>icons:menu-settings.png</normaloff>icons:menu-settings.png</iconset>
</property>
</item>
<item>
<property name="text">
<string>Lobby</string>
</property>
<property name="icon">
<iconset>
<normaloff>icons:menu-lobby.png</normaloff>icons:menu-lobby.png</iconset>
</property>
</item>
</widget>
</item>
<item row="2" column="0">
<widget class="QLabel" name="startGameTitle">
<property name="font">
<font>
<weight>75</weight>
<bold>true</bold>
</font>
</property>
@ -143,8 +157,9 @@
<property name="currentIndex">
<number>0</number>
</property>
<widget class="CModListView" name="stackedWidgetPage2"/>
<widget class="CModListView" name="modlistView"/>
<widget class="CSettingsView" name="settingsView"/>
<widget class="Lobby" name="lobbyView"/>
</widget>
</item>
<item row="1" column="0">
@ -202,6 +217,12 @@
<header>settingsView/csettingsview_moc.h</header>
<container>1</container>
</customwidget>
<customwidget>
<class>Lobby</class>
<extends>QWidget</extends>
<header>lobby/lobby_moc.h</header>
<container>1</container>
</customwidget>
</customwidgets>
<tabstops>
<tabstop>tabSelectList</tabstop>

View File

@ -102,6 +102,17 @@ CModListView::CModListView(QWidget * parent)
{
manager->resetRepositories();
}
#ifdef Q_OS_IOS
for(auto * scrollWidget : {
(QAbstractItemView*)ui->allModsView,
(QAbstractItemView*)ui->screenshotsList})
{
QScroller::grabGesture(scrollWidget, QScroller::LeftMouseButtonGesture);
scrollWidget->setVerticalScrollMode(QAbstractItemView::ScrollPerPixel);
scrollWidget->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
}
#endif
}
void CModListView::loadRepositories()
@ -825,3 +836,9 @@ void CModListView::on_showInfoButton_clicked()
{
showModInfo();
}
const CModList & CModListView::getModList() const
{
assert(modModel);
return *modModel;
}

View File

@ -18,6 +18,7 @@ class CModListView;
}
class CModManager;
class CModList;
class CModListModel;
class CModFilterModel;
class CDownloadManager;
@ -80,6 +81,8 @@ public:
void selectMod(const QModelIndex & index);
bool isExtraResolutionsModEnabled() const;
const CModList & getModList() const;
private slots:
void dataChanged(const QModelIndex & topleft, const QModelIndex & bottomRight);
void modSelected(const QModelIndex & current, const QModelIndex & previous);

View File

@ -170,6 +170,10 @@ void CVCMIServer::run()
#endif
startAsyncAccept();
if(!remoteConnectionsThread && cmdLineOptions.count("lobby"))
{
remoteConnectionsThread = vstd::make_unique<boost::thread>(&CVCMIServer::establishRemoteConnections, this);
}
#if defined(VCMI_ANDROID)
CAndroidVMHelper vmHelper;
@ -195,6 +199,38 @@ void CVCMIServer::run()
boost::this_thread::sleep(boost::posix_time::milliseconds(50));
}
void CVCMIServer::establishRemoteConnections()
{
uuid = cmdLineOptions["lobby-uuid"].as<std::string>();
int numOfConnections = cmdLineOptions["connections"].as<ui16>();
auto address = cmdLineOptions["lobby"].as<std::string>();
int port = cmdLineOptions["lobby-port"].as<ui16>();
logGlobal->info("Server is connecting to remote at %s:%d with uuid %s %d times", address, port, uuid, numOfConnections);
for(int i = 0; i < numOfConnections; ++i)
connectToRemote(address, port);
}
void CVCMIServer::connectToRemote(const std::string & addr, int port)
{
std::shared_ptr<CConnection> c;
try
{
logNetwork->info("Establishing connection...");
c = std::make_shared<CConnection>(addr, port, SERVER_NAME, uuid);
}
catch(...)
{
logNetwork->error("\nCannot establish remote connection!");
}
if(c)
{
connections.insert(c);
c->handler = std::make_shared<boost::thread>(&CVCMIServer::threadHandleClient, this, c);
}
}
void CVCMIServer::threadAnnounceLobby()
{
while(state != EServerState::SHUTDOWN)
@ -952,10 +988,6 @@ void handleLinuxSignal(int sig)
static void handleCommandOptions(int argc, char * argv[], boost::program_options::variables_map & options)
{
namespace po = boost::program_options;
#ifdef SINGLE_PROCESS_APP
options.emplace("run-by-client", po::variable_value{true, true});
options.emplace("uuid", po::variable_value{std::string{argv[1]}, true});
#else
po::options_description opts("Allowed options");
opts.add_options()
("help,h", "display help and exit")
@ -964,7 +996,11 @@ static void handleCommandOptions(int argc, char * argv[], boost::program_options
("uuid", po::value<std::string>(), "")
("enable-shm-uuid", "use UUID for shared memory identifier")
("enable-shm", "enable usage of shared memory")
("port", po::value<ui16>(), "port at which server will listen to connections from client");
("port", po::value<ui16>(), "port at which server will listen to connections from client")
("lobby", po::value<std::string>(), "address to remote lobby")
("lobby-port", po::value<ui16>(), "port at which server connect to remote lobby")
("lobby-uuid", po::value<std::string>(), "")
("connections", po::value<ui16>(), "amount of connections to remote lobby");
if(argc > 1)
{
@ -977,7 +1013,6 @@ static void handleCommandOptions(int argc, char * argv[], boost::program_options
std::cerr << "Failure during parsing command-line options:\n" << e.what() << std::endl;
}
}
#endif
po::notify(options);
@ -1079,19 +1114,21 @@ int main(int argc, char * argv[])
}
#ifdef VCMI_ANDROID
void CVCMIServer::create()
void CVCMIServer::create(const std::vector<std::string> & args)
{
const char * foo[1] = {"android-server"};
const char * foo = "android-server";
std::vector<const void *> argv = {foo};
for(auto & a : args)
argv.push_back(a.c_str());
main(1, const_cast<char **>(foo));
main(argv.size(), const_cast<char **>(foo));
}
#elif defined(SINGLE_PROCESS_APP)
void CVCMIServer::create(boost::condition_variable * cond, const std::string & uuid)
void CVCMIServer::create(boost::condition_variable * cond, const std::vector<std::string> & args)
{
const std::initializer_list<const void *> argv = {
cond,
uuid.c_str(),
};
main(argv.size(), reinterpret_cast<char **>(const_cast<void **>(argv.begin())));
std::vector<const void *> argv = {cond};
for(auto & a : args)
argv.push_back(a.c_str());
main(argv.size(), reinterpret_cast<char **>(const_cast<void **>(&*argv.begin())));
}
#endif

View File

@ -52,7 +52,7 @@ class CVCMIServer : public LobbyInfo
std::list<std::unique_ptr<CPackForLobby>> announceQueue;
boost::recursive_mutex mx;
std::shared_ptr<CApplier<CBaseForServerApply>> applier;
std::unique_ptr<boost::thread> announceLobbyThread;
std::unique_ptr<boost::thread> announceLobbyThread, remoteConnectionsThread;
public:
std::shared_ptr<CGameHandler> gh;
@ -74,6 +74,8 @@ public:
void prepareToRestart();
void startGameImmidiately();
void establishRemoteConnections();
void connectToRemote(const std::string & addr, int port);
void startAsyncAccept();
void connectionAccepted(const boost::system::error_code & ec);
void threadHandleClient(std::shared_ptr<CConnection> c);
@ -112,8 +114,8 @@ public:
ui8 getIdOfFirstUnallocatedPlayer() const;
#ifdef VCMI_ANDROID
static void create();
static void create(const std::vector<std::string> & args);
#elif defined(SINGLE_PROCESS_APP)
static void create(boost::condition_variable * cond, const std::string & uuid);
static void create(boost::condition_variable * cond, const std::vector<std::string> & args);
#endif
};