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