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