-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmainwindow.cpp
553 lines (481 loc) · 18.2 KB
/
mainwindow.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
#include "mainwindow.h"
#include "botviewdelegate.h"
#include "spinbox.h"
#include "tournamentcontroller.h"
#include <QHeaderView>
#include <QItemDelegate>
#include <QItemEditorFactory>
#include <QComboBox>
#include <QVBoxLayout>
#include <QGridLayout>
#include <QHBoxLayout>
#include <QPushButton>
#include <QApplication>
#include <QGroupBox>
#include <QSettings>
#include <QFileInfo>
#include <QMessageBox>
#include <QProcess>
#include <QCheckBox>
#include <QDebug>
#include <QFileDialog>
#include <QTimer>
#include <QLabel>
#include <QThread>
#include <QTime>
#include <QTabWidget>
#include <QQuickWidget>
#include <QQuickItem>
#include <QQmlContext>
#include <QQmlEngine>
#include <QAction>
#define SERVERPATH_KEY "serverpath"
#define ROUNDS_KEY "rounds"
#define AUTOSTART_KEY "autostart"
#define AUTOQUIT_KEY "autoquit"
#define TICKINTERVAL_KEY "tickinterval"
#define FULLSCREEN_KEY "fullscreen"
#define HEADLESS_KEY "headless"
#define TICKLESS_KEY "tickless"
#define ROUNDSPLAYED_KEY "roundsplayed"
static MainWindow *instance = 0;
void messageHandler(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
QByteArray localMsg = msg.toLocal8Bit();
if (instance) {
switch (type) {
case QtWarningMsg:
case QtCriticalMsg:
instance->errorOutput(msg);
break;
case QtFatalMsg:
fprintf(stderr, "Fatal: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line, context.function);
abort();
case QtDebugMsg:
case QtInfoMsg:
default:
instance->normalOutput(msg);
break;
}
}
switch (type) {
case QtWarningMsg:
fprintf(stderr, "Warning: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line, context.function);
break;
case QtCriticalMsg:
fprintf(stderr, "Critical: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line, context.function);
break;
case QtFatalMsg:
fprintf(stderr, "Fatal: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line, context.function);
abort();
case QtDebugMsg:
case QtInfoMsg:
default:
fprintf(stderr, "Debug: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line, context.function);
break;
}
}
MainWindow::MainWindow(QWidget *parent)
: QSplitter(parent),
m_botsView(new QTableView(this)),
m_botModel(BotModel::instance()),
m_logFile("BORG.log")
{
m_logFile.open(QIODevice::WriteOnly | QIODevice::Append);
instance = this;
qInstallMessageHandler(messageHandler);
QSettings settings;
m_roundsPlayed = settings.value(ROUNDSPLAYED_KEY, 0).toInt();
///////////
/// Main/left part of window
///
m_tabWidget = new QTabWidget;
addWidget(m_tabWidget);
m_tabWidget->setTabPosition(QTabWidget::East);
///////////
/// Tournament overview
///
QQuickWidget *tournamentView = new QQuickWidget(QUrl("qrc:/TournamentView.qml"));
tournamentView->setResizeMode(QQuickWidget::SizeRootObjectToView);
m_tabWidget->addTab(tournamentView, "Tournament view");
QWidget *setupWidget = new QWidget;
QLayout *setupLayout = new QVBoxLayout;
setupWidget->setLayout(setupLayout);
///////////
/// Bot list view
///
m_botsView->setItemDelegate(new BotViewDelegate);
m_botsView->setModel(m_botModel);
m_botsView->setShowGrid(false);
m_botsView->setSelectionMode(QAbstractItemView::SingleSelection);
m_botsView->setSelectionBehavior(QAbstractItemView::SelectRows);
m_botsView->resizeColumnsToContents();
m_botsView->horizontalHeader()->setStretchLastSection(true);
m_botsView->selectRow(0);
m_botsView->setAlternatingRowColors(true);
setupLayout->addWidget(m_botsView);
///////////
/// Add/remove buttons
///
QWidget *addRemoveGroup = new QWidget;
addRemoveGroup->setLayout(new QHBoxLayout);
setupLayout->addWidget(addRemoveGroup);
// Reset tournament button
QPushButton *resetBotButton = new QPushButton(tr("Reset &bots"));
addRemoveGroup->layout()->addWidget(resetBotButton);
// Reset tournament button
QPushButton *resetTournamentButton = new QPushButton(tr("&Reset tournament"));
addRemoveGroup->layout()->addWidget(resetTournamentButton);
connect(resetTournamentButton, &QAbstractButton::clicked, this, &MainWindow::resetBots);
addRemoveGroup->layout()->addItem(new QSpacerItem(0, 0, QSizePolicy::Expanding));
// Add button
QPushButton *addButton = new QPushButton(tr("&Add new bot..."));
connect(addButton, &QPushButton::clicked, this, &MainWindow::addBot);
addRemoveGroup->layout()->addWidget(addButton);
// Add multiple button
QPushButton *addMultipleButton = new QPushButton(tr("Add &multiple bots..."));
connect(addMultipleButton, &QPushButton::clicked, this, &MainWindow::addBots);
addRemoveGroup->layout()->addWidget(addMultipleButton);
// Remove button
QPushButton *removeButton = new QPushButton(tr("Remo&ve selected"));
connect(removeButton, SIGNAL(clicked()), SLOT(removeBot()));
addRemoveGroup->layout()->addWidget(removeButton);
m_tabWidget->addTab(setupWidget, "S&etup");
///////////
/// Server control
///
QWidget *serverBox = new QWidget;
serverBox->setLayout(new QVBoxLayout);
setupLayout->addWidget(serverBox);
///////////
/// Server settings
///
QWidget *serverLaunch = new QWidget;
serverLaunch->setLayout(new QHBoxLayout);
serverBox->layout()->addWidget(serverLaunch);
// Server path editor
m_serverPath = new PathEditor;
serverLaunch->layout()->addWidget(m_serverPath);
m_serverPath->setPath(settings.value(SERVERPATH_KEY, "").toString());
///////////
/// Server settings
///
QWidget *serverSettings = new QWidget;
QBoxLayout *serverSettingsLayout = new QHBoxLayout;
serverSettings->setLayout(serverSettingsLayout);
serverBox->layout()->addWidget(serverSettings);
// Round count editor
m_rounds = new QSpinBox;
m_rounds->setMinimum(1);
m_rounds->setMaximum(10000);
m_rounds->setSuffix(tr(" rounds"));
serverSettings->layout()->addWidget(m_rounds);
m_rounds->setValue(settings.value(ROUNDS_KEY, 4).toInt());
// Tick interval editor
m_tickInterval = new QSpinBox;
m_tickInterval->setMinimum(10);
m_tickInterval->setMaximum(1000);
m_tickInterval->setSuffix(" ms ticks");
serverSettings->layout()->addWidget(m_tickInterval);
m_tickInterval->setValue(settings.value(TICKINTERVAL_KEY, 50).toInt());
// Fullscreen checkbox
m_fullscreen = new QCheckBox(tr("Fullscreen"));
serverSettings->layout()->addWidget(m_fullscreen);
m_fullscreen->setChecked(settings.value(FULLSCREEN_KEY, false).toBool());
serverSettingsLayout->addStretch();
///////////
/// Right part of window
///
QWidget *rightWidget = new QWidget;
QVBoxLayout *rightLayout = new QVBoxLayout;
rightWidget->setLayout(rightLayout);
addWidget(rightWidget);
// Top players list
m_topPlayers.setText("<h3>Top players</h3><ol><li>...</li></ol>");
rightWidget->layout()->addWidget(&m_topPlayers);
updateTopPlayers();
// Log/output view
m_serverOutput.setReadOnly(true);
// m_serverOutput.setTextColor(Qt::black);
rightLayout->addWidget(&m_serverOutput, 10);
QPushButton *clearButton = new QPushButton(tr("Clear output"));
rightLayout->addWidget(clearButton);
connect(clearButton, &QPushButton::clicked, this, [=](){
this->m_serverOutput.clear();
});
// Server launch button
QPushButton *launchButton = new QPushButton(tr("&Start server"));
launchButton->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
rightLayout->addWidget(launchButton, 2);
// Kill button
QPushButton *killButton = new QPushButton(tr("&Kill server"));
rightWidget->layout()->addWidget(killButton);
rightLayout->addSpacing(10);
///////////
/// Quit button
///
QPushButton *quitButton = new QPushButton(tr("&Quit"));
connect(quitButton, SIGNAL(clicked()), qApp, SLOT(quit()));
rightWidget->layout()->addWidget(quitButton);
QAction *showUiAction = new QAction;
showUiAction->setShortcut(Qt::Key_Escape);
connect(showUiAction, &QAction::triggered, this, [=]() {
rightWidget->setVisible(!rightWidget->isVisible());
m_tabWidget->tabBar()->setVisible(!m_tabWidget->tabBar()->isVisible());
});
addAction(showUiAction);
// Connections
// connect(killButton, SIGNAL(clicked()), SLOT(kill()));
connect(killButton, &QPushButton::clicked, this, &MainWindow::kill);
connect(m_serverPath, &PathEditor::pathChanged, this, &MainWindow::saveSettings);
connect(m_rounds, static_cast<void(QSpinBox::*)(int)>(&QSpinBox::valueChanged), this, &MainWindow::saveSettings);
connect(m_tickInterval, static_cast<void(QSpinBox::*)(int)>(&QSpinBox::valueChanged), this, &MainWindow::saveSettings);
connect(m_fullscreen, &QCheckBox::stateChanged, this, &MainWindow::saveSettings);
connect(launchButton, &QAbstractButton::clicked, this, &MainWindow::launchServer);
connect(&m_serverProcess, &QProcess::readyReadStandardError, this, &MainWindow::readServerErr);
connect(&m_serverProcess, &QProcess::readyReadStandardOutput, this, &MainWindow::readServerOut);
connect(&m_serverProcess, static_cast<void(QProcess::*)(int, QProcess::ExitStatus)>(&QProcess::finished), this, &MainWindow::serverFinished);
setMinimumSize(1920, 1080);
}
MainWindow::~MainWindow()
{
kill();
}
void MainWindow::saveSettings()
{
QSettings settings;
settings.setValue(SERVERPATH_KEY, m_serverPath->path());
settings.setValue(ROUNDS_KEY, m_rounds->value());
settings.setValue(TICKINTERVAL_KEY, m_tickInterval->value());
settings.setValue(FULLSCREEN_KEY, m_fullscreen->isChecked());
settings.setValue(ROUNDSPLAYED_KEY, m_roundsPlayed);
}
void MainWindow::launchServer()
{
bool tournamentMode = m_tabWidget->currentIndex() == 0;
m_botModel->setTournamentMode(tournamentMode);
if (m_botModel->enabledPlayers() > 8 || m_botModel->enabledPlayers() < 2) {
QMessageBox::warning(this, tr("Invalid number of players"), tr("Either too few or too many players enabled"));
return;
}
if (m_logFile.isOpen()) {
m_logFile.close();
}
m_logFile.setFileName(QDateTime::currentDateTime().toString(Qt::ISODate) + ".log");
m_logFile.open(QIODevice::WriteOnly | QIODevice::Append);
m_logFile.write("Starting " + QByteArray::number(m_roundsPlayed) + "\n");
if (m_serverProcess.state() == QProcess::Running) {
QMessageBox::warning(this, tr("Server already running"), tr("The server executable is still running"));
return;
}
QFileInfo serverExecutable(m_serverPath->path());
if (!serverExecutable.exists()) {
QMessageBox::warning(this, tr("Server not found"), tr("Can't find the server at the path provided!"));
return;
}
if (!serverExecutable.isExecutable()) {
QMessageBox::warning(this, tr("Server not runnable"), tr("The server is not an executable file!"));
return;
}
QStringList arguments;
arguments << "--tick-interval" << QString::number(m_tickInterval->value());
arguments << "--rounds" << QString::number(m_rounds->value());
for (const QString &botPath : m_botModel->enabledBotPaths()) {
arguments << "--bot" << botPath;
}
if (m_fullscreen->isChecked()) {
arguments << "--fullscreen";
}
m_serverProcess.setWorkingDirectory(serverExecutable.path());
QFile::remove(m_serverProcess.workingDirectory() + "/scores.txt");
m_serverProcess.start(serverExecutable.filePath(), arguments);
}
void MainWindow::readServerErr()
{
QByteArray output = m_serverProcess.readAllStandardError();
errorOutput(output);
}
void MainWindow::readServerOut()
{
QByteArray output = m_serverProcess.readAllStandardOutput();
normalOutput(output);
}
void MainWindow::addBot()
{
QString path = QFileDialog::getOpenFileName(this, tr("Select bot"), QStringLiteral("/home/sandsmark/tg/17/ai"));
if (path.isEmpty()) {
return;
}
m_botModel->addBot(path);
}
void MainWindow::addBots()
{
QString dirPath = QFileDialog::getExistingDirectory(this, tr("Open Directory"),
QStringLiteral("/home/sandsmark/tg/18/ai"),
QFileDialog::ShowDirsOnly
| QFileDialog::DontResolveSymlinks);
if (dirPath.isEmpty()) {
return;
}
qDebug() << "Checking for bots in" << dirPath;
QDir dir(dirPath);
for (const QString &subinfo : dir.entryList(QDir::Dirs | QDir::NoDotAndDotDot)) {
QDir subdir(dir.filePath(subinfo));
QFileInfoList files = subdir.entryInfoList(QStringList("*.bot"), QDir::Files);
if (!files.isEmpty()) {
m_botModel->addBot(files.first().absoluteFilePath());
continue;
}
}
for (const QFileInfo &botFile : dir.entryInfoList(QStringList("*.bot"), QDir::Files)) {
m_botModel->addBot(botFile.absoluteFilePath());
}
}
void MainWindow::removeBot()
{
const QModelIndex index = m_botsView->currentIndex();
if (!index.isValid()) {
return;
}
const int row = index.row();
QString name = m_botModel->data(m_botModel->index(row, BotModel::Name)).toString();
if (QMessageBox::question(this, tr("Really remove?"), tr("Are you sure you want to remove %1?").arg(name)) == QMessageBox::No) {
return;
}
m_botModel->removeRow(row);
}
void MainWindow::kill()
{
m_serverProcess.terminate();
QThread::usleep(200);
m_serverProcess.kill();
}
static bool isTie(const QList<int> &list)
{
const int first = list.first();
for (const int num : list) {
if (num != first) {
return false;
}
}
return true;
}
void MainWindow::serverFinished(int status)
{
m_logFile.close();
m_logFile.setFileName("BORG.log");
m_logFile.open(QIODevice::WriteOnly | QIODevice::Append);
qWarning() << m_roundsPlayed << "finished";
if (status != 0) {
qWarning() << "Server finished with unclean status" << status;
m_serverOutput.append(QStringLiteral("Server finished with unclean status %1!\n").arg(status));
}
QFile resultsLog(m_serverProcess.workingDirectory() + "/scores.txt");
if (!resultsLog.open(QIODevice::ReadOnly)) {
QMessageBox::warning(this, tr("Unable to open server log"), tr("Unable to open server log with results"));
qWarning() << "unable to open results log!";
return;
}
int playersRead = 0;
QMap<QString, int> results;
QMap<QString, int> pointResults;
while (!resultsLog.atEnd()) {
QList<QByteArray> player = resultsLog.readLine().trimmed().split(';');
if (player.length() != 3) {
QMessageBox::warning(this, tr("Invalid scores.txt"), tr("The scores.txt file is corrupt (invalid column), please adjust scores manually."));
return;
}
bool roundWinsValid = false;
bool scoreValid = false;
QString name = QString::fromUtf8(player[0]);
int wins = player[1].toInt(&roundWinsValid);
int points = player[2].toInt(&scoreValid);
if (!roundWinsValid || !scoreValid || name.isEmpty()) {
qWarning() << roundWinsValid << scoreValid << player;
QMessageBox::warning(this, tr("Invalid scores.txt"), tr("The scores.txt file is corrupt (invalid values), please adjust scores manually."));
return;
}
m_botModel->roundOver(name, (playersRead == 0), wins, points);
results[name] = wins;
pointResults[name] = points;
playersRead++;
}
if (playersRead != m_botModel->enabledPlayers()) {
QMessageBox::warning(this, tr("Missing players"), tr("Missing players (%1 read of %2) from the scores.txt, please adjust manually").arg(playersRead).arg(m_botModel->enabledPlayers()));
}
if (isTie(results.values())) {
if (isTie(pointResults.values())) {
qDebug() << pointResults;
QMessageBox::warning(this, tr("Was tie"), tr("Was tie, unable to use tie breaker"));
return;
}
int maxPoints = pointResults.values().first();
QString winnerBotName = pointResults.keys().first();
for (const QString &botName : pointResults.keys()) {
if (pointResults[botName] <= maxPoints) {
continue;
}
maxPoints = pointResults[botName];
winnerBotName = botName;
}
for (const QString &botName : pointResults.keys()) {
if (botName == winnerBotName) {
results[botName] = 1;
} else {
results[botName] = 0;
}
}
}
bool tournamentMode = m_tabWidget->currentIndex() == 0;
if (tournamentMode) {
TournamentController::instance()->onMatchCompleted(results);
}
m_roundsPlayed++;
updateTopPlayers();
saveSettings();
}
void MainWindow::resetBots()
{
if (QMessageBox::question(this, tr("Really reset?"), tr("Are you sure you want to reset everything?")) == QMessageBox::No) {
return;
}
m_roundsPlayed = 0;
saveSettings();
m_botModel->resetBots();
TournamentController::instance()->initializeMatches();
updateTopPlayers();
}
void MainWindow::updateTopPlayers()
{
QString labelContent("<h3>Top players:</h3><ol>");
foreach(const QString name, m_botModel->topPlayers()) {
labelContent += QString("<li>%1</li>").arg(name);
}
labelContent += "</ol><br>";
m_topPlayers.setText(labelContent);
}
void MainWindow::errorOutput(QString message)
{
message = message.trimmed();
if (message.isEmpty()) {
return;
}
m_serverOutput.setTextColor(Qt::red);
m_serverOutput.append(message);
m_serverOutput.setTextColor(Qt::black);
if (m_logFile.isOpen()) {
m_logFile.write(message.toUtf8() + "\n");
}
}
void MainWindow::normalOutput(QString message)
{
message = message.trimmed();
if (message.isEmpty()) {
return;
}
m_serverOutput.append(message);
// m_serverOutput.setTextColor(Qt::black);
if (m_logFile.isOpen()) {
m_logFile.write(message.toUtf8() + "\n");
}
}