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