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