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