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