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