remove all trace of SAE from source code.
[ardour.git] / gtk2_ardour / audio_region_view.cc
1 /*
2     Copyright (C) 2001-2006 Paul Davis
3
4     This program is free software; you can r>edistribute 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 #include <cmath>
20 #include <cassert>
21 #include <algorithm>
22 #include <vector>
23
24 #include <boost/scoped_array.hpp>
25
26 #include <gtkmm.h>
27
28 #include <gtkmm2ext/gtk_ui.h>
29
30 #include "ardour/playlist.h"
31 #include "ardour/audioregion.h"
32 #include "ardour/audiosource.h"
33 #include "ardour/profile.h"
34 #include "ardour/session.h"
35
36 #include "pbd/memento_command.h"
37 #include "pbd/stacktrace.h"
38
39 #include "evoral/Curve.hpp"
40
41 #include "canvas/rectangle.h"
42 #include "canvas/polygon.h"
43 #include "canvas/poly_line.h"
44 #include "canvas/line.h"
45 #include "canvas/text.h"
46 #include "canvas/xfade_curve.h"
47 #include "canvas/debug.h"
48 #include "canvas/utils.h"
49 #include "canvas/colors.h"
50
51 #include "streamview.h"
52 #include "audio_region_view.h"
53 #include "audio_time_axis.h"
54 #include "public_editor.h"
55 #include "audio_region_editor.h"
56 #include "audio_streamview.h"
57 #include "region_gain_line.h"
58 #include "control_point.h"
59 #include "ghostregion.h"
60 #include "audio_time_axis.h"
61 #include "rgb_macros.h"
62 #include "gui_thread.h"
63 #include "ui_config.h"
64
65 #include "i18n.h"
66
67 #define MUTED_ALPHA 48
68
69 using namespace std;
70 using namespace ARDOUR;
71 using namespace PBD;
72 using namespace Editing;
73 using namespace ArdourCanvas;
74
75 static double const handle_size = 10; /* height of fade handles */
76
77 Cairo::RefPtr<Cairo::Pattern> AudioRegionView::pending_peak_pattern;
78
79 static Cairo::RefPtr<Cairo::Pattern> create_pending_peak_pattern() {
80         cairo_surface_t * is = cairo_image_surface_create (CAIRO_FORMAT_ARGB32, 8, 8);
81
82         // create checker pattern
83         unsigned char *img = cairo_image_surface_get_data (is);
84         cairo_surface_flush (is);
85         const int stride = cairo_image_surface_get_stride (is);
86
87         for (int y = 0; y < 8; ++y) {
88                 for (int x = 0; x < 8; ++x) {
89                         const int off = (y * stride + x * 4);
90                         uint32_t *pixel = (uint32_t*) &img[off];
91                         if ((x < 4) ^ (y < 4)) {
92                                 *pixel = 0xa0000000;
93                         } else {
94                                 *pixel = 0x40000000;
95                         }
96                 }
97         }
98         cairo_surface_mark_dirty (is);
99
100         cairo_pattern_t* pat = cairo_pattern_create_for_surface (is);
101         cairo_pattern_set_extend (pat, CAIRO_EXTEND_REPEAT);
102         Cairo::RefPtr<Cairo::Pattern> p (new Cairo::Pattern (pat, false));
103         cairo_surface_destroy (is);
104         return p;
105 }
106
107 AudioRegionView::AudioRegionView (ArdourCanvas::Container *parent, RouteTimeAxisView &tv, boost::shared_ptr<AudioRegion> r, double spu,
108                                   uint32_t basic_color)
109         : RegionView (parent, tv, r, spu, basic_color)
110         , sync_mark(0)
111         , fade_in_handle(0)
112         , fade_out_handle(0)
113         , fade_in_trim_handle(0)
114         , fade_out_trim_handle(0)
115         , pending_peak_data(0)
116         , start_xfade_curve (0)
117         , start_xfade_rect (0)
118         , _start_xfade_visible (false)
119         , end_xfade_curve (0)
120         , end_xfade_rect (0)
121         , _end_xfade_visible (false)
122         , _amplitude_above_axis(1.0)
123         , trim_fade_in_drag_active(false)
124         , trim_fade_out_drag_active(false)
125 {
126         UIConfiguration::instance().ParameterChanged.connect (sigc::mem_fun (*this, &AudioRegionView::parameter_changed));
127 }
128
129 AudioRegionView::AudioRegionView (ArdourCanvas::Container *parent, RouteTimeAxisView &tv, boost::shared_ptr<AudioRegion> r, double spu,
130                                   uint32_t basic_color, bool recording, TimeAxisViewItem::Visibility visibility)
131         : RegionView (parent, tv, r, spu, basic_color, recording, visibility)
132         , sync_mark(0)
133         , fade_in_handle(0)
134         , fade_out_handle(0)
135         , fade_in_trim_handle(0)
136         , fade_out_trim_handle(0)
137         , pending_peak_data(0)
138         , start_xfade_curve (0)
139         , start_xfade_rect (0)
140         , _start_xfade_visible (false)
141         , end_xfade_curve (0)
142         , end_xfade_rect (0)
143         , _end_xfade_visible (false)
144         , _amplitude_above_axis(1.0)
145         , trim_fade_in_drag_active(false)
146         , trim_fade_out_drag_active(false)
147 {
148         UIConfiguration::instance().ParameterChanged.connect (sigc::mem_fun (*this, &AudioRegionView::parameter_changed));
149 }
150
151 AudioRegionView::AudioRegionView (const AudioRegionView& other, boost::shared_ptr<AudioRegion> other_region)
152         : RegionView (other, boost::shared_ptr<Region> (other_region))
153         , fade_in_handle(0)
154         , fade_out_handle(0)
155         , fade_in_trim_handle(0)
156         , fade_out_trim_handle(0)
157         , pending_peak_data(0)
158         , start_xfade_curve (0)
159         , start_xfade_rect (0)
160         , _start_xfade_visible (false)
161         , end_xfade_curve (0)
162         , end_xfade_rect (0)
163         , _end_xfade_visible (false)
164         , _amplitude_above_axis (other._amplitude_above_axis)
165         , trim_fade_in_drag_active(false)
166         , trim_fade_out_drag_active(false)
167 {
168         init (true);
169
170         UIConfiguration::instance().ParameterChanged.connect (sigc::mem_fun (*this, &AudioRegionView::parameter_changed));
171 }
172
173 void
174 AudioRegionView::init (bool wfd)
175 {
176         // FIXME: Some redundancy here with RegionView::init.  Need to figure out
177         // where order is important and where it isn't...
178
179         if (!pending_peak_pattern) {
180                 pending_peak_pattern = create_pending_peak_pattern();
181         }
182
183         // needs to be created first, RegionView::init() calls set_height()
184         pending_peak_data = new ArdourCanvas::Rectangle (group);
185         CANVAS_DEBUG_NAME (pending_peak_data, string_compose ("pending peak rectangle for %1", region()->name()));
186         pending_peak_data->set_outline_color (ArdourCanvas::rgba_to_color (0, 0, 0, 0.0));
187         pending_peak_data->set_pattern (pending_peak_pattern);
188         pending_peak_data->set_data ("regionview", this);
189         pending_peak_data->hide ();
190
191         RegionView::init (wfd);
192
193         _amplitude_above_axis = 1.0;
194
195         create_waves ();
196
197         if (!_recregion) {
198                 fade_in_handle = new ArdourCanvas::Rectangle (group);
199                 CANVAS_DEBUG_NAME (fade_in_handle, string_compose ("fade in handle for %1", region()->name()));
200                 fade_in_handle->set_outline_color (ArdourCanvas::rgba_to_color (0, 0, 0, 1.0));
201                 fade_in_handle->set_fill_color (UIConfiguration::instance().color ("inactive fade handle"));
202                 fade_in_handle->set_data ("regionview", this);
203                 fade_in_handle->hide ();
204
205                 fade_out_handle = new ArdourCanvas::Rectangle (group);
206                 CANVAS_DEBUG_NAME (fade_out_handle, string_compose ("fade out handle for %1", region()->name()));
207                 fade_out_handle->set_outline_color (ArdourCanvas::rgba_to_color (0, 0, 0, 1.0));
208                 fade_out_handle->set_fill_color (UIConfiguration::instance().color ("inactive fade handle"));
209                 fade_out_handle->set_data ("regionview", this);
210                 fade_out_handle->hide ();
211
212                 fade_in_trim_handle = new ArdourCanvas::Rectangle (group);
213                 CANVAS_DEBUG_NAME (fade_in_handle, string_compose ("fade in trim handle for %1", region()->name()));
214                 fade_in_trim_handle->set_outline_color (ArdourCanvas::rgba_to_color (0, 0, 0, 1.0));
215                 fade_in_trim_handle->set_fill_color (UIConfiguration::instance().color ("inactive fade handle"));
216                 fade_in_trim_handle->set_data ("regionview", this);
217                 fade_in_trim_handle->hide ();
218
219                 fade_out_trim_handle = new ArdourCanvas::Rectangle (group);
220                 CANVAS_DEBUG_NAME (fade_out_handle, string_compose ("fade out trim handle for %1", region()->name()));
221                 fade_out_trim_handle->set_outline_color (ArdourCanvas::rgba_to_color (0, 0, 0, 1.0));
222                 fade_out_trim_handle->set_fill_color (UIConfiguration::instance().color ("inactive fade handle"));
223                 fade_out_trim_handle->set_data ("regionview", this);
224                 fade_out_trim_handle->hide ();
225         }
226
227         setup_fade_handle_positions ();
228
229         if (!trackview.session()->config.get_show_region_fades()) {
230                 set_fade_visibility (false);
231         }
232
233         const string line_name = _region->name() + ":gain";
234         gain_line.reset (new AudioRegionGainLine (line_name, *this, *group, audio_region()->envelope()));
235
236         update_envelope_visibility ();
237         gain_line->reset ();
238
239         set_height (trackview.current_height()); // XXX not correct for Layered mode, but set_height() will fix later.
240
241         region_muted ();
242         region_sync_changed ();
243
244         region_resized (ARDOUR::bounds_change);
245
246         for (vector<GhostRegion*>::iterator i = ghosts.begin(); i != ghosts.end(); ++i) {
247                 (*i)->set_duration (_region->length() / samples_per_pixel);
248         }
249
250         region_locked ();
251         envelope_active_changed ();
252         fade_in_active_changed ();
253         fade_out_active_changed ();
254
255         reset_width_dependent_items (_pixel_width);
256
257         if (fade_in_handle) {
258                 fade_in_handle->Event.connect (sigc::bind (sigc::mem_fun (PublicEditor::instance(), &PublicEditor::canvas_fade_in_handle_event), fade_in_handle, this, false));
259         }
260
261         if (fade_out_handle) {
262                 fade_out_handle->Event.connect (sigc::bind (sigc::mem_fun (PublicEditor::instance(), &PublicEditor::canvas_fade_out_handle_event), fade_out_handle, this, false));
263         }
264
265         if (fade_in_trim_handle) {
266                 fade_in_trim_handle->Event.connect (sigc::bind (sigc::mem_fun (PublicEditor::instance(), &PublicEditor::canvas_fade_in_handle_event), fade_in_trim_handle, this, true));
267         }
268
269         if (fade_out_trim_handle) {
270                 fade_out_trim_handle->Event.connect (sigc::bind (sigc::mem_fun (PublicEditor::instance(), &PublicEditor::canvas_fade_out_handle_event), fade_out_trim_handle, this, true));
271         }
272
273         set_colors ();
274
275         setup_waveform_visibility ();
276
277         pending_peak_data->raise_to_top ();
278
279         if (frame_handle_start) {
280                 frame_handle_start->raise_to_top ();
281         }
282         if (frame_handle_end) {
283                 frame_handle_end->raise_to_top ();
284         }
285
286         /* XXX sync mark drag? */
287 }
288
289 AudioRegionView::~AudioRegionView ()
290 {
291         in_destructor = true;
292
293         RegionViewGoingAway (this); /* EMIT_SIGNAL */
294
295         for (vector<ScopedConnection*>::iterator i = _data_ready_connections.begin(); i != _data_ready_connections.end(); ++i) {
296                 delete *i;
297         }
298         _data_ready_connections.clear ();
299
300         for (list<std::pair<framepos_t, ArdourCanvas::Line*> >::iterator i = feature_lines.begin(); i != feature_lines.end(); ++i) {
301                 delete ((*i).second);
302         }
303
304         /* all waveviews etc will be destroyed when the group is destroyed */
305 }
306
307 boost::shared_ptr<ARDOUR::AudioRegion>
308 AudioRegionView::audio_region() const
309 {
310         // "Guaranteed" to succeed...
311         return boost::dynamic_pointer_cast<AudioRegion>(_region);
312 }
313
314 void
315 AudioRegionView::region_changed (const PropertyChange& what_changed)
316 {
317         ENSURE_GUI_THREAD (*this, &AudioRegionView::region_changed, what_changed);
318
319         RegionView::region_changed (what_changed);
320
321         if (what_changed.contains (ARDOUR::Properties::scale_amplitude)) {
322                 region_scale_amplitude_changed ();
323         }
324         if (what_changed.contains (ARDOUR::Properties::fade_in)) {
325                 fade_in_changed ();
326         }
327         if (what_changed.contains (ARDOUR::Properties::fade_out)) {
328                 fade_out_changed ();
329         }
330         if (what_changed.contains (ARDOUR::Properties::fade_in_active)) {
331                 fade_in_active_changed ();
332         }
333         if (what_changed.contains (ARDOUR::Properties::fade_out_active)) {
334                 fade_out_active_changed ();
335         }
336         if (what_changed.contains (ARDOUR::Properties::envelope_active)) {
337                 envelope_active_changed ();
338         }
339         if (what_changed.contains (ARDOUR::Properties::valid_transients)) {
340                 transients_changed ();
341         }
342 }
343
344 void
345 AudioRegionView::fade_in_changed ()
346 {
347         reset_fade_in_shape ();
348 }
349
350 void
351 AudioRegionView::fade_out_changed ()
352 {
353         reset_fade_out_shape ();
354 }
355
356 void
357 AudioRegionView::fade_in_active_changed ()
358 {
359         if (start_xfade_rect) {
360                 if (audio_region()->fade_in_active()) {
361                         start_xfade_rect->set_fill (false);
362                 } else {
363                         start_xfade_rect->set_fill_color (UIConfiguration::instance().color_mod ("inactive crossfade", "inactive crossfade"));
364                         start_xfade_rect->set_fill (true);
365                 }
366         }
367 }
368
369 void
370 AudioRegionView::fade_out_active_changed ()
371 {
372         if (end_xfade_rect) {
373                 if (audio_region()->fade_out_active()) {
374                         end_xfade_rect->set_fill (false);
375                 } else {
376                         end_xfade_rect->set_fill_color (UIConfiguration::instance().color_mod ("inactive crossfade", "inactive crossfade"));
377                         end_xfade_rect->set_fill (true);
378                 }
379         }
380 }
381
382
383 void
384 AudioRegionView::region_scale_amplitude_changed ()
385 {
386         for (uint32_t n = 0; n < waves.size(); ++n) {
387                 waves[n]->gain_changed ();
388         }
389 }
390
391 void
392 AudioRegionView::region_renamed ()
393 {
394         std::string str = RegionView::make_name ();
395
396         if (audio_region()->speed_mismatch (trackview.session()->frame_rate())) {
397                 str = string ("*") + str;
398         }
399
400         if (_region->muted()) {
401                 str = string ("!") + str;
402         }
403
404         set_item_name (str, this);
405         set_name_text (str);
406 }
407
408 void
409 AudioRegionView::region_resized (const PropertyChange& what_changed)
410 {
411         AudioGhostRegion* agr;
412
413         RegionView::region_resized(what_changed);
414         PropertyChange interesting_stuff;
415
416         interesting_stuff.add (ARDOUR::Properties::start);
417         interesting_stuff.add (ARDOUR::Properties::length);
418
419         if (what_changed.contains (interesting_stuff)) {
420
421                 for (uint32_t n = 0; n < waves.size(); ++n) {
422                         waves[n]->region_resized ();
423                 }
424
425                 for (vector<GhostRegion*>::iterator i = ghosts.begin(); i != ghosts.end(); ++i) {
426                         if ((agr = dynamic_cast<AudioGhostRegion*>(*i)) != 0) {
427
428                                 for (vector<WaveView*>::iterator w = agr->waves.begin(); w != agr->waves.end(); ++w) {
429                                         (*w)->region_resized ();
430                                 }
431                         }
432                 }
433
434                 /* hide transient lines that extend beyond the region end */
435
436                 list<std::pair<framepos_t, ArdourCanvas::Line*> >::iterator l;
437
438                 for (l = feature_lines.begin(); l != feature_lines.end(); ++l) {
439                         if (l->first > _region->length() - 1) {
440                                 l->second->hide();
441                         } else {
442                                 l->second->show();
443                         }
444                 }
445         }
446 }
447
448 void
449 AudioRegionView::reset_width_dependent_items (double pixel_width)
450 {
451         RegionView::reset_width_dependent_items(pixel_width);
452         assert(_pixel_width == pixel_width);
453
454         pending_peak_data->set_x1(pixel_width);
455
456         if (pixel_width <= 20.0 || _height < 5.0 || !trackview.session()->config.get_show_region_fades()) {
457                 if (fade_in_handle)       { fade_in_handle->hide(); }
458                 if (fade_out_handle)      { fade_out_handle->hide(); }
459                 if (fade_in_trim_handle)  { fade_in_trim_handle->hide(); }
460                 if (fade_out_trim_handle) { fade_out_trim_handle->hide(); }
461                 if (start_xfade_rect)     { start_xfade_rect->set_outline (false); }
462                 if (end_xfade_rect)       { end_xfade_rect->set_outline (false); }
463         }
464
465         AnalysisFeatureList analysis_features = _region->transients();
466         AnalysisFeatureList::const_iterator i;
467
468         list<std::pair<framepos_t, ArdourCanvas::Line*> >::iterator l;
469
470         for (i = analysis_features.begin(), l = feature_lines.begin(); i != analysis_features.end() && l != feature_lines.end(); ++i, ++l) {
471
472                 float x_pos = trackview.editor().sample_to_pixel (*i);
473
474                 (*l).second->set (ArdourCanvas::Duple (x_pos, 2.0),
475                                   ArdourCanvas::Duple (x_pos, _height - TimeAxisViewItem::NAME_HIGHLIGHT_SIZE - 1));
476
477                 (*l).first = *i;
478
479                 (*l).second->set (ArdourCanvas::Duple (x_pos, 2.0),
480                                   ArdourCanvas::Duple (x_pos, _height - TimeAxisViewItem::NAME_HIGHLIGHT_SIZE - 1));
481         }
482
483         reset_fade_shapes ();
484 }
485
486 void
487 AudioRegionView::region_muted ()
488 {
489         RegionView::region_muted();
490         set_waveform_colors ();
491 }
492
493 void
494 AudioRegionView::setup_fade_handle_positions()
495 {
496         /* position of fade handle offset from the top of the region view */
497         double const handle_pos = 0.0;
498
499         if (fade_in_handle) {
500                 fade_in_handle->set_y0 (handle_pos);
501                 fade_in_handle->set_y1 (handle_pos + handle_size);
502         }
503
504         if (fade_out_handle) {
505                 fade_out_handle->set_y0 (handle_pos);
506                 fade_out_handle->set_y1 (handle_pos + handle_size);
507         }
508
509         if (fade_in_trim_handle) {
510                 fade_in_trim_handle->set_y0 (_height - handle_size);
511                 fade_in_trim_handle->set_y1 (_height);
512         }
513
514         if (fade_out_trim_handle) {
515                 fade_out_trim_handle->set_y0 (_height - handle_size );
516                 fade_out_trim_handle->set_y1 (_height);
517         }
518 }
519
520 void
521 AudioRegionView::set_height (gdouble height)
522 {
523         RegionView::set_height (height);
524         pending_peak_data->set_y1 (height);
525
526         uint32_t wcnt = waves.size();
527
528         if (wcnt > 0) {
529
530                 gdouble ht;
531
532                 if (!UIConfiguration::instance().get_show_name_highlight() || (height < NAME_HIGHLIGHT_THRESH)) {
533                         ht = height / (double) wcnt;
534                 } else {
535                         ht = (height - NAME_HIGHLIGHT_SIZE) / (double) wcnt;
536                 }
537
538                 for (uint32_t n = 0; n < wcnt; ++n) {
539
540                         gdouble yoff = floor (ht * n);
541
542                         waves[n]->set_height (ht);
543                         waves[n]->set_y_position (yoff);
544                 }
545         }
546
547         if (gain_line) {
548
549                 if ((height/wcnt) < NAME_HIGHLIGHT_THRESH) {
550                         gain_line->hide ();
551                 } else {
552                         update_envelope_visibility ();
553                 }
554
555                 gain_line->set_height ((uint32_t) rint (height - NAME_HIGHLIGHT_SIZE) - 2);
556         }
557
558         reset_fade_shapes ();
559
560         /* Update hights for any active feature lines */
561         list<std::pair<framepos_t, ArdourCanvas::Line*> >::iterator l;
562
563         for (l = feature_lines.begin(); l != feature_lines.end(); ++l) {
564
565                 float pos_x = trackview.editor().sample_to_pixel((*l).first);
566
567                 if (height >= NAME_HIGHLIGHT_THRESH) {
568                         (*l).second->set (ArdourCanvas::Duple (pos_x, 2.0),
569                                           ArdourCanvas::Duple (pos_x, _height - TimeAxisViewItem::NAME_HIGHLIGHT_SIZE - 1));
570                 } else {
571                         (*l).second->set (ArdourCanvas::Duple (pos_x, 2.0),
572                                           ArdourCanvas::Duple (pos_x, _height - 1));
573                 }
574         }
575
576         if (name_text) {
577                 name_text->raise_to_top();
578         }
579
580         setup_fade_handle_positions();
581 }
582
583 void
584 AudioRegionView::reset_fade_shapes ()
585 {
586         if (!trim_fade_in_drag_active) { reset_fade_in_shape (); }
587         if (!trim_fade_out_drag_active) { reset_fade_out_shape (); }
588 }
589
590 void
591 AudioRegionView::reset_fade_in_shape ()
592 {
593         reset_fade_in_shape_width (audio_region(), (framecnt_t) audio_region()->fade_in()->back()->when);
594 }
595
596 void
597 AudioRegionView::reset_fade_in_shape_width (boost::shared_ptr<AudioRegion> ar, framecnt_t width, bool drag_active)
598 {
599         trim_fade_in_drag_active = drag_active;
600         if (fade_in_handle == 0) {
601                 return;
602         }
603
604         /* smallest size for a fade is 64 frames */
605
606         width = std::max ((framecnt_t) 64, width);
607
608         /* round here to prevent little visual glitches with sub-pixel placement */
609         double const pwidth = floor (width / samples_per_pixel);
610         double const handle_left = pwidth;
611
612         /* Put the fade in handle so that its left side is at the end-of-fade line */
613         fade_in_handle->set_x0 (handle_left);
614         fade_in_handle->set_x1 (handle_left + handle_size);
615
616         if (fade_in_trim_handle) {
617                 fade_in_trim_handle->set_x0 (0);
618                 fade_in_trim_handle->set_x1 (handle_size);
619         }
620
621         if (fade_in_handle->visible()) {
622                 //see comment for drag_start
623                 entered();
624         }
625
626         if (pwidth < 5) {
627                 hide_start_xfade();
628                 return;
629         }
630
631         if (!trackview.session()->config.get_show_region_fades()) {
632                 hide_start_xfade ();
633                 return;
634         }
635
636         double effective_height;
637
638         if (_height >= NAME_HIGHLIGHT_THRESH) {
639                 effective_height = _height - NAME_HIGHLIGHT_SIZE;
640         } else {
641                 effective_height = _height;
642         }
643
644         /* points *MUST* be in anti-clockwise order */
645
646         Points points;
647         Points::size_type pi;
648         boost::shared_ptr<const Evoral::ControlList> list (audio_region()->fade_in());
649         Evoral::ControlList::const_iterator x;
650         double length = list->length();
651
652         points.assign (list->size(), Duple());
653
654         for (x = list->begin(), pi = 0; x != list->end(); ++x, ++pi) {
655                 points[pi].x = (pwidth * ((*x)->when/length));
656                 points[pi].y = effective_height - ((*x)->value * (effective_height - 1.));
657         }
658
659         /* draw the line */
660
661         redraw_start_xfade_to (ar, width, points, effective_height, handle_left);
662
663         /* ensure trim handle stays on top */
664         if (frame_handle_start) {
665                 frame_handle_start->raise_to_top();
666         }
667 }
668
669 void
670 AudioRegionView::reset_fade_out_shape ()
671 {
672         reset_fade_out_shape_width (audio_region(), (framecnt_t) audio_region()->fade_out()->back()->when);
673 }
674
675 void
676 AudioRegionView::reset_fade_out_shape_width (boost::shared_ptr<AudioRegion> ar, framecnt_t width, bool drag_active)
677 {
678         trim_fade_out_drag_active = drag_active;
679         if (fade_out_handle == 0) {
680                 return;
681         }
682
683         /* smallest size for a fade is 64 frames */
684
685         width = std::max ((framecnt_t) 64, width);
686
687
688         double const pwidth = floor(trackview.editor().sample_to_pixel (width));
689
690         /* the right edge should be right on the region frame is the pixel
691          * width is zero. Hence the additional + 1.0 at the end.
692          */
693
694         double const handle_right = rint(trackview.editor().sample_to_pixel (_region->length()) - pwidth);
695         double const trim_handle_right = rint(trackview.editor().sample_to_pixel (_region->length()));
696
697         /* Put the fade out handle so that its right side is at the end-of-fade line;
698          */
699         fade_out_handle->set_x0 (handle_right - handle_size);
700         fade_out_handle->set_x1 (handle_right);
701         if (fade_out_trim_handle) {
702                 fade_out_trim_handle->set_x0 (1 + trim_handle_right - handle_size);
703                 fade_out_trim_handle->set_x1 (1 + trim_handle_right);
704         }
705
706         if (fade_out_handle->visible()) {
707                 //see comment for drag_start
708                 entered();
709         }
710         /* don't show shape if its too small */
711
712         if (pwidth < 5) {
713                 hide_end_xfade();
714                 return;
715         }
716
717         if (!trackview.session()->config.get_show_region_fades()) {
718                 hide_end_xfade();
719                 return;
720         }
721
722         double effective_height;
723
724         effective_height = _height;
725
726         if (UIConfiguration::instance().get_show_name_highlight() && effective_height >= NAME_HIGHLIGHT_THRESH) {
727                 effective_height -= NAME_HIGHLIGHT_SIZE;
728         }
729
730         /* points *MUST* be in anti-clockwise order */
731
732         Points points;
733         Points::size_type pi;
734         boost::shared_ptr<const Evoral::ControlList> list (audio_region()->fade_out());
735         Evoral::ControlList::const_iterator x;
736         double length = list->length();
737
738         points.assign (list->size(), Duple());
739
740         for (x = list->begin(), pi = 0; x != list->end(); ++x, ++pi) {
741                 points[pi].x = _pixel_width - pwidth + (pwidth * ((*x)->when/length));
742                 points[pi].y = effective_height - ((*x)->value * (effective_height - 1.));
743         }
744
745         /* draw the line */
746
747         redraw_end_xfade_to (ar, width, points, effective_height, handle_right, pwidth);
748
749         /* ensure trim handle stays on top */
750         if (frame_handle_end) {
751                 frame_handle_end->raise_to_top();
752         }
753 }
754
755 framepos_t
756 AudioRegionView::get_fade_in_shape_width ()
757 {
758         return audio_region()->fade_in()->back()->when;
759 }
760
761 framepos_t
762 AudioRegionView::get_fade_out_shape_width ()
763 {
764         return audio_region()->fade_out()->back()->when;
765 }
766
767
768 void
769 AudioRegionView::redraw_start_xfade ()
770 {
771         boost::shared_ptr<AudioRegion> ar (audio_region());
772
773         if (!ar->fade_in() || ar->fade_in()->empty()) {
774                 return;
775         }
776
777         show_start_xfade();
778         reset_fade_in_shape_width (ar, ar->fade_in()->back()->when);
779 }
780
781 void
782 AudioRegionView::redraw_start_xfade_to (boost::shared_ptr<AudioRegion> ar, framecnt_t /*width*/, Points& points, double effective_height,
783                                         double rect_width)
784 {
785         if (points.size() < 2) {
786                 return;
787         }
788
789         if (!start_xfade_curve) {
790                 start_xfade_curve = new ArdourCanvas::XFadeCurve (group, ArdourCanvas::XFadeCurve::Start);
791                 CANVAS_DEBUG_NAME (start_xfade_curve, string_compose ("xfade start out line for %1", region()->name()));
792                 start_xfade_curve->set_fill_color (UIConfiguration::instance().color_mod ("active crossfade", "crossfade alpha"));
793                 start_xfade_curve->set_outline_color (UIConfiguration::instance().color ("crossfade line"));
794                 start_xfade_curve->set_ignore_events (true);
795         }
796         if (!start_xfade_rect) {
797                 start_xfade_rect = new ArdourCanvas::Rectangle (group);
798                 CANVAS_DEBUG_NAME (start_xfade_rect, string_compose ("xfade start rect for %1", region()->name()));
799                 start_xfade_rect->set_outline_color (UIConfiguration::instance().color ("crossfade line"));
800                 start_xfade_rect->set_fill (false);
801                 start_xfade_rect->set_outline (false);
802                 start_xfade_rect->Event.connect (sigc::bind (sigc::mem_fun (PublicEditor::instance(), &PublicEditor::canvas_start_xfade_event), start_xfade_rect, this));
803                 start_xfade_rect->set_data ("regionview", this);
804         }
805
806         start_xfade_rect->set (ArdourCanvas::Rect (0.0, 0.0, rect_width, effective_height));
807
808         /* fade out line */
809
810         boost::shared_ptr<AutomationList> inverse = ar->inverse_fade_in ();
811         Points ipoints;
812         Points::size_type npoints;
813
814         if (!inverse) {
815
816                 /* there is no explicit inverse fade in curve, so take the
817                  * regular fade in curve given to use as "points" (already a
818                  * set of coordinates), and convert to the inverse shape.
819                  */
820
821                 npoints = points.size();
822                 ipoints.assign (npoints, Duple());
823
824                 for (Points::size_type i = 0, pci = 0; i < npoints; ++i, ++pci) {
825                         ArdourCanvas::Duple &p (ipoints[pci]);
826                         /* leave x-axis alone but invert with respect to y-axis */
827                         p.y = effective_height - points[pci].y;
828                 }
829
830         } else {
831
832                 /* there is an explicit inverse fade in curve. Grab the points
833                    and convert them into coordinates for the inverse fade in
834                    line.
835                 */
836
837                 npoints = inverse->size();
838                 ipoints.assign (npoints, Duple());
839
840                 Evoral::ControlList::const_iterator x;
841                 Points::size_type pi;
842                 double length = inverse->length();
843
844                 for (x = inverse->begin(), pi = 0; x != inverse->end(); ++x, ++pi) {
845                         ArdourCanvas::Duple& p (ipoints[pi]);
846                         p.x = (rect_width * ((*x)->when/length));
847                         p.y = effective_height - ((*x)->value * (effective_height));
848                 }
849         }
850
851         start_xfade_curve->set_inout (points, ipoints);
852
853         show_start_xfade();
854 }
855
856 void
857 AudioRegionView::redraw_end_xfade ()
858 {
859         boost::shared_ptr<AudioRegion> ar (audio_region());
860
861         if (!ar->fade_out() || ar->fade_out()->empty()) {
862                 return;
863         }
864
865         show_end_xfade();
866
867         reset_fade_out_shape_width (ar, ar->fade_out()->back()->when);
868 }
869
870 void
871 AudioRegionView::redraw_end_xfade_to (boost::shared_ptr<AudioRegion> ar, framecnt_t width, Points& points, double effective_height,
872                                       double rect_edge, double rect_width)
873 {
874         if (points.size() < 2) {
875                 return;
876         }
877
878         if (!end_xfade_curve) {
879                 end_xfade_curve = new ArdourCanvas::XFadeCurve (group, ArdourCanvas::XFadeCurve::End);
880                 CANVAS_DEBUG_NAME (end_xfade_curve, string_compose ("xfade end out line for %1", region()->name()));
881                 end_xfade_curve->set_fill_color (UIConfiguration::instance().color_mod ("active crossfade", "crossfade alpha"));
882                 end_xfade_curve->set_outline_color (UIConfiguration::instance().color ("crossfade line"));
883                 end_xfade_curve->set_ignore_events (true);
884         }
885
886         if (!end_xfade_rect) {
887                 end_xfade_rect = new ArdourCanvas::Rectangle (group);
888                 CANVAS_DEBUG_NAME (end_xfade_rect, string_compose ("xfade end rect for %1", region()->name()));
889                 end_xfade_rect->set_outline_color (UIConfiguration::instance().color ("crossfade line"));
890                 end_xfade_rect->set_fill (false);
891                 end_xfade_rect->set_outline (false);
892                 end_xfade_rect->Event.connect (sigc::bind (sigc::mem_fun (PublicEditor::instance(), &PublicEditor::canvas_end_xfade_event), end_xfade_rect, this));
893                 end_xfade_rect->set_data ("regionview", this);
894         }
895
896         end_xfade_rect->set (ArdourCanvas::Rect (rect_edge, 0.0, rect_edge + rect_width, effective_height));
897
898         /* fade in line */
899
900         boost::shared_ptr<AutomationList> inverse = ar->inverse_fade_out ();
901         Points ipoints;
902         Points::size_type npoints;
903
904         if (!inverse) {
905
906                 /* there is no explicit inverse fade out curve, so take the
907                  * regular fade out curve given to use as "points" (already a
908                  * set of coordinates), and convert to the inverse shape.
909                  */
910
911                 npoints = points.size();
912                 ipoints.assign (npoints, Duple());
913
914                 Points::size_type pci;
915
916                 for (pci = 0; pci < npoints; ++pci) {
917                         ArdourCanvas::Duple &p (ipoints[pci]);
918                         p.y = effective_height - points[pci].y;
919                 }
920
921         } else {
922
923                 /* there is an explicit inverse fade out curve. Grab the points
924                    and convert them into coordinates for the inverse fade out
925                    line.
926                 */
927
928                 npoints = inverse->size();
929                 ipoints.assign (npoints, Duple());
930
931                 const double rend = trackview.editor().sample_to_pixel (_region->length() - width);
932
933                 Evoral::ControlList::const_iterator x;
934                 Points::size_type pi;
935                 double length = inverse->length();
936
937                 for (x = inverse->begin(), pi = 0; x != inverse->end(); ++x, ++pi) {
938                         ArdourCanvas::Duple& p (ipoints[pi]);
939                         p.x = (rect_width * ((*x)->when/length)) + rend;
940                         p.y = effective_height - ((*x)->value * (effective_height));
941                 }
942         }
943
944         end_xfade_curve->set_inout (ipoints, points);
945
946         show_end_xfade();
947 }
948
949 void
950 AudioRegionView::hide_xfades ()
951 {
952         hide_start_xfade ();
953         hide_end_xfade ();
954 }
955
956 void
957 AudioRegionView::hide_start_xfade ()
958 {
959         if (start_xfade_curve) {
960                 start_xfade_curve->hide();
961         }
962         if (start_xfade_rect) {
963                 start_xfade_rect->hide ();
964         }
965
966         _start_xfade_visible = false;
967 }
968
969 void
970 AudioRegionView::hide_end_xfade ()
971 {
972         if (end_xfade_curve) {
973                 end_xfade_curve->hide();
974         }
975         if (end_xfade_rect) {
976                 end_xfade_rect->hide ();
977         }
978
979         _end_xfade_visible = false;
980 }
981
982 void
983 AudioRegionView::show_start_xfade ()
984 {
985         if (start_xfade_curve) {
986                 start_xfade_curve->show();
987         }
988         if (start_xfade_rect) {
989                 start_xfade_rect->show ();
990         }
991
992         _start_xfade_visible = true;
993 }
994
995 void
996 AudioRegionView::show_end_xfade ()
997 {
998         if (end_xfade_curve) {
999                 end_xfade_curve->show();
1000         }
1001         if (end_xfade_rect) {
1002                 end_xfade_rect->show ();
1003         }
1004
1005         _end_xfade_visible = true;
1006 }
1007
1008 void
1009 AudioRegionView::set_samples_per_pixel (gdouble fpp)
1010 {
1011         RegionView::set_samples_per_pixel (fpp);
1012
1013         if (UIConfiguration::instance().get_show_waveforms ()) {
1014                 for (uint32_t n = 0; n < waves.size(); ++n) {
1015                         waves[n]->set_samples_per_pixel (fpp);
1016                 }
1017         }
1018
1019         if (gain_line) {
1020                 gain_line->reset ();
1021         }
1022
1023         reset_fade_shapes ();
1024 }
1025
1026 void
1027 AudioRegionView::set_amplitude_above_axis (gdouble a)
1028 {
1029         for (uint32_t n=0; n < waves.size(); ++n) {
1030                 waves[n]->set_amplitude_above_axis (a);
1031         }
1032 }
1033
1034 void
1035 AudioRegionView::set_colors ()
1036 {
1037         RegionView::set_colors();
1038
1039         if (gain_line) {
1040                 gain_line->set_line_color (audio_region()->envelope_active() ?
1041                                            UIConfiguration::instance().color ("gain line") :
1042                                            UIConfiguration::instance().color_mod ("gain line inactive", "gain line inactive"));
1043         }
1044
1045         set_waveform_colors ();
1046
1047         if (start_xfade_curve) {
1048                 start_xfade_curve->set_fill_color (UIConfiguration::instance().color_mod ("active crossfade", "crossfade alpha"));
1049                 start_xfade_curve->set_outline_color (UIConfiguration::instance().color ("crossfade line"));
1050         }
1051         if (end_xfade_curve) {
1052                 end_xfade_curve->set_fill_color (UIConfiguration::instance().color_mod ("active crossfade", "crossfade alpha"));
1053                 end_xfade_curve->set_outline_color (UIConfiguration::instance().color ("crossfade line"));
1054         }
1055
1056         if (start_xfade_rect) {
1057                 start_xfade_rect->set_outline_color (UIConfiguration::instance().color ("crossfade line"));
1058         }
1059         if (end_xfade_rect) {
1060                 end_xfade_rect->set_outline_color (UIConfiguration::instance().color ("crossfade line"));
1061         }
1062 }
1063
1064 void
1065 AudioRegionView::setup_waveform_visibility ()
1066 {
1067         if (UIConfiguration::instance().get_show_waveforms ()) {
1068                 for (uint32_t n = 0; n < waves.size(); ++n) {
1069                         /* make sure the zoom level is correct, since we don't update
1070                            this when waveforms are hidden.
1071                         */
1072                         // CAIROCANVAS
1073                         // waves[n]->set_samples_per_pixel (_samples_per_pixel);
1074                         waves[n]->show();
1075                 }
1076         } else {
1077                 for (uint32_t n = 0; n < waves.size(); ++n) {
1078                         waves[n]->hide();
1079                 }
1080         }
1081 }
1082
1083 void
1084 AudioRegionView::temporarily_hide_envelope ()
1085 {
1086         if (gain_line) {
1087                 gain_line->hide ();
1088         }
1089 }
1090
1091 void
1092 AudioRegionView::unhide_envelope ()
1093 {
1094         update_envelope_visibility ();
1095 }
1096
1097 void
1098 AudioRegionView::update_envelope_visibility ()
1099 {
1100         if (!gain_line) {
1101                 return;
1102         }
1103
1104         if (trackview.editor().current_mouse_mode() == Editing::MouseDraw || trackview.editor().current_mouse_mode() == Editing::MouseContent ) {
1105                 gain_line->set_visibility (AutomationLine::VisibleAspects(AutomationLine::ControlPoints|AutomationLine::Line));
1106                 gain_line->canvas_group().raise_to_top ();
1107         } else if (UIConfiguration::instance().get_show_region_gain() || trackview.editor().current_mouse_mode() == Editing::MouseRange ) {
1108                 gain_line->set_visibility (AutomationLine::VisibleAspects(AutomationLine::Line));
1109                 gain_line->canvas_group().raise_to_top ();
1110         } else {
1111                 gain_line->set_visibility (AutomationLine::VisibleAspects(0));
1112         }
1113 }
1114
1115 void
1116 AudioRegionView::delete_waves ()
1117 {
1118         for (vector<ScopedConnection*>::iterator i = _data_ready_connections.begin(); i != _data_ready_connections.end(); ++i) {
1119                 delete *i;
1120         }
1121         _data_ready_connections.clear ();
1122
1123         for (vector<WaveView*>::iterator w = waves.begin(); w != waves.end(); ++w) {
1124                 group->remove(*w);
1125         }
1126         waves.clear();
1127         tmp_waves.clear();
1128         pending_peak_data->show ();
1129 }
1130
1131 void
1132 AudioRegionView::create_waves ()
1133 {
1134         // cerr << "AudioRegionView::create_waves() called on " << this << endl;//DEBUG
1135         RouteTimeAxisView& atv (*(dynamic_cast<RouteTimeAxisView*>(&trackview))); // ick
1136
1137         if (!atv.track()) {
1138                 return;
1139         }
1140
1141         ChanCount nchans = atv.track()->n_channels();
1142
1143         // cerr << "creating waves for " << _region->name() << " with wfd = " << wait_for_data
1144         //              << " and channels = " << nchans.n_audio() << endl;
1145
1146         /* in tmp_waves, set up null pointers for each channel so the vector is allocated */
1147         for (uint32_t n = 0; n < nchans.n_audio(); ++n) {
1148                 tmp_waves.push_back (0);
1149         }
1150
1151         for (vector<ScopedConnection*>::iterator i = _data_ready_connections.begin(); i != _data_ready_connections.end(); ++i) {
1152                 delete *i;
1153         }
1154
1155         _data_ready_connections.clear ();
1156
1157         for (uint32_t i = 0; i < nchans.n_audio(); ++i) {
1158                 _data_ready_connections.push_back (0);
1159         }
1160
1161         for (uint32_t n = 0; n < nchans.n_audio(); ++n) {
1162
1163                 if (n >= audio_region()->n_channels()) {
1164                         break;
1165                 }
1166
1167                 // cerr << "\tchannel " << n << endl;
1168
1169                 if (wait_for_data) {
1170                         if (audio_region()->audio_source(n)->peaks_ready (boost::bind (&AudioRegionView::peaks_ready_handler, this, n), &_data_ready_connections[n], gui_context())) {
1171                                 // cerr << "\tData is ready\n";
1172                                 create_one_wave (n, true);
1173                         } else {
1174                                 // cerr << "\tdata is not ready\n";
1175                                 // we'll get a PeaksReady signal from the source in the future
1176                                 // and will call create_one_wave(n) then.
1177                                 pending_peak_data->show ();
1178                         }
1179
1180                 } else {
1181                         // cerr << "\tdon't delay, display today!\n";
1182                         create_one_wave (n, true);
1183                 }
1184
1185         }
1186 }
1187
1188 void
1189 AudioRegionView::create_one_wave (uint32_t which, bool /*direct*/)
1190 {
1191         //cerr << "AudioRegionView::create_one_wave() called which: " << which << " this: " << this << endl;//DEBUG
1192         RouteTimeAxisView& atv (*(dynamic_cast<RouteTimeAxisView*>(&trackview))); // ick
1193         if (!trackview.session() || trackview.session()->deletion_in_progress () || !atv.track()) {
1194                 /* peaks_ready_handler() may be called from peak_thread_work() while
1195                  * session deletion is in progress.
1196                  * Since session-unload happens in the GUI thread, we need to test
1197                  * in this context.
1198                  */
1199                 return;
1200         }
1201         uint32_t nchans = atv.track()->n_channels().n_audio();
1202         uint32_t n;
1203         uint32_t nwaves = std::min (nchans, audio_region()->n_channels());
1204         gdouble ht;
1205
1206         /* compare to set_height(), use _height as set by streamview (child_height),
1207          * not trackview.current_height() to take stacked layering into acconnt
1208          */
1209         if (!UIConfiguration::instance().get_show_name_highlight() || (_height < NAME_HIGHLIGHT_THRESH)) {
1210                 ht = _height / (double) nchans;
1211         } else {
1212                 ht = (_height - NAME_HIGHLIGHT_SIZE) / (double) nchans;
1213         }
1214
1215         /* first waveview starts at 1.0, not 0.0 since that will overlap the
1216          * frame
1217          */
1218
1219         gdouble yoff = which * ht;
1220
1221         WaveView *wave = new WaveView (group, audio_region ());
1222         CANVAS_DEBUG_NAME (wave, string_compose ("wave view for chn %1 of %2", which, get_item_name()));
1223
1224         wave->set_channel (which);
1225         wave->set_y_position (yoff);
1226         wave->set_height (ht);
1227         wave->set_samples_per_pixel (samples_per_pixel);
1228         wave->set_show_zero_line (true);
1229         wave->set_clip_level (UIConfiguration::instance().get_waveform_clip_level ());
1230         wave->set_start_shift (1.0);
1231
1232         wave->Event.connect (sigc::bind (sigc::mem_fun (PublicEditor::instance(), &PublicEditor::canvas_wave_view_event), wave, this));
1233
1234         switch (UIConfiguration::instance().get_waveform_shape()) {
1235         case Rectified:
1236                 wave->set_shape (WaveView::Rectified);
1237                 break;
1238         default:
1239                 wave->set_shape (WaveView::Normal);
1240         }
1241
1242         wave->set_logscaled (UIConfiguration::instance().get_waveform_scale() == Logarithmic);
1243
1244         vector<ArdourCanvas::WaveView*> v;
1245         v.push_back (wave);
1246         set_some_waveform_colors (v);
1247
1248         if (!UIConfiguration::instance().get_show_waveforms ()) {
1249                 wave->hide();
1250         }
1251
1252         /* note: calling this function is serialized by the lock
1253            held in the peak building thread that signals that
1254            peaks are ready for use *or* by the fact that it is
1255            called one by one from the GUI thread.
1256         */
1257
1258         if (which < nchans) {
1259                 tmp_waves[which] = wave;
1260         } else {
1261                 /* n-channel track, >n-channel source */
1262         }
1263
1264         /* see if we're all ready */
1265
1266         for (n = 0; n < nchans; ++n) {
1267                 if (tmp_waves[n] == 0) {
1268                         break;
1269                 }
1270         }
1271
1272         if (n == nwaves && waves.empty()) {
1273                 /* all waves are ready */
1274                 tmp_waves.resize(nwaves);
1275
1276                 waves = tmp_waves;
1277                 tmp_waves.clear ();
1278
1279                 /* indicate peak-completed */
1280                 pending_peak_data->hide ();
1281
1282                 /* Restore stacked coverage */
1283                 std::string str = trackview.gui_property ("layer-display");
1284                 if (!str.empty()) {
1285                         LayerDisplay layer_display;
1286                         update_coverage_frames (LayerDisplay (string_2_enum (str, layer_display)));
1287                 }
1288         }
1289
1290         /* channel wave created, don't hook into peaks ready anymore */
1291         delete _data_ready_connections[which];
1292         _data_ready_connections[which] = 0;
1293 }
1294
1295 void
1296 AudioRegionView::peaks_ready_handler (uint32_t which)
1297 {
1298         Gtkmm2ext::UI::instance()->call_slot (invalidator (*this), boost::bind (&AudioRegionView::create_one_wave, this, which, false));
1299         // cerr << "AudioRegionView::peaks_ready_handler() called on " << which << " this: " << this << endl;
1300 }
1301
1302 void
1303 AudioRegionView::add_gain_point_event (ArdourCanvas::Item *item, GdkEvent *ev, bool with_guard_points)
1304 {
1305         if (!gain_line) {
1306                 return;
1307         }
1308
1309         uint32_t before_p, after_p;
1310         double mx = ev->button.x;
1311         double my = ev->button.y;
1312
1313         item->canvas_to_item (mx, my);
1314
1315         framecnt_t const frame_within_region = (framecnt_t) floor (mx * samples_per_pixel);
1316
1317         if (!gain_line->control_points_adjacent (frame_within_region, before_p, after_p)) {
1318                 /* no adjacent points */
1319                 return;
1320         }
1321
1322         /*y is in item frame */
1323         double const bx = gain_line->nth (before_p)->get_x();
1324         double const ax = gain_line->nth (after_p)->get_x();
1325         double const click_ratio = (ax - mx) / (ax - bx);
1326
1327         double y = ((gain_line->nth (before_p)->get_y() * click_ratio) + (gain_line->nth (after_p)->get_y() * (1 - click_ratio)));
1328
1329         /* don't create points that can't be seen */
1330
1331         update_envelope_visibility ();
1332
1333         framepos_t rpos = region ()->position ();
1334         framepos_t fx = trackview.editor().pixel_to_sample (mx) + rpos;
1335         trackview.editor ().snap_to_with_modifier (fx, ev);
1336         fx -= rpos;
1337
1338         if (fx > _region->length()) {
1339                 return;
1340         }
1341
1342         /* compute vertical fractional position */
1343
1344         y = 1.0 - (y / (gain_line->height()));
1345
1346         /* map using gain line */
1347
1348         gain_line->view_to_model_coord (mx, y);
1349
1350         /* XXX STATEFUL: can't convert to stateful diff until we
1351            can represent automation data with it.
1352         */
1353
1354         XMLNode &before = audio_region()->envelope()->get_state();
1355         MementoCommand<AudioRegion>* region_memento = 0;
1356
1357         if (!audio_region()->envelope_active()) {
1358                 XMLNode &region_before = audio_region()->get_state();
1359                 audio_region()->set_envelope_active(true);
1360                 XMLNode &region_after = audio_region()->get_state();
1361                 region_memento = new MementoCommand<AudioRegion>(*(audio_region().get()), &region_before, &region_after);
1362         }
1363
1364         if (audio_region()->envelope()->editor_add (fx, y, with_guard_points)) {
1365                 XMLNode &after = audio_region()->envelope()->get_state();
1366                 std::list<Selectable*> results;
1367
1368                 trackview.editor().begin_reversible_command (_("add gain control point"));
1369
1370                 if (region_memento) {
1371                         trackview.session()->add_command (region_memento);
1372                 }
1373
1374                 trackview.session()->add_command (new MementoCommand<AutomationList>(*audio_region()->envelope().get(), &before, &after));
1375
1376                 gain_line->get_selectables (fx + region ()->position (), fx + region ()->position (), 0.0, 1.0, results);
1377                 trackview.editor ().get_selection ().set (results);
1378
1379                 trackview.editor ().commit_reversible_command ();
1380                 trackview.session ()->set_dirty ();
1381         }
1382 }
1383
1384 void
1385 AudioRegionView::remove_gain_point_event (ArdourCanvas::Item *item, GdkEvent* /*ev*/)
1386 {
1387         ControlPoint *cp = reinterpret_cast<ControlPoint *> (item->get_data ("control_point"));
1388         audio_region()->envelope()->erase (cp->model());
1389 }
1390
1391 GhostRegion*
1392 AudioRegionView::add_ghost (TimeAxisView& tv)
1393 {
1394         RouteTimeAxisView* rtv = dynamic_cast<RouteTimeAxisView*>(&trackview);
1395         assert(rtv);
1396
1397         double unit_position = _region->position () / samples_per_pixel;
1398         AudioGhostRegion* ghost = new AudioGhostRegion (*this, tv, trackview, unit_position);
1399         uint32_t nchans;
1400
1401         nchans = rtv->track()->n_channels().n_audio();
1402
1403         for (uint32_t n = 0; n < nchans; ++n) {
1404
1405                 if (n >= audio_region()->n_channels()) {
1406                         break;
1407                 }
1408
1409                 WaveView *wave = new WaveView (ghost->group, audio_region());
1410                 CANVAS_DEBUG_NAME (wave, string_compose ("ghost wave for %1", get_item_name()));
1411
1412                 wave->set_channel (n);
1413                 wave->set_samples_per_pixel (samples_per_pixel);
1414                 wave->set_amplitude_above_axis (_amplitude_above_axis);
1415
1416                 ghost->waves.push_back(wave);
1417         }
1418
1419         ghost->set_height ();
1420         ghost->set_duration (_region->length() / samples_per_pixel);
1421         ghost->set_colors();
1422         ghosts.push_back (ghost);
1423
1424         return ghost;
1425 }
1426
1427 void
1428 AudioRegionView::entered ()
1429 {
1430         trackview.editor().set_current_trimmable (_region);
1431         trackview.editor().set_current_movable (_region);
1432
1433         update_envelope_visibility();
1434
1435         if ((trackview.editor().current_mouse_mode() == Editing::MouseObject)) {
1436                 if (start_xfade_rect) {
1437                         start_xfade_rect->set_outline (true);
1438                 }
1439                 if (end_xfade_rect) {
1440                         end_xfade_rect->set_outline (true);
1441                 }
1442                 if (fade_in_handle) {
1443                         fade_in_handle->show ();
1444                         fade_in_handle->raise_to_top ();
1445                 }
1446                 if (fade_out_handle) {
1447                         fade_out_handle->show ();
1448                         fade_out_handle->raise_to_top ();
1449                 }
1450                 if (fade_in_trim_handle) {
1451                         boost::shared_ptr<AudioRegion> ar (audio_region());
1452                         if (!ar->locked() && (ar->fade_in()->back()->when > 64 || (ar->can_trim() & Trimmable::FrontTrimEarlier))) {
1453                                 fade_in_trim_handle->show ();
1454                                 fade_in_trim_handle->raise_to_top ();
1455                         } else {
1456                                 fade_in_trim_handle->hide ();
1457                         }
1458                 }
1459                 if (fade_out_trim_handle) {
1460                         boost::shared_ptr<AudioRegion> ar (audio_region());
1461                         if (!ar->locked() && (ar->fade_out()->back()->when > 64 || (ar->can_trim() & Trimmable::EndTrimLater))) {
1462                                 fade_out_trim_handle->show ();
1463                                 fade_out_trim_handle->raise_to_top ();
1464                         } else {
1465                                 fade_out_trim_handle->hide ();
1466                         }
1467                 }
1468         } else {  //this happens when we switch tools; if we switch away from Grab mode,  hide all the fade handles
1469                 if (fade_in_handle)       { fade_in_handle->hide(); }
1470                 if (fade_out_handle)      { fade_out_handle->hide(); }
1471                 if (fade_in_trim_handle)  { fade_in_trim_handle->hide(); }
1472                 if (fade_out_trim_handle) { fade_out_trim_handle->hide(); }
1473                 if (start_xfade_rect)     { start_xfade_rect->set_outline (false); }
1474                 if (end_xfade_rect)       { end_xfade_rect->set_outline (false); }
1475         }
1476 }
1477
1478 void
1479 AudioRegionView::exited ()
1480 {
1481         trackview.editor().set_current_trimmable (boost::shared_ptr<Trimmable>());
1482         trackview.editor().set_current_movable (boost::shared_ptr<Movable>());
1483
1484 //      if (gain_line) {
1485 //              gain_line->remove_visibility (AutomationLine::ControlPoints);
1486 //      }
1487
1488         if (fade_in_handle)       { fade_in_handle->hide(); }
1489         if (fade_out_handle)      { fade_out_handle->hide(); }
1490         if (fade_in_trim_handle)  { fade_in_trim_handle->hide(); }
1491         if (fade_out_trim_handle) { fade_out_trim_handle->hide(); }
1492         if (start_xfade_rect)     { start_xfade_rect->set_outline (false); }
1493         if (end_xfade_rect)       { end_xfade_rect->set_outline (false); }
1494 }
1495
1496 void
1497 AudioRegionView::envelope_active_changed ()
1498 {
1499         if (gain_line) {
1500                 gain_line->set_line_color (audio_region()->envelope_active() ?
1501                                            UIConfiguration::instance().color ("gain line") :
1502                                            UIConfiguration::instance().color_mod ("gain line inactive", "gain line inactive"));
1503                 update_envelope_visibility ();
1504         }
1505 }
1506
1507 void
1508 AudioRegionView::color_handler ()
1509 {
1510         //case cMutedWaveForm:
1511         //case cWaveForm:
1512         //case cWaveFormClip:
1513         //case cZeroLine:
1514         set_colors ();
1515
1516         //case cGainLineInactive:
1517         //case cGainLine:
1518         envelope_active_changed();
1519
1520 }
1521
1522 void
1523 AudioRegionView::set_waveform_colors ()
1524 {
1525         set_some_waveform_colors (waves);
1526 }
1527
1528 void
1529 AudioRegionView::set_some_waveform_colors (vector<ArdourCanvas::WaveView*>& waves_to_color)
1530 {
1531         ArdourCanvas::Color fill;
1532         ArdourCanvas::Color outline;
1533         ArdourCanvas::Color clip = UIConfiguration::instance().color ("clipped waveform");
1534         ArdourCanvas::Color zero = UIConfiguration::instance().color ("zero line");
1535
1536         if (_selected) {
1537                 if (_region->muted()) {
1538                         /* hide outline with zero alpha */
1539                         outline = UINT_RGBA_CHANGE_A(UIConfiguration::instance().color ("selected waveform outline"), 0);
1540                         fill = UINT_RGBA_CHANGE_A(UIConfiguration::instance().color ("selected waveform fill"), MUTED_ALPHA);
1541                 } else {
1542                         outline = UIConfiguration::instance().color ("selected waveform outline");
1543                         fill = UIConfiguration::instance().color ("selected waveform fill");
1544                 }
1545         } else {
1546                 if (_recregion) {
1547                         outline = UIConfiguration::instance().color ("recording waveform outline");
1548                         fill = UIConfiguration::instance().color ("recording waveform fill");
1549                 } else {
1550                         if (_region->muted()) {
1551                                 /* hide outline with zero alpha */
1552                                 outline = UINT_RGBA_CHANGE_A(UIConfiguration::instance().color ("waveform outline"), 0);
1553                                 fill = UINT_RGBA_CHANGE_A(UIConfiguration::instance().color ("waveform fill"), MUTED_ALPHA);
1554                         } else {
1555                                 outline = UIConfiguration::instance().color ("waveform outline");
1556                                 fill = UIConfiguration::instance().color ("waveform fill");
1557                         }
1558                 }
1559         }
1560
1561         for (vector<ArdourCanvas::WaveView*>::iterator w = waves_to_color.begin(); w != waves_to_color.end(); ++w) {
1562                 (*w)->set_fill_color (fill);
1563                 (*w)->set_outline_color (outline);
1564                 (*w)->set_clip_color (clip);
1565                 (*w)->set_zero_color (zero);
1566         }
1567 }
1568
1569 void
1570 AudioRegionView::set_frame_color ()
1571 {
1572         if (!frame) {
1573                 return;
1574         }
1575
1576         RegionView::set_frame_color ();
1577
1578         set_waveform_colors ();
1579 }
1580
1581 void
1582 AudioRegionView::set_fade_visibility (bool yn)
1583 {
1584         if (yn) {
1585                 if (start_xfade_curve)    { start_xfade_curve->show (); }
1586                 if (end_xfade_curve)      { end_xfade_curve->show (); }
1587                 if (start_xfade_rect)     { start_xfade_rect->show (); }
1588                 if (end_xfade_rect)       { end_xfade_rect->show (); }
1589                 } else {
1590                 if (start_xfade_curve)    { start_xfade_curve->hide(); }
1591                 if (end_xfade_curve)      { end_xfade_curve->hide(); }
1592                 if (fade_in_handle)       { fade_in_handle->hide(); }
1593                 if (fade_out_handle)      { fade_out_handle->hide(); }
1594                 if (fade_in_trim_handle)  { fade_in_trim_handle->hide(); }
1595                 if (fade_out_trim_handle) { fade_out_trim_handle->hide(); }
1596                 if (start_xfade_rect)     { start_xfade_rect->hide (); }
1597                 if (end_xfade_rect)       { end_xfade_rect->hide (); }
1598                 if (start_xfade_rect)     { start_xfade_rect->set_outline (false); }
1599                 if (end_xfade_rect)       { end_xfade_rect->set_outline (false); }
1600         }
1601 }
1602
1603 void
1604 AudioRegionView::update_coverage_frames (LayerDisplay d)
1605 {
1606         RegionView::update_coverage_frames (d);
1607
1608         if (fade_in_handle)       { fade_in_handle->raise_to_top (); }
1609         if (fade_out_handle)      { fade_out_handle->raise_to_top (); }
1610         if (fade_in_trim_handle)  { fade_in_trim_handle->raise_to_top (); }
1611         if (fade_out_trim_handle) { fade_out_trim_handle->raise_to_top (); }
1612 }
1613
1614 void
1615 AudioRegionView::show_region_editor ()
1616 {
1617         if (editor == 0) {
1618                 editor = new AudioRegionEditor (trackview.session(), audio_region());
1619         }
1620
1621         editor->present ();
1622         editor->show_all();
1623 }
1624
1625 void
1626 AudioRegionView::transients_changed ()
1627 {
1628         AnalysisFeatureList analysis_features = _region->transients();
1629
1630         while (feature_lines.size() < analysis_features.size()) {
1631
1632                 ArdourCanvas::Line* canvas_item = new ArdourCanvas::Line(group);
1633                 CANVAS_DEBUG_NAME (canvas_item, string_compose ("transient group for %1", region()->name()));
1634
1635                 canvas_item->set (ArdourCanvas::Duple (-1.0, 2.0),
1636                                   ArdourCanvas::Duple (1.0, _height - TimeAxisViewItem::NAME_HIGHLIGHT_SIZE - 1));
1637
1638                 canvas_item->raise_to_top ();
1639                 canvas_item->show ();
1640
1641                 canvas_item->set_data ("regionview", this);
1642                 canvas_item->Event.connect (sigc::bind (sigc::mem_fun (PublicEditor::instance(), &PublicEditor::canvas_feature_line_event), canvas_item, this));
1643
1644                 feature_lines.push_back (make_pair(0, canvas_item));
1645         }
1646
1647         while (feature_lines.size() > analysis_features.size()) {
1648                 ArdourCanvas::Line* line = feature_lines.back().second;
1649                 feature_lines.pop_back ();
1650                 delete line;
1651         }
1652
1653         AnalysisFeatureList::const_iterator i;
1654         list<std::pair<framepos_t, ArdourCanvas::Line*> >::iterator l;
1655
1656         for (i = analysis_features.begin(), l = feature_lines.begin(); i != analysis_features.end() && l != feature_lines.end(); ++i, ++l) {
1657
1658                 float *pos = new float;
1659                 *pos = trackview.editor().sample_to_pixel (*i);
1660
1661                 (*l).second->set (
1662                         ArdourCanvas::Duple (*pos, 2.0),
1663                         ArdourCanvas::Duple (*pos, _height - TimeAxisViewItem::NAME_HIGHLIGHT_SIZE - 1)
1664                         );
1665
1666                 (*l).second->set_data ("position", pos);
1667                 (*l).first = *i;
1668         }
1669 }
1670
1671 void
1672 AudioRegionView::update_transient(float /*old_pos*/, float new_pos)
1673 {
1674         /* Find frame at old pos, calulate new frame then update region transients*/
1675         list<std::pair<framepos_t, ArdourCanvas::Line*> >::iterator l;
1676
1677         for (l = feature_lines.begin(); l != feature_lines.end(); ++l) {
1678
1679                 /* Line has been updated in drag so we compare to new_pos */
1680
1681                 float* pos = (float*) (*l).second->get_data ("position");
1682
1683                 if (rint(new_pos) == rint(*pos)) {
1684
1685                     framepos_t old_frame = (*l).first;
1686                     framepos_t new_frame = trackview.editor().pixel_to_sample (new_pos);
1687
1688                     _region->update_transient (old_frame, new_frame);
1689
1690                     break;
1691                 }
1692         }
1693 }
1694
1695 void
1696 AudioRegionView::remove_transient(float pos)
1697 {
1698         /* Find frame at old pos, calulate new frame then update region transients*/
1699         list<std::pair<framepos_t, ArdourCanvas::Line*> >::iterator l;
1700
1701         for (l = feature_lines.begin(); l != feature_lines.end(); ++l) {
1702
1703                 /* Line has been updated in drag so we compare to new_pos */
1704                 float *line_pos = (float*) (*l).second->get_data ("position");
1705
1706                 if (rint(pos) == rint(*line_pos)) {
1707                     _region->remove_transient ((*l).first);
1708                     break;
1709                 }
1710         }
1711 }
1712
1713 void
1714 AudioRegionView::thaw_after_trim ()
1715 {
1716         RegionView::thaw_after_trim ();
1717         unhide_envelope ();
1718         drag_end ();
1719 }
1720
1721
1722 void
1723 AudioRegionView::show_xfades ()
1724 {
1725         show_start_xfade ();
1726         show_end_xfade ();
1727 }
1728
1729 void
1730 AudioRegionView::drag_start ()
1731 {
1732         TimeAxisViewItem::drag_start ();
1733
1734         //we used to hide xfades here.  I don't see the point with the new model, but we can re-implement if needed
1735 }
1736
1737 void
1738 AudioRegionView::drag_end ()
1739 {
1740         TimeAxisViewItem::drag_end ();
1741         //see comment for drag_start
1742
1743         if (fade_in_handle && fade_in_handle->visible()) {
1744                 // lenght of region or fade changed, re-check
1745                 // if fade_in_trim_handle or fade_out_trim_handle should
1746                 // be visible. -- If the fade_in_handle is visible
1747                 // we have focus and are not in internal edit mode.
1748                 entered();
1749         }
1750 }
1751
1752 void
1753 AudioRegionView::parameter_changed (string const & p)
1754 {
1755         if (p == "show-waveforms") {
1756                 setup_waveform_visibility ();
1757         }
1758 }