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