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