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