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