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