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