just use show() and hide() to manage control point visibility in automation lines
[ardour.git] / gtk2_ardour / automation_line.cc
1 /*
2     Copyright (C) 2002-2003 Paul Davis
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 <cmath>
21 #include <climits>
22 #include <vector>
23 #include <fstream>
24
25 #include "boost/shared_ptr.hpp"
26
27 #include "pbd/floating.h"
28 #include "pbd/memento_command.h"
29 #include "pbd/stl_delete.h"
30 #include "pbd/stacktrace.h"
31
32 #include "ardour/automation_list.h"
33 #include "ardour/dB.h"
34 #include "ardour/debug.h"
35
36 #include "evoral/Curve.hpp"
37
38 #include "canvas/debug.h"
39
40 #include "automation_line.h"
41 #include "control_point.h"
42 #include "gui_thread.h"
43 #include "rgb_macros.h"
44 #include "ardour_ui.h"
45 #include "public_editor.h"
46 #include "utils.h"
47 #include "selection.h"
48 #include "time_axis_view.h"
49 #include "point_selection.h"
50 #include "automation_time_axis.h"
51
52 #include "ardour/event_type_map.h"
53 #include "ardour/session.h"
54
55 #include "i18n.h"
56
57 using namespace std;
58 using namespace ARDOUR;
59 using namespace PBD;
60 using namespace Editing;
61
62 /** @param converter A TimeConverter whose origin_b is the start time of the AutomationList in session frames.
63  *  This will not be deleted by AutomationLine.
64  */
65 AutomationLine::AutomationLine (const string& name, TimeAxisView& tv, ArdourCanvas::Group& parent,
66                 boost::shared_ptr<AutomationList> al,
67                 Evoral::TimeConverter<double, framepos_t>* converter)
68         : trackview (tv)
69         , _name (name)
70         , alist (al)
71         , _time_converter (converter ? converter : new Evoral::IdentityConverter<double, framepos_t>)
72         , _parent_group (parent)
73         , _offset (0)
74         , _maximum_time (max_framepos)
75 {
76         if (converter) {
77                 _time_converter = converter;
78                 _our_time_converter = false;
79         } else {
80                 _time_converter = new Evoral::IdentityConverter<double, framepos_t>;
81                 _our_time_converter = true;
82         }
83         
84         _visible = Line;
85
86         update_pending = false;
87         have_timeout = false;
88         _uses_gain_mapping = false;
89         no_draw = false;
90         _is_boolean = false;
91         terminal_points_can_slide = true;
92         _height = 0;
93
94         group = new ArdourCanvas::Group (&parent);
95         CANVAS_DEBUG_NAME (group, "region gain envelope group");
96
97         line = new ArdourCanvas::PolyLine (group);
98         CANVAS_DEBUG_NAME (line, "region gain envelope line");
99         line->set_data ("line", this);
100         line->set_outline_width (2.0);
101
102         line->Event.connect (sigc::mem_fun (*this, &AutomationLine::event_handler));
103
104         trackview.session()->register_with_memento_command_factory(alist->id(), this);
105
106         if (alist->parameter().type() == GainAutomation ||
107             alist->parameter().type() == EnvelopeAutomation) {
108                 set_uses_gain_mapping (true);
109         }
110
111         interpolation_changed (alist->interpolation ());
112
113         connect_to_list ();
114 }
115
116 AutomationLine::~AutomationLine ()
117 {
118         vector_delete (&control_points);
119         delete group;
120
121         if (_our_time_converter) {
122                 delete _time_converter;
123         }
124 }
125
126 bool
127 AutomationLine::event_handler (GdkEvent* event)
128 {
129         return PublicEditor::instance().canvas_line_event (event, line, this);
130 }
131
132 void
133 AutomationLine::show ()
134 {
135         if (_visible & Line) {
136                 /* Only show the line there are some points, otherwise we may show an out-of-date line
137                    when automation points have been removed (the line will still follow the shape of the
138                    old points).
139                 */
140                 if (alist->interpolation() != AutomationList::Discrete && control_points.size() >= 2) {
141                         line->show();
142                 } else {
143                         line->hide ();
144                 }
145         } else {
146                 line->hide();
147         }
148
149         if (_visible & ControlPoints) {
150                 for (vector<ControlPoint*>::iterator i = control_points.begin(); i != control_points.end(); ++i) {
151                         (*i)->show ();
152                 }
153         } else if (_visible & SelectedControlPoints) {
154                 for (vector<ControlPoint*>::iterator i = control_points.begin(); i != control_points.end(); ++i) {
155                         if ((*i)->get_selected()) {
156                                 (*i)->show ();
157                         } else {
158                                 (*i)->hide ();
159                         }
160                 }
161         } else {
162                 for (vector<ControlPoint*>::iterator i = control_points.begin(); i != control_points.end(); ++i) {
163                         (*i)->hide ();
164                 }
165         }
166 }
167
168 void
169 AutomationLine::hide ()
170 {
171         set_visibility (VisibleAspects (0));
172 }
173
174 double
175 AutomationLine::control_point_box_size ()
176 {
177         if (alist->interpolation() == AutomationList::Discrete) {
178                 return max((_height*4.0) / (double)(alist->parameter().max() - alist->parameter().min()),
179                                 4.0);
180         }
181
182         if (_height > TimeAxisView::preset_height (HeightLarger)) {
183                 return 8.0;
184         } else if (_height > (guint32) TimeAxisView::preset_height (HeightNormal)) {
185                 return 6.0;
186         }
187         return 4.0;
188 }
189
190 void
191 AutomationLine::set_height (guint32 h)
192 {
193         if (h != _height) {
194                 _height = h;
195
196                 double bsz = control_point_box_size();
197
198                 for (vector<ControlPoint*>::iterator i = control_points.begin(); i != control_points.end(); ++i) {
199                         (*i)->set_size (bsz);
200                 }
201
202                 reset ();
203         }
204 }
205
206 void
207 AutomationLine::set_line_color (uint32_t color)
208 {
209         _line_color = color;
210         line->set_outline_color (color);
211 }
212
213 void
214 AutomationLine::set_uses_gain_mapping (bool yn)
215 {
216         if (yn != _uses_gain_mapping) {
217                 _uses_gain_mapping = yn;
218                 reset ();
219         }
220 }
221
222 ControlPoint*
223 AutomationLine::nth (uint32_t n)
224 {
225         if (n < control_points.size()) {
226                 return control_points[n];
227         } else {
228                 return 0;
229         }
230 }
231
232 ControlPoint const *
233 AutomationLine::nth (uint32_t n) const
234 {
235         if (n < control_points.size()) {
236                 return control_points[n];
237         } else {
238                 return 0;
239         }
240 }
241
242 void
243 AutomationLine::modify_point_y (ControlPoint& cp, double y)
244 {
245         /* clamp y-coord appropriately. y is supposed to be a normalized fraction (0.0-1.0),
246            and needs to be converted to a canvas unit distance.
247         */
248
249         y = max (0.0, y);
250         y = min (1.0, y);
251         y = _height - (y * _height);
252
253         double const x = trackview.editor().sample_to_pixel_unrounded (_time_converter->to((*cp.model())->when) - _offset);
254
255         trackview.editor().session()->begin_reversible_command (_("automation event move"));
256         trackview.editor().session()->add_command (
257                 new MementoCommand<AutomationList> (memento_command_binder(), &get_state(), 0)
258                 );
259
260         cp.move_to (x, y, ControlPoint::Full);
261
262         reset_line_coords (cp);
263
264         if (line_points.size() > 1) {
265                 line->set (line_points);
266         }
267
268         alist->freeze ();
269         sync_model_with_view_point (cp);
270         alist->thaw ();
271
272         update_pending = false;
273
274         trackview.editor().session()->add_command (
275                 new MementoCommand<AutomationList> (memento_command_binder(), 0, &alist->get_state())
276                 );
277
278         trackview.editor().session()->commit_reversible_command ();
279         trackview.editor().session()->set_dirty ();
280 }
281
282 void
283 AutomationLine::reset_line_coords (ControlPoint& cp)
284 {
285         if (cp.view_index() < line_points.size()) {
286                 line_points[cp.view_index()].x = cp.get_x ();
287                 line_points[cp.view_index()].y = cp.get_y ();
288         }
289 }
290
291 void
292 AutomationLine::sync_model_with_view_points (list<ControlPoint*> cp)
293 {
294         update_pending = true;
295
296         for (list<ControlPoint*>::iterator i = cp.begin(); i != cp.end(); ++i) {
297                 sync_model_with_view_point (**i);
298         }
299 }
300
301 string
302 AutomationLine::get_verbose_cursor_string (double fraction) const
303 {
304         std::string s = fraction_to_string (fraction);
305         if (_uses_gain_mapping) {
306                 s += " dB";
307         }
308
309         return s;
310 }
311
312 string
313 AutomationLine::get_verbose_cursor_relative_string (double original, double fraction) const
314 {
315         std::string s = fraction_to_string (fraction);
316         if (_uses_gain_mapping) {
317                 s += " dB";
318         }
319
320         std::string d = fraction_to_relative_string (original, fraction);
321
322         if (!d.empty()) {
323
324                 s += " (\u0394";
325                 s += d;
326
327                 if (_uses_gain_mapping) {
328                         s += " dB";
329                 }
330
331                 s += ')';
332         }
333
334         return s;
335 }
336
337 /**
338  *  @param fraction y fraction
339  *  @return string representation of this value, using dB if appropriate.
340  */
341 string
342 AutomationLine::fraction_to_string (double fraction) const
343 {
344         char buf[32];
345
346         if (_uses_gain_mapping) {
347                 if (fraction == 0.0) {
348                         snprintf (buf, sizeof (buf), "-inf");
349                 } else {
350                         snprintf (buf, sizeof (buf), "%.1f", accurate_coefficient_to_dB (slider_position_to_gain_with_max (fraction, Config->get_max_gain())));
351                 }
352         } else {
353                 view_to_model_coord_y (fraction);
354                 if (EventTypeMap::instance().is_integer (alist->parameter())) {
355                         snprintf (buf, sizeof (buf), "%d", (int)fraction);
356                 } else {
357                         snprintf (buf, sizeof (buf), "%.2f", fraction);
358                 }
359         }
360
361         return buf;
362 }
363
364 /**
365  *  @param original an old y-axis fraction
366  *  @param fraction the new y fraction
367  *  @return string representation of the difference between original and fraction, using dB if appropriate.
368  */
369 string
370 AutomationLine::fraction_to_relative_string (double original, double fraction) const
371 {
372         char buf[32];
373
374         if (original == fraction) {
375                 return "0";
376         }
377
378         if (_uses_gain_mapping) {
379                 if (original == 0.0) {
380                         /* there is no sensible representation of a relative
381                            change from -inf dB, so return an empty string.
382                         */
383                         return "";
384                 } else if (fraction == 0.0) {
385                         snprintf (buf, sizeof (buf), "-inf");
386                 } else {
387                         double old_db = accurate_coefficient_to_dB (slider_position_to_gain_with_max (original, Config->get_max_gain()));
388                         double new_db = accurate_coefficient_to_dB (slider_position_to_gain_with_max (fraction, Config->get_max_gain()));
389                         snprintf (buf, sizeof (buf), "%.1f", new_db - old_db);
390                 }
391         } else {
392                 view_to_model_coord_y (original);
393                 view_to_model_coord_y (fraction);
394                 if (EventTypeMap::instance().is_integer (alist->parameter())) {
395                         snprintf (buf, sizeof (buf), "%d", (int)fraction - (int)original);
396                 } else {
397                         snprintf (buf, sizeof (buf), "%.2f", fraction - original);
398                 }
399         }
400
401         return buf;
402 }
403
404 /**
405  *  @param s Value string in the form as returned by fraction_to_string.
406  *  @return Corresponding y fraction.
407  */
408 double
409 AutomationLine::string_to_fraction (string const & s) const
410 {
411         if (s == "-inf") {
412                 return 0;
413         }
414
415         double v;
416         sscanf (s.c_str(), "%lf", &v);
417
418         if (_uses_gain_mapping) {
419                 v = gain_to_slider_position_with_max (dB_to_coefficient (v), Config->get_max_gain());
420         } else {
421                 double dummy = 0.0;
422                 model_to_view_coord (dummy, v);
423         }
424
425         return v;
426 }
427
428 /** Start dragging a single point, possibly adding others if the supplied point is selected and there
429  *  are other selected points.
430  *
431  *  @param cp Point to drag.
432  *  @param x Initial x position (units).
433  *  @param fraction Initial y position (as a fraction of the track height, where 0 is the bottom and 1 the top)
434  */
435 void
436 AutomationLine::start_drag_single (ControlPoint* cp, double x, float fraction)
437 {
438         trackview.editor().session()->begin_reversible_command (_("automation event move"));
439         trackview.editor().session()->add_command (
440                 new MementoCommand<AutomationList> (memento_command_binder(), &get_state(), 0)
441                 );
442
443         _drag_points.clear ();
444         _drag_points.push_back (cp);
445
446         if (cp->get_selected ()) {
447                 for (vector<ControlPoint*>::iterator i = control_points.begin(); i != control_points.end(); ++i) {
448                         if (*i != cp && (*i)->get_selected()) {
449                                 _drag_points.push_back (*i);
450                         }
451                 }
452         }
453
454         start_drag_common (x, fraction);
455 }
456
457 /** Start dragging a line vertically (with no change in x)
458  *  @param i1 Control point index of the `left' point on the line.
459  *  @param i2 Control point index of the `right' point on the line.
460  *  @param fraction Initial y position (as a fraction of the track height, where 0 is the bottom and 1 the top)
461  */
462 void
463 AutomationLine::start_drag_line (uint32_t i1, uint32_t i2, float fraction)
464 {
465         trackview.editor().session()->begin_reversible_command (_("automation range move"));
466         trackview.editor().session()->add_command (
467                 new MementoCommand<AutomationList> (memento_command_binder (), &get_state(), 0)
468                 );
469
470         _drag_points.clear ();
471
472         for (uint32_t i = i1; i <= i2; i++) {
473                 _drag_points.push_back (nth (i));
474         }
475
476         start_drag_common (0, fraction);
477 }
478
479 /** Start dragging multiple points (with no change in x)
480  *  @param cp Points to drag.
481  *  @param fraction Initial y position (as a fraction of the track height, where 0 is the bottom and 1 the top)
482  */
483 void
484 AutomationLine::start_drag_multiple (list<ControlPoint*> cp, float fraction, XMLNode* state)
485 {
486         trackview.editor().session()->begin_reversible_command (_("automation range move"));
487         trackview.editor().session()->add_command (
488                 new MementoCommand<AutomationList> (memento_command_binder(), state, 0)
489                 );
490
491         _drag_points = cp;
492         start_drag_common (0, fraction);
493 }
494
495 struct ControlPointSorter
496 {
497         bool operator() (ControlPoint const * a, ControlPoint const * b) const {
498                 if (floateq (a->get_x(), b->get_x(), 1)) {
499                         return a->view_index() < b->view_index();
500                 } 
501                 return a->get_x() < b->get_x();
502         }
503 };
504
505 AutomationLine::ContiguousControlPoints::ContiguousControlPoints (AutomationLine& al)
506         : line (al), before_x (0), after_x (DBL_MAX) 
507 {
508 }
509
510 void
511 AutomationLine::ContiguousControlPoints::compute_x_bounds ()
512 {
513         uint32_t sz = size();
514
515         if (sz > 0 && sz < line.npoints()) {
516
517                 /* determine the limits on x-axis motion for this 
518                    contiguous range of control points
519                 */
520
521                 if (front()->view_index() > 0) {
522                         before_x = line.nth (front()->view_index() - 1)->get_x();
523                 }
524
525                 /* if our last point has a point after it in the line,
526                    we have an "after" bound
527                 */
528
529                 if (back()->view_index() < (line.npoints() - 2)) {
530                         after_x = line.nth (back()->view_index() + 1)->get_x();
531                 }
532         }
533 }
534
535 double 
536 AutomationLine::ContiguousControlPoints::clamp_dx (double dx) 
537 {
538         if (empty()) {
539                 return dx;
540         }
541
542         /* get the maximum distance we can move any of these points along the x-axis
543          */
544         
545         double tx; /* possible position a point would move to, given dx */
546         ControlPoint* cp;
547         
548         if (dx > 0) {
549                 /* check the last point, since we're moving later in time */
550                 cp = back();
551         } else {
552                 /* check the first point, since we're moving earlier in time */
553                 cp = front();
554         }
555
556         tx = cp->get_x() + dx; // new possible position if we just add the motion 
557         tx = max (tx, before_x); // can't move later than following point
558         tx = min (tx, after_x);  // can't move earlier than preceeding point
559         return  tx - cp->get_x (); 
560 }
561
562 void 
563 AutomationLine::ContiguousControlPoints::move (double dx, double dy) 
564 {
565         for (std::list<ControlPoint*>::iterator i = begin(); i != end(); ++i) {
566                 (*i)->move_to ((*i)->get_x() + dx, (*i)->get_y() - line.height() * dy, ControlPoint::Full);
567                 line.reset_line_coords (**i);
568         }
569 }
570
571 /** Common parts of starting a drag.
572  *  @param x Starting x position in units, or 0 if x is being ignored.
573  *  @param fraction Starting y position (as a fraction of the track height, where 0 is the bottom and 1 the top)
574  */
575 void
576 AutomationLine::start_drag_common (double x, float fraction)
577 {
578         _drag_x = x;
579         _drag_distance = 0;
580         _last_drag_fraction = fraction;
581         _drag_had_movement = false;
582         did_push = false;
583
584         /* they are probably ordered already, but we have to make sure */
585
586         _drag_points.sort (ControlPointSorter());
587 }
588
589
590 /** Should be called to indicate motion during a drag.
591  *  @param x New x position of the drag in canvas units, or undefined if ignore_x == true.
592  *  @param fraction New y fraction.
593  *  @return x position and y fraction that were actually used (once clamped).
594  */
595 pair<double, float>
596 AutomationLine::drag_motion (double const x, float fraction, bool ignore_x, bool with_push, uint32_t& final_index)
597 {
598         if (_drag_points.empty()) {
599                 return pair<double,float> (x,fraction);
600         }
601
602         double dx = ignore_x ? 0 : (x - _drag_x);
603         double dy = fraction - _last_drag_fraction;
604
605         if (!_drag_had_movement) {
606
607                 /* "first move" ... do some stuff that we don't want to do if 
608                    no motion ever took place, but need to do before we handle
609                    motion.
610                 */
611         
612                 /* partition the points we are dragging into (potentially several)
613                  * set(s) of contiguous points. this will not happen with a normal
614                  * drag, but if the user does a discontiguous selection, it can.
615                  */
616                 
617                 uint32_t expected_view_index = 0;
618                 CCP contig;
619                 
620                 for (list<ControlPoint*>::iterator i = _drag_points.begin(); i != _drag_points.end(); ++i) {
621                         if (i == _drag_points.begin() || (*i)->view_index() != expected_view_index) {
622                                 contig.reset (new ContiguousControlPoints (*this));
623                                 contiguous_points.push_back (contig);
624                         }
625                         contig->push_back (*i);
626                         expected_view_index = (*i)->view_index() + 1;
627                 }
628
629                 if (contiguous_points.back()->empty()) {
630                         contiguous_points.pop_back ();
631                 }
632
633                 for (vector<CCP>::iterator ccp = contiguous_points.begin(); ccp != contiguous_points.end(); ++ccp) {
634                         (*ccp)->compute_x_bounds ();
635                 }
636         }       
637
638         /* OK, now on to the stuff related to *this* motion event. First, for
639          * each contiguous range, figure out the maximum x-axis motion we are
640          * allowed (because of neighbouring points that are not moving.
641          * 
642          * if we are moving forwards with push, we don't need to do this, 
643          * since all later points will move too.
644          */
645
646         if (dx < 0 || ((dx > 0) && !with_push)) {
647                 for (vector<CCP>::iterator ccp = contiguous_points.begin(); ccp != contiguous_points.end(); ++ccp) {
648                         double dxt = (*ccp)->clamp_dx (dx);
649                         if (fabs (dxt) < fabs (dx)) {
650                                 dx = dxt;
651                         }
652                 }
653         }
654
655         /* clamp y */
656         
657         for (list<ControlPoint*>::iterator i = _drag_points.begin(); i != _drag_points.end(); ++i) {
658                 double const y = ((_height - (*i)->get_y()) / _height) + dy;
659                 if (y < 0) {
660                         dy -= y;
661                 }
662                 if (y > 1) {
663                         dy -= (y - 1);
664                 }
665         }
666
667         if (dx || dy) {
668
669                 /* and now move each section */
670                 
671                 for (vector<CCP>::iterator ccp = contiguous_points.begin(); ccp != contiguous_points.end(); ++ccp) {
672                         (*ccp)->move (dx, dy);
673                 }
674                 if (with_push) {
675                         final_index = contiguous_points.back()->back()->view_index () + 1;
676                         ControlPoint* p;
677                         uint32_t i = final_index;
678                         while ((p = nth (i)) != 0 && p->can_slide()) {
679                                 p->move_to (p->get_x() + dx, p->get_y(), ControlPoint::Full);
680                                 reset_line_coords (*p);
681                                 ++i;
682                         }
683                 }
684
685                 /* update actual line coordinates (will queue a redraw)
686                  */
687
688                 if (line_points.size() > 1) {
689                         line->set (line_points);
690                 }
691         }
692         
693         _drag_distance += dx;
694         _drag_x += dx;
695         _last_drag_fraction = fraction;
696         _drag_had_movement = true;
697         did_push = with_push;
698
699         return pair<double, float> (_drag_x + dx, _last_drag_fraction + dy);
700 }
701
702 /** Should be called to indicate the end of a drag */
703 void
704 AutomationLine::end_drag (bool with_push, uint32_t final_index)
705 {
706         if (!_drag_had_movement) {
707                 return;
708         }
709
710         alist->freeze ();
711         sync_model_with_view_points (_drag_points);
712
713         if (with_push) {
714                 ControlPoint* p;
715                 uint32_t i = final_index;
716                 while ((p = nth (i)) != 0 && p->can_slide()) {
717                         sync_model_with_view_point (*p);
718                         ++i;
719                 }
720         }
721
722         alist->thaw ();
723
724         update_pending = false;
725
726         trackview.editor().session()->add_command (
727                 new MementoCommand<AutomationList>(memento_command_binder (), 0, &alist->get_state())
728                 );
729
730         trackview.editor().session()->set_dirty ();
731         did_push = false;
732
733         contiguous_points.clear ();
734 }
735
736 void
737 AutomationLine::sync_model_with_view_point (ControlPoint& cp)
738 {
739         /* find out where the visual control point is.
740            initial results are in canvas units. ask the
741            line to convert them to something relevant.
742         */
743
744         double view_x = cp.get_x();
745         double view_y = 1.0 - (cp.get_y() / _height);
746
747         /* if xval has not changed, set it directly from the model to avoid rounding errors */
748
749         if (view_x == trackview.editor().sample_to_pixel_unrounded (_time_converter->to ((*cp.model())->when)) - _offset) {
750                 view_x = (*cp.model())->when - _offset;
751         } else {
752                 view_x = trackview.editor().pixel_to_sample (view_x);
753                 view_x = _time_converter->from (view_x + _offset);
754         }
755
756         update_pending = true;
757
758         view_to_model_coord_y (view_y);
759
760         alist->modify (cp.model(), view_x, view_y);
761 }
762
763 bool
764 AutomationLine::control_points_adjacent (double xval, uint32_t & before, uint32_t& after)
765 {
766         ControlPoint *bcp = 0;
767         ControlPoint *acp = 0;
768         double unit_xval;
769
770         unit_xval = trackview.editor().sample_to_pixel_unrounded (xval);
771
772         for (vector<ControlPoint*>::iterator i = control_points.begin(); i != control_points.end(); ++i) {
773
774                 if ((*i)->get_x() <= unit_xval) {
775
776                         if (!bcp || (*i)->get_x() > bcp->get_x()) {
777                                 bcp = *i;
778                                 before = bcp->view_index();
779                         }
780
781                 } else if ((*i)->get_x() > unit_xval) {
782                         acp = *i;
783                         after = acp->view_index();
784                         break;
785                 }
786         }
787
788         return bcp && acp;
789 }
790
791 bool
792 AutomationLine::is_last_point (ControlPoint& cp)
793 {
794         // If the list is not empty, and the point is the last point in the list
795
796         if (alist->empty()) {
797                 return false;
798         }
799
800         AutomationList::const_iterator i = alist->end();
801         --i;
802
803         if (cp.model() == i) {
804                 return true;
805         }
806
807         return false;
808 }
809
810 bool
811 AutomationLine::is_first_point (ControlPoint& cp)
812 {
813         // If the list is not empty, and the point is the first point in the list
814
815         if (!alist->empty() && cp.model() == alist->begin()) {
816                 return true;
817         }
818
819         return false;
820 }
821
822 // This is copied into AudioRegionGainLine
823 void
824 AutomationLine::remove_point (ControlPoint& cp)
825 {
826         trackview.editor().session()->begin_reversible_command (_("remove control point"));
827         XMLNode &before = alist->get_state();
828
829         alist->erase (cp.model());
830         
831         trackview.editor().session()->add_command(
832                 new MementoCommand<AutomationList> (memento_command_binder (), &before, &alist->get_state())
833                 );
834
835         trackview.editor().session()->commit_reversible_command ();
836         trackview.editor().session()->set_dirty ();
837 }
838
839 /** Get selectable points within an area.
840  *  @param start Start position in session frames.
841  *  @param end End position in session frames.
842  *  @param bot Bottom y range, as a fraction of line height, where 0 is the bottom of the line.
843  *  @param top Top y range, as a fraction of line height, where 0 is the bottom of the line.
844  *  @param result Filled in with selectable things; in this case, ControlPoints.
845  */
846 void
847 AutomationLine::get_selectables (framepos_t start, framepos_t end, double botfrac, double topfrac, list<Selectable*>& results)
848 {
849         /* convert fractions to display coordinates with 0 at the top of the track */
850         double const bot_track = (1 - topfrac) * trackview.current_height ();
851         double const top_track = (1 - botfrac) * trackview.current_height ();
852
853         for (vector<ControlPoint*>::iterator i = control_points.begin(); i != control_points.end(); ++i) {
854                 double const model_when = (*(*i)->model())->when;
855
856                 /* model_when is relative to the start of the source, so we just need to add on the origin_b here
857                    (as it is the session frame position of the start of the source)
858                 */
859                 
860                 framepos_t const session_frames_when = _time_converter->to (model_when) + _time_converter->origin_b ();
861
862                 if (session_frames_when >= start && session_frames_when <= end && (*i)->get_y() >= bot_track && (*i)->get_y() <= top_track) {
863                         results.push_back (*i);
864                 }
865         }
866 }
867
868 void
869 AutomationLine::get_inverted_selectables (Selection&, list<Selectable*>& /*results*/)
870 {
871         // hmmm ....
872 }
873
874 void
875 AutomationLine::set_selected_points (PointSelection const & points)
876 {
877         for (vector<ControlPoint*>::iterator i = control_points.begin(); i != control_points.end(); ++i) {
878                 (*i)->set_selected (false);
879         }
880
881         for (PointSelection::const_iterator i = points.begin(); i != points.end(); ++i) {
882                 (*i)->set_selected (true);
883         }
884
885         set_colors ();
886 }
887
888 void AutomationLine::set_colors ()
889 {
890         set_line_color (ARDOUR_UI::config()->get_canvasvar_AutomationLine());
891         for (vector<ControlPoint*>::iterator i = control_points.begin(); i != control_points.end(); ++i) {
892                 (*i)->set_color ();
893         }
894 }
895
896 void
897 AutomationLine::list_changed ()
898 {
899         DEBUG_TRACE (DEBUG::Automation, string_compose ("\tline changed, existing update pending? %1\n", update_pending));
900
901         if (!update_pending) {
902                 update_pending = true;
903                 Gtkmm2ext::UI::instance()->call_slot (invalidator (*this), boost::bind (&AutomationLine::queue_reset, this));
904         }
905 }
906
907 void
908 AutomationLine::reset_callback (const Evoral::ControlList& events)
909 {
910         uint32_t vp = 0;
911         uint32_t pi = 0;
912         uint32_t np;
913
914         if (events.empty()) {
915                 for (vector<ControlPoint*>::iterator i = control_points.begin(); i != control_points.end(); ++i) {
916                         delete *i;
917                 }
918                 control_points.clear ();
919                 line->hide();
920                 return;
921         }
922
923         /* hide all existing points, and the line */
924
925         for (vector<ControlPoint*>::iterator i = control_points.begin(); i != control_points.end(); ++i) {
926                 (*i)->hide();
927         }
928
929         line->hide ();
930         np = events.size();
931
932         Evoral::ControlList& e = const_cast<Evoral::ControlList&> (events);
933         
934         for (AutomationList::iterator ai = e.begin(); ai != e.end(); ++ai, ++pi) {
935
936                 double tx = (*ai)->when;
937                 double ty = (*ai)->value;
938
939                 /* convert from model coordinates to canonical view coordinates */
940
941                 model_to_view_coord (tx, ty);
942
943                 if (std::isnan (tx) || std::isnan (ty)) {
944                         warning << string_compose (_("Ignoring illegal points on AutomationLine \"%1\""),
945                                                    _name) << endmsg;
946                         continue;
947                 }
948                 
949                 if (tx >= max_framepos || tx < 0 || tx >= _maximum_time) {
950                         continue;
951                 }
952                 
953                 /* convert x-coordinate to a canvas unit coordinate (this takes
954                  * zoom and scroll into account).
955                  */
956                         
957                 tx = trackview.editor().sample_to_pixel_unrounded (tx);
958                 
959                 /* convert from canonical view height (0..1.0) to actual
960                  * height coordinates (using X11's top-left rooted system)
961                  */
962
963                 ty = _height - (ty * _height);
964
965                 add_visible_control_point (vp, pi, tx, ty, ai, np);
966                 vp++;
967         }
968
969         /* discard extra CP's to avoid confusing ourselves */
970
971         while (control_points.size() > vp) {
972                 ControlPoint* cp = control_points.back();
973                 control_points.pop_back ();
974                 delete cp;
975         }
976
977         if (!terminal_points_can_slide) {
978                 control_points.back()->set_can_slide(false);
979         }
980
981         if (vp > 1) {
982
983                 /* reset the line coordinates given to the CanvasLine */
984
985                 while (line_points.size() < vp) {
986                         line_points.push_back (ArdourCanvas::Duple (0,0));
987                 }
988
989                 while (line_points.size() > vp) {
990                         line_points.pop_back ();
991                 }
992
993                 for (uint32_t n = 0; n < vp; ++n) {
994                         line_points[n].x = control_points[n]->get_x();
995                         line_points[n].y = control_points[n]->get_y();
996                 }
997
998                 line->set (line_points);
999
1000                 if (_visible && alist->interpolation() != AutomationList::Discrete) {
1001                         line->show();
1002                 }
1003         }
1004
1005         set_selected_points (trackview.editor().get_selection().points);
1006 }
1007
1008 void
1009 AutomationLine::reset ()
1010 {
1011         DEBUG_TRACE (DEBUG::Automation, "\t\tLINE RESET\n");
1012         update_pending = false;
1013         have_timeout = false;
1014
1015         if (no_draw) {
1016                 return;
1017         }
1018
1019         alist->apply_to_points (*this, &AutomationLine::reset_callback);
1020 }
1021
1022 void
1023 AutomationLine::queue_reset ()
1024 {
1025         /* this must be called from the GUI thread
1026          */
1027
1028         if (trackview.editor().session()->transport_rolling() && alist->automation_write()) {
1029                 /* automation write pass ... defer to a timeout */
1030                 /* redraw in 1/4 second */
1031                 if (!have_timeout) {
1032                         DEBUG_TRACE (DEBUG::Automation, "\tqueue timeout\n");
1033                         Glib::signal_timeout().connect (sigc::bind_return (sigc::mem_fun (*this, &AutomationLine::reset), false), 250);
1034                         have_timeout = true;
1035                 } else {
1036                         DEBUG_TRACE (DEBUG::Automation, "\ttimeout already queued, change ignored\n");
1037                 }
1038         } else {
1039                 reset ();
1040         }
1041 }
1042
1043 void
1044 AutomationLine::clear ()
1045 {
1046         /* parent must create and commit command */
1047         XMLNode &before = alist->get_state();
1048         alist->clear();
1049
1050         trackview.editor().session()->add_command (
1051                 new MementoCommand<AutomationList> (memento_command_binder (), &before, &alist->get_state())
1052                 );
1053 }
1054
1055 void
1056 AutomationLine::change_model (AutomationList::iterator /*i*/, double /*x*/, double /*y*/)
1057 {
1058 }
1059
1060 void
1061 AutomationLine::set_list (boost::shared_ptr<ARDOUR::AutomationList> list)
1062 {
1063         alist = list;
1064         queue_reset ();
1065         connect_to_list ();
1066 }
1067
1068 void
1069 AutomationLine::add_visibility (VisibleAspects va)
1070 {
1071         _visible = VisibleAspects (_visible | va);
1072         show ();
1073 }
1074
1075 void
1076 AutomationLine::set_visibility (VisibleAspects va)
1077 {
1078         _visible = va;
1079         show ();
1080 }
1081
1082 void
1083 AutomationLine::remove_visibility (VisibleAspects va)
1084 {
1085         _visible = VisibleAspects (_visible & ~va);
1086         show ();
1087 }
1088
1089 void
1090 AutomationLine::track_entered()
1091 {
1092         if (alist->interpolation() != AutomationList::Discrete) {
1093                 add_visibility (ControlPoints);
1094         }
1095 }
1096
1097 void
1098 AutomationLine::track_exited()
1099 {
1100         if (alist->interpolation() != AutomationList::Discrete) {
1101                 remove_visibility (ControlPoints);
1102         }
1103 }
1104
1105 XMLNode &
1106 AutomationLine::get_state (void)
1107 {
1108         /* function as a proxy for the model */
1109         return alist->get_state();
1110 }
1111
1112 int
1113 AutomationLine::set_state (const XMLNode &node, int version)
1114 {
1115         /* function as a proxy for the model */
1116         return alist->set_state (node, version);
1117 }
1118
1119 void
1120 AutomationLine::view_to_model_coord (double& x, double& y) const
1121 {
1122         x = _time_converter->from (x);
1123         view_to_model_coord_y (y);
1124 }
1125
1126 void
1127 AutomationLine::view_to_model_coord_y (double& y) const
1128 {
1129         /* TODO: This should be more generic ... */
1130         if (alist->parameter().type() == GainAutomation ||
1131             alist->parameter().type() == EnvelopeAutomation) {
1132                 y = slider_position_to_gain_with_max (y, Config->get_max_gain());
1133                 y = max (0.0, y);
1134                 y = min (2.0, y);
1135         } else if (alist->parameter().type() == PanAzimuthAutomation ||
1136                    alist->parameter().type() == PanElevationAutomation ||
1137                    alist->parameter().type() == PanWidthAutomation) {
1138                 y = 1.0 - y;
1139         } else if (alist->parameter().type() == PluginAutomation) {
1140                 y = y * (double)(alist->get_max_y()- alist->get_min_y()) + alist->get_min_y();
1141         } else {
1142                 y = rint (y * alist->parameter().max());
1143         }
1144 }
1145
1146 void
1147 AutomationLine::model_to_view_coord (double& x, double& y) const
1148 {
1149         /* TODO: This should be more generic ... */
1150         if (alist->parameter().type() == GainAutomation ||
1151             alist->parameter().type() == EnvelopeAutomation) {
1152                 y = gain_to_slider_position_with_max (y, Config->get_max_gain());
1153         } else if (alist->parameter().type() == PanAzimuthAutomation ||
1154                    alist->parameter().type() == PanElevationAutomation ||
1155                    alist->parameter().type() == PanWidthAutomation) {
1156                 // vertical coordinate axis reversal
1157                 y = 1.0 - y;
1158         } else if (alist->parameter().type() == PluginAutomation) {
1159                 y = (y - alist->get_min_y()) / (double)(alist->get_max_y()- alist->get_min_y());
1160         } else {
1161                 y = y / (double)alist->parameter().max(); /* ... like this */
1162         }
1163
1164         x = _time_converter->to (x) - _offset;
1165 }
1166
1167 /** Called when our list has announced that its interpolation style has changed */
1168 void
1169 AutomationLine::interpolation_changed (AutomationList::InterpolationStyle style)
1170 {
1171         if (style == AutomationList::Discrete) {
1172                 set_visibility (ControlPoints);
1173                 line->hide();
1174         } else {
1175                 set_visibility (Line);
1176         }
1177 }
1178
1179 void
1180 AutomationLine::add_visible_control_point (uint32_t view_index, uint32_t pi, double tx, double ty, 
1181                                            AutomationList::iterator model, uint32_t npoints)
1182 {
1183         ControlPoint::ShapeType shape;
1184
1185         if (view_index >= control_points.size()) {
1186
1187                 /* make sure we have enough control points */
1188
1189                 ControlPoint* ncp = new ControlPoint (*this);
1190                 ncp->set_size (control_point_box_size ());
1191
1192                 control_points.push_back (ncp);
1193         }
1194
1195         if (!terminal_points_can_slide) {
1196                 if (pi == 0) {
1197                         control_points[view_index]->set_can_slide (false);
1198                         if (tx == 0) {
1199                                 shape = ControlPoint::Start;
1200                         } else {
1201                                 shape = ControlPoint::Full;
1202                         }
1203                 } else if (pi == npoints - 1) {
1204                         control_points[view_index]->set_can_slide (false);
1205                         shape = ControlPoint::End;
1206                 } else {
1207                         control_points[view_index]->set_can_slide (true);
1208                         shape = ControlPoint::Full;
1209                 }
1210         } else {
1211                 control_points[view_index]->set_can_slide (true);
1212                 shape = ControlPoint::Full;
1213         }
1214
1215         control_points[view_index]->reset (tx, ty, model, view_index, shape);
1216
1217         /* finally, control visibility */
1218
1219         if (_visible & ControlPoints) {
1220                 control_points[view_index]->show ();
1221         } else {
1222                 control_points[view_index]->hide ();
1223         }
1224 }
1225
1226 void
1227 AutomationLine::connect_to_list ()
1228 {
1229         _list_connections.drop_connections ();
1230
1231         alist->StateChanged.connect (_list_connections, invalidator (*this), boost::bind (&AutomationLine::list_changed, this), gui_context());
1232
1233         alist->InterpolationChanged.connect (
1234                 _list_connections, invalidator (*this), boost::bind (&AutomationLine::interpolation_changed, this, _1), gui_context()
1235                 );
1236 }
1237
1238 MementoCommandBinder<AutomationList>*
1239 AutomationLine::memento_command_binder ()
1240 {
1241         return new SimpleMementoCommandBinder<AutomationList> (*alist.get());
1242 }
1243
1244 /** Set the maximum time that points on this line can be at, relative
1245  *  to the start of the track or region that it is on.
1246  */
1247 void
1248 AutomationLine::set_maximum_time (framecnt_t t)
1249 {
1250         if (_maximum_time == t) {
1251                 return;
1252         }
1253
1254         _maximum_time = t;
1255         reset ();
1256 }
1257
1258
1259 /** @return min and max x positions of points that are in the list, in session frames */
1260 pair<framepos_t, framepos_t>
1261 AutomationLine::get_point_x_range () const
1262 {
1263         pair<framepos_t, framepos_t> r (max_framepos, 0);
1264
1265         for (AutomationList::const_iterator i = the_list()->begin(); i != the_list()->end(); ++i) {
1266                 r.first = min (r.first, session_position (i));
1267                 r.second = max (r.second, session_position (i));
1268         }
1269
1270         return r;
1271 }
1272
1273 framepos_t
1274 AutomationLine::session_position (AutomationList::const_iterator p) const
1275 {
1276         return _time_converter->to ((*p)->when) + _offset + _time_converter->origin_b ();
1277 }
1278
1279 void
1280 AutomationLine::set_offset (framepos_t off)
1281 {
1282         if (_offset == off) {
1283                 return;
1284         }
1285
1286         _offset = off;
1287         reset ();
1288 }