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