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         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().get_value_or(0), _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                 if (!_timeline.pixels_per_second()) {
296                         return;
297                 }
298
299                 double const pps = _timeline.pixels_per_second().get ();
300                 
301                 gc->SetPen (*wxThePenList->FindOrCreatePen (wxColour (0, 0, 0), 1, wxPENSTYLE_SOLID));
302                 
303                 double mark_interval = rint (128 / pps);
304                 if (mark_interval > 5) {
305                         mark_interval -= int (rint (mark_interval)) % 5;
306                 }
307                 if (mark_interval > 10) {
308                         mark_interval -= int (rint (mark_interval)) % 10;
309                 }
310                 if (mark_interval > 60) {
311                         mark_interval -= int (rint (mark_interval)) % 60;
312                 }
313                 if (mark_interval > 3600) {
314                         mark_interval -= int (rint (mark_interval)) % 3600;
315                 }
316                 
317                 if (mark_interval < 1) {
318                         mark_interval = 1;
319                 }
320
321                 wxGraphicsPath path = gc->CreatePath ();
322                 path.MoveToPoint (_timeline.x_offset(), _y);
323                 path.AddLineToPoint (_timeline.width(), _y);
324                 gc->StrokePath (path);
325
326                 /* Time in seconds */
327                 DCPTime t;
328                 while ((t.seconds() * pps) < _timeline.width()) {
329                         wxGraphicsPath path = gc->CreatePath ();
330                         path.MoveToPoint (time_x (t), _y - 4);
331                         path.AddLineToPoint (time_x (t), _y + 4);
332                         gc->StrokePath (path);
333
334                         double tc = t.seconds ();
335                         int const h = tc / 3600;
336                         tc -= h * 3600;
337                         int const m = tc / 60;
338                         tc -= m * 60;
339                         int const s = tc;
340                         
341                         wxString str = wxString::Format (wxT ("%02d:%02d:%02d"), h, m, s);
342                         wxDouble str_width;
343                         wxDouble str_height;
344                         wxDouble str_descent;
345                         wxDouble str_leading;
346                         gc->GetTextExtent (str, &str_width, &str_height, &str_descent, &str_leading);
347                         
348                         int const tx = _timeline.x_offset() + t.seconds() * pps;
349                         if ((tx + str_width) < _timeline.width()) {
350                                 gc->DrawText (str, time_x (t), _y + 16);
351                         }
352                         
353                         t += DCPTime::from_seconds (mark_interval);
354                 }
355         }
356
357 private:
358         int _y;
359 };
360
361
362 Timeline::Timeline (wxWindow* parent, FilmEditor* ed, shared_ptr<Film> film)
363         : wxPanel (parent, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxFULL_REPAINT_ON_RESIZE)
364         , _film_editor (ed)
365         , _film (film)
366         , _time_axis_view (new TimeAxisView (*this, 32))
367         , _tracks (0)
368         , _left_down (false)
369         , _down_view_position (0)
370         , _first_move (false)
371         , _menu (this)
372         , _snap (true)
373 {
374 #ifndef __WXOSX__
375         SetDoubleBuffered (true);
376 #endif  
377
378         Bind (wxEVT_PAINT,      boost::bind (&Timeline::paint,       this));
379         Bind (wxEVT_LEFT_DOWN,  boost::bind (&Timeline::left_down,   this, _1));
380         Bind (wxEVT_LEFT_UP,    boost::bind (&Timeline::left_up,     this, _1));
381         Bind (wxEVT_RIGHT_DOWN, boost::bind (&Timeline::right_down,  this, _1));
382         Bind (wxEVT_MOTION,     boost::bind (&Timeline::mouse_moved, this, _1));
383         Bind (wxEVT_SIZE,       boost::bind (&Timeline::resized,     this));
384
385         playlist_changed ();
386
387         SetMinSize (wxSize (640, tracks() * track_height() + 96));
388
389         _playlist_connection = film->playlist()->Changed.connect (bind (&Timeline::playlist_changed, this));
390 }
391
392 void
393 Timeline::paint ()
394 {
395         wxPaintDC dc (this);
396
397         wxGraphicsContext* gc = wxGraphicsContext::Create (dc);
398         if (!gc) {
399                 return;
400         }
401
402         gc->SetFont (gc->CreateFont (*wxNORMAL_FONT));
403
404         for (ViewList::iterator i = _views.begin(); i != _views.end(); ++i) {
405                 (*i)->paint (gc);
406         }
407
408         delete gc;
409 }
410
411 void
412 Timeline::playlist_changed ()
413 {
414         ensure_ui_thread ();
415         
416         shared_ptr<const Film> fl = _film.lock ();
417         if (!fl) {
418                 return;
419         }
420
421         _views.clear ();
422         _views.push_back (_time_axis_view);
423
424         ContentList content = fl->playlist()->content ();
425
426         for (ContentList::iterator i = content.begin(); i != content.end(); ++i) {
427                 if (dynamic_pointer_cast<VideoContent> (*i)) {
428                         _views.push_back (shared_ptr<View> (new VideoContentView (*this, *i)));
429                 }
430                 if (dynamic_pointer_cast<AudioContent> (*i)) {
431                         _views.push_back (shared_ptr<View> (new AudioContentView (*this, *i)));
432                 }
433                 if (dynamic_pointer_cast<SubtitleContent> (*i)) {
434                         _views.push_back (shared_ptr<View> (new SubtitleContentView (*this, *i)));
435                 }
436         }
437
438         assign_tracks ();
439         setup_pixels_per_second ();
440         Refresh ();
441 }
442
443 void
444 Timeline::assign_tracks ()
445 {
446         for (ViewList::iterator i = _views.begin(); i != _views.end(); ++i) {
447                 shared_ptr<ContentView> cv = dynamic_pointer_cast<ContentView> (*i);
448                 if (!cv) {
449                         continue;
450                 }
451
452                 shared_ptr<Content> content = cv->content();
453
454                 int t = 0;
455                 while (true) {
456                         ViewList::iterator j = _views.begin();
457                         while (j != _views.end()) {
458                                 shared_ptr<ContentView> test = dynamic_pointer_cast<ContentView> (*j);
459                                 if (!test) {
460                                         ++j;
461                                         continue;
462                                 }
463                                 
464                                 shared_ptr<Content> test_content = test->content();
465                                         
466                                 if (test && test->track() && test->track().get() == t) {
467                                         bool const no_overlap =
468                                                 (content->position() < test_content->position() && content->end() < test_content->position()) ||
469                                                 (content->position() > test_content->end()      && content->end() > test_content->end());
470                                         
471                                         if (!no_overlap) {
472                                                 /* we have an overlap on track `t' */
473                                                 ++t;
474                                                 break;
475                                         }
476                                 }
477                                 
478                                 ++j;
479                         }
480
481                         if (j == _views.end ()) {
482                                 /* no overlap on `t' */
483                                 break;
484                         }
485                 }
486
487                 cv->set_track (t);
488                 _tracks = max (_tracks, t + 1);
489         }
490
491         _time_axis_view->set_y (tracks() * track_height() + 32);
492 }
493
494 int
495 Timeline::tracks () const
496 {
497         return _tracks;
498 }
499
500 void
501 Timeline::setup_pixels_per_second ()
502 {
503         shared_ptr<const Film> film = _film.lock ();
504         if (!film || film->length() == DCPTime ()) {
505                 return;
506         }
507
508         _pixels_per_second = static_cast<double>(width() - x_offset() * 2) / film->length().seconds ();
509 }
510
511 shared_ptr<View>
512 Timeline::event_to_view (wxMouseEvent& ev)
513 {
514         ViewList::iterator i = _views.begin();
515         Position<int> const p (ev.GetX(), ev.GetY());
516         while (i != _views.end() && !(*i)->bbox().contains (p)) {
517                 ++i;
518         }
519
520         if (i == _views.end ()) {
521                 return shared_ptr<View> ();
522         }
523
524         return *i;
525 }
526
527 void
528 Timeline::left_down (wxMouseEvent& ev)
529 {
530         shared_ptr<View> view = event_to_view (ev);
531         shared_ptr<ContentView> content_view = dynamic_pointer_cast<ContentView> (view);
532
533         _down_view.reset ();
534
535         if (content_view) {
536                 _down_view = content_view;
537                 _down_view_position = content_view->content()->position ();
538         }
539
540         for (ViewList::iterator i = _views.begin(); i != _views.end(); ++i) {
541                 shared_ptr<ContentView> cv = dynamic_pointer_cast<ContentView> (*i);
542                 if (!cv) {
543                         continue;
544                 }
545                 
546                 if (!ev.ShiftDown ()) {
547                         cv->set_selected (view == *i);
548                 }
549                 
550                 if (view == *i) {
551                         _film_editor->set_selection (cv->content ());
552                 }
553         }
554
555         if (content_view && ev.ShiftDown ()) {
556                 content_view->set_selected (!content_view->selected ());
557         }
558
559         _left_down = true;
560         _down_point = ev.GetPosition ();
561         _first_move = false;
562
563         if (_down_view) {
564                 _down_view->content()->set_change_signals_frequent (true);
565         }
566 }
567
568 void
569 Timeline::left_up (wxMouseEvent& ev)
570 {
571         _left_down = false;
572
573         if (_down_view) {
574                 _down_view->content()->set_change_signals_frequent (false);
575         }
576
577         set_position_from_event (ev);
578 }
579
580 void
581 Timeline::mouse_moved (wxMouseEvent& ev)
582 {
583         if (!_left_down) {
584                 return;
585         }
586
587         set_position_from_event (ev);
588 }
589
590 void
591 Timeline::right_down (wxMouseEvent& ev)
592 {
593         shared_ptr<View> view = event_to_view (ev);
594         shared_ptr<ContentView> cv = dynamic_pointer_cast<ContentView> (view);
595         if (!cv) {
596                 return;
597         }
598
599         if (!cv->selected ()) {
600                 clear_selection ();
601                 cv->set_selected (true);
602         }
603
604         _menu.popup (_film, selected_content (), ev.GetPosition ());
605 }
606
607 void
608 Timeline::set_position_from_event (wxMouseEvent& ev)
609 {
610         if (!_pixels_per_second) {
611                 return;
612         }
613
614         double const pps = _pixels_per_second.get ();
615
616         wxPoint const p = ev.GetPosition();
617
618         if (!_first_move) {
619                 /* We haven't moved yet; in that case, we must move the mouse some reasonable distance
620                    before the drag is considered to have started.
621                 */
622                 int const dist = sqrt (pow (p.x - _down_point.x, 2) + pow (p.y - _down_point.y, 2));
623                 if (dist < 8) {
624                         return;
625                 }
626                 _first_move = true;
627         }
628
629         if (!_down_view) {
630                 return;
631         }
632         
633         DCPTime new_position = _down_view_position + DCPTime::from_seconds ((p.x - _down_point.x) / pps);
634         
635         if (_snap) {
636                 
637                 bool first = true;
638                 DCPTime nearest_distance = DCPTime::max ();
639                 DCPTime nearest_new_position = DCPTime::max ();
640                 
641                 /* Find the nearest content edge; this is inefficient */
642                 for (ViewList::iterator i = _views.begin(); i != _views.end(); ++i) {
643                         shared_ptr<ContentView> cv = dynamic_pointer_cast<ContentView> (*i);
644                         if (!cv || cv == _down_view) {
645                                 continue;
646                         }
647                         
648                         {
649                                 /* Snap starts to ends */
650                                 DCPTime const d = DCPTime (cv->content()->end() - new_position).abs ();
651                                 if (first || d < nearest_distance) {
652                                         nearest_distance = d;
653                                         nearest_new_position = cv->content()->end();
654                                 }
655                         }
656                         
657                         {
658                                 /* Snap ends to starts */
659                                 DCPTime const d = DCPTime (
660                                         cv->content()->position() - (new_position + _down_view->content()->length_after_trim())
661                                         ).abs ();
662                                 
663                                 if (d < nearest_distance) {
664                                         nearest_distance = d;
665                                         nearest_new_position = cv->content()->position() - _down_view->content()->length_after_trim ();
666                                 }
667                         }
668                         
669                         first = false;
670                 }
671                 
672                 if (!first) {
673                         /* Snap if it's close; `close' means within a proportion of the time on the timeline */
674                         if (nearest_distance < DCPTime::from_seconds ((width() / pps) / 32)) {
675                                 new_position = nearest_new_position;
676                         }
677                 }
678         }
679         
680         if (new_position < DCPTime ()) {
681                 new_position = DCPTime ();
682         }
683         
684         _down_view->content()->set_position (new_position);
685         
686         shared_ptr<Film> film = _film.lock ();
687         assert (film);
688         film->set_sequence_video (false);
689 }
690
691 void
692 Timeline::force_redraw (dcpomatic::Rect<int> const & r)
693 {
694         RefreshRect (wxRect (r.x, r.y, r.width, r.height), false);
695 }
696
697 shared_ptr<const Film>
698 Timeline::film () const
699 {
700         return _film.lock ();
701 }
702
703 void
704 Timeline::resized ()
705 {
706         setup_pixels_per_second ();
707 }
708
709 void
710 Timeline::clear_selection ()
711 {
712         for (ViewList::iterator i = _views.begin(); i != _views.end(); ++i) {
713                 shared_ptr<ContentView> cv = dynamic_pointer_cast<ContentView> (*i);
714                 if (cv) {
715                         cv->set_selected (false);
716                 }
717         }
718 }
719
720 Timeline::ContentViewList
721 Timeline::selected_views () const
722 {
723         ContentViewList sel;
724         
725         for (ViewList::const_iterator i = _views.begin(); i != _views.end(); ++i) {
726                 shared_ptr<ContentView> cv = dynamic_pointer_cast<ContentView> (*i);
727                 if (cv && cv->selected()) {
728                         sel.push_back (cv);
729                 }
730         }
731
732         return sel;
733 }
734
735 ContentList
736 Timeline::selected_content () const
737 {
738         ContentList sel;
739         ContentViewList views = selected_views ();
740         
741         for (ContentViewList::const_iterator i = views.begin(); i != views.end(); ++i) {
742                 sel.push_back ((*i)->content ());
743         }
744
745         return sel;
746 }