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