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