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