Merge branch 'master' into windows
[ardour.git] / gtk2_ardour / editor_drag.cc
1 /*
2     Copyright (C) 2009 Paul Davis
3
4     This program is free software; you can redistribute 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
20 #ifdef WAF_BUILD
21 #include "gtk2ardour-config.h"
22 #endif
23
24 #include <stdint.h>
25 #include <algorithm>
26
27 #include "pbd/memento_command.h"
28 #include "pbd/basename.h"
29 #include "pbd/stateful_diff_command.h"
30
31 #include "gtkmm2ext/utils.h"
32
33 #include "ardour/audioengine.h"
34 #include "ardour/audioregion.h"
35 #include "ardour/dB.h"
36 #include "ardour/midi_region.h"
37 #include "ardour/operations.h"
38 #include "ardour/region_factory.h"
39 #include "ardour/session.h"
40
41 #include "editor.h"
42 #include "i18n.h"
43 #include "keyboard.h"
44 #include "audio_region_view.h"
45 #include "midi_region_view.h"
46 #include "ardour_ui.h"
47 #include "gui_thread.h"
48 #include "control_point.h"
49 #include "utils.h"
50 #include "region_gain_line.h"
51 #include "editor_drag.h"
52 #include "audio_time_axis.h"
53 #include "midi_time_axis.h"
54 #include "canvas-note.h"
55 #include "selection.h"
56 #include "midi_selection.h"
57 #include "automation_time_axis.h"
58 #include "debug.h"
59 #include "editor_cursors.h"
60 #include "mouse_cursors.h"
61 #include "verbose_cursor.h"
62
63 using namespace std;
64 using namespace ARDOUR;
65 using namespace PBD;
66 using namespace Gtk;
67 using namespace Gtkmm2ext;
68 using namespace Editing;
69 using namespace ArdourCanvas;
70
71 using Gtkmm2ext::Keyboard;
72
73 double ControlPointDrag::_zero_gain_fraction = -1.0;
74
75 DragManager::DragManager (Editor* e)
76         : _editor (e)
77         , _ending (false)
78         , _current_pointer_frame (0)
79 {
80 }
81
82 DragManager::~DragManager ()
83 {
84         abort ();
85 }
86
87 /** Call abort for each active drag */
88 void
89 DragManager::abort ()
90 {
91         _ending = true;
92
93         for (list<Drag*>::const_iterator i = _drags.begin(); i != _drags.end(); ++i) {
94                 (*i)->abort ();
95                 delete *i;
96         }
97
98         if (!_drags.empty ()) {
99                 _editor->set_follow_playhead (_old_follow_playhead, false);
100         }
101
102         _drags.clear ();
103
104         _ending = false;
105 }
106
107 void
108 DragManager::add (Drag* d)
109 {
110         d->set_manager (this);
111         _drags.push_back (d);
112 }
113
114 void
115 DragManager::set (Drag* d, GdkEvent* e, Gdk::Cursor* c)
116 {
117         d->set_manager (this);
118         _drags.push_back (d);
119         start_grab (e, c);
120 }
121
122 void
123 DragManager::start_grab (GdkEvent* e, Gdk::Cursor* c)
124 {
125         /* Prevent follow playhead during the drag to be nice to the user */
126         _old_follow_playhead = _editor->follow_playhead ();
127         _editor->set_follow_playhead (false);
128
129         _current_pointer_frame = _editor->event_frame (e, &_current_pointer_x, &_current_pointer_y);
130
131         for (list<Drag*>::const_iterator i = _drags.begin(); i != _drags.end(); ++i) {
132                 (*i)->start_grab (e, c);
133         }
134 }
135
136 /** Call end_grab for each active drag.
137  *  @return true if any drag reported movement having occurred.
138  */
139 bool
140 DragManager::end_grab (GdkEvent* e)
141 {
142         _ending = true;
143
144         bool r = false;
145         for (list<Drag*>::iterator i = _drags.begin(); i != _drags.end(); ++i) {
146                 bool const t = (*i)->end_grab (e);
147                 if (t) {
148                         r = true;
149                 }
150                 delete *i;
151         }
152
153         _drags.clear ();
154
155         _ending = false;
156
157         _editor->set_follow_playhead (_old_follow_playhead, false);
158
159         return r;
160 }
161
162 bool
163 DragManager::motion_handler (GdkEvent* e, bool from_autoscroll)
164 {
165         bool r = false;
166
167         _current_pointer_frame = _editor->event_frame (e, &_current_pointer_x, &_current_pointer_y);
168
169         for (list<Drag*>::iterator i = _drags.begin(); i != _drags.end(); ++i) {
170                 bool const t = (*i)->motion_handler (e, from_autoscroll);
171                 if (t) {
172                         r = true;
173                 }
174
175         }
176
177         return r;
178 }
179
180 bool
181 DragManager::have_item (ArdourCanvas::Item* i) const
182 {
183         list<Drag*>::const_iterator j = _drags.begin ();
184         while (j != _drags.end() && (*j)->item () != i) {
185                 ++j;
186         }
187
188         return j != _drags.end ();
189 }
190
191 Drag::Drag (Editor* e, ArdourCanvas::Item* i)
192         : _editor (e)
193         , _item (i)
194         , _pointer_frame_offset (0)
195         , _move_threshold_passed (false)
196         , _raw_grab_frame (0)
197         , _grab_frame (0)
198         , _last_pointer_frame (0)
199 {
200
201 }
202
203 void
204 Drag::swap_grab (ArdourCanvas::Item* new_item, Gdk::Cursor* cursor, uint32_t time)
205 {
206         _item->ungrab (0);
207         _item = new_item;
208
209         if (cursor == 0) {
210                 _item->grab (Gdk::POINTER_MOTION_MASK | Gdk::BUTTON_PRESS_MASK | Gdk::BUTTON_RELEASE_MASK, time);
211         } else {
212                 _item->grab (Gdk::POINTER_MOTION_MASK | Gdk::BUTTON_PRESS_MASK | Gdk::BUTTON_RELEASE_MASK, *cursor, time);
213         }
214 }
215
216 void
217 Drag::start_grab (GdkEvent* event, Gdk::Cursor *cursor)
218 {
219         // if dragging with button2, the motion is x constrained, with Alt-button2 it is y constrained
220
221         if (Keyboard::is_button2_event (&event->button)) {
222                 if (Keyboard::modifier_state_equals (event->button.state, Keyboard::SecondaryModifier)) {
223                         _y_constrained = true;
224                         _x_constrained = false;
225                 } else {
226                         _y_constrained = false;
227                         _x_constrained = true;
228                 }
229         } else {
230                 _x_constrained = false;
231                 _y_constrained = false;
232         }
233
234         _raw_grab_frame = _editor->event_frame (event, &_grab_x, &_grab_y);
235         setup_pointer_frame_offset ();
236         _grab_frame = adjusted_frame (_raw_grab_frame, event);
237         _last_pointer_frame = _grab_frame;
238         _last_pointer_x = _grab_x;
239         _last_pointer_y = _grab_y;
240
241         if (cursor == 0) {
242                 _item->grab (Gdk::POINTER_MOTION_MASK|Gdk::BUTTON_PRESS_MASK|Gdk::BUTTON_RELEASE_MASK,
243                              event->button.time);
244         } else {
245                 _item->grab (Gdk::POINTER_MOTION_MASK|Gdk::BUTTON_PRESS_MASK|Gdk::BUTTON_RELEASE_MASK,
246                              *cursor,
247                              event->button.time);
248         }
249
250         if (_editor->session() && _editor->session()->transport_rolling()) {
251                 _was_rolling = true;
252         } else {
253                 _was_rolling = false;
254         }
255
256         switch (_editor->snap_type()) {
257         case SnapToRegionStart:
258         case SnapToRegionEnd:
259         case SnapToRegionSync:
260         case SnapToRegionBoundary:
261                 _editor->build_region_boundary_cache ();
262                 break;
263         default:
264                 break;
265         }
266 }
267
268 /** Call to end a drag `successfully'.  Ungrabs item and calls
269  *  subclass' finished() method.
270  *
271  *  @param event GDK event, or 0.
272  *  @return true if some movement occurred, otherwise false.
273  */
274 bool
275 Drag::end_grab (GdkEvent* event)
276 {
277         _editor->stop_canvas_autoscroll ();
278
279         _item->ungrab (event ? event->button.time : 0);
280
281         finished (event, _move_threshold_passed);
282
283         _editor->verbose_cursor()->hide ();
284
285         return _move_threshold_passed;
286 }
287
288 framepos_t
289 Drag::adjusted_frame (framepos_t f, GdkEvent const * event, bool snap) const
290 {
291         framepos_t pos = 0;
292
293         if (f > _pointer_frame_offset) {
294                 pos = f - _pointer_frame_offset;
295         }
296
297         if (snap) {
298                 _editor->snap_to_with_modifier (pos, event);
299         }
300
301         return pos;
302 }
303
304 framepos_t
305 Drag::adjusted_current_frame (GdkEvent const * event, bool snap) const
306 {
307         return adjusted_frame (_drags->current_pointer_frame (), event, snap);
308 }
309
310 bool
311 Drag::motion_handler (GdkEvent* event, bool from_autoscroll)
312 {
313         /* check to see if we have moved in any way that matters since the last motion event */
314         if (_move_threshold_passed &&
315             (!x_movement_matters() || _last_pointer_frame == adjusted_current_frame (event)) &&
316             (!y_movement_matters() || _last_pointer_y == _drags->current_pointer_y ()) ) {
317                 return false;
318         }
319
320         pair<framecnt_t, int> const threshold = move_threshold ();
321
322         bool const old_move_threshold_passed = _move_threshold_passed;
323
324         if (!from_autoscroll && !_move_threshold_passed) {
325
326                 bool const xp = (::llabs (_drags->current_pointer_frame () - _raw_grab_frame) >= threshold.first);
327                 bool const yp = (::fabs ((_drags->current_pointer_y () - _grab_y)) >= threshold.second);
328
329                 _move_threshold_passed = ((xp && x_movement_matters()) || (yp && y_movement_matters()));
330         }
331
332         if (active (_editor->mouse_mode) && _move_threshold_passed) {
333
334                 if (event->motion.state & Gdk::BUTTON1_MASK || event->motion.state & Gdk::BUTTON2_MASK) {
335                         if (!from_autoscroll) {
336                                 bool const moving_left = _drags->current_pointer_x() < _last_pointer_x;
337                                 bool const moving_up = _drags->current_pointer_y() < _last_pointer_y;
338                                 _editor->maybe_autoscroll (true, allow_vertical_autoscroll (), moving_left, moving_up);
339                         }
340
341                         motion (event, _move_threshold_passed != old_move_threshold_passed);
342
343                         _last_pointer_x = _drags->current_pointer_x ();
344                         _last_pointer_y = _drags->current_pointer_y ();
345                         _last_pointer_frame = adjusted_current_frame (event);
346
347                         return true;
348                 }
349         }
350         return false;
351 }
352
353 /** Call to abort a drag.  Ungrabs item and calls subclass's aborted () */
354 void
355 Drag::abort ()
356 {
357         if (_item) {
358                 _item->ungrab (0);
359         }
360
361         aborted (_move_threshold_passed);
362
363         _editor->stop_canvas_autoscroll ();
364         _editor->verbose_cursor()->hide ();
365 }
366
367 void
368 Drag::show_verbose_cursor_time (framepos_t frame)
369 {
370         _editor->verbose_cursor()->set_time (
371                 frame,
372                 _drags->current_pointer_x() + 10 - _editor->horizontal_position(),
373                 _drags->current_pointer_y() + 10 - _editor->vertical_adjustment.get_value() + _editor->canvas_timebars_vsize
374                 );
375
376         _editor->verbose_cursor()->show ();
377 }
378
379 void
380 Drag::show_verbose_cursor_duration (framepos_t start, framepos_t end, double xoffset)
381 {
382         _editor->verbose_cursor()->show (xoffset);
383
384         _editor->verbose_cursor()->set_duration (
385                 start, end,
386                 _drags->current_pointer_x() + 10 - _editor->horizontal_position(),
387                 _drags->current_pointer_y() + 10 - _editor->vertical_adjustment.get_value() + _editor->canvas_timebars_vsize
388                 );
389 }
390
391 void
392 Drag::show_verbose_cursor_text (string const & text)
393 {
394         _editor->verbose_cursor()->show ();
395
396         _editor->verbose_cursor()->set (
397                 text,
398                 _drags->current_pointer_x() + 10 - _editor->horizontal_position(),
399                 _drags->current_pointer_y() + 10 - _editor->vertical_adjustment.get_value() + _editor->canvas_timebars_vsize
400                 );
401 }
402
403 boost::shared_ptr<Region>
404 Drag::add_midi_region (MidiTimeAxisView* view)
405 {
406         if (_editor->session()) {
407                 const TempoMap& map (_editor->session()->tempo_map());
408                 framecnt_t pos = grab_frame();
409                 const Meter& m = map.meter_at (pos);
410                 /* not that the frame rate used here can be affected by pull up/down which
411                    might be wrong.
412                 */
413                 framecnt_t len = m.frames_per_bar (map.tempo_at (pos), _editor->session()->frame_rate());
414                 return view->add_region (grab_frame(), len, true);
415         }
416
417         return boost::shared_ptr<Region>();
418 }
419
420 struct EditorOrderTimeAxisViewSorter {
421     bool operator() (TimeAxisView* a, TimeAxisView* b) {
422             RouteTimeAxisView* ra = dynamic_cast<RouteTimeAxisView*> (a);
423             RouteTimeAxisView* rb = dynamic_cast<RouteTimeAxisView*> (b);
424             assert (ra && rb);
425             return ra->route()->order_key (EditorSort) < rb->route()->order_key (EditorSort);
426     }
427 };
428
429 RegionDrag::RegionDrag (Editor* e, ArdourCanvas::Item* i, RegionView* p, list<RegionView*> const & v)
430         : Drag (e, i),
431           _primary (p)
432 {
433         _editor->visible_order_range (&_visible_y_low, &_visible_y_high);
434
435         /* Make a list of tracks to refer to during the drag; we include hidden tracks,
436            as some of the regions we are dragging may be on such tracks.
437         */
438
439         TrackViewList track_views = _editor->track_views;
440         track_views.sort (EditorOrderTimeAxisViewSorter ());
441
442         for (TrackViewList::iterator i = track_views.begin(); i != track_views.end(); ++i) {
443                 _time_axis_views.push_back (*i);
444                 
445                 TimeAxisView::Children children_list = (*i)->get_child_list ();
446                 for (TimeAxisView::Children::iterator j = children_list.begin(); j != children_list.end(); ++j) {
447                         _time_axis_views.push_back (j->get());
448                 }
449         }
450
451         /* the list of views can be empty at this point if this is a region list-insert drag
452          */
453
454         for (list<RegionView*>::const_iterator i = v.begin(); i != v.end(); ++i) {
455                 _views.push_back (DraggingView (*i, this));
456         }
457
458         RegionView::RegionViewGoingAway.connect (death_connection, invalidator (*this), boost::bind (&RegionDrag::region_going_away, this, _1), gui_context());
459 }
460
461 void
462 RegionDrag::region_going_away (RegionView* v)
463 {
464         list<DraggingView>::iterator i = _views.begin ();
465         while (i != _views.end() && i->view != v) {
466                 ++i;
467         }
468
469         if (i != _views.end()) {
470                 _views.erase (i);
471         }
472 }
473
474 /** Given a TimeAxisView, return the index of it into the _time_axis_views vector,
475  *  or -1 if it is not found.
476  */
477 int
478 RegionDrag::find_time_axis_view (TimeAxisView* t) const
479 {
480         int i = 0;
481         int const N = _time_axis_views.size ();
482         while (i < N && _time_axis_views[i] != t) {
483                 ++i;
484         }
485
486         if (i == N) {
487                 return -1;
488         }
489
490         return i;
491 }
492
493 RegionMotionDrag::RegionMotionDrag (Editor* e, ArdourCanvas::Item* i, RegionView* p, list<RegionView*> const & v, bool b)
494         : RegionDrag (e, i, p, v),
495           _brushing (b),
496           _total_x_delta (0)
497 {
498
499 }
500
501
502 void
503 RegionMotionDrag::start_grab (GdkEvent* event, Gdk::Cursor* cursor)
504 {
505         Drag::start_grab (event, cursor);
506
507         show_verbose_cursor_time (_last_frame_position);
508
509         pair<TimeAxisView*, double> const tv = _editor->trackview_by_y_position (_drags->current_pointer_y ());
510         _last_pointer_time_axis_view = find_time_axis_view (tv.first);
511         _last_pointer_layer = tv.first->layer_display() == Overlaid ? 0 : tv.second;
512 }
513
514 double
515 RegionMotionDrag::compute_x_delta (GdkEvent const * event, framepos_t* pending_region_position)
516 {
517         /* compute the amount of pointer motion in frames, and where
518            the region would be if we moved it by that much.
519         */
520         *pending_region_position = adjusted_current_frame (event);
521
522         framepos_t sync_frame;
523         framecnt_t sync_offset;
524         int32_t sync_dir;
525
526         sync_offset = _primary->region()->sync_offset (sync_dir);
527
528         /* we don't handle a sync point that lies before zero.
529          */
530         if (sync_dir >= 0 || (sync_dir < 0 && *pending_region_position >= sync_offset)) {
531
532                 sync_frame = *pending_region_position + (sync_dir*sync_offset);
533
534                 _editor->snap_to_with_modifier (sync_frame, event);
535
536                 *pending_region_position = _primary->region()->adjust_to_sync (sync_frame);
537
538         } else {
539                 *pending_region_position = _last_frame_position;
540         }
541
542         if (*pending_region_position > max_framepos - _primary->region()->length()) {
543                 *pending_region_position = _last_frame_position;
544         }
545
546         double dx = 0;
547
548         /* in locked edit mode, reverse the usual meaning of _x_constrained */
549         bool const x_move_allowed = Config->get_edit_mode() == Lock ? _x_constrained : !_x_constrained;
550
551         if ((*pending_region_position != _last_frame_position) && x_move_allowed) {
552
553                 /* x movement since last time (in pixels) */
554                 dx = (static_cast<double> (*pending_region_position) - _last_frame_position) / _editor->frames_per_unit;
555
556                 /* total x movement */
557                 framecnt_t total_dx = *pending_region_position;
558                 if (regions_came_from_canvas()) {
559                         total_dx = total_dx - grab_frame ();
560                 }
561
562                 /* check that no regions have gone off the start of the session */
563                 for (list<DraggingView>::const_iterator i = _views.begin(); i != _views.end(); ++i) {
564                         if ((i->view->region()->position() + total_dx) < 0) {
565                                 dx = 0;
566                                 *pending_region_position = _last_frame_position;
567                                 break;
568                         }
569                 }
570
571                 _last_frame_position = *pending_region_position;
572         }
573
574         return dx;
575 }
576
577 bool
578 RegionMotionDrag::y_movement_allowed (int delta_track, double delta_layer) const
579 {
580         for (list<DraggingView>::const_iterator i = _views.begin(); i != _views.end(); ++i) {
581                 int const n = i->time_axis_view + delta_track;
582                 if (n < 0 || n >= int (_time_axis_views.size())) {
583                         /* off the top or bottom track */
584                         return false;
585                 }
586
587                 RouteTimeAxisView const * to = dynamic_cast<RouteTimeAxisView const *> (_time_axis_views[n]);
588                 if (to == 0 || !to->is_track() || to->track()->data_type() != i->view->region()->data_type()) {
589                         /* not a track, or the wrong type */
590                         return false;
591                 }
592
593                 double const l = i->layer + delta_layer;
594
595                 /* Note that we allow layer to be up to 0.5 below zero, as this is used by `Expanded'
596                    mode to allow the user to place a region below another on layer 0.
597                 */
598                 if (delta_track == 0 && (l < -0.5 || l >= int (to->view()->layers()))) {
599                         /* Off the top or bottom layer; note that we only refuse if the track hasn't changed.
600                            If it has, the layers will be munged later anyway, so it's ok.
601                         */
602                         return false;
603                 }
604         }
605
606         /* all regions being dragged are ok with this change */
607         return true;
608 }
609
610 void
611 RegionMotionDrag::motion (GdkEvent* event, bool first_move)
612 {
613         assert (!_views.empty ());
614
615         /* Find the TimeAxisView that the pointer is now over */
616         pair<TimeAxisView*, double> const tv = _editor->trackview_by_y_position (_drags->current_pointer_y ());
617
618         if (first_move && tv.first->view()->layer_display() == Stacked) {
619                 tv.first->view()->set_layer_display (Expanded);
620         }
621
622         /* Bail early if we're not over a track */
623         RouteTimeAxisView* rtv = dynamic_cast<RouteTimeAxisView*> (tv.first);
624         if (!rtv || !rtv->is_track()) {
625                 _editor->verbose_cursor()->hide ();
626                 return;
627         }
628
629         /* Note: time axis views in this method are often expressed as an index into the _time_axis_views vector */
630
631         /* Here's the current pointer position in terms of time axis view and layer */
632         int const current_pointer_time_axis_view = find_time_axis_view (tv.first);
633         double const current_pointer_layer = tv.first->layer_display() == Overlaid ? 0 : tv.second;
634
635         /* Work out the change in x */
636         framepos_t pending_region_position;
637         double const x_delta = compute_x_delta (event, &pending_region_position);
638
639         /* Work out the change in y */
640         int delta_time_axis_view = current_pointer_time_axis_view - _last_pointer_time_axis_view;
641         double delta_layer = current_pointer_layer - _last_pointer_layer;
642
643         if (!y_movement_allowed (delta_time_axis_view, delta_layer)) {
644                 /* this y movement is not allowed, so do no y movement this time */
645                 delta_time_axis_view = 0;
646                 delta_layer = 0;
647         }
648
649         if (x_delta == 0 && delta_time_axis_view == 0 && delta_layer == 0 && !first_move) {
650                 /* haven't reached next snap point, and we're not switching
651                    trackviews nor layers. nothing to do.
652                 */
653                 return;
654         }
655
656         pair<set<boost::shared_ptr<Playlist> >::iterator,bool> insert_result;
657
658         for (list<DraggingView>::iterator i = _views.begin(); i != _views.end(); ++i) {
659
660                 RegionView* rv = i->view;
661
662                 if (rv->region()->locked() || rv->region()->video_locked()) {
663                         continue;
664                 }
665
666                 if (first_move) {
667
668                         rv->drag_start (); 
669
670                         /* Absolutely no idea why this is necessary, but it is; without
671                            it, the region view disappears after the reparent.
672                         */
673                         _editor->update_canvas_now ();
674                         
675                         /* Reparent to a non scrolling group so that we can keep the
676                            region selection above all time axis views.
677                            Reparenting means that we will have to move the region view
678                            later, as the two parent groups have different coordinates.
679                         */
680
681                         rv->get_canvas_group()->reparent (*(_editor->_region_motion_group));
682                         
683                         rv->fake_set_opaque (true);
684                 }
685
686                 /* If we have moved tracks, we'll fudge the layer delta so that the
687                    region gets moved back onto layer 0 on its new track; this avoids
688                    confusion when dragging regions from non-zero layers onto different
689                    tracks.
690                 */
691                 double this_delta_layer = delta_layer;
692                 if (delta_time_axis_view != 0) {
693                         this_delta_layer = - i->layer;
694                 }
695
696                 /* The TimeAxisView that this region is now on */
697                 TimeAxisView* tv = _time_axis_views[i->time_axis_view + delta_time_axis_view];
698
699                 /* Ensure it is moved from stacked -> expanded if appropriate */
700                 if (tv->view()->layer_display() == Stacked) {
701                         tv->view()->set_layer_display (Expanded);
702                 }
703                 
704                 /* We're only allowed to go -ve in layer on Expanded views */
705                 if (tv->view()->layer_display() != Expanded && (i->layer + this_delta_layer) < 0) {
706                         this_delta_layer = - i->layer;
707                 }
708                 
709                 /* Set height */
710                 rv->set_height (tv->view()->child_height ());
711                 
712                 /* Update show/hidden status as the region view may have come from a hidden track,
713                    or have moved to one.
714                 */
715                 if (tv->hidden ()) {
716                         rv->get_canvas_group()->hide ();
717                 } else {
718                         rv->get_canvas_group()->show ();
719                 }
720
721                 /* Update the DraggingView */
722                 i->time_axis_view += delta_time_axis_view;
723                 i->layer += this_delta_layer;
724
725                 if (_brushing) {
726                         _editor->mouse_brush_insert_region (rv, pending_region_position);
727                 } else {
728                         double x = 0;
729                         double y = 0;
730
731                         /* Get the y coordinate of the top of the track that this region is now on */
732                         tv->canvas_display()->i2w (x, y);
733                         y += _editor->get_trackview_group_vertical_offset();
734                         
735                         /* And adjust for the layer that it should be on */
736                         StreamView* cv = tv->view ();
737                         switch (cv->layer_display ()) {
738                         case Overlaid:
739                                 break;
740                         case Stacked:
741                                 y += (cv->layers() - i->layer - 1) * cv->child_height ();
742                                 break;
743                         case Expanded:
744                                 y += (cv->layers() - i->layer - 0.5) * 2 * cv->child_height ();
745                                 break;
746                         }
747
748                         /* Now move the region view */
749                         rv->move (x_delta, y - rv->get_canvas_group()->property_y());
750                 }
751
752         } /* foreach region */
753
754         _total_x_delta += x_delta;
755
756         if (first_move) {
757                 _editor->cursor_group->raise_to_top();
758         }
759
760         if (x_delta != 0 && !_brushing) {
761                 show_verbose_cursor_time (_last_frame_position);
762         }
763
764         _last_pointer_time_axis_view += delta_time_axis_view;
765         _last_pointer_layer += delta_layer;
766 }
767
768 void
769 RegionMoveDrag::motion (GdkEvent* event, bool first_move)
770 {
771         if (_copy && first_move) {
772
773                 /* duplicate the regionview(s) and region(s) */
774
775                 list<DraggingView> new_regionviews;
776
777                 for (list<DraggingView>::const_iterator i = _views.begin(); i != _views.end(); ++i) {
778
779                         RegionView* rv = i->view;
780                         AudioRegionView* arv = dynamic_cast<AudioRegionView*>(rv);
781                         MidiRegionView* mrv = dynamic_cast<MidiRegionView*>(rv);
782
783                         const boost::shared_ptr<const Region> original = rv->region();
784                         boost::shared_ptr<Region> region_copy = RegionFactory::create (original, true);
785                         region_copy->set_position (original->position());
786
787                         RegionView* nrv;
788                         if (arv) {
789                                 boost::shared_ptr<AudioRegion> audioregion_copy
790                                 = boost::dynamic_pointer_cast<AudioRegion>(region_copy);
791
792                                 nrv = new AudioRegionView (*arv, audioregion_copy);
793                         } else if (mrv) {
794                                 boost::shared_ptr<MidiRegion> midiregion_copy
795                                         = boost::dynamic_pointer_cast<MidiRegion>(region_copy);
796                                 nrv = new MidiRegionView (*mrv, midiregion_copy);
797                         } else {
798                                 continue;
799                         }
800
801                         nrv->get_canvas_group()->show ();
802                         new_regionviews.push_back (DraggingView (nrv, this));
803
804                         /* swap _primary to the copy */
805
806                         if (rv == _primary) {
807                                 _primary = nrv;
808                         }
809
810                         /* ..and deselect the one we copied */
811
812                         rv->set_selected (false);
813                 }
814
815                 if (!new_regionviews.empty()) {
816
817                         /* reflect the fact that we are dragging the copies */
818
819                         _views = new_regionviews;
820
821                         swap_grab (new_regionviews.front().view->get_canvas_group (), 0, event ? event->motion.time : 0);
822
823                         /*
824                           sync the canvas to what we think is its current state
825                           without it, the canvas seems to
826                           "forget" to update properly after the upcoming reparent()
827                           ..only if the mouse is in rapid motion at the time of the grab.
828                           something to do with regionview creation taking so long?
829                         */
830                         _editor->update_canvas_now();
831                 }
832         }
833
834         RegionMotionDrag::motion (event, first_move);
835 }
836
837 void
838 RegionMotionDrag::finished (GdkEvent *, bool)
839 {
840         for (vector<TimeAxisView*>::iterator i = _time_axis_views.begin(); i != _time_axis_views.end(); ++i) {
841                 if (!(*i)->view()) {
842                         continue;
843                 }
844
845                 if ((*i)->view()->layer_display() == Expanded) {
846                         (*i)->view()->set_layer_display (Stacked);
847                 }
848         }
849 }
850
851 void
852 RegionMoveDrag::finished (GdkEvent* ev, bool movement_occurred)
853 {
854         RegionMotionDrag::finished (ev, movement_occurred);
855         
856         if (!movement_occurred) {
857                 /* just a click */
858                 return;
859         }
860
861         /* reverse this here so that we have the correct logic to finalize
862            the drag.
863         */
864
865         if (Config->get_edit_mode() == Lock) {
866                 _x_constrained = !_x_constrained;
867         }
868
869         assert (!_views.empty ());
870
871         /* We might have hidden region views so that they weren't visible during the drag
872            (when they have been reparented).  Now everything can be shown again, as region
873            views are back in their track parent groups.
874         */
875         for (list<DraggingView>::iterator i = _views.begin(); i != _views.end(); ++i) {
876                 i->view->get_canvas_group()->show ();
877         }
878         
879         bool const changed_position = (_last_frame_position != _primary->region()->position());
880         bool const changed_tracks = (_time_axis_views[_views.front().time_axis_view] != &_views.front().view->get_time_axis_view());
881         framecnt_t const drag_delta = _primary->region()->position() - _last_frame_position;
882         
883         _editor->update_canvas_now ();
884
885         if (_copy) {
886
887                 finished_copy (
888                         changed_position,
889                         changed_tracks,
890                         drag_delta
891                         );
892
893         } else {
894
895                 finished_no_copy (
896                         changed_position,
897                         changed_tracks,
898                         drag_delta
899                         );
900
901         }
902
903         _editor->maybe_locate_with_edit_preroll (_editor->get_selection().regions.start());
904 }
905
906 void
907 RegionMoveDrag::finished_copy (bool const changed_position, bool const /*changed_tracks*/, framecnt_t const drag_delta)
908 {
909         RegionSelection new_views;
910         PlaylistSet modified_playlists;
911         list<RegionView*> views_to_delete;
912
913         if (_brushing) {
914                 /* all changes were made during motion event handlers */
915
916                 for (list<DraggingView>::iterator i = _views.begin(); i != _views.end(); ++i) {
917                         delete i->view;
918                 }
919
920                 _editor->commit_reversible_command ();
921                 return;
922         }
923
924         if (_x_constrained) {
925                 _editor->begin_reversible_command (Operations::fixed_time_region_copy);
926         } else {
927                 _editor->begin_reversible_command (Operations::region_copy);
928         }
929
930         /* insert the regions into their new playlists */
931         for (list<DraggingView>::const_iterator i = _views.begin(); i != _views.end(); ++i) {
932
933                 if (i->view->region()->locked() || i->view->region()->video_locked()) {
934                         continue;
935                 }
936
937                 framepos_t where;
938
939                 if (changed_position && !_x_constrained) {
940                         where = i->view->region()->position() - drag_delta;
941                 } else {
942                         where = i->view->region()->position();
943                 }
944
945                 RegionView* new_view = insert_region_into_playlist (
946                         i->view->region(), dynamic_cast<RouteTimeAxisView*> (_time_axis_views[i->time_axis_view]), i->layer, where, modified_playlists
947                         );
948
949                 if (new_view == 0) {
950                         continue;
951                 }
952
953                 new_views.push_back (new_view);
954
955                 /* we don't need the copied RegionView any more */
956                 views_to_delete.push_back (i->view);
957         }
958
959         /* Delete views that are no longer needed; we can't do this directly in the iteration over _views
960            because when views are deleted they are automagically removed from _views, which messes
961            up the iteration.
962         */
963         for (list<RegionView*>::iterator i = views_to_delete.begin(); i != views_to_delete.end(); ++i) {
964                 delete *i;
965         }
966
967         /* If we've created new regions either by copying or moving
968            to a new track, we want to replace the old selection with the new ones
969         */
970
971         if (new_views.size() > 0) {
972                 _editor->selection->set (new_views);
973         }
974
975         /* write commands for the accumulated diffs for all our modified playlists */
976         add_stateful_diff_commands_for_playlists (modified_playlists);
977
978         _editor->commit_reversible_command ();
979 }
980
981 void
982 RegionMoveDrag::finished_no_copy (
983         bool const changed_position,
984         bool const changed_tracks,
985         framecnt_t const drag_delta
986         )
987 {
988         RegionSelection new_views;
989         PlaylistSet modified_playlists;
990         PlaylistSet frozen_playlists;
991         set<RouteTimeAxisView*> views_to_update;
992
993         if (_brushing) {
994                 /* all changes were made during motion event handlers */
995                 _editor->commit_reversible_command ();
996                 return;
997         }
998
999         if (_x_constrained) {
1000                 _editor->begin_reversible_command (_("fixed time region drag"));
1001         } else {
1002                 _editor->begin_reversible_command (Operations::region_drag);
1003         }
1004
1005         for (list<DraggingView>::const_iterator i = _views.begin(); i != _views.end(); ) {
1006
1007                 RegionView* rv = i->view;
1008
1009                 RouteTimeAxisView* const dest_rtv = dynamic_cast<RouteTimeAxisView*> (_time_axis_views[i->time_axis_view]);
1010                 double const dest_layer = i->layer;
1011
1012                 if (rv->region()->locked() || rv->region()->video_locked()) {
1013                         ++i;
1014                         continue;
1015                 }
1016
1017                 views_to_update.insert (dest_rtv);
1018
1019                 framepos_t where;
1020
1021                 if (changed_position && !_x_constrained) {
1022                         where = rv->region()->position() - drag_delta;
1023                 } else {
1024                         where = rv->region()->position();
1025                 }
1026
1027                 if (changed_tracks) {
1028
1029                         /* insert into new playlist */
1030
1031                         RegionView* new_view = insert_region_into_playlist (
1032                                 RegionFactory::create (rv->region (), true), dest_rtv, dest_layer, where, modified_playlists
1033                                 );
1034
1035                         if (new_view == 0) {
1036                                 ++i;
1037                                 continue;
1038                         }
1039
1040                         new_views.push_back (new_view);
1041
1042                         /* remove from old playlist */
1043
1044                         /* the region that used to be in the old playlist is not
1045                            moved to the new one - we use a copy of it. as a result,
1046                            any existing editor for the region should no longer be
1047                            visible.
1048                         */
1049                         rv->hide_region_editor();
1050                         rv->fake_set_opaque (false);
1051
1052                         remove_region_from_playlist (rv->region(), i->initial_playlist, modified_playlists);
1053
1054                 } else {
1055
1056                         rv->region()->clear_changes ();
1057
1058                         /*
1059                            motion on the same track. plonk the previously reparented region
1060                            back to its original canvas group (its streamview).
1061                            No need to do anything for copies as they are fake regions which will be deleted.
1062                         */
1063
1064                         rv->get_canvas_group()->reparent (*dest_rtv->view()->canvas_item());
1065                         rv->get_canvas_group()->property_y() = i->initial_y;
1066                         rv->drag_end ();
1067
1068                         /* just change the model */
1069
1070                         boost::shared_ptr<Playlist> playlist = dest_rtv->playlist();
1071
1072                         if (dest_rtv->view()->layer_display() == Stacked || dest_rtv->view()->layer_display() == Expanded) {
1073                                 playlist->set_layer (rv->region(), dest_layer);
1074                         }
1075
1076                         /* freeze playlist to avoid lots of relayering in the case of a multi-region drag */
1077
1078                         pair<PlaylistSet::iterator, bool> r = frozen_playlists.insert (playlist);
1079
1080                         if (r.second) {
1081                                 playlist->freeze ();
1082                         }
1083
1084                         /* this movement may result in a crossfade being modified, so we need to get undo
1085                            data from the playlist as well as the region.
1086                         */
1087
1088                         r = modified_playlists.insert (playlist);
1089                         if (r.second) {
1090                                 playlist->clear_changes ();
1091                         }
1092
1093                         rv->region()->set_position (where);
1094
1095                         _editor->session()->add_command (new StatefulDiffCommand (rv->region()));
1096                 }
1097
1098                 if (changed_tracks) {
1099
1100                         /* OK, this is where it gets tricky. If the playlist was being used by >1 tracks, and the region
1101                            was selected in all of them, then removing it from a playlist will have removed all
1102                            trace of it from _views (i.e. there were N regions selected, we removed 1,
1103                            but since its the same playlist for N tracks, all N tracks updated themselves, removed the
1104                            corresponding regionview, and _views is now empty).
1105
1106                            This could have invalidated any and all iterators into _views.
1107
1108                            The heuristic we use here is: if the region selection is empty, break out of the loop
1109                            here. if the region selection is not empty, then restart the loop because we know that
1110                            we must have removed at least the region(view) we've just been working on as well as any
1111                            that we processed on previous iterations.
1112
1113                            EXCEPT .... if we are doing a copy drag, then _views hasn't been modified and
1114                            we can just iterate.
1115                         */
1116
1117
1118                         if (_views.empty()) {
1119                                 break;
1120                         } else {
1121                                 i = _views.begin();
1122                         }
1123
1124                 } else {
1125                         ++i;
1126                 }
1127         }
1128
1129         /* If we've created new regions either by copying or moving
1130            to a new track, we want to replace the old selection with the new ones
1131         */
1132
1133         if (new_views.size() > 0) {
1134                 _editor->selection->set (new_views);
1135         }
1136
1137         for (set<boost::shared_ptr<Playlist> >::iterator p = frozen_playlists.begin(); p != frozen_playlists.end(); ++p) {
1138                 (*p)->thaw();
1139         }
1140
1141         /* write commands for the accumulated diffs for all our modified playlists */
1142         add_stateful_diff_commands_for_playlists (modified_playlists);
1143
1144         _editor->commit_reversible_command ();
1145
1146         /* We have futzed with the layering of canvas items on our streamviews.
1147            If any region changed layer, this will have resulted in the stream
1148            views being asked to set up their region views, and all will be well.
1149            If not, we might now have badly-ordered region views.  Ask the StreamViews
1150            involved to sort themselves out, just in case.
1151         */
1152
1153         for (set<RouteTimeAxisView*>::iterator i = views_to_update.begin(); i != views_to_update.end(); ++i) {
1154                 (*i)->view()->playlist_layered ((*i)->track ());
1155         }
1156 }
1157
1158 /** Remove a region from a playlist, clearing the diff history of the playlist first if necessary.
1159  *  @param region Region to remove.
1160  *  @param playlist playlist To remove from.
1161  *  @param modified_playlists The playlist will be added to this if it is not there already; used to ensure
1162  *  that clear_changes () is only called once per playlist.
1163  */
1164 void
1165 RegionMoveDrag::remove_region_from_playlist (
1166         boost::shared_ptr<Region> region,
1167         boost::shared_ptr<Playlist> playlist,
1168         PlaylistSet& modified_playlists
1169         )
1170 {
1171         pair<set<boost::shared_ptr<Playlist> >::iterator, bool> r = modified_playlists.insert (playlist);
1172
1173         if (r.second) {
1174                 playlist->clear_changes ();
1175         }
1176
1177         playlist->remove_region (region);
1178 }
1179
1180
1181 /** Insert a region into a playlist, handling the recovery of the resulting new RegionView, and
1182  *  clearing the playlist's diff history first if necessary.
1183  *  @param region Region to insert.
1184  *  @param dest_rtv Destination RouteTimeAxisView.
1185  *  @param dest_layer Destination layer.
1186  *  @param where Destination position.
1187  *  @param modified_playlists The playlist will be added to this if it is not there already; used to ensure
1188  *  that clear_changes () is only called once per playlist.
1189  *  @return New RegionView, or 0 if no insert was performed.
1190  */
1191 RegionView *
1192 RegionMoveDrag::insert_region_into_playlist (
1193         boost::shared_ptr<Region> region,
1194         RouteTimeAxisView* dest_rtv,
1195         layer_t dest_layer,
1196         framecnt_t where,
1197         PlaylistSet& modified_playlists
1198         )
1199 {
1200         boost::shared_ptr<Playlist> dest_playlist = dest_rtv->playlist ();
1201         if (!dest_playlist) {
1202                 return 0;
1203         }
1204
1205         /* arrange to collect the new region view that will be created as a result of our playlist insertion */
1206         _new_region_view = 0;
1207         sigc::connection c = dest_rtv->view()->RegionViewAdded.connect (sigc::mem_fun (*this, &RegionMoveDrag::collect_new_region_view));
1208
1209         /* clear history for the playlist we are about to insert to, provided we haven't already done so */
1210         pair<PlaylistSet::iterator, bool> r = modified_playlists.insert (dest_playlist);
1211         if (r.second) {
1212                 dest_playlist->clear_changes ();
1213         }
1214
1215         dest_playlist->add_region (region, where);
1216
1217         if (dest_rtv->view()->layer_display() == Stacked || dest_rtv->view()->layer_display() == Expanded) {
1218                 dest_playlist->set_layer (region, dest_layer);
1219         }
1220
1221         c.disconnect ();
1222
1223         assert (_new_region_view);
1224
1225         return _new_region_view;
1226 }
1227
1228 void
1229 RegionMoveDrag::collect_new_region_view (RegionView* rv)
1230 {
1231         _new_region_view = rv;
1232 }
1233
1234 void
1235 RegionMoveDrag::add_stateful_diff_commands_for_playlists (PlaylistSet const & playlists)
1236 {
1237         for (PlaylistSet::const_iterator i = playlists.begin(); i != playlists.end(); ++i) {
1238                 StatefulDiffCommand* c = new StatefulDiffCommand (*i);
1239                 if (!c->empty()) {
1240                         _editor->session()->add_command (c);
1241                 } else {
1242                         delete c;
1243                 }
1244         }
1245 }
1246
1247
1248 void
1249 RegionMoveDrag::aborted (bool movement_occurred)
1250 {
1251         if (_copy) {
1252
1253                 for (list<DraggingView>::const_iterator i = _views.begin(); i != _views.end(); ++i) {
1254                         delete i->view;
1255                 }
1256
1257                 _views.clear ();
1258
1259         } else {
1260                 RegionMotionDrag::aborted (movement_occurred);
1261         }
1262 }
1263
1264 void
1265 RegionMotionDrag::aborted (bool)
1266 {
1267         for (vector<TimeAxisView*>::iterator i = _time_axis_views.begin(); i != _time_axis_views.end(); ++i) {
1268                 if ((*i)->view()->layer_display() == Expanded) {
1269                         (*i)->view()->set_layer_display (Stacked);
1270                 }
1271         }
1272         
1273         for (list<DraggingView>::const_iterator i = _views.begin(); i != _views.end(); ++i) {
1274                 RegionView* rv = i->view;
1275                 TimeAxisView* tv = &(rv->get_time_axis_view ());
1276                 RouteTimeAxisView* rtv = dynamic_cast<RouteTimeAxisView*> (tv);
1277                 assert (rtv);
1278                 rv->get_canvas_group()->reparent (*rtv->view()->canvas_item());
1279                 rv->get_canvas_group()->property_y() = 0;
1280                 rv->drag_end ();
1281                 rv->fake_set_opaque (false);
1282                 rv->move (-_total_x_delta, 0);
1283                 rv->set_height (rtv->view()->child_height ());
1284         }
1285
1286         _editor->update_canvas_now ();
1287 }
1288
1289 /** @param b true to brush, otherwise false.
1290  *  @param c true to make copies of the regions being moved, otherwise false.
1291  */
1292 RegionMoveDrag::RegionMoveDrag (Editor* e, ArdourCanvas::Item* i, RegionView* p, list<RegionView*> const & v, bool b, bool c)
1293         : RegionMotionDrag (e, i, p, v, b),
1294           _copy (c)
1295 {
1296         DEBUG_TRACE (DEBUG::Drags, "New RegionMoveDrag\n");
1297
1298         double speed = 1;
1299         RouteTimeAxisView* rtv = dynamic_cast<RouteTimeAxisView*> (&_primary->get_time_axis_view ());
1300         if (rtv && rtv->is_track()) {
1301                 speed = rtv->track()->speed ();
1302         }
1303
1304         _last_frame_position = static_cast<framepos_t> (_primary->region()->position() / speed);
1305 }
1306
1307 void
1308 RegionMoveDrag::setup_pointer_frame_offset ()
1309 {
1310         _pointer_frame_offset = raw_grab_frame() - _last_frame_position;
1311 }
1312
1313 RegionInsertDrag::RegionInsertDrag (Editor* e, boost::shared_ptr<Region> r, RouteTimeAxisView* v, framepos_t pos)
1314         : RegionMotionDrag (e, 0, 0, list<RegionView*> (), false)
1315 {
1316         DEBUG_TRACE (DEBUG::Drags, "New RegionInsertDrag\n");
1317
1318         assert ((boost::dynamic_pointer_cast<AudioRegion> (r) && dynamic_cast<AudioTimeAxisView*> (v)) ||
1319                 (boost::dynamic_pointer_cast<MidiRegion> (r) && dynamic_cast<MidiTimeAxisView*> (v)));
1320
1321         _primary = v->view()->create_region_view (r, false, false);
1322
1323         _primary->get_canvas_group()->show ();
1324         _primary->set_position (pos, 0);
1325         _views.push_back (DraggingView (_primary, this));
1326
1327         _last_frame_position = pos;
1328
1329         _item = _primary->get_canvas_group ();
1330 }
1331
1332 void
1333 RegionInsertDrag::finished (GdkEvent *, bool)
1334 {
1335         _editor->update_canvas_now ();
1336
1337         RouteTimeAxisView* dest_rtv = dynamic_cast<RouteTimeAxisView*> (_time_axis_views[_views.front().time_axis_view]);
1338
1339         _primary->get_canvas_group()->reparent (*dest_rtv->view()->canvas_item());
1340         _primary->get_canvas_group()->property_y() = 0;
1341
1342         boost::shared_ptr<Playlist> playlist = dest_rtv->playlist();
1343
1344         _editor->begin_reversible_command (Operations::insert_region);
1345         playlist->clear_changes ();
1346         playlist->add_region (_primary->region (), _last_frame_position);
1347         _editor->session()->add_command (new StatefulDiffCommand (playlist));
1348         _editor->commit_reversible_command ();
1349
1350         delete _primary;
1351         _primary = 0;
1352         _views.clear ();
1353 }
1354
1355 void
1356 RegionInsertDrag::aborted (bool)
1357 {
1358         delete _primary;
1359         _primary = 0;
1360         _views.clear ();
1361 }
1362
1363 RegionSpliceDrag::RegionSpliceDrag (Editor* e, ArdourCanvas::Item* i, RegionView* p, list<RegionView*> const & v)
1364         : RegionMoveDrag (e, i, p, v, false, false)
1365 {
1366         DEBUG_TRACE (DEBUG::Drags, "New RegionSpliceDrag\n");
1367 }
1368
1369 struct RegionSelectionByPosition {
1370     bool operator() (RegionView*a, RegionView* b) {
1371             return a->region()->position () < b->region()->position();
1372     }
1373 };
1374
1375 void
1376 RegionSpliceDrag::motion (GdkEvent* event, bool)
1377 {
1378         /* Which trackview is this ? */
1379
1380         pair<TimeAxisView*, double> const tvp = _editor->trackview_by_y_position (_drags->current_pointer_y ());
1381         RouteTimeAxisView* tv = dynamic_cast<RouteTimeAxisView*> (tvp.first);
1382
1383         /* The region motion is only processed if the pointer is over
1384            an audio track.
1385         */
1386
1387         if (!tv || !tv->is_track()) {
1388                 /* To make sure we hide the verbose canvas cursor when the mouse is
1389                    not held over and audiotrack.
1390                 */
1391                 _editor->verbose_cursor()->hide ();
1392                 return;
1393         }
1394
1395         int dir;
1396
1397         if ((_drags->current_pointer_x() - last_pointer_x()) > 0) {
1398                 dir = 1;
1399         } else {
1400                 dir = -1;
1401         }
1402
1403         RegionSelection copy (_editor->selection->regions);
1404
1405         RegionSelectionByPosition cmp;
1406         copy.sort (cmp);
1407
1408         framepos_t const pf = adjusted_current_frame (event);
1409
1410         for (RegionSelection::iterator i = copy.begin(); i != copy.end(); ++i) {
1411
1412                 RouteTimeAxisView* atv = dynamic_cast<RouteTimeAxisView*> (&(*i)->get_time_axis_view());
1413
1414                 if (!atv) {
1415                         continue;
1416                 }
1417
1418                 boost::shared_ptr<Playlist> playlist;
1419
1420                 if ((playlist = atv->playlist()) == 0) {
1421                         continue;
1422                 }
1423
1424                 if (!playlist->region_is_shuffle_constrained ((*i)->region())) {
1425                         continue;
1426                 }
1427
1428                 if (dir > 0) {
1429                         if (pf < (*i)->region()->last_frame() + 1) {
1430                                 continue;
1431                         }
1432                 } else {
1433                         if (pf > (*i)->region()->first_frame()) {
1434                                 continue;
1435                         }
1436                 }
1437
1438
1439                 playlist->shuffle ((*i)->region(), dir);
1440         }
1441 }
1442
1443 void
1444 RegionSpliceDrag::finished (GdkEvent* event, bool movement_occurred)
1445 {
1446         RegionMoveDrag::finished (event, movement_occurred);
1447 }
1448
1449 void
1450 RegionSpliceDrag::aborted (bool)
1451 {
1452         /* XXX: TODO */
1453 }
1454
1455 RegionCreateDrag::RegionCreateDrag (Editor* e, ArdourCanvas::Item* i, TimeAxisView* v)
1456         : Drag (e, i),
1457           _view (dynamic_cast<MidiTimeAxisView*> (v))
1458 {
1459         DEBUG_TRACE (DEBUG::Drags, "New RegionCreateDrag\n");
1460
1461         assert (_view);
1462 }
1463
1464 void
1465 RegionCreateDrag::motion (GdkEvent* event, bool first_move)
1466 {
1467         if (first_move) {
1468                 _region = add_midi_region (_view);
1469                 _view->playlist()->freeze ();
1470         } else {
1471                 if (_region) {
1472                         framepos_t const f = adjusted_current_frame (event);
1473                         if (f < grab_frame()) {
1474                                 _region->set_position (f);
1475                         }
1476
1477                         /* Don't use a zero-length region, and subtract 1 frame from the snapped length
1478                            so that if this region is duplicated, its duplicate starts on
1479                            a snap point rather than 1 frame after a snap point.  Otherwise things get
1480                            a bit confusing as if a region starts 1 frame after a snap point, one cannot
1481                            place snapped notes at the start of the region.
1482                         */
1483
1484                         framecnt_t const len = (framecnt_t) fabs (f - grab_frame () - 1);
1485                         _region->set_length (len < 1 ? 1 : len);
1486                 }
1487         }
1488 }
1489
1490 void
1491 RegionCreateDrag::finished (GdkEvent*, bool movement_occurred)
1492 {
1493         if (!movement_occurred) {
1494                 add_midi_region (_view);
1495         } else {
1496                 _view->playlist()->thaw ();
1497         }
1498 }
1499
1500 void
1501 RegionCreateDrag::aborted (bool)
1502 {
1503         if (_region) {
1504                 _view->playlist()->thaw ();
1505         }
1506
1507         /* XXX */
1508 }
1509
1510 NoteResizeDrag::NoteResizeDrag (Editor* e, ArdourCanvas::Item* i)
1511         : Drag (e, i)
1512         , region (0)
1513 {
1514         DEBUG_TRACE (DEBUG::Drags, "New NoteResizeDrag\n");
1515 }
1516
1517 void
1518 NoteResizeDrag::start_grab (GdkEvent* event, Gdk::Cursor* /*ignored*/)
1519 {
1520         Gdk::Cursor* cursor;
1521         ArdourCanvas::CanvasNoteEvent* cnote = dynamic_cast<ArdourCanvas::CanvasNoteEvent*>(_item);
1522         float x_fraction = cnote->mouse_x_fraction ();
1523
1524         if (x_fraction > 0.0 && x_fraction < 0.25) {
1525                 cursor = _editor->cursors()->left_side_trim;
1526         } else  {
1527                 cursor = _editor->cursors()->right_side_trim;
1528         }
1529
1530         Drag::start_grab (event, cursor);
1531
1532         region = &cnote->region_view();
1533
1534         double const region_start = region->get_position_pixels();
1535         double const middle_point = region_start + cnote->x1() + (cnote->x2() - cnote->x1()) / 2.0L;
1536
1537         if (grab_x() <= middle_point) {
1538                 cursor = _editor->cursors()->left_side_trim;
1539                 at_front = true;
1540         } else {
1541                 cursor = _editor->cursors()->right_side_trim;
1542                 at_front = false;
1543         }
1544
1545         _item->grab(GDK_POINTER_MOTION_MASK | GDK_BUTTON_RELEASE_MASK, *cursor, event->motion.time);
1546
1547         if (event->motion.state & Keyboard::PrimaryModifier) {
1548                 relative = false;
1549         } else {
1550                 relative = true;
1551         }
1552
1553         MidiRegionSelection& ms (_editor->get_selection().midi_regions);
1554
1555         if (ms.size() > 1) {
1556                 /* has to be relative, may make no sense otherwise */
1557                 relative = true;
1558         }
1559
1560         /* select this note; if it is already selected, preserve the existing selection,
1561            otherwise make this note the only one selected.
1562         */
1563         region->note_selected (cnote, cnote->selected ());
1564
1565         for (MidiRegionSelection::iterator r = ms.begin(); r != ms.end(); ) {
1566                 MidiRegionSelection::iterator next;
1567                 next = r;
1568                 ++next;
1569                 (*r)->begin_resizing (at_front);
1570                 r = next;
1571         }
1572 }
1573
1574 void
1575 NoteResizeDrag::motion (GdkEvent* /*event*/, bool /*first_move*/)
1576 {
1577         MidiRegionSelection& ms (_editor->get_selection().midi_regions);
1578         for (MidiRegionSelection::iterator r = ms.begin(); r != ms.end(); ++r) {
1579                 (*r)->update_resizing (dynamic_cast<ArdourCanvas::CanvasNoteEvent*>(_item), at_front, _drags->current_pointer_x() - grab_x(), relative);
1580         }
1581 }
1582
1583 void
1584 NoteResizeDrag::finished (GdkEvent*, bool /*movement_occurred*/)
1585 {
1586         MidiRegionSelection& ms (_editor->get_selection().midi_regions);
1587         for (MidiRegionSelection::iterator r = ms.begin(); r != ms.end(); ++r) {
1588                 (*r)->commit_resizing (dynamic_cast<ArdourCanvas::CanvasNoteEvent*>(_item), at_front, _drags->current_pointer_x() - grab_x(), relative);
1589         }
1590 }
1591
1592 void
1593 NoteResizeDrag::aborted (bool)
1594 {
1595         MidiRegionSelection& ms (_editor->get_selection().midi_regions);
1596         for (MidiRegionSelection::iterator r = ms.begin(); r != ms.end(); ++r) {
1597                 (*r)->abort_resizing ();
1598         }
1599 }
1600
1601 AVDraggingView::AVDraggingView (RegionView* v)
1602         : view (v)
1603 {
1604         initial_position = v->region()->position ();
1605 }
1606
1607 VideoTimeLineDrag::VideoTimeLineDrag (Editor* e, ArdourCanvas::Item* i)
1608         : Drag (e, i)
1609 {
1610         DEBUG_TRACE (DEBUG::Drags, "New VideoTimeLineDrag\n");
1611
1612         RegionSelection rs;
1613         TrackViewList empty;
1614         empty.clear();
1615         _editor->get_regions_after(rs, (framepos_t) 0, empty);
1616         std::list<RegionView*> views = rs.by_layer();
1617
1618         for (list<RegionView*>::iterator i = views.begin(); i != views.end(); ++i) {
1619                 RegionView* rv = (*i);
1620                 if (!rv->region()->video_locked()) {
1621                         continue;
1622                 }
1623                 _views.push_back (AVDraggingView (rv));
1624         }
1625 }
1626
1627 void
1628 VideoTimeLineDrag::start_grab (GdkEvent* event, Gdk::Cursor*)
1629 {
1630         Drag::start_grab (event);
1631         if (_editor->session() == 0) {
1632                 return;
1633         }
1634
1635         _startdrag_video_offset=ARDOUR_UI::instance()->video_timeline->get_offset();
1636         _max_backwards_drag = (
1637                           ARDOUR_UI::instance()->video_timeline->get_duration()
1638                         + ARDOUR_UI::instance()->video_timeline->get_offset()
1639                         - ceil(ARDOUR_UI::instance()->video_timeline->get_apv())
1640                         );
1641
1642         for (list<AVDraggingView>::iterator i = _views.begin(); i != _views.end(); ++i) {
1643                 if (i->initial_position < _max_backwards_drag || _max_backwards_drag < 0) {
1644                         _max_backwards_drag = ARDOUR_UI::instance()->video_timeline->quantify_frames_to_apv (i->initial_position);
1645                 }
1646         }
1647         DEBUG_TRACE (DEBUG::Drags, string_compose("VideoTimeLineDrag: max backwards-drag: %1\n", _max_backwards_drag));
1648
1649         char buf[128];
1650         Timecode::Time timecode;
1651         _editor->session()->sample_to_timecode(abs(_startdrag_video_offset), timecode, true /* use_offset */, false /* use_subframes */ );
1652         snprintf (buf, sizeof (buf), "Video Start:\n%c%02" PRId32 ":%02" PRId32 ":%02" PRId32 ":%02" PRId32, (_startdrag_video_offset<0?'-':' '), timecode.hours, timecode.minutes, timecode.seconds, timecode.frames);
1653         _editor->verbose_cursor()->set(buf, event->button.x + 10, event->button.y + 10);
1654         _editor->verbose_cursor()->show ();
1655 }
1656
1657 void
1658 VideoTimeLineDrag::motion (GdkEvent* event, bool first_move)
1659 {
1660         if (_editor->session() == 0) {
1661                 return;
1662         }
1663         if (ARDOUR_UI::instance()->video_timeline->is_offset_locked()) {
1664                 return;
1665         }
1666
1667         framecnt_t dt = adjusted_current_frame (event) - raw_grab_frame() + _pointer_frame_offset;
1668         dt = ARDOUR_UI::instance()->video_timeline->quantify_frames_to_apv(_startdrag_video_offset+dt) - _startdrag_video_offset;
1669
1670         if (_max_backwards_drag >= 0 && dt <= - _max_backwards_drag) {
1671                 dt = - _max_backwards_drag;
1672         }
1673
1674         ARDOUR_UI::instance()->video_timeline->set_offset(_startdrag_video_offset+dt);
1675         ARDOUR_UI::instance()->flush_videotimeline_cache(true);
1676
1677         for (list<AVDraggingView>::iterator i = _views.begin(); i != _views.end(); ++i) {
1678                 RegionView* rv = i->view;
1679                 DEBUG_TRACE (DEBUG::Drags, string_compose("SHIFT REGION at %1 by %2\n", i->initial_position, dt));
1680                 if (first_move) {
1681                         rv->drag_start ();
1682                         _editor->update_canvas_now ();
1683                         rv->fake_set_opaque (true);
1684                         rv->region()->clear_changes ();
1685                         rv->region()->suspend_property_changes();
1686                 }
1687                 rv->region()->set_position(i->initial_position + dt);
1688                 rv->region_changed(ARDOUR::Properties::position);
1689         }
1690
1691         const framepos_t offset = ARDOUR_UI::instance()->video_timeline->get_offset();
1692         Timecode::Time timecode;
1693         Timecode::Time timediff;
1694         char buf[128];
1695         _editor->session()->sample_to_timecode(abs(offset), timecode, true /* use_offset */, false /* use_subframes */ );
1696         _editor->session()->sample_to_timecode(abs(dt), timediff, false /* use_offset */, false /* use_subframes */ );
1697         snprintf (buf, sizeof (buf),
1698                         "%s\n%c%02" PRId32 ":%02" PRId32 ":%02" PRId32 ":%02" PRId32
1699                         "\n%s\n%c%02" PRId32 ":%02" PRId32 ":%02" PRId32 ":%02" PRId32
1700                         , _("Video Start:"),
1701                                 (offset<0?'-':' '), timecode.hours, timecode.minutes, timecode.seconds, timecode.frames
1702                         , _("Diff:"),
1703                                 (dt<0?'-':' '), timediff.hours, timediff.minutes, timediff.seconds, timediff.frames
1704                                 );
1705         _editor->verbose_cursor()->set(buf, event->button.x + 10, event->button.y + 10);
1706         _editor->verbose_cursor()->show ();
1707 }
1708
1709 void
1710 VideoTimeLineDrag::finished (GdkEvent * /*event*/, bool movement_occurred)
1711 {
1712         if (ARDOUR_UI::instance()->video_timeline->is_offset_locked()) {
1713                 return;
1714         }
1715
1716         if (!movement_occurred || ! _editor->session()) {
1717                 return;
1718         }
1719
1720         ARDOUR_UI::instance()->flush_videotimeline_cache(true);
1721
1722         _editor->begin_reversible_command (_("Move Video"));
1723
1724         XMLNode &before = ARDOUR_UI::instance()->video_timeline->get_state();
1725         ARDOUR_UI::instance()->video_timeline->save_undo();
1726         XMLNode &after = ARDOUR_UI::instance()->video_timeline->get_state();
1727         _editor->session()->add_command(new MementoCommand<VideoTimeLine>(*(ARDOUR_UI::instance()->video_timeline), &before, &after));
1728
1729         for (list<AVDraggingView>::iterator i = _views.begin(); i != _views.end(); ++i) {
1730                 i->view->drag_end();
1731                 i->view->fake_set_opaque (false);
1732                 i->view->region()->resume_property_changes ();
1733
1734                 _editor->session()->add_command (new StatefulDiffCommand (i->view->region()));
1735         }
1736
1737         _editor->session()->maybe_update_session_range(
1738                         std::max(ARDOUR_UI::instance()->video_timeline->get_offset(), (ARDOUR::frameoffset_t) 0),
1739                         std::max(ARDOUR_UI::instance()->video_timeline->get_offset() + ARDOUR_UI::instance()->video_timeline->get_duration(), (ARDOUR::frameoffset_t) 0)
1740                         );
1741
1742
1743         _editor->commit_reversible_command ();
1744         _editor->update_canvas_now ();
1745 }
1746
1747 void
1748 VideoTimeLineDrag::aborted (bool)
1749 {
1750         if (ARDOUR_UI::instance()->video_timeline->is_offset_locked()) {
1751                 return;
1752         }
1753         ARDOUR_UI::instance()->video_timeline->set_offset(_startdrag_video_offset);
1754         ARDOUR_UI::instance()->flush_videotimeline_cache(true);
1755
1756         for (list<AVDraggingView>::iterator i = _views.begin(); i != _views.end(); ++i) {
1757                 i->view->region()->resume_property_changes ();
1758                 i->view->region()->set_position(i->initial_position);
1759         }
1760 }
1761
1762 TrimDrag::TrimDrag (Editor* e, ArdourCanvas::Item* i, RegionView* p, list<RegionView*> const & v, bool preserve_fade_anchor)
1763         : RegionDrag (e, i, p, v)
1764 {
1765         DEBUG_TRACE (DEBUG::Drags, "New TrimDrag\n");
1766         _preserve_fade_anchor = preserve_fade_anchor;
1767 }
1768
1769 void
1770 TrimDrag::start_grab (GdkEvent* event, Gdk::Cursor*)
1771 {
1772         double speed = 1.0;
1773         TimeAxisView* tvp = &_primary->get_time_axis_view ();
1774         RouteTimeAxisView* tv = dynamic_cast<RouteTimeAxisView*>(tvp);
1775
1776         if (tv && tv->is_track()) {
1777                 speed = tv->track()->speed();
1778         }
1779
1780         framepos_t const region_start = (framepos_t) (_primary->region()->position() / speed);
1781         framepos_t const region_end = (framepos_t) (_primary->region()->last_frame() / speed);
1782         framecnt_t const region_length = (framecnt_t) (_primary->region()->length() / speed);
1783
1784         framepos_t const pf = adjusted_current_frame (event);
1785
1786         if (Keyboard::modifier_state_equals (event->button.state, Keyboard::PrimaryModifier)) {
1787                 /* Move the contents of the region around without changing the region bounds */
1788                 _operation = ContentsTrim;
1789                 Drag::start_grab (event, _editor->cursors()->trimmer);
1790         } else {
1791                 /* These will get overridden for a point trim.*/
1792                 if (pf < (region_start + region_length/2)) {
1793                         /* closer to front */
1794                         _operation = StartTrim;
1795                         Drag::start_grab (event, _editor->cursors()->left_side_trim);
1796                 } else {
1797                         /* closer to end */
1798                         _operation = EndTrim;
1799                         Drag::start_grab (event, _editor->cursors()->right_side_trim);
1800                 }
1801         }
1802
1803         switch (_operation) {
1804         case StartTrim:
1805                 show_verbose_cursor_time (region_start);
1806                 for (list<DraggingView>::iterator i = _views.begin(); i != _views.end(); ++i) {
1807                         i->view->trim_front_starting ();
1808                 }
1809                 break;
1810         case EndTrim:
1811                 show_verbose_cursor_time (region_end);
1812                 break;
1813         case ContentsTrim:
1814                 show_verbose_cursor_time (pf);
1815                 break;
1816         }
1817
1818         for (list<DraggingView>::const_iterator i = _views.begin(); i != _views.end(); ++i) {
1819                 i->view->region()->suspend_property_changes ();
1820         }
1821 }
1822
1823 void
1824 TrimDrag::motion (GdkEvent* event, bool first_move)
1825 {
1826         RegionView* rv = _primary;
1827
1828         double speed = 1.0;
1829         TimeAxisView* tvp = &_primary->get_time_axis_view ();
1830         RouteTimeAxisView* tv = dynamic_cast<RouteTimeAxisView*>(tvp);
1831         pair<set<boost::shared_ptr<Playlist> >::iterator,bool> insert_result;
1832
1833         if (tv && tv->is_track()) {
1834                 speed = tv->track()->speed();
1835         }
1836
1837         framecnt_t const dt = adjusted_current_frame (event) - raw_grab_frame () + _pointer_frame_offset;
1838
1839         if (first_move) {
1840
1841                 string trim_type;
1842
1843                 switch (_operation) {
1844                 case StartTrim:
1845                         trim_type = "Region start trim";
1846                         break;
1847                 case EndTrim:
1848                         trim_type = "Region end trim";
1849                         break;
1850                 case ContentsTrim:
1851                         trim_type = "Region content trim";
1852                         break;
1853                 }
1854
1855                 _editor->begin_reversible_command (trim_type);
1856
1857                 for (list<DraggingView>::const_iterator i = _views.begin(); i != _views.end(); ++i) {
1858                         RegionView* rv = i->view;
1859                         rv->fake_set_opaque (false);
1860                         rv->enable_display (false);
1861                         rv->region()->playlist()->clear_owned_changes ();
1862
1863                         AudioRegionView* const arv = dynamic_cast<AudioRegionView*> (rv);
1864
1865                         if (arv) {
1866                                 arv->temporarily_hide_envelope ();
1867                                 arv->drag_start ();
1868                         }
1869
1870                         boost::shared_ptr<Playlist> pl = rv->region()->playlist();
1871                         insert_result = _editor->motion_frozen_playlists.insert (pl);
1872
1873                         if (insert_result.second) {
1874                                 pl->freeze();
1875                         }
1876                 }
1877         }
1878
1879         bool non_overlap_trim = false;
1880
1881         if (event && Keyboard::modifier_state_equals (event->button.state, Keyboard::TertiaryModifier)) {
1882                 non_overlap_trim = true;
1883         }
1884
1885         switch (_operation) {
1886         case StartTrim:
1887                 for (list<DraggingView>::const_iterator i = _views.begin(); i != _views.end(); ++i) {
1888                         bool changed = i->view->trim_front (i->initial_position + dt, non_overlap_trim);
1889                         if (changed && _preserve_fade_anchor) {
1890                                 AudioRegionView* arv = dynamic_cast<AudioRegionView*> (i->view);
1891                                 if (arv) {
1892                                         double distance;
1893                                         double new_length;
1894                                         framecnt_t len;
1895                                         boost::shared_ptr<AudioRegion> ar (arv->audio_region());
1896                                         distance = _drags->current_pointer_x() - grab_x();
1897                                         len = ar->fade_in()->back()->when;
1898                                         new_length = len - _editor->unit_to_frame (distance);
1899                                         new_length = ar->verify_xfade_bounds (new_length, true  /*START*/ );
1900                                         arv->reset_fade_in_shape_width (ar, new_length);  //the grey shape
1901                                 }
1902                         }
1903                 }
1904                 break;
1905
1906         case EndTrim:
1907                 for (list<DraggingView>::const_iterator i = _views.begin(); i != _views.end(); ++i) {
1908                         bool changed = i->view->trim_end (i->initial_end + dt, non_overlap_trim);
1909                         if (changed && _preserve_fade_anchor) {
1910                                 AudioRegionView* arv = dynamic_cast<AudioRegionView*> (i->view);
1911                                 if (arv) {
1912                                         double distance;
1913                                         double new_length;
1914                                         framecnt_t len;
1915                                         boost::shared_ptr<AudioRegion> ar (arv->audio_region());
1916                                         distance = grab_x() - _drags->current_pointer_x();
1917                                         len = ar->fade_out()->back()->when;
1918                                         new_length = len - _editor->unit_to_frame (distance);
1919                                         new_length = ar->verify_xfade_bounds (new_length, false  /*END*/ );
1920                                         arv->reset_fade_out_shape_width (ar, new_length);  //the grey shape
1921                                 }
1922                         }
1923                 }
1924                 break;
1925
1926         case ContentsTrim:
1927                 {
1928                         bool swap_direction = false;
1929
1930                         if (event && Keyboard::modifier_state_equals (event->button.state, Keyboard::PrimaryModifier)) {
1931                                 swap_direction = true;
1932                         }
1933
1934                         framecnt_t frame_delta = 0;
1935
1936                         bool left_direction = false;
1937                         if (last_pointer_frame() > adjusted_current_frame(event)) {
1938                                 left_direction = true;
1939                         }
1940
1941                         if (left_direction) {
1942                                 frame_delta = (last_pointer_frame() - adjusted_current_frame(event));
1943                         } else {
1944                                 frame_delta = (adjusted_current_frame(event) - last_pointer_frame());
1945                         }
1946
1947                         for (list<DraggingView>::const_iterator i = _views.begin(); i != _views.end(); ++i) {
1948                                 i->view->trim_contents (frame_delta, left_direction, swap_direction);
1949                         }
1950                 }
1951                 break;
1952         }
1953
1954         switch (_operation) {
1955         case StartTrim:
1956                 show_verbose_cursor_time ((framepos_t) (rv->region()->position() / speed));
1957                 break;
1958         case EndTrim:
1959                 show_verbose_cursor_time ((framepos_t) (rv->region()->last_frame() / speed));
1960                 break;
1961         case ContentsTrim:
1962                 show_verbose_cursor_time (adjusted_current_frame (event));
1963                 break;
1964         }
1965 }
1966
1967
1968 void
1969 TrimDrag::finished (GdkEvent* event, bool movement_occurred)
1970 {
1971         if (movement_occurred) {
1972                 motion (event, false);
1973
1974                 if (_operation == StartTrim) {
1975                         for (list<DraggingView>::const_iterator i = _views.begin(); i != _views.end(); ++i) {
1976                                 {
1977                                         /* This must happen before the region's StatefulDiffCommand is created, as it may
1978                                            `correct' (ahem) the region's _start from being negative to being zero.  It
1979                                            needs to be zero in the undo record.
1980                                         */
1981                                         i->view->trim_front_ending ();
1982                                 }
1983                                 if (_preserve_fade_anchor) {
1984                                         AudioRegionView* arv = dynamic_cast<AudioRegionView*> (i->view);
1985                                         if (arv) {
1986                                                 double distance;
1987                                                 double new_length;
1988                                                 framecnt_t len;
1989                                                 boost::shared_ptr<AudioRegion> ar (arv->audio_region());
1990                                                 distance = _drags->current_pointer_x() - grab_x();
1991                                                 len = ar->fade_in()->back()->when;
1992                                                 new_length = len - _editor->unit_to_frame (distance);
1993                                                 new_length = ar->verify_xfade_bounds (new_length, true  /*START*/ );
1994                                                 ar->set_fade_in_length(new_length);
1995                                         }
1996                                 }
1997                         }
1998                 } else if (_operation == EndTrim) {
1999                         for (list<DraggingView>::const_iterator i = _views.begin(); i != _views.end(); ++i) {
2000                                 if (_preserve_fade_anchor) {
2001                                         AudioRegionView* arv = dynamic_cast<AudioRegionView*> (i->view);
2002                                         if (arv) {
2003                                                 double distance;
2004                                                 double new_length;
2005                                                 framecnt_t len;
2006                                                 boost::shared_ptr<AudioRegion> ar (arv->audio_region());
2007                                                 distance = _drags->current_pointer_x() - grab_x();
2008                                                 len = ar->fade_out()->back()->when;
2009                                                 new_length = len - _editor->unit_to_frame (distance);
2010                                                 new_length = ar->verify_xfade_bounds (new_length, false  /*END*/ );
2011                                                 ar->set_fade_out_length(new_length);
2012                                         }
2013                                 }
2014                         }
2015                 }
2016
2017                 if (!_views.empty()) {
2018                         if (_operation == StartTrim) {
2019                                 _editor->maybe_locate_with_edit_preroll(
2020                                         _views.begin()->view->region()->position());
2021                         }
2022                         if (_operation == EndTrim) {
2023                                 _editor->maybe_locate_with_edit_preroll(
2024                                         _views.begin()->view->region()->position() +
2025                                         _views.begin()->view->region()->length());
2026                         }
2027                 }
2028         
2029                 if (!_editor->selection->selected (_primary)) {
2030                         _primary->thaw_after_trim ();
2031                 } else {
2032
2033                         set<boost::shared_ptr<Playlist> > diffed_playlists;
2034
2035                         for (list<DraggingView>::const_iterator i = _views.begin(); i != _views.end(); ++i) {
2036                                 i->view->thaw_after_trim ();
2037                                 i->view->enable_display (true);
2038                                 i->view->fake_set_opaque (true);
2039
2040                                 /* Trimming one region may affect others on the playlist, so we need
2041                                    to get undo Commands from the whole playlist rather than just the
2042                                    region.  Use diffed_playlists to make sure we don't diff a given
2043                                    playlist more than once.
2044                                 */
2045                                 boost::shared_ptr<Playlist> p = i->view->region()->playlist ();
2046                                 if (diffed_playlists.find (p) == diffed_playlists.end()) {
2047                                         vector<Command*> cmds;
2048                                         p->rdiff (cmds);
2049                                         _editor->session()->add_commands (cmds);
2050                                         diffed_playlists.insert (p);
2051                                 }
2052                         }
2053                 }
2054
2055                 for (set<boost::shared_ptr<Playlist> >::iterator p = _editor->motion_frozen_playlists.begin(); p != _editor->motion_frozen_playlists.end(); ++p) {
2056                         (*p)->thaw ();
2057                 }
2058
2059                 _editor->motion_frozen_playlists.clear ();
2060                 _editor->commit_reversible_command();
2061
2062         } else {
2063                 /* no mouse movement */
2064                 _editor->point_trim (event, adjusted_current_frame (event));
2065         }
2066
2067         for (list<DraggingView>::const_iterator i = _views.begin(); i != _views.end(); ++i) {
2068                 if (_operation == StartTrim) {
2069                         i->view->trim_front_ending ();
2070                 }
2071
2072                 i->view->region()->resume_property_changes ();
2073         }
2074 }
2075
2076 void
2077 TrimDrag::aborted (bool movement_occurred)
2078 {
2079         /* Our motion method is changing model state, so use the Undo system
2080            to cancel.  Perhaps not ideal, as this will leave an Undo point
2081            behind which may be slightly odd from the user's point of view.
2082         */
2083
2084         finished (0, true);
2085
2086         if (movement_occurred) {
2087                 _editor->undo ();
2088         }
2089
2090         for (list<DraggingView>::const_iterator i = _views.begin(); i != _views.end(); ++i) {
2091                 i->view->region()->resume_property_changes ();
2092         }
2093 }
2094
2095 void
2096 TrimDrag::setup_pointer_frame_offset ()
2097 {
2098         list<DraggingView>::iterator i = _views.begin ();
2099         while (i != _views.end() && i->view != _primary) {
2100                 ++i;
2101         }
2102
2103         if (i == _views.end()) {
2104                 return;
2105         }
2106
2107         switch (_operation) {
2108         case StartTrim:
2109                 _pointer_frame_offset = raw_grab_frame() - i->initial_position;
2110                 break;
2111         case EndTrim:
2112                 _pointer_frame_offset = raw_grab_frame() - i->initial_end;
2113                 break;
2114         case ContentsTrim:
2115                 break;
2116         }
2117 }
2118
2119 MeterMarkerDrag::MeterMarkerDrag (Editor* e, ArdourCanvas::Item* i, bool c)
2120         : Drag (e, i),
2121           _copy (c)
2122 {
2123         DEBUG_TRACE (DEBUG::Drags, "New MeterMarkerDrag\n");
2124         _marker = reinterpret_cast<MeterMarker*> (_item->get_data ("marker"));
2125         assert (_marker);
2126 }
2127
2128 void
2129 MeterMarkerDrag::start_grab (GdkEvent* event, Gdk::Cursor* cursor)
2130 {
2131         Drag::start_grab (event, cursor);
2132         show_verbose_cursor_time (adjusted_current_frame(event));
2133 }
2134
2135 void
2136 MeterMarkerDrag::setup_pointer_frame_offset ()
2137 {
2138         _pointer_frame_offset = raw_grab_frame() - _marker->meter().frame();
2139 }
2140
2141 void
2142 MeterMarkerDrag::motion (GdkEvent* event, bool first_move)
2143 {
2144         if (first_move) {
2145
2146                 // create a dummy marker for visual representation of moving the
2147                 // section, because whether its a copy or not, we're going to 
2148                 // leave or lose the original marker (leave if its a copy; lose if its
2149                 // not, because we'll remove it from the map).
2150                 
2151                 MeterSection section (_marker->meter());
2152
2153                 if (!section.movable()) {
2154                         return;
2155                 }
2156                 
2157                 char name[64];
2158                 snprintf (name, sizeof(name), "%g/%g", _marker->meter().divisions_per_bar(), _marker->meter().note_divisor ());
2159                 
2160                 _marker = new MeterMarker (
2161                         *_editor,
2162                         *_editor->meter_group,
2163                         ARDOUR_UI::config()->canvasvar_MeterMarker.get(),
2164                         name,
2165                         *new MeterSection (_marker->meter())
2166                 );
2167                 
2168                 /* use the new marker for the grab */
2169                 swap_grab (&_marker->the_item(), 0, GDK_CURRENT_TIME);
2170
2171                 if (!_copy) {
2172                         TempoMap& map (_editor->session()->tempo_map());
2173                         /* get current state */
2174                         before_state = &map.get_state();
2175                         /* remove the section while we drag it */
2176                         map.remove_meter (section, true);
2177                 }
2178         }
2179
2180         framepos_t const pf = adjusted_current_frame (event);
2181         _marker->set_position (pf);
2182         show_verbose_cursor_time (pf);
2183 }
2184
2185 void
2186 MeterMarkerDrag::finished (GdkEvent* event, bool movement_occurred)
2187 {
2188         if (!movement_occurred) {
2189                 return;
2190         }
2191
2192         motion (event, false);
2193
2194         Timecode::BBT_Time when;
2195
2196         TempoMap& map (_editor->session()->tempo_map());
2197         map.bbt_time (last_pointer_frame(), when);
2198         
2199         if (_copy == true) {
2200                 _editor->begin_reversible_command (_("copy meter mark"));
2201                 XMLNode &before = map.get_state();
2202                 map.add_meter (_marker->meter(), when);
2203                 XMLNode &after = map.get_state();
2204                 _editor->session()->add_command(new MementoCommand<TempoMap>(map, &before, &after));
2205                 _editor->commit_reversible_command ();
2206
2207         } else {
2208                 _editor->begin_reversible_command (_("move meter mark"));
2209
2210                 /* we removed it before, so add it back now */
2211                 
2212                 map.add_meter (_marker->meter(), when);
2213                 XMLNode &after = map.get_state();
2214                 _editor->session()->add_command(new MementoCommand<TempoMap>(map, before_state, &after));
2215                 _editor->commit_reversible_command ();
2216         }
2217
2218         // delete the dummy marker we used for visual representation while moving.
2219         // a new visual marker will show up automatically.
2220         delete _marker;
2221 }
2222
2223 void
2224 MeterMarkerDrag::aborted (bool moved)
2225 {
2226         _marker->set_position (_marker->meter().frame ());
2227
2228         if (moved) {
2229                 TempoMap& map (_editor->session()->tempo_map());
2230                 /* we removed it before, so add it back now */
2231                 map.add_meter (_marker->meter(), _marker->meter().frame());
2232                 // delete the dummy marker we used for visual representation while moving.
2233                 // a new visual marker will show up automatically.
2234                 delete _marker;
2235         }
2236 }
2237
2238 TempoMarkerDrag::TempoMarkerDrag (Editor* e, ArdourCanvas::Item* i, bool c)
2239         : Drag (e, i),
2240           _copy (c)
2241 {
2242         DEBUG_TRACE (DEBUG::Drags, "New TempoMarkerDrag\n");
2243
2244         _marker = reinterpret_cast<TempoMarker*> (_item->get_data ("marker"));
2245         assert (_marker);
2246 }
2247
2248 void
2249 TempoMarkerDrag::start_grab (GdkEvent* event, Gdk::Cursor* cursor)
2250 {
2251         Drag::start_grab (event, cursor);
2252         show_verbose_cursor_time (adjusted_current_frame (event));
2253 }
2254
2255 void
2256 TempoMarkerDrag::setup_pointer_frame_offset ()
2257 {
2258         _pointer_frame_offset = raw_grab_frame() - _marker->tempo().frame();
2259 }
2260
2261 void
2262 TempoMarkerDrag::motion (GdkEvent* event, bool first_move)
2263 {
2264         if (first_move) {
2265
2266                 // create a dummy marker for visual representation of moving the
2267                 // section, because whether its a copy or not, we're going to 
2268                 // leave or lose the original marker (leave if its a copy; lose if its
2269                 // not, because we'll remove it from the map).
2270                 
2271                 // create a dummy marker for visual representation of moving the copy.
2272                 // The actual copying is not done before we reach the finish callback.
2273
2274                 char name[64];
2275                 snprintf (name, sizeof (name), "%.2f", _marker->tempo().beats_per_minute());
2276
2277                 TempoSection section (_marker->tempo());
2278
2279                 _marker = new TempoMarker (
2280                         *_editor,
2281                         *_editor->tempo_group,
2282                         ARDOUR_UI::config()->canvasvar_TempoMarker.get(),
2283                         name,
2284                         *new TempoSection (_marker->tempo())
2285                         );
2286
2287                 /* use the new marker for the grab */
2288                 swap_grab (&_marker->the_item(), 0, GDK_CURRENT_TIME);
2289
2290                 if (!_copy) {
2291                         TempoMap& map (_editor->session()->tempo_map());
2292                         /* get current state */
2293                         before_state = &map.get_state();
2294                         /* remove the section while we drag it */
2295                         map.remove_tempo (section, true);
2296                 }
2297         }
2298
2299         framepos_t const pf = adjusted_current_frame (event);
2300         _marker->set_position (pf);
2301         show_verbose_cursor_time (pf);
2302 }
2303
2304 void
2305 TempoMarkerDrag::finished (GdkEvent* event, bool movement_occurred)
2306 {
2307         if (!movement_occurred) {
2308                 return;
2309         }
2310
2311         motion (event, false);
2312
2313         TempoMap& map (_editor->session()->tempo_map());
2314         framepos_t beat_time = map.round_to_beat (last_pointer_frame(), 0);
2315         Timecode::BBT_Time when;
2316
2317         map.bbt_time (beat_time, when);
2318
2319         if (_copy == true) {
2320                 _editor->begin_reversible_command (_("copy tempo mark"));
2321                 XMLNode &before = map.get_state();
2322                 map.add_tempo (_marker->tempo(), when);
2323                 XMLNode &after = map.get_state();
2324                 _editor->session()->add_command (new MementoCommand<TempoMap>(map, &before, &after));
2325                 _editor->commit_reversible_command ();
2326
2327         } else {
2328                 _editor->begin_reversible_command (_("move tempo mark"));
2329                 /* we removed it before, so add it back now */
2330                 map.add_tempo (_marker->tempo(), when);
2331                 XMLNode &after = map.get_state();
2332                 _editor->session()->add_command (new MementoCommand<TempoMap>(map, before_state, &after));
2333                 _editor->commit_reversible_command ();
2334         }
2335
2336         // delete the dummy marker we used for visual representation while moving.
2337         // a new visual marker will show up automatically.
2338         delete _marker;
2339 }
2340
2341 void
2342 TempoMarkerDrag::aborted (bool moved)
2343 {
2344         _marker->set_position (_marker->tempo().frame());
2345         if (moved) {
2346                 TempoMap& map (_editor->session()->tempo_map());
2347                 /* we removed it before, so add it back now */
2348                 map.add_tempo (_marker->tempo(), _marker->tempo().start());
2349                 // delete the dummy marker we used for visual representation while moving.
2350                 // a new visual marker will show up automatically.
2351                 delete _marker;
2352         }
2353 }
2354
2355 CursorDrag::CursorDrag (Editor* e, ArdourCanvas::Item* i, bool s)
2356         : Drag (e, i),
2357           _stop (s)
2358 {
2359         DEBUG_TRACE (DEBUG::Drags, "New CursorDrag\n");
2360 }
2361
2362 /** Do all the things we do when dragging the playhead to make it look as though
2363  *  we have located, without actually doing the locate (because that would cause
2364  *  the diskstream buffers to be refilled, which is too slow).
2365  */
2366 void
2367 CursorDrag::fake_locate (framepos_t t)
2368 {
2369         _editor->playhead_cursor->set_position (t);
2370
2371         Session* s = _editor->session ();
2372         if (s->timecode_transmission_suspended ()) {
2373                 framepos_t const f = _editor->playhead_cursor->current_frame;
2374                 s->send_mmc_locate (f);
2375                 s->send_full_time_code (f);
2376                 s->send_song_position_pointer (f);
2377         }
2378
2379         show_verbose_cursor_time (t);
2380         _editor->UpdateAllTransportClocks (t);
2381 }
2382
2383 void
2384 CursorDrag::start_grab (GdkEvent* event, Gdk::Cursor* c)
2385 {
2386         Drag::start_grab (event, c);
2387
2388         _grab_zoom = _editor->frames_per_unit;
2389
2390         framepos_t where = _editor->event_frame (event, 0, 0);
2391         _editor->snap_to_with_modifier (where, event);
2392
2393         _editor->_dragging_playhead = true;
2394
2395         Session* s = _editor->session ();
2396
2397         if (s) {
2398                 if (_was_rolling && _stop) {
2399                         s->request_stop ();
2400                 }
2401
2402                 if (s->is_auditioning()) {
2403                         s->cancel_audition ();
2404                 }
2405
2406
2407                 if (AudioEngine::instance()->connected()) {
2408                         
2409                         /* do this only if we're the engine is connected
2410                          * because otherwise this request will never be
2411                          * serviced and we'll busy wait forever. likewise,
2412                          * notice if we are disconnected while waiting for the
2413                          * request to be serviced.
2414                          */
2415
2416                         s->request_suspend_timecode_transmission ();
2417                         while (AudioEngine::instance()->connected() && !s->timecode_transmission_suspended ()) {
2418                                 /* twiddle our thumbs */
2419                         }
2420                 }
2421         }
2422
2423         fake_locate (where);
2424 }
2425
2426 void
2427 CursorDrag::motion (GdkEvent* event, bool)
2428 {
2429         framepos_t const adjusted_frame = adjusted_current_frame (event);
2430         if (adjusted_frame != last_pointer_frame()) {
2431                 fake_locate (adjusted_frame);
2432 #ifdef GTKOSX
2433                 _editor->update_canvas_now ();
2434 #endif
2435         }
2436 }
2437
2438 void
2439 CursorDrag::finished (GdkEvent* event, bool movement_occurred)
2440 {
2441         _editor->_dragging_playhead = false;
2442
2443         if (!movement_occurred && _stop) {
2444                 return;
2445         }
2446
2447         motion (event, false);
2448
2449         Session* s = _editor->session ();
2450         if (s) {
2451                 s->request_locate (_editor->playhead_cursor->current_frame, _was_rolling);
2452                 _editor->_pending_locate_request = true;
2453                 s->request_resume_timecode_transmission ();
2454         }
2455 }
2456
2457 void
2458 CursorDrag::aborted (bool)
2459 {
2460         if (_editor->_dragging_playhead) {
2461                 _editor->session()->request_resume_timecode_transmission ();
2462                 _editor->_dragging_playhead = false;
2463         }
2464
2465         _editor->playhead_cursor->set_position (adjusted_frame (grab_frame (), 0, false));
2466 }
2467
2468 FadeInDrag::FadeInDrag (Editor* e, ArdourCanvas::Item* i, RegionView* p, list<RegionView*> const & v)
2469         : RegionDrag (e, i, p, v)
2470 {
2471         DEBUG_TRACE (DEBUG::Drags, "New FadeInDrag\n");
2472 }
2473
2474 void
2475 FadeInDrag::start_grab (GdkEvent* event, Gdk::Cursor* cursor)
2476 {
2477         Drag::start_grab (event, cursor);
2478
2479         AudioRegionView* arv = dynamic_cast<AudioRegionView*> (_primary);
2480         boost::shared_ptr<AudioRegion> const r = arv->audio_region ();
2481
2482         show_verbose_cursor_duration (r->position(), r->position() + r->fade_in()->back()->when, 32);
2483 }
2484
2485 void
2486 FadeInDrag::setup_pointer_frame_offset ()
2487 {
2488         AudioRegionView* arv = dynamic_cast<AudioRegionView*> (_primary);
2489         boost::shared_ptr<AudioRegion> const r = arv->audio_region ();
2490         _pointer_frame_offset = raw_grab_frame() - ((framecnt_t) r->fade_in()->back()->when + r->position());
2491 }
2492
2493 void
2494 FadeInDrag::motion (GdkEvent* event, bool)
2495 {
2496         framecnt_t fade_length;
2497
2498         framepos_t const pos = adjusted_current_frame (event);
2499
2500         boost::shared_ptr<Region> region = _primary->region ();
2501
2502         if (pos < (region->position() + 64)) {
2503                 fade_length = 64; // this should be a minimum defined somewhere
2504         } else if (pos > region->last_frame()) {
2505                 fade_length = region->length();
2506         } else {
2507                 fade_length = pos - region->position();
2508         }
2509
2510         for (list<DraggingView>::iterator i = _views.begin(); i != _views.end(); ++i) {
2511
2512                 AudioRegionView* tmp = dynamic_cast<AudioRegionView*> (i->view);
2513
2514                 if (!tmp) {
2515                         continue;
2516                 }
2517
2518                 tmp->reset_fade_in_shape_width (tmp->audio_region(), fade_length);
2519         }
2520
2521         show_verbose_cursor_duration (region->position(), region->position() + fade_length, 32);
2522 }
2523
2524 void
2525 FadeInDrag::finished (GdkEvent* event, bool movement_occurred)
2526 {
2527         if (!movement_occurred) {
2528                 return;
2529         }
2530
2531         framecnt_t fade_length;
2532
2533         framepos_t const pos = adjusted_current_frame (event);
2534
2535         boost::shared_ptr<Region> region = _primary->region ();
2536
2537         if (pos < (region->position() + 64)) {
2538                 fade_length = 64; // this should be a minimum defined somewhere
2539         } else if (pos > region->last_frame()) {
2540                 fade_length = region->length();
2541         } else {
2542                 fade_length = pos - region->position();
2543         }
2544
2545         _editor->begin_reversible_command (_("change fade in length"));
2546
2547         for (list<DraggingView>::iterator i = _views.begin(); i != _views.end(); ++i) {
2548
2549                 AudioRegionView* tmp = dynamic_cast<AudioRegionView*> (i->view);
2550
2551                 if (!tmp) {
2552                         continue;
2553                 }
2554
2555                 boost::shared_ptr<AutomationList> alist = tmp->audio_region()->fade_in();
2556                 XMLNode &before = alist->get_state();
2557
2558                 tmp->audio_region()->set_fade_in_length (fade_length);
2559                 tmp->audio_region()->set_fade_in_active (true);
2560
2561                 XMLNode &after = alist->get_state();
2562                 _editor->session()->add_command(new MementoCommand<AutomationList>(*alist.get(), &before, &after));
2563         }
2564
2565         _editor->commit_reversible_command ();
2566 }
2567
2568 void
2569 FadeInDrag::aborted (bool)
2570 {
2571         for (list<DraggingView>::iterator i = _views.begin(); i != _views.end(); ++i) {
2572                 AudioRegionView* tmp = dynamic_cast<AudioRegionView*> (i->view);
2573
2574                 if (!tmp) {
2575                         continue;
2576                 }
2577
2578                 tmp->reset_fade_in_shape_width (tmp->audio_region(), tmp->audio_region()->fade_in()->back()->when);
2579         }
2580 }
2581
2582 FadeOutDrag::FadeOutDrag (Editor* e, ArdourCanvas::Item* i, RegionView* p, list<RegionView*> const & v)
2583         : RegionDrag (e, i, p, v)
2584 {
2585         DEBUG_TRACE (DEBUG::Drags, "New FadeOutDrag\n");
2586 }
2587
2588 void
2589 FadeOutDrag::start_grab (GdkEvent* event, Gdk::Cursor* cursor)
2590 {
2591         Drag::start_grab (event, cursor);
2592
2593         AudioRegionView* arv = dynamic_cast<AudioRegionView*> (_primary);
2594         boost::shared_ptr<AudioRegion> r = arv->audio_region ();
2595
2596         show_verbose_cursor_duration (r->last_frame() - r->fade_out()->back()->when, r->last_frame());
2597 }
2598
2599 void
2600 FadeOutDrag::setup_pointer_frame_offset ()
2601 {
2602         AudioRegionView* arv = dynamic_cast<AudioRegionView*> (_primary);
2603         boost::shared_ptr<AudioRegion> r = arv->audio_region ();
2604         _pointer_frame_offset = raw_grab_frame() - (r->length() - (framecnt_t) r->fade_out()->back()->when + r->position());
2605 }
2606
2607 void
2608 FadeOutDrag::motion (GdkEvent* event, bool)
2609 {
2610         framecnt_t fade_length;
2611
2612         framepos_t const pos = adjusted_current_frame (event);
2613
2614         boost::shared_ptr<Region> region = _primary->region ();
2615
2616         if (pos > (region->last_frame() - 64)) {
2617                 fade_length = 64; // this should really be a minimum fade defined somewhere
2618         }
2619         else if (pos < region->position()) {
2620                 fade_length = region->length();
2621         }
2622         else {
2623                 fade_length = region->last_frame() - pos;
2624         }
2625
2626         for (list<DraggingView>::iterator i = _views.begin(); i != _views.end(); ++i) {
2627
2628                 AudioRegionView* tmp = dynamic_cast<AudioRegionView*> (i->view);
2629
2630                 if (!tmp) {
2631                         continue;
2632                 }
2633
2634                 tmp->reset_fade_out_shape_width (tmp->audio_region(), fade_length);
2635         }
2636
2637         show_verbose_cursor_duration (region->last_frame() - fade_length, region->last_frame());
2638 }
2639
2640 void
2641 FadeOutDrag::finished (GdkEvent* event, bool movement_occurred)
2642 {
2643         if (!movement_occurred) {
2644                 return;
2645         }
2646
2647         framecnt_t fade_length;
2648
2649         framepos_t const pos = adjusted_current_frame (event);
2650
2651         boost::shared_ptr<Region> region = _primary->region ();
2652
2653         if (pos > (region->last_frame() - 64)) {
2654                 fade_length = 64; // this should really be a minimum fade defined somewhere
2655         }
2656         else if (pos < region->position()) {
2657                 fade_length = region->length();
2658         }
2659         else {
2660                 fade_length = region->last_frame() - pos;
2661         }
2662
2663         _editor->begin_reversible_command (_("change fade out length"));
2664
2665         for (list<DraggingView>::iterator i = _views.begin(); i != _views.end(); ++i) {
2666
2667                 AudioRegionView* tmp = dynamic_cast<AudioRegionView*> (i->view);
2668
2669                 if (!tmp) {
2670                         continue;
2671                 }
2672
2673                 boost::shared_ptr<AutomationList> alist = tmp->audio_region()->fade_out();
2674                 XMLNode &before = alist->get_state();
2675
2676                 tmp->audio_region()->set_fade_out_length (fade_length);
2677                 tmp->audio_region()->set_fade_out_active (true);
2678
2679                 XMLNode &after = alist->get_state();
2680                 _editor->session()->add_command(new MementoCommand<AutomationList>(*alist.get(), &before, &after));
2681         }
2682
2683         _editor->commit_reversible_command ();
2684 }
2685
2686 void
2687 FadeOutDrag::aborted (bool)
2688 {
2689         for (list<DraggingView>::iterator i = _views.begin(); i != _views.end(); ++i) {
2690                 AudioRegionView* tmp = dynamic_cast<AudioRegionView*> (i->view);
2691
2692                 if (!tmp) {
2693                         continue;
2694                 }
2695
2696                 tmp->reset_fade_out_shape_width (tmp->audio_region(), tmp->audio_region()->fade_out()->back()->when);
2697         }
2698 }
2699
2700 MarkerDrag::MarkerDrag (Editor* e, ArdourCanvas::Item* i)
2701         : Drag (e, i)
2702 {
2703         DEBUG_TRACE (DEBUG::Drags, "New MarkerDrag\n");
2704
2705         _marker = reinterpret_cast<Marker*> (_item->get_data ("marker"));
2706         assert (_marker);
2707
2708         _points.push_back (Gnome::Art::Point (0, 0));
2709         _points.push_back (Gnome::Art::Point (0, physical_screen_height (_editor->get_window())));
2710 }
2711
2712 MarkerDrag::~MarkerDrag ()
2713 {
2714         for (CopiedLocationInfo::iterator i = _copied_locations.begin(); i != _copied_locations.end(); ++i) {
2715                 delete i->location;
2716         }
2717 }
2718
2719 MarkerDrag::CopiedLocationMarkerInfo::CopiedLocationMarkerInfo (Location* l, Marker* m)
2720 {
2721         location = new Location (*l);
2722         markers.push_back (m);
2723         move_both = false;
2724 }
2725
2726 void
2727 MarkerDrag::start_grab (GdkEvent* event, Gdk::Cursor* cursor)
2728 {
2729         Drag::start_grab (event, cursor);
2730
2731         bool is_start;
2732
2733         Location *location = _editor->find_location_from_marker (_marker, is_start);
2734         _editor->_dragging_edit_point = true;
2735
2736         update_item (location);
2737
2738         // _drag_line->show();
2739         // _line->raise_to_top();
2740
2741         if (is_start) {
2742                 show_verbose_cursor_time (location->start());
2743         } else {
2744                 show_verbose_cursor_time (location->end());
2745         }
2746
2747         Selection::Operation op = ArdourKeyboard::selection_type (event->button.state);
2748
2749         switch (op) {
2750         case Selection::Toggle:
2751                 /* we toggle on the button release */
2752                 break;
2753         case Selection::Set:
2754                 if (!_editor->selection->selected (_marker)) {
2755                         _editor->selection->set (_marker);
2756                 }
2757                 break;
2758         case Selection::Extend:
2759         {
2760                 Locations::LocationList ll;
2761                 list<Marker*> to_add;
2762                 framepos_t s, e;
2763                 _editor->selection->markers.range (s, e);
2764                 s = min (_marker->position(), s);
2765                 e = max (_marker->position(), e);
2766                 s = min (s, e);
2767                 e = max (s, e);
2768                 if (e < max_framepos) {
2769                         ++e;
2770                 }
2771                 _editor->session()->locations()->find_all_between (s, e, ll, Location::Flags (0));
2772                 for (Locations::LocationList::iterator i = ll.begin(); i != ll.end(); ++i) {
2773                         Editor::LocationMarkers* lm = _editor->find_location_markers (*i);
2774                         if (lm) {
2775                                 if (lm->start) {
2776                                         to_add.push_back (lm->start);
2777                                 }
2778                                 if (lm->end) {
2779                                         to_add.push_back (lm->end);
2780                                 }
2781                         }
2782                 }
2783                 if (!to_add.empty()) {
2784                         _editor->selection->add (to_add);
2785                 }
2786                 break;
2787         }
2788         case Selection::Add:
2789                 _editor->selection->add (_marker);
2790                 break;
2791         }
2792
2793         /* Set up copies for us to manipulate during the drag 
2794          */
2795
2796         for (MarkerSelection::iterator i = _editor->selection->markers.begin(); i != _editor->selection->markers.end(); ++i) {
2797
2798                 Location* l = _editor->find_location_from_marker (*i, is_start);
2799
2800                 if (!l) {
2801                         continue;
2802                 }
2803
2804                 if (l->is_mark()) {
2805                         _copied_locations.push_back (CopiedLocationMarkerInfo (l, *i));
2806                 } else {
2807                         /* range: check that the other end of the range isn't
2808                            already there.
2809                         */
2810                         CopiedLocationInfo::iterator x;
2811                         for (x = _copied_locations.begin(); x != _copied_locations.end(); ++x) {
2812                                 if (*(*x).location == *l) {
2813                                         break;
2814                                 }
2815                         }
2816                         if (x == _copied_locations.end()) {
2817                                 _copied_locations.push_back (CopiedLocationMarkerInfo (l, *i));
2818                         } else {
2819                                 (*x).markers.push_back (*i);
2820                                 (*x).move_both = true;
2821                         }
2822                 }
2823                         
2824         }
2825 }
2826
2827 void
2828 MarkerDrag::setup_pointer_frame_offset ()
2829 {
2830         bool is_start;
2831         Location *location = _editor->find_location_from_marker (_marker, is_start);
2832         _pointer_frame_offset = raw_grab_frame() - (is_start ? location->start() : location->end());
2833 }
2834
2835 void
2836 MarkerDrag::motion (GdkEvent* event, bool)
2837 {
2838         framecnt_t f_delta = 0;
2839         bool is_start;
2840         bool move_both = false;
2841         Location *real_location;
2842         Location *copy_location = 0;
2843
2844         framepos_t const newframe = adjusted_current_frame (event);
2845         framepos_t next = newframe;
2846
2847         if (Keyboard::modifier_state_equals (event->button.state, Keyboard::PrimaryModifier)) {
2848                 move_both = true;
2849         }
2850
2851         CopiedLocationInfo::iterator x;
2852
2853         /* find the marker we're dragging, and compute the delta */
2854
2855         for (x = _copied_locations.begin(); x != _copied_locations.end(); ++x) {
2856
2857                 copy_location = (*x).location;
2858
2859                 if (find (x->markers.begin(), x->markers.end(), _marker) != x->markers.end()) {
2860
2861                         /* this marker is represented by this
2862                          * CopiedLocationMarkerInfo 
2863                          */
2864
2865                         if ((real_location = _editor->find_location_from_marker (_marker, is_start)) == 0) {
2866                                 /* que pasa ?? */
2867                                 return;
2868                         }
2869
2870                         if (real_location->is_mark()) {
2871                                 f_delta = newframe - copy_location->start();
2872                         } else {
2873
2874
2875                                 switch (_marker->type()) {
2876                                 case Marker::SessionStart:
2877                                 case Marker::RangeStart:
2878                                 case Marker::LoopStart:
2879                                 case Marker::PunchIn:
2880                                         f_delta = newframe - copy_location->start();
2881                                         break;
2882
2883                                 case Marker::SessionEnd:
2884                                 case Marker::RangeEnd:
2885                                 case Marker::LoopEnd:
2886                                 case Marker::PunchOut:
2887                                         f_delta = newframe - copy_location->end();
2888                                         break;
2889                                 default:
2890                                         /* what kind of marker is this ? */
2891                                         return;
2892                                 }
2893                         }
2894
2895                         break;
2896                 }
2897         }
2898
2899         if (x == _copied_locations.end()) {
2900                 /* hmm, impossible - we didn't find the dragged marker */
2901                 return;
2902         }
2903
2904         /* now move them all */
2905
2906         for (x = _copied_locations.begin(); x != _copied_locations.end(); ++x) {
2907
2908                 copy_location = x->location;
2909
2910                 /* call this to find out if its the start or end */
2911
2912                 if ((real_location = _editor->find_location_from_marker (x->markers.front(), is_start)) == 0) {
2913                         continue;
2914                 }
2915
2916                 if (real_location->locked()) {
2917                         continue;
2918                 }
2919
2920                 if (copy_location->is_mark()) {
2921
2922                         /* now move it */
2923
2924                         copy_location->set_start (copy_location->start() + f_delta);
2925
2926                 } else {
2927                         
2928                         framepos_t new_start = copy_location->start() + f_delta;
2929                         framepos_t new_end = copy_location->end() + f_delta;
2930                         
2931                         if (is_start) { // start-of-range marker
2932                                 
2933                                 if (move_both || (*x).move_both) {
2934                                         copy_location->set_start (new_start);
2935                                         copy_location->set_end (new_end);
2936                                 } else  if (new_start < copy_location->end()) {
2937                                         copy_location->set_start (new_start);
2938                                 } else if (newframe > 0) {
2939                                         _editor->snap_to (next, 1, true);
2940                                         copy_location->set_end (next);
2941                                         copy_location->set_start (newframe);
2942                                 }
2943
2944                         } else { // end marker
2945
2946                                 if (move_both || (*x).move_both) {
2947                                         copy_location->set_end (new_end);
2948                                         copy_location->set_start (new_start);
2949                                 } else if (new_end > copy_location->start()) {
2950                                         copy_location->set_end (new_end);
2951                                 } else if (newframe > 0) {
2952                                         _editor->snap_to (next, -1, true);
2953                                         copy_location->set_start (next);
2954                                         copy_location->set_end (newframe);
2955                                 }
2956                         }
2957                 }
2958
2959                 update_item (copy_location);
2960                 
2961                 /* now lookup the actual GUI items used to display this
2962                  * location and move them to wherever the copy of the location
2963                  * is now. This means that the logic in ARDOUR::Location is
2964                  * still enforced, even though we are not (yet) modifying 
2965                  * the real Location itself.
2966                  */
2967                 
2968                 Editor::LocationMarkers* lm = _editor->find_location_markers (real_location);
2969
2970                 if (lm) {
2971                         lm->set_position (copy_location->start(), copy_location->end());
2972                 }
2973
2974         }
2975
2976         assert (!_copied_locations.empty());
2977
2978         show_verbose_cursor_time (newframe);
2979
2980 #ifdef GTKOSX
2981         _editor->update_canvas_now ();
2982 #endif
2983 }
2984
2985 void
2986 MarkerDrag::finished (GdkEvent* event, bool movement_occurred)
2987 {
2988         if (!movement_occurred) {
2989
2990                 /* just a click, do nothing but finish
2991                    off the selection process
2992                 */
2993
2994                 Selection::Operation op = ArdourKeyboard::selection_type (event->button.state);
2995
2996                 switch (op) {
2997                 case Selection::Set:
2998                         if (_editor->selection->selected (_marker) && _editor->selection->markers.size() > 1) {
2999                                 _editor->selection->set (_marker);
3000                         }
3001                         break;
3002
3003                 case Selection::Toggle:
3004                         /* we toggle on the button release, click only */
3005                         _editor->selection->toggle (_marker);
3006                         break;
3007
3008                 case Selection::Extend:
3009                 case Selection::Add:
3010                         break;
3011                 }
3012
3013                 return;
3014         }
3015
3016         _editor->_dragging_edit_point = false;
3017
3018         _editor->begin_reversible_command ( _("move marker") );
3019         XMLNode &before = _editor->session()->locations()->get_state();
3020
3021         MarkerSelection::iterator i;
3022         CopiedLocationInfo::iterator x;
3023         bool is_start;
3024
3025         for (i = _editor->selection->markers.begin(), x = _copied_locations.begin();
3026              x != _copied_locations.end() && i != _editor->selection->markers.end();
3027              ++i, ++x) {
3028
3029                 Location * location = _editor->find_location_from_marker (*i, is_start);
3030
3031                 if (location) {
3032
3033                         if (location->locked()) {
3034                                 return;
3035                         }
3036
3037                         if (location->is_mark()) {
3038                                 location->set_start (((*x).location)->start());
3039                         } else {
3040                                 location->set (((*x).location)->start(), ((*x).location)->end());
3041                         }
3042                 }
3043         }
3044
3045         XMLNode &after = _editor->session()->locations()->get_state();
3046         _editor->session()->add_command(new MementoCommand<Locations>(*(_editor->session()->locations()), &before, &after));
3047         _editor->commit_reversible_command ();
3048 }
3049
3050 void
3051 MarkerDrag::aborted (bool)
3052 {
3053         /* XXX: TODO */
3054 }
3055
3056 void
3057 MarkerDrag::update_item (Location*)
3058 {
3059         /* noop */
3060 }
3061
3062 ControlPointDrag::ControlPointDrag (Editor* e, ArdourCanvas::Item* i)
3063         : Drag (e, i),
3064           _cumulative_x_drag (0),
3065           _cumulative_y_drag (0)
3066 {
3067         if (_zero_gain_fraction < 0.0) {
3068                 _zero_gain_fraction = gain_to_slider_position_with_max (dB_to_coefficient (0.0), Config->get_max_gain());
3069         }
3070
3071         DEBUG_TRACE (DEBUG::Drags, "New ControlPointDrag\n");
3072
3073         _point = reinterpret_cast<ControlPoint*> (_item->get_data ("control_point"));
3074         assert (_point);
3075 }
3076
3077
3078 void
3079 ControlPointDrag::start_grab (GdkEvent* event, Gdk::Cursor* /*cursor*/)
3080 {
3081         Drag::start_grab (event, _editor->cursors()->fader);
3082
3083         // start the grab at the center of the control point so
3084         // the point doesn't 'jump' to the mouse after the first drag
3085         _fixed_grab_x = _point->get_x();
3086         _fixed_grab_y = _point->get_y();
3087
3088         float const fraction = 1 - (_point->get_y() / _point->line().height());
3089
3090         _point->line().start_drag_single (_point, _fixed_grab_x, fraction);
3091
3092         _editor->verbose_cursor()->set (_point->line().get_verbose_cursor_string (fraction),
3093                                         event->button.x + 10, event->button.y + 10);
3094
3095         _editor->verbose_cursor()->show ();
3096
3097         _pushing = Keyboard::modifier_state_contains (event->button.state, Keyboard::PrimaryModifier);
3098
3099         if (!_point->can_slide ()) {
3100                 _x_constrained = true;
3101         }
3102 }
3103
3104 void
3105 ControlPointDrag::motion (GdkEvent* event, bool)
3106 {
3107         double dx = _drags->current_pointer_x() - last_pointer_x();
3108         double dy = _drags->current_pointer_y() - last_pointer_y();
3109
3110         if (event->button.state & Keyboard::SecondaryModifier) {
3111                 dx *= 0.1;
3112                 dy *= 0.1;
3113         }
3114
3115         /* coordinate in pixels relative to the start of the region (for region-based automation)
3116            or track (for track-based automation) */
3117         double cx = _fixed_grab_x + _cumulative_x_drag + dx;
3118         double cy = _fixed_grab_y + _cumulative_y_drag + dy;
3119
3120         // calculate zero crossing point. back off by .01 to stay on the
3121         // positive side of zero
3122         double const zero_gain_y = (1.0 - _zero_gain_fraction) * _point->line().height() - .01;
3123
3124         // make sure we hit zero when passing through
3125         if ((cy < zero_gain_y && (cy - dy) > zero_gain_y) || (cy > zero_gain_y && (cy - dy) < zero_gain_y)) {
3126                 cy = zero_gain_y;
3127         }
3128
3129         if (_x_constrained) {
3130                 cx = _fixed_grab_x;
3131         }
3132         if (_y_constrained) {
3133                 cy = _fixed_grab_y;
3134         }
3135
3136         _cumulative_x_drag = cx - _fixed_grab_x;
3137         _cumulative_y_drag = cy - _fixed_grab_y;
3138
3139         cx = max (0.0, cx);
3140         cy = max (0.0, cy);
3141         cy = min ((double) _point->line().height(), cy);
3142
3143         framepos_t cx_frames = _editor->unit_to_frame (cx);
3144
3145         if (!_x_constrained) {
3146                 _editor->snap_to_with_modifier (cx_frames, event);
3147         }
3148
3149         cx_frames = min (cx_frames, _point->line().maximum_time());
3150
3151         float const fraction = 1.0 - (cy / _point->line().height());
3152
3153         _point->line().drag_motion (_editor->frame_to_unit_unrounded (cx_frames), fraction, false, _pushing, _final_index);
3154
3155         _editor->verbose_cursor()->set_text (_point->line().get_verbose_cursor_string (fraction));
3156 }
3157
3158 void
3159 ControlPointDrag::finished (GdkEvent* event, bool movement_occurred)
3160 {
3161         if (!movement_occurred) {
3162
3163                 /* just a click */
3164
3165                 if (Keyboard::modifier_state_equals (event->button.state, Keyboard::TertiaryModifier)) {
3166                         _editor->reset_point_selection ();
3167                 }
3168
3169         } else {
3170                 motion (event, false);
3171         }
3172
3173         _point->line().end_drag (_pushing, _final_index);
3174         _editor->session()->commit_reversible_command ();
3175 }
3176
3177 void
3178 ControlPointDrag::aborted (bool)
3179 {
3180         _point->line().reset ();
3181 }
3182
3183 bool
3184 ControlPointDrag::active (Editing::MouseMode m)
3185 {
3186         if (m == Editing::MouseGain) {
3187                 /* always active in mouse gain */
3188                 return true;
3189         }
3190
3191         /* otherwise active if the point is on an automation line (ie not if its on a region gain line) */
3192         return dynamic_cast<AutomationLine*> (&(_point->line())) != 0;
3193 }
3194
3195 LineDrag::LineDrag (Editor* e, ArdourCanvas::Item* i)
3196         : Drag (e, i),
3197           _line (0),
3198           _cumulative_y_drag (0)
3199 {
3200         DEBUG_TRACE (DEBUG::Drags, "New LineDrag\n");
3201 }
3202
3203 void
3204 LineDrag::start_grab (GdkEvent* event, Gdk::Cursor* /*cursor*/)
3205 {
3206         _line = reinterpret_cast<AutomationLine*> (_item->get_data ("line"));
3207         assert (_line);
3208
3209         _item = &_line->grab_item ();
3210
3211         /* need to get x coordinate in terms of parent (TimeAxisItemView)
3212            origin, and ditto for y.
3213         */
3214
3215         double cx = event->button.x;
3216         double cy = event->button.y;
3217
3218         _line->parent_group().w2i (cx, cy);
3219
3220         framecnt_t const frame_within_region = (framecnt_t) floor (cx * _editor->frames_per_unit);
3221
3222         uint32_t before;
3223         uint32_t after;
3224
3225         if (!_line->control_points_adjacent (frame_within_region, before, after)) {
3226                 /* no adjacent points */
3227                 return;
3228         }
3229
3230         Drag::start_grab (event, _editor->cursors()->fader);
3231
3232         /* store grab start in parent frame */
3233
3234         _fixed_grab_x = cx;
3235         _fixed_grab_y = cy;
3236
3237         double fraction = 1.0 - (cy / _line->height());
3238
3239         _line->start_drag_line (before, after, fraction);
3240
3241         _editor->verbose_cursor()->set (_line->get_verbose_cursor_string (fraction),
3242                                         event->button.x + 10, event->button.y + 10);
3243
3244         _editor->verbose_cursor()->show ();
3245 }
3246
3247 void
3248 LineDrag::motion (GdkEvent* event, bool)
3249 {
3250         double dy = _drags->current_pointer_y() - last_pointer_y();
3251
3252         if (event->button.state & Keyboard::SecondaryModifier) {
3253                 dy *= 0.1;
3254         }
3255
3256         double cy = _fixed_grab_y + _cumulative_y_drag + dy;
3257
3258         _cumulative_y_drag = cy - _fixed_grab_y;
3259
3260         cy = max (0.0, cy);
3261         cy = min ((double) _line->height(), cy);
3262
3263         double const fraction = 1.0 - (cy / _line->height());
3264         uint32_t ignored;
3265
3266         /* we are ignoring x position for this drag, so we can just pass in anything */
3267         _line->drag_motion (0, fraction, true, false, ignored);
3268
3269         _editor->verbose_cursor()->set_text (_line->get_verbose_cursor_string (fraction));
3270 }
3271
3272 void
3273 LineDrag::finished (GdkEvent* event, bool)
3274 {
3275         motion (event, false);
3276         _line->end_drag (false, 0);
3277         _editor->session()->commit_reversible_command ();
3278 }
3279
3280 void
3281 LineDrag::aborted (bool)
3282 {
3283         _line->reset ();
3284 }
3285
3286 FeatureLineDrag::FeatureLineDrag (Editor* e, ArdourCanvas::Item* i)
3287         : Drag (e, i),
3288           _line (0),
3289           _cumulative_x_drag (0)
3290 {
3291         DEBUG_TRACE (DEBUG::Drags, "New FeatureLineDrag\n");
3292 }
3293
3294 void
3295 FeatureLineDrag::start_grab (GdkEvent* event, Gdk::Cursor* /*cursor*/)
3296 {
3297         Drag::start_grab (event);
3298
3299         _line = reinterpret_cast<Line*> (_item);
3300         assert (_line);
3301
3302         /* need to get x coordinate in terms of parent (AudioRegionView) origin. */
3303
3304         double cx = event->button.x;
3305         double cy = event->button.y;
3306
3307         _item->property_parent().get_value()->w2i(cx, cy);
3308
3309         /* store grab start in parent frame */
3310         _region_view_grab_x = cx;
3311
3312         _before = *(float*) _item->get_data ("position");
3313
3314         _arv = reinterpret_cast<AudioRegionView*> (_item->get_data ("regionview"));
3315
3316         _max_x = _editor->frame_to_pixel(_arv->get_duration());
3317 }
3318
3319 void
3320 FeatureLineDrag::motion (GdkEvent*, bool)
3321 {
3322         double dx = _drags->current_pointer_x() - last_pointer_x();
3323
3324         double cx = _region_view_grab_x + _cumulative_x_drag + dx;
3325
3326         _cumulative_x_drag += dx;
3327
3328         /* Clamp the min and max extent of the drag to keep it within the region view bounds */
3329
3330         if (cx > _max_x){
3331                 cx = _max_x;
3332         }
3333         else if(cx < 0){
3334                 cx = 0;
3335         }
3336
3337         ArdourCanvas::Points points;
3338
3339         double x1 = 0, x2 = 0, y1 = 0, y2 = 0;
3340
3341         _line->get_bounds(x1, y2, x2, y2);
3342
3343         points.push_back(Gnome::Art::Point(cx, 2.0)); // first x-coord needs to be a non-normal value
3344         points.push_back(Gnome::Art::Point(cx, y2 - y1));
3345
3346         _line->property_points() = points;
3347
3348         float *pos = new float;
3349         *pos = cx;
3350
3351         _line->set_data ("position", pos);
3352
3353         _before = cx;
3354 }
3355
3356 void
3357 FeatureLineDrag::finished (GdkEvent*, bool)
3358 {
3359         _arv = reinterpret_cast<AudioRegionView*> (_item->get_data ("regionview"));
3360         _arv->update_transient(_before, _before);
3361 }
3362
3363 void
3364 FeatureLineDrag::aborted (bool)
3365 {
3366         //_line->reset ();
3367 }
3368
3369 RubberbandSelectDrag::RubberbandSelectDrag (Editor* e, ArdourCanvas::Item* i)
3370         : Drag (e, i)
3371         , _vertical_only (false)
3372 {
3373         DEBUG_TRACE (DEBUG::Drags, "New RubberbandSelectDrag\n");
3374 }
3375
3376 void
3377 RubberbandSelectDrag::start_grab (GdkEvent* event, Gdk::Cursor *)
3378 {
3379         Drag::start_grab (event);
3380         show_verbose_cursor_time (adjusted_current_frame (event));
3381 }
3382
3383 void
3384 RubberbandSelectDrag::motion (GdkEvent* event, bool)
3385 {
3386         framepos_t start;
3387         framepos_t end;
3388         double y1;
3389         double y2;
3390
3391         framepos_t const pf = adjusted_current_frame (event, Config->get_rubberbanding_snaps_to_grid ());
3392
3393         framepos_t grab = grab_frame ();
3394         if (Config->get_rubberbanding_snaps_to_grid ()) {
3395                 _editor->snap_to_with_modifier (grab, event);
3396         }
3397
3398         /* base start and end on initial click position */
3399
3400         if (pf < grab) {
3401                 start = pf;
3402                 end = grab;
3403         } else {
3404                 end = pf;
3405                 start = grab;
3406         }
3407
3408         if (_drags->current_pointer_y() < grab_y()) {
3409                 y1 = _drags->current_pointer_y();
3410                 y2 = grab_y();
3411         } else {
3412                 y2 = _drags->current_pointer_y();
3413                 y1 = grab_y();
3414         }
3415
3416
3417         if (start != end || y1 != y2) {
3418
3419                 double x1 = _editor->frame_to_pixel (start);
3420                 double x2 = _editor->frame_to_pixel (end);
3421
3422                 _editor->rubberband_rect->property_x1() = x1;
3423                 if (_vertical_only) {
3424                         /* fixed 10 pixel width */
3425                         _editor->rubberband_rect->property_x2() = x1 + 10;
3426                 } else {
3427                         _editor->rubberband_rect->property_x2() = x2;
3428                 } 
3429
3430                 _editor->rubberband_rect->property_y1() = y1;
3431                 _editor->rubberband_rect->property_y2() = y2;
3432
3433                 _editor->rubberband_rect->show();
3434                 _editor->rubberband_rect->raise_to_top();
3435
3436                 show_verbose_cursor_time (pf);
3437
3438                 do_select_things (event, true);
3439         }
3440 }
3441
3442 void
3443 RubberbandSelectDrag::do_select_things (GdkEvent* event, bool drag_in_progress)
3444 {
3445         framepos_t x1;
3446         framepos_t x2;
3447         
3448         if (grab_frame() < last_pointer_frame()) {
3449                 x1 = grab_frame ();
3450                 x2 = last_pointer_frame ();
3451         } else {
3452                 x2 = grab_frame ();
3453                 x1 = last_pointer_frame ();
3454         }
3455
3456         double y1;
3457         double y2;
3458         
3459         if (_drags->current_pointer_y() < grab_y()) {
3460                 y1 = _drags->current_pointer_y();
3461                 y2 = grab_y();
3462         } else {
3463                 y2 = _drags->current_pointer_y();
3464                 y1 = grab_y();
3465         }
3466
3467         select_things (event->button.state, x1, x2, y1, y2, drag_in_progress);
3468 }
3469
3470 void
3471 RubberbandSelectDrag::finished (GdkEvent* event, bool movement_occurred)
3472 {
3473         if (movement_occurred) {
3474
3475                 motion (event, false);
3476                 do_select_things (event, false);
3477
3478         } else {
3479
3480                 /* just a click */
3481
3482                 bool do_deselect = true;
3483                 MidiTimeAxisView* mtv;
3484
3485                 if ((mtv = dynamic_cast<MidiTimeAxisView*>(_editor->clicked_axisview)) != 0) {
3486                         /* MIDI track */
3487                         if (_editor->selection->empty()) {
3488                                 /* nothing selected */
3489                                 add_midi_region (mtv);
3490                                 do_deselect = false;
3491                         }
3492                 } 
3493
3494                 /* do not deselect if Primary or Tertiary (toggle-select or
3495                  * extend-select are pressed.
3496                  */
3497
3498                 if (!Keyboard::modifier_state_contains (event->button.state, Keyboard::PrimaryModifier) && 
3499                     !Keyboard::modifier_state_contains (event->button.state, Keyboard::TertiaryModifier) && 
3500                     do_deselect) {
3501                         deselect_things ();
3502                 }
3503
3504         }
3505
3506         _editor->rubberband_rect->hide();
3507 }
3508
3509 void
3510 RubberbandSelectDrag::aborted (bool)
3511 {
3512         _editor->rubberband_rect->hide ();
3513 }
3514
3515 TimeFXDrag::TimeFXDrag (Editor* e, ArdourCanvas::Item* i, RegionView* p, std::list<RegionView*> const & v)
3516         : RegionDrag (e, i, p, v)
3517 {
3518         DEBUG_TRACE (DEBUG::Drags, "New TimeFXDrag\n");
3519 }
3520
3521 void
3522 TimeFXDrag::start_grab (GdkEvent* event, Gdk::Cursor* cursor)
3523 {
3524         Drag::start_grab (event, cursor);
3525
3526         show_verbose_cursor_time (adjusted_current_frame (event));
3527 }
3528
3529 void
3530 TimeFXDrag::motion (GdkEvent* event, bool)
3531 {
3532         RegionView* rv = _primary;
3533         StreamView* cv = rv->get_time_axis_view().view ();
3534
3535         pair<TimeAxisView*, double> const tv = _editor->trackview_by_y_position (grab_y());
3536         int layer = tv.first->layer_display() == Overlaid ? 0 : tv.second;
3537         int layers = tv.first->layer_display() == Overlaid ? 1 : cv->layers();
3538
3539         framepos_t const pf = adjusted_current_frame (event);
3540
3541         if (pf > rv->region()->position()) {
3542                 rv->get_time_axis_view().show_timestretch (rv->region()->position(), pf, layers, layer);
3543         }
3544
3545         show_verbose_cursor_time (pf);
3546 }
3547
3548 void
3549 TimeFXDrag::finished (GdkEvent* /*event*/, bool movement_occurred)
3550 {
3551         _primary->get_time_axis_view().hide_timestretch ();
3552
3553         if (!movement_occurred) {
3554                 return;
3555         }
3556
3557         if (last_pointer_frame() < _primary->region()->position()) {
3558                 /* backwards drag of the left edge - not usable */
3559                 return;
3560         }
3561
3562         framecnt_t newlen = last_pointer_frame() - _primary->region()->position();
3563
3564         float percentage = (double) newlen / (double) _primary->region()->length();
3565
3566 #ifndef USE_RUBBERBAND
3567         // Soundtouch uses percentage / 100 instead of normal (/ 1)
3568         if (_primary->region()->data_type() == DataType::AUDIO) {
3569                 percentage = (float) ((double) newlen - (double) _primary->region()->length()) / ((double) newlen) * 100.0f;
3570         }
3571 #endif
3572
3573         if (!_editor->get_selection().regions.empty()) {
3574                 /* primary will already be included in the selection, and edit
3575                    group shared editing will propagate selection across
3576                    equivalent regions, so just use the current region
3577                    selection.
3578                 */
3579
3580                 if (_editor->time_stretch (_editor->get_selection().regions, percentage) == -1) {
3581                         error << _("An error occurred while executing time stretch operation") << endmsg;
3582                 }
3583         }
3584 }
3585
3586 void
3587 TimeFXDrag::aborted (bool)
3588 {
3589         _primary->get_time_axis_view().hide_timestretch ();
3590 }
3591
3592 ScrubDrag::ScrubDrag (Editor* e, ArdourCanvas::Item* i)
3593         : Drag (e, i)
3594 {
3595         DEBUG_TRACE (DEBUG::Drags, "New ScrubDrag\n");
3596 }
3597
3598 void
3599 ScrubDrag::start_grab (GdkEvent* event, Gdk::Cursor *)
3600 {
3601         Drag::start_grab (event);
3602 }
3603
3604 void
3605 ScrubDrag::motion (GdkEvent* /*event*/, bool)
3606 {
3607         _editor->scrub (adjusted_current_frame (0, false), _drags->current_pointer_x ());
3608 }
3609
3610 void
3611 ScrubDrag::finished (GdkEvent* /*event*/, bool movement_occurred)
3612 {
3613         if (movement_occurred && _editor->session()) {
3614                 /* make sure we stop */
3615                 _editor->session()->request_transport_speed (0.0);
3616         }
3617 }
3618
3619 void
3620 ScrubDrag::aborted (bool)
3621 {
3622         /* XXX: TODO */
3623 }
3624
3625 SelectionDrag::SelectionDrag (Editor* e, ArdourCanvas::Item* i, Operation o)
3626         : Drag (e, i)
3627         , _operation (o)
3628         , _add (false)
3629         , _extend (false)
3630         , _original_pointer_time_axis (-1)
3631         , _last_pointer_time_axis (-1)
3632         , _time_selection_at_start (!_editor->get_selection().time.empty())
3633 {
3634         DEBUG_TRACE (DEBUG::Drags, "New SelectionDrag\n");
3635         
3636         if (_time_selection_at_start) {
3637                 start_at_start = _editor->get_selection().time.start();
3638                 end_at_start = _editor->get_selection().time.end_frame();
3639         }
3640 }
3641
3642 void
3643 SelectionDrag::start_grab (GdkEvent* event, Gdk::Cursor*)
3644 {
3645         if (_editor->session() == 0) {
3646                 return;
3647         }
3648
3649         Gdk::Cursor* cursor = 0;
3650
3651         switch (_operation) {
3652         case CreateSelection:
3653                 if (Keyboard::modifier_state_equals (event->button.state, Keyboard::CopyModifier)) {
3654                         _add = true;
3655                 } else {
3656                         _add = false;
3657                 }
3658                 cursor = _editor->cursors()->selector;
3659                 Drag::start_grab (event, cursor);
3660                 break;
3661
3662         case SelectionStartTrim:
3663                 if (_editor->clicked_axisview) {
3664                         _editor->clicked_axisview->order_selection_trims (_item, true);
3665                 }
3666                 Drag::start_grab (event, _editor->cursors()->left_side_trim);
3667                 break;
3668
3669         case SelectionEndTrim:
3670                 if (_editor->clicked_axisview) {
3671                         _editor->clicked_axisview->order_selection_trims (_item, false);
3672                 }
3673                 Drag::start_grab (event, _editor->cursors()->right_side_trim);
3674                 break;
3675
3676         case SelectionMove:
3677                 Drag::start_grab (event, cursor);
3678                 break;
3679
3680         case SelectionExtend:
3681                 Drag::start_grab (event, cursor);
3682                 break;
3683         }
3684
3685         if (_operation == SelectionMove) {
3686                 show_verbose_cursor_time (_editor->selection->time[_editor->clicked_selection].start);
3687         } else {
3688                 show_verbose_cursor_time (adjusted_current_frame (event));
3689         }
3690
3691         _original_pointer_time_axis = _editor->trackview_by_y_position (_drags->current_pointer_y ()).first->order ();
3692 }
3693
3694 void
3695 SelectionDrag::setup_pointer_frame_offset ()
3696 {
3697         switch (_operation) {
3698         case CreateSelection:
3699                 _pointer_frame_offset = 0;
3700                 break;
3701
3702         case SelectionStartTrim:
3703         case SelectionMove:
3704                 _pointer_frame_offset = raw_grab_frame() - _editor->selection->time[_editor->clicked_selection].start;
3705                 break;
3706
3707         case SelectionEndTrim:
3708                 _pointer_frame_offset = raw_grab_frame() - _editor->selection->time[_editor->clicked_selection].end;
3709                 break;
3710
3711         case SelectionExtend:
3712                 break;
3713         }
3714 }
3715
3716 void
3717 SelectionDrag::motion (GdkEvent* event, bool first_move)
3718 {
3719         framepos_t start = 0;
3720         framepos_t end = 0;
3721         framecnt_t length = 0;
3722         framecnt_t distance = 0;
3723
3724         pair<TimeAxisView*, int> const pending_time_axis = _editor->trackview_by_y_position (_drags->current_pointer_y ());
3725         if (pending_time_axis.first == 0) {
3726                 return;
3727         }
3728
3729         framepos_t const pending_position = adjusted_current_frame (event);
3730
3731         /* only alter selection if things have changed */
3732
3733         if (pending_time_axis.first->order() == _last_pointer_time_axis && pending_position == last_pointer_frame()) {
3734                 return;
3735         }
3736
3737         switch (_operation) {
3738         case CreateSelection:
3739         {
3740                 framepos_t grab = grab_frame ();
3741
3742                 if (first_move) {
3743                         grab = adjusted_current_frame (event, false);
3744                         if (grab < pending_position) {
3745                                 _editor->snap_to (grab, -1);
3746                         }  else {
3747                                 _editor->snap_to (grab, 1);
3748                         }
3749                 }
3750
3751                 if (pending_position < grab) {
3752                         start = pending_position;
3753                         end = grab;
3754                 } else {
3755                         end = pending_position;
3756                         start = grab;
3757                 }
3758
3759                 /* first drag: Either add to the selection
3760                    or create a new selection
3761                 */
3762
3763                 if (first_move) {
3764
3765                         if (_add) {
3766                                 /* adding to the selection */
3767                                 _editor->set_selected_track_as_side_effect (Selection::Add);
3768                                 //_editor->selection->add (_editor->clicked_axisview);
3769                                 _editor->clicked_selection = _editor->selection->add (start, end);
3770                                 _add = false;
3771                         } else {
3772                                 /* new selection */
3773
3774                                 if (_editor->clicked_axisview && !_editor->selection->selected (_editor->clicked_axisview)) {
3775                                         //_editor->selection->set (_editor->clicked_axisview);
3776                                         _editor->set_selected_track_as_side_effect (Selection::Set);
3777                                 }
3778
3779                                 _editor->clicked_selection = _editor->selection->set (start, end);
3780                         }
3781                 }
3782
3783                 /* select the track that we're in */
3784                 if (find (_added_time_axes.begin(), _added_time_axes.end(), pending_time_axis.first) == _added_time_axes.end()) {
3785                         // _editor->set_selected_track_as_side_effect (Selection::Add);
3786                         _editor->selection->add (pending_time_axis.first);
3787                         _added_time_axes.push_back (pending_time_axis.first);
3788                 }
3789
3790                 /* deselect any tracks that this drag no longer includes, being careful to only deselect
3791                    tracks that we selected in the first place.
3792                 */
3793
3794                 int min_order = min (_original_pointer_time_axis, pending_time_axis.first->order());
3795                 int max_order = max (_original_pointer_time_axis, pending_time_axis.first->order());
3796
3797                 list<TimeAxisView*>::iterator i = _added_time_axes.begin();
3798                 while (i != _added_time_axes.end()) {
3799
3800                         list<TimeAxisView*>::iterator tmp = i;
3801                         ++tmp;
3802
3803                         if ((*i)->order() < min_order || (*i)->order() > max_order) {
3804                                 _editor->selection->remove (*i);
3805                                 _added_time_axes.remove (*i);
3806                         }
3807
3808                         i = tmp;
3809                 }
3810
3811         }
3812         break;
3813
3814         case SelectionStartTrim:
3815
3816                 start = _editor->selection->time[_editor->clicked_selection].start;
3817                 end = _editor->selection->time[_editor->clicked_selection].end;
3818
3819                 if (pending_position > end) {
3820                         start = end;
3821                 } else {
3822                         start = pending_position;
3823                 }
3824                 break;
3825
3826         case SelectionEndTrim:
3827
3828                 start = _editor->selection->time[_editor->clicked_selection].start;
3829                 end = _editor->selection->time[_editor->clicked_selection].end;
3830
3831                 if (pending_position < start) {
3832                         end = start;
3833                 } else {
3834                         end = pending_position;
3835                 }
3836
3837                 break;
3838                 
3839         case SelectionMove:
3840
3841                 start = _editor->selection->time[_editor->clicked_selection].start;
3842                 end = _editor->selection->time[_editor->clicked_selection].end;
3843
3844                 length = end - start;
3845                 distance = pending_position - start;
3846                 start = pending_position;
3847                 _editor->snap_to (start);
3848
3849                 end = start + length;
3850
3851                 break;
3852
3853         case SelectionExtend:
3854                 break;
3855         }
3856
3857         if (event->button.x >= _editor->horizontal_position() + _editor->_canvas_width) {
3858                 _editor->start_canvas_autoscroll (1, 0);
3859         }
3860
3861         if (start != end) {
3862                 switch (_operation) {
3863                 case SelectionMove:     
3864                         if (_time_selection_at_start) {
3865                                 _editor->selection->move_time (distance);
3866                         }
3867                         break;
3868                 default:
3869                         _editor->selection->replace (_editor->clicked_selection, start, end);
3870                 }
3871         }
3872
3873         if (_operation == SelectionMove) {
3874                 show_verbose_cursor_time(start);
3875         } else {
3876                 show_verbose_cursor_time(pending_position);
3877         }
3878 }
3879
3880 void
3881 SelectionDrag::finished (GdkEvent* event, bool movement_occurred)
3882 {
3883         Session* s = _editor->session();
3884
3885         if (movement_occurred) {
3886                 motion (event, false);
3887                 /* XXX this is not object-oriented programming at all. ick */
3888                 if (_editor->selection->time.consolidate()) {
3889                         _editor->selection->TimeChanged ();
3890                 }
3891
3892                 /* XXX what if its a music time selection? */
3893                 if (s) {
3894                         if ( s->get_play_range() && s->transport_rolling() ) {
3895                                 s->request_play_range (&_editor->selection->time, true);
3896                         } else {
3897                                 if (Config->get_always_play_range() && !s->transport_rolling()) {
3898                                         s->request_locate (_editor->get_selection().time.start());
3899                                 }
3900                         }
3901                 }
3902
3903         } else {
3904                 /* just a click, no pointer movement.
3905                  */
3906
3907                 if (_operation == SelectionExtend) {
3908                         if (_time_selection_at_start) {
3909                                 framepos_t pos = adjusted_current_frame (event, false);
3910                                 framepos_t start = min (pos, start_at_start);
3911                                 framepos_t end = max (pos, end_at_start);
3912                                 _editor->selection->set (start, end);
3913                         }
3914                 } else {
3915                         if (Keyboard::modifier_state_equals (event->button.state, Keyboard::CopyModifier)) {
3916                                 if (_editor->clicked_selection) {
3917                                         _editor->selection->remove (_editor->clicked_selection);
3918                                 }
3919                         } else {
3920                                 if (!_editor->clicked_selection) {
3921                                         _editor->selection->clear_time();
3922                                 }
3923                         }
3924                 }
3925
3926                 if (_editor->clicked_axisview && !_editor->selection->selected (_editor->clicked_axisview)) {
3927                         _editor->selection->set (_editor->clicked_axisview);
3928                 }
3929                         
3930                 if (s && s->get_play_range () && s->transport_rolling()) {
3931                         s->request_stop (false, false);
3932                 }
3933
3934         }
3935
3936         _editor->stop_canvas_autoscroll ();
3937         _editor->clicked_selection = 0;
3938 }
3939
3940 void
3941 SelectionDrag::aborted (bool)
3942 {
3943         /* XXX: TODO */
3944 }
3945
3946 RangeMarkerBarDrag::RangeMarkerBarDrag (Editor* e, ArdourCanvas::Item* i, Operation o)
3947         : Drag (e, i),
3948           _operation (o),
3949           _copy (false)
3950 {
3951         DEBUG_TRACE (DEBUG::Drags, "New RangeMarkerBarDrag\n");
3952
3953         _drag_rect = new ArdourCanvas::SimpleRect (*_editor->time_line_group, 0.0, 0.0, 0.0,
3954                                                    physical_screen_height (_editor->get_window()));
3955         _drag_rect->hide ();
3956
3957         _drag_rect->property_fill_color_rgba() = ARDOUR_UI::config()->canvasvar_RangeDragRect.get();
3958         _drag_rect->property_outline_color_rgba() = ARDOUR_UI::config()->canvasvar_RangeDragRect.get();
3959 }
3960
3961 void
3962 RangeMarkerBarDrag::start_grab (GdkEvent* event, Gdk::Cursor *)
3963 {
3964         if (_editor->session() == 0) {
3965                 return;
3966         }
3967
3968         Gdk::Cursor* cursor = 0;
3969
3970         if (!_editor->temp_location) {
3971                 _editor->temp_location = new Location (*_editor->session());
3972         }
3973
3974         switch (_operation) {
3975         case CreateRangeMarker:
3976         case CreateTransportMarker:
3977         case CreateCDMarker:
3978
3979                 if (Keyboard::modifier_state_equals (event->button.state, Keyboard::TertiaryModifier)) {
3980                         _copy = true;
3981                 } else {
3982                         _copy = false;
3983                 }
3984                 cursor = _editor->cursors()->selector;
3985                 break;
3986         }
3987
3988         Drag::start_grab (event, cursor);
3989
3990         show_verbose_cursor_time (adjusted_current_frame (event));
3991 }
3992
3993 void
3994 RangeMarkerBarDrag::motion (GdkEvent* event, bool first_move)
3995 {
3996         framepos_t start = 0;
3997         framepos_t end = 0;
3998         ArdourCanvas::SimpleRect *crect;
3999
4000         switch (_operation) {
4001         case CreateRangeMarker:
4002                 crect = _editor->range_bar_drag_rect;
4003                 break;
4004         case CreateTransportMarker:
4005                 crect = _editor->transport_bar_drag_rect;
4006                 break;
4007         case CreateCDMarker:
4008                 crect = _editor->cd_marker_bar_drag_rect;
4009                 break;
4010         default:
4011                 error << string_compose (_("programming_error: %1"), "Error: unknown range marker op passed to Editor::drag_range_markerbar_op ()") << endmsg;
4012                 return;
4013                 break;
4014         }
4015
4016         framepos_t const pf = adjusted_current_frame (event);
4017
4018         if (_operation == CreateRangeMarker || _operation == CreateTransportMarker || _operation == CreateCDMarker) {
4019                 framepos_t grab = grab_frame ();
4020                 _editor->snap_to (grab);
4021
4022                 if (pf < grab_frame()) {
4023                         start = pf;
4024                         end = grab;
4025                 } else {
4026                         end = pf;
4027                         start = grab;
4028                 }
4029
4030                 /* first drag: Either add to the selection
4031                    or create a new selection.
4032                 */
4033
4034                 if (first_move) {
4035
4036                         _editor->temp_location->set (start, end);
4037
4038                         crect->show ();
4039
4040                         update_item (_editor->temp_location);
4041                         _drag_rect->show();
4042                         //_drag_rect->raise_to_top();
4043
4044                 }
4045         }
4046
4047         if (event->button.x >= _editor->horizontal_position() + _editor->_canvas_width) {
4048                 _editor->start_canvas_autoscroll (1, 0);
4049         }
4050
4051         if (start != end) {
4052                 _editor->temp_location->set (start, end);
4053
4054                 double x1 = _editor->frame_to_pixel (start);
4055                 double x2 = _editor->frame_to_pixel (end);
4056                 crect->property_x1() = x1;
4057                 crect->property_x2() = x2;
4058
4059                 update_item (_editor->temp_location);
4060         }
4061
4062         show_verbose_cursor_time (pf);
4063
4064 }
4065
4066 void
4067 RangeMarkerBarDrag::finished (GdkEvent* event, bool movement_occurred)
4068 {
4069         Location * newloc = 0;
4070         string rangename;
4071         int flags;
4072
4073         if (movement_occurred) {
4074                 motion (event, false);
4075                 _drag_rect->hide();
4076
4077                 switch (_operation) {
4078                 case CreateRangeMarker:
4079                 case CreateCDMarker:
4080                     {
4081                         _editor->begin_reversible_command (_("new range marker"));
4082                         XMLNode &before = _editor->session()->locations()->get_state();
4083                         _editor->session()->locations()->next_available_name(rangename,"unnamed");
4084                         if (_operation == CreateCDMarker) {
4085                                 flags = Location::IsRangeMarker | Location::IsCDMarker;
4086                                 _editor->cd_marker_bar_drag_rect->hide();
4087                         }
4088                         else {
4089                                 flags = Location::IsRangeMarker;
4090                                 _editor->range_bar_drag_rect->hide();
4091                         }
4092                         newloc = new Location (
4093                                 *_editor->session(), _editor->temp_location->start(), _editor->temp_location->end(), rangename, (Location::Flags) flags
4094                                 );
4095
4096                         _editor->session()->locations()->add (newloc, true);
4097                         XMLNode &after = _editor->session()->locations()->get_state();
4098                         _editor->session()->add_command(new MementoCommand<Locations>(*(_editor->session()->locations()), &before, &after));
4099                         _editor->commit_reversible_command ();
4100                         break;
4101                     }
4102
4103                 case CreateTransportMarker:
4104                         // popup menu to pick loop or punch
4105                         _editor->new_transport_marker_context_menu (&event->button, _item);
4106                         break;
4107                 }
4108         } else {
4109                 /* just a click, no pointer movement. remember that context menu stuff was handled elsewhere */
4110
4111                 if (Keyboard::no_modifier_keys_pressed (&event->button) && _operation != CreateCDMarker) {
4112
4113                         framepos_t start;
4114                         framepos_t end;
4115
4116                         _editor->session()->locations()->marks_either_side (grab_frame(), start, end);
4117
4118                         if (end == max_framepos) {
4119                                 end = _editor->session()->current_end_frame ();
4120                         }
4121
4122                         if (start == max_framepos) {
4123                                 start = _editor->session()->current_start_frame ();
4124                         }
4125
4126                         switch (_editor->mouse_mode) {
4127                         case MouseObject:
4128                                 /* find the two markers on either side and then make the selection from it */
4129                                 _editor->select_all_within (start, end, 0.0f, FLT_MAX, _editor->track_views, Selection::Set, false);
4130                                 break;
4131
4132                         case MouseRange:
4133                                 /* find the two markers on either side of the click and make the range out of it */
4134                                 _editor->selection->set (start, end);
4135                                 break;
4136
4137                         default:
4138                                 break;
4139                         }
4140                 }
4141         }
4142
4143         _editor->stop_canvas_autoscroll ();
4144 }
4145
4146 void
4147 RangeMarkerBarDrag::aborted (bool)
4148 {
4149         /* XXX: TODO */
4150 }
4151
4152 void
4153 RangeMarkerBarDrag::update_item (Location* location)
4154 {
4155         double const x1 = _editor->frame_to_pixel (location->start());
4156         double const x2 = _editor->frame_to_pixel (location->end());
4157
4158         _drag_rect->property_x1() = x1;
4159         _drag_rect->property_x2() = x2;
4160 }
4161
4162 MouseZoomDrag::MouseZoomDrag (Editor* e, ArdourCanvas::Item* i)
4163         : Drag (e, i)
4164         , _zoom_out (false)
4165 {
4166         DEBUG_TRACE (DEBUG::Drags, "New MouseZoomDrag\n");
4167 }
4168
4169 void
4170 MouseZoomDrag::start_grab (GdkEvent* event, Gdk::Cursor *)
4171 {
4172         if (Keyboard::the_keyboard().key_is_down (GDK_Control_L)) {
4173                 Drag::start_grab (event, _editor->cursors()->zoom_out);
4174                 _zoom_out = true;
4175         } else {
4176                 Drag::start_grab (event, _editor->cursors()->zoom_in);
4177                 _zoom_out = false;
4178         }
4179
4180         show_verbose_cursor_time (adjusted_current_frame (event));
4181 }
4182
4183 void
4184 MouseZoomDrag::motion (GdkEvent* event, bool first_move)
4185 {
4186         framepos_t start;
4187         framepos_t end;
4188
4189         framepos_t const pf = adjusted_current_frame (event);
4190
4191         framepos_t grab = grab_frame ();
4192         _editor->snap_to_with_modifier (grab, event);
4193
4194         /* base start and end on initial click position */
4195         if (pf < grab) {
4196                 start = pf;
4197                 end = grab;
4198         } else {
4199                 end = pf;
4200                 start = grab;
4201         }
4202
4203         if (start != end) {
4204
4205                 if (first_move) {
4206                         _editor->zoom_rect->show();
4207                         _editor->zoom_rect->raise_to_top();
4208                 }
4209
4210                 _editor->reposition_zoom_rect(start, end);
4211
4212                 show_verbose_cursor_time (pf);
4213         }
4214 }
4215
4216 void
4217 MouseZoomDrag::finished (GdkEvent* event, bool movement_occurred)
4218 {
4219         if (movement_occurred) {
4220                 motion (event, false);
4221
4222                 if (grab_frame() < last_pointer_frame()) {
4223                         _editor->temporal_zoom_by_frame (grab_frame(), last_pointer_frame());
4224                 } else {
4225                         _editor->temporal_zoom_by_frame (last_pointer_frame(), grab_frame());
4226                 }
4227         } else {
4228                 if (Keyboard::the_keyboard().key_is_down (GDK_Shift_L)) {
4229                         _editor->tav_zoom_step (_zoom_out);
4230                 } else {
4231                         _editor->temporal_zoom_to_frame (_zoom_out, grab_frame());
4232                 }
4233         }
4234
4235         _editor->zoom_rect->hide();
4236 }
4237
4238 void
4239 MouseZoomDrag::aborted (bool)
4240 {
4241         _editor->zoom_rect->hide ();
4242 }
4243
4244 NoteDrag::NoteDrag (Editor* e, ArdourCanvas::Item* i)
4245         : Drag (e, i)
4246         , _cumulative_dx (0)
4247         , _cumulative_dy (0)
4248 {
4249         DEBUG_TRACE (DEBUG::Drags, "New NoteDrag\n");
4250
4251         _primary = dynamic_cast<CanvasNoteEvent*> (_item);
4252         _region = &_primary->region_view ();
4253         _note_height = _region->midi_stream_view()->note_height ();
4254 }
4255
4256 void
4257 NoteDrag::start_grab (GdkEvent* event, Gdk::Cursor *)
4258 {
4259         Drag::start_grab (event);
4260
4261         if (!(_was_selected = _primary->selected())) {
4262
4263                 /* tertiary-click means extend selection - we'll do that on button release,
4264                    so don't add it here, because otherwise we make it hard to figure
4265                    out the "extend-to" range.
4266                 */
4267
4268                 bool extend = Keyboard::modifier_state_equals (event->button.state, Keyboard::TertiaryModifier);
4269
4270                 if (!extend) {
4271                         bool add = Keyboard::modifier_state_equals (event->button.state, Keyboard::PrimaryModifier);
4272
4273                         if (add) {
4274                                 _region->note_selected (_primary, true);
4275                         } else {
4276                                 _region->unique_select (_primary);
4277                         }
4278                 }
4279         }
4280 }
4281
4282 /** @return Current total drag x change in frames */
4283 frameoffset_t
4284 NoteDrag::total_dx () const
4285 {
4286         /* dx in frames */
4287         frameoffset_t const dx = _editor->unit_to_frame (_drags->current_pointer_x() - grab_x());
4288
4289         /* primary note time */
4290         frameoffset_t const n = _region->source_beats_to_absolute_frames (_primary->note()->time ());
4291
4292         /* new time of the primary note in session frames */
4293         frameoffset_t st = n + dx;
4294
4295         framepos_t const rp = _region->region()->position ();
4296
4297         /* prevent the note being dragged earlier than the region's position */
4298         st = max (st, rp);
4299
4300         /* snap and return corresponding delta */
4301         return _region->snap_frame_to_frame (st - rp) + rp - n;
4302 }
4303
4304 /** @return Current total drag y change in note number */
4305 int8_t
4306 NoteDrag::total_dy () const
4307 {
4308         MidiStreamView* msv = _region->midi_stream_view ();
4309         double const y = _region->midi_view()->y_position ();
4310         /* new current note */
4311         uint8_t n = msv->y_to_note (_drags->current_pointer_y () - y);
4312         /* clamp */
4313         n = max (msv->lowest_note(), n);
4314         n = min (msv->highest_note(), n);
4315         /* and work out delta */
4316         return n - msv->y_to_note (grab_y() - y);
4317 }
4318
4319 void
4320 NoteDrag::motion (GdkEvent *, bool)
4321 {
4322         /* Total change in x and y since the start of the drag */
4323         frameoffset_t const dx = total_dx ();
4324         int8_t const dy = total_dy ();
4325
4326         /* Now work out what we have to do to the note canvas items to set this new drag delta */
4327         double const tdx = _editor->frame_to_unit (dx) - _cumulative_dx;
4328         double const tdy = -dy * _note_height - _cumulative_dy;
4329
4330         if (tdx || tdy) {
4331                 _cumulative_dx += tdx;
4332                 _cumulative_dy += tdy;
4333
4334                 int8_t note_delta = total_dy();
4335
4336                 _region->move_selection (tdx, tdy, note_delta);
4337
4338                 /* the new note value may be the same as the old one, but we
4339                  * don't know what that means because the selection may have
4340                  * involved more than one note and we might be doing something
4341                  * odd with them. so show the note value anyway, always.
4342                  */
4343
4344                 char buf[12];
4345                 uint8_t new_note = min (max (_primary->note()->note() + note_delta, 0), 127);
4346                 
4347                 snprintf (buf, sizeof (buf), "%s (%d)", Evoral::midi_note_name (new_note).c_str(),
4348                           (int) floor (new_note));
4349
4350                 show_verbose_cursor_text (buf);
4351         }
4352 }
4353
4354 void
4355 NoteDrag::finished (GdkEvent* ev, bool moved)
4356 {
4357         if (!moved) {
4358                 /* no motion - select note */
4359                 
4360                 if (_editor->current_mouse_mode() == Editing::MouseObject ||
4361                     _editor->current_mouse_mode() == Editing::MouseDraw) {
4362                         
4363                         if (_was_selected) {
4364                                 bool add = Keyboard::modifier_state_equals (ev->button.state, Keyboard::PrimaryModifier);
4365                                 if (add) {
4366                                         _region->note_deselected (_primary);
4367                                 }
4368                         } else {
4369                                 bool extend = Keyboard::modifier_state_equals (ev->button.state, Keyboard::TertiaryModifier);
4370                                 bool add = Keyboard::modifier_state_equals (ev->button.state, Keyboard::PrimaryModifier);
4371
4372                                 if (!extend && !add && _region->selection_size() > 1) {
4373                                         _region->unique_select (_primary);
4374                                 } else if (extend) {
4375                                         _region->note_selected (_primary, true, true);
4376                                 } else {
4377                                         /* it was added during button press */
4378                                 }
4379                         }
4380                 }
4381         } else {
4382                 _region->note_dropped (_primary, total_dx(), total_dy());
4383         }
4384 }
4385
4386 void
4387 NoteDrag::aborted (bool)
4388 {
4389         /* XXX: TODO */
4390 }
4391
4392 /** Make an AutomationRangeDrag for lines in an AutomationTimeAxisView */
4393 AutomationRangeDrag::AutomationRangeDrag (Editor* editor, AutomationTimeAxisView* atv, list<AudioRange> const & r)
4394         : Drag (editor, atv->base_item ())
4395         , _ranges (r)
4396         , _nothing_to_drag (false)
4397 {
4398         DEBUG_TRACE (DEBUG::Drags, "New AutomationRangeDrag\n");
4399         y_origin = atv->y_position();
4400         setup (atv->lines ());
4401 }
4402
4403 /** Make an AutomationRangeDrag for region gain lines */
4404 AutomationRangeDrag::AutomationRangeDrag (Editor* editor, AudioRegionView* rv, list<AudioRange> const & r)
4405         : Drag (editor, rv->get_canvas_group ())
4406         , _ranges (r)
4407         , _nothing_to_drag (false)
4408 {
4409         DEBUG_TRACE (DEBUG::Drags, "New AutomationRangeDrag\n");
4410
4411         list<boost::shared_ptr<AutomationLine> > lines;
4412         lines.push_back (rv->get_gain_line ());
4413         y_origin = rv->get_time_axis_view().y_position();
4414         setup (lines);
4415 }
4416
4417 /** @param lines AutomationLines to drag.
4418  *  @param offset Offset from the session start to the points in the AutomationLines.
4419  */
4420 void
4421 AutomationRangeDrag::setup (list<boost::shared_ptr<AutomationLine> > const & lines)
4422 {
4423         /* find the lines that overlap the ranges being dragged */
4424         list<boost::shared_ptr<AutomationLine> >::const_iterator i = lines.begin ();
4425         while (i != lines.end ()) {
4426                 list<boost::shared_ptr<AutomationLine> >::const_iterator j = i;
4427                 ++j;
4428
4429                 pair<framepos_t, framepos_t> r = (*i)->get_point_x_range ();
4430
4431                 /* check this range against all the AudioRanges that we are using */
4432                 list<AudioRange>::const_iterator k = _ranges.begin ();
4433                 while (k != _ranges.end()) {
4434                         if (k->coverage (r.first, r.second) != Evoral::OverlapNone) {
4435                                 break;
4436                         }
4437                         ++k;
4438                 }
4439
4440                 /* add it to our list if it overlaps at all */
4441                 if (k != _ranges.end()) {
4442                         Line n;
4443                         n.line = *i;
4444                         n.state = 0;
4445                         n.range = r;
4446                         _lines.push_back (n);
4447                 }
4448
4449                 i = j;
4450         }
4451
4452         /* Now ::lines contains the AutomationLines that somehow overlap our drag */
4453 }
4454
4455 double
4456 AutomationRangeDrag::y_fraction (boost::shared_ptr<AutomationLine> line, double global_y) const
4457 {
4458         return 1.0 - ((global_y - y_origin) / line->height());
4459 }
4460
4461 void
4462 AutomationRangeDrag::start_grab (GdkEvent* event, Gdk::Cursor* cursor)
4463 {
4464         Drag::start_grab (event, cursor);
4465
4466         /* Get line states before we start changing things */
4467         for (list<Line>::iterator i = _lines.begin(); i != _lines.end(); ++i) {
4468                 i->state = &i->line->get_state ();
4469                 i->original_fraction = y_fraction (i->line, _drags->current_pointer_y());
4470         }
4471
4472         if (_ranges.empty()) {
4473
4474                 /* No selected time ranges: drag all points */
4475                 for (list<Line>::iterator i = _lines.begin(); i != _lines.end(); ++i) {
4476                         uint32_t const N = i->line->npoints ();
4477                         for (uint32_t j = 0; j < N; ++j) {
4478                                 i->points.push_back (i->line->nth (j));
4479                         }
4480                 }
4481
4482         } else {
4483
4484                 for (list<AudioRange>::const_iterator i = _ranges.begin(); i != _ranges.end(); ++i) {
4485
4486                         framecnt_t const half = (i->start + i->end) / 2;
4487
4488                         /* find the line that this audio range starts in */
4489                         list<Line>::iterator j = _lines.begin();
4490                         while (j != _lines.end() && (j->range.first > i->start || j->range.second < i->start)) {
4491                                 ++j;
4492                         }
4493
4494                         if (j != _lines.end()) {
4495                                 boost::shared_ptr<AutomationList> the_list = j->line->the_list ();
4496
4497                                 /* j is the line that this audio range starts in; fade into it;
4498                                    64 samples length plucked out of thin air.
4499                                 */
4500
4501                                 framepos_t a = i->start + 64;
4502                                 if (a > half) {
4503                                         a = half;
4504                                 }
4505
4506                                 double const p = j->line->time_converter().from (i->start - j->line->time_converter().origin_b ());
4507                                 double const q = j->line->time_converter().from (a - j->line->time_converter().origin_b ());
4508
4509                                 the_list->add (p, the_list->eval (p));
4510                                 the_list->add (q, the_list->eval (q));
4511                         }
4512
4513                         /* same thing for the end */
4514
4515                         j = _lines.begin();
4516                         while (j != _lines.end() && (j->range.first > i->end || j->range.second < i->end)) {
4517                                 ++j;
4518                         }
4519
4520                         if (j != _lines.end()) {
4521                                 boost::shared_ptr<AutomationList> the_list = j->line->the_list ();
4522
4523                                 /* j is the line that this audio range starts in; fade out of it;
4524                                    64 samples length plucked out of thin air.
4525                                 */
4526
4527                                 framepos_t b = i->end - 64;
4528                                 if (b < half) {
4529                                         b = half;
4530                                 }
4531
4532                                 double const p = j->line->time_converter().from (b - j->line->time_converter().origin_b ());
4533                                 double const q = j->line->time_converter().from (i->end - j->line->time_converter().origin_b ());
4534
4535                                 the_list->add (p, the_list->eval (p));
4536                                 the_list->add (q, the_list->eval (q));
4537                         }
4538                 }
4539
4540                 _nothing_to_drag = true;
4541
4542                 /* Find all the points that should be dragged and put them in the relevant
4543                    points lists in the Line structs.
4544                 */
4545
4546                 for (list<Line>::iterator i = _lines.begin(); i != _lines.end(); ++i) {
4547
4548                         uint32_t const N = i->line->npoints ();
4549                         for (uint32_t j = 0; j < N; ++j) {
4550
4551                                 /* here's a control point on this line */
4552                                 ControlPoint* p = i->line->nth (j);
4553                                 double const w = i->line->time_converter().to ((*p->model())->when) + i->line->time_converter().origin_b ();
4554
4555                                 /* see if it's inside a range */
4556                                 list<AudioRange>::const_iterator k = _ranges.begin ();
4557                                 while (k != _ranges.end() && (k->start >= w || k->end <= w)) {
4558                                         ++k;
4559                                 }
4560
4561                                 if (k != _ranges.end()) {
4562                                         /* dragging this point */
4563                                         _nothing_to_drag = false;
4564                                         i->points.push_back (p);
4565                                 }
4566                         }
4567                 }
4568         }
4569
4570         if (_nothing_to_drag) {
4571                 return;
4572         }
4573
4574         for (list<Line>::iterator i = _lines.begin(); i != _lines.end(); ++i) {
4575                 i->line->start_drag_multiple (i->points, y_fraction (i->line, _drags->current_pointer_y()), i->state);
4576         }
4577 }
4578
4579 void
4580 AutomationRangeDrag::motion (GdkEvent*, bool /*first_move*/)
4581 {
4582         if (_nothing_to_drag) {
4583                 return;
4584         }
4585
4586         for (list<Line>::iterator l = _lines.begin(); l != _lines.end(); ++l) {
4587                 float const f = y_fraction (l->line, _drags->current_pointer_y());
4588                 /* we are ignoring x position for this drag, so we can just pass in anything */
4589                 uint32_t ignored;
4590                 l->line->drag_motion (0, f, true, false, ignored);
4591                 show_verbose_cursor_text (l->line->get_verbose_cursor_relative_string (l->original_fraction, f));
4592         }
4593 }
4594
4595 void
4596 AutomationRangeDrag::finished (GdkEvent* event, bool)
4597 {
4598         if (_nothing_to_drag) {
4599                 return;
4600         }
4601
4602         motion (event, false);
4603         for (list<Line>::iterator i = _lines.begin(); i != _lines.end(); ++i) {
4604                 i->line->end_drag (false, 0);
4605         }
4606
4607         _editor->session()->commit_reversible_command ();
4608 }
4609
4610 void
4611 AutomationRangeDrag::aborted (bool)
4612 {
4613         for (list<Line>::iterator i = _lines.begin(); i != _lines.end(); ++i) {
4614                 i->line->reset ();
4615         }
4616 }
4617
4618 DraggingView::DraggingView (RegionView* v, RegionDrag* parent)
4619         : view (v)
4620 {
4621         time_axis_view = parent->find_time_axis_view (&v->get_time_axis_view ());
4622         layer = v->region()->layer ();
4623         initial_y = v->get_canvas_group()->property_y ();
4624         initial_playlist = v->region()->playlist ();
4625         initial_position = v->region()->position ();
4626         initial_end = v->region()->position () + v->region()->length ();
4627 }
4628
4629 PatchChangeDrag::PatchChangeDrag (Editor* e, CanvasPatchChange* i, MidiRegionView* r)
4630         : Drag (e, i)
4631         , _region_view (r)
4632         , _patch_change (i)
4633         , _cumulative_dx (0)
4634 {
4635         DEBUG_TRACE (DEBUG::Drags, string_compose ("New PatchChangeDrag, patch @ %1, grab @ %2\n",
4636                                                    _region_view->source_beats_to_absolute_frames (_patch_change->patch()->time()),
4637                                                    grab_frame()));
4638 }
4639
4640 void
4641 PatchChangeDrag::motion (GdkEvent* ev, bool)
4642 {
4643         framepos_t f = adjusted_current_frame (ev);
4644         boost::shared_ptr<Region> r = _region_view->region ();
4645         f = max (f, r->position ());
4646         f = min (f, r->last_frame ());
4647
4648         framecnt_t const dxf = f - grab_frame(); // permitted dx in frames
4649         double const dxu = _editor->frame_to_unit (dxf); // permitted fx in units
4650         _patch_change->move (dxu - _cumulative_dx, 0);
4651         _cumulative_dx = dxu;
4652 }
4653
4654 void
4655 PatchChangeDrag::finished (GdkEvent* ev, bool movement_occurred)
4656 {
4657         if (!movement_occurred) {
4658                 return;
4659         }
4660
4661         boost::shared_ptr<Region> r (_region_view->region ());
4662         framepos_t f = adjusted_current_frame (ev);
4663         f = max (f, r->position ());
4664         f = min (f, r->last_frame ());
4665
4666         _region_view->move_patch_change (
4667                 *_patch_change,
4668                 _region_view->region_frames_to_region_beats (f - (r->position() - r->start()))
4669                 );
4670 }
4671
4672 void
4673 PatchChangeDrag::aborted (bool)
4674 {
4675         _patch_change->move (-_cumulative_dx, 0);
4676 }
4677
4678 void
4679 PatchChangeDrag::setup_pointer_frame_offset ()
4680 {
4681         boost::shared_ptr<Region> region = _region_view->region ();
4682         _pointer_frame_offset = raw_grab_frame() - _region_view->source_beats_to_absolute_frames (_patch_change->patch()->time());
4683 }
4684
4685 MidiRubberbandSelectDrag::MidiRubberbandSelectDrag (Editor* e, MidiRegionView* rv)
4686         : RubberbandSelectDrag (e, rv->get_canvas_frame ())
4687         , _region_view (rv)
4688 {
4689
4690 }
4691
4692 void
4693 MidiRubberbandSelectDrag::select_things (int button_state, framepos_t x1, framepos_t x2, double y1, double y2, bool /*drag_in_progress*/)
4694 {
4695         framepos_t const p = _region_view->region()->position ();
4696         double const y = _region_view->midi_view()->y_position ();
4697
4698         x1 = max ((framepos_t) 0, x1 - p);
4699         x2 = max ((framepos_t) 0, x2 - p);
4700         y1 = max (0.0, y1 - y);
4701         y2 = max (0.0, y2 - y);
4702         
4703         _region_view->update_drag_selection (
4704                 _editor->frame_to_pixel (x1),
4705                 _editor->frame_to_pixel (x2),
4706                 y1,
4707                 y2,
4708                 Keyboard::modifier_state_contains (button_state, Keyboard::TertiaryModifier)
4709                 );
4710 }
4711
4712 void
4713 MidiRubberbandSelectDrag::deselect_things ()
4714 {
4715         /* XXX */
4716 }
4717
4718 MidiVerticalSelectDrag::MidiVerticalSelectDrag (Editor* e, MidiRegionView* rv)
4719         : RubberbandSelectDrag (e, rv->get_canvas_frame ())
4720         , _region_view (rv)
4721 {
4722         _vertical_only = true;
4723 }
4724
4725 void
4726 MidiVerticalSelectDrag::select_things (int button_state, framepos_t /*x1*/, framepos_t /*x2*/, double y1, double y2, bool /*drag_in_progress*/)
4727 {
4728         double const y = _region_view->midi_view()->y_position ();
4729
4730         y1 = max (0.0, y1 - y);
4731         y2 = max (0.0, y2 - y);
4732         
4733         _region_view->update_vertical_drag_selection (
4734                 y1,
4735                 y2,
4736                 Keyboard::modifier_state_contains (button_state, Keyboard::TertiaryModifier)
4737                 );
4738 }
4739
4740 void
4741 MidiVerticalSelectDrag::deselect_things ()
4742 {
4743         /* XXX */
4744 }
4745
4746 EditorRubberbandSelectDrag::EditorRubberbandSelectDrag (Editor* e, ArdourCanvas::Item* i)
4747         : RubberbandSelectDrag (e, i)
4748 {
4749
4750 }
4751
4752 void
4753 EditorRubberbandSelectDrag::select_things (int button_state, framepos_t x1, framepos_t x2, double y1, double y2, bool drag_in_progress)
4754 {
4755         if (drag_in_progress) {
4756                 /* We just want to select things at the end of the drag, not during it */
4757                 return;
4758         }
4759         
4760         Selection::Operation op = ArdourKeyboard::selection_type (button_state);
4761         
4762         _editor->begin_reversible_command (_("rubberband selection"));
4763         _editor->select_all_within (x1, x2 - 1, y1, y2, _editor->track_views, op, false);
4764         _editor->commit_reversible_command ();
4765 }
4766
4767 void
4768 EditorRubberbandSelectDrag::deselect_things ()
4769 {
4770         if (!getenv("ARDOUR_SAE")) {
4771                 _editor->selection->clear_tracks();
4772         }
4773         _editor->selection->clear_regions();
4774         _editor->selection->clear_points ();
4775         _editor->selection->clear_lines ();
4776 }
4777
4778 NoteCreateDrag::NoteCreateDrag (Editor* e, ArdourCanvas::Item* i, MidiRegionView* rv)
4779         : Drag (e, i)
4780         , _region_view (rv)
4781         , _drag_rect (0)
4782 {
4783         
4784 }
4785
4786 NoteCreateDrag::~NoteCreateDrag ()
4787 {
4788         delete _drag_rect;
4789 }
4790
4791 framecnt_t
4792 NoteCreateDrag::grid_frames (framepos_t t) const
4793 {
4794         bool success;
4795         Evoral::MusicalTime grid_beats = _editor->get_grid_type_as_beats (success, t);
4796         if (!success) {
4797                 grid_beats = 1;
4798         }
4799
4800         return _region_view->region_beats_to_region_frames (grid_beats);
4801 }
4802
4803 void
4804 NoteCreateDrag::start_grab (GdkEvent* event, Gdk::Cursor* cursor)
4805 {
4806         Drag::start_grab (event, cursor);
4807                                                  
4808         _drag_rect = new ArdourCanvas::SimpleRect (*_region_view->get_canvas_group ());
4809
4810         framepos_t pf = _drags->current_pointer_frame ();
4811         framecnt_t const g = grid_frames (pf);
4812
4813         /* Hack so that we always snap to the note that we are over, instead of snapping
4814            to the next one if we're more than halfway through the one we're over.
4815         */
4816         if (_editor->snap_mode() == SnapNormal && pf > g / 2) {
4817                 pf -= g / 2;
4818         }
4819
4820         _note[0] = adjusted_frame (pf, event) - _region_view->region()->position ();
4821
4822         MidiStreamView* sv = _region_view->midi_stream_view ();
4823         double const x = _editor->frame_to_pixel (_note[0]);
4824         double const y = sv->note_to_y (sv->y_to_note (y_to_region (event->button.y)));
4825
4826         _drag_rect->property_x1() = x;
4827         _drag_rect->property_y1() = y;
4828         _drag_rect->property_x2() = x;
4829         _drag_rect->property_y2() = y + floor (_region_view->midi_stream_view()->note_height ());
4830
4831         _drag_rect->property_outline_what() = 0xff;
4832         _drag_rect->property_outline_color_rgba() = 0xffffff99;
4833         _drag_rect->property_fill_color_rgba()    = 0xffffff66;
4834 }
4835
4836 void
4837 NoteCreateDrag::motion (GdkEvent* event, bool)
4838 {
4839         _note[1] = max ((framepos_t)0, adjusted_current_frame (event) - _region_view->region()->position ());
4840         double const x = _editor->frame_to_pixel (_note[1]);
4841         if (_note[1] > _note[0]) {
4842                 _drag_rect->property_x2() = x;
4843         } else {
4844                 _drag_rect->property_x1() = x;
4845         }
4846 }
4847
4848 void
4849 NoteCreateDrag::finished (GdkEvent*, bool had_movement)
4850 {
4851         if (!had_movement) {
4852                 return;
4853         }
4854         
4855         framepos_t const start = min (_note[0], _note[1]);
4856         framecnt_t length = (framecnt_t) fabs (_note[0] - _note[1]);
4857
4858         framecnt_t const g = grid_frames (start);
4859         double const one_tick = 1 / Timecode::BBT_Time::ticks_per_beat;
4860         
4861         if (_editor->snap_mode() == SnapNormal && length < g) {
4862                 length = g - one_tick;
4863         }
4864
4865         double const length_beats = max (one_tick, _region_view->region_frames_to_region_beats (length));
4866
4867         _region_view->create_note_at (start, _drag_rect->property_y1(), length_beats, false);
4868 }
4869
4870 double
4871 NoteCreateDrag::y_to_region (double y) const
4872 {
4873         double x = 0;
4874         _region_view->get_canvas_group()->w2i (x, y);
4875         return y;
4876 }
4877
4878 void
4879 NoteCreateDrag::aborted (bool)
4880 {
4881         
4882 }
4883
4884 CrossfadeEdgeDrag::CrossfadeEdgeDrag (Editor* e, AudioRegionView* rv, ArdourCanvas::Item* i, bool start_yn)
4885         : Drag (e, i)
4886         , arv (rv)
4887         , start (start_yn)
4888 {
4889         std::cout << ("CrossfadeEdgeDrag is DEPRECATED.  See TrimDrag::preserve_fade_anchor") << endl;
4890 }
4891
4892 void
4893 CrossfadeEdgeDrag::start_grab (GdkEvent* event, Gdk::Cursor *cursor)
4894 {
4895         Drag::start_grab (event, cursor);
4896 }
4897
4898 void
4899 CrossfadeEdgeDrag::motion (GdkEvent*, bool)
4900 {
4901         double distance;
4902         double new_length;
4903         framecnt_t len;
4904
4905         boost::shared_ptr<AudioRegion> ar (arv->audio_region());
4906
4907         if (start) {
4908                 distance = _drags->current_pointer_x() - grab_x();
4909                 len = ar->fade_in()->back()->when;
4910         } else {
4911                 distance = grab_x() - _drags->current_pointer_x();
4912                 len = ar->fade_out()->back()->when;
4913         }
4914
4915         /* how long should it be ? */
4916
4917         new_length = len + _editor->unit_to_frame (distance);
4918
4919         /* now check with the region that this is legal */
4920
4921         new_length = ar->verify_xfade_bounds (new_length, start);
4922
4923         if (start) {
4924                 arv->redraw_start_xfade_to (ar, new_length);
4925         } else {
4926                 arv->redraw_end_xfade_to (ar, new_length);
4927         }
4928 }
4929
4930 void
4931 CrossfadeEdgeDrag::finished (GdkEvent*, bool)
4932 {
4933         double distance;
4934         double new_length;
4935         framecnt_t len;
4936
4937         boost::shared_ptr<AudioRegion> ar (arv->audio_region());
4938
4939         if (start) {
4940                 distance = _drags->current_pointer_x() - grab_x();
4941                 len = ar->fade_in()->back()->when;
4942         } else {
4943                 distance = grab_x() - _drags->current_pointer_x();
4944                 len = ar->fade_out()->back()->when;
4945         }
4946
4947         new_length = ar->verify_xfade_bounds (len + _editor->unit_to_frame (distance), start);
4948         
4949         _editor->begin_reversible_command ("xfade trim");
4950         ar->playlist()->clear_owned_changes (); 
4951
4952         if (start) {
4953                 ar->set_fade_in_length (new_length);
4954         } else {
4955                 ar->set_fade_out_length (new_length);
4956         }
4957
4958         /* Adjusting the xfade may affect other regions in the playlist, so we need
4959            to get undo Commands from the whole playlist rather than just the
4960            region.
4961         */
4962
4963         vector<Command*> cmds;
4964         ar->playlist()->rdiff (cmds);
4965         _editor->session()->add_commands (cmds);
4966         _editor->commit_reversible_command ();
4967
4968 }
4969
4970 void
4971 CrossfadeEdgeDrag::aborted (bool)
4972 {
4973         if (start) {
4974                 arv->redraw_start_xfade ();
4975         } else {
4976                 arv->redraw_end_xfade ();
4977         }
4978 }
4979