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