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