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