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