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