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