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