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