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