Merge master.
[dcpomatic.git] / src / wx / timeline.cc
1 /*
2     Copyright (C) 2013-2014 Carl Hetherington <cth@carlh.net>
3
4     This program is free software; you can redistribute it and/or modify
5     it under the terms of the GNU General Public License as published by
6     the Free Software Foundation; either version 2 of the License, or
7     (at your option) any later version.
8
9     This program is distributed in the hope that it will be useful,
10     but WITHOUT ANY WARRANTY; without even the implied warranty of
11     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12     GNU General Public License for more details.
13
14     You should have received a copy of the GNU General Public License
15     along with this program; if not, write to the Free Software
16     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17
18 */
19
20 #include <list>
21 #include <wx/graphics.h>
22 #include <boost/weak_ptr.hpp>
23 #include "lib/film.h"
24 #include "lib/playlist.h"
25 #include "film_editor.h"
26 #include "timeline.h"
27 #include "wx_util.h"
28
29 using std::list;
30 using std::cout;
31 using std::max;
32 using boost::shared_ptr;
33 using boost::weak_ptr;
34 using boost::dynamic_pointer_cast;
35 using boost::bind;
36 using boost::optional;
37
38 /** @class View
39  *  @brief Parent class for components of the timeline (e.g. a piece of content or an axis).
40  */
41 class View : public boost::noncopyable
42 {
43 public:
44         View (Timeline& t)
45                 : _timeline (t)
46         {
47
48         }
49
50         virtual ~View () {}
51                 
52         void paint (wxGraphicsContext* g)
53         {
54                 _last_paint_bbox = bbox ();
55                 do_paint (g);
56         }
57         
58         void force_redraw ()
59         {
60                 _timeline.force_redraw (_last_paint_bbox);
61                 _timeline.force_redraw (bbox ());
62         }
63
64         virtual dcpomatic::Rect<int> bbox () const = 0;
65
66 protected:
67         virtual void do_paint (wxGraphicsContext *) = 0;
68         
69         int time_x (DCPTime t) const
70         {
71                 return _timeline.tracks_position().x + t.seconds() * _timeline.pixels_per_second().get_value_or (0);
72         }
73         
74         Timeline& _timeline;
75
76 private:
77         dcpomatic::Rect<int> _last_paint_bbox;
78 };
79
80
81 /** @class ContentView
82  *  @brief Parent class for views of pieces of content.
83  */
84 class ContentView : public View
85 {
86 public:
87         ContentView (Timeline& tl, shared_ptr<Content> c)
88                 : View (tl)
89                 , _content (c)
90                 , _selected (false)
91         {
92                 _content_connection = c->Changed.connect (bind (&ContentView::content_changed, this, _2, _3));
93         }
94
95         dcpomatic::Rect<int> bbox () const
96         {
97                 assert (_track);
98
99                 shared_ptr<const Film> film = _timeline.film ();
100                 shared_ptr<const Content> content = _content.lock ();
101                 if (!film || !content) {
102                         return dcpomatic::Rect<int> ();
103                 }
104                 
105                 return dcpomatic::Rect<int> (
106                         time_x (content->position ()) - 8,
107                         y_pos (_track.get()) - 8,
108                         content->length_after_trim().seconds() * _timeline.pixels_per_second().get_value_or(0) + 16,
109                         _timeline.track_height() + 16
110                         );
111         }
112
113         void set_selected (bool s) {
114                 _selected = s;
115                 force_redraw ();
116         }
117         
118         bool selected () const {
119                 return _selected;
120         }
121
122         shared_ptr<Content> content () const {
123                 return _content.lock ();
124         }
125
126         void set_track (int t) {
127                 _track = t;
128         }
129
130         void unset_track () {
131                 _track = boost::optional<int> ();
132         }
133
134         optional<int> track () const {
135                 return _track;
136         }
137
138         virtual wxString type () const = 0;
139         virtual wxColour colour () const = 0;
140         
141 private:
142
143         void do_paint (wxGraphicsContext* gc)
144         {
145                 assert (_track);
146
147                 shared_ptr<const Film> film = _timeline.film ();
148                 shared_ptr<const Content> cont = content ();
149                 if (!film || !cont) {
150                         return;
151                 }
152
153                 DCPTime const position = cont->position ();
154                 DCPTime const len = cont->length_after_trim ();
155
156                 wxColour selected (colour().Red() / 2, colour().Green() / 2, colour().Blue() / 2);
157
158                 gc->SetPen (*wxBLACK_PEN);
159                 
160                 gc->SetPen (*wxThePenList->FindOrCreatePen (wxColour (0, 0, 0), 4, wxPENSTYLE_SOLID));
161                 if (_selected) {
162                         gc->SetBrush (*wxTheBrushList->FindOrCreateBrush (selected, wxBRUSHSTYLE_SOLID));
163                 } else {
164                         gc->SetBrush (*wxTheBrushList->FindOrCreateBrush (colour(), wxBRUSHSTYLE_SOLID));
165                 }
166
167                 wxGraphicsPath path = gc->CreatePath ();
168                 path.MoveToPoint    (time_x (position),       y_pos (_track.get()) + 4);
169                 path.AddLineToPoint (time_x (position + len), y_pos (_track.get()) + 4);
170                 path.AddLineToPoint (time_x (position + len), y_pos (_track.get() + 1) - 4);
171                 path.AddLineToPoint (time_x (position),       y_pos (_track.get() + 1) - 4);
172                 path.AddLineToPoint (time_x (position),       y_pos (_track.get()) + 4);
173                 gc->StrokePath (path);
174                 gc->FillPath (path);
175
176                 wxString name = wxString::Format (wxT ("%s [%s]"), std_to_wx (cont->path_summary()).data(), type().data());
177                 wxDouble name_width;
178                 wxDouble name_height;
179                 wxDouble name_descent;
180                 wxDouble name_leading;
181                 gc->GetTextExtent (name, &name_width, &name_height, &name_descent, &name_leading);
182                 
183                 gc->Clip (wxRegion (time_x (position), y_pos (_track.get()), len.seconds() * _timeline.pixels_per_second().get_value_or(0), _timeline.track_height()));
184                 gc->DrawText (name, time_x (position) + 12, y_pos (_track.get() + 1) - name_height - 4);
185                 gc->ResetClip ();
186         }
187
188         int y_pos (int t) const
189         {
190                 return _timeline.tracks_position().y + t * _timeline.track_height();
191         }
192
193         void content_changed (int p, bool frequent)
194         {
195                 ensure_ui_thread ();
196                 
197                 if (p == ContentProperty::POSITION || p == ContentProperty::LENGTH) {
198                         force_redraw ();
199                 }
200
201                 if (!frequent) {
202                         _timeline.setup_pixels_per_second ();
203                         _timeline.Refresh ();
204                 }
205         }
206
207         boost::weak_ptr<Content> _content;
208         optional<int> _track;
209         bool _selected;
210
211         boost::signals2::scoped_connection _content_connection;
212 };
213
214 class AudioContentView : public ContentView
215 {
216 public:
217         AudioContentView (Timeline& tl, shared_ptr<Content> c)
218                 : ContentView (tl, c)
219         {}
220         
221 private:
222         wxString type () const
223         {
224                 return _("audio");
225         }
226
227         wxColour colour () const
228         {
229                 return wxColour (149, 121, 232, 255);
230         }
231 };
232
233 class VideoContentView : public ContentView
234 {
235 public:
236         VideoContentView (Timeline& tl, shared_ptr<Content> c)
237                 : ContentView (tl, c)
238         {}
239
240 private:        
241
242         wxString type () const
243         {
244                 if (dynamic_pointer_cast<FFmpegContent> (content ())) {
245                         return _("video");
246                 } else {
247                         return _("still");
248                 }
249         }
250
251         wxColour colour () const
252         {
253                 return wxColour (242, 92, 120, 255);
254         }
255 };
256
257 class SubtitleContentView : public ContentView
258 {
259 public:
260         SubtitleContentView (Timeline& tl, shared_ptr<Content> c)
261                 : ContentView (tl, c)
262         {}
263
264 private:
265         wxString type () const
266         {
267                 return _("subtitles");
268         }
269
270         wxColour colour () const
271         {
272                 return wxColour (163, 255, 154, 255);
273         }
274 };
275
276 class TimeAxisView : public View
277 {
278 public:
279         TimeAxisView (Timeline& tl, int y)
280                 : View (tl)
281                 , _y (y)
282         {}
283         
284         dcpomatic::Rect<int> bbox () const
285         {
286                 return dcpomatic::Rect<int> (0, _y - 4, _timeline.width(), 24);
287         }
288
289         void set_y (int y)
290         {
291                 _y = y;
292                 force_redraw ();
293         }
294
295 private:        
296
297         void do_paint (wxGraphicsContext* gc)
298         {
299                 if (!_timeline.pixels_per_second()) {
300                         return;
301                 }
302
303                 double const pps = _timeline.pixels_per_second().get ();
304                 
305                 gc->SetPen (*wxThePenList->FindOrCreatePen (wxColour (0, 0, 0), 1, wxPENSTYLE_SOLID));
306                 
307                 double mark_interval = rint (128 / pps);
308                 if (mark_interval > 5) {
309                         mark_interval -= int (rint (mark_interval)) % 5;
310                 }
311                 if (mark_interval > 10) {
312                         mark_interval -= int (rint (mark_interval)) % 10;
313                 }
314                 if (mark_interval > 60) {
315                         mark_interval -= int (rint (mark_interval)) % 60;
316                 }
317                 if (mark_interval > 3600) {
318                         mark_interval -= int (rint (mark_interval)) % 3600;
319                 }
320                 
321                 if (mark_interval < 1) {
322                         mark_interval = 1;
323                 }
324
325                 wxGraphicsPath path = gc->CreatePath ();
326                 path.MoveToPoint (_timeline.x_offset(), _y);
327                 path.AddLineToPoint (_timeline.width(), _y);
328                 gc->StrokePath (path);
329
330                 /* Time in seconds */
331                 DCPTime t;
332                 while ((t.seconds() * pps) < _timeline.width()) {
333                         wxGraphicsPath path = gc->CreatePath ();
334                         path.MoveToPoint (time_x (t), _y - 4);
335                         path.AddLineToPoint (time_x (t), _y + 4);
336                         gc->StrokePath (path);
337
338                         double tc = t.seconds ();
339                         int const h = tc / 3600;
340                         tc -= h * 3600;
341                         int const m = tc / 60;
342                         tc -= m * 60;
343                         int const s = tc;
344                         
345                         wxString str = wxString::Format (wxT ("%02d:%02d:%02d"), h, m, s);
346                         wxDouble str_width;
347                         wxDouble str_height;
348                         wxDouble str_descent;
349                         wxDouble str_leading;
350                         gc->GetTextExtent (str, &str_width, &str_height, &str_descent, &str_leading);
351                         
352                         int const tx = _timeline.x_offset() + t.seconds() * pps;
353                         if ((tx + str_width) < _timeline.width()) {
354                                 gc->DrawText (str, time_x (t), _y + 16);
355                         }
356                         
357                         t += DCPTime::from_seconds (mark_interval);
358                 }
359         }
360
361 private:
362         int _y;
363 };
364
365
366 Timeline::Timeline (wxWindow* parent, FilmEditor* ed, shared_ptr<Film> film)
367         : wxPanel (parent, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxFULL_REPAINT_ON_RESIZE)
368         , _film_editor (ed)
369         , _film (film)
370         , _time_axis_view (new TimeAxisView (*this, 32))
371         , _tracks (0)
372         , _left_down (false)
373         , _down_view_position (0)
374         , _first_move (false)
375         , _menu (this)
376         , _snap (true)
377 {
378 #ifndef __WXOSX__
379         SetDoubleBuffered (true);
380 #endif  
381
382         Bind (wxEVT_PAINT,      boost::bind (&Timeline::paint,       this));
383         Bind (wxEVT_LEFT_DOWN,  boost::bind (&Timeline::left_down,   this, _1));
384         Bind (wxEVT_LEFT_UP,    boost::bind (&Timeline::left_up,     this, _1));
385         Bind (wxEVT_RIGHT_DOWN, boost::bind (&Timeline::right_down,  this, _1));
386         Bind (wxEVT_MOTION,     boost::bind (&Timeline::mouse_moved, this, _1));
387         Bind (wxEVT_SIZE,       boost::bind (&Timeline::resized,     this));
388
389         playlist_changed ();
390
391         SetMinSize (wxSize (640, tracks() * track_height() + 96));
392
393         _playlist_changed_connection = film->playlist()->Changed.connect (bind (&Timeline::playlist_changed, this));
394         _playlist_content_changed_connection = film->playlist()->ContentChanged.connect (bind (&Timeline::playlist_content_changed, this, _2));
395 }
396
397 void
398 Timeline::paint ()
399 {
400         wxPaintDC dc (this);
401
402         wxGraphicsContext* gc = wxGraphicsContext::Create (dc);
403         if (!gc) {
404                 return;
405         }
406
407         gc->SetFont (gc->CreateFont (*wxNORMAL_FONT));
408
409         for (ViewList::iterator i = _views.begin(); i != _views.end(); ++i) {
410                 (*i)->paint (gc);
411         }
412
413         delete gc;
414 }
415
416 void
417 Timeline::playlist_changed ()
418 {
419         ensure_ui_thread ();
420         
421         shared_ptr<const Film> fl = _film.lock ();
422         if (!fl) {
423                 return;
424         }
425
426         _views.clear ();
427         _views.push_back (_time_axis_view);
428
429         ContentList content = fl->playlist()->content ();
430
431         for (ContentList::iterator i = content.begin(); i != content.end(); ++i) {
432                 if (dynamic_pointer_cast<VideoContent> (*i)) {
433                         _views.push_back (shared_ptr<View> (new VideoContentView (*this, *i)));
434                 }
435                 if (dynamic_pointer_cast<AudioContent> (*i)) {
436                         _views.push_back (shared_ptr<View> (new AudioContentView (*this, *i)));
437                 }
438                 if (dynamic_pointer_cast<SubtitleContent> (*i)) {
439                         _views.push_back (shared_ptr<View> (new SubtitleContentView (*this, *i)));
440                 }
441         }
442
443         assign_tracks ();
444         setup_pixels_per_second ();
445         Refresh ();
446 }
447
448 void
449 Timeline::playlist_content_changed (int property)
450 {
451         ensure_ui_thread ();
452
453         if (property == ContentProperty::POSITION) {
454                 assign_tracks ();
455                 setup_pixels_per_second ();
456                 Refresh ();
457         }
458 }
459
460 void
461 Timeline::assign_tracks ()
462 {
463         for (ViewList::iterator i = _views.begin(); i != _views.end(); ++i) {
464                 shared_ptr<ContentView> c = dynamic_pointer_cast<ContentView> (*i);
465                 if (c) {
466                         c->unset_track ();
467                 }
468         }
469
470         for (ViewList::iterator i = _views.begin(); i != _views.end(); ++i) {
471                 shared_ptr<ContentView> cv = dynamic_pointer_cast<ContentView> (*i);
472                 if (!cv) {
473                         continue;
474                 }
475
476                 shared_ptr<Content> content = cv->content();
477
478                 int t = 0;
479                 while (true) {
480                         ViewList::iterator j = _views.begin();
481                         while (j != _views.end()) {
482                                 shared_ptr<ContentView> test = dynamic_pointer_cast<ContentView> (*j);
483                                 if (!test) {
484                                         ++j;
485                                         continue;
486                                 }
487                                 
488                                 shared_ptr<Content> test_content = test->content();
489                                         
490                                 if (test && test->track() && test->track().get() == t) {
491                                         bool const no_overlap =
492                                                 (content->position() < test_content->position() && content->end() < test_content->position()) ||
493                                                 (content->position() > test_content->end()      && content->end() > test_content->end());
494                                         
495                                         if (!no_overlap) {
496                                                 /* we have an overlap on track `t' */
497                                                 ++t;
498                                                 break;
499                                         }
500                                 }
501                                 
502                                 ++j;
503                         }
504
505                         if (j == _views.end ()) {
506                                 /* no overlap on `t' */
507                                 break;
508                         }
509                 }
510
511                 cv->set_track (t);
512                 _tracks = max (_tracks, t + 1);
513         }
514
515         _time_axis_view->set_y (tracks() * track_height() + 32);
516 }
517
518 int
519 Timeline::tracks () const
520 {
521         return _tracks;
522 }
523
524 void
525 Timeline::setup_pixels_per_second ()
526 {
527         shared_ptr<const Film> film = _film.lock ();
528         if (!film || film->length() == DCPTime ()) {
529                 return;
530         }
531
532         _pixels_per_second = static_cast<double>(width() - x_offset() * 2) / film->length().seconds ();
533 }
534
535 shared_ptr<View>
536 Timeline::event_to_view (wxMouseEvent& ev)
537 {
538         ViewList::iterator i = _views.begin();
539         Position<int> const p (ev.GetX(), ev.GetY());
540         while (i != _views.end() && !(*i)->bbox().contains (p)) {
541                 ++i;
542         }
543
544         if (i == _views.end ()) {
545                 return shared_ptr<View> ();
546         }
547
548         return *i;
549 }
550
551 void
552 Timeline::left_down (wxMouseEvent& ev)
553 {
554         shared_ptr<View> view = event_to_view (ev);
555         shared_ptr<ContentView> content_view = dynamic_pointer_cast<ContentView> (view);
556
557         _down_view.reset ();
558
559         if (content_view) {
560                 _down_view = content_view;
561                 _down_view_position = content_view->content()->position ();
562         }
563
564         for (ViewList::iterator i = _views.begin(); i != _views.end(); ++i) {
565                 shared_ptr<ContentView> cv = dynamic_pointer_cast<ContentView> (*i);
566                 if (!cv) {
567                         continue;
568                 }
569                 
570                 if (!ev.ShiftDown ()) {
571                         cv->set_selected (view == *i);
572                 }
573                 
574                 if (view == *i) {
575                         _film_editor->set_selection (cv->content ());
576                 }
577         }
578
579         if (content_view && ev.ShiftDown ()) {
580                 content_view->set_selected (!content_view->selected ());
581         }
582
583         _left_down = true;
584         _down_point = ev.GetPosition ();
585         _first_move = false;
586
587         if (_down_view) {
588                 _down_view->content()->set_change_signals_frequent (true);
589         }
590 }
591
592 void
593 Timeline::left_up (wxMouseEvent& ev)
594 {
595         _left_down = false;
596
597         if (_down_view) {
598                 _down_view->content()->set_change_signals_frequent (false);
599         }
600
601         set_position_from_event (ev);
602 }
603
604 void
605 Timeline::mouse_moved (wxMouseEvent& ev)
606 {
607         if (!_left_down) {
608                 return;
609         }
610
611         set_position_from_event (ev);
612 }
613
614 void
615 Timeline::right_down (wxMouseEvent& ev)
616 {
617         shared_ptr<View> view = event_to_view (ev);
618         shared_ptr<ContentView> cv = dynamic_pointer_cast<ContentView> (view);
619         if (!cv) {
620                 return;
621         }
622
623         if (!cv->selected ()) {
624                 clear_selection ();
625                 cv->set_selected (true);
626         }
627
628         _menu.popup (_film, selected_content (), ev.GetPosition ());
629 }
630
631 void
632 Timeline::set_position_from_event (wxMouseEvent& ev)
633 {
634         if (!_pixels_per_second) {
635                 return;
636         }
637
638         double const pps = _pixels_per_second.get ();
639
640         wxPoint const p = ev.GetPosition();
641
642         if (!_first_move) {
643                 /* We haven't moved yet; in that case, we must move the mouse some reasonable distance
644                    before the drag is considered to have started.
645                 */
646                 int const dist = sqrt (pow (p.x - _down_point.x, 2) + pow (p.y - _down_point.y, 2));
647                 if (dist < 8) {
648                         return;
649                 }
650                 _first_move = true;
651         }
652
653         if (!_down_view) {
654                 return;
655         }
656         
657         DCPTime new_position = _down_view_position + DCPTime::from_seconds ((p.x - _down_point.x) / pps);
658         
659         if (_snap) {
660                 
661                 bool first = true;
662                 DCPTime nearest_distance = DCPTime::max ();
663                 DCPTime nearest_new_position = DCPTime::max ();
664                 
665                 /* Find the nearest content edge; this is inefficient */
666                 for (ViewList::iterator i = _views.begin(); i != _views.end(); ++i) {
667                         shared_ptr<ContentView> cv = dynamic_pointer_cast<ContentView> (*i);
668                         if (!cv || cv == _down_view) {
669                                 continue;
670                         }
671                         
672                         {
673                                 /* Snap starts to ends */
674                                 DCPTime const d = DCPTime (cv->content()->end() - new_position).abs ();
675                                 if (first || d < nearest_distance) {
676                                         nearest_distance = d;
677                                         nearest_new_position = cv->content()->end();
678                                 }
679                         }
680                         
681                         {
682                                 /* Snap ends to starts */
683                                 DCPTime const d = DCPTime (
684                                         cv->content()->position() - (new_position + _down_view->content()->length_after_trim())
685                                         ).abs ();
686                                 
687                                 if (d < nearest_distance) {
688                                         nearest_distance = d;
689                                         nearest_new_position = cv->content()->position() - _down_view->content()->length_after_trim ();
690                                 }
691                         }
692                         
693                         first = false;
694                 }
695                 
696                 if (!first) {
697                         /* Snap if it's close; `close' means within a proportion of the time on the timeline */
698                         if (nearest_distance < DCPTime::from_seconds ((width() / pps) / 32)) {
699                                 new_position = nearest_new_position;
700                         }
701                 }
702         }
703         
704         if (new_position < DCPTime ()) {
705                 new_position = DCPTime ();
706         }
707
708         _down_view->content()->set_position (new_position);
709         
710         shared_ptr<Film> film = _film.lock ();
711         assert (film);
712         film->set_sequence_video (false);
713 }
714
715 void
716 Timeline::force_redraw (dcpomatic::Rect<int> const & r)
717 {
718         RefreshRect (wxRect (r.x, r.y, r.width, r.height), false);
719 }
720
721 shared_ptr<const Film>
722 Timeline::film () const
723 {
724         return _film.lock ();
725 }
726
727 void
728 Timeline::resized ()
729 {
730         setup_pixels_per_second ();
731 }
732
733 void
734 Timeline::clear_selection ()
735 {
736         for (ViewList::iterator i = _views.begin(); i != _views.end(); ++i) {
737                 shared_ptr<ContentView> cv = dynamic_pointer_cast<ContentView> (*i);
738                 if (cv) {
739                         cv->set_selected (false);
740                 }
741         }
742 }
743
744 Timeline::ContentViewList
745 Timeline::selected_views () const
746 {
747         ContentViewList sel;
748         
749         for (ViewList::const_iterator i = _views.begin(); i != _views.end(); ++i) {
750                 shared_ptr<ContentView> cv = dynamic_pointer_cast<ContentView> (*i);
751                 if (cv && cv->selected()) {
752                         sel.push_back (cv);
753                 }
754         }
755
756         return sel;
757 }
758
759 ContentList
760 Timeline::selected_content () const
761 {
762         ContentList sel;
763         ContentViewList views = selected_views ();
764         
765         for (ContentViewList::const_iterator i = views.begin(); i != views.end(); ++i) {
766                 sel.push_back ((*i)->content ());
767         }
768
769         return sel;
770 }