4683769d403f423316e95ad0d841cb8b131b3466
[dcpomatic.git] / src / wx / timeline.cc
1 /*
2     Copyright (C) 2013-2021 Carl Hetherington <cth@carlh.net>
3
4     This file is part of DCP-o-matic.
5
6     DCP-o-matic is free software; you can redistribute it and/or modify
7     it under the terms of the GNU General Public License as published by
8     the Free Software Foundation; either version 2 of the License, or
9     (at your option) any later version.
10
11     DCP-o-matic is distributed in the hope that it will be useful,
12     but WITHOUT ANY WARRANTY; without even the implied warranty of
13     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14     GNU General Public License for more details.
15
16     You should have received a copy of the GNU General Public License
17     along with DCP-o-matic.  If not, see <http://www.gnu.org/licenses/>.
18
19 */
20
21 #include "content_panel.h"
22 #include "film_editor.h"
23 #include "film_viewer.h"
24 #include "timeline.h"
25 #include "timeline_atmos_content_view.h"
26 #include "timeline_audio_content_view.h"
27 #include "timeline_labels_view.h"
28 #include "timeline_reels_view.h"
29 #include "timeline_text_content_view.h"
30 #include "timeline_time_axis_view.h"
31 #include "timeline_video_content_view.h"
32 #include "wx_util.h"
33 #include "lib/atmos_mxf_content.h"
34 #include "lib/audio_content.h"
35 #include "lib/film.h"
36 #include "lib/image_content.h"
37 #include "lib/playlist.h"
38 #include "lib/text_content.h"
39 #include "lib/timer.h"
40 #include "lib/video_content.h"
41 #include <dcp/scope_guard.h>
42 #include <dcp/warnings.h>
43 LIBDCP_DISABLE_WARNINGS
44 #include <wx/graphics.h>
45 LIBDCP_ENABLE_WARNINGS
46 #include <iterator>
47 #include <list>
48
49
50 using std::abs;
51 using std::dynamic_pointer_cast;
52 using std::list;
53 using std::make_shared;
54 using std::max;
55 using std::min;
56 using std::shared_ptr;
57 using std::weak_ptr;
58 using boost::bind;
59 using boost::optional;
60 using namespace dcpomatic;
61 #if BOOST_VERSION >= 106100
62 using namespace boost::placeholders;
63 #endif
64
65
66 /* 3 hours in 640 pixels */
67 double const Timeline::_minimum_pixels_per_second = 640.0 / (60 * 60 * 3);
68 int const Timeline::_minimum_pixels_per_track = 16;
69
70
71 Timeline::Timeline(wxWindow* parent, ContentPanel* cp, shared_ptr<Film> film, FilmViewer& viewer)
72         : wxPanel (parent, wxID_ANY)
73         , _labels_canvas (new wxScrolledCanvas (this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxFULL_REPAINT_ON_RESIZE))
74         , _main_canvas (new wxScrolledCanvas (this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxFULL_REPAINT_ON_RESIZE))
75         , _content_panel (cp)
76         , _film (film)
77         , _viewer (viewer)
78         , _time_axis_view (new TimelineTimeAxisView (*this, 64))
79         , _reels_view (new TimelineReelsView (*this, 32))
80         , _labels_view (new TimelineLabelsView (*this))
81         , _tracks (0)
82         , _left_down (false)
83         , _down_view_position (0)
84         , _first_move (false)
85         , _menu (this, viewer)
86         , _snap (true)
87         , _tool (SELECT)
88         , _x_scroll_rate (16)
89         , _y_scroll_rate (16)
90         , _pixels_per_track (48)
91         , _first_resize (true)
92         , _timer (this)
93 {
94 #ifndef __WXOSX__
95         _labels_canvas->SetDoubleBuffered (true);
96         _main_canvas->SetDoubleBuffered (true);
97 #endif
98
99         auto sizer = new wxBoxSizer (wxHORIZONTAL);
100         sizer->Add (_labels_canvas, 0, wxEXPAND);
101         _labels_canvas->SetMinSize (wxSize (_labels_view->bbox().width, -1));
102         sizer->Add (_main_canvas, 1, wxEXPAND);
103         SetSizer (sizer);
104
105         _labels_canvas->Bind (wxEVT_PAINT,      boost::bind (&Timeline::paint_labels, this));
106         _main_canvas->Bind   (wxEVT_PAINT,      boost::bind (&Timeline::paint_main,   this));
107         _main_canvas->Bind   (wxEVT_LEFT_DOWN,  boost::bind (&Timeline::left_down,    this, _1));
108         _main_canvas->Bind   (wxEVT_LEFT_UP,    boost::bind (&Timeline::left_up,      this, _1));
109         _main_canvas->Bind   (wxEVT_RIGHT_DOWN, boost::bind (&Timeline::right_down,   this, _1));
110         _main_canvas->Bind   (wxEVT_MOTION,     boost::bind (&Timeline::mouse_moved,  this, _1));
111         _main_canvas->Bind   (wxEVT_SIZE,       boost::bind (&Timeline::resized,      this));
112         _main_canvas->Bind   (wxEVT_SCROLLWIN_TOP,        boost::bind (&Timeline::scrolled,     this, _1));
113         _main_canvas->Bind   (wxEVT_SCROLLWIN_BOTTOM,     boost::bind (&Timeline::scrolled,     this, _1));
114         _main_canvas->Bind   (wxEVT_SCROLLWIN_LINEUP,     boost::bind (&Timeline::scrolled,     this, _1));
115         _main_canvas->Bind   (wxEVT_SCROLLWIN_LINEDOWN,   boost::bind (&Timeline::scrolled,     this, _1));
116         _main_canvas->Bind   (wxEVT_SCROLLWIN_PAGEUP,     boost::bind (&Timeline::scrolled,     this, _1));
117         _main_canvas->Bind   (wxEVT_SCROLLWIN_PAGEDOWN,   boost::bind (&Timeline::scrolled,     this, _1));
118         _main_canvas->Bind   (wxEVT_SCROLLWIN_THUMBTRACK, boost::bind (&Timeline::scrolled,     this, _1));
119
120         film_change(ChangeType::DONE, FilmProperty::CONTENT);
121
122         SetMinSize (wxSize (640, 4 * pixels_per_track() + 96));
123
124         _film_changed_connection = film->Change.connect (bind (&Timeline::film_change, this, _1, _2));
125         _film_content_change_connection = film->ContentChange.connect (bind (&Timeline::film_content_change, this, _1, _3, _4));
126
127         Bind (wxEVT_TIMER, boost::bind(&Timeline::update_playhead, this));
128         _timer.Start (200, wxTIMER_CONTINUOUS);
129
130         setup_scrollbars ();
131         _labels_canvas->ShowScrollbars (wxSHOW_SB_NEVER, wxSHOW_SB_NEVER);
132 }
133
134
135 void
136 Timeline::update_playhead ()
137 {
138         Refresh ();
139 }
140
141
142 void
143 Timeline::set_pixels_per_second (double pps)
144 {
145         _pixels_per_second = max (_minimum_pixels_per_second, pps);
146 }
147
148
149 void
150 Timeline::paint_labels ()
151 {
152         wxPaintDC dc (_labels_canvas);
153
154         auto film = _film.lock();
155         if (film->content().empty()) {
156                 return;
157         }
158
159         auto gc = wxGraphicsContext::Create (dc);
160         if (!gc) {
161                 return;
162         }
163
164         dcp::ScopeGuard sg = [gc]() { delete gc; };
165
166         int vsx, vsy;
167         _labels_canvas->GetViewStart (&vsx, &vsy);
168         gc->Translate (-vsx * _x_scroll_rate, -vsy * _y_scroll_rate + tracks_y_offset());
169
170         _labels_view->paint (gc, {});
171 }
172
173
174 void
175 Timeline::paint_main ()
176 {
177         wxPaintDC dc (_main_canvas);
178         dc.Clear();
179
180         auto film = _film.lock();
181         if (film->content().empty()) {
182                 return;
183         }
184
185         _main_canvas->DoPrepareDC (dc);
186
187         auto gc = wxGraphicsContext::Create (dc);
188         if (!gc) {
189                 return;
190         }
191
192         dcp::ScopeGuard sg = [gc]() { delete gc; };
193
194         gc->SetAntialiasMode (wxANTIALIAS_DEFAULT);
195
196         for (auto i: _views) {
197
198                 auto ic = dynamic_pointer_cast<TimelineContentView> (i);
199
200                 /* Find areas of overlap with other content views, so that we can plot them */
201                 list<dcpomatic::Rect<int>> overlaps;
202                 for (auto j: _views) {
203                         auto jc = dynamic_pointer_cast<TimelineContentView> (j);
204                         /* No overlap with non-content views, views on different tracks, audio views or non-active views */
205                         if (!ic || !jc || i == j || ic->track() != jc->track() || ic->track().get_value_or(2) >= 2 || !ic->active() || !jc->active()) {
206                                 continue;
207                         }
208
209                         auto r = j->bbox().intersection(i->bbox());
210                         if (r) {
211                                 overlaps.push_back (r.get ());
212                         }
213                 }
214
215                 i->paint (gc, overlaps);
216         }
217
218         if (_zoom_point) {
219                 gc->SetPen(gui_is_dark() ? *wxWHITE_PEN : *wxBLACK_PEN);
220                 gc->SetBrush (*wxTRANSPARENT_BRUSH);
221                 gc->DrawRectangle (
222                         min (_down_point.x, _zoom_point->x),
223                         min (_down_point.y, _zoom_point->y),
224                         abs (_down_point.x - _zoom_point->x),
225                         abs (_down_point.y - _zoom_point->y)
226                         );
227         }
228
229         /* Playhead */
230
231         gc->SetPen (*wxRED_PEN);
232         auto path = gc->CreatePath ();
233         double const ph = _viewer.position().seconds() * pixels_per_second().get_value_or(0);
234         path.MoveToPoint (ph, 0);
235         path.AddLineToPoint (ph, pixels_per_track() * _tracks + 32);
236         gc->StrokePath (path);
237 }
238
239
240 void
241 Timeline::film_change(ChangeType type, FilmProperty p)
242 {
243         if (type != ChangeType::DONE) {
244                 return;
245         }
246
247         if (p == FilmProperty::CONTENT || p == FilmProperty::REEL_TYPE || p == FilmProperty::REEL_LENGTH) {
248                 ensure_ui_thread ();
249                 recreate_views ();
250         } else if (p == FilmProperty::CONTENT_ORDER) {
251                 Refresh ();
252         }
253 }
254
255
256 void
257 Timeline::recreate_views ()
258 {
259         auto film = _film.lock ();
260         if (!film) {
261                 return;
262         }
263
264         _views.clear ();
265         _views.push_back (_time_axis_view);
266         _views.push_back (_reels_view);
267
268         for (auto i: film->content ()) {
269                 if (i->video) {
270                         _views.push_back (make_shared<TimelineVideoContentView>(*this, i));
271                 }
272
273                 if (i->audio && !i->audio->mapping().mapped_output_channels().empty ()) {
274                         _views.push_back (make_shared<TimelineAudioContentView>(*this, i));
275                 }
276
277                 for (auto j: i->text) {
278                         _views.push_back (make_shared<TimelineTextContentView>(*this, i, j));
279                 }
280
281                 if (i->atmos) {
282                         _views.push_back (make_shared<TimelineAtmosContentView>(*this, i));
283                 }
284         }
285
286         assign_tracks ();
287         setup_scrollbars ();
288         Refresh ();
289 }
290
291
292 void
293 Timeline::film_content_change (ChangeType type, int property, bool frequent)
294 {
295         if (type != ChangeType::DONE) {
296                 return;
297         }
298
299         ensure_ui_thread ();
300
301         if (property == AudioContentProperty::STREAMS || property == VideoContentProperty::FRAME_TYPE) {
302                 recreate_views ();
303         } else if (property == ContentProperty::POSITION || property == ContentProperty::LENGTH) {
304                 _reels_view->force_redraw ();
305         } else if (!frequent) {
306                 setup_scrollbars ();
307                 Refresh ();
308         }
309 }
310
311
312 template <class T>
313 int
314 place (shared_ptr<const Film> film, TimelineViewList& views, int& tracks)
315 {
316         int const base = tracks;
317
318         for (auto i: views) {
319                 if (!dynamic_pointer_cast<T>(i)) {
320                         continue;
321                 }
322
323                 auto cv = dynamic_pointer_cast<TimelineContentView> (i);
324                 DCPOMATIC_ASSERT(cv);
325
326                 int t = base;
327
328                 auto content = cv->content();
329                 DCPTimePeriod const content_period = content->period(film);
330
331                 while (true) {
332                         auto j = views.begin();
333                         while (j != views.end()) {
334                                 auto test = dynamic_pointer_cast<T> (*j);
335                                 if (!test) {
336                                         ++j;
337                                         continue;
338                                 }
339
340                                 auto test_content = test->content();
341                                 if (
342                                         test->track() && test->track().get() == t &&
343                                         content_period.overlap(test_content->period(film))
344                                    ) {
345                                         /* we have an overlap on track `t' */
346                                         ++t;
347                                         break;
348                                 }
349
350                                 ++j;
351                         }
352
353                         if (j == views.end ()) {
354                                 /* no overlap on `t' */
355                                 break;
356                         }
357                 }
358
359                 cv->set_track (t);
360                 tracks = max (tracks, t + 1);
361         }
362
363         return tracks - base;
364 }
365
366
367 /** Compare the mapped output channels of two TimelineViews, so we can into
368  *  order of first mapped DCP channel.
369  */
370 struct AudioMappingComparator {
371         bool operator()(shared_ptr<TimelineView> a, shared_ptr<TimelineView> b) {
372                 int la = -1;
373                 auto cva = dynamic_pointer_cast<TimelineAudioContentView>(a);
374                 if (cva) {
375                         auto oc = cva->content()->audio->mapping().mapped_output_channels();
376                         la = *min_element(boost::begin(oc), boost::end(oc));
377                 }
378                 int lb = -1;
379                 auto cvb = dynamic_pointer_cast<TimelineAudioContentView>(b);
380                 if (cvb) {
381                         auto oc = cvb->content()->audio->mapping().mapped_output_channels();
382                         lb = *min_element(boost::begin(oc), boost::end(oc));
383                 }
384                 return la < lb;
385         }
386 };
387
388
389 void
390 Timeline::assign_tracks ()
391 {
392         /* Tracks are:
393            Video 1
394            Video 2
395            Video N
396            Text 1
397            Text 2
398            Text N
399            Atmos
400            Audio 1
401            Audio 2
402            Audio N
403         */
404
405         auto film = _film.lock ();
406         DCPOMATIC_ASSERT (film);
407
408         _tracks = 0;
409
410         for (auto i: _views) {
411                 auto c = dynamic_pointer_cast<TimelineContentView>(i);
412                 if (c) {
413                         c->unset_track ();
414                 }
415         }
416
417         int const video_tracks = place<TimelineVideoContentView> (film, _views, _tracks);
418         int const text_tracks = place<TimelineTextContentView> (film, _views, _tracks);
419
420         /* Atmos */
421
422         bool have_atmos = false;
423         for (auto i: _views) {
424                 auto cv = dynamic_pointer_cast<TimelineAtmosContentView>(i);
425                 if (cv) {
426                         cv->set_track (_tracks);
427                         have_atmos = true;
428                 }
429         }
430
431         if (have_atmos) {
432                 ++_tracks;
433         }
434
435         /* Audio.  We're sorting the views so that we get the audio views in order of increasing
436            DCP channel index.
437         */
438
439         auto views = _views;
440         sort(views.begin(), views.end(), AudioMappingComparator());
441         int const audio_tracks = place<TimelineAudioContentView> (film, views, _tracks);
442
443         _labels_view->set_video_tracks (video_tracks);
444         _labels_view->set_audio_tracks (audio_tracks);
445         _labels_view->set_text_tracks (text_tracks);
446         _labels_view->set_atmos (have_atmos);
447
448         _time_axis_view->set_y (tracks());
449         _reels_view->set_y (8);
450 }
451
452
453 int
454 Timeline::tracks () const
455 {
456         return _tracks;
457 }
458
459
460 void
461 Timeline::setup_scrollbars ()
462 {
463         auto film = _film.lock ();
464         if (!film || !_pixels_per_second) {
465                 return;
466         }
467
468         int const h = tracks() * pixels_per_track() + tracks_y_offset() + _time_axis_view->bbox().height;
469
470         _labels_canvas->SetVirtualSize (_labels_view->bbox().width, h);
471         _labels_canvas->SetScrollRate (_x_scroll_rate, _y_scroll_rate);
472         _main_canvas->SetVirtualSize (*_pixels_per_second * film->length().seconds(), h);
473         _main_canvas->SetScrollRate (_x_scroll_rate, _y_scroll_rate);
474 }
475
476
477 shared_ptr<TimelineView>
478 Timeline::event_to_view (wxMouseEvent& ev)
479 {
480         /* Search backwards through views so that we find the uppermost one first */
481         auto i = _views.rbegin();
482
483         int vsx, vsy;
484         _main_canvas->GetViewStart (&vsx, &vsy);
485         Position<int> const p (ev.GetX() + vsx * _x_scroll_rate, ev.GetY() + vsy * _y_scroll_rate);
486
487         while (i != _views.rend() && !(*i)->bbox().contains (p)) {
488                 ++i;
489         }
490
491         if (i == _views.rend ()) {
492                 return {};
493         }
494
495         return *i;
496 }
497
498
499 void
500 Timeline::left_down (wxMouseEvent& ev)
501 {
502         _left_down = true;
503         _down_point = ev.GetPosition ();
504
505         switch (_tool) {
506         case SELECT:
507                 left_down_select (ev);
508                 break;
509         case ZOOM:
510         case ZOOM_ALL:
511         case SNAP:
512         case SEQUENCE:
513                 /* Nothing to do */
514                 break;
515         }
516 }
517
518
519 void
520 Timeline::left_down_select (wxMouseEvent& ev)
521 {
522         auto view = event_to_view (ev);
523         auto content_view = dynamic_pointer_cast<TimelineContentView>(view);
524
525         _down_view.reset ();
526
527         if (content_view) {
528                 _down_view = content_view;
529                 _down_view_position = content_view->content()->position ();
530         }
531
532         if (dynamic_pointer_cast<TimelineTimeAxisView>(view)) {
533                 int vsx, vsy;
534                 _main_canvas->GetViewStart(&vsx, &vsy);
535                 _viewer.seek(DCPTime::from_seconds((ev.GetPosition().x + vsx * _x_scroll_rate) / _pixels_per_second.get_value_or(1)), true);
536         }
537
538         for (auto i: _views) {
539                 auto cv = dynamic_pointer_cast<TimelineContentView>(i);
540                 if (!cv) {
541                         continue;
542                 }
543
544                 if (!ev.ShiftDown ()) {
545                         cv->set_selected (view == i);
546                 }
547         }
548
549         if (content_view && ev.ShiftDown ()) {
550                 content_view->set_selected (!content_view->selected ());
551         }
552
553         _first_move = false;
554
555         if (_down_view) {
556                 /* Pre-compute the points that we might snap to */
557                 for (auto i: _views) {
558                         auto cv = dynamic_pointer_cast<TimelineContentView>(i);
559                         if (!cv || cv == _down_view || cv->content() == _down_view->content()) {
560                                 continue;
561                         }
562
563                         auto film = _film.lock ();
564                         DCPOMATIC_ASSERT (film);
565
566                         _start_snaps.push_back (cv->content()->position());
567                         _end_snaps.push_back (cv->content()->position());
568                         _start_snaps.push_back (cv->content()->end(film));
569                         _end_snaps.push_back (cv->content()->end(film));
570
571                         for (auto i: cv->content()->reel_split_points(film)) {
572                                 _start_snaps.push_back (i);
573                         }
574                 }
575
576                 /* Tell everyone that things might change frequently during the drag */
577                 _down_view->content()->set_change_signals_frequent (true);
578         }
579 }
580
581
582 void
583 Timeline::left_up (wxMouseEvent& ev)
584 {
585         _left_down = false;
586
587         switch (_tool) {
588         case SELECT:
589                 left_up_select (ev);
590                 break;
591         case ZOOM:
592                 left_up_zoom (ev);
593                 break;
594         case ZOOM_ALL:
595         case SNAP:
596         case SEQUENCE:
597                 break;
598         }
599 }
600
601
602 void
603 Timeline::left_up_select (wxMouseEvent& ev)
604 {
605         if (_down_view) {
606                 _down_view->content()->set_change_signals_frequent (false);
607         }
608
609         _content_panel->set_selection (selected_content ());
610         /* Since we may have just set change signals back to `not-frequent', we have to
611            make sure this position change is signalled, even if the position value has
612            not changed since the last time it was set (with frequent=true).  This is
613            a bit of a hack.
614         */
615         set_position_from_event (ev, true);
616
617         /* Clear up up the stuff we don't do during drag */
618         assign_tracks ();
619         setup_scrollbars ();
620         Refresh ();
621
622         _start_snaps.clear ();
623         _end_snaps.clear ();
624 }
625
626
627 void
628 Timeline::left_up_zoom (wxMouseEvent& ev)
629 {
630         _zoom_point = ev.GetPosition ();
631
632         int vsx, vsy;
633         _main_canvas->GetViewStart (&vsx, &vsy);
634
635         wxPoint top_left(min(_down_point.x, _zoom_point->x), min(_down_point.y, _zoom_point->y));
636         wxPoint bottom_right(max(_down_point.x, _zoom_point->x), max(_down_point.y, _zoom_point->y));
637
638         if ((bottom_right.x - top_left.x) < 8 || (bottom_right.y - top_left.y) < 8) {
639                 /* Very small zoom rectangle: we assume it wasn't intentional */
640                 _zoom_point = optional<wxPoint> ();
641                 Refresh ();
642                 return;
643         }
644
645         auto const time_left = DCPTime::from_seconds((top_left.x + vsx) / *_pixels_per_second);
646         auto const time_right = DCPTime::from_seconds((bottom_right.x + vsx) / *_pixels_per_second);
647         set_pixels_per_second (double(GetSize().GetWidth()) / (time_right.seconds() - time_left.seconds()));
648
649         double const tracks_top = double(top_left.y - tracks_y_offset()) / _pixels_per_track;
650         double const tracks_bottom = double(bottom_right.y - tracks_y_offset()) / _pixels_per_track;
651         set_pixels_per_track (lrint(GetSize().GetHeight() / (tracks_bottom - tracks_top)));
652
653         setup_scrollbars ();
654         int const y = (tracks_top * _pixels_per_track + tracks_y_offset()) / _y_scroll_rate;
655         _main_canvas->Scroll (time_left.seconds() * *_pixels_per_second / _x_scroll_rate, y);
656         _labels_canvas->Scroll (0, y);
657
658         _zoom_point = optional<wxPoint> ();
659         Refresh ();
660 }
661
662
663 void
664 Timeline::set_pixels_per_track (int h)
665 {
666         _pixels_per_track = max(_minimum_pixels_per_track, h);
667 }
668
669
670 void
671 Timeline::mouse_moved (wxMouseEvent& ev)
672 {
673         switch (_tool) {
674         case SELECT:
675                 mouse_moved_select (ev);
676                 break;
677         case ZOOM:
678                 mouse_moved_zoom (ev);
679                 break;
680         case ZOOM_ALL:
681         case SNAP:
682         case SEQUENCE:
683                 break;
684         }
685 }
686
687
688 void
689 Timeline::mouse_moved_select (wxMouseEvent& ev)
690 {
691         if (!_left_down) {
692                 return;
693         }
694
695         set_position_from_event (ev);
696 }
697
698
699 void
700 Timeline::mouse_moved_zoom (wxMouseEvent& ev)
701 {
702         if (!_left_down) {
703                 return;
704         }
705
706         _zoom_point = ev.GetPosition ();
707         setup_scrollbars();
708         Refresh ();
709 }
710
711
712 void
713 Timeline::right_down (wxMouseEvent& ev)
714 {
715         switch (_tool) {
716         case SELECT:
717                 right_down_select (ev);
718                 break;
719         case ZOOM:
720                 /* Zoom out */
721                 set_pixels_per_second (*_pixels_per_second / 2);
722                 set_pixels_per_track (_pixels_per_track / 2);
723                 setup_scrollbars ();
724                 Refresh ();
725                 break;
726         case ZOOM_ALL:
727         case SNAP:
728         case SEQUENCE:
729                 break;
730         }
731 }
732
733
734 void
735 Timeline::right_down_select (wxMouseEvent& ev)
736 {
737         auto view = event_to_view (ev);
738         auto cv = dynamic_pointer_cast<TimelineContentView> (view);
739         if (!cv) {
740                 return;
741         }
742
743         if (!cv->selected ()) {
744                 clear_selection ();
745                 cv->set_selected (true);
746         }
747
748         _menu.popup (_film, selected_content (), selected_views (), ev.GetPosition ());
749 }
750
751
752 void
753 Timeline::maybe_snap (DCPTime a, DCPTime b, optional<DCPTime>& nearest_distance) const
754 {
755         auto const d = a - b;
756         if (!nearest_distance || d.abs() < nearest_distance.get().abs()) {
757                 nearest_distance = d;
758         }
759 }
760
761
762 void
763 Timeline::set_position_from_event (wxMouseEvent& ev, bool force_emit)
764 {
765         if (!_pixels_per_second) {
766                 return;
767         }
768
769         double const pps = _pixels_per_second.get ();
770
771         auto const p = ev.GetPosition();
772
773         if (!_first_move) {
774                 /* We haven't moved yet; in that case, we must move the mouse some reasonable distance
775                    before the drag is considered to have started.
776                 */
777                 int const dist = sqrt (pow (p.x - _down_point.x, 2) + pow (p.y - _down_point.y, 2));
778                 if (dist < 8) {
779                         return;
780                 }
781                 _first_move = true;
782         }
783
784         if (!_down_view) {
785                 return;
786         }
787
788         auto new_position = _down_view_position + DCPTime::from_seconds ((p.x - _down_point.x) / pps);
789
790         auto film = _film.lock ();
791         DCPOMATIC_ASSERT (film);
792
793         if (_snap) {
794                 auto const new_end = new_position + _down_view->content()->length_after_trim(film);
795                 /* Signed `distance' to nearest thing (i.e. negative is left on the timeline,
796                    positive is right).
797                 */
798                 optional<DCPTime> nearest_distance;
799
800                 /* Find the nearest snap point */
801
802                 for (auto i: _start_snaps) {
803                         maybe_snap (i, new_position, nearest_distance);
804                 }
805
806                 for (auto i: _end_snaps) {
807                         maybe_snap (i, new_end, nearest_distance);
808                 }
809
810                 if (nearest_distance) {
811                         /* Snap if it's close; `close' means within a proportion of the time on the timeline */
812                         if (nearest_distance.get().abs() < DCPTime::from_seconds ((width() / pps) / 64)) {
813                                 new_position += nearest_distance.get ();
814                         }
815                 }
816         }
817
818         if (new_position < DCPTime ()) {
819                 new_position = DCPTime ();
820         }
821
822         _down_view->content()->set_position (film, new_position, force_emit);
823
824         film->set_sequence (false);
825 }
826
827
828 void
829 Timeline::force_redraw (dcpomatic::Rect<int> const & r)
830 {
831         _main_canvas->RefreshRect (wxRect (r.x, r.y, r.width, r.height), false);
832 }
833
834
835 shared_ptr<const Film>
836 Timeline::film () const
837 {
838         return _film.lock ();
839 }
840
841
842 void
843 Timeline::resized ()
844 {
845         if (_main_canvas->GetSize().GetWidth() > 0 && _first_resize) {
846                 zoom_all ();
847                 _first_resize = false;
848         }
849         setup_scrollbars ();
850 }
851
852
853 void
854 Timeline::clear_selection ()
855 {
856         for (auto i: _views) {
857                 shared_ptr<TimelineContentView> cv = dynamic_pointer_cast<TimelineContentView>(i);
858                 if (cv) {
859                         cv->set_selected (false);
860                 }
861         }
862 }
863
864
865 TimelineContentViewList
866 Timeline::selected_views () const
867 {
868         TimelineContentViewList sel;
869
870         for (auto i: _views) {
871                 auto cv = dynamic_pointer_cast<TimelineContentView>(i);
872                 if (cv && cv->selected()) {
873                         sel.push_back (cv);
874                 }
875         }
876
877         return sel;
878 }
879
880
881 ContentList
882 Timeline::selected_content () const
883 {
884         ContentList sel;
885
886         for (auto i: selected_views()) {
887                 sel.push_back(i->content());
888         }
889
890         return sel;
891 }
892
893
894 void
895 Timeline::set_selection (ContentList selection)
896 {
897         for (auto i: _views) {
898                 auto cv = dynamic_pointer_cast<TimelineContentView> (i);
899                 if (cv) {
900                         cv->set_selected (find (selection.begin(), selection.end(), cv->content ()) != selection.end ());
901                 }
902         }
903 }
904
905
906 int
907 Timeline::tracks_y_offset () const
908 {
909         return _reels_view->bbox().height + 4;
910 }
911
912
913 int
914 Timeline::width () const
915 {
916         return _main_canvas->GetVirtualSize().GetWidth();
917 }
918
919
920 void
921 Timeline::scrolled (wxScrollWinEvent& ev)
922 {
923         if (ev.GetOrientation() == wxVERTICAL) {
924                 int x, y;
925                 _main_canvas->GetViewStart (&x, &y);
926                 _labels_canvas->Scroll (0, y);
927         }
928         ev.Skip ();
929 }
930
931
932 void
933 Timeline::tool_clicked (Tool t)
934 {
935         switch (t) {
936         case ZOOM:
937         case SELECT:
938                 _tool = t;
939                 break;
940         case ZOOM_ALL:
941                 zoom_all ();
942                 break;
943         case SNAP:
944         case SEQUENCE:
945                 break;
946         }
947 }
948
949
950 void
951 Timeline::zoom_all ()
952 {
953         auto film = _film.lock ();
954         DCPOMATIC_ASSERT (film);
955         set_pixels_per_second((_main_canvas->GetSize().GetWidth() - 32) / std::max(1.0, film->length().seconds()));
956         set_pixels_per_track((_main_canvas->GetSize().GetHeight() - tracks_y_offset() - _time_axis_view->bbox().height - 32) / std::max(1, _tracks));
957         setup_scrollbars ();
958         _main_canvas->Scroll (0, 0);
959         _labels_canvas->Scroll (0, 0);
960         Refresh ();
961 }
962
963
964 void
965 Timeline::keypress(wxKeyEvent const& event)
966 {
967         if (event.GetKeyCode() == WXK_DELETE) {
968                 auto film = _film.lock();
969                 DCPOMATIC_ASSERT(film);
970                 film->remove_content(selected_content());
971         } else {
972                 switch (event.GetRawKeyCode()) {
973                 case '+':
974                         set_pixels_per_second(_pixels_per_second.get_value_or(1) * 2);
975                         setup_scrollbars();
976                         break;
977                 case '-':
978                         set_pixels_per_second(_pixels_per_second.get_value_or(1) / 2);
979                         setup_scrollbars();
980                         break;
981                 }
982         }
983 }
984