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