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