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