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