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