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