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