]> git.sesse.net Git - nageru/blob - futatabi/mainwindow.cpp
Add basic MIDI input support (jog, cue in/out, play, camera switch) to Futatabi....
[nageru] / futatabi / mainwindow.cpp
1 #include "mainwindow.h"
2
3 #include "clip_list.h"
4 #include "export.h"
5 #include "flags.h"
6 #include "frame_on_disk.h"
7 #include "player.h"
8 #include "futatabi_midi_mapping.pb.h"
9 #include "shared/aboutdialog.h"
10 #include "shared/disk_space_estimator.h"
11 #include "shared/post_to_main_thread.h"
12 #include "shared/timebase.h"
13 #include "ui_mainwindow.h"
14
15 #include <QDesktopServices>
16 #include <QFileDialog>
17 #include <QMessageBox>
18 #include <QMouseEvent>
19 #include <QNetworkReply>
20 #include <QShortcut>
21 #include <QTimer>
22 #include <QWheelEvent>
23 #include <future>
24 #include <sqlite3.h>
25 #include <string>
26 #include <vector>
27
28 using namespace std;
29 using namespace std::placeholders;
30
31 MainWindow *global_mainwindow = nullptr;
32 static ClipList *cliplist_clips;
33 static PlayList *playlist_clips;
34
35 extern int64_t current_pts;
36
37 namespace {
38
39 void set_pts_in(int64_t pts, int64_t current_pts, ClipProxy &clip)
40 {
41         pts = std::max<int64_t>(pts, 0);
42         if (clip->pts_out == -1) {
43                 pts = std::min(pts, current_pts);
44         } else {
45                 pts = std::min(pts, clip->pts_out);
46         }
47         clip->pts_in = pts;
48 }
49
50 }  // namespace
51
52 MainWindow::MainWindow()
53         : ui(new Ui::MainWindow),
54           db(global_flags.working_directory + "/futatabi.db"),
55           midi_mapper(this)
56 {
57         global_mainwindow = this;
58         ui->setupUi(this);
59
60         // Load settings from database.
61         SettingsProto settings = db.get_settings();
62         if (!global_flags.interpolation_quality_set) {
63                 if (settings.interpolation_quality() != 0) {
64                         global_flags.interpolation_quality = settings.interpolation_quality() - 1;
65                 }
66         }
67         if (!global_flags.cue_point_padding_set) {
68                 global_flags.cue_point_padding_seconds = settings.cue_point_padding_seconds();  // Default 0 is fine.
69         }
70         if (global_flags.interpolation_quality == 0) {
71                 // Allocate something just for simplicity; we won't be using it
72                 // unless the user changes runtime, in which case 1 is fine.
73                 flow_initialized_interpolation_quality = 1;
74         } else {
75                 flow_initialized_interpolation_quality = global_flags.interpolation_quality;
76         }
77         save_settings();
78
79         // The menus.
80         connect(ui->exit_action, &QAction::triggered, this, &MainWindow::exit_triggered);
81         connect(ui->export_cliplist_clip_multitrack_action, &QAction::triggered, this, &MainWindow::export_cliplist_clip_multitrack_triggered);
82         connect(ui->export_playlist_clip_interpolated_action, &QAction::triggered, this, &MainWindow::export_playlist_clip_interpolated_triggered);
83         connect(ui->manual_action, &QAction::triggered, this, &MainWindow::manual_triggered);
84         connect(ui->about_action, &QAction::triggered, this, &MainWindow::about_triggered);
85         connect(ui->undo_action, &QAction::triggered, this, &MainWindow::undo_triggered);
86         connect(ui->redo_action, &QAction::triggered, this, &MainWindow::redo_triggered);
87         ui->undo_action->setEnabled(false);
88         ui->redo_action->setEnabled(false);
89
90         // The quality group.
91         QActionGroup *quality_group = new QActionGroup(ui->interpolation_menu);
92         quality_group->addAction(ui->quality_0_action);
93         quality_group->addAction(ui->quality_1_action);
94         quality_group->addAction(ui->quality_2_action);
95         quality_group->addAction(ui->quality_3_action);
96         quality_group->addAction(ui->quality_4_action);
97         if (global_flags.interpolation_quality == 0) {
98                 ui->quality_0_action->setChecked(true);
99         } else if (global_flags.interpolation_quality == 1) {
100                 ui->quality_1_action->setChecked(true);
101         } else if (global_flags.interpolation_quality == 2) {
102                 ui->quality_2_action->setChecked(true);
103         } else if (global_flags.interpolation_quality == 3) {
104                 ui->quality_3_action->setChecked(true);
105         } else if (global_flags.interpolation_quality == 4) {
106                 ui->quality_4_action->setChecked(true);
107         } else {
108                 assert(false);
109         }
110         connect(ui->quality_0_action, &QAction::toggled, bind(&MainWindow::quality_toggled, this, 0, _1));
111         connect(ui->quality_1_action, &QAction::toggled, bind(&MainWindow::quality_toggled, this, 1, _1));
112         connect(ui->quality_2_action, &QAction::toggled, bind(&MainWindow::quality_toggled, this, 2, _1));
113         connect(ui->quality_3_action, &QAction::toggled, bind(&MainWindow::quality_toggled, this, 3, _1));
114         connect(ui->quality_4_action, &QAction::toggled, bind(&MainWindow::quality_toggled, this, 4, _1));
115
116         // The cue point padding group.
117         QActionGroup *padding_group = new QActionGroup(ui->interpolation_menu);
118         padding_group->addAction(ui->padding_0_action);
119         padding_group->addAction(ui->padding_1_action);
120         padding_group->addAction(ui->padding_2_action);
121         padding_group->addAction(ui->padding_5_action);
122         if (global_flags.cue_point_padding_seconds <= 1e-3) {
123                 ui->padding_0_action->setChecked(true);
124         } else if (fabs(global_flags.cue_point_padding_seconds - 1.0) < 1e-3) {
125                 ui->padding_1_action->setChecked(true);
126         } else if (fabs(global_flags.cue_point_padding_seconds - 2.0) < 1e-3) {
127                 ui->padding_2_action->setChecked(true);
128         } else if (fabs(global_flags.cue_point_padding_seconds - 5.0) < 1e-3) {
129                 ui->padding_5_action->setChecked(true);
130         } else {
131                 // Nothing to check, which is fine.
132         }
133         connect(ui->padding_0_action, &QAction::toggled, bind(&MainWindow::padding_toggled, this, 0.0, _1));
134         connect(ui->padding_1_action, &QAction::toggled, bind(&MainWindow::padding_toggled, this, 1.0, _1));
135         connect(ui->padding_2_action, &QAction::toggled, bind(&MainWindow::padding_toggled, this, 2.0, _1));
136         connect(ui->padding_5_action, &QAction::toggled, bind(&MainWindow::padding_toggled, this, 5.0, _1));
137
138         global_disk_space_estimator = new DiskSpaceEstimator(bind(&MainWindow::report_disk_space, this, _1, _2));
139         disk_free_label = new QLabel(this);
140         disk_free_label->setStyleSheet("QLabel {padding-right: 5px;}");
141         ui->menuBar->setCornerWidget(disk_free_label);
142
143         StateProto state = db.get_state();
144         undo_stack.push_back(state);  // The undo stack always has the current state on top.
145
146         cliplist_clips = new ClipList(state.clip_list());
147         ui->clip_list->setModel(cliplist_clips);
148         connect(cliplist_clips, &ClipList::any_content_changed, this, &MainWindow::content_changed);
149
150         playlist_clips = new PlayList(state.play_list());
151         ui->playlist->setModel(playlist_clips);
152         connect(playlist_clips, &PlayList::any_content_changed, this, &MainWindow::content_changed);
153
154         // For un-highlighting when we lose focus.
155         ui->clip_list->installEventFilter(this);
156
157         // For scrubbing in the pts columns.
158         ui->clip_list->viewport()->installEventFilter(this);
159         ui->playlist->viewport()->installEventFilter(this);
160
161         QShortcut *cue_in = new QShortcut(QKeySequence(Qt::Key_A), this);
162         connect(cue_in, &QShortcut::activated, ui->cue_in_btn, &QPushButton::click);
163         connect(ui->cue_in_btn, &QPushButton::clicked, this, &MainWindow::cue_in_clicked);
164
165         QShortcut *cue_out = new QShortcut(QKeySequence(Qt::Key_S), this);
166         connect(cue_out, &QShortcut::activated, ui->cue_out_btn, &QPushButton::click);
167         connect(ui->cue_out_btn, &QPushButton::clicked, this, &MainWindow::cue_out_clicked);
168
169         QShortcut *queue = new QShortcut(QKeySequence(Qt::Key_Q), this);
170         connect(queue, &QShortcut::activated, ui->queue_btn, &QPushButton::click);
171         connect(ui->queue_btn, &QPushButton::clicked, this, &MainWindow::queue_clicked);
172
173         QShortcut *preview = new QShortcut(QKeySequence(Qt::Key_W), this);
174         connect(preview, &QShortcut::activated, ui->preview_btn, &QPushButton::click);
175         connect(ui->preview_btn, &QPushButton::clicked, this, &MainWindow::preview_clicked);
176
177         QShortcut *play = new QShortcut(QKeySequence(Qt::Key_Space), this);
178         connect(play, &QShortcut::activated, ui->play_btn, &QPushButton::click);
179         connect(ui->play_btn, &QPushButton::clicked, this, &MainWindow::play_clicked);
180
181         connect(ui->stop_btn, &QPushButton::clicked, this, &MainWindow::stop_clicked);
182         ui->stop_btn->setEnabled(false);
183
184         connect(ui->playlist_duplicate_btn, &QPushButton::clicked, this, &MainWindow::playlist_duplicate);
185
186         connect(ui->playlist_remove_btn, &QPushButton::clicked, this, &MainWindow::playlist_remove);
187         QShortcut *delete_key = new QShortcut(QKeySequence(Qt::Key_Delete), ui->playlist);
188         connect(delete_key, &QShortcut::activated, [this] {
189                 if (ui->playlist->hasFocus()) {
190                         playlist_remove();
191                 }
192         });
193
194         // TODO: support drag-and-drop.
195         connect(ui->playlist_move_up_btn, &QPushButton::clicked, [this] { playlist_move(-1); });
196         connect(ui->playlist_move_down_btn, &QPushButton::clicked, [this] { playlist_move(1); });
197
198         connect(ui->playlist->selectionModel(), &QItemSelectionModel::selectionChanged,
199                 this, &MainWindow::playlist_selection_changed);
200         playlist_selection_changed();  // First time set-up.
201
202         preview_player.reset(new Player(ui->preview_display, Player::NO_STREAM_OUTPUT));
203         live_player.reset(new Player(ui->live_display, Player::HTTPD_STREAM_OUTPUT));
204         live_player->set_done_callback([this] {
205                 post_to_main_thread([this] {
206                         live_player_done();
207                 });
208         });
209         live_player->set_progress_callback([this](const map<uint64_t, double> &progress, double time_remaining) {
210                 post_to_main_thread([this, progress, time_remaining] {
211                         live_player_clip_progress(progress, time_remaining);
212                 });
213         });
214         set_output_status("paused");
215         enable_or_disable_queue_button();
216
217         defer_timeout = new QTimer(this);
218         defer_timeout->setSingleShot(true);
219         connect(defer_timeout, &QTimer::timeout, this, &MainWindow::defer_timer_expired);
220         ui->undo_action->setEnabled(true);
221
222         connect(ui->clip_list->selectionModel(), &QItemSelectionModel::currentChanged,
223                 this, &MainWindow::clip_list_selection_changed);
224         enable_or_disable_queue_button();
225
226         // Find out how many cameras we have in the existing frames;
227         // if none, we start with two cameras.
228         num_cameras = 2;
229         {
230                 lock_guard<mutex> lock(frame_mu);
231                 for (size_t stream_idx = 2; stream_idx < MAX_STREAMS; ++stream_idx) {
232                         if (!frames[stream_idx].empty()) {
233                                 num_cameras = stream_idx + 1;
234                         }
235                 }
236         }
237         change_num_cameras();
238
239         if (!global_flags.tally_url.empty()) {
240                 start_tally();
241         }
242
243         if (!global_flags.midi_mapping_filename.empty()) {
244                 MIDIMappingProto midi_mapping;
245                 if (!load_midi_mapping_from_file(global_flags.midi_mapping_filename, &midi_mapping)) {
246                         fprintf(stderr, "Couldn't load MIDI mapping '%s'; exiting.\n",
247                                 global_flags.midi_mapping_filename.c_str());
248                         exit(1);
249                 }
250                 midi_mapper.set_midi_mapping(midi_mapping);
251         }
252         midi_mapper.refresh_lights();
253         midi_mapper.start_thread();
254 }
255
256 void MainWindow::change_num_cameras()
257 {
258         assert(num_cameras >= displays.size());  // We only add, never remove.
259
260         // Make new display rows.
261         unsigned display_rows = (num_cameras + 1) / 2;
262         ui->video_displays->setStretch(1, display_rows);
263         for (unsigned i = displays.size(); i < num_cameras; ++i) {
264                 QFrame *frame = new QFrame(this);
265                 frame->setAutoFillBackground(true);
266
267                 QLayout *layout = new QGridLayout(frame);
268                 frame->setLayout(layout);
269                 layout->setContentsMargins(3, 3, 3, 3);
270
271                 JPEGFrameView *display = new JPEGFrameView(frame);
272                 display->setAutoFillBackground(true);
273                 layout->addWidget(display);
274
275                 ui->input_displays->addWidget(frame, i / 2, i % 2);
276                 display->set_overlay(to_string(i + 1));
277
278                 QPushButton *preview_btn = new QPushButton(this);
279                 preview_btn->setMaximumSize(20, 17);
280                 preview_btn->setText(QString::fromStdString(to_string(i + 1)));
281                 ui->preview_layout->addWidget(preview_btn);
282
283                 displays.emplace_back(FrameAndDisplay{ frame, display, preview_btn });
284
285                 connect(display, &JPEGFrameView::clicked, preview_btn, &QPushButton::click);
286                 QShortcut *shortcut = new QShortcut(QKeySequence(Qt::Key_1 + i), this);
287                 connect(shortcut, &QShortcut::activated, preview_btn, &QPushButton::click);
288
289                 connect(preview_btn, &QPushButton::clicked, [this, i] { preview_angle_clicked(i); });
290         }
291
292         cliplist_clips->change_num_cameras(num_cameras);
293         playlist_clips->change_num_cameras(num_cameras);
294
295         QMetaObject::invokeMethod(this, "relayout", Qt::QueuedConnection);
296 }
297
298 MainWindow::~MainWindow()
299 {
300         // Empty so that we can forward-declare Player in the .h file.
301 }
302
303 void MainWindow::cue_in_clicked()
304 {
305         if (!cliplist_clips->empty() && cliplist_clips->back()->pts_out < 0) {
306                 cliplist_clips->mutable_back()->pts_in = current_pts;
307         } else {
308                 Clip clip;
309                 clip.pts_in = max<int64_t>(current_pts - lrint(global_flags.cue_point_padding_seconds * TIMEBASE), 0);
310                 cliplist_clips->add_clip(clip);
311                 playlist_selection_changed();
312         }
313
314         // Select the item so that we can jog it.
315         ui->clip_list->setFocus();
316         QModelIndex index = cliplist_clips->index(cliplist_clips->size() - 1, int(ClipList::Column::IN));
317         ui->clip_list->selectionModel()->setCurrentIndex(index, QItemSelectionModel::ClearAndSelect);
318         ui->clip_list->scrollToBottom();
319         enable_or_disable_queue_button();
320 }
321
322 void MainWindow::cue_out_clicked()
323 {
324         if (cliplist_clips->empty()) {
325                 return;
326         }
327
328         cliplist_clips->mutable_back()->pts_out = current_pts + lrint(global_flags.cue_point_padding_seconds * TIMEBASE);
329
330         // Select the item so that we can jog it.
331         ui->clip_list->setFocus();
332         QModelIndex index = cliplist_clips->index(cliplist_clips->size() - 1, int(ClipList::Column::OUT));
333         ui->clip_list->selectionModel()->setCurrentIndex(index, QItemSelectionModel::ClearAndSelect);
334         ui->clip_list->scrollToBottom();
335         enable_or_disable_queue_button();
336 }
337
338 void MainWindow::queue_clicked()
339 {
340         // See also enable_or_disable_queue_button().
341
342         if (cliplist_clips->empty()) {
343                 return;
344         }
345
346         QItemSelectionModel *selected = ui->clip_list->selectionModel();
347         if (!selected->hasSelection()) {
348                 Clip clip = *cliplist_clips->back();
349                 clip.stream_idx = 0;
350                 if (clip.pts_out != -1) {
351                         playlist_clips->add_clip(clip);
352                         playlist_selection_changed();
353                         ui->playlist->scrollToBottom();
354                 }
355                 return;
356         }
357
358         QModelIndex index = selected->currentIndex();
359         Clip clip = *cliplist_clips->clip(index.row());
360         if (cliplist_clips->is_camera_column(index.column())) {
361                 clip.stream_idx = index.column() - int(ClipList::Column::CAMERA_1);
362         } else {
363                 clip.stream_idx = ui->preview_display->get_stream_idx();
364         }
365
366         if (clip.pts_out != -1) {
367                 playlist_clips->add_clip(clip);
368                 playlist_selection_changed();
369                 ui->playlist->scrollToBottom();
370                 if (!ui->playlist->selectionModel()->hasSelection()) {
371                         // TODO: Figure out why this doesn't always seem to actually select the row.
372                         QModelIndex bottom = playlist_clips->index(playlist_clips->size() - 1, 0);
373                         ui->playlist->setCurrentIndex(bottom);
374                 }
375         }
376 }
377
378 void MainWindow::preview_clicked()
379 {
380         // See also enable_or_disable_preview_button().
381
382         if (ui->playlist->hasFocus()) {
383                 // Allow the playlist as preview iff it has focus and something is selected.
384                 QItemSelectionModel *selected = ui->playlist->selectionModel();
385                 if (selected->hasSelection()) {
386                         QModelIndex index = selected->currentIndex();
387                         const Clip &clip = *playlist_clips->clip(index.row());
388                         preview_player->play(clip);
389                         return;
390                 }
391         }
392
393         if (cliplist_clips->empty())
394                 return;
395
396         QItemSelectionModel *selected = ui->clip_list->selectionModel();
397         if (!selected->hasSelection()) {
398                 preview_player->play(*cliplist_clips->back());
399                 return;
400         }
401
402         QModelIndex index = selected->currentIndex();
403         Clip clip = *cliplist_clips->clip(index.row());
404         if (cliplist_clips->is_camera_column(index.column())) {
405                 clip.stream_idx = index.column() - int(ClipList::Column::CAMERA_1);
406         } else {
407                 clip.stream_idx = ui->preview_display->get_stream_idx();
408         }
409         preview_player->play(clip);
410 }
411
412 void MainWindow::preview_angle_clicked(unsigned stream_idx)
413 {
414         preview_player->override_angle(stream_idx);
415
416         // Change the selection if we were previewing a clip from the clip list.
417         // (The only other thing we could be showing is a pts scrub, and if so,
418         // that would be selected.)
419         QItemSelectionModel *selected = ui->clip_list->selectionModel();
420         if (selected->hasSelection()) {
421                 QModelIndex cell = selected->selectedIndexes()[0];
422                 int column = int(ClipList::Column::CAMERA_1) + stream_idx;
423                 selected->setCurrentIndex(cell.sibling(cell.row(), column), QItemSelectionModel::ClearAndSelect);
424         }
425 }
426
427 void MainWindow::playlist_duplicate()
428 {
429         QItemSelectionModel *selected = ui->playlist->selectionModel();
430         if (!selected->hasSelection()) {
431                 // Should have been grayed out, but OK.
432                 return;
433         }
434         QModelIndexList rows = selected->selectedRows();
435         int first = rows.front().row(), last = rows.back().row();
436         playlist_clips->duplicate_clips(first, last);
437         playlist_selection_changed();
438 }
439
440 void MainWindow::playlist_remove()
441 {
442         QItemSelectionModel *selected = ui->playlist->selectionModel();
443         if (!selected->hasSelection()) {
444                 // Should have been grayed out, but OK.
445                 return;
446         }
447         QModelIndexList rows = selected->selectedRows();
448         int first = rows.front().row(), last = rows.back().row();
449         playlist_clips->erase_clips(first, last);
450
451         // TODO: select the next one in the list?
452
453         playlist_selection_changed();
454 }
455
456 void MainWindow::playlist_move(int delta)
457 {
458         QItemSelectionModel *selected = ui->playlist->selectionModel();
459         if (!selected->hasSelection()) {
460                 // Should have been grayed out, but OK.
461                 return;
462         }
463
464         QModelIndexList rows = selected->selectedRows();
465         int first = rows.front().row(), last = rows.back().row();
466         if ((delta == -1 && first == 0) ||
467             (delta == 1 && size_t(last) == playlist_clips->size() - 1)) {
468                 // Should have been grayed out, but OK.
469                 return;
470         }
471
472         playlist_clips->move_clips(first, last, delta);
473         playlist_selection_changed();
474 }
475
476 void MainWindow::jog_internal(JogDestination jog_destination, int row, int column, int stream_idx, int pts_delta)
477 {
478         constexpr int camera_pts_per_pixel = 1500;  // One click of most mice (15 degrees), multiplied by the default wheel_sensitivity.
479
480         int in_column, out_column, camera_column;
481         if (jog_destination == JOG_CLIP_LIST) {
482                 in_column = int(ClipList::Column::IN);
483                 out_column = int(ClipList::Column::OUT);
484                 camera_column = -1;
485         } else if (jog_destination == JOG_PLAYLIST) {
486                 in_column = int(PlayList::Column::IN);
487                 out_column = int(PlayList::Column::OUT);
488                 camera_column = int(PlayList::Column::CAMERA);
489         } else {
490                 assert(false);
491         }
492
493         currently_deferring_model_changes = true;
494         {
495                 current_change_id = (jog_destination == JOG_CLIP_LIST) ? "cliplist:" : "playlist:";
496                 ClipProxy clip = (jog_destination == JOG_CLIP_LIST) ? cliplist_clips->mutable_clip(row) : playlist_clips->mutable_clip(row);
497                 if (jog_destination == JOG_PLAYLIST) {
498                         stream_idx = clip->stream_idx;
499                 }
500
501                 if (column == in_column) {
502                         current_change_id += "in:" + to_string(row);
503                         int64_t pts = clip->pts_in + pts_delta;
504                         set_pts_in(pts, current_pts, clip);
505                         preview_single_frame(pts, stream_idx, FIRST_AT_OR_AFTER);
506                 } else if (column == out_column) {
507                         current_change_id += "out:" + to_string(row);
508                         int64_t pts = clip->pts_out + pts_delta;
509                         pts = std::max(pts, clip->pts_in);
510                         pts = std::min(pts, current_pts);
511                         clip->pts_out = pts;
512                         preview_single_frame(pts, stream_idx, LAST_BEFORE);
513                 } else if (column == camera_column) {
514                         current_change_id += "camera:" + to_string(row);
515                         int angle_degrees = pts_delta;
516                         if (last_mousewheel_camera_row == row) {
517                                 angle_degrees += leftover_angle_degrees;
518                         }
519
520                         int stream_idx = clip->stream_idx + angle_degrees / camera_pts_per_pixel;
521                         stream_idx = std::max(stream_idx, 0);
522                         stream_idx = std::min<int>(stream_idx, num_cameras - 1);
523                         clip->stream_idx = stream_idx;
524
525                         last_mousewheel_camera_row = row;
526                         leftover_angle_degrees = angle_degrees % camera_pts_per_pixel;
527
528                         // Don't update the live view, that's rarely what the operator wants.
529                 }
530         }
531         currently_deferring_model_changes = false;
532 }
533
534 void MainWindow::defer_timer_expired()
535 {
536         state_changed(deferred_state);
537 }
538
539 void MainWindow::content_changed()
540 {
541         // If we are playing, update the part of the playlist that's not playing yet.
542         vector<ClipWithID> clips;
543         for (unsigned row = 0; row < playlist_clips->size(); ++row) {
544                 clips.emplace_back(*playlist_clips->clip_with_id(row));
545         }
546         live_player->splice_play(clips);
547
548         // Serialize the state.
549         if (defer_timeout->isActive() &&
550             (!currently_deferring_model_changes || deferred_change_id != current_change_id)) {
551                 // There's some deferred event waiting, but this event is unrelated.
552                 // So it's time to short-circuit that timer and do the work it wanted to do.
553                 defer_timeout->stop();
554                 state_changed(deferred_state);
555         }
556         StateProto state;
557         *state.mutable_clip_list() = cliplist_clips->serialize();
558         *state.mutable_play_list() = playlist_clips->serialize();
559         if (currently_deferring_model_changes) {
560                 deferred_change_id = current_change_id;
561                 deferred_state = std::move(state);
562                 defer_timeout->start(200);
563                 return;
564         }
565         state_changed(state);
566 }
567
568 void MainWindow::state_changed(const StateProto &state)
569 {
570         db.store_state(state);
571
572         redo_stack.clear();
573         ui->redo_action->setEnabled(false);
574
575         undo_stack.push_back(state);
576         ui->undo_action->setEnabled(undo_stack.size() > 1);
577
578         // Make sure it doesn't grow without bounds.
579         while (undo_stack.size() >= 100) {
580                 undo_stack.pop_front();
581         }
582 }
583
584 void MainWindow::save_settings()
585 {
586         SettingsProto settings;
587         settings.set_interpolation_quality(global_flags.interpolation_quality + 1);
588         settings.set_cue_point_padding_seconds(global_flags.cue_point_padding_seconds);
589         db.store_settings(settings);
590 }
591
592 void MainWindow::play_clicked()
593 {
594         if (playlist_clips->empty())
595                 return;
596
597         QItemSelectionModel *selected = ui->playlist->selectionModel();
598         unsigned start_row;
599         if (!selected->hasSelection()) {
600                 start_row = 0;
601         } else {
602                 start_row = selected->selectedRows(0)[0].row();
603         }
604
605         vector<ClipWithID> clips;
606         for (unsigned row = start_row; row < playlist_clips->size(); ++row) {
607                 clips.emplace_back(*playlist_clips->clip_with_id(row));
608         }
609         live_player->play(clips);
610         playlist_clips->set_progress({ { start_row, 0.0f } });
611         ui->playlist->selectionModel()->clear();
612         playlist_selection_changed();
613
614         ui->stop_btn->setEnabled(true);
615 }
616
617 void MainWindow::stop_clicked()
618 {
619         Clip fake_clip;
620         fake_clip.pts_in = 0;
621         fake_clip.pts_out = 0;
622         playlist_clips->set_progress({});
623         live_player->play(fake_clip);
624         ui->stop_btn->setEnabled(false);
625 }
626
627 void MainWindow::live_player_done()
628 {
629         playlist_selection_changed();
630         playlist_clips->set_progress({});
631         ui->stop_btn->setEnabled(false);
632 }
633
634 void MainWindow::live_player_clip_progress(const map<uint64_t, double> &progress, double time_remaining)
635 {
636         playlist_clips->set_progress(progress);
637         set_output_status(format_duration(time_remaining) + " left");
638 }
639
640 void MainWindow::resizeEvent(QResizeEvent *event)
641 {
642         QMainWindow::resizeEvent(event);
643
644         // Ask for a relayout, but only after the event loop is done doing relayout
645         // on everything else.
646         QMetaObject::invokeMethod(this, "relayout", Qt::QueuedConnection);
647 }
648
649 void MainWindow::relayout()
650 {
651         ui->live_display->setMinimumWidth(ui->live_display->height() * 16 / 9);
652         ui->preview_display->setMinimumWidth(ui->preview_display->height() * 16 / 9);
653 }
654
655 bool MainWindow::eventFilter(QObject *watched, QEvent *event)
656 {
657         constexpr int dead_zone_pixels = 3;  // To avoid that simple clicks get misinterpreted.
658         int scrub_sensitivity = 100;  // pts units per pixel.
659         int wheel_sensitivity = 100;  // pts units per degree.
660
661         if (event->type() == QEvent::FocusIn || event->type() == QEvent::FocusOut) {
662                 enable_or_disable_preview_button();
663                 hidden_jog_column = -1;
664         }
665
666         unsigned stream_idx = ui->preview_display->get_stream_idx();
667
668         if (watched == ui->clip_list) {
669                 if (event->type() == QEvent::FocusOut) {
670                         highlight_camera_input(-1);
671                 }
672                 return false;
673         }
674
675         if (event->type() != QEvent::Wheel) {
676                 last_mousewheel_camera_row = -1;
677         }
678
679         if (event->type() == QEvent::MouseButtonPress) {
680                 QMouseEvent *mouse = (QMouseEvent *)event;
681
682                 QTableView *destination;
683                 ScrubType type;
684
685                 if (watched == ui->clip_list->viewport()) {
686                         destination = ui->clip_list;
687                         type = SCRUBBING_CLIP_LIST;
688                 } else if (watched == ui->playlist->viewport()) {
689                         destination = ui->playlist;
690                         type = SCRUBBING_PLAYLIST;
691                 } else {
692                         return false;
693                 }
694                 int column = destination->columnAt(mouse->x());
695                 int row = destination->rowAt(mouse->y());
696                 if (column == -1 || row == -1)
697                         return false;
698
699                 if (type == SCRUBBING_CLIP_LIST) {
700                         if (ClipList::Column(column) == ClipList::Column::IN) {
701                                 scrub_pts_origin = cliplist_clips->clip(row)->pts_in;
702                                 preview_single_frame(scrub_pts_origin, stream_idx, FIRST_AT_OR_AFTER);
703                         } else if (ClipList::Column(column) == ClipList::Column::OUT) {
704                                 scrub_pts_origin = cliplist_clips->clip(row)->pts_out;
705                                 preview_single_frame(scrub_pts_origin, stream_idx, LAST_BEFORE);
706                         } else {
707                                 return false;
708                         }
709                 } else {
710                         if (PlayList::Column(column) == PlayList::Column::IN) {
711                                 scrub_pts_origin = playlist_clips->clip(row)->pts_in;
712                                 preview_single_frame(scrub_pts_origin, stream_idx, FIRST_AT_OR_AFTER);
713                         } else if (PlayList::Column(column) == PlayList::Column::OUT) {
714                                 scrub_pts_origin = playlist_clips->clip(row)->pts_out;
715                                 preview_single_frame(scrub_pts_origin, stream_idx, LAST_BEFORE);
716                         } else {
717                                 return false;
718                         }
719                 }
720
721                 scrubbing = true;
722                 scrub_row = row;
723                 scrub_column = column;
724                 scrub_x_origin = mouse->x();
725                 scrub_type = type;
726         } else if (event->type() == QEvent::MouseMove) {
727                 QMouseEvent *mouse = (QMouseEvent *)event;
728                 if (mouse->modifiers() & Qt::KeyboardModifier::ShiftModifier) {
729                         scrub_sensitivity *= 10;
730                         wheel_sensitivity *= 10;
731                 }
732                 if (mouse->modifiers() & Qt::KeyboardModifier::AltModifier) {  // Note: Shift + Alt cancel each other out.
733                         scrub_sensitivity /= 10;
734                         wheel_sensitivity /= 10;
735                 }
736                 if (scrubbing) {
737                         int offset = mouse->x() - scrub_x_origin;
738                         int adjusted_offset;
739                         if (offset >= dead_zone_pixels) {
740                                 adjusted_offset = offset - dead_zone_pixels;
741                         } else if (offset < -dead_zone_pixels) {
742                                 adjusted_offset = offset + dead_zone_pixels;
743                         } else {
744                                 adjusted_offset = 0;
745                         }
746
747                         int64_t pts = scrub_pts_origin + adjusted_offset * scrub_sensitivity;
748                         currently_deferring_model_changes = true;
749                         if (scrub_type == SCRUBBING_CLIP_LIST) {
750                                 ClipProxy clip = cliplist_clips->mutable_clip(scrub_row);
751                                 if (scrub_column == int(ClipList::Column::IN)) {
752                                         current_change_id = "cliplist:in:" + to_string(scrub_row);
753                                         set_pts_in(pts, current_pts, clip);
754                                         preview_single_frame(pts, stream_idx, FIRST_AT_OR_AFTER);
755                                 } else {
756                                         current_change_id = "cliplist:out" + to_string(scrub_row);
757                                         pts = std::max(pts, clip->pts_in);
758                                         pts = std::min(pts, current_pts);
759                                         clip->pts_out = pts;
760                                         preview_single_frame(pts, stream_idx, LAST_BEFORE);
761                                 }
762                         } else {
763                                 ClipProxy clip = playlist_clips->mutable_clip(scrub_row);
764                                 if (scrub_column == int(PlayList::Column::IN)) {
765                                         current_change_id = "playlist:in:" + to_string(scrub_row);
766                                         set_pts_in(pts, current_pts, clip);
767                                         preview_single_frame(pts, clip->stream_idx, FIRST_AT_OR_AFTER);
768                                 } else {
769                                         current_change_id = "playlist:out:" + to_string(scrub_row);
770                                         pts = std::max(pts, clip->pts_in);
771                                         pts = std::min(pts, current_pts);
772                                         clip->pts_out = pts;
773                                         preview_single_frame(pts, clip->stream_idx, LAST_BEFORE);
774                                 }
775                         }
776                         currently_deferring_model_changes = false;
777
778                         return true;  // Don't use this mouse movement for selecting things.
779                 }
780         } else if (event->type() == QEvent::Wheel) {
781                 QWheelEvent *wheel = (QWheelEvent *)event;
782                 int angle_delta = wheel->angleDelta().y();
783                 if (wheel->modifiers() & Qt::KeyboardModifier::ShiftModifier) {
784                         scrub_sensitivity *= 10;
785                         wheel_sensitivity *= 10;
786                 }
787                 if (wheel->modifiers() & Qt::KeyboardModifier::AltModifier) {  // Note: Shift + Alt cancel each other out.
788                         scrub_sensitivity /= 10;
789                         wheel_sensitivity /= 10;
790                         angle_delta = wheel->angleDelta().x();  // Qt ickiness.
791                 }
792
793                 QTableView *destination;
794                 JogDestination jog_destination;
795                 if (watched == ui->clip_list->viewport()) {
796                         destination = ui->clip_list;
797                         jog_destination = JOG_CLIP_LIST;
798                         last_mousewheel_camera_row = -1;
799                 } else if (watched == ui->playlist->viewport()) {
800                         destination = ui->playlist;
801                         jog_destination = JOG_PLAYLIST;
802                         if (destination->columnAt(wheel->x()) != int(PlayList::Column::CAMERA)) {
803                                 last_mousewheel_camera_row = -1;
804                         }
805                 } else {
806                         last_mousewheel_camera_row = -1;
807                         return false;
808                 }
809
810                 int column = destination->columnAt(wheel->x());
811                 int row = destination->rowAt(wheel->y());
812                 if (column == -1 || row == -1)
813                         return false;
814
815                 // Only adjust pts with the wheel if the given row is selected.
816                 if (!destination->hasFocus() ||
817                     row != destination->selectionModel()->currentIndex().row()) {
818                         return false;
819                 }
820
821                 jog_internal(jog_destination, row, column, stream_idx, angle_delta * wheel_sensitivity);
822                 return true;  // Don't scroll.
823         } else if (event->type() == QEvent::MouseButtonRelease) {
824                 scrubbing = false;
825         }
826         return false;
827 }
828
829 void MainWindow::preview_single_frame(int64_t pts, unsigned stream_idx, MainWindow::Rounding rounding)
830 {
831         if (rounding == LAST_BEFORE) {
832                 lock_guard<mutex> lock(frame_mu);
833                 if (frames[stream_idx].empty())
834                         return;
835                 auto it = find_last_frame_before(frames[stream_idx], pts);
836                 if (it != frames[stream_idx].end()) {
837                         pts = it->pts;
838                 }
839         } else {
840                 assert(rounding == FIRST_AT_OR_AFTER);
841                 lock_guard<mutex> lock(frame_mu);
842                 if (frames[stream_idx].empty())
843                         return;
844                 auto it = find_first_frame_at_or_after(frames[stream_idx], pts);
845                 if (it != frames[stream_idx].end()) {
846                         pts = it->pts;
847                 }
848         }
849
850         Clip fake_clip;
851         fake_clip.pts_in = pts;
852         fake_clip.pts_out = pts + 1;
853         fake_clip.stream_idx = stream_idx;
854         preview_player->play(fake_clip);
855 }
856
857 void MainWindow::playlist_selection_changed()
858 {
859         enable_or_disable_preview_button();
860
861         QItemSelectionModel *selected = ui->playlist->selectionModel();
862         bool any_selected = selected->hasSelection();
863         ui->playlist_duplicate_btn->setEnabled(any_selected);
864         ui->playlist_remove_btn->setEnabled(any_selected);
865         ui->playlist_move_up_btn->setEnabled(
866                 any_selected && selected->selectedRows().front().row() > 0);
867         ui->playlist_move_down_btn->setEnabled(
868                 any_selected && selected->selectedRows().back().row() < int(playlist_clips->size()) - 1);
869
870         ui->play_btn->setEnabled(!playlist_clips->empty());
871         midi_mapper.set_play_enabled(!playlist_clips->empty());
872
873         if (!any_selected) {
874                 set_output_status("paused");
875         } else {
876                 vector<ClipWithID> clips;
877                 for (size_t row = selected->selectedRows().front().row(); row < playlist_clips->size(); ++row) {
878                         clips.emplace_back(*playlist_clips->clip_with_id(row));
879                 }
880                 double remaining = compute_total_time(clips);
881                 set_output_status(format_duration(remaining) + " ready");
882         }
883 }
884
885 void MainWindow::clip_list_selection_changed(const QModelIndex &current, const QModelIndex &previous)
886 {
887         int camera_selected = -1;
888         if (cliplist_clips->is_camera_column(current.column())) {
889                 camera_selected = current.column() - int(ClipList::Column::CAMERA_1);
890
891                 // See the comment on hidden_jog_column.
892                 if (current.row() != previous.row()) {
893                         hidden_jog_column = -1;
894                 } else if (hidden_jog_column == -1) {
895                         hidden_jog_column = previous.column();
896                 }
897         } else {
898                 hidden_jog_column = -1;
899         }
900         highlight_camera_input(camera_selected);
901         enable_or_disable_queue_button();
902 }
903
904 void MainWindow::report_disk_space(off_t free_bytes, double estimated_seconds_left)
905 {
906         char time_str[256];
907         if (estimated_seconds_left < 60.0) {
908                 strcpy(time_str, "<font color=\"red\">Less than a minute</font>");
909         } else if (estimated_seconds_left < 1800.0) {  // Less than half an hour: Xm Ys (red).
910                 int s = lrintf(estimated_seconds_left);
911                 int m = s / 60;
912                 s %= 60;
913                 snprintf(time_str, sizeof(time_str), "<font color=\"red\">%dm %ds</font>", m, s);
914         } else if (estimated_seconds_left < 3600.0) {  // Less than an hour: Xm.
915                 int m = lrintf(estimated_seconds_left / 60.0);
916                 snprintf(time_str, sizeof(time_str), "%dm", m);
917         } else if (estimated_seconds_left < 36000.0) {  // Less than ten hours: Xh Ym.
918                 int m = lrintf(estimated_seconds_left / 60.0);
919                 int h = m / 60;
920                 m %= 60;
921                 snprintf(time_str, sizeof(time_str), "%dh %dm", h, m);
922         } else {  // More than ten hours: Xh.
923                 int h = lrintf(estimated_seconds_left / 3600.0);
924                 snprintf(time_str, sizeof(time_str), "%dh", h);
925         }
926         char buf[256];
927         snprintf(buf, sizeof(buf), "Disk free: %'.0f MB (approx. %s)", free_bytes / 1048576.0, time_str);
928
929         std::string label = buf;
930
931         post_to_main_thread([this, label] {
932                 disk_free_label->setText(QString::fromStdString(label));
933                 ui->menuBar->setCornerWidget(disk_free_label);  // Need to set this again for the sizing to get right.
934         });
935 }
936
937 void MainWindow::exit_triggered()
938 {
939         close();
940 }
941
942 void MainWindow::export_cliplist_clip_multitrack_triggered()
943 {
944         QItemSelectionModel *selected = ui->clip_list->selectionModel();
945         if (!selected->hasSelection()) {
946                 QMessageBox msgbox;
947                 msgbox.setText("No clip selected in the clip list. Select one and try exporting again.");
948                 msgbox.exec();
949                 return;
950         }
951
952         QModelIndex index = selected->currentIndex();
953         Clip clip = *cliplist_clips->clip(index.row());
954         QString filename = QFileDialog::getSaveFileName(this,
955                 "Export multitrack clip", QString(), tr("Matroska video files (*.mkv)"));
956         if (filename.isNull()) {
957                 // Cancel.
958                 return;
959         }
960         if (!filename.endsWith(".mkv")) {
961                 filename += ".mkv";
962         }
963         export_multitrack_clip(filename.toStdString(), clip);
964 }
965
966 void MainWindow::export_playlist_clip_interpolated_triggered()
967 {
968         QItemSelectionModel *selected = ui->playlist->selectionModel();
969         if (!selected->hasSelection()) {
970                 QMessageBox msgbox;
971                 msgbox.setText("No clip selected in the playlist. Select one and try exporting again.");
972                 msgbox.exec();
973                 return;
974         }
975
976         QString filename = QFileDialog::getSaveFileName(this,
977                 "Export interpolated clip", QString(), tr("Matroska video files (*.mkv)"));
978         if (filename.isNull()) {
979                 // Cancel.
980                 return;
981         }
982         if (!filename.endsWith(".mkv")) {
983                 filename += ".mkv";
984         }
985
986         vector<Clip> clips;
987         QModelIndexList rows = selected->selectedRows();
988         for (QModelIndex index : rows) {
989                 clips.push_back(*playlist_clips->clip(index.row()));
990         }
991         export_interpolated_clip(filename.toStdString(), clips);
992 }
993
994 void MainWindow::manual_triggered()
995 {
996         if (!QDesktopServices::openUrl(QUrl("https://nageru.sesse.net/doc/"))) {
997                 QMessageBox msgbox;
998                 msgbox.setText("Could not launch manual in web browser.\nPlease see https://nageru.sesse.net/doc/ manually.");
999                 msgbox.exec();
1000         }
1001 }
1002
1003 void MainWindow::about_triggered()
1004 {
1005         AboutDialog("Futatabi", "Multicamera slow motion video server").exec();
1006 }
1007
1008 void MainWindow::undo_triggered()
1009 {
1010         // Finish any deferred action.
1011         if (defer_timeout->isActive()) {
1012                 defer_timeout->stop();
1013                 state_changed(deferred_state);
1014         }
1015
1016         StateProto redo_state;
1017         *redo_state.mutable_clip_list() = cliplist_clips->serialize();
1018         *redo_state.mutable_play_list() = playlist_clips->serialize();
1019         redo_stack.push_back(std::move(redo_state));
1020         ui->redo_action->setEnabled(true);
1021
1022         assert(undo_stack.size() > 1);
1023
1024         // Pop off the current state, which is always at the top of the stack.
1025         undo_stack.pop_back();
1026
1027         StateProto state = undo_stack.back();
1028         ui->undo_action->setEnabled(undo_stack.size() > 1);
1029
1030         replace_model(ui->clip_list, &cliplist_clips, new ClipList(state.clip_list()));
1031         replace_model(ui->playlist, &playlist_clips, new PlayList(state.play_list()));
1032
1033         db.store_state(state);
1034 }
1035
1036 void MainWindow::redo_triggered()
1037 {
1038         assert(!redo_stack.empty());
1039
1040         ui->undo_action->setEnabled(true);
1041         ui->redo_action->setEnabled(true);
1042
1043         undo_stack.push_back(std::move(redo_stack.back()));
1044         redo_stack.pop_back();
1045         ui->undo_action->setEnabled(true);
1046         ui->redo_action->setEnabled(!redo_stack.empty());
1047
1048         const StateProto &state = undo_stack.back();
1049         replace_model(ui->clip_list, &cliplist_clips, new ClipList(state.clip_list()));
1050         replace_model(ui->playlist, &playlist_clips, new PlayList(state.play_list()));
1051
1052         db.store_state(state);
1053 }
1054
1055 void MainWindow::quality_toggled(int quality, bool checked)
1056 {
1057         if (!checked) {
1058                 return;
1059         }
1060         global_flags.interpolation_quality = quality;
1061         if (quality != 0 &&  // Turning interpolation off is always possible.
1062             quality != flow_initialized_interpolation_quality) {
1063                 QMessageBox msgbox;
1064                 msgbox.setText(QString::fromStdString(
1065                         "The interpolation quality for the main output cannot be changed at runtime, "
1066                         "except being turned completely off; it will take effect for exported files "
1067                         "only until next restart. The live output quality thus remains at " +
1068                         to_string(flow_initialized_interpolation_quality) + "."));
1069                 msgbox.exec();
1070         }
1071
1072         save_settings();
1073 }
1074
1075 void MainWindow::padding_toggled(double seconds, bool checked)
1076 {
1077         if (!checked) {
1078                 return;
1079         }
1080         global_flags.cue_point_padding_seconds = seconds;
1081         save_settings();
1082 }
1083
1084 void MainWindow::highlight_camera_input(int stream_idx)
1085 {
1086         for (unsigned i = 0; i < num_cameras; ++i) {
1087                 if (unsigned(stream_idx) == i) {
1088                         displays[i].frame->setStyleSheet("background: rgb(0,255,0)");
1089                 } else {
1090                         displays[i].frame->setStyleSheet("");
1091                 }
1092         }
1093         midi_mapper.highlight_camera_input(stream_idx);
1094 }
1095
1096 void MainWindow::enable_or_disable_preview_button()
1097 {
1098         // Follows the logic in preview_clicked().
1099
1100         if (ui->playlist->hasFocus()) {
1101                 // Allow the playlist as preview iff it has focus and something is selected.
1102                 // TODO: Is this part really relevant?
1103                 QItemSelectionModel *selected = ui->playlist->selectionModel();
1104                 if (selected->hasSelection()) {
1105                         ui->preview_btn->setEnabled(true);
1106                         midi_mapper.set_preview_enabled(true);
1107                         return;
1108                 }
1109         }
1110
1111         // TODO: Perhaps only enable this if something is actually selected.
1112         ui->preview_btn->setEnabled(!cliplist_clips->empty());
1113         midi_mapper.set_preview_enabled(!cliplist_clips->empty());
1114 }
1115
1116 void MainWindow::enable_or_disable_queue_button()
1117 {
1118         // Follows the logic in queue_clicked().
1119         // TODO: Perhaps only enable this if something is actually selected.
1120
1121         bool enabled;
1122
1123         if (cliplist_clips->empty()) {
1124                 enabled = false;
1125         } else {
1126                 QItemSelectionModel *selected = ui->clip_list->selectionModel();
1127                 if (!selected->hasSelection()) {
1128                         Clip clip = *cliplist_clips->back();
1129                         enabled = clip.pts_out != -1;
1130                 } else {
1131                         QModelIndex index = selected->currentIndex();
1132                         Clip clip = *cliplist_clips->clip(index.row());
1133                         enabled = clip.pts_out != -1;
1134                 }
1135         }
1136
1137         ui->queue_btn->setEnabled(enabled);
1138         midi_mapper.set_queue_enabled(enabled);
1139 }
1140
1141 void MainWindow::set_output_status(const string &status)
1142 {
1143         ui->live_label->setText(QString::fromStdString("Current output (" + status + ")"));
1144         if (live_player != nullptr) {
1145                 live_player->set_pause_status(status);
1146         }
1147
1148         lock_guard<mutex> lock(queue_status_mu);
1149         queue_status = status;
1150 }
1151
1152 pair<string, string> MainWindow::get_queue_status() const
1153 {
1154         lock_guard<mutex> lock(queue_status_mu);
1155         return { queue_status, "text/plain" };
1156 }
1157
1158 void MainWindow::display_frame(unsigned stream_idx, const FrameOnDisk &frame)
1159 {
1160         if (stream_idx >= MAX_STREAMS) {
1161                 fprintf(stderr, "WARNING: Ignoring too-high stream index %u.\n", stream_idx);
1162                 return;
1163         }
1164         if (stream_idx >= num_cameras) {
1165                 post_to_main_thread_and_wait([this, stream_idx] {
1166                         num_cameras = stream_idx + 1;
1167                         change_num_cameras();
1168                 });
1169         }
1170         displays[stream_idx].display->setFrame(stream_idx, frame);
1171 }
1172
1173 void MainWindow::preview()
1174 {
1175         post_to_main_thread([this] {
1176                 preview_clicked();
1177         });
1178 }
1179
1180 void MainWindow::queue()
1181 {
1182         post_to_main_thread([this] {
1183                 queue_clicked();
1184         });
1185 }
1186
1187 void MainWindow::play()
1188 {
1189         post_to_main_thread([this] {
1190                 play_clicked();
1191         });
1192 }
1193
1194 void MainWindow::jog(int delta)
1195 {
1196         post_to_main_thread([this, delta] {
1197                 int64_t pts_delta = delta * (TIMEBASE / 60);  // One click = frame at 60 fps.
1198                 if (ui->playlist->hasFocus()) {
1199                         QModelIndex selected = ui->playlist->selectionModel()->currentIndex();
1200                         if (selected.column() != -1 && selected.row() != -1) {
1201                                 jog_internal(JOG_PLAYLIST, selected.row(), selected.column(), /*stream_idx=*/-1, pts_delta);
1202                         }
1203                 } else if (ui->clip_list->hasFocus()) {
1204                         QModelIndex selected = ui->clip_list->selectionModel()->currentIndex();
1205                         if (cliplist_clips->is_camera_column(selected.column()) &&
1206                             hidden_jog_column != -1) {
1207                                 // See the definition on hidden_jog_column.
1208                                 selected = selected.sibling(selected.row(), hidden_jog_column);
1209                                 ui->clip_list->selectionModel()->setCurrentIndex(selected, QItemSelectionModel::ClearAndSelect);
1210                                 hidden_jog_column = -1;
1211                         }
1212                         if (selected.column() != -1 && selected.row() != -1) {
1213                                 jog_internal(JOG_CLIP_LIST, selected.row(), selected.column(), ui->preview_display->get_stream_idx(), pts_delta);
1214                         }
1215                 }
1216         });
1217 }
1218
1219 void MainWindow::switch_camera(unsigned camera_idx)
1220 {
1221         post_to_main_thread([this, camera_idx] {
1222                 if (camera_idx < num_cameras) {  // TODO: Also make this change a highlighted clip?
1223                         preview_angle_clicked(camera_idx);
1224                 }
1225         });
1226 }
1227
1228 void MainWindow::cue_in()
1229 {
1230         post_to_main_thread([this] { cue_in_clicked(); });
1231 }
1232
1233 void MainWindow::cue_out()
1234 {
1235         post_to_main_thread([this] { cue_out_clicked(); });
1236 }
1237
1238 template<class Model>
1239 void MainWindow::replace_model(QTableView *view, Model **model, Model *new_model)
1240 {
1241         QItemSelectionModel *old_selection_model = view->selectionModel();
1242         view->setModel(new_model);
1243         delete *model;
1244         delete old_selection_model;
1245         *model = new_model;
1246         connect(new_model, &Model::any_content_changed, this, &MainWindow::content_changed);
1247 }
1248
1249 void MainWindow::start_tally()
1250 {
1251         http_reply = http.get(QNetworkRequest(QString::fromStdString(global_flags.tally_url)));
1252         connect(http_reply, &QNetworkReply::finished, this, &MainWindow::tally_received);
1253 }
1254
1255 void MainWindow::tally_received()
1256 {
1257         unsigned time_to_next_tally_ms;
1258         if (http_reply->error()) {
1259                 fprintf(stderr, "HTTP get of '%s' failed: %s\n", global_flags.tally_url.c_str(),
1260                         http_reply->errorString().toStdString().c_str());
1261                 ui->live_frame->setStyleSheet("");
1262                 time_to_next_tally_ms = 1000;
1263         } else {
1264                 string contents = http_reply->readAll().toStdString();
1265                 ui->live_frame->setStyleSheet(QString::fromStdString("background: " + contents));
1266                 time_to_next_tally_ms = 100;
1267         }
1268         http_reply->deleteLater();
1269         http_reply = nullptr;
1270
1271         QTimer::singleShot(time_to_next_tally_ms, this, &MainWindow::start_tally);
1272 }