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