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