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