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