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