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