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