use newly factored canvas in gtk2_ardour
[ardour.git] / gtk2_ardour / automation_line.cc
1 /*
2     Copyright (C) 2002-2003 Paul Davis
3
4     This program is free software; you can redistribute it and/or modify
5     it under the terms of the GNU General Public License as published by
6     the Free Software Foundation; either version 2 of the License, or
7     (at your option) any later version.
8
9     This program is distributed in the hope that it will be useful,
10     but WITHOUT ANY WARRANTY; without even the implied warranty of
11     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12     GNU General Public License for more details.
13
14     You should have received a copy of the GNU General Public License
15     along with this program; if not, write to the Free Software
16     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17
18 */
19
20 #ifdef COMPILER_MSVC
21 #include <float.h>
22 /* isinf() & isnan() are C99 standards, which older MSVC doesn't provide */
23 #define isinf(val) !((bool)_finite((double)val))
24 #define isnan(val) (bool)_isnan((double)val)
25 #endif
26
27 #include <cmath>
28 #include <climits>
29 #include <vector>
30 #include <fstream>
31
32 #include "boost/shared_ptr.hpp"
33
34 #include "pbd/floating.h"
35 #include "pbd/memento_command.h"
36 #include "pbd/stl_delete.h"
37 #include "pbd/stacktrace.h"
38
39 #include "ardour/automation_list.h"
40 #include "ardour/dB.h"
41 #include "ardour/debug.h"
42 #include "ardour/tempo.h"
43
44 #include "evoral/Curve.hpp"
45
46 #include "canvas/debug.h"
47
48 #include "automation_line.h"
49 #include "control_point.h"
50 #include "gui_thread.h"
51 #include "rgb_macros.h"
52 #include "ardour_ui.h"
53 #include "public_editor.h"
54 #include "utils.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
63 #include "i18n.h"
64
65 using namespace std;
66 using namespace ARDOUR;
67 using namespace PBD;
68 using namespace Editing;
69
70 /** @param converter A TimeConverter whose origin_b is the start time of the AutomationList in session frames.
71  *  This will not be deleted by AutomationLine.
72  */
73 AutomationLine::AutomationLine (const string& name, TimeAxisView& tv, ArdourCanvas::Item& parent,
74                                 boost::shared_ptr<AutomationList> al,
75                                 Evoral::TimeConverter<double, framepos_t>* converter)
76         : trackview (tv)
77         , _name (name)
78         , alist (al)
79         , _time_converter (converter ? converter : new Evoral::IdentityConverter<double, framepos_t>)
80         , _parent_group (parent)
81         , _offset (0)
82         , _maximum_time (max_framepos)
83 {
84         if (converter) {
85                 _time_converter = converter;
86                 _our_time_converter = false;
87         } else {
88                 _time_converter = new Evoral::IdentityConverter<double, framepos_t>;
89                 _our_time_converter = true;
90         }
91         
92         _visible = Line;
93
94         update_pending = false;
95         have_timeout = false;
96         _uses_gain_mapping = false;
97         no_draw = false;
98         _is_boolean = false;
99         terminal_points_can_slide = true;
100         _height = 0;
101
102         group = new ArdourCanvas::Layout (&parent);
103         CANVAS_DEBUG_NAME (group, "region gain envelope group");
104
105         line = new ArdourCanvas::PolyLine (group);
106         CANVAS_DEBUG_NAME (line, "region gain envelope line");
107         line->set_data ("line", this);
108         line->set_outline_width (2.0);
109         line->set_covers_threshold (4.0);
110
111         line->Event.connect (sigc::mem_fun (*this, &AutomationLine::event_handler));
112
113         trackview.session()->register_with_memento_command_factory(alist->id(), this);
114
115         if (alist->parameter().type() == GainAutomation ||
116             alist->parameter().type() == EnvelopeAutomation) {
117                 set_uses_gain_mapping (true);
118         }
119
120         interpolation_changed (alist->interpolation ());
121
122         connect_to_list ();
123 }
124
125 AutomationLine::~AutomationLine ()
126 {
127         vector_delete (&control_points);
128         delete group;
129
130         if (_our_time_converter) {
131                 delete _time_converter;
132         }
133 }
134
135 bool
136 AutomationLine::event_handler (GdkEvent* event)
137 {
138         return PublicEditor::instance().canvas_line_event (event, line, this);
139 }
140
141 void
142 AutomationLine::update_visibility ()
143 {
144         if (_visible & Line) {
145                 /* Only show the line there are some points, otherwise we may show an out-of-date line
146                    when automation points have been removed (the line will still follow the shape of the
147                    old points).
148                 */
149                 if (alist->interpolation() != AutomationList::Discrete && control_points.size() >= 2) {
150                         line->show();
151                 } else {
152                         line->hide ();
153                 }
154
155                 if (_visible & ControlPoints) {
156                         for (vector<ControlPoint*>::iterator i = control_points.begin(); i != control_points.end(); ++i) {
157                                 (*i)->show ();
158                         }
159                 } else if (_visible & SelectedControlPoints) {
160                         for (vector<ControlPoint*>::iterator i = control_points.begin(); i != control_points.end(); ++i) {
161                                 if ((*i)->get_selected()) {
162                                         (*i)->show ();
163                                 } else {
164                                         (*i)->hide ();
165                                 }
166                         }
167                 } else {
168                         for (vector<ControlPoint*>::iterator i = control_points.begin(); i != control_points.end(); ++i) {
169                                 (*i)->hide ();
170                         }
171                 }
172
173         } else {
174                 line->hide ();
175                 for (vector<ControlPoint*>::iterator i = control_points.begin(); i != control_points.end(); ++i) {
176                         (*i)->hide ();
177                 }
178         }
179
180 }
181
182 void
183 AutomationLine::hide ()
184 {
185         /* leave control points setting unchanged, we are just hiding the
186            overall line 
187         */
188         
189         set_visibility (AutomationLine::VisibleAspects (_visible & ~Line));
190 }
191
192 double
193 AutomationLine::control_point_box_size ()
194 {
195         if (alist->interpolation() == AutomationList::Discrete) {
196                 return max((_height*4.0) / (double)(alist->parameter().max() - alist->parameter().min()),
197                            4.0);
198         }
199
200         if (_height > TimeAxisView::preset_height (HeightLarger)) {
201                 return 8.0;
202         } else if (_height > (guint32) TimeAxisView::preset_height (HeightNormal)) {
203                 return 6.0;
204         }
205         return 4.0;
206 }
207
208 void
209 AutomationLine::set_height (guint32 h)
210 {
211         if (h != _height) {
212                 _height = h;
213
214                 double bsz = control_point_box_size();
215
216                 for (vector<ControlPoint*>::iterator i = control_points.begin(); i != control_points.end(); ++i) {
217                         (*i)->set_size (bsz);
218                 }
219
220                 reset ();
221         }
222 }
223
224 void
225 AutomationLine::set_line_color (uint32_t color)
226 {
227         _line_color = color;
228         line->set_outline_color (color);
229 }
230
231 void
232 AutomationLine::set_uses_gain_mapping (bool yn)
233 {
234         if (yn != _uses_gain_mapping) {
235                 _uses_gain_mapping = yn;
236                 reset ();
237         }
238 }
239
240 ControlPoint*
241 AutomationLine::nth (uint32_t n)
242 {
243         if (n < control_points.size()) {
244                 return control_points[n];
245         } else {
246                 return 0;
247         }
248 }
249
250 ControlPoint const *
251 AutomationLine::nth (uint32_t n) const
252 {
253         if (n < control_points.size()) {
254                 return control_points[n];
255         } else {
256                 return 0;
257         }
258 }
259
260 void
261 AutomationLine::modify_point_y (ControlPoint& cp, double y)
262 {
263         /* clamp y-coord appropriately. y is supposed to be a normalized fraction (0.0-1.0),
264            and needs to be converted to a canvas unit distance.
265         */
266
267         y = max (0.0, y);
268         y = min (1.0, y);
269         y = _height - (y * _height);
270
271         double const x = trackview.editor().sample_to_pixel_unrounded (_time_converter->to((*cp.model())->when) - _offset);
272
273         trackview.editor().session()->begin_reversible_command (_("automation event move"));
274         trackview.editor().session()->add_command (
275                 new MementoCommand<AutomationList> (memento_command_binder(), &get_state(), 0));
276
277         cp.move_to (x, y, ControlPoint::Full);
278
279         reset_line_coords (cp);
280
281         if (line_points.size() > 1) {
282                 line->set (line_points);
283         }
284
285         alist->freeze ();
286         sync_model_with_view_point (cp);
287         alist->thaw ();
288
289         update_pending = false;
290
291         trackview.editor().session()->add_command (
292                 new MementoCommand<AutomationList> (memento_command_binder(), 0, &alist->get_state()));
293
294         trackview.editor().session()->commit_reversible_command ();
295         trackview.editor().session()->set_dirty ();
296 }
297
298 void
299 AutomationLine::reset_line_coords (ControlPoint& cp)
300 {
301         if (cp.view_index() < line_points.size()) {
302                 line_points[cp.view_index()].x = cp.get_x ();
303                 line_points[cp.view_index()].y = cp.get_y ();
304         }
305 }
306
307 void
308 AutomationLine::sync_model_with_view_points (list<ControlPoint*> cp)
309 {
310         update_pending = true;
311
312         for (list<ControlPoint*>::iterator i = cp.begin(); i != cp.end(); ++i) {
313                 sync_model_with_view_point (**i);
314         }
315 }
316
317 string
318 AutomationLine::get_verbose_cursor_string (double fraction) const
319 {
320         std::string s = fraction_to_string (fraction);
321         if (_uses_gain_mapping) {
322                 s += " dB";
323         }
324
325         return s;
326 }
327
328 string
329 AutomationLine::get_verbose_cursor_relative_string (double original, double fraction) const
330 {
331         std::string s = fraction_to_string (fraction);
332         if (_uses_gain_mapping) {
333                 s += " dB";
334         }
335
336         std::string d = fraction_to_relative_string (original, fraction);
337
338         if (!d.empty()) {
339
340                 s += " (\u0394";
341                 s += d;
342
343                 if (_uses_gain_mapping) {
344                         s += " dB";
345                 }
346
347                 s += ')';
348         }
349
350         return s;
351 }
352
353 /**
354  *  @param fraction y fraction
355  *  @return string representation of this value, using dB if appropriate.
356  */
357 string
358 AutomationLine::fraction_to_string (double fraction) const
359 {
360         char buf[32];
361
362         if (_uses_gain_mapping) {
363                 if (fraction == 0.0) {
364                         snprintf (buf, sizeof (buf), "-inf");
365                 } else {
366                         snprintf (buf, sizeof (buf), "%.1f", accurate_coefficient_to_dB (slider_position_to_gain_with_max (fraction, Config->get_max_gain())));
367                 }
368         } else {
369                 view_to_model_coord_y (fraction);
370                 if (EventTypeMap::instance().is_integer (alist->parameter())) {
371                         snprintf (buf, sizeof (buf), "%d", (int)fraction);
372                 } else {
373                         snprintf (buf, sizeof (buf), "%.2f", fraction);
374                 }
375         }
376
377         return buf;
378 }
379
380 /**
381  *  @param original an old y-axis fraction
382  *  @param fraction the new y fraction
383  *  @return string representation of the difference between original and fraction, using dB if appropriate.
384  */
385 string
386 AutomationLine::fraction_to_relative_string (double original, double fraction) const
387 {
388         char buf[32];
389
390         if (original == fraction) {
391                 return "0";
392         }
393
394         if (_uses_gain_mapping) {
395                 if (original == 0.0) {
396                         /* there is no sensible representation of a relative
397                            change from -inf dB, so return an empty string.
398                         */
399                         return "";
400                 } else if (fraction == 0.0) {
401                         snprintf (buf, sizeof (buf), "-inf");
402                 } else {
403                         double old_db = accurate_coefficient_to_dB (slider_position_to_gain_with_max (original, Config->get_max_gain()));
404                         double new_db = accurate_coefficient_to_dB (slider_position_to_gain_with_max (fraction, Config->get_max_gain()));
405                         snprintf (buf, sizeof (buf), "%.1f", new_db - old_db);
406                 }
407         } else {
408                 view_to_model_coord_y (original);
409                 view_to_model_coord_y (fraction);
410                 if (EventTypeMap::instance().is_integer (alist->parameter())) {
411                         snprintf (buf, sizeof (buf), "%d", (int)fraction - (int)original);
412                 } else {
413                         snprintf (buf, sizeof (buf), "%.2f", fraction - original);
414                 }
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         set_colors ();
914 }
915
916 void AutomationLine::set_colors ()
917 {
918         set_line_color (ARDOUR_UI::config()->get_canvasvar_AutomationLine());
919         for (vector<ControlPoint*>::iterator i = control_points.begin(); i != control_points.end(); ++i) {
920                 (*i)->set_color ();
921         }
922 }
923
924 void
925 AutomationLine::list_changed ()
926 {
927         DEBUG_TRACE (DEBUG::Automation, string_compose ("\tline changed, existing update pending? %1\n", update_pending));
928
929         if (!update_pending) {
930                 update_pending = true;
931                 Gtkmm2ext::UI::instance()->call_slot (invalidator (*this), boost::bind (&AutomationLine::queue_reset, this));
932         }
933 }
934
935 void
936 AutomationLine::reset_callback (const Evoral::ControlList& events)
937 {
938         uint32_t vp = 0;
939         uint32_t pi = 0;
940         uint32_t np;
941
942         if (events.empty()) {
943                 for (vector<ControlPoint*>::iterator i = control_points.begin(); i != control_points.end(); ++i) {
944                         delete *i;
945                 }
946                 control_points.clear ();
947                 line->hide();
948                 return;
949         }
950
951         /* hide all existing points, and the line */
952
953         for (vector<ControlPoint*>::iterator i = control_points.begin(); i != control_points.end(); ++i) {
954                 (*i)->hide();
955         }
956
957         line->hide ();
958         np = events.size();
959
960         Evoral::ControlList& e = const_cast<Evoral::ControlList&> (events);
961         
962         for (AutomationList::iterator ai = e.begin(); ai != e.end(); ++ai, ++pi) {
963
964                 double tx = (*ai)->when;
965                 double ty = (*ai)->value;
966
967                 /* convert from model coordinates to canonical view coordinates */
968
969                 model_to_view_coord (tx, ty);
970
971                 if (isnan (tx) || isnan (ty)) {
972                         warning << string_compose (_("Ignoring illegal points on AutomationLine \"%1\""),
973                                                    _name) << endmsg;
974                         continue;
975                 }
976                 
977                 if (tx >= max_framepos || tx < 0 || tx >= _maximum_time) {
978                         continue;
979                 }
980                 
981                 /* convert x-coordinate to a canvas unit coordinate (this takes
982                  * zoom and scroll into account).
983                  */
984                         
985                 tx = trackview.editor().sample_to_pixel_unrounded (tx);
986                 
987                 /* convert from canonical view height (0..1.0) to actual
988                  * height coordinates (using X11's top-left rooted system)
989                  */
990
991                 ty = _height - (ty * _height);
992
993                 add_visible_control_point (vp, pi, tx, ty, ai, np);
994                 vp++;
995         }
996
997         /* discard extra CP's to avoid confusing ourselves */
998
999         while (control_points.size() > vp) {
1000                 ControlPoint* cp = control_points.back();
1001                 control_points.pop_back ();
1002                 delete cp;
1003         }
1004
1005         if (!terminal_points_can_slide) {
1006                 control_points.back()->set_can_slide(false);
1007         }
1008
1009         if (vp > 1) {
1010
1011                 /* reset the line coordinates given to the CanvasLine */
1012
1013                 while (line_points.size() < vp) {
1014                         line_points.push_back (ArdourCanvas::Duple (0,0));
1015                 }
1016
1017                 while (line_points.size() > vp) {
1018                         line_points.pop_back ();
1019                 }
1020
1021                 for (uint32_t n = 0; n < vp; ++n) {
1022                         line_points[n].x = control_points[n]->get_x();
1023                         line_points[n].y = control_points[n]->get_y();
1024                 }
1025
1026                 line->set (line_points);
1027
1028                 update_visibility ();
1029         }
1030
1031         set_selected_points (trackview.editor().get_selection().points);
1032 }
1033
1034 void
1035 AutomationLine::reset ()
1036 {
1037         DEBUG_TRACE (DEBUG::Automation, "\t\tLINE RESET\n");
1038         update_pending = false;
1039         have_timeout = false;
1040
1041         if (no_draw) {
1042                 return;
1043         }
1044
1045         alist->apply_to_points (*this, &AutomationLine::reset_callback);
1046 }
1047
1048 void
1049 AutomationLine::queue_reset ()
1050 {
1051         /* this must be called from the GUI thread
1052          */
1053
1054         if (trackview.editor().session()->transport_rolling() && alist->automation_write()) {
1055                 /* automation write pass ... defer to a timeout */
1056                 /* redraw in 1/4 second */
1057                 if (!have_timeout) {
1058                         DEBUG_TRACE (DEBUG::Automation, "\tqueue timeout\n");
1059                         Glib::signal_timeout().connect (sigc::bind_return (sigc::mem_fun (*this, &AutomationLine::reset), false), 250);
1060                         have_timeout = true;
1061                 } else {
1062                         DEBUG_TRACE (DEBUG::Automation, "\ttimeout already queued, change ignored\n");
1063                 }
1064         } else {
1065                 reset ();
1066         }
1067 }
1068
1069 void
1070 AutomationLine::clear ()
1071 {
1072         /* parent must create and commit command */
1073         XMLNode &before = alist->get_state();
1074         alist->clear();
1075
1076         trackview.editor().session()->add_command (
1077                 new MementoCommand<AutomationList> (memento_command_binder (), &before, &alist->get_state()));
1078 }
1079
1080 void
1081 AutomationLine::change_model (AutomationList::iterator /*i*/, double /*x*/, double /*y*/)
1082 {
1083 }
1084
1085 void
1086 AutomationLine::set_list (boost::shared_ptr<ARDOUR::AutomationList> list)
1087 {
1088         alist = list;
1089         queue_reset ();
1090         connect_to_list ();
1091 }
1092
1093 void
1094 AutomationLine::add_visibility (VisibleAspects va)
1095 {
1096         VisibleAspects old = _visible;
1097
1098         _visible = VisibleAspects (_visible | va);
1099
1100         if (old != _visible) {
1101                 update_visibility ();
1102         }
1103 }
1104
1105 void
1106 AutomationLine::set_visibility (VisibleAspects va)
1107 {
1108         if (_visible != va) {
1109                 _visible = va;
1110                 update_visibility ();
1111         }
1112 }
1113
1114 void
1115 AutomationLine::remove_visibility (VisibleAspects va)
1116 {
1117         VisibleAspects old = _visible;
1118
1119         _visible = VisibleAspects (_visible & ~va);
1120
1121         if (old != _visible) {
1122                 update_visibility ();
1123         }
1124 }
1125
1126 void
1127 AutomationLine::track_entered()
1128 {
1129         if (alist->interpolation() != AutomationList::Discrete) {
1130                 add_visibility (ControlPoints);
1131         }
1132 }
1133
1134 void
1135 AutomationLine::track_exited()
1136 {
1137         if (alist->interpolation() != AutomationList::Discrete) {
1138                 remove_visibility (ControlPoints);
1139         }
1140 }
1141
1142 XMLNode &
1143 AutomationLine::get_state (void)
1144 {
1145         /* function as a proxy for the model */
1146         return alist->get_state();
1147 }
1148
1149 int
1150 AutomationLine::set_state (const XMLNode &node, int version)
1151 {
1152         /* function as a proxy for the model */
1153         return alist->set_state (node, version);
1154 }
1155
1156 void
1157 AutomationLine::view_to_model_coord (double& x, double& y) const
1158 {
1159         x = _time_converter->from (x);
1160         view_to_model_coord_y (y);
1161 }
1162
1163 void
1164 AutomationLine::view_to_model_coord_y (double& y) const
1165 {
1166         /* TODO: This should be more generic ... */
1167         if (alist->parameter().type() == GainAutomation ||
1168             alist->parameter().type() == EnvelopeAutomation) {
1169                 y = slider_position_to_gain_with_max (y, Config->get_max_gain());
1170                 y = max (0.0, y);
1171                 y = min (2.0, y);
1172         } else if (alist->parameter().type() == PanAzimuthAutomation ||
1173                    alist->parameter().type() == PanElevationAutomation) {
1174                 y = 1.0 - y;
1175         } else if (alist->parameter().type() == PanWidthAutomation) {
1176                 y = 2.0 * y - 1.0;
1177         } else if (alist->parameter().type() == PluginAutomation) {
1178                 y = y * (double)(alist->get_max_y()- alist->get_min_y()) + alist->get_min_y();
1179         } else {
1180                 y = rint (y * alist->parameter().max());
1181         }
1182 }
1183
1184 void
1185 AutomationLine::model_to_view_coord (double& x, double& y) const
1186 {
1187         /* TODO: This should be more generic ... */
1188         if (alist->parameter().type() == GainAutomation ||
1189             alist->parameter().type() == EnvelopeAutomation) {
1190                 y = gain_to_slider_position_with_max (y, Config->get_max_gain());
1191         } else if (alist->parameter().type() == PanAzimuthAutomation ||
1192                    alist->parameter().type() == PanElevationAutomation) {
1193                 y = 1.0 - y;
1194         } else if (alist->parameter().type() == PanWidthAutomation) {
1195                 y = .5 + y * .5;
1196         } else if (alist->parameter().type() == PluginAutomation) {
1197                 y = (y - alist->get_min_y()) / (double)(alist->get_max_y()- alist->get_min_y());
1198         } else {
1199                 y = y / (double)alist->parameter().max(); /* ... like this */
1200         }
1201
1202         x = _time_converter->to (x) - _offset;
1203 }
1204
1205 /** Called when our list has announced that its interpolation style has changed */
1206 void
1207 AutomationLine::interpolation_changed (AutomationList::InterpolationStyle style)
1208 {
1209         if (style == AutomationList::Discrete) {
1210                 set_visibility (ControlPoints);
1211                 line->hide();
1212         } else {
1213                 set_visibility (Line);
1214         }
1215 }
1216
1217 void
1218 AutomationLine::add_visible_control_point (uint32_t view_index, uint32_t pi, double tx, double ty, 
1219                                            AutomationList::iterator model, uint32_t npoints)
1220 {
1221         ControlPoint::ShapeType shape;
1222
1223         if (view_index >= control_points.size()) {
1224
1225                 /* make sure we have enough control points */
1226
1227                 ControlPoint* ncp = new ControlPoint (*this);
1228                 ncp->set_size (control_point_box_size ());
1229
1230                 control_points.push_back (ncp);
1231         }
1232
1233         if (!terminal_points_can_slide) {
1234                 if (pi == 0) {
1235                         control_points[view_index]->set_can_slide (false);
1236                         if (tx == 0) {
1237                                 shape = ControlPoint::Start;
1238                         } else {
1239                                 shape = ControlPoint::Full;
1240                         }
1241                 } else if (pi == npoints - 1) {
1242                         control_points[view_index]->set_can_slide (false);
1243                         shape = ControlPoint::End;
1244                 } else {
1245                         control_points[view_index]->set_can_slide (true);
1246                         shape = ControlPoint::Full;
1247                 }
1248         } else {
1249                 control_points[view_index]->set_can_slide (true);
1250                 shape = ControlPoint::Full;
1251         }
1252
1253         control_points[view_index]->reset (tx, ty, model, view_index, shape);
1254
1255         /* finally, control visibility */
1256
1257         if (_visible & ControlPoints) {
1258                 control_points[view_index]->show ();
1259         } else {
1260                 control_points[view_index]->hide ();
1261         }
1262 }
1263
1264 void
1265 AutomationLine::connect_to_list ()
1266 {
1267         _list_connections.drop_connections ();
1268
1269         alist->StateChanged.connect (_list_connections, invalidator (*this), boost::bind (&AutomationLine::list_changed, this), gui_context());
1270
1271         alist->InterpolationChanged.connect (
1272                 _list_connections, invalidator (*this), boost::bind (&AutomationLine::interpolation_changed, this, _1), gui_context());
1273 }
1274
1275 MementoCommandBinder<AutomationList>*
1276 AutomationLine::memento_command_binder ()
1277 {
1278         return new SimpleMementoCommandBinder<AutomationList> (*alist.get());
1279 }
1280
1281 /** Set the maximum time that points on this line can be at, relative
1282  *  to the start of the track or region that it is on.
1283  */
1284 void
1285 AutomationLine::set_maximum_time (framecnt_t t)
1286 {
1287         if (_maximum_time == t) {
1288                 return;
1289         }
1290
1291         _maximum_time = t;
1292         reset ();
1293 }
1294
1295
1296 /** @return min and max x positions of points that are in the list, in session frames */
1297 pair<framepos_t, framepos_t>
1298 AutomationLine::get_point_x_range () const
1299 {
1300         pair<framepos_t, framepos_t> r (max_framepos, 0);
1301
1302         for (AutomationList::const_iterator i = the_list()->begin(); i != the_list()->end(); ++i) {
1303                 r.first = min (r.first, session_position (i));
1304                 r.second = max (r.second, session_position (i));
1305         }
1306
1307         return r;
1308 }
1309
1310 framepos_t
1311 AutomationLine::session_position (AutomationList::const_iterator p) const
1312 {
1313         return _time_converter->to ((*p)->when) + _offset + _time_converter->origin_b ();
1314 }
1315
1316 void
1317 AutomationLine::set_offset (framepos_t off)
1318 {
1319         if (_offset == off) {
1320                 return;
1321         }
1322
1323         _offset = off;
1324         reset ();
1325 }