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