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