4a21e7905a3dc51eef7e4fd7a8e02f9271e23546
[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);
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)
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         for (uint32_t i = i1; i <= i2; i++) {
472                 _drag_points.push_back (nth (i));
473         }
474
475         start_drag_common (0, fraction);
476 }
477
478 /** Start dragging multiple points (with no change in x)
479  *  @param cp Points to drag.
480  *  @param fraction Initial y position (as a fraction of the track height, where 0 is the bottom and 1 the top)
481  */
482 void
483 AutomationLine::start_drag_multiple (list<ControlPoint*> cp, float fraction, XMLNode* state)
484 {
485         trackview.editor().session()->begin_reversible_command (_("automation range move"));
486         trackview.editor().session()->add_command (
487                 new MementoCommand<AutomationList> (memento_command_binder(), state, 0)
488                 );
489
490         _drag_points = cp;
491         start_drag_common (0, fraction);
492 }
493
494
495 struct ControlPointSorter
496 {
497         bool operator() (ControlPoint const * a, ControlPoint const * b) {
498                 return a->get_x() < b->get_x();
499         }
500 };
501
502 /** Common parts of starting a drag.
503  *  @param x Starting x position in units, or 0 if x is being ignored.
504  *  @param fraction Starting y position (as a fraction of the track height, where 0 is the bottom and 1 the top)
505  */
506 void
507 AutomationLine::start_drag_common (double x, float fraction)
508 {
509         _drag_x = x;
510         _drag_distance = 0;
511         _last_drag_fraction = fraction;
512         _drag_had_movement = false;
513         did_push = false;
514
515         _drag_points.sort (ControlPointSorter ());
516
517         /* find the additional points that will be dragged when the user is holding
518            the "push" modifier
519         */
520
521         uint32_t i = _drag_points.back()->view_index () + 1;
522         ControlPoint* p = 0;
523         _push_points.clear ();
524         while ((p = nth (i)) != 0 && p->can_slide()) {
525                 _push_points.push_back (p);
526                 ++i;
527         }
528 }
529
530 /** Should be called to indicate motion during a drag.
531  *  @param x New x position of the drag in canvas units, or undefined if ignore_x == true.
532  *  @param fraction New y fraction.
533  *  @return x position and y fraction that were actually used (once clamped).
534  */
535 pair<double, float>
536 AutomationLine::drag_motion (double const x, float fraction, bool ignore_x, bool with_push)
537 {
538         /* setup the points that are to be moved this time round */
539         list<ControlPoint*> points = _drag_points;
540         if (with_push) {
541                 copy (_push_points.begin(), _push_points.end(), back_inserter (points));
542                 points.sort (ControlPointSorter ());
543         }
544
545         double dx = ignore_x ? 0 : (x - _drag_x);
546         double dy = fraction - _last_drag_fraction;
547
548         for (list<ControlPoint*>::iterator i = points.begin(); i != points.end(); ++i) {
549                 /* Find the points that aren't being moved before and after
550                    this one on the control_points list
551                 */
552
553                 ControlPoint* before = 0;
554                 ControlPoint* after = 0;
555
556                 ControlPoint* last = 0;
557                 for (vector<ControlPoint*>::iterator j = control_points.begin(); j != control_points.end(); ++j) {
558
559                         if (*j == *i) {
560                                 
561                                 before = last;
562                                 
563                                 vector<ControlPoint*>::iterator k = j;
564
565                                 /* Next point */
566                                 ++k;
567
568                                 /* Now move past any points that are being moved this time */
569                                 while (find (points.begin(), points.end(), *k) != points.end() && k != control_points.end ()) {
570                                         ++k;
571                                 }
572                                 
573                                 if (k != control_points.end()) {
574                                         after = *k;
575                                 }
576                                 break;
577                         }
578
579                         if (find (points.begin(), points.end(), *j) == points.end ()) {
580                                 /* This point isn't being moved, so it's the `last' point we've seen */
581                                 last = *j;
582                         }
583                 }
584
585                 /* Clamp dx for this point */
586                 double const before_x = before ? before->get_x() : 0;
587                 double const after_x = after ? after->get_x() : DBL_MAX;
588
589                 double tx = (*i)->get_x() + dx;
590                 tx = max (tx, before_x);
591                 tx = min (tx, after_x);
592                 dx = tx - (*i)->get_x ();
593         }
594
595         /* clamp y */
596         for (list<ControlPoint*>::iterator i = points.begin(); i != points.end(); ++i) {
597                 double const y = ((_height - (*i)->get_y()) / _height) + dy;
598                 if (y < 0) {
599                         dy -= y;
600                 }
601                 if (y > 1) {
602                         dy -= (y - 1);
603                 }
604         }
605
606         pair<double, float> const clamped (_drag_x + dx, _last_drag_fraction + dy);
607         _drag_distance += dx;
608         _drag_x += dx;
609         _last_drag_fraction = fraction;
610
611         for (list<ControlPoint*>::iterator i = _drag_points.begin(); i != _drag_points.end(); ++i) {
612                 (*i)->move_to ((*i)->get_x() + dx, (*i)->get_y() - _height * dy, ControlPoint::Full);
613                 reset_line_coords (**i);
614         }
615
616         if (with_push) {
617                 /* move push points, preserving their y */
618                 for (list<ControlPoint*>::iterator i = _push_points.begin(); i != _push_points.end(); ++i) {
619                         (*i)->move_to ((*i)->get_x() + dx, (*i)->get_y(), ControlPoint::Full);
620                         reset_line_coords (**i);
621                 }
622         }
623
624         if (line_points.size() > 1) {
625                 line->property_points() = line_points;
626         }
627
628         _drag_had_movement = true;
629         if (with_push) {
630                 did_push = with_push;
631         }
632
633         return clamped;
634 }
635
636 /** Should be called to indicate the end of a drag */
637 void
638 AutomationLine::end_drag ()
639 {
640         if (!_drag_had_movement) {
641                 return;
642         }
643
644         alist->freeze ();
645
646         /* set up the points that were moved this time round */
647         list<ControlPoint*> points = _drag_points;
648         if (did_push) {
649                 copy (_push_points.begin(), _push_points.end(), back_inserter (points));
650                 points.sort (ControlPointSorter ());
651         }
652
653         sync_model_with_view_points (points);
654
655         alist->thaw ();
656
657         update_pending = false;
658
659         trackview.editor().session()->add_command (
660                 new MementoCommand<AutomationList>(memento_command_binder (), 0, &alist->get_state())
661                 );
662
663         trackview.editor().session()->set_dirty ();
664         did_push = false;
665 }
666
667 void
668 AutomationLine::sync_model_with_view_point (ControlPoint& cp)
669 {
670         /* find out where the visual control point is.
671            initial results are in canvas units. ask the
672            line to convert them to something relevant.
673         */
674
675         double view_x = cp.get_x();
676         double view_y = 1.0 - (cp.get_y() / _height);
677
678         /* if xval has not changed, set it directly from the model to avoid rounding errors */
679
680         if (view_x == trackview.editor().frame_to_unit_unrounded (_time_converter->to ((*cp.model())->when)) - _offset) {
681                 view_x = (*cp.model())->when - _offset;
682         } else {
683                 view_x = trackview.editor().unit_to_frame (view_x);
684                 view_x = _time_converter->from (view_x + _offset);
685         }
686
687         update_pending = true;
688
689         view_to_model_coord_y (view_y);
690
691         alist->modify (cp.model(), view_x, view_y);
692 }
693
694 bool
695 AutomationLine::control_points_adjacent (double xval, uint32_t & before, uint32_t& after)
696 {
697         ControlPoint *bcp = 0;
698         ControlPoint *acp = 0;
699         double unit_xval;
700
701         unit_xval = trackview.editor().frame_to_unit_unrounded (xval);
702
703         for (vector<ControlPoint*>::iterator i = control_points.begin(); i != control_points.end(); ++i) {
704
705                 if ((*i)->get_x() <= unit_xval) {
706
707                         if (!bcp || (*i)->get_x() > bcp->get_x()) {
708                                 bcp = *i;
709                                 before = bcp->view_index();
710                         }
711
712                 } else if ((*i)->get_x() > unit_xval) {
713                         acp = *i;
714                         after = acp->view_index();
715                         break;
716                 }
717         }
718
719         return bcp && acp;
720 }
721
722 bool
723 AutomationLine::is_last_point (ControlPoint& cp)
724 {
725         // If the list is not empty, and the point is the last point in the list
726
727         if (alist->empty()) {
728                 return false;
729         }
730
731         AutomationList::const_iterator i = alist->end();
732         --i;
733
734         if (cp.model() == i) {
735                 return true;
736         }
737
738         return false;
739 }
740
741 bool
742 AutomationLine::is_first_point (ControlPoint& cp)
743 {
744         // If the list is not empty, and the point is the first point in the list
745
746         if (!alist->empty() && cp.model() == alist->begin()) {
747                 return true;
748         }
749
750         return false;
751 }
752
753 // This is copied into AudioRegionGainLine
754 void
755 AutomationLine::remove_point (ControlPoint& cp)
756 {
757         trackview.editor().session()->begin_reversible_command (_("remove control point"));
758         XMLNode &before = alist->get_state();
759
760         alist->erase (cp.model());
761         
762         trackview.editor().session()->add_command(
763                 new MementoCommand<AutomationList> (memento_command_binder (), &before, &alist->get_state())
764                 );
765
766         trackview.editor().session()->commit_reversible_command ();
767         trackview.editor().session()->set_dirty ();
768 }
769
770 /** Get selectable points within an area.
771  *  @param start Start position in session frames.
772  *  @param end End position in session frames.
773  *  @param bot Bottom y range, as a fraction of line height, where 0 is the bottom of the line.
774  *  @param top Top y range, as a fraction of line height, where 0 is the bottom of the line.
775  *  @param result Filled in with selectable things; in this case, ControlPoints.
776  */
777 void
778 AutomationLine::get_selectables (
779         framepos_t start, framepos_t end, double botfrac, double topfrac, list<Selectable*>& results
780         )
781 {
782         /* convert fractions to display coordinates with 0 at the top of the track */
783         double const bot_track = (1 - topfrac) * trackview.current_height ();
784         double const top_track = (1 - botfrac) * trackview.current_height ();
785
786         for (vector<ControlPoint*>::iterator i = control_points.begin(); i != control_points.end(); ++i) {
787                 double const model_when = (*(*i)->model())->when;
788
789                 /* model_when is relative to the start of the source, so we just need to add on the origin_b here
790                    (as it is the session frame position of the start of the source)
791                 */
792                 
793                 framepos_t const session_frames_when = _time_converter->to (model_when) + _time_converter->origin_b ();
794
795                 if (session_frames_when >= start && session_frames_when <= end && (*i)->get_y() >= bot_track && (*i)->get_y() <= top_track) {
796                         results.push_back (*i);
797                 }
798         }
799 }
800
801 void
802 AutomationLine::get_inverted_selectables (Selection&, list<Selectable*>& /*results*/)
803 {
804         // hmmm ....
805 }
806
807 void
808 AutomationLine::set_selected_points (PointSelection const & points)
809 {
810         for (vector<ControlPoint*>::iterator i = control_points.begin(); i != control_points.end(); ++i) {
811                 (*i)->set_selected (false);
812         }
813
814         for (PointSelection::const_iterator i = points.begin(); i != points.end(); ++i) {
815                 (*i)->set_selected (true);
816         }
817
818         set_colors ();
819 }
820
821 void AutomationLine::set_colors ()
822 {
823         set_line_color (ARDOUR_UI::config()->canvasvar_AutomationLine.get());
824         for (vector<ControlPoint*>::iterator i = control_points.begin(); i != control_points.end(); ++i) {
825                 (*i)->set_color ();
826         }
827 }
828
829 void
830 AutomationLine::list_changed ()
831 {
832         queue_reset ();
833 }
834
835 void
836 AutomationLine::reset_callback (const Evoral::ControlList& events)
837 {
838         uint32_t vp = 0;
839         uint32_t pi = 0;
840         uint32_t np;
841
842         if (events.empty()) {
843                 for (vector<ControlPoint*>::iterator i = control_points.begin(); i != control_points.end(); ++i) {
844                         delete *i;
845                 }
846                 control_points.clear ();
847                 line->hide();
848                 return;
849         }
850
851         /* hide all existing points, and the line */
852
853         for (vector<ControlPoint*>::iterator i = control_points.begin(); i != control_points.end(); ++i) {
854                 (*i)->hide();
855         }
856
857         line->hide ();
858         np = events.size();
859
860         Evoral::ControlList& e = const_cast<Evoral::ControlList&> (events);
861         
862         for (AutomationList::iterator ai = e.begin(); ai != e.end(); ++ai, ++pi) {
863
864                 double tx = (*ai)->when;
865                 double ty = (*ai)->value;
866
867                 /* convert from model coordinates to canonical view coordinates */
868
869                 model_to_view_coord (tx, ty);
870
871                 if (std::isnan (tx) || std::isnan (ty)) {
872                         warning << string_compose (_("Ignoring illegal points on AutomationLine \"%1\""),
873                                                    _name) << endmsg;
874                         continue;
875                 }
876                 
877                 if (tx >= max_framepos || tx < 0 || tx >= _maximum_time) {
878                         continue;
879                 }
880                 
881                 /* convert x-coordinate to a canvas unit coordinate (this takes
882                  * zoom and scroll into account).
883                  */
884                         
885                 tx = trackview.editor().frame_to_unit_unrounded (tx);
886                 
887                 /* convert from canonical view height (0..1.0) to actual
888                  * height coordinates (using X11's top-left rooted system)
889                  */
890
891                 ty = _height - (ty * _height);
892
893                 add_visible_control_point (vp, pi, tx, ty, ai, np);
894                 vp++;
895         }
896
897         /* discard extra CP's to avoid confusing ourselves */
898
899         while (control_points.size() > vp) {
900                 ControlPoint* cp = control_points.back();
901                 control_points.pop_back ();
902                 delete cp;
903         }
904
905         if (!terminal_points_can_slide) {
906                 control_points.back()->set_can_slide(false);
907         }
908
909         if (vp > 1) {
910
911                 /* reset the line coordinates given to the CanvasLine */
912
913                 while (line_points.size() < vp) {
914                         line_points.push_back (Art::Point (0,0));
915                 }
916
917                 while (line_points.size() > vp) {
918                         line_points.pop_back ();
919                 }
920
921                 for (uint32_t n = 0; n < vp; ++n) {
922                         line_points[n].set_x (control_points[n]->get_x());
923                         line_points[n].set_y (control_points[n]->get_y());
924                 }
925
926                 line->property_points() = line_points;
927
928                 if (_visible && alist->interpolation() != AutomationList::Discrete) {
929                         line->show();
930                 }
931         }
932
933         set_selected_points (trackview.editor().get_selection().points);
934 }
935
936 void
937 AutomationLine::reset ()
938 {
939         update_pending = false;
940
941         if (no_draw) {
942                 return;
943         }
944
945         alist->apply_to_points (*this, &AutomationLine::reset_callback);
946 }
947
948 void
949 AutomationLine::clear ()
950 {
951         /* parent must create and commit command */
952         XMLNode &before = alist->get_state();
953         alist->clear();
954
955         trackview.editor().session()->add_command (
956                 new MementoCommand<AutomationList> (memento_command_binder (), &before, &alist->get_state())
957                 );
958 }
959
960 void
961 AutomationLine::change_model (AutomationList::iterator /*i*/, double /*x*/, double /*y*/)
962 {
963 }
964
965 void
966 AutomationLine::set_list (boost::shared_ptr<ARDOUR::AutomationList> list)
967 {
968         alist = list;
969         queue_reset ();
970         connect_to_list ();
971 }
972
973 void
974 AutomationLine::add_visibility (VisibleAspects va)
975 {
976         _visible = VisibleAspects (_visible | va);
977         show ();
978 }
979
980 void
981 AutomationLine::set_visibility (VisibleAspects va)
982 {
983         _visible = va;
984         show ();
985 }
986
987 void
988 AutomationLine::remove_visibility (VisibleAspects va)
989 {
990         _visible = VisibleAspects (_visible & ~va);
991         show ();
992 }
993
994 void
995 AutomationLine::track_entered()
996 {
997         if (alist->interpolation() != AutomationList::Discrete) {
998                 add_visibility (ControlPoints);
999         }
1000 }
1001
1002 void
1003 AutomationLine::track_exited()
1004 {
1005         if (alist->interpolation() != AutomationList::Discrete) {
1006                 remove_visibility (ControlPoints);
1007         }
1008 }
1009
1010 XMLNode &
1011 AutomationLine::get_state (void)
1012 {
1013         /* function as a proxy for the model */
1014         return alist->get_state();
1015 }
1016
1017 int
1018 AutomationLine::set_state (const XMLNode &node, int version)
1019 {
1020         /* function as a proxy for the model */
1021         return alist->set_state (node, version);
1022 }
1023
1024 void
1025 AutomationLine::view_to_model_coord (double& x, double& y) const
1026 {
1027         x = _time_converter->from (x);
1028         view_to_model_coord_y (y);
1029 }
1030
1031 void
1032 AutomationLine::view_to_model_coord_y (double& y) const
1033 {
1034         /* TODO: This should be more generic ... */
1035         if (alist->parameter().type() == GainAutomation ||
1036             alist->parameter().type() == EnvelopeAutomation) {
1037                 y = slider_position_to_gain_with_max (y, Config->get_max_gain());
1038                 y = max (0.0, y);
1039                 y = min (2.0, y);
1040         } else if (alist->parameter().type() == PanAzimuthAutomation ||
1041                    alist->parameter().type() == PanElevationAutomation ||
1042                    alist->parameter().type() == PanWidthAutomation) {
1043                 y = 1.0 - y;
1044         } else if (alist->parameter().type() == PluginAutomation) {
1045                 y = y * (double)(alist->get_max_y()- alist->get_min_y()) + alist->get_min_y();
1046         } else {
1047                 y = rint (y * alist->parameter().max());
1048         }
1049 }
1050
1051 void
1052 AutomationLine::model_to_view_coord (double& x, double& y) const
1053 {
1054         /* TODO: This should be more generic ... */
1055         if (alist->parameter().type() == GainAutomation ||
1056             alist->parameter().type() == EnvelopeAutomation) {
1057                 y = gain_to_slider_position_with_max (y, Config->get_max_gain());
1058         } else if (alist->parameter().type() == PanAzimuthAutomation ||
1059                    alist->parameter().type() == PanElevationAutomation ||
1060                    alist->parameter().type() == PanWidthAutomation) {
1061                 // vertical coordinate axis reversal
1062                 y = 1.0 - y;
1063         } else if (alist->parameter().type() == PluginAutomation) {
1064                 y = (y - alist->get_min_y()) / (double)(alist->get_max_y()- alist->get_min_y());
1065         } else {
1066                 y = y / (double)alist->parameter().max(); /* ... like this */
1067         }
1068
1069         x = _time_converter->to (x) - _offset;
1070 }
1071
1072 /** Called when our list has announced that its interpolation style has changed */
1073 void
1074 AutomationLine::interpolation_changed (AutomationList::InterpolationStyle style)
1075 {
1076         if (style == AutomationList::Discrete) {
1077                 set_visibility (ControlPoints);
1078                 line->hide();
1079         } else {
1080                 set_visibility (Line);
1081         }
1082 }
1083
1084 void
1085 AutomationLine::add_visible_control_point (uint32_t view_index, uint32_t pi, double tx, double ty, 
1086                                            AutomationList::iterator model, uint32_t npoints)
1087 {
1088         ControlPoint::ShapeType shape;
1089
1090         if (view_index >= control_points.size()) {
1091
1092                 /* make sure we have enough control points */
1093
1094                 ControlPoint* ncp = new ControlPoint (*this);
1095                 ncp->set_size (control_point_box_size ());
1096
1097                 control_points.push_back (ncp);
1098         }
1099
1100         if (!terminal_points_can_slide) {
1101                 if (pi == 0) {
1102                         control_points[view_index]->set_can_slide (false);
1103                         if (tx == 0) {
1104                                 shape = ControlPoint::Start;
1105                         } else {
1106                                 shape = ControlPoint::Full;
1107                         }
1108                 } else if (pi == npoints - 1) {
1109                         control_points[view_index]->set_can_slide (false);
1110                         shape = ControlPoint::End;
1111                 } else {
1112                         control_points[view_index]->set_can_slide (true);
1113                         shape = ControlPoint::Full;
1114                 }
1115         } else {
1116                 control_points[view_index]->set_can_slide (true);
1117                 shape = ControlPoint::Full;
1118         }
1119
1120         control_points[view_index]->reset (tx, ty, model, view_index, shape);
1121
1122         /* finally, control visibility */
1123
1124         if (_visible & ControlPoints) {
1125                 control_points[view_index]->show ();
1126                 control_points[view_index]->set_visible (true);
1127         } else {
1128                 control_points[view_index]->set_visible (false);
1129         }
1130 }
1131
1132 void
1133 AutomationLine::connect_to_list ()
1134 {
1135         _list_connections.drop_connections ();
1136
1137         alist->StateChanged.connect (_list_connections, invalidator (*this), boost::bind (&AutomationLine::list_changed, this), gui_context());
1138
1139         alist->InterpolationChanged.connect (
1140                 _list_connections, invalidator (*this), boost::bind (&AutomationLine::interpolation_changed, this, _1), gui_context()
1141                 );
1142 }
1143
1144 MementoCommandBinder<AutomationList>*
1145 AutomationLine::memento_command_binder ()
1146 {
1147         return new SimpleMementoCommandBinder<AutomationList> (*alist.get());
1148 }
1149
1150 /** Set the maximum time that points on this line can be at, relative
1151  *  to the start of the track or region that it is on.
1152  */
1153 void
1154 AutomationLine::set_maximum_time (framecnt_t t)
1155 {
1156         if (_maximum_time == t) {
1157                 return;
1158         }
1159
1160         _maximum_time = t;
1161         reset ();
1162 }
1163
1164
1165 /** @return min and max x positions of points that are in the list, in session frames */
1166 pair<framepos_t, framepos_t>
1167 AutomationLine::get_point_x_range () const
1168 {
1169         pair<framepos_t, framepos_t> r (max_framepos, 0);
1170
1171         for (AutomationList::const_iterator i = the_list()->begin(); i != the_list()->end(); ++i) {
1172                 r.first = min (r.first, session_position (i));
1173                 r.second = max (r.second, session_position (i));
1174         }
1175
1176         return r;
1177 }
1178
1179 framepos_t
1180 AutomationLine::session_position (AutomationList::const_iterator p) const
1181 {
1182         return _time_converter->to ((*p)->when) + _offset + _time_converter->origin_b ();
1183 }
1184
1185 void
1186 AutomationLine::set_offset (framepos_t off)
1187 {
1188         if (_offset == off) {
1189                 return;
1190         }
1191
1192         _offset = off;
1193         reset ();
1194 }