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