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