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