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