Make send automation work (#4734).
[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 "pbd/stl_delete.h"
26 #include "pbd/memento_command.h"
27 #include "pbd/stacktrace.h"
28
29 #include "ardour/automation_list.h"
30 #include "ardour/dB.h"
31 #include "evoral/Curve.hpp"
32
33 #include "simplerect.h"
34 #include "automation_line.h"
35 #include "control_point.h"
36 #include "gui_thread.h"
37 #include "rgb_macros.h"
38 #include "ardour_ui.h"
39 #include "public_editor.h"
40 #include "utils.h"
41 #include "selection.h"
42 #include "time_axis_view.h"
43 #include "point_selection.h"
44 #include "automation_time_axis.h"
45
46 #include "ardour/event_type_map.h"
47 #include "ardour/session.h"
48
49 #include "i18n.h"
50
51 using namespace std;
52 using namespace ARDOUR;
53 using namespace PBD;
54 using namespace Editing;
55 using namespace Gnome; // for Canvas
56
57 /** @param converter A TimeConverter whose origin_b is the start time of the AutomationList in session frames.
58  *  This will not be deleted by AutomationLine.
59  */
60 AutomationLine::AutomationLine (const string& name, TimeAxisView& tv, ArdourCanvas::Group& parent,
61                 boost::shared_ptr<AutomationList> al,
62                 Evoral::TimeConverter<double, framepos_t>* converter)
63         : trackview (tv)
64         , _name (name)
65         , alist (al)
66         , _time_converter (converter ? converter : new Evoral::IdentityConverter<double, framepos_t>)
67         , _parent_group (parent)
68         , _offset (0)
69         , _maximum_time (max_framepos)
70 {
71         if (converter) {
72                 _time_converter = converter;
73                 _our_time_converter = false;
74         } else {
75                 _time_converter = new Evoral::IdentityConverter<double, framepos_t>;
76                 _our_time_converter = true;
77         }
78         
79         _visible = Line;
80
81         update_pending = false;
82         _uses_gain_mapping = false;
83         no_draw = false;
84         _is_boolean = false;
85         terminal_points_can_slide = true;
86         _height = 0;
87
88         group = new ArdourCanvas::Group (parent);
89         group->property_x() = 0.0;
90         group->property_y() = 0.0;
91
92         line = new ArdourCanvas::Line (*group);
93         line->property_width_pixels() = (guint)1;
94         line->set_data ("line", this);
95
96         line->signal_event().connect (sigc::mem_fun (*this, &AutomationLine::event_handler));
97
98         trackview.session()->register_with_memento_command_factory(alist->id(), this);
99
100         if (alist->parameter().type() == GainAutomation ||
101             alist->parameter().type() == EnvelopeAutomation) {
102                 set_uses_gain_mapping (true);
103         }
104
105         interpolation_changed (alist->interpolation ());
106
107         connect_to_list ();
108 }
109
110 AutomationLine::~AutomationLine ()
111 {
112         vector_delete (&control_points);
113         delete group;
114
115         if (_our_time_converter) {
116                 delete _time_converter;
117         }
118 }
119
120 bool
121 AutomationLine::event_handler (GdkEvent* event)
122 {
123         return PublicEditor::instance().canvas_line_event (event, line, this);
124 }
125
126 void
127 AutomationLine::queue_reset ()
128 {
129         if (!update_pending) {
130                 update_pending = true;
131                 Gtkmm2ext::UI::instance()->call_slot (invalidator (*this), boost::bind (&AutomationLine::reset, this));
132         }
133 }
134
135 void
136 AutomationLine::show ()
137 {
138         if (_visible & Line) {
139                 /* Only show the line there are some points, otherwise we may show an out-of-date line
140                    when automation points have been removed (the line will still follow the shape of the
141                    old points).
142                 */
143                 if (alist->interpolation() != AutomationList::Discrete && control_points.size() >= 2) {
144                         line->show();
145                 } else {
146                         line->hide ();
147                 }
148         } else {
149                 line->hide();
150         }
151
152         if (_visible & ControlPoints) {
153                 for (vector<ControlPoint*>::iterator i = control_points.begin(); i != control_points.end(); ++i) {
154                         (*i)->set_visible (true);
155                         (*i)->show ();
156                 }
157         } else if (_visible & SelectedControlPoints) {
158                 for (vector<ControlPoint*>::iterator i = control_points.begin(); i != control_points.end(); ++i) {
159                         (*i)->set_visible ((*i)->get_selected());
160                 }
161         } else {
162                 for (vector<ControlPoint*>::iterator i = control_points.begin(); i != control_points.end(); ++i) {
163                         (*i)->set_visible (false);
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->property_fill_color_rgba() = 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().frame_to_unit_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->property_points() = line_points;
266         }
267
268         alist->freeze ();
269         sync_model_with_view_point (cp, 0);
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()].set_x (cp.get_x());
287                 line_points[cp.view_index()].set_y (cp.get_y());
288         }
289 }
290
291 void
292 AutomationLine::sync_model_with_view_points (list<ControlPoint*> cp, int64_t distance)
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, distance);
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 /**
313  *  @param fraction y fraction
314  *  @return string representation of this value, using dB if appropriate.
315  */
316 string
317 AutomationLine::fraction_to_string (double fraction) const
318 {
319         char buf[32];
320
321         if (_uses_gain_mapping) {
322                 if (fraction == 0.0) {
323                         snprintf (buf, sizeof (buf), "-inf");
324                 } else {
325                         snprintf (buf, sizeof (buf), "%.1f", accurate_coefficient_to_dB (slider_position_to_gain_with_max (fraction, Config->get_max_gain())));
326                 }
327         } else {
328                 view_to_model_coord_y (fraction);
329                 if (EventTypeMap::instance().is_integer (alist->parameter())) {
330                         snprintf (buf, sizeof (buf), "%d", (int)fraction);
331                 } else {
332                         snprintf (buf, sizeof (buf), "%.2f", fraction);
333                 }
334         }
335
336         return buf;
337 }
338
339
340 /**
341  *  @param s Value string in the form as returned by fraction_to_string.
342  *  @return Corresponding y fraction.
343  */
344 double
345 AutomationLine::string_to_fraction (string const & s) const
346 {
347         if (s == "-inf") {
348                 return 0;
349         }
350
351         double v;
352         sscanf (s.c_str(), "%lf", &v);
353
354         if (_uses_gain_mapping) {
355                 v = gain_to_slider_position_with_max (dB_to_coefficient (v), Config->get_max_gain());
356         } else {
357                 double dummy = 0.0;
358                 model_to_view_coord (dummy, v);
359         }
360
361         return v;
362 }
363
364 /** Start dragging a single point, possibly adding others if the supplied point is selected and there
365  *  are other selected points.
366  *
367  *  @param cp Point to drag.
368  *  @param x Initial x position (units).
369  *  @param fraction Initial y position (as a fraction of the track height, where 0 is the bottom and 1 the top)
370  */
371 void
372 AutomationLine::start_drag_single (ControlPoint* cp, double x, float fraction)
373 {
374         trackview.editor().session()->begin_reversible_command (_("automation event move"));
375         trackview.editor().session()->add_command (
376                 new MementoCommand<AutomationList> (memento_command_binder(), &get_state(), 0)
377                 );
378
379         _drag_points.clear ();
380         _drag_points.push_back (cp);
381
382         if (cp->get_selected ()) {
383                 for (vector<ControlPoint*>::iterator i = control_points.begin(); i != control_points.end(); ++i) {
384                         if (*i != cp && (*i)->get_selected()) {
385                                 _drag_points.push_back (*i);
386                         }
387                 }
388         }
389
390         start_drag_common (x, fraction);
391 }
392
393 /** Start dragging a line vertically (with no change in x)
394  *  @param i1 Control point index of the `left' point on the line.
395  *  @param i2 Control point index of the `right' point on the line.
396  *  @param fraction Initial y position (as a fraction of the track height, where 0 is the bottom and 1 the top)
397  */
398 void
399 AutomationLine::start_drag_line (uint32_t i1, uint32_t i2, float fraction)
400 {
401         trackview.editor().session()->begin_reversible_command (_("automation range move"));
402         trackview.editor().session()->add_command (
403                 new MementoCommand<AutomationList> (memento_command_binder (), &get_state(), 0)
404                 );
405
406         _drag_points.clear ();
407         for (uint32_t i = i1; i <= i2; i++) {
408                 _drag_points.push_back (nth (i));
409         }
410
411         start_drag_common (0, fraction);
412 }
413
414 /** Start dragging multiple points (with no change in x)
415  *  @param cp Points to drag.
416  *  @param fraction Initial y position (as a fraction of the track height, where 0 is the bottom and 1 the top)
417  */
418 void
419 AutomationLine::start_drag_multiple (list<ControlPoint*> cp, float fraction, XMLNode* state)
420 {
421         trackview.editor().session()->begin_reversible_command (_("automation range move"));
422         trackview.editor().session()->add_command (
423                 new MementoCommand<AutomationList> (memento_command_binder(), state, 0)
424                 );
425
426         _drag_points = cp;
427         start_drag_common (0, fraction);
428 }
429
430
431 struct ControlPointSorter
432 {
433         bool operator() (ControlPoint const * a, ControlPoint const * b) {
434                 return a->get_x() < b->get_x();
435         }
436 };
437
438 /** Common parts of starting a drag.
439  *  @param x Starting x position in units, or 0 if x is being ignored.
440  *  @param fraction Starting y position (as a fraction of the track height, where 0 is the bottom and 1 the top)
441  */
442 void
443 AutomationLine::start_drag_common (double x, float fraction)
444 {
445         _drag_x = x;
446         _drag_distance = 0;
447         _last_drag_fraction = fraction;
448         _drag_had_movement = false;
449         did_push = false;
450
451         _drag_points.sort (ControlPointSorter ());
452
453         /* find the additional points that will be dragged when the user is holding
454            the "push" modifier
455         */
456
457         uint32_t i = _drag_points.back()->view_index () + 1;
458         ControlPoint* p = 0;
459         _push_points.clear ();
460         while ((p = nth (i)) != 0 && p->can_slide()) {
461                 _push_points.push_back (p);
462                 ++i;
463         }
464 }
465
466 /** Should be called to indicate motion during a drag.
467  *  @param x New x position of the drag in canvas units, or undefined if ignore_x == true.
468  *  @param fraction New y fraction.
469  *  @return x position and y fraction that were actually used (once clamped).
470  */
471 pair<double, float>
472 AutomationLine::drag_motion (double const x, float fraction, bool ignore_x, bool with_push)
473 {
474         /* setup the points that are to be moved this time round */
475         list<ControlPoint*> points = _drag_points;
476         if (with_push) {
477                 copy (_push_points.begin(), _push_points.end(), back_inserter (points));
478                 points.sort (ControlPointSorter ());
479         }
480
481         double dx = ignore_x ? 0 : (x - _drag_x);
482         double dy = fraction - _last_drag_fraction;
483
484         for (list<ControlPoint*>::iterator i = points.begin(); i != points.end(); ++i) {
485                 /* Find the points that aren't being moved before and after
486                    this one on the control_points list
487                 */
488
489                 ControlPoint* before = 0;
490                 ControlPoint* after = 0;
491
492                 ControlPoint* last = 0;
493                 for (vector<ControlPoint*>::iterator j = control_points.begin(); j != control_points.end(); ++j) {
494
495                         if (*j == *i) {
496                                 
497                                 before = last;
498                                 
499                                 vector<ControlPoint*>::iterator k = j;
500
501                                 /* Next point */
502                                 ++k;
503
504                                 /* Now move past any points that are being moved this time */
505                                 while (find (points.begin(), points.end(), *k) != points.end() && k != control_points.end ()) {
506                                         ++k;
507                                 }
508                                 
509                                 if (k != control_points.end()) {
510                                         after = *k;
511                                 }
512                                 break;
513                         }
514
515                         if (find (points.begin(), points.end(), *j) == points.end ()) {
516                                 /* This point isn't being moved, so it's the `last' point we've seen */
517                                 last = *j;
518                         }
519                 }
520
521                 /* Clamp dx for this point */
522                 double const before_x = before ? before->get_x() : 0;
523                 double const after_x = after ? after->get_x() : DBL_MAX;
524
525                 double tx = (*i)->get_x() + dx;
526                 tx = max (tx, before_x);
527                 tx = min (tx, after_x);
528                 dx = tx - (*i)->get_x ();
529         }
530
531         /* clamp y */
532         for (list<ControlPoint*>::iterator i = points.begin(); i != points.end(); ++i) {
533                 double const y = ((_height - (*i)->get_y()) / _height) + dy;
534                 if (y < 0) {
535                         dy -= y;
536                 }
537                 if (y > 1) {
538                         dy -= (y - 1);
539                 }
540         }
541
542         pair<double, float> const clamped (_drag_x + dx, _last_drag_fraction + dy);
543         _drag_distance += dx;
544         _drag_x += dx;
545         _last_drag_fraction = fraction;
546
547         for (list<ControlPoint*>::iterator i = _drag_points.begin(); i != _drag_points.end(); ++i) {
548                 (*i)->move_to ((*i)->get_x() + dx, (*i)->get_y() - _height * dy, ControlPoint::Full);
549                 reset_line_coords (**i);
550         }
551
552         if (with_push) {
553                 /* move push points, preserving their y */
554                 for (list<ControlPoint*>::iterator i = _push_points.begin(); i != _push_points.end(); ++i) {
555                         (*i)->move_to ((*i)->get_x() + dx, (*i)->get_y(), ControlPoint::Full);
556                         reset_line_coords (**i);
557                 }
558         }
559
560         if (line_points.size() > 1) {
561                 line->property_points() = line_points;
562         }
563
564         _drag_had_movement = true;
565         if (with_push) {
566                 did_push = with_push;
567         }
568
569         return clamped;
570 }
571
572 /** Should be called to indicate the end of a drag */
573 void
574 AutomationLine::end_drag ()
575 {
576         if (!_drag_had_movement) {
577                 return;
578         }
579
580         alist->freeze ();
581
582         /* set up the points that were moved this time round */
583         list<ControlPoint*> points = _drag_points;
584         if (did_push) {
585                 copy (_push_points.begin(), _push_points.end(), back_inserter (points));
586                 points.sort (ControlPointSorter ());
587         }
588
589         sync_model_with_view_points (points, trackview.editor().unit_to_frame (_drag_distance));
590
591         alist->thaw ();
592
593         update_pending = false;
594
595         trackview.editor().session()->add_command (
596                 new MementoCommand<AutomationList>(memento_command_binder (), 0, &alist->get_state())
597                 );
598
599         trackview.editor().session()->set_dirty ();
600         did_push = false;
601 }
602
603 void
604 AutomationLine::sync_model_with_view_point (ControlPoint& cp, framecnt_t distance)
605 {
606         /* find out where the visual control point is.
607            initial results are in canvas units. ask the
608            line to convert them to something relevant.
609         */
610
611         double view_x = cp.get_x();
612         double view_y = 1.0 - (cp.get_y() / _height);
613
614         /* if xval has not changed, set it directly from the model to avoid rounding errors */
615
616         if (view_x == trackview.editor().frame_to_unit_unrounded (_time_converter->to ((*cp.model())->when)) - _offset) {
617                 view_x = (*cp.model())->when - _offset;
618         } else {
619                 view_x = trackview.editor().unit_to_frame (view_x);
620                 view_x = _time_converter->from (view_x + _offset);
621         }
622
623         update_pending = true;
624
625         view_to_model_coord_y (view_y);
626
627         alist->modify (cp.model(), view_x, view_y);
628 }
629
630 bool
631 AutomationLine::control_points_adjacent (double xval, uint32_t & before, uint32_t& after)
632 {
633         ControlPoint *bcp = 0;
634         ControlPoint *acp = 0;
635         double unit_xval;
636
637         unit_xval = trackview.editor().frame_to_unit_unrounded (xval);
638
639         for (vector<ControlPoint*>::iterator i = control_points.begin(); i != control_points.end(); ++i) {
640
641                 if ((*i)->get_x() <= unit_xval) {
642
643                         if (!bcp || (*i)->get_x() > bcp->get_x()) {
644                                 bcp = *i;
645                                 before = bcp->view_index();
646                         }
647
648                 } else if ((*i)->get_x() > unit_xval) {
649                         acp = *i;
650                         after = acp->view_index();
651                         break;
652                 }
653         }
654
655         return bcp && acp;
656 }
657
658 bool
659 AutomationLine::is_last_point (ControlPoint& cp)
660 {
661         // If the list is not empty, and the point is the last point in the list
662
663         if (alist->empty()) {
664                 return false;
665         }
666
667         AutomationList::const_iterator i = alist->end();
668         --i;
669
670         if (cp.model() == i) {
671                 return true;
672         }
673
674         return false;
675 }
676
677 bool
678 AutomationLine::is_first_point (ControlPoint& cp)
679 {
680         // If the list is not empty, and the point is the first point in the list
681
682         if (!alist->empty() && cp.model() == alist->begin()) {
683                 return true;
684         }
685
686         return false;
687 }
688
689 // This is copied into AudioRegionGainLine
690 void
691 AutomationLine::remove_point (ControlPoint& cp)
692 {
693         trackview.editor().session()->begin_reversible_command (_("remove control point"));
694         XMLNode &before = alist->get_state();
695
696         alist->erase (cp.model());
697         
698         trackview.editor().session()->add_command(
699                 new MementoCommand<AutomationList> (memento_command_binder (), &before, &alist->get_state())
700                 );
701
702         trackview.editor().session()->commit_reversible_command ();
703         trackview.editor().session()->set_dirty ();
704 }
705
706 /** Get selectable points within an area.
707  *  @param start Start position in session frames.
708  *  @param end End position in session frames.
709  *  @param bot Bottom y range, as a fraction of line height, where 0 is the bottom of the line.
710  *  @param top Top y range, as a fraction of line height, where 0 is the bottom of the line.
711  *  @param result Filled in with selectable things; in this case, ControlPoints.
712  */
713 void
714 AutomationLine::get_selectables (
715         framepos_t start, framepos_t end, double botfrac, double topfrac, list<Selectable*>& results
716         )
717 {
718         /* convert fractions to display coordinates with 0 at the top of the track */
719         double const bot_track = (1 - topfrac) * trackview.current_height ();
720         double const top_track = (1 - botfrac) * trackview.current_height ();
721
722         for (vector<ControlPoint*>::iterator i = control_points.begin(); i != control_points.end(); ++i) {
723                 double const model_when = (*(*i)->model())->when;
724
725                 /* model_when is relative to the start of the source, so we just need to add on the origin_b here
726                    (as it is the session frame position of the start of the source)
727                 */
728                 
729                 framepos_t const session_frames_when = _time_converter->to (model_when) + _time_converter->origin_b ();
730
731                 if (session_frames_when >= start && session_frames_when <= end && (*i)->get_y() >= bot_track && (*i)->get_y() <= top_track) {
732                         results.push_back (*i);
733                 }
734         }
735 }
736
737 void
738 AutomationLine::get_inverted_selectables (Selection&, list<Selectable*>& /*results*/)
739 {
740         // hmmm ....
741 }
742
743 void
744 AutomationLine::set_selected_points (PointSelection const & points)
745 {
746         for (vector<ControlPoint*>::iterator i = control_points.begin(); i != control_points.end(); ++i) {
747                 (*i)->set_selected (false);
748         }
749
750         for (PointSelection::const_iterator i = points.begin(); i != points.end(); ++i) {
751                 (*i)->set_selected (true);
752         }
753
754         set_colors ();
755 }
756
757 void AutomationLine::set_colors ()
758 {
759         set_line_color (ARDOUR_UI::config()->canvasvar_AutomationLine.get());
760         for (vector<ControlPoint*>::iterator i = control_points.begin(); i != control_points.end(); ++i) {
761                 (*i)->set_color ();
762         }
763 }
764
765 void
766 AutomationLine::list_changed ()
767 {
768         queue_reset ();
769 }
770
771 void
772 AutomationLine::reset_callback (const Evoral::ControlList& events)
773 {
774         uint32_t vp = 0;
775         uint32_t pi = 0;
776         uint32_t np;
777
778         if (events.empty()) {
779                 for (vector<ControlPoint*>::iterator i = control_points.begin(); i != control_points.end(); ++i) {
780                         delete *i;
781                 }
782                 control_points.clear ();
783                 line->hide();
784                 return;
785         }
786
787         /* hide all existing points, and the line */
788
789         for (vector<ControlPoint*>::iterator i = control_points.begin(); i != control_points.end(); ++i) {
790                 (*i)->hide();
791         }
792
793         line->hide ();
794         np = events.size();
795
796         Evoral::ControlList& e = const_cast<Evoral::ControlList&> (events);
797         
798         for (AutomationList::iterator ai = e.begin(); ai != e.end(); ++ai, ++pi) {
799
800                 double tx = (*ai)->when;
801                 double ty = (*ai)->value;
802
803                 /* convert from model coordinates to canonical view coordinates */
804
805                 model_to_view_coord (tx, ty);
806
807                 if (std::isnan (tx) || std::isnan (ty)) {
808                         warning << string_compose (_("Ignoring illegal points on AutomationLine \"%1\""),
809                                                    _name) << endmsg;
810                         continue;
811                 }
812                 
813                 if (tx >= max_framepos || tx < 0 || tx >= _maximum_time) {
814                         continue;
815                 }
816                 
817                 /* convert x-coordinate to a canvas unit coordinate (this takes
818                  * zoom and scroll into account).
819                  */
820                         
821                 tx = trackview.editor().frame_to_unit_unrounded (tx);
822                 
823                 /* convert from canonical view height (0..1.0) to actual
824                  * height coordinates (using X11's top-left rooted system)
825                  */
826
827                 ty = _height - (ty * _height);
828
829                 add_visible_control_point (vp, pi, tx, ty, ai, np);
830                 vp++;
831         }
832
833         /* discard extra CP's to avoid confusing ourselves */
834
835         while (control_points.size() > vp) {
836                 ControlPoint* cp = control_points.back();
837                 control_points.pop_back ();
838                 delete cp;
839         }
840
841         if (!terminal_points_can_slide) {
842                 control_points.back()->set_can_slide(false);
843         }
844
845         if (vp > 1) {
846
847                 /* reset the line coordinates given to the CanvasLine */
848
849                 while (line_points.size() < vp) {
850                         line_points.push_back (Art::Point (0,0));
851                 }
852
853                 while (line_points.size() > vp) {
854                         line_points.pop_back ();
855                 }
856
857                 for (uint32_t n = 0; n < vp; ++n) {
858                         line_points[n].set_x (control_points[n]->get_x());
859                         line_points[n].set_y (control_points[n]->get_y());
860                 }
861
862                 line->property_points() = line_points;
863
864                 if (_visible && alist->interpolation() != AutomationList::Discrete) {
865                         line->show();
866                 }
867         }
868
869         set_selected_points (trackview.editor().get_selection().points);
870 }
871
872 void
873 AutomationLine::reset ()
874 {
875         update_pending = false;
876
877         if (no_draw) {
878                 return;
879         }
880
881         alist->apply_to_points (*this, &AutomationLine::reset_callback);
882 }
883
884 void
885 AutomationLine::clear ()
886 {
887         /* parent must create and commit command */
888         XMLNode &before = alist->get_state();
889         alist->clear();
890
891         trackview.editor().session()->add_command (
892                 new MementoCommand<AutomationList> (memento_command_binder (), &before, &alist->get_state())
893                 );
894 }
895
896 void
897 AutomationLine::change_model (AutomationList::iterator /*i*/, double /*x*/, double /*y*/)
898 {
899 }
900
901 void
902 AutomationLine::set_list (boost::shared_ptr<ARDOUR::AutomationList> list)
903 {
904         alist = list;
905         queue_reset ();
906         connect_to_list ();
907 }
908
909 void
910 AutomationLine::add_visibility (VisibleAspects va)
911 {
912         _visible = VisibleAspects (_visible | va);
913         show ();
914 }
915
916 void
917 AutomationLine::set_visibility (VisibleAspects va)
918 {
919         _visible = va;
920         show ();
921 }
922
923 void
924 AutomationLine::remove_visibility (VisibleAspects va)
925 {
926         _visible = VisibleAspects (_visible & ~va);
927         show ();
928 }
929
930 void
931 AutomationLine::track_entered()
932 {
933         if (alist->interpolation() != AutomationList::Discrete) {
934                 add_visibility (ControlPoints);
935         }
936 }
937
938 void
939 AutomationLine::track_exited()
940 {
941         if (alist->interpolation() != AutomationList::Discrete) {
942                 remove_visibility (ControlPoints);
943         }
944 }
945
946 XMLNode &
947 AutomationLine::get_state (void)
948 {
949         /* function as a proxy for the model */
950         return alist->get_state();
951 }
952
953 int
954 AutomationLine::set_state (const XMLNode &node, int version)
955 {
956         /* function as a proxy for the model */
957         return alist->set_state (node, version);
958 }
959
960 void
961 AutomationLine::view_to_model_coord (double& x, double& y) const
962 {
963         x = _time_converter->from (x);
964         view_to_model_coord_y (y);
965 }
966
967 void
968 AutomationLine::view_to_model_coord_y (double& y) const
969 {
970         /* TODO: This should be more generic ... */
971         if (alist->parameter().type() == GainAutomation ||
972             alist->parameter().type() == EnvelopeAutomation) {
973                 y = slider_position_to_gain_with_max (y, Config->get_max_gain());
974                 y = max (0.0, y);
975                 y = min (2.0, y);
976         } else if (alist->parameter().type() == PanAzimuthAutomation ||
977                    alist->parameter().type() == PanElevationAutomation ||
978                    alist->parameter().type() == PanWidthAutomation) {
979                 y = 1.0 - y;
980         } else if (alist->parameter().type() == PluginAutomation) {
981                 y = y * (double)(alist->get_max_y()- alist->get_min_y()) + alist->get_min_y();
982         } else {
983                 y = rint (y * alist->parameter().max());
984         }
985 }
986
987 void
988 AutomationLine::model_to_view_coord (double& x, double& y) const
989 {
990         /* TODO: This should be more generic ... */
991         if (alist->parameter().type() == GainAutomation ||
992             alist->parameter().type() == EnvelopeAutomation) {
993                 y = gain_to_slider_position_with_max (y, Config->get_max_gain());
994         } else if (alist->parameter().type() == PanAzimuthAutomation ||
995                    alist->parameter().type() == PanElevationAutomation ||
996                    alist->parameter().type() == PanWidthAutomation) {
997                 // vertical coordinate axis reversal
998                 y = 1.0 - y;
999         } else if (alist->parameter().type() == PluginAutomation) {
1000                 y = (y - alist->get_min_y()) / (double)(alist->get_max_y()- alist->get_min_y());
1001         } else {
1002                 y = y / (double)alist->parameter().max(); /* ... like this */
1003         }
1004
1005         x = _time_converter->to (x) - _offset;
1006 }
1007
1008 /** Called when our list has announced that its interpolation style has changed */
1009 void
1010 AutomationLine::interpolation_changed (AutomationList::InterpolationStyle style)
1011 {
1012         if (style == AutomationList::Discrete) {
1013                 set_visibility (ControlPoints);
1014                 line->hide();
1015         } else {
1016                 set_visibility (Line);
1017         }
1018 }
1019
1020 void
1021 AutomationLine::add_visible_control_point (uint32_t view_index, uint32_t pi, double tx, double ty, 
1022                                            AutomationList::iterator model, uint32_t npoints)
1023 {
1024         ControlPoint::ShapeType shape;
1025
1026         if (view_index >= control_points.size()) {
1027
1028                 /* make sure we have enough control points */
1029
1030                 ControlPoint* ncp = new ControlPoint (*this);
1031                 ncp->set_size (control_point_box_size ());
1032
1033                 control_points.push_back (ncp);
1034         }
1035
1036         if (!terminal_points_can_slide) {
1037                 if (pi == 0) {
1038                         control_points[view_index]->set_can_slide (false);
1039                         if (tx == 0) {
1040                                 shape = ControlPoint::Start;
1041                         } else {
1042                                 shape = ControlPoint::Full;
1043                         }
1044                 } else if (pi == npoints - 1) {
1045                         control_points[view_index]->set_can_slide (false);
1046                         shape = ControlPoint::End;
1047                 } else {
1048                         control_points[view_index]->set_can_slide (true);
1049                         shape = ControlPoint::Full;
1050                 }
1051         } else {
1052                 control_points[view_index]->set_can_slide (true);
1053                 shape = ControlPoint::Full;
1054         }
1055
1056         control_points[view_index]->reset (tx, ty, model, view_index, shape);
1057
1058         /* finally, control visibility */
1059
1060         if (_visible & ControlPoints) {
1061                 control_points[view_index]->show ();
1062                 control_points[view_index]->set_visible (true);
1063         } else {
1064                 control_points[view_index]->set_visible (false);
1065         }
1066 }
1067
1068 void
1069 AutomationLine::connect_to_list ()
1070 {
1071         _list_connections.drop_connections ();
1072
1073         alist->StateChanged.connect (_list_connections, invalidator (*this), boost::bind (&AutomationLine::list_changed, this), gui_context());
1074
1075         alist->InterpolationChanged.connect (
1076                 _list_connections, invalidator (*this), boost::bind (&AutomationLine::interpolation_changed, this, _1), gui_context()
1077                 );
1078 }
1079
1080 MementoCommandBinder<AutomationList>*
1081 AutomationLine::memento_command_binder ()
1082 {
1083         return new SimpleMementoCommandBinder<AutomationList> (*alist.get());
1084 }
1085
1086 /** Set the maximum time that points on this line can be at, relative
1087  *  to the start of the track or region that it is on.
1088  */
1089 void
1090 AutomationLine::set_maximum_time (framecnt_t t)
1091 {
1092         if (_maximum_time == t) {
1093                 return;
1094         }
1095
1096         _maximum_time = t;
1097         reset ();
1098 }
1099
1100
1101 /** @return min and max x positions of points that are in the list, in session frames */
1102 pair<framepos_t, framepos_t>
1103 AutomationLine::get_point_x_range () const
1104 {
1105         pair<framepos_t, framepos_t> r (max_framepos, 0);
1106
1107         for (AutomationList::const_iterator i = the_list()->begin(); i != the_list()->end(); ++i) {
1108                 r.first = min (r.first, session_position (i));
1109                 r.second = max (r.second, session_position (i));
1110         }
1111
1112         return r;
1113 }
1114
1115 framepos_t
1116 AutomationLine::session_position (AutomationList::const_iterator p) const
1117 {
1118         return _time_converter->to ((*p)->when) + _offset + _time_converter->origin_b ();
1119 }
1120
1121 void
1122 AutomationLine::set_offset (framepos_t off)
1123 {
1124         if (_offset == off) {
1125                 return;
1126         }
1127
1128         _offset = off;
1129         reset ();
1130 }