2b8fba6fd50468766c09a36e3c05646df1d0a5a5
[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/scope_guard.h"
39 #include "lib/text_content.h"
40 #include "lib/timer.h"
41 #include "lib/video_content.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, Film::Property::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         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
179         auto film = _film.lock();
180         if (film->content().empty()) {
181                 return;
182         }
183
184         _main_canvas->DoPrepareDC (dc);
185
186         auto gc = wxGraphicsContext::Create (dc);
187         if (!gc) {
188                 return;
189         }
190
191         ScopeGuard sg = [gc]() { delete gc; };
192
193         int vsx, vsy;
194         _main_canvas->GetViewStart (&vsx, &vsy);
195         gc->Translate (-vsx * _x_scroll_rate, -vsy * _y_scroll_rate);
196
197         gc->SetAntialiasMode (wxANTIALIAS_DEFAULT);
198
199         for (auto i: _views) {
200
201                 auto ic = dynamic_pointer_cast<TimelineContentView> (i);
202
203                 /* Find areas of overlap with other content views, so that we can plot them */
204                 list<dcpomatic::Rect<int>> overlaps;
205                 for (auto j: _views) {
206                         auto jc = dynamic_pointer_cast<TimelineContentView> (j);
207                         /* No overlap with non-content views, views on different tracks, audio views or non-active views */
208                         if (!ic || !jc || i == j || ic->track() != jc->track() || ic->track().get_value_or(2) >= 2 || !ic->active() || !jc->active()) {
209                                 continue;
210                         }
211
212                         auto r = j->bbox().intersection(i->bbox());
213                         if (r) {
214                                 overlaps.push_back (r.get ());
215                         }
216                 }
217
218                 i->paint (gc, overlaps);
219         }
220
221         if (_zoom_point) {
222                 /* Translate back as _down_point and _zoom_point do not take scroll into account */
223                 gc->Translate (vsx * _x_scroll_rate, vsy * _y_scroll_rate);
224                 gc->SetPen(gui_is_dark() ? *wxWHITE_PEN : *wxBLACK_PEN);
225                 gc->SetBrush (*wxTRANSPARENT_BRUSH);
226                 gc->DrawRectangle (
227                         min (_down_point.x, _zoom_point->x),
228                         min (_down_point.y, _zoom_point->y),
229                         abs (_down_point.x - _zoom_point->x),
230                         abs (_down_point.y - _zoom_point->y)
231                         );
232         }
233
234         /* Playhead */
235
236         gc->SetPen (*wxRED_PEN);
237         auto path = gc->CreatePath ();
238         double const ph = _viewer.position().seconds() * pixels_per_second().get_value_or(0);
239         path.MoveToPoint (ph, 0);
240         path.AddLineToPoint (ph, pixels_per_track() * _tracks + 32);
241         gc->StrokePath (path);
242 }
243
244
245 void
246 Timeline::film_change (ChangeType type, Film::Property p)
247 {
248         if (type != ChangeType::DONE) {
249                 return;
250         }
251
252         if (p == Film::Property::CONTENT || p == Film::Property::REEL_TYPE || p == Film::Property::REEL_LENGTH) {
253                 ensure_ui_thread ();
254                 recreate_views ();
255         } else if (p == Film::Property::CONTENT_ORDER) {
256                 Refresh ();
257         }
258 }
259
260
261 void
262 Timeline::recreate_views ()
263 {
264         auto film = _film.lock ();
265         if (!film) {
266                 return;
267         }
268
269         _views.clear ();
270         _views.push_back (_time_axis_view);
271         _views.push_back (_reels_view);
272
273         for (auto i: film->content ()) {
274                 if (i->video) {
275                         _views.push_back (make_shared<TimelineVideoContentView>(*this, i));
276                 }
277
278                 if (i->audio && !i->audio->mapping().mapped_output_channels().empty ()) {
279                         _views.push_back (make_shared<TimelineAudioContentView>(*this, i));
280                 }
281
282                 for (auto j: i->text) {
283                         _views.push_back (make_shared<TimelineTextContentView>(*this, i, j));
284                 }
285
286                 if (i->atmos) {
287                         _views.push_back (make_shared<TimelineAtmosContentView>(*this, i));
288                 }
289         }
290
291         assign_tracks ();
292         setup_scrollbars ();
293         Refresh ();
294 }
295
296
297 void
298 Timeline::film_content_change (ChangeType type, int property, bool frequent)
299 {
300         if (type != ChangeType::DONE) {
301                 return;
302         }
303
304         ensure_ui_thread ();
305
306         if (property == AudioContentProperty::STREAMS || property == VideoContentProperty::FRAME_TYPE) {
307                 recreate_views ();
308         } else if (property == ContentProperty::POSITION || property == ContentProperty::LENGTH) {
309                 _reels_view->force_redraw ();
310         } else if (!frequent) {
311                 setup_scrollbars ();
312                 Refresh ();
313         }
314 }
315
316
317 template <class T>
318 int
319 place (shared_ptr<const Film> film, TimelineViewList& views, int& tracks)
320 {
321         int const base = tracks;
322
323         for (auto i: views) {
324                 if (!dynamic_pointer_cast<T>(i)) {
325                         continue;
326                 }
327
328                 auto cv = dynamic_pointer_cast<TimelineContentView> (i);
329
330                 int t = base;
331
332                 auto content = cv->content();
333                 DCPTimePeriod const content_period = content->period(film);
334
335                 while (true) {
336                         auto j = views.begin();
337                         while (j != views.end()) {
338                                 auto test = dynamic_pointer_cast<T> (*j);
339                                 if (!test) {
340                                         ++j;
341                                         continue;
342                                 }
343
344                                 auto test_content = test->content();
345                                 if (
346                                         test->track() && test->track().get() == t &&
347                                         content_period.overlap(test_content->period(film))
348                                    ) {
349                                         /* we have an overlap on track `t' */
350                                         ++t;
351                                         break;
352                                 }
353
354                                 ++j;
355                         }
356
357                         if (j == views.end ()) {
358                                 /* no overlap on `t' */
359                                 break;
360                         }
361                 }
362
363                 cv->set_track (t);
364                 tracks = max (tracks, t + 1);
365         }
366
367         return tracks - base;
368 }
369
370
371 /** Compare the mapped output channels of two TimelineViews, so we can into
372  *  order of first mapped DCP channel.
373  */
374 struct AudioMappingComparator {
375         bool operator()(shared_ptr<TimelineView> a, shared_ptr<TimelineView> b) {
376                 int la = -1;
377                 auto cva = dynamic_pointer_cast<TimelineAudioContentView>(a);
378                 if (cva) {
379                         auto oc = cva->content()->audio->mapping().mapped_output_channels();
380                         la = *min_element(boost::begin(oc), boost::end(oc));
381                 }
382                 int lb = -1;
383                 auto cvb = dynamic_pointer_cast<TimelineAudioContentView>(b);
384                 if (cvb) {
385                         auto oc = cvb->content()->audio->mapping().mapped_output_channels();
386                         lb = *min_element(boost::begin(oc), boost::end(oc));
387                 }
388                 return la < lb;
389         }
390 };
391
392
393 void
394 Timeline::assign_tracks ()
395 {
396         /* Tracks are:
397            Video 1
398            Video 2
399            Video N
400            Text 1
401            Text 2
402            Text N
403            Atmos
404            Audio 1
405            Audio 2
406            Audio N
407         */
408
409         auto film = _film.lock ();
410         DCPOMATIC_ASSERT (film);
411
412         _tracks = 0;
413
414         for (auto i: _views) {
415                 auto c = dynamic_pointer_cast<TimelineContentView>(i);
416                 if (c) {
417                         c->unset_track ();
418                 }
419         }
420
421         int const video_tracks = place<TimelineVideoContentView> (film, _views, _tracks);
422         int const text_tracks = place<TimelineTextContentView> (film, _views, _tracks);
423
424         /* Atmos */
425
426         bool have_atmos = false;
427         for (auto i: _views) {
428                 auto cv = dynamic_pointer_cast<TimelineAtmosContentView>(i);
429                 if (cv) {
430                         cv->set_track (_tracks);
431                         have_atmos = true;
432                 }
433         }
434
435         if (have_atmos) {
436                 ++_tracks;
437         }
438
439         /* Audio.  We're sorting the views so that we get the audio views in order of increasing
440            DCP channel index.
441         */
442
443         auto views = _views;
444         sort(views.begin(), views.end(), AudioMappingComparator());
445         int const audio_tracks = place<TimelineAudioContentView> (film, views, _tracks);
446
447         _labels_view->set_video_tracks (video_tracks);
448         _labels_view->set_audio_tracks (audio_tracks);
449         _labels_view->set_text_tracks (text_tracks);
450         _labels_view->set_atmos (have_atmos);
451
452         _time_axis_view->set_y (tracks());
453         _reels_view->set_y (8);
454 }
455
456
457 int
458 Timeline::tracks () const
459 {
460         return _tracks;
461 }
462
463
464 void
465 Timeline::setup_scrollbars ()
466 {
467         auto film = _film.lock ();
468         if (!film || !_pixels_per_second) {
469                 return;
470         }
471
472         int const h = tracks() * pixels_per_track() + tracks_y_offset() + _time_axis_view->bbox().height;
473
474         _labels_canvas->SetVirtualSize (_labels_view->bbox().width, h);
475         _labels_canvas->SetScrollRate (_x_scroll_rate, _y_scroll_rate);
476         _main_canvas->SetVirtualSize (*_pixels_per_second * film->length().seconds(), h);
477         _main_canvas->SetScrollRate (_x_scroll_rate, _y_scroll_rate);
478 }
479
480
481 shared_ptr<TimelineView>
482 Timeline::event_to_view (wxMouseEvent& ev)
483 {
484         /* Search backwards through views so that we find the uppermost one first */
485         auto i = _views.rbegin();
486
487         int vsx, vsy;
488         _main_canvas->GetViewStart (&vsx, &vsy);
489         Position<int> const p (ev.GetX() + vsx * _x_scroll_rate, ev.GetY() + vsy * _y_scroll_rate);
490
491         while (i != _views.rend() && !(*i)->bbox().contains (p)) {
492                 ++i;
493         }
494
495         if (i == _views.rend ()) {
496                 return {};
497         }
498
499         return *i;
500 }
501
502
503 void
504 Timeline::left_down (wxMouseEvent& ev)
505 {
506         _left_down = true;
507         _down_point = ev.GetPosition ();
508
509         switch (_tool) {
510         case SELECT:
511                 left_down_select (ev);
512                 break;
513         case ZOOM:
514         case ZOOM_ALL:
515         case SNAP:
516         case SEQUENCE:
517                 /* Nothing to do */
518                 break;
519         }
520 }
521
522
523 void
524 Timeline::left_down_select (wxMouseEvent& ev)
525 {
526         auto view = event_to_view (ev);
527         auto content_view = dynamic_pointer_cast<TimelineContentView>(view);
528
529         _down_view.reset ();
530
531         if (content_view) {
532                 _down_view = content_view;
533                 _down_view_position = content_view->content()->position ();
534         }
535
536         if (dynamic_pointer_cast<TimelineTimeAxisView>(view)) {
537                 int vsx, vsy;
538                 _main_canvas->GetViewStart(&vsx, &vsy);
539                 _viewer.seek(DCPTime::from_seconds((ev.GetPosition().x + vsx * _x_scroll_rate) / _pixels_per_second.get_value_or(1)), true);
540         }
541
542         for (auto i: _views) {
543                 auto cv = dynamic_pointer_cast<TimelineContentView>(i);
544                 if (!cv) {
545                         continue;
546                 }
547
548                 if (!ev.ShiftDown ()) {
549                         cv->set_selected (view == i);
550                 }
551         }
552
553         if (content_view && ev.ShiftDown ()) {
554                 content_view->set_selected (!content_view->selected ());
555         }
556
557         _first_move = false;
558
559         if (_down_view) {
560                 /* Pre-compute the points that we might snap to */
561                 for (auto i: _views) {
562                         auto cv = dynamic_pointer_cast<TimelineContentView>(i);
563                         if (!cv || cv == _down_view || cv->content() == _down_view->content()) {
564                                 continue;
565                         }
566
567                         auto film = _film.lock ();
568                         DCPOMATIC_ASSERT (film);
569
570                         _start_snaps.push_back (cv->content()->position());
571                         _end_snaps.push_back (cv->content()->position());
572                         _start_snaps.push_back (cv->content()->end(film));
573                         _end_snaps.push_back (cv->content()->end(film));
574
575                         for (auto i: cv->content()->reel_split_points(film)) {
576                                 _start_snaps.push_back (i);
577                         }
578                 }
579
580                 /* Tell everyone that things might change frequently during the drag */
581                 _down_view->content()->set_change_signals_frequent (true);
582         }
583 }
584
585
586 void
587 Timeline::left_up (wxMouseEvent& ev)
588 {
589         _left_down = false;
590
591         switch (_tool) {
592         case SELECT:
593                 left_up_select (ev);
594                 break;
595         case ZOOM:
596                 left_up_zoom (ev);
597                 break;
598         case ZOOM_ALL:
599         case SNAP:
600         case SEQUENCE:
601                 break;
602         }
603 }
604
605
606 void
607 Timeline::left_up_select (wxMouseEvent& ev)
608 {
609         if (_down_view) {
610                 _down_view->content()->set_change_signals_frequent (false);
611         }
612
613         _content_panel->set_selection (selected_content ());
614         /* Since we may have just set change signals back to `not-frequent', we have to
615            make sure this position change is signalled, even if the position value has
616            not changed since the last time it was set (with frequent=true).  This is
617            a bit of a hack.
618         */
619         set_position_from_event (ev, true);
620
621         /* Clear up up the stuff we don't do during drag */
622         assign_tracks ();
623         setup_scrollbars ();
624         Refresh ();
625
626         _start_snaps.clear ();
627         _end_snaps.clear ();
628 }
629
630
631 void
632 Timeline::left_up_zoom (wxMouseEvent& ev)
633 {
634         _zoom_point = ev.GetPosition ();
635
636         int vsx, vsy;
637         _main_canvas->GetViewStart (&vsx, &vsy);
638
639         wxPoint top_left(min(_down_point.x, _zoom_point->x), min(_down_point.y, _zoom_point->y));
640         wxPoint bottom_right(max(_down_point.x, _zoom_point->x), max(_down_point.y, _zoom_point->y));
641
642         if ((bottom_right.x - top_left.x) < 8 || (bottom_right.y - top_left.y) < 8) {
643                 /* Very small zoom rectangle: we assume it wasn't intentional */
644                 _zoom_point = optional<wxPoint> ();
645                 Refresh ();
646                 return;
647         }
648
649         auto const time_left = DCPTime::from_seconds((top_left.x + vsx) / *_pixels_per_second);
650         auto const time_right = DCPTime::from_seconds((bottom_right.x + vsx) / *_pixels_per_second);
651         set_pixels_per_second (double(GetSize().GetWidth()) / (time_right.seconds() - time_left.seconds()));
652
653         double const tracks_top = double(top_left.y - tracks_y_offset()) / _pixels_per_track;
654         double const tracks_bottom = double(bottom_right.y - tracks_y_offset()) / _pixels_per_track;
655         set_pixels_per_track (lrint(GetSize().GetHeight() / (tracks_bottom - tracks_top)));
656
657         setup_scrollbars ();
658         int const y = (tracks_top * _pixels_per_track + tracks_y_offset()) / _y_scroll_rate;
659         _main_canvas->Scroll (time_left.seconds() * *_pixels_per_second / _x_scroll_rate, y);
660         _labels_canvas->Scroll (0, y);
661
662         _zoom_point = optional<wxPoint> ();
663         Refresh ();
664 }
665
666
667 void
668 Timeline::set_pixels_per_track (int h)
669 {
670         _pixels_per_track = max(_minimum_pixels_per_track, h);
671 }
672
673
674 void
675 Timeline::mouse_moved (wxMouseEvent& ev)
676 {
677         switch (_tool) {
678         case SELECT:
679                 mouse_moved_select (ev);
680                 break;
681         case ZOOM:
682                 mouse_moved_zoom (ev);
683                 break;
684         case ZOOM_ALL:
685         case SNAP:
686         case SEQUENCE:
687                 break;
688         }
689 }
690
691
692 void
693 Timeline::mouse_moved_select (wxMouseEvent& ev)
694 {
695         if (!_left_down) {
696                 return;
697         }
698
699         set_position_from_event (ev);
700 }
701
702
703 void
704 Timeline::mouse_moved_zoom (wxMouseEvent& ev)
705 {
706         if (!_left_down) {
707                 return;
708         }
709
710         _zoom_point = ev.GetPosition ();
711         Refresh ();
712 }
713
714
715 void
716 Timeline::right_down (wxMouseEvent& ev)
717 {
718         switch (_tool) {
719         case SELECT:
720                 right_down_select (ev);
721                 break;
722         case ZOOM:
723                 /* Zoom out */
724                 set_pixels_per_second (*_pixels_per_second / 2);
725                 set_pixels_per_track (_pixels_per_track / 2);
726                 setup_scrollbars ();
727                 Refresh ();
728                 break;
729         case ZOOM_ALL:
730         case SNAP:
731         case SEQUENCE:
732                 break;
733         }
734 }
735
736
737 void
738 Timeline::right_down_select (wxMouseEvent& ev)
739 {
740         auto view = event_to_view (ev);
741         auto cv = dynamic_pointer_cast<TimelineContentView> (view);
742         if (!cv) {
743                 return;
744         }
745
746         if (!cv->selected ()) {
747                 clear_selection ();
748                 cv->set_selected (true);
749         }
750
751         _menu.popup (_film, selected_content (), selected_views (), ev.GetPosition ());
752 }
753
754
755 void
756 Timeline::maybe_snap (DCPTime a, DCPTime b, optional<DCPTime>& nearest_distance) const
757 {
758         auto const d = a - b;
759         if (!nearest_distance || d.abs() < nearest_distance.get().abs()) {
760                 nearest_distance = d;
761         }
762 }
763
764
765 void
766 Timeline::set_position_from_event (wxMouseEvent& ev, bool force_emit)
767 {
768         if (!_pixels_per_second) {
769                 return;
770         }
771
772         double const pps = _pixels_per_second.get ();
773
774         auto const p = ev.GetPosition();
775
776         if (!_first_move) {
777                 /* We haven't moved yet; in that case, we must move the mouse some reasonable distance
778                    before the drag is considered to have started.
779                 */
780                 int const dist = sqrt (pow (p.x - _down_point.x, 2) + pow (p.y - _down_point.y, 2));
781                 if (dist < 8) {
782                         return;
783                 }
784                 _first_move = true;
785         }
786
787         if (!_down_view) {
788                 return;
789         }
790
791         auto new_position = _down_view_position + DCPTime::from_seconds ((p.x - _down_point.x) / pps);
792
793         auto film = _film.lock ();
794         DCPOMATIC_ASSERT (film);
795
796         if (_snap) {
797                 auto const new_end = new_position + _down_view->content()->length_after_trim(film);
798                 /* Signed `distance' to nearest thing (i.e. negative is left on the timeline,
799                    positive is right).
800                 */
801                 optional<DCPTime> nearest_distance;
802
803                 /* Find the nearest snap point */
804
805                 for (auto i: _start_snaps) {
806                         maybe_snap (i, new_position, nearest_distance);
807                 }
808
809                 for (auto i: _end_snaps) {
810                         maybe_snap (i, new_end, nearest_distance);
811                 }
812
813                 if (nearest_distance) {
814                         /* Snap if it's close; `close' means within a proportion of the time on the timeline */
815                         if (nearest_distance.get().abs() < DCPTime::from_seconds ((width() / pps) / 64)) {
816                                 new_position += nearest_distance.get ();
817                         }
818                 }
819         }
820
821         if (new_position < DCPTime ()) {
822                 new_position = DCPTime ();
823         }
824
825         _down_view->content()->set_position (film, new_position, force_emit);
826
827         film->set_sequence (false);
828 }
829
830
831 void
832 Timeline::force_redraw (dcpomatic::Rect<int> const & r)
833 {
834         _main_canvas->RefreshRect (wxRect (r.x, r.y, r.width, r.height), false);
835 }
836
837
838 shared_ptr<const Film>
839 Timeline::film () const
840 {
841         return _film.lock ();
842 }
843
844
845 void
846 Timeline::resized ()
847 {
848         if (_main_canvas->GetSize().GetWidth() > 0 && _first_resize) {
849                 zoom_all ();
850                 _first_resize = false;
851         }
852         setup_scrollbars ();
853 }
854
855
856 void
857 Timeline::clear_selection ()
858 {
859         for (auto i: _views) {
860                 shared_ptr<TimelineContentView> cv = dynamic_pointer_cast<TimelineContentView>(i);
861                 if (cv) {
862                         cv->set_selected (false);
863                 }
864         }
865 }
866
867
868 TimelineContentViewList
869 Timeline::selected_views () const
870 {
871         TimelineContentViewList sel;
872
873         for (auto i: _views) {
874                 auto cv = dynamic_pointer_cast<TimelineContentView>(i);
875                 if (cv && cv->selected()) {
876                         sel.push_back (cv);
877                 }
878         }
879
880         return sel;
881 }
882
883
884 ContentList
885 Timeline::selected_content () const
886 {
887         ContentList sel;
888
889         for (auto i: selected_views()) {
890                 sel.push_back(i->content());
891         }
892
893         return sel;
894 }
895
896
897 void
898 Timeline::set_selection (ContentList selection)
899 {
900         for (auto i: _views) {
901                 auto cv = dynamic_pointer_cast<TimelineContentView> (i);
902                 if (cv) {
903                         cv->set_selected (find (selection.begin(), selection.end(), cv->content ()) != selection.end ());
904                 }
905         }
906 }
907
908
909 int
910 Timeline::tracks_y_offset () const
911 {
912         return _reels_view->bbox().height + 4;
913 }
914
915
916 int
917 Timeline::width () const
918 {
919         return _main_canvas->GetVirtualSize().GetWidth();
920 }
921
922
923 void
924 Timeline::scrolled (wxScrollWinEvent& ev)
925 {
926         if (ev.GetOrientation() == wxVERTICAL) {
927                 int x, y;
928                 _main_canvas->GetViewStart (&x, &y);
929                 _labels_canvas->Scroll (0, y);
930         }
931         ev.Skip ();
932 }
933
934
935 void
936 Timeline::tool_clicked (Tool t)
937 {
938         switch (t) {
939         case ZOOM:
940         case SELECT:
941                 _tool = t;
942                 break;
943         case ZOOM_ALL:
944                 zoom_all ();
945                 break;
946         case SNAP:
947         case SEQUENCE:
948                 break;
949         }
950 }
951
952
953 void
954 Timeline::zoom_all ()
955 {
956         auto film = _film.lock ();
957         DCPOMATIC_ASSERT (film);
958         set_pixels_per_second ((_main_canvas->GetSize().GetWidth() - 32) / film->length().seconds());
959         set_pixels_per_track ((_main_canvas->GetSize().GetHeight() - tracks_y_offset() - _time_axis_view->bbox().height - 32) / _tracks);
960         setup_scrollbars ();
961         _main_canvas->Scroll (0, 0);
962         _labels_canvas->Scroll (0, 0);
963         Refresh ();
964 }
965
966
967 void
968 Timeline::keypress(wxKeyEvent const& event)
969 {
970         if (event.GetKeyCode() == WXK_DELETE) {
971                 auto film = _film.lock();
972                 film->remove_content(selected_content());
973         }
974 }
975