]> git.sesse.net Git - pkanalytics/blob - main.cpp
42d42cc0899300aefd254b5f3682e3856f308388
[pkanalytics] / main.cpp
1 #include <QMediaPlayer>
2 #include <QMainWindow>
3 #include <QApplication>
4 #include <QGridLayout>
5 #include <QVideoWidget>
6 #include <QShortcut>
7 #include <QInputDialog>
8 #include <algorithm>
9 #include <string>
10 #include <map>
11 #include <vector>
12 #include <optional>
13 #include <sqlite3.h>
14 #include "mainwindow.h"
15 #include "ui_mainwindow.h"
16 #include "events.h"
17 #include "players.h"
18 #include "formations.h"
19 #include "json.h"
20
21 using namespace std;
22
23 string format_timestamp(uint64_t pos)
24 {
25         int ms = pos % 1000;
26         pos /= 1000;
27         int sec = pos % 60;
28         pos /= 60;
29         int min = pos % 60;
30         int hour = pos / 60;
31
32         char buf[256];
33         snprintf(buf, sizeof(buf), "%d:%02d:%02d.%03d", hour, min, sec, ms);
34         return buf;
35 }
36
37 MainWindow::MainWindow(EventsModel *events, PlayersModel *players,
38                        FormationsModel *offensive_formations, FormationsModel *defensive_formations)
39         : events(events), players(players), offensive_formations(offensive_formations), defensive_formations(defensive_formations)
40 {
41         video = new QMediaPlayer;
42         //video->setSource(QUrl::fromLocalFile("/home/sesse/dev/stats/ultimate.mkv"));
43         video->setSource(QUrl::fromLocalFile("/home/sesse/dev/stats/ultimate-prores.mkv"));
44         video->play();
45
46         ui = new Ui::MainWindow;
47         ui->setupUi(this);
48
49         ui->event_view->setModel(events);
50         ui->event_view->setColumnWidth(1, 150);
51         ui->event_view->setColumnWidth(2, 150);
52         connect(ui->event_view->selectionModel(), &QItemSelectionModel::currentRowChanged,
53                 [this, events](const QModelIndex &current, const QModelIndex &previous) {
54                         uint64_t t = events->get_time(current.row());
55                         if (t != video->position()) {
56                                 video->setPosition(events->get_time(current.row()));
57                         } else {
58                                 // Selection could have changed, so we still need to update.
59                                 // (Just calling setPosition() would not give us the signal
60                                 // in this case.)
61                                 update_ui_from_time(t);
62                         }
63                 });
64
65         ui->player_view->setModel(players);
66         ui->player_view->setColumnWidth(0, 30);
67         ui->player_view->setColumnWidth(1, 20);
68         ui->player_view->horizontalHeader()->setStretchLastSection(true);
69
70         auto formation_changed = [this](const QModelIndex &current, const QModelIndex &previous) {
71                 update_action_buttons(video->position());
72         };
73         ui->offensive_formation_view->setModel(offensive_formations);
74         ui->defensive_formation_view->setModel(defensive_formations);
75         connect(ui->offensive_formation_view->selectionModel(), &QItemSelectionModel::currentRowChanged, formation_changed);
76         connect(ui->defensive_formation_view->selectionModel(), &QItemSelectionModel::currentRowChanged, formation_changed);
77         connect(ui->offensive_formation_view, &QListView::doubleClicked, [this](const QModelIndex &index) {
78                 formation_double_clicked(true, index.row());
79         });
80         connect(ui->defensive_formation_view, &QListView::doubleClicked, [this](const QModelIndex &index) {
81                 formation_double_clicked(false, index.row());
82         });
83
84         connect(video, &QMediaPlayer::positionChanged, [this](uint64_t pos) {
85                 position_changed(pos);
86         });
87
88         video->setVideoOutput(ui->video);
89
90         // It's not really clear whether PgUp should be forwards or backwards,
91         // but mpv does at least up = forwards, so that's probably standard.
92         QShortcut *pgdown = new QShortcut(QKeySequence(Qt::Key_PageDown), this);
93         connect(pgdown, &QShortcut::activated, [this]() { seek(-120000); });
94         QShortcut *pgup = new QShortcut(QKeySequence(Qt::Key_PageUp), this);
95         connect(pgup, &QShortcut::activated, [this]() { seek(120000); });
96
97         // Ugh. Used when Qt messes up and hangs the video.
98         QShortcut *f5 = new QShortcut(QKeySequence(Qt::Key_F5), this);
99         connect(f5, &QShortcut::activated, [this]() {
100                 QVideoWidget *nvw = new QVideoWidget(ui->video->parentWidget());
101                 nvw->setObjectName("video");
102                 nvw->setMinimumSize(QSize(320, 240));
103                 video->setVideoOutput(nvw);
104                 ui->main_grid->replaceWidget(ui->video, nvw);
105                 ui->video = nvw;
106         });
107
108         connect(ui->minus10s, &QPushButton::clicked, [this]() { seek(-10000); });
109         connect(ui->plus10s, &QPushButton::clicked, [this]() { seek(10000); });
110
111         connect(ui->minus2s, &QPushButton::clicked, [this]() { seek(-2000); });
112         connect(ui->plus2s, &QPushButton::clicked, [this]() { seek(2000); });
113
114         // TODO: Would be nice to actually have a frame...
115         connect(ui->minus1f, &QPushButton::clicked, [this]() { seek(-20); });
116         connect(ui->plus1f, &QPushButton::clicked, [this]() { seek(20); });
117
118         connect(ui->play_pause, &QPushButton::clicked, [this]() {
119                 if (playing) {
120                         video->pause();
121                         ui->play_pause->setText("Play (space)");
122                 } else {
123                         video->setPlaybackRate(1.0);
124                         video->play();
125                         ui->play_pause->setText("Pause (space)");
126                 }
127                 playing = !playing;
128
129                 // Needs to be set anew when we modify setText(), evidently.
130                 ui->play_pause->setShortcut(QCoreApplication::translate("MainWindow", "Space", nullptr));
131         });
132
133         connect(ui->player_1, &QPushButton::clicked, [this]() { insert_player_event(0); });
134         connect(ui->player_2, &QPushButton::clicked, [this]() { insert_player_event(1); });
135         connect(ui->player_3, &QPushButton::clicked, [this]() { insert_player_event(2); });
136         connect(ui->player_4, &QPushButton::clicked, [this]() { insert_player_event(3); });
137         connect(ui->player_5, &QPushButton::clicked, [this]() { insert_player_event(4); });
138         connect(ui->player_6, &QPushButton::clicked, [this]() { insert_player_event(5); });
139         connect(ui->player_7, &QPushButton::clicked, [this]() { insert_player_event(6); });
140
141         // Offensive events
142         connect(ui->offense_label, &ClickableLabel::clicked, [this]() { insert_noplayer_event("set_offense"); });
143         connect(ui->catch_, &QPushButton::clicked, [this]() { set_current_event_type("catch"); });
144         connect(ui->throwaway, &QPushButton::clicked, [this, events]() {
145                 EventsModel::Status s = events->get_status_at(video->position());
146                 if (s.attack_state == EventsModel::Status::DEFENSE && s.pull_state == EventsModel::Status::PULL_IN_AIR) {
147                         insert_noplayer_event("pull_oob");
148                 } else {
149                         set_current_event_type("throwaway");
150                 }
151         });
152         connect(ui->drop, &QPushButton::clicked, [this]() { set_current_event_type("drop"); });
153         connect(ui->goal, &QPushButton::clicked, [this]() { set_current_event_type("goal"); });
154         connect(ui->offensive_soft_plus, &QPushButton::clicked, [this]() { set_current_event_type("offensive_soft_plus"); });
155         connect(ui->offensive_soft_minus, &QPushButton::clicked, [this]() { set_current_event_type("offensive_soft_minus"); });
156         connect(ui->pull, &QPushButton::clicked, [this, events]() {
157                 EventsModel::Status s = events->get_status_at(video->position());
158                 if (s.pull_state == EventsModel::Status::SHOULD_PULL) {
159                         set_current_event_type("pull");
160                 } else if (EventsModel::Status::PULL_IN_AIR) {
161                         insert_noplayer_event("pull_landed");
162                 }
163         });
164
165         // Defensive events (TODO add more)
166         connect(ui->interception, &QPushButton::clicked, [this]() { set_current_event_type("interception"); });
167         connect(ui->defense_label, &ClickableLabel::clicked, [this]() { insert_noplayer_event("set_defense"); });
168         connect(ui->their_throwaway, &QPushButton::clicked, [this]() { insert_noplayer_event("their_throwaway"); });
169         connect(ui->their_goal, &QPushButton::clicked, [this]() { insert_noplayer_event("their_goal"); });
170         connect(ui->their_pull, &QPushButton::clicked, [this, events]() {
171                 EventsModel::Status s = events->get_status_at(video->position());
172                 if (s.pull_state == EventsModel::Status::SHOULD_PULL) {
173                         insert_noplayer_event("their_pull");
174                 }
175         });
176         connect(ui->our_defense, &QPushButton::clicked, [this]() { set_current_event_type("defense"); });
177         connect(ui->defensive_soft_plus, &QPushButton::clicked, [this]() { set_current_event_type("defensive_soft_plus"); });
178         connect(ui->defensive_soft_minus, &QPushButton::clicked, [this]() { set_current_event_type("defensive_soft_minus"); });
179
180         // Misc. events
181         connect(ui->substitution, &QPushButton::clicked, [this]() { make_substitution(); });
182         connect(ui->stoppage, &QPushButton::clicked, [this, events]() {
183                 EventsModel::Status s = events->get_status_at(video->position());
184                 if (s.stoppage) {
185                         insert_noplayer_event("restart");
186                 } else {
187                         insert_noplayer_event("stoppage");
188                 }
189         });
190         connect(ui->unknown, &QPushButton::clicked, [this]() { insert_noplayer_event("unknown"); });
191
192         QShortcut *key_delete = new QShortcut(QKeySequence(Qt::Key_Delete), this);
193         connect(key_delete, &QShortcut::activated, [this]() { ui->delete_->animateClick(); });
194         connect(ui->delete_, &QPushButton::clicked, [this]() { delete_current_event(); });
195 }
196
197 void MainWindow::position_changed(uint64_t pos)
198 {
199         ui->timestamp->setText(QString::fromUtf8(format_timestamp(pos)));
200         if (buffered_seek) {
201                 video->setPosition(*buffered_seek);
202                 buffered_seek.reset();
203         }
204         if (!playing) {
205                 video->pause();  // We only played to get a picture.
206         }
207         if (playing) {
208                 QModelIndex row = events->get_last_event_qt(video->position());
209                 ui->event_view->scrollTo(row, QAbstractItemView::PositionAtCenter);
210         }
211         update_ui_from_time(pos);
212 }
213
214 void MainWindow::seek(int64_t delta_ms)
215 {
216         int64_t current_pos = buffered_seek ? *buffered_seek : video->position();
217         uint64_t pos = max<int64_t>(current_pos + delta_ms, 0);
218         buffered_seek = pos;
219         if (!playing) {
220                 video->setPlaybackRate(0.01);
221                 video->play();  // Or Qt won't show the seek.
222         }
223 }
224
225 void MainWindow::insert_player_event(int button_id)
226 {
227         uint64_t t = video->position();
228         vector<int> team = events->sort_team(events->get_team_at(t));
229         if (button_id >= team.size()) {
230                 return;
231         }
232         int player_id = team[button_id];
233
234         EventsModel::Status s = events->get_status_at(t);
235
236         ui->event_view->selectionModel()->blockSignals(true);
237         if (s.attack_state == EventsModel::Status::OFFENSE) {
238                 // TODO: Perhaps not if that player already did the last catch?
239                 ui->event_view->selectRow(events->insert_event(t, player_id, nullopt, "catch"));
240         } else {
241                 ui->event_view->selectRow(events->insert_event(t, player_id, nullopt));
242         }
243         ui->event_view->selectionModel()->blockSignals(false);
244
245         update_ui_from_time(t);
246 }
247
248 void MainWindow::insert_noplayer_event(const string &type)
249 {
250         uint64_t t = video->position();
251
252         ui->event_view->selectionModel()->blockSignals(true);
253         ui->event_view->selectRow(events->insert_event(t, nullopt, nullopt, type));
254         ui->event_view->selectionModel()->blockSignals(false);
255
256         update_ui_from_time(t);
257 }
258
259 void MainWindow::set_current_event_type(const string &type)
260 {
261         QItemSelectionModel *select = ui->event_view->selectionModel();
262         if (!select->hasSelection()) {
263                 return;
264         }
265         int row = select->selectedRows().front().row();  // Should only be one, due to our selection behavior.
266         events->set_event_type(row, type);
267         update_ui_from_time(video->position());
268 }
269
270 void MainWindow::delete_current_event()
271 {
272         QItemSelectionModel *select = ui->event_view->selectionModel();
273         if (!select->hasSelection()) {
274                 return;
275         }
276         int row = select->selectedRows().front().row();  // Should only be one, due to our selection behavior.
277         ui->event_view->selectionModel()->blockSignals(true);
278         events->delete_event(row);
279         ui->event_view->selectionModel()->blockSignals(false);
280         update_ui_from_time(video->position());
281 }
282
283 void MainWindow::make_substitution()
284 {
285         QItemSelectionModel *select = ui->player_view->selectionModel();
286         set<int> new_team;
287         for (QModelIndex row : select->selectedRows()) {
288                 new_team.insert(players->get_player_id(row.row()));
289         }
290         events->set_team_at(video->position(), new_team);
291 }
292
293 void MainWindow::update_ui_from_time(uint64_t t)
294 {
295         update_status(t);
296         update_player_buttons(t);
297         update_action_buttons(t);
298 }
299
300 void MainWindow::update_status(uint64_t t)
301 {
302         EventsModel::Status s = events->get_status_at(t);
303         char buf[256];
304         const char *offense = "not started";
305         if (s.attack_state == EventsModel::Status::OFFENSE) {
306                 offense = "offense";
307         } else if (s.attack_state == EventsModel::Status::DEFENSE) {
308                 offense = "defense";
309         }
310
311         snprintf(buf, sizeof(buf), "%d–%d | %s | %d passes, %d sec possession",
312                 s.our_score, s.their_score, offense, s.num_passes, s.possession_sec);
313         if (s.stoppage_sec > 0) {
314                 char buf2[256];
315                 snprintf(buf2, sizeof(buf2), "%s (plus %d sec stoppage)", buf, s.stoppage_sec);
316                 ui->status->setText(buf2);
317         } else {
318                 ui->status->setText(buf);
319         }
320 }
321
322 void MainWindow::update_player_buttons(uint64_t t)
323 {
324         QPushButton *buttons[] = {
325                 ui->player_1,
326                 ui->player_2,
327                 ui->player_3,
328                 ui->player_4,
329                 ui->player_5,
330                 ui->player_6,
331                 ui->player_7
332         };
333         const char shortcuts[] = "qweasdf";
334         int num_players = 0;
335         for (int player_id : events->sort_team(events->get_team_at(t))) {
336                 QPushButton *btn = buttons[num_players];
337                 string label = players->get_player_name_by_id(player_id) + " (&" + shortcuts[num_players] + ")";
338                 char shortcut[2] = "";
339                 shortcut[0] = toupper(shortcuts[num_players]);
340                 btn->setText(QString::fromUtf8(label));
341                 btn->setShortcut(QCoreApplication::translate("MainWindow", shortcut, nullptr));
342                 btn->setEnabled(true);
343                 if (++num_players == 7) {
344                         break;
345                 }
346         }
347         for (int i = num_players; i < 7; ++i) {
348                 QPushButton *btn = buttons[i];
349                 btn->setText("No player");
350                 btn->setEnabled(false);
351         }
352 }
353
354 void MainWindow::update_action_buttons(uint64_t t)
355 {
356         {
357                 QItemSelectionModel *select = ui->offensive_formation_view->selectionModel();
358                 if (select->hasSelection()) {
359                         int row = select->selectedRows().front().row();  // Should only be one, due to our selection behavior.
360                         ui->offensive_formation->setEnabled(offensive_formations->get_formation_id(row) != -1);
361                 } else {
362                         ui->offensive_formation->setEnabled(false);
363                 }
364         }
365         {
366                 QItemSelectionModel *select = ui->defensive_formation_view->selectionModel();
367                 if (select->hasSelection()) {
368                         int row = select->selectedRows().front().row();  // Should only be one, due to our selection behavior.
369                         ui->defensive_formation->setEnabled(defensive_formations->get_formation_id(row) != -1);
370                 } else {
371                         ui->defensive_formation->setEnabled(false);
372                 }
373         }
374
375         EventsModel::Status s = events->get_status_at(t);
376
377         bool has_selection = false;
378         bool has_selection_with_player = false;
379
380         QItemSelectionModel *select = ui->event_view->selectionModel();
381         if (select->hasSelection()) {
382                 has_selection = true;
383                 int row = select->selectedRows().front().row();  // Should only be one, due to our selection behavior.
384                 has_selection_with_player = events->get_player_id(row).has_value();
385         }
386         ui->delete_->setEnabled(has_selection);
387
388         if (s.stoppage) {
389                 ui->stoppage->setText("Restart (&v)");
390                 ui->stoppage->setShortcut(QCoreApplication::translate("MainWindow", "V", nullptr));
391                 ui->catch_->setEnabled(false);
392                 ui->throwaway->setEnabled(false);
393                 ui->drop->setEnabled(false);
394                 ui->goal->setEnabled(false);
395                 ui->offensive_soft_plus->setEnabled(false);
396                 ui->offensive_soft_minus->setEnabled(false);
397                 ui->pull->setEnabled(false);
398                 ui->interception->setEnabled(false);
399                 ui->their_throwaway->setEnabled(false);
400                 ui->our_defense->setEnabled(false);
401                 ui->their_goal->setEnabled(false);
402                 ui->defensive_soft_plus->setEnabled(false);
403                 ui->defensive_soft_minus->setEnabled(false);
404                 ui->their_pull->setEnabled(false);
405                 return;
406         } else {
407                 ui->stoppage->setText("Stoppage (&v)");
408                 ui->stoppage->setShortcut(QCoreApplication::translate("MainWindow", "V", nullptr));
409         }
410
411         // Defaults for pull-related buttons.
412         ui->pull->setText("Pull (&p)");
413         ui->their_pull->setText("Their pull (&p)");
414         ui->pull->setShortcut(QCoreApplication::translate("MainWindow", "P", nullptr));
415         ui->their_pull->setShortcut(QCoreApplication::translate("MainWindow", "P", nullptr));
416         ui->throwaway->setText("Throwaway (&t)");
417         ui->throwaway->setShortcut(QCoreApplication::translate("MainWindow", "T", nullptr));
418
419         if (s.pull_state == EventsModel::Status::SHOULD_PULL) {
420                 ui->pull->setEnabled(s.attack_state == EventsModel::Status::DEFENSE && has_selection_with_player);
421                 ui->their_pull->setEnabled(s.attack_state == EventsModel::Status::OFFENSE);
422
423                 ui->catch_->setEnabled(false);
424                 ui->throwaway->setEnabled(false);
425                 ui->drop->setEnabled(false);
426                 ui->goal->setEnabled(false);
427                 ui->offensive_soft_plus->setEnabled(false);
428                 ui->offensive_soft_minus->setEnabled(false);
429                 ui->interception->setEnabled(false);
430                 ui->their_throwaway->setEnabled(false);
431                 ui->our_defense->setEnabled(false);
432                 ui->their_goal->setEnabled(false);
433                 ui->defensive_soft_plus->setEnabled(false);
434                 ui->defensive_soft_minus->setEnabled(false);
435                 return;
436         }
437         if (s.pull_state == EventsModel::Status::PULL_IN_AIR) {
438                 if (s.attack_state == EventsModel::Status::DEFENSE) {
439                         ui->pull->setText("Pull landed (&p)");
440                         ui->pull->setShortcut(QCoreApplication::translate("MainWindow", "P", nullptr));
441                         ui->pull->setEnabled(true);
442
443                         ui->throwaway->setText("Pull OOB (&t)");
444                         ui->throwaway->setShortcut(QCoreApplication::translate("MainWindow", "T", nullptr));
445                         ui->throwaway->setEnabled(true);
446                 } else {
447                         ui->pull->setEnabled(false);
448                         ui->throwaway->setEnabled(false);
449                 }
450                 ui->their_pull->setEnabled(false);  // We don't track their pull landings; only by means of catch etc.
451
452                 ui->catch_->setEnabled(false);
453                 ui->drop->setEnabled(false);
454                 ui->goal->setEnabled(false);
455                 ui->offensive_soft_plus->setEnabled(false);
456                 ui->offensive_soft_minus->setEnabled(false);
457                 ui->interception->setEnabled(false);
458                 ui->their_throwaway->setEnabled(false);
459                 ui->our_defense->setEnabled(false);
460                 ui->their_goal->setEnabled(false);
461                 ui->defensive_soft_plus->setEnabled(false);
462                 ui->defensive_soft_minus->setEnabled(false);
463                 return;
464         }
465
466         ui->catch_->setEnabled(s.attack_state == EventsModel::Status::OFFENSE && has_selection_with_player);
467         ui->throwaway->setEnabled(s.attack_state == EventsModel::Status::OFFENSE && has_selection_with_player);
468         ui->drop->setEnabled(s.attack_state == EventsModel::Status::OFFENSE && has_selection_with_player);
469         ui->goal->setEnabled(s.attack_state == EventsModel::Status::OFFENSE && has_selection_with_player);
470         ui->offensive_soft_plus->setEnabled(s.attack_state == EventsModel::Status::OFFENSE && has_selection_with_player);
471         ui->offensive_soft_minus->setEnabled(s.attack_state == EventsModel::Status::OFFENSE && has_selection_with_player);
472         ui->pull->setEnabled(false);
473
474         ui->interception->setEnabled(s.attack_state == EventsModel::Status::DEFENSE && has_selection_with_player);
475         ui->their_throwaway->setEnabled(s.attack_state == EventsModel::Status::DEFENSE);
476         ui->our_defense->setEnabled(s.attack_state == EventsModel::Status::DEFENSE && has_selection_with_player);
477         ui->their_goal->setEnabled(s.attack_state == EventsModel::Status::DEFENSE);
478         ui->defensive_soft_plus->setEnabled(s.attack_state == EventsModel::Status::DEFENSE && has_selection_with_player);
479         ui->defensive_soft_minus->setEnabled(s.attack_state == EventsModel::Status::DEFENSE && has_selection_with_player);
480         ui->their_pull->setEnabled(false);
481 }
482
483 void MainWindow::formation_double_clicked(bool offense, unsigned row)
484 {
485         FormationsModel *formations = offense ? offensive_formations : defensive_formations;
486         int id = formations->get_formation_id(row);
487         if (id == -1) {  // “Add new” clicked.
488                 bool ok;
489                 QString new_formation_str = QInputDialog::getText(this, "New formation", "Choose name for new formation:", QLineEdit::Normal, "", &ok);
490                 if (!ok || new_formation_str.isEmpty()) {
491                         return;
492                 }
493
494                 id = formations->insert_new(new_formation_str.toStdString());
495                 QListView *view = offense ? ui->offensive_formation_view : ui->defensive_formation_view;
496                 view->selectionModel()->select(formations->index(formations->get_row_from_id(id), 0), QItemSelectionModel::ClearAndSelect);
497                 events->inserted_new_formation(id, new_formation_str.toStdString());
498         } else {
499                 events->set_formation_at(video->position(), offense, id);
500         }
501 }
502
503 sqlite3 *open_db(const char *filename)
504 {
505         sqlite3 *db;
506         int ret = sqlite3_open(filename, &db);
507         if (ret != SQLITE_OK) {
508                 fprintf(stderr, "%s: %s\n", filename, sqlite3_errmsg(db));
509                 exit(1);
510         }
511
512         sqlite3_exec(db, R"(
513                 CREATE TABLE IF NOT EXISTS player (player INTEGER PRIMARY KEY, number VARCHAR, name VARCHAR, gender VARCHAR(1));
514         )", nullptr, nullptr, nullptr);  // Ignore errors.
515
516         sqlite3_exec(db, R"(
517                 CREATE TABLE IF NOT EXISTS match (match INTEGER PRIMARY KEY, description VARCHAR);
518         )", nullptr, nullptr, nullptr);  // Ignore errors.
519
520         sqlite3_exec(db, R"(
521                 CREATE TABLE IF NOT EXISTS formation (formation INTEGER PRIMARY KEY, name VARCHAR, offense BOOLEAN NOT NULL);
522         )", nullptr, nullptr, nullptr);  // Ignore errors.
523
524         sqlite3_exec(db, R"(
525                 CREATE TABLE IF NOT EXISTS event (event INTEGER PRIMARY KEY, match INTEGER, t INTEGER, player INTEGER, type VARCHAR, formation INTEGER, FOREIGN KEY (player) REFERENCES player(player), FOREIGN KEY (match) REFERENCES match (match), FOREIGN KEY (formation) REFERENCES formation (formation));
526         )", nullptr, nullptr, nullptr);  // Ignore errors.
527
528         sqlite3_exec(db, "PRAGMA journal_mode=WAL", nullptr, nullptr, nullptr);  // Ignore errors.
529         sqlite3_exec(db, "PRAGMA synchronous=NORMAL", nullptr, nullptr, nullptr);  // Ignore errors.
530         sqlite3_exec(db, "PRAGMA foreign_keys=ON", nullptr, nullptr, nullptr);  // Ignore errors.
531         return db;
532 }
533
534 int get_match_id(sqlite3 *db, QWidget *parent, int requested_match)
535 {
536         QStringList items;
537         vector<int> ids;
538         bool requested_match_ok = false;
539
540         // Read the list of matches already in the database.
541         sqlite3_stmt *stmt;
542         int ret = sqlite3_prepare_v2(db, "SELECT match, description FROM match ORDER BY match", -1, &stmt, 0);
543         if (ret != SQLITE_OK) {
544                 fprintf(stderr, "SELECT prepare: %s\n", sqlite3_errmsg(db));
545                 abort();
546         }
547         for ( ;; ) {
548                 ret = sqlite3_step(stmt);
549                 if (ret == SQLITE_ROW) {
550                         char buf[256];
551                         snprintf(buf, sizeof(buf), "%s (%d)", sqlite3_column_text(stmt, 1), sqlite3_column_int(stmt, 0));
552                         ids.push_back(sqlite3_column_int(stmt, 0));
553                         if (ids.back() == requested_match) {
554                                 requested_match_ok = true;
555                         }
556                         items.push_back(buf);
557                 } else if (ret == SQLITE_DONE) {
558                         break;
559                 } else {
560                         fprintf(stderr, "SELECT step: %s\n", sqlite3_errmsg(db));
561                         abort();
562                 }
563         }
564         ret = sqlite3_finalize(stmt);
565         if (ret != SQLITE_OK) {
566                 fprintf(stderr, "SELECT finalize: %s\n", sqlite3_errmsg(db));
567                 abort();
568         }
569         items.push_back("Add new…");
570
571         if (requested_match_ok) {
572                 return requested_match;
573         }
574
575         QString chosen_str;
576         {
577                 QInputDialog dialog(parent, Qt::WindowFlags());
578                 dialog.setWindowTitle("Open game");
579                 dialog.setLabelText("Choose game to analyze:");
580                 dialog.setComboBoxItems(items);
581                 dialog.setTextValue(items[items.size() - 2]);
582                 dialog.setOption(QInputDialog::UseListViewForComboBoxItems, true);
583                 if (!dialog.exec()) {
584                         return -1;
585                 }
586                 chosen_str = dialog.textValue();
587         }
588
589         for (unsigned i = 0; i < ids.size(); ++i) {
590                 if (chosen_str == items[i]) {
591                         return ids[i];
592                 }
593         }
594
595         // Must be a new game. Get its name and insert it into the database.
596         bool ok;
597         QString new_game_str = QInputDialog::getText(parent, "New game", "Choose name for new game:", QLineEdit::Normal, "", &ok);
598         if (!ok || new_game_str.isEmpty()) {
599                 return -1;
600         }
601
602         // Insert the new row into the database.
603         ret = sqlite3_prepare_v2(db, "INSERT INTO match (description) VALUES (?)", -1, &stmt, 0);
604         if (ret != SQLITE_OK) {
605                 fprintf(stderr, "INSERT prepare: %s\n", sqlite3_errmsg(db));
606                 abort();
607         }
608
609         QByteArray new_game_utf8 = new_game_str.toUtf8();
610         sqlite3_bind_text(stmt, 1, (const char *)new_game_utf8.data(), new_game_utf8.size(), SQLITE_STATIC);
611
612         ret = sqlite3_step(stmt);
613         if (ret == SQLITE_ROW) {
614                 fprintf(stderr, "INSERT step: %s\n", sqlite3_errmsg(db));
615                 abort();
616         }
617
618         ret = sqlite3_finalize(stmt);
619         if (ret != SQLITE_OK) {
620                 fprintf(stderr, "INSERT finalize: %s\n", sqlite3_errmsg(db));
621                 abort();
622         }
623
624         return sqlite3_last_insert_rowid(db);
625 }
626
627 int main(int argc, char *argv[])
628 {
629         QApplication app(argc, argv);
630         sqlite3 *db = open_db("ultimate.db");
631
632         // TODO: do this on-demand instead, from a menu
633         export_to_json(db, "ultimate.json");
634
635         int requested_match = -1;
636         if (argc >= 2) {
637                 requested_match = atoi(argv[1]);
638         }
639
640         int match_id = get_match_id(db, nullptr, requested_match);
641         if (match_id <= 0) {  // Cancel.
642                 return 0;
643         }
644
645         MainWindow mainWindow(new EventsModel(db, match_id), new PlayersModel(db),
646                               new FormationsModel(db, true), new FormationsModel(db, false));
647         mainWindow.resize(QSize(1280, 720));
648         mainWindow.show();
649
650         return app.exec();
651
652 }