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