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