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